hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
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 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28a96354b6fc753935b11ab30b47e9243bb51f82
| 2,738 |
cc
|
C++
|
tensorflow/python/saved_model/experimental/pywrap_libexport.cc
|
ashutom/tensorflow-upstream
|
c16069c19de9e286dd664abb78d0ea421e9f32d4
|
[
"Apache-2.0"
] | 10 |
2021-05-25T17:43:04.000Z
|
2022-03-08T10:46:09.000Z
|
tensorflow/python/saved_model/experimental/pywrap_libexport.cc
|
CaptainGizzy21/tensorflow
|
3457a2b122e50b4d44ceaaed5a663d635e5c22df
|
[
"Apache-2.0"
] | 6 |
2021-11-10T20:16:36.000Z
|
2022-02-10T05:52:17.000Z
|
tensorflow/python/saved_model/experimental/pywrap_libexport.cc
|
CaptainGizzy21/tensorflow
|
3457a2b122e50b4d44ceaaed5a663d635e5c22df
|
[
"Apache-2.0"
] | 3 |
2021-09-26T22:20:25.000Z
|
2021-09-26T23:07:13.000Z
|
/* Copyright 2021 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.
==============================================================================*/
// Defines the pywrap_libexport module. In order to have only one dynamically-
// linked shared object, all SavedModel C++ APIs must be added here.
#include "pybind11/pybind11.h"
#include "tensorflow/cc/experimental/libexport/constants.h"
#include "tensorflow/cc/experimental/libexport/save.h"
#include "tensorflow/python/lib/core/pybind11_status.h"
#include "tensorflow/python/saved_model/experimental/pywrap_libexport_metrics.h"
namespace py = pybind11;
PYBIND11_MODULE(pywrap_libexport, m) {
m.doc() = "TensorFlow exporter Python bindings";
m.attr("ASSETS_DIRECTORY") = py::str(tensorflow::libexport::kAssetsDirectory);
m.attr("EXTRA_ASSETS_DIRECTORY") =
py::str(tensorflow::libexport::kExtraAssetsDirectory);
m.attr("ASSETS_KEY") = py::str(tensorflow::libexport::kAssetsKey);
m.attr("DEBUG_DIRECTORY") = py::str(tensorflow::libexport::kDebugDirectory);
m.attr("DEBUG_INFO_FILENAME_PB") =
py::str(tensorflow::libexport::kDebugInfoFilenamePb);
m.attr("INIT_OP_SIGNATURE_KEY") =
py::str(tensorflow::libexport::kInitOpSignatureKey);
m.attr("LEGACY_INIT_OP_KEY") =
py::str(tensorflow::libexport::kLegacyInitOpKey);
m.attr("MAIN_OP_KEY") = py::str(tensorflow::libexport::kMainOpKey);
m.attr("TRAIN_OP_KEY") = py::str(tensorflow::libexport::kTrainOpKey);
m.attr("TRAIN_OP_SIGNATURE_KEY") =
py::str(tensorflow::libexport::kTrainOpSignatureKey);
m.attr("SAVED_MODEL_FILENAME_PB") =
py::str(tensorflow::libexport::kSavedModelFilenamePb);
m.attr("SAVED_MODEL_FILENAME_PBTXT") =
py::str(tensorflow::libexport::kSavedModelFilenamePbtxt);
m.attr("SAVED_MODEL_SCHEMA_VERSION") =
tensorflow::libexport::kSavedModelSchemaVersion;
m.attr("VARIABLES_DIRECTORY") =
py::str(tensorflow::libexport::kVariablesDirectory);
m.attr("VARIABLES_FILENAME") =
py::str(tensorflow::libexport::kVariablesFilename);
m.def("Save", [](const char* export_dir) {
tensorflow::MaybeRaiseFromStatus(tensorflow::libexport::Save(export_dir));
});
tensorflow::DefineMetricsModule(m);
}
| 36.026316 | 80 | 0.72973 |
ashutom
|
28abb27fd199f22440597d85f90b972ddd7ad853
| 2,852 |
cpp
|
C++
|
vulkanon/generator/data/code/vulkanon/l0_enemy23.cpp
|
pqrs-org/Vulkanon
|
3c161b83e64f18be2ba916055e5761fbc0b61028
|
[
"Unlicense"
] | 5 |
2020-04-20T02:28:15.000Z
|
2021-12-05T22:04:06.000Z
|
vulkanon/generator/data/code/vulkanon/l0_enemy23.cpp
|
pqrs-org/Vulkanon
|
3c161b83e64f18be2ba916055e5761fbc0b61028
|
[
"Unlicense"
] | null | null | null |
vulkanon/generator/data/code/vulkanon/l0_enemy23.cpp
|
pqrs-org/Vulkanon
|
3c161b83e64f18be2ba916055e5761fbc0b61028
|
[
"Unlicense"
] | null | null | null |
// XXX uniqID XXX 318a5e347d432a1a29542cd45457692a XXX
#include <gba_types.h>
#include "bullet.hpp"
#include "fixed.hpp"
#include "vulkanon/l0_enemy23.hpp"
extern const BulletStepFunc bullet_72977f5a201704a116fed2c268b98db5_318a5e347d432a1a29542cd45457692a[] = {
stepfunc_b9f3746024faf71a948d02a3f58cba12_318a5e347d432a1a29542cd45457692a,
stepfunc_874e5b4a542f0f7f52ac24d8da866549_318a5e347d432a1a29542cd45457692a,
NULL};
extern const BulletStepFunc bullet_da391036f4887058d231358ef78fb2f0_318a5e347d432a1a29542cd45457692a[] = {
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a,
stepfunc_dae2cf81747ffb5070f05c8837b1d568_318a5e347d432a1a29542cd45457692a,
NULL};
void stepfunc_b9f3746024faf71a948d02a3f58cba12_318a5e347d432a1a29542cd45457692a(BulletInfo *p) {
p->wait = static_cast<u16>(10);
}
void stepfunc_874e5b4a542f0f7f52ac24d8da866549_318a5e347d432a1a29542cd45457692a(BulletInfo *p) {
{
u16 life = static_cast<u16>(1); FixedPointNum speed = (256 * -90 / 360) + ((180 * 1.0 * 256 / 360)) - p->getAngle();p->setRound(speed, life);}
}
void stepfunc_f8e5484dd9ba577849087e287b940bef_318a5e347d432a1a29542cd45457692a(BulletInfo *p) {
{
BulletInfo *bi; p->lastBulletAngle = p->lastBulletAngle + ((30 * 1.0 * 256 / 360)); p->lastBulletSpeed = (1); bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(BULLET_TYPE_NORMAL, p->getPosX(), p->getPosY(), p->lastBulletAngle, p->lastBulletSpeed, bullet_72977f5a201704a116fed2c268b98db5_318a5e347d432a1a29542cd45457692a);
}
}
}
void stepfunc_dae2cf81747ffb5070f05c8837b1d568_318a5e347d432a1a29542cd45457692a(BulletInfo *p) {
ListBullets::stepFuncDrop(p);}
BulletInfo *genBulletFunc_318a5e347d432a1a29542cd45457692a(FixedPointNum posx, FixedPointNum posy) { BulletInfo * bi; bi = ListBullets::makeNewBullet(); if (bi != NULL) { bi->initialize(BULLET_TYPE_ROOT, posx, posy, BulletInfo::DEFAULT_ANGLE, 0, bullet_da391036f4887058d231358ef78fb2f0_318a5e347d432a1a29542cd45457692a);
}
return bi;}
| 55.921569 | 350 | 0.860098 |
pqrs-org
|
28aed5b93bdeecdc93413dc3373a6ac59c3ee569
| 1,496 |
cpp
|
C++
|
runtime/fni/std/std_RegexMatcher.cpp
|
fanx-dev/fanx
|
902128c44b4b5c236a8b0a49986569097c7ca0aa
|
[
"AFL-3.0"
] | 146 |
2019-03-18T14:09:46.000Z
|
2022-01-22T21:58:22.000Z
|
runtime/fni/std/std_RegexMatcher.cpp
|
chunquedong/FanCore
|
4d5dfb06f4c7d0fe0272c4238529e42950531d3b
|
[
"AFL-3.0"
] | 11 |
2019-11-27T19:00:22.000Z
|
2022-03-24T02:15:46.000Z
|
runtime/fni/std/std_RegexMatcher.cpp
|
chunquedong/FanCore
|
4d5dfb06f4c7d0fe0272c4238529e42950531d3b
|
[
"AFL-3.0"
] | 12 |
2019-06-03T05:06:49.000Z
|
2021-09-09T05:59:30.000Z
|
#include "fni_ext.h"
#include "pod_std_native.h"
#include <regex>
static std::cmatch* getMatcher(fr_Env env, fr_Obj self) {
static fr_Field f = fr_findField(env, fr_getObjType(env, self), "handle");
fr_Value val;
fr_getInstanceField(env, self, f, &val);
std::cmatch* raw = (std::cmatch*)(val.i);
return raw;
}
fr_Bool std_RegexMatcher_matches(fr_Env env, fr_Obj self) {
std::cmatch* m = getMatcher(env, self);
return !m->empty();
}
fr_Bool std_RegexMatcher_find(fr_Env env, fr_Obj self) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
fr_Obj std_RegexMatcher_replaceFirst(fr_Env env, fr_Obj self, fr_Obj replacement) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
fr_Obj std_RegexMatcher_replaceAll(fr_Env env, fr_Obj self, fr_Obj replacement) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
fr_Int std_RegexMatcher_groupCount(fr_Env env, fr_Obj self) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
fr_Obj std_RegexMatcher_group(fr_Env env, fr_Obj self, fr_Int group) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
fr_Int std_RegexMatcher_start(fr_Env env, fr_Obj self, fr_Int group) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
fr_Int std_RegexMatcher_end(fr_Env env, fr_Obj self, fr_Int group) {
std::cmatch* m = getMatcher(env, self);
return 0;
}
void std_RegexMatcher_finalize(fr_Env env, fr_Obj self) {
std::cmatch* m = getMatcher(env, self);
delete m;
}
| 30.530612 | 83 | 0.697861 |
fanx-dev
|
28b08ebb4e2e8a1448c6ecb8dded527de3550256
| 963 |
cpp
|
C++
|
vnoj/nkpath.cpp
|
tiozo/Training
|
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
|
[
"MIT"
] | 1 |
2021-08-28T04:16:34.000Z
|
2021-08-28T04:16:34.000Z
|
vnoj/nkpath.cpp
|
tiozo/Training
|
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
|
[
"MIT"
] | null | null | null |
vnoj/nkpath.cpp
|
tiozo/Training
|
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
long long gcd(long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
long long lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
const int MOD=1e9;
int main() {
int M,N;
cin >> M >> N;
vector<vi > a(M+1,vi (N+1,0));
for (int i=1;i<=M;++i) {
for (int j=1;j<=N;++j) {
cin >> a[i][j];
}
}
vector<vi > F(M+1,vi (N+1,0));
for (int i=1;i<=M;++i) {
F[i][1]=1;
}
for (int i=1;i<=M;++i) {
for (int j=1;j<=N;++j) {
for (int x=1;x<=i;++x) {
for (int y=1;y<=j;++y) {
if (y < N && x+y<i+j && gcd(a[x][y],a[i][j])!=1)
F[i][j]=(F[i][j]+F[x][y])%MOD;
}
}
}
}
int sum=0;
for (int i=1;i<=M;++i) {
sum=(sum+F[i][N])%MOD;
}
cout << sum;
return 0;
}
| 19.26 | 69 | 0.379024 |
tiozo
|
28b228e30a88dc3fe1dc4ac1bc92be301b415469
| 3,215 |
cpp
|
C++
|
passes/pre_eval/eval/shift.cpp
|
nandor/genm-opt
|
b3347d508fff707837d1dc8232487ebfe157fe2a
|
[
"MIT"
] | 13 |
2020-06-25T18:26:54.000Z
|
2021-02-16T03:14:38.000Z
|
passes/pre_eval/eval/shift.cpp
|
nandor/genm-opt
|
b3347d508fff707837d1dc8232487ebfe157fe2a
|
[
"MIT"
] | 3 |
2020-07-01T01:39:47.000Z
|
2022-01-24T23:47:12.000Z
|
passes/pre_eval/eval/shift.cpp
|
nandor/genm-opt
|
b3347d508fff707837d1dc8232487ebfe157fe2a
|
[
"MIT"
] | 2 |
2021-03-11T05:08:09.000Z
|
2021-07-17T23:36:17.000Z
|
// This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#include "passes/pre_eval/symbolic_context.h"
#include "passes/pre_eval/symbolic_eval.h"
#include "passes/pre_eval/symbolic_value.h"
#include "passes/pre_eval/symbolic_visitor.h"
// -----------------------------------------------------------------------------
bool SymbolicEval::VisitSllInst(SllInst &i)
{
class Visitor final : public BinaryVisitor<SllInst> {
public:
Visitor(SymbolicEval &e, SllInst &i) : BinaryVisitor(e, i) {}
bool Visit(Scalar, const APInt &) override
{
return SetScalar();
}
bool Visit(const APInt &, Scalar) override
{
return SetScalar();
}
bool Visit(const APInt &l, const APInt &r) override
{
return SetInteger(l.shl(r.getSExtValue()));
}
bool Visit(const APInt &, LowerBoundedInteger) override
{
return SetScalar();
}
bool Visit(LowerBoundedInteger l, const APInt &r) override
{
auto newBound = l.Bound.shl(r.getSExtValue());
if (newBound.isNonNegative()) {
return SetLowerBounded(newBound);
} else {
return SetScalar();
}
}
bool Visit(Pointer l, const APInt &r) override
{
return SetValue(l.Ptr->Decay());
}
bool Visit(Value l, const APInt &r) override
{
return SetValue(l.Ptr->Decay());
}
bool Visit(Nullable l, const APInt &r) override
{
return SetValue(l.Ptr->Decay());
}
};
return Visitor(*this, i).Evaluate();
}
// -----------------------------------------------------------------------------
bool SymbolicEval::VisitSrlInst(SrlInst &i)
{
class Visitor final : public BinaryVisitor<SrlInst> {
public:
Visitor(SymbolicEval &e, SrlInst &i) : BinaryVisitor(e, i) {}
bool Visit(Scalar, Scalar) override
{
return SetScalar();
}
bool Visit(Scalar, const APInt &) override
{
return SetScalar();
}
bool Visit(LowerBoundedInteger l, const APInt &r) override
{
return SetScalar();
}
bool Visit(Pointer l, const APInt &r) override
{
return SetPointer(l.Ptr->Decay());
}
bool Visit(Value l, const APInt &r) override
{
return SetValue(l.Ptr->Decay());
}
bool Visit(Nullable l, const APInt &r) override
{
return SetValue(l.Ptr->Decay());
}
bool Visit(const APInt &l, const APInt &r) override
{
return SetInteger(l.lshr(r.getZExtValue()));
}
};
return Visitor(*this, i).Evaluate();
}
// -----------------------------------------------------------------------------
bool SymbolicEval::VisitSraInst(SraInst &i)
{
class Visitor final : public BinaryVisitor<SraInst> {
public:
Visitor(SymbolicEval &e, SraInst &i) : BinaryVisitor(e, i) {}
bool Visit(Scalar, const APInt &) override
{
return SetScalar();
}
bool Visit(const APInt &l, const APInt &r) override
{
return SetInteger(l.ashr(r.getZExtValue()));
}
bool Visit(Value l, const APInt &r) override
{
return SetValue(l.Ptr->Decay());
}
};
return Visitor(*this, i).Evaluate();
}
| 23.639706 | 80 | 0.579782 |
nandor
|
28b5525bc8a63b03219b8d88bf631993ca818f4f
| 28,439 |
hpp
|
C++
|
include/netp/constants.hpp
|
cainiaoDJ/netplus
|
03350d507830b3a39620374225d16c0b57623ef1
|
[
"MIT"
] | null | null | null |
include/netp/constants.hpp
|
cainiaoDJ/netplus
|
03350d507830b3a39620374225d16c0b57623ef1
|
[
"MIT"
] | null | null | null |
include/netp/constants.hpp
|
cainiaoDJ/netplus
|
03350d507830b3a39620374225d16c0b57623ef1
|
[
"MIT"
] | null | null | null |
#ifndef _NETP_CONSTANTS_H_
#define _NETP_CONSTANTS_H_
#include <climits>
#include <netp/core/platform.hpp>
#define NETP_SOCKET_ERROR (-1)
#define NETP_INVALID_SOCKET netp::SOCKET(~0)
namespace netp {
namespace u8 {
const u32_t MAX = 0xffU;
}
namespace i8 {
const u32_t MAX = 0x7f;
}
namespace u16 {
const u32_t MAX = 0xffffU;
}
namespace i16 {
const u32_t MAX = 0x7fffU;
}
namespace u32 {
const u32_t MAX = 0xffffffffUL;
}
namespace i32 {
const u32_t MAX = 0x7fffffffUL;
}
namespace u64 {
const u64_t MAX = 0xffffffffffffffffULL;
}
namespace i64 {
const u64_t MAX = 0x7fffffffffffffffULL;
}
//WSAEWOULDBLOCK
const int OK = 0;
#if defined(_NETP_APPLE)
const int E_EPERM = -1; /* Operation not permitted */
const int E_ENOENT = -2; /* No such file or directory */
const int E_ESRCH = -3; /* No such process */
const int E_EINTR =-4; /* Interrupted system call */
const int E_EIO = -5; /* Input/output error */
const int E_ENXIO = -6; /* Device not configured */
const int E_E2BIG = -7; /* Argument list too long */
const int E_ENOEXEC = -8; /* Exec format error */
const int E_EBADF = -9; /* Bad file descriptor */
const int E_ECHILD = -10; /* No child processes */
const int E_EDEADLK = -11; /* Resource deadlock avoided */
/* 11 was EAGAIN */
const int E_ENOMEM = -12; /* Cannot allocate memory */
const int E_EACCES = -13; /* Permission denied */
const int E_EFAULT = -14; /* Bad address */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_ENOTBLK = -15; ; /* Block device required */
#endif
const int E_EBUSY = -16; /* Device / Resource busy */
const int E_EEXIST =-17; /* File exists */
const int E_EXDEV = -18; /* Cross-device link */
const int E_ENODEV = -19; /* Operation not supported by device */
const int E_ENOTDIR = -20; /* Not a directory */
const int E_EISDIR = -21; /* Is a directory */
const int E_EINVAL = -22; /* Invalid argument */
const int E_ENFILE = -23; /* Too many open files in system */
const int E_EMFILE = -24; /* Too many open files */
const int E_ENOTTY = -25; /* Inappropriate ioctl for device */
const int E_ETXTBSY = 26; /* Text file busy */
const int E_EFBIG = -27; /* File too large */
const int E_ENOSPC = -28; /* No space left on device */
const int E_ESPIPE = -29; /* Illegal seek */
const int E_EROFS = -30; /* Read-only file system */
const int E_EMLINK = -31; /* Too many links */
const int E_EPIPE = -32; /* Broken pipe */
/* math software */
const int E_EDOM = -33; /* Numerical argument out of domain */
const int E_ERANGE = -34; /* Result too large */
/* non-blocking and interrupt i/o */
const int E_EAGAIN = -35; /* Resource temporarily unavailable */
const int E_EWOULDBLOCK = E_EAGAIN; /* Operation would block */
const int E_EINPROGRESS = -36; /* Operation now in progress */
const int E_EALREADY = -37; /* Operation already in progress */
/* ipc/network software -- argument errors */
const int E_ENOTSOCK = -38; /* Socket operation on non-socket */
const int E_EDESTADDRREQ = -39; /* Destination address required */
const int E_EMSGSIZE = -40; /* Message too long */
const int E_EPROTOTYPE = -41; /* Protocol wrong type for socket */
const int E_ENOPROTOOPT = -42; /* Protocol not available */
const int E_EPROTONOSUPPORT = -43; /* Protocol not supported */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_ESOCKTNOSUPPORT = -44; /* Socket type not supported */
#endif
const int E_ENOTSUP = -45; /* Operation not supported */
#if !__DARWIN_UNIX03 && !defined(KERNEL)
/*
* This is the same for binary and source copmpatability, unless compiling
* the kernel itself, or compiling __DARWIN_UNIX03; if compiling for the
* kernel, the correct value will be returned. If compiling non-POSIX
* source, the kernel return value will be converted by a stub in libc, and
* if compiling source with __DARWIN_UNIX03, the conversion in libc is not
* done, and the caller gets the expected (discrete) value.
*/
const int E_EOPNOTSUPP = E_ENOTSUP; /* Operation not supported on socket */
#endif /* !__DARWIN_UNIX03 && !KERNEL */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EPFNOSUPPORT = -46; /* Protocol family not supported */
#endif
const int E_EAFNOSUPPORT = -47; /* Address family not supported by protocol family */
const int E_EADDRINUSE = -48; /* Address already in use */
const int E_EADDRNOTAVAIL = -49; /* Can't assign requested address */
/* ipc/network software -- operational errors */
const int E_ENETDOWN = -50; /* Network is down */
const int E_ENETUNREACH = -51; /* Network is unreachable */
const int E_ENETRESET = -52;/* Network dropped connection on reset */
const int E_ECONNABORTED = -53; /* Software caused connection abort */
const int E_ECONNRESET = -54; /* Connection reset by peer */
const int E_ENOBUFS = -55; /* No buffer space available */
const int E_EISCONN = -56; /* Socket is already connected */
const int E_ENOTCONN = -57; /* Socket is not connected */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_ESHUTDOWN = -58; /* Can't send after socket shutdown */
const int E_ETOOMANYREFS = -59; /* Too many references: can't splice */
#endif
const int E_ETIMEDOUT = -60; /* Operation timed out */
const int E_ECONNREFUSED = -61; /* Connection refused */
const int E_ELOOP = -62; /* Too many levels of symbolic links */
const int E_ENAMETOOLONG = -63; /* File name too long */
/* should be rearranged */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EHOSTDOWN = -64; /* Host is down */
#endif
const int E_EHOSTUNREACH = -65; /* No route to host */
const int E_ENOTEMPTY = -66; /* Directory not empty */
/* quotas & mush */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EPROCLIM = -67; /* Too many processes */
const int E_EUSERS = -68; /* Too many users */
#endif
const int E_EDQUOT = -69; /* Disc quota exceeded */
/* Network File System */
const int E_ESTALE = -70; /* Stale NFS file handle */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EREMOTE = -71; /* Too many levels of remote in path */
const int E_EBADRPC = -72; /* RPC struct is bad */
const int E_ERPCMISMATCH = -73; /* RPC version wrong */
const int E_EPROGUNAVAIL = -74; /* RPC prog. not avail */
const int E_EPROGMISMATCH = -75; /* Program version wrong */
const int E_EPROCUNAVAIL = -76; /* Bad procedure for program */
#endif
const int E_ENOLCK = -77; /* No locks available */
const int E_ENOSYS = -78; /* Function not implemented */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EFTYPE = -79; /* Inappropriate file type or format */
const int E_EAUTH = -80; /* Authentication error */
const int E_ENEEDAUTH = -81; /* Need authenticator */
/* Intelligent device errors */
const int E_EPWROFF = -82; /* Device power is off */
const int E_EDEVERR = -83; /* Device error, e.g. paper out */
#endif
const int E_EOVERFLOW = -84; /* Value too large to be stored in data type */
/* Program loading errors */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EBADEXEC = -85; /* Bad executable */
const int E_EBADARCH = -86; /* Bad CPU type in executable */
const int E_ESHLIBVERS = -87; /* Shared library version mismatch */
const int E_EBADMACHO = -88; /* Malformed Macho file */
#endif
const int E_ECANCELED = -89; /* Operation canceled */
const int E_EIDRM = -90; /* Identifier removed */
const int E_ENOMSG = -91; /* No message of desired type */
const int E_EILSEQ = -92; /* Illegal byte sequence */
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_ENOATTR = -93; /* Attribute not found */
#endif
const int E_EBADMSG = -94; /* Bad message */
const int E_EMULTIHOP = -95; /* Reserved */
const int E_ENODATA = -96; /* No message available on STREAM */
const int E_ENOLINK = -97; /* Reserved */
const int E_ENOSR = -98; /* No STREAM resources */
const int E_ENOSTR = -99; /* Not a STREAM */
const int E_EPROTO = -100; /* Protocol error */
const int E_ETIME = -101; /* STREAM ioctl timeout */
#if __DARWIN_UNIX03 || defined(KERNEL)
/* This value is only discrete when compiling __DARWIN_UNIX03, or KERNEL */
const int E_EOPNOTSUPP = -102; /* Operation not supported on socket */
#endif /* __DARWIN_UNIX03 || KERNEL */
const int E_ENOPOLICY = -103; /* No such policy registered */
#if __DARWIN_C_LEVEL >= 200809L
const int E_ENOTRECOVERABLE = -104; /* State not recoverable */
const int E_EOWNERDEAD = -105; /* Previous owner died */
#endif
#if __DARWIN_C_LEVEL >= __DARWIN_C_FULL
const int E_EQFULL = -106; /* Interface output queue is full */
const int E_ELAST = -106; /* Must be equal largest errno */
#endif
#elif defined(_NETP_GNU_LINUX) || defined(_NETP_ANDROID)
const int E_EPERM = -1; //operation not permitted
const int E_ENOENT = -2; //no such file or directory
const int E_ESRCH = -3; //no such process
const int E_EINTR = -4; //interrupted system call
const int E_EIO = -5; //I/O error
const int E_ENXIO = -6; //no such device or address
const int E_E2BIG = -7; //Arg list too long
const int E_ENOEXEC = -8; //Exec format error
const int E_EBADF = -9; //Bad file number
const int E_ECHILD = -10; //No child processes
const int E_EAGAIN = -11; //Try again
const int E_ENOMEM = -12; //Out of memory
const int E_EACCESS = -13; //Permission denied
const int E_EFAULT = -14; //Bad address
const int E_ENOTBLK = -15; //Block device required
const int E_EBUSY = -16; //Device or resource busy
const int E_EEXIST = -17; //File exists
const int E_EEXDEV = -18; //Cross-device link
const int E_ENODEV = -19; //No such device
const int E_ENOTDIR = -20; //Not a directory
const int E_EISDIR = -21; //Is a directory
const int E_EINVAL = -22; //Invalid argument
const int E_ENFILE = -23; //File table overflow
const int E_EMFILE = -24; //Too many open files
const int E_ENOTTY = -25; //Not a tty device
const int E_ETXTBSY = -26; //Text file busy
const int E_EFBIG = -27; //File too large
const int E_ENOSPC = -28; //No space left on device
const int E_ESPIPE = -29; //Illegal seek
const int E_EROFS = -30; //read-only file system
const int E_EMLINK = -31; //Too many links
const int E_EPIPE = -32; //broken pipe
const int E_EDOM = -33; //Math argument out of domain
const int E_ERANGE = -34; //Math result not representable
const int E_EDEADLK = -35; //dead lock wolld occur
const int E_ENAMETOOLONG = -36; //file too long
const int E_ENOLCK = -37; //No record locks available
const int E_ENOSYS = -38; //Function not implemented
const int E_ENOTEMPTY = -39; //dierctory not empty
const int E_ELOOP = -40; //too many symbolic links encountered
const int E_EWOULDBLOCK = -41; //same as EAGAIN
const int E_ENOMSG = -42; //No message of desired type
const int E_EIDRM = -43; //identifier removed
const int E_ECHRNG = -44; //channel number out of range
const int E_EL2NSYNC = -45; //level 2 not synchronized
const int E_EL3HLT = -46; //level 3 halted
const int E_EL3RST = -47; //level3 reset
const int E_ELNRNG = -48; //Link number out of range
const int E_EUNATCH = -49; //protocol driver not attached
const int E_ENOCSI = -50; //No CSI structure available
const int E_EL2HLT = -51; //Level 2 halted
const int E_EBADE = -52; //Invalid exchange
const int E_EBADR = -53; //Invalid request descriptor
const int E_EXFULL = -54; //Exchange full
const int E_ENOANO = -55; //No anode
const int E_EBADRQC = -56; //Invalid request code
const int E_EBADSLT = -57; //Invalid slot
const int E_EDEADLOCK = -58; //Same as EDEADLK
const int E_EBFONT = -59; //Bad font file format
const int E_ENOSTR = -60; //No data available
const int E_ENODATA = -61; //No data available
const int E_ETIME = -62; //Timer expired
const int E_ENOSR = -63; //Out of streams resources
const int E_ERROR_NETNAME_DELETED = -64; //WINDOWS IOCP: The specified network name is no longer available
const int E_ENONET = -64; //machine is not on network
const int E_ENOPKG = -65; //Package not installed
const int E_EREMOTE = -66; //Object is remote
const int E_ENOLINK = -67; //Link has been severed
const int E_EADV = -68; //Advertise error
const int E_ESRMNT = -69; //Srmount error
const int E_ECOMM = -70; //Communication error on send
const int E_EPROTO = -71; //protocol error
const int E_EMULTIHOP = -72; //Multihop attempted
const int E_EDOTDOT = -73; //RFS specific error
const int E_EBADMSG = -74; //Not a data message
const int E_EOVERFLOW = -75; //Value too large for defined data type
const int E_ENOTUNIQ = -76; //Name not unique on network
const int E_EBADFD = -77; //File descriptor in bad state
const int E_REMCHG = -78; //Remote address changed
const int E_ELIBACC = -79; //Cannot access a needed shared library
const int E_ELIBBAD = -80; //Accessing a corrupted shared library
const int E_ELIBSCN = -81; //A .lib section in an .out is corrupted
const int E_ELIMAX = -82; //Linking in too many shared libraries
const int E_ELIEXEC = -83; //Cannot exec a shared library directly
const int E_ELIILSEQ = -84; //Illegal byte sequence
const int E_ERESTART = -85; //Interrupted system call should be restarted
const int E_ESTRPIPE = -86; //Streams pipe error
const int E_EUSERS = -87; //Too many users
const int E_ENOTSOCK = -88; //socket operation on non-socket
const int E_EDESTADDRREQ = -89; //Destination address required
const int E_EMSGSIZE = -90; //Message too long
const int E_EPROTOTYPE = -91; //protocol wrong type for socket
const int E_ENOPROTOOPT = -92; //protocol not available
const int E_EPROTONOSUPPORT = -93; //protocol not supported
const int E_ESOCKTNOSUPPORT = -94; //socket type not supported
const int E_EOPNOTSUPP = -95; //Operation not supported on transport
const int E_EPFNOSUPPORT = -96; //protocol family not supported
const int E_EAFNOSUPPORT = -97; //address family not supported by protocol
const int E_EADDRINUSE = -98; //address already in use
const int E_EADDRNOTAVAIL = -99; //Cannot assign requested address
const int E_ENETDOWN = -100; //Network is down
const int E_ENETUNREACH = -101; //Network is unreachable
const int E_ENETRESET = -102; //Network dropped
const int E_ECONNABORTED = -103; //Software caused connection
const int E_ECONNRESET = -104; //Connection reset by
const int E_ENOBUFS = -105; //No buffer space available
const int E_EISCONN = -106; //Transport endpoint
const int E_ENOTCONN = -107; //Transport endpoint
const int E_ESHUTDOWN = -108; //Cannot send after transport
const int E_ETOOMANYREFS = -109; //Too many references
const int E_ETIMEOUT = -110; //Connection timed
const int E_ECONNREFUSED = -111; //Connection refused
const int E_EHOSTDOWN = -112; //Host is down
const int E_EHOSTUNREACH = -113; //No route to host
const int E_EALREADY = -114; //Operation already
const int E_EINPROGRESS = -115; //Operation now in
const int E_ESTALE = -116; //Stale NFS file handle
const int E_EUCLEAN = -117; //Structure needs cleaning
const int E_ENOTNAM = -118; //Not a XENIX-named
const int E_ENAVAIL = -119; //No XENIX semaphores
const int E_EISNAM = -120; //Is a named type file
const int E_EREMOTEIO = -121; //Remote I/O error
const int E_EDQUOT = -122; //Quota exceeded
const int E_ENOMEDIUM = -123; //No medium found
const int E_EMEDIUMTYPE = -124; //Wrong medium type
const int E_ECANCELED = -125;
const int E_ENOKEY = -126;
const int E_EKEYEXPIRED = -127;
const int E_EKEYREVOKED = -128;
const int E_EKEYREJECTED = -129;
const int E_EOWNERDEAD = -130;
const int E_ENOTRECOVERABLE = -131;
const int E_ERFKILL = -132;
const int E_EHWPOISON = -133;
#elif defined(_NETP_WIN)
const int E_ERROR_ACCESS_DENIED = -5;
const int E_WSA_INVALID_HANDLE = -6;
const int E_ERROR_HANDLE_EOF = -38;
const int E_WSA_INVALID_PARAMETER = -87;
const int E_ERROR_MORE_DATA = -234;
const int E_WAIT_TIMEOUT = -258;
const int E_ERROR_ABANDONED_WAIT_0 = -735;
const int E_WSA_OPERATION_ABORTED = -995;
const int E_WSA_IO_INCOMPLETE = -996;
const int E_WSA_IO_PENDING = -997;
const int E_ERROR_PRIVILEGE_NOT_HELD = -1314;
const int E_ERROR_CONNECTION_ABORTED = -1236;
// 1---19999; reserved for system call error code (windows)
const int E_WSAEINTR = -10004; // A blocking operation was interrupted by a call to WSACancelBlockingCall.
const int E_WSAEBADF = -10009; // The file handle supplied is not valid.
const int E_WSAEACCES = -10013; //An attempt was made to access a socket in a way forbidden by its access permissions.
const int E_WSAEFAULT = -10014; // The system detected an invalid pointer address in attempting to use a pointer argument in a call.
const int E_WSAEINVAL = -10022; // An invalid argument was supplied
const int E_WSAEMFILE = -10024; // Too many open sockets.
const int E_WSAEWOULDBLOCK = -10035; // A non-blocking socket operation could not be completed immediately.
const int E_WSAEINPROGRESS = -10036; // A blocking operation is currently executing.
const int E_WSAEALREADY = -10037; // An operation was attempted on a non-blocking socket that already had an operation in progress.
const int E_WSAENOTSOCK = -10038; // An operation was attempted on something that is not a socket.
const int E_WSAEMSGSIZE = -10040; // A message sent on a datagram socket was larger than the internal message buffer or some other network limit; or the buffer used to receive a datagram into was smaller than the datagram itself.
const int E_WSAEPROTOTYPE = -10041; //A protocol was specified in the socket function call that does not support the semantics of the socket type requested.
const int E_WSAENOPROTOOPT = -10042; //An unknown; invalid; or unsupported option or level was specified in a getsockopt or setsockopt call
const int E_WSAEPROTONOSUPPORT = -10043; //The requested protocol has not been configured into the system; or no implementation for it exists.
const int E_WSAESOCKTNOSUPPORT = -10044; //The support for the specified socket type does not exist in this address family
const int E_WSAEOPNOTSUPP = -10045; //The attempted operation is not supported for the type of object referenced.
const int E_WSAEPFNOSUPPORT = -10046; //The protocol family has not been configured into the system or no implementation for it exists
const int E_WSAEAFNOSUPPORT = -10047; //An address incompatible with the requested protocol was used
const int E_WSAEADDRINUSE = -10048; // Only one usage of each socket address (protocol/network address/port) is normally permitted.
const int E_WSAEADDRNOTAVAIL = -10049; // The requested address is not valid in its context.
const int E_WSAENETDOWN = -10050; //A socket operation encountered a dead network.
const int E_WSAENETUNREACH = -10051; // A socket operation was attempted to an unreachable network.
const int E_WSAENETRESET = -10052; // The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress.
const int E_WSAECONNABORTED = -10053; // An established connection was aborted by the software in your host machine.
const int E_WSAECONNRESET = -10054; // An existing connection was forcibly closed by the remote host.
const int E_WSAENOBUFS = -10055; // An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
const int E_WSAEISCONN = -10056; // A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
const int E_WSAENOTCONN = -10057; // A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
const int E_WSAESHUTDOWN = -10058; //A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call
const int E_WSAETOOMANYREFS = -10059; //Too many references to some kernel object.
const int E_WSAETIMEDOUT = -10060; //A connection attempt failed because the connected party did not properly respond after a period of time; or established connection failed because connected host has failed to respond.
const int E_WSAECONNREFUSED = -10061; //No connection could be made because the target machine actively refused it.
const int E_WSAELOOP = -10062; //Cannot translate name
const int E_WSAEHOSTDOWN = -10064; // A socket operation failed because the destination host was down
const int E_WSAEHOSTUNREACH = -10065; // A socket operation was attempted to an unreachable host.
const int E_WSAEPROCLIM = -10067; // A Windows Sockets implementation may have a limit on the number of applications that may use it simultaneously.
const int E_WSAEUSERS = -10068;
const int E_WSAEDQUOT = -10069;
const int E_WSASYSNOTREADY = -10091;
const int E_WSANOTINITIALISED = -10093;
const int E_WSAEPROVIDERFAILEDINIT = -10106;
const int E_WSASYSCALLFAILURE = -10107;
const int E_WSASERVICE_NOT_FOUND = -10108;
const int E_WSATYPE_NOT_FOUND = -10109;
const int E_WSA_E_NO_MORE = -10110;
const int E_WSA_E_CANCELLED = -10111;
const int E_WSAEREFUSED = -10112;
const int E_WSAHOST_NOT_FOUND = -11001;
const int E_WSATRY_AGAIN = -11002;
const int E_WSANO_RECOVERY = -11003;
const int E_WSANO_DATA = -11004;
const int E_WSA_QOS_RECEIVERS = -11005;
const int E_WSA_QOS_SENDERS = -11006;
const int E_ECONNABORTED = E_WSAECONNABORTED;
const int E_EINTR = E_WSAEINTR;
const int E_EWOULDBLOCK = E_WSAEWOULDBLOCK;
const int E_EAGAIN = E_EWOULDBLOCK;
const int E_EINPROGRESS = E_WSAEWOULDBLOCK; //pls refer tohttps://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect
const int E_EMFILE = E_WSAEMFILE;
const int E_EACCESS = E_WSAEACCES;
const int E_EBADF = E_WSAEBADF;
const int E_EALREADY = E_WSAEALREADY;
const int E_ECONNRESET = E_WSAECONNRESET;
const int E_ETIMEOUT = E_WSAETIMEDOUT;
const int E_EADDRINUSE = E_WSAEADDRINUSE;
const int E_EINVAL = E_WSAEINVAL;
const int E_ENOTCONN = E_WSAENOTCONN;
#endif
//internal error
const int E_NETP_APP_EXIT = -20000;
const int E_NO_NET_DEV = -20001;
const int E_INVALID_OPERATION = -20002;
const int E_INVALID_STATE = -20003;
const int E_MEMORY_MALLOC_FAILED = -20004;
const int E_MEMORY_ACCESS_ERROR = -20005;
const int E_MEMORY_ALLOC_FAILED = -20006;
const int E_MEMORY_NEW_FAILED = -20007;
const int E_TRY_AGAIN = -20008;
const int E_INVAL = -20009;
const int E_ASSERT_FAILED = -20010;
const int E_NETP_THROW = -20011;
const int E_UNKNOWN = -20012;
const int E_THREAD_INTERRUPT = -20013;
const int E_TODO = -20014;
const int E_BAD_CAST = -20015;
const int E_OP_INPROCESS = -20016;
const int E_OP_ABORT = -20017;
const int E_OP_TIMEOUT = -20018;
const int E_OP_ALREADY = -20019;
const int E_EVENT_BROKER_BINDED_ALREADY = -21001;
const int E_EVENT_BROKER_NO_LISTENER = -21002;
const int E_XXTEA_INVALID_DATA = -22001;
const int E_XXTEA_DECRYPT_FAILED = -22002;
const int E_XXTEA_ENCRYPT_FAILED = -22003;
const int E_DH_HANDSHAKE_MESSAGE_CHECK_FAILED = -22011;
const int E_DH_HANDSHAKE_FAILED = -22012;
const int E_IO_EVENT_LOOP_NOTIFY_TERMINATING = -25001;
const int E_IO_EVENT_LOOP_TERMINATED = -25002;
const int E_IO_EVENT_LOOP_BYE_DO_NOTHING = -25003;
const int E_IO_BEGIN_FAILED = -25004;
//30000 - 30999 //system level socket error
const int E_SOCKET_EPOLLHUP = -30001;
const int E_SOCKET_GRACE_CLOSE = -30002;
//31000 - 31999 //user custom socket error
const int E_SOCKET_INVALID_FAMILY = -31001;
const int E_SOCKET_INVALID_TYPE = -31002;
const int E_SOCKET_INVALID_ADDRESS = -31003;
const int E_SOCKET_INVALID_PROTOCOL = -31004;
const int E_SOCKET_INVALID_STATE = -31005;
const int E_SOCKET_SELF_CONNCTED = -31006;
const int E_SOCKET_READ_CLOSED_ALREADY = -31007;
const int E_SOCKET_WRITE_CLOSED_ALREADY = -31008;
const int E_SOCKET_NO_AVAILABLE_ADDR = -31009;
const int E_SOCKET_OP_ALREADY = -31010;
const int E_CHANNEL_BDLIMIT = -34001;
const int E_CHANNEL_READ_BLOCK = -34002;
const int E_CHANNEL_WRITE_BLOCK = -34003;
const int E_CHANNEL_READ_CLOSED = -34004;
const int E_CHANNEL_WRITE_CLOSED = -34005;
const int E_CHANNEL_INVALID_STATE = -34006;
const int E_CHANNEL_NOT_EXISTS = -34007;
const int E_CHANNEL_EXISTS = -34008;
const int E_CHANNEL_CLOSED = -34009;
const int E_CHANNEL_CLOSING = -34010;
const int E_CHANNEL_WRITE_SHUTDOWNING = -34011;
const int E_CHANNEL_WRITING = -34012;
const int E_CHANNEL_OUTGO_LIST_EMPTY = -34013; //FOR IOCP
const int E_CHANNEL_READ_WRITE_ERROR = -34014;
const int E_CHANNEL_ABORT = -34015;
const int E_CHANNEL_CONTEXT_REMOVED = -34016;
const int E_CHANNEL_OVERLAPPED_OP_TRY = -34017;
const int E_CHANNEL_MISSING_MAKER = -34018;//custom socket channel must have its own maker
const int E_FORWARDER_DOMAIN_LEN_EXCEED = -35001;
const int E_FORWARDER_INVALID_IPV4 = -35002;
const int E_FORWARDER_DIAL_DST_FAILED = -35003;
const int E_DNS_LOOKUP_RETURN_NO_IP = -36001;
const int E_DNS_TEMPORARY_ERROR = -36002;
const int E_DNS_PROTOCOL_ERROR = -36003;
const int E_DNS_DOMAIN_NAME_NOT_EXISTS = -36004;
const int E_DNS_DOMAIN_NO_DATA = -36005;
const int E_DNS_NOMEM = -36006;
const int E_DNS_BADQUERY = -36007;
const int E_DNS_SERVER_SHUTDOWN = -36008;
const int E_MUX_STREAM_TRANSPORT_CLOSED = -37001;
const int E_MUX_STREAM_RST = -37002;
const int E_RPC_NO_WRITE_CHANNEL = -40001;
const int E_RPC_CALL_UNKNOWN_API = -40002;
const int E_RPC_CALL_INVALID_PARAM = -40003;
const int E_RPC_CALL_ERROR_UNKNOWN = -40004;
const int E_RPC_CALL_CANCEL = -40005;
const int E_RPC_CALL_TIMEOUT = -40006;
const int E_RPC_WRITE_TIMEOUT = -40007;
const int E_RPC_CONNECT_ABORT = -40008;
const int E_RPC_MESSAGE_DECODE_FAILED = -40009;
const int E_HTTP_CLIENT_REQ_IN_OP = -41001;
const int E_HTTP_MESSAGE_INVALID_TYPE = -41002;
const int E_HTTP_REQUEST_NOT_DONE = -41003;
const int E_HTTP_INVALID_HOST = -41004;
const int E_HTTP_INVALID_OP = -41005;
const int E_HTTP_REQ_TIMEOUT = -41006;
const int E_HTTP_CLIENT_DIAL_CANCEL = -41007;
const int E_HTTP_CLIENT_CLOSING = -41008;
const int E_HTTP_EMPTY_FILED_NAME = -41009;
} //endif netp ns
#endif //END OF NETP_ERROR_HEADER
| 50.513321 | 236 | 0.674215 |
cainiaoDJ
|
28b5ef0e98123bbcae16199980e1ed619eb5e3f4
| 103,207 |
inl
|
C++
|
Src/FEMTree.IsoSurface.specialized.inl
|
DamonsJ/PoissonRecon
|
fec7801bd10a02bbb9036b52de5f7c3955f399dc
|
[
"MIT"
] | 15 |
2021-05-26T11:47:59.000Z
|
2022-01-20T12:34:15.000Z
|
Src/FEMTree.IsoSurface.specialized.inl
|
DamonsJ/PoissonRecon
|
fec7801bd10a02bbb9036b52de5f7c3955f399dc
|
[
"MIT"
] | 7 |
2021-06-08T08:35:00.000Z
|
2021-11-07T10:27:30.000Z
|
Src/FEMTree.IsoSurface.specialized.inl
|
DamonsJ/PoissonRecon
|
fec7801bd10a02bbb9036b52de5f7c3955f399dc
|
[
"MIT"
] | 14 |
2017-03-16T10:09:22.000Z
|
2021-12-28T03:53:18.000Z
|
/*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the Johns Hopkins University nor the names of its contributors
may be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/
#include <sstream>
#include <sstream>
#include <iomanip>
#include <unordered_map>
#include "MyMiscellany.h"
#include "MarchingCubes.h"
#include "MAT.h"
// Specialized iso-surface extraction
template< class Real , class Vertex >
struct IsoSurfaceExtractor< 3 , Real , Vertex >
{
static const unsigned int Dim = 3;
typedef typename FEMTree< Dim , Real >::LocalDepth LocalDepth;
typedef typename FEMTree< Dim , Real >::LocalOffset LocalOffset;
typedef typename FEMTree< Dim , Real >::ConstOneRingNeighborKey ConstOneRingNeighborKey;
typedef typename FEMTree< Dim , Real >::ConstOneRingNeighbors ConstOneRingNeighbors;
typedef RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > TreeNode;
template< unsigned int WeightDegree > using DensityEstimator = typename FEMTree< Dim , Real >::template DensityEstimator< WeightDegree >;
template< typename FEMSigPack , unsigned int PointD > using _Evaluator = typename FEMTree< Dim , Real >::template _Evaluator< FEMSigPack , PointD >;
protected:
static std::mutex _pointInsertionMutex;
static std::atomic< size_t > _BadRootCount;
//////////
// _Key //
//////////
struct _Key
{
int idx[Dim];
_Key( void ){ for( unsigned int d=0 ; d<Dim ; d++ ) idx[d] = 0; }
int &operator[]( int i ){ return idx[i]; }
const int &operator[]( int i ) const { return idx[i]; }
bool operator == ( const _Key &key ) const
{
for( unsigned int d=0 ; d<Dim ; d++ ) if( idx[d]!=key[d] ) return false;
return true;
}
bool operator != ( const _Key &key ) const { return !operator==( key ); }
std::string to_string( void ) const
{
std::stringstream stream;
stream << "(";
for( unsigned int d=0 ; d<Dim ; d++ )
{
if( d ) stream << ",";
stream << idx[d];
}
stream << ")";
return stream.str();
}
struct Hasher
{
size_t operator()( const _Key &i ) const
{
size_t hash = 0;
for( unsigned int d=0 ; d<Dim ; d++ ) hash ^= i.idx[d];
return hash;
}
};
};
//////////////
// _IsoEdge //
//////////////
struct _IsoEdge
{
_Key vertices[2];
_IsoEdge( void ) {}
_IsoEdge( _Key v1 , _Key v2 ){ vertices[0] = v1 , vertices[1] = v2; }
_Key &operator[]( int idx ){ return vertices[idx]; }
const _Key &operator[]( int idx ) const { return vertices[idx]; }
};
////////////////
// _FaceEdges //
////////////////
struct _FaceEdges{ _IsoEdge edges[2] ; int count; };
///////////////
// SliceData //
///////////////
class SliceData
{
typedef RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > TreeOctNode;
public:
template< unsigned int Indices >
struct _Indices
{
node_index_type idx[Indices];
_Indices( void ){ for( unsigned int i=0 ; i<Indices ; i++ ) idx[i] = -1; }
node_index_type& operator[] ( int i ) { return idx[i]; }
const node_index_type& operator[] ( int i ) const { return idx[i]; }
};
typedef _Indices< HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() > SquareCornerIndices;
typedef _Indices< HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() > SquareEdgeIndices;
typedef _Indices< HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() > SquareFaceIndices;
struct SliceTableData
{
Pointer( SquareCornerIndices ) cTable;
Pointer( SquareEdgeIndices ) eTable;
Pointer( SquareFaceIndices ) fTable;
node_index_type nodeOffset;
node_index_type cCount , eCount , fCount;
node_index_type nodeCount;
SliceTableData( void ){ fCount = eCount = cCount = 0 , _oldNodeCount = 0 , cTable = NullPointer( SquareCornerIndices ) , eTable = NullPointer( SquareEdgeIndices ) , fTable = NullPointer( SquareFaceIndices ) , _cMap = _eMap = _fMap = NullPointer( node_index_type ) , _processed = NullPointer( char ); }
void clear( void ){ DeletePointer( cTable ) ; DeletePointer( eTable ) ; DeletePointer( fTable ) ; DeletePointer( _cMap ) ; DeletePointer( _eMap ) ; DeletePointer( _fMap ) ; DeletePointer( _processed ) ; fCount = eCount = cCount = 0; }
~SliceTableData( void ){ clear(); }
SquareCornerIndices& cornerIndices( const TreeOctNode* node ) { return cTable[ node->nodeData.nodeIndex - nodeOffset ]; }
SquareCornerIndices& cornerIndices( node_index_type idx ) { return cTable[ idx - nodeOffset ]; }
const SquareCornerIndices& cornerIndices( const TreeOctNode* node ) const { return cTable[ node->nodeData.nodeIndex - nodeOffset ]; }
const SquareCornerIndices& cornerIndices( node_index_type idx ) const { return cTable[ idx - nodeOffset ]; }
SquareEdgeIndices& edgeIndices( const TreeOctNode* node ) { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; }
SquareEdgeIndices& edgeIndices( node_index_type idx ) { return eTable[ idx - nodeOffset ]; }
const SquareEdgeIndices& edgeIndices( const TreeOctNode* node ) const { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; }
const SquareEdgeIndices& edgeIndices( node_index_type idx ) const { return eTable[ idx - nodeOffset ]; }
SquareFaceIndices& faceIndices( const TreeOctNode* node ) { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; }
SquareFaceIndices& faceIndices( node_index_type idx ) { return fTable[ idx - nodeOffset ]; }
const SquareFaceIndices& faceIndices( const TreeOctNode* node ) const { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; }
const SquareFaceIndices& faceIndices( node_index_type idx ) const { return fTable[ idx - nodeOffset ]; }
protected:
Pointer( node_index_type ) _cMap;
Pointer( node_index_type ) _eMap;
Pointer( node_index_type ) _fMap;
Pointer( char ) _processed;
node_index_type _oldNodeCount;
friend SliceData;
};
struct XSliceTableData
{
Pointer( SquareCornerIndices ) eTable;
Pointer( SquareEdgeIndices ) fTable;
node_index_type nodeOffset;
node_index_type fCount , eCount;
node_index_type nodeCount;
XSliceTableData( void ){ fCount = eCount = 0 , _oldNodeCount = 0 , eTable = NullPointer( SquareCornerIndices ) , fTable = NullPointer( SquareEdgeIndices ) , _eMap = _fMap = NullPointer( node_index_type ); }
~XSliceTableData( void ){ clear(); }
void clear( void ) { DeletePointer( fTable ) ; DeletePointer( eTable ) ; DeletePointer( _eMap ) ; DeletePointer( _fMap ) ; fCount = eCount = 0; }
SquareCornerIndices& edgeIndices( const TreeOctNode* node ) { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; }
SquareCornerIndices& edgeIndices( node_index_type idx ) { return eTable[ idx - nodeOffset ]; }
const SquareCornerIndices& edgeIndices( const TreeOctNode* node ) const { return eTable[ node->nodeData.nodeIndex - nodeOffset ]; }
const SquareCornerIndices& edgeIndices( node_index_type idx ) const { return eTable[ idx - nodeOffset ]; }
SquareEdgeIndices& faceIndices( const TreeOctNode* node ) { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; }
SquareEdgeIndices& faceIndices( node_index_type idx ) { return fTable[ idx - nodeOffset ]; }
const SquareEdgeIndices& faceIndices( const TreeOctNode* node ) const { return fTable[ node->nodeData.nodeIndex - nodeOffset ]; }
const SquareEdgeIndices& faceIndices( node_index_type idx ) const { return fTable[ idx - nodeOffset ]; }
protected:
Pointer( node_index_type ) _eMap;
Pointer( node_index_type ) _fMap;
node_index_type _oldNodeCount;
friend SliceData;
};
template< unsigned int D , unsigned int ... Ks > struct HyperCubeTables{};
template< unsigned int D , unsigned int K >
struct HyperCubeTables< D , K >
{
static unsigned int CellOffset[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ];
static unsigned int IncidentElementCoIndex[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ];
static unsigned int CellOffsetAntipodal[ HyperCube::Cube< D >::template ElementNum< K >() ];
static typename HyperCube::Cube< D >::template IncidentCubeIndex< K > IncidentCube[ HyperCube::Cube< D >::template ElementNum< K >() ];
static typename HyperCube::Direction Directions[ HyperCube::Cube< D >::template ElementNum< K >() ][ D ];
static void SetTables( void )
{
for( typename HyperCube::Cube< D >::template Element< K > e ; e<HyperCube::Cube< D >::template ElementNum< K >() ; e++ )
{
for( typename HyperCube::Cube< D >::template IncidentCubeIndex< K > i ; i<HyperCube::Cube< D >::template IncidentCubeNum< K >() ; i++ )
{
CellOffset[e.index][i.index] = HyperCube::Cube< D >::CellOffset( e , i );
IncidentElementCoIndex[e.index][i.index] = HyperCube::Cube< D >::IncidentElement( e , i ).coIndex();
}
CellOffsetAntipodal[e.index] = HyperCube::Cube< D >::CellOffset( e , HyperCube::Cube< D >::IncidentCube( e ).antipodal() );
IncidentCube[ e.index ] = HyperCube::Cube< D >::IncidentCube( e );
e.directions( Directions[e.index] );
}
}
};
template< unsigned int D , unsigned int K1 , unsigned int K2 >
struct HyperCubeTables< D , K1 , K2 >
{
static typename HyperCube::Cube< D >::template Element< K2 > OverlapElements[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template OverlapElementNum< K1 , K2 >() ];
static bool Overlap[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template ElementNum< K2 >() ];
static void SetTables( void )
{
for( typename HyperCube::Cube< D >::template Element< K1 > e ; e<HyperCube::Cube< D >::template ElementNum< K1 >() ; e++ )
{
for( typename HyperCube::Cube< D >::template Element< K2 > _e ; _e<HyperCube::Cube< D >::template ElementNum< K2 >() ; _e++ )
Overlap[e.index][_e.index] = HyperCube::Cube< D >::Overlap( e , _e );
HyperCube::Cube< D >::OverlapElements( e , OverlapElements[e.index] );
}
if( !K2 ) HyperCubeTables< D , K1 >::SetTables();
}
};
template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< K2!=0 >::type SetHyperCubeTables( void )
{
HyperCubeTables< D , K1 , K2 >::SetTables() ; SetHyperCubeTables< D , K1 , K2-1 >();
}
template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< K1!=0 && K2==0 >::type SetHyperCubeTables( void )
{
HyperCubeTables< D , K1 , K2 >::SetTables(); SetHyperCubeTables< D , K1-1 , D >();
}
template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< D!=1 && K1==0 && K2==0 >::type SetHyperCubeTables( void )
{
HyperCubeTables< D , K1 , K2 >::SetTables() ; SetHyperCubeTables< D-1 , D-1 , D-1 >();
}
template< unsigned int D=Dim , unsigned int K1=Dim , unsigned int K2=Dim > static typename std::enable_if< D==1 && K1==0 && K2==0 >::type SetHyperCubeTables( void )
{
HyperCubeTables< D , K1 , K2 >::SetTables();
}
static void SetSliceTableData( const SortedTreeNodes< Dim >& sNodes , SliceTableData* sData0 , XSliceTableData* xData , SliceTableData* sData1 , int depth , int offset )
{
// [NOTE] This is structure is purely for determining adjacency and is independent of the FEM degree
typedef typename FEMTree< Dim , Real >::ConstOneRingNeighborKey ConstOneRingNeighborKey;
if( offset<0 || offset>((size_t)1<<depth) ) return;
if( sData0 )
{
std::pair< node_index_type , node_index_type > span( sNodes.begin( depth , offset-1 ) , sNodes.end( depth , offset ) );
sData0->nodeOffset = span.first , sData0->nodeCount = span.second - span.first;
}
if( sData1 )
{
std::pair< node_index_type , node_index_type > span( sNodes.begin( depth , offset ) , sNodes.end( depth , offset+1 ) );
sData1->nodeOffset = span.first , sData1->nodeCount = span.second - span.first;
}
if( xData )
{
std::pair< node_index_type , node_index_type > span( sNodes.begin( depth , offset ) , sNodes.end( depth , offset ) );
xData->nodeOffset = span.first , xData->nodeCount = span.second - span.first;
}
SliceTableData* sData[] = { sData0 , sData1 };
for( int i=0 ; i<2 ; i++ ) if( sData[i] )
{
if( sData[i]->nodeCount>sData[i]->_oldNodeCount )
{
DeletePointer( sData[i]->_cMap ) ; DeletePointer( sData[i]->_eMap ) ; DeletePointer( sData[i]->_fMap );
DeletePointer( sData[i]->cTable ) ; DeletePointer( sData[i]->eTable ) ; DeletePointer( sData[i]->fTable );
DeletePointer( sData[i]->_processed );
sData[i]->_cMap = NewPointer< node_index_type >( sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() );
sData[i]->_eMap = NewPointer< node_index_type >( sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() );
sData[i]->_fMap = NewPointer< node_index_type >( sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() );
sData[i]->_processed = NewPointer< char >( sData[i]->nodeCount );
sData[i]->cTable = NewPointer< typename SliceData::SquareCornerIndices >( sData[i]->nodeCount );
sData[i]->eTable = NewPointer< typename SliceData::SquareEdgeIndices >( sData[i]->nodeCount );
sData[i]->fTable = NewPointer< typename SliceData::SquareFaceIndices >( sData[i]->nodeCount );
sData[i]->_oldNodeCount = sData[i]->nodeCount;
}
memset( sData[i]->_cMap , 0 , sizeof(node_index_type) * sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() );
memset( sData[i]->_eMap , 0 , sizeof(node_index_type) * sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() );
memset( sData[i]->_fMap , 0 , sizeof(node_index_type) * sData[i]->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() );
memset( sData[i]->_processed , 0 , sizeof(char) * sData[i]->nodeCount );
}
if( xData )
{
if( xData->nodeCount>xData->_oldNodeCount )
{
DeletePointer( xData->_eMap ) ; DeletePointer( xData->_fMap );
DeletePointer( xData->eTable ) ; DeletePointer( xData->fTable );
xData->_eMap = NewPointer< node_index_type >( xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() );
xData->_fMap = NewPointer< node_index_type >( xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() );
xData->eTable = NewPointer< typename SliceData::SquareCornerIndices >( xData->nodeCount );
xData->fTable = NewPointer< typename SliceData::SquareEdgeIndices >( xData->nodeCount );
xData->_oldNodeCount = xData->nodeCount;
}
memset( xData->_eMap , 0 , sizeof(node_index_type) * xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() );
memset( xData->_fMap , 0 , sizeof(node_index_type) * xData->nodeCount * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() );
}
std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( depth );
typedef typename FEMTree< Dim , Real >::ConstOneRingNeighbors ConstNeighbors;
// Process the corners
// z: which side of the cell \in {0,1}
// zOff: which neighbor \in {-1,0,1}
auto ProcessCorners = []( SliceTableData& sData , const ConstNeighbors& neighbors , HyperCube::Direction zDir , int zOff )
{
const TreeOctNode* node = neighbors.neighbors[1][1][1+zOff];
node_index_type i = node->nodeData.nodeIndex;
// Iterate over the corners in the face
for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ )
{
bool owner = true;
typename HyperCube::Cube< Dim >::template Element< 0 > c( zDir , _c.index ); // Corner-in-cube index
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 0 > my_ic = HyperCubeTables< Dim , 0 >::IncidentCube[c.index]; // The index of the node relative to the corner
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 0 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 0 >() ; ic++ ) // Iterate over the nodes adjacent to the corner
{
// Get the index of cube relative to the corner neighbors
unsigned int xx = HyperCubeTables< Dim , 0 >::CellOffset[c.index][ic.index] + zOff;
// If the neighbor exists and comes before, they own the corner
if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; }
}
if( owner )
{
node_index_type myCount = ( i-sData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() + _c.index;
sData._cMap[ myCount ] = 1;
// Set the corner pointer for all cubes incident on the corner
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 0 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 0 >() ; ic++ ) // Iterate over the nodes adjacent to the corner
{
unsigned int xx = HyperCubeTables< Dim , 0 >::CellOffset[c.index][ic.index] + zOff;
// If the neighbor exits, sets its corner
if( neighbors.neighbors.data[xx] ) sData.cornerIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 0 >::IncidentElementCoIndex[c.index][ic.index] ] = myCount;
}
}
}
};
// Process the in-plane edges
auto ProcessIEdges = []( SliceTableData& sData , const ConstNeighbors& neighbors , HyperCube::Direction zDir , int zOff )
{
const TreeOctNode* node = neighbors.neighbors[1][1][1+zOff];
node_index_type i = node->nodeData.nodeIndex;
// Iterate over the edges in the face
for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ )
{
bool owner = true;
// The edge in the cube
typename HyperCube::Cube< Dim >::template Element< 1 > e( zDir , _e.index );
// The index of the cube relative to the edge
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = HyperCubeTables< Dim , 1 >::IncidentCube[e.index];
// Iterate over the cubes incident on the edge
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ )
{
// Get the indices of the cube relative to the center
unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index] + zOff;
// If the neighbor exists and comes before, they own the corner
if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; }
}
if( owner )
{
node_index_type myCount = ( i - sData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() + _e.index;
sData._eMap[ myCount ] = 1;
// Set all edge indices
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index] + zOff;
// If the neighbor exists, set the index
if( neighbors.neighbors.data[xx] ) sData.edgeIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 1 >::IncidentElementCoIndex[e.index][ic.index] ] = myCount;
}
}
}
};
// Process the cross-plane edges
auto ProcessXEdges = []( XSliceTableData& xData , const ConstNeighbors& neighbors )
{
const TreeOctNode* node = neighbors.neighbors[1][1][1];
node_index_type i = node->nodeData.nodeIndex;
for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ )
{
bool owner = true;
typename HyperCube::Cube< Dim >::template Element< 1 > e( HyperCube::CROSS , _c.index );
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = HyperCubeTables< Dim , 1 >::IncidentCube[e.index];
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index];
if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; }
}
if( owner )
{
node_index_type myCount = ( i - xData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() + _c.index;
xData._eMap[ myCount ] = 1;
// Set all edge indices
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index];
if( neighbors.neighbors.data[xx] ) xData.edgeIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 1 >::IncidentElementCoIndex[e.index][ic.index] ] = myCount;
}
}
}
};
// Process the in-plane faces
auto ProcessIFaces = []( SliceTableData& sData , const ConstNeighbors& neighbors , HyperCube::Direction zDir , int zOff )
{
const TreeOctNode* node = neighbors.neighbors[1][1][1+zOff];
node_index_type i = node->nodeData.nodeIndex;
for( typename HyperCube::Cube< Dim-1 >::template Element< 2 > _f ; _f<HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ; _f++ )
{
bool owner = true;
typename HyperCube::Cube< Dim >::template Element< 2 > f( zDir , _f.index );
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > my_ic = HyperCubeTables< Dim , 2 >::IncidentCube[f.index];
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index] + zOff;
if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; }
}
if( owner )
{
node_index_type myCount = ( i - sData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() + _f.index;
sData._fMap[ myCount ] = 1;
// Set all the face indices
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index] + zOff;
if( neighbors.neighbors.data[xx] ) sData.faceIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 2 >::IncidentElementCoIndex[f.index][ic.index] ] = myCount;
}
}
}
};
// Process the cross-plane faces
auto ProcessXFaces = []( XSliceTableData& xData , const ConstNeighbors& neighbors )
{
const TreeOctNode* node = neighbors.neighbors[1][1][1];
node_index_type i = node->nodeData.nodeIndex;
for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ )
{
bool owner = true;
typename HyperCube::Cube< Dim >::template Element< 2 > f( HyperCube::CROSS , _e.index );
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > my_ic = HyperCubeTables< Dim , 2 >::IncidentCube[f.index];
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index];
if( neighbors.neighbors.data[xx] && ic<my_ic ){ owner = false ; break; }
}
if( owner )
{
node_index_type myCount = ( i - xData.nodeOffset ) * HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() + _e.index;
xData._fMap[ myCount ] = 1;
// Set all the face indices
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 2 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 2 >() ; ic++ )
{
unsigned int xx = HyperCubeTables< Dim , 2 >::CellOffset[f.index][ic.index];
if( neighbors.neighbors.data[xx] ) xData.faceIndices( neighbors.neighbors.data[xx] )[ HyperCubeTables< Dim , 2 >::IncidentElementCoIndex[f.index][ic.index] ] = myCount;
}
}
}
};
// Try and get at the nodes outside of the slab through the neighbor key
ThreadPool::Parallel_for( sNodes.begin(depth,offset) , sNodes.end(depth,offset) , [&]( unsigned int thread , size_t i )
{
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
const TreeOctNode* node = sNodes.treeNodes[i];
ConstNeighbors& neighbors = neighborKey.getNeighbors( node );
for( int i=0 ; i<3 ; i++ ) for( int j=0 ; j<3 ; j++ ) for( int k=0 ; k<3 ; k++ ) if( !IsActiveNode< Dim >( neighbors.neighbors[i][j][k] ) ) neighbors.neighbors[i][j][k] = NULL;
if( sData0 )
{
ProcessCorners( *sData0 , neighbors , HyperCube::BACK , 0 ) , ProcessIEdges( *sData0 , neighbors , HyperCube::BACK , 0 ) , ProcessIFaces( *sData0 , neighbors , HyperCube::BACK , 0 );
const TreeOctNode* _node = neighbors.neighbors[1][1][0];
if( _node )
{
ProcessCorners( *sData0 , neighbors , HyperCube::FRONT , -1 ) , ProcessIEdges( *sData0 , neighbors , HyperCube::FRONT , -1 ) , ProcessIFaces( *sData0 , neighbors , HyperCube::FRONT , -1 );
sData0->_processed[ _node->nodeData.nodeIndex - sNodes.begin(depth,offset-1) ] = 1;
}
}
if( sData1 )
{
ProcessCorners( *sData1 , neighbors , HyperCube::FRONT , 0 ) , ProcessIEdges( *sData1 , neighbors , HyperCube::FRONT , 0 ) , ProcessIFaces( *sData1 , neighbors , HyperCube::FRONT , 0 );
const TreeOctNode* _node = neighbors.neighbors[1][1][2];
if( _node )
{
ProcessCorners( *sData1 , neighbors , HyperCube::BACK , 1 ) , ProcessIEdges( *sData1 , neighbors , HyperCube::BACK , 1 ) , ProcessIFaces( *sData1, neighbors , HyperCube::BACK , 1 );
sData1->_processed[ _node->nodeData.nodeIndex - sNodes.begin(depth,offset+1) ] = true;
}
}
if( xData ) ProcessXEdges( *xData , neighbors ) , ProcessXFaces( *xData , neighbors );
}
);
if( sData0 )
{
node_index_type off = sNodes.begin(depth,offset-1);
node_index_type size = sNodes.end(depth,offset-1) - sNodes.begin(depth,offset-1);
ThreadPool::Parallel_for( 0 , size , [&]( unsigned int thread , size_t i )
{
if( !sData0->_processed[i] )
{
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
const TreeOctNode* node = sNodes.treeNodes[i+off];
ConstNeighbors& neighbors = neighborKey.getNeighbors( node );
for( int i=0 ; i<3 ; i++ ) for( int j=0 ; j<3 ; j++ ) for( int k=0 ; k<3 ; k++ ) if( !IsActiveNode< Dim >( neighbors.neighbors[i][j][k] ) ) neighbors.neighbors[i][j][k] = NULL;
ProcessCorners( *sData0 , neighbors , HyperCube::FRONT , 0 ) , ProcessIEdges( *sData0 , neighbors , HyperCube::FRONT , 0 ) , ProcessIFaces( *sData0 , neighbors , HyperCube::FRONT , 0 );
}
}
);
}
if( sData1 )
{
node_index_type off = sNodes.begin(depth,offset+1);
node_index_type size = sNodes.end(depth,offset+1) - sNodes.begin(depth,offset+1);
ThreadPool::Parallel_for( 0 , size , [&]( unsigned int thread , size_t i )
{
if( !sData1->_processed[i] )
{
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
const TreeOctNode* node = sNodes.treeNodes[i+off];
ConstNeighbors& neighbors = neighborKey.getNeighbors( node );
for( int i=0 ; i<3 ; i++ ) for( int j=0 ; j<3 ; j++ ) for( int k=0 ; k<3 ; k++ ) if( !IsActiveNode< Dim >( neighbors.neighbors[i][j][k] ) ) neighbors.neighbors[i][j][k] = NULL;
ProcessCorners( *sData1 , neighbors , HyperCube::BACK , 0 ) , ProcessIEdges( *sData1 , neighbors , HyperCube::BACK , 0 ) , ProcessIFaces( *sData1 , neighbors , HyperCube::BACK , 0 );
}
}
);
}
auto SetICounts = [&]( SliceTableData& sData )
{
node_index_type cCount = 0 , eCount = 0 , fCount = 0;
for( node_index_type i=0 ; i<sData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; i++ ) if( sData._cMap[i] ) sData._cMap[i] = cCount++;
for( node_index_type i=0 ; i<sData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; i++ ) if( sData._eMap[i] ) sData._eMap[i] = eCount++;
for( node_index_type i=0 ; i<sData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ; i++ ) if( sData._fMap[i] ) sData._fMap[i] = fCount++;
ThreadPool::Parallel_for( 0 , sData.nodeCount , [&]( unsigned int , size_t i )
{
for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; j++ ) sData.cTable[i][j] = sData._cMap[ sData.cTable[i][j] ];
for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; j++ ) sData.eTable[i][j] = sData._eMap[ sData.eTable[i][j] ];
for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 2 >() ; j++ ) sData.fTable[i][j] = sData._fMap[ sData.fTable[i][j] ];
}
);
sData.cCount = cCount , sData.eCount = eCount , sData.fCount = fCount;
};
auto SetXCounts = [&]( XSliceTableData& xData )
{
node_index_type eCount = 0 , fCount = 0;
for( node_index_type i=0 ; i<xData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; i++ ) if( xData._eMap[i] ) xData._eMap[i] = eCount++;
for( node_index_type i=0 ; i<xData.nodeCount * (node_index_type)HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; i++ ) if( xData._fMap[i] ) xData._fMap[i] = fCount++;
ThreadPool::Parallel_for( 0 , xData.nodeCount , [&]( unsigned int , size_t i )
{
for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; j++ ) xData.eTable[i][j] = xData._eMap[ xData.eTable[i][j] ];
for( unsigned int j=0 ; j<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; j++ ) xData.fTable[i][j] = xData._fMap[ xData.fTable[i][j] ];
}
);
xData.eCount = eCount , xData.fCount = fCount;
};
if( sData0 ) SetICounts( *sData0 );
if( sData1 ) SetICounts( *sData1 );
if( xData ) SetXCounts( *xData );
}
};
//////////////////
// _SliceValues //
//////////////////
struct _SliceValues
{
typename SliceData::SliceTableData sliceData;
Pointer( Real ) cornerValues ; Pointer( Point< Real , Dim > ) cornerGradients ; Pointer( char ) cornerSet;
Pointer( _Key ) edgeKeys ; Pointer( char ) edgeSet;
Pointer( _FaceEdges ) faceEdges ; Pointer( char ) faceSet;
Pointer( char ) mcIndices;
std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher > faceEdgeMap;
std::unordered_map< _Key , std::pair< node_index_type, Vertex > , typename _Key::Hasher > edgeVertexMap;
std::unordered_map< _Key , _Key , typename _Key::Hasher > vertexPairMap;
std::vector< std::vector< std::pair< _Key , std::vector< _IsoEdge > > > > faceEdgeKeyValues;
std::vector< std::vector< std::pair< _Key , std::pair< node_index_type , Vertex > > > > edgeVertexKeyValues;
std::vector< std::vector< std::pair< _Key , _Key > > > vertexPairKeyValues;
_SliceValues( void )
{
_oldCCount = _oldECount = _oldFCount = 0;
_oldNCount = 0;
cornerValues = NullPointer( Real ) ; cornerGradients = NullPointer( Point< Real , Dim > ) ; cornerSet = NullPointer( char );
edgeKeys = NullPointer( _Key ) ; edgeSet = NullPointer( char );
faceEdges = NullPointer( _FaceEdges ) ; faceSet = NullPointer( char );
mcIndices = NullPointer( char );
edgeVertexKeyValues.resize( ThreadPool::NumThreads() );
vertexPairKeyValues.resize( ThreadPool::NumThreads() );
faceEdgeKeyValues.resize( ThreadPool::NumThreads() );
}
~_SliceValues( void )
{
_oldCCount = _oldECount = _oldFCount = 0;
_oldNCount = 0;
FreePointer( cornerValues ) ; FreePointer( cornerGradients ) ; FreePointer( cornerSet );
FreePointer( edgeKeys ) ; FreePointer( edgeSet );
FreePointer( faceEdges ) ; FreePointer( faceSet );
FreePointer( mcIndices );
}
void setEdgeVertexMap( void )
{
for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ )
{
for( int j=0 ; j<edgeVertexKeyValues[i].size() ; j++ ) edgeVertexMap[ edgeVertexKeyValues[i][j].first ] = edgeVertexKeyValues[i][j].second;
edgeVertexKeyValues[i].clear();
}
}
void setVertexPairMap( void )
{
for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ )
{
for( int j=0 ; j<vertexPairKeyValues[i].size() ; j++ )
{
vertexPairMap[ vertexPairKeyValues[i][j].first ] = vertexPairKeyValues[i][j].second;
vertexPairMap[ vertexPairKeyValues[i][j].second ] = vertexPairKeyValues[i][j].first;
}
vertexPairKeyValues[i].clear();
}
}
void setFaceEdgeMap( void )
{
for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ )
{
for( int j=0 ; j<faceEdgeKeyValues[i].size() ; j++ )
{
auto iter = faceEdgeMap.find( faceEdgeKeyValues[i][j].first );
if( iter==faceEdgeMap.end() ) faceEdgeMap[ faceEdgeKeyValues[i][j].first ] = faceEdgeKeyValues[i][j].second;
else for( int k=0 ; k<faceEdgeKeyValues[i][j].second.size() ; k++ ) iter->second.push_back( faceEdgeKeyValues[i][j].second[k] );
}
faceEdgeKeyValues[i].clear();
}
}
void reset( bool nonLinearFit )
{
faceEdgeMap.clear() , edgeVertexMap.clear() , vertexPairMap.clear();
for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ ) edgeVertexKeyValues[i].clear();
for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ ) vertexPairKeyValues[i].clear();
for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ ) faceEdgeKeyValues[i].clear();
if( _oldNCount<sliceData.nodeCount )
{
_oldNCount = sliceData.nodeCount;
FreePointer( mcIndices );
if( sliceData.nodeCount>0 ) mcIndices = AllocPointer< char >( _oldNCount );
}
if( _oldCCount<sliceData.cCount )
{
_oldCCount = sliceData.cCount;
FreePointer( cornerValues ) ; FreePointer( cornerGradients ) ; FreePointer( cornerSet );
if( sliceData.cCount>0 )
{
cornerValues = AllocPointer< Real >( _oldCCount );
if( nonLinearFit ) cornerGradients = AllocPointer< Point< Real , Dim > >( _oldCCount );
cornerSet = AllocPointer< char >( _oldCCount );
}
}
if( _oldECount<sliceData.eCount )
{
_oldECount = sliceData.eCount;
FreePointer( edgeKeys ) ; FreePointer( edgeSet );
edgeKeys = AllocPointer< _Key >( _oldECount );
edgeSet = AllocPointer< char >( _oldECount );
}
if( _oldFCount<sliceData.fCount )
{
_oldFCount = sliceData.fCount;
FreePointer( faceEdges ) ; FreePointer( faceSet );
faceEdges = AllocPointer< _FaceEdges >( _oldFCount );
faceSet = AllocPointer< char >( _oldFCount );
}
if( sliceData.cCount>0 ) memset( cornerSet , 0 , sizeof( char ) * sliceData.cCount );
if( sliceData.eCount>0 ) memset( edgeSet , 0 , sizeof( char ) * sliceData.eCount );
if( sliceData.fCount>0 ) memset( faceSet , 0 , sizeof( char ) * sliceData.fCount );
}
protected:
node_index_type _oldCCount , _oldECount , _oldFCount;
node_index_type _oldNCount;
};
///////////////////
// _XSliceValues //
///////////////////
struct _XSliceValues
{
typename SliceData::XSliceTableData xSliceData;
Pointer( _Key ) edgeKeys ; Pointer( char ) edgeSet;
Pointer( _FaceEdges ) faceEdges ; Pointer( char ) faceSet;
std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher > faceEdgeMap;
std::unordered_map< _Key , std::pair< node_index_type , Vertex > , typename _Key::Hasher > edgeVertexMap;
std::unordered_map< _Key , _Key , typename _Key::Hasher > vertexPairMap;
std::vector< std::vector< std::pair< _Key , std::pair< node_index_type , Vertex > > > > edgeVertexKeyValues;
std::vector< std::vector< std::pair< _Key , _Key > > > vertexPairKeyValues;
std::vector< std::vector< std::pair< _Key , std::vector< _IsoEdge > > > > faceEdgeKeyValues;
_XSliceValues( void )
{
_oldECount = _oldFCount = 0;
edgeKeys = NullPointer( _Key ) ; edgeSet = NullPointer( char );
faceEdges = NullPointer( _FaceEdges ) ; faceSet = NullPointer( char );
edgeVertexKeyValues.resize( ThreadPool::NumThreads() );
vertexPairKeyValues.resize( ThreadPool::NumThreads() );
faceEdgeKeyValues.resize( ThreadPool::NumThreads() );
}
~_XSliceValues( void )
{
_oldECount = _oldFCount = 0;
FreePointer( edgeKeys ) ; FreePointer( edgeSet );
FreePointer( faceEdges ) ; FreePointer( faceSet );
}
void setEdgeVertexMap( void )
{
for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ )
{
for( int j=0 ; j<edgeVertexKeyValues[i].size() ; j++ ) edgeVertexMap[ edgeVertexKeyValues[i][j].first ] = edgeVertexKeyValues[i][j].second;
edgeVertexKeyValues[i].clear();
}
}
void setVertexPairMap( void )
{
for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ )
{
for( int j=0 ; j<vertexPairKeyValues[i].size() ; j++ )
{
vertexPairMap[ vertexPairKeyValues[i][j].first ] = vertexPairKeyValues[i][j].second;
vertexPairMap[ vertexPairKeyValues[i][j].second ] = vertexPairKeyValues[i][j].first;
}
vertexPairKeyValues[i].clear();
}
}
void setFaceEdgeMap( void )
{
for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ )
{
for( int j=0 ; j<faceEdgeKeyValues[i].size() ; j++ )
{
auto iter = faceEdgeMap.find( faceEdgeKeyValues[i][j].first );
if( iter==faceEdgeMap.end() ) faceEdgeMap[ faceEdgeKeyValues[i][j].first ] = faceEdgeKeyValues[i][j].second;
else for( int k=0 ; k<faceEdgeKeyValues[i][j].second.size() ; k++ ) iter->second.push_back( faceEdgeKeyValues[i][j].second[k] );
}
faceEdgeKeyValues[i].clear();
}
}
void reset( void )
{
faceEdgeMap.clear() , edgeVertexMap.clear() , vertexPairMap.clear();
for( node_index_type i=0 ; i<(node_index_type)edgeVertexKeyValues.size() ; i++ ) edgeVertexKeyValues[i].clear();
for( node_index_type i=0 ; i<(node_index_type)vertexPairKeyValues.size() ; i++ ) vertexPairKeyValues[i].clear();
for( node_index_type i=0 ; i<(node_index_type)faceEdgeKeyValues.size() ; i++ ) faceEdgeKeyValues[i].clear();
if( _oldECount<xSliceData.eCount )
{
_oldECount = xSliceData.eCount;
FreePointer( edgeKeys ) ; FreePointer( edgeSet );
edgeKeys = AllocPointer< _Key >( _oldECount );
edgeSet = AllocPointer< char >( _oldECount );
}
if( _oldFCount<xSliceData.fCount )
{
_oldFCount = xSliceData.fCount;
FreePointer( faceEdges ) ; FreePointer( faceSet );
faceEdges = AllocPointer< _FaceEdges >( _oldFCount );
faceSet = AllocPointer< char >( _oldFCount );
}
if( xSliceData.eCount>0 ) memset( edgeSet , 0 , sizeof( char ) * xSliceData.eCount );
if( xSliceData.fCount>0 ) memset( faceSet , 0 , sizeof( char ) * xSliceData.fCount );
}
protected:
node_index_type _oldECount , _oldFCount;
};
/////////////////
// _SlabValues //
/////////////////
struct _SlabValues
{
protected:
_XSliceValues _xSliceValues[2];
_SliceValues _sliceValues[2];
public:
_SliceValues& sliceValues( int idx ){ return _sliceValues[idx&1]; }
const _SliceValues& sliceValues( int idx ) const { return _sliceValues[idx&1]; }
_XSliceValues& xSliceValues( int idx ){ return _xSliceValues[idx&1]; }
const _XSliceValues& xSliceValues( int idx ) const { return _xSliceValues[idx&1]; }
};
template< unsigned int ... FEMSigs >
static void _SetSliceIsoCorners( const FEMTree< Dim , Real >& tree , ConstPointer( Real ) coefficients , ConstPointer( Real ) coarseCoefficients , Real isoValue , LocalDepth depth , int slice , std::vector< _SlabValues >& slabValues , const _Evaluator< UIntPack< FEMSigs ... > , 1 >& evaluator )
{
if( slice>0 ) _SetSliceIsoCorners< FEMSigs ... >( tree , coefficients , coarseCoefficients , isoValue , depth , slice , HyperCube::FRONT , slabValues , evaluator );
if( slice<(1<<depth) ) _SetSliceIsoCorners< FEMSigs ... >( tree , coefficients , coarseCoefficients , isoValue , depth , slice , HyperCube::BACK , slabValues , evaluator );
}
template< unsigned int ... FEMSigs >
static void _SetSliceIsoCorners( const FEMTree< Dim , Real >& tree , ConstPointer( Real ) coefficients , ConstPointer( Real ) coarseCoefficients , Real isoValue , LocalDepth depth , int slice , HyperCube::Direction zDir , std::vector< _SlabValues >& slabValues , const _Evaluator< UIntPack< FEMSigs ... > , 1 >& evaluator )
{
static const unsigned int FEMDegrees[] = { FEMSignature< FEMSigs >::Degree ... };
_SliceValues& sValues = slabValues[depth].sliceValues( slice );
bool useBoundaryEvaluation = false;
for( int d=0 ; d<Dim ; d++ ) if( FEMDegrees[d]==0 || ( FEMDegrees[d]==1 && sValues.cornerGradients ) ) useBoundaryEvaluation = true;
std::vector< ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > > > neighborKeys( ThreadPool::NumThreads() );
std::vector< ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > > > bNeighborKeys( ThreadPool::NumThreads() );
if( useBoundaryEvaluation ) for( size_t i=0 ; i<neighborKeys.size() ; i++ ) bNeighborKeys[i].set( tree._localToGlobal( depth ) );
else for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) );
ThreadPool::Parallel_for( tree._sNodesBegin(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
{
Real squareValues[ HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ];
ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey = neighborKeys[ thread ];
ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bNeighborKey = bNeighborKeys[ thread ];
TreeNode* leaf = tree._sNodes.treeNodes[i];
if( !IsActiveNode< Dim >( leaf->children ) )
{
const typename SliceData::SquareCornerIndices& cIndices = sValues.sliceData.cornerIndices( leaf );
bool isInterior = tree._isInteriorlySupported( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , leaf->parent );
if( useBoundaryEvaluation ) bNeighborKey.getNeighbors( leaf );
else neighborKey.getNeighbors( leaf );
for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ )
{
typename HyperCube::Cube< Dim >::template Element< 0 > c( zDir , _c.index );
node_index_type vIndex = cIndices[_c.index];
if( !sValues.cornerSet[vIndex] )
{
if( sValues.cornerGradients )
{
CumulativeDerivativeValues< Real , Dim , 1 > p;
if( useBoundaryEvaluation ) p = tree.template _getCornerValues< Real , 1 >( bNeighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior );
else p = tree.template _getCornerValues< Real , 1 >( neighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior );
sValues.cornerValues[vIndex] = p[0] , sValues.cornerGradients[vIndex] = Point< Real , Dim >( p[1] , p[2] , p[3] );
}
else
{
if( useBoundaryEvaluation ) sValues.cornerValues[vIndex] = tree.template _getCornerValues< Real , 0 >( bNeighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior )[0];
else sValues.cornerValues[vIndex] = tree.template _getCornerValues< Real , 0 >( neighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior )[0];
}
sValues.cornerSet[vIndex] = 1;
}
squareValues[_c.index] = sValues.cornerValues[ vIndex ];
TreeNode* node = leaf;
LocalDepth _depth = depth;
int _slice = slice;
while( tree._isValidSpaceNode( node->parent ) && (node-node->parent->children)==c.index )
{
node = node->parent , _depth-- , _slice >>= 1;
_SliceValues& _sValues = slabValues[_depth].sliceValues( _slice );
const typename SliceData::SquareCornerIndices& _cIndices = _sValues.sliceData.cornerIndices( node );
node_index_type _vIndex = _cIndices[_c.index];
_sValues.cornerValues[_vIndex] = sValues.cornerValues[vIndex];
if( _sValues.cornerGradients ) _sValues.cornerGradients[_vIndex] = sValues.cornerGradients[vIndex];
_sValues.cornerSet[_vIndex] = 1;
}
}
sValues.mcIndices[ i - sValues.sliceData.nodeOffset ] = HyperCube::Cube< Dim-1 >::MCIndex( squareValues , isoValue );
}
}
}
);
}
/////////////////
// _VertexData //
/////////////////
class _VertexData
{
public:
static _Key EdgeIndex( const TreeNode* node , typename HyperCube::Cube< Dim >::template Element< 1 > e , int maxDepth )
{
_Key key;
const HyperCube::Direction* x = SliceData::template HyperCubeTables< Dim , 1 >::Directions[ e.index ];
int d , off[Dim];
node->depthAndOffset( d , off );
for( int dd=0 ; dd<Dim ; dd++ )
{
if( x[dd]==HyperCube::CROSS )
{
key[(dd+0)%3] = (int)BinaryNode::CornerIndex( maxDepth+1 , d+1 , off[(dd+0)%3]<<1 , 1 );
key[(dd+1)%3] = (int)BinaryNode::CornerIndex( maxDepth+1 , d , off[(dd+1)%3] , x[(dd+1)%3]==HyperCube::BACK ? 0 : 1 );
key[(dd+2)%3] = (int)BinaryNode::CornerIndex( maxDepth+1 , d , off[(dd+2)%3] , x[(dd+2)%3]==HyperCube::BACK ? 0 : 1 );
}
}
return key;
}
static _Key FaceIndex( const TreeNode* node , typename HyperCube::Cube< Dim >::template Element< Dim-1 > f , int maxDepth )
{
_Key key;
const HyperCube::Direction* x = SliceData::template HyperCubeTables< Dim , 2 >::Directions[ f.index ];
int d , o[Dim];
node->depthAndOffset( d , o );
for( int dd=0 ; dd<Dim ; dd++ )
if( x[dd]==HyperCube::CROSS ) key[dd] = (int)BinaryNode::CornerIndex( maxDepth+1 , d+1 , o[dd]<<1 , 1 );
else key[dd] = (int)BinaryNode::CornerIndex( maxDepth+1 , d , o[dd] , x[dd]==HyperCube::BACK ? 0 : 1 );
return key;
}
};
template< unsigned int WeightDegree , typename Data , unsigned int DataSig >
static void _SetSliceIsoVertices( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , LocalDepth depth , int slice , node_index_type& vOffset , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< _SlabValues >& slabValues , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex )
{
if( slice>0 ) _SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , depth , slice , HyperCube::FRONT , vOffset , mesh , slabValues , SetVertex );
if( slice<(1<<depth) ) _SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , depth , slice , HyperCube::BACK , vOffset , mesh , slabValues , SetVertex );
}
template< unsigned int WeightDegree , typename Data , unsigned int DataSig >
static void _SetSliceIsoVertices( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , LocalDepth depth , int slice , HyperCube::Direction zDir , node_index_type& vOffset , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< _SlabValues >& slabValues , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex )
{
static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
_SliceValues& sValues = slabValues[depth].sliceValues( slice );
// [WARNING] In the case Degree=2, these two keys are the same, so we don't have to maintain them separately.
std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > > > weightKeys( ThreadPool::NumThreads() );
std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > > > dataKeys( ThreadPool::NumThreads() );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ) , weightKeys[i].set( tree._localToGlobal( depth ) ) , dataKeys[i].set( tree._localToGlobal( depth ) );
ThreadPool::Parallel_for( tree._sNodesBegin(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
{
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey = weightKeys[ thread ];
ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > >& dataKey = dataKeys[ thread ];
TreeNode* leaf = tree._sNodes.treeNodes[i];
if( !IsActiveNode< Dim >( leaf->children ) )
{
node_index_type idx = (node_index_type)i - sValues.sliceData.nodeOffset;
const typename SliceData::SquareEdgeIndices& eIndices = sValues.sliceData.edgeIndices( leaf );
if( HyperCube::Cube< Dim-1 >::HasMCRoots( sValues.mcIndices[idx] ) )
{
neighborKey.getNeighbors( leaf );
if( densityWeights ) weightKey.getNeighbors( leaf );
if( data ) dataKey.getNeighbors( leaf );
for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ )
if( HyperCube::Cube< 1 >::HasMCRoots( HyperCube::Cube< Dim-1 >::ElementMCIndex( _e , sValues.mcIndices[idx] ) ) )
{
typename HyperCube::Cube< Dim >::template Element< 1 > e( zDir , _e.index );
node_index_type vIndex = eIndices[_e.index];
volatile char &edgeSet = sValues.edgeSet[vIndex];
if( !edgeSet )
{
Vertex vertex;
_Key key = _VertexData::EdgeIndex( leaf , e , tree._localToGlobal( tree._maxDepth ) );
_GetIsoVertex< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , weightKey , dataKey , leaf , _e , zDir , sValues , vertex , SetVertex );
bool stillOwner = false;
std::pair< node_index_type , Vertex > hashed_vertex;
{
std::lock_guard< std::mutex > lock( _pointInsertionMutex );
if( !edgeSet )
{
mesh.addOutOfCorePoint( vertex );
edgeSet = 1;
hashed_vertex = std::pair< node_index_type , Vertex >( vOffset , vertex );
sValues.edgeKeys[ vIndex ] = key;
vOffset++;
stillOwner = true;
}
}
if( stillOwner ) sValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) );
if( stillOwner )
{
// We only need to pass the iso-vertex down if the edge it lies on is adjacent to a coarser leaf
auto IsNeeded = [&]( unsigned int depth )
{
bool isNeeded = false;
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = SliceData::template HyperCubeTables< Dim , 1 >::IncidentCube[e.index];
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) if( ic!=my_ic )
{
unsigned int xx = SliceData::template HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index];
isNeeded |= !tree._isValidSpaceNode( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] );
}
return isNeeded;
};
if( IsNeeded( depth ) )
{
const typename HyperCube::Cube< Dim >::template Element< Dim-1 > *f = SliceData::template HyperCubeTables< Dim , 1 , Dim-1 >::OverlapElements[e.index];
for( int k=0 ; k<2 ; k++ )
{
TreeNode* node = leaf;
LocalDepth _depth = depth;
int _slice = slice;
while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f[k].index][(unsigned int)(node-node->parent->children) ] )
{
node = node->parent , _depth-- , _slice >>= 1;
_SliceValues& _sValues = slabValues[_depth].sliceValues( _slice );
_sValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) );
if( !IsNeeded( _depth ) ) break;
}
}
}
}
}
}
}
}
}
}
);
}
////////////////////
// Iso-Extraction //
////////////////////
template< unsigned int WeightDegree , typename Data , unsigned int DataSig >
static void _SetXSliceIsoVertices( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , LocalDepth depth , int slab , node_index_type &vOffset , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< _SlabValues >& slabValues , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex )
{
static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
_SliceValues& bValues = slabValues[depth].sliceValues ( slab );
_SliceValues& fValues = slabValues[depth].sliceValues ( slab+1 );
_XSliceValues& xValues = slabValues[depth].xSliceValues( slab );
// [WARNING] In the case Degree=2, these two keys are the same, so we don't have to maintain them separately.
std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > > > weightKeys( ThreadPool::NumThreads() );
std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > > > dataKeys( ThreadPool::NumThreads() );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ) , weightKeys[i].set( tree._localToGlobal( depth ) ) , dataKeys[i].set( tree._localToGlobal( depth ) );
ThreadPool::Parallel_for( tree._sNodesBegin(depth,slab) , tree._sNodesEnd(depth,slab) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
{
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey = weightKeys[ thread ];
ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > >& dataKey = dataKeys[ thread ];
TreeNode* leaf = tree._sNodes.treeNodes[i];
if( !IsActiveNode< Dim >( leaf->children ) )
{
unsigned char mcIndex = ( bValues.mcIndices[ i - bValues.sliceData.nodeOffset ] ) | ( fValues.mcIndices[ i - fValues.sliceData.nodeOffset ] )<<4;
const typename SliceData::SquareCornerIndices& eIndices = xValues.xSliceData.edgeIndices( leaf );
if( HyperCube::Cube< Dim >::HasMCRoots( mcIndex ) )
{
neighborKey.getNeighbors( leaf );
if( densityWeights ) weightKey.getNeighbors( leaf );
if( data ) dataKey.getNeighbors( leaf );
for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ )
{
typename HyperCube::Cube< Dim >::template Element< 1 > e( HyperCube::CROSS , _c.index );
unsigned int _mcIndex = HyperCube::Cube< Dim >::ElementMCIndex( e , mcIndex );
if( HyperCube::Cube< 1 >::HasMCRoots( _mcIndex ) )
{
node_index_type vIndex = eIndices[_c.index];
volatile char &edgeSet = xValues.edgeSet[vIndex];
if( !edgeSet )
{
Vertex vertex;
_Key key = _VertexData::EdgeIndex( leaf , e.index , tree._localToGlobal( tree._maxDepth ) );
_GetIsoVertex< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , weightKey , dataKey , leaf , _c , bValues , fValues , vertex , SetVertex );
bool stillOwner = false;
std::pair< node_index_type , Vertex > hashed_vertex;
{
std::lock_guard< std::mutex > lock( _pointInsertionMutex );
if( !edgeSet )
{
mesh.addOutOfCorePoint( vertex );
edgeSet = 1;
hashed_vertex = std::pair< node_index_type , Vertex >( vOffset , vertex );
xValues.edgeKeys[ vIndex ] = key;
vOffset++;
stillOwner = true;
}
}
if( stillOwner ) xValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) );
if( stillOwner )
{
// We only need to pass the iso-vertex down if the edge it lies on is adjacent to a coarser leaf
auto IsNeeded = [&]( unsigned int depth )
{
bool isNeeded = false;
typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > my_ic = SliceData::template HyperCubeTables< Dim , 1 >::IncidentCube[e.index];
for( typename HyperCube::Cube< Dim >::template IncidentCubeIndex< 1 > ic ; ic<HyperCube::Cube< Dim >::template IncidentCubeNum< 1 >() ; ic++ ) if( ic!=my_ic )
{
unsigned int xx = SliceData::template HyperCubeTables< Dim , 1 >::CellOffset[e.index][ic.index];
isNeeded |= !tree._isValidSpaceNode( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] );
}
return isNeeded;
};
if( IsNeeded( depth ) )
{
const typename HyperCube::Cube< Dim >::template Element< Dim-1 > *f = SliceData::template HyperCubeTables< Dim , 1 , Dim-1 >::OverlapElements[e.index];
for( int k=0 ; k<2 ; k++ )
{
TreeNode* node = leaf;
LocalDepth _depth = depth;
int _slab = slab;
while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f[k].index][(unsigned int)(node-node->parent->children) ] )
{
node = node->parent , _depth-- , _slab >>= 1;
_XSliceValues& _xValues = slabValues[_depth].xSliceValues( _slab );
_xValues.edgeVertexKeyValues[ thread ].push_back( std::pair< _Key , std::pair< node_index_type , Vertex > >( key , hashed_vertex ) );
if( !IsNeeded( _depth ) ) break;
}
}
}
}
}
}
}
}
}
}
}
);
}
static void _CopyFinerSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , std::vector< _SlabValues >& slabValues )
{
if( slice>0 ) _CopyFinerSliceIsoEdgeKeys( tree , depth , slice , HyperCube::FRONT , slabValues );
if( slice<(1<<depth) ) _CopyFinerSliceIsoEdgeKeys( tree , depth , slice , HyperCube::BACK , slabValues );
}
static void _CopyFinerSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , HyperCube::Direction zDir , std::vector< _SlabValues >& slabValues )
{
_SliceValues& pSliceValues = slabValues[depth ].sliceValues(slice );
_SliceValues& cSliceValues = slabValues[depth+1].sliceValues(slice<<1);
typename SliceData::SliceTableData& pSliceData = pSliceValues.sliceData;
typename SliceData::SliceTableData& cSliceData = cSliceValues.sliceData;
ThreadPool::Parallel_for( tree._sNodesBegin(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) if( IsActiveNode< Dim >( tree._sNodes.treeNodes[i]->children ) )
{
typename SliceData::SquareEdgeIndices& pIndices = pSliceData.edgeIndices( (node_index_type)i );
// Copy the edges that overlap the coarser edges
for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ )
{
node_index_type pIndex = pIndices[_e.index];
if( !pSliceValues.edgeSet[ pIndex ] )
{
typename HyperCube::Cube< Dim >::template Element< 1 > e( zDir , _e.index );
const typename HyperCube::Cube< Dim >::template Element< 0 > *c = SliceData::template HyperCubeTables< Dim , 1 , 0 >::OverlapElements[e.index];
// [SANITY CHECK]
// if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[0].index )!=tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[1].index ) ) ERROR_OUT( "Finer edges should both be valid or invalid" );
if( !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[0].index ) || !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[1].index ) ) continue;
node_index_type cIndex1 = cSliceData.edgeIndices( tree._sNodes.treeNodes[i]->children + c[0].index )[_e.index];
node_index_type cIndex2 = cSliceData.edgeIndices( tree._sNodes.treeNodes[i]->children + c[1].index )[_e.index];
if( cSliceValues.edgeSet[cIndex1] != cSliceValues.edgeSet[cIndex2] )
{
_Key key;
if( cSliceValues.edgeSet[cIndex1] ) key = cSliceValues.edgeKeys[cIndex1];
else key = cSliceValues.edgeKeys[cIndex2];
pSliceValues.edgeKeys[pIndex] = key;
pSliceValues.edgeSet[pIndex] = 1;
}
else if( cSliceValues.edgeSet[cIndex1] && cSliceValues.edgeSet[cIndex2] )
{
_Key key1 = cSliceValues.edgeKeys[cIndex1] , key2 = cSliceValues.edgeKeys[cIndex2];
pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key1 , key2 ) );
const TreeNode* node = tree._sNodes.treeNodes[i];
LocalDepth _depth = depth;
int _slice = slice;
while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 1 , 0 >::Overlap[e.index][(unsigned int)(node-node->parent->children) ] )
{
node = node->parent , _depth-- , _slice >>= 1;
_SliceValues& _pSliceValues = slabValues[_depth].sliceValues(_slice);
_pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key1 , key2 ) );
}
}
}
}
}
}
);
}
static void _CopyFinerXSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slab , std::vector< _SlabValues>& slabValues )
{
_XSliceValues& pSliceValues = slabValues[depth ].xSliceValues(slab);
_XSliceValues& cSliceValues0 = slabValues[depth+1].xSliceValues( (slab<<1)|0 );
_XSliceValues& cSliceValues1 = slabValues[depth+1].xSliceValues( (slab<<1)|1 );
typename SliceData::XSliceTableData& pSliceData = pSliceValues.xSliceData;
typename SliceData::XSliceTableData& cSliceData0 = cSliceValues0.xSliceData;
typename SliceData::XSliceTableData& cSliceData1 = cSliceValues1.xSliceData;
ThreadPool::Parallel_for( tree._sNodesBegin(depth,slab) , tree._sNodesEnd(depth,slab) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) if( IsActiveNode< Dim >( tree._sNodes.treeNodes[i]->children ) )
{
typename SliceData::SquareCornerIndices& pIndices = pSliceData.edgeIndices( (node_index_type)i );
for( typename HyperCube::Cube< Dim-1 >::template Element< 0 > _c ; _c<HyperCube::Cube< Dim-1 >::template ElementNum< 0 >() ; _c++ )
{
typename HyperCube::Cube< Dim >::template Element< 1 > e( HyperCube::CROSS , _c.index );
node_index_type pIndex = pIndices[ _c.index ];
if( !pSliceValues.edgeSet[pIndex] )
{
typename HyperCube::Cube< Dim >::template Element< 0 > c0( HyperCube::BACK , _c.index ) , c1( HyperCube::FRONT , _c.index );
// [SANITY CHECK]
// if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c0 )!=tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c1 ) ) ERROR_OUT( "Finer edges should both be valid or invalid" );
if( !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c0.index ) || !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c1.index ) ) continue;
node_index_type cIndex0 = cSliceData0.edgeIndices( tree._sNodes.treeNodes[i]->children + c0.index )[_c.index];
node_index_type cIndex1 = cSliceData1.edgeIndices( tree._sNodes.treeNodes[i]->children + c1.index )[_c.index];
// If there's one zero-crossing along the edge
if( cSliceValues0.edgeSet[cIndex0] != cSliceValues1.edgeSet[cIndex1] )
{
_Key key;
if( cSliceValues0.edgeSet[cIndex0] ) key = cSliceValues0.edgeKeys[cIndex0]; //, vPair = cSliceValues0.edgeVertexMap.find( key )->second;
else key = cSliceValues1.edgeKeys[cIndex1]; //, vPair = cSliceValues1.edgeVertexMap.find( key )->second;
pSliceValues.edgeKeys[ pIndex ] = key;
pSliceValues.edgeSet[ pIndex ] = 1;
}
// If there's are two zero-crossings along the edge
else if( cSliceValues0.edgeSet[cIndex0] && cSliceValues1.edgeSet[cIndex1] )
{
_Key key0 = cSliceValues0.edgeKeys[cIndex0] , key1 = cSliceValues1.edgeKeys[cIndex1];
pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key0 , key1 ) );
const TreeNode* node = tree._sNodes.treeNodes[i];
LocalDepth _depth = depth;
int _slab = slab;
while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 1 , 0 >::Overlap[e.index][(unsigned int)(node-node->parent->children) ] )
{
node = node->parent , _depth-- , _slab>>= 1;
_SliceValues& _pSliceValues = slabValues[_depth].sliceValues(_slab);
_pSliceValues.vertexPairKeyValues[ thread ].push_back( std::pair< _Key , _Key >( key0 , key1 ) );
}
}
}
}
}
}
);
}
static void _SetSliceIsoEdges( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , std::vector< _SlabValues >& slabValues )
{
if( slice>0 ) _SetSliceIsoEdges( tree , depth , slice , HyperCube::FRONT , slabValues );
if( slice<(1<<depth) ) _SetSliceIsoEdges( tree , depth , slice , HyperCube::BACK , slabValues );
}
static void _SetSliceIsoEdges( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slice , HyperCube::Direction zDir , std::vector< _SlabValues >& slabValues )
{
_SliceValues& sValues = slabValues[depth].sliceValues( slice );
std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) );
ThreadPool::Parallel_for( tree._sNodesBegin(depth, slice-(zDir==HyperCube::BACK ? 0 : 1)) , tree._sNodesEnd(depth,slice-(zDir==HyperCube::BACK ? 0 : 1)) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
{
int isoEdges[ 2 * HyperCube::MarchingSquares::MAX_EDGES ];
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
TreeNode* leaf = tree._sNodes.treeNodes[i];
if( !IsActiveNode< Dim >( leaf->children ) )
{
node_index_type idx = (node_index_type)i - sValues.sliceData.nodeOffset;
const typename SliceData::SquareEdgeIndices& eIndices = sValues.sliceData.edgeIndices( leaf );
const typename SliceData::SquareFaceIndices& fIndices = sValues.sliceData.faceIndices( leaf );
unsigned char mcIndex = sValues.mcIndices[idx];
if( !sValues.faceSet[ fIndices[0] ] )
{
neighborKey.getNeighbors( leaf );
unsigned int xx = WindowIndex< IsotropicUIntPack< Dim , 3 > , IsotropicUIntPack< Dim , 1 > >::Index + (zDir==HyperCube::BACK ? -1 : 1);
if( !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] ) || !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx]->children ) )
{
_FaceEdges fe;
fe.count = HyperCube::MarchingSquares::AddEdgeIndices( mcIndex , isoEdges );
for( int j=0 ; j<fe.count ; j++ ) for( int k=0 ; k<2 ; k++ )
{
if( !sValues.edgeSet[ eIndices[ isoEdges[2*j+k] ] ] ) ERROR_OUT( "Edge not set: " , slice , " / " , 1<<depth );
fe.edges[j][k] = sValues.edgeKeys[ eIndices[ isoEdges[2*j+k] ] ];
}
sValues.faceSet[ fIndices[0] ] = 1;
sValues.faceEdges[ fIndices[0] ] = fe;
TreeNode* node = leaf;
LocalDepth _depth = depth;
int _slice = slice;
typename HyperCube::Cube< Dim >::template Element< Dim-1 > f( zDir , 0 );
std::vector< _IsoEdge > edges;
edges.resize( fe.count );
for( int j=0 ; j<fe.count ; j++ ) edges[j] = fe.edges[j];
while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f.index][(unsigned int)(node-node->parent->children) ] )
{
node = node->parent , _depth-- , _slice >>= 1;
if( IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx] ) && IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx]->children ) ) break;
_Key key = _VertexData::FaceIndex( node , f , tree._localToGlobal( tree._maxDepth ) );
_SliceValues& _sValues = slabValues[_depth].sliceValues( _slice );
_sValues.faceEdgeKeyValues[ thread ].push_back( std::pair< _Key , std::vector< _IsoEdge > >( key , edges ) );
}
}
}
}
}
}
);
}
static void _SetXSliceIsoEdges( const FEMTree< Dim , Real >& tree , LocalDepth depth , int slab , std::vector< _SlabValues >& slabValues )
{
_SliceValues& bValues = slabValues[depth].sliceValues ( slab );
_SliceValues& fValues = slabValues[depth].sliceValues ( slab+1 );
_XSliceValues& xValues = slabValues[depth].xSliceValues( slab );
std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) );
ThreadPool::Parallel_for( tree._sNodesBegin(depth,slab) , tree._sNodesEnd(depth,slab) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
{
int isoEdges[ 2 * HyperCube::MarchingSquares::MAX_EDGES ];
ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
TreeNode* leaf = tree._sNodes.treeNodes[i];
if( !IsActiveNode< Dim >( leaf->children ) )
{
const typename SliceData::SquareCornerIndices& cIndices = xValues.xSliceData.edgeIndices( leaf );
const typename SliceData::SquareEdgeIndices& eIndices = xValues.xSliceData.faceIndices( leaf );
unsigned char mcIndex = ( bValues.mcIndices[ i - bValues.sliceData.nodeOffset ] ) | ( fValues.mcIndices[ i - fValues.sliceData.nodeOffset ]<<4 );
{
neighborKey.getNeighbors( leaf );
// Iterate over the edges on the back
for( typename HyperCube::Cube< Dim-1 >::template Element< 1 > _e ; _e<HyperCube::Cube< Dim-1 >::template ElementNum< 1 >() ; _e++ )
{
typename HyperCube::Cube< Dim >::template Element< 2 > f( HyperCube::CROSS , _e.index );
unsigned char _mcIndex = HyperCube::Cube< Dim >::template ElementMCIndex< 2 >( f , mcIndex );
unsigned int xx = SliceData::template HyperCubeTables< Dim , 2 >::CellOffsetAntipodal[f.index];
if( !xValues.faceSet[ eIndices[_e.index] ] && ( !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx] ) || !IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( depth ) ].neighbors.data[xx]->children ) ) )
{
_FaceEdges fe;
fe.count = HyperCube::MarchingSquares::AddEdgeIndices( _mcIndex , isoEdges );
for( int j=0 ; j<fe.count ; j++ ) for( int k=0 ; k<2 ; k++ )
{
typename HyperCube::Cube< Dim >::template Element< 1 > e( f , typename HyperCube::Cube< Dim-1 >::template Element< 1 >( isoEdges[2*j+k] ) );
HyperCube::Direction dir ; unsigned int coIndex;
e.factor( dir , coIndex );
if( dir==HyperCube::CROSS ) // Cross-edge
{
node_index_type idx = cIndices[ coIndex ];
if( !xValues.edgeSet[ idx ] ) ERROR_OUT( "Edge not set: " , slab , " / " , 1<<depth );
fe.edges[j][k] = xValues.edgeKeys[ idx ];
}
else
{
const _SliceValues& sValues = dir==HyperCube::BACK ? bValues : fValues;
node_index_type idx = sValues.sliceData.edgeIndices((node_index_type)i)[ coIndex ];
if( !sValues.edgeSet[ idx ] ) ERROR_OUT( "Edge not set: " , slab , " / " , 1<<depth );
fe.edges[j][k] = sValues.edgeKeys[ idx ];
}
}
xValues.faceSet[ eIndices[_e.index] ] = 1;
xValues.faceEdges[ eIndices[_e.index] ] = fe;
TreeNode* node = leaf;
LocalDepth _depth = depth;
int _slab = slab;
std::vector< _IsoEdge > edges;
edges.resize( fe.count );
for( int j=0 ; j<fe.count ; j++ ) edges[j] = fe.edges[j];
while( tree._isValidSpaceNode( node->parent ) && SliceData::template HyperCubeTables< Dim , 2 , 0 >::Overlap[f.index][(unsigned int)(node-node->parent->children) ] )
{
node = node->parent , _depth-- , _slab >>= 1;
if( IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx] ) && IsActiveNode< Dim >( neighborKey.neighbors[ tree._localToGlobal( _depth ) ].neighbors.data[xx]->children ) ) break;
_Key key = _VertexData::FaceIndex( node , f , tree._localToGlobal( tree._maxDepth ) );
_XSliceValues& _xValues = slabValues[_depth].xSliceValues( _slab );
_xValues.faceEdgeKeyValues[ thread ].push_back( std::pair< _Key , std::vector< _IsoEdge > >( key , edges ) );
}
}
}
}
}
}
}
);
}
static void _SetIsoSurface( const FEMTree< Dim , Real >& tree , LocalDepth depth , int offset , const _SliceValues& bValues , const _SliceValues& fValues , const _XSliceValues& xValues , CoredMeshData< Vertex , node_index_type >& mesh , bool polygonMesh , bool addBarycenter , node_index_type& vOffset , bool flipOrientation )
{
std::vector< std::pair< node_index_type , Vertex > > polygon;
std::vector< std::vector< _IsoEdge > > edgess( ThreadPool::NumThreads() );
ThreadPool::Parallel_for( tree._sNodesBegin(depth,offset) , tree._sNodesEnd(depth,offset) , [&]( unsigned int thread , size_t i )
{
if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
{
std::vector< _IsoEdge >& edges = edgess[ thread ];
TreeNode* leaf = tree._sNodes.treeNodes[i];
int res = 1<<depth;
LocalDepth d ; LocalOffset off;
tree._localDepthAndOffset( leaf , d , off );
bool inBounds = off[0]>=0 && off[0]<res && off[1]>=0 && off[1]<res && off[2]>=0 && off[2]<res;
if( inBounds && !IsActiveNode< Dim >( leaf->children ) )
{
edges.clear();
unsigned char mcIndex = ( bValues.mcIndices[ i - bValues.sliceData.nodeOffset ] ) | ( fValues.mcIndices[ i - fValues.sliceData.nodeOffset ]<<4 );
// [WARNING] Just because the node looks empty doesn't mean it doesn't get eges from finer neighbors
{
// Gather the edges from the faces (with the correct orientation)
for( typename HyperCube::Cube< Dim >::template Element< Dim-1 > f ; f<HyperCube::Cube< Dim >::template ElementNum< Dim-1 >() ; f++ )
{
int flip = HyperCube::Cube< Dim >::IsOriented( f ) ? 0 : 1;
HyperCube::Direction fDir = f.direction();
if( fDir==HyperCube::BACK || fDir==HyperCube::FRONT )
{
const _SliceValues& sValues = (fDir==HyperCube::BACK) ? bValues : fValues;
node_index_type fIdx = sValues.sliceData.faceIndices((node_index_type)i)[0];
if( sValues.faceSet[fIdx] )
{
const _FaceEdges& fe = sValues.faceEdges[ fIdx ];
for( int j=0 ; j<fe.count ; j++ ) edges.push_back( _IsoEdge( fe.edges[j][flip] , fe.edges[j][1-flip] ) );
}
else
{
_Key key = _VertexData::FaceIndex( leaf , f , tree._localToGlobal( tree._maxDepth ) );
typename std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher >::const_iterator iter = sValues.faceEdgeMap.find(key);
if( iter!=sValues.faceEdgeMap.end() )
{
const std::vector< _IsoEdge >& _edges = iter->second;
for( size_t j=0 ; j<_edges.size() ; j++ ) edges.push_back( _IsoEdge( _edges[j][flip] , _edges[j][1-flip] ) );
}
else ERROR_OUT( "Invalid faces: " , i , " " , fDir==HyperCube::BACK ? "back" : ( fDir==HyperCube::FRONT ? "front" : ( fDir==HyperCube::CROSS ? "cross" : "unknown" ) ) );
}
}
else
{
node_index_type fIdx = xValues.xSliceData.faceIndices((node_index_type)i)[ f.coIndex() ];
if( xValues.faceSet[fIdx] )
{
const _FaceEdges& fe = xValues.faceEdges[ fIdx ];
for( int j=0 ; j<fe.count ; j++ ) edges.push_back( _IsoEdge( fe.edges[j][flip] , fe.edges[j][1-flip] ) );
}
else
{
_Key key = _VertexData::FaceIndex( leaf , f , tree._localToGlobal( tree._maxDepth ) );
typename std::unordered_map< _Key , std::vector< _IsoEdge > , typename _Key::Hasher >::const_iterator iter = xValues.faceEdgeMap.find(key);
if( iter!=xValues.faceEdgeMap.end() )
{
const std::vector< _IsoEdge >& _edges = iter->second;
for( size_t j=0 ; j<_edges.size() ; j++ ) edges.push_back( _IsoEdge( _edges[j][flip] , _edges[j][1-flip] ) );
}
else ERROR_OUT( "Invalid faces: " , i , " " , fDir==HyperCube::BACK ? "back" : ( fDir==HyperCube::FRONT ? "front" : ( fDir==HyperCube::CROSS ? "cross" : "unknown" ) ) );
}
}
}
// Get the edge loops
std::vector< std::vector< _Key > > loops;
while( edges.size() )
{
loops.resize( loops.size()+1 );
_IsoEdge edge = edges.back();
edges.pop_back();
_Key start = edge[0] , current = edge[1];
while( current!=start )
{
int idx;
for( idx=0 ; idx<(int)edges.size() ; idx++ ) if( edges[idx][0]==current ) break;
if( idx==edges.size() )
{
typename std::unordered_map< _Key , _Key , typename _Key::Hasher >::const_iterator iter;
if ( (iter=bValues.vertexPairMap.find(current))!=bValues.vertexPairMap.end() ) loops.back().push_back( current ) , current = iter->second;
else if( (iter=fValues.vertexPairMap.find(current))!=fValues.vertexPairMap.end() ) loops.back().push_back( current ) , current = iter->second;
else if( (iter=xValues.vertexPairMap.find(current))!=xValues.vertexPairMap.end() ) loops.back().push_back( current ) , current = iter->second;
else
{
LocalDepth d ; LocalOffset off;
tree._localDepthAndOffset( leaf , d , off );
ERROR_OUT( "Failed to close loop [" , d-1 , ": " , off[0] , " " , off[1] , " " , off[2] , "] | (" , i , "): " , current.to_string() );
}
}
else
{
loops.back().push_back( current );
current = edges[idx][1];
edges[idx] = edges.back() , edges.pop_back();
}
}
loops.back().push_back( start );
}
// Add the loops to the mesh
for( size_t j=0 ; j<loops.size() ; j++ )
{
std::vector< std::pair< node_index_type , Vertex > > polygon( loops[j].size() );
for( size_t k=0 ; k<loops[j].size() ; k++ )
{
_Key key = loops[j][k];
typename std::unordered_map< _Key , std::pair< node_index_type , Vertex > , typename _Key::Hasher >::const_iterator iter;
size_t kk = flipOrientation ? loops[j].size()-1-k : k;
if ( ( iter=bValues.edgeVertexMap.find( key ) )!=bValues.edgeVertexMap.end() ) polygon[kk] = iter->second;
else if( ( iter=fValues.edgeVertexMap.find( key ) )!=fValues.edgeVertexMap.end() ) polygon[kk] = iter->second;
else if( ( iter=xValues.edgeVertexMap.find( key ) )!=xValues.edgeVertexMap.end() ) polygon[kk] = iter->second;
else ERROR_OUT( "Couldn't find vertex in edge map" );
}
_AddIsoPolygons( thread , mesh , polygon , polygonMesh , addBarycenter , vOffset );
}
}
}
}
}
);
}
template< unsigned int WeightDegree , typename Data , unsigned int DataSig >
static bool _GetIsoVertex( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , ConstPointSupportKey< IsotropicUIntPack< Dim , FEMSignature< DataSig >::Degree > >& dataKey , const TreeNode* node , typename HyperCube::template Cube< Dim-1 >::template Element< 1 > _e , HyperCube::Direction zDir , const _SliceValues& sValues , Vertex& vertex , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex )
{
static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
Point< Real , Dim > position;
int c0 , c1;
const typename HyperCube::Cube< Dim-1 >::template Element< 0 > *_c = SliceData::template HyperCubeTables< Dim-1 , 1 , 0 >::OverlapElements[_e.index];
c0 = _c[0].index , c1 = _c[1].index;
bool nonLinearFit = sValues.cornerGradients!=NullPointer( Point< Real , Dim > );
const typename SliceData::SquareCornerIndices& idx = sValues.sliceData.cornerIndices( node );
Real x0 = sValues.cornerValues[idx[c0]] , x1 = sValues.cornerValues[idx[c1]];
Point< Real , Dim > s;
Real start , width;
tree._startAndWidth( node , s , width );
int o;
{
const HyperCube::Direction* dirs = SliceData::template HyperCubeTables< Dim-1 , 1 >::Directions[ _e.index ];
for( int d=0 ; d<Dim-1 ; d++ ) if( dirs[d]==HyperCube::CROSS )
{
o = d;
start = s[d];
for( int dd=1 ; dd<Dim-1 ; dd++ ) position[(d+dd)%(Dim-1)] = s[(d+dd)%(Dim-1)] + width * ( dirs[(d+dd)%(Dim-1)]==HyperCube::BACK ? 0 : 1 );
}
}
position[ Dim-1 ] = s[Dim-1] + width * ( zDir==HyperCube::BACK ? 0 : 1 );
double averageRoot;
bool rootFound = false;
if( nonLinearFit )
{
double dx0 = sValues.cornerGradients[idx[c0]][o] * width , dx1 = sValues.cornerGradients[idx[c1]][o] * width;
// The scaling will turn the Hermite Spline into a quadratic
double scl = (x1-x0) / ( (dx1+dx0 ) / 2 );
dx0 *= scl , dx1 *= scl;
// Hermite Spline
Polynomial< 2 > P;
P.coefficients[0] = x0;
P.coefficients[1] = dx0;
P.coefficients[2] = 3*(x1-x0)-dx1-2*dx0;
double roots[2];
int rCount = 0 , rootCount = P.getSolutions( isoValue , roots , 0 );
averageRoot = 0;
for( int i=0 ; i<rootCount ; i++ ) if( roots[i]>=0 && roots[i]<=1 ) averageRoot += roots[i] , rCount++;
if( rCount ) rootFound = true;
averageRoot /= rCount;
}
if( !rootFound )
{
// We have a linear function L, with L(0) = x0 and L(1) = x1
// => L(t) = x0 + t * (x1-x0)
// => L(t) = isoValue <=> t = ( isoValue - x0 ) / ( x1 - x0 )
if( x0==x1 ) ERROR_OUT( "Not a zero-crossing root: " , x0 , " " , x1 );
averageRoot = ( isoValue - x0 ) / ( x1 - x0 );
}
if( averageRoot<=0 || averageRoot>=1 )
{
_BadRootCount++;
if( averageRoot<0 ) averageRoot = 0;
if( averageRoot>1 ) averageRoot = 1;
}
position[o] = Real( start + width*averageRoot );
Real depth = (Real)1.;
Data dataValue;
if( densityWeights )
{
Real weight;
tree._getSampleDepthAndWeight( *densityWeights , node , position , weightKey , depth , weight );
}
if( data )
{
if( DataDegree==0 )
{
Point< Real , 3 > center( s[0] + width/2 , s[1] + width/2 , s[2] + width/2 );
dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , center , *pointEvaluator , dataKey ).value();
}
else dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , position , *pointEvaluator , dataKey ).value();
}
SetVertex( vertex , position , depth , dataValue );
return true;
}
template< unsigned int WeightDegree , typename Data , unsigned int DataSig >
static bool _GetIsoVertex( const FEMTree< Dim , Real >& tree , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , ConstPointSupportKey< IsotropicUIntPack< Dim , FEMSignature< DataSig >::Degree > >& dataKey , const TreeNode* node , typename HyperCube::template Cube< Dim-1 >::template Element< 0 > _c , const _SliceValues& bValues , const _SliceValues& fValues , Vertex& vertex , std::function< void ( Vertex& , Point< Real , Dim > , Real , Data ) > SetVertex )
{
static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
Point< Real , Dim > position;
bool nonLinearFit = bValues.cornerGradients!=NullPointer( Point< Real , Dim > ) && fValues.cornerGradients!=NullPointer( Point< Real , Dim > );
const typename SliceData::SquareCornerIndices& idx0 = bValues.sliceData.cornerIndices( node );
const typename SliceData::SquareCornerIndices& idx1 = fValues.sliceData.cornerIndices( node );
Real x0 = bValues.cornerValues[ idx0[_c.index] ] , x1 = fValues.cornerValues[ idx1[_c.index] ];
Point< Real , Dim > s;
Real start , width;
tree._startAndWidth( node , s , width );
start = s[2];
int x , y;
{
const HyperCube::Direction* xx = SliceData::template HyperCubeTables< Dim-1 , 0 >::Directions[ _c.index ];
x = xx[0]==HyperCube::BACK ? 0 : 1 , y = xx[1]==HyperCube::BACK ? 0 : 1;
}
position[0] = s[0] + width*x;
position[1] = s[1] + width*y;
double averageRoot;
bool rootFound = false;
if( nonLinearFit )
{
double dx0 = bValues.cornerGradients[ idx0[_c.index] ][2] * width , dx1 = fValues.cornerGradients[ idx1[_c.index] ][2] * width;
// The scaling will turn the Hermite Spline into a quadratic
double scl = (x1-x0) / ( (dx1+dx0 ) / 2 );
dx0 *= scl , dx1 *= scl;
// Hermite Spline
Polynomial< 2 > P;
P.coefficients[0] = x0;
P.coefficients[1] = dx0;
P.coefficients[2] = 3*(x1-x0)-dx1-2*dx0;
double roots[2];
int rCount = 0 , rootCount = P.getSolutions( isoValue , roots , 0 );
averageRoot = 0;
for( int i=0 ; i<rootCount ; i++ ) if( roots[i]>=0 && roots[i]<=1 ) averageRoot += roots[i] , rCount++;
if( rCount ) rootFound = true;
averageRoot /= rCount;
}
if( !rootFound )
{
// We have a linear function L, with L(0) = x0 and L(1) = x1
// => L(t) = x0 + t * (x1-x0)
// => L(t) = isoValue <=> t = ( isoValue - x0 ) / ( x1 - x0 )
if( x0==x1 ) ERROR_OUT( "Not a zero-crossing root: " , x0 , " " , x1 );
averageRoot = ( isoValue - x0 ) / ( x1 - x0 );
}
if( averageRoot<=0 || averageRoot>=1 )
{
_BadRootCount++;
}
position[2] = Real( start + width*averageRoot );
Real depth = (Real)1.;
Data dataValue;
if( densityWeights )
{
Real weight;
tree._getSampleDepthAndWeight( *densityWeights , node , position , weightKey , depth , weight );
}
if( data )
{
if( DataDegree==0 )
{
Point< Real , 3 > center( s[0] + width/2 , s[1] + width/2 , s[2] + width/2 );
dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , center , *pointEvaluator , dataKey ).value();
}
else dataValue = tree.template _evaluate< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , position , *pointEvaluator , dataKey ).value();
}
SetVertex( vertex , position , depth , dataValue );
return true;
}
static unsigned int _AddIsoPolygons( unsigned int thread , CoredMeshData< Vertex , node_index_type >& mesh , std::vector< std::pair< node_index_type , Vertex > >& polygon , bool polygonMesh , bool addBarycenter , node_index_type &vOffset )
{
if( polygonMesh )
{
std::vector< node_index_type > vertices( polygon.size() );
for( unsigned int i=0 ; i<polygon.size() ; i++ ) vertices[i] = polygon[polygon.size()-1-i].first;
mesh.addPolygon_s( thread , vertices );
return 1;
}
if( polygon.size()>3 )
{
bool isCoplanar = false;
std::vector< node_index_type > triangle( 3 );
if( addBarycenter )
for( unsigned int i=0 ; i<polygon.size() ; i++ ) for( unsigned int j=0 ; j<i ; j++ )
if( (i+1)%polygon.size()!=j && (j+1)%polygon.size()!=i )
{
Vertex v1 = polygon[i].second , v2 = polygon[j].second;
for( int k=0 ; k<3 ; k++ ) if( v1.point[k]==v2.point[k] ) isCoplanar = true;
}
if( isCoplanar )
{
Vertex c;
c *= 0;
for( unsigned int i=0 ; i<polygon.size() ; i++ ) c += polygon[i].second;
c /= ( typename Vertex::Real )polygon.size();
node_index_type cIdx;
{
std::lock_guard< std::mutex > lock( _pointInsertionMutex );
cIdx = mesh.addOutOfCorePoint( c );
vOffset++;
}
for( unsigned i=0 ; i<polygon.size() ; i++ )
{
triangle[0] = polygon[ i ].first;
triangle[1] = cIdx;
triangle[2] = polygon[(i+1)%polygon.size()].first;
mesh.addPolygon_s( thread , triangle );
}
return (unsigned int)polygon.size();
}
else
{
std::vector< Point< Real , Dim > > vertices( polygon.size() );
for( unsigned int i=0 ; i<polygon.size() ; i++ ) vertices[i] = polygon[i].second.point;
std::vector< TriangleIndex< node_index_type > > triangles = MinimalAreaTriangulation< node_index_type , Real , Dim >( ( ConstPointer( Point< Real , Dim > ) )GetPointer( vertices ) , (node_index_type)vertices.size() );
if( triangles.size()!=polygon.size()-2 ) ERROR_OUT( "Minimal area triangulation failed:" , triangles.size() , " != " , polygon.size()-2 );
for( unsigned int i=0 ; i<triangles.size() ; i++ )
{
for( int j=0 ; j<3 ; j++ ) triangle[2-j] = polygon[ triangles[i].idx[j] ].first;
mesh.addPolygon_s( thread , triangle );
}
}
}
else if( polygon.size()==3 )
{
std::vector< node_index_type > vertices( 3 );
for( int i=0 ; i<3 ; i++ ) vertices[2-i] = polygon[i].first;
mesh.addPolygon_s( thread , vertices );
}
return (unsigned int)polygon.size()-2;
}
public:
struct IsoStats
{
double cornersTime , verticesTime , edgesTime , surfaceTime;
double copyFinerTime , setTableTime;
IsoStats( void ) : cornersTime(0) , verticesTime(0) , edgesTime(0) , surfaceTime(0) , copyFinerTime(0) , setTableTime(0) {;}
std::string toString( void ) const
{
std::stringstream stream;
stream << "Corners / Vertices / Edges / Surface / Set Table / Copy Finer: ";
stream << std::fixed << std::setprecision(1) << cornersTime << " / " << verticesTime << " / " << edgesTime << " / " << surfaceTime << " / " << setTableTime << " / " << copyFinerTime;
stream << " (s)";
return stream.str();
}
};
template< typename Data , typename SetVertexFunction , unsigned int ... FEMSigs , unsigned int WeightDegree , unsigned int DataSig >
static IsoStats Extract( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , const FEMTree< Dim , Real >& tree , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , Real isoValue , CoredMeshData< Vertex , node_index_type >& mesh , const SetVertexFunction &SetVertex , bool nonLinearFit , bool addBarycenter , bool polygonMesh , bool flipOrientation )
{
_BadRootCount = 0u;
IsoStats isoStats;
static_assert( sizeof...(FEMSigs)==Dim , "[ERROR] Number of signatures should match dimension" );
tree._setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
static const int FEMDegrees[] = { FEMSignature< FEMSigs >::Degree ... };
for( int d=0 ; d<Dim ; d++ ) if( FEMDegrees[d]==0 && nonLinearFit ) WARN( "Constant B-Splines do not support non-linear interpolation" ) , nonLinearFit = false;
SliceData::SetHyperCubeTables();
typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator = NULL;
if( data ) pointEvaluator = new typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >( tree._maxDepth );
DenseNodeData< Real , UIntPack< FEMSigs ... > > coarseCoefficients( tree._sNodesEnd( tree._maxDepth-1 ) );
memset( coarseCoefficients() , 0 , sizeof(Real)*tree._sNodesEnd( tree._maxDepth-1 ) );
ThreadPool::Parallel_for( tree._sNodesBegin(0) , tree._sNodesEnd( tree._maxDepth-1 ) , [&]( unsigned int, size_t i ){ coarseCoefficients[i] = coefficients[i]; } );
typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > rp;
for( LocalDepth d=1 ; d<tree._maxDepth ; d++ ) tree._upSample( UIntPack< FEMSigs ... >() , rp , d , coarseCoefficients() );
FEMTree< Dim , Real >::MemoryUsage();
std::vector< _Evaluator< UIntPack< FEMSigs ... > , 1 > > evaluators( tree._maxDepth+1 );
for( LocalDepth d=0 ; d<=tree._maxDepth ; d++ ) evaluators[d].set( tree._maxDepth );
node_index_type vertexOffset = 0;
std::vector< _SlabValues > slabValues( tree._maxDepth+1 );
// Initialize the back slice
for( LocalDepth d=tree._maxDepth ; d>=0 ; d-- )
{
double t = Time();
SliceData::SetSliceTableData( tree._sNodes , &slabValues[d].sliceValues(0).sliceData , &slabValues[d].xSliceValues(0).xSliceData , &slabValues[d].sliceValues(1).sliceData , tree._localToGlobal( d ) , tree._localInset( d ) );
isoStats.setTableTime += Time()-t;
slabValues[d].sliceValues (0).reset( nonLinearFit );
slabValues[d].sliceValues (1).reset( nonLinearFit );
slabValues[d].xSliceValues(0).reset( );
}
for( LocalDepth d=tree._maxDepth ; d>=0 ; d-- )
{
// Copy edges from finer
double t = Time();
if( d<tree._maxDepth ) _CopyFinerSliceIsoEdgeKeys( tree , d , 0 , slabValues );
isoStats.copyFinerTime += Time()-t , t = Time();
_SetSliceIsoCorners< FEMSigs ... >( tree , coefficients() , coarseCoefficients() , isoValue , d , 0 , slabValues , evaluators[d] );
isoStats.cornersTime += Time()-t , t = Time();
_SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , d , 0 , vertexOffset , mesh , slabValues , SetVertex );
isoStats.verticesTime += Time()-t , t = Time();
_SetSliceIsoEdges( tree , d , 0 , slabValues );
isoStats.edgesTime += Time()-t , t = Time();
}
// Iterate over the slices at the finest level
for( int slice=0 ; slice<( 1<<tree._maxDepth ) ; slice++ )
{
// Process at all depths that contain this slice
LocalDepth d ; int o;
for( d=tree._maxDepth , o=slice+1 ; d>=0 ; d-- , o>>=1 )
{
// Copy edges from finer (required to ensure we correctly track edge cancellations)
double t = Time();
if( d<tree._maxDepth )
{
_CopyFinerSliceIsoEdgeKeys( tree , d , o , slabValues );
_CopyFinerXSliceIsoEdgeKeys( tree , d , o-1 , slabValues );
}
isoStats.copyFinerTime += Time()-t , t = Time();
// Set the slice values/vertices
_SetSliceIsoCorners< FEMSigs ... >( tree , coefficients() , coarseCoefficients() , isoValue , d , o , slabValues , evaluators[d] );
isoStats.cornersTime += Time()-t , t = Time();
_SetSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , d , o , vertexOffset , mesh , slabValues , SetVertex );
isoStats.verticesTime += Time()-t , t = Time();
_SetSliceIsoEdges( tree , d , o , slabValues );
isoStats.edgesTime += Time()-t , t = Time();
// Set the cross-slice edges
_SetXSliceIsoVertices< WeightDegree , Data , DataSig >( tree , pointEvaluator , densityWeights , data , isoValue , d , o-1 , vertexOffset , mesh , slabValues , SetVertex );
isoStats.verticesTime += Time()-t , t = Time();
_SetXSliceIsoEdges( tree , d , o-1 , slabValues );
isoStats.edgesTime += Time()-t , t = Time();
ThreadPool::ParallelSections
(
[ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o-1).setEdgeVertexMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o ).setEdgeVertexMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d].xSliceValues(o-1).setEdgeVertexMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o-1).setVertexPairMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o ).setVertexPairMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d].xSliceValues(o-1).setVertexPairMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o-1).setFaceEdgeMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d]. sliceValues(o ).setFaceEdgeMap(); } ,
[ &slabValues , d , o ]( void ){ slabValues[d].xSliceValues(o-1).setFaceEdgeMap(); }
);
// Add the triangles
t = Time();
_SetIsoSurface( tree , d , o-1 , slabValues[d].sliceValues(o-1) , slabValues[d].sliceValues(o) , slabValues[d].xSliceValues(o-1) , mesh , polygonMesh , addBarycenter , vertexOffset , flipOrientation );
isoStats.surfaceTime += Time()-t;
if( o&1 ) break;
}
for( d=tree._maxDepth , o=slice+1 ; d>=0 ; d-- , o>>=1 )
{
// Initialize for the next pass
if( o<(1<<(d+1)) )
{
double t = Time();
SliceData::SetSliceTableData( tree._sNodes , NULL , &slabValues[d].xSliceValues(o).xSliceData , &slabValues[d].sliceValues(o+1).sliceData , tree._localToGlobal( d ) , o + tree._localInset( d ) );
isoStats.setTableTime += Time()-t;
slabValues[d].sliceValues(o+1).reset( nonLinearFit );
slabValues[d].xSliceValues(o).reset();
}
if( o&1 ) break;
}
}
FEMTree< Dim , Real >::MemoryUsage();
if( pointEvaluator ) delete pointEvaluator;
size_t badRootCount = _BadRootCount;
if( badRootCount!=0 ) WARN( "bad average roots: " , badRootCount );
return isoStats;
}
};
template< class Real , class Vertex > std::mutex IsoSurfaceExtractor< 3 , Real , Vertex >::_pointInsertionMutex;
template< class Real , class Vertex > std::atomic< size_t > IsoSurfaceExtractor< 3 , Real , Vertex >::_BadRootCount;
template< class Real , class Vertex > template< unsigned int D , unsigned int K >
unsigned int IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::CellOffset[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ];
template< class Real , class Vertex > template< unsigned int D , unsigned int K >
unsigned int IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::IncidentElementCoIndex[ HyperCube::Cube< D >::template ElementNum< K >() ][ HyperCube::Cube< D >::template IncidentCubeNum< K >() ];
template< class Real , class Vertex > template< unsigned int D , unsigned int K >
unsigned int IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::CellOffsetAntipodal[ HyperCube::Cube< D >::template ElementNum< K >() ];
template< class Real , class Vertex > template< unsigned int D , unsigned int K >
typename HyperCube::Cube< D >::template IncidentCubeIndex < K > IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::IncidentCube[ HyperCube::Cube< D >::template ElementNum< K >() ];
template< class Real , class Vertex > template< unsigned int D , unsigned int K >
typename HyperCube::Direction IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K >::Directions[ HyperCube::Cube< D >::template ElementNum< K >() ][ D ];
template< class Real , class Vertex > template< unsigned int D , unsigned int K1 , unsigned int K2 >
typename HyperCube::Cube< D >::template Element< K2 > IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K1 , K2 >::OverlapElements[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template OverlapElementNum< K1 , K2 >() ];
template< class Real , class Vertex > template< unsigned int D , unsigned int K1 , unsigned int K2 >
bool IsoSurfaceExtractor< 3 , Real , Vertex >::SliceData::HyperCubeTables< D , K1 , K2 >::Overlap[ HyperCube::Cube< D >::template ElementNum< K1 >() ][ HyperCube::Cube< D >::template ElementNum< K2 >() ];
| 54.89734 | 785 | 0.65075 |
DamonsJ
|
28bc3aa89f9c3c29f8a3e2e9536533af149ceb1f
| 774 |
cpp
|
C++
|
test/localization/locale.categories/category.time/locale.time.get/time_base.pass.cpp
|
caiohamamura/libcxx
|
27c836ff3a9c505deb9fd1616012924de8ff9279
|
[
"MIT"
] | 1,244 |
2015-01-02T21:08:56.000Z
|
2022-03-22T21:34:16.000Z
|
test/localization/locale.categories/category.time/locale.time.get/time_base.pass.cpp
|
caiohamamura/libcxx
|
27c836ff3a9c505deb9fd1616012924de8ff9279
|
[
"MIT"
] | 125 |
2015-01-22T01:08:00.000Z
|
2020-05-25T08:28:17.000Z
|
test/localization/locale.categories/category.time/locale.time.get/time_base.pass.cpp
|
caiohamamura/libcxx
|
27c836ff3a9c505deb9fd1616012924de8ff9279
|
[
"MIT"
] | 124 |
2015-01-12T15:06:17.000Z
|
2022-03-26T07:48:53.000Z
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <locale>
// class time_base
// {
// public:
// enum dateorder {no_order, dmy, mdy, ymd, ydm};
// };
#include <locale>
#include <cassert>
int main()
{
std::time_base::dateorder d = std::time_base::no_order;
assert(std::time_base::no_order == 0);
assert(std::time_base::dmy == 1);
assert(std::time_base::mdy == 2);
assert(std::time_base::ymd == 3);
assert(std::time_base::ydm == 4);
}
| 25.8 | 80 | 0.489664 |
caiohamamura
|
28bd1df68cd3643736999d01cb1bdc1184d60d1c
| 7,492 |
hpp
|
C++
|
server/api_grammar.hpp
|
aaronbenz/osrm-backend
|
758d4023050d1f49971f919cea872a2276dafe14
|
[
"BSD-2-Clause"
] | 1 |
2021-03-06T05:07:44.000Z
|
2021-03-06T05:07:44.000Z
|
server/api_grammar.hpp
|
aaronbenz/osrm-backend
|
758d4023050d1f49971f919cea872a2276dafe14
|
[
"BSD-2-Clause"
] | null | null | null |
server/api_grammar.hpp
|
aaronbenz/osrm-backend
|
758d4023050d1f49971f919cea872a2276dafe14
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Copyright (c) 2013, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
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.
*/
#ifndef API_GRAMMAR_HPP
#define API_GRAMMAR_HPP
#include <boost/bind.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
namespace qi = boost::spirit::qi;
template <typename Iterator, class HandlerT> struct APIGrammar : qi::grammar<Iterator>
{
explicit APIGrammar(HandlerT *h) : APIGrammar::base_type(api_call), handler(h)
{
api_call = qi::lit('/') >> string[boost::bind(&HandlerT::setService, handler, ::_1)] >>
-query;
query = ('?') >> +(zoom | output | jsonp | checksum | uturns | location_with_options | destination_with_options | source_with_options | cmp |
language | instruction | geometry | alt_route | old_API | num_results |
matching_beta | gps_precision | classify | locs);
// all combinations of timestamp, uturn, hint and bearing without duplicates
t_u = (u >> -timestamp) | (timestamp >> -u);
t_h = (hint >> -timestamp) | (timestamp >> -hint);
u_h = (u >> -hint) | (hint >> -u);
t_u_h = (hint >> -t_u) | (u >> -t_h) | (timestamp >> -u_h);
location_options = (bearing >> -t_u_h) | (t_u_h >> -bearing) | //
(u >> bearing >> -t_h) | (timestamp >> bearing >> -u_h) | (hint >> bearing >> t_u) | //
(t_h >> bearing >> -u) | (u_h >> bearing >> -timestamp) | (t_u >> bearing >> -hint);
location_with_options = location >> -location_options;
source_with_options = source >> -location_options;
destination_with_options = destination >> -location_options;
zoom = (-qi::lit('&')) >> qi::lit('z') >> '=' >>
qi::short_[boost::bind(&HandlerT::setZoomLevel, handler, ::_1)];
output = (-qi::lit('&')) >> qi::lit("output") >> '=' >>
string[boost::bind(&HandlerT::setOutputFormat, handler, ::_1)];
jsonp = (-qi::lit('&')) >> qi::lit("jsonp") >> '=' >>
stringwithPercent[boost::bind(&HandlerT::setJSONpParameter, handler, ::_1)];
checksum = (-qi::lit('&')) >> qi::lit("checksum") >> '=' >>
qi::uint_[boost::bind(&HandlerT::setChecksum, handler, ::_1)];
instruction = (-qi::lit('&')) >> qi::lit("instructions") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setInstructionFlag, handler, ::_1)];
geometry = (-qi::lit('&')) >> qi::lit("geometry") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setGeometryFlag, handler, ::_1)];
cmp = (-qi::lit('&')) >> qi::lit("compression") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setCompressionFlag, handler, ::_1)];
location = (-qi::lit('&')) >> qi::lit("loc") >> '=' >>
(qi::double_ >> qi::lit(',') >>
qi::double_)[boost::bind(&HandlerT::addCoordinate, handler, ::_1)];
destination = (-qi::lit('&')) >> qi::lit("dst") >> '=' >>
(qi::double_ >> qi::lit(',') >>
qi::double_)[boost::bind(&HandlerT::addDestination, handler, ::_1)];
source = (-qi::lit('&')) >> qi::lit("src") >> '=' >>
(qi::double_ >> qi::lit(',') >>
qi::double_)[boost::bind(&HandlerT::addSource, handler, ::_1)];
hint = (-qi::lit('&')) >> qi::lit("hint") >> '=' >>
stringwithDot[boost::bind(&HandlerT::addHint, handler, ::_1)];
timestamp = (-qi::lit('&')) >> qi::lit("t") >> '=' >>
qi::uint_[boost::bind(&HandlerT::addTimestamp, handler, ::_1)];
bearing = (-qi::lit('&')) >> qi::lit("b") >> '=' >>
(qi::int_ >> -(qi::lit(',') >> qi::int_ | qi::attr(10)))[boost::bind(&HandlerT::addBearing, handler, ::_1, ::_2, ::_3)];
u = (-qi::lit('&')) >> qi::lit("u") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setUTurn, handler, ::_1)];
uturns = (-qi::lit('&')) >> qi::lit("uturns") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setAllUTurns, handler, ::_1)];
language = (-qi::lit('&')) >> qi::lit("hl") >> '=' >>
string[boost::bind(&HandlerT::setLanguage, handler, ::_1)];
alt_route = (-qi::lit('&')) >> qi::lit("alt") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setAlternateRouteFlag, handler, ::_1)];
old_API = (-qi::lit('&')) >> qi::lit("geomformat") >> '=' >>
string[boost::bind(&HandlerT::setDeprecatedAPIFlag, handler, ::_1)];
num_results = (-qi::lit('&')) >> qi::lit("num_results") >> '=' >>
qi::short_[boost::bind(&HandlerT::setNumberOfResults, handler, ::_1)];
matching_beta = (-qi::lit('&')) >> qi::lit("matching_beta") >> '=' >>
qi::float_[boost::bind(&HandlerT::setMatchingBeta, handler, ::_1)];
gps_precision = (-qi::lit('&')) >> qi::lit("gps_precision") >> '=' >>
qi::float_[boost::bind(&HandlerT::setGPSPrecision, handler, ::_1)];
classify = (-qi::lit('&')) >> qi::lit("classify") >> '=' >>
qi::bool_[boost::bind(&HandlerT::setClassify, handler, ::_1)];
locs = (-qi::lit('&')) >> qi::lit("locs") >> '=' >>
stringforPolyline[boost::bind(&HandlerT::getCoordinatesFromGeometry, handler, ::_1)];
string = +(qi::char_("a-zA-Z"));
stringwithDot = +(qi::char_("a-zA-Z0-9_.-"));
stringwithPercent = +(qi::char_("a-zA-Z0-9_.-") | qi::char_('[') | qi::char_(']') |
(qi::char_('%') >> qi::char_("0-9A-Z") >> qi::char_("0-9A-Z")));
stringforPolyline = +(qi::char_("a-zA-Z0-9_.-[]{}@?|\\%~`^"));
}
qi::rule<Iterator> api_call, query, location_options, location_with_options, destination_with_options, source_with_options, t_u, t_h, u_h, t_u_h;
qi::rule<Iterator, std::string()> service, zoom, output, string, jsonp, checksum, location, destination, source,
hint, timestamp, bearing, stringwithDot, stringwithPercent, language, geometry, cmp, alt_route, u,
uturns, old_API, num_results, matching_beta, gps_precision, classify, locs, instruction, stringforPolyline;
HandlerT *handler;
};
#endif /* API_GRAMMAR_HPP */
| 60.910569 | 150 | 0.573946 |
aaronbenz
|
28bd5aed619a987f6f1a13ee398a199eec1d31bb
| 2,377 |
cpp
|
C++
|
rs/test/if_empty_test.cpp
|
dymk/rs
|
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
|
[
"Apache-2.0"
] | 19 |
2017-05-15T08:20:00.000Z
|
2021-12-03T05:58:32.000Z
|
rs/test/if_empty_test.cpp
|
dymk/rs
|
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
|
[
"Apache-2.0"
] | null | null | null |
rs/test/if_empty_test.cpp
|
dymk/rs
|
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
|
[
"Apache-2.0"
] | 3 |
2018-01-16T18:07:30.000Z
|
2021-06-30T07:33:44.000Z
|
// Copyright 2017 Per Grön. 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 <catch.hpp>
#include <string>
#include <vector>
#include <rs/if_empty.h>
#include <rs/just.h>
#include "infinite_range.h"
#include "test_util.h"
namespace shk {
TEST_CASE("IfEmpty") {
SECTION("type") {
auto stream = IfEmpty(Just())(Just());
static_assert(
IsPublisher<decltype(stream)>,
"IfEmpty stream should be a publisher");
}
SECTION("non-empty stream") {
auto null_publisher = MakePublisher([](auto &&subscriber) {
CHECK(!"should not be subscribed to");
return MakeSubscription();
});
SECTION("one value") {
auto stream = IfEmpty(null_publisher)(Just(2));
CHECK(GetAll<int>(stream) == (std::vector<int>{ 2 }));
}
SECTION("several values") {
auto stream = IfEmpty(null_publisher)(Just(2, 4, 6, 8));
CHECK(GetAll<int>(stream) == (std::vector<int>{ 2, 4, 6, 8 }));
}
SECTION("noncopyable value") {
auto if_empty = IfEmpty(Start([] { return std::make_unique<int>(1); }));
auto stream = if_empty(Start([] { return std::make_unique<int>(2); }));
auto result = GetAll<std::unique_ptr<int>>(stream);
REQUIRE(result.size() == 1);
REQUIRE(result[0]);
CHECK(*result[0] == 2);
}
SECTION("don't leak the subscriber") {
CheckLeak(IfEmpty(Just(1))(Just(2)));
}
}
SECTION("empty stream") {
SECTION("one value") {
auto stream = IfEmpty(Just(1))(Just());
CHECK(GetAll<int>(stream) == (std::vector<int>{ 1 }));
}
SECTION("several values") {
auto stream = IfEmpty(Just(1, 2, 3))(Just());
CHECK(GetAll<int>(stream) == (std::vector<int>{ 1, 2, 3 }));
}
SECTION("don't leak the subscriber") {
CheckLeak(IfEmpty(Just(1))(Just()));
}
}
}
} // namespace shk
| 28.297619 | 78 | 0.625999 |
dymk
|
28c23c3de7693604cec684e893fa21e00fedbf30
| 2,870 |
hpp
|
C++
|
vize/include/vize/model/volume.hpp
|
oprogramadorreal/vize
|
042c16f96d8790303563be6787200558e1ec00b2
|
[
"MIT"
] | 47 |
2020-03-30T14:36:46.000Z
|
2022-03-06T07:44:54.000Z
|
vize/include/vize/model/volume.hpp
|
oprogramadorreal/vize
|
042c16f96d8790303563be6787200558e1ec00b2
|
[
"MIT"
] | null | null | null |
vize/include/vize/model/volume.hpp
|
oprogramadorreal/vize
|
042c16f96d8790303563be6787200558e1ec00b2
|
[
"MIT"
] | 8 |
2020-04-01T01:22:45.000Z
|
2022-01-02T13:06:09.000Z
|
#ifndef VIZE_VOLUME_HPP
#define VIZE_VOLUME_HPP
#include "vize/config.hpp"
#include "vize/serialization/volume_serializer.hpp"
#include <ayla/geometry/voxel_grid.hpp>
namespace vize {
class VolumeHistogram;
/**
* A tridimensional array of pixels (or "voxels"). Or a pile of images.
*
* A volume can be loaded from a sequence of image files.
*
* Each voxel of this volume is supposed to be stored in only one byte.
* The voxel data can be seen as an intensity value ranging from 0 to 255.
*
* The volume abstraction will be used to create an OpenGL 3D texture,
* where will be assumed that each pixel of the 3D texture is stored in
* only one byte.
*
* @see vize::VolumeFactory
* @see vize::GLVolumeTexture
*
* @author O Programador
*/
class Volume final {
public:
Volume();
Volume(SizeType widthInVolxes, SizeType heightInVoxels, SizeType depthInVoxels);
~Volume();
public:
/**
* Extract a sub volume of this volume starting at @param subVolumeBegin and
* with dimensions specified by @param subVolumeWidth, @param subVolumeHeight and @param subVolumeDepth.
*/
std::unique_ptr<Volume> extractSubVolume(const ayla::Index3D& subVolumeBegin, SizeType subVolumeWidth, SizeType subVolumeHeight, SizeType subVolumeDepth) const;
/**
* @return The width of this volume in voxels.
*/
SizeType getWidth() const;
/**
* @return The height of this volume in voxels.
*/
SizeType getHeight() const;
/**
* @return The depth of this volume in voxels.
*/
SizeType getDepth() const;
/**
* @return The total number of voxels stored by this volume.
*/
SizeType getNumberOfVoxels() const;
/**
* @return A pointer to the first byte of this volume data.
* @remarks Volume data is stored in an internal array.
*/
const std::uint8_t* getRawData() const;
/**
* A model matrix is used to give position, orientation and size to the volume.
* Use this matrix to place a volume in a 3D space.
*
* @return The model matrix of this volume.
*/
glm::mat4 getModelMatrix() const;
/**
* Set the model matrix of this volume.
*/
void setModelMatrix(const glm::mat4& modelMatrix);
/**
* @return A bounding box for this volume.
*/
ayla::AxisAlignedBox getAABB() const;
const VolumeHistogram* getHistogram();
void applyHistogramEqualization();
private:
ayla::ByteVoxelGrid _voxelGrid;
glm::mat4 _modelMatrix = glm::mat4(1.0f); // gives position, orientation and size to the volume
std::unique_ptr<VolumeHistogram> _histogram;
private:
friend class TiffVolumeFactory;
friend class DicomVolumeFactory;
friend class VolumeFactory;
template<class Archive> friend void boost::serialization::serialize(Archive&, vize::Volume&, const unsigned int);
template<class Archive> friend void boost::serialization::load_construct_data(Archive&, vize::Volume*, const unsigned int);
};
}
#endif // VIZE_VOLUME_HPP
| 26.330275 | 161 | 0.731359 |
oprogramadorreal
|
28c44172bf3c7d44323a7f7fde8bda2fbb4e42c5
| 6,213 |
cpp
|
C++
|
src/pmp/gl/MeshViewer.cpp
|
choyfung/pmp-library
|
4a72c918494dac92f5e77545b71c7a327dafe71e
|
[
"BSD-3-Clause"
] | 1 |
2020-05-21T04:15:44.000Z
|
2020-05-21T04:15:44.000Z
|
src/pmp/gl/MeshViewer.cpp
|
choyfung/pmp-library
|
4a72c918494dac92f5e77545b71c7a327dafe71e
|
[
"BSD-3-Clause"
] | null | null | null |
src/pmp/gl/MeshViewer.cpp
|
choyfung/pmp-library
|
4a72c918494dac92f5e77545b71c7a327dafe71e
|
[
"BSD-3-Clause"
] | 1 |
2020-05-21T04:15:52.000Z
|
2020-05-21T04:15:52.000Z
|
//=============================================================================
// Copyright (C) 2011-2018 The pmp-library developers
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holder 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 "MeshViewer.h"
#include <imgui.h>
#include <cfloat>
#include <iostream>
#include <sstream>
//=============================================================================
namespace pmp {
//=============================================================================
MeshViewer::MeshViewer(const char* title, int width, int height, bool showgui)
: TrackballViewer(title, width, height, showgui)
{
// setup draw modes
clearDrawModes();
addDrawMode("Points");
addDrawMode("Hidden Line");
addDrawMode("Smooth Shading");
addDrawMode("Texture");
setDrawMode("Smooth Shading");
m_creaseAngle = 90.0;
}
//-----------------------------------------------------------------------------
MeshViewer::~MeshViewer() = default;
//-----------------------------------------------------------------------------
bool MeshViewer::loadMesh(const char* filename)
{
// load mesh
if (m_mesh.read(filename))
{
// update scene center and bounds
BoundingBox bb = m_mesh.bounds();
setScene(bb.center(), 0.5 * bb.size());
// compute face & vertex normals, update face indices
updateMesh();
std::cout << "Load " << filename << ": " << m_mesh.nVertices()
<< " vertices, " << m_mesh.nFaces() << " faces\n";
m_filename = filename;
m_creaseAngle = m_mesh.creaseAngle();
return true;
}
std::cerr << "Failed to read mesh from " << filename << " !" << std::endl;
return false;
}
//-----------------------------------------------------------------------------
bool MeshViewer::loadTexture(const char* filename, GLint format,
GLint minFilter, GLint magFilter, GLint wrap)
{
// load texture from file
if (!m_mesh.loadTexture(filename, format, minFilter, magFilter, wrap))
return false;
setDrawMode("Texture");
// set material
m_mesh.setAmbient(1.0);
m_mesh.setDiffuse(0.9);
m_mesh.setSpecular(0.0);
m_mesh.setShininess(1.0);
return true;
}
//-----------------------------------------------------------------------------
void MeshViewer::updateMesh()
{
// re-compute face and vertex normals
m_mesh.updateOpenGLBuffers();
}
//-----------------------------------------------------------------------------
void MeshViewer::processImGUI()
{
if (ImGui::CollapsingHeader("Mesh Info", ImGuiTreeNodeFlags_DefaultOpen))
{
// output mesh statistics
ImGui::BulletText("%d vertices", (int)m_mesh.nVertices());
ImGui::BulletText("%d edges", (int)m_mesh.nEdges());
ImGui::BulletText("%d faces", (int)m_mesh.nFaces());
// control crease angle
ImGui::PushItemWidth(100);
ImGui::SliderFloat("Crease Angle", &m_creaseAngle, 0.0f, 180.0f,
"%.0f");
ImGui::PopItemWidth();
if (m_creaseAngle != m_mesh.creaseAngle())
{
m_mesh.setCreaseAngle(m_creaseAngle);
std::cerr << "change crease angle\n";
}
}
}
//-----------------------------------------------------------------------------
void MeshViewer::draw(const std::string& drawMode)
{
// draw mesh
m_mesh.draw(m_projectionMatrix, m_modelviewMatrix, drawMode);
}
//-----------------------------------------------------------------------------
//
void MeshViewer::keyboard(int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS && action != GLFW_REPEAT)
return;
switch (key)
{
case GLFW_KEY_BACKSPACE: // reload model
{
loadMesh(m_filename.c_str());
break;
}
case GLFW_KEY_C: // adjust crease angle
{
if (mods & GLFW_MOD_SHIFT)
m_mesh.setCreaseAngle(m_mesh.creaseAngle() + 10);
else
m_mesh.setCreaseAngle(m_mesh.creaseAngle() - 10);
m_creaseAngle = m_mesh.creaseAngle();
std::cout << "crease angle: " << m_mesh.creaseAngle() << std::endl;
break;
}
case GLFW_KEY_O: // write mesh
{
m_mesh.write("output.off");
break;
}
default:
{
TrackballViewer::keyboard(key, scancode, action, mods);
break;
}
}
}
//=============================================================================
} // namespace pmp
//=============================================================================
| 32.528796 | 80 | 0.532593 |
choyfung
|
28c521ed55bcc1b7d2e830657df4b633b0a6b0cb
| 4,034 |
cpp
|
C++
|
contests/advertising_agency.cpp
|
RoundofThree/competitive-programming
|
19b0931f59503068daabb8c58bcf041f11b217aa
|
[
"MIT"
] | 1 |
2021-02-01T20:35:22.000Z
|
2021-02-01T20:35:22.000Z
|
contests/advertising_agency.cpp
|
RoundofThree/competitive-programming
|
19b0931f59503068daabb8c58bcf041f11b217aa
|
[
"MIT"
] | null | null | null |
contests/advertising_agency.cpp
|
RoundofThree/competitive-programming
|
19b0931f59503068daabb8c58bcf041f11b217aa
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define ar array
#define ll unsigned long long
const int MAX_N = 1e5 + 1;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ll LINF = 1e18;
// test:
// 50 19
// 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 47 30 47 47 47 47 47 47 47 47 25 30 47 47 47 30 47 47 47 47 47 47 47 47 47 47 17 47 47 37 25 47
ll binomialCoeffUtil(int n, int k, ll** dp)
{
// If value in lookup table then return
if (dp[n][k] != -1) //
return dp[n][k];
// store value in a table before return
if (k == 0) {
dp[n][k] = 1;
return dp[n][k];
}
// store value in table before return
if (k == n) {
dp[n][k] = 1;
return dp[n][k];
}
// save value in lookup table before return
dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) +
binomialCoeffUtil(n - 1, k, dp);
dp[n][k] %= MOD;
return dp[n][k];
}
ll binomialCoeff(int n, int k)
{
ll** dp; // make a temporary lookup table
dp = new ll*[n + 1];
// loop to create table dynamically
for (int i = 0; i < (n + 1); i++) {
dp[i] = new ll[k + 1];
}
// nested loop to initialise the table with -1
for (int i = 0; i < (n + 1); i++) {
for (int j = 0; j < (k + 1); j++) {
dp[i][j] = -1;
}
}
return binomialCoeffUtil(n, k, dp);
}
// broken
ll choose(int n, int k) {
// n choose m
if (k > n) return 0;
if (k*2 > n) k = n-k;
if (k==0) return 1;
ll ret = n;
for (int i=2; i<=k; ++i) {
ret = (ret * (ll)(n-i+1)/(ll)i)%MOD; // wrong because division should be product with modular inverse
cout << ret << ", ";
}
cout << "\n";
return ret;
}
// a more efficient way of nCk------------------------------------------------
ll powmod(ll base, ll exp, ll mod) {
base %= mod;
ll ret = 1;
while (exp > 0) {
if (exp & 1) ret = (ret * base)%mod;
base = (base * base)%mod;
exp >>= 1;
}
return ret;
}
// degree of mod in n! (exponent of mod in factorization of factorial)
int fact_exp(ll n, ll mod) {
int ret = 0;
ll curr = mod;
while (curr <= n) {
ret += n/curr;
curr *= mod;
}
return ret;
}
// nCk
ll fermat_binomial(ll n, ll k, ll mod) {
if (k == 0) return 1;
int num_degree = fact_exp(n, mod) - fact_exp(n-k, mod);
int den_degree = fact_exp(k, mod);
if (num_degree > den_degree) return 0;
if (k > n) return 0;
// compute numerator
ll num = 1;
for (ll i=n; i>n-k; --i) {
ll curr = i;
while (curr % mod == 0) curr /= mod;
num = (num * curr)%mod;
}
// compute denominator
ll den = 1;
for (ll i=1; i<=k; ++i) {
ll curr = i;
while (curr % mod == 0) curr /= mod;
den = (den * curr) % mod;
}
// apply fermat little theorem for inverse multiplicative of den
return (num * powmod(den, mod-2, mod))%mod;
}
// ways to make k-sum equal to largest k-sum
ll solve(vector<int> arr, int k) {
sort(arr.begin(), arr.end(), greater<int>()); // descending order
int repeated = 1;
int last = arr[k-1];
while (k-1-repeated>=0 && arr[k-1-repeated]==last) ++repeated;
int total = repeated;
for (int i=k; i<arr.size(); ++i) {
if (arr[i]==last) ++total;
else break;
}
// cout << total << "choose" << repeated << "\n";
return fermat_binomial(total, repeated, 1e9+7);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int tc;
cin >> tc;
for (int t = 1; t <= tc; t++) {
int n, k;
cin >> n >> k;
vector<int> followers(n);
for (int i=0; i<n; ++i) cin >> followers[i];
if (n == k) {
cout << 1 << "\n"; continue;
}
cout << solve(followers, k) << "\n";
}
}
| 25.2125 | 152 | 0.501487 |
RoundofThree
|
28c58478d55622296b9540fb61d83e076cbf5c9e
| 5,087 |
cpp
|
C++
|
src/cpp/server/scene/SceneView.cpp
|
ey6es/witgap
|
8f4af7adbde6bb172b4c66c0969e6f5d8736e7cb
|
[
"BSD-2-Clause"
] | 2 |
2017-06-24T03:47:12.000Z
|
2017-08-11T00:04:46.000Z
|
src/cpp/server/scene/SceneView.cpp
|
ey6es/witgap
|
8f4af7adbde6bb172b4c66c0969e6f5d8736e7cb
|
[
"BSD-2-Clause"
] | null | null | null |
src/cpp/server/scene/SceneView.cpp
|
ey6es/witgap
|
8f4af7adbde6bb172b4c66c0969e6f5d8736e7cb
|
[
"BSD-2-Clause"
] | null | null | null |
//
// $Id$
#include <QtDebug>
#include "actor/Pawn.h"
#include "net/Session.h"
#include "scene/Scene.h"
#include "scene/SceneView.h"
SceneView::SceneView (Session* session) :
Component(0)
{
connect(session, SIGNAL(didEnterScene(Scene*)), SLOT(handleDidEnterScene(Scene*)));
connect(session, SIGNAL(willLeaveScene(Scene*)), SLOT(handleWillLeaveScene(Scene*)));
}
SceneView::~SceneView ()
{
Session* session = this->session();
if (session != 0) {
Scene* scene = session->scene();
if (scene != 0) {
scene->removeSpatial(this);
}
}
}
void SceneView::setWorldBounds (const QRect& bounds)
{
if (_worldBounds != bounds) {
QRect oldBounds = _worldBounds;
Scene* scene = session()->scene();
if (scene == 0) {
_worldBounds = bounds;
_scrollAmount = QPoint(0, 0);
} else {
// detect scrolling
if (_worldBounds.size() == bounds.size() && _worldBounds.intersects(bounds)) {
QPoint delta = _worldBounds.topLeft() - bounds.topLeft();
_scrollAmount += delta;
scrollDirty(delta);
} else {
_scrollAmount = QPoint(0, 0);
dirty();
}
scene->removeSpatial(this);
_worldBounds = bounds;
scene->addSpatial(this);
}
emit worldBoundsChanged(oldBounds);
}
}
void SceneView::handleDidEnterScene (Scene* scene)
{
scene->addSpatial(this);
connect(scene, SIGNAL(recordChanged(SceneRecord)), SLOT(maybeScroll()));
Pawn* pawn = session()->pawn();
if (pawn != 0) {
// center around the pawn and adjust when it moves
connect(pawn, SIGNAL(positionChanged(QPoint)), SLOT(maybeScroll()));
QSize size = _bounds.size();
setWorldBounds(QRect(pawn->position() - QPoint(size.width()/2, size.height()/2), size));
}
_scrollAmount = QPoint(0, 0);
dirty();
}
void SceneView::handleWillLeaveScene (Scene* scene)
{
Pawn* pawn = session()->pawn();
if (pawn != 0) {
disconnect(pawn);
}
disconnect(scene);
scene->removeSpatial(this);
}
/**
* Helper function for maybeScroll: returns the signed distance between the specified value and the
* given range.
*/
static int getDelta (int value, int start, int end)
{
return (value < start) ? (value - start) : (value > end ? (value - end) : 0);
}
void SceneView::maybeScroll ()
{
Session* session = this->session();
const SceneRecord& record = session->scene()->record();
QRect scrollBounds(
_worldBounds.left() + _worldBounds.width()/2 - record.scrollWidth/2,
_worldBounds.top() + _worldBounds.height()/2 - record.scrollHeight/2,
record.scrollWidth, record.scrollHeight);
// scroll to fit the pawn position within the scroll bounds
const QPoint& pos = session->pawn()->position();
setWorldBounds(_worldBounds.translated(
getDelta(pos.x(), scrollBounds.left(), scrollBounds.right()),
getDelta(pos.y(), scrollBounds.top(), scrollBounds.bottom())));
}
void SceneView::invalidate ()
{
Component::invalidate();
// resize world bounds if necessary
setWorldBounds(QRect(_worldBounds.topLeft(), _bounds.size()));
}
void SceneView::draw (DrawContext* ctx)
{
Component::draw(ctx);
// apply scroll, if any
if (_scrollAmount != QPoint(0, 0)) {
ctx->scrollContents(localBounds(), _scrollAmount);
_scrollAmount = QPoint(0, 0);
}
Scene* scene = session()->scene();
if (scene == 0) {
return;
}
const QHash<QPoint, Scene::Block>& blocks = scene->blocks();
// find the intersection of the dirty bounds in world space and the world bounds
QRect dirty = ctx->dirty().boundingRect();
dirty.translate(-ctx->pos());
dirty.translate(_worldBounds.topLeft());
dirty &= _worldBounds;
// draw all blocks that intersect
int bx1 = dirty.left() >> Scene::Block::LgSize;
int bx2 = dirty.right() >> Scene::Block::LgSize;
int by1 = dirty.top() >> Scene::Block::LgSize;
int by2 = dirty.bottom() >> Scene::Block::LgSize;
QRect bbounds(0, 0, Scene::Block::Size, Scene::Block::Size);
for (int by = by1; by <= by2; by++) {
for (int bx = bx1; bx <= bx2; bx++) {
QHash<QPoint, Scene::Block>::const_iterator it = blocks.constFind(QPoint(bx, by));
if (it != blocks.constEnd()) {
const Scene::Block& block = *it;
bbounds.moveTo(bx << Scene::Block::LgSize, by << Scene::Block::LgSize);
QRect ibounds = bbounds.intersected(_worldBounds);
ctx->drawContents(
ibounds.left() - _worldBounds.left(), ibounds.top() - _worldBounds.top(),
ibounds.width(), ibounds.height(), block.constData() +
(ibounds.top() - bbounds.top() << Scene::Block::LgSize) +
(ibounds.left() - bbounds.left()),
true, Scene::Block::Size);
}
}
}
}
| 31.79375 | 99 | 0.591115 |
ey6es
|
28c59491ae0716bf6a4924a9954fe186e61d8d6a
| 18,040 |
cpp
|
C++
|
src/ir/ExpressionAnalyzer.cpp
|
Warchant/binaryen
|
c6237e8ea6236aa4a622cae64517cc3fd4f27b83
|
[
"Apache-2.0"
] | null | null | null |
src/ir/ExpressionAnalyzer.cpp
|
Warchant/binaryen
|
c6237e8ea6236aa4a622cae64517cc3fd4f27b83
|
[
"Apache-2.0"
] | null | null | null |
src/ir/ExpressionAnalyzer.cpp
|
Warchant/binaryen
|
c6237e8ea6236aa4a622cae64517cc3fd4f27b83
|
[
"Apache-2.0"
] | 1 |
2020-12-23T13:47:00.000Z
|
2020-12-23T13:47:00.000Z
|
/*
* Copyright 2016 WebAssembly Community Group participants
*
* 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 "support/hash.h"
#include "ir/iteration.h"
#include "ir/load-utils.h"
#include "ir/utils.h"
namespace wasm {
// Given a stack of expressions, checks if the topmost is used as a result.
// For example, if the parent is a block and the node is before the last position,
// it is not used.
bool ExpressionAnalyzer::isResultUsed(ExpressionStack& stack, Function* func) {
for (int i = int(stack.size()) - 2; i >= 0; i--) {
auto* curr = stack[i];
auto* above = stack[i + 1];
// only if and block can drop values (pre-drop expression was added) FIXME
if (curr->is<Block>()) {
auto* block = curr->cast<Block>();
for (size_t j = 0; j < block->list.size() - 1; j++) {
if (block->list[j] == above) return false;
}
assert(block->list.back() == above);
// continue down
} else if (curr->is<If>()) {
auto* iff = curr->cast<If>();
if (above == iff->condition) return true;
if (!iff->ifFalse) return false;
assert(above == iff->ifTrue || above == iff->ifFalse);
// continue down
} else {
if (curr->is<Drop>()) return false;
return true; // all other node types use the result
}
}
// The value might be used, so it depends on if the function returns
return func->result != none;
}
// Checks if a value is dropped.
bool ExpressionAnalyzer::isResultDropped(ExpressionStack& stack) {
for (int i = int(stack.size()) - 2; i >= 0; i--) {
auto* curr = stack[i];
auto* above = stack[i + 1];
if (curr->is<Block>()) {
auto* block = curr->cast<Block>();
for (size_t j = 0; j < block->list.size() - 1; j++) {
if (block->list[j] == above) return false;
}
assert(block->list.back() == above);
// continue down
} else if (curr->is<If>()) {
auto* iff = curr->cast<If>();
if (above == iff->condition) return false;
if (!iff->ifFalse) return false;
assert(above == iff->ifTrue || above == iff->ifFalse);
// continue down
} else {
if (curr->is<Drop>()) return true; // dropped
return false; // all other node types use the result
}
}
return false;
}
bool ExpressionAnalyzer::flexibleEqual(Expression* left, Expression* right, ExprComparer comparer) {
std::vector<Name> nameStack;
std::map<Name, std::vector<Name>> rightNames; // for each name on the left, the stack of names on the right (a stack, since names are scoped and can nest duplicatively
Nop popNameMarker;
std::vector<Expression*> leftStack;
std::vector<Expression*> rightStack;
auto noteNames = [&](Name left, Name right) {
if (left.is() != right.is()) return false;
if (left.is()) {
nameStack.push_back(left);
rightNames[left].push_back(right);
leftStack.push_back(&popNameMarker);
rightStack.push_back(&popNameMarker);
}
return true;
};
auto checkNames = [&](Name left, Name right) {
auto iter = rightNames.find(left);
if (iter == rightNames.end()) return left == right; // non-internal name
return iter->second.back() == right;
};
auto popName = [&]() {
auto left = nameStack.back();
nameStack.pop_back();
rightNames[left].pop_back();
};
leftStack.push_back(left);
rightStack.push_back(right);
while (leftStack.size() > 0 && rightStack.size() > 0) {
left = leftStack.back();
leftStack.pop_back();
right = rightStack.back();
rightStack.pop_back();
if (!left != !right) return false;
if (!left) continue;
if (left == &popNameMarker) {
popName();
continue;
}
if (comparer(left, right)) continue; // comparison hook, before all the rest
// continue with normal structural comparison
if (left->_id != right->_id) return false;
// Compare immediate values
#define CHECK(clazz, what) \
if (left->cast<clazz>()->what != right->cast<clazz>()->what) return false;
switch (left->_id) {
case Expression::Id::BlockId: {
if (!noteNames(left->cast<Block>()->name, right->cast<Block>()->name)) return false;
CHECK(Block, list.size());
break;
}
case Expression::Id::LoopId: {
if (!noteNames(left->cast<Loop>()->name, right->cast<Loop>()->name)) return false;
break;
}
case Expression::Id::BreakId: {
if (!checkNames(left->cast<Break>()->name, right->cast<Break>()->name)) return false;
break;
}
case Expression::Id::SwitchId: {
CHECK(Switch, targets.size());
for (Index i = 0; i < left->cast<Switch>()->targets.size(); i++) {
if (!checkNames(left->cast<Switch>()->targets[i], right->cast<Switch>()->targets[i])) return false;
}
if (!checkNames(left->cast<Switch>()->default_, right->cast<Switch>()->default_)) return false;
break;
}
case Expression::Id::CallId: {
CHECK(Call, target);
CHECK(Call, operands.size());
break;
}
case Expression::Id::CallIndirectId: {
CHECK(CallIndirect, fullType);
CHECK(CallIndirect, operands.size());
break;
}
case Expression::Id::GetLocalId: {
CHECK(GetLocal, index);
break;
}
case Expression::Id::SetLocalId: {
CHECK(SetLocal, index);
CHECK(SetLocal, type); // for tee/set
break;
}
case Expression::Id::GetGlobalId: {
CHECK(GetGlobal, name);
break;
}
case Expression::Id::SetGlobalId: {
CHECK(SetGlobal, name);
break;
}
case Expression::Id::LoadId: {
CHECK(Load, bytes);
if (LoadUtils::isSignRelevant(left->cast<Load>()) &&
LoadUtils::isSignRelevant(right->cast<Load>())) {
CHECK(Load, signed_);
}
CHECK(Load, offset);
CHECK(Load, align);
CHECK(Load, isAtomic);
break;
}
case Expression::Id::StoreId: {
CHECK(Store, bytes);
CHECK(Store, offset);
CHECK(Store, align);
CHECK(Store, valueType);
CHECK(Store, isAtomic);
break;
}
case Expression::Id::AtomicCmpxchgId: {
CHECK(AtomicCmpxchg, bytes);
CHECK(AtomicCmpxchg, offset);
break;
}
case Expression::Id::AtomicRMWId: {
CHECK(AtomicRMW, op);
CHECK(AtomicRMW, bytes);
CHECK(AtomicRMW, offset);
break;
}
case Expression::Id::AtomicWaitId: {
CHECK(AtomicWait, expectedType);
break;
}
case Expression::Id::AtomicWakeId: {
break;
}
case Expression::Id::SIMDExtractId: {
CHECK(SIMDExtract, op);
CHECK(SIMDExtract, index);
break;
}
case Expression::Id::SIMDReplaceId: {
CHECK(SIMDReplace, op);
CHECK(SIMDReplace, index);
break;
}
case Expression::Id::SIMDShuffleId: {
CHECK(SIMDShuffle, mask);
break;
}
case Expression::Id::SIMDBitselectId: {
break;
}
case Expression::Id::SIMDShiftId: {
CHECK(SIMDShift, op);
break;
}
case Expression::Id::MemoryInitId: {
CHECK(MemoryInit, segment);
break;
}
case Expression::Id::DataDropId: {
CHECK(DataDrop, segment);
break;
}
case Expression::Id::MemoryCopyId: {
break;
}
case Expression::Id::MemoryFillId: {
break;
}
case Expression::Id::ConstId: {
if (left->cast<Const>()->value != right->cast<Const>()->value) {
return false;
}
break;
}
case Expression::Id::UnaryId: {
CHECK(Unary, op);
break;
}
case Expression::Id::BinaryId: {
CHECK(Binary, op);
break;
}
case Expression::Id::HostId: {
CHECK(Host, op);
CHECK(Host, nameOperand);
CHECK(Host, operands.size());
break;
}
case Expression::Id::NopId: {
break;
}
case Expression::Id::UnreachableId: {
break;
}
case Expression::Id::InvalidId:
case Expression::Id::NumExpressionIds: {
WASM_UNREACHABLE();
}
case Expression::Id::IfId:
case Expression::Id::SelectId:
case Expression::Id::DropId:
case Expression::Id::ReturnId: {
break; // some nodes have no immediate fields
}
}
// Add child nodes
for (auto* child : ChildIterator(left)) {
leftStack.push_back(child);
}
for (auto* child : ChildIterator(right)) {
rightStack.push_back(child);
}
#undef CHECK
}
if (leftStack.size() > 0 || rightStack.size() > 0) return false;
return true;
}
// hash an expression, ignoring superficial details like specific internal names
HashType ExpressionAnalyzer::hash(Expression* curr) {
HashType digest = 0;
auto hash = [&digest](HashType hash) {
digest = rehash(digest, hash);
};
auto hash64 = [&digest](uint64_t hash) {
digest = rehash(rehash(digest, HashType(hash >> 32)), HashType(hash));
};
std::vector<Name> nameStack;
Index internalCounter = 0;
std::map<Name, std::vector<Index>> internalNames; // for each internal name, a vector if unique ids
Nop popNameMarker;
std::vector<Expression*> stack;
auto noteName = [&](Name curr) {
if (curr.is()) {
nameStack.push_back(curr);
internalNames[curr].push_back(internalCounter++);
stack.push_back(&popNameMarker);
}
return true;
};
auto hashName = [&](Name curr) {
auto iter = internalNames.find(curr);
if (iter == internalNames.end()) hash64(uint64_t(curr.str));
else hash(iter->second.back());
};
auto popName = [&]() {
auto curr = nameStack.back();
nameStack.pop_back();
internalNames[curr].pop_back();
};
stack.push_back(curr);
while (stack.size() > 0) {
curr = stack.back();
stack.pop_back();
if (!curr) continue;
if (curr == &popNameMarker) {
popName();
continue;
}
hash(curr->_id);
// we often don't need to hash the type, as it is tied to other values
// we are hashing anyhow, but there are exceptions: for example, a
// local.get's type is determined by the function, so if we are
// hashing only expression fragments, then two from different
// functions may turn out the same even if the type differs. Likewise,
// if we hash between modules, then we need to take int account
// call_imports type, etc. The simplest thing is just to hash the
// type for all of them.
hash(curr->type);
#define PUSH(clazz, what) \
stack.push_back(curr->cast<clazz>()->what);
#define HASH(clazz, what) \
hash(curr->cast<clazz>()->what);
#define HASH64(clazz, what) \
hash64(curr->cast<clazz>()->what);
#define HASH_NAME(clazz, what) \
hash64(uint64_t(curr->cast<clazz>()->what.str));
#define HASH_PTR(clazz, what) \
hash64(uint64_t(curr->cast<clazz>()->what));
switch (curr->_id) {
case Expression::Id::BlockId: {
noteName(curr->cast<Block>()->name);
HASH(Block, list.size());
for (Index i = 0; i < curr->cast<Block>()->list.size(); i++) {
PUSH(Block, list[i]);
}
break;
}
case Expression::Id::IfId: {
PUSH(If, condition);
PUSH(If, ifTrue);
PUSH(If, ifFalse);
break;
}
case Expression::Id::LoopId: {
noteName(curr->cast<Loop>()->name);
PUSH(Loop, body);
break;
}
case Expression::Id::BreakId: {
hashName(curr->cast<Break>()->name);
PUSH(Break, condition);
PUSH(Break, value);
break;
}
case Expression::Id::SwitchId: {
HASH(Switch, targets.size());
for (Index i = 0; i < curr->cast<Switch>()->targets.size(); i++) {
hashName(curr->cast<Switch>()->targets[i]);
}
hashName(curr->cast<Switch>()->default_);
PUSH(Switch, condition);
PUSH(Switch, value);
break;
}
case Expression::Id::CallId: {
HASH_NAME(Call, target);
HASH(Call, operands.size());
for (Index i = 0; i < curr->cast<Call>()->operands.size(); i++) {
PUSH(Call, operands[i]);
}
break;
}
case Expression::Id::CallIndirectId: {
PUSH(CallIndirect, target);
HASH_NAME(CallIndirect, fullType);
HASH(CallIndirect, operands.size());
for (Index i = 0; i < curr->cast<CallIndirect>()->operands.size(); i++) {
PUSH(CallIndirect, operands[i]);
}
break;
}
case Expression::Id::GetLocalId: {
HASH(GetLocal, index);
break;
}
case Expression::Id::SetLocalId: {
HASH(SetLocal, index);
PUSH(SetLocal, value);
break;
}
case Expression::Id::GetGlobalId: {
HASH_NAME(GetGlobal, name);
break;
}
case Expression::Id::SetGlobalId: {
HASH_NAME(SetGlobal, name);
PUSH(SetGlobal, value);
break;
}
case Expression::Id::LoadId: {
HASH(Load, bytes);
if (LoadUtils::isSignRelevant(curr->cast<Load>())) {
HASH(Load, signed_);
}
HASH(Load, offset);
HASH(Load, align);
HASH(Load, isAtomic);
PUSH(Load, ptr);
break;
}
case Expression::Id::StoreId: {
HASH(Store, bytes);
HASH(Store, offset);
HASH(Store, align);
HASH(Store, valueType);
HASH(Store, isAtomic);
PUSH(Store, ptr);
PUSH(Store, value);
break;
}
case Expression::Id::AtomicCmpxchgId: {
HASH(AtomicCmpxchg, bytes);
HASH(AtomicCmpxchg, offset);
PUSH(AtomicCmpxchg, ptr);
PUSH(AtomicCmpxchg, expected);
PUSH(AtomicCmpxchg, replacement);
break;
}
case Expression::Id::AtomicRMWId: {
HASH(AtomicRMW, op);
HASH(AtomicRMW, bytes);
HASH(AtomicRMW, offset);
PUSH(AtomicRMW, ptr);
PUSH(AtomicRMW, value);
break;
}
case Expression::Id::AtomicWaitId: {
HASH(AtomicWait, offset);
HASH(AtomicWait, expectedType);
PUSH(AtomicWait, ptr);
PUSH(AtomicWait, expected);
PUSH(AtomicWait, timeout);
break;
}
case Expression::Id::AtomicWakeId: {
HASH(AtomicWake, offset);
PUSH(AtomicWake, ptr);
PUSH(AtomicWake, wakeCount);
break;
}
case Expression::Id::SIMDExtractId: {
HASH(SIMDExtract, op);
HASH(SIMDExtract, index);
PUSH(SIMDExtract, vec);
break;
}
case Expression::Id::SIMDReplaceId: {
HASH(SIMDReplace, op);
HASH(SIMDReplace, index);
PUSH(SIMDReplace, vec);
PUSH(SIMDReplace, value);
break;
}
case Expression::Id::SIMDShuffleId: {
for (size_t i = 0; i < 16; ++i) {
HASH(SIMDShuffle, mask[i]);
}
PUSH(SIMDShuffle, left);
PUSH(SIMDShuffle, right);
break;
}
case Expression::Id::SIMDBitselectId: {
PUSH(SIMDBitselect, left);
PUSH(SIMDBitselect, right);
PUSH(SIMDBitselect, cond);
break;
}
case Expression::Id::SIMDShiftId: {
HASH(SIMDShift, op);
PUSH(SIMDShift, vec);
PUSH(SIMDShift, shift);
break;
}
case Expression::Id::MemoryInitId: {
HASH(MemoryInit, segment);
PUSH(MemoryInit, dest);
PUSH(MemoryInit, offset);
PUSH(MemoryInit, size);
break;
}
case Expression::Id::DataDropId: {
HASH(DataDrop, segment);
break;
}
case Expression::Id::MemoryCopyId: {
PUSH(MemoryCopy, dest);
PUSH(MemoryCopy, source);
PUSH(MemoryCopy, size);
break;
}
case Expression::Id::MemoryFillId: {
PUSH(MemoryFill, dest);
PUSH(MemoryFill, value);
PUSH(MemoryFill, size);
break;
}
case Expression::Id::ConstId: {
auto* c = curr->cast<Const>();
hash(c->type);
hash(std::hash<Literal>()(c->value));
break;
}
case Expression::Id::UnaryId: {
HASH(Unary, op);
PUSH(Unary, value);
break;
}
case Expression::Id::BinaryId: {
HASH(Binary, op);
PUSH(Binary, left);
PUSH(Binary, right);
break;
}
case Expression::Id::SelectId: {
PUSH(Select, ifTrue);
PUSH(Select, ifFalse);
PUSH(Select, condition);
break;
}
case Expression::Id::DropId: {
PUSH(Drop, value);
break;
}
case Expression::Id::ReturnId: {
PUSH(Return, value);
break;
}
case Expression::Id::HostId: {
HASH(Host, op);
HASH_NAME(Host, nameOperand);
HASH(Host, operands.size());
for (Index i = 0; i < curr->cast<Host>()->operands.size(); i++) {
PUSH(Host, operands[i]);
}
break;
}
case Expression::Id::NopId: {
break;
}
case Expression::Id::UnreachableId: {
break;
}
case Expression::Id::InvalidId:
case Expression::Id::NumExpressionIds: {
WASM_UNREACHABLE();
}
}
#undef HASH
#undef PUSH
}
return digest;
}
} // namespace wasm
| 29.86755 | 169 | 0.567406 |
Warchant
|
28c60af06486c6c0d4e5e16f2d899d71a52dc0e9
| 91 |
cpp
|
C++
|
QTP/views/clientview.cpp
|
Qu3tzal/TpQt
|
a741c64659d4808693c92de217261c75ed5fe17a
|
[
"MIT"
] | null | null | null |
QTP/views/clientview.cpp
|
Qu3tzal/TpQt
|
a741c64659d4808693c92de217261c75ed5fe17a
|
[
"MIT"
] | null | null | null |
QTP/views/clientview.cpp
|
Qu3tzal/TpQt
|
a741c64659d4808693c92de217261c75ed5fe17a
|
[
"MIT"
] | 1 |
2018-09-30T10:39:37.000Z
|
2018-09-30T10:39:37.000Z
|
#include "clientview.h"
ClientView::ClientView(QWidget *parent) : QTableView(parent)
{
}
| 13 | 60 | 0.736264 |
Qu3tzal
|
28c6123cc903f54864a936a4a4afcda8618cec8a
| 543 |
hpp
|
C++
|
part-27-vulkan-load-textures/main/src/core/mesh.hpp
|
tanzle-aames/a-simple-triangle
|
3cf7d76e8e8a3b5d42c6db35d3cbfef91b139ab0
|
[
"MIT"
] | 52 |
2019-11-30T04:45:02.000Z
|
2022-03-10T17:17:57.000Z
|
part-30-basic-user-input/main/src/core/mesh.hpp
|
eugenebokhan/a-simple-triangle
|
3cf7d76e8e8a3b5d42c6db35d3cbfef91b139ab0
|
[
"MIT"
] | null | null | null |
part-30-basic-user-input/main/src/core/mesh.hpp
|
eugenebokhan/a-simple-triangle
|
3cf7d76e8e8a3b5d42c6db35d3cbfef91b139ab0
|
[
"MIT"
] | 10 |
2020-03-30T16:18:30.000Z
|
2022-01-30T14:53:45.000Z
|
#pragma once
#include "internal-ptr.hpp"
#include "vertex.hpp"
#include <vector>
namespace ast
{
struct Mesh
{
Mesh(const std::vector<ast::Vertex>& vertices, const std::vector<uint32_t>& indices);
const std::vector<ast::Vertex>& getVertices() const;
const std::vector<uint32_t>& getIndices() const;
const uint32_t& getNumVertices() const;
const uint32_t& getNumIndices() const;
private:
struct Internal;
ast::internal_ptr<Internal> internal;
};
} // namespace ast
| 20.884615 | 93 | 0.642726 |
tanzle-aames
|
28ca111689a28c63c69729f5ca3405bfd07cb618
| 129 |
cpp
|
C++
|
src/modules/replay/replay_main.cpp
|
Diksha-agg/Firmware_val
|
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
|
[
"BSD-3-Clause"
] | null | null | null |
src/modules/replay/replay_main.cpp
|
Diksha-agg/Firmware_val
|
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
|
[
"BSD-3-Clause"
] | null | null | null |
src/modules/replay/replay_main.cpp
|
Diksha-agg/Firmware_val
|
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
|
[
"BSD-3-Clause"
] | null | null | null |
version https://git-lfs.github.com/spec/v1
oid sha256:a88a7b61d2bf7615571ada8de82e2cf5034f40407f98a48fadeaad6849143d52
size 2097
| 32.25 | 75 | 0.883721 |
Diksha-agg
|
28ca4208c578f7cdcc4db8288ec2fa9313bab65e
| 3,672 |
cpp
|
C++
|
test/atomic/tst_atomic.cpp
|
ombre5733/weos
|
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
|
[
"BSD-2-Clause"
] | 11 |
2015-10-06T21:00:30.000Z
|
2021-07-27T05:54:44.000Z
|
test/atomic/tst_atomic.cpp
|
ombre5733/weos
|
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
|
[
"BSD-2-Clause"
] | null | null | null |
test/atomic/tst_atomic.cpp
|
ombre5733/weos
|
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
|
[
"BSD-2-Clause"
] | 1 |
2015-10-03T03:51:28.000Z
|
2015-10-03T03:51:28.000Z
|
/*******************************************************************************
WEOS - Wrapper for embedded operating systems
Copyright (c) 2013-2016, Manuel Freiberger
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <atomic.hpp>
#include "../common/testutils.hpp"
#include "gtest/gtest.h"
TEST(atomic_flag, default_construction)
{
weos::atomic_flag flag;
(void)flag;
}
TEST(atomic_flag, initialization)
{
weos::atomic_flag flag = ATOMIC_FLAG_INIT;
(void)flag;
}
TEST(atomic_flag, test_and_set)
{
weos::atomic_flag flag = ATOMIC_FLAG_INIT;
ASSERT_FALSE(flag.test_and_set());
ASSERT_TRUE(flag.test_and_set());
flag.clear();
ASSERT_FALSE(flag.test_and_set());
ASSERT_TRUE(flag.test_and_set());
}
TEST(atomic_int, default_construction)
{
weos::atomic_int x;
(void)x;
}
TEST(atomic_int, construct_with_value)
{
int value;
weos::atomic_int x(68);
value = x;
ASSERT_EQ(68, value);
}
TEST(atomic_int, load_and_store)
{
int value;
weos::atomic_int x(68);
value = x.load();
ASSERT_EQ(68, value);
x.store(21);
value = x.load();
ASSERT_EQ(21, value);
value = x;
ASSERT_EQ(21, value);
}
TEST(atomic_int, exchange)
{
int value;
weos::atomic_int x(68);
value = x.load();
ASSERT_EQ(68, value);
value = x.exchange(21);
ASSERT_EQ(68, value);
value = x;
ASSERT_EQ(21, value);
}
TEST(atomic_int, fetch_X)
{
int value;
weos::atomic_int x(68);
value = x.fetch_add(3);
ASSERT_EQ(68, value);
value = x.fetch_sub(5);
ASSERT_EQ(71, value);
value = x.fetch_and(64);
ASSERT_EQ(66, value);
value = x.fetch_or(17);
ASSERT_EQ(64, value);
value = x.fetch_xor(66);
ASSERT_EQ(81, value);
value = x;
ASSERT_EQ(19, value);
}
TEST(atomic_int, compare_exchange_strong)
{
int expected = 66;
bool exchanged;
weos::atomic_int x(68);
exchanged = x.compare_exchange_strong(expected, 77);
ASSERT_FALSE(exchanged);
ASSERT_EQ(68, expected);
ASSERT_EQ(68, int(x));
exchanged = x.compare_exchange_strong(expected, 77);
ASSERT_TRUE(exchanged);
ASSERT_EQ(68, expected);
ASSERT_EQ(77, int(x));
}
TEST(atomic_int, operators)
{
weos::atomic_int x(68);
ASSERT_EQ(68, int(x));
x = 77;
ASSERT_EQ(77, int(x));
}
| 25.5 | 80 | 0.666667 |
ombre5733
|
28ce81fbcfeeda7774c485b7a25136c08c1e9ed6
| 1,742 |
hpp
|
C++
|
src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/memory_LSTMCell.hpp
|
pazamelin/openvino
|
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
|
[
"Apache-2.0"
] | 1 |
2019-09-22T01:05:07.000Z
|
2019-09-22T01:05:07.000Z
|
src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/memory_LSTMCell.hpp
|
pazamelin/openvino
|
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
|
[
"Apache-2.0"
] | 58 |
2020-11-06T12:13:45.000Z
|
2022-03-28T13:20:11.000Z
|
src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/memory_LSTMCell.hpp
|
pazamelin/openvino
|
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
|
[
"Apache-2.0"
] | 2 |
2019-09-20T01:33:37.000Z
|
2019-09-20T08:42:11.000Z
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "common_test_utils/test_common.hpp"
#include "shared_test_classes/base/layer_test_utils.hpp"
#include <ie_core.hpp>
namespace SubgraphTestsDefinitions {
typedef std::tuple<
ngraph::helpers::MemoryTransformation, // Apply Memory transformation
std::string, // Target device name
InferenceEngine::Precision, // Network precision
size_t, // Input size
size_t, // Hidden size
std::map<std::string, std::string> // Configuration
> memoryLSTMCellParams;
class MemoryLSTMCellTest : virtual public LayerTestsUtils::LayerTestsCommon,
public testing::WithParamInterface<memoryLSTMCellParams> {
private:
// you have to Unroll TI manually and remove memory untill ngraph supports it
// since we switching models we need to generate and save weights biases and inputs in SetUp
void switchToNgraphFriendlyModel();
void CreatePureTensorIteratorModel();
void InitMemory();
void ApplyLowLatency();
ngraph::helpers::MemoryTransformation transformation;
std::vector<float> input_bias;
std::vector<float> input_weights;
std::vector<float> hidden_memory_init;
std::vector<float> cell_memory_init;
std::vector<float> weights_vals;
std::vector<float> reccurrenceWeights_vals;
std::vector<float> bias_vals;
protected:
void SetUp() override;
void Run() override;
void LoadNetwork() override;
void Infer() override;
public:
static std::string getTestCaseName(const testing::TestParamInfo<memoryLSTMCellParams> &obj);
};
} // namespace SubgraphTestsDefinitions
| 36.291667 | 96 | 0.710677 |
pazamelin
|
28cec803ab7a589801d844c1e0c48f30689078d1
| 9,617 |
cc
|
C++
|
android_webview/browser/hardware_renderer.cc
|
tmpsantos/chromium
|
802d4aeeb33af25c01ee5994037bbf14086d4ac0
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
android_webview/browser/hardware_renderer.cc
|
tmpsantos/chromium
|
802d4aeeb33af25c01ee5994037bbf14086d4ac0
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
android_webview/browser/hardware_renderer.cc
|
tmpsantos/chromium
|
802d4aeeb33af25c01ee5994037bbf14086d4ac0
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 |
2020-11-04T07:23:37.000Z
|
2020-11-04T07:23:37.000Z
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/hardware_renderer.h"
#include "android_webview/browser/aw_gl_surface.h"
#include "android_webview/browser/deferred_gpu_command_service.h"
#include "android_webview/browser/parent_output_surface.h"
#include "android_webview/browser/shared_renderer_state.h"
#include "android_webview/public/browser/draw_gl.h"
#include "base/auto_reset.h"
#include "base/debug/trace_event.h"
#include "base/strings/string_number_conversions.h"
#include "cc/layers/delegated_frame_provider.h"
#include "cc/layers/delegated_renderer_layer.h"
#include "cc/layers/layer.h"
#include "cc/output/compositor_frame.h"
#include "cc/output/output_surface.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_settings.h"
#include "gpu/command_buffer/client/gl_in_process_context.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"
#include "ui/gfx/frame_time.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/transform.h"
#include "ui/gl/gl_bindings.h"
#include "webkit/common/gpu/context_provider_in_process.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
namespace android_webview {
namespace {
using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl;
using webkit::gpu::WebGraphicsContext3DImpl;
scoped_refptr<cc::ContextProvider> CreateContext(
scoped_refptr<gfx::GLSurface> surface,
scoped_refptr<gpu::InProcessCommandBuffer::Service> service,
gpu::GLInProcessContext* share_context) {
const gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu;
blink::WebGraphicsContext3D::Attributes attributes;
attributes.antialias = false;
attributes.depth = false;
attributes.stencil = false;
attributes.shareResources = true;
attributes.noAutomaticFlushes = true;
gpu::gles2::ContextCreationAttribHelper attribs_for_gles2;
WebGraphicsContext3DImpl::ConvertAttributes(
attributes, &attribs_for_gles2);
attribs_for_gles2.lose_context_when_out_of_memory = true;
scoped_ptr<gpu::GLInProcessContext> context(gpu::GLInProcessContext::Create(
service,
surface,
surface->IsOffscreen(),
gfx::kNullAcceleratedWidget,
surface->GetSize(),
share_context,
false /* share_resources */,
attribs_for_gles2,
gpu_preference,
gpu::GLInProcessContextSharedMemoryLimits()));
DCHECK(context.get());
return webkit::gpu::ContextProviderInProcess::Create(
WebGraphicsContext3DInProcessCommandBufferImpl::WrapContext(
context.Pass(), attributes),
"Parent-Compositor");
}
} // namespace
HardwareRenderer::HardwareRenderer(SharedRendererState* state)
: shared_renderer_state_(state),
last_egl_context_(eglGetCurrentContext()),
stencil_enabled_(false),
viewport_clip_valid_for_dcheck_(false),
gl_surface_(new AwGLSurface),
root_layer_(cc::Layer::Create()),
resource_collection_(new cc::DelegatedFrameResourceCollection),
output_surface_(NULL) {
DCHECK(last_egl_context_);
resource_collection_->SetClient(this);
cc::LayerTreeSettings settings;
// Should be kept in sync with compositor_impl_android.cc.
settings.allow_antialiasing = false;
settings.highp_threshold_min = 2048;
// Webview does not own the surface so should not clear it.
settings.should_clear_root_render_pass = false;
// TODO(enne): Update this this compositor to use a synchronous scheduler.
settings.single_thread_proxy_scheduler = false;
layer_tree_host_ =
cc::LayerTreeHost::CreateSingleThreaded(this, this, NULL, settings, NULL);
layer_tree_host_->SetRootLayer(root_layer_);
layer_tree_host_->SetLayerTreeHostClientReady();
layer_tree_host_->set_has_transparent_background(true);
}
HardwareRenderer::~HardwareRenderer() {
// Must reset everything before |resource_collection_| to ensure all
// resources are returned before resetting |resource_collection_| client.
layer_tree_host_.reset();
root_layer_ = NULL;
delegated_layer_ = NULL;
frame_provider_ = NULL;
#if DCHECK_IS_ON
// Check collection is empty.
cc::ReturnedResourceArray returned_resources;
resource_collection_->TakeUnusedResourcesForChildCompositor(
&returned_resources);
DCHECK_EQ(0u, returned_resources.size());
#endif // DCHECK_IS_ON
resource_collection_->SetClient(NULL);
// Reset draw constraints.
shared_renderer_state_->UpdateDrawConstraints(
ParentCompositorDrawConstraints());
}
void HardwareRenderer::DidBeginMainFrame() {
// This is called after OutputSurface is created, but before the impl frame
// starts. We set the draw constraints here.
DCHECK(output_surface_);
DCHECK(viewport_clip_valid_for_dcheck_);
output_surface_->SetExternalStencilTest(stencil_enabled_);
output_surface_->SetDrawConstraints(viewport_, clip_);
}
void HardwareRenderer::CommitFrame() {
scoped_ptr<DrawGLInput> input = shared_renderer_state_->PassDrawGLInput();
if (!input.get()) {
DLOG(WARNING) << "No frame to commit";
return;
}
DCHECK(!input->frame.gl_frame_data);
DCHECK(!input->frame.software_frame_data);
// DelegatedRendererLayerImpl applies the inverse device_scale_factor of the
// renderer frame, assuming that the browser compositor will scale
// it back up to device scale. But on Android we put our browser layers in
// physical pixels and set our browser CC device_scale_factor to 1, so this
// suppresses the transform.
input->frame.delegated_frame_data->device_scale_factor = 1.0f;
gfx::Size frame_size =
input->frame.delegated_frame_data->render_pass_list.back()
->output_rect.size();
bool size_changed = frame_size != frame_size_;
frame_size_ = frame_size;
scroll_offset_ = input->scroll_offset;
if (!frame_provider_ || size_changed) {
if (delegated_layer_) {
delegated_layer_->RemoveFromParent();
}
frame_provider_ = new cc::DelegatedFrameProvider(
resource_collection_.get(), input->frame.delegated_frame_data.Pass());
delegated_layer_ = cc::DelegatedRendererLayer::Create(frame_provider_);
delegated_layer_->SetBounds(gfx::Size(input->width, input->height));
delegated_layer_->SetIsDrawable(true);
root_layer_->AddChild(delegated_layer_);
} else {
frame_provider_->SetFrameData(input->frame.delegated_frame_data.Pass());
}
}
void HardwareRenderer::DrawGL(bool stencil_enabled,
int framebuffer_binding_ext,
AwDrawGLInfo* draw_info) {
TRACE_EVENT0("android_webview", "HardwareRenderer::DrawGL");
// We need to watch if the current Android context has changed and enforce
// a clean-up in the compositor.
EGLContext current_context = eglGetCurrentContext();
if (!current_context) {
DLOG(ERROR) << "DrawGL called without EGLContext";
return;
}
if (!delegated_layer_.get()) {
DLOG(ERROR) << "No frame committed";
return;
}
// TODO(boliu): Handle context loss.
if (last_egl_context_ != current_context)
DLOG(WARNING) << "EGLContextChanged";
gfx::Transform transform(gfx::Transform::kSkipInitialization);
transform.matrix().setColMajorf(draw_info->transform);
transform.Translate(scroll_offset_.x(), scroll_offset_.y());
// Need to post the new transform matrix back to child compositor
// because there is no onDraw during a Render Thread animation, and child
// compositor might not have the tiles rasterized as the animation goes on.
ParentCompositorDrawConstraints draw_constraints(
draw_info->is_layer, transform, gfx::Rect(viewport_));
if (!draw_constraints_.Equals(draw_constraints)) {
draw_constraints_ = draw_constraints;
shared_renderer_state_->PostExternalDrawConstraintsToChildCompositor(
draw_constraints);
}
viewport_.SetSize(draw_info->width, draw_info->height);
layer_tree_host_->SetViewportSize(viewport_);
clip_.SetRect(draw_info->clip_left,
draw_info->clip_top,
draw_info->clip_right - draw_info->clip_left,
draw_info->clip_bottom - draw_info->clip_top);
stencil_enabled_ = stencil_enabled;
delegated_layer_->SetTransform(transform);
gl_surface_->SetBackingFrameBufferObject(framebuffer_binding_ext);
{
base::AutoReset<bool> frame_resetter(&viewport_clip_valid_for_dcheck_,
true);
layer_tree_host_->SetNeedsRedrawRect(clip_);
layer_tree_host_->Composite(gfx::FrameTime::Now());
}
gl_surface_->ResetBackingFrameBufferObject();
}
scoped_ptr<cc::OutputSurface> HardwareRenderer::CreateOutputSurface(
bool fallback) {
// Android webview does not support losing output surface.
DCHECK(!fallback);
scoped_refptr<cc::ContextProvider> context_provider =
CreateContext(gl_surface_,
DeferredGpuCommandService::GetInstance(),
shared_renderer_state_->GetSharedContext());
scoped_ptr<ParentOutputSurface> output_surface_holder(
new ParentOutputSurface(context_provider));
output_surface_ = output_surface_holder.get();
return output_surface_holder.PassAs<cc::OutputSurface>();
}
void HardwareRenderer::UnusedResourcesAreAvailable() {
cc::ReturnedResourceArray returned_resources;
resource_collection_->TakeUnusedResourcesForChildCompositor(
&returned_resources);
shared_renderer_state_->InsertReturnedResources(returned_resources);
}
} // namespace android_webview
| 36.846743 | 82 | 0.756369 |
tmpsantos
|
28d1199c443a1c6ac89737eeda20afa14e6c7b01
| 726 |
cpp
|
C++
|
libs/json/src/io.cpp
|
silvergasp/json_spirit
|
51a5c4154c8599a6b57595c7005e43491c1356fd
|
[
"BSL-1.0"
] | 103 |
2015-01-13T18:06:47.000Z
|
2021-11-24T11:22:29.000Z
|
libs/json/src/io.cpp
|
silvergasp/json_spirit
|
51a5c4154c8599a6b57595c7005e43491c1356fd
|
[
"BSL-1.0"
] | 12 |
2015-08-04T12:46:17.000Z
|
2021-01-12T06:49:24.000Z
|
libs/json/src/io.cpp
|
silvergasp/json_spirit
|
51a5c4154c8599a6b57595c7005e43491c1356fd
|
[
"BSL-1.0"
] | 37 |
2015-03-07T01:16:37.000Z
|
2022-01-26T08:42:51.000Z
|
/**
* Copyright (C) 2012 ciere consulting, ciere.com
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
#include "ciere/json/value.hpp"
#include "ciere/json/parser/grammar_def.hpp"
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <string>
#include <vector>
using string_iter_t = std::string::const_iterator;
using vector_uint8_iter_t = std::vector<uint8_t>::const_iterator;
template struct ciere::json::parser::grammar<string_iter_t>;
template struct ciere::json::parser::grammar<boost::spirit::istream_iterator>;
template struct ciere::json::parser::grammar<vector_uint8_iter_t>;
| 31.565217 | 81 | 0.764463 |
silvergasp
|
28d2d288b28a076d0f22683a831e1365877a90dc
| 6,867 |
cpp
|
C++
|
vrclient_x64/vrclient_x64/cppIVRApplications_IVRApplications_005.cpp
|
neuroradiology/Proton
|
5aed286761234b1b362471ca5cf80d25f64cb719
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 17,337 |
2018-08-21T21:43:27.000Z
|
2022-03-31T18:06:05.000Z
|
vrclient_x64/vrclient_x64/cppIVRApplications_IVRApplications_005.cpp
|
neuroradiology/Proton
|
5aed286761234b1b362471ca5cf80d25f64cb719
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,641 |
2018-08-21T22:40:50.000Z
|
2022-03-31T23:58:40.000Z
|
vrclient_x64/vrclient_x64/cppIVRApplications_IVRApplications_005.cpp
|
neuroradiology/Proton
|
5aed286761234b1b362471ca5cf80d25f64cb719
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 910 |
2018-08-21T22:54:53.000Z
|
2022-03-29T17:35:31.000Z
|
#include "vrclient_private.h"
#include "vrclient_defs.h"
#include "openvr_v1.0.1/openvr.h"
using namespace vr;
extern "C" {
#include "struct_converters.h"
}
#include "cppIVRApplications_IVRApplications_005.h"
#ifdef __cplusplus
extern "C" {
#endif
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_AddApplicationManifest(void *linux_side, const char * pchApplicationManifestFullPath, bool bTemporary)
{
return ((IVRApplications*)linux_side)->AddApplicationManifest((const char *)pchApplicationManifestFullPath, (bool)bTemporary);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_RemoveApplicationManifest(void *linux_side, const char * pchApplicationManifestFullPath)
{
return ((IVRApplications*)linux_side)->RemoveApplicationManifest((const char *)pchApplicationManifestFullPath);
}
bool cppIVRApplications_IVRApplications_005_IsApplicationInstalled(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->IsApplicationInstalled((const char *)pchAppKey);
}
uint32_t cppIVRApplications_IVRApplications_005_GetApplicationCount(void *linux_side)
{
return ((IVRApplications*)linux_side)->GetApplicationCount();
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_GetApplicationKeyByIndex(void *linux_side, uint32_t unApplicationIndex, char * pchAppKeyBuffer, uint32_t unAppKeyBufferLen)
{
return ((IVRApplications*)linux_side)->GetApplicationKeyByIndex((uint32_t)unApplicationIndex, (char *)pchAppKeyBuffer, (uint32_t)unAppKeyBufferLen);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_GetApplicationKeyByProcessId(void *linux_side, uint32_t unProcessId, char * pchAppKeyBuffer, uint32_t unAppKeyBufferLen)
{
return ((IVRApplications*)linux_side)->GetApplicationKeyByProcessId((uint32_t)unProcessId, (char *)pchAppKeyBuffer, (uint32_t)unAppKeyBufferLen);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchApplication(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->LaunchApplication((const char *)pchAppKey);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchTemplateApplication(void *linux_side, const char * pchTemplateAppKey, const char * pchNewAppKey, AppOverrideKeys_t * pKeys, uint32_t unKeys)
{
return ((IVRApplications*)linux_side)->LaunchTemplateApplication((const char *)pchTemplateAppKey, (const char *)pchNewAppKey, (const vr::AppOverrideKeys_t *)pKeys, (uint32_t)unKeys);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchDashboardOverlay(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->LaunchDashboardOverlay((const char *)pchAppKey);
}
bool cppIVRApplications_IVRApplications_005_CancelApplicationLaunch(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->CancelApplicationLaunch((const char *)pchAppKey);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_IdentifyApplication(void *linux_side, uint32_t unProcessId, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->IdentifyApplication((uint32_t)unProcessId, (const char *)pchAppKey);
}
uint32_t cppIVRApplications_IVRApplications_005_GetApplicationProcessId(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->GetApplicationProcessId((const char *)pchAppKey);
}
const char * cppIVRApplications_IVRApplications_005_GetApplicationsErrorNameFromEnum(void *linux_side, EVRApplicationError error)
{
return ((IVRApplications*)linux_side)->GetApplicationsErrorNameFromEnum((vr::EVRApplicationError)error);
}
uint32_t cppIVRApplications_IVRApplications_005_GetApplicationPropertyString(void *linux_side, const char * pchAppKey, EVRApplicationProperty eProperty, char * pchPropertyValueBuffer, uint32_t unPropertyValueBufferLen, EVRApplicationError * peError)
{
return ((IVRApplications*)linux_side)->GetApplicationPropertyString((const char *)pchAppKey, (vr::EVRApplicationProperty)eProperty, (char *)pchPropertyValueBuffer, (uint32_t)unPropertyValueBufferLen, (vr::EVRApplicationError *)peError);
}
bool cppIVRApplications_IVRApplications_005_GetApplicationPropertyBool(void *linux_side, const char * pchAppKey, EVRApplicationProperty eProperty, EVRApplicationError * peError)
{
return ((IVRApplications*)linux_side)->GetApplicationPropertyBool((const char *)pchAppKey, (vr::EVRApplicationProperty)eProperty, (vr::EVRApplicationError *)peError);
}
uint64_t cppIVRApplications_IVRApplications_005_GetApplicationPropertyUint64(void *linux_side, const char * pchAppKey, EVRApplicationProperty eProperty, EVRApplicationError * peError)
{
return ((IVRApplications*)linux_side)->GetApplicationPropertyUint64((const char *)pchAppKey, (vr::EVRApplicationProperty)eProperty, (vr::EVRApplicationError *)peError);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_SetApplicationAutoLaunch(void *linux_side, const char * pchAppKey, bool bAutoLaunch)
{
return ((IVRApplications*)linux_side)->SetApplicationAutoLaunch((const char *)pchAppKey, (bool)bAutoLaunch);
}
bool cppIVRApplications_IVRApplications_005_GetApplicationAutoLaunch(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->GetApplicationAutoLaunch((const char *)pchAppKey);
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_GetStartingApplication(void *linux_side, char * pchAppKeyBuffer, uint32_t unAppKeyBufferLen)
{
return ((IVRApplications*)linux_side)->GetStartingApplication((char *)pchAppKeyBuffer, (uint32_t)unAppKeyBufferLen);
}
vr::EVRApplicationTransitionState cppIVRApplications_IVRApplications_005_GetTransitionState(void *linux_side)
{
return ((IVRApplications*)linux_side)->GetTransitionState();
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_PerformApplicationPrelaunchCheck(void *linux_side, const char * pchAppKey)
{
return ((IVRApplications*)linux_side)->PerformApplicationPrelaunchCheck((const char *)pchAppKey);
}
const char * cppIVRApplications_IVRApplications_005_GetApplicationsTransitionStateNameFromEnum(void *linux_side, EVRApplicationTransitionState state)
{
return ((IVRApplications*)linux_side)->GetApplicationsTransitionStateNameFromEnum((vr::EVRApplicationTransitionState)state);
}
bool cppIVRApplications_IVRApplications_005_IsQuitUserPromptRequested(void *linux_side)
{
return ((IVRApplications*)linux_side)->IsQuitUserPromptRequested();
}
vr::EVRApplicationError cppIVRApplications_IVRApplications_005_LaunchInternalProcess(void *linux_side, const char * pchBinaryPath, const char * pchArguments, const char * pchWorkingDirectory)
{
return ((IVRApplications*)linux_side)->LaunchInternalProcess((const char *)pchBinaryPath, (const char *)pchArguments, (const char *)pchWorkingDirectory);
}
#ifdef __cplusplus
}
#endif
| 50.866667 | 249 | 0.831076 |
neuroradiology
|
28d4650279037d2c0656b38773cdd4d0514ceb31
| 2,645 |
cxx
|
C++
|
etc/xsd/example/driver.cxx
|
sutambe/LEESA
|
fedaf4c0d7887c361d2a79967e3e770f375ddc25
|
[
"BSD-3-Clause"
] | null | null | null |
etc/xsd/example/driver.cxx
|
sutambe/LEESA
|
fedaf4c0d7887c361d2a79967e3e770f375ddc25
|
[
"BSD-3-Clause"
] | 3 |
2018-09-17T19:12:54.000Z
|
2018-09-19T16:09:53.000Z
|
etc/xsd/example/driver.cxx
|
sutambe/LEESA
|
fedaf4c0d7887c361d2a79967e3e770f375ddc25
|
[
"BSD-3-Clause"
] | null | null | null |
// file : examples/cxx/tree/library/driver.cxx
// author : Boris Kolpackov <boris@codesynthesis.com>
// copyright : not copyrighted - public domain
#include <memory> // std::auto_ptr
#include <iostream>
#include "library.hpp"
#define SCHEMA_NAMESPACE_FOR_LEESA library
#include "LEESA.h"
using std::cerr;
using std::endl;
library::catalog::book_sequence
foo (const library::catalog & c)
{
using namespace LEESA;
using namespace library;
BOOST_AUTO(expr, catalog() >> book());
catalog::book_sequence b = evaluate(c, expr);
return b;
}
bool starts_with_s (library::name const & n)
{
return (n[0] == 'S');
}
void print (library::name const & n)
{
std::cout << n << endl;
}
LEESA::ContainerGen<library::name>::type
bar (const library::catalog & c)
{
using namespace LEESA;
using namespace library;
BOOST_AUTO(expr, catalog() >> book() >> author() >> name()
>> ForEach(name(), print)
>> Select(name(), starts_with_s));
ContainerGen<name>::type names = evaluate(c, expr);
return names;
}
int
main (int argc, char* argv[])
{
if (argc != 2)
{
cerr << "usage: " << argv[0] << " library.xml" << endl;
return 1;
}
try
{
using namespace library;
// Read in the XML file and obtain its object model.
//
std::auto_ptr<catalog> c (catalog_ (argv[1]));
catalog::book_sequence b1 = foo (*c);
// Let's print what we've got.
//
for (catalog::book_const_iterator bi (b1.begin ());
bi != b1.end ();
++bi)
{
cerr << endl
<< "ID : " << bi->id () << endl
<< "ISBN : " << bi->isbn () << endl
<< "Title : " << bi->title () << endl
<< "Genre : " << bi->genre () << endl;
for (book::author_const_iterator ai (bi->author ().begin ());
ai != bi->author ().end ();
++ai)
{
cerr << "Author : " << ai->name () << endl;
cerr << " Born : " << ai->born () << endl;
if (ai->died ())
cerr << " Died : " << *ai->died () << endl;
//if (ai->recommends ())
// cerr << " Recommends : " << (*ai->recommends ())->title () << endl;
}
cerr << "Available : " << std::boolalpha << bi->available () << endl;
}
LEESA::ContainerGen<name>::type names = bar(*c);
for (LEESA::ContainerGen<name>::type::const_iterator i(names.begin());
i != names.end(); ++i)
{
std::cout << *i << endl;
}
return 0;
}
catch (const xml_schema::exception& e)
{
cerr << e << endl;
return 1;
}
}
| 24.045455 | 80 | 0.524386 |
sutambe
|
28d4eec23864a024c50381dbe5e0a85707441286
| 5,886 |
cpp
|
C++
|
Source/Ilum/Editor/Panels/Hierarchy.cpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | 11 |
2022-01-09T05:32:56.000Z
|
2022-03-28T06:35:16.000Z
|
Source/Ilum/Editor/Panels/Hierarchy.cpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | null | null | null |
Source/Ilum/Editor/Panels/Hierarchy.cpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | 1 |
2021-11-20T15:39:03.000Z
|
2021-11-20T15:39:03.000Z
|
#include "Hierarchy.hpp"
#include "Scene/Component/Hierarchy.hpp"
#include "Scene/Component/Tag.hpp"
#include "Scene/Component/Transform.hpp"
#include "Scene/Entity.hpp"
#include "Editor/Editor.hpp"
#include <imgui.h>
namespace Ilum::panel
{
inline void delete_node(Entity entity)
{
if (!entity)
{
return;
}
auto child = Entity(entity.getComponent<cmpt::Hierarchy>().first);
auto sibling = child ? Entity(child.getComponent<cmpt::Hierarchy>().next) : Entity();
while (sibling)
{
auto tmp = Entity(sibling.getComponent<cmpt::Hierarchy>().next);
delete_node(sibling);
sibling = tmp;
}
delete_node(child);
entity.destroy();
}
inline bool is_parent_of(Entity lhs, Entity rhs)
{
auto parent = Entity(rhs.getComponent<cmpt::Hierarchy>().parent);
while (parent)
{
if (parent == lhs)
{
return true;
}
parent = Entity(parent.getComponent<cmpt::Hierarchy>().parent);
}
return false;
}
inline void set_as_son(Entity new_parent, Entity new_son)
{
if (new_parent && is_parent_of(new_son, new_parent))
{
return;
}
auto &h2 = new_son.getComponent<cmpt::Hierarchy>();
if (h2.next != entt::null)
{
Entity(h2.next).getComponent<cmpt::Hierarchy>().prev = h2.prev;
}
if (h2.prev != entt::null)
{
Entity(h2.prev).getComponent<cmpt::Hierarchy>().next = h2.next;
}
if (h2.parent != entt::null && new_son == Entity(h2.parent).getComponent<cmpt::Hierarchy>().first)
{
Entity(h2.parent).getComponent<cmpt::Hierarchy>().first = h2.next;
}
h2.next = new_parent ? new_parent.getComponent<cmpt::Hierarchy>().first : entt::null;
h2.prev = entt::null;
h2.parent = new_parent ? new_parent.getHandle() : entt::null;
if (new_parent && new_parent.getComponent<cmpt::Hierarchy>().first != entt::null)
{
Entity(new_parent.getComponent<cmpt::Hierarchy>().first).getComponent<cmpt::Hierarchy>().prev = new_son;
}
if (new_parent)
{
new_parent.getComponent<cmpt::Hierarchy>().first = new_son;
}
}
inline void draw_node(Entity entity)
{
if (!entity)
{
return;
}
auto &tag = entity.getComponent<cmpt::Tag>().name;
bool has_child = entity.hasComponent<cmpt::Hierarchy>() && entity.getComponent<cmpt::Hierarchy>().first != entt::null;
// Setting up
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(5, 5));
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_FramePadding | ImGuiTreeNodeFlags_DefaultOpen | (Editor::instance()->getSelect() == entity ? ImGuiTreeNodeFlags_Selected : 0) | (has_child ? 0 : ImGuiTreeNodeFlags_Leaf);
bool open = ImGui::TreeNodeEx(std::to_string(entity).c_str(), flags, "%s", tag.c_str());
ImGui::PopStyleVar();
// Delete entity
ImGui::PushID(std::to_string(entity).c_str());
bool entity_deleted = false;
if (ImGui::BeginPopupContextItem(std::to_string(entity).c_str()))
{
if (ImGui::MenuItem("Delete Entity"))
{
entity_deleted = true;
}
ImGui::EndPopup();
}
ImGui::PopID();
// Select entity
if (ImGui::IsItemClicked())
{
Editor::instance()->select(entity);
}
// Drag and drop
if (ImGui::BeginDragDropSource())
{
if (entity.hasComponent<cmpt::Hierarchy>())
{
ImGui::SetDragDropPayload("Entity", &entity, sizeof(Entity));
}
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget())
{
if (const auto *pay_load = ImGui::AcceptDragDropPayload("Entity"))
{
ASSERT(pay_load->DataSize == sizeof(Entity));
set_as_son(entity, *static_cast<Entity *>(pay_load->Data));
entity.getComponent<cmpt::Transform>().update = true;
static_cast<Entity *>(pay_load->Data)->getComponent<cmpt::Transform>().update = true;
}
ImGui::EndDragDropTarget();
}
// Recursively open children entities
if (open)
{
if (has_child)
{
auto child = Entity(entity.getComponent<cmpt::Hierarchy>().first);
while (child)
{
draw_node(child);
if (child)
{
child = Entity(child.getComponent<cmpt::Hierarchy>().next);
}
}
}
ImGui::TreePop();
}
// Delete callback
if (entity_deleted)
{
if (Entity(entity.getComponent<cmpt::Hierarchy>().prev))
{
Entity(entity.getComponent<cmpt::Hierarchy>().prev).getComponent<cmpt::Hierarchy>().next = entity.getComponent<cmpt::Hierarchy>().next;
}
if (Entity(entity.getComponent<cmpt::Hierarchy>().next))
{
Entity(entity.getComponent<cmpt::Hierarchy>().next).getComponent<cmpt::Hierarchy>().prev = entity.getComponent<cmpt::Hierarchy>().prev;
}
if (Entity(entity.getComponent<cmpt::Hierarchy>().parent) && entity == Entity(entity.getComponent<cmpt::Hierarchy>().parent).getComponent<cmpt::Hierarchy>().first)
{
Entity(entity.getComponent<cmpt::Hierarchy>().parent).getComponent<cmpt::Hierarchy>().first = entity.getComponent<cmpt::Hierarchy>().next;
}
delete_node(entity);
if (Editor::instance()->getSelect() == entity)
{
Editor::instance()->select(Entity());
}
}
}
Hierarchy::Hierarchy()
{
m_name = "Hierarchy";
}
void Hierarchy::draw(float delta_time)
{
ImGui::Begin("Scene Hierarchy", &active);
if (ImGui::BeginDragDropTarget())
{
if (const auto *pay_load = ImGui::AcceptDragDropPayload("Entity"))
{
ASSERT(pay_load->DataSize == sizeof(Entity));
set_as_son(Entity(), *static_cast<Entity *>(pay_load->Data));
static_cast<Entity *>(pay_load->Data)->getComponent<cmpt::Transform>().update = true;
}
}
Scene::instance()->getRegistry().each([&](auto entity_id) {
if (Entity(entity_id) && Entity(entity_id).getComponent<cmpt::Hierarchy>().parent == entt::null)
{
draw_node(Entity(entity_id));
}
});
if (ImGui::IsMouseDown(ImGuiMouseButton_Left) && ImGui::IsWindowHovered())
{
Editor::instance()->select(Entity());
}
// Right-click on blank space
if (ImGui::BeginPopupContextWindow(0, 1, false))
{
if (ImGui::MenuItem("New Entity"))
{
Scene::instance()->createEntity("Untitled Entity");
}
ImGui::EndPopup();
}
ImGui::End();
}
} // namespace Ilum::panel
| 25.153846 | 217 | 0.681617 |
Chaf-Libraries
|
28d69e42f3993b3aef47de906eaa6b8a5745446d
| 153 |
cpp
|
C++
|
lib/source/mylib.cpp
|
Honeybunch/cpplibtemplate
|
23ea15343bb469198420f54eb3d87c4055468084
|
[
"MIT"
] | null | null | null |
lib/source/mylib.cpp
|
Honeybunch/cpplibtemplate
|
23ea15343bb469198420f54eb3d87c4055468084
|
[
"MIT"
] | null | null | null |
lib/source/mylib.cpp
|
Honeybunch/cpplibtemplate
|
23ea15343bb469198420f54eb3d87c4055468084
|
[
"MIT"
] | null | null | null |
#include "mylib.h"
int my_val = 0;
void init_my_lib() { my_val = 10; }
int get_my_lib_val() { return my_val; }
void shutdown_my_lib() { my_val = 0; }
| 17 | 39 | 0.660131 |
Honeybunch
|
28db93888191a41fd1097f3d2e69265cd481042d
| 11,791 |
cpp
|
C++
|
connectivity/FEATURE_BLE/source/generic/KVStoreSecurityDb.cpp
|
heuisam/mbed-os
|
eb32b25c8abb37f0aab505451074448e7e420517
|
[
"Apache-2.0"
] | 1 |
2021-02-09T21:27:17.000Z
|
2021-02-09T21:27:17.000Z
|
connectivity/FEATURE_BLE/source/generic/KVStoreSecurityDb.cpp
|
heuisam/mbed-os
|
eb32b25c8abb37f0aab505451074448e7e420517
|
[
"Apache-2.0"
] | 1 |
2021-12-13T14:33:09.000Z
|
2021-12-13T14:33:09.000Z
|
connectivity/FEATURE_BLE/source/generic/KVStoreSecurityDb.cpp
|
heuisam/mbed-os
|
eb32b25c8abb37f0aab505451074448e7e420517
|
[
"Apache-2.0"
] | null | null | null |
/* mbed Microcontroller Library
* Copyright (c) 2006-2020 ARM Limited
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if BLE_SECURITY_DATABASE_KVSTORE
#include "KVStoreSecurityDb.h"
namespace ble {
#if BLE_SECURITY_DATABASE_MAX_ENTRIES > 9
#error "BLE_SECURITY_DATABASE_MAX_ENTRIES must be only one digit long"
#endif
#define ENTRY_INVALID (0xFF)
constexpr uint8_t KVStoreSecurityDb::KVSTORESECURITYDB_VERSION;
constexpr size_t KVStoreSecurityDb::DB_PREFIX_SIZE;
constexpr size_t KVStoreSecurityDb::DB_KEY_SIZE;
constexpr size_t KVStoreSecurityDb::DB_ENTRY_KEY_SIZE;
constexpr size_t KVStoreSecurityDb::DB_FULL_KEY_SIZE;
constexpr char KVStoreSecurityDb::DB_PREFIX[DB_PREFIX_SIZE+1];
constexpr char KVStoreSecurityDb::DB_ENTRIES[DB_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_ENTRY_PEER_IDENTITY[DB_ENTRY_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_ENTRY_LOCAL_KEYS[DB_ENTRY_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_ENTRY_PEER_KEYS[DB_ENTRY_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_ENTRY_PEER_SIGNING[DB_ENTRY_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_LOCAL_IDENTITY[DB_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_LOCAL_CSRK[DB_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_LOCAL_SIGN_COUNT[DB_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_VERSION[DB_KEY_SIZE];
constexpr char KVStoreSecurityDb::DB_RESTORE[DB_KEY_SIZE];
typedef SecurityDb::entry_handle_t entry_handle_t;
KVStoreSecurityDb::KVStoreSecurityDb()
: SecurityDb() {
memset(_entries, 0, sizeof(_entries));
for (size_t i = 0; i < get_entry_count(); i++) {
_entries[i].index = ENTRY_INVALID;
}
}
KVStoreSecurityDb::~KVStoreSecurityDb()
{
}
bool KVStoreSecurityDb::open_db()
{
uint8_t version = 0;
char db_key[DB_FULL_KEY_SIZE];
create_key(db_key, DB_VERSION);
size_t size;
int ret = kv_get(db_key, &version, sizeof(uint8_t), &size);
/* kvstore problem (check if it's been successfully initialised before this call) */
if (ret != MBED_ERROR_ITEM_NOT_FOUND && (ret != MBED_SUCCESS || size != sizeof(uint8_t))) {
return false;
}
/* wipe the db if it's the wrong version or it doesn't exist */
if (version != KVSTORESECURITYDB_VERSION) {
return erase_db();
}
return true;
}
bool KVStoreSecurityDb::erase_db()
{
union zero_t {
int dummy; /* we need a dummy for initialisation */
uint8_t buffer[sizeof(SecurityEntryKeys_t)];
entry_t entries[BLE_SECURITY_DATABASE_MAX_ENTRIES];
} zero = { 0 };
memset(&zero, 0, sizeof(zero));
/* we zero the database and make sure we can fit all our keys */
db_write(zero.entries, DB_ENTRIES);
db_write((SecurityEntryIdentity_t*)zero.buffer, DB_LOCAL_IDENTITY);
db_write((csrk_t*)zero.buffer, DB_LOCAL_CSRK);
db_write((sign_count_t*)zero.buffer, DB_LOCAL_SIGN_COUNT);
bool reload = false;
db_write(&reload, DB_RESTORE);
for (int index = 0; index < BLE_SECURITY_DATABASE_MAX_ENTRIES; ++index) {
db_write_entry((SecurityEntryKeys_t*)zero.buffer, DB_ENTRY_LOCAL_KEYS, index);
db_write_entry((SecurityEntryIdentity_t*)zero.buffer, DB_ENTRY_PEER_IDENTITY, index);
db_write_entry((SecurityEntryKeys_t*)zero.buffer, DB_ENTRY_PEER_KEYS, index);
db_write_entry((SecurityEntrySigning_t*)zero.buffer, DB_ENTRY_PEER_SIGNING, index);
}
/* now we write the version and read it back to see if was written succesfully */
uint8_t version = KVSTORESECURITYDB_VERSION;
db_write(&version, DB_VERSION);
version = 0;
db_read(&version, DB_VERSION);
return (version == KVSTORESECURITYDB_VERSION);
}
SecurityDistributionFlags_t* KVStoreSecurityDb::get_distribution_flags(
entry_handle_t db_handle
)
{
return reinterpret_cast<SecurityDistributionFlags_t*>(db_handle);
}
/* local keys */
/* set */
void KVStoreSecurityDb::set_entry_local_ltk(
entry_handle_t db_handle,
const ltk_t <k
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
entry->flags.ltk_sent = true;
SecurityEntryKeys_t* current_entry = read_in_entry_local_keys(db_handle);
current_entry->ltk = ltk;
db_write_entry(current_entry, DB_ENTRY_LOCAL_KEYS, entry->index);
}
void KVStoreSecurityDb::set_entry_local_ediv_rand(
entry_handle_t db_handle,
const ediv_t &ediv,
const rand_t &rand
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
SecurityEntryKeys_t* current_entry = read_in_entry_local_keys(db_handle);
current_entry->ediv = ediv;
current_entry->rand = rand;
db_write_entry(current_entry, DB_ENTRY_LOCAL_KEYS, entry->index);
}
/* peer's keys */
/* set */
void KVStoreSecurityDb::set_entry_peer_ltk(
entry_handle_t db_handle,
const ltk_t <k
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
entry->flags.ltk_stored = true;
SecurityEntryKeys_t* current_entry = read_in_entry_peer_keys(db_handle);
current_entry->ltk = ltk;
db_write_entry(current_entry, DB_ENTRY_PEER_KEYS, entry->index);
}
void KVStoreSecurityDb::set_entry_peer_ediv_rand(
entry_handle_t db_handle,
const ediv_t &ediv,
const rand_t &rand
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
SecurityEntryKeys_t* current_entry = read_in_entry_peer_keys(db_handle);
current_entry->ediv = ediv;
current_entry->rand = rand;
db_write_entry(current_entry, DB_ENTRY_PEER_KEYS, entry->index);
}
void KVStoreSecurityDb::set_entry_peer_irk(
entry_handle_t db_handle,
const irk_t &irk
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
entry->flags.irk_stored = true;
SecurityEntryIdentity_t* current_entry = read_in_entry_peer_identity(db_handle);
current_entry->irk = irk;
db_write_entry(current_entry, DB_ENTRY_PEER_IDENTITY, entry->index);
}
void KVStoreSecurityDb::set_entry_peer_bdaddr(
entry_handle_t db_handle,
bool address_is_public,
const address_t &peer_address
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
SecurityEntryIdentity_t* current_entry = read_in_entry_peer_identity(db_handle);
current_entry->identity_address = peer_address;
current_entry->identity_address_is_public = address_is_public;
db_write_entry(current_entry, DB_ENTRY_PEER_IDENTITY, entry->index);
}
void KVStoreSecurityDb::set_entry_peer_csrk(
entry_handle_t db_handle,
const csrk_t &csrk
)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
entry->flags.csrk_stored = true;
SecurityEntrySigning_t* current_entry = read_in_entry_peer_signing(db_handle);
current_entry->csrk = csrk;
db_write_entry(current_entry, DB_ENTRY_PEER_SIGNING, entry->index);
}
void KVStoreSecurityDb::set_entry_peer_sign_counter(
entry_handle_t db_handle,
sign_count_t sign_counter
)
{
entry_t *entry = as_entry(db_handle);
if (entry) {
entry->peer_sign_counter = sign_counter;
}
}
void KVStoreSecurityDb::set_local_csrk(
const csrk_t &csrk
)
{
this->SecurityDb::set_local_csrk(csrk);
db_write(&_local_csrk, DB_LOCAL_CSRK);
}
void KVStoreSecurityDb::set_local_identity(
const irk_t &irk,
const address_t &identity_address,
bool public_address
)
{
this->SecurityDb::set_local_identity(irk, identity_address, public_address);
db_write(&_local_identity, DB_LOCAL_IDENTITY);
}
/* saving and loading from nvm */
void KVStoreSecurityDb::restore()
{
/* restore if requested */
bool restore_toggle = false;
db_read(&restore_toggle, DB_RESTORE);
if (!restore_toggle) {
erase_db();
return;
}
db_read(&_entries, DB_ENTRIES);
db_read(&_local_identity, DB_LOCAL_IDENTITY);
db_read(&_local_csrk, DB_LOCAL_CSRK);
db_read(&_local_sign_counter, DB_LOCAL_SIGN_COUNT);
}
void KVStoreSecurityDb::sync(entry_handle_t db_handle)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
/* all entries are stored in a single key so we store them all*/
db_write(&_entries, DB_ENTRIES);
db_write(&_local_identity, DB_LOCAL_IDENTITY);
db_write(&_local_csrk, DB_LOCAL_CSRK);
db_write(&_local_sign_counter, DB_LOCAL_SIGN_COUNT);
}
void KVStoreSecurityDb::set_restore(bool reload)
{
db_write(&reload, DB_RESTORE);
}
/* helper functions */
uint8_t KVStoreSecurityDb::get_entry_count()
{
return BLE_SECURITY_DATABASE_MAX_ENTRIES;
}
SecurityDistributionFlags_t* KVStoreSecurityDb::get_entry_handle_by_index(uint8_t index)
{
if (index < get_entry_count()) {
return &_entries[index].flags;
} else {
return nullptr;
}
}
void KVStoreSecurityDb::reset_entry(entry_handle_t db_handle)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return;
}
if (entry->index != ENTRY_INVALID) {
uint8_t zero_buffer[sizeof(SecurityEntryKeys_t)] = {0};
db_write_entry((SecurityEntryKeys_t*)zero_buffer, DB_ENTRY_LOCAL_KEYS, entry->index);
db_write_entry((SecurityEntryIdentity_t*)zero_buffer, DB_ENTRY_PEER_IDENTITY, entry->index);
db_write_entry((SecurityEntryKeys_t*)zero_buffer, DB_ENTRY_PEER_KEYS, entry->index);
db_write_entry((SecurityEntrySigning_t*)zero_buffer, DB_ENTRY_PEER_SIGNING, entry->index);
entry->index = ENTRY_INVALID;
}
entry->flags = SecurityDistributionFlags_t();
entry->peer_sign_counter = 0;
}
SecurityEntryIdentity_t* KVStoreSecurityDb::read_in_entry_peer_identity(entry_handle_t db_handle)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return nullptr;
}
SecurityEntryIdentity_t* identity = reinterpret_cast<SecurityEntryIdentity_t*>(_buffer);
db_read_entry(identity, DB_ENTRY_PEER_IDENTITY, entry->index);
return identity;
};
SecurityEntryKeys_t* KVStoreSecurityDb::read_in_entry_peer_keys(entry_handle_t db_handle)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return nullptr;
}
SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer);
db_read_entry(keys, DB_ENTRY_PEER_KEYS, entry->index);
return keys;
};
SecurityEntryKeys_t* KVStoreSecurityDb::read_in_entry_local_keys(entry_handle_t db_handle)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return nullptr;
}
SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer);
db_read_entry(keys, DB_ENTRY_LOCAL_KEYS, entry->index);
return keys;
};
SecurityEntrySigning_t* KVStoreSecurityDb::read_in_entry_peer_signing(entry_handle_t db_handle)
{
entry_t *entry = as_entry(db_handle);
if (!entry) {
return nullptr;
}
/* only read in the csrk */
csrk_t* csrk = reinterpret_cast<csrk_t*>(_buffer);
db_read_entry(csrk, DB_ENTRY_PEER_SIGNING, entry->index);
/* use the counter held in memory */
SecurityEntrySigning_t* signing = reinterpret_cast<SecurityEntrySigning_t*>(_buffer);
signing->counter = entry->peer_sign_counter;
return signing;
};
} /* namespace generic */
#endif // BLE_SECURITY_DATABASE_KVSTORE
| 27.549065 | 100 | 0.728691 |
heuisam
|
28df19f035b53278ef72263eb673ad9cdc3dd03a
| 9,143 |
hpp
|
C++
|
src/lib/clxx/info/platform_layer_info.hpp
|
ptomulik/clxx
|
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
|
[
"MIT"
] | 1 |
2015-08-12T13:11:35.000Z
|
2015-08-12T13:11:35.000Z
|
src/lib/clxx/info/platform_layer_info.hpp
|
ptomulik/clxx
|
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
|
[
"MIT"
] | 67 |
2015-01-03T10:11:13.000Z
|
2015-10-21T11:03:06.000Z
|
src/lib/clxx/info/platform_layer_info.hpp
|
ptomulik/clxx
|
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
|
[
"MIT"
] | null | null | null |
// @COPYRIGHT@
// Licensed under MIT license (LICENSE.txt)
// clxx/info/platform_layer_info.hpp
/** // doc: clxx/info/platform_layer_info.hpp {{{
* \file clxx/info/platform_layer_info.hpp
* \brief Defines \ref clxx::platform_layer_info "platform_layer_info" class
*/ // }}}
#ifndef CLXX_INFO_PLATFORM_LAYER_INFO_HPP_INCLUDED
#define CLXX_INFO_PLATFORM_LAYER_INFO_HPP_INCLUDED
#include <clxx/info/platform_info_ptrs.hpp>
#include <clxx/info/device_info_ptrs.hpp>
#include <boost/bimap/bimap.hpp>
#include <boost/bimap/vector_of.hpp>
#include <boost/bimap/set_of.hpp>
#include <vector>
namespace clxx {
/** // doc: class platform_layer_info {{{
* \ingroup clxx_info
* \brief Platform layer info
*
* This object gathers together a couple of \ref clxx::platform_info
* "platform_infos" and \ref clxx::device_info "device_infos" to represent
* a complete information about an OpenCL platform layer (including, for
* example, all locally available platforms together with their devices).
*
* It's possible to preserve the original layout of an OpenCL platform layer,
* and browse through either platforms or devices.
*/ // }}}
class platform_layer_info
{
template <class Archive>
friend void _serialize(Archive&, platform_layer_info&, const unsigned int);
public:
/** // doc: class_version {{{
* \brief Class version number
*
* This is used by the serialization machinery (see \ref clxx_s11n)
*/ // }}}
static constexpr unsigned int class_version = 0x000001;
private:
typedef boost::bimaps::vector_of<const_platform_info_ptr> Left_Set;
typedef boost::bimaps::set_of<const_device_info_ptr> Right_Set;
typedef boost::bimaps::bimap<Left_Set, Right_Set> bimap;
public:
/** // doc: platform_layer_info() {{{
* \brief Default constructor
*
* Initializes an empty platform_layer_info object.
*/ // }}}
platform_layer_info();
/** // doc: ~platform_layer_info() {{{
* \brief Destructor
*/ // }}}
virtual ~platform_layer_info();
/** // doc: clear() {{{
* \brief Clears the whole platform layer info
*
* This deletes all the platform and device infos contained in the object.
*/ // }}}
void clear();
/** // doc: platforms() {{{
* \brief Retrieve all the platform infos
* \returns A sequence of pointers to platform_info objects for the platform
* layer described by this object
*/ // }}}
platform_info_ptrs get_platforms();
/** // doc: platforms() {{{
* \brief Retrieve all the platform infos (const version)
* \returns A sequence of pointers to platform_info objects for the platform
* layer described by this object
*/ // }}}
const_platform_info_ptrs get_platforms() const;
/** // doc: get_platform() {{{
* \brief Get a platform info for given device
*
* The \em dev must belong to this platform layer, that is it must be stored
* in this #platform_layer_info object. In short, it must be one of the
* pointers returned by #get_devices().
*
* \param dev A pointer to device info for which the platform has to be returned
* \returns A pointer to the platform requested
*/ // }}}
platform_info_ptr get_platform(const_device_info_ptr dev);
/** // doc: get_platform() {{{
* \brief Get a platform info for given device (const version)
*
* The \em dev must belong to this platform layer, that is it must be stored
* in this #platform_layer_info object. In short, it must be one of the
* pointers returned by #get_devices() const.
*
* \param dev A pointer to device info for which the platform has to be returned
* \returns A pointer to the platform requested
*/ // }}}
const_platform_info_ptr get_platform(const_device_info_ptr dev) const;
/** // doc: get_devices() {{{
* \brief Get devices that belong to this platform layer
* \return A sequence of pointers to \ref clxx::device_info "device_infos"
* that belong to this #platform_layer_info.
*/ // }}}
device_info_ptrs get_devices();
/** // doc: get_devices() {{{
* \brief Get devices that belong to this platform layer
* \return A sequence of pointers to \ref clxx::device_info "device_infos"
* that belong to this #platform_layer_info.
*/ // }}}
const_device_info_ptrs get_devices() const;
/** // doc: get_devices(plat) {{{
* \brief Get devices that belong to a given platform
* \param plat Platform info for the platform in question.
* \return A sequence of pointers to \ref clxx::device_info "device_infos"
* that belong to the platform \em plat.
*/ // }}}
device_info_ptrs get_devices(const_platform_info_ptr plat);
/** // doc: get_devices(plat) {{{
* \brief Get devices that belong to a given platform (const version)
* \param plat Platform info for the platform in question.
* \return A sequence of pointers to \ref clxx::device_info "device_infos"
* that belong to the platform \em plat.
*/ // }}}
const_device_info_ptrs get_devices(const_platform_info_ptr plat) const;
/** // doc: push_back(dev) {{{// end namespace clxx
* \brief Add device (together with its platform) to #platform_layer_info
* \param dev Device to be included.
* \param plat Platform, to which the device \em dev belongs.
*/ // }}}
void push_back(device_info_ptr dev, platform_info_ptr plat);
/** // doc: remove(dev) {{{
* \brief Remove a platform from the #platform_layer_info
*
* Together with platform, all their devices get removed from
* #platform_layer_info.
*
* \param plat The platform to be removed
*/ // }}}
void remove(const_platform_info_ptr plat);
/** // doc: remove(dev) {{{
* \brief Remove a device from the #platform_layer_info
* \param dev Device to be removed
*
* When last device of some platform gets removed, the platform gets
* automatically removed from #platform_layer_info automatically.
*/ // }}}
void remove(const_device_info_ptr dev);
/** // doc: empty() {{{
* \brief Whether this object is empty
* \returns \c true if there is no device nor platform infos in the object
*/ // }}}
bool empty() const;
/** // doc: cmp(p) {{{
* \brief Compare this object with an other one
* \param other The other object to be compared with this one
*
* Two \ref clxx::platform_layer_info "platform_layer_infos" are equal if and
* only if
*
* - they're equal in size (have same number of platforms/devices), and
* - underlying platform layers they describe have same layout, and
* - corresponding platform infos and device infos on both sides are equal.
*
* \returns \c true if this object equals the other or \c false otherwise
*/ // }}}
bool cmp(platform_layer_info const& other) const;
/** // doc: indices() {{{
* \brief Indices that describe mapping of devices to their platforms in
* #platform_layer_info container
*
* The #platform_layer_info object contains a set of
* \ref clxx::platform_info "platform_info" objects and a set of
* \ref clxx::device_info "device_info" objects. Each device shall be related
* to one of the platforms contained in the #platform_layer_info. The
* sequence of \ref clxx::platform_info "platform_infos" can be retrieved
* with #get_platforms() whereas the sequence of \ref clxx::device_info
* "device_infos" may be obtained with #get_devices().
*
* The indices returned by #indices() establish the mapping between devices
* retrieved with #get_devices() and their platforms as obtained by
* #get_platforms(). The notation
*
* \code
* get_platforms()[indices()[i]]
* \endcode
*
* returns a platform info for platform of device <tt>devices()[i]</tt>.
*
* \returns A vector of integer indices that define the mapping
*/ // }}}
std::vector<int> indices() const;
private:
bimap _bimap;
};
/** \addtogroup clxx_info
* @{ */
/** // doc: operator==(l,r) {{{
* \brief Compare two \ref clxx::platform_layer_info "platform_layer_infos"
*
* See the \ref clxx::platform_layer_info::cmp() for definition of the
* \ref clxx::platform_layer_info "platform_layer_info's" equality.
*
* \param a Left hand side operand to the comparison
* \param b Right hand side operand to the comparison
* \returns \c true if two infos are same or \c false otherwise
*/ // }}}
inline bool operator==(platform_layer_info const& a, platform_layer_info const& b)
{
return a.cmp(b);
}
/** // doc: operator!=(l,r) {{{
* \brief Compare two \ref clxx::platform_layer_info "platform_layer_infos"
*
* See the \ref clxx::platform_layer_info::cmp() for definition of the
* \ref clxx::platform_layer_info "platform_layer_info's" equality.
*
* \param a Left hand side operand to the comparison
* \param b Right hand side operand to the comparison
* \returns \c false if two infos are same or \c true otherwise
*/ // }}}
inline bool operator!=(platform_layer_info const& a, platform_layer_info const& b)
{
return !a.cmp(b);
}
/** @} */
} // end namespace clxx
#endif /* CLXX_INFO_PLATFORM_LAYER_INFO_HPP_INCLUDED */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:
| 39.07265 | 82 | 0.694849 |
ptomulik
|
28df54ef5b9d2ce9d90f25518306dd1d85e428b0
| 3,337 |
cpp
|
C++
|
modules/core/utils.cpp
|
yjmm10/ModernOCR
|
a7070c9801ecccbbc5ad66618ca86c830480c573
|
[
"MIT"
] | null | null | null |
modules/core/utils.cpp
|
yjmm10/ModernOCR
|
a7070c9801ecccbbc5ad66618ca86c830480c573
|
[
"MIT"
] | null | null | null |
modules/core/utils.cpp
|
yjmm10/ModernOCR
|
a7070c9801ecccbbc5ad66618ca86c830480c573
|
[
"MIT"
] | null | null | null |
/*
* @Author: Petrichor
* @Date: 2022-03-11 11:40:37
* @LastEditTime: 2022-03-11 17:21:28
* @LastEditors: Petrichor
* @Description:
* @FilePath: \ModernOCR\modules\core\utils.cpp
* 版权声明
*/
#include "utils.h"
namespace ModernOCR {
namespace utils{
};
namespace image{
cv::Mat getRotateCropImage(const cv::Mat &src, std::vector<cv::Point> box) {
cv::Mat image;
src.copyTo(image);
std::vector<cv::Point> points = box;
int collectX[4] = {box[0].x, box[1].x, box[2].x, box[3].x};
int collectY[4] = {box[0].y, box[1].y, box[2].y, box[3].y};
int left = int(*std::min_element(collectX, collectX + 4));
int right = int(*std::max_element(collectX, collectX + 4));
int top = int(*std::min_element(collectY, collectY + 4));
int bottom = int(*std::max_element(collectY, collectY + 4));
cv::Mat imgCrop;
image(cv::Rect(left, top, right - left, bottom - top)).copyTo(imgCrop);
for (int i = 0; i < points.size(); i++) {
points[i].x -= left;
points[i].y -= top;
}
int imgCropWidth = int(sqrt(pow(points[0].x - points[1].x, 2) +
pow(points[0].y - points[1].y, 2)));
int imgCropHeight = int(sqrt(pow(points[0].x - points[3].x, 2) +
pow(points[0].y - points[3].y, 2)));
cv::Point2f ptsDst[4];
ptsDst[0] = cv::Point2f(0., 0.);
ptsDst[1] = cv::Point2f(imgCropWidth, 0.);
ptsDst[2] = cv::Point2f(imgCropWidth, imgCropHeight);
ptsDst[3] = cv::Point2f(0.f, imgCropHeight);
cv::Point2f ptsSrc[4];
ptsSrc[0] = cv::Point2f(points[0].x, points[0].y);
ptsSrc[1] = cv::Point2f(points[1].x, points[1].y);
ptsSrc[2] = cv::Point2f(points[2].x, points[2].y);
ptsSrc[3] = cv::Point2f(points[3].x, points[3].y);
cv::Mat M = cv::getPerspectiveTransform(ptsSrc, ptsDst);
cv::Mat partImg;
cv::warpPerspective(imgCrop, partImg, M,
cv::Size(imgCropWidth, imgCropHeight),
cv::BORDER_REPLICATE);
if (float(partImg.rows) >= float(partImg.cols) * 1.5) {
cv::Mat srcCopy = cv::Mat(partImg.rows, partImg.cols, partImg.depth());
cv::transpose(partImg, srcCopy);
cv::flip(srcCopy, srcCopy, 0);
return srcCopy;
} else {
return partImg;
}
}
std::vector<cv::Mat> getPartImages(cv::Mat &src, std::vector<types::BoxInfo> &textBoxes) {
std::vector<cv::Mat> partImages;
for (int i = 0; i < textBoxes.size(); ++i) {
cv::Mat partImg = getRotateCropImage(src, textBoxes[i].boxPoint);
partImages.emplace_back(partImg);
// //OutPut DebugImg
if (true) {
std::string debugImgFile = getDebugImgFilePath("", "hh", i, "-part-");
saveImg(partImg, debugImgFile.c_str());
}
}
return partImages;
}
};
namespace str{
};
};
| 34.760417 | 98 | 0.493857 |
yjmm10
|
28e37f5a3be244df1969dc1a5659a396b97c769d
| 1,344 |
hpp
|
C++
|
deps/boost/include/boost/geometry/algorithms/detail/normalize.hpp
|
kindlychung/mediasoup-sfu-cpp
|
f69d2f48f7edbf4f0c57244280a47bea985f39cf
|
[
"Apache-2.0"
] | 995 |
2018-06-22T10:39:18.000Z
|
2022-03-25T01:22:14.000Z
|
deps/boost/include/boost/geometry/algorithms/detail/normalize.hpp
|
kindlychung/mediasoup-sfu-cpp
|
f69d2f48f7edbf4f0c57244280a47bea985f39cf
|
[
"Apache-2.0"
] | 32 |
2018-06-23T14:19:37.000Z
|
2022-03-29T10:20:37.000Z
|
deps/boost/include/boost/geometry/algorithms/detail/normalize.hpp
|
kindlychung/mediasoup-sfu-cpp
|
f69d2f48f7edbf4f0c57244280a47bea985f39cf
|
[
"Apache-2.0"
] | 172 |
2018-06-22T11:12:00.000Z
|
2022-03-29T07:44:33.000Z
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2015-2018, Oracle and/or its affiliates.
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_NORMALIZE_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_NORMALIZE_HPP
// For backward compatibility
#include <boost/geometry/strategies/normalize.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail
{
template <typename GeometryIn, typename GeometryOut, typename Strategy>
inline void normalize(GeometryIn const& geometry_in, GeometryOut& geometry_out, Strategy const& )
{
Strategy::apply(geometry_in, geometry_out);
}
template <typename GeometryOut, typename GeometryIn, typename Strategy>
inline GeometryOut return_normalized(GeometryIn const& geometry_in, Strategy const& strategy)
{
GeometryOut geometry_out;
detail::normalize(geometry_in, geometry_out, strategy);
return geometry_out;
}
} // namespace detail
#endif // DOXYGEN_NO_DETAIL
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_NORMALIZE_HPP
| 27.428571 | 98 | 0.766369 |
kindlychung
|
28e42f59d897527a305c2e3a439854cb855e8a89
| 30,158 |
cpp
|
C++
|
other/bb_sudoku/bb_sudoku_solver.cpp
|
dobrichev/tdoku
|
cda2e52229656bd03db141e6405d50a2a80e2338
|
[
"BSD-2-Clause"
] | 100 |
2019-07-01T20:16:33.000Z
|
2022-03-27T10:36:48.000Z
|
other/bb_sudoku/bb_sudoku_solver.cpp
|
doc22940/tdoku
|
63d190a9090d9dc8e613e48e4770c635a5b7e3c3
|
[
"BSD-2-Clause"
] | 7 |
2019-12-18T09:07:58.000Z
|
2022-03-13T19:39:46.000Z
|
other/bb_sudoku/bb_sudoku_solver.cpp
|
doc22940/tdoku
|
63d190a9090d9dc8e613e48e4770c635a5b7e3c3
|
[
"BSD-2-Clause"
] | 14 |
2019-06-18T05:47:28.000Z
|
2022-03-05T08:58:05.000Z
|
/****************************************************************\
** BB_Sudoku Bit Based Sudoku Solver **
\****************************************************************/
/****************************************************************\
** (c) Copyright Brian Turner, 2008-2009. This file may be **
** freely used, modified, and copied for personal, **
** educational, or non-commercial purposes provided this **
** notice remains attached. **
\****************************************************************/
#include <cstdio>
#include <cstring>
#include "random.h"
#include "bb_sudoku_tables.h"
// moved here from driver program bb_sudoku.cpp
bool InitTables()
{ int i, v;
RND_Init();
for (i = 0; i < 512; i++)
{ B2V[i] = NSet[i] = 0;
for (v = i; v; NSet[i]++)
{ NSetX[i][NSet[i]] = v & -v;
v = v ^ NSetX[i][NSet[i]];
}
}
for (i = 1; i <= 9; i++)
B2V[1 << (i-1)] = i;
return true;
}
// G - Grid data structure
// This contains everything needed for backtracking.
// The larger this gets, the slower backtracking will be
// since the entire structure is copied.
struct Grid_Type
{ int CellsLeft; // Cells left to solve
unsigned int Grid[81]; // Possibilities left for each cell
unsigned int Grp[27]; // Values found in each group
} G[64];
// Solution Grid, which will contain the answer after the puzzle is solved
unsigned int SolGrid[81];
// Naked Singles FIFO stack - new singles found are stored here before
char SingleCnt = 0;
char SinglePos[128];
unsigned int SingleVal[128];
#define PushSingle(p, b) { SinglePos[SingleCnt] = p; SingleVal[SingleCnt] = b; SingleCnt++; Changed = 1; }
// Changed Flags
int Changed; // Flag to indicate Grid has changed
char ChangedGroup[27]; // Marks which groups have changed
char ChangedLC[27];
int SingleGroup[27];
#define MarkChanged(x) { ChangedGroup[C2Grp[x][0]] = ChangedGroup[C2Grp[x][1]] = ChangedGroup[C2Grp[x][2]] = Changed = 1; }
// Guess structure
char GuessPos[128];
int GuessVal[128];
int OneStepP[81], OneStepI;
// Key global variables used throughout the solving
long PuzzleCnt = 0; // Total puzzles tested
long SolvedCnt = 0; // Total puzzles solved
int PuzSolCnt; // Solutions for a single puzzle
int No_Sol; // Flag to indicate there is no solution possible
int PIdx; // Position Index, used for guessing and backtracking
// Debug stats
int SCnt = 0, HCnt = 0, GCnt = 0, LCCnt = 0, SSCnt = 0, FCnt = 0, OneCnt = 0, TwoCnt = 0;
long TSCnt = 0, THCnt = 0, TGCnt = 0, TLCCnt = 0, TSSCnt = 0, TFCnt = 0, TOneCnt = 0, TTwoCnt = 0;
int MaxDepth = 0, Givens = 0;
// forward procedure declarations
int DecodePuzzleString (int ret_puz, char* buffer);
inline void InitGrid ();
inline void ProcessInitSingles (void);
inline void ProcessSingles (void);
inline void FindHiddenSingles (void);
inline void FindLockedCandidates (void);
inline void FindSubsets (void);
inline void FindFishies (void);
void DoStep (int doing_2_step, int use_methods);
inline void MakeGuess (void);
/************\
** Solver *****************************************************\
** **
** Solver runs the sudoku solver. Input puzzle is in the **
** buffer array, and somewhat controlled by a number of **
** globals (see the globals at the top of the main program **
** for globals and meanings). **
** **
\****************************************************************/
int Solver (char num_search, unsigned int use_methods, char ret_puzzle, int initp, char* buffer)
{ int i, PuzSolCnt = 0;
if (!initp)
use_methods |= DecodePuzzleString(ret_puzzle, buffer); // Load the Grid from the buffer
// Loop through the puzzle solving routines until finished
while (Changed)
{ // If No Solution possible, jump straight to the backtrack routine
if (!No_Sol)
{ // Check if any Singles to be propogated
if (SingleCnt)
{ SCnt++;
if (SingleCnt > 2) // If multiple singles
ProcessInitSingles(); // process them all at once
if (SingleCnt) // otherwise
ProcessSingles(); // process them one at a time
if (!G[PIdx].CellsLeft)
{ if (!No_Sol)
{ if (!PuzSolCnt && ret_puzzle)
for (i = 0; i < 81; i++) buffer[i] = '0' + B2V[SolGrid[i]];
if (PuzSolCnt && (ret_puzzle == 2))
for (i = 0; i < 81; i++)
if (buffer[i] != ('0' + B2V[SolGrid[i]])) buffer[i] = '.';
PuzSolCnt++;
if ((PuzSolCnt > 1) && (num_search == 2)) break;
if (num_search == 1) break;
}
No_Sol = Changed = 1;
continue;
}
}
// If nothing has changed, apply the next solver
if (Changed)
{ HCnt++; FindHiddenSingles(); if (SingleCnt) continue;
if (use_methods & USE_LOCK_CAND)
{ LCCnt++; FindLockedCandidates(); if (Changed) continue; }
if (use_methods & USE_SUBSETS)
{ SSCnt++; FindSubsets(); if (Changed) continue; }
if (use_methods & USE_FISHIES)
{ FCnt++; FindFishies(); if (Changed) continue; }
if (use_methods & USE_1_STEP)
{ OneCnt++; DoStep(0, use_methods); if (Changed) continue; }
if (use_methods & USE_2_STEP)
{ TwoCnt++; DoStep(1, use_methods); if (Changed) continue; }
}
}
//If nothing new found, just make a guess
if (use_methods & USE_GUESSES)
{ GCnt++; MakeGuess(); }
if (No_Sol) break;
if (!initp && (MaxDepth < PIdx)) MaxDepth = PIdx;
if (PIdx > 62) { printf ("Max Depth exceeded, recompile for more depth.\n\n"); exit(0); }
}
if (No_Sol && !initp && (ret_puzzle == 2) && !(use_methods & USE_GUESSES))
for (i = 0; i < 81; i++)
buffer[i] = (G[0].Grid[i]) ? '.' : '0' + B2V[SolGrid[i]];
TSCnt += SCnt; // Update Stats
THCnt += HCnt;
TGCnt += GCnt;
TLCCnt += LCCnt;
TSSCnt += SSCnt;
TFCnt += FCnt;
TOneCnt += OneCnt;
TTwoCnt += TwoCnt;
return PuzSolCnt;
}
/************************\
** DecodePuzzleString *****************************************\
** **
** DecodePuzzleString sets up the initial grid (along with **
** InitGrid), and determine what variations are being used. **
** **
\****************************************************************/
int DecodePuzzleString (int ret_puz, char* buffer)
{ int p=0, i=0, KillIdx = 0, CompIdx = 0, g, ret_methods = 0, cpos = 0;
char b[500];
InitGrid();
p = 0; i = 2; b[0] = 'g'; b[1] = '=';
while (buffer[p] > 0) // remove spaces and commas
{ if (buffer[p] == '#') { cpos = p; break; }
if ((buffer[p] != ' ') && (buffer[p] != 9))
{ b[i] = buffer[p]; i++;} p++;
}
if (ret_puz)
{ if (cpos) memmove(&buffer[81], &buffer[p], strlen(buffer)-p+1);
else buffer[81] = 0; // end the buffer
}
b[i] = b[i+1] = b[i+2] = 0; p = 0;
if (b[3] == '=') p = 2;
while (b[p] > 0)
{ if (b[p+1] == '=')
switch (b[p])
{ case 'p' : // Puzzle size (needs to be defined first in used)
case 'P' :
printf ("Size variation are not supported in this version\n");
exit (0);
break;
case 'c' : // Comparison puzzle (Greater Than / Less Than)
case 'C' : //p = Decode_GT_LT(p, b);
//if (GT_LT[0][0] != GT_LT[0][1]) ret_methods |= GT_LT_PUZZLE;
//break;
case 'k' : // Killer Sudoku (Additive or Multiplicitive, and disjoint)
case 'K' :
//break;
case 'j' : // Jigsaw Sudoku (plus additional groupings and disjoint)
case 'J' :
//break;
case 'e' : // Even / Odd Sudoku
case 'E' :
//break;
case 's' : // Subset puzzles
case 'S' :
//break;
case 'a' : // Additional constraints (diagonals, etc)
case 'A' :
printf ("Variations are not supported in this version\n");
exit (0);
break;
case 'g' : // Givens (default puzzle)
case 'G' :
default : p += 2; g = i = 0;
while (g < 81)
{ if ((b[i+p] == ':') || (b[i+p] == ';') || (b[i+p] == '#') || (b[i+p] == 0)) break;
if ((b[i+p] == '/') || (b[i+p] == '\\'))
g = g + 9 - (g % 9) - 1;
if ((b[i+p] > '0') && (b[i+p] <= '9'))
PushSingle((char)(g), V2B[b[i+p] - '0']);
i++; g++;
}
Givens += SingleCnt;
break;
}
p += i;
}
buffer[81] = 10; buffer[82] = 0; // end the buffer
return ret_methods;
}
/**************\
** InitGrid ***************************************************\
** **
** InitGrid takes the text string stored in the buffer and **
** populates the solution grid. It assumes the text is **
** properly formatted. **
** **
\****************************************************************/
inline void InitGrid (void)
{ char i;
// Initialize some key variables
G[0].CellsLeft = 81;
PIdx = 0;
SingleCnt = 0;
Changed = 1;
No_Sol = 0;
OneStepI = 0;
Givens = 0;
SCnt = HCnt = GCnt = LCCnt = SSCnt = FCnt = OneCnt = TwoCnt = 0;
// Loop through the buffer and set the singles to be set
for (i = 0; i < 81; i++)
{ G[0].Grid[i] = 0x1FF;
SolGrid[i] = OneStepP[i] = 0;
}
// Clear the Groups Found values
for (i = 0; i < 27; i++)
G[0].Grp[i] = ChangedGroup[i] = ChangedLC[i] = SingleGroup[i] = 0;
}
/************************\
** ProcessInitSingles *****************************************\
** **
** ProcessInitSingles takes a naked single and marks each **
** cell in the 3 associated groups as not allowing that **
** number. It also marks the groups as changed so we know **
** to check for hidden singles in that group. **
** **
** This routines marks all the groups first, then marks the **
** cells for each changed groups. **
** **
\****************************************************************/
inline void ProcessInitSingles (void)
{ int i, t, g, t2, j;
unsigned int b;
while (SingleCnt > 2)
{ for (i = 0; i < SingleCnt; i++)
{ t = SinglePos[i]; // Get local copy of position
b = SingleVal[i]; // Get local copy of the value
if (G[PIdx].Grid[t] == 0) continue; // Check if we already processed this position
if (!(G[PIdx].Grid[t] & b)) // Check for error conditions
{ No_Sol = 1; SingleCnt = Changed = 0; return; }
SolGrid[SinglePos[i]] = SingleVal[i]; // Store the single in the solution grid
G[PIdx].CellsLeft--; // mark one less empty space
G[PIdx].Grid[t] = 0; // mark this position processed
for (g = 0; g < 3; g++) // loop through all 3 groups
{ if (G[PIdx].Grp[C2Grp[t][g]] & b)
{ No_Sol = 1; SingleCnt = Changed = 0; return; }
G[PIdx].Grp[C2Grp[t][g]] |= b; // mark the value as found in the group
SingleGroup[C2Grp[t][g]] = 1;
}
}
SingleCnt = 0;
for (i = 0; i < 27; i++)
if (SingleGroup[i])
{ SingleGroup[i] = 0;
for (j = 0; j < 9; j++)
{ t2 = Group[i][j]; // get temp copy of position
b = G[PIdx].Grp[i];
if (G[PIdx].Grid[t2] & b) // check if removing a possibility
{ G[PIdx].Grid[t2] = G[PIdx].Grid[t2] & ~b; // remove possibility
if (G[PIdx].Grid[t2] == 0) // check for error (no possibility)
{ No_Sol = 1; SingleCnt = 0; Changed = 0; return; }
if (B2V[G[PIdx].Grid[t2]]) // Check if a naked single is found
PushSingle(t2, G[PIdx].Grid[t2]);
MarkChanged(t2); // Mark groups as changed
}
}
}
}
}
/********************\
** ProcessSingles *********************************************\
** **
** ProcessSingles takes a naked single and marks each cell **
** in the 3 associated groups as not allowing that number. **
** It also marks the groups as changed so we know to check **
** for hidden singles in that group. **
** **
** This routines marks cells changed as each single is **
** processed. **
** **
\****************************************************************/
inline void ProcessSingles (void)
{ int i, t, g, t2;
unsigned int b;
for (i = 0; i < SingleCnt; i++)
{ t = SinglePos[i]; // Get local copy of position
b = SingleVal[i]; // Get local copy of the value
if (G[PIdx].Grid[t] == 0) continue; // Check if we already processed this position
if (!(G[PIdx].Grid[t] & b)) // Check for error conditions
{ No_Sol = 1; SingleCnt = Changed = 0; return; }
SolGrid[SinglePos[i]] = SingleVal[i]; // Store the single in the solution grid
G[PIdx].CellsLeft--; // mark one less empty space
G[PIdx].Grid[t] = 0; // mark this position processed
for (g = 0; g < 3; g++) // loop through all 3 groups
G[PIdx].Grp[C2Grp[t][g]] |= b; // mark the value as found in the group
for (g = 0; g < 20; g++) // loop through each cell in the groups
{ t2 = (int)In_Groups[t][g]; // get temp copy of position
if (G[PIdx].Grid[t2] & b) // check if removing a possibility
{ G[PIdx].Grid[t2] = G[PIdx].Grid[t2] ^ b; // remove possibility
if (G[PIdx].Grid[t2] == 0) // check for error (no possibility)
{ No_Sol = 1; SingleCnt = 0; Changed = 0; return; }
if (B2V[G[PIdx].Grid[t2]]) // Check if a naked single is found
PushSingle(t2, G[PIdx].Grid[t2]);
MarkChanged(t2); // Mark groups as changed
}
}
}
SingleCnt = 0; // Clear the single count
}
/***********************\
** FindHiddenSingles ******************************************\
** **
** FindHiddenSingles checks each grouping that has changed **
** to see if they contain any hidden singles. If one is **
** found, the routine adds it to the queue and exits. **
** **
\****************************************************************/
inline void FindHiddenSingles (void)
{ unsigned int t1, t2, t3, b, t;
int i, j;
for (i = 0; i < 27; i++)
if (ChangedGroup[i])
{ ChangedLC[i] = 1;
t1 = t2 = t3 = 0;
for (j = 0; j < 9; j++)
{ b = G[PIdx].Grid[Group[i][j]];
t2 = t2 | (t1 & b);
t1 = t1 | b;
}
if ((t1 | G[PIdx].Grp[i]) != 0x01FF)
{ No_Sol = 1; SingleCnt = 0; Changed = 0; return; }
t3 = t2 ^ t1;
if (t3)
{ for (j = 0; j < 9; j++)
if (t3 & G[PIdx].Grid[Group[i][j]])
{ t = t3 & G[PIdx].Grid[Group[i][j]];
if (!B2V[t]) { No_Sol = 1; SingleCnt = 0; Changed = 0; return; }
PushSingle((char)Group[i][j], t);
if (t3 == t) return;
t3 = t3 ^ t;
}
}
ChangedGroup[i] = 0;
}
Changed = 0;
}
/**************************\
** FindLockedCandidates ***************************************\
** **
** FindLockedCandidates will scan through the grid to find **
** any locked candidates. **
** **
\****************************************************************/
inline void FindLockedCandidates (void)
{ unsigned int Seg[9], b;
int i, j, k, x;
int s, s1, s2, gp;
for (i = 0; i < 18; i += 3)
if (ChangedLC[i] || ChangedLC[i+1] || ChangedLC[i+2])
{ ChangedLC[i] = ChangedLC[i+1] = ChangedLC[i+2] = 0;
Seg[0] = G[PIdx].Grid[Group[i ][0]] | G[PIdx].Grid[Group[i ][1]] | G[PIdx].Grid[Group[i ][2]];
Seg[1] = G[PIdx].Grid[Group[i ][3]] | G[PIdx].Grid[Group[i ][4]] | G[PIdx].Grid[Group[i ][5]];
Seg[2] = G[PIdx].Grid[Group[i ][6]] | G[PIdx].Grid[Group[i ][7]] | G[PIdx].Grid[Group[i ][8]];
Seg[3] = G[PIdx].Grid[Group[i+1][0]] | G[PIdx].Grid[Group[i+1][1]] | G[PIdx].Grid[Group[i+1][2]];
Seg[4] = G[PIdx].Grid[Group[i+1][3]] | G[PIdx].Grid[Group[i+1][4]] | G[PIdx].Grid[Group[i+1][5]];
Seg[5] = G[PIdx].Grid[Group[i+1][6]] | G[PIdx].Grid[Group[i+1][7]] | G[PIdx].Grid[Group[i+1][8]];
Seg[6] = G[PIdx].Grid[Group[i+2][0]] | G[PIdx].Grid[Group[i+2][1]] | G[PIdx].Grid[Group[i+2][2]];
Seg[7] = G[PIdx].Grid[Group[i+2][3]] | G[PIdx].Grid[Group[i+2][4]] | G[PIdx].Grid[Group[i+2][5]];
Seg[8] = G[PIdx].Grid[Group[i+2][6]] | G[PIdx].Grid[Group[i+2][7]] | G[PIdx].Grid[Group[i+2][8]];
for (j = 0; j < 9; j++)
{ b = Seg[j] & ((Seg[LC_Segment[j][0]] | Seg[LC_Segment[j][1]]) ^ (Seg[LC_Segment[j][2]] | Seg[LC_Segment[j][3]]));
if (b)
{
for (k = 0; k < 4; k++)
{ s = LC_Segment[j][k];
s1 = i+s/3; s2 = (s%3)*3;
for (x = 0; x < 3; x++)
{ gp = Group[s1][s2+x];
if (G[PIdx].Grid[gp] & b)
{ G[PIdx].Grid[gp] = G[PIdx].Grid[gp] & ~b;
MarkChanged(gp);
if (!(G[PIdx].Grid[gp]))
{ No_Sol = 1; SingleCnt = 0; Changed = 0; return; }
if (B2V[G[PIdx].Grid[gp]])
PushSingle(gp, G[PIdx].Grid[gp]);
}
}
}
return;
}
}
}
}
/*****************\
** FindSubsets ************************************************\
** **
** FindSubsets will find all disjoint subsets (Naked/Hidden **
** Pairs/Triples/Quads). While this reduces the solving **
** time on some puzzles, and reduces the numbers of guesses **
** by around 18%, the overhead increases solving time for **
** general puzzles by 100% (doubling the time). **
** **
\****************************************************************/
inline void FindSubsets (void)
{
int i, g, p, m, t[8], v[8];
for (g = 0; g < 27; g++)
{ if (Changed) break;
m = 7 - NSet[G[PIdx].Grp[g]];
if (m < 2) continue;
p = 1; t[1] = -1;
while(p > 0)
{ t[p]++;
if (t[p] == 9) { p--; continue; }
if (p == 1)
{ v[1] = G[PIdx].Grid[Group[g][t[p]]];
if ((!v[1]) || (NSet[v[1]] > m)) continue;
p++; t[2] = t[1]; continue;
}
if (!G[PIdx].Grid[Group[g][t[p]]]) continue;
v[p] = v[p-1] | G[PIdx].Grid[Group[g][t[p]]];
if (NSet[v[p]] > m) continue;
if (NSet[v[p]] == p)
{ for (i = 0; i < 9; i++)
if ((G[PIdx].Grid[Group[g][i]] & ~v[p]) && (G[PIdx].Grid[Group[g][i]] & v[p]))
{ G[PIdx].Grid[Group[g][i]] &= ~v[p];
if (B2V[G[PIdx].Grid[Group[g][i]]])
PushSingle(Group[g][i], G[PIdx].Grid[Group[g][i]]);
MarkChanged(Group[g][i]);
}
p = 1;
continue;
}
if (p < m) { p++; t[p] = t[p-1]; }
}
}
}
/*****************\
** FindFishies ************************************************\
** **
** FindFishies finds the row / column subsets, such as **
** X-Wing, Swordfish, and Jellyfish. **
** **
\****************************************************************/
inline void FindFishies (void)
{ int b, i, g, p, m, t[10], v[10], grid[10], x, y;
for (b = 1; b <= 9; b++)
{ if (Changed) break;
for (g = 0; g < 9; g++) grid[g] = 0;
for (g = 0; g < 9; g ++)
for (i = 0; i < 9; i++)
if (G[PIdx].Grid[(g*9)+i] & V2B[b]) grid[g] |= V2B[i+1];
for (g = m = 0; g < 9; g++)
if (grid[g]) m++;
if (m < 2) continue;
m--;
p = 1; t[1] = -1; t[0] = 0;
while(p > 0)
{ t[p]++;
if (t[p] == 9) { p--; continue; }
if (p == 1)
{ v[1] = grid[t[p]];
if ((!v[1]) || (NSet[v[1]] > m)) continue;
p++; t[2] = t[1]; continue;
}
if (!grid[t[p]]) continue;
v[p] = v[p-1] | grid[t[p]];
if (NSet[v[p]] > m) continue;
if (NSet[v[p]] == p)
{ for (i = 0; i < 9; i++)
if (grid[i] & ~v[p])
{ x = grid[i] & v[p];
while (x)
{ y = (i*9) + B2V[x & -x] - 1;
if (G[PIdx].Grid[y] & V2B[b])
{ G[PIdx].Grid[y] ^= V2B[b];
if (B2V[G[PIdx].Grid[y]])
PushSingle(y, G[PIdx].Grid[y]);
MarkChanged(y);
}
x ^= (x & -x);
}
}
p = 1;
continue;
}
if (p < m) { p++; t[p] = t[p-1]; }
}
}
}
/************\
** DoStep *****************************************************\
** **
** FindFishies finds the row / column subsets, such as **
** X-Wing, Swordfish, and Jellyfish. **
** **
\****************************************************************/
void DoStep (int doing_2_step, int use_methods)
{ static int LastPos = 0;
int i, j, x1, x2, x3, mt, testcell, tested[81], testpidx, new_method;
for (i = 0; i < 81; i++) tested[i] = 0;
testpidx = PIdx;
while (!Changed)
{ // Find next spot to check
testcell = mt = x3 = 99;
for (i = 0; i < 81; i++)
if ((NSet[G[PIdx].Grid[i]] <= mt) && (NSet[G[PIdx].Grid[i]] > 1) && !tested[i])
{ x1 = NSet[G[PIdx].Grp[C2Grp[i][0]]] + NSet[G[PIdx].Grp[C2Grp[i][1]]] + NSet[G[PIdx].Grp[C2Grp[i][2]]];
if ((NSet[G[PIdx].Grid[i]] < mt) ||
((NSet[G[PIdx].Grid[i]] == mt) && (x1 <= x2) && (OneStepP[i] <= x3)))
{ x2 = x1;
testcell = i;
mt = NSet[G[PIdx].Grid[i]];
x3 = OneStepP[i];
}
}
if (testcell == 99) return;
tested[testcell] = 1;
OneStepI++; OneStepP[testcell] = OneStepI;
for (j = 0; j < NSet[G[PIdx].Grid[testcell]]; j++)
{
G[PIdx+1+j] = G[PIdx];
PushSingle(testcell, NSetX[G[PIdx].Grid[testcell]][j]);
PIdx = testpidx + 1 + j;
if ((use_methods & USE_2_STEP) && doing_2_step)
new_method = (use_methods | USE_1_STEP) & ~(USE_GUESSES | USE_2_STEP);
else
new_method = use_methods & ~(USE_GUESSES | USE_1_STEP | USE_2_STEP);
Solver(1, new_method, 0, PIdx, NULL);
PIdx = testpidx;
if (No_Sol)
for (i = 0; i < 81; i++) G[PIdx+1+j].Grid[i] = 0;
else
for (i = 0; i < 81; i++)
if (!G[PIdx+1+j].Grid[i]) G[PIdx+1+j].Grid[i] = SolGrid[i];
No_Sol = 0; SingleCnt = 0;
}
for (j = 1; j < NSet[G[PIdx].Grid[testcell]]; j++)
for (i = 0; i < 81; i++) G[PIdx+1].Grid[i] |= G[PIdx+1+j].Grid[i];
for (i = 0; i < 27; i++) ChangedGroup[i] = 0; Changed = 0;
for (i = 0; i < 81; i++)
if (G[PIdx].Grid[i] && (G[PIdx].Grid[i] != G[PIdx+1].Grid[i]))
{ G[PIdx].Grid[i] = G[PIdx+1].Grid[i];
if (B2V[G[PIdx].Grid[i]]) PushSingle(i, G[PIdx].Grid[i]);
MarkChanged(i);
}
}
}
/***************\
** MakeGuess **************************************************\
** **
** MakeGuess handles the guessing and backtracking used **
** when solving puzzles. **
** **
\****************************************************************/
inline void MakeGuess (void)
{
static int LastPos = 0;
int i;
int x1, x2;
unsigned int v;
int Found = 0;
char mt;
Changed = 1;
SingleCnt = 0;
// Check to see where the next guess should be
if (No_Sol)
while (No_Sol)
{ if (PIdx == 0) return;
G[PIdx-1].Grid[GuessPos[PIdx]] ^= GuessVal[PIdx];
if (G[PIdx-1].Grid[GuessPos[PIdx]])
{ if (B2V[G[PIdx-1].Grid[GuessPos[PIdx]]])
PushSingle(GuessPos[PIdx], G[PIdx-1].Grid[GuessPos[PIdx]]);
No_Sol = 0;
MarkChanged(GuessPos[PIdx]);
PIdx--;
return;
}
}
// Populate the grid for the next guess
G[PIdx+1] = G[PIdx];
PIdx++;
// Find next spot to check
if (!Found)
{ mt = 99;
i = LastPos;
do
{ if ((NSet[G[PIdx].Grid[i]] < mt) && (NSet[G[PIdx].Grid[i]] > 1))
{ GuessPos[PIdx] = i;
mt = NSet[G[PIdx].Grid[i]];
if (mt == 2) break; // if 2, then its the best it can get
}
if (++i >= 81) i = 0;
} while (i != LastPos);
LastPos = i;
}
// Mark the next guess in the position
No_Sol = 1;
v = G[PIdx].Grid[GuessPos[PIdx]];
if (v)
{ v = v & -v;
GuessVal[PIdx] = v;
PushSingle(GuessPos[PIdx], v);
Changed = 1;
No_Sol = 0;
}
}
/****************\
** RatePuzzle *************************************************\
** **
** RatePuzzle converts the status counts into a rating for a **
** given puzzle. This should be called after the solver has **
** been called. **
** **
** ok, I never got a formula I liked. So, if someone wants **
** to play around with this and suggest something, please **
** go ahead. **
** **
** One of the problems is that the soling routines are so **
** generic. I treat X-Wings and Jellyfishes the sames way, **
** same for naked pairs and hidden quads. Makes coming up **
** with a rating difficult. **
** **
\****************************************************************/
int RatePuzzle (void)
{
// Values available to manipulate into a puzzle are
// SCnt, HCnt, GCnt, LCCnt, SSCnt, FCnt, OneCnt, TwoCnt, GCnt
return 0;
}
/***************\
** CatPuzzle **************************************************\
** **
** CatPuzzle returns a difficulty category, rather than a **
** complete ratings. This is based entirely on the most **
** difficult solving technique used. **
** **
** Categories are: **
** - Invalid : No Solution, or Multiple Solutions **
** - Easy : Naked / Hidden Single, Locked Candidate **
** - Medium : Disjoint Subsets / Fishies **
** - Hard : 1 Step Commonality **
** - Expert : 2 Step Commonality **
** - Insane : so far, none exist **
** **
\****************************************************************/
int CatPuzzle (char *buf)
{
if (Solver(2, 0x01, 0, 0, buf) != 1) return 0; // Invalid (No Solution, or mulitples)
if (Solver(1, 0x3E, 0, 0, buf) == 0) return 5; // Insane (none exist, that I know of)
if (TwoCnt) return 4; // Expert (2 Step Commonality)
if (OneCnt) return 3; // Hard (1 Step Commonality)
if (FCnt || SCnt) return 2; // Medium (Disjoint Subsets / Fishies)
return 1; // Easy (Naked/Hidden Single / Locked Candidate)
}
| 38.320203 | 124 | 0.418463 |
dobrichev
|
28e45dbdbc5bf09ce27c548339c59ceff1d433bc
| 1,138 |
hpp
|
C++
|
core/src/jni/jni/Error.hpp
|
RomanWlm/lib-ledger-core
|
8c068fccb074c516096abb818a4e20786e02318b
|
[
"MIT"
] | 92 |
2016-11-13T01:28:34.000Z
|
2022-03-25T01:11:37.000Z
|
core/src/jni/jni/Error.hpp
|
RomanWlm/lib-ledger-core
|
8c068fccb074c516096abb818a4e20786e02318b
|
[
"MIT"
] | 242 |
2016-11-28T11:13:09.000Z
|
2022-03-04T13:02:53.000Z
|
core/src/jni/jni/Error.hpp
|
RomanWlm/lib-ledger-core
|
8c068fccb074c516096abb818a4e20786e02318b
|
[
"MIT"
] | 91 |
2017-06-20T10:35:28.000Z
|
2022-03-09T14:15:40.000Z
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from errors.djinni
#ifndef DJINNI_GENERATED_ERROR_HPP_JNI_
#define DJINNI_GENERATED_ERROR_HPP_JNI_
#include "../../api/Error.hpp"
#include "djinni_support.hpp"
namespace djinni_generated {
class Error final {
public:
using CppType = ::ledger::core::api::Error;
using JniType = jobject;
using Boxed = Error;
~Error();
static CppType toCpp(JNIEnv* jniEnv, JniType j);
static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c);
private:
Error();
friend ::djinni::JniClass<Error>;
const ::djinni::GlobalRef<jclass> clazz { ::djinni::jniFindClass("co/ledger/core/Error") };
const jmethodID jconstructor { ::djinni::jniGetMethodID(clazz.get(), "<init>", "(Lco/ledger/core/ErrorCode;Ljava/lang/String;)V") };
const jfieldID field_code { ::djinni::jniGetFieldID(clazz.get(), "code", "Lco/ledger/core/ErrorCode;") };
const jfieldID field_message { ::djinni::jniGetFieldID(clazz.get(), "message", "Ljava/lang/String;") };
};
} // namespace djinni_generated
#endif //DJINNI_GENERATED_ERROR_HPP_JNI_
| 31.611111 | 136 | 0.710018 |
RomanWlm
|
28e4a5dff6a2acf6e2e0efcd8f539a46a56c41dd
| 21,403 |
hpp
|
C++
|
include/slib/core/rc.hpp
|
syntheticgio/fda-hive
|
5e645c6a5b76b5a437635631819a1c934c7fd7fc
|
[
"Unlicense",
"MIT"
] | null | null | null |
include/slib/core/rc.hpp
|
syntheticgio/fda-hive
|
5e645c6a5b76b5a437635631819a1c934c7fd7fc
|
[
"Unlicense",
"MIT"
] | null | null | null |
include/slib/core/rc.hpp
|
syntheticgio/fda-hive
|
5e645c6a5b76b5a437635631819a1c934c7fd7fc
|
[
"Unlicense",
"MIT"
] | null | null | null |
/*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* 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.
*/
#pragma once
#ifndef sLib_core_rc_hpp
#define sLib_core_rc_hpp
#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <slib/core/def.hpp>
// macros allowing us to define enum names and corresponding description strings in one place
#define SLIB_RC_OPERATION_ENTRIES \
SLIB_RC_ENTRY_WITH_VAL(eOperationNone, 0, 0), \
SLIB_RC_ENTRY(eAccessing, "accessing"), \
SLIB_RC_ENTRY(eAllocating, "allocating"), \
SLIB_RC_ENTRY(eAppending, "appending"), \
SLIB_RC_ENTRY(eArithmetic, "performing arithmetic"), \
SLIB_RC_ENTRY(eAttaching, "attaching"), \
SLIB_RC_ENTRY(eAuthenticating, "authenticating"), \
SLIB_RC_ENTRY(eAuthorizing, "authorizing"), \
SLIB_RC_ENTRY(eBackingUp, "backing up"), \
SLIB_RC_ENTRY(eBalancing, "balancing"), \
SLIB_RC_ENTRY(eCaching, "caching"), \
SLIB_RC_ENTRY(eCalling, "calling"), \
SLIB_RC_ENTRY(eChecking, "checking"), \
SLIB_RC_ENTRY(eCasting, "type-casting"), \
SLIB_RC_ENTRY(eClassifying, "classifying"), \
SLIB_RC_ENTRY(eCleaningUp, "cleaning up"), \
SLIB_RC_ENTRY(eClearing, "clearing"), \
SLIB_RC_ENTRY(eClosing, "closing"), \
SLIB_RC_ENTRY(eCommitting, "committing"), \
SLIB_RC_ENTRY(eComparing, "comparing"), \
SLIB_RC_ENTRY(eCompiling, "compiling"), \
SLIB_RC_ENTRY(eCompressing, "compressing"), \
SLIB_RC_ENTRY(eConcatenating, "concatenating"), \
SLIB_RC_ENTRY(eConnecting, "connecting"), \
SLIB_RC_ENTRY(eConstructing, "constructing"), \
SLIB_RC_ENTRY(eConverting, "converting"), \
SLIB_RC_ENTRY(eCopying, "copying"), \
SLIB_RC_ENTRY(eCreating, "creating"), \
SLIB_RC_ENTRY(eCutting, "cutting"), \
SLIB_RC_ENTRY(eDeallocating, "deallocating"), \
SLIB_RC_ENTRY(eDecrypting, "decrypting"), \
SLIB_RC_ENTRY(eDeleting, "deleting"), \
SLIB_RC_ENTRY(eDestroying, "destroying"), \
SLIB_RC_ENTRY(eDetaching, "detaching"), \
SLIB_RC_ENTRY(eDisconnecting, "disconnecting"), \
SLIB_RC_ENTRY(eEncrypting, "encrypting"), \
SLIB_RC_ENTRY(eEscaping, "escaping"), \
SLIB_RC_ENTRY(eEvaluating, "evaluating"), \
SLIB_RC_ENTRY(eExecuting, "executing"), \
SLIB_RC_ENTRY(eExpanding, "expanding"), \
SLIB_RC_ENTRY(eFinding, "finding"), \
SLIB_RC_ENTRY(eFlushing, "flushing"), \
SLIB_RC_ENTRY(eFormatting, "formatting"), \
SLIB_RC_ENTRY(eGrabbing, "grabbing"), \
SLIB_RC_ENTRY(eHashing, "hashing"), \
SLIB_RC_ENTRY(eIdentifying, "identifying"), \
SLIB_RC_ENTRY(eIndexing, "indexing"), \
SLIB_RC_ENTRY(eInitializing, "initializing"), \
SLIB_RC_ENTRY(eInserting, "inserting"), \
SLIB_RC_ENTRY(eInverting, "inverting"), \
SLIB_RC_ENTRY(eJoining, "joining"), \
SLIB_RC_ENTRY(eLaunching, "launching"), \
SLIB_RC_ENTRY(eLinking, "linking"), \
SLIB_RC_ENTRY(eLoading, "loading"), \
SLIB_RC_ENTRY(eLocking, "locking"), \
SLIB_RC_ENTRY(eLogging, "logging"), \
SLIB_RC_ENTRY(eMapping, "mapping"), \
SLIB_RC_ENTRY(eMoving, "moving"), \
SLIB_RC_ENTRY(eOpening, "opening"), \
SLIB_RC_ENTRY(ePacking, "packing"), \
SLIB_RC_ENTRY(eParsing, "parsing"), \
SLIB_RC_ENTRY(ePausing, "pausing"), \
SLIB_RC_ENTRY(ePopping, "popping"), \
SLIB_RC_ENTRY(ePositioning, "positioning"), \
SLIB_RC_ENTRY(ePreparing, "preparing"), \
SLIB_RC_ENTRY(ePrepending, "prepending"), \
SLIB_RC_ENTRY(ePrinting, "printing"), \
SLIB_RC_ENTRY(eProcessing, "processing"), \
SLIB_RC_ENTRY(ePurging, "purging"), \
SLIB_RC_ENTRY(ePushing, "pushing"), \
SLIB_RC_ENTRY(eReading, "reading"), \
SLIB_RC_ENTRY(eReceiving, "receiving"), \
SLIB_RC_ENTRY(eRegistering, "registering"), \
SLIB_RC_ENTRY(eReleasing, "releasing"), \
SLIB_RC_ENTRY(eRenaming, "renaming"), \
SLIB_RC_ENTRY(eRemoving, "removing"), \
SLIB_RC_ENTRY(eResetting, "resetting"), \
SLIB_RC_ENTRY(eResizing, "resizing"), \
SLIB_RC_ENTRY(eResolving, "resolving"), \
SLIB_RC_ENTRY(eRestarting, "restarting"), \
SLIB_RC_ENTRY(eResuming, "resuming"), \
SLIB_RC_ENTRY(eRetrying, "retrying"), \
SLIB_RC_ENTRY(eReversing, "reversing"), \
SLIB_RC_ENTRY(eReverting, "reverting"), \
SLIB_RC_ENTRY(eRunning, "running"), \
SLIB_RC_ENTRY(eSaving, "saving"), \
SLIB_RC_ENTRY(eScanning, "scanning"), \
SLIB_RC_ENTRY(eSearching, "searching"), \
SLIB_RC_ENTRY(eSelecting, "selecting"), \
SLIB_RC_ENTRY(eSending, "sending"), \
SLIB_RC_ENTRY(eSerializing, "serializing"), \
SLIB_RC_ENTRY(eSetting, "setting"), \
SLIB_RC_ENTRY(eShrinking, "shrinking"), \
SLIB_RC_ENTRY(eSignaling, "signaling"), \
SLIB_RC_ENTRY(eSleeping, "sleeping"), \
SLIB_RC_ENTRY(eSorting, "sorting"), \
SLIB_RC_ENTRY(eSplitting, "splitting"), \
SLIB_RC_ENTRY(eStarting, "starting"), \
SLIB_RC_ENTRY(eStopping, "stopping"), \
SLIB_RC_ENTRY(eTerminating, "terminating"), \
SLIB_RC_ENTRY(eTesting, "testing"), \
SLIB_RC_ENTRY(eTokenizing, "tokenizing"), \
SLIB_RC_ENTRY(eUncompressing, "uncompressing"), \
SLIB_RC_ENTRY(eUnescaping, "unescaping"), \
SLIB_RC_ENTRY(eUnlinking, "unlinking"), \
SLIB_RC_ENTRY(eUnlocking, "unlocking"), \
SLIB_RC_ENTRY(eUnpacking, "unpacking"), \
SLIB_RC_ENTRY(eUnregistering, "unregistering"), \
SLIB_RC_ENTRY(eUpdating, "updating"), \
SLIB_RC_ENTRY(eValidating, "validating"), \
SLIB_RC_ENTRY(eVisiting, "visiting"), \
SLIB_RC_ENTRY(eWaiting, "waiting"), \
SLIB_RC_ENTRY(eWriting, "writing"), \
SLIB_RC_ENTRY(eDownload, "downloading"), \
/* Insert new entries after existing ones and before this line */ \
SLIB_RC_ENTRY_WITH_VAL(eOperationOther, 255, "some operation on")
#define SLIB_RC_ENTITY_ENTRIES \
SLIB_RC_ENTRY_WITH_VAL(eEntityNone, 0, 0), \
SLIB_RC_ENTRY(eAddress, "address"), \
SLIB_RC_ENTRY(eAlgorithm, "algorithm"), \
SLIB_RC_ENTRY(eAnnotation, "annotation"), \
SLIB_RC_ENTRY(eArchive, "archive"), \
SLIB_RC_ENTRY(eArray, "array"), \
SLIB_RC_ENTRY(eBlob, "blob"), \
SLIB_RC_ENTRY(eBranch, "branch"), \
SLIB_RC_ENTRY(eBuffer, "buffer"), \
SLIB_RC_ENTRY(eByteOrder, "byte order"), \
SLIB_RC_ENTRY(eCallback, "callback"), \
SLIB_RC_ENTRY(eCategory, "category"), \
SLIB_RC_ENTRY(eCell, "cell"), \
SLIB_RC_ENTRY(eChain, "chain"), \
SLIB_RC_ENTRY(eCharacter, "character"), \
SLIB_RC_ENTRY(eChecksum, "checksum"), \
SLIB_RC_ENTRY(eChild, "child"), \
SLIB_RC_ENTRY(eClass, "class"), \
SLIB_RC_ENTRY(eCode, "code"), \
SLIB_RC_ENTRY(eColumn, "column"), \
SLIB_RC_ENTRY(eCommand, "command"), \
SLIB_RC_ENTRY(eCommandLine, "command line"), \
SLIB_RC_ENTRY(eConfig, "configuration"), \
SLIB_RC_ENTRY(eConnection, "connection"), \
SLIB_RC_ENTRY(eConstraint, "constraint"), \
SLIB_RC_ENTRY(eContext, "context"), \
SLIB_RC_ENTRY(eCookie, "cookie"), \
SLIB_RC_ENTRY(eCount, "count"), \
SLIB_RC_ENTRY(eCSV, "CSV data"), \
SLIB_RC_ENTRY(eCursor, "cursor"), \
SLIB_RC_ENTRY(eData, "data"), \
SLIB_RC_ENTRY(eDatabase, "database"), \
SLIB_RC_ENTRY(eDescriptor, "descriptor"), \
SLIB_RC_ENTRY(eDestination, "destination"), \
SLIB_RC_ENTRY(eDictionary, "dictionary"), \
SLIB_RC_ENTRY(eDirectory, "directory"), \
SLIB_RC_ENTRY(eDiskSpace, "disk space"), \
SLIB_RC_ENTRY(eDistance, "distance"), \
SLIB_RC_ENTRY(eDocument, "document"), \
SLIB_RC_ENTRY(eDomain, "domain"), \
SLIB_RC_ENTRY(eElement, "element"), \
SLIB_RC_ENTRY(eEmail, "email"), \
SLIB_RC_ENTRY(eEncryption, "encryption"), \
SLIB_RC_ENTRY(eEnd, "end"), \
SLIB_RC_ENTRY(eEngine, "engine"), \
SLIB_RC_ENTRY(eEnvironment, "environment"), \
SLIB_RC_ENTRY(eExpression, "expression"), \
SLIB_RC_ENTRY(eExtension, "extension"), \
SLIB_RC_ENTRY(eFactory, "factory"), \
SLIB_RC_ENTRY(eFASTA, "FASTA data"), \
SLIB_RC_ENTRY(eField, "field"), \
SLIB_RC_ENTRY(eFile, "file"), \
SLIB_RC_ENTRY(eFileSystem, "filesystem"), \
SLIB_RC_ENTRY(eFlag, "flag"), \
SLIB_RC_ENTRY(eForm, "form"), \
SLIB_RC_ENTRY(eFormat, "format"), \
SLIB_RC_ENTRY(eFormula, "formula"), \
SLIB_RC_ENTRY(eFrame, "frame"), \
SLIB_RC_ENTRY(eFrequency, "frequency"), \
SLIB_RC_ENTRY(eFunction, "function"), \
SLIB_RC_ENTRY(eGroup, "group"), \
SLIB_RC_ENTRY(eHandle, "handle"), \
SLIB_RC_ENTRY(eHash, "hash"), \
SLIB_RC_ENTRY(eHeader, "header"), \
SLIB_RC_ENTRY(eHeap, "heap"), \
SLIB_RC_ENTRY(eHierarchy, "hierarchy"), \
SLIB_RC_ENTRY(eHost, "host"), \
SLIB_RC_ENTRY(eID, "ID"), \
SLIB_RC_ENTRY(eImage, "image"), \
SLIB_RC_ENTRY(eIndex, "index"), \
SLIB_RC_ENTRY(eInput, "input"), \
SLIB_RC_ENTRY(eInterface, "interface"), \
SLIB_RC_ENTRY(eIO, "I/O"), \
SLIB_RC_ENTRY(eIon, "Ion"), \
SLIB_RC_ENTRY(eItem, "item"), \
SLIB_RC_ENTRY(eIterator, "iterator"), \
SLIB_RC_ENTRY(eJob, "job"), \
SLIB_RC_ENTRY(eJSON, "JSON data"), \
SLIB_RC_ENTRY(eKey, "key"), \
SLIB_RC_ENTRY(eLength, "length"), \
SLIB_RC_ENTRY(eLetter, "letter"), \
SLIB_RC_ENTRY(eLevel, "level"), \
SLIB_RC_ENTRY(eLibrary, "library"), \
SLIB_RC_ENTRY(eLimit, "limit"), \
SLIB_RC_ENTRY(eLine, "line"), \
SLIB_RC_ENTRY(eList, "list"), \
SLIB_RC_ENTRY(eLocation, "location"), \
SLIB_RC_ENTRY(eLock, "lock"), \
SLIB_RC_ENTRY(eLog, "log"), \
SLIB_RC_ENTRY(eMap, "map"), \
SLIB_RC_ENTRY(eMatrix, "matrix"), \
SLIB_RC_ENTRY(eMemMap, "memmap"), \
SLIB_RC_ENTRY(eMemory, "memory"), \
SLIB_RC_ENTRY(eMessage, "message"), \
SLIB_RC_ENTRY(eMode, "mode"), \
SLIB_RC_ENTRY(eModule, "module"), \
SLIB_RC_ENTRY(eName, "name"), \
SLIB_RC_ENTRY(eNode, "node"), \
SLIB_RC_ENTRY(eNumber, "number"), \
SLIB_RC_ENTRY(eObject, "object"), \
SLIB_RC_ENTRY(eOffset, "offset"), \
SLIB_RC_ENTRY(eOperation, "operation"), \
SLIB_RC_ENTRY(eOrder, "order"), \
SLIB_RC_ENTRY(eOutput, "output"), \
SLIB_RC_ENTRY(eOwner, "owner"), \
SLIB_RC_ENTRY(eParameter, "parameter"), \
SLIB_RC_ENTRY(eParent, "parent"), \
SLIB_RC_ENTRY(eParser, "parser"), \
SLIB_RC_ENTRY(ePassword, "password"), \
SLIB_RC_ENTRY(ePath, "path"), \
SLIB_RC_ENTRY(ePattern, "pattern"), \
SLIB_RC_ENTRY(ePermission, "permission"), \
SLIB_RC_ENTRY(ePipe, "pipe"), \
SLIB_RC_ENTRY(ePlugin, "plugin"), \
SLIB_RC_ENTRY(ePointer, "pointer"), \
SLIB_RC_ENTRY(ePool, "pool"), \
SLIB_RC_ENTRY(ePosition, "position"), \
SLIB_RC_ENTRY(eProcess, "process"), \
SLIB_RC_ENTRY(eProperty, "property"), \
SLIB_RC_ENTRY(eProtocol, "protocol"), \
SLIB_RC_ENTRY(eQuery, "query"), \
SLIB_RC_ENTRY(eQueue, "queue"), \
SLIB_RC_ENTRY(eRange, "range"), \
SLIB_RC_ENTRY(eReference, "reference"), \
SLIB_RC_ENTRY(eReferenceCount, "reference count"), \
SLIB_RC_ENTRY(eRequest, "request"), \
SLIB_RC_ENTRY(eResource, "resource"), \
SLIB_RC_ENTRY(eResponse, "response"), \
SLIB_RC_ENTRY(eResult, "result"), \
SLIB_RC_ENTRY(eRow, "row"), \
SLIB_RC_ENTRY(eScope, "scope"), \
SLIB_RC_ENTRY(eSeed, "seed"), \
SLIB_RC_ENTRY(eSegment, "segment"), \
SLIB_RC_ENTRY(eSelection, "selection"), \
SLIB_RC_ENTRY(eSeparator, "separator"), \
SLIB_RC_ENTRY(eSequence, "sequence"), \
SLIB_RC_ENTRY(eService, "service"), \
SLIB_RC_ENTRY(eSession, "session"), \
SLIB_RC_ENTRY(eSignal, "signal"), \
SLIB_RC_ENTRY(eSize, "size"), \
SLIB_RC_ENTRY(eSocket, "socket"), \
SLIB_RC_ENTRY(eSource, "source"), \
SLIB_RC_ENTRY(eStack, "stack"), \
SLIB_RC_ENTRY(eStart, "start"), \
SLIB_RC_ENTRY(eString, "string"), \
SLIB_RC_ENTRY(eStructure, "structure"), \
SLIB_RC_ENTRY(eSubject, "subject"), \
SLIB_RC_ENTRY(eSymbol, "symbol"), \
SLIB_RC_ENTRY(eSymLink, "symlink"), \
SLIB_RC_ENTRY(eTable, "table"), \
SLIB_RC_ENTRY(eTarget, "target"), \
SLIB_RC_ENTRY(eTemplate, "template"), \
SLIB_RC_ENTRY(eText, "text"), \
SLIB_RC_ENTRY(eThread, "thread"), \
SLIB_RC_ENTRY(eTimeout, "timeout"), \
SLIB_RC_ENTRY(eTimeStamp, "time stamp"), \
SLIB_RC_ENTRY(eToken, "token"), \
SLIB_RC_ENTRY(eTree, "tree"), \
SLIB_RC_ENTRY(eType, "type"), \
SLIB_RC_ENTRY(eURL, "URL"), \
SLIB_RC_ENTRY(eUser, "user"), \
SLIB_RC_ENTRY(eValue, "value"), \
SLIB_RC_ENTRY(eVariable, "variable"), \
SLIB_RC_ENTRY(eVersion, "version"), \
SLIB_RC_ENTRY(eXML, "XML data"), \
SLIB_RC_ENTRY(eNetwork, "network"), \
SLIB_RC_ENTRY(eCertificate, "certificate"), \
SLIB_RC_ENTRY(eServer, "server"), \
SLIB_RC_ENTRY(eAuthentication, "authentication"), \
/* Insert new entries after existing ones and before this line */ \
SLIB_RC_ENTRY_WITH_VAL(eEntityOther, 255, "something")
#define SLIB_RC_STATE_ENTRIES \
SLIB_RC_ENTRY_WITH_VAL(eStateOK, 0, 0), \
SLIB_RC_ENTRY(eAmbiguous, "ambiguous"), \
SLIB_RC_ENTRY(eBlocked, "blocked"), \
SLIB_RC_ENTRY(eBusy, "busy"), \
SLIB_RC_ENTRY(eCanceled, "canceled"), \
SLIB_RC_ENTRY(eChanged, "changed"), \
SLIB_RC_ENTRY(eCircularRef, "has a circular reference"), \
SLIB_RC_ENTRY(eClosed, "closed"), \
SLIB_RC_ENTRY(eCorrupt, "corrupt"), \
SLIB_RC_ENTRY(eDeadlocked, "deadlocked"), \
SLIB_RC_ENTRY(eDestroyed, "destroyed"), \
SLIB_RC_ENTRY(eDetached, "detached"), \
SLIB_RC_ENTRY(eDisabled, "disabled"), \
SLIB_RC_ENTRY(eDown, "down"), \
SLIB_RC_ENTRY(eDuplicate, "duplicate"), \
SLIB_RC_ENTRY(eEnabled, "enabled"), \
SLIB_RC_ENTRY(eEncrypted, "encrypted"), \
SLIB_RC_ENTRY(eEmpty, "empty"), \
SLIB_RC_ENTRY(eEqual, "equal"), \
SLIB_RC_ENTRY(eExcessive, "excessive"), \
SLIB_RC_ENTRY(eExhausted, "exhausted"), \
SLIB_RC_ENTRY(eExists, "already exists"), \
SLIB_RC_ENTRY(eExpired, "expired"), \
SLIB_RC_ENTRY(eFailed, "failed"), \
SLIB_RC_ENTRY(eIgnored, "ignored"), \
SLIB_RC_ENTRY(eIncompatible, "incompatible"), \
SLIB_RC_ENTRY(eIncomplete, "incomplete"), \
SLIB_RC_ENTRY(eInconsistent, "inconsistent"), \
SLIB_RC_ENTRY(eIncorrect, "incorrect"), \
SLIB_RC_ENTRY(eInsecure, "potentially insecure"), \
SLIB_RC_ENTRY(eInsufficient, "insufficient"), \
SLIB_RC_ENTRY(eInterrupted, "interrupted"), \
SLIB_RC_ENTRY(eInvalid, "invalid"), \
SLIB_RC_ENTRY(eKilled, "killed"), \
SLIB_RC_ENTRY(eLocked, "locked"), \
SLIB_RC_ENTRY(eNotAuthenticated, "not authenticated"), \
SLIB_RC_ENTRY(eNotAuthorized, "not authorized"), \
SLIB_RC_ENTRY(eNotEqual, "not equal"), \
SLIB_RC_ENTRY(eNotFinished, "not finished"), \
SLIB_RC_ENTRY(eNotFound, "not found"), \
SLIB_RC_ENTRY(eNotLocked, "not locked"), \
SLIB_RC_ENTRY(eNotMatched, "not matched"), \
SLIB_RC_ENTRY(eNotPermitted, "not permitted"), \
SLIB_RC_ENTRY(eNotSorted, "not sorted"), \
SLIB_RC_ENTRY(eNotSupported, "not supported"), \
SLIB_RC_ENTRY(eNull, "is null"), \
SLIB_RC_ENTRY(eObsolete, "obsolete"), \
SLIB_RC_ENTRY(eOpen, "open"), \
SLIB_RC_ENTRY(eOutOfRange, "out of range"), \
SLIB_RC_ENTRY(ePaused, "paused"), \
SLIB_RC_ENTRY(eProhibited, "prohibited"), \
SLIB_RC_ENTRY(eReadOnly, "read-only"), \
SLIB_RC_ENTRY(eRemoved, "removed"), \
SLIB_RC_ENTRY(eStarted, "started"), \
SLIB_RC_ENTRY(eStopped, "stopped"), \
SLIB_RC_ENTRY(eTerminated, "terminated"), \
SLIB_RC_ENTRY(eTimedOut, "timed out"), \
SLIB_RC_ENTRY(eTooBig, "too big"), \
SLIB_RC_ENTRY(eTooLong, "too long"), \
SLIB_RC_ENTRY(eTooShort, "too short"), \
SLIB_RC_ENTRY(eTooSmall, "too small"), \
SLIB_RC_ENTRY(eUnavailable, "unavailable"), \
SLIB_RC_ENTRY(eUndefined, "undefined"), \
SLIB_RC_ENTRY(eUnexpected, "unexpected"), \
SLIB_RC_ENTRY(eUninitialized, "uninitialized"), \
SLIB_RC_ENTRY(eUnknown, "unknown"), \
SLIB_RC_ENTRY(eUnreachable, "unreachable"), \
SLIB_RC_ENTRY(eUnrecognized, "unrecognized"), \
SLIB_RC_ENTRY(eViolated, "violated"), \
SLIB_RC_ENTRY(eVirtual, "only virtual"), \
SLIB_RC_ENTRY(eWriteOnly, "write-only"), \
SLIB_RC_ENTRY(eWrongFormat, "in wrong format"), \
SLIB_RC_ENTRY(eWrongOrder, "in wrong order"), \
SLIB_RC_ENTRY(eWrongType, "of wrong type"), \
SLIB_RC_ENTRY(eZero, "is zero"), \
/* Insert new entries after existing ones and before this line */ \
SLIB_RC_ENTRY_WITH_VAL(eStateOther, 255, "in some state")
#define SLIB_RC_ENTRY(id, description) id
#define SLIB_RC_ENTRY_WITH_VAL(id, val, description) id = val
namespace slib
{
class sStr; // forward-declare
//! 32-bit status code: operation A on target entity B failed because other entity C has unexpected state D
struct sRC
{
// TODO: use scoped enums when we switch to c++11 : "enum EFoo: unsigned char"
//! Operation performed on an entity
enum EOperation {
SLIB_RC_OPERATION_ENTRIES
};
//! Entity that is either the target of an operation or whose bad status caused an operation to fail
enum EEntity {
SLIB_RC_ENTITY_ENTRIES
};
//! Unexpected states of an entity
enum EState {
SLIB_RC_STATE_ENTRIES
};
union {
struct {
//TODO: change members from unsigned char to scoped enums when we switch to c++11
unsigned char op; //!< sRC::EOperation value: what operation was attempted
unsigned char op_target; //!< sRC::EEntity value: operation on what thing
unsigned char bad_entity; //!< sRC::EEntity value: other thing with unexpected state that was encountered
unsigned char state; //!< sRC::EState value: the unexpected state of bad_entity
} parts;
uint32_t whole;
} val;
static const sRC zero; //!< default unset RC value
inline sRC()
{
val.whole = 0;
}
inline sRC(EOperation op_, EEntity op_target_, EEntity bad_entity_, EState state_)
{
set(op_, op_target_, bad_entity_, state_);
}
inline bool set(EOperation op_, EEntity op_target_, EEntity bad_entity_, EState state_)
{
val.parts.op = (unsigned char)op_;
val.parts.op_target = (unsigned char)op_target_;
val.parts.bad_entity = (unsigned char)bad_entity_;
val.parts.state = (unsigned char)state_;
return isSet();
}
inline sRC(const sRC & rhs)
{
operator=(rhs);
}
inline sRC & operator=(const sRC & rhs)
{
val = rhs.val;
return *this;
}
inline bool isSet() const
{
return val.whole;
}
inline bool isUnset() const
{
return !isSet();
}
//! useful for the following pattern: <code> if( sRC rc = foobar(...) ) { /* foobar failed, error handled here */ } </code>
inline operator bool() const
{
return isSet();
}
static const char * operation2string(EOperation op, bool asEnumName=false);
static const char * entity2string(EEntity entity, bool asEnumName=false);
static const char * state2string(EState state, bool asEnumName=false);
//! Print an sRC code
/*! \param out where to print; if 0, prints to internal static buffer
* \param asEnumNames if true, prints EOperation/EEntity/EState enum names ("eParsing eTable")
* instead of corresponding descriptions ("parsing table")
* \returns pointer to start of printed string */
const char * print(sStr * out=0, bool asEnumNames=false) const;
};
};
#endif /* sLib_core_rc_hpp */
| 42.21499 | 135 | 0.658272 |
syntheticgio
|
28e4c2089b979618e7976220fff29caa27869d48
| 104,500 |
cpp
|
C++
|
source/sfsbp/FDP.cpp
|
kali-allison/SCycle
|
0a81edfae8730acb44531e2c2b3f51f25ea193d2
|
[
"MIT"
] | 14 |
2019-04-12T16:36:36.000Z
|
2022-03-16T00:35:03.000Z
|
source/sfsbp/FDP.cpp
|
kali-allison/SCycle
|
0a81edfae8730acb44531e2c2b3f51f25ea193d2
|
[
"MIT"
] | null | null | null |
source/sfsbp/FDP.cpp
|
kali-allison/SCycle
|
0a81edfae8730acb44531e2c2b3f51f25ea193d2
|
[
"MIT"
] | 6 |
2019-07-22T23:53:15.000Z
|
2022-03-10T03:30:50.000Z
|
/* FDP.cpp
* -------
* -----------------------------
* Finite-Difference in Parallel
* -----------------------------
*
* Adding Linear Solve Functionality in the Solve_Linear_Equation function.
* - It currently needs to be able to wrap MatMult in MyMatMult, using my Finite-Difference
* Stencils to calculate the matrix-vector product between the vector and the 2nd derivative
* matrix.
*
* The other main part of this program is the MMS Test.
* - The first section of Globals allows the user to change the parameters of the MMS test.
* - There are two sections of Globals for the MMS Test.
* - The first section allows the user to define parameters for the 1-D MMS Test.
* - The second allows the user to define parameters for the 2-D MMS Test.
* - These parameters include a beginning point, and an end point (in each direction for 2-D)
* - There is also another parameter for the number of grid points in each direction.
* - Lastly, there is a parameter that dictates how many times the user wants the program to solve
* each derivative. For example, changing the NUM_GRID_SPACE_CALCULATIONS will change the number of times
* the program will solve the 1st derivative using finite-difference stencils in 1-D.
*/
#include <petscvec.h>
#include <petscdmda.h>
#include <math.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
// 1-D MMS Test Globals
#define MIN_GRID_POINT 0
#define MAX_GRID_POINT 3
#define STARTING_GRID_SPACING 1//201
#define NUM_GRID_SPACE_CALCULATIONS 0 // 14 FIXME what's the limit here?
#define NUM_2ND_GRID_SPACE_CALCULATIONS 0
// 2-D MMS Test Globals
#define NUM_2D_GRID_SPACE_CALCULATIONS 0 //12 // FIXME is there a limit here? SLOWS DOWN A LOT ON 20k+ values in each direction?
#define NUM_2D_2ND_GRID_SPACE_CALCULATIONS 0
#define COEFFICIENT_SOLVE 1 // IMPORTANT: 0 for NO coefficient solve (w mu), 1 (or any other numeric value) to solve WITH coefficient
#define NUM_X_PTS 5 //201
#define NUM_Y_PTS 6 //201
#define X_MIN 0
#define Y_MIN 0
#define X_MAX 5
#define Y_MAX 10
//--------------------------------------------------------------------------------------------------------------------------------
//Globals for the Linear Solve Program
#define PTS_IN_X 6
#define PTS_IN_Y 5
#define X_MINIMUM 0.0
#define Y_MINIMUM 0.0
#define X_MAXIMUM 5.0
#define Y_MAXIMUM 10.0
typedef struct {
/* problem parameters */
PetscInt order;
PetscInt n_x, n_y;
Vec Bottom, Top, Left, Right; /* boundary values */
PetscScalar alphaDx, alphaDy, alphaT, beta;
Vec mu;
PetscScalar dx_spacing, dy_spacing;
/* Working space */
Vec localX, localV; /* ghosted local vector */
DM da; /* distributed array data structure */
DM cda;
Mat H;
} AppCtx;
PetscScalar MMS_uA(PetscScalar x, PetscScalar y) {
return cos(x) * sin(y) + 2;
}
PetscScalar MMS_uA_dx(PetscScalar x, PetscScalar y) {
return -sin(x) * sin(y);
}
PetscScalar MMS_uA_dxx(PetscScalar x, PetscScalar y) {
return -cos(x) * sin(y);
}
PetscScalar MMS_uA_dy(PetscScalar x, PetscScalar y) {
return cos(x) * cos(y);
}
PetscScalar MMS_uA_dyy(PetscScalar x, PetscScalar y) {
return -cos(x) * sin(y);
}
PetscScalar MMS_mu(PetscScalar x, PetscScalar y) {
return sin(x) * sin(y) + 2;
}
PetscScalar MMS_mu_dx(PetscScalar x, PetscScalar y) {
return cos(x) * sin(y);
}
PetscScalar MMS_mu_dy(PetscScalar x, PetscScalar y) {
return sin(x) * cos(y);
}
PetscScalar MMS_uA_dmuxx(PetscScalar x, PetscScalar y) {
return MMS_mu(x,y) * MMS_uA_dxx(x,y) + MMS_mu_dx(x,y) * MMS_uA_dx(x,y);
}
PetscScalar MMS_uA_dmuyy(PetscScalar x, PetscScalar y) {
return MMS_mu(x,y) * MMS_uA_dyy(x,y) + MMS_mu_dy(x,y) * MMS_uA_dx(x,y);
}
PetscScalar MMS_uS(PetscScalar x, PetscScalar y) {
return MMS_mu(x,y) * (MMS_uA_dxx(x,y) + MMS_uA_dyy(x,y))
+ MMS_mu_dx(x,y) * MMS_uA_dx(x,y) + MMS_mu_dy(x,y) * MMS_uA_dy(x,y);
}
/* Function: writeVec
* ------------------
* This function allows users to pass in a vector and
* a file location (including name) for a PETSc vector.
* If the current directory is the desired location,
* a string containing the name of the file
* will suffice. The vector can then be imported to
* MATLAB for error checking or other usage.
*/
PetscErrorCode writeVec(Vec vec,const char * loc)
{
PetscErrorCode ierr = 0;
PetscViewer viewer;
PetscViewerBinaryOpen(PETSC_COMM_WORLD,loc,FILE_MODE_WRITE,&viewer);
ierr = VecView(vec,viewer);CHKERRQ(ierr);
ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
return ierr;
}
/* Function: calculate_two_norm
* ----------------------------
* This function calculates the two-norm
* of the difference of two vectors, multiplies
* the calculated norm by 1/sqrt(length of vector)
* and outputs this error value as well as the log (base 2)
* of the error value. The Vec that will contain the difference is
* the first argument (diff). The second and third arguments
* are the two Vecs that we are taking the difference of. The last
* argument is the length of the vectors, the number of entries
* in the given Vecs.
*/
PetscErrorCode calculate_two_norm(Vec &diff, const Vec &x, const Vec &y, int size) {
PetscErrorCode ierr = 0;
PetscScalar a = -1; // set the multiple in the WAXPY operation to negative so it just subtracts
VecWAXPY(diff,a,x,y); // diff = x - y
PetscReal norm = 0; // zeroes out the norm value
VecNorm(diff,NORM_2,&norm); // norm = NORM_2(diff)
PetscReal answer = norm * (1/(sqrt(size))); // error equals norm times 1 over the sqrt of the Vec length
PetscPrintf(PETSC_COMM_WORLD, "Error: % .5e ", answer);
answer = log2(answer); // take the log (base 2) for easier readability
PetscPrintf(PETSC_COMM_WORLD, "Log of Error: % .5e\n", answer); // I USED TO HAVE %.15e
return ierr;
}
/* Function: Dx_1d
* ------------------------------------
* This function takes in a derivative matrix (in the form of a vector)
* that it will fill. It also takes in a grid spacing interval (PetscScalar)
* and the values at each interval (which is a matrix placed in the form
* of a vector). The vectors are passed in by reference. One
* also needs to pass in the DMDA associated with the given Vecs.
*
* Vecs:
* - u is the vector that one passes in to hold the calculated derivative.
* - z is the vector that holds the sampled values of the function
*/
PetscErrorCode Dx_1d(Vec &u, Vec &z, PetscScalar spacing, DM &da) {
PetscErrorCode ierr = 0;
// Creating local Vecs y (function values) and calc_diff (derivative)
Vec y, calc_diff;
// Values that hold specific indices for iteration
PetscInt yistart, yiend, fistart, fiend, yi_extra;
// Creates local vectors using the DMDA to ensure correct partitioning
DMCreateLocalVector(da,&y);
DMCreateLocalVector(da,&calc_diff);
// Make it such that the DMDA splits the global Vecs into local Vecs
ierr = DMGlobalToLocalBegin(da,z,INSERT_VALUES,y);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da,z,INSERT_VALUES,y);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr);
// Obtains the ownership range of both the function-value Vec and the derivative Vec
ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr);
ierr = VecGetOwnershipRange(calc_diff,&fistart,&fiend);CHKERRQ(ierr);
// Here we set the current to the beginning and the previous to the beginning
// We set the next to the one directly after the start.
PetscInt yi_current = yistart;
PetscInt yi_prev = yistart;
PetscInt yi_next = yistart + 1;
PetscScalar slope = 0; // This will contain the derivative on each calculation
PetscScalar y_1, y_2, y_3; // These are used to keep the derivative values we pull from the function Vec
PetscInt fi = fistart; // We start the current iteration on the first value in the function Vec
while(yi_current < yiend) {
yi_next = yi_current + 1;
// If the current index is between the start and the end of the Vec
// simply calculate the derivative using the central difference method
if (yi_current > yistart && yi_current < yiend - 1) {
yi_prev = yi_current - 1;
ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_next,&y_2);CHKERRQ(ierr);
slope = ((y_2 - y_1) / (2 * spacing));
// This is where I calculate the derivative at the beginning
// of the Vec. I use coefficients and 3 points to obtain
// second-order accuracy.
} else if (yi_current == yistart) {
ierr = VecGetValues(y,1,&yi_current,&y_1);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_next,&y_2);CHKERRQ(ierr);
yi_extra = yi_next + 1;
ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr);
slope = (((-y_3) + (4 * y_2) + (-3 * y_1)) / (2 * spacing));
// This is where I calculate the derivative at the end of the
// Vec. I use coefficients and 3 points at the end of the Vec
// to obtain second-order accuracy.
} else if (yi_current == yiend - 1) {
yi_prev = yi_current - 1;
ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_current,&y_2);CHKERRQ(ierr);
yi_extra = yi_prev - 1;
ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr);
slope = (((y_3) + (-4 * y_1) + (3 * y_2)) / (2 * spacing));
}
// This sets the Vec value to the calculated derivative
ierr = VecSetValues(calc_diff,1,&fi,&slope,INSERT_VALUES);CHKERRQ(ierr);
// Increment here
fi++;
yi_current++;
}
// Assemble the Vec - do we need this here? Not sure.
ierr = VecAssemblyBegin(calc_diff);CHKERRQ(ierr);
ierr = VecAssemblyEnd(calc_diff);CHKERRQ(ierr);
// Take the Vec values from the local Vecs and put them back in their respective global Vecs.
ierr = DMLocalToGlobalBegin(da,y,INSERT_VALUES,z);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da,y,INSERT_VALUES,z);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr);
// Dispose of the local Vecs
VecDestroy(&y);
VecDestroy(&calc_diff);
return ierr;
}
/* Function: Dxx_1d
* ------------------------------------
* This function takes in a derivative matrix (in the form of a vector)
* that it will fill. It also takes in a grid spacing interval (PetscScalar)
* and the values at each interval (which is a matrix placed in the form
* of a vector). The vectors are passed in by reference. One
* also needs to pass in the DMDA associated with the given Vecs.
*
* Vecs:
* - u is the vector that one passes in to hold the calculated derivative.
* - z is the vector that holds the sampled values of the function
*/
PetscErrorCode Dxx_1d(Vec &u, Vec &z, PetscScalar spacing, DM &da) {
PetscErrorCode ierr = 0;
// Creating local Vecs y (function values) and calc_diff (derivative)
Vec y, calc_diff;
// Values that hold specific indices for iteration
PetscInt yistart, yiend, fistart, fiend, yi_extra;
// Creates local vectors using the DMDA to ensure correct partitioning
DMCreateLocalVector(da,&y);
DMCreateLocalVector(da,&calc_diff);
// Make it such that the DMDA splits the global Vecs into local Vecs
ierr = DMGlobalToLocalBegin(da,z,INSERT_VALUES,y);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da,z,INSERT_VALUES,y);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr);
// Obtains the ownership range of both the function-value Vec and the derivative Vec
ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr);
ierr = VecGetOwnershipRange(calc_diff,&fistart,&fiend);CHKERRQ(ierr);
// Here we set the current to the beginning and the previous to the beginning
// We set the next to the one directly after the start.
PetscInt yi_current = yistart;
PetscInt yi_prev = yistart;
PetscInt yi_next = yistart + 1;
PetscScalar slope = 0; // This will contain the derivative on each calculation
PetscScalar y_1, y_2, y_3; // These are used to keep the derivative values we pull from the function Vec
PetscInt fi = fistart; // We start the current iteration on the first value in the function Vec
while(yi_current < yiend) {
yi_next = yi_current + 1;
// If the current index is between the start and the end of the Vec
// simply calculate the derivative using the central difference method
if (yi_current > yistart && yi_current < yiend - 1) {
yi_prev = yi_current - 1;
ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_current,&y_2);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_next,&y_3);CHKERRQ(ierr);
slope = ((y_1 - (2 * y_2) + y_3) / (spacing * spacing));
// This is where I calculate the derivative at the beginning
// of the Vec. I use coefficients and 3 points to obtain
// second-order accuracy.
} else if (yi_current == yistart) {
ierr = VecGetValues(y,1,&yi_current,&y_1);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_next,&y_2);CHKERRQ(ierr);
yi_extra = yi_next + 1;
ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr);
slope = (y_1 - (2 * y_2) + y_3) / (spacing * spacing);
// This is where I calculate the derivative at the end of the
// Vec. I use coefficients and 3 points at the end of the Vec
// to obtain second-order accuracy.
} else if (yi_current == yiend - 1) {
yi_prev = yi_current - 1;
ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr);
ierr = VecGetValues(y,1,&yi_current,&y_2);CHKERRQ(ierr);
yi_extra = yi_prev - 1;
ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr);
slope = (y_2 - (2 * (y_1)) + y_3) / (spacing * spacing);
}
// This sets the Vec value to the calculated derivative
ierr = VecSetValues(calc_diff,1,&fi,&slope,INSERT_VALUES);CHKERRQ(ierr);
// Increment here
fi++;
yi_current++;
}
// Assemble the Vec - do we need this here? Not sure.
ierr = VecAssemblyBegin(calc_diff);CHKERRQ(ierr);
ierr = VecAssemblyEnd(calc_diff);CHKERRQ(ierr);
// Take the Vec values from the local Vecs and put them back in their respective global Vecs.
ierr = DMLocalToGlobalBegin(da,y,INSERT_VALUES,z);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da,y,INSERT_VALUES,z);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr);
// Dispose of the local Vecs
VecDestroy(&y);
VecDestroy(&calc_diff);
return ierr;
}
/* Function: calculate_Dx_1d
* -----------------------------
* This function calculates the first
* derivative of a Vec using only
* the number of entries (n), the minimum value (x_min),
* and the maximum value (x_max). It calculates
* all other need values.
*/
PetscErrorCode calculate_Dx_1d(PetscInt n, PetscInt x_min, PetscInt x_max)
{
PetscErrorCode ierr = 0;
PetscInt i = 0, xistart, xiend, yistart, yiend, diff_start, diff_end; /* iteration values */
PetscScalar v = 0, mult = 0; /* v is my temp value I use to fill Vecs, mult is the spacing between each value of the Vec (h, dx) */
Vec w = NULL, x = NULL, y = NULL, calc_diff = NULL, diff = NULL; /* vectors */
mult = ((PetscReal)(x_max - x_min))/(n - 1); // evenly partitioning the Vec to have equally sized spacing between values
// MUST CREATE DMDA - STENCIL WIDTH 1 FOR BOUNDARIES
// IMPORTANT: SINCE STENCIL WIDTH IS 1, BE SURE THAT THERE ARE AT LEAST 3 END VALUES ON THE END OF A PARTITIONED VEC
DM da;
DMDACreate1d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE,n,1,1,NULL,&da);
// Create first Vec, this one holds the values at specific points (at every spacing)
ierr = DMCreateGlobalVector(da,&x); // Holds spacing values
// Same Vec format, duplicated.
ierr = VecDuplicate(x,&w);CHKERRQ(ierr); // Will eventually be used to hold the difference between the actual derivative and the calculated one.
ierr = VecDuplicate(x,&y);CHKERRQ(ierr); // Holds function values
ierr = VecDuplicate(x,&calc_diff);CHKERRQ(ierr); // Holds calculated derivative
ierr = VecDuplicate(x,&diff);CHKERRQ(ierr); // Holds actual derivative
ierr = PetscObjectSetName((PetscObject) x, "x (spacing values)");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) w, "w");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) y, "y (func. values)");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) calc_diff, "calculated derivative");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) diff, "actual derivative");CHKERRQ(ierr);
/* This is where I fill in the x vector.
* I put in multiples defined by the grid
* spacing from the minimum value to the maximum.
*/
VecGetOwnershipRange(x,&xistart,&xiend);
for(i = xistart; i < xiend; i++) {
v = (i*mult);
VecSetValues(x,1,&i,&v,INSERT_VALUES);
}
ierr = VecAssemblyBegin(x);CHKERRQ(ierr);
ierr = VecAssemblyEnd(x);CHKERRQ(ierr);
/* This is where I fill in the y vector.
* Its values can be defined by a hard-coded
* function below. Comment out a single
* function to dictate what will be in the y Vec.
*/
ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr);
for(i = yistart; i < yiend; i++) {
ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr);
// v *= v; // x^2
// v = (v*v*v); // x^3
v = sin(v); // sine function
// v = cos(v); // cosine function
ierr = VecSetValues(y,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(y);CHKERRQ(ierr);
ierr = VecAssemblyEnd(y);CHKERRQ(ierr);
/* This is where I fill in the true
* analytical derivative. It's hard-coded
* as well.
*/
ierr = VecGetOwnershipRange(diff,&diff_start,&diff_end);CHKERRQ(ierr);
for(i = diff_start; i < diff_end; i++) {
ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr);
// v = 2*v; // 2x
// v = (3)*(v*v); //3x^2
v = cos(v); // cosine function
// v = -sin(v); // -sine function
ierr = VecSetValues(diff,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(diff);CHKERRQ(ierr);
ierr = VecAssemblyEnd(diff);CHKERRQ(ierr);
/* Here we pass in the calculated derivative Vec (to be filled),
* our spacing, our Vec with function values (y), and the DMDA.
* It will fill the calc_diff Vec with our calculated derivative.
*/
ierr = Dx_1d(calc_diff, y, mult, da);CHKERRQ(ierr);
/* This is where we calculate norm using the difference between
* the analytical (true) derivative and the calculated derivative and print
* out the error. Below here, we print out information (number of entries,
* the current spacing).
*/
PetscPrintf(PETSC_COMM_WORLD, "Nx: %15i Spacing: % .15e ", n, mult);
ierr = calculate_two_norm(w, calc_diff, diff, n);CHKERRQ(ierr);
/* To print out any of the Vecs, uncomment one of the lines below */
// ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// ierr = VecView(y,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// ierr = VecView(calc_diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// ierr = VecView(diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// BE SURE TO DISPOSE OF ALL VECS AND DMDAS!
ierr = VecDestroy(&w);CHKERRQ(ierr);
ierr = VecDestroy(&x);CHKERRQ(ierr);
ierr = VecDestroy(&y);CHKERRQ(ierr);
ierr = VecDestroy(&calc_diff);CHKERRQ(ierr);
ierr = VecDestroy(&diff);CHKERRQ(ierr);
ierr = DMDestroy(&da);CHKERRQ(ierr);
return ierr;
}
/* Function: calculate_Dxx_1d
* -----------------------------
* This function calculates the second
* derivative of a Vec using only
* the number of entries (n), the minimum value (x_min),
* and the maximum value (x_max). It calculates
* all other need values.
*/
PetscErrorCode calculate_Dxx_1d(PetscInt n, PetscInt x_min, PetscInt x_max)
{
PetscErrorCode ierr = 0;
PetscInt i = 0, xistart, xiend, yistart, yiend, diff_start, diff_end; /* iteration values */
PetscScalar v = 0, mult = 0; /* v is my temp value I use to fill Vecs, mult is the spacing between each value of the Vec (h, dx) */
Vec w = NULL, x = NULL, y = NULL, calc_diff = NULL, diff = NULL; /* vectors */
mult = ((PetscReal)(x_max - x_min))/(n - 1); // evenly partitioning the Vec to have equally sized spacing between values
// MUST CREATE DMDA - STENCIL WIDTH 1 FOR BOUNDARIES
// IMPORTANT: SINCE STENCIL WIDTH IS 1, BE SURE THAT THERE ARE AT LEAST 3 END VALUES ON THE END OF A PARTITIONED VEC
DM da;
DMDACreate1d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE,n,1,1,NULL,&da);
// Create first Vec, this one holds the values at specific points (at every spacing)
ierr = DMCreateGlobalVector(da,&x); // Holds spacing values
// Same Vec format, duplicated.
ierr = VecDuplicate(x,&w);CHKERRQ(ierr); // Will eventually be used to hold the difference between the actual derivative and the calculated one.
ierr = VecDuplicate(x,&y);CHKERRQ(ierr); // Holds function values
ierr = VecDuplicate(x,&calc_diff);CHKERRQ(ierr); // Holds calculated derivative
ierr = VecDuplicate(x,&diff);CHKERRQ(ierr); // Holds actual derivative
ierr = PetscObjectSetName((PetscObject) x, "x (spacing values)");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) w, "w");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) y, "y (func. values)");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) calc_diff, "calculated derivative");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) diff, "actual derivative");CHKERRQ(ierr);
/* This is where I fill in the x vector.
* I put in multiples defined by the grid
* spacing from the minimum value to the maximum.
*/
VecGetOwnershipRange(x,&xistart,&xiend);
for(i = xistart; i < xiend; i++) {
v = (i*mult);
VecSetValues(x,1,&i,&v,INSERT_VALUES);
}
ierr = VecAssemblyBegin(x);CHKERRQ(ierr);
ierr = VecAssemblyEnd(x);CHKERRQ(ierr);
/* This is where I fill in the y vector.
* Its values can be defined by a hard-coded
* function below. Comment out a single
* function to dictate what will be in the y Vec.
*/
ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr);
for(i = yistart; i < yiend; i++) {
ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr);
// v *= v; // x^2
// v = (v*v*v); // x^3
v = sin(v); // sine function
// v = cos(v); // cosine function
ierr = VecSetValues(y,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(y);CHKERRQ(ierr);
ierr = VecAssemblyEnd(y);CHKERRQ(ierr);
/* This is where I fill in the true
* analytical derivative. It's hard-coded
* as well.
*/
ierr = VecGetOwnershipRange(diff,&diff_start,&diff_end);CHKERRQ(ierr);
for(i = diff_start; i < diff_end; i++) {
ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr);
// v = 2*v; // 2x
// v = (3)*(v*v); //3x^2
// v = cos(v); // cosine function
v = -sin(v); // -sine function
ierr = VecSetValues(diff,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(diff);CHKERRQ(ierr);
ierr = VecAssemblyEnd(diff);CHKERRQ(ierr);
/* Here we pass in the calculated derivative Vec (to be filled),
* our spacing, our Vec with function values (y), and the DMDA.
* It will fill the calc_diff Vec with our calculated derivative.
*/
ierr = Dxx_1d(calc_diff, y, mult, da);CHKERRQ(ierr);
/* This is where we calculate norm using the difference between
* the analytical (true) derivative and the calculated derivative and print
* out the error. Below here, we print out information (number of entries,
* the current spacing).
*/
PetscPrintf(PETSC_COMM_WORLD, "Nx: %15i Spacing: % .15e ", n, mult);
ierr = calculate_two_norm(w, calc_diff, diff, n);CHKERRQ(ierr);
/* To print out any of the Vecs, uncomment one of the lines below */
// ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// ierr = VecView(y,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// ierr = VecView(calc_diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// ierr = VecView(diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// BE SURE TO DISPOSE OF ALL VECS AND DMDAS!
ierr = VecDestroy(&w);CHKERRQ(ierr);
ierr = VecDestroy(&x);CHKERRQ(ierr);
ierr = VecDestroy(&y);CHKERRQ(ierr);
ierr = VecDestroy(&calc_diff);CHKERRQ(ierr);
ierr = VecDestroy(&diff);CHKERRQ(ierr);
ierr = DMDestroy(&da);CHKERRQ(ierr);
return ierr;
}
/* Function: truncation_error
* --------------------------
* This function serves as a test function to see where the convergence fails.
*/
PetscErrorCode truncation_error(Vec &diff_x, PetscScalar &mult_x, DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M;
DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_x;
PetscScalar** local_diff_x_arr;
ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, diff_x, INSERT_VALUES, local_diff_x);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, diff_x, INSERT_VALUES, local_diff_x);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
PetscInt x_index = (((int)M/5));
PetscPrintf(PETSC_COMM_WORLD, "Spacing: % .15e At index ([j][i]) [%i][%5i]F'(0.0001) = % .15e\n", mult_x, 2, x_index, local_diff_x_arr[2][x_index]);
return ierr;
}
/* Function: Dy_2d
* ----------------------------------
* 1st derivative solve in the y-direction for 2-D.
*
* diff_y - the output Vec (it will hold the calculated derivative)
* grid - the input Vec (it holds the function values to draw from)
* dy - the spacing between each point in the y-direction
* da - DMDA object
*/
PetscErrorCode Dy_2d(Vec &diff_y, Vec &grid, PetscScalar dy, DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, N;
DMDAGetInfo(da,NULL,NULL,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_y, local_grid;
PetscScalar** local_diff_y_arr;
PetscScalar** local_grid_arr;
ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (j > 0 && j < N - 1) { local_diff_y_arr[j][i] = (local_grid_arr[j+1][i] - local_grid_arr[j-1][i])/(2.0 * dy); }
else if (j == 0) { local_diff_y_arr[j][i] = (-1.5 * local_grid_arr[0][i] + 2.0 * local_grid_arr[1][i] - 0.5 * local_grid_arr[2][i])/ dy; }
else if (j == N - 1) { local_diff_y_arr[j][i] = (0.5 * local_grid_arr[N-3][i] - 2.0 *
local_grid_arr[N-2][i] + 1.5 * local_grid_arr[N-1][i]) / dy; }
}
}
ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
VecDestroy(&local_diff_y);
VecDestroy(&local_grid);
return ierr;
}
/* Function: Dx_2d
* ----------------------------------
*
* diff_x - the output Vec (it will hold the calculated derivative)
* grid - the input Vec (it holds the function values to draw from)
* dx - the spacing between each point in the x-direction
* da - DMDA object
*/
//~PetscErrorCode Dx_2d(Vec &diff_x, Vec &grid, PetscScalar dx, DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M;
DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_x, local_grid;
PetscScalar** local_diff_x_arr;
PetscScalar** local_grid_arr;
ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (i > 0 && i < M - 1) {local_diff_x_arr[j][i] = (local_grid_arr[j][i+1] -
local_grid_arr[j][i-1])/(2.0 * dx); }
else if (i == 0) { local_diff_x_arr[j][i] = (-1.5 * local_grid_arr[j][0] +
2.0 * local_grid_arr[j][1] - 0.5 * local_grid_arr[j][2])/ dx; }
else if (i == M - 1) { local_diff_x_arr[j][i] = (0.5 * local_grid_arr[j][M-3] -
2.0 * local_grid_arr[j][M-2] + 1.5 * local_grid_arr[j][M-1]) / dx; }
}
}
ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
VecDestroy(&local_diff_x);
VecDestroy(&local_grid);
return ierr;
}
/* Function: Dyy_2d
* ----------------------------------
* diff_y - the output Vec (it will hold the calculated derivative)
* grid - the input Vec (it holds the function values to draw from)
* dy - the spacing between each point in the y-direction
* da - DMDA object
*/
PetscErrorCode Dyy_2d(Vec &diff_y, const Vec &grid, const PetscScalar dy, const DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, N;
DMDAGetInfo(da,NULL,NULL,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_y, local_grid;
PetscScalar** local_diff_y_arr;
PetscScalar** local_grid_arr;
ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (j > 0 && j < N - 1) { local_diff_y_arr[j][i] = (local_grid_arr[j+1][i] - (2*local_grid_arr[j][i]) + local_grid_arr[j-1][i])/(dy * dy); }
else if (j == 0) { local_diff_y_arr[j][i] = (local_grid_arr[0][i] - (2 * local_grid_arr[1][i]) + local_grid_arr[2][i])/(dy * dy); }
else if (j == N - 1) { local_diff_y_arr[j][i] = (local_grid_arr[N-1][i] - (2 * local_grid_arr[N-2][i]) + local_grid_arr[N-3][i])/(dy * dy); }
}
}
ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
VecDestroy(&local_diff_y);
VecDestroy(&local_grid);
return ierr;
}
/* Function: Dxx_2d
* --------------------------------------
* diff_x - the output Vec (it will hold the calculated derivative)
* grid - the input Vec (it holds the function values to draw from)
* dx - the spacing between each point in the x-direction
* da - DMDA object
*/
PetscErrorCode Dxx_2d(Vec &diff_x, const Vec &grid, const PetscScalar dx, const DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M;
DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
VecSet(diff_x,0.0);
Vec local_diff_x, local_grid;
PetscScalar** local_diff_x_arr;
PetscScalar** local_grid_arr;
ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (i > 0 && i < M - 1) {local_diff_x_arr[j][i] = (local_grid_arr[j][i+1] -
(2 * local_grid_arr[j][i]) + local_grid_arr[j][i-1])/(dx * dx); }
else if (i == 0) { local_diff_x_arr[j][i] = (local_grid_arr[j][0] -
(2 * local_grid_arr[j][1]) + local_grid_arr[j][2])/(dx * dx); }
else if (i == M - 1) { local_diff_x_arr[j][i] = (local_grid_arr[j][M-1] -
(2 * local_grid_arr[j][M-2]) + local_grid_arr[j][M-3])/(dx * dx); }
//PetscPrintf(PETSC_COMM_SELF, "[%i][%i] = %g\n", j, i, local_diff_x_arr[j][i]);
}
}
ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
VecDestroy(&local_diff_x);
VecDestroy(&local_grid);
return ierr;
}
/* Function: Dmuyy_2d
* ------------------
* diff_y - the output Vec (it will hold the calculated derivative)
* grid - the input Vec (it holds the function values to draw from)
* mu - the Vec that holds the values of mu
* dy - the spacing between each point in the y-direction
* da - DMDA object
*/
PetscErrorCode Dmuyy_2d(Vec &diff_y, const Vec &grid, const Vec &mu, const PetscScalar dy, const DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, N;
DMDAGetInfo(da,NULL,NULL,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_y = NULL, local_grid = NULL, local_mu = NULL;
PetscScalar** local_diff_y_arr;
PetscScalar** local_grid_arr;
PetscScalar** local_mu_arr;
ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_mu);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_mu, &local_mu_arr); CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (j > 0 && j < N - 1) { local_diff_y_arr[j][i] = (0.5 * (((local_mu_arr[j][i] + local_mu_arr[j-1][i]) * local_grid_arr[j-1][i])
- ((local_mu_arr[j+1][i] + 2 * local_mu_arr[j][i] + local_mu_arr[j-1][i]) * local_grid_arr[j][i])
+ ((local_mu_arr[j][i] + local_mu_arr[j+1][i]) * local_grid_arr[j+1][i])
))/(dy * dy); }
else if (j == 0) { local_diff_y_arr[j][i] = (0.5 * (((local_mu_arr[1][i] + local_mu_arr[0][i]) * local_grid_arr[0][i])
- ((local_mu_arr[2][i] + 2 * local_mu_arr[1][i] + local_mu_arr[0][i]) * local_grid_arr[1][i])
+ ((local_mu_arr[1][i] + local_mu_arr[2][i]) * local_grid_arr[2][i])
))/(dy * dy); }
else if (j == N - 1) { local_diff_y_arr[j][i] = (0.5 * (((local_mu_arr[N-2][i] + local_mu_arr[N-1][i]) * local_grid_arr[N-1][i])
- ((local_mu_arr[N-3][i] + 2 * local_mu_arr[N-2][i] + local_mu_arr[N-1][i]) * local_grid_arr[N-2][i])
+ ((local_mu_arr[N-2][i] + local_mu_arr[N-3][i]) * local_grid_arr[N-3][i])
))/(dy * dy); }
}
}
ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_mu, &local_mu_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
VecDestroy(&local_diff_y);
VecDestroy(&local_grid);
VecDestroy(&local_mu);
return ierr;
}
/* Function: Dmuxx_2d
* --------------------------------------
* diff_x - the output Vec (it will hold the calculated derivative)
* grid - the input Vec (it holds the function values to draw from)
* mu - the Vec that holds the values of mu
* dx - the spacing between each point in the x-direction
* da - DMDA object
*/
PetscErrorCode Dmuxx_2d(Vec &diff_x, const Vec &grid, const Vec &mu, const PetscScalar dx, const DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M;
DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_x = NULL, local_grid = NULL, local_mu = NULL;
PetscScalar** local_diff_x_arr;
PetscScalar** local_grid_arr;
PetscScalar** local_mu_arr;
ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_mu);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_mu, &local_mu_arr); CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (i > 0 && i < M - 1) {local_diff_x_arr[j][i] = (0.5 * (((local_mu_arr[j][i] + local_mu_arr[j][i-1]) * local_grid_arr[j][i-1])
- ((local_mu_arr[j][i+1] + 2 * local_mu_arr[j][i] + local_mu_arr[j][i-1]) * local_grid_arr[j][i])
+ ((local_mu_arr[j][i] + local_mu_arr[j][i+1]) * local_grid_arr[j][i+1])
))/(dx * dx); }
else if (i == 0) { local_diff_x_arr[j][i] = (0.5 * (((local_mu_arr[j][1] + local_mu_arr[j][0]) * local_grid_arr[j][0])
- ((local_mu_arr[j][2] + 2 * local_mu_arr[j][1] + local_mu_arr[j][0]) * local_grid_arr[j][1])
+ ((local_mu_arr[j][1] + local_mu_arr[j][2]) * local_grid_arr[j][2])
))/(dx * dx); }
else if (i == M - 1) { local_diff_x_arr[j][i] = (0.5 * (((local_mu_arr[j][M-2] + local_mu_arr[j][M-1]) * local_grid_arr[j][M-1])
- ((local_mu_arr[j][M-3] + 2 * local_mu_arr[j][M-2] + local_mu_arr[j][M-1]) * local_grid_arr[j][M-2])
+ ((local_mu_arr[j][M-2] + local_mu_arr[j][M-3]) * local_grid_arr[j][M-3])
))/(dx * dx); }
//PetscPrintf(PETSC_COMM_SELF, "[%i][%i] = %g\n", j, i, local_diff_x_arr[j][i]);
}
}
ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_mu, &local_mu_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
VecDestroy(&local_diff_x);
VecDestroy(&local_grid);
VecDestroy(&local_mu);
return ierr;
}
/* Function: calculate_Dx_Dy_2D
* ---------------------------------------
* Calculates both the first derivative in x and y for a 2-D grid.
* x_len - number of points in the x direction
* y_len - number of points in the y direction
* x_max - maximum value in the x direction
* x_min - minimum value in the x_direction
* y_max - maximum value in the y direction
* y_min - minimum value in the y direction
*/
PetscErrorCode calculate_Dx_Dy_2D(PetscInt x_len, PetscInt y_len, PetscScalar x_max, PetscScalar x_min, PetscScalar y_max, PetscScalar y_min) {
PetscErrorCode ierr = 0;
double t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0;
t1 = MPI_Wtime();
PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0,
grid_istart, grid_iend, diff_x_start, diff_x_end, diff_y_start, diff_y_end;
PetscScalar v = 0, mult_x = 0, mult_y = 0;
Vec grid = NULL, diff_x = NULL, diff_y = NULL, act_diff_x = NULL, act_diff_y = NULL, grid_error_diff = NULL, /* vectors */
local_coords = NULL, local_grid = NULL, local_act_diff_x = NULL, local_act_diff_y = NULL;
// first row, global vectors, second row, local vectors
PetscInt num_grid_entries = (x_len) * (y_len); // total number of entries on the grid
mult_x = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction
mult_y = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction
DM da;
DM cda;
DMDACoor2d **coords; // 2D array containing x and y data members
// FIXME should I use DMDA_STENCIL_STAR && do we need a stencil width of 2?
ierr = DMDACreate2d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE,
DMDA_STENCIL_BOX, x_len, y_len, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &da); CHKERRQ(ierr);
DMDASetUniformCoordinates(da, x_min, x_max, y_min, y_max, 0.0, 0.0);
DMGetCoordinateDM(da, &cda);
DMGetCoordinatesLocal(da, &local_coords);
DMDAVecGetArray(cda, local_coords, &coords);
DMDAGetCorners(cda, &mStart, &nStart, 0, &m, &n, 0);
ierr = DMCreateGlobalVector(da,&grid);
ierr = VecDuplicate(grid, &diff_x);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &diff_y);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &act_diff_x);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &act_diff_y);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &grid_error_diff);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) grid, "global grid");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) diff_x, "diff_x");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) diff_y, "diff_y");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) act_diff_x, "act_diff_x");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) act_diff_y, "act_diff_y");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) grid_error_diff, "grid_error_diff");CHKERRQ(ierr);
// Set up GRID
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
//FIXME
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
//FIXME
PetscInt x_index = x_len/5;
bool printed = false;
PetscScalar **local_grid_arr;
DMDAVecGetArray(da, local_grid, &local_grid_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_grid_arr[j][i] = coords[j][i].y;
// FIXME
//if(i == x_index && printed == false) {
// PetscPrintf(PETSC_COMM_WORLD, "\nx_index: %i SHOULD BE 0.1 = % .5e\n", x_index, coords[j][x_index].x);
// printed = true;
//}
//local_grid_arr[j][i] = (.01*(coords[j][i].x * coords[j][i].x * coords[j][i].x) + (coords[j][i].y * coords[j][i].y * coords[j][i].y));
local_grid_arr[j][i] = cos(coords[j][i].x) * sin(coords[j][i].y);//sin(coords[j][i].x) + cos(coords[j][i].y);
}
}
DMDAVecRestoreArray(da, local_grid, &local_grid_arr);
ierr = DMLocalToGlobalBegin(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr);
// SET UP ACT_DIFF_X
ierr = DMCreateLocalVector(da, &local_act_diff_x);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr);
PetscScalar **local_act_diff_x_arr;
DMDAVecGetArray(da, local_act_diff_x, &local_act_diff_x_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_act_diff_x_arr[j][i] = coords[j][i].x;
local_act_diff_x_arr[j][i] = -sin(coords[j][i].x) * sin(coords[j][i].y);//cos(coords[j][i].x);
//local_act_diff_x_arr[j][i] = .01*(3 * coords[j][i].x * coords[j][i].x);
}
}
DMDAVecRestoreArray(da, local_act_diff_x, &local_act_diff_x_arr);
ierr = DMLocalToGlobalBegin(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr);
// SET UP ACT_DIFF_Y
ierr = DMCreateLocalVector(da, &local_act_diff_y);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr);
PetscScalar **local_act_diff_y_arr;
DMDAVecGetArray(da, local_act_diff_y, &local_act_diff_y_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
//local_act_diff_y_arr[j][i] = .01*(3 * coords[j][i].y * coords[j][i].y);
local_act_diff_y_arr[j][i] = cos(coords[j][i].y) * cos(coords[j][i].x);
}
}
DMDAVecRestoreArray(da, local_act_diff_y, &local_act_diff_y_arr);
ierr = DMLocalToGlobalBegin(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr);
t2 = MPI_Wtime();
ierr = Dy_2d(diff_y, grid, mult_y, da);CHKERRQ(ierr);
t3 = MPI_Wtime();
ierr = Dx_2d(diff_x, grid, mult_x, da);CHKERRQ(ierr);
t4 = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "Ny: %5i Spacing: % .5e Log of Spacing: % .5e ", y_len, mult_y, log2(mult_y)); // I used to have %15!
calculate_two_norm(grid_error_diff, diff_y, act_diff_y, num_grid_entries);
PetscPrintf(PETSC_COMM_WORLD, " Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x));
calculate_two_norm(grid_error_diff, diff_x, act_diff_x, num_grid_entries);
t5 = MPI_Wtime();
// writeVec(grid, "grid_file");
// writeVec(diff_x, "calc_diff_x_file");
// writeVec(diff_y, "calc_diff_y_file");
// writeVec(act_diff_x, "actual_diff_x_file");
// writeVec(act_diff_y, "actual_diff_y_file");
// Truncation Error Test!!!
//ierr = truncation_error(diff_x, mult_x, da);CHKERRQ(ierr);
// FIXME make sure all Vecs and DMs are being destroyed - go to other functions as well!
ierr = VecDestroy(&grid);CHKERRQ(ierr);
ierr = VecDestroy(&diff_y);CHKERRQ(ierr);
ierr = VecDestroy(&diff_x);CHKERRQ(ierr);
ierr = VecDestroy(&act_diff_y);CHKERRQ(ierr);
ierr = VecDestroy(&act_diff_x);CHKERRQ(ierr);
ierr = VecDestroy(&grid_error_diff);CHKERRQ(ierr);
ierr = VecDestroy(&local_grid);CHKERRQ(ierr);
ierr = VecDestroy(&local_act_diff_y);CHKERRQ(ierr);
ierr = VecDestroy(&local_act_diff_x);CHKERRQ(ierr);
//ierr = VecDestroy(&local_coords);CHKERRQ(ierr);
//ierr = DMDestroy(&cda);CHKERRQ(ierr);
ierr = DMDestroy(&da);CHKERRQ(ierr);
t6 = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "\nTime spent setting up and filling grid/actual derivative Vecs: % 8g\n", t2 - t1);
PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dy derivative: % 8g\n", t3 - t2);
PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dx derivative: % 8g\n", t4 - t3);
PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating norms: % 8g\n", t5 - t4);
PetscPrintf(PETSC_COMM_WORLD, "Total time for this iteration: % 8g\n\n", t6 - t1);
return ierr;
}
/* Function: calculate_Dxx_Dyy_2D
* -------------------------------------------
* Calculates both second derivatives in x and y for a 2-D grid.
* IMPORTANT: Depending on the global set at the top of this program,
* the function will either solve the second derivative WITH coefficient or WITHOUT.
*
* x_len - number of points in the x direction
* y_len - number of points in the y direction
* x_max - maximum value in the x direction
* x_min - minimum value in the x_direction
* y_max - maximum value in the y direction
* y_min - minimum value in the y direction
*/
PetscErrorCode calculate_Dxx_Dyy_2D(PetscInt x_len, PetscInt y_len, PetscScalar x_max, PetscScalar x_min, PetscScalar y_max, PetscScalar y_min) {
PetscErrorCode ierr = 0;
double t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0;
t1 = MPI_Wtime();
PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0,
grid_istart, grid_iend, diff_x_start, diff_x_end, diff_y_start, diff_y_end;
PetscScalar v = 0, mult_x = 0, mult_y = 0;
Vec grid = NULL, diff_x = NULL, diff_y = NULL, act_diff_x = NULL, act_diff_y = NULL, grid_error_diff = NULL, /* vectors */
local_coords = NULL, local_grid = NULL, local_act_diff_x = NULL, local_act_diff_y = NULL,
mu = NULL, local_mu = NULL, dxxmu = NULL, local_dxxmu = NULL, dyymu = NULL, local_dyymu = NULL;
// first row, global vectors | second row, local vectors | third row, mu
PetscInt num_grid_entries = (x_len) * (y_len); // total number of entries on the grid
mult_x = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction
mult_y = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction
DM da;
DM cda;
DMDACoor2d **coords; // 2D array containing x and y data members
// FIXME should I use DMDA_STENCIL_STAR?? DMDA Set Up
ierr = DMDACreate2d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE,
DMDA_STENCIL_BOX, x_len, y_len, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &da); CHKERRQ(ierr);
DMDASetUniformCoordinates(da, x_min, x_max, y_min, y_max, 0.0, 0.0);
DMGetCoordinateDM(da, &cda);
DMGetCoordinatesLocal(da, &local_coords);
DMDAVecGetArray(cda, local_coords, &coords);
DMDAGetCorners(cda, &mStart, &nStart, 0, &m, &n, 0);
ierr = DMCreateGlobalVector(da,&grid);
ierr = VecDuplicate(grid, &diff_x);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &diff_y);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &act_diff_x);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &act_diff_y);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &grid_error_diff);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &mu);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &dxxmu);CHKERRQ(ierr);
ierr = VecDuplicate(grid, &dyymu);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) grid, "global grid");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) diff_x, "diff_x");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) diff_y, "diff_y");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) act_diff_x, "act_diff_x");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) act_diff_y, "act_diff_y");CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) grid_error_diff, "grid_error_diff");CHKERRQ(ierr);
//FIXME
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
// Set up GRID
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
PetscScalar **local_grid_arr;
DMDAVecGetArray(da, local_grid, &local_grid_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_grid_arr[j][i] = coords[j][i].y;
// local_grid_arr[j][i] = (coords[j][i].x * coords[j][i].x * coords[j][i].x) + (coords[j][i].y * coords[j][i].y * coords[j][i].y);
local_grid_arr[j][i] = cos(coords[j][i].x) + sin(coords[j][i].y);
// PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_grid_arr[j][i]);
}
}
DMDAVecRestoreArray(da, local_grid, &local_grid_arr);
ierr = DMLocalToGlobalBegin(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr);
// SET UP ACT_DIFF_X
ierr = DMCreateLocalVector(da, &local_act_diff_x);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr);
PetscScalar **local_act_diff_x_arr;
DMDAVecGetArray(da, local_act_diff_x, &local_act_diff_x_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_act_diff_x_arr[j][i] = coords[j][i].x;
local_act_diff_x_arr[j][i] = -cos(coords[j][i].x);
// PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_act_diff_x_arr[j][i]);
// local_act_diff_x_arr[j][i] = (6 * coords[j][i].x);
}
}
DMDAVecRestoreArray(da, local_act_diff_x, &local_act_diff_x_arr);
ierr = DMLocalToGlobalBegin(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr);
// SET UP ACT_DIFF_Y
ierr = DMCreateLocalVector(da, &local_act_diff_y);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr);
PetscScalar **local_act_diff_y_arr;
DMDAVecGetArray(da, local_act_diff_y, &local_act_diff_y_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_act_diff_y_arr[j][i] = (6 * coords[j][i].y);
local_act_diff_y_arr[j][i] = -sin(coords[j][i].y);
}
}
DMDAVecRestoreArray(da, local_act_diff_y, &local_act_diff_y_arr);
ierr = DMLocalToGlobalBegin(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr);
// SET UP MU
ierr = DMCreateLocalVector(da, &local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
PetscScalar **local_mu_arr;
DMDAVecGetArray(da, local_mu, &local_mu_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_mu_arr[j][i] = sin(coords[j][i].x)*(sin(coords[j][i].y)) + 2;
//cos(coords[j][i].x + coords[j][i].y) + 4;
// local_mu_arr[j][i] = 1;
}
}
DMDAVecRestoreArray(da, local_mu, &local_mu_arr);
ierr = DMLocalToGlobalBegin(da, local_mu, INSERT_VALUES, mu);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_mu, INSERT_VALUES, mu);CHKERRQ(ierr);
// SET UP DxxMU
ierr = DMCreateLocalVector(da, &local_dxxmu);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr);
PetscScalar **local_dxxmu_arr;
DMDAVecGetArray(da, local_dxxmu, &local_dxxmu_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_dxxmu_arr[j][i] = 0;
//(-sin(coords[j][i].x + coords[j][i].y) * cos(coords[j][i].x)) +
//((cos(coords[j][i].x + coords[j][i].y) + 4) * (-sin(coords[j][i].x)));
// local_dxxmu_arr[j][i] = -sin(coords[j][i].x);
}
}
DMDAVecRestoreArray(da, local_dxxmu, &local_dxxmu_arr);
ierr = DMLocalToGlobalBegin(da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr);
// SET UP DyyMU
ierr = DMCreateLocalVector(da, &local_dyymu);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr);
PetscScalar **local_dyymu_arr;
DMDAVecGetArray(da, local_dyymu, &local_dyymu_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_dyymu_arr[j][i] = 0;
//(-sin(coords[j][i].x + coords[j][i].y) * (-sin(coords[j][i].y))) +
//((cos(coords[j][i].x + coords[j][i].y) + 4) * (-cos(coords[j][i].y)));
// local_dyymu_arr[j][i] = -cos(coords[j][i].y);
}
}
DMDAVecRestoreArray(da, local_dyymu, &local_dyymu_arr);
ierr = DMLocalToGlobalBegin(da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr);
// derivative calculations & error calculations
if(COEFFICIENT_SOLVE) {
t2 = MPI_Wtime();
ierr = Dmuyy_2d(diff_y, grid, mu, mult_y, da);CHKERRQ(ierr);
t3 = MPI_Wtime();
ierr = Dmuxx_2d(diff_x, grid, mu, mult_x, da);CHKERRQ(ierr);
t4 = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "Ny: %5i Spacing: % .5e Log of Spacing: % .5e ", y_len, mult_y, log2(mult_y)); // I used to have %15!
calculate_two_norm(grid_error_diff, diff_y, dyymu, num_grid_entries);
// PetscPrintf(PETSC_COMM_WORLD, "Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x));
PetscPrintf(PETSC_COMM_WORLD, " Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x));
calculate_two_norm(grid_error_diff, diff_x, dxxmu, num_grid_entries);
} else {
t2 = MPI_Wtime();
ierr = Dyy_2d(diff_y, grid, mult_y, da);CHKERRQ(ierr);
t3 = MPI_Wtime();
ierr = Dxx_2d(diff_x, grid, mult_x, da);CHKERRQ(ierr);
t4 = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "Ny: %5i Spacing: % .5e Log of Spacing: % .5e ", y_len, mult_y, log2(mult_y)); // I used to have %15!
calculate_two_norm(grid_error_diff, diff_y, act_diff_y, num_grid_entries);
//PetscPrintf(PETSC_COMM_WORLD, "Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x));
PetscPrintf(PETSC_COMM_WORLD, " Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x));
calculate_two_norm(grid_error_diff, diff_x, act_diff_x, num_grid_entries);
}
t5 = MPI_Wtime();
// writeVec(grid, "grid_file");
// writeVec(diff_x, "calc_diff_x_file");
// writeVec(diff_y, "calc_diff_y_file");
// writeVec(act_diff_x, "actual_diff_x_file");
// writeVec(act_diff_y, "actual_diff_y_file");
// FIXME make sure all Vecs and DMs are being destroyed - go to other functions as well!
ierr = VecDestroy(&grid);CHKERRQ(ierr);
ierr = VecDestroy(&diff_y);CHKERRQ(ierr);
ierr = VecDestroy(&diff_x);CHKERRQ(ierr);
ierr = VecDestroy(&act_diff_y);CHKERRQ(ierr);
ierr = VecDestroy(&act_diff_x);CHKERRQ(ierr);
ierr = VecDestroy(&grid_error_diff);CHKERRQ(ierr);
ierr = VecDestroy(&local_grid);CHKERRQ(ierr);
ierr = VecDestroy(&local_act_diff_y);CHKERRQ(ierr);
ierr = VecDestroy(&local_act_diff_x);CHKERRQ(ierr);
ierr = VecDestroy(&mu);CHKERRQ(ierr);
ierr = VecDestroy(&dxxmu);CHKERRQ(ierr);
ierr = VecDestroy(&dyymu);CHKERRQ(ierr);
ierr = VecDestroy(&local_mu);CHKERRQ(ierr);
ierr = VecDestroy(&local_dxxmu);CHKERRQ(ierr);
ierr = VecDestroy(&local_dyymu);CHKERRQ(ierr);
//ierr = DMDestroy(&cda);CHKERRQ(ierr);
ierr = DMDestroy(&da);CHKERRQ(ierr);
t6 = MPI_Wtime();
PetscPrintf(PETSC_COMM_WORLD, "\nTime spent setting up and filling grid/actual derivative Vecs: % 8g\n", t2 - t1);
PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dy derivative: % 8g\n", t3 - t2);
PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dx derivative: % 8g\n", t4 - t3);
PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating norms: % 8g\n", t5 - t4);
PetscPrintf(PETSC_COMM_WORLD, "Total time for this iteration: % 8g\n\n", t6 - t1);
return ierr;
}
/* Function: MMSTest()
* -------------------
*
*/
PetscErrorCode MMSTest() {
PetscErrorCode ierr = 0;
PetscInt n = STARTING_GRID_SPACING, min = MIN_GRID_POINT, max = MAX_GRID_POINT, x_len = NUM_X_PTS, y_len = NUM_Y_PTS;
PetscScalar x_min = X_MIN, x_max = X_MAX, y_max = Y_MAX, y_min = Y_MIN;
assert(n > 2);
PetscPrintf(PETSC_COMM_WORLD, "1-D 1ST DERIVATIVES\n");
for(int i = 0; i < NUM_GRID_SPACE_CALCULATIONS; i++) {
PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1);
ierr = calculate_Dx_1d(n, min, max);CHKERRQ(ierr);
n = ((n - 1) * 2) + 1;
}
PetscPrintf(PETSC_COMM_WORLD, "1-D 2ND DERIVATIVES\n");
for(int i = 0; i < NUM_2ND_GRID_SPACE_CALCULATIONS; i++) {
PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1);
ierr = calculate_Dxx_1d(n, min, max);CHKERRQ(ierr);
n = ((n - 1) * 2) + 1;
}
PetscPrintf(PETSC_COMM_WORLD, "2-D 1ST DERIVATIVES\n");
assert(x_len > 3);
assert(y_len > 3);
for(int i = 0; i < NUM_2D_GRID_SPACE_CALCULATIONS; i++) {
PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1);
calculate_Dx_Dy_2D(x_len, y_len, x_max, x_min, y_max, y_min);
x_len = ((x_len - 1) * 2) + 1;
y_len = ((y_len - 1) * 2) + 1;
}
PetscPrintf(PETSC_COMM_WORLD, "2-D 2ND DERIVATIVES\n");
x_len = NUM_X_PTS;
y_len = NUM_Y_PTS;
x_min = X_MIN;
x_max = X_MAX;
y_max = Y_MAX;
y_min = Y_MIN;
assert(x_len > 3);
assert(y_len > 3);
for(int i = 0; i < NUM_2D_2ND_GRID_SPACE_CALCULATIONS; i++) {
PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1);
calculate_Dxx_Dyy_2D(x_len, y_len, x_max, x_min, y_max, y_min);
x_len = ((x_len - 1) * 2) + 1;
y_len = ((y_len - 1) * 2) + 1;
}
PetscPrintf(PETSC_COMM_WORLD, "\n");
return ierr;
}
/* Function: setRHS_R
* ------------------
*
*/
PetscErrorCode setRHS_R(Vec &RHS, const Vec &r, const PetscScalar &h_11,
const PetscScalar alpha_R, const DM &da) {
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL, ristart, riend;
PetscScalar v;
DMDAGetInfo(da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);
ierr = VecGetOwnershipRange(r,&ristart,&riend);CHKERRQ(ierr);
for(i = ristart; i < riend; i++) {
ierr = VecGetValues(r,1,&i,&v);CHKERRQ(ierr);
v = v * h_11 * alpha_R;
ierr = VecSetValues(r,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(r);CHKERRQ(ierr);
ierr = VecAssemblyEnd(r);CHKERRQ(ierr);
//ierr = VecView(r,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// VecScatter routine! IMPORTANT!
VecScatter scatter; // scatter context
IS from,to; // index sets that define the scatter
int idx_from[M], idx_to[M];
for(i = 0; i < M; i++) {
idx_from[i] = i;
}
for(i = 0; i < M; i++) {
idx_to[i] = i + ((N-1) * M);
}
AO ao;
DMDAGetAO(da,&ao);
AOApplicationToPetsc(ao,M,idx_to);
ISCreateGeneral(PETSC_COMM_SELF,M,idx_from,PETSC_COPY_VALUES,&from);
ISCreateGeneral(PETSC_COMM_SELF,M,idx_to,PETSC_COPY_VALUES,&to);
VecScatterCreate(r,from,RHS,to,&scatter); // gx = source vector, gy = destination vector
VecScatterBegin(scatter,r,RHS,INSERT_VALUES,SCATTER_FORWARD);
VecScatterEnd(scatter,r,RHS,INSERT_VALUES,SCATTER_FORWARD);
//VecView(RHS,PETSC_VIEWER_STDOUT_WORLD);
ISDestroy(&from);
ISDestroy(&to);
VecScatterDestroy(&scatter);
// PRINT OUT RHS
/*
Vec local_RHS;
ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
PetscScalar **local_RHS_arr;
DMDAVecGetArray(da, local_RHS, &local_RHS_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]);
}
}
DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr);
ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
VecDestroy(&local_RHS);
*/
return ierr;
}
/* Function: setRHS_B
* ------------------
*
*/
PetscErrorCode setRHS_B(Vec &RHS, const Vec &b, const PetscScalar &h_11,
const PetscScalar alpha_B, const DM &da) {
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL, bistart, biend;
PetscScalar v;
DMDAGetInfo(da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);
ierr = VecGetOwnershipRange(b,&bistart,&biend);CHKERRQ(ierr);
for(i = bistart; i < biend; i++) {
ierr = VecGetValues(b,1,&i,&v);CHKERRQ(ierr);
v = v * h_11 * alpha_B;
ierr = VecSetValues(b,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(b);CHKERRQ(ierr);
ierr = VecAssemblyEnd(b);CHKERRQ(ierr);
//ierr = VecView(b,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// VecScatter routine! IMPORTANT!
VecScatter scatter; // scatter context
IS from,to; // index sets that define the scatter
int idx_from[N], idx_to[N];
for(i = 0; i < N; i++) {
idx_from[i] = i;
}
for(i = 0; i < N; i++) {
idx_to[i] = i * M + (M-1);
}
AO ao;
DMDAGetAO(da,&ao);
AOApplicationToPetsc(ao,N,idx_to);
ISCreateGeneral(PETSC_COMM_SELF,N,idx_from,PETSC_COPY_VALUES,&from);
ISCreateGeneral(PETSC_COMM_SELF,N,idx_to,PETSC_COPY_VALUES,&to);
VecScatterCreate(b,from,RHS,to,&scatter); // gx = source vector, gy = destination vector
VecScatterBegin(scatter,b,RHS,INSERT_VALUES,SCATTER_FORWARD);
VecScatterEnd(scatter,b,RHS,INSERT_VALUES,SCATTER_FORWARD);
//VecView(RHS,PETSC_VIEWER_STDOUT_WORLD);
ISDestroy(&from);
ISDestroy(&to);
VecScatterDestroy(&scatter);
// PRINT OUT RHS
/*
Vec local_RHS;
ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
PetscScalar **local_RHS_arr;
DMDAVecGetArray(da, local_RHS, &local_RHS_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]);
}
}
DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr);
ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
VecDestroy(&local_RHS);
*/
return ierr;
}
/* Function: setRHS_T
* --------------
*
*/
PetscErrorCode setRHS_T(Vec &RHS, const Vec &g, const PetscScalar &h_11,
const PetscScalar alpha_T, const DM &da) {
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL, gistart, giend;
PetscScalar v;
DMDAGetInfo(da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);
ierr = VecGetOwnershipRange(g,&gistart,&giend);CHKERRQ(ierr);
for(i = gistart; i < giend; i++) {
ierr = VecGetValues(g,1,&i,&v);CHKERRQ(ierr);
v = (v + i) * (1/h_11) * alpha_T;
//v = (double) i;
ierr = VecSetValues(g,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(g);CHKERRQ(ierr);
ierr = VecAssemblyEnd(g);CHKERRQ(ierr);
//ierr = VecView(g,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// VecScatter routine! IMPORTANT!
VecScatter scatter; // scatter context
IS from,to; // index sets that define the scatter
//int idx_from[] = {0,1,2,3,4}, idx_to[] = {0,11,22,33,44};
int idx_from[N], idx_to[N];
for(i = 0; i < N; i++) {
idx_from[i] = i;
}
for(i = 0; i < N; i++) {
idx_to[i] = i * M;
}
AO ao;
DMDAGetAO(da,&ao);
AOApplicationToPetsc(ao,N,idx_to);
ISCreateGeneral(PETSC_COMM_SELF,N,idx_from,PETSC_COPY_VALUES,&from);
ISCreateGeneral(PETSC_COMM_SELF,N,idx_to,PETSC_COPY_VALUES,&to);
VecScatterCreate(g,from,RHS,to,&scatter); // gx = source vector, gy = destination vector
VecScatterBegin(scatter,g,RHS,INSERT_VALUES,SCATTER_FORWARD);
VecScatterEnd(scatter,g,RHS,INSERT_VALUES,SCATTER_FORWARD);
//VecView(RHS,PETSC_VIEWER_STDOUT_WORLD);
ISDestroy(&from);
ISDestroy(&to);
VecScatterDestroy(&scatter);
// PRINT OUT RHS
/*
Vec local_RHS;
ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
PetscScalar **local_RHS_arr;
DMDAVecGetArray(da, local_RHS, &local_RHS_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]);
}
}
DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr);
ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
VecDestroy(&local_RHS);
*/
return ierr;
}
/* Function: Dy_2d_Boundary
* ----------------------------------
* 1st derivative solve in the y-direction for 2-D.
*
* diff_y - the output Vec (it will hold the calculated derivative on the boundary in y-direction)
* grid - the input Vec (it holds the function values to draw from)
* dy - the spacing between each point in the y-direction
* da - DMDA object
*/
PetscErrorCode Dy_2d_Boundary(Vec &diff_y, Vec &grid, PetscScalar dy, DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M, N;
DMDAGetInfo(da,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_y, local_grid;
PetscScalar** local_diff_y_arr;
PetscScalar** local_grid_arr;
ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (j > 0 && j < N - 1 && i > 0 && i < M - 1) { local_diff_y_arr[j][i] = 0; }
else if (j == 0) { local_diff_y_arr[j][i] = -(-1.5 * local_grid_arr[0][i] + 2.0 * local_grid_arr[1][i] - 0.5 * local_grid_arr[2][i])/ dy; }
else if (j == N - 1) { local_diff_y_arr[j][i] = (0.5 * local_grid_arr[N-3][i] - 2.0 *
local_grid_arr[N-2][i] + 1.5 * local_grid_arr[N-1][i]) / dy; }
}
}
ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr);
VecDestroy(&local_diff_y);
VecDestroy(&local_grid);
return ierr;
}
/* Function: Dx_2d_Boundary
* ----------------------------------
*
* diff_x - the output Vec (it will hold the calculated derivative on the boundary in x-direction)
* grid - the input Vec (it holds the function values to draw from)
* dx - the spacing between each point in the x-direction
* da - DMDA object
*/
PetscErrorCode Dx_2d_Boundary(Vec &diff_x, Vec &grid, PetscScalar dx, DM &da) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M, N;
DMDAGetInfo(da,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_diff_x, local_grid;
PetscScalar** local_diff_x_arr;
PetscScalar** local_grid_arr;
ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr);
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr);
ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (i > 0 && i < M - 1 && j > 0 && j < N - 1) {local_diff_x_arr[j][i] = 0; }
else if (i == 0) { local_diff_x_arr[j][i] = -(-1.5 * local_grid_arr[j][0] +
2.0 * local_grid_arr[j][1] - 0.5 * local_grid_arr[j][2])/ dx; }
else if (i == M - 1) { local_diff_x_arr[j][i] = (0.5 * local_grid_arr[j][M-3] -
2.0 * local_grid_arr[j][M-2] + 1.5 * local_grid_arr[j][M-1]) / dx; }
}
}
ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr);
VecDestroy(&local_diff_x);
VecDestroy(&local_grid);
return ierr;
}
PetscErrorCode multiplyByHinvx(Vec &out, Vec &in, PetscScalar h, PetscInt order, AppCtx* ctx) {
PetscErrorCode ierr = 0;
ierr = VecSet(out, 0);CHKERRQ(ierr);
if(order == 2) {
PetscInt m, n, mStart, nStart, j, i, M, N;
DMDAGetInfo(ctx->da,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_out, local_in;
PetscScalar** local_out_arr;
PetscScalar** local_in_arr;
ierr = DMCreateLocalVector(ctx->da, &local_out);CHKERRQ(ierr);
ierr = DMCreateLocalVector(ctx->da, &local_in);CHKERRQ(ierr);
ierr = DMDAVecGetArray(ctx->da, local_out, &local_out_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx->da, in, INSERT_VALUES, local_in);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx->da, in, INSERT_VALUES, local_in);CHKERRQ(ierr);
ierr = DMDAVecGetArray(ctx->da, local_in, &local_in_arr); CHKERRQ(ierr);
ierr = DMDAGetCorners(ctx->da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
if (j > 0 && j < N - 1)
local_out_arr[j][i] = 1/h * local_in_arr[j][i];
else
local_out_arr[j][i] = 2/h * local_in_arr[j][i];
/*
else if (i == 0) {
//local_out_arr[j][i] = -(-1.5 * local_in_arr[j][0] +
//2.0 * local_in_arr[j][1] - 0.5 * local_in_arr[j][2])/ h; }
else if (i == M - 1) { local_out_arr[j][i] = (0.5 * local_in_arr[j][M-3] -
2.0 * local_in_arr[j][M-2] + 1.5 * local_in_arr[j][M-1]) / h; }*/
}
}
ierr = DMDAVecRestoreArray(ctx->da, local_out, &local_out_arr);CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(ctx->da, local_in, &local_in_arr);CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(ctx->da, local_out, INSERT_VALUES, out);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx->da, local_out, INSERT_VALUES, out);CHKERRQ(ierr);
VecDestroy(&local_out);
VecDestroy(&local_in);
return ierr;
} else if (order == 4) {
}
return -1;
}
PetscErrorCode multiplyBy_BSx_IyT_s(Vec &ADisp2, Vec& mu, Vec &fx, PetscScalar h) {
//, string& Stype, string& Btype) {
PetscErrorCode ierr = 0;
return ierr;
}
PetscErrorCode SetLeftToMult(Vec& ADisp1, Vec& mu, Vec& temp, AppCtx* ctx) {
PetscErrorCode ierr = 0;
PetscInt m, n, mStart, nStart, j, i, M, N;
DMDAGetInfo(ctx->da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
Vec local_ADisp1, local_mu, local_temp;
PetscScalar **local_ADisp1_arr;
PetscScalar** local_mu_arr;
PetscScalar** local_temp_arr;
ierr = DMCreateLocalVector(ctx->da, &local_ADisp1);CHKERRQ(ierr);
ierr = DMCreateLocalVector(ctx->da, &local_mu);CHKERRQ(ierr);
ierr = DMCreateLocalVector(ctx->da, &local_temp);CHKERRQ(ierr);
DMDAGetCorners(ctx->da, &mStart, &nStart, 0, &m, &n, 0);
//rank
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
ierr = DMGlobalToLocalBegin(ctx->da, ADisp1, INSERT_VALUES, local_ADisp1);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx->da, ADisp1, INSERT_VALUES, local_ADisp1);CHKERRQ(ierr);
ierr = DMDAVecGetArray(ctx->da, local_ADisp1, &local_ADisp1_arr);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx->da, temp, INSERT_VALUES, local_temp);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx->da, temp, INSERT_VALUES, local_temp);CHKERRQ(ierr);
ierr = DMDAVecGetArray(ctx->da, local_temp, &local_temp_arr); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx->da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx->da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMDAVecGetArray(ctx->da, local_mu, &local_mu_arr); CHKERRQ(ierr);
j = nStart + n - 1;
for (i = mStart; i < mStart + m; i++) {
local_ADisp1_arr[j][i] = local_mu_arr[j][i] * local_temp_arr[j][i];
}
DMDAVecRestoreArray(ctx->da, local_ADisp1, &local_ADisp1_arr);
ierr = DMLocalToGlobalBegin(ctx->da, local_ADisp1, INSERT_VALUES, ADisp1);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx->da, local_ADisp1, INSERT_VALUES, ADisp1);CHKERRQ(ierr);
VecDestroy(&local_ADisp1);
VecDestroy(&local_mu);
VecDestroy(&local_temp);
return ierr;
}
PetscErrorCode setRHS_L(Vec &RHS, const Vec &fx, const PetscScalar &h_11,
const PetscScalar alpha_L, const DM &da) {
PetscErrorCode ierr = 0;
/*
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
Vec temp;
Vec rhs_disp1;
ierr = VecDuplicate(fx, &rhs_disp1);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &temp);CHKERRQ(ierr);
ierr = VecSet(rhs_disp1, 0);CHKERRQ(ierr);
ierr = multiplyByHinvx(temp, fx, da, 2, ctx);CHKERRQ(ierr);
Vec rhs_disp2;
ierr = VecDuplicate(fx, &rhs_disp2);CHKERRQ(ierr);
ierr = VecSet(rhs_disp2, 0);CHKERRQ(ierr);
*/
return ierr;
}
/* Function: MyMatMult
* -------------------
*
*
*/
PetscErrorCode MyMatMult(Mat A, Vec fx, Vec ans) {
PetscErrorCode ierr = 0;
void *ptr;
AppCtx *ctx;
MatShellGetContext(A,&ptr);
ctx = (AppCtx*)ptr;
// Below is what the multiplication operation should do!
Vec sum = NULL, dmuxx = NULL, dmuyy = NULL;
ierr = VecDuplicate(fx, &sum);
ierr = VecDuplicate(fx, &dmuxx);
ierr = VecDuplicate(fx, &dmuyy);
ierr = Dmuxx_2d(dmuxx, fx, ctx->mu, ctx->dx_spacing, ctx->da);CHKERRQ(ierr);
//writeVec(dmuxx, "Uxx");
ierr = Dmuyy_2d(dmuyy, fx, ctx->mu, ctx->dy_spacing, ctx->da);CHKERRQ(ierr);
//writeVec(dmuyy, "Uxx");
PetscScalar one = 1.0;
ierr = VecAXPY(dmuyy, one, dmuxx);CHKERRQ(ierr);
ierr = VecCopy(dmuyy, ans);CHKERRQ(ierr);
Vec Dx, Dy, DxDyBoundary;
ierr = VecDuplicate(fx, &Dx);
ierr = VecDuplicate(fx, &Dy);
ierr = VecDuplicate(fx, &DxDyBoundary);
ierr = Dx_2d_Boundary(Dx, fx, ctx->dx_spacing, ctx->da);CHKERRQ(ierr);
ierr = Dy_2d_Boundary(Dy, fx, ctx->dx_spacing, ctx->da);CHKERRQ(ierr);
ierr = VecAXPY(Dy, one, Dx);CHKERRQ(ierr);
ierr = VecCopy(Dy, DxDyBoundary);CHKERRQ(ierr);
ierr = VecAXPY(dmuyy, one, DxDyBoundary);CHKERRQ(ierr);
ierr = VecCopy(dmuyy, ans);CHKERRQ(ierr);
// BOUNDARY CONDITIONS
Vec out;
ierr = VecDuplicate(fx, &out);CHKERRQ(ierr);
ierr = VecSet(out, 0);CHKERRQ(ierr);
Vec temp;
ierr = VecDuplicate(fx, &temp);CHKERRQ(ierr);
ierr = VecSet(temp, 0);CHKERRQ(ierr);
// DISPLACEMENT
// LEFT BOUNDARY
Vec ADisp1;
ierr = VecDuplicate(fx, &ADisp1);CHKERRQ(ierr);
ierr = VecSet(ADisp1, 0);CHKERRQ(ierr);
ierr = multiplyByHinvx(temp, fx, ctx->dx_spacing, ctx->order, ctx);CHKERRQ(ierr);
ierr = SetLeftToMult(ADisp1, ctx->mu, temp, ctx);CHKERRQ(ierr);
Vec ADisp2;
ierr = VecDuplicate(fx, &ADisp1);CHKERRQ(ierr);
ierr = VecSet(ADisp1, 0);CHKERRQ(ierr);
//string Stype = ""; // = ctx.Stype
//string Btype = "";
ierr = multiplyBy_BSx_IyT_s(ADisp2, ctx->mu, fx, ctx->dx_spacing);//, Stype, Btype);
// RIGHT BOUNDARY
// TRACTION
// TOP BOUNDARY
// BOTTOM BOUNDARY
//print
/*
PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL;
DMDAGetInfo(ctx->da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DMDAGetCorners(ctx->da, &mStart, &nStart, 0, &m, &n, 0);
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
Vec DxDyBoundary_print;
ierr = DMCreateLocalVector(ctx->da, &DxDyBoundary_print);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx->da, DxDyBoundary, INSERT_VALUES, DxDyBoundary_print);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx->da, DxDyBoundary, INSERT_VALUES, DxDyBoundary_print);CHKERRQ(ierr);
PetscScalar **DxDyBoundary_print_arr;
DMDAVecGetArray(ctx->da, DxDyBoundary_print, &DxDyBoundary_print_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, DxDyBoundary_print_arr[j][i]);
}
}
DMDAVecRestoreArray(ctx->da, DxDyBoundary_print, &DxDyBoundary_print_arr);
ierr = DMLocalToGlobalBegin(ctx->da, DxDyBoundary_print, INSERT_VALUES, DxDyBoundary);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx->da, DxDyBoundary_print, INSERT_VALUES, DxDyBoundary);CHKERRQ(ierr);
VecDestroy(&DxDyBoundary_print);
*/
//writeVec(DxDyBoundary, "DxDyBoundary");
//endprint
//FIXME!!!! DO WE ADD THE BOUNDARY TO EXISTING VALUES FROM THE DERIVATIVE, OR DO WE ZERO
// THEM OUT BEFORE ADDING???
//calculate RHS with 1st derivative on borders
//Vec RHS = NULL;
//ierr = VecDuplicate(fx, &RHS);
//PetscScalar h_11 = 1;
//PetscScalar alpha_R = 2;
//setRHS_R(RHS, ans, h_11,
// alpha_R, ctx->da);
//setRHS_L(RHS, ans, h_11,
// alpha_R, ctx->da);
//setRHS_T(RHS, ans, h_11,
// alpha_R, ctx->da);
//setRHS_B(RHS, ans, h_11,
// alpha_R, ctx->da);
ierr = VecDestroy(&Dx);CHKERRQ(ierr);
ierr = VecDestroy(&Dy);CHKERRQ(ierr);
ierr = VecDestroy(&DxDyBoundary);CHKERRQ(ierr);
ierr = VecDestroy(&sum);CHKERRQ(ierr);
ierr = VecDestroy(&dmuxx);CHKERRQ(ierr);
ierr = VecDestroy(&dmuyy);CHKERRQ(ierr);
return ierr;
}
PetscErrorCode testMyMatMult() {
PetscErrorCode ierr = 0;
AppCtx ctx;
PetscScalar x_len = NUM_X_PTS, y_len = NUM_Y_PTS;
PetscScalar x_min = X_MIN, x_max = X_MAX, y_max = Y_MAX, y_min = Y_MIN;
for(int i = 0; i < NUM_2D_2ND_GRID_SPACE_CALCULATIONS; i++) {
x_len = ((x_len - 1) * 2) + 1;
y_len = ((y_len - 1) * 2) + 1;
}
PetscPrintf(PETSC_COMM_WORLD, "Test for MyMatMult\n");
PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0,
fx_istart, fx_iend, dx_start, dx_end, dy_start, dy_end;
PetscScalar v = 0;
Vec fx = NULL, dx = NULL, dy = NULL, a_dx = NULL, a_dy = NULL, fx_err = NULL, /* vectors */
local_coords = NULL, local_fx = NULL, local_a_dx = NULL, local_a_dy = NULL,
/* mu = NULL, */ local_mu = NULL, dxxmu = NULL, local_dxxmu = NULL, dyymu = NULL, local_dyymu = NULL,
ans = NULL, a_ans = NULL;
// first row, global vecs, second row, local vecs, third row, mu and 2nd derivatives
// last row, answer vector
PetscInt num_entries = (x_len) * (y_len); //total number of entries on the grid
ctx.dx_spacing = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction
ctx.dy_spacing = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction
ctx.n_x = x_len;
ctx.n_y = y_len;
ctx.alphaDx = -4/ctx.dx_spacing;
ctx.alphaDy = -4/ctx.dy_spacing;
ctx.alphaT = -1;
ctx.beta = 1;
ctx.order = 2;
DMDACoor2d **coords;
DMDACreate2d(PETSC_COMM_WORLD, DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE,
DMDA_STENCIL_BOX, ctx.n_x, ctx.n_y, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &ctx.da);
DMDASetUniformCoordinates(ctx.da, x_min, x_max, y_min, y_max, 0.0, 0.0);
DMGetCoordinateDM(ctx.da, &ctx.cda);
DMGetCoordinatesLocal(ctx.da, &local_coords);
DMDAVecGetArray(ctx.cda, local_coords, &coords);
DMDAGetCorners(ctx.cda, &mStart, &nStart, 0, &m, &n, 0);
// allows us to have information about the DMDA
DMDALocalInfo info;
ierr = DMDAGetLocalInfo(ctx.da, &info);
ierr = DMCreateGlobalVector(ctx.da, &fx);
ierr = VecDuplicate(fx, &dx);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &dy);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &a_dx);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &a_dy);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &fx_err);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &ctx.mu);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &dxxmu);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &dyymu);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &ans);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &a_ans);CHKERRQ(ierr);
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
// Set up fx to pull values from
ierr = DMCreateLocalVector(ctx.da, &local_fx);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr);
PetscScalar **local_fx_arr;
DMDAVecGetArray(ctx.da, local_fx, &local_fx_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
//PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_fx_arr[j][i] = coords[j][i].y;
// local_fx_arr[j][i] = (coords[j][i].x * coords[j][i].x * coords[j][i].x) + (coords[j][i].y * coords[j][i].y * coords[j][i].y);
// local_fx_arr[j][i] = coords[j][i].x;
local_fx_arr[j][i] = MMS_uA(coords[j][i].x, coords[j][i].y);
// local_fx_arr[j][i] = cos(coords[j][i].x) * sin(coords[j][i].y);
// PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_grid_arr[j][i]);
}
}
DMDAVecRestoreArray(ctx.da, local_fx, &local_fx_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr);
//set up a_dx
ierr = DMCreateLocalVector(ctx.da, &local_a_dx);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, a_dx, INSERT_VALUES, local_a_dx);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, a_dx, INSERT_VALUES, local_a_dx);CHKERRQ(ierr);
PetscScalar **local_a_dx_arr;
DMDAVecGetArray(ctx.da, local_a_dx, &local_a_dx_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_act_diff_x_arr[j][i] = coords[j][i].x;
local_a_dx_arr[j][i] = MMS_uA_dx(coords[j][i].x, coords[j][i].y);
//local_a_dx_arr[j][i] = -sin(coords[j][i].x);
// PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_act_diff_x_arr[j][i]);
// local_act_diff_x_arr[j][i] = (6 * coords[j][i].x);
}
}
DMDAVecRestoreArray(ctx.da, local_a_dx, &local_a_dx_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_a_dx, INSERT_VALUES, a_dx);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_a_dx, INSERT_VALUES, a_dx);CHKERRQ(ierr);
// SET UP ACT_DIFF_Y
ierr = DMCreateLocalVector(ctx.da, &local_a_dy);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, a_dy, INSERT_VALUES, local_a_dy);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, a_dy, INSERT_VALUES, local_a_dy);CHKERRQ(ierr);
PetscScalar **local_a_dy_arr;
DMDAVecGetArray(ctx.da, local_a_dy, &local_a_dy_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
// PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y);
// local_act_diff_y_arr[j][i] = (6 * coords[j][i].y);
//local_a_dy_arr[j][i] = -cos(coords[j][i].y);
local_a_dy_arr[j][i] = MMS_uA_dy(coords[j][i].x, coords[j][i].y);
}
}
DMDAVecRestoreArray(ctx.da, local_a_dy, &local_a_dy_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_a_dy, INSERT_VALUES, a_dy);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_a_dy, INSERT_VALUES, a_dy);CHKERRQ(ierr);
// SET UP MU
ierr = DMCreateLocalVector(ctx.da, &local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, ctx.mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, ctx.mu, INSERT_VALUES, local_mu);CHKERRQ(ierr);
PetscScalar **local_mu_arr;
DMDAVecGetArray(ctx.da, local_mu, &local_mu_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_mu_arr[j][i] = MMS_mu(coords[j][i].x, coords[j][i].y);
//local_mu_arr[j][i] = sin(coords[j][i].x) * sin(coords[j][i].y) + 2;
// local_mu_arr[j][i] = 1;
}
}
DMDAVecRestoreArray(ctx.da, local_mu, &local_mu_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_mu, INSERT_VALUES, ctx.mu);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_mu, INSERT_VALUES, ctx.mu);CHKERRQ(ierr);
// SET UP DxxMU
ierr = DMCreateLocalVector(ctx.da, &local_dxxmu);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr);
PetscScalar **local_dxxmu_arr;
DMDAVecGetArray(ctx.da, local_dxxmu, &local_dxxmu_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_dxxmu_arr[j][i] = MMS_uA_dmuxx(coords[j][i].x, coords[j][i].y);
//local_dxxmu_arr[j][i] = (-sin(coords[j][i].x + coords[j][i].y) * cos(coords[j][i].x)) +
// ((cos(coords[j][i].x + coords[j][i].y) + 4) * (-sin(coords[j][i].x)));
// local_dxxmu_arr[j][i] = -sin(coords[j][i].x);
}
}
DMDAVecRestoreArray(ctx.da, local_dxxmu, &local_dxxmu_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr);
// SET UP DyyMU
ierr = DMCreateLocalVector(ctx.da, &local_dyymu);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr);
PetscScalar **local_dyymu_arr;
DMDAVecGetArray(ctx.da, local_dyymu, &local_dyymu_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_dyymu_arr[j][i] = MMS_uA_dmuyy(coords[j][i].x, coords[j][i].y);
//local_dyymu_arr[j][i] = (-sin(coords[j][i].x + coords[j][i].y) * (-sin(coords[j][i].y))) +
// ((cos(coords[j][i].x + coords[j][i].y) + 4) * (-cos(coords[j][i].y)));
// local_dyymu_arr[j][i] = -cos(coords[j][i].y);
}
}
DMDAVecRestoreArray(ctx.da, local_dyymu, &local_dyymu_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr);
//writeVec(fx,"fx");
//Vec dfx;
//ierr = VecDuplicate(fx, &dfx);
//ierr = Dx_2d(dfx, fx, ctx.dx_spacing, ctx.da);
//writeVec(dfx, "dfx");
PetscInt vec_size = NULL;
VecGetLocalSize(fx, &vec_size);
// set up linear solve context (matrices, etc.)
Mat H_Shell;
//MatCreateAIJ(MPI_COMM_WORLD,info.xm,info.ym,info.mx,info.my,7,NULL,3,NULL,&(user.H));
MatCreateShell(PETSC_COMM_WORLD, vec_size, vec_size,
num_entries, num_entries,(void*)&ctx,&H_Shell);
MatShellSetOperation(H_Shell,MATOP_MULT,
(void(*)(void))MyMatMult);
MatMult(H_Shell, fx, ans);
//writeVec(ans, "ans");
// calculate analytical answer
ierr = VecCopy(a_dy, a_ans);CHKERRQ(ierr);
PetscScalar one = 1.0;
ierr = VecAXPY(a_ans, one, a_dx);
calculate_two_norm(fx_err, ans, a_ans, num_entries);
MatDestroy(&H_Shell);
VecDestroy(&fx);
VecDestroy(&dx);
VecDestroy(&dy);
VecDestroy(&a_dx);
VecDestroy(&a_dy);
VecDestroy(&fx_err);
//VecDestroy(&local_coords);
VecDestroy(&local_fx);
VecDestroy(&local_a_dx);
VecDestroy(&local_a_dy);
VecDestroy(&local_mu);
VecDestroy(&dxxmu);
VecDestroy(&local_dxxmu);
VecDestroy(&dyymu);
VecDestroy(&local_dyymu);
VecDestroy(&ans);
VecDestroy(&a_ans);
VecDestroy(&ctx.mu);
DMDestroy(&ctx.da);
PetscPrintf(PETSC_COMM_WORLD, "\n");
return ierr;
}
/* Function: Solve_Linear_Equation
* -------------------------------
*
*/
PetscErrorCode Solve_Linear_Equation() {
PetscErrorCode ierr = 0;
PetscInt num_x_pts = NUM_X_PTS, num_y_pts = NUM_Y_PTS;
PetscScalar x_min = X_MINIMUM, x_max = X_MAXIMUM, y_max = Y_MAXIMUM, y_min = Y_MINIMUM;
PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0;
PetscScalar v = 0, mult_x = 0, mult_y = 0, alpha_T = -1, alpha_B = -2, alpha_L = -3, alpha_R = -4, h_11 = 2;
Vec grid = NULL, RHS = NULL, g = NULL, b = NULL, l = NULL, r = NULL,
local_grid = NULL, local_RHS = NULL, local_coords = NULL;
PetscInt num_grid_entries = (num_x_pts) * (num_y_pts); // total number of entries on the grid
mult_x = ((PetscReal)(x_max - x_min))/(num_x_pts - 1); // spacing in the x direction
mult_y = ((PetscReal)(y_max - y_min))/(num_y_pts - 1); // spacing in the y direction
DM da;
DM cda;
DMDACoor2d **coords; // 2D array containing x and y data members
ierr = DMDACreate2d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE,
DMDA_STENCIL_BOX, num_x_pts, num_y_pts, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &da); CHKERRQ(ierr);
DMDASetUniformCoordinates(da, x_min, x_max, y_min, y_max, 0.0, 0.0);
DMGetCoordinateDM(da, &cda);
DMGetCoordinatesLocal(da, &local_coords);
DMDAVecGetArray(cda, local_coords, &coords);
DMDAGetCorners(cda, &mStart, &nStart, 0, &m, &n, 0);
ierr = DMCreateGlobalVector(da,&grid);
ierr = VecDuplicate(grid, &RHS);CHKERRQ(ierr);
//FIXME
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
// FILL GRID
ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr);
PetscScalar **local_grid_arr;
DMDAVecGetArray(da, local_grid, &local_grid_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_grid_arr[j][i] = (coords[j][i].x);
}
}
DMDAVecRestoreArray(da, local_grid, &local_grid_arr);
ierr = DMLocalToGlobalBegin(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr);
//FILL RHS
ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr);
PetscScalar **local_RHS_arr;
DMDAVecGetArray(da, local_RHS, &local_RHS_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_RHS_arr[j][i] = 0;
// PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]);
}
}
DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr);
ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr);
// FILL g
VecCreate(PETSC_COMM_WORLD,&g);
VecSetSizes(g,PETSC_DECIDE,num_y_pts);
VecSetFromOptions(g);
PetscObjectSetName((PetscObject) g, "g");
VecSet(g,1.0);
// FILL b
VecCreate(PETSC_COMM_WORLD,&b);
VecSetSizes(b,PETSC_DECIDE,num_y_pts);
VecSetFromOptions(b);
PetscObjectSetName((PetscObject) b, "b");
VecSet(b,1.0);
// FILL l
VecCreate(PETSC_COMM_WORLD,&l);
VecSetSizes(l,PETSC_DECIDE,num_x_pts);
VecSetFromOptions(l);
PetscObjectSetName((PetscObject) l, "l");
VecSet(l,1.0);
// FILL r
VecCreate(PETSC_COMM_WORLD,&r);
VecSetSizes(r,PETSC_DECIDE,num_x_pts);
VecSetFromOptions(r);
PetscObjectSetName((PetscObject) r, "r");
VecSet(r,1.0);
ierr = setRHS_T(RHS, g, h_11, alpha_T, da);CHKERRQ(ierr);
ierr = setRHS_B(RHS, b, h_11, alpha_B, da);CHKERRQ(ierr);
ierr = setRHS_L(RHS, l, h_11, alpha_L, da);CHKERRQ(ierr);
ierr = setRHS_R(RHS, r, h_11, alpha_R, da);CHKERRQ(ierr);
// PRINT RHS
/*
Vec local_RHS_print;
ierr = DMCreateLocalVector(da, &local_RHS_print);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS_print);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS_print);CHKERRQ(ierr);
PetscScalar **local_RHS_print_arr;
DMDAVecGetArray(da, local_RHS_print, &local_RHS_print_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_print_arr[j][i]);
}
}
DMDAVecRestoreArray(da, local_RHS_print, &local_RHS_print_arr);
ierr = DMLocalToGlobalBegin(da, local_RHS_print, INSERT_VALUES, RHS);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(da, local_RHS_print, INSERT_VALUES, RHS);CHKERRQ(ierr);
VecDestroy(&local_RHS_print);
// writeVec(RHS, "RHS");
*/
VecDestroy(&grid);
VecDestroy(&RHS);
VecDestroy(&g);
VecDestroy(&b);
VecDestroy(&l);
VecDestroy(&r);
VecDestroy(&local_grid);
VecDestroy(&local_RHS);
DMDestroy(&da);
DMDestroy(&cda);
return ierr;
}
PetscErrorCode testMultiplyByHinvx() {
PetscErrorCode ierr = 0;
AppCtx ctx;
PetscScalar x_len = NUM_X_PTS, y_len = NUM_Y_PTS;
PetscScalar x_min = X_MIN, x_max = X_MAX, y_max = Y_MAX, y_min = Y_MIN;
Vec fx = NULL, dx = NULL, /* vectors */ temp,
local_coords = NULL, local_fx = NULL;
for(int i = 0; i < NUM_2D_2ND_GRID_SPACE_CALCULATIONS; i++) {
x_len = ((x_len - 1) * 2) + 1;
y_len = ((y_len - 1) * 2) + 1;
}
PetscInt num_entries = (x_len) * (y_len); //total number of entries on the grid
ctx.dx_spacing = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction
ctx.dy_spacing = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction
ctx.n_x = x_len;
ctx.n_y = y_len;
ctx.alphaDx = -4/ctx.dx_spacing;
ctx.alphaDy = -4/ctx.dy_spacing;
ctx.alphaT = -1;
ctx.beta = 1;
ctx.order = 2;
DMDACoor2d **coords;
DMDACreate2d(PETSC_COMM_WORLD, DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE,
DMDA_STENCIL_BOX, ctx.n_x, ctx.n_y, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &ctx.da);
PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0,
fx_istart, fx_iend, dx_start, dx_end, dy_start, dy_end;
PetscScalar v = 0;
ierr = DMCreateGlobalVector(ctx.da, &fx);CHKERRQ(ierr);
ierr = VecDuplicate(fx, &temp);CHKERRQ(ierr);
DMDASetUniformCoordinates(ctx.da, x_min, x_max, y_min, y_max, 0.0, 0.0);
DMGetCoordinateDM(ctx.da, &ctx.cda);
DMGetCoordinatesLocal(ctx.da, &local_coords);
DMDAVecGetArray(ctx.cda, local_coords, &coords);
DMDAGetCorners(ctx.cda, &mStart, &nStart, 0, &m, &n, 0);
// allows us to have information about the DMDA
DMDALocalInfo info;
ierr = DMDAGetLocalInfo(ctx.da, &info);
PetscMPIInt rank;
MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
// Set up fx to pull values from
ierr = DMCreateLocalVector(ctx.da, &local_fx);CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr);
PetscScalar **local_fx_arr;
DMDAVecGetArray(ctx.da, local_fx, &local_fx_arr);
for (j = nStart; j < nStart + n; j++) {
for (i = mStart; i < mStart + m; i++) {
local_fx_arr[j][i] = MMS_uA(coords[j][i].x, coords[j][i].y);
}
}
DMDAVecRestoreArray(ctx.da, local_fx, &local_fx_arr);
ierr = DMLocalToGlobalBegin(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr);
ierr = multiplyByHinvx(temp, fx, ctx.dx_spacing, ctx.order, &ctx);CHKERRQ(ierr);
writeVec(temp, "Hinvx_C");
return ierr;
}
/* Function: main
* --------------
*
*/
int main(int argc,char **argv)
{
PetscErrorCode ierr = 0;
PetscInitialize(&argc,&argv,(char*)0,NULL);
//ierr = MMSTest();CHKERRQ(ierr);
//ierr = Solve_Linear_Equation();CHKERRQ(ierr);
//testMyMatMult();
testMultiplyByHinvx();
PetscFinalize();
return ierr;
}
| 42.986425 | 154 | 0.65533 |
kali-allison
|
28e4dd08d57b29ea49ce0da075a25972d028a369
| 599 |
cpp
|
C++
|
ares/msx/cartridge/slot.cpp
|
moon-chilled/Ares
|
909fb098c292f8336d0502dc677050312d8b5c81
|
[
"0BSD"
] | 7 |
2020-07-25T11:44:39.000Z
|
2021-01-29T13:21:31.000Z
|
ares/msx/cartridge/slot.cpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | null | null | null |
ares/msx/cartridge/slot.cpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | 1 |
2021-03-22T16:15:30.000Z
|
2021-03-22T16:15:30.000Z
|
CartridgeSlot cartridgeSlot{"Cartridge Slot"};
CartridgeSlot expansionSlot{"Expansion Slot"};
CartridgeSlot::CartridgeSlot(string name) : name(name) {
}
auto CartridgeSlot::load(Node::Object parent) -> void {
port = parent->append<Node::Port>(name);
port->setFamily(interface->name());
port->setType("Cartridge");
port->setAllocate([&](auto name) { return cartridge.allocate(port); });
port->setConnect([&] { return cartridge.connect(); });
port->setDisconnect([&] { return cartridge.disconnect(); });
}
auto CartridgeSlot::unload() -> void {
cartridge.disconnect();
port = {};
}
| 29.95 | 73 | 0.692821 |
moon-chilled
|
28e68ae27d59696ba3a543ed75abea88f0146efa
| 7,627 |
cpp
|
C++
|
src/FirebaseCommunication.cpp
|
floryt/floryt-credential-provider
|
c6fba1aa791e192927a6f7a53a7db1b6cd398e14
|
[
"Apache-2.0"
] | 5 |
2017-05-10T15:06:43.000Z
|
2017-11-25T09:49:27.000Z
|
src/FirebaseCommunication.cpp
|
floryt/floryt-credential-provider
|
c6fba1aa791e192927a6f7a53a7db1b6cd398e14
|
[
"Apache-2.0"
] | 14 |
2017-05-02T21:43:37.000Z
|
2017-06-17T11:44:36.000Z
|
src/FirebaseCommunication.cpp
|
floryt/floryt-credential-provider
|
c6fba1aa791e192927a6f7a53a7db1b6cd398e14
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <windows.h>
#include <thread>
#include "FirebaseCommunication.h"
#include <atlbase.h>
#include <atlconv.h>
#include <vector>
FirebaseCommunication::FirebaseCommunication()
{
http = new HTTPclient();
cv = false;
}
EXIT_TYPE FirebaseCommunication::TryToConnect(LPCWSTR username)
{
//post - "ping" to check if server is a avalible
EXIT_TYPE to_return;
dbugLog::log_write("TryToConnect", "attempting to connect");
//------------------------------ping------------------------------
//setting the data
std::string answer = "_"; //so if the request failed we will se "_" in the log
//***********getting text from config*********
std::string firebase_function = config::get_val("GETcheckConnectionFooName");
//********************************************
char* data = _strdup(http->createJson(username)); //"{\"username\":\"Steven\",\"computerUID\":\"123456789\"}"; //from const char* to char*
std::string tempd(data);
dbugLog::log_write("AuthenticationPost", "created json: " + tempd + "length: " + std::to_string(tempd.length()));
if (tempd.length() > 0) //to prevent exception
{
if (data[0] == ' ') //fixing bug
{
data[0] = '{';
dbugLog::log_write("AuthenticationPost", "[FIXED] fixed json: " + std::string(data));
}
}
else
{
dbugLog::log_write("AuthenticationPost", "[ERROR] json is empty");
}
bool isError = false;
//initial CV
cv = false;
//starting thread
std::thread tempt(&FirebaseCommunication::ThreadWait, this, firebase_function, data, std::ref(answer), std::ref(isError));
tempt.detach();
//waiting for response
while (cv == false)
{
dbugLog::log_write("TryToConnect", "no response yet");
Sleep(1000);
}
//---after reciving response
std::string ans(answer);
dbugLog::log_write("TryToConnect", "recived: " + ans);
if (isError)
{
dbugLog::log_write("TryToConnect", "could'nt connect");
to_return = cant_connect_to_server;
}
else
{
//processig the data
if (strcmp(answer.c_str(), "OK") == 0)
{
dbugLog::log_write("TryToConnect", "connection succeeded");
to_return = connection_to_server_succeeded;
}
else
{
dbugLog::log_write("TryToConnect", "connection failed");
to_return = cant_connect_to_server;
}
}
return to_return;
}
EXIT_TYPE FirebaseCommunication::AuthenticationPostMock(LPCWSTR username, LPCWSTR* recived_message, POST_STEP step)
{
*recived_message = L"my message";
return authentication_succeeded;
}
EXIT_TYPE FirebaseCommunication::TryToConnectMock()
{
return connection_to_server_succeeded;
}
//works for all types of requests we need here
EXIT_TYPE FirebaseCommunication::AuthenticationPost(LPCWSTR username, LPCWSTR* recived_message, POST_STEP step) //recived_message: a pointer to enter the message from admin
{
//post with json
EXIT_TYPE to_return;
(*recived_message) = L"_";
//no need of config - log purpose only.
std::string mes = "no step";
if (step == obtain_user_identity)
{
mes = "obtainIdentityVerification";
}
else if (step == obtain_admin_permission)
{
mes = "obtainAdminPermission";
}
dbugLog::log_write("AuthenticationPost", "attempting to Authenticate: step " + mes);
//------------------------------post------------------------------
//setting the data
std::string answer = "__";
cv = false;
std::string firebase_function = "";
if (step == obtain_user_identity)
{
//***********getting text from config*********
firebase_function = config::get_val("POSTobtainUserIdentityFooName");
//********************************************
}
else if (step == obtain_admin_permission)
{
//***********getting text from config*********
firebase_function = config::get_val("POSTobtainAdminPermissionFooName");
//********************************************
}
bool isError = false;
char* data = _strdup(http->createJson(username)); //"{\"username\":\"Steven\",\"computerUID\":\"123456789\"}"; //from const char* to char*
std::string tempd(data);
dbugLog::log_write("AuthenticationPost", "created json: " + tempd + "length: "+ std::to_string(tempd.length()));
if (tempd.length() > 0) //to prevent exception
{
if (data[0] == ' ') //fixing bug
{
data[0] = '{';
dbugLog::log_write("AuthenticationPost", "[FIXED] fixed json: " + std::string(data));
}
}
else
{
dbugLog::log_write("AuthenticationPost", "[ERROR] json is empty");
}
//initial CV
cv = false;
//starting thread
std::thread tempt(&FirebaseCommunication::ThreadWait, this, firebase_function, strdup(data), std::ref(answer), std::ref(isError));
tempt.detach();
//waiting for response
while (cv == false)
{
dbugLog::log_write("AuthenticationPost", "no response yet");
Sleep(1000);
}
//---after reciving response
std::string ans(answer);
dbugLog::log_write("AuthenticationPost", "got response: " + ans);
if (isError) //it could be a timeout for example
{
if (strcmp((answer.substr(0, 11)).c_str(), "12002") == 0)
{
to_return = time_out;
dbugLog::log_write("AuthenticationPost", "detedcet timeout");
}
else
{
to_return = bad_request; //it's not a bad request but it will be handled the same way
dbugLog::log_write("AuthenticationPost", "detedcet some error in request");
}
}
else
{
//processig the data
if (strcmp((answer.substr(0, 11)).c_str(), "Bad Request") == 0)
{
dbugLog::log_write("AuthenticationPost", "connection failed: Bad request");
to_return = bad_request;
}
else //we got an actual data
{
std::string* message = new std::string();
(*message) = "";
bool isAccess = http->parseJSON((char*)ans.c_str(), message);
//--parsing the message
/*std::wstring stemp = s2ws(*message);
LPCWSTR result = stemp.c_str();*/
if (message->size() == 2) //bug fix - message is ""
{
(*message) = ":)"; //recived no messgae. TODO- update field in struct
dbugLog::log_write("AuthenticationPost", "detected message bug - recived empty message");
}
std::wstring stemp = std::wstring(message->begin(), message->end()); //CASTING: string to lpcwstr
LPCWSTR result = stemp.c_str();
(*recived_message) = result;
dbugLog::log_write("AuthenticationPost", "message from admin: " + (*message));
if (isAccess) //access = true
{
dbugLog::log_write("AuthenticationPost", "step succeeded");
to_return = authentication_succeeded;
}
else
{
dbugLog::log_write("AuthenticationPost", "access denied");
to_return = access_denied;
}
}
}
return to_return;
}
std::wstring FirebaseCommunication::s2ws(const std::string& s) //TODO: move to helpers
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
FirebaseCommunication::~FirebaseCommunication()
{
dbugLog::log_write("~FirebaseCommunication", "distractor");
//delete _log;
delete http;
}
void FirebaseCommunication::ThreadWait(std::string req_type, char* data, std::string &packet_buffer, bool& is_Error)
{
char* ans;
bool isError = false;
//if (req_type == "/connectivity_check") //TODO: send struct and return struct
//{
// ans = http->GET(isError, _strdup(req_type.c_str())); //CASTING: string to char*
// std::string str(ans);
// packet_buffer = ans;
//}
std::vector<char> cstr(req_type.c_str(), req_type.c_str() + req_type.size() + 1);
ans = http->POST(data, isError, _strdup(req_type.c_str()));
std::string str(ans);
packet_buffer = ans;
is_Error = isError;
cv = true;
}
| 25.680135 | 172 | 0.65373 |
floryt
|
28e8e12c7fd4e9a32413e89bc05840b200afbfb8
| 2,939 |
hpp
|
C++
|
include/conjunctive.hpp
|
taboege/libpropcalc
|
b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6
|
[
"Artistic-2.0"
] | 1 |
2021-06-01T01:08:56.000Z
|
2021-06-01T01:08:56.000Z
|
include/conjunctive.hpp
|
taboege/libpropcalc
|
b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6
|
[
"Artistic-2.0"
] | null | null | null |
include/conjunctive.hpp
|
taboege/libpropcalc
|
b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6
|
[
"Artistic-2.0"
] | null | null | null |
/*
* conjunctive.hpp - Clause and Conjunctive
*
* Copyright (C) 2019-2020 Tobias Boege
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Artistic License 2.0
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Artistic License 2.0 for more details.
*/
#ifndef PROPCALC_CONJUNCTIVE_HPP
#define PROPCALC_CONJUNCTIVE_HPP
#include <propcalc/varmap.hpp>
#include <propcalc/stream.hpp>
#include <propcalc/assignment.hpp>
namespace Propcalc {
/**
* A clause represents a collection of literals, that is a mapping of
* variables to signs. A variable mapping to true is a positive literal,
* one mapping to false a negative literal.
*
* Put another way, the value a variable maps to is the assignment to
* that variable which would satisfy the clause.
*/
class Clause : public VarMap {
public:
/** Create a dummy clause on no variables. */
Clause(void) : VarMap() { }
/** Create the any-false clause on the given variables. */
Clause(std::vector<VarRef> vars) : VarMap(vars) { }
/** Initialize the mapping with the given data. */
Clause(std::initializer_list<std::pair<VarRef, bool>> il) : VarMap(il) { }
/** Initialize the clause from a VarMap object. */
Clause(VarMap&& vm) : VarMap(vm) { }
/** Flip all signs in the clause. */
Clause operator~(void) const {
Clause neg(order);
for (auto& v : order)
neg[v] = !vmap.at(v);
return neg;
}
/**
* Evaluate the Clause on an Assignment. This uses the natural partial
* assignment semantics, that is when a variable in the assignment is
* not mentioned in the clause, this fact is ignored. Such a variable
* cannot make the clause true.
*
* In particular an empty clause always yields false (the identity
* element with respect to disjunction).
*/
bool eval(const Assignment& assign) const {
for (auto v : assign.vars()) {
if (exists(v) && (*this)[v] == assign[v])
return true;
}
return false;
}
};
namespace {
[[maybe_unused]]
std::ostream& operator<<(std::ostream& os, const Clause& cl) {
os << "{ ";
for (auto& v : cl.vars())
os << (cl[v] ? "" : "-") << v->name << " ";
return os << "}";
}
}
class Conjunctive : public Stream<Clause> {
public:
/**
* Evaluate the conjunction of clauses enumerated. If there is no
* clause, returns true (the identity element with respect to
* conjunction), as all clauses are satisfied.
*
* If you want to evaluate the Conjunctive multiple times, it must
* be put into caching mode before the first clause is iterated..
*/
bool eval(const Assignment& assign) {
for (auto cl : *this) {
if (!cl.eval(assign))
return false;
}
return true;
}
};
}
#endif /* PROPCALC_CONJUNCTIVE_HPP */
| 29.686869 | 76 | 0.668935 |
taboege
|
28ea17e10746395d1ce39607211a0cdb94805391
| 4,221 |
cpp
|
C++
|
core/3d/CCFrustum.cpp
|
DelinWorks/adxe
|
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
|
[
"MIT"
] | 76 |
2021-05-20T12:27:10.000Z
|
2022-03-23T15:27:42.000Z
|
core/3d/CCFrustum.cpp
|
DelinWorks/adxe
|
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
|
[
"MIT"
] | 171 |
2021-05-18T11:07:25.000Z
|
2022-03-29T20:53:27.000Z
|
core/3d/CCFrustum.cpp
|
DelinWorks/adxe
|
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
|
[
"MIT"
] | 42 |
2021-05-18T10:05:06.000Z
|
2022-03-22T05:40:56.000Z
|
/****************************************************************************
Copyright (c) 2014-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://adxeproject.github.io/
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 "3d/CCFrustum.h"
#include "2d/CCCamera.h"
NS_CC_BEGIN
bool Frustum::initFrustum(const Camera* camera)
{
_initialized = true;
createPlane(camera);
return true;
}
bool Frustum::isOutOfFrustum(const AABB& aabb) const
{
if (_initialized)
{
Vec3 point;
int plane = _clipZ ? 6 : 4;
for (int i = 0; i < plane; i++)
{
const Vec3& normal = _plane[i].getNormal();
point.x = normal.x < 0 ? aabb._max.x : aabb._min.x;
point.y = normal.y < 0 ? aabb._max.y : aabb._min.y;
point.z = normal.z < 0 ? aabb._max.z : aabb._min.z;
if (_plane[i].getSide(point) == PointSide::FRONT_PLANE)
return true;
}
}
return false;
}
bool Frustum::isOutOfFrustum(const OBB& obb) const
{
if (_initialized)
{
Vec3 point;
int plane = _clipZ ? 6 : 4;
Vec3 obbExtentX = obb._xAxis * obb._extents.x;
Vec3 obbExtentY = obb._yAxis * obb._extents.y;
Vec3 obbExtentZ = obb._zAxis * obb._extents.z;
for (int i = 0; i < plane; i++)
{
const Vec3& normal = _plane[i].getNormal();
point = obb._center;
point = normal.dot(obb._xAxis) > 0 ? point - obbExtentX : point + obbExtentX;
point = normal.dot(obb._yAxis) > 0 ? point - obbExtentY : point + obbExtentY;
point = normal.dot(obb._zAxis) > 0 ? point - obbExtentZ : point + obbExtentZ;
if (_plane[i].getSide(point) == PointSide::FRONT_PLANE)
return true;
}
}
return false;
}
void Frustum::createPlane(const Camera* camera)
{
const Mat4& mat = camera->getViewProjectionMatrix();
// ref http://www.lighthouse3d.com/tutorials/view-frustum-culling/clip-space-approach-extracting-the-planes/
// extract frustum plane
_plane[0].initPlane(-Vec3(mat.m[3] + mat.m[0], mat.m[7] + mat.m[4], mat.m[11] + mat.m[8]),
(mat.m[15] + mat.m[12])); // left
_plane[1].initPlane(-Vec3(mat.m[3] - mat.m[0], mat.m[7] - mat.m[4], mat.m[11] - mat.m[8]),
(mat.m[15] - mat.m[12])); // right
_plane[2].initPlane(-Vec3(mat.m[3] + mat.m[1], mat.m[7] + mat.m[5], mat.m[11] + mat.m[9]),
(mat.m[15] + mat.m[13])); // bottom
_plane[3].initPlane(-Vec3(mat.m[3] - mat.m[1], mat.m[7] - mat.m[5], mat.m[11] - mat.m[9]),
(mat.m[15] - mat.m[13])); // top
_plane[4].initPlane(-Vec3(mat.m[3] + mat.m[2], mat.m[7] + mat.m[6], mat.m[11] + mat.m[10]),
(mat.m[15] + mat.m[14])); // near
_plane[5].initPlane(-Vec3(mat.m[3] - mat.m[2], mat.m[7] - mat.m[6], mat.m[11] - mat.m[10]),
(mat.m[15] - mat.m[14])); // far
}
NS_CC_END
| 40.980583 | 112 | 0.57285 |
DelinWorks
|
28ec2f8060965f1042a092c1eee0b20d6470cf2d
| 5,576 |
hpp
|
C++
|
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/python/to_python_value.hpp
|
sotaoverride/backup
|
ca53a10b72295387ef4948a9289cb78ab70bc449
|
[
"Apache-2.0"
] | null | null | null |
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/python/to_python_value.hpp
|
sotaoverride/backup
|
ca53a10b72295387ef4948a9289cb78ab70bc449
|
[
"Apache-2.0"
] | null | null | null |
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/python/to_python_value.hpp
|
sotaoverride/backup
|
ca53a10b72295387ef4948a9289cb78ab70bc449
|
[
"Apache-2.0"
] | null | null | null |
// Copyright David Abrahams 2002.
// Copyright Stefan Seefeld 2016.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef boost_python_to_python_value_hpp_
#define boost_python_to_python_value_hpp_
#include <boost/mpl/if.hpp>
#include <boost/mpl/or.hpp>
#include <boost/python/converter/builtin_converters.hpp>
#include <boost/python/converter/object_manager.hpp>
#include <boost/python/converter/registered.hpp>
#include <boost/python/converter/registry.hpp>
#include <boost/python/converter/shared_ptr_to_python.hpp>
#include <boost/python/detail/prefix.hpp>
#include <boost/python/detail/type_traits.hpp>
#include <boost/python/detail/value_arg.hpp>
#include <boost/python/detail/value_is_shared_ptr.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/refcount.hpp>
#include <boost/python/tag.hpp>
namespace boost
{
namespace python
{
namespace detail
{
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
template <bool is_const_ref>
struct object_manager_get_pytype
{
template <class U>
static PyTypeObject const* get(U& (*)() = 0)
{
return converter::object_manager_traits<U>::get_pytype();
}
};
template <>
struct object_manager_get_pytype<true>
{
template <class U>
static PyTypeObject const* get(U const& (*)() = 0)
{
return converter::object_manager_traits<U>::get_pytype();
}
};
#endif
template <class T>
struct object_manager_to_python_value
{
typedef typename value_arg<T>::type argument_type;
PyObject* operator()(argument_type) const;
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
typedef boost::mpl::bool_<is_handle<T>::value> is_t_handle;
typedef boost::detail::indirect_traits::is_reference_to_const<T> is_t_const;
PyTypeObject const* get_pytype() const
{
return get_pytype_aux((is_t_handle*)0);
}
inline static PyTypeObject const* get_pytype_aux(mpl::true_*)
{
return converter::object_manager_traits<T>::get_pytype();
}
inline static PyTypeObject const* get_pytype_aux(mpl::false_*)
{
return object_manager_get_pytype<is_t_const::value>::get((T(*)())0);
}
#endif
// This information helps make_getter() decide whether to try to
// return an internal reference or not. I don't like it much,
// but it will have to serve for now.
BOOST_STATIC_CONSTANT(bool, uses_registry = false);
};
template <class T>
struct registry_to_python_value
{
typedef typename value_arg<T>::type argument_type;
PyObject* operator()(argument_type) const;
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
PyTypeObject const* get_pytype() const
{
return converter::registered<T>::converters.to_python_target_type();
}
#endif
// This information helps make_getter() decide whether to try to
// return an internal reference or not. I don't like it much,
// but it will have to serve for now.
BOOST_STATIC_CONSTANT(bool, uses_registry = true);
};
template <class T>
struct shared_ptr_to_python_value
{
typedef typename value_arg<T>::type argument_type;
PyObject* operator()(argument_type) const;
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
PyTypeObject const* get_pytype() const
{
return get_pytype((boost::type<argument_type>*)0);
}
#endif
// This information helps make_getter() decide whether to try to
// return an internal reference or not. I don't like it much,
// but it will have to serve for now.
BOOST_STATIC_CONSTANT(bool, uses_registry = false);
private:
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
template <class U>
PyTypeObject const* get_pytype(boost::type<shared_ptr<U>&>*) const
{
return converter::registered<U>::converters.to_python_target_type();
}
template <class U>
PyTypeObject const* get_pytype(boost::type<const shared_ptr<U>&>*) const
{
return converter::registered<U>::converters.to_python_target_type();
}
#if !defined(BOOST_NO_CXX11_SMART_PTR)
template <class U>
PyTypeObject const* get_pytype(boost::type<std::shared_ptr<U>&>*) const
{
return converter::registered<U>::converters.to_python_target_type();
}
template <class U>
PyTypeObject const*
get_pytype(boost::type<const std::shared_ptr<U>&>*) const
{
return converter::registered<U>::converters.to_python_target_type();
}
#endif
#endif
};
} // namespace detail
template <class T>
struct to_python_value
: mpl::if_<detail::value_is_shared_ptr<T>,
detail::shared_ptr_to_python_value<T>,
typename mpl::if_<
mpl::or_<converter::is_object_manager<T>,
converter::is_reference_to_object_manager<T>>,
detail::object_manager_to_python_value<T>,
detail::registry_to_python_value<T>>::type>::type
{
};
//
// implementation
//
namespace detail
{
template <class T>
inline PyObject* registry_to_python_value<T>::operator()(argument_type x) const
{
return converter::registered<argument_type>::converters.to_python(&x);
}
template <class T>
inline PyObject* object_manager_to_python_value<T>::
operator()(argument_type x) const
{
return python::upcast<PyObject>(
python::xincref(get_managed_object(x, tag)));
}
template <class T>
inline PyObject* shared_ptr_to_python_value<T>::
operator()(argument_type x) const
{
return converter::shared_ptr_to_python(x);
}
} // namespace detail
} // namespace python
} // namespace boost
#endif
| 28.44898 | 80 | 0.713056 |
sotaoverride
|
28ee2971e314ad6b1d93446ca500b09d146aa587
| 6,151 |
cpp
|
C++
|
taichi/ir/type_factory.cpp
|
gaoxinge/taichi
|
86d403f071b8505858763d4712b37cd71b89db91
|
[
"MIT"
] | 1 |
2020-11-10T07:17:01.000Z
|
2020-11-10T07:17:01.000Z
|
taichi/ir/type_factory.cpp
|
gaoxinge/taichi
|
86d403f071b8505858763d4712b37cd71b89db91
|
[
"MIT"
] | 1 |
2020-08-24T05:18:43.000Z
|
2020-08-24T05:18:43.000Z
|
taichi/ir/type_factory.cpp
|
gaoxinge/taichi
|
86d403f071b8505858763d4712b37cd71b89db91
|
[
"MIT"
] | null | null | null |
#include "taichi/ir/type_factory.h"
#include "taichi/ir/type_utils.h"
TLANG_NAMESPACE_BEGIN
TypeFactory &TypeFactory::get_instance() {
static TypeFactory *type_factory = new TypeFactory;
return *type_factory;
}
TypeFactory::TypeFactory() {
}
Type *TypeFactory::get_primitive_type(PrimitiveTypeID id) {
std::lock_guard<std::mutex> _(mut_);
if (primitive_types_.find(id) == primitive_types_.end()) {
primitive_types_[id] = std::make_unique<PrimitiveType>(id);
}
return primitive_types_[id].get();
}
Type *TypeFactory::get_tensor_type(std::vector<int> shape, Type *element) {
auto encode = [](const std::vector<int> &shape) -> std::string {
std::string s;
for (int i = 0; i < (int)shape.size(); ++i)
s += fmt::format(i == 0 ? "{}" : "_{}", std::to_string(shape[i]));
return s;
};
auto key = std::make_pair(encode(shape), element);
if (tensor_types_.find(key) == tensor_types_.end()) {
tensor_types_[key] = std::make_unique<TensorType>(shape, element);
}
return tensor_types_[key].get();
}
Type *TypeFactory::get_pointer_type(Type *element, bool is_bit_pointer) {
auto key = std::make_pair(element, is_bit_pointer);
if (pointer_types_.find(key) == pointer_types_.end()) {
pointer_types_[key] =
std::make_unique<PointerType>(element, is_bit_pointer);
}
return pointer_types_[key].get();
}
Type *TypeFactory::get_custom_int_type(int num_bits,
bool is_signed,
Type *compute_type) {
auto key = std::make_tuple(num_bits, is_signed, compute_type);
if (custom_int_types_.find(key) == custom_int_types_.end()) {
custom_int_types_[key] =
std::make_unique<CustomIntType>(num_bits, is_signed, compute_type);
}
return custom_int_types_[key].get();
}
Type *TypeFactory::get_custom_float_type(Type *digits_type,
Type *exponent_type,
Type *compute_type,
float64 scale) {
auto key = std::make_tuple(digits_type, exponent_type, compute_type, scale);
if (custom_float_types_.find(key) == custom_float_types_.end()) {
custom_float_types_[key] = std::make_unique<CustomFloatType>(
digits_type, exponent_type, compute_type, scale);
}
return custom_float_types_[key].get();
}
Type *TypeFactory::get_bit_struct_type(PrimitiveType *physical_type,
std::vector<Type *> member_types,
std::vector<int> member_bit_offsets) {
bit_struct_types_.push_back(std::make_unique<BitStructType>(
physical_type, member_types, member_bit_offsets));
return bit_struct_types_.back().get();
}
Type *TypeFactory::get_bit_array_type(PrimitiveType *physical_type,
Type *element_type,
int num_elements) {
bit_array_types_.push_back(std::make_unique<BitArrayType>(
physical_type, element_type, num_elements));
return bit_array_types_.back().get();
}
PrimitiveType *TypeFactory::get_primitive_int_type(int bits, bool is_signed) {
Type *int_type;
if (bits == 8) {
int_type = get_primitive_type(PrimitiveTypeID::i8);
} else if (bits == 16) {
int_type = get_primitive_type(PrimitiveTypeID::i16);
} else if (bits == 32) {
int_type = get_primitive_type(PrimitiveTypeID::i32);
} else if (bits == 64) {
int_type = get_primitive_type(PrimitiveTypeID::i64);
} else {
TI_ERROR("No primitive int type has {} bits", bits);
}
if (!is_signed) {
int_type = to_unsigned(DataType(int_type));
}
return int_type->cast<PrimitiveType>();
}
PrimitiveType *TypeFactory::get_primitive_real_type(int bits) {
Type *real_type;
if (bits == 16) {
real_type = get_primitive_type(PrimitiveTypeID::f16);
} else if (bits == 32) {
real_type = get_primitive_type(PrimitiveTypeID::f32);
} else if (bits == 64) {
real_type = get_primitive_type(PrimitiveTypeID::f64);
} else {
TI_ERROR("No primitive real type has {} bits", bits);
}
return real_type->cast<PrimitiveType>();
}
DataType TypeFactory::create_vector_or_scalar_type(int width,
DataType element,
bool element_is_pointer) {
TI_ASSERT(width == 1);
if (element_is_pointer) {
return TypeFactory::get_instance().get_pointer_type(element);
} else {
return element;
}
}
DataType TypeFactory::create_tensor_type(std::vector<int> shape,
DataType element) {
return TypeFactory::get_instance().get_tensor_type(shape, element);
}
namespace {
static bool compare_types(DataType x, DataType y) {
// Is the first type "bigger" than the second type?
if (is_real(x) != is_real(y)) {
// One is real, the other is integral.
// real > integral
return is_real(x);
} else {
if (is_real(x) && is_real(y)) {
// Both are real
return data_type_bits(x) > data_type_bits(y);
} else {
// Both are integral
auto x_bits = data_type_bits(x);
auto y_bits = data_type_bits(y);
if (x_bits != y_bits) {
return x_bits > y_bits;
} else {
// Same number of bits. Unsigned > signed
auto x_unsigned = !is_signed(x);
auto y_unsigned = !is_signed(y);
return x_unsigned > y_unsigned;
}
}
}
}
static DataType to_primitive_type(DataType d) {
if (d->is<PointerType>()) {
d = d->as<PointerType>()->get_pointee_type();
TI_WARN("promoted_type got a pointer input.");
}
if (d->is<TensorType>()) {
d = d->as<TensorType>()->get_element_type();
TI_WARN("promoted_type got a tensor input.");
}
auto primitive = d->cast<PrimitiveType>();
TI_ASSERT_INFO(primitive, "Failed to get primitive type from {}",
d->to_string());
return primitive;
};
} // namespace
DataType promoted_type(DataType x, DataType y) {
if (compare_types(to_primitive_type(x), to_primitive_type(y)))
return x;
else
return y;
}
TLANG_NAMESPACE_END
| 32.544974 | 78 | 0.635994 |
gaoxinge
|
28f640562ad99b13585c57fbf97d8b1e249ecc96
| 12,024 |
cpp
|
C++
|
src/ledger/LedgerTxnClaimableBalanceSQL.cpp
|
V5DF8/stellar-core
|
3fb2dc6bea41ed9160313f856e57451897f68cd9
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 10 |
2017-09-23T08:25:40.000Z
|
2022-01-04T10:28:02.000Z
|
src/ledger/LedgerTxnClaimableBalanceSQL.cpp
|
V5DF8/stellar-core
|
3fb2dc6bea41ed9160313f856e57451897f68cd9
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 1 |
2021-11-10T00:25:10.000Z
|
2021-11-10T02:50:40.000Z
|
src/ledger/LedgerTxnClaimableBalanceSQL.cpp
|
V5DF8/stellar-core
|
3fb2dc6bea41ed9160313f856e57451897f68cd9
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 2 |
2021-10-21T20:34:04.000Z
|
2021-11-21T14:13:54.000Z
|
// Copyright 2020 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "ledger/LedgerTxnImpl.h"
#include "util/GlobalChecks.h"
#include "util/types.h"
namespace stellar
{
std::shared_ptr<LedgerEntry const>
LedgerTxnRoot::Impl::loadClaimableBalance(LedgerKey const& key) const
{
auto balanceID = toOpaqueBase64(key.claimableBalance().balanceID);
std::string claimableBalanceEntryStr;
LedgerEntry le;
std::string sql = "SELECT ledgerentry "
"FROM claimablebalance "
"WHERE balanceid= :balanceid";
auto prep = mDatabase.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::into(claimableBalanceEntryStr));
st.exchange(soci::use(balanceID));
st.define_and_bind();
st.execute(true);
if (!st.got_data())
{
return nullptr;
}
fromOpaqueBase64(le, claimableBalanceEntryStr);
releaseAssert(le.data.type() == CLAIMABLE_BALANCE);
return std::make_shared<LedgerEntry const>(std::move(le));
}
class BulkLoadClaimableBalanceOperation
: public DatabaseTypeSpecificOperation<std::vector<LedgerEntry>>
{
Database& mDb;
std::vector<std::string> mBalanceIDs;
std::vector<LedgerEntry>
executeAndFetch(soci::statement& st)
{
std::string balanceIdStr, claimableBalanceEntryStr;
st.exchange(soci::into(balanceIdStr));
st.exchange(soci::into(claimableBalanceEntryStr));
st.define_and_bind();
{
auto timer = mDb.getSelectTimer("claimablebalance");
st.execute(true);
}
std::vector<LedgerEntry> res;
while (st.got_data())
{
res.emplace_back();
auto& le = res.back();
fromOpaqueBase64(le, claimableBalanceEntryStr);
releaseAssert(le.data.type() == CLAIMABLE_BALANCE);
st.fetch();
}
return res;
}
public:
BulkLoadClaimableBalanceOperation(Database& db,
UnorderedSet<LedgerKey> const& keys)
: mDb(db)
{
mBalanceIDs.reserve(keys.size());
for (auto const& k : keys)
{
releaseAssert(k.type() == CLAIMABLE_BALANCE);
mBalanceIDs.emplace_back(
toOpaqueBase64(k.claimableBalance().balanceID));
}
}
std::vector<LedgerEntry>
doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override
{
std::vector<char const*> cstrBalanceIDs;
cstrBalanceIDs.reserve(mBalanceIDs.size());
for (size_t i = 0; i < mBalanceIDs.size(); ++i)
{
cstrBalanceIDs.emplace_back(mBalanceIDs[i].c_str());
}
std::string sql = "WITH r AS (SELECT value FROM carray(?, ?, 'char*')) "
"SELECT balanceid, ledgerentry "
"FROM claimablebalance "
"WHERE balanceid IN r";
auto prep = mDb.getPreparedStatement(sql);
auto be = prep.statement().get_backend();
if (be == nullptr)
{
throw std::runtime_error("no sql backend");
}
auto sqliteStatement =
dynamic_cast<soci::sqlite3_statement_backend*>(be);
auto st = sqliteStatement->stmt_;
sqlite3_reset(st);
sqlite3_bind_pointer(st, 1, cstrBalanceIDs.data(), "carray", 0);
sqlite3_bind_int(st, 2, static_cast<int>(cstrBalanceIDs.size()));
return executeAndFetch(prep.statement());
}
#ifdef USE_POSTGRES
std::vector<LedgerEntry>
doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override
{
std::string strBalanceIDs;
marshalToPGArray(pg->conn_, strBalanceIDs, mBalanceIDs);
std::string sql = "WITH r AS (SELECT unnest(:v1::TEXT[])) "
"SELECT balanceid, ledgerentry "
"FROM claimablebalance "
"WHERE balanceid IN (SELECT * from r)";
auto prep = mDb.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::use(strBalanceIDs));
return executeAndFetch(st);
}
#endif
};
UnorderedMap<LedgerKey, std::shared_ptr<LedgerEntry const>>
LedgerTxnRoot::Impl::bulkLoadClaimableBalance(
UnorderedSet<LedgerKey> const& keys) const
{
if (!keys.empty())
{
BulkLoadClaimableBalanceOperation op(mDatabase, keys);
return populateLoadedEntries(
keys, mDatabase.doDatabaseTypeSpecificOperation(op));
}
else
{
return {};
}
}
class BulkDeleteClaimableBalanceOperation
: public DatabaseTypeSpecificOperation<void>
{
Database& mDb;
LedgerTxnConsistency mCons;
std::vector<std::string> mBalanceIDs;
public:
BulkDeleteClaimableBalanceOperation(
Database& db, LedgerTxnConsistency cons,
std::vector<EntryIterator> const& entries)
: mDb(db), mCons(cons)
{
mBalanceIDs.reserve(entries.size());
for (auto const& e : entries)
{
releaseAssert(!e.entryExists());
releaseAssert(e.key().ledgerKey().type() == CLAIMABLE_BALANCE);
mBalanceIDs.emplace_back(toOpaqueBase64(
e.key().ledgerKey().claimableBalance().balanceID));
}
}
void
doSociGenericOperation()
{
std::string sql = "DELETE FROM claimablebalance WHERE balanceid = :id";
auto prep = mDb.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::use(mBalanceIDs));
st.define_and_bind();
{
auto timer = mDb.getDeleteTimer("claimablebalance");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size() &&
mCons == LedgerTxnConsistency::EXACT)
{
throw std::runtime_error("Could not update data in SQL");
}
}
void
doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override
{
doSociGenericOperation();
}
#ifdef USE_POSTGRES
void
doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override
{
std::string strBalanceIDs;
marshalToPGArray(pg->conn_, strBalanceIDs, mBalanceIDs);
std::string sql = "WITH r AS (SELECT unnest(:v1::TEXT[])) "
"DELETE FROM claimablebalance "
"WHERE balanceid IN (SELECT * FROM r)";
auto prep = mDb.getPreparedStatement(sql);
auto& st = prep.statement();
st.exchange(soci::use(strBalanceIDs));
st.define_and_bind();
{
auto timer = mDb.getDeleteTimer("claimablebalance");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size() &&
mCons == LedgerTxnConsistency::EXACT)
{
throw std::runtime_error("Could not update data in SQL");
}
}
#endif
};
void
LedgerTxnRoot::Impl::bulkDeleteClaimableBalance(
std::vector<EntryIterator> const& entries, LedgerTxnConsistency cons)
{
BulkDeleteClaimableBalanceOperation op(mDatabase, cons, entries);
mDatabase.doDatabaseTypeSpecificOperation(op);
}
class BulkUpsertClaimableBalanceOperation
: public DatabaseTypeSpecificOperation<void>
{
Database& mDb;
std::vector<std::string> mBalanceIDs;
std::vector<std::string> mClaimableBalanceEntrys;
std::vector<int32_t> mLastModifieds;
void
accumulateEntry(LedgerEntry const& entry)
{
releaseAssert(entry.data.type() == CLAIMABLE_BALANCE);
mBalanceIDs.emplace_back(
toOpaqueBase64(entry.data.claimableBalance().balanceID));
mClaimableBalanceEntrys.emplace_back(toOpaqueBase64(entry));
mLastModifieds.emplace_back(
unsignedToSigned(entry.lastModifiedLedgerSeq));
}
public:
BulkUpsertClaimableBalanceOperation(
Database& Db, std::vector<EntryIterator> const& entryIter)
: mDb(Db)
{
for (auto const& e : entryIter)
{
releaseAssert(e.entryExists());
accumulateEntry(e.entry().ledgerEntry());
}
}
void
doSociGenericOperation()
{
std::string sql = "INSERT INTO claimablebalance "
"(balanceid, ledgerentry, lastmodified) "
"VALUES "
"( :id, :v1, :v2 ) "
"ON CONFLICT (balanceid) DO UPDATE SET "
"balanceid = excluded.balanceid, ledgerentry = "
"excluded.ledgerentry, lastmodified = "
"excluded.lastmodified";
auto prep = mDb.getPreparedStatement(sql);
soci::statement& st = prep.statement();
st.exchange(soci::use(mBalanceIDs));
st.exchange(soci::use(mClaimableBalanceEntrys));
st.exchange(soci::use(mLastModifieds));
st.define_and_bind();
{
auto timer = mDb.getUpsertTimer("claimablebalance");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size())
{
throw std::runtime_error("Could not update data in SQL");
}
}
void
doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override
{
doSociGenericOperation();
}
#ifdef USE_POSTGRES
void
doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override
{
std::string strBalanceIDs, strClaimableBalanceEntry, strLastModifieds;
PGconn* conn = pg->conn_;
marshalToPGArray(conn, strBalanceIDs, mBalanceIDs);
marshalToPGArray(conn, strClaimableBalanceEntry,
mClaimableBalanceEntrys);
marshalToPGArray(conn, strLastModifieds, mLastModifieds);
std::string sql = "WITH r AS "
"(SELECT unnest(:ids::TEXT[]), unnest(:v1::TEXT[]), "
"unnest(:v2::INT[]))"
"INSERT INTO claimablebalance "
"(balanceid, ledgerentry, lastmodified) "
"SELECT * FROM r "
"ON CONFLICT (balanceid) DO UPDATE SET "
"balanceid = excluded.balanceid, ledgerentry = "
"excluded.ledgerentry, "
"lastmodified = excluded.lastmodified";
auto prep = mDb.getPreparedStatement(sql);
soci::statement& st = prep.statement();
st.exchange(soci::use(strBalanceIDs));
st.exchange(soci::use(strClaimableBalanceEntry));
st.exchange(soci::use(strLastModifieds));
st.define_and_bind();
{
auto timer = mDb.getUpsertTimer("claimablebalance");
st.execute(true);
}
if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size())
{
throw std::runtime_error("Could not update data in SQL");
}
}
#endif
};
void
LedgerTxnRoot::Impl::bulkUpsertClaimableBalance(
std::vector<EntryIterator> const& entries)
{
BulkUpsertClaimableBalanceOperation op(mDatabase, entries);
mDatabase.doDatabaseTypeSpecificOperation(op);
}
void
LedgerTxnRoot::Impl::dropClaimableBalances()
{
throwIfChild();
mEntryCache.clear();
mBestOffers.clear();
std::string coll = mDatabase.getSimpleCollationClause();
mDatabase.getSession() << "DROP TABLE IF EXISTS claimablebalance;";
mDatabase.getSession() << "CREATE TABLE claimablebalance ("
<< "balanceid VARCHAR(48) " << coll
<< " PRIMARY KEY, "
<< "ledgerentry TEXT NOT NULL, "
<< "lastmodified INT NOT NULL);";
}
}
| 32.585366 | 80 | 0.603127 |
V5DF8
|
28f7b2a9efaeb2b9a22cf5b02803470c9cdc2706
| 4,072 |
cpp
|
C++
|
OpenGL/GLFWContextGL.cpp
|
IKholopov/TierGine
|
1a3c7cd2bed460af672d7cd5c33d7e7863043989
|
[
"Apache-2.0"
] | null | null | null |
OpenGL/GLFWContextGL.cpp
|
IKholopov/TierGine
|
1a3c7cd2bed460af672d7cd5c33d7e7863043989
|
[
"Apache-2.0"
] | null | null | null |
OpenGL/GLFWContextGL.cpp
|
IKholopov/TierGine
|
1a3c7cd2bed460af672d7cd5c33d7e7863043989
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2018 Igor Kholopov, 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 <GLFWContextGL.h>
#include <GLMaterial.h>
#include <GLShader.h>
namespace TierGine {
IShader* GLFWContextGL::CreateShader(IShader::Type shaderType)
{
GLShader* shader = new GLShader(shaderType, *this);
shaders.insert({shader, nullptr}).first->second.reset(shader);
return shader;
}
void GLFWContextGL::BindShader(const IShader* shader, IPipeline* pipeline)
{
auto foundShader = shaders.find(shader);
assert(foundShader != shaders.end());
auto foundPipeline = pipelines.find(pipeline);
assert(foundPipeline != pipelines.end());
foundPipeline->second->BindShader(*foundShader->second);
}
TG_Status GLFWContextGL::Activate()
{
glfwMakeContextCurrent(window.GetWindow());
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return TG_Ok;
}
IPipeline* GLFWContextGL::CreatePipeline()
{
GLProgram* program = new GLProgram(*this);
pipelines.insert({program, nullptr}).first->second.reset(program);
return program;
}
void GLFWContextGL::DeletePipeline(IPipeline* pipeline)
{
auto storedPipeline = pipelines.find(pipeline);
assert(storedPipeline != pipelines.end());
pipelines.erase(storedPipeline);
}
void GLFWContextGL::DeleteShader(IShader* shader)
{
auto storedShader = shaders.find(shader);
assert(storedShader != shaders.end());
shaders.erase(storedShader);
}
IMesh* GLFWContextGL::CreateMesh()
{
GLMesh* mesh = new GLMesh(*this);
meshes.insert({mesh, nullptr}).first->second.reset(mesh);
return mesh;
}
void GLFWContextGL::DeleteMesh(const IMesh* mesh)
{
auto storedMesh = meshes.find(mesh);
assert(storedMesh != meshes.end());
meshes.erase(storedMesh);
}
ITexture* GLFWContextGL::CreateTexture()
{
GLTexture* texture = new GLTexture(*this);
textures.insert({texture, nullptr}).first->second.reset(texture);
return texture;
}
void GLFWContextGL::DeleteTexture(const ITexture* texture)
{
auto storedTexture = textures.find(texture);
assert(storedTexture != textures.end());
textures.erase(storedTexture);
}
ITextureSampler* GLFWContextGL::CreateTextureSampler(const std::string& name)
{
GLTextureSampler* sampler = new GLTextureSampler(*this, name);
textureSamplers.insert({sampler, nullptr}).first->second.reset(sampler);
return sampler;
}
void GLFWContextGL::DeleteTextureSampler(const ITextureSampler* sampler)
{
auto storedSampler = textureSamplers.find(sampler);
assert(storedSampler != textureSamplers.end());
textureSamplers.erase(storedSampler);
}
IFramebuffer* GLFWContextGL::CreateFramebuffer(int width, int height)
{
GLFramebuffer* buffer = new GLFramebuffer(*this, width, height);
framebuffers.insert({buffer, nullptr}).first->second.reset(buffer);
return buffer;
}
void GLFWContextGL::DeleteFramebuffer(const IFramebuffer* buffer)
{
auto storedBuffer = framebuffers.find(buffer);
assert(storedBuffer != framebuffers.end());
framebuffers.erase(storedBuffer);
}
float GLFWContextGL::GetScreenDepthAt(int x, int y) const
{
float value = -1.0f;
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &value);
return value;
}
std::unique_ptr<IMaterial> GLFWContextGL::CreateMaterial(ITextureSampler* sampler)
{
return std::unique_ptr<IMaterial>(new GLMaterial(sampler));
}
}
| 29.085714 | 82 | 0.718566 |
IKholopov
|
28fa9a0f35c465b171eff066be2899cb0884efe2
| 8,494 |
cpp
|
C++
|
mbed-os/drivers/QSPI.cpp
|
h7ga40/PeachCam
|
06d023a908dc38228e77b47f80bc8496a4d35806
|
[
"Apache-2.0"
] | 1 |
2019-12-13T05:51:34.000Z
|
2019-12-13T05:51:34.000Z
|
mbed-os/drivers/QSPI.cpp
|
h7ga40/PeachCam
|
06d023a908dc38228e77b47f80bc8496a4d35806
|
[
"Apache-2.0"
] | null | null | null |
mbed-os/drivers/QSPI.cpp
|
h7ga40/PeachCam
|
06d023a908dc38228e77b47f80bc8496a4d35806
|
[
"Apache-2.0"
] | 1 |
2021-09-17T15:41:36.000Z
|
2021-09-17T15:41:36.000Z
|
/* mbed Microcontroller Library
* Copyright (c) 2006-2018 ARM Limited
*
* 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 "drivers/QSPI.h"
#include "platform/mbed_critical.h"
#include <string.h>
#if DEVICE_QSPI
namespace mbed {
QSPI *QSPI::_owner = NULL;
SingletonPtr<PlatformMutex> QSPI::_mutex;
QSPI::QSPI(PinName io0, PinName io1, PinName io2, PinName io3, PinName sclk, PinName ssel, int mode) : _qspi()
{
_qspi_io0 = io0;
_qspi_io1 = io1;
_qspi_io2 = io2;
_qspi_io3 = io3;
_qspi_clk = sclk;
_qspi_cs = ssel;
_inst_width = QSPI_CFG_BUS_SINGLE;
_address_width = QSPI_CFG_BUS_SINGLE;
_address_size = QSPI_CFG_ADDR_SIZE_24;
_alt_width = QSPI_CFG_BUS_SINGLE;
_alt_size = QSPI_CFG_ALT_SIZE_8;
_data_width = QSPI_CFG_BUS_SINGLE;
_num_dummy_cycles = 0;
_mode = mode;
_hz = ONE_MHZ;
_initialized = false;
//Go ahead init the device here with the default config
bool success = _initialize();
MBED_ASSERT(success);
}
qspi_status_t QSPI::configure_format(qspi_bus_width_t inst_width, qspi_bus_width_t address_width, qspi_address_size_t address_size, qspi_bus_width_t alt_width, qspi_alt_size_t alt_size, qspi_bus_width_t data_width, int dummy_cycles)
{
qspi_status_t ret_status = QSPI_STATUS_OK;
lock();
_inst_width = inst_width;
_address_width = address_width;
_address_size = address_size;
_alt_width = alt_width;
_alt_size = alt_size;
_data_width = data_width;
_num_dummy_cycles = dummy_cycles;
unlock();
return ret_status;
}
qspi_status_t QSPI::set_frequency(int hz)
{
qspi_status_t ret_status = QSPI_STATUS_OK;
if (_initialized) {
lock();
_hz = hz;
//If the same owner, just change freq.
//Otherwise we may have to change mode as well, so call _acquire
if (_owner == this) {
if (QSPI_STATUS_OK != qspi_frequency(&_qspi, _hz)) {
ret_status = QSPI_STATUS_ERROR;
}
} else {
_acquire();
}
unlock();
} else {
ret_status = QSPI_STATUS_ERROR;
}
return ret_status;
}
qspi_status_t QSPI::read(int address, char *rx_buffer, size_t *rx_length)
{
qspi_status_t ret_status = QSPI_STATUS_ERROR;
if (_initialized) {
if ((rx_length != NULL) && (rx_buffer != NULL)) {
if (*rx_length != 0) {
lock();
if (true == _acquire()) {
_build_qspi_command(-1, address, -1);
if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) {
ret_status = QSPI_STATUS_OK;
}
}
unlock();
}
} else {
ret_status = QSPI_STATUS_INVALID_PARAMETER;
}
}
return ret_status;
}
qspi_status_t QSPI::write(int address, const char *tx_buffer, size_t *tx_length)
{
qspi_status_t ret_status = QSPI_STATUS_ERROR;
if (_initialized) {
if ((tx_length != NULL) && (tx_buffer != NULL)) {
if (*tx_length != 0) {
lock();
if (true == _acquire()) {
_build_qspi_command(-1, address, -1);
if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) {
ret_status = QSPI_STATUS_OK;
}
}
unlock();
}
} else {
ret_status = QSPI_STATUS_INVALID_PARAMETER;
}
}
return ret_status;
}
qspi_status_t QSPI::read(int instruction, int alt, int address, char *rx_buffer, size_t *rx_length)
{
qspi_status_t ret_status = QSPI_STATUS_ERROR;
if (_initialized) {
if ((rx_length != NULL) && (rx_buffer != NULL)) {
if (*rx_length != 0) {
lock();
if (true == _acquire()) {
_build_qspi_command(instruction, address, alt);
if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) {
ret_status = QSPI_STATUS_OK;
}
}
unlock();
}
} else {
ret_status = QSPI_STATUS_INVALID_PARAMETER;
}
}
return ret_status;
}
qspi_status_t QSPI::write(int instruction, int alt, int address, const char *tx_buffer, size_t *tx_length)
{
qspi_status_t ret_status = QSPI_STATUS_ERROR;
if (_initialized) {
if ((tx_length != NULL) && (tx_buffer != NULL)) {
if (*tx_length != 0) {
lock();
if (true == _acquire()) {
_build_qspi_command(instruction, address, alt);
if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) {
ret_status = QSPI_STATUS_OK;
}
}
unlock();
}
} else {
ret_status = QSPI_STATUS_INVALID_PARAMETER;
}
}
return ret_status;
}
qspi_status_t QSPI::command_transfer(int instruction, int address, const char *tx_buffer, size_t tx_length, const char *rx_buffer, size_t rx_length)
{
qspi_status_t ret_status = QSPI_STATUS_ERROR;
if (_initialized) {
lock();
if (true == _acquire()) {
_build_qspi_command(instruction, address, -1); //We just need the command
if (QSPI_STATUS_OK == qspi_command_transfer(&_qspi, &_qspi_command, (const void *)tx_buffer, tx_length, (void *)rx_buffer, rx_length)) {
ret_status = QSPI_STATUS_OK;
}
}
unlock();
}
return ret_status;
}
void QSPI::lock()
{
_mutex->lock();
}
void QSPI::unlock()
{
_mutex->unlock();
}
// Note: Private helper function to initialize qspi HAL
bool QSPI::_initialize()
{
if (_mode != 0 && _mode != 1) {
_initialized = false;
return _initialized;
}
qspi_status_t ret = qspi_init(&_qspi, _qspi_io0, _qspi_io1, _qspi_io2, _qspi_io3, _qspi_clk, _qspi_cs, _hz, _mode);
if (QSPI_STATUS_OK == ret) {
_initialized = true;
} else {
_initialized = false;
}
return _initialized;
}
// Note: Private function with no locking
bool QSPI::_acquire()
{
if (_owner != this) {
//This will set freq as well
_initialize();
_owner = this;
}
return _initialized;
}
void QSPI::_build_qspi_command(int instruction, int address, int alt)
{
memset(&_qspi_command, 0, sizeof(qspi_command_t));
//Set up instruction phase parameters
_qspi_command.instruction.bus_width = _inst_width;
if (instruction != -1) {
_qspi_command.instruction.value = instruction;
_qspi_command.instruction.disabled = false;
} else {
_qspi_command.instruction.disabled = true;
}
//Set up address phase parameters
_qspi_command.address.bus_width = _address_width;
_qspi_command.address.size = _address_size;
if (address != -1) {
_qspi_command.address.value = address;
_qspi_command.address.disabled = false;
} else {
_qspi_command.address.disabled = true;
}
//Set up alt phase parameters
_qspi_command.alt.bus_width = _alt_width;
_qspi_command.alt.size = _alt_size;
if (alt != -1) {
_qspi_command.alt.value = alt;
_qspi_command.alt.disabled = false;
} else {
_qspi_command.alt.disabled = true;
}
_qspi_command.dummy_count = _num_dummy_cycles;
//Set up bus width for data phase
_qspi_command.data.bus_width = _data_width;
}
} // namespace mbed
#endif
| 29.391003 | 233 | 0.585708 |
h7ga40
|
28facf720609c04d87a5b43e7e093224eeff0866
| 4,630 |
cpp
|
C++
|
modules/imgproc/test/test_watershed.cpp
|
snosov1/opencv
|
ce05d6cb89450a5778f4c0169b5da5589798192a
|
[
"BSD-3-Clause"
] | 144 |
2015-01-15T03:38:44.000Z
|
2022-02-17T09:07:52.000Z
|
modules/imgproc/test/test_watershed.cpp
|
snosov1/opencv
|
ce05d6cb89450a5778f4c0169b5da5589798192a
|
[
"BSD-3-Clause"
] | 28 |
2016-10-16T19:42:37.000Z
|
2018-09-14T21:29:48.000Z
|
modules/imgproc/test/test_watershed.cpp
|
snosov1/opencv
|
ce05d6cb89450a5778f4c0169b5da5589798192a
|
[
"BSD-3-Clause"
] | 58 |
2015-01-14T23:43:49.000Z
|
2021-11-15T05:19:08.000Z
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include <string>
using namespace cv;
using namespace std;
class CV_WatershedTest : public cvtest::BaseTest
{
public:
CV_WatershedTest();
~CV_WatershedTest();
protected:
void run(int);
};
CV_WatershedTest::CV_WatershedTest() {}
CV_WatershedTest::~CV_WatershedTest() {}
void CV_WatershedTest::run( int /* start_from */)
{
string exp_path = string(ts->get_data_path()) + "watershed/wshed_exp.png";
Mat exp = imread(exp_path, 0);
Mat orig = imread(string(ts->get_data_path()) + "inpaint/orig.png");
FileStorage fs(string(ts->get_data_path()) + "watershed/comp.xml", FileStorage::READ);
if (orig.empty() || !fs.isOpened())
{
ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
return;
}
CvSeq* cnts = (CvSeq*)fs["contours"].readObj();
Mat markers(orig.size(), CV_32SC1);
markers = Scalar(0);
IplImage iplmrks = markers;
vector<unsigned char> colors(1);
for(int i = 0; cnts != 0; cnts = cnts->h_next, ++i )
{
cvDrawContours( &iplmrks, cnts, Scalar::all(i + 1), Scalar::all(i + 1), -1, CV_FILLED);
Point* p = (Point*)cvGetSeqElem(cnts, 0);
//expected image was added with 1 in order to save to png
//so now we substract 1 to get real color
if(!exp.empty())
colors.push_back(exp.ptr(p->y)[p->x] - 1);
}
fs.release();
const int compNum = (int)(colors.size() - 1);
watershed(orig, markers);
for(int j = 0; j < markers.rows; ++j)
{
int* line = markers.ptr<int>(j);
for(int i = 0; i < markers.cols; ++i)
{
int& pixel = line[i];
if (pixel == -1) // border
continue;
if (pixel <= 0 || pixel > compNum)
continue; // bad result, doing nothing and going to get error latter;
// repaint in saved color to compare with expected;
if(!exp.empty())
pixel = colors[pixel];
}
}
Mat markers8U;
markers.convertTo(markers8U, CV_8U, 1, 1);
if( exp.empty() || orig.size() != exp.size() )
{
imwrite(exp_path, markers8U);
exp = markers8U;
}
if (0 != norm(markers8U, exp, NORM_INF))
{
ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
return;
}
ts->set_failed_test_info(cvtest::TS::OK);
}
TEST(Imgproc_Watershed, regression) { CV_WatershedTest test; test.safe_run(); }
| 34.81203 | 95 | 0.643413 |
snosov1
|
28fb6f6d11fe5dd49b984fa8107b29b7eb1c4a35
| 1,103 |
cpp
|
C++
|
source/lab4/dfp.cpp
|
Jovvik/methopt-lab-1
|
2c3acaf653c7214a925ed1292b9d1d30a33d2737
|
[
"Unlicense"
] | null | null | null |
source/lab4/dfp.cpp
|
Jovvik/methopt-lab-1
|
2c3acaf653c7214a925ed1292b9d1d30a33d2737
|
[
"Unlicense"
] | null | null | null |
source/lab4/dfp.cpp
|
Jovvik/methopt-lab-1
|
2c3acaf653c7214a925ed1292b9d1d30a33d2737
|
[
"Unlicense"
] | null | null | null |
#include "lab4/dfp.h"
#include "iostream"
#include "lab1/brent.h"
#include "lab3/solver.h"
using namespace lab4;
DFP::DFP()
: s(lab2::Vector({1})),
d(lab2::Vector({1})),
G(lab2::Matrix({{1}}, std::nullopt)) {}
lab2::Vector DFP::iteration(lab2::NFunction &f, double) {
lab2::Vector x_k_1 = get_points().back(), g_x = f.grad(x_k_1);
if (iteration_count == 0) {
G = lab2::Matrix::I(x_k_1.size());
d = g_x * (-1);
return x_k_1;
}
const auto r = lab1::Brent(
[&f, x = x_k_1, d_ = d](double a) {
return f(x + d_ * a);
},
ONE_DIM_EPS, ONE_DIM_START, ONE_DIM_END)
.optimize();
s = d * r;
auto x = x_k_1 + s, g_y = g_x;
g_x = f.grad(x);
auto p = g_x - g_y, v = G * p;
G = G + lab2::Matrix::vector_mul(s, s) / (s * p)
- lab2::Matrix::vector_mul(v, v) / (v * p);
d = (G * g_x) * (-1);
return x;
}
bool DFP::is_done(lab2::NFunction &, double epsilon) const {
return s.norm() < epsilon;
}
| 28.282051 | 66 | 0.483228 |
Jovvik
|
28fc02a851e81e019b0eca73e0ce310b05bacffc
| 1,765 |
cpp
|
C++
|
week2/6_sinExample_circlePlusPath/src/ofApp.cpp
|
evejweinberg/algo2012
|
7e13c20bab94e1769f6751c4e124964ae05b7087
|
[
"MIT"
] | 94 |
2015-01-12T16:07:57.000Z
|
2021-12-24T06:48:04.000Z
|
week2/6_sinExample_circlePlusPath/src/ofApp.cpp
|
theomission/algo2012
|
7e13c20bab94e1769f6751c4e124964ae05b7087
|
[
"MIT"
] | null | null | null |
week2/6_sinExample_circlePlusPath/src/ofApp.cpp
|
theomission/algo2012
|
7e13c20bab94e1769f6751c4e124964ae05b7087
|
[
"MIT"
] | 18 |
2015-03-12T23:11:08.000Z
|
2022-02-05T05:43:51.000Z
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
ofBackground(0,0,0);
ofSetCircleResolution(100);
radius = 50;
}
//--------------------------------------------------------------
void ofApp::update(){
radius = radius + 0.1;
}
//--------------------------------------------------------------
void ofApp::draw(){
float xorig = 500;
float yorig = 300;
float angle = ofGetElapsedTimef()*3.5;
float x = xorig + radius * cos(angle);
float y = yorig + radius * -sin(angle);
ofPoint temp;
temp.x = x;
temp.y = y;
points.push_back(temp);
if (points.size() > 1000){
points.erase(points.begin());
}
ofSetRectMode(OF_RECTMODE_CENTER);
ofSetColor(255,0,127);
ofFill();
ofCircle(x,y,10);
ofSetColor(255,255,255);
ofNoFill();
ofBeginShape();
for (int i = 0; i < points.size(); i++){
ofVertex(points[i].x, points[i].y);
}
ofEndShape();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
| 17.65 | 64 | 0.398867 |
evejweinberg
|
28fc99035e0c7318fc6617c3c8d037dd9c7adecb
| 2,602 |
cpp
|
C++
|
unit_tests/stencil_composition/test_make_loop_intervals.cpp
|
mbianco/gridtools
|
1abef09881a31495a3d02a15d3fe21620c6dde98
|
[
"BSD-3-Clause"
] | null | null | null |
unit_tests/stencil_composition/test_make_loop_intervals.cpp
|
mbianco/gridtools
|
1abef09881a31495a3d02a15d3fe21620c6dde98
|
[
"BSD-3-Clause"
] | null | null | null |
unit_tests/stencil_composition/test_make_loop_intervals.cpp
|
mbianco/gridtools
|
1abef09881a31495a3d02a15d3fe21620c6dde98
|
[
"BSD-3-Clause"
] | 1 |
2019-06-14T10:35:50.000Z
|
2019-06-14T10:35:50.000Z
|
/*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <gridtools/stencil_composition/make_loop_intervals.hpp>
#include <gtest/gtest.h>
#include <gridtools/common/defs.hpp>
#include <gridtools/meta.hpp>
#include <gridtools/stencil_composition/interval.hpp>
#include <gridtools/stencil_composition/level.hpp>
namespace gridtools {
namespace {
using meta::list;
template <uint_t Splitter, int_t Offset>
using lev = level<Splitter, Offset, 3>;
using from_t = lev<0, 1>;
using to_t = lev<3, -1>;
using axis_interval_t = interval<from_t, to_t>;
struct stage1 {};
struct stage2 {};
template <template <class...> class StagesMaker>
GT_META_DEFINE_ALIAS(testee, make_loop_intervals, (StagesMaker, axis_interval_t));
namespace no_stages {
using testee_t = GT_META_CALL(testee, meta::always<list<>>::apply);
static_assert(std::is_same<testee_t, list<>>{}, "");
} // namespace no_stages
namespace simple {
using testee_t = GT_META_CALL(testee, meta::always<list<stage1>>::apply);
static_assert(std::is_same<testee_t, list<loop_interval<from_t, to_t, list<stage1>>>>{}, "");
} // namespace simple
namespace overlap {
template <uint_t Splitter, int_t Offset>
constexpr int_t idx() {
return level_to_index<lev<Splitter, Offset>>::value;
}
constexpr bool has_stage1(int_t i) { return i >= idx<0, 2>() && i < idx<2, 1>(); }
constexpr bool has_stage2(int_t i) { return i >= idx<1, 1>() && i < idx<3, -1>(); }
template <class Index>
GT_META_DEFINE_ALIAS(stages_maker,
meta::filter,
(meta::not_<std::is_void>::apply,
meta::list<conditional_t<has_stage1(Index::value), stage1, void>,
conditional_t<has_stage2(Index::value), stage2, void>>));
using testee_t = GT_META_CALL(testee, stages_maker);
using expected_t = list<loop_interval<lev<0, 2>, lev<1, -1>, list<stage1>>,
loop_interval<lev<1, 1>, lev<2, -1>, list<stage1, stage2>>,
loop_interval<lev<2, 1>, lev<3, -2>, list<stage2>>>;
static_assert(std::is_same<testee_t, expected_t>{}, "");
} // namespace overlap
TEST(dummy, dummy) {}
} // namespace
} // namespace gridtools
| 35.162162 | 105 | 0.60146 |
mbianco
|
28fc9f8b5966ad5fa16cf33a230b6e621d29ef4f
| 1,035 |
cpp
|
C++
|
src/swimport/tests/14_arrays/src.cpp
|
talos-gis/swimport
|
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
|
[
"MIT"
] | 1 |
2019-03-07T20:43:42.000Z
|
2019-03-07T20:43:42.000Z
|
src/swimport/tests/14_arrays/src.cpp
|
talos-gis/swimport
|
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
|
[
"MIT"
] | null | null | null |
src/swimport/tests/14_arrays/src.cpp
|
talos-gis/swimport
|
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
|
[
"MIT"
] | null | null | null |
#include "src.h"
#include <string.h>
#include <stdlib.h>
int sum(int const * A_members, size_t n){
auto ret = 0;
for (int i = 0; i < n; i++){
ret += *A_members;
A_members++;
}
return ret;
}
void digits(int n, int** A_output, size_t* size, int base){
auto ret = (int*)malloc(0);
size_t i = 0;
while (n != 0){
ret = (int*)realloc(ret, sizeof(int)*(++i));
ret[i-1] = n%base;
n /= base;
}
*size = i;
*A_output = ret;
}
void inc(double * AIO_x, size_t n, double offset){
for (size_t i = 0; i < n; i++){
AIO_x[i] += offset;
}
}
const int VERY_BIG_NUMBER = 1'000'000;
void very_big_array(int** A_out, size_t* size){
*A_out = new int[VERY_BIG_NUMBER];
*size = VERY_BIG_NUMBER;
}
void very_big_array_malloc(int** A_out, size_t* size){
*A_out = (int*)calloc(VERY_BIG_NUMBER, sizeof(int));
*size = VERY_BIG_NUMBER;
}
int vbav[1000] = {};
void very_big_array_view(int*& A_out, size_t& size){
A_out = vbav;
size = 1000;
}
| 21.5625 | 59 | 0.571981 |
talos-gis
|
28fcc247a08f4de74270d83536ad306853dc7395
| 6,726 |
cpp
|
C++
|
aws-cpp-sdk-apigatewayv2/source/model/Stage.cpp
|
Neusoft-Technology-Solutions/aws-sdk-cpp
|
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
|
[
"Apache-2.0"
] | 1 |
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-apigatewayv2/source/model/Stage.cpp
|
Neusoft-Technology-Solutions/aws-sdk-cpp
|
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
|
[
"Apache-2.0"
] | 1 |
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-apigatewayv2/source/model/Stage.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1 |
2021-11-09T12:02:58.000Z
|
2021-11-09T12:02:58.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/apigatewayv2/model/Stage.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ApiGatewayV2
{
namespace Model
{
Stage::Stage() :
m_accessLogSettingsHasBeenSet(false),
m_apiGatewayManaged(false),
m_apiGatewayManagedHasBeenSet(false),
m_autoDeploy(false),
m_autoDeployHasBeenSet(false),
m_clientCertificateIdHasBeenSet(false),
m_createdDateHasBeenSet(false),
m_defaultRouteSettingsHasBeenSet(false),
m_deploymentIdHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_lastDeploymentStatusMessageHasBeenSet(false),
m_lastUpdatedDateHasBeenSet(false),
m_routeSettingsHasBeenSet(false),
m_stageNameHasBeenSet(false),
m_stageVariablesHasBeenSet(false),
m_tagsHasBeenSet(false)
{
}
Stage::Stage(JsonView jsonValue) :
m_accessLogSettingsHasBeenSet(false),
m_apiGatewayManaged(false),
m_apiGatewayManagedHasBeenSet(false),
m_autoDeploy(false),
m_autoDeployHasBeenSet(false),
m_clientCertificateIdHasBeenSet(false),
m_createdDateHasBeenSet(false),
m_defaultRouteSettingsHasBeenSet(false),
m_deploymentIdHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_lastDeploymentStatusMessageHasBeenSet(false),
m_lastUpdatedDateHasBeenSet(false),
m_routeSettingsHasBeenSet(false),
m_stageNameHasBeenSet(false),
m_stageVariablesHasBeenSet(false),
m_tagsHasBeenSet(false)
{
*this = jsonValue;
}
Stage& Stage::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("accessLogSettings"))
{
m_accessLogSettings = jsonValue.GetObject("accessLogSettings");
m_accessLogSettingsHasBeenSet = true;
}
if(jsonValue.ValueExists("apiGatewayManaged"))
{
m_apiGatewayManaged = jsonValue.GetBool("apiGatewayManaged");
m_apiGatewayManagedHasBeenSet = true;
}
if(jsonValue.ValueExists("autoDeploy"))
{
m_autoDeploy = jsonValue.GetBool("autoDeploy");
m_autoDeployHasBeenSet = true;
}
if(jsonValue.ValueExists("clientCertificateId"))
{
m_clientCertificateId = jsonValue.GetString("clientCertificateId");
m_clientCertificateIdHasBeenSet = true;
}
if(jsonValue.ValueExists("createdDate"))
{
m_createdDate = jsonValue.GetString("createdDate");
m_createdDateHasBeenSet = true;
}
if(jsonValue.ValueExists("defaultRouteSettings"))
{
m_defaultRouteSettings = jsonValue.GetObject("defaultRouteSettings");
m_defaultRouteSettingsHasBeenSet = true;
}
if(jsonValue.ValueExists("deploymentId"))
{
m_deploymentId = jsonValue.GetString("deploymentId");
m_deploymentIdHasBeenSet = true;
}
if(jsonValue.ValueExists("description"))
{
m_description = jsonValue.GetString("description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("lastDeploymentStatusMessage"))
{
m_lastDeploymentStatusMessage = jsonValue.GetString("lastDeploymentStatusMessage");
m_lastDeploymentStatusMessageHasBeenSet = true;
}
if(jsonValue.ValueExists("lastUpdatedDate"))
{
m_lastUpdatedDate = jsonValue.GetString("lastUpdatedDate");
m_lastUpdatedDateHasBeenSet = true;
}
if(jsonValue.ValueExists("routeSettings"))
{
Aws::Map<Aws::String, JsonView> routeSettingsJsonMap = jsonValue.GetObject("routeSettings").GetAllObjects();
for(auto& routeSettingsItem : routeSettingsJsonMap)
{
m_routeSettings[routeSettingsItem.first] = routeSettingsItem.second.AsObject();
}
m_routeSettingsHasBeenSet = true;
}
if(jsonValue.ValueExists("stageName"))
{
m_stageName = jsonValue.GetString("stageName");
m_stageNameHasBeenSet = true;
}
if(jsonValue.ValueExists("stageVariables"))
{
Aws::Map<Aws::String, JsonView> stageVariablesJsonMap = jsonValue.GetObject("stageVariables").GetAllObjects();
for(auto& stageVariablesItem : stageVariablesJsonMap)
{
m_stageVariables[stageVariablesItem.first] = stageVariablesItem.second.AsString();
}
m_stageVariablesHasBeenSet = true;
}
if(jsonValue.ValueExists("tags"))
{
Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects();
for(auto& tagsItem : tagsJsonMap)
{
m_tags[tagsItem.first] = tagsItem.second.AsString();
}
m_tagsHasBeenSet = true;
}
return *this;
}
JsonValue Stage::Jsonize() const
{
JsonValue payload;
if(m_accessLogSettingsHasBeenSet)
{
payload.WithObject("accessLogSettings", m_accessLogSettings.Jsonize());
}
if(m_apiGatewayManagedHasBeenSet)
{
payload.WithBool("apiGatewayManaged", m_apiGatewayManaged);
}
if(m_autoDeployHasBeenSet)
{
payload.WithBool("autoDeploy", m_autoDeploy);
}
if(m_clientCertificateIdHasBeenSet)
{
payload.WithString("clientCertificateId", m_clientCertificateId);
}
if(m_createdDateHasBeenSet)
{
payload.WithString("createdDate", m_createdDate.ToGmtString(DateFormat::ISO_8601));
}
if(m_defaultRouteSettingsHasBeenSet)
{
payload.WithObject("defaultRouteSettings", m_defaultRouteSettings.Jsonize());
}
if(m_deploymentIdHasBeenSet)
{
payload.WithString("deploymentId", m_deploymentId);
}
if(m_descriptionHasBeenSet)
{
payload.WithString("description", m_description);
}
if(m_lastDeploymentStatusMessageHasBeenSet)
{
payload.WithString("lastDeploymentStatusMessage", m_lastDeploymentStatusMessage);
}
if(m_lastUpdatedDateHasBeenSet)
{
payload.WithString("lastUpdatedDate", m_lastUpdatedDate.ToGmtString(DateFormat::ISO_8601));
}
if(m_routeSettingsHasBeenSet)
{
JsonValue routeSettingsJsonMap;
for(auto& routeSettingsItem : m_routeSettings)
{
routeSettingsJsonMap.WithObject(routeSettingsItem.first, routeSettingsItem.second.Jsonize());
}
payload.WithObject("routeSettings", std::move(routeSettingsJsonMap));
}
if(m_stageNameHasBeenSet)
{
payload.WithString("stageName", m_stageName);
}
if(m_stageVariablesHasBeenSet)
{
JsonValue stageVariablesJsonMap;
for(auto& stageVariablesItem : m_stageVariables)
{
stageVariablesJsonMap.WithString(stageVariablesItem.first, stageVariablesItem.second);
}
payload.WithObject("stageVariables", std::move(stageVariablesJsonMap));
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("tags", std::move(tagsJsonMap));
}
return payload;
}
} // namespace Model
} // namespace ApiGatewayV2
} // namespace Aws
| 23.935943 | 114 | 0.741748 |
Neusoft-Technology-Solutions
|
28fd242a80f8682bd11333cca0515fa98191be66
| 16,513 |
cpp
|
C++
|
earth_enterprise/src/fusion/fusionui/AssetChooser.cpp
|
tornado12345/earthenterprise
|
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
|
[
"Apache-2.0"
] | 2,661 |
2017-03-20T22:12:50.000Z
|
2022-03-30T09:43:19.000Z
|
earth_enterprise/src/fusion/fusionui/AssetChooser.cpp
|
tornado12345/earthenterprise
|
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
|
[
"Apache-2.0"
] | 1,531 |
2017-03-24T17:20:32.000Z
|
2022-03-16T18:11:14.000Z
|
earth_enterprise/src/fusion/fusionui/AssetChooser.cpp
|
tornado12345/earthenterprise
|
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
|
[
"Apache-2.0"
] | 990 |
2017-03-24T11:54:28.000Z
|
2022-03-22T11:51:47.000Z
|
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "fusion/fusionui/AssetChooser.h"
#include <Qt/qstring.h>
#include <Qt/qlineedit.h>
#include <Qt/qpushbutton.h>
#include <Qt/qcombobox.h>
#include <Qt/qmessagebox.h>
#include <Qt/q3iconview.h>
#include <Qt/qinputdialog.h>
#include <Qt/qapplication.h>
#include <Qt/qcoreevent.h>
#include "fusion/gst/gstAssetManager.h"
#include "fusion/fusionui/Preferences.h"
#include "fusion/fusionui/AssetManager.h"
namespace {
int ChangeDirEventId = int(QEvent::registerEventType());
class ChangeDirEvent : public QCustomEvent {
public:
explicit ChangeDirEvent(const gstAssetFolder &folder) :
QCustomEvent(ChangeDirEventId),
folder_(folder)
{ }
gstAssetFolder folder_;
};
// -----------------------------------------------------------------------------
using QIconView = Q3IconView;
class FolderItem : public QIconViewItem {
public:
FolderItem(QIconView* parent, const gstAssetFolder& f);
const gstAssetFolder getFolder() { return folder; }
private:
gstAssetFolder folder;
};
// -----------------------------------------------------------------------------
FolderItem::FolderItem(QIconView* parent, const gstAssetFolder& f)
: QIconViewItem(parent), folder(f) {
std::string san = shortAssetName(f.name());
setText(san.c_str());
AssetDisplayHelper a(AssetDefs::Invalid, std::string());
setPixmap(a.GetPixmap());
setKey(QString("0" + text()));
}
// -----------------------------------------------------------------------------
class AssetItem : public QIconViewItem {
public:
AssetItem(QIconView* parent, gstAssetHandle handle);
gstAssetHandle getAssetHandle() { return assetHandle; }
private:
gstAssetHandle assetHandle;
};
// -----------------------------------------------------------------------------
AssetItem::AssetItem(QIconView* parent, gstAssetHandle handle)
: QIconViewItem(parent), assetHandle(handle) {
auto saname = shortAssetName(handle->getName());
setText(saname.c_str());
Asset asset = handle->getAsset();
AssetDisplayHelper a(asset->type, asset->subtype);
setPixmap(a.GetPixmap());
setKey(QString("%1").arg(a.GetSortKey()) + text());
}
} // namespace
// -----------------------------------------------------------------------------
/////////////////////////////// OPEN RESOURCE
AssetChooser::AssetChooser(QWidget* parent, AssetChooser::Mode m,
AssetDefs::Type t, const std::string& st)
: AssetChooserBase(parent, 0, false, 0), mode_(m),
type_(t), subtype_(st),
current_folder_(theAssetManager->getAssetRoot()) {
const QString SaveBtnText = QObject::tr("Save");
const QString OpenBtnText = QObject::tr("Open");
iconView->setSorting(true);
if (mode_ == Save || mode_ == SaveAs) {
ok_btn->setText(SaveBtnText);
setCaption(SaveBtnText);
} else {
ok_btn->setText(OpenBtnText);
setCaption(OpenBtnText);
}
AssetDisplayHelper adh(type_, subtype_);
compatible_asset_types_.push_back(adh);
filterCombo->insertItem(adh.GetPixmap(), adh.PrettyName());
filterCombo->insertItem("All");
// This will draw the iconview contents.
chooseFilter(adh.PrettyName());
ok_btn->setEnabled(false);
// Accept key presses.
setFocusPolicy(Qt::StrongFocus);
// Restore previous directory for this type/subtype.
RestorePreviousDir(adh);
}
AssetChooser::AssetChooser(
QWidget* parent, AssetChooser::Mode m,
const std::vector<AssetCategoryDef>& compatible_asset_defs,
const std::string &all_compatible_assets_filter_text,
const std::string &all_compatible_assets_icon_name)
: AssetChooserBase(parent, 0, false, 0), mode_(m),
all_compatible_assets_filter_text_(all_compatible_assets_filter_text),
current_folder_(theAssetManager->getAssetRoot()) {
assert(mode_ == Open);
assert(!compatible_asset_defs.empty());
{
// Note: it is not required for Open Dialog, but just to have them
// initialized.
const AssetCategoryDef& asset_category_def = compatible_asset_defs[0];
type_ = asset_category_def.type;
subtype_ = asset_category_def.subtype;
}
const QString OpenBtnText = QObject::tr("Open");
ok_btn->setText(OpenBtnText);
setCaption(OpenBtnText);
iconView->setSorting(true);
// Insert 'all compatible assets' item in view filter combobox of OpenDialog.
if (!all_compatible_assets_filter_text_.empty()) {
if (!(all_compatible_assets_filter_text_.empty() ||
all_compatible_assets_icon_name.empty())) {
filterCombo->insertItem(
AssetDisplayHelper::LoadPixmap(
QObject::tr(all_compatible_assets_icon_name.c_str())),
QObject::tr(all_compatible_assets_filter_text_.c_str()));
} else {
assert(!all_compatible_assets_filter_text_.empty());
assert(all_compatible_assets_icon_name.empty());
filterCombo->insertItem(
QObject::tr(all_compatible_assets_filter_text_.c_str()));
}
}
// Insert compatible asset items in view filter combobox of OpenDialog.
for (const auto& i : compatible_asset_defs) {
AssetDisplayHelper adh(i.type, i.subtype);
compatible_asset_types_.push_back(adh);
filterCombo->insertItem(adh.GetPixmap(), adh.PrettyName());
}
filterCombo->insertItem("All");
assert(compatible_asset_types_.size() != 0);
// This will draw the iconview contents.
if (!all_compatible_assets_filter_text_.empty()) {
chooseFilter(QObject::tr(all_compatible_assets_filter_text_.c_str()));
} else {
const AssetDisplayHelper& adh = compatible_asset_types_[0];
chooseFilter(adh.PrettyName());
}
ok_btn->setEnabled(false);
// Accept key presses.
setFocusPolicy(Qt::StrongFocus);
// Restore previous directory for this type/subtype.
const AssetDisplayHelper& adh = compatible_asset_types_[0];
RestorePreviousDir(adh);
}
void AssetChooser::RestorePreviousDir(const AssetDisplayHelper& adh) {
if (khExists(Preferences::filepath("assetchooser.xml").latin1())) {
if (chooser_history_.Load(
Preferences::filepath("assetchooser.xml").latin1())) {
QString dir = chooser_history_.FindDir(adh.GetSortKey());
if (!dir.isEmpty()) {
QString path = AssetDefs::AssetRoot().c_str();
path += "/";
path += dir;
if (khDirExists(path.latin1())) {
updateView(gstAssetFolder(path));
} else {
notify(NFY_WARN, "Invalid path in history: %s", path.latin1());
}
}
}
}
}
void AssetChooser::chooseFilter(const QString& str) {
if (str == "All") {
match_string_.clear();
} else {
match_string_ = str.latin1();
}
updateView(current_folder_);
}
bool AssetChooser::matchFilter(const gstAssetHandle handle) const {
Asset asset = handle->getAsset();
if (asset->meta.GetAs("hidden", false)) {
return false;
}
if (match_string_.empty())
return true;
AssetDisplayHelper a(asset->type, asset->subtype);
if (match_string_ == all_compatible_assets_filter_text_) {
assert(!all_compatible_assets_filter_text_.empty());
for (const auto& i : compatible_asset_types_) {
if (a.PrettyName() == i.PrettyName())
return true;
}
return false;
}
return (a.PrettyName() == match_string_.c_str());
}
void AssetChooser::keyPressEvent(QKeyEvent* e) {
if (e->key() == Qt::Key_Backspace) {
cdtoparent();
e->accept();
} else if (e->key() == Qt::Key_Escape) {
reject();
e->accept();
} else {
e->ignore();
}
}
void AssetChooser::customEvent(QEvent *e) {
// Make sure this is really an event that we sent.
if (int(e->type()) == ChangeDirEventId) {
ChangeDirEvent* cdEvent = dynamic_cast<ChangeDirEvent*>(e);
iconView->clearSelection();
updateView(cdEvent->folder_);
}
}
void AssetChooser::accept() {
if (mode_ == Open) {
// Check whether item has been selected;
// Note: there is no textEdited-signal in Qt3, so we compare
// name of selected/current item with nameEdit's text to make a decision
// whether it has been edited.
QIconViewItem* item = iconView->currentItem();
if (item != NULL) {
AssetItem* assetItem = dynamic_cast<AssetItem*>(item);
if (assetItem != NULL) {
// If name doesn't match with current item name, then reset item
// pointer to initiate searching of item by name below.
auto gname = getName();
std::string san1 { shortAssetName(assetItem->getAssetHandle()
->getName().toUtf8().constData()) };
std::string san2 { shortAssetName(assetItem->getAssetHandle()
->getName().toStdString().c_str()) };
if (san1 == san2) {
gname.clear();
gname = QString(san2.c_str());
}
if (gname != san2.c_str()) {
item = NULL;
}
}
}
if (item == NULL) {
// Note: means that name have been edited and we try to find item by name.
item = iconView->findItem(getName(), QKeySequence::ExactMatch);
}
// here
AssetItem* assetItem = dynamic_cast<AssetItem*>(item);
if (assetItem != NULL) {
auto saname = shortAssetName(assetItem->getAssetHandle()->getName());
nameEdit->setText(saname.c_str());
gstAssetHandle asset_handle = assetItem->getAssetHandle();
Asset asset = asset_handle->getAsset();
type_ = asset->type;
subtype_ = asset->subtype;
} else {
QMessageBox::critical(
this, "Error",
tr("The specified asset \"") + getName() + tr("\" does not exist."),
tr("OK"), QString::null, QString::null, 0);
return;
}
}
QString fullpath;
if (!getFullPath(fullpath)) {
QMessageBox::critical(this, tr("Error"),
fullpath, tr("OK"), QString::null, QString::null, 0);
return;
}
if (mode_ == Save || mode_ == SaveAs) {
// validate this asset name is unique and prompt if not!
std::string ref { fullpath.toUtf8().constData() };
if (Asset(ref)) {
if (QMessageBox::warning(this, "Warning",
fullpath + tr(" already exists.\nDo you want to replace it?"),
tr("OK"), tr("Cancel"), 0, 1) == 1)
return;
}
} else {
// Validate whether this asset exists and has compatible asset type.
std::string ref { fullpath.toUtf8().constData() };
if (!Asset(ref)) {
QMessageBox::critical(
this, "Error",
tr("The specified asset \"") + getName() + tr("\" does not exist."),
tr("OK"), QString::null, QString::null, 0);
return;
}
if (!IsCompatibleAsset()) {
QMessageBox::critical(this, "Error",
tr("The selected asset \"") + getName() +
tr("\" has an incompatible asset type."),
tr("OK"), QString::null, QString::null, 0);
return;
}
}
// save directory for this type/subtype
AssetDisplayHelper adh(type_, subtype_);
chooser_history_.SetDir(adh.GetSortKey(), current_folder_.relativePath());
chooser_history_.Save(Preferences::filepath("assetchooser.xml").latin1());
AssetChooserBase::accept();
}
bool AssetChooser::getFullPath(QString& fullpath) const {
QString path;
if (current_folder_.relativePath().isEmpty()) {
path = getName();
} else {
path = current_folder_.relativePath() + "/" + getName();
}
QString errormsg;
std::string fullassetname;
try {
fullassetname = AssetDefs::NormalizeAssetName(path.latin1(), type_,
subtype_);
} catch(const std::exception& e) {
errormsg = QString::fromUtf8(e.what());
} catch(...) {
errormsg = "Unknown error";
}
if (!errormsg.isEmpty()) {
fullpath = errormsg;
return false;
}
fullpath = fullassetname.c_str();
return true;
}
bool AssetChooser::IsCompatibleAsset() const {
assert(mode_ == Open);
const AssetDisplayHelper adh(type_, subtype_);
std::vector<AssetDisplayHelper>::const_iterator it = std::find(
compatible_asset_types_.begin(), compatible_asset_types_.end(), adh);
return it != compatible_asset_types_.end();
}
QString AssetChooser::getName() const {
return nameEdit->text();
}
const gstAssetFolder& AssetChooser::getFolder() const {
return current_folder_;
}
void AssetChooser::selectItem(QIconViewItem* item) {
AssetItem* assetItem = dynamic_cast<AssetItem*>(item);
if (assetItem != NULL) {
std::string aname { assetItem->getAssetHandle()->getName().toStdString() },
sname { shortAssetName(aname.c_str()) };
nameEdit->setText(sname.c_str());
}
}
void AssetChooser::nameChanged(const QString& str) {
if (str.isEmpty()) {
ok_btn->setEnabled(false);
} else {
QIconViewItem* item = iconView->currentItem();
if (item != NULL) {
// If name doesn't match with current item, then clear selection.
AssetItem* assetItem = dynamic_cast<AssetItem*>(item);
if (assetItem != NULL) {
std::string san = shortAssetName(assetItem->getAssetHandle()->getName());
if (getName().toStdString() != san) {
iconView->clearSelection();
}
}
}
ok_btn->setEnabled(true);
ok_btn->setDefault(true);
}
}
void AssetChooser::chooseItem(QIconViewItem* item) {
FolderItem* folder = dynamic_cast<FolderItem*>(item);
if (folder != NULL) {
// we can't call updateView directly since it will replace the contents
// of the list. And the Qt routine that called us will access it again
// after we return. Post an event back to myself with the folder
// and we'll call updateView when we get it
QApplication::postEvent(this,
new ChangeDirEvent(folder->getFolder()));
return;
}
AssetItem* asset = dynamic_cast<AssetItem*>(item);
if (asset != NULL)
accept();
}
void AssetChooser::cdtoparent() {
if (current_folder_.name() == theAssetManager->getAssetRoot().name())
return;
updateView(current_folder_.getParentFolder());
}
void AssetChooser::NewDirectory() {
bool ok;
QString text = QInputDialog::getText("Make New Folder",
tr("Enter new folder name:"),
QLineEdit::Normal, QString::null, &ok, this);
if (ok && !text.isEmpty()) {
QString newdir(current_folder_.fullPath() + "/" + text);
QString error;
if (!theAssetManager->makeDir
(AssetDefs::FilenameToAssetPath(newdir.latin1()), error)) {
QMessageBox::critical(this, tr("Error"),
error, tr("OK"), QString::null, QString::null, 0);
} else {
updateView(current_folder_);
}
}
}
void AssetChooser::updateView(const gstAssetFolder& folder) {
current_folder_ = folder;
if (folder.name() == theAssetManager->getAssetRoot().name()) {
cdtoparentBtn->setEnabled(false);
} else {
cdtoparentBtn->setEnabled(true);
}
iconView->clear();
//
// first add all folders
//
std::vector<gstAssetFolder> folders = folder.getAssetFolders();
for (const auto& it : folders) {
(void)new FolderItem(iconView, it);
}
//
// now add all assets
//
std::vector<gstAssetHandle> items = folder.getAssetHandles();
for (auto& it : items) {
if (matchFilter(it))
(void)new AssetItem(iconView, it);
}
//
// populate ancestry combobox
//
ancestryCombo->clear();
gstAssetFolder f = folder;
while (f.isValid() && f.name() != theAssetManager->getAssetRoot().name()) {
ancestryCombo->insertItem(AssetManager::AssetRoot() + "/"
+ f.relativePath(), 0);
f = f.getParentFolder();
}
ancestryCombo->insertItem(AssetManager::AssetRoot() + "/", 0);
ancestryCombo->setCurrentItem(ancestryCombo->count() - 1);
}
void AssetChooser::chooseAncestor(const QString& ancestor) {
gstAssetFolder f = current_folder_;
while (f.isValid()) {
if (ancestor == QString(AssetManager::AssetRoot() + "/")
+ f.relativePath()) {
updateView(f);
return;
}
f = f.getParentFolder();
}
}
| 30.410681 | 83 | 0.639072 |
tornado12345
|
28fd96fc5361c29e837e17697d3fb454a7f06f87
| 3,052 |
cpp
|
C++
|
main.cpp
|
olpotkin/storyboard
|
8fa3012f84e6eac023cbf7f3a77d5c05306ee282
|
[
"MIT"
] | null | null | null |
main.cpp
|
olpotkin/storyboard
|
8fa3012f84e6eac023cbf7f3a77d5c05306ee282
|
[
"MIT"
] | null | null | null |
main.cpp
|
olpotkin/storyboard
|
8fa3012f84e6eac023cbf7f3a77d5c05306ee282
|
[
"MIT"
] | null | null | null |
/* In this exercise we want to design a Storyboard. Our version of the Storyboard
* contains arbitrary many notes (imagine it like putting sticky notes on a board).
* Every note has a title, a text and a set of tags. E.g.
* - title: "Test Traceplayer"
* - text: "Implement a unit test for the class Traceplayer of the spark core framework."
* - tags: {"unit test", "traceplayer", "testing", "spark core"}
*
* Our Storyboard should enable us to search for notes by title, text and tags.
* E.g.:
* searchByTitle("Test Traceplayer")
* searchByTag({"testing", "unit test"})
* searchByText("Implement a unit test for the class Traceplayer of the spark core framework.")
* For the sake of simplicity we don't want to do any similiarity or prefix matching when
* searching for a title, tag or text. Only an exact match should give results.
*
* The skeleton code below can be used as a starting point but doesn't have to.
* The comments "fill in" are placeholders where you definitely have to put in some code when
* you use this skeleton code. But this doesn't mean that you shouldn't or can't put code anywhere else.
*
* Also write some simple unit tests to show how you would test the functionality of the Storyboard.
* Don't use any testing framework. Simple if-statements are sufficient for this exercise.
*
* Hint: Think about performance versus memory tradeoffs in your design, so you can give good
* reasons for your decision.
*/
///
/// @brief
/// @author Oleg Potkin <olpotkin@gmail.com>
///
#include "core/storyboard.h"
int main() {
Note note_1{1, "Note 1", "Some text #", {"tag1", "tag2"} };
Note note_2{2, "Note 2", "Some text #", {"tag2", "tag3"} };
Note note_3{3, "Note 3", "Some text #", {"tag1", "tag5"} };
Note note_4{4, "Note 4", "Some text #", {"tag1", "tag5"} };
Storyboard sb{};
sb.addNote(note_1);
sb.addNote(note_2);
sb.addNote(note_3);
sb.addNote(note_4);
std::cout << "Initial size of storyboard = " << sb.getSize() << std::endl;
sb.deleteNote(4);
std::cout << "Size of storyboard after deletion of 1 note = " << sb.getSize() << std::endl;
std::cout << std::endl;
auto search_1 = sb.searchByTitle("Note 1");
for (const auto& s : search_1) {
auto n = sb.getNoteById(s);
std::cout << "search by title:"
<< " ID=" << n.getId()
<< " Title=" << n.getTitle()
<< std::endl;
}
std::cout << std::endl;
auto search_2 = sb.searchByText("Some text #");
for (const auto& s : search_2) {
auto n = sb.getNoteById(s);
std::cout << "search by text:"
<< " ID=" << n.getId()
<< " Title=" << n.getTitle()
<< std::endl;
}
std::cout << std::endl;
auto search_3 = sb.searchByTag("tag5");
for (const auto& s : search_3) {
auto n = sb.getNoteById(s);
std::cout << "search by tag " << "'#tag5': "
<< " ID=" << n.getId()
<< " Title=" << n.getTitle()
<< std::endl;
}
std::cout << std::endl;
return 0;
}
| 35.905882 | 104 | 0.617628 |
olpotkin
|
28fda0af045e54a3671e62bbcc2d434c1e57a272
| 73,497 |
cpp
|
C++
|
src/tests/ClassPath/src/bstrwrap.cpp
|
TakuKitamura/verimqtt-c
|
30109f66df126e5860f2329ce2ad3cfb7f12d9da
|
[
"MIT"
] | 42 |
2020-03-15T22:07:04.000Z
|
2022-03-18T18:49:35.000Z
|
src/tests/ClassPath/src/bstrwrap.cpp
|
TakuKitamura/verimqtt-c
|
30109f66df126e5860f2329ce2ad3cfb7f12d9da
|
[
"MIT"
] | 6 |
2020-06-04T17:07:29.000Z
|
2021-02-17T14:49:05.000Z
|
src/tests/ClassPath/src/bstrwrap.cpp
|
TakuKitamura/verimqtt-c
|
30109f66df126e5860f2329ce2ad3cfb7f12d9da
|
[
"MIT"
] | 9 |
2020-08-07T11:49:08.000Z
|
2022-02-20T14:15:35.000Z
|
/*
* This source file is part of the bstring string library. This code was
* written by Paul Hsieh in 2002 - 2006, and is covered by the BSD open source
* license. Refer to the accompanying documentation for details on usage and
* license.
*/
/*
* bstrwrap.c
*
* This file is the C++ wrapper for the bstring functions.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <limits.h>
#include <ctype.h>
#include "../include/Strings/bstring.hpp"
#include "../include/Strings/VerySimpleReadOnlyString.hpp"
#if defined(BSTRLIB_MEMORY_DEBUG)
#include "memdbg.h"
#endif
// Forward declare the uint64 serializer
namespace Strings { char* ulltoa(uint64 value, char* result, int base); }
namespace Bstrlib
{
// Constructors.
String::String()
{
slen = 0; mlen = 8;
data = (unsigned char*)malloc(mlen);
if (!data)
{
mlen = 0;
bstringThrow("Failure in default constructor");
}
else data[0] = '\0';
}
String::String(const void * blk, int len)
{
slen = mlen = 0; data = 0;
if (len >= 0)
{
mlen = len + 1;
slen = len;
data = (uint8 * ) malloc(mlen);
}
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in block constructor");
}
else
{
if (slen > 0 && blk) memcpy(data, blk, slen);
data[slen] = '\0';
}
}
String::String(const void * ownedBlock, const int len, const int allocLen)
{
slen = len; mlen = allocLen; data = (unsigned char*)ownedBlock;
}
String::String(char c, int len)
{
slen = mlen = 0; data = 0;
if (len >= 0)
{
mlen = len + 1;
slen = len;
data = (uint8 * ) malloc(mlen);
}
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in repeat(char) constructor");
}
else
{
if (slen > 0) memset(data, c, slen);
data[slen] = '\0';
}
}
String::String(char c)
{
slen = mlen = 0; data = 0;
data = (unsigned char*)malloc(2);
if (data)
{
data[0] = (unsigned char)c;
data[1] = '\0';
mlen = 2; slen = 1;
} else
bstringThrow("Failure in (char) constructor");
}
String::String(unsigned char c)
{
slen = mlen = 0; data = 0;
data = (unsigned char*)malloc(2);
if (data)
{
data[0] = c;
data[1] = '\0';
mlen = 2; slen = 1;
} else
bstringThrow("Failure in (char) constructor");
}
String::String(const char *s)
{
slen = mlen = 0; data = 0;
if (s)
{
slen = (int)strlen(s);
mlen = slen + 1;
data = (unsigned char*)malloc(mlen);
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in (char *) constructor");
}
else memcpy(data, s, mlen);
}
}
String::String(int len, const char *s)
{
slen = mlen = 0; data = 0;
if (s)
{
slen = (int)strlen(s);
mlen = slen + 1;
if (mlen < len)
mlen = len;
data = (uint8 * ) malloc(mlen);
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in (int len, char *) constructor");
}
memcpy(data, s, slen + 1);
}
}
String::String(const String& b)
{
slen = b.slen;
mlen = slen + 1;
data = 0;
if (mlen > 0)
data = (uint8 * ) malloc(mlen);
if (!data)
{
bstringThrow("Failure in (String) constructor");
}
else
{
memcpy(data, b.data, slen);
data[slen] = '\0';
}
}
String::String(const tagbstring& x)
{
slen = x.slen;
mlen = slen + 1;
data = 0;
if (slen >= 0 && x.data != NULL)
data = (uint8 * ) malloc(mlen);
if (!data)
{
bstringThrow("Failure in (tagbstring) constructor");
}
else
{
memcpy(data, x.data, slen);
data[slen] = '\0';
}
}
String::String(const Strings::VerySimpleReadOnlyString & b)
{
slen = mlen = 0; data = 0;
if (b.getLength() >= 0)
{
mlen = b.getLength() + 1;
slen = b.getLength();
data = (uint8 * ) malloc(mlen);
}
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in block constructor");
}
else
{
if (slen > 0 && b.getData()) memcpy(data, b.getData(), slen);
data[slen] = '\0';
}
}
// Destructor.
String::~String()
{
if (data != NULL)
{
free(data);
data = NULL;
}
mlen = 0;
slen = -__LINE__;
}
// = operator.
const String& String::operator=(char c)
{
if (mlen <= 0) bstringThrow("Write protection error");
if (2 >= mlen) Alloc(2);
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in =(char) operator");
}
else
{
slen = 1;
data[0] = (unsigned char) c;
data[1] = '\0';
}
return *this;
}
const String& String::operator=(unsigned char c)
{
if (mlen <= 0) bstringThrow("Write protection error");
if (2 >= mlen) Alloc(2);
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in =(char) operator");
}
else
{
slen = 1;
data[0] = c;
data[1] = '\0';
}
return *this;
}
const String& String::operator=(const char *s)
{
int tmpSlen;
if (mlen <= 0) bstringThrow("Write protection error");
if (NULL == s) s = "";
if ((tmpSlen = (int)strlen(s)) >= mlen) Alloc(tmpSlen);
if (data)
{
slen = tmpSlen;
memcpy(data, s, tmpSlen + 1);
}
else
{
mlen = slen = 0;
bstringThrow("Failure in =(const char *) operator");
}
return *this;
}
const String& String::operator=(const String& b)
{
if (&b == this) return *this;
if (mlen <= 0) bstringThrow("Write protection error");
if (b.slen >= mlen) Alloc(b.slen);
slen = b.slen;
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in =(String) operator");
}
else
{
memcpy(data, b.data, slen);
data[slen] = '\0';
}
return *this;
}
const String& String::operator=(const tagbstring& x)
{
if (mlen <= 0) bstringThrow("Write protection error");
if (x.slen < 0) bstringThrow("Failure in =(tagbstring) operator, badly formed tagbstring");
if (x.slen >= mlen) Alloc(x.slen);
slen = x.slen;
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in =(tagbstring) operator");
}
else
{
memcpy(data, x.data, slen);
data[slen] = '\0';
}
return *this;
}
const String& String::operator +=(const String& b)
{
if (BSTR_ERR == bconcat(this, (bstring)&b))
bstringThrow("Failure in concatenate");
return *this;
}
const String& String::operator +=(const char *s)
{
struct tagbstring x;
char * d;
int i, l;
if (mlen <= 0) bstringThrow("Write protection error");
/* Optimistically concatenate directly */
l = mlen - slen;
d = (char *) &data[slen];
for (i = 0; i < l; i++)
{
if ((*d++ = *s++) == '\0')
{
slen += i;
return *this;
}
}
slen += i;
cstr2tbstr(x, s);
if (BSTR_ERR == bconcat(this, &x)) bstringThrow("Failure in concatenate");
return *this;
}
const String& String::operator +=(char c)
{
if (BSTR_ERR == bconchar(this, c)) bstringThrow("Failure in concatenate");
return *this;
}
const String& String::operator +=(unsigned char c)
{
if (BSTR_ERR == bconchar(this, (char) c)) bstringThrow("Failure in concatenate");
return *this;
}
const String& String::operator +=(const tagbstring& x)
{
if (mlen <= 0) bstringThrow("Write protection error");
if (x.slen < 0) bstringThrow("Failure in +=(tagbstring) operator, badly formed tagbstring");
Alloc(x.slen + slen + 1);
if (!data)
{
mlen = slen = 0;
bstringThrow("Failure in +=(tagbstring) operator");
}
else
{
memcpy(data + slen, x.data, x.slen);
slen += x.slen;
data[slen] = '\0';
}
return *this;
}
const String String::operator+(char c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(unsigned char c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(const String& b) const
{
String retval(*this);
retval += b;
return retval;
}
const String String::operator+(const char *s) const
{
String retval(*this);
if (s == NULL) return retval;
retval += s;
return retval;
}
const String String::operator+(const uint8 * s) const
{
String retval(*this);
if (s == NULL) return retval;
retval +=(char *) s;
return retval;
}
const String String::operator+(const int c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(const unsigned int c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(const float c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(const double c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(const int64 c) const
{
String retval(*this);
retval += c;
return retval;
}
const String String::operator+(const uint64 c) const
{
String retval(*this);
retval += c;
return retval;
}
const String& String::operator +=(const int c)
{
#ifndef HasFloatParsing
char buffer[12] = { c < 0 ? '-': '\0' };
utoa((unsigned long)(c < 0 ? -c : c), &buffer[c < 0 ? 1 : 0], 10);
return *this += buffer;
#else
return *this += String::Print("%d", c);
#endif
}
const String& String::operator +=(const unsigned int c)
{
#ifndef HasFloatParsing
char buffer[11] = { 0 };
utoa((unsigned long)c, buffer, 10);
return *this += buffer;
#else
return *this += String::Print("%u", c);
#endif
}
const String& String::operator +=(const int64 c)
{
#ifndef HasFloatParsing
char buffer[22] = { c < 0 ? '-': '\0' };
Strings::ulltoa((uint64)(c < 0 ? -c : c), &buffer[c < 0 ? 1 : 0], 10);
return *this += buffer;
#else
return *this += String::Print(PF_LLD, c);
#endif
}
const String& String::operator +=(const uint64 c)
{
#ifndef HasFloatParsing
char buffer[21] = { 0 };
Strings::ulltoa(c, buffer, 10);
return *this += buffer;
#else
return *this += String::Print(PF_LLU, c);
#endif
}
String String::getHexOf(const uint64 c)
{
char buffer[23] = { '0', 'x' };
Strings::ulltoa(c, buffer+2, 16);
return String(buffer);
}
int64 String::parseInt(int base, int * endPos) const
{
const char * text = (const char*)data;
if (!slen) { if (endPos) *endPos = 0; return 0; }
bool negative = text[0] == '-';
text += (int)negative;
const char baseText[] = "0123456789abcdef", BASEText[] = "0123456789ABCDEF";
// Check the current base, if auto detection is activated
if (!base)
{
if (text[0] != '0') base = 10;
else switch(text[1])
{
case 'X': case 'x': base = 16; text += 2; break;
case 'B': case 'b': base = 2; text += 2; break;
default: base = 8; text += 1; break;
}
}
// Let's start conversion
int64 ret = 0;
while (text)
{
const char * charPos = strchr(baseText, *text);
int digit = (int)(charPos - baseText);
if (charPos == NULL && base > 10) { charPos = strchr(BASEText, *text); digit = (int)(charPos - BASEText); }
if (charPos == NULL) break;
if (digit >= base) break;
ret = ret * base + digit;
text++;
}
if (endPos) *endPos = (int)(text - (const char*)data);
return negative ? -ret : ret;
}
const String& String::operator +=(const float c)
{
#ifndef HasFloatParsing
char buffer[15] = { 0 };
ftoa(c, buffer, 6);
return *this += buffer;
#else
return *this += String::Print("%lg", c);
#endif
}
const String& String::operator +=(const double c)
{
#ifndef HasFloatParsing
char buffer[15] = { 0 };
ftoa((float)c, buffer, 6);
return *this += buffer;
#else
return *this += String::Print("%lg", c);
#endif
}
const String String::operator+(const tagbstring& x) const
{
if (x.slen < 0) bstringThrow("Failure in + (tagbstring) operator, badly formed tagbstring");
String retval(*this);
retval += x;
return retval;
}
bool String::operator ==(const String& b) const
{
int retval;
if (BSTR_ERR ==(retval = biseq((bstring)this, (bstring)&b))) bstringThrow("Failure in compare (==)");
return retval != 0;
}
bool String::operator ==(const char * s) const
{
int retval;
if (NULL == s) return slen == 0;
if (BSTR_ERR ==(retval = biseqcstr((bstring) this, s))) bstringThrow("Failure in compare (==)");
return retval != 0;
}
bool String::operator ==(const uint8 * s) const
{
int retval;
if (NULL == s) return slen == 0;
if (BSTR_ERR ==(retval = biseqcstr((bstring) this, (char *) s))) bstringThrow("Failure in compare (==)");
return retval != 0;
}
bool String::operator !=(const String& b) const
{
return !((*this) == b);
}
bool String::operator !=(const char * s) const
{
return !((*this) == s);
}
bool String::operator !=(const uint8 * s) const
{
return !((*this) == s);
}
bool String::operator <(const String& b) const
{
int retval;
if (SHRT_MIN ==(retval = bstrcmp((bstring) this, (bstring)&b)))
bstringThrow("Failure in compare (<)");
return retval < 0;
}
bool String::operator <(const char * s) const
{
if (NULL == s) return false;
return strcmp((const char *)this->data, s) < 0;
}
bool String::operator <(const uint8 * s) const
{
if (NULL == s) return false;
return strcmp((const char *)this->data, (const char *)s) < 0;
}
bool String::operator <=(const String& b) const
{
int retval;
if (SHRT_MIN ==(retval = bstrcmp((bstring) this, (bstring)&b))) bstringThrow("Failure in compare (<=)");
return retval <= 0;
}
bool String::operator <=(const char * s) const
{
if (NULL == s) return slen == 0;
return strcmp((const char *)this->data, s) <= 0;
}
bool String::operator <=(const uint8 * s) const
{
if (NULL == s) return slen == 0;
return strcmp((const char *)this->data, (const char *)s) <= 0;
}
bool String::operator >(const String& b) const
{
return !((*this) <= b);
}
bool String::operator >(const char * s) const
{
return !((*this) <= s);
}
bool String::operator >(const uint8 * s) const
{
return !((*this) <= s);
}
bool String::operator >=(const String& b) const
{
return !((*this) < b);
}
bool String::operator >=(const char * s) const
{
return !((*this) < s);
}
bool String::operator >=(const uint8 * s) const
{
return !((*this) < s);
}
#ifdef HasFloatParsing
String::operator double() const
{
return parseDouble();
}
String::operator float() const
{
return (float)parseDouble();
}
double String::parseDouble(int * consumed) const
{
char * ep = NULL;
double ret = data ? strtod((const char*)data, &ep) : 0;
if (consumed) *consumed = (int)(ep - (const char*)data);
return ret;
}
#endif
String::operator signed int() const
{
return (signed int)parseInt(10);
}
String::operator unsigned int() const
{
return (unsigned int)parseInt(10);
}
String::operator int64() const
{
return (int64)parseInt(10);
}
int String::Scan(const char * fmt, void * data) const
{
return sscanf((const char *)this->data, fmt, data);
}
#ifdef __TURBOC__
# ifndef BSTRLIB_NOVSNP
# define BSTRLIB_NOVSNP
# endif
#endif
/* Give WATCOM C/C++, MSVC some latitude for their non - support of vsnprintf */
#if defined(__WATCOMC__) || defined(_MSC_VER)
#define exvsnprintf(r,b,n,f,a) {r = _vsnprintf (b,n,f,a);}
#else
#ifdef BSTRLIB_NOVSNP
/* This is just a hack. If you are using a system without a vsnprintf, it is
not recommended that bformat be used at all. */
#define exvsnprintf(r,b,n,f,a) {vsprintf (b,f,a); r = -1;}
#define START_VSNBUFF (256)
#else
#if defined(__GNUC__) && !defined(__PPC__)
/* Something is making gcc complain about this prototype not being here, so
I've just gone ahead and put it in. */
extern "C"
{
extern int vsnprintf(char *buf, size_t count, const char *format, va_list arg);
}
#endif
#define exvsnprintf(r,b,n,f,a) {r = vsnprintf (b,n,f,a);}
#endif
#endif
#ifndef START_VSNBUFF
#define START_VSNBUFF (16)
#endif
/*
* Yeah I'd like to just call a vformat function or something, but because of
* the ANSI specified brokeness of the va_* macros, it is actually not
* possible to do this correctly.
*/
String & String::Format(const char * fmt, ...)
{
bstring b;
va_list arglist;
int r, n;
if (mlen <= 0) bstringThrow("Write protection error");
if (fmt == NULL)
*this = "<NULL>";
else
{
if ((b = bfromcstr("")) == NULL)
{
*this = "<NULL>";
}
else
{
if ((n = 2*(int)strlen(fmt)) < START_VSNBUFF)
n = START_VSNBUFF;
for (;;)
{
if (BSTR_OK != balloc(b, n + 2))
{
b = bformat("<OUTM>");
break;
}
va_start(arglist, fmt);
exvsnprintf(r, (char *) b->data, n + 1, fmt, arglist);
va_end(arglist);
b->data[n] = '\0';
b->slen = (int)strlen((char *) b->data);
if (b->slen < n) break;
if (r > n) n = r;
else n += n;
}
*this = *b;
bdestroy(b);
}
}
return *this;
}
/*
* Yeah I'd like to just call a vformat function or something, but because of
* the ANSI specified brokeness of the va_* macros, it is actually not
* possible to do this correctly.
*/
String String::Print(const char * fmt, ...)
{
bstring b;
va_list arglist;
int r, n;
String ret;
if (fmt == NULL) return ret;
else
{
if ((b = bfromcstr("")) == NULL)
{
ret = "<NULL>";
}
else
{
if ((n = 2*(int)strlen(fmt)) < START_VSNBUFF)
n = START_VSNBUFF;
for (;;)
{
if (BSTR_OK != balloc(b, n + 2))
{
b = bformat("<OUTM>");
break;
}
va_start(arglist, fmt);
exvsnprintf(r, (char *) b->data, n + 1, fmt, arglist);
va_end(arglist);
b->data[n] = '\0';
b->slen = (int)strlen((char *) b->data);
if (b->slen < n) break;
if (r > n) n = r;
else n += n;
}
ret = *b;
bdestroy(b);
}
}
return ret;
}
void String::Formata(const char * fmt, ...)
{
bstring b;
va_list arglist;
int r, n;
if (mlen <= 0) bstringThrow("Write protection error");
if (fmt == NULL)
{
*this += "<NULL>";
}
else
{
if ((b = bfromcstr("")) == NULL)
{
*this += "<NULL>";
}
else
{
if ((n = 2*(int)strlen(fmt)) < START_VSNBUFF)
n = START_VSNBUFF;
for (;;)
{
if (BSTR_OK != balloc(b, n + 2))
{
b = bformat("<OUTM>");
break;
}
va_start(arglist, fmt);
exvsnprintf(r, (char *) b->data, n + 1, fmt, arglist);
va_end(arglist);
b->data[n] = '\0';
b->slen = (int)strlen((char *) b->data);
if (b->slen < n) break;
if (r > n) n = r;
else n += n;
}
*this += *b;
bdestroy(b);
}
}
}
bool String::caselessEqual(const String& b) const
{
int ret;
if (BSTR_ERR ==(ret = biseqcaseless((bstring) this, (bstring) &b))) bstringThrow("String::caselessEqual Unable to compare");
return ret == 1;
}
int String::caselessCmp(const String& b) const
{
int ret;
if (SHRT_MIN ==(ret = bstricmp((bstring) this, (bstring) &b))) bstringThrow("String::caselessCmp Unable to compare");
return ret;
}
int String::Count(const String & b) const
{
int i = 0, j = 0;
int count = 0;
for (; i + j < slen; )
{
if ((unsigned char) b[j] == data[i + j])
{
j++;
if (j == b.slen) { i+= j; j = 0; count ++; continue; }
continue;
}
i++;
j = 0;
}
return count;
}
int String::Find(const String& b, int pos) const
{
return binstr((bstring) this, pos, (bstring) &b);
}
int String::Find(const char * b, int pos) const
{
int i, j;
if (NULL == b) return BSTR_ERR;
if ((unsigned int) pos > (unsigned int) slen)
return BSTR_ERR;
if ('\0' == b[0]) return pos;
if (pos == slen) return BSTR_ERR;
i = pos;
j = 0;
for (; i + j < slen; )
{
if ((unsigned char) b[j] == data[i + j])
{
j++;
if ('\0' == b[j]) return i;
continue;
}
i++;
j = 0;
}
return BSTR_ERR;
}
int String::caselessFind(const String& b, int pos) const
{
return binstrcaseless((bstring) this, pos, (bstring) &b);
}
int String::caselessFind(const char * b, int pos) const
{
struct tagbstring t;
if (NULL == b) return BSTR_ERR;
if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR;
if ('\0' == b[0]) return pos;
if (pos == slen) return BSTR_ERR;
btfromcstr(t, b);
return binstrcaseless((bstring) this, pos, (bstring) &t);
}
int String::Find(char c, int pos) const
{
if (pos < 0) return BSTR_ERR;
for (; pos < slen; pos++)
{
if (data[pos] ==(unsigned char) c)
return pos;
}
return BSTR_ERR;
}
int String::reverseFind(const String& b, int pos) const
{
return binstrr((bstring) this, pos, (bstring) &b);
}
int String::reverseFind(const char * b, int pos) const
{
struct tagbstring t;
if (NULL == b) return BSTR_ERR;
cstr2tbstr(t, b);
return binstrr((bstring) this, pos, &t);
}
int String::caselessReverseFind(const String& b, int pos) const
{
return binstrrcaseless((bstring) this, pos, (bstring) &b);
}
int String::caselessReverseFind(const char * b, int pos) const
{
struct tagbstring t;
if (NULL == b) return BSTR_ERR;
if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR;
if ('\0' == b[0]) return pos;
if (pos == slen) return BSTR_ERR;
btfromcstr(t, b);
return binstrrcaseless((bstring) this, pos, (bstring) &t);
}
int String::reverseFind(char c, int pos) const
{
if (pos < 0) pos = slen-1;
if (pos > slen) return BSTR_ERR;
if (pos == slen) pos--;
for (; pos >= 0; pos--)
{
if (data[pos] ==(unsigned char) c) return pos;
}
return BSTR_ERR;
}
int String::findAnyChar(const String& b, int pos) const
{
return binchr((bstring) this, pos, (bstring) &b);
}
int String::findAnyChar(const char * s, int pos) const
{
struct tagbstring t;
if (NULL == s) return BSTR_ERR;
cstr2tbstr(t, s);
return binchr((bstring) this, pos, (bstring) &t);
}
int String::invFindAnyChar(const String& b, int pos) const
{
return bninchr((bstring) this, pos, (bstring) &b);
}
int String::invFindAnyChar(const char * s, int pos) const
{
struct tagbstring t;
if (NULL == s) return BSTR_ERR;
cstr2tbstr(t, s);
return bninchr((bstring) this, pos, &t);
}
int String::reverseFindAnyChar(const String& b, int pos) const
{
return binchrr((bstring) this, pos, (bstring) &b);
}
int String::reverseFindAnyChar(const char * s, int pos) const
{
struct tagbstring t;
if (NULL == s) return BSTR_ERR;
cstr2tbstr(t, s);
return binchrr((bstring) this, pos, &t);
}
int String::invReverseFindAnyChar(const String& b, int pos) const
{
return bninchrr((bstring) this, pos, (bstring) &b);
}
int String::invReverseFindAnyChar(const char * s, int pos) const
{
struct tagbstring t;
if (NULL == s) return BSTR_ERR;
cstr2tbstr(t, s);
return bninchrr((bstring) this, pos, &t);
}
String String::extractToken(char c, int & pos) const
{
String ret;
if (pos >= slen) return ret;
int findNextPos = Find(c, pos);
if (findNextPos == -1) findNextPos = slen;
ret = midString(pos, findNextPos - pos);
pos = findNextPos + 1;
return ret;
}
const String String::midString(int left, int len) const
{
struct tagbstring t;
if (len < 0)
{ // Want data from the right of the string, without specifying the start point
// For example String("abcdefgh").midString(0, -3) => "abcde"
if (-len >= slen) left = 0;
else
{ // Check for String("abcdef").midString(-3, -1) => "de"
if (left < 0) { left = max(0, slen + left); len = slen + len - left; }
else len += slen;
}
}
if (left < 0)
{ // Want data from the right of the string
len = len > -left ? -left : len;
left = slen + left;
}
if (len > slen - left) len = slen - left;
if (len <= 0 || left < 0) return String("");
blk2tbstr(t, data + left, len);
return String(t);
}
char * String::Alloc(int length)
{
if (BSTR_ERR == balloc((bstring)this, length)) bstringThrow("Failure in Alloc");
return (char*)data;
}
void String::Fill(int length, unsigned char fill)
{
slen = 0;
if (BSTR_ERR == bsetstr(this, length, NULL, fill)) bstringThrow("Failure in fill");
}
void String::setSubstring(int pos, const String& b, unsigned char fill)
{
if (BSTR_ERR == bsetstr(this, pos, (bstring) &b, fill)) bstringThrow("Failure in setstr");
}
void String::setSubstring(int pos, const char * s, unsigned char fill)
{
struct tagbstring t;
if (NULL == s) return;
cstr2tbstr(t, s);
if (BSTR_ERR == bsetstr(this, pos, &t, fill))
{
bstringThrow("Failure in setstr");
}
}
void String::Insert(int pos, const String& b, unsigned char fill)
{
if (BSTR_ERR == binsert(this, pos, (bstring) &b, fill)) bstringThrow("Failure in insert");
}
void String::Insert(int pos, const char * s, unsigned char fill)
{
struct tagbstring t;
if (NULL == s) return;
cstr2tbstr(t, s);
if (BSTR_ERR == binsert(this, pos, &t, fill)) bstringThrow("Failure in insert");
}
void String::insertChars(int pos, int len, unsigned char fill)
{
if (BSTR_ERR == binsertch(this, pos, len, fill)) bstringThrow("Failure in insertchrs");
}
void String::Replace(int pos, int len, const String& b, unsigned char fill)
{
if (BSTR_ERR == breplace(this, pos, len, (bstring) &b, fill)) bstringThrow("Failure in Replace");
}
void String::Replace(int pos, int len, const char * s, unsigned char fill)
{
struct tagbstring t;
int q;
if (mlen <= 0) bstringThrow("Write protection error");
if (NULL == s || (pos | len) < 0) return;
if (pos + len >= slen)
{
cstr2tbstr(t, s);
if (BSTR_ERR == bsetstr(this, pos, &t, fill))
bstringThrow("Failure in Replace");
else if (pos + t.slen < slen)
{
slen = pos + t.slen;
data[slen] = '\0';
}
}
else
{
/* Aliasing case */
if ((unsigned int)(data - (uint8 * ) s) < (unsigned int) slen)
{
Replace(pos, len, String(s), fill);
return;
}
if ((q = (int)strlen(s)) > len)
{
Alloc(slen + q - len);
if (NULL == data) return;
}
if (q != len) memmove(data + pos + q, data + pos + len, slen - (pos + len));
memcpy(data + pos, s, q);
slen += q - len;
data[slen] = '\0';
}
}
String & String::findAndReplace(const String& find, const String& repl, int pos)
{
if (BSTR_ERR == bfindreplace(this, (bstring) &find, (bstring) &repl, pos)) bstringThrow("Failure in findreplace");
return *this;
}
String & String::findAndReplace(const String& find, const char * repl, int pos)
{
struct tagbstring t;
if (NULL == repl) return *this;
cstr2tbstr(t, repl);
if (BSTR_ERR == bfindreplace(this, (bstring) &find, (bstring) &t, pos)) bstringThrow("Failure in findreplace");
return *this;
}
String & String::findAndReplace(const char * find, const String& repl, int pos)
{
struct tagbstring t;
if (NULL == find) return *this;
cstr2tbstr(t, find);
if (BSTR_ERR == bfindreplace(this, (bstring) &t, (bstring) &repl, pos)) bstringThrow("Failure in findreplace");
return *this;
}
String & String::findAndReplace(const char * find, const char * repl, int pos)
{
struct tagbstring t, u;
if (NULL == repl || NULL == find) return *this;
cstr2tbstr(t, find);
cstr2tbstr(u, repl);
if (BSTR_ERR == bfindreplace(this, (bstring) &t, (bstring) &u, pos)) bstringThrow("Failure in findreplace");
return *this;
}
String & String::findAndReplaceCaseless(const String& find, const String& repl, int pos)
{
if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &find, (bstring) &repl, pos)) bstringThrow("Failure in findreplacecaseless");
return *this;
}
String & String::findAndReplaceCaseless(const String& find, const char * repl, int pos)
{
struct tagbstring t;
if (NULL == repl) return *this;
cstr2tbstr(t, repl);
if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &find, (bstring) &t, pos)) bstringThrow("Failure in findreplacecaseless");
return *this;
}
String & String::findAndReplaceCaseless(const char * find, const String& repl, int pos)
{
struct tagbstring t;
if (NULL == find) return *this;
cstr2tbstr(t, find);
if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &t, (bstring) &repl, pos)) bstringThrow("Failure in findreplacecaseless");
return *this;
}
String & String::findAndReplaceCaseless(const char * find, const char * repl, int pos)
{
struct tagbstring t, u;
if (NULL == repl || NULL == find) return *this;
cstr2tbstr(t, find);
cstr2tbstr(u, repl);
if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &t, (bstring) &u, pos)) bstringThrow("Failure in findreplacecaseless");
return *this;
}
void String::Remove(int pos, int len)
{
if (BSTR_ERR == bdelete(this, pos, len)) bstringThrow("Failure in remove");
}
void String::Truncate(int len)
{
if (len < 0) return;
if (len < slen)
{
slen = len;
data[len] = '\0';
}
}
void String::leftTrim(const String& b)
{
if (!b.slen) return;
int l = invFindAnyChar(b, 0);
if (l == BSTR_ERR) l = slen;
Remove(0, l);
}
void String::rightTrim(const String& b)
{
if (!b.slen) return;
int l = invReverseFindAnyChar(b, slen - 1);
if (l == BSTR_ERR) l = slen - 1;
slen = l + 1;
if (mlen > slen) data[slen] = '\0';
}
void String::toUppercase()
{
if (BSTR_ERR == btoupper((bstring) this)) bstringThrow("Failure in toupper");
}
void String::toLowercase()
{
if (BSTR_ERR == btolower((bstring) this)) bstringThrow("Failure in tolower");
}
void String::Repeat(int count)
{
count *= slen;
if (count <= 0)
{
Truncate(0);
return;
}
if (BSTR_ERR == bpattern(this, count)) bstringThrow("Failure in repeat");
}
/*
int String::gets(bNgetc getcPtr, void * parm, char terminator)
{
if (mlen <= 0) bstringThrow("Write protection error");
bstring b = bgets(getcPtr, parm, terminator);
if (b == NULL)
{
slen = 0;
return -1;
}
*this = *b;
bdestroy(b);
return 0;
}
int String::read(bNread readPtr, void * parm)
{
if (mlen <= 0) bstringThrow("Write protection error");
bstring b = bread(readPtr, parm);
if (b == NULL)
{
slen = 0;
return -1;
}
*this = *b;
bdestroy(b);
return 0;
}
*/
const String operator+(const char *a, const String& b)
{
return String(a) + b;
}
const String operator+(const uint8 * a, const String& b)
{
return String((const char *)a) + b;
}
const String operator+(char c, const String& b)
{
return String(c) + b;
}
const String operator+(unsigned char c, const String& b)
{
return String(c) + b;
}
const String operator+(const tagbstring& x, const String& b)
{
return String(x) + b;
}
String String::normalizedPath(char sep, const bool includeLastSep) const
{
int rightLimit = slen - 1;
while (rightLimit >= 0 && data[rightLimit] == sep) rightLimit--;
return includeLastSep || rightLimit < 0 ? midString(0, rightLimit+1) + sep : midString(0, rightLimit+1);
}
String & String::replaceAllTokens(char from, char to)
{
if (!from || !to) return *this;
for (int i = 0; i < slen; i++)
if (data[i] == from) data[i] = to;
return *this;
}
String String::replacedAll(const String & find, const String & by) const
{
int count = Count(find);
int replacedLength = (slen + count * (by.slen - find.slen)) + 1;
char * rep = (char*)malloc(replacedLength);
if (rep == NULL) return String();
int pos = 0, repos = 0, newPos = 0;
while ((newPos = Find(find, pos)) != -1)
{
memcpy(&rep[repos], &data[pos], (newPos - pos));
repos += (newPos - pos);
memcpy(&rep[repos], by.data, by.slen);
repos += by.slen;
newPos += find.slen;
pos = newPos;
}
// Copy the remaining part
if (pos < slen)
{
memcpy(&rep[repos], &data[pos], slen - pos);
repos += slen - pos;
}
rep[repos] = '\0';
return String(rep, replacedLength - 1, replacedLength);
}
// Get the string up to the first occurrence of the given string
const String String::upToFirst(const String & find, const bool includeFind) const
{
int pos = Find(find, 0);
if (pos == -1) return includeFind ? "" : *this;
return midString(0, includeFind ? pos + find.getLength() : pos);
}
// Get the string up to the last occurrence of the given string
const String String::upToLast(const String & find, const bool includeFind) const
{
int pos = reverseFind(find, slen - 1);
if (pos == -1) return includeFind ? "" : *this;
return midString(0, includeFind ? pos + find.getLength() : pos);
}
// Get the string from the first occurrence of the given string
const String String::fromFirst(const String & find, const bool includeFind) const
{
int pos = Find(find, 0);
if (pos == -1) return includeFind ? *this : String();
return midString(includeFind ? pos : pos + find.getLength(), slen);
}
// Get the string from the first occurrence of the given string
const String String::dropUpTo(const String & find, const bool includeFind) const
{
const unsigned int pos = Find(find);
if (pos == (unsigned int)-1) return *this;
return midString(includeFind ? pos : pos + find.getLength(), slen);
}
// Get the string from the last occurrence of the given string
const String String::fromLast(const String & find, const bool includeFind) const
{
int pos = reverseFind(find, slen - 1);
if (pos == -1) return includeFind ? *this : String();
return midString(includeFind ? pos : pos + find.getLength(), slen);
}
// Split a string when the needle is found first, returning the part before the needle, and
// updating the string to start on or after the needle.
const String String::splitFrom(const String & find, const bool includeFind)
{
int pos = Find(find, 0);
if (pos == -1)
{
if (includeFind)
{
String ret(*this);
*this = "";
return ret;
}
return String();
}
int size = pos + find.getLength();
String ret = midString(0, includeFind ? size : pos);
if (BSTR_ERR == bdelete(this, 0, size)) bstringThrow("Failure in remove");
return ret;
}
// Split a string when the needle is found first, returning the part before the needle, and
// updating the string to start on or after the needle.
const String String::fromTo(const String & from, const String & to, const bool includeFind) const
{
const int fromPos = Find(from);
if (fromPos == -1) return "";
const int toPos = Find(to, fromPos + from.slen);
return midString(includeFind ? fromPos : fromPos + from.slen, toPos != -1 ? (includeFind ? toPos + to.slen - fromPos : toPos - fromPos - from.slen)
// If the "to" needle was not found, either we return the whole string (includeFind) or an empty string
: (includeFind ? slen - fromPos : 0));
}
// Get the substring up to the given needle if found, or the whole string if not, and split from here.
const String String::splitUpTo(const String & find, const bool includeFind)
{
int pos = Find(find, 0);
if (pos == -1)
{
String ret(*this);
*this = "";
return ret;
}
int size = pos + find.getLength();
String ret = midString(0, includeFind ? size : pos);
if (BSTR_ERR == bdelete(this, 0, size)) bstringThrow("Failure in remove");
return ret;
}
// Split the string at the given position.
const String String::splitAt(const int pos)
{
String ret = midString(0, pos);
if (BSTR_ERR == bdelete(this, 0, pos)) bstringThrow("Failure in remove");
return ret;
}
// Split the string when no more in the given set
const String String::splitWhenNoMore(const String & set)
{
int pos = invFindAnyChar(set);
String ret = midString(0, pos == -1 ? slen : pos);
if (BSTR_ERR == bdelete(this, 0, ret.slen)) bstringThrow("Failure in remove");
return ret;
}
// Align the string so it fits in the given length.
String String::alignedTo(const int length, int side, char fill) const
{
if (slen > length) return *this;
int diffInSize = (length - slen),
leftCount = side == 1 ? diffInSize : (side == 0 ? diffInSize / 2 : 0),
rightCount = side == -1 ? diffInSize : (side == 0 ? (diffInSize + 1) / 2 : 0);
return String().Filled(leftCount, fill) + *this + Filled(rightCount, fill);
}
void String::writeProtect()
{
if (mlen >= 0) mlen = -1;
}
void String::writeAllow()
{
if (mlen == -1) mlen = slen + (slen == 0);
else if (mlen < 0) bstringThrow("Cannot unprotect a constant");
}
uint32 getUnicode(const unsigned char * & array)
{
// Get the current char
const uint8 c = *array;
if ((c & 0x80))
{
// The data is in the 7 low bits
uint32 dataMask = 0x7f;
// The count bit mask
uint32 bitCountMask = 0x40;
// The consumption count
int charCount = 0;
while ((c & bitCountMask) != 0 && bitCountMask)
{
++charCount;
dataMask >>= 1; bitCountMask >>= 1;
}
// Get the few bits remaining here
uint32 n = (c & dataMask);
// Then extract the remaining bits
++array;
while (--charCount >= 0 && *array)
{
const uint8 extra = *array;
// Make sure it's a valid UTF8 encoding
if ((extra & 0xc0) != 0x80) break;
// Store the new bits too
n <<= 6; n |= (extra & 0x3f);
++array;
}
return n;
}
if (c) ++array;
return c;
}
int getUnicodeCharCount(const unsigned char * array)
{
const uint8 c = *array;
if ((c & 0x80))
{
// The count bit mask
uint32 bitCountMask = 0x40;
// The consumption count
int charCount = 0;
while ((c & bitCountMask) != 0 && bitCountMask)
{
++charCount;
bitCountMask >>= 1;
}
return charCount;
}
return c == 0 ? 0 : 1;
}
// Get the i-th unicode char.
uint32 String::getUnicodeChar(int pos) const
{
// 1. Iterate to the given position
const unsigned char * array = data;
while (pos && *array)
{
(void)getUnicode(array);
pos--;
}
return getUnicode(array);
}
// This counts the number of Unicode characters in the string.
size_t String::getUnicodeLength() const
{
size_t size = 0;
unsigned char * array = data, * end = data + slen;
int cnt = getUnicodeCharCount(&array[size]);
while (cnt && array < end)
{
size ++;
array += cnt;
cnt = getUnicodeCharCount(array);
}
return size;
}
#if (WantRegularExpressions == 1)
// Forward declare the functions we'll be using
namespace RegExp
{
#define TestReturn(cond, error) if (cond) return (error)
struct Branch
{
/** Index of the bracket pair */
int bracketIndex;
/** Position of branching in the regular expression */
const char * branchPos;
};
struct BracketPair
{
/** Index of the branch for this pair */
int branchIndex;
/** The number of branches in this pair */
int branchesCount;
/** First char after '(' in expression */
const char * ptr;
/** Text length in char between parenthesis */
int len;
};
/** A Capture */
struct Cap
{
const char * ptr;
int len;
};
/** Default construct the information with stack based allocation, and only expand if required to heap based allocation */
struct RegexpInfo
{
enum RegExError
{
NotFound = -1,
SyntaxError = -2,
UnexpectedQuantifier = -3,
UnbalancedBrackets = -4,
BadSetOfCharacter = -5,
BadMetaCharacter = -6,
CapturesArrayTooSmall = -7,
NotEnoughMemory = -8,
};
/** Store all branches in the regular expression. */
Branch * branches;
int branchesCount;
/** Store all brackets pair in the expression. The first entry contains the whole expression */
BracketPair * brackets;
int bracketsCount;
/* Array of captures provided by the user */
Cap * caps;
int capsCount;
/** You can use (?i) to start the Regular Expression, or use caseInsensitive search while matching */
bool caseSensitive;
/** First position for the match */
int firstMatchPos;
/** The stack based allocation for the branches */
Branch stackBranch[10];
/** The stack based allocation for the pairs */
BracketPair stackPair[10];
/** Construction */
RegexpInfo(Cap * capts, int capsCount, bool caseSensitive = true)
: branches(stackBranch), branchesCount(0), brackets(stackPair), bracketsCount(0), caps(capts), capsCount(capsCount), caseSensitive(caseSensitive), firstMatchPos(-1)
{}
~RegexpInfo()
{
if (branches != stackBranch) { free(branches); branches = 0; }
if (brackets != stackPair) { free(brackets); brackets = 0; }
}
/** This is used for marking allowed metacharacters and quantifiers */
static uint8 charMap[256];
bool addBrackets(const char * ptr, int len)
{
if ((size_t)(bracketsCount + 1) >= ArrSz(stackPair))
{
// Need to re-allocate the brackets pair
BracketPair * newPair = (BracketPair *)malloc((bracketsCount + 1) * sizeof(BracketPair));
if (!newPair) return false;
memcpy(newPair, brackets, bracketsCount * sizeof(BracketPair));
if (brackets != stackPair) free(brackets);
brackets = newPair;
}
brackets[bracketsCount].ptr = ptr;
brackets[bracketsCount].len = len;
bracketsCount++;
return true;
}
bool addBranch(int index, const char * pos)
{
if ((size_t)(branchesCount + 1) >= ArrSz(stackBranch))
{
// Need to re-allocate the brackets pair
Branch * newBranch = (Branch *)malloc((branchesCount + 1) * sizeof(Branch));
if (!newBranch) return false;
memcpy(newBranch, branches, branchesCount * sizeof(Branch));
if (branches != stackBranch) free(branches);
branches = newBranch;
}
branches[branchesCount].bracketIndex = index;
branches[branchesCount].branchPos = pos;
branchesCount++;
return true;
}
/** Helper functions */
static inline int operatorLen(const char *re) { return re[0] == '\\' && re[1] == 'x' ? 4 : re[0] == '\\' ? 2 : 1; }
static inline int getOperatorLen(const char *re, int regExpLen)
{
if (re[0] != '[') return operatorLen(re);
int len = 1;
while (len < regExpLen && re[len] != ']') len += operatorLen(re + len);
return regExpLen > len ? len + 1 : 0;
}
static inline int hexToInteger(const uint8 * s) { return (charMap[s[0]] & 0xF0) | (charMap[s[1]] >> 4); }
int matchOperand(const uint8 * re, const uint8 * s)
{
switch (*re)
{
// If we reach those, the expression is malformed
case '|': return SyntaxError;
case '$': return NotFound;
// Any char would do, let's accept it
case '.': break;
case '\\':
// Metacharacters
switch (re[1])
{
case 'S':
TestReturn((charMap[*s] & 4), NotFound);
break;
case 's':
TestReturn(!(charMap[*s] & 4), NotFound);
break;
case 'd':
TestReturn(!(charMap[*s] & 8), NotFound);
break;
case 'x':
// Match byte, \xHH where HH is hexadecimal byte representaion
TestReturn(hexToInteger(re + 2) != *s, NotFound);
break;
default:
// Valid metacharacter check is done in internalProcess()
TestReturn(re[1] != s[0], NotFound);
break;
}
break;
// Any normal character
default:
if (!caseSensitive)
{
TestReturn(tolower(*re) != tolower(*s), NotFound);
} else
{
TestReturn(*re != *s, NotFound);
}
break;
}
return 1;
}
// This is used to match a "[]" based set
int matchSet(const char *re, int regExpLen, const char *s)
{
int len = 0, result = -1, invert = re[0] == '^';
// If the set is inverted, eat the first char
if (invert) re++,regExpLen--;
// Inverted logic, result should stay 0 for matching
while (len <= regExpLen && re[len] != ']' && result <= 0)
{
// Check range
if ( (re[len] != '-' && re[len + 1] == '-' && re[len + 2] != ']')
&& (re[len + 2] != '\0'))
{
result = !caseSensitive ? (*s >= re[len] && *s <= re[len + 2]) :
(tolower(*s) >= tolower(re[len]) && tolower(*s) <= tolower(re[len + 2]));
len += 3;
} else
{
result = matchOperand((uint8 * )re + len, (uint8 *)s);
len += operatorLen(re + len);
}
}
return (invert && result <= 0) || (!invert && result > 0) ? 1 : -1;
}
int internalProcess(const char *re, int regExpLen, const char *s, int s_len, int bracketIndex)
{
int reIndex = 0, strIndex = 0, n, step;
for (reIndex = strIndex = 0; reIndex < regExpLen && strIndex <= s_len; reIndex += step)
{
// Handle quantifiers. Get the length of the chunk.
step = re[reIndex] == '(' ? brackets[bracketIndex + 1].len + 2 : getOperatorLen(re + reIndex, regExpLen - reIndex);
TestReturn(charMap[(uint8)re[reIndex]] & 2, UnexpectedQuantifier);
TestReturn(step <= 0, BadSetOfCharacter);
// Is it a quantifier ?
if (reIndex + step < regExpLen && (charMap[(uint8)re[reIndex + step]] & 2))
{
if (re[reIndex + step] == '?')
{ // Zero or once
int result = internalProcess(re + reIndex, step, s + strIndex, s_len - strIndex, bracketIndex);
strIndex += result > 0 ? result : 0; // Silent failure
reIndex++;
} else if (re[reIndex + step] == '+' || re[reIndex + step] == '*')
{ // Zero|One or more
bool greedy = true;
int strMatchEndIndex = strIndex, strEndIndex = strIndex, strFirstMatchIndex, strSecondMatchIndex = -1, reEndIndex;
// Check for greedyness mode
reEndIndex = reIndex + step + 1;
if (reEndIndex < regExpLen && re[reEndIndex] == '?')
{
greedy = false;
reEndIndex++;
}
do
{
// Match the quantified expression only once
if ((strFirstMatchIndex = internalProcess(re + reIndex, step, s + strMatchEndIndex, s_len - strMatchEndIndex, bracketIndex)) > 0)
strMatchEndIndex += strFirstMatchIndex;
// Is only one match required (and this one failed) ?
if (re[reIndex + step] == '+' && strFirstMatchIndex < 0) break;
// Check if we have something after quantifier
if (reEndIndex >= regExpLen)
// Nothing left in expression after quantifier, let's try to eat as much as possible
strEndIndex = strMatchEndIndex;
// Try to match the rest of the expression after the quantifier
else if ((strSecondMatchIndex = internalProcess(re + reEndIndex, regExpLen - reEndIndex, s + strMatchEndIndex, s_len - strMatchEndIndex, bracketIndex)) >= 0)
// Matched after quantifier
strEndIndex = strMatchEndIndex + strSecondMatchIndex;
// Continue if greedy and something else to eat
if (strEndIndex > strIndex && !greedy) break;
} while (strFirstMatchIndex > 0);
// Try zero match too (try to match the rest of the expression after quantifier)
if (strFirstMatchIndex < 0 && re[reIndex + step] == '*' && strSecondMatchIndex < 0 &&
(strSecondMatchIndex = internalProcess(re + reEndIndex, regExpLen - reEndIndex, s + strIndex, s_len - strIndex, bracketIndex)) > 0)
strEndIndex = strIndex + strSecondMatchIndex;
TestReturn(re[reIndex + step] == '+' && strEndIndex == strIndex, NotFound);
// Check the rest of the regex in case of zero match (ie: on *)
TestReturn(strEndIndex == strIndex && reEndIndex < regExpLen && strSecondMatchIndex < 0, NotFound);
// Expression matched completely
return strEndIndex;
}
continue;
}
n = 0;
switch(re[reIndex])
{
// Is a set ?
case '[':
n = matchSet(re + reIndex + 1, regExpLen - (reIndex + 2), s + strIndex);
TestReturn(n <= 0, NotFound);
break;
// Is a bracket ?
case '(':
n = NotFound;
bracketIndex++;
TestReturn(bracketIndex >= bracketsCount, SyntaxError);
if (regExpLen - (reIndex + step) <= 0)
{
// Nothing after the bracket
n = processBranch(s + strIndex, s_len - strIndex, bracketIndex);
} else
{
// Need to process the branch, and then the remaining expression
int j2;
for (j2 = 0; j2 <= s_len - strIndex; j2++)
{
if ( (n = processBranch(s + strIndex, s_len - (strIndex + j2), bracketIndex)) >= 0
&& internalProcess(re + reIndex + step, regExpLen - (reIndex + step), s + strIndex + n, s_len - (strIndex + n), bracketIndex) >= 0)
break;
}
}
TestReturn(n < 0, n);
if (caps != NULL && n > 0)
{
caps[bracketIndex - 1].ptr = s + strIndex;
caps[bracketIndex - 1].len = n;
}
break;
// Begin of section
case '^':
TestReturn(strIndex != 0, NotFound);
break;
// End of section
case '$':
TestReturn(strIndex != s_len, NotFound);
break;
default:
TestReturn(strIndex >= s_len, NotFound);
n = matchOperand((uint8 * ) (re + reIndex), (uint8 * ) (s + strIndex));
TestReturn(n <= 0, n);
break;
}
strIndex += n;
}
return strIndex;
}
// Process branch points
int processBranch(const char *s, int s_len, int branchIndex)
{
const BracketPair * b = &brackets[branchIndex];
int i = 0, len, result;
const char *p;
do
{
p = i == 0 ? b->ptr : branches[b->branchIndex + i - 1].branchPos + 1;
len = b->branchesCount == 0 ? b->len : (i == b->branchesCount ? b->ptr + b->len - p : branches[b->branchIndex + i].branchPos - p);
result = internalProcess(p, len, s, s_len, branchIndex);
} while (result <= 0 && i++ < b->branchesCount); // At least 1 iteration
return result;
}
int process(const char *s, int s_len)
{
int result = -1;
bool isAnchored = brackets[0].ptr[0] == '^';
for (int i = 0; i <= s_len; i++)
{
result = processBranch(s + i, s_len - i, 0);
if (result >= 0)
{ // Completed search
firstMatchPos = i;
result += i;
break;
}
if (isAnchored) break;
}
return result;
}
void setupBranchPoints()
{
int i, j;
Branch tmp;
// Sort branches first based on bracketIndex
for (i = 0; i < branchesCount; i++)
{
for (j = i + 1; j < branchesCount; j++)
{
if (branches[i].bracketIndex > branches[j].bracketIndex)
{
tmp = branches[i];
branches[i] = branches[j];
branches[j] = tmp;
}
}
}
// Sort brackets too to know beforehand where (and how many branches) the branches points
for (i = j = 0; i < bracketsCount; i++)
{
brackets[i].branchesCount = 0;
brackets[i].branchIndex = j;
while (j < branchesCount && branches[j].bracketIndex == i)
{
brackets[i].branchesCount++;
j++;
}
}
}
int analyze(const char *re, int regExpLen, const char *s, int s_len, int & capsRequired)
{
int step = 0, depth = 0;
// Capture the complete expression in the first bracket
TestReturn(!addBrackets(re, regExpLen), NotEnoughMemory);
// Compute the number of brackets and branches required, and test basic validity for the expression
for (int i = 0; i < regExpLen; i += step)
{
step = getOperatorLen(re + i, regExpLen - i);
if (re[i] == '|')
{
TestReturn(!addBranch(brackets[bracketsCount - 1].len == -1 ? bracketsCount - 1 : depth, re+i), NotEnoughMemory);
} else if (re[i] == '\\')
{
TestReturn(i >= regExpLen - 1, BadMetaCharacter);
if (re[i + 1] == 'x')
{
// Hex digit specification must follow hexadecimal numbers
TestReturn(re[i + 1] == 'x' && i >= regExpLen - 3, BadMetaCharacter);
TestReturn(re[i + 1] == 'x' && !((charMap[(uint8)re[i + 2]] & 0xF8) && (charMap[(uint8)re[i + 3]] & 0xF8)), BadMetaCharacter);
} else
{
TestReturn((RegexpInfo::charMap[(uint8)re[i + 1]] & 1) == 0, BadMetaCharacter);
}
} else if (re[i] == '(')
{
// Need to increment the depth to set the correct index on matching parenthesis
depth++;
TestReturn(!addBrackets(re+i+1, -1), NotEnoughMemory);
capsRequired++;
TestReturn(s && capsCount > 0 && bracketsCount - 1 > capsCount, CapturesArrayTooSmall);
} else if (re[i] == ')')
{
// Fix index
int ind = brackets[bracketsCount - 1].len == -1 ? bracketsCount - 1 : depth;
brackets[ind].len = &re[i] - brackets[ind].ptr;
depth--;
TestReturn(depth < 0, UnbalancedBrackets);
// Shortcut bad expression failure
TestReturn(i > 0 && re[i - 1] == '(', NotFound);
}
}
TestReturn(depth != 0, UnbalancedBrackets);
setupBranchPoints();
return 0;
}
};
// Stores : bit 0 = metacharacter
// bit 1 = quantifier
// bit 2 = space
// bit 3 = digit
// bit 4-7 = hex/decimal value
uint8 RegexpInfo::charMap[] =
{
0 /* 0 */, 0 /* 1 */, 0 /* 2 */, 0 /* 3 */, 0 /* 4 */, 0 /* 5 */, 0 /* 6 */, 0 /* 7 */, 0 /* 8 */, 4 /* 9 */, 4 /* 10 */, 4 /* 11 */, 4 /* 12 */, 4 /* 13 */, 0 /* 14 */, 0 /* 15 */,
0 /* 16 */, 0 /* 17 */, 0 /* 18 */, 0 /* 19 */, 0 /* 20 */, 0 /* 21 */, 0 /* 22 */, 0 /* 23 */, 0 /* 24 */, 0 /* 25 */, 0 /* 26 */, 0 /* 27 */, 0 /* 28 */, 0 /* 29 */, 0 /* 30 */, 0 /* 31 */,
4 /* ' ' */, 0 /* '!' */, 0 /* '"' */, 0 /* '#' */, 1 /* '$' */, 0 /* '%' */, 0 /* '&' */, 0 /* ''' */, 1 /* '(' */, 1 /* ')' */, 3 /* '*' */, 3 /* '+' */, 0 /* ',' */, 0 /* '-' */, 1 /* '.' */, 0 /* '/' */,
8 /* '0' */, 0x18 /* '1' */, 0x28 /* '2' */, 0x38 /* '3' */, 0x48 /* '4' */, 0x58 /* '5' */, 0x68 /* '6' */, 0x78 /* '7' */, 0x88 /* '8' */, 0x98 /* '9' */, 0 /* ':' */, 0 /* ';' */, 0 /* '<' */, 0 /* '=' */, 0 /* '>' */, 3 /* '?' */,
0 /* '@' */, 0xA0 /* 'A' */, 0xB0 /* 'B' */, 0xC0 /* 'C' */, 0xD0 /* 'D' */, 0xE0 /* 'E' */, 0xF0 /* 'F' */, 0 /* 'G' */, 0 /* 'H' */, 0 /* 'I' */, 0 /* 'J' */, 0 /* 'K' */, 0 /* 'L' */, 0 /* 'M' */, 0 /* 'N' */, 0 /* 'O' */,
0 /* 'P' */, 0 /* 'Q' */, 0 /* 'R' */, 1 /* 'S' */, 0 /* 'T' */, 0 /* 'U' */, 0 /* 'V' */, 0 /* 'W' */, 0 /* 'X' */, 0 /* 'Y' */, 0 /* 'Z' */, 1 /* '[' */, 1 /* '\' */, 1 /* ']' */, 1 /* '^' */, 0 /* '_' */,
0 /* '`' */, 0xA0 /* 'a' */, 0xB0 /* 'b' */, 0xC0 /* 'c' */, 0xD1 /* 'd' */, 0xE0 /* 'e' */, 0xF0 /* 'f' */, 0 /* 'g' */, 0 /* 'h' */, 0 /* 'i' */, 0 /* 'j' */, 0 /* 'k' */, 0 /* 'l' */, 0 /* 'm' */, 0 /* 'n' */, 0 /* 'o' */,
0 /* 'p' */, 0 /* 'q' */, 0 /* 'r' */, 1 /* 's' */, 0 /* 't' */, 0 /* 'u' */, 0 /* 'v' */, 0 /* 'w' */, 0 /* 'x' */, 0 /* 'y' */, 0 /* 'z' */, 0 /* '{' */, 1 /* '|' */, 0 /* '}' */, 0 /* '~' */, 0 /* '' */,
};
static int RegExpMatch(const char *regexp, const char *s, int s_len, Cap * caps, int capsCount, int & capsRequired, bool caseSensitive, int * matchPos = 0)
{
if (memcmp(regexp, "(?i)", 4) == 0)
{
caseSensitive = false;
regexp += 4;
}
RegexpInfo info(caps, capsCount, caseSensitive);
capsRequired = 0;
int res = info.analyze(regexp, strlen(regexp), s, s_len, capsRequired);
if (res != 0) return res;
if (!s) return 0;
res = info.process(s, s_len);
if (matchPos) *matchPos = info.firstMatchPos;
return res;
}
}
// Match the expression against the compiled regular expression
int String::regExMatch(const String & regEx, String * captures, int & capCount, const bool caseSensitive, int * matchPos) const
{
// If no captures, run a trial run to get the amount of captures required
if (!captures)
return RegExp::RegExpMatch(regEx, (const char*)0, 0, 0, 0, capCount, caseSensitive);
RegExp::Cap * caps = new RegExp::Cap[capCount];
if (!caps) return NotEnoughMemory;
memset(caps, 0, capCount * sizeof(*caps));
int res = RegExp::RegExpMatch(regEx, (const char*)data, slen, caps, capCount, capCount, caseSensitive, matchPos);
for (int i = 0; i < capCount; i++)
captures[i] = String(caps[i].ptr, caps[i].len);
delete[] caps;
return res;
}
// Fit the regular expression for this string
bool String::regExFit(const String & regEx, const bool caseSensitive, void ** captOpt, int * captCount) const
{
int localCap = 0; void * localOpt = 0;
int & capturesCount = captCount ? *captCount : localCap;
void * & capturesOpt = captOpt ? *captOpt : localOpt;
if (!capturesCount || !capturesOpt)
{
if (RegExp::RegExpMatch(regEx, (const char*)0, 0, 0, 0, capturesCount, caseSensitive) < 0) return false;
// Allocate the buffer now
capturesOpt = malloc(capturesCount * sizeof(RegExp::Cap));
}
// Cast the buffer to something we can support
RegExp::Cap * caps = (RegExp::Cap *)capturesOpt;
if (!caps) return false;
memset(caps, 0, capturesCount * sizeof(*caps));
int req = 0;
int res = RegExp::RegExpMatch(regEx, (const char*)data, slen, caps, capturesCount, req, caseSensitive);
if (&capturesOpt == &localOpt) free(localOpt);
return res >= 0;
}
// Return a string with value replaced as regular expression
String String::regExReplace(const String & regEx, const String & _with, const bool caseSensitive, int iterations) const
{
int capCount = 0;
int res = RegExp::RegExpMatch(regEx, (const char*)0, 0, 0, 0, capCount, caseSensitive);
if (res) return "";
RegExp::Cap * caps = new RegExp::Cap[capCount + 1];
if (!caps) return "";
int processedData = 0;
String ret;
while(iterations--)
{
memset(caps, 0, capCount * sizeof(*caps));
String with = _with;
int matchPos = 0;
res = RegExp::RegExpMatch(regEx, (const char*)data + processedData, slen - processedData, caps+1, capCount, capCount, caseSensitive, &matchPos);
if (res <= 0) break;
caps[0].ptr = (const char*)data + processedData + matchPos; caps[0].len = res - processedData - matchPos;
ret += midString(processedData, matchPos) + with.splitUpTo("\\");
while (with.slen)
{
int noMoreDigitPos = with.invFindAnyChar("0123456789");
if (noMoreDigitPos == 0) { ret += '\\'; }
else if (noMoreDigitPos == -1) { noMoreDigitPos = with.getLength(); }
if (noMoreDigitPos > 0)
{
int pos = with.midString(0, noMoreDigitPos).parseInt(10);
if (pos <= capCount)
{
ret += String(caps[pos].ptr, caps[pos].len);
with.splitAt(noMoreDigitPos);
}
else
{
// Output the slashed text
ret += '\\'; ret += with.data[0];
with.splitAt(1);
}
}
// Output the rest
ret += with.splitUpTo("\\");
}
processedData += res;
}
// Copy the remaining part
ret += midString(processedData, slen);
delete[] caps;
return ret;
}
#endif
} // namespace Bstrlib
| 32.738085 | 234 | 0.466876 |
TakuKitamura
|
e9005849663072c857de6b3ce39173f8d237bd98
| 6,361 |
cpp
|
C++
|
src/appleseed/renderer/modeling/bsdf/bsdfsample.cpp
|
joelbarmettlerUZH/appleseed
|
6da8ff684aa33648a247a4d4005bb4595862e0b3
|
[
"MIT"
] | 1,907 |
2015-01-04T00:13:22.000Z
|
2022-03-30T15:14:00.000Z
|
src/appleseed/renderer/modeling/bsdf/bsdfsample.cpp
|
joelbarmettlerUZH/appleseed
|
6da8ff684aa33648a247a4d4005bb4595862e0b3
|
[
"MIT"
] | 1,196 |
2015-01-04T10:50:01.000Z
|
2022-03-04T09:18:22.000Z
|
src/appleseed/renderer/modeling/bsdf/bsdfsample.cpp
|
joelbarmettlerUZH/appleseed
|
6da8ff684aa33648a247a4d4005bb4595862e0b3
|
[
"MIT"
] | 373 |
2015-01-06T10:08:53.000Z
|
2022-03-12T10:25:57.000Z
|
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2018 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "bsdfsample.h"
// appleseed.foundation headers.
#include "foundation/math/basis.h"
// Standard headers.
#include <cmath>
using namespace foundation;
namespace renderer
{
namespace
{
void compute_normal_derivatives(
const BSDF::LocalGeometry& local_geometry,
const Vector3f& o,
const Vector3f& dodx,
const Vector3f& dody,
foundation::Vector3f& dndx,
foundation::Vector3f& dndy,
float& ddndx,
float& ddndy)
{
//
// Reference:
//
// Physically Based Rendering, first edition, page 513.
//
const Vector3f dndu(local_geometry.m_shading_point->get_dndu(0));
const Vector3f dndv(local_geometry.m_shading_point->get_dndv(0));
const Vector2f duvdx(local_geometry.m_shading_point->get_duvdx(0));
const Vector2f duvdy(local_geometry.m_shading_point->get_duvdy(0));
dndx = dndu * duvdx[0] + dndv * duvdx[1];
dndy = dndu * duvdy[0] + dndv * duvdy[1];
const Vector3f& n = local_geometry.m_shading_basis.get_normal();
ddndx = dot(dodx, n) + dot(o, dndx);
ddndy = dot(dody, n) + dot(o, dndy);
}
}
//
// BSDFSample class implementation.
//
void BSDFSample::compute_specular_reflected_differentials(
const BSDF::LocalGeometry& local_geometry,
const Dual3f& outgoing)
{
if (outgoing.has_derivatives())
{
//
// Reference:
//
// Physically Based Rendering, first edition, page 513.
//
const Vector3f dodx = -(outgoing.get_dx() - outgoing.get_value());
const Vector3f dody = -(outgoing.get_dy() - outgoing.get_value());
Vector3f dndx, dndy;
float ddndx, ddndy;
compute_normal_derivatives(
local_geometry,
outgoing.get_value(),
dodx,
dody,
dndx,
dndy,
ddndx,
ddndy);
const Vector3f& n = local_geometry.m_shading_basis.get_normal();
const float dot_on = dot(outgoing.get_value(), n);
const Vector3f& i = m_incoming.get_value();
m_incoming.set_derivatives(
i - dodx + 2.0f * Vector3f(dot_on * dndx + ddndx * n),
i - dody + 2.0f * Vector3f(dot_on * dndy + ddndy * n));
}
}
void BSDFSample::compute_specular_transmitted_differentials(
const BSDF::LocalGeometry& local_geometry,
const float eta,
const bool is_entering,
const Dual3f& outgoing)
{
if (outgoing.has_derivatives())
{
const Vector3f dodx = -(outgoing.get_dx() - outgoing.get_value());
const Vector3f dody = -(outgoing.get_dy() - outgoing.get_value());
Vector3f dndx, dndy;
float ddndx, ddndy;
compute_normal_derivatives(
local_geometry,
outgoing.get_value(),
dodx,
dody,
dndx,
dndy,
ddndx,
ddndy);
const Vector3f& n = local_geometry.m_shading_basis.get_normal();
const float dot_on = dot(-outgoing.get_value(), n);
const float dot_in = std::abs(dot(m_incoming.get_value(), n));
const float mu = eta * dot_on - dot_in;
const float a = eta - (square(eta) * dot_on) / dot_in;
const float dmudx = a * ddndx;
const float dmudy = a * ddndy;
const Vector3f& i = m_incoming.get_value();
m_incoming.set_derivatives(
i - eta * dodx - Vector3f(mu * dndx + dmudx * n),
i - eta * dody - Vector3f(mu * dndy + dmudy * n));
}
}
void BSDFSample::compute_glossy_reflected_differentials(
const BSDF::LocalGeometry& local_geometry,
const float roughness,
const Dual3f& outgoing)
{
// TODO: scale differentials based on roughness.
compute_specular_reflected_differentials(local_geometry, outgoing);
}
void BSDFSample::compute_glossy_transmitted_differentials(
const BSDF::LocalGeometry& local_geometry,
const float eta,
const float roughness,
const bool is_entering,
const Dual3f& outgoing)
{
// TODO: scale differentials based on roughness.
compute_specular_transmitted_differentials(
local_geometry,
eta,
is_entering,
outgoing);
}
void BSDFSample::compute_diffuse_differentials(const Dual3f& outgoing)
{
if (outgoing.has_derivatives())
{
// 1/25 of the hemisphere.
// Reference: https://www.pbrt.org/texcache.pdf
const auto& i = m_incoming.get_value();
const Basis3f basis(m_incoming.get_value());
m_incoming.set_derivatives(
normalize(i + 0.2f * basis.get_tangent_u()),
normalize(i + 0.2f * basis.get_tangent_v()));
}
}
} // namespace renderer
| 32.454082 | 80 | 0.622386 |
joelbarmettlerUZH
|
e90096d4600be5ce516dff8cb5d49840032d3696
| 4,037 |
cpp
|
C++
|
src/rschol/geometry/FiniteDifference.cpp
|
jeffc71/rank_structured_cholesky
|
1b5df69bd6b9187435897786e7461cdd341e8db0
|
[
"Unlicense"
] | 3 |
2017-09-07T16:14:33.000Z
|
2021-09-18T04:47:06.000Z
|
src/rschol/geometry/FiniteDifference.cpp
|
jeffchadwick/rank_structured_cholesky
|
1b5df69bd6b9187435897786e7461cdd341e8db0
|
[
"Unlicense"
] | null | null | null |
src/rschol/geometry/FiniteDifference.cpp
|
jeffchadwick/rank_structured_cholesky
|
1b5df69bd6b9187435897786e7461cdd341e8db0
|
[
"Unlicense"
] | null | null | null |
//////////////////////////////////////////////////////////////////////
// Copyright (c) 2015, Jeff Chadwick and David Bindel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// FiniteDifference.cpp: Implementation
//
//////////////////////////////////////////////////////////////////////
#include "FiniteDifference.h"
//////////////////////////////////////////////////////////////////////
// Stencils for finite difference laplacian operator
//////////////////////////////////////////////////////////////////////
const Real FiniteDifference::LAPLACIAN_STENCIL[] = { -1.0, 2.0, -1.0 };
const int FiniteDifference::LAPLACIAN_STENCIL_INDEX[] = { -1, 0, 1 };
const int FiniteDifference::LAPLACIAN_STENCIL_SZ = 3;
//////////////////////////////////////////////////////////////////////
// Generates a finite difference Laplacian matrix with Dirichlet
// boundary conditions, assuming a constant grid cell spacing of h
//////////////////////////////////////////////////////////////////////
void FiniteDifference::generateLaplacian( SPARSE_MATRIX &L,
Tuple3i gridDivisions,
Real h )
{
int sz = GRID_SIZE( gridDivisions );
Real inv_h2 = 1.0 / ( h * h );
L.resize( sz, sz );
L.clear();
FOR_ALL_3D_POINTS( gridDivisions, idx )
{
// Apply the Laplacian along each dimension
for ( int d = 0; d < 3; d++ )
{
for ( int lap_idx = 0; lap_idx < LAPLACIAN_STENCIL_SZ; lap_idx++ )
{
Tuple3i entry_idx = idx;
int row_idx = INDEX_3D_GRID( gridDivisions, idx );
int offset = LAPLACIAN_STENCIL_INDEX[ lap_idx ];
entry_idx[d] += offset;
if ( !checkFDIndex( gridDivisions, entry_idx ) )
continue;
int col_idx = INDEX_3D_GRID( gridDivisions, entry_idx );
L( row_idx, col_idx ) += LAPLACIAN_STENCIL[ lap_idx ] * inv_h2;
}
}
}
}
// Evaluates a function at all points of a finite difference grid
void FiniteDifference::evaluateGridEntries( const Tuple3i &gridDivisions, Real h,
const ScalarEvaluator &f,
VECTOR &x )
{
int sz = GRID_SIZE( gridDivisions );
VEC3F p;
int x_idx = 0;
x.resizeAndWipe( sz );
FOR_ALL_3D_POINTS( gridDivisions, idx )
{
p = assignPoint( idx, h );
x( x_idx ) = f( p );
x_idx++;
}
}
| 36.369369 | 81 | 0.583354 |
jeffc71
|
e902b84a9cfaa34c2c09dffbd1740b49dbc860ff
| 2,122 |
hpp
|
C++
|
file_access.hpp
|
piccolo255/mhd2d-solver
|
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
|
[
"Unlicense"
] | null | null | null |
file_access.hpp
|
piccolo255/mhd2d-solver
|
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
|
[
"Unlicense"
] | null | null | null |
file_access.hpp
|
piccolo255/mhd2d-solver
|
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
|
[
"Unlicense"
] | null | null | null |
#ifndef FILE_ACCESS_HPP_INCLUDED
#define FILE_ACCESS_HPP_INCLUDED
// Read value of a key, show warning and default value if the key is missing
template <class T>
T readEntry
( boost::property_tree::ptree pt
, std::string section
, std::string name
, T defaultValue );
// Read settings from property tree: Div B corrector
void readParamsDivBCorrector
( boost::property_tree::ptree &pt
, t_params ¶ms );
// Read settings from property tree: Shock tube problem
void readProblemShockTube
( boost::property_tree::ptree &pt
, t_params ¶ms
, t_data &data );
// Read settings from property tree: Explosion problem
void readProblemExplosion
( boost::property_tree::ptree &pt
, t_params ¶ms
, t_data &data );
// Read settings from property tree: Orszag-Tang vortex problem
void readProblemOTVortex
( boost::property_tree::ptree &pt
, t_params ¶ms
, t_data &data );
// Read settings from property tree: Plasma sheet problem
void readProblemPlasmaSheet
( boost::property_tree::ptree &pt
, t_params ¶ms
, t_data &data );
// Read settings from property tree: Wave test problem
void readProblemWaveTest
( boost::property_tree::ptree &pt
, t_params ¶ms
, t_data &data );
// Print info about the binary file structure (with hints for plotting with GNUplot)
void outputBinaryHintFile
( const std::string filename
, const t_params ¶ms
, const t_output &output_grid );
// Output grid data file in binary format
void outputGridDataBinary
( const t_output &output
, const t_params ¶ms
, const t_data &data
, int step
, int index
, int divb_nxfirst
, int divb_nxlast
, int divb_nyfirst
, int divb_nylast
, double uumax );
// Output grid data file in textual format
void outputGridDataText
( const t_output &output
, const t_params ¶ms
, const t_data &data
, int step
, int index
, int divb_nxfirst
, int divb_nxlast
, int divb_nyfirst
, int divb_nylast
, double uumax );
#endif // FILE_ACCESS_HPP_INCLUDED
| 26.525 | 84 | 0.696984 |
piccolo255
|
e902e7570e55f2b4279d1fec67f70f1d90a0049a
| 2,629 |
cpp
|
C++
|
Supermicro/benchmarks/maskrcnn/implementations/pytorch_SYS-420GP-TNAR/maskrcnn_benchmark/csrc/cuda/nhwc/transforms.cpp
|
gglin001/training_results_v1.1
|
58fd4103f0f465bda6eb56a06a74b7bbccbbcf24
|
[
"Apache-2.0"
] | 48 |
2020-07-29T18:09:23.000Z
|
2021-10-09T01:53:33.000Z
|
Supermicro/benchmarks/maskrcnn/implementations/pytorch_SYS-420GP-TNAR/maskrcnn_benchmark/csrc/cuda/nhwc/transforms.cpp
|
gglin001/training_results_v1.1
|
58fd4103f0f465bda6eb56a06a74b7bbccbbcf24
|
[
"Apache-2.0"
] | 21 |
2021-08-31T08:34:50.000Z
|
2022-03-17T11:42:10.000Z
|
NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/nhwc/transforms.cpp
|
lablup/training_results_v0.7
|
f5bb59aa0f8b18b602763abe47d1d24d0d54b197
|
[
"Apache-2.0"
] | 42 |
2020-08-01T06:41:24.000Z
|
2022-01-20T10:33:08.000Z
|
/******************************************************************************
*
* Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <ATen/Config.h>
#include <ATen/cuda/CUDAConfig.h>
#include <ATen/cuda/Exceptions.h>
#include <cudnn.h>
#include "THC/THC.h"
#include "torch/torch.h"
#include <ATen/cudnn/cudnn-wrapper.h>
#include "Descriptors.h"
//#include <ATen/cudnn/Types.h>
#include "Types.h"
#include <ATen/cudnn/Utils.h>
#include "ParamsHash.h"
#include <ATen/TensorUtils.h>
#include <functional>
#include <iterator>
#include <sstream>
#include <algorithm>
#include <memory>
#include <mutex>
#include <stdint.h>
#include <unordered_map>
namespace at { namespace native { namespace nhwc {
at::Tensor cudnnNhwcToNchw(const at::Tensor& input) {
int N = input.size(0);
int C = input.size(3);
int H = input.size(1);
int W = input.size(2);
at::Tensor output = at::empty({N,C,H,W}, input.options());
auto handle = getCudnnHandle();
auto dataType = getCudnnDataType(input);
at::native::nhwc::TensorDescriptor in_desc;
at::native::nchw::TensorDescriptor out_desc;
in_desc.set(input);
out_desc.set(output);
float alpha=1.0f;
float beta=0.0f;
cudnnTransformTensor(handle, &alpha, in_desc.desc(), input.data_ptr(), &beta, out_desc.desc(), output.data_ptr());
return output;
}
at::Tensor cudnnNchwToNhwc(const at::Tensor& input) {
int N = input.size(0);
int C = input.size(1);
int H = input.size(2);
int W = input.size(3);
at::Tensor output = at::empty({N,H,W,C}, input.options());
auto handle = getCudnnHandle();
auto dataType = getCudnnDataType(input);
at::native::nchw::TensorDescriptor in_desc;
at::native::nhwc::TensorDescriptor out_desc;
in_desc.set(input);
out_desc.set(output);
float alpha=1.0f;
float beta=0.0f;
cudnnTransformTensor(handle, &alpha, in_desc.desc(), input.data_ptr(), &beta, out_desc.desc(), output.data_ptr());
return output;
}
}}}
| 30.929412 | 116 | 0.670978 |
gglin001
|
e90363efe24449aee213324e34ea26d2fc0605bd
| 644 |
cpp
|
C++
|
NotSoFAT32/Fat32Directory.cpp
|
Rohansi/NotSoFAT32
|
fd6b6a5528b5af00518a83b3d1c2061a87b007e3
|
[
"MIT"
] | 1 |
2020-11-03T16:11:59.000Z
|
2020-11-03T16:11:59.000Z
|
NotSoFAT32/Fat32Directory.cpp
|
Rohansi/NotSoFAT32
|
fd6b6a5528b5af00518a83b3d1c2061a87b007e3
|
[
"MIT"
] | 1 |
2020-11-04T11:34:44.000Z
|
2020-11-04T11:34:44.000Z
|
NotSoFAT32/Fat32Directory.cpp
|
Rohansi/NotSoFAT32
|
fd6b6a5528b5af00518a83b3d1c2061a87b007e3
|
[
"MIT"
] | null | null | null |
#include "Interface/IFat32Directory.hpp"
#include "Fat32Directory.hpp"
#include "Fat32Root.hpp"
#include "Fat32File.hpp"
#include <algorithm>
#include <string>
Fat32Directory::Fat32Directory(std::weak_ptr<Fat32Disk> fat32, std::shared_ptr<DirectoryEntry> entry)
: IFat32Directory(fat32)
{
m_fat32 = fat32;
m_entry = entry;
}
Fat32Directory::Fat32Directory(Fat32Directory &&other)
: IFat32Directory(std::move(other))
{
m_fat32 = std::move(other.m_fat32);
m_entry = std::move(other.m_entry);
}
void Fat32Directory::initialize()
{
IFat32Directory::m_entry = std::move(m_entry);
IFat32Directory::initialize();
}
| 23 | 101 | 0.728261 |
Rohansi
|
e9072b9c77026ef3859d16d1fb06f7b3292b71ea
| 4,641 |
cc
|
C++
|
compiler/optimizing/dex_cache_array_fixups_arm.cc
|
lifansama/xposed_art_n
|
ec3fbe417d74d4664cec053d91dd4e3881176374
|
[
"MIT"
] | 234 |
2017-07-18T05:30:27.000Z
|
2022-01-07T02:21:31.000Z
|
compiler/optimizing/dex_cache_array_fixups_arm.cc
|
lifansama/xposed_art_n
|
ec3fbe417d74d4664cec053d91dd4e3881176374
|
[
"MIT"
] | 21 |
2017-07-18T04:56:09.000Z
|
2018-08-10T17:32:16.000Z
|
compiler/optimizing/dex_cache_array_fixups_arm.cc
|
lifansama/xposed_art_n
|
ec3fbe417d74d4664cec053d91dd4e3881176374
|
[
"MIT"
] | 56 |
2017-07-18T10:37:10.000Z
|
2022-01-07T02:19:22.000Z
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dex_cache_array_fixups_arm.h"
#include "base/arena_containers.h"
#include "utils/dex_cache_arrays_layout-inl.h"
namespace art {
namespace arm {
/**
* Finds instructions that need the dex cache arrays base as an input.
*/
class DexCacheArrayFixupsVisitor : public HGraphVisitor {
public:
explicit DexCacheArrayFixupsVisitor(HGraph* graph)
: HGraphVisitor(graph),
dex_cache_array_bases_(std::less<const DexFile*>(),
// Attribute memory use to code generator.
graph->GetArena()->Adapter(kArenaAllocCodeGenerator)) {}
void MoveBasesIfNeeded() {
for (const auto& entry : dex_cache_array_bases_) {
// Bring the base closer to the first use (previously, it was in the
// entry block) and relieve some pressure on the register allocator
// while avoiding recalculation of the base in a loop.
HArmDexCacheArraysBase* base = entry.second;
base->MoveBeforeFirstUserAndOutOfLoops();
}
}
private:
void VisitLoadString(HLoadString* load_string) OVERRIDE {
// If this is a load with PC-relative access to the dex cache methods array,
// we need to add the dex cache arrays base as the special input.
if (load_string->GetLoadKind() == HLoadString::LoadKind::kDexCachePcRelative) {
// Initialize base for target dex file if needed.
const DexFile& dex_file = load_string->GetDexFile();
HArmDexCacheArraysBase* base = GetOrCreateDexCacheArrayBase(dex_file);
// Update the element offset in base.
DexCacheArraysLayout layout(kArmPointerSize, &dex_file);
base->UpdateElementOffset(layout.StringOffset(load_string->GetStringIndex()));
// Add the special argument base to the load.
load_string->AddSpecialInput(base);
}
}
void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
// If this is an invoke with PC-relative access to the dex cache methods array,
// we need to add the dex cache arrays base as the special input.
if (invoke->HasPcRelativeDexCache()) {
// Initialize base for target method dex file if needed.
MethodReference target_method = invoke->GetTargetMethod();
HArmDexCacheArraysBase* base = GetOrCreateDexCacheArrayBase(*target_method.dex_file);
// Update the element offset in base.
DexCacheArraysLayout layout(kArmPointerSize, target_method.dex_file);
base->UpdateElementOffset(layout.MethodOffset(target_method.dex_method_index));
// Add the special argument base to the method.
DCHECK(!invoke->HasCurrentMethodInput());
invoke->AddSpecialInput(base);
}
}
HArmDexCacheArraysBase* GetOrCreateDexCacheArrayBase(const DexFile& dex_file) {
// Ensure we only initialize the pointer once for each dex file.
auto lb = dex_cache_array_bases_.lower_bound(&dex_file);
if (lb != dex_cache_array_bases_.end() &&
!dex_cache_array_bases_.key_comp()(&dex_file, lb->first)) {
return lb->second;
}
// Insert the base at the start of the entry block, move it to a better
// position later in MoveBaseIfNeeded().
HArmDexCacheArraysBase* base = new (GetGraph()->GetArena()) HArmDexCacheArraysBase(dex_file);
HBasicBlock* entry_block = GetGraph()->GetEntryBlock();
entry_block->InsertInstructionBefore(base, entry_block->GetFirstInstruction());
dex_cache_array_bases_.PutBefore(lb, &dex_file, base);
return base;
}
using DexCacheArraysBaseMap =
ArenaSafeMap<const DexFile*, HArmDexCacheArraysBase*, std::less<const DexFile*>>;
DexCacheArraysBaseMap dex_cache_array_bases_;
};
void DexCacheArrayFixups::Run() {
if (graph_->HasIrreducibleLoops()) {
// Do not run this optimization, as irreducible loops do not work with an instruction
// that can be live-in at the irreducible loop header.
return;
}
DexCacheArrayFixupsVisitor visitor(graph_);
visitor.VisitInsertionOrder();
visitor.MoveBasesIfNeeded();
}
} // namespace arm
} // namespace art
| 41.070796 | 97 | 0.721181 |
lifansama
|
e9086e1fbdc59a6691aded7cb2e54cb31b51dba5
| 15,212 |
cpp
|
C++
|
nfc/src/DOOM/doomclassic/timidity/resample.cpp
|
1337programming/leviathan
|
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
|
[
"Apache-2.0"
] | null | null | null |
nfc/src/DOOM/doomclassic/timidity/resample.cpp
|
1337programming/leviathan
|
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
|
[
"Apache-2.0"
] | null | null | null |
nfc/src/DOOM/doomclassic/timidity/resample.cpp
|
1337programming/leviathan
|
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
|
[
"Apache-2.0"
] | null | null | null |
/*
TiMidity -- Experimental MIDI to WAVE converter
Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
resample.c
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "config.h"
#include "common.h"
#include "instrum.h"
#include "playmidi.h"
#include "output.h"
#include "controls.h"
#include "tables.h"
#include "resample.h"
#ifdef LINEAR_INTERPOLATION
# if defined(LOOKUP_HACK) && defined(LOOKUP_INTERPOLATION)
# define RESAMPLATION \
v1=src[ofs>>FRACTION_BITS];\
v2=src[(ofs>>FRACTION_BITS)+1];\
*dest++ = v1 + (iplookup[(((v2-v1)<<5) & 0x03FE0) | \
((ofs & FRACTION_MASK) >> (FRACTION_BITS-5))]);
# else
# define RESAMPLATION \
v1=src[ofs>>FRACTION_BITS];\
v2=src[(ofs>>FRACTION_BITS)+1];\
*dest++ = v1 + (((v2-v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS);
# endif
# define INTERPVARS sample_t v1, v2
#else
/* Earplugs recommended for maximum listening enjoyment */
# define RESAMPLATION *dest++=src[ofs>>FRACTION_BITS];
# define INTERPVARS
#endif
#define FINALINTERP if (ofs == le) *dest++=src[ofs>>FRACTION_BITS];
/* So it isn't interpolation. At least it's final. */
extern sample_t *resample_buffer;
void Real_Tim_Free( void *pt );
/*************** resampling with fixed increment *****************/
static sample_t *rs_plain(int v, int32_t *countptr)
{
/* Play sample until end, then free the voice. */
INTERPVARS;
Voice
*vp=&voice[v];
sample_t
*dest=resample_buffer,
*src=vp->sample->data;
int32_t
ofs=vp->sample_offset,
incr=vp->sample_increment,
le=vp->sample->data_length,
count=*countptr;
#ifdef PRECALC_LOOPS
int32_t i;
if (incr<0) incr = -incr; /* In case we're coming out of a bidir loop */
/* Precalc how many times we should go through the loop.
NOTE: Assumes that incr > 0 and that ofs <= le */
i = (le - ofs) / incr + 1;
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
while (i--)
{
RESAMPLATION;
ofs += incr;
}
if (ofs >= le)
{
FINALINTERP;
vp->status=VOICE_FREE;
ctl->note(v);
*countptr-=count+1;
}
#else /* PRECALC_LOOPS */
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs >= le)
{
FINALINTERP;
vp->status=VOICE_FREE;
ctl->note(v);
*countptr-=count+1;
break;
}
}
#endif /* PRECALC_LOOPS */
vp->sample_offset=ofs; /* Update offset */
return resample_buffer;
}
static sample_t *rs_loop(Voice *vp, int32_t count)
{
/* Play sample until end-of-loop, skip back and continue. */
INTERPVARS;
int32_t
ofs=vp->sample_offset,
incr=vp->sample_increment,
le=vp->sample->loop_end,
ll=le - vp->sample->loop_start;
sample_t
*dest=resample_buffer,
*src=vp->sample->data;
#ifdef PRECALC_LOOPS
int32_t i;
while (count)
{
if (ofs >= le)
/* NOTE: Assumes that ll > incr and that incr > 0. */
ofs -= ll;
/* Precalc how many times we should go through the loop */
i = (le - ofs) / incr + 1;
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
while (i--)
{
RESAMPLATION;
ofs += incr;
}
}
#else
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs>=le)
ofs -= ll; /* Hopefully the loop is longer than an increment. */
}
#endif
vp->sample_offset=ofs; /* Update offset */
return resample_buffer;
}
static sample_t *rs_bidir(Voice *vp, int32_t count)
{
INTERPVARS;
int32_t
ofs=vp->sample_offset,
incr=vp->sample_increment,
le=vp->sample->loop_end,
ls=vp->sample->loop_start;
sample_t
*dest=resample_buffer,
*src=vp->sample->data;
#ifdef PRECALC_LOOPS
int32_t
le2 = le<<1,
ls2 = ls<<1,
i;
/* Play normally until inside the loop region */
if (ofs <= ls)
{
/* NOTE: Assumes that incr > 0, which is NOT always the case
when doing bidirectional looping. I have yet to see a case
where both ofs <= ls AND incr < 0, however. */
i = (ls - ofs) / incr + 1;
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
while (i--)
{
RESAMPLATION;
ofs += incr;
}
}
/* Then do the bidirectional looping */
while(count)
{
/* Precalc how many times we should go through the loop */
i = ((incr > 0 ? le : ls) - ofs) / incr + 1;
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
while (i--)
{
RESAMPLATION;
ofs += incr;
}
if (ofs>=le)
{
/* fold the overshoot back in */
ofs = le2 - ofs;
incr *= -1;
}
else if (ofs <= ls)
{
ofs = ls2 - ofs;
incr *= -1;
}
}
#else /* PRECALC_LOOPS */
/* Play normally until inside the loop region */
if (ofs < ls)
{
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs>=ls)
break;
}
}
/* Then do the bidirectional looping */
if (count>0)
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs>=le)
{
/* fold the overshoot back in */
ofs = le - (ofs - le);
incr = -incr;
}
else if (ofs <= ls)
{
ofs = ls + (ls - ofs);
incr = -incr;
}
}
#endif /* PRECALC_LOOPS */
vp->sample_increment=incr;
vp->sample_offset=ofs; /* Update offset */
return resample_buffer;
}
/*********************** vibrato versions ***************************/
/* We only need to compute one half of the vibrato sine cycle */
static int vib_phase_to_inc_ptr(int phase)
{
if (phase < VIBRATO_SAMPLE_INCREMENTS/2)
return VIBRATO_SAMPLE_INCREMENTS/2-1-phase;
else if (phase >= 3*VIBRATO_SAMPLE_INCREMENTS/2)
return 5*VIBRATO_SAMPLE_INCREMENTS/2-1-phase;
else
return phase-VIBRATO_SAMPLE_INCREMENTS/2;
}
static int32_t update_vibrato(Voice *vp, int sign)
{
int32_t depth;
int phase, pb;
double a;
if (vp->vibrato_phase++ >= 2*VIBRATO_SAMPLE_INCREMENTS-1)
vp->vibrato_phase=0;
phase=vib_phase_to_inc_ptr(vp->vibrato_phase);
if (vp->vibrato_sample_increment[phase])
{
if (sign)
return -vp->vibrato_sample_increment[phase];
else
return vp->vibrato_sample_increment[phase];
}
/* Need to compute this sample increment. */
depth=vp->sample->vibrato_depth<<7;
if (vp->vibrato_sweep)
{
/* Need to update sweep */
vp->vibrato_sweep_position += vp->vibrato_sweep;
if (vp->vibrato_sweep_position >= (1<<SWEEP_SHIFT))
vp->vibrato_sweep=0;
else
{
/* Adjust depth */
depth *= vp->vibrato_sweep_position;
depth >>= SWEEP_SHIFT;
}
}
a = FSCALE(((double)(vp->sample->sample_rate) *
(double)(vp->frequency)) /
((double)(vp->sample->root_freq) *
(double)(play_mode->rate)),
FRACTION_BITS);
pb=(int)((sine(vp->vibrato_phase *
(SINE_CYCLE_LENGTH/(2*VIBRATO_SAMPLE_INCREMENTS)))
* (double)(depth) * VIBRATO_AMPLITUDE_TUNING));
if (pb<0)
{
pb=-pb;
a /= bend_fine[(pb>>5) & 0xFF] * bend_coarse[pb>>13];
}
else
a *= bend_fine[(pb>>5) & 0xFF] * bend_coarse[pb>>13];
/* If the sweep's over, we can store the newly computed sample_increment */
if (!vp->vibrato_sweep)
vp->vibrato_sample_increment[phase]=(int32_t) a;
if (sign)
a = -a; /* need to preserve the loop direction */
return (int32_t) a;
}
static sample_t *rs_vib_plain(int v, int32_t *countptr)
{
/* Play sample until end, then free the voice. */
INTERPVARS;
Voice *vp=&voice[v];
sample_t
*dest=resample_buffer,
*src=vp->sample->data;
int32_t
le=vp->sample->data_length,
ofs=vp->sample_offset,
incr=vp->sample_increment,
count=*countptr;
int
cc=vp->vibrato_control_counter;
/* This has never been tested */
if (incr<0) incr = -incr; /* In case we're coming out of a bidir loop */
while (count--)
{
if (!cc--)
{
cc=vp->vibrato_control_ratio;
incr=update_vibrato(vp, 0);
}
RESAMPLATION;
ofs += incr;
if (ofs >= le)
{
FINALINTERP;
vp->status=VOICE_FREE;
ctl->note(v);
*countptr-=count+1;
break;
}
}
vp->vibrato_control_counter=cc;
vp->sample_increment=incr;
vp->sample_offset=ofs; /* Update offset */
return resample_buffer;
}
static sample_t *rs_vib_loop(Voice *vp, int32_t count)
{
/* Play sample until end-of-loop, skip back and continue. */
INTERPVARS;
int32_t
ofs=vp->sample_offset,
incr=vp->sample_increment,
le=vp->sample->loop_end,
ll=le - vp->sample->loop_start;
sample_t
*dest=resample_buffer,
*src=vp->sample->data;
int
cc=vp->vibrato_control_counter;
#ifdef PRECALC_LOOPS
int32_t i;
int
vibflag=0;
while (count)
{
/* Hopefully the loop is longer than an increment */
if(ofs >= le)
ofs -= ll;
/* Precalc how many times to go through the loop, taking
the vibrato control ratio into account this time. */
i = (le - ofs) / incr + 1;
if(i > count) i = count;
if(i > cc)
{
i = cc;
vibflag = 1;
}
else cc -= i;
count -= i;
while(i--)
{
RESAMPLATION;
ofs += incr;
}
if(vibflag)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, 0);
vibflag = 0;
}
}
#else /* PRECALC_LOOPS */
while (count--)
{
if (!cc--)
{
cc=vp->vibrato_control_ratio;
incr=update_vibrato(vp, 0);
}
RESAMPLATION;
ofs += incr;
if (ofs>=le)
ofs -= ll; /* Hopefully the loop is longer than an increment. */
}
#endif /* PRECALC_LOOPS */
vp->vibrato_control_counter=cc;
vp->sample_increment=incr;
vp->sample_offset=ofs; /* Update offset */
return resample_buffer;
}
static sample_t *rs_vib_bidir(Voice *vp, int32_t count)
{
INTERPVARS;
int32_t
ofs=vp->sample_offset,
incr=vp->sample_increment,
le=vp->sample->loop_end,
ls=vp->sample->loop_start;
sample_t
*dest=resample_buffer,
*src=vp->sample->data;
int
cc=vp->vibrato_control_counter;
#ifdef PRECALC_LOOPS
int32_t
le2=le<<1,
ls2=ls<<1,
i;
int
vibflag = 0;
/* Play normally until inside the loop region */
while (count && (ofs <= ls))
{
i = (ls - ofs) / incr + 1;
if (i > count) i = count;
if (i > cc)
{
i = cc;
vibflag = 1;
}
else cc -= i;
count -= i;
while (i--)
{
RESAMPLATION;
ofs += incr;
}
if (vibflag)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, 0);
vibflag = 0;
}
}
/* Then do the bidirectional looping */
while (count)
{
/* Precalc how many times we should go through the loop */
i = ((incr > 0 ? le : ls) - ofs) / incr + 1;
if(i > count) i = count;
if(i > cc)
{
i = cc;
vibflag = 1;
}
else cc -= i;
count -= i;
while (i--)
{
RESAMPLATION;
ofs += incr;
}
if (vibflag)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, (incr < 0));
vibflag = 0;
}
if (ofs >= le)
{
/* fold the overshoot back in */
ofs = le2 - ofs;
incr *= -1;
}
else if (ofs <= ls)
{
ofs = ls2 - ofs;
incr *= -1;
}
}
#else /* PRECALC_LOOPS */
/* Play normally until inside the loop region */
if (ofs < ls)
{
while (count--)
{
if (!cc--)
{
cc=vp->vibrato_control_ratio;
incr=update_vibrato(vp, 0);
}
RESAMPLATION;
ofs += incr;
if (ofs>=ls)
break;
}
}
/* Then do the bidirectional looping */
if (count>0)
while (count--)
{
if (!cc--)
{
cc=vp->vibrato_control_ratio;
incr=update_vibrato(vp, (incr < 0));
}
RESAMPLATION;
ofs += incr;
if (ofs>=le)
{
/* fold the overshoot back in */
ofs = le - (ofs - le);
incr = -incr;
}
else if (ofs <= ls)
{
ofs = ls + (ls - ofs);
incr = -incr;
}
}
#endif /* PRECALC_LOOPS */
vp->vibrato_control_counter=cc;
vp->sample_increment=incr;
vp->sample_offset=ofs; /* Update offset */
return resample_buffer;
}
sample_t *resample_voice(int v, int32_t *countptr)
{
int32_t ofs;
uint8_t modes;
Voice *vp=&voice[v];
if (!(vp->sample->sample_rate))
{
/* Pre-resampled data -- just update the offset and check if
we're out of data. */
ofs=vp->sample_offset >> FRACTION_BITS; /* Kind of silly to use
FRACTION_BITS here... */
if (*countptr >= (vp->sample->data_length>>FRACTION_BITS) - ofs)
{
/* Note finished. Free the voice. */
vp->status = VOICE_FREE;
ctl->note(v);
/* Let the caller know how much data we had left */
*countptr = (vp->sample->data_length>>FRACTION_BITS) - ofs;
}
else
vp->sample_offset += *countptr << FRACTION_BITS;
return vp->sample->data+ofs;
}
/* Need to resample. Use the proper function. */
modes=vp->sample->modes;
if (vp->vibrato_control_ratio)
{
if ((modes & MODES_LOOPING) &&
((modes & MODES_ENVELOPE) ||
(vp->status==VOICE_ON || vp->status==VOICE_SUSTAINED)))
{
if (modes & MODES_PINGPONG)
return rs_vib_bidir(vp, *countptr);
else
return rs_vib_loop(vp, *countptr);
}
else
return rs_vib_plain(v, countptr);
}
else
{
if ((modes & MODES_LOOPING) &&
((modes & MODES_ENVELOPE) ||
(vp->status==VOICE_ON || vp->status==VOICE_SUSTAINED)))
{
if (modes & MODES_PINGPONG)
return rs_bidir(vp, *countptr);
else
return rs_loop(vp, *countptr);
}
else
return rs_plain(v, countptr);
}
}
void pre_resample(Sample * sp)
{
double a, xdiff;
int32_t incr, ofs, newlen, count;
int16_t *newdata, *dest, *src = (int16_t *) sp->data;
int16_t v1, v2, v3, v4, *vptr;
static const char note_name[12][3] =
{
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
};
ctl->cmsg(CMSG_INFO, VERB_NOISY, " * pre-resampling for note %d (%s%d)",
sp->note_to_use,
note_name[sp->note_to_use % 12], (sp->note_to_use & 0x7F) / 12);
a = ((double) (sp->sample_rate) * freq_table[(int) (sp->note_to_use)]) /
((double) (sp->root_freq) * play_mode->rate);
newlen = (int32_t)(sp->data_length / a);
dest = newdata = (int16_t*)safe_malloc(newlen >> (FRACTION_BITS - 1));
count = (newlen >> FRACTION_BITS) - 1;
ofs = incr = (sp->data_length - (1 << FRACTION_BITS)) / count;
if (--count)
*dest++ = src[0];
/* Since we're pre-processing and this doesn't have to be done in
real-time, we go ahead and do the full sliding cubic interpolation. */
while (--count)
{
vptr = src + (ofs >> FRACTION_BITS);
v1 = *(vptr - 1);
v2 = *vptr;
v3 = *(vptr + 1);
v4 = *(vptr + 2);
xdiff = FSCALENEG(ofs & FRACTION_MASK, FRACTION_BITS);
*dest++ = (int16_t)(v2 + (xdiff / 6.0) * (-2 * v1 - 3 * v2 + 6 * v3 - v4 +
xdiff * (3 * (v1 - 2 * v2 + v3) + xdiff * (-v1 + 3 * (v2 - v3) + v4))));
ofs += incr;
}
if (ofs & FRACTION_MASK)
{
v1 = src[ofs >> FRACTION_BITS];
v2 = src[(ofs >> FRACTION_BITS) + 1];
*dest++ = v1 + (((v2 - v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS);
}
else
*dest++ = src[ofs >> FRACTION_BITS];
sp->data_length = newlen;
sp->loop_start = (int32_t)(sp->loop_start / a);
sp->loop_end = (int32_t)(sp->loop_end / a);
Real_Tim_Free(sp->data);
sp->data = (sample_t *) newdata;
sp->sample_rate = 0;
}
| 20.584574 | 76 | 0.619445 |
1337programming
|
e9095f5c3976ebb5e723a494ff5ea410ceeea824
| 1,831 |
cc
|
C++
|
pw_result/result_test.cc
|
LuDuda/pigweed
|
dcd7230895a234156bc7b6e5061e6936627c5fbb
|
[
"Apache-2.0"
] | null | null | null |
pw_result/result_test.cc
|
LuDuda/pigweed
|
dcd7230895a234156bc7b6e5061e6936627c5fbb
|
[
"Apache-2.0"
] | null | null | null |
pw_result/result_test.cc
|
LuDuda/pigweed
|
dcd7230895a234156bc7b6e5061e6936627c5fbb
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 The Pigweed 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#include "pw_result/result.h"
#include "gtest/gtest.h"
namespace pw {
namespace {
TEST(Result, CreateOk) {
Result<const char*> res("hello");
EXPECT_TRUE(res.ok());
EXPECT_EQ(res.status(), OkStatus());
EXPECT_EQ(res.value(), "hello");
}
TEST(Result, CreateNotOk) {
Result<int> res(Status::DataLoss());
EXPECT_FALSE(res.ok());
EXPECT_EQ(res.status(), Status::DataLoss());
}
TEST(Result, ValueOr) {
Result<int> good(3);
Result<int> bad(Status::DataLoss());
EXPECT_EQ(good.value_or(42), 3);
EXPECT_EQ(bad.value_or(42), 42);
}
TEST(Result, ConstructType) {
struct Point {
Point(int a, int b) : x(a), y(b) {}
int x;
int y;
};
Result<Point> origin{std::in_place, 0, 0};
ASSERT_TRUE(origin.ok());
ASSERT_EQ(origin.value().x, 0);
ASSERT_EQ(origin.value().y, 0);
}
Result<float> Divide(float a, float b) {
if (b == 0) {
return Status::InvalidArgument();
}
return a / b;
}
TEST(Divide, ReturnOk) {
Result<float> res = Divide(10, 5);
ASSERT_TRUE(res.ok());
EXPECT_EQ(res.value(), 2.0f);
}
TEST(Divide, ReturnNotOk) {
Result<float> res = Divide(10, 0);
EXPECT_FALSE(res.ok());
EXPECT_EQ(res.status(), Status::InvalidArgument());
}
} // namespace
} // namespace pw
| 23.779221 | 80 | 0.67231 |
LuDuda
|
e90ae0565c37d5f0e74b9139ce7411ccba6f1ba1
| 604 |
cpp
|
C++
|
C-C++/activitySelection(Greedy).cpp
|
psinha30/dataStructure-Algorithms
|
a5b097f9136cf458d8b95350a05ac19a99f3cbf3
|
[
"MIT"
] | 1 |
2019-12-30T18:07:07.000Z
|
2019-12-30T18:07:07.000Z
|
C-C++/activitySelection(Greedy).cpp
|
psinha30/dataStructure-Algorithms
|
a5b097f9136cf458d8b95350a05ac19a99f3cbf3
|
[
"MIT"
] | null | null | null |
C-C++/activitySelection(Greedy).cpp
|
psinha30/dataStructure-Algorithms
|
a5b097f9136cf458d8b95350a05ac19a99f3cbf3
|
[
"MIT"
] | 1 |
2018-12-20T04:58:26.000Z
|
2018-12-20T04:58:26.000Z
|
#include <bits/stdc++.h>
using namespace std;
int i, n;
struct activity
{
int s,f;
};
bool compare(activity a1, activity a2)
{
return (a1.f < a2.f);
}
void activity_greedy(activity a[], int m)
{
if(m >= n)
return;
if(a[m].s >= a[i].f)
{
if(i == 0)
cout << "{" << a[i].s << "," << a[i].f << "} ";
cout << "{" << a[m].s << "," << a[m].f << "} ";
i = m;
activity_greedy(a, m + 1);
}
else
activity_greedy(a, m + 1);
}
int main()
{
cin >> n;
activity a[n];
for(int i = 0; i < n; i++)
cin >> a[i].s >> a[i].f;
sort(a, a+n, compare);
activity_greedy(a, 0);
return 0;
}
| 13.422222 | 50 | 0.488411 |
psinha30
|
e90b8019e09a093019fe759575d1090ce194170b
| 8,206 |
cpp
|
C++
|
src/mongo/s/catalog/type_config_version.cpp
|
LightBitsLabs/mongo
|
9480ef00a8df2464457ab0f31c7a336f882e8ec1
|
[
"Apache-2.0"
] | 25 |
2016-12-07T09:39:51.000Z
|
2021-12-16T11:17:37.000Z
|
src/mongo/s/catalog/type_config_version.cpp
|
Man1029/CMONGO
|
c40380caa14e05509f46993aa8b8da966b09b0b5
|
[
"ECL-2.0",
"Apache-2.0"
] | 1 |
2015-05-29T16:12:10.000Z
|
2015-05-29T16:12:10.000Z
|
src/mongo/s/catalog/type_config_version.cpp
|
Man1029/CMONGO
|
c40380caa14e05509f46993aa8b8da966b09b0b5
|
[
"ECL-2.0",
"Apache-2.0"
] | 23 |
2017-01-22T03:35:26.000Z
|
2021-12-16T11:17:39.000Z
|
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/s/catalog/type_config_version.h"
#include "mongo/base/status_with.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/s/catalog/config_server_version.h"
#include "mongo/s/catalog/legacy/config_upgrade.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
const std::string VersionType::ConfigNS = "config.version";
const BSONField<int> VersionType::minCompatibleVersion("minCompatibleVersion");
const BSONField<int> VersionType::currentVersion("currentVersion");
const BSONField<BSONArray> VersionType::excludingMongoVersions("excluding");
const BSONField<OID> VersionType::clusterId("clusterId");
const BSONField<OID> VersionType::upgradeId("upgradeId");
const BSONField<BSONObj> VersionType::upgradeState("upgradeState");
void VersionType::clear() {
_minCompatibleVersion.reset();
_currentVersion.reset();
_excludingMongoVersions.reset();
_clusterId.reset();
_upgradeId.reset();
_upgradeState.reset();
}
void VersionType::cloneTo(VersionType* other) const {
other->clear();
other->_minCompatibleVersion = _minCompatibleVersion;
other->_currentVersion = _currentVersion;
other->_excludingMongoVersions = _excludingMongoVersions;
other->_clusterId = _clusterId;
other->_upgradeId = _upgradeId;
other->_upgradeState = _upgradeState;
}
Status VersionType::validate() const {
if (!_minCompatibleVersion.is_initialized()) {
return {ErrorCodes::NoSuchKey,
str::stream() << "missing " << minCompatibleVersion.name() << " field"};
}
if (!_currentVersion.is_initialized()) {
return {ErrorCodes::NoSuchKey,
str::stream() << "missing " << currentVersion.name() << " field"};
}
// UpgradeHistory::UpgradeHistory_NoEpochVersion is the last version without a cluster id
if (getCurrentVersion() > UpgradeHistory::UpgradeHistory_NoEpochVersion &&
!_clusterId.is_initialized()) {
return {ErrorCodes::NoSuchKey, str::stream() << "missing " << clusterId.name() << " field"};
}
return Status::OK();
}
BSONObj VersionType::toBSON() const {
BSONObjBuilder builder;
builder.append("_id", 1);
if (_minCompatibleVersion)
builder.append(minCompatibleVersion.name(), getMinCompatibleVersion());
if (_currentVersion)
builder.append(currentVersion.name(), getCurrentVersion());
if (_excludingMongoVersions) {
builder.append(excludingMongoVersions.name(),
MongoVersionRange::toBSONArray(getExcludingMongoVersions()));
}
if (_clusterId)
builder.append(clusterId.name(), getClusterId());
if (_upgradeId) {
builder.append(upgradeId.name(), getUpgradeId());
builder.append(upgradeState.name(), getUpgradeState());
}
return builder.obj();
}
StatusWith<VersionType> VersionType::fromBSON(const BSONObj& source) {
VersionType version;
{
long long vMinCompatibleVersion;
Status status =
bsonExtractIntegerField(source, minCompatibleVersion.name(), &vMinCompatibleVersion);
if (!status.isOK())
return status;
version._minCompatibleVersion = vMinCompatibleVersion;
}
{
long long vCurrentVersion;
Status status = bsonExtractIntegerField(source, currentVersion.name(), &vCurrentVersion);
if (status.isOK()) {
version._currentVersion = vCurrentVersion;
} else if (status == ErrorCodes::NoSuchKey) {
version._currentVersion = version._minCompatibleVersion;
} else {
return status;
}
}
{
BSONElement vClusterIdElem;
Status status =
bsonExtractTypedField(source, clusterId.name(), BSONType::jstOID, &vClusterIdElem);
if (status.isOK()) {
version._clusterId = vClusterIdElem.OID();
} else if (status == ErrorCodes::NoSuchKey &&
version.getCurrentVersion() <= UpgradeHistory::UpgradeHistory_NoEpochVersion) {
// UpgradeHistory::UpgradeHistory_NoEpochVersion is the last version
// without a cluster id
} else {
return status;
}
}
{
BSONElement vExclMongoVersionsElem;
Status status = bsonExtractTypedField(
source, excludingMongoVersions.name(), BSONType::Array, &vExclMongoVersionsElem);
if (status.isOK()) {
version._excludingMongoVersions = std::vector<MongoVersionRange>();
BSONObjIterator it(vExclMongoVersionsElem.Obj());
while (it.more()) {
MongoVersionRange range;
std::string errMsg;
if (!range.parseBSONElement(it.next(), &errMsg)) {
return {ErrorCodes::FailedToParse, errMsg};
}
version._excludingMongoVersions->push_back(range);
}
} else if (status == ErrorCodes::NoSuchKey) {
// 'excludingMongoVersions' field is optional
} else {
return status;
}
}
{
BSONElement vUpgradeIdElem;
Status status =
bsonExtractTypedField(source, upgradeId.name(), BSONType::jstOID, &vUpgradeIdElem);
if (status.isOK()) {
version._upgradeId = vUpgradeIdElem.OID();
} else if (status == ErrorCodes::NoSuchKey) {
// 'upgradeId' field is optional
} else {
return status;
}
}
if (source.hasField(upgradeState.name())) {
BSONElement vUpgradeStateElem;
Status status = bsonExtractTypedField(
source, upgradeState.name(), BSONType::Object, &vUpgradeStateElem);
if (status.isOK()) {
version._upgradeState = vUpgradeStateElem.Obj().getOwned();
} else if (status == ErrorCodes::NoSuchKey) {
// 'upgradeState' field is optional
} else {
return status;
}
}
return version;
}
void VersionType::setMinCompatibleVersion(const int minCompatibleVersion) {
_minCompatibleVersion = minCompatibleVersion;
}
void VersionType::setCurrentVersion(const int currentVersion) {
_currentVersion = currentVersion;
}
void VersionType::setClusterId(const OID& clusterId) {
invariant(clusterId.isSet());
_clusterId = clusterId;
}
void VersionType::setExcludingMongoVersions(
const std::vector<MongoVersionRange>& excludingMongoVersions) {
_excludingMongoVersions = excludingMongoVersions;
}
std::string VersionType::toString() const {
return toBSON().toString();
}
} // namespace mongo
| 35.991228 | 100 | 0.668535 |
LightBitsLabs
|
e90c56f98148e6359b1636cd2dd13aff6c42f4cd
| 6,985 |
cpp
|
C++
|
Cursor.cpp
|
JermSmith/TDGame
|
198599ef229eb6c852dabc7ea72f5537dd10ab5c
|
[
"MIT"
] | null | null | null |
Cursor.cpp
|
JermSmith/TDGame
|
198599ef229eb6c852dabc7ea72f5537dd10ab5c
|
[
"MIT"
] | null | null | null |
Cursor.cpp
|
JermSmith/TDGame
|
198599ef229eb6c852dabc7ea72f5537dd10ab5c
|
[
"MIT"
] | null | null | null |
#include "Cursor.h"
#include "Util\Math.h"
Cursor::Cursor(const sf::RenderWindow& window) : Tower(window) {}
void Cursor::update(const sf::RenderWindow& window, const Path& path,
const std::vector<std::unique_ptr<Tower>>& towers, bool bTowerBeingPlaced)
{
if (bTowerBeingPlaced)
{
// place dummy tower at the current mouse position to check what color the cursor circle should be
m_position = sf::Vector2f(window.mapPixelToCoords(sf::Mouse::getPosition(window)));
if (!bInterferesWithScene(towers, path))
{
updatePositive(); //possible to place tower here
}
else
{
updateNegative(); //not possible to place tower here
}
}
else
{
hide(); //do not show a cursor, since no tower is being placed
}
}
void Cursor::render(sf::RenderTarget& renderer)
{
InteractableShape::render(renderer);
renderer.draw(m_rangeCircle);
}
bool Cursor::bInterferesWithScene(const std::vector<std::unique_ptr<Tower>>& towers, const Path& path)
{
// depends on tower properties m_position and m_size
float t_ = path.getWidth() / 2; // t_ is half width
std::vector<sf::Vector2f> corners = {}; // vector containing all points to check for potential collision
// the following assignment assumes m_position takes centre of circle (and that circle is aligned with axes, although doesn't matter for circles)
corners.push_back(m_position); // centre
int numOfPointsOnCircle = 16; // number of points on circle to check for possible collisions; power of 2 allows top and bottom of circle to be included
for (int angle = (-numOfPointsOnCircle / 2 + 1); angle <= numOfPointsOnCircle; angle++)
{
corners.push_back(sf::Vector2f(
m_position.x + cos(angle * PI * 2 / numOfPointsOnCircle) * getPrimaryDim(),
m_position.y + sin(angle * PI * 2 / numOfPointsOnCircle) * getPrimaryDim())); // e.g. for increments of PI/4, # of divisions is 8
}
/* could specify different "corners" for a square, diamond, etc. */
for (unsigned int i = 1; i < path.getVertices().size(); i++)
{
sf::Vector2f vo = path.getVertices().at(i - 1);
sf::Vector2f vi = path.getVertices().at(i);
float theta = atan2f(vi.y - vo.y, vi.x - vo.x); // angle of path segment in radians (CW is +ve from +ve x-axis)
// ol is back left corner of the rectangle, ir is front right corner of the rectangle
sf::Vector2f ol = sf::Vector2f(vo.x - t_*cos(theta) + t_*sin(theta), vo.y - t_*cos(theta) - t_*sin(theta));
sf::Vector2f or = sf::Vector2f(vo.x - t_*cos(theta) - t_*sin(theta), vo.y + t_*cos(theta) - t_*sin(theta));
sf::Vector2f il = sf::Vector2f(vi.x + t_*cos(theta) + t_*sin(theta), vi.y - t_*cos(theta) + t_*sin(theta));
sf::Vector2f ir = sf::Vector2f(vi.x + t_*cos(theta) - t_*sin(theta), vi.y + t_*cos(theta) + t_*sin(theta));
float m_; // slope of path segment ("down-right" is positive, "up-right" is negative)
for (sf::Vector2f& corner : corners)
{
// check vertex interference
if (i != path.getVertices().size() - 1) // NOT last vertex
{
if (distanceBetweenPoints(corner, vo) <= path.getVertexWidth() / sqrtf(2))
{
return true; // a "corner" interferes with a vertex
}
}
else //
{
if (distanceBetweenPoints(corner, vo) <= path.getVertexWidth() / sqrtf(2))
{
return true; // a "corner" interferes with second-last vertex
}
if (distanceBetweenPoints(corner, vi) <= path.getVertexWidth() / sqrtf(2))
{
return true; // a "corner" interferes with last vertex
}
}
// check straight section interference
if (theta == 0 || theta == PI || theta == -PI)
{
if (cos(theta) * corner.y >= cos(theta) * ol.y &&
cos(theta) * corner.y <= cos(theta) * ir.y &&
cos(theta) * corner.x >= cos(theta) * ol.x &&
cos(theta) * corner.x <= cos(theta) * ir.x)
{
return true; // a "corner" is inside the path space
}
}
else if (theta == PI / 2 || theta == -PI / 2)
{
if (sin(theta) * corner.y >= sin(theta) * ol.y &&
sin(theta) * corner.y <= sin(theta) * ir.y &&
sin(theta) * corner.x <= sin(theta) * ol.x &&
sin(theta) * corner.x >= sin(theta) * ir.x)
{
return true; // a "corner" is inside the path space
}
}
else // theta != 0, pi/2, pi, -pi/2, -pi
{
m_ = (vi.y - vo.y) / (vi.x - vo.x); // slope of path segment
if (cos(theta) * (corner.y - m_*corner.x) > cos(theta) * (ol.y - m_*ol.x) &&
cos(theta) * (corner.y - m_*corner.x) < cos(theta) * (ir.y - m_*ir.x) &&
sin(theta) * (corner.y + (1 / m_)*corner.x) > sin(theta) * (ol.y + (1 / m_)*ol.x) &&
sin(theta) * (corner.y + (1 / m_)*corner.x) < sin(theta) * (ir.y + (1 / m_)*ir.x))
{
return true; // a "corner" is inside the path space
}
}
}
}
// above here is checking for interference between newObj and path
// below here is checking for interference between newObj and other objects, assuming all objects are circles (size.x = size.y for circles)
for (unsigned int i = 0; i < towers.size(); i++)
{
if (distanceBetweenPoints(m_position, towers.at(i)->getPosition()) <
(getPrimaryDim() + towers.at(i)->getRadius()))
{
return true;
}
}
// below here is checking for interference with menu
if (m_position.x > sizes::WORLD_SIZE_X - (sizes::PLAYINGMENU_X + getPrimaryDim()) || // menu width + 1/2 tower radius
(m_position.x < getPrimaryDim()) ||
m_position.y < getPrimaryDim() ||
m_position.y > sizes::WORLD_SIZE_Y - getPrimaryDim())
{
return true;
}
return false;
}
// private methods below this line
void Cursor::hide()
{
InteractableShape::setFillColour(sf::Color::Transparent);
InteractableShape::setOutlineThickness(0);
m_rangeCircle.setRadius(0);
}
void Cursor::updatePositive()
{
InteractableShape::setOutlineThickness(-2);
InteractableShape::setOutlineColour(sf::Color::Cyan);
InteractableShape::setPosition(m_position);
m_rangeCircle.setRadius(m_range);
m_rangeCircle.setFillColor(sf::Color(255, 255, 255, 63));
m_rangeCircle.setOutlineThickness(-2);
m_rangeCircle.setOutlineColor(sf::Color::Green);
m_rangeCircle.setPosition(m_position);
}
void Cursor::updateNegative()
{
InteractableShape::setFillColour(sf::Color::Transparent);
InteractableShape::setOutlineThickness(-2);
InteractableShape::setOutlineColour(sf::Color::Red);
InteractableShape::setPosition(m_position);
m_rangeCircle.setOutlineColor(sf::Color::Transparent);
m_rangeCircle.setFillColor(sf::Color::Transparent);
}
void Cursor::generateWidgets(const sf::RenderWindow& window)
{
bnrCursorNote.setText("Click to place tower");
}
void Cursor::populateHoverMenu()
{
m_hoverMenu.addWidget(bnrCursorNote);
m_hoverMenu.showOutline();
}
void Cursor::populateUpgradeMenu()
{
}
void Cursor::hideHoverMenu()
{
m_hoverMenu.clearWidgets();
m_hoverMenu.hideOutline();
}
| 32.041284 | 153 | 0.644094 |
JermSmith
|
e90d5ab2a2d550f066f51c6659c4d2a1b8d878a5
| 8,823 |
cpp
|
C++
|
Source/WebKit/mg/control/license/loadSplash.cpp
|
VincentWei/mdolphin-core
|
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
|
[
"Apache-2.0"
] | 6 |
2017-05-31T01:46:45.000Z
|
2018-06-12T10:53:30.000Z
|
Source/WebKit/mg/control/license/loadSplash.cpp
|
FMSoftCN/mdolphin-core
|
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
|
[
"Apache-2.0"
] | null | null | null |
Source/WebKit/mg/control/license/loadSplash.cpp
|
FMSoftCN/mdolphin-core
|
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
|
[
"Apache-2.0"
] | 2 |
2017-07-17T06:02:42.000Z
|
2018-09-19T10:08:38.000Z
|
/*
** $Id$
**
** loadSplash.cpp:
**
** Copyright (C) 2003 ~ 2010 Beijing Feynman Software Technology Co., Ltd.
**
** All rights reserved by Feynman Software.
**
** Current maintainer: lvlei
**
** Create date: 2010-08-25
*/
#include "mdconfig.h"
#ifdef _MD_ENABLE_WATERMARK
#include "licenseHidden.h"
#include "c_files/watermark/watermark4.dat.c"
#endif
#ifdef _MD_ENABLE_LOADSPLASH
#include "loadSplash.h"
#include "sharedTimerLoadSplash.h"
#include "c_files/loadsplash/_loadsplash_inner_res.c"
#include "c_files/loadsplash/loadsplash01.dat.c"
#include "c_files/loadsplash/loadsplash02.dat.c"
#include "c_files/loadsplash/loadsplash03.dat.c"
#include "c_files/loadsplash/loadsplash04.dat.c"
#include "c_files/loadsplash/loadsplash05.dat.c"
#include "c_files/loadsplash/loadsplash06.dat.c"
#include "c_files/loadsplash/loadsplash07.dat.c"
#include "c_files/loadsplash/loadsplash08.dat.c"
#include "c_files/loadsplash/loadsplash09.dat.c"
#include "c_files/loadsplash/loadsplash10.dat.c"
#include "c_files/loadsplash/loadsplash11.dat.c"
#include "c_files/loadsplash/loadsplash12.dat.c"
#include "c_files/loadsplash/loadsplash13.dat.c"
unsigned int loadSplash::intervalInMS = 100;
HDC loadSplash::pictureDC = HDC_INVALID;
int loadSplash::frameCount = 0;
int loadSplash::splashWidth = 0;
int loadSplash::splashHeight = 0;
loadSplash::loadSplash(HWND hWnd, HDC hdc)
:m_hwnd(hWnd)
{
m_isRunning = false;
init(hdc);
m_index = 0;
resetTimer();
}
loadSplash::~loadSplash()
{
finish();
DeleteMemDC(m_bgndDC);
#if 0
DeleteMemDC(loadSplash::pictureDC);
#endif
}
void loadSplash::initMemDCIfNeed(HDC hdc)
{
static bool hadInit = false;
if (hadInit) {
m_bgndDC = CreateCompatibleDC(loadSplash::pictureDC);
int oldColor = SetBrushColor(m_bgndDC, PIXEL_lightwhite);
FillBox(m_bgndDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight);
SetBrushColor(m_bgndDC, oldColor);
return;
}
unsigned char *data;
int len;
BITMAP bitmap;
data = __md_loadsplash_loadsplash_inner_res[0].data;
len = __md_loadsplash_loadsplash_inner_res[0].data_len;
LoadBitmapFromMem(hdc, &bitmap, data, len, "png");
loadSplash::splashWidth = bitmap.bmWidth;
loadSplash::splashHeight = bitmap.bmHeight;
loadSplash::pictureDC = CreateCompatibleDCEx(hdc, bitmap.bmWidth, bitmap.bmHeight);
//loadSplash::pictureDC = CreateMemDCFromBitmap(hdc, &bitmap);
m_bgndDC = CreateCompatibleDC(loadSplash::pictureDC);
loadSplash::frameCount = TABLESIZE(__md_loadsplash_loadsplash_inner_res); // 13;
int oldColor = SetBrushColor(m_bgndDC, PIXEL_lightwhite);
FillBox(m_bgndDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight);
SetBrushColor(m_bgndDC, oldColor);
UnloadBitmap(&bitmap);
hadInit = true;
}
bool loadSplash::init(HDC hdc)
{
//FixMe: It is uncomfortable using hdc , but using Shared MemDC to save memory
loadSplash::initMemDCIfNeed(hdc);
return true;
#if 0
RECT rc;
SetRect(&rc, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight);
int w, h;
int pitch;
Uint8 *bits = LockDC(loadSplash::pictureDC, &rc, &w, &h, &pitch);
memcpy (bits, bitmap.bmBits, pitch* h);
UnlockDC(loadSplash::pictureDC);
#endif
//FillBoxWithBitmap(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, &bitmap);
//UnloadBitmap(&bitmap);
}
void loadSplash::calcOffsetPos()
{
RECT rect;
GetClientRect(m_hwnd, &rect);
#ifdef LOADSPLASH_CENTER
m_offsetX = (RECTW(rect) - loadSplash::splashWidth)/2.0;
if (m_offsetX < 0)
m_offsetX = 0;
m_offsetY = (RECTH(rect) - loadSplash::splashHeight)/2.0;
if (m_offsetY < 0)
m_offsetY = 0;
#else // right-top
m_offsetX = RECTW(rect) - loadSplash::splashWidth;
m_offsetX -= 20; //scrollWidth
if (m_offsetX < 0)
m_offsetX = 0;
m_offsetY = 0;
#endif
}
void loadSplash::updateBackgroundDC(HDC backGroundDC)
{
BitBlt(backGroundDC, m_offsetX, m_offsetY, loadSplash::splashWidth, loadSplash::splashHeight, m_bgndDC, 0, 0, -1);
}
void loadSplash::updateDC()
{
unsigned char *data;
int len;
BITMAP bitmap;
data = __md_loadsplash_loadsplash_inner_res[m_index].data;
len = __md_loadsplash_loadsplash_inner_res[m_index].data_len;
LoadBitmapFromMem(loadSplash::pictureDC, &bitmap, data, len, "png");
m_index = (m_index + 1) % loadSplash::frameCount;
#if 0
FillBoxWithBitmap(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, &bitmap);
#else
RECT rc;
SetRect(&rc, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight);
int w, h;
int pitch;
gal_pixel colorKey;
Uint8 *bits = LockDC(loadSplash::pictureDC, &rc, &w, &h, &pitch);
memcpy (bits, bitmap.bmBits, pitch* h);
colorKey = *(gal_pixel *)bits;
UnlockDC(loadSplash::pictureDC);
#endif
SetMemDCAlpha(loadSplash::pictureDC, MEMDC_FLAG_SRCALPHA, 160);
//SetMemDCColorKey(loadSplash::pictureDC, MEMDC_FLAG_SRCCOLORKEY, RGBA2Pixel(loadSplash::pictureDC, 0xFF, 0xFF, 0xFF, 0x00));
SetMemDCColorKey(loadSplash::pictureDC, MEMDC_FLAG_SRCCOLORKEY, colorKey);
UnloadBitmap(&bitmap);
}
void loadSplash::updateToWindow()
{
updateDC();
HDC hdc = GetClientDC(m_hwnd);
PCLIPRGN pClipRgn = CreateClipRgn();
RECT rect;
GetClipRegion(hdc, pClipRgn);
SetRect(&rect, m_offsetX, m_offsetY, m_offsetX + loadSplash::splashWidth, m_offsetY + loadSplash::splashHeight);
IncludeClipRect(hdc, &rect);
#ifdef PERFORMANCE_FIRST
BitBlt(m_bgndDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, m_offsetX, m_offsetY, -1);
BitBlt(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, m_offsetX, m_offsetY, -1);
#else
HDC copyDC = CreateCompatibleDC(m_bgndDC);
BitBlt(m_bgndDC, 0, 0, 0, 0, copyDC, 0, 0, -1);
BitBlt(loadSplash::pictureDC, 0, 0, 0, 0, copyDC, 0, 0, -1);
BitBlt(copyDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, m_offsetX, m_offsetY, -1);
DeleteMemDC(copyDC);
#endif
SelectClipRegion(hdc, pClipRgn);
DestroyClipRgn(pClipRgn);
ReleaseDC(hdc);
}
#if 0
void loadSplash::drawContentAndBackground(HDC backGroundDC, int offsetX, int offsetY, int maxWidth, int maxHeight)
{
unsigned char *data;
int len;
BITMAP bitmap;
data = __md_loadsplash_loadsplash_inner_res[m_index].data;
len = __md_loadsplash_loadsplash_inner_res[m_index].data_len;
LoadBitmapFromMem(HDC_SCREEN, &bitmap, data, len, "png");
m_index = (m_index + 1) % loadSplash::frameCount;
HDC imageDC = CreateMemDCFromBitmap(HDC_SCREEN,&bitmap);
BitBlt(backGroundDC, offsetX, offsetY, loadSplash::splashWidth, loadSplash::splashHeight, loadSplash::pictureDC, 0, 0, -1);
SetMemDCAlpha(imageDC,MEMDC_FLAG_SRCALPHA, 0x80);
BitBlt(imageDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, loadSplash::pictureDC, 0, 0, -1);
DeleteMemDC(imageDC);
UnloadBitmap(&bitmap);
}
void loadSplash::updateToDC(HDC hdc, int offsetX, int offsetY, int maxWidth, int maxHeight)
{
PCLIPRGN pClipRgn = CreateClipRgn();
RECT rect;
GetClipRegion(hdc, pClipRgn);
SetRect(&rect, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight);
IncludeClipRect(hdc, &rect):
BitBlt(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, offsetX, offsetY, -1);
SelectClipRegion(hdc, pClipRgn);
DestroyClipRgn(pClipRgn);
}
#endif
BOOL loadSplash::timerFired()
{
//printf("loadSplash:timerFired\n");
if (!IsWindowVisible(m_hwnd)) {
return TRUE;
}
updateToWindow();
return TRUE;
}
bool loadSplash::isRuning()
{
return m_isRunning;
}
bool loadSplash::start()
{
#if 0
static unsigned int t_id = 1;
while (IsTimerInstalled(m_hwnd, t_id))
t_id++;
// using shared timer ?
if (!SetTimerEx(m_hwnd, t_id, (loadSplash::intervalInMS)/10.0, loadSplash::timerFired)) {
fprintf(stderr, "loadSplash: SetTimerEx failed !\n");
m_timerID = 0;
reture false;
}
m_timerID = t_id;
#endif
if (!m_isRunning) {
sharedTimerLoadSplash* sharedTimer = sharedTimerLoadSplash::sharedTimerLoadSplashInstance();
sharedTimer->registerObject(this);
m_isRunning = true;
}
return true;
}
bool loadSplash::finish()
{
#if 0
if (m_timerID){
KillTimer(m_hwnd, m_timerID);
m_timerID = 0;
}
#endif
if (m_isRunning) {
sharedTimerLoadSplash* sharedTimer = sharedTimerLoadSplash::sharedTimerLoadSplashInstance();
sharedTimer->unRegisterObject(this);
m_isRunning = false;
}
return true;
}
#endif //end _MD_ENABLE_LOADSPLASH
| 29.41 | 129 | 0.702142 |
VincentWei
|
e90ddfc73a37d14850a6693e7f8f62f8cecc169b
| 9,227 |
cpp
|
C++
|
lib/ofsocket.cpp
|
timmyw/ofsystem
|
6f955d53dc3025148763333bea0a11d0bce28c06
|
[
"MIT"
] | null | null | null |
lib/ofsocket.cpp
|
timmyw/ofsystem
|
6f955d53dc3025148763333bea0a11d0bce28c06
|
[
"MIT"
] | null | null | null |
lib/ofsocket.cpp
|
timmyw/ofsystem
|
6f955d53dc3025148763333bea0a11d0bce28c06
|
[
"MIT"
] | null | null | null |
/*
Copyright (C) 1997-2011 by Suntail.com AS, Tim Whelan
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 <ofsys.h>
#include <ofsocket.h>
#include <ofutility.h>
#include <oflogservice.h>
#include <ofplatform.h>
#if defined(OFOPSYS_WIN32)
typedef LINGER OFLINGER;
#else
typedef struct linger OFLINGER;
#if defined(OFOPSYS_LINUX)
#include <netinet/tcp.h>
#endif
#endif
OFSocket::OFSocket( ) :
m_addr( 0 ),
m_open( false )
{
m_socket = socket( AF_INET, SOCK_STREAM, 0 );
set_options_();
}
OFSocket::OFSocket( const OFAddress &remote ) :
m_addr( remote ),
m_open( false )
{
m_socket = socket( AF_INET, SOCK_STREAM, 0 );
set_options_();
}
OFSocket::OFSocket( OFOS::of_socket_t socketHandle ) :
m_addr( 0 ),
m_open( true )
{
m_socket = socketHandle;
set_options_();
}
OFSocket::~OFSocket( )
{
closeSocket( );
}
ofint32
OFSocket::connect( const OFAddress &remote )
{
m_addr = remote;
if ( m_socket == -1 )
return ERR_INVAL_SOCKET;
sockaddr *addr = (sockaddr*)m_addr.address();
ofint32 retv = ::connect( m_socket, addr, sizeof(sockaddr) );
if ( retv == -1 )
return OFUtility::translateLastSystemError( );
m_open = true;
#if defined(OFOPSYS_WIN32)
oflong param = 1;
if (ioctlsocket(m_socket, FIONBIO, ¶m) == SOCKET_ERROR)
#else
ofuint32 param = fcntl(m_socket, F_GETFL);
if (fcntl(m_socket, F_SETFL, param | O_NONBLOCK))
#endif
OFLogService::debugLine("Error setting NBIO: %s",
retrieveMsg(OFUtility::translateLastSystemError()));
return ERR_SUCCESS;
}
ofint32
OFSocket::listen( )
{
ofint32 ret = 0;
ofint32 temp = 1;
ret = setsockopt( m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&temp), sizeof(temp) );
if ( ret == -1 )
return ret;
ret = bind( m_socket, (struct sockaddr *)m_addr.address(), sizeof(*m_addr.address()) );
if ( !ret )
ret = ::listen( m_socket, 5 );
return ret;
}
void
OFSocket::closeSocket( )
{
// cout << "OFSocket::closeSocket" << endl;
if ( m_open )
{
m_open = false;
shutdown( m_socket, 2 );
#if defined(OFOPSYS_WIN32)
closesocket( m_socket );
#else
close( m_socket );
#endif
}
else
{
#if defined(OFOPSYS_WIN32)
if ( m_socket != OFOS::OF_INVALID_SOCKET )
{
shutdown( m_socket, 2 );
closesocket( m_socket );
}
#else
if (m_socket != OFOS::OF_INVALID_SOCKET)
{
shutdown( m_socket, 2 );
close( m_socket );
}
#endif
}
m_socket = OFOS::OF_INVALID_SOCKET;
}
ofint32
OFSocket::send( void *buffer,
ofuint32 bufferLength,
bool *terminate /* = NULL */,
ofuint32 chunkSize /* = 2048 */,
ofuint32 timeOut /* = 30 */ )
{
ofint32 leftToSend = bufferLength;
char *tempBuf = static_cast<char*>(buffer);
ofint32 cursent = 0;
time_t timenow;
time_t timestart;
time( ×tart );
struct timeval tv;
fd_set fdwrite;
for(;;)
{
ofint32 rc = 0;
FD_ZERO( &fdwrite );
FD_SET( m_socket, &fdwrite );
tv.tv_sec = 1;
tv.tv_usec = 0;
rc = select( m_socket+1, 0, &fdwrite, 0, &tv );
if ( terminate != 0 && *terminate ) return 1;
if ( rc > 0 && FD_ISSET( m_socket, &fdwrite ) )
{
time( ×tart );
ofint32 chunkToSend = (leftToSend < (ofint32)chunkSize)
?leftToSend:chunkSize;
cursent = ::send( m_socket, tempBuf, chunkToSend, 0 );
if ( terminate != 0 && *terminate ) return 1;
if ( cursent < 0 ) return -1;
leftToSend -= cursent;
tempBuf += cursent;
if ( leftToSend <= 0 )
return 0;
}
time( &timenow );
if ( (ofuint32)timenow > timestart + timeOut ) break;
}
return 1;
}
ofint32
OFSocket::recv( void *buffer,
ofuint32 bufferLength,
ofuint32 &bytesReceived,
bool *terminate /* = NULL */,
ofuint32 chunkSize /* = 2048 */,
ofuint32 timeOut /* = 30 */ )
{
bytesReceived = 0;
time_t timenow;
time_t timestart;
time( ×tart );
struct timeval tv;
fd_set fdread;
for(;;)
{
ofint32 rc = 0;
FD_ZERO( &fdread );
FD_SET( m_socket, &fdread );
tv.tv_sec = 1;
tv.tv_usec = 0;
rc = select( m_socket+1, &fdread, 0, 0, &tv );
if ( terminate != 0 && *terminate ) return 1;
if ( rc > 0 && FD_ISSET( m_socket, &fdread ) ) break;
time( &timenow );
if ( (ofuint32)timenow > timestart + timeOut ) return 1;
}
ofint32 chunkToRead = (bufferLength < (ofuint32)chunkSize)
?bufferLength:chunkSize;
ofint32 curRecv = ::recv( m_socket, static_cast<char *>(buffer),
chunkToRead, 0 );
#if defined(VERBOSE_NETWORK)
cout << "Socket:" << m_socket
<< " received " << curRecv
<< " bytes" << endl;
#endif
if ( terminate != 0 && *terminate ) return 1;
if (curRecv < 0)
{
#if defined(VERBOSE_NETWORK)
cout << "Socket:" << m_socket
<< " received -1" << endl;
return -1;
#endif
}
if ( curRecv > 0 )
{
bytesReceived = curRecv;
return 0;
}
return -1;
}
void
OFSocket::startup( )
{
#if defined(OFOPSYS_WIN32)
WSADATA data;
WSAStartup( MAKEWORD(2,0), &data );
#endif
}
void
OFSocket::closedown()
{
#if defined(OFOPSYS_WIN32)
WSACleanup();
#endif
}
ofuint32 OFSocket::getnamefromaddr(char* peerName,
ofuint32 peerNameLen,
struct in_addr* addr,
ofuint32 addrLen,
char useDNS /*=0*/)
{
const char* pn = "unknown";
if (!useDNS)
{
pn = inet_ntoa(*addr);
}
else
{
#if defined(OFOPSYS_WIN32)
struct hostent* he = gethostbyaddr((char*)addr, addrLen, AF_INET);
#else
struct hostent* he = gethostbyaddr(addr, addrLen, AF_INET);
#endif
if (he && he->h_name)
pn = he->h_name;
}
OFOS::strncpy2(peerName, pn, peerNameLen);
return 0;
}
ofuint32 OFSocket::getpeername(char* peerName,
ofuint32 peerNameLen,
char useDNS /*= 0*/)
{
struct sockaddr_in pa;
OFOS::of_socklen_t sl = sizeof(pa);
int r = ::getpeername(m_socket, (sockaddr*)&pa, &sl);
if (r != -1)
{
OFSocket::getnamefromaddr(peerName, peerNameLen,
&pa.sin_addr, sizeof(pa.sin_addr),
useDNS);
}
return r==0?ERR_SUCCESS:OFUtility::translateSystemError(r);
}
/* static */
void
OFSocket::getHostName( char *host, ofuint32 length )
{
RESETSTRING( host );
char x[1024];
gethostname( x, 1024 );
struct hostent *he = gethostbyname( x );
if ( he )
{
OFOS::strncpy2( host, he->h_name, length );
}
}
/* static */
ofuint32
OFSocket::getLocalIP( )
{
char name[1025];
gethostname( name, 1024 );
return OFPlatform::getHostIP(name);
}
void
OFSocket::set_options_()
{
#if defined(OFOPSYS_LINUX) || defined(OFOPSYS_WIN32)
ofuint32 f = 1;
setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, (char *)&f, sizeof(f));
setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&f, sizeof(f));
f = OF_SOCK_SEND_BUFSIZE;
setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char*)&f, sizeof(f));
f = OF_SOCK_RECV_BUFSIZE;
setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char*)&f, sizeof(f));
struct timeval tv;
memset(&tv, 0, sizeof(tv));
tv.tv_sec = 180;
setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));
#endif
}
#if defined(UNIT_TEST)
#include "UnitTest.h"
int
main( ofint32 argc, char *argv[] )
{
UT_BATCH_START( "OFSocket class unit test" );
UT_TEST_START( 1, "OFSocket::getLocalIP" );
ofuint32 la = OFSocket::getLocalIP();
printf("local address: %08lx", la);
UT_BATCH_END;
return 0;
}
#endif // #if defined(UNIT_TEST)
| 24.671123 | 112 | 0.60117 |
timmyw
|
e90e0e1b80506adc742ea818d1bbdf997615580f
| 9,408 |
cpp
|
C++
|
third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
|
wenfeifei/miniblink49
|
2ed562ff70130485148d94b0e5f4c343da0c2ba4
|
[
"Apache-2.0"
] | 5,964 |
2016-09-27T03:46:29.000Z
|
2022-03-31T16:25:27.000Z
|
third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
|
w4454962/miniblink49
|
b294b6eacb3333659bf7b94d670d96edeeba14c0
|
[
"Apache-2.0"
] | 459 |
2016-09-29T00:51:38.000Z
|
2022-03-07T14:37:46.000Z
|
third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
|
w4454962/miniblink49
|
b294b6eacb3333659bf7b94d670d96edeeba14c0
|
[
"Apache-2.0"
] | 1,006 |
2016-09-27T05:17:27.000Z
|
2022-03-30T02:46:51.000Z
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "bindings/core/v8/ScriptState.h"
#include "core/dom/DOMException.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/frame/UseCounter.h"
#include "modules/encryptedmedia/EncryptedMediaUtils.h"
#include "modules/encryptedmedia/MediaKeySession.h"
#include "modules/encryptedmedia/MediaKeySystemAccess.h"
#include "modules/encryptedmedia/MediaKeysController.h"
#include "platform/EncryptedMediaRequest.h"
#include "platform/Logging.h"
#include "platform/network/ParsedContentType.h"
#include "public/platform/WebEncryptedMediaClient.h"
#include "public/platform/WebEncryptedMediaRequest.h"
#include "public/platform/WebMediaKeySystemConfiguration.h"
#include "public/platform/WebMediaKeySystemMediaCapability.h"
#include "public/platform/WebVector.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
namespace blink {
namespace {
static WebVector<WebEncryptedMediaInitDataType> convertInitDataTypes(const Vector<String>& initDataTypes)
{
WebVector<WebEncryptedMediaInitDataType> result(initDataTypes.size());
for (size_t i = 0; i < initDataTypes.size(); ++i)
result[i] = EncryptedMediaUtils::convertToInitDataType(initDataTypes[i]);
return result;
}
static WebVector<WebMediaKeySystemMediaCapability> convertCapabilities(const HeapVector<MediaKeySystemMediaCapability>& capabilities)
{
WebVector<WebMediaKeySystemMediaCapability> result(capabilities.size());
for (size_t i = 0; i < capabilities.size(); ++i) {
const WebString& contentType = capabilities[i].contentType();
result[i].contentType = contentType;
if (isValidContentType(contentType)) {
// FIXME: Fail if there are unrecognized parameters.
ParsedContentType type(capabilities[i].contentType());
result[i].mimeType = type.mimeType();
result[i].codecs = type.parameterValueForName("codecs");
}
result[i].robustness = capabilities[i].robustness();
}
return result;
}
static WebMediaKeySystemConfiguration::Requirement convertMediaKeysRequirement(const String& requirement)
{
if (requirement == "required")
return WebMediaKeySystemConfiguration::Requirement::Required;
if (requirement == "optional")
return WebMediaKeySystemConfiguration::Requirement::Optional;
if (requirement == "not-allowed")
return WebMediaKeySystemConfiguration::Requirement::NotAllowed;
// Everything else gets the default value.
ASSERT_NOT_REACHED();
return WebMediaKeySystemConfiguration::Requirement::Optional;
}
static WebVector<WebEncryptedMediaSessionType> convertSessionTypes(const Vector<String>& sessionTypes)
{
WebVector<WebEncryptedMediaSessionType> result(sessionTypes.size());
for (size_t i = 0; i < sessionTypes.size(); ++i)
result[i] = EncryptedMediaUtils::convertToSessionType(sessionTypes[i]);
return result;
}
// This class allows capabilities to be checked and a MediaKeySystemAccess
// object to be created asynchronously.
class MediaKeySystemAccessInitializer final : public EncryptedMediaRequest {
WTF_MAKE_NONCOPYABLE(MediaKeySystemAccessInitializer);
public:
MediaKeySystemAccessInitializer(ScriptState*, const String& keySystem, const HeapVector<MediaKeySystemConfiguration>& supportedConfigurations);
~MediaKeySystemAccessInitializer() override { }
// EncryptedMediaRequest implementation.
WebString keySystem() const override { return m_keySystem; }
const WebVector<WebMediaKeySystemConfiguration>& supportedConfigurations() const override { return m_supportedConfigurations; }
SecurityOrigin* securityOrigin() const override { return m_resolver->executionContext()->securityOrigin(); }
void requestSucceeded(WebContentDecryptionModuleAccess*) override;
void requestNotSupported(const WebString& errorMessage) override;
ScriptPromise promise() { return m_resolver->promise(); }
private:
RefPtr<ScriptPromiseResolver> m_resolver;
const String m_keySystem;
WebVector<WebMediaKeySystemConfiguration> m_supportedConfigurations;
};
MediaKeySystemAccessInitializer::MediaKeySystemAccessInitializer(ScriptState* scriptState, const String& keySystem, const HeapVector<MediaKeySystemConfiguration>& supportedConfigurations)
: m_resolver(ScriptPromiseResolver::create(scriptState))
, m_keySystem(keySystem)
, m_supportedConfigurations(supportedConfigurations.size())
{
for (size_t i = 0; i < supportedConfigurations.size(); ++i) {
const MediaKeySystemConfiguration& config = supportedConfigurations[i];
WebMediaKeySystemConfiguration webConfig;
if (config.hasInitDataTypes()) {
webConfig.hasInitDataTypes = true;
webConfig.initDataTypes = convertInitDataTypes(config.initDataTypes());
}
if (config.hasAudioCapabilities()) {
webConfig.hasAudioCapabilities = true;
webConfig.audioCapabilities = convertCapabilities(config.audioCapabilities());
}
if (config.hasVideoCapabilities()) {
webConfig.hasVideoCapabilities = true;
webConfig.videoCapabilities = convertCapabilities(config.videoCapabilities());
}
ASSERT(config.hasDistinctiveIdentifier());
webConfig.distinctiveIdentifier = convertMediaKeysRequirement(config.distinctiveIdentifier());
ASSERT(config.hasPersistentState());
webConfig.persistentState = convertMediaKeysRequirement(config.persistentState());
if (config.hasSessionTypes()) {
webConfig.hasSessionTypes = true;
webConfig.sessionTypes = convertSessionTypes(config.sessionTypes());
}
// If |label| is not present, it will be a null string.
webConfig.label = config.label();
m_supportedConfigurations[i] = webConfig;
}
}
void MediaKeySystemAccessInitializer::requestSucceeded(WebContentDecryptionModuleAccess* access)
{
m_resolver->resolve(new MediaKeySystemAccess(m_keySystem, adoptPtr(access)));
m_resolver.clear();
}
void MediaKeySystemAccessInitializer::requestNotSupported(const WebString& errorMessage)
{
m_resolver->reject(DOMException::create(NotSupportedError, errorMessage));
m_resolver.clear();
}
} // namespace
ScriptPromise NavigatorRequestMediaKeySystemAccess::requestMediaKeySystemAccess(
ScriptState* scriptState,
Navigator& navigator,
const String& keySystem,
const HeapVector<MediaKeySystemConfiguration>& supportedConfigurations)
{
WTF_LOG(Media, "NavigatorRequestMediaKeySystemAccess::requestMediaKeySystemAccess()");
// From https://w3c.github.io/encrypted-media/#requestMediaKeySystemAccess
// When this method is invoked, the user agent must run the following steps:
// 1. If keySystem is an empty string, return a promise rejected with a
// new DOMException whose name is InvalidAccessError.
if (keySystem.isEmpty()) {
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(InvalidAccessError, "The keySystem parameter is empty."));
}
// 2. If supportedConfigurations was provided and is empty, return a
// promise rejected with a new DOMException whose name is
// InvalidAccessError.
if (!supportedConfigurations.size()) {
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(InvalidAccessError, "The supportedConfigurations parameter is empty."));
}
// 3-4. 'May Document use powerful features?' check.
ExecutionContext* executionContext = scriptState->executionContext();
String errorMessage;
if (executionContext->isPrivilegedContext(errorMessage)) {
UseCounter::count(executionContext, UseCounter::EncryptedMediaSecureOrigin);
} else {
UseCounter::countDeprecation(executionContext, UseCounter::EncryptedMediaInsecureOrigin);
// TODO(ddorwin): Implement the following:
// Reject promise with a new DOMException whose name is NotSupportedError.
}
// 5. Let origin be the origin of document.
// (Passed with the execution context in step 7.)
// 6. Let promise be a new promise.
Document* document = toDocument(executionContext);
if (!document->page()) {
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(InvalidStateError, "The context provided is not associated with a page."));
}
MediaKeySystemAccessInitializer* initializer = new MediaKeySystemAccessInitializer(scriptState, keySystem, supportedConfigurations);
ScriptPromise promise = initializer->promise();
// 7. Asynchronously determine support, and if allowed, create and
// initialize the MediaKeySystemAccess object.
MediaKeysController* controller = MediaKeysController::from(document->page());
WebEncryptedMediaClient* mediaClient = controller->encryptedMediaClient(executionContext);
mediaClient->requestMediaKeySystemAccess(WebEncryptedMediaRequest(initializer));
// 8. Return promise.
return promise;
}
} // namespace blink
| 44.169014 | 187 | 0.75 |
wenfeifei
|
e90f4bead4b3127c61e8ccd7159d46826fd68eb8
| 1,591 |
cpp
|
C++
|
tests/msat/msat-array-models.cpp
|
andrewvaughanj/smt-switch
|
9c1ba328f8d69fb3b832820b765df71b0cd9bc65
|
[
"BSD-3-Clause"
] | 49 |
2018-02-20T12:47:28.000Z
|
2021-08-14T17:06:19.000Z
|
tests/msat/msat-array-models.cpp
|
andrewvaughanj/smt-switch
|
9c1ba328f8d69fb3b832820b765df71b0cd9bc65
|
[
"BSD-3-Clause"
] | 117 |
2017-06-30T18:26:02.000Z
|
2021-08-17T19:50:18.000Z
|
tests/msat/msat-array-models.cpp
|
andrewvaughanj/smt-switch
|
9c1ba328f8d69fb3b832820b765df71b0cd9bc65
|
[
"BSD-3-Clause"
] | 21 |
2019-10-10T22:22:03.000Z
|
2021-07-22T14:15:10.000Z
|
/********************* */
/*! \file msat-array-models.cpp
** \verbatim
** Top contributors (to current version):
** Makai Mann
** This file is part of the smt-switch project.
** Copyright (c) 2020 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file LICENSE in the top-level source
** directory for licensing information.\endverbatim
**
** \brief
**
**
**/
#include <iostream>
#include <memory>
#include <vector>
#include "assert.h"
#include "msat_factory.h"
#include "smt.h"
// after a full installation
// #include "smt-switch/msat_factory.h"
// #include "smt-switch/smt.h"
using namespace smt;
using namespace std;
int main()
{
SmtSolver s = MsatSolverFactory::create(false);
s->set_opt("produce-models", "true");
Sort bvsort32 = s->make_sort(BV, 32);
Sort array32_32 = s->make_sort(ARRAY, bvsort32, bvsort32);
Term x0 = s->make_symbol("x0", bvsort32);
Term x1 = s->make_symbol("x1", bvsort32);
Term y = s->make_symbol("y", bvsort32);
Term arr = s->make_symbol("arr", array32_32);
Term constraint = s->make_term(Equal, s->make_term(Select, arr, x0), x1);
constraint = s->make_term(
And, constraint, s->make_term(Equal, s->make_term(Select, arr, x1), y));
constraint = s->make_term(And, constraint, s->make_term(Distinct, x1, y));
s->assert_formula(constraint);
Result r = s->check_sat();
assert(r.is_sat());
Term arr_val = s->get_value(arr);
cout << arr_val << endl;
return 0;
}
| 27.912281 | 80 | 0.65242 |
andrewvaughanj
|
e90fd826c539b8636606798846eaecad36402fdb
| 529 |
cpp
|
C++
|
Synthesizer/MainScreen.cpp
|
161563/Sylph-Synthesizer
|
548e62f1353f254af874d2d06fd6216b808edfd6
|
[
"MIT"
] | null | null | null |
Synthesizer/MainScreen.cpp
|
161563/Sylph-Synthesizer
|
548e62f1353f254af874d2d06fd6216b808edfd6
|
[
"MIT"
] | null | null | null |
Synthesizer/MainScreen.cpp
|
161563/Sylph-Synthesizer
|
548e62f1353f254af874d2d06fd6216b808edfd6
|
[
"MIT"
] | null | null | null |
#include "MainScreen.h"
#include "Song.h"
#include "Music.h"
#include <string>
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
void main(array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
for (int i = 0; i < args->Length; i++) {
//MessageBox::Show(args[i]);
}
Synthesizer::MainScreen screen;
if (args->Length == 1) {
screen.setSong(new Song(args[0]));
}
else {
screen.setSong(new Song());
}
Application::Run(%screen);
}
| 21.16 | 55 | 0.691871 |
161563
|
e910c788acd61fff99e72aaa8cc69885e5ee4470
| 352 |
cc
|
C++
|
CondFormats/ESObjects/src/ESADCToGeVConstant.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 3 |
2018-08-24T19:10:26.000Z
|
2019-02-19T11:45:32.000Z
|
CondFormats/ESObjects/src/ESADCToGeVConstant.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 3 |
2018-08-23T13:40:24.000Z
|
2019-12-05T21:16:03.000Z
|
CondFormats/ESObjects/src/ESADCToGeVConstant.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 5 |
2018-08-21T16:37:52.000Z
|
2020-01-09T13:33:17.000Z
|
#include "CondFormats/ESObjects/interface/ESADCToGeVConstant.h"
ESADCToGeVConstant::ESADCToGeVConstant()
{
ESvaluelow_=0.;
ESvaluehigh_=0.;
}
ESADCToGeVConstant::ESADCToGeVConstant(const float & ESvaluelow, const float & ESvaluehigh) {
ESvaluelow_ = ESvaluelow;
ESvaluehigh_ = ESvaluehigh;
}
ESADCToGeVConstant::~ESADCToGeVConstant() {
}
| 19.555556 | 93 | 0.775568 |
nistefan
|
e916529e0689dec760e84712b9d2d9244d169ea4
| 1,661 |
cpp
|
C++
|
src/nn/axpby.cpp
|
tahsinkose/graphnn
|
cf38e2a4e459a2d0138c3153d1aa9d69137b04b2
|
[
"MIT"
] | 277 |
2016-01-26T10:47:03.000Z
|
2022-03-28T11:47:03.000Z
|
src/nn/axpby.cpp
|
tahsinkose/graphnn
|
cf38e2a4e459a2d0138c3153d1aa9d69137b04b2
|
[
"MIT"
] | 35 |
2017-04-05T16:02:16.000Z
|
2022-02-17T15:24:25.000Z
|
src/nn/axpby.cpp
|
tahsinkose/graphnn
|
cf38e2a4e459a2d0138c3153d1aa9d69137b04b2
|
[
"MIT"
] | 90 |
2016-01-26T10:40:39.000Z
|
2022-02-28T10:55:32.000Z
|
#include "nn/axpby.h"
namespace gnn
{
template<typename mode, typename Dtype>
Axpby<mode, Dtype>::Axpby(std::string _name, Dtype _a, Dtype _b, PropErr _properr)
: Factor(_name, _properr), a(_a), b(_b)
{
}
template<typename mode, typename Dtype>
void Axpby<mode, Dtype>::Forward(std::vector< std::shared_ptr<Variable> >& operands,
std::vector< std::shared_ptr<Variable> >& outputs,
Phase phase)
{
ASSERT(operands.size() == 2, "unexpected input size for " << StrType());
ASSERT(outputs.size() == 1, "unexpected output size for " << StrType());
auto& output = dynamic_cast<DTensorVar<mode, Dtype>*>(outputs[0].get())->value;
auto& x = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[0].get())->value;
auto& y = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[1].get())->value;
output.CopyFrom(y);
output.Axpby(a, x, b);
}
template<typename mode, typename Dtype>
void Axpby<mode, Dtype>::Backward(std::vector< std::shared_ptr<Variable> >& operands,
std::vector< bool >& isConst,
std::vector< std::shared_ptr<Variable> >& outputs)
{
ASSERT(operands.size() == 2, "unexpected input size for " << StrType());
ASSERT(outputs.size() == 1, "unexpected output size for " << StrType());
auto cur_grad = dynamic_cast<DTensorVar<mode, Dtype>*>(outputs[0].get())->grad.Full();
for (size_t i = 0; i < operands.size(); ++i)
{
if (isConst[i])
continue;
auto& grad_i = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[i].get())->grad;
ASSERT(grad_i.shape == cur_grad.shape, "no broadcasting is supported right now");
grad_i.Full().Axpy( i == 0 ? a : b, cur_grad);
}
}
INSTANTIATE_CLASS(Axpby)
}
| 31.942308 | 87 | 0.662854 |
tahsinkose
|
e9176cffaec1e7d5f5a498abdb09a3fe2ae6dc3c
| 1,072 |
cpp
|
C++
|
WirelessThermometer/TimerSwitchWithServo/ServoMotion.cpp
|
anders-liu/arduino-gallery
|
8c65701a33358891b7105b50f831d7f5797288ad
|
[
"MIT"
] | 1 |
2019-11-07T22:44:27.000Z
|
2019-11-07T22:44:27.000Z
|
WirelessThermometer/TimerSwitchWithServo/ServoMotion.cpp
|
anders-liu/arduino-gallery
|
8c65701a33358891b7105b50f831d7f5797288ad
|
[
"MIT"
] | null | null | null |
WirelessThermometer/TimerSwitchWithServo/ServoMotion.cpp
|
anders-liu/arduino-gallery
|
8c65701a33358891b7105b50f831d7f5797288ad
|
[
"MIT"
] | null | null | null |
#include "ServoMotion.h"
#include "DataStore.h"
#define START_DELAY 200
#define RUNNING_HOLD_PERIOD 1000
enum ServoMotionState_t {
SS_OFF,
SS_JUST_ON,
SS_RUNNING,
};
static void s_powerOff(uint8_t powerPin) {
digitalWrite(powerPin, LOW);
}
static void s_powerOn(uint8_t powerPin) {
digitalWrite(powerPin, HIGH);
}
void ServoMotion::setup() {
pinMode(this->powerPin, OUTPUT);
s_powerOff(this->powerPin);
this->servo.attach(this->controlPin);
}
void ServoMotion::loop() {
switch (this->state) {
case SS_OFF:
if (ds.getCurrentServoValueReadyToSend()) {
this->servo.write(ds.getCurrentServoValue());
ds.clearCurrentServoValueReadyToSend();
this->state = SS_JUST_ON;
this->lastMillis = millis();
}
break;
case SS_JUST_ON:
if (millis() - this->lastMillis > START_DELAY) {
s_powerOn(this->powerPin);
this->state = SS_RUNNING;
this->lastMillis = millis();
}
break;
case SS_RUNNING:
if (millis() - this->lastMillis > RUNNING_HOLD_PERIOD) {
s_powerOff(this->powerPin);
this->state = SS_OFF;
}
break;
}
}
| 19.490909 | 58 | 0.697761 |
anders-liu
|
e917c8d3fb72073d52dbfa4de3fb13a5bec68f82
| 1,171 |
cpp
|
C++
|
deps/src/boost_1_65_1/libs/python/test/destroy_test.cpp
|
shreyasvj25/turicreate
|
32e84ca16aef8d04aff3d49ae9984bd49326bffd
|
[
"BSD-3-Clause"
] | 11,356 |
2017-12-08T19:42:32.000Z
|
2022-03-31T16:55:25.000Z
|
deps/src/boost_1_65_1/libs/python/test/destroy_test.cpp
|
shreyasvj25/turicreate
|
32e84ca16aef8d04aff3d49ae9984bd49326bffd
|
[
"BSD-3-Clause"
] | 2,402 |
2017-12-08T22:31:01.000Z
|
2022-03-28T19:25:52.000Z
|
deps/src/boost_1_65_1/libs/python/test/destroy_test.cpp
|
shreyasvj25/turicreate
|
32e84ca16aef8d04aff3d49ae9984bd49326bffd
|
[
"BSD-3-Clause"
] | 1,343 |
2017-12-08T19:47:19.000Z
|
2022-03-26T11:31:36.000Z
|
// Copyright David Abrahams 2004. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python/detail/destroy.hpp>
#include <boost/detail/lightweight_test.hpp>
int count;
int marks[] = {
-1
, -1, -1
, -1, -1, -1, -1
, -1
};
int* kills = marks;
struct foo
{
foo() : n(count++) {}
~foo()
{
*kills++ = n;
}
int n;
// This used to cause compiler errors with MSVC 9.0.
foo& operator~();
foo& T();
};
void assert_destructions(int n)
{
for (int i = 0; i < n; ++i)
BOOST_TEST(marks[i] == i);
BOOST_TEST(marks[n] == -1);
}
int main()
{
assert_destructions(0);
foo* f1 = new foo;
boost::python::detail::destroy_referent<foo const volatile&>(f1);
assert_destructions(1);
foo* f2 = new foo[2];
typedef foo x[2];
boost::python::detail::destroy_referent<x const&>(f2);
assert_destructions(3);
typedef foo y[2][2];
x* f3 = new y;
boost::python::detail::destroy_referent<y&>(f3);
assert_destructions(7);
return boost::report_errors();
}
| 19.847458 | 72 | 0.600342 |
shreyasvj25
|
e917d0a96f269a8a0fb6cc14e7c1320b3cf3a3f7
| 700 |
hpp
|
C++
|
android-29/android/media/MediaRecorder_AudioEncoder.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12 |
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/android/media/MediaRecorder_AudioEncoder.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1 |
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-30/android/media/MediaRecorder_AudioEncoder.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3 |
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
#include "../../JObject.hpp"
namespace android::media
{
class MediaRecorder;
}
namespace android::media
{
class MediaRecorder_AudioEncoder : public JObject
{
public:
// Fields
static jint AAC();
static jint AAC_ELD();
static jint AMR_NB();
static jint AMR_WB();
static jint DEFAULT();
static jint HE_AAC();
static jint OPUS();
static jint VORBIS();
// QJniObject forward
template<typename ...Ts> explicit MediaRecorder_AudioEncoder(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
MediaRecorder_AudioEncoder(QJniObject obj);
// Constructors
// Methods
};
} // namespace android::media
| 20 | 167 | 0.692857 |
YJBeetle
|
e91a18927dc83eb1469e3ebc933d4917f5b0214b
| 944 |
cc
|
C++
|
jax/training/21-09/29/b_precessing_queries.cc
|
JaxVanYang/acm
|
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
|
[
"MIT"
] | 2 |
2022-01-01T16:55:02.000Z
|
2022-03-16T14:47:29.000Z
|
jax/training/21-09/29/b_precessing_queries.cc
|
JaxVanYang/acm
|
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
|
[
"MIT"
] | null | null | null |
jax/training/21-09/29/b_precessing_queries.cc
|
JaxVanYang/acm
|
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <queue>
using namespace std;
using ll = long long;
const int N = 2e5 + 10;
ll ans[N];
struct Node {
int t, d, id;
};
int main() {
int n, b;
scanf("%d%d", &n, &b);
ll ed = 0;
queue<Node> q;
for (int i = 0; i < n; ++i) {
int t, d;
scanf("%d%d", &t, &d);
if (q.size() == b + 1) {
ll lmt = max(ed, (ll)q.front().t) + q.front().d;
if (lmt > t) {
ans[i] = -1;
} else {
ans[q.front().id] = lmt;
q.pop();
ed = lmt;
q.push({t, d, i});
}
} else {
q.push({t, d, i});
}
}
while (q.size()) {
ed = max(ed, (ll)q.front().t) + q.front().d;
ans[q.front().id] = ed;
q.pop();
}
for (int i = 0; i < n; ++i) {
printf("%lld ", ans[i]);
}
puts("");
}
| 17.811321 | 60 | 0.347458 |
JaxVanYang
|
e91ac1f5e22f7be38a8ace97a06691abd2c9b452
| 27,860 |
cpp
|
C++
|
libqd/qd.cpp
|
philippeb8/fcalc
|
b62a78e02b56dc4319e06d8eb36bb3d6fdafd256
|
[
"MIT"
] | 2 |
2020-10-24T01:15:51.000Z
|
2020-10-25T04:07:30.000Z
|
libqd/qd.cpp
|
philippeb8/fcalc
|
b62a78e02b56dc4319e06d8eb36bb3d6fdafd256
|
[
"MIT"
] | null | null | null |
libqd/qd.cpp
|
philippeb8/fcalc
|
b62a78e02b56dc4319e06d8eb36bb3d6fdafd256
|
[
"MIT"
] | null | null | null |
/*
* src/qd.cc
*
* This work was supported by the Director, Office of Science, Division
* of Mathematical, Information, and Computational Sciences of the
* U.S. Department of Energy under contract number DE-AC03-76SF00098.
*
* Copyright (c) 2000-2001
*
* Contains implementation of non-inlined functions of quad-double
* package. Inlined functions are found in qd_inline.h (in include directory).
*/
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <iostream>
//#include "config.h"
//#include "bits.h"
#include "qd.h"
#ifndef QD_INLINE
#include "qd_inline.h"
#endif
#ifdef _MSC_VER
#define STD_RAND ::rand
#else
#define STD_RAND std::rand
#endif
using std::cout;
using std::cerr;
using std::endl;
using std::istream;
using std::ostream;
using std::ios_base;
using namespace qd;
static const char *digits = "0123456789*";
void qd_real::abort() {
exit(-1);
}
/********** Multiplications **********/
qd_real nint(const qd_real &a) {
real x0, x1, x2, x3;
x0 = nint(a[0]);
x1 = x2 = x3 = real(0.0);
if (x0 == a[0]) {
/* First real is already an integer. */
x1 = nint(a[1]);
if (x1 == a[1]) {
/* Second real is already an integer. */
x2 = nint(a[2]);
if (x2 == a[2]) {
/* Third real is already an integer. */
x3 = nint(a[3]);
} else {
if (fabsl(x2 - a[2]) == real(0.5) && a[3] < real(0.0)) {
x2 -= real(1.0);
}
}
} else {
if (fabsl(x1 - a[1]) == real(0.5) && a[2] < real(0.0)) {
x1 -= real(1.0);
}
}
} else {
/* First real is not an integer. */
if (fabsl(x0 - a[0]) == real(0.5) && a[1] < real(0.0)) {
x0 -= real(1.0);
}
}
renorm(x0, x1, x2, x3);
return qd_real(x0, x1, x2, x3);
}
qd_real floor(const qd_real &a) {
real x0, x1, x2, x3;
x1 = x2 = x3 = real(0.0);
x0 = floorl(a[0]);
if (x0 == a[0]) {
x1 = floorl(a[1]);
if (x1 == a[1]) {
x2 = floorl(a[2]);
if (x2 == a[2]) {
x3 = floorl(a[3]);
}
}
renorm(x0, x1, x2, x3);
return qd_real(x0, x1, x2, x3);
}
return qd_real(x0, x1, x2, x3);
}
qd_real ceil(const qd_real &a) {
real x0, x1, x2, x3;
x1 = x2 = x3 = real(0.0);
x0 = ceill(a[0]);
if (x0 == a[0]) {
x1 = ceill(a[1]);
if (x1 == a[1]) {
x2 = ceill(a[2]);
if (x2 == a[2]) {
x3 = ceill(a[3]);
}
}
renorm(x0, x1, x2, x3);
return qd_real(x0, x1, x2, x3);
}
return qd_real(x0, x1, x2, x3);
}
/********** Divisions **********/
/* quad-real / real */
qd_real operator/(const qd_real &a, real b) {
/* Strategy: compute approximate quotient using high order
reals, and then correct it 3 times using the remainder.
(Analogous to long division.) */
real t0, t1;
real q0, q1, q2, q3;
qd_real r;
q0 = a[0] / b; /* approximate quotient */
/* Compute the remainder a - q0 * b */
t0 = two_prod(q0, b, t1);
r = a - dd_real(t0, t1);
/* Compute the first correction */
q1 = r[0] / b;
t0 = two_prod(q1, b, t1);
r -= dd_real(t0, t1);
/* Second correction to the quotient. */
q2 = r[0] / b;
t0 = two_prod(q2, b, t1);
r -= dd_real(t0, t1);
/* Final correction to the quotient. */
q3 = r[0] / b;
renorm(q0, q1, q2, q3);
return qd_real(q0, q1, q2, q3);
}
/*
qd_real::qd_real(const char *s) {
int r = qd_real::read(s, *this);
if (r != 0) {
qd_real::abort();
cerr << "ERROR (qd_real::qd_real): INPUT ERROR." << endl;
}
}
*/
istream &operator>>(istream &s, qd_real &qd) {
char str[255];
s >> str;
qd.read(str, qd);
return s;
}
ostream &operator<<(ostream &s, const qd_real &qd) {
char str[255];
qd.write(str, s.precision(), s.flags());
return s << str;
}
/* Read a quad-real from s. */
int qd_real::read(const char *s, qd_real &qd) {
const char *p = s;
char ch;
int sign = 0;
int point = -1; /* location of decimal point */
int nd = 0; /* number of digits read */
int e = 0; /* exponent. */
bool done = false;
qd_real r = real(0.0); /* number being read */
/* Skip any leading spaces */
while (*p == ' ') p++;
while (!done && (ch = *p) != '\0') {
if (ch >= '0' && ch <= '9') {
/* It's a digit */
int d = ch - '0';
r *= real(10.0);
r += (real) d;
nd++;
} else {
/* Non-digit */
switch (ch) {
case '.':
if (point >= 0)
return -1; /* we've already encountered a decimal point. */
point = nd;
break;
case '-':
case '+':
if (sign != 0 || nd > 0)
return -1; /* we've already encountered a sign, or if its
not at first position. */
sign = (ch == '-') ? -1 : 1;
break;
case 'E':
case 'e':
int nread;
nread = sscanf(p+1, "%d", &e);
done = true;
if (nread != 1)
return -1; /* read of exponent failed. */
break;
case ' ':
done = true;
break;
default:
return -1;
}
}
p++;
}
/* Adjust exponent to account for decimal point */
if (point >= 0) {
e -= (nd - point);
}
/* Multiply the the exponent */
if (e != 0) {
r *= (qd_real(10.0) ^ e);
}
qd = (sign < 0) ? -r : r;
return 0;
}
/* Converts a quad-real to a string.
d is the number of (decimal) significant digits.
The string s must be able to hold d+8 characters. */
void qd_real::write(char *s, int d, ios_base::fmtflags l) const {
qd_real r = fabs(*this);
qd_real p;
int e; /* exponent */
int i = 0, j = 0;
/* First determine the (approximate) exponent. */
e = (int) floorl(log10l(fabsl(x[0])));
/* Find dimensions. */
bool m = (l & qd_real::showmagnitude), n = (l & std::ios_base::showpoint), is = (l & qd_real::imperialsystem);
int D = (n ? d : e + (d < 1 ? d : 1)) + 1;
if (x[0] == real(0.0))
{
/* this == real(0.0) */
s[i ++] = digits[0];
if (n)
{
s[i ++] = '.';
}
s[i ++] = '\0';
return;
}
/* Test for infinity and nan. */
if (isinf())
{
sprintf(s, "NAN");
return;
}
if (isnan())
{
sprintf(s, "NAN");
return;
}
/* Digits */
int *a = new int[D];
if (e < -4000)
{
r *= qd_real(10.0) ^ 4000;
p = qd_real(10.0) ^ (e + 4000);
r /= p;
}
else
{
p = qd_real(10.0) ^ e;
r /= p;
}
/* Fix exponent if we are off by one */
if ((real const &)(r) >= real(10.0))
{
r /= real(10.0);
e++;
}
else if ((real const &)(r) < real(1.0))
{
r *= real(10.0);
e--;
}
if ((real const &)(r) >= real(10.0) || (real const &)(r) < real(1.0))
{
//cerr << "ERROR (qd_real::to_str): can't compute exponent." << endl;
delete [] a;
//qd_real::abort();
return;
}
/* Extract the digits */
for (i = 0; i < D; i++)
{
a[i] = (int) r[0];
r -= (real) a[i];
r *= real(10.0);
}
/* Fix negative digits. */
for (i = D-1; i > 0; i--)
{
if (a[i] < 0)
{
a[i-1]--;
a[i] += 10;
}
}
if (a[0] <= 0)
{
//cerr << "ERROR (qd_real::to_str): non-positive leading digit." << endl;
delete [] a;
//qd_real::abort();
return;
}
/* Round, handle carry */
if (a[D - 1] >= 5)
{
a[D - 2] ++;
int i = D - 2;
while (i > 0 && a[i] >= 10)
{
a[i] -= 10;
a[-- i] ++;
}
if (a[0] == 10)
{
++ e;
a[0] = 1;
}
}
/* Start fill in the string. */
if (x[0] < real(0.0))
{
s[i ++] = '-';
}
bool scientific = (l & std::ios_base::scientific) || ! (e > -4 && e < D - 1);
long f = scientific ? 0 : e, t = (f > 0 ? f : 0);
if (! m)
{
// C/C++ notation
for (; j < D - 1; -- f, ++ j)
{
if (a[j] != 0)
{
// Feed in leading zeros (0.0001...; 1.000...01)
for (; t != f; -- t)
{
s[i ++] = digits[0];
if (t % 3 == 0)
if (t == 0 && (scientific || n))
s[i ++] = '.';
}
s[i ++] = digits[a[j]];
if (t % 3 == 0)
if (t == 0 && (scientific || n))
s[i ++] = '.';
-- t;
}
}
// Dangling zeros (10000...)
for (; t >= 0; -- t)
{
s[i ++] = digits[0];
if (t % 3 == 0)
if (t == 0 && (scientific || n))
s[i ++] = '.';
}
}
else if (! is)
{
// Metric notation
for (bool first = true; j < D - 1; first = false, -- f, ++ j)
{
if (a[j] != 0)
{
// Feed in leading zeros (0.0001...; 1.000...01)
for (; t != f; -- t)
{
if ((t + 1) % 3 == 0)
if (t == -1 && (scientific || n))
s[i ++] = ',';
else if (! first)
s[i ++] = ' ';
s[i ++] = digits[0];
}
if ((t + 1) % 3 == 0)
if (t == -1 && (scientific || n))
s[i ++] = ',';
else if (! first)
s[i ++] = ' ';
s[i ++] = digits[a[j]];
-- t;
}
}
// Dangling zeros (10000...)
for (bool first = true; t >= 0; first = false, -- t)
{
if ((t + 1) % 3 == 0)
if (t == -1 && (scientific || n))
s[i ++] = ',';
else if (! first)
s[i ++] = ' ';
s[i ++] = digits[0];
}
}
else
{
// Imperial notation
for (; j < D - 1; -- f, ++ j)
{
if (a[j] != 0)
{
// Feed in leading zeros (0.0001...; 1.000...01)
for (; t != f; -- t)
{
s[i ++] = digits[0];
if (t % 3 == 0)
if (t == 0 && (scientific || n))
s[i ++] = '.';
else if (t > 0)
s[i ++] = ',';
}
s[i ++] = digits[a[j]];
if (t % 3 == 0)
if (t == 0 && (scientific || n))
s[i ++] = '.';
else if (t > 0)
s[i ++] = ',';
-- t;
}
}
// Dangling zeros (10000...)
for (; t >= 0; -- t)
{
s[i ++] = digits[0];
if (t % 3 == 0)
if (t == 0 && (scientific || n))
s[i ++] = '.';
else if (t > 0)
s[i ++] = ',';
}
}
if (! scientific)
{
s[i ++] = '\0';
}
else
{
s[i ++] = 'e';
sprintf(&s[i], "%d", e);
}
delete [] a;
}
/* Computes qd^n, where n is an integer. */
qd_real npwr(const qd_real &a, int n) {
if (n == 0)
return real(1.0);
qd_real r = a; /* odd-case multiplier */
qd_real s = real(1.0); /* current answer */
int N = abs(n);
if (N > 1) {
/* Use binary exponentiation. */
while (N > 0) {
if (N % 2 == 1) {
/* If odd, multiply by r. Note eventually N = 1, so this
eventually executes. */
s *= r;
}
N /= 2;
if (N > 0)
r = sqr(r);
}
} else {
s = r;
}
if (n < 0)
return (real(1.0) / s);
return s;
}
/* Computes real-real ^ real-real. */
qd_real pow(const qd_real &a, const qd_real &n) {
if (n == floor(n))
{
return npwr(a, n);
}
return exp(n * log(a));
}
#ifdef QD_DEBUG
/* Debugging routines */
void qd_real::dump_bits() const {
cout << "[ ";
print_real_info(x[0]);
cout << endl << " ";
print_real_info(x[1]);
cout << endl << " ";
print_real_info(x[2]);
cout << endl << " ";
print_real_info(x[3]);
cout << " ]" << endl;
}
void qd_real::dump_components() const {
printf("[ %.18e %.18e %.18e %.18e ]\n", x[0], x[1], x[2], x[3]);
}
void qd_real::dump() const {
cout << "[ ";
printf(" %25.19e ", x[0]);
print_real_info(x[0]);
cout << endl << " ";
printf(" %25.19e ", x[1]);
print_real_info(x[1]);
cout << endl << " ";
printf(" %25.19e ", x[2]);
print_real_info(x[2]);
cout << endl << " ";
printf(" %25.19e ", x[3]);
print_real_info(x[3]);
cout << " ]" << endl;
}
#endif
/* Divisions */
/* quad-real / real-real */
qd_real operator/ (const qd_real &a, const dd_real &b) {
real q0, q1, q2, q3;
qd_real r;
q0 = a[0] / b._hi();
r = a - q0 * b;
q1 = r[0] / b._hi();
r -= (q1 * b);
q2 = r[0] / b._hi();
r -= (q2 * b);
q3 = r[0] / b._hi();
#ifdef QD_SLOPPY_DIV
renorm(q0, q1, q2, q3);
#else
r -= (q3 * b);
real q4 = r[0] / b._hi();
renorm(q0, q1, q2, q3, q4);
#endif
return qd_real(q0, q1, q2, q3);
}
/* quad-real / quad-real */
qd_real operator/(const qd_real &a, const qd_real &b) {
real q0, q1, q2, q3;
qd_real r;
q0 = a[0] / b[0];
r = a - (b * q0);
q1 = r[0] / b[0];
r -= (b * q1);
q2 = r[0] / b[0];
r -= (b * q2);
q3 = r[0] / b[0];
#ifdef QD_SLOPPY_DIV
renorm(q0, q1, q2, q3);
#else
r -= (b * q3);
real q4 = r[0] / b[0];
renorm(q0, q1, q2, q3, q4);
#endif
return qd_real(q0, q1, q2, q3);
}
qd_real sqrt(const qd_real &a) {
/* Strategy:
Perform the following Newton iteration:
x' = x + (1 - a * x^2) * x / 2;
which converges to 1/sqrt(a), starting with the
real precision approximation to 1/sqrt(a).
Since Newton's iteration more or less reals the
number of correct digits, we only need to perform it
twice.
*/
if (a == real(0.0)) {
return qd_real(0.0);
}
qd_real r = (real(1.0) / sqrtl(a[0]));
qd_real h = a * real(0.5);
r += ((real(0.5) - h * sqr(r)) * r);
r += ((real(0.5) - h * sqr(r)) * r);
r += ((real(0.5) - h * sqr(r)) * r);
r *= a;
return r;
}
/* Computes the n-th root of a */
qd_real nroot(const qd_real &a, int n) {
/* Strategy: Use Newton's iteration to solve
1/(x^n) - a = 0
Newton iteration becomes
x' = x + x * (1 - a * x^n) / n
Since Newton's iteration converges quadratically,
we only need to perform it twice.
*/
if (a == real(0.0)) {
return qd_real(0.0);
}
qd_real r = powl(a[0], -real(1.0)/n);
r += r * (real(1.0) - a * (r ^ n)) / (real) n;
r += r * (real(1.0) - a * (r ^ n)) / (real) n;
r += r * (real(1.0) - a * (r ^ n)) / (real) n;
return real(1.0) / r;
}
qd_real exp(const qd_real &a) {
/* Strategy: We first reduce the size of x by noting that
exp(kr + m) = exp(m) * exp(r)^k
Thus by choosing m to be a multiple of log(2) closest
to x, we can make |kr| <= log(2) / 2 = 0.3466. Now
we can set k = 256, so that |r| <= 0.00136. Then
exp(x) = exp(kr + s log 2) = (2^s) * [exp(r)]^256
Then exp(r) is evaluated using the familiar Taylor series.
Reducing the argument substantially speeds up the convergence.
*/
const int k = 256;
if (a[0] <= real(-11335.0))
return real(0.0);
if (a[0] >= real(11335.0)) {
//cerr << "ERROR (qd_real::exp): Argument too large." << endl;
//qd_real::abort();
return qd_real::_inf;
}
if (a.is_zero()) {
return real(1.0);
}
if (a.is_one()) {
return qd_real::_e;
}
const int z = (int) nint(a / qd_real::_log2)[0];
qd_real r = (a - qd_real::_log2 * (real) z) / (real) k;
qd_real s, p;
real m;
real thresh = qd_real::_eps;
p = sqr(r) / real(2.0);
s = real(1.0) + r + p;
m = real(2.0);
do {
m += real(1.0);
p *= r;
p /= m;
s += p;
} while (fabsl((real) p) > thresh);
r = npwr(s, k);
r = mul_pwr2(r, ldexpl(real(1.0), z));
return r;
}
/* Logarithm. Computes log(x) in quad-real precision.
This is a natural logarithm (i.e., base e). */
qd_real log(const qd_real &a) {
/* Strategy. The Taylor series for log converges much more
slowly than that of exp, due to the lack of the factorial
term in the denominator. Hence this routine instead tries
to determine the root of the function
f(x) = exp(x) - a
using Newton iteration. The iteration is given by
x' = x - f(x)/f'(x)
= x - (1 - a * exp(-x))
= x + a * exp(-x) - 1.
Two iteration is needed, since Newton's iteration
approximately reals the number of digits per iteration. */
if (a.is_one()) {
return real(0.0);
}
if (a[0] <= real(0.0)) {
//cerr << "ERROR (qd_real::log): Non-positive argument." << endl;
//qd_real::abort();
return qd_real::_nan;
}
qd_real x = logl(a[0]); /* Initial approximation */
x = x + a * exp(-x) - real(1.0);
x = x + a * exp(-x) - real(1.0);
x = x + a * exp(-x) - real(1.0);
return x;
}
qd_real log10(const qd_real &a) {
return log(a) / qd_real::_log10;
}
/* Computes sin(a) and cos(a) using Taylor series.
Assumes |a| <= pi/2048. */
static void sincos_taylor(const qd_real &a,
qd_real &sin_a, qd_real &cos_a) {
const real thresh = qd_real::_eps * fabsl((real) a);
qd_real p; /* Current power of a. */
qd_real s; /* Current partial sum. */
qd_real x; /* = -sqr(a) */
real m;
if (a.is_zero()) {
sin_a = real(0.0);
cos_a = real(1.0);
return;
}
x = -sqr(a);
s = a;
p = a;
m = real(1.0);
do {
p *= x;
m += real(2.0);
p /= (m*(m-1));
s += p;
} while (fabsl((real) p) > thresh);
sin_a = s;
cos_a = sqrt(real(1.0) - sqr(s));
}
qd_real sin(const qd_real &a) {
/* Strategy. To compute sin(x), we choose integers a, b so that
x = s + a * (pi/2) + b * (pi/1024)
and |s| <= pi/2048. Using a precomputed table of
sin(k pi / 1024) and cos(k pi / 1024), we can compute
sin(x) from sin(s) and cos(s). This greatly increases the
convergence of the sine Taylor series. */
if (a.is_zero()) {
return real(0.0);
}
/* First reduce modulo 2*pi so that |r| <= pi. */
qd_real r = drem(a, qd_real::_2pi);
/* Now reduce by modulo pi/2 and then by pi/1024 so that
we obtain numbers a, b, and t. */
qd_real t;
qd_real sin_t, cos_t;
qd_real s, c;
int j = (int) divrem(r, qd_real::_pi2, t);
int abs_j = abs(j);
int k = (int) divrem(t, qd_real::_pi1024, t);
int abs_k = abs(k);
if (abs_j > 2) {
//cerr << "ERROR (qd_real::sin): Cannot reduce modulo pi/2." << endl;
//qd_real::abort();
return qd_real::_nan;
}
if (abs_k > 256) {
//cerr << "ERROR (qd_real::sin): Cannot reduce modulo pi/1024." << endl;
//qd_real::abort();
return qd_real::_nan;
}
sincos_taylor(t, sin_t, cos_t);
if (abs_k == 0) {
s = sin_t;
c = cos_t;
} else {
qd_real u = qd_real::cos_table[abs_k-1];
qd_real v = qd_real::sin_table[abs_k-1];
if (k > 0) {
s = u * sin_t + v * cos_t;
c = u * cos_t - v * sin_t;
} else {
s = u * sin_t - v * cos_t;
c = u * cos_t + v * sin_t;
}
}
if (abs_j == 0) {
r = s;
} else if (j == 1) {
r = c;
} else if (j == -1) {
r = -c;
} else {
r = -s;
}
return r;
}
qd_real cos(const qd_real &a) {
if (a.is_zero()) {
return real(1.0);
}
/* First reduce modulo 2*pi so that |r| <= pi. */
qd_real r = drem(a, qd_real::_2pi);
/* Now reduce by modulo pi/2 and then by pi/1024 so that
we obtain numbers a, b, and t. */
qd_real t;
qd_real sin_t, cos_t;
qd_real s, c;
int j = (int) divrem(r, qd_real::_pi2, t);
int abs_j = abs(j);
int k = (int) divrem(t, qd_real::_pi1024, t);
int abs_k = abs(k);
if (abs_j > 2) {
//cerr << "ERROR (qd_real::cos): Cannot reduce modulo pi/2." << endl;
//qd_real::abort();
return qd_real::_nan;
}
if (abs_k > 256) {
//cerr << "ERROR (qd_real::cos): Cannot reduce modulo pi/1024." << endl;
//qd_real::abort();
return qd_real::_nan;
}
sincos_taylor(t, sin_t, cos_t);
if (abs_k == 0) {
s = sin_t;
c = cos_t;
} else {
qd_real u = qd_real::cos_table[abs_k-1];
qd_real v = qd_real::sin_table[abs_k-1];
if (k > 0) {
s = u * sin_t + v * cos_t;
c = u * cos_t - v * sin_t;
} else {
s = u * sin_t - v * cos_t;
c = u * cos_t + v * sin_t;
}
}
if (abs_j == 0) {
r = c;
} else if (j == 1) {
r = -s;
} else if (j == -1) {
r = s;
} else {
r = -c;
}
return r;
}
void sincos(const qd_real &a, qd_real &sin_a, qd_real &cos_a) {
if (a.is_zero()) {
sin_a = real(0.0);
cos_a = real(1.0);
return;
}
/* First reduce modulo 2*pi so that |r| <= pi. */
qd_real r = drem(a, qd_real::_2pi);
/* Now reduce by modulo pi/2 and then by pi/1024 so that
we obtain numbers a, b, and t. */
qd_real t;
qd_real sin_t, cos_t;
qd_real s, c;
int j = (int) divrem(r, qd_real::_pi2, t);
int abs_j = abs(j);
int k = (int) divrem(t, qd_real::_pi1024, t);
int abs_k = abs(k);
if (abs_j > 2) {
//cerr << "ERROR (qd_real::sincos): Cannot reduce modulo pi/2." << endl;
//qd_real::abort();
return;
}
if (abs_k > 256) {
//cerr << "ERROR (qd_real::sincos): Cannot reduce modulo pi/1024." << endl;
//qd_real::abort();
return;
}
sincos_taylor(t, sin_t, cos_t);
if (abs_k == 0) {
s = sin_t;
c = cos_t;
} else {
qd_real u = qd_real::cos_table[abs_k-1];
qd_real v = qd_real::sin_table[abs_k-1];
if (k > 0) {
s = u * sin_t + v * cos_t;
c = u * cos_t - v * sin_t;
} else {
s = u * sin_t - v * cos_t;
c = u * cos_t + v * sin_t;
}
}
if (abs_j == 0) {
sin_a = s;
cos_a = c;
} else if (j == 1) {
sin_a = c;
cos_a = -s;
} else if (j == -1) {
sin_a = -c;
cos_a = s;
} else {
sin_a = -s;
cos_a = -c;
}
}
qd_real atan(const qd_real &a) {
return atan2(a, qd_real(1.0));
}
qd_real atan2(const qd_real &y, const qd_real &x) {
/* Strategy: Instead of using Taylor series to compute
arctan, we instead use Newton's iteration to solve
the equation
sin(z) = y/r or cos(z) = x/r
where r = sqrt(x^2 + y^2).
The iteration is given by
z' = z + (y - sin(z)) / cos(z) (for equation 1)
z' = z - (x - cos(z)) / sin(z) (for equation 2)
Here, x and y are normalized so that x^2 + y^2 = 1.
If |x| > |y|, then first iteration is used since the
denominator is larger. Otherwise, the second is used.
*/
if (x.is_zero()) {
if (y.is_zero()) {
/* Both x and y is zero. */
//cerr << "ERROR (qd_real::atan2): Both arguments zero." << endl;
//qd_real::abort();
return qd_real::_nan;
}
return (y.is_positive()) ? qd_real::_pi2 : -qd_real::_pi2;
} else if (y.is_zero()) {
return (x.is_positive()) ? qd_real(0.0) : qd_real::_pi;
}
if (x == y) {
return (y.is_positive()) ? qd_real::_pi4 : -qd_real::_3pi4;
}
if (x == -y) {
return (y.is_positive()) ? qd_real::_3pi4 : -qd_real::_pi4;
}
qd_real r = sqrt(sqr(x) + sqr(y));
qd_real xx = x / r;
qd_real yy = y / r;
/* Compute real precision approximation to atan. */
qd_real z = atan2((real) y, (real) x);
qd_real sin_z, cos_z;
if (xx > yy) {
/* Use Newton iteration 1. z' = z + (y - sin(z)) / cos(z) */
sincos(z, sin_z, cos_z);
z += (yy - sin_z) / cos_z;
sincos(z, sin_z, cos_z);
z += (yy - sin_z) / cos_z;
sincos(z, sin_z, cos_z);
z += (yy - sin_z) / cos_z;
} else {
/* Use Newton iteration 2. z' = z - (x - cos(z)) / sin(z) */
sincos(z, sin_z, cos_z);
z -= (xx - cos_z) / sin_z;
sincos(z, sin_z, cos_z);
z -= (xx - cos_z) / sin_z;
sincos(z, sin_z, cos_z);
z -= (xx - cos_z) / sin_z;
}
return z;
}
qd_real drem(const qd_real &a, const qd_real &b) {
qd_real n = nint(a/b);
return (a - n * b);
}
qd_real divrem(const qd_real &a, const qd_real &b, qd_real &r) {
qd_real n = nint(a/b);
r = a - n * b;
return n;
}
qd_real tan(const qd_real &a) {
qd_real s, c;
sincos(a, s, c);
return s/c;
}
qd_real asin(const qd_real &a) {
qd_real abs_a = fabs(a);
if (abs_a > real(1.0)) {
//cerr << "ERROR (qd_real::asin): Argument out of domain." << endl;
//qd_real::abort();
return qd_real::_nan;
}
if (abs_a.is_one()) {
return (a.is_positive()) ? qd_real::_pi2 : -qd_real::_pi2;
}
return atan2(a, sqrt(real(1.0) - sqr(a)));
}
qd_real acos(const qd_real &a) {
qd_real abs_a = fabs(a);
if (abs_a > real(1.0)) {
//cerr << "ERROR (qd_real::acos): Argument out of domain." << endl;
//qd_real::abort();
return qd_real::_nan;
}
if (abs_a.is_one()) {
return (a.is_positive()) ? qd_real(0.0) : qd_real::_pi;
}
return atan2(sqrt(real(1.0) - sqr(a)), a);
}
qd_real sinh(const qd_real &a) {
if (a.is_zero()) {
return real(0.0);
}
if (fabs(a) > real(0.05)) {
qd_real ea = exp(a);
return mul_pwr2(ea - inv(ea), real(0.5));
}
/* Since a is small, using the above formula gives
a lot of cancellation. So use Taylor series. */
qd_real s = a;
qd_real t = a;
qd_real r = sqr(t);
real m = real(1.0);
real thresh = fabsl(((real) a) * qd_real::_eps);
do {
m += real(2.0);
t *= r;
t /= (m-1) * m;
s += t;
} while (fabs(t) > thresh);
return s;
}
qd_real cosh(const qd_real &a) {
if (a.is_zero()) {
return real(1.0);
}
qd_real ea = exp(a);
return mul_pwr2(ea + inv(ea), real(0.5));
}
qd_real tanh(const qd_real &a) {
if (a.is_zero()) {
return real(0.0);
}
if (fabsl((real) a) > real(0.05)) {
qd_real ea = exp(a);
qd_real inv_ea = inv(ea);
return (ea - inv_ea) / (ea + inv_ea);
} else {
qd_real s, c;
s = sinh(a);
c = sqrt(real(1.0) + sqr(s));
return s / c;
}
}
void sincosh(const qd_real &a, qd_real &s, qd_real &c) {
if (fabs((real) a) <= real(0.05)) {
s = sinh(a);
c = sqrt(real(1.0) + sqr(s));
} else {
qd_real ea = exp(a);
qd_real inv_ea = inv(ea);
s = mul_pwr2(ea - inv_ea, real(0.5));
c = mul_pwr2(ea + inv_ea, real(0.5));
}
}
qd_real asinh(const qd_real &a) {
return log(a + sqrt(sqr(a) + real(1.0)));
}
qd_real acosh(const qd_real &a) {
if (a < real(1.0)) {
//cerr << "ERROR (qd_real::acosh): Argument out of domain." << endl;
//qd_real::abort();
return qd_real::_nan;
}
return log(a + sqrt(sqr(a) - real(1.0)));
}
qd_real atanh(const qd_real &a) {
if (fabs(a) >= real(1.0)) {
//cerr << "ERROR (qd_real::atanh): Argument out of domain." << endl;
//qd_real::abort();
return qd_real::_nan;
}
return mul_pwr2(log((real(1.0) + a) / (real(1.0) - a)), real(0.5));
}
qd_real qdrand() {
static const real m_const = 4.6566128730773926e-10; /* = 2^{-31} */
real m = m_const;
qd_real r = real(0.0);
real d;
/* Strategy: Generate 31 bits at a time, using lrand48
random number generator. Shift the bits, and repeat
7 times. */
for (int i = 0; i < 7; i++, m *= m_const) {
d = STD_RAND() * m;
r += d;
}
return r;
}
/* polyeval(c, n, x)
Evaluates the given n-th degree polynomial at x.
The polynomial is given by the array of (n+1) coefficients. */
qd_real polyeval(const qd_real *c, int n, const qd_real &x) {
/* Just use Horner's method of polynomial evaluation. */
qd_real r = c[n];
for (int i = n-1; i >= 0; i--) {
r *= x;
r += c[i];
}
return r;
}
/* polyroot(c, n, x0)
Given an n-th degree polynomial, finds a root close to
the given guess x0. Note that this uses simple Newton
iteration scheme, and does not work for multiple roots. */
qd_real polyroot(const qd_real *c, int n, const qd_real &x0,
real thresh) {
qd_real x = x0;
qd_real f;
qd_real *d = new qd_real[n];
bool conv = false;
int i;
/* Compute the coefficients of the derivatives. */
for (i = 0; i < n; i++) {
d[i] = c[i+1] * (real) (i+1);
}
/* Newton iteration. */
for (i = 0; i < 20; i++) {
f = polyeval(c, n, x);
if (abs(f) < thresh) {
conv = true;
break;
}
x -= (f / polyeval(d, n-1, x));
}
delete [] d;
if (!conv) {
//cerr << "ERROR (qd_real::polyroot): Failed to converge." << endl;
//qd_real::abort();
return qd_real::_nan;
}
return x;
}
#ifdef QD_DEBUG
qd_real qd_real::debug_rand() {
if (STD_RAND() % 2 == 0)
return qdrand();
int expn = 0;
qd_real a = real(0.0);
real d;
for (int i = 0; i < 4; i++) {
d = ldexpl(STD_RAND() / (real) RAND_MAX, -expn);
a += d;
expn = expn + 54 + STD_RAND() % 200;
}
return a;
}
#endif
void qd_real::renorm() {
::renorm(x[0], x[1], x[2], x[3]);
}
void qd_real::renorm(real &e) {
::renorm(x[0], x[1], x[2], x[3], e);
}
| 20.380395 | 112 | 0.5 |
philippeb8
|
e91ad983f822d9ff5302359d933c695141d3b9fc
| 40,106 |
cc
|
C++
|
third_party/blink/renderer/core/editing/layout_selection.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 |
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
third_party/blink/renderer/core/editing/layout_selection.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 |
2015-10-21T13:02:42.000Z
|
2022-03-14T07:50:50.000Z
|
third_party/blink/renderer/core/editing/layout_selection.cc
|
chromium/chromium
|
df46e572c3449a4b108d6e02fbe4f6d24cf98381
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 |
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights
* reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "third_party/blink/renderer/core/editing/layout_selection.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/visible_position.h"
#include "third_party/blink/renderer/core/editing/visible_units.h"
#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
namespace {
// TODO(yoichio): Share condition between NGOffsetMapping::AcceptsPosition.
bool ShouldUseLayoutNGTextContent(const Node& node) {
LayoutObject* layout_object = node.GetLayoutObject();
DCHECK(layout_object);
if (layout_object->IsInline())
return layout_object->ContainingNGBlockFlow();
if (auto* block_flow = DynamicTo<LayoutBlockFlow>(layout_object))
return NGBlockNode::CanUseNewLayout(*block_flow);
return false;
}
} // namespace
// The current selection to be painted is represented as 2 pairs of
// (Node, offset).
// Each offset represents text offsets on selection edge if it is text.
// For example, suppose we select "f^oo<br><img>|",
// |start_offset_| is 1 and |end_offset_| is nullopt.
// If on NG, offset is on text content offset rather than each text node.
class SelectionPaintRange : public GarbageCollected<SelectionPaintRange> {
public:
SelectionPaintRange() = default;
SelectionPaintRange(const Node& passed_start_node,
absl::optional<unsigned> passed_start_offset,
const Node& passed_end_node,
absl::optional<unsigned> passed_end_offset)
: start_node(passed_start_node),
start_offset(passed_start_offset),
end_node(passed_end_node),
end_offset(passed_end_offset) {}
void Trace(Visitor* visitor) const {
visitor->Trace(start_node);
visitor->Trace(end_node);
}
bool IsNull() const { return !start_node; }
void AssertSanity() const {
#if DCHECK_IS_ON()
if (start_node) {
DCHECK(end_node);
DCHECK(start_node->GetLayoutObject()->GetSelectionState() ==
SelectionState::kStart ||
start_node->GetLayoutObject()->GetSelectionState() ==
SelectionState::kStartAndEnd);
DCHECK(end_node->GetLayoutObject()->GetSelectionState() ==
SelectionState::kEnd ||
end_node->GetLayoutObject()->GetSelectionState() ==
SelectionState::kStartAndEnd);
return;
}
DCHECK(!end_node);
DCHECK(!start_offset.has_value());
DCHECK(!end_offset.has_value());
#endif
}
Member<const Node> start_node;
absl::optional<unsigned> start_offset;
Member<const Node> end_node;
absl::optional<unsigned> end_offset;
};
LayoutSelection::LayoutSelection(FrameSelection& frame_selection)
: frame_selection_(&frame_selection),
has_pending_selection_(false),
paint_range_(MakeGarbageCollected<SelectionPaintRange>()) {}
enum class SelectionMode {
kNone,
kRange,
};
void LayoutSelection::AssertIsValid() const {
const Document& document = frame_selection_->GetDocument();
DCHECK_GE(document.Lifecycle().GetState(), DocumentLifecycle::kLayoutClean);
DCHECK(!document.IsSlotAssignmentOrLegacyDistributionDirty());
DCHECK(!has_pending_selection_);
}
static SelectionMode ComputeSelectionMode(
const FrameSelection& frame_selection) {
const SelectionInDOMTree& selection_in_dom =
frame_selection.GetSelectionInDOMTree();
if (selection_in_dom.IsRange())
return SelectionMode::kRange;
DCHECK(selection_in_dom.IsCaret());
return SelectionMode::kNone;
}
static EphemeralRangeInFlatTree CalcSelectionInFlatTree(
const FrameSelection& frame_selection) {
const SelectionInDOMTree& selection_in_dom =
frame_selection.GetSelectionInDOMTree();
switch (ComputeSelectionMode(frame_selection)) {
case SelectionMode::kNone:
return {};
case SelectionMode::kRange: {
const PositionInFlatTree& base =
ToPositionInFlatTree(selection_in_dom.Base());
const PositionInFlatTree& extent =
ToPositionInFlatTree(selection_in_dom.Extent());
if (base.IsNull() || extent.IsNull() || base == extent ||
!base.IsValidFor(frame_selection.GetDocument()) ||
!extent.IsValidFor(frame_selection.GetDocument()))
return {};
return base <= extent ? EphemeralRangeInFlatTree(base, extent)
: EphemeralRangeInFlatTree(extent, base);
}
}
NOTREACHED();
return {};
}
// OldSelectedNodes is current selected Nodes with
// current SelectionState which is kStart, kEnd, kStartAndEnd or kInside.
struct OldSelectedNodes {
STACK_ALLOCATED();
public:
OldSelectedNodes()
: paint_range(MakeGarbageCollected<SelectionPaintRange>()) {}
OldSelectedNodes(OldSelectedNodes&& other) {
paint_range = other.paint_range;
selected_map = std::move(other.selected_map);
}
OldSelectedNodes(const OldSelectedNodes&) = delete;
OldSelectedNodes& operator=(const OldSelectedNodes&) = delete;
SelectionPaintRange* paint_range;
HeapHashMap<Member<const Node>, SelectionState> selected_map;
};
std::ostream& operator<<(std::ostream&, const OldSelectedNodes&);
// This struct represents a selection range in layout tree and each
// Node is SelectionState-marked.
struct NewPaintRangeAndSelectedNodes {
STACK_ALLOCATED();
public:
NewPaintRangeAndSelectedNodes()
: paint_range(MakeGarbageCollected<SelectionPaintRange>()) {}
NewPaintRangeAndSelectedNodes(
SelectionPaintRange* passed_paint_range,
HeapHashSet<Member<const Node>>&& passed_selected_objects)
: paint_range(passed_paint_range),
selected_objects(std::move(passed_selected_objects)) {}
NewPaintRangeAndSelectedNodes(NewPaintRangeAndSelectedNodes&& other) {
paint_range = other.paint_range;
selected_objects = std::move(other.selected_objects);
}
NewPaintRangeAndSelectedNodes(const NewPaintRangeAndSelectedNodes&) = delete;
NewPaintRangeAndSelectedNodes& operator=(
const NewPaintRangeAndSelectedNodes&) = delete;
void AssertSanity() const {
#if DCHECK_IS_ON()
paint_range->AssertSanity();
if (paint_range->start_node) {
DCHECK(selected_objects.Contains(paint_range->start_node)) << this;
DCHECK(selected_objects.Contains(paint_range->end_node)) << this;
return;
}
DCHECK(selected_objects.IsEmpty()) << this;
#endif
}
SelectionPaintRange* paint_range;
HeapHashSet<Member<const Node>> selected_objects;
};
std::ostream& operator<<(std::ostream&, const NewPaintRangeAndSelectedNodes&);
static void SetShouldInvalidateIfNeeded(LayoutObject* layout_object) {
if (layout_object->ShouldInvalidateSelection())
return;
layout_object->SetShouldInvalidateSelection();
// We should invalidate if ancestor of |layout_object| is LayoutSVGText
// because SVGRootInlineBoxPainter::Paint() paints selection for
// |layout_object| in/ LayoutSVGText and it is invoked when parent
// LayoutSVGText is invalidated.
// That is different from InlineTextBoxPainter::Paint() which paints
// LayoutText selection when LayoutText is invalidated.
if (!layout_object->IsSVG())
return;
for (LayoutObject* parent = layout_object->Parent(); parent;
parent = parent->Parent()) {
if (parent->IsSVGRoot())
return;
if (parent->IsSVGText() || parent->IsNGSVGText()) {
if (!parent->ShouldInvalidateSelection())
parent->SetShouldInvalidateSelection();
return;
}
}
}
static LayoutTextFragment* FirstLetterPartFor(
const LayoutObject* layout_object) {
// TODO(yoichio): LayoutText::GetFirstLetterPart() should be typed
// LayoutTextFragment.
if (const auto* layout_text = DynamicTo<LayoutText>(layout_object))
return To<LayoutTextFragment>(layout_text->GetFirstLetterPart());
return nullptr;
}
static void SetShouldInvalidateIfNeeded(const Node& node) {
LayoutObject* layout_object = node.GetLayoutObject();
if (!layout_object)
return;
if (LayoutTextFragment* first_letter = FirstLetterPartFor(layout_object))
SetShouldInvalidateIfNeeded(first_letter);
SetShouldInvalidateIfNeeded(layout_object);
}
static void SetSelectionStateIfNeeded(const Node& node, SelectionState state) {
DCHECK_NE(state, SelectionState::kContain) << node;
DCHECK_NE(state, SelectionState::kNone) << node;
LayoutObject* layout_object = node.GetLayoutObject();
if (layout_object->GetSelectionState() == state)
return;
layout_object->SetSelectionState(state);
// Set ancestors SelectionState kContain for CSS ::selection style.
// See LayoutObject::InvalidateSelectedChildrenOnStyleChange().
for (Node& ancestor : FlatTreeTraversal::AncestorsOf(node)) {
LayoutObject* ancestor_layout = ancestor.GetLayoutObject();
if (!ancestor_layout)
continue;
if (ancestor_layout->GetSelectionState() == SelectionState::kContain)
return;
ancestor_layout->LayoutObject::SetSelectionState(SelectionState::kContain);
}
}
// Set ShouldInvalidateSelection flag of LayoutObjects
// comparing them in |new_range| and |old_range|.
static void SetShouldInvalidateSelection(
const NewPaintRangeAndSelectedNodes& new_range,
const OldSelectedNodes& old_selected_objects) {
// We invalidate each LayoutObject in
// MakeGarbageCollected<SelectionPaintRange> which has SelectionState of
// kStart, kEnd, kStartAndEnd, or kInside and is not in old
// SelectionPaintRange.
for (const Node* node : new_range.selected_objects) {
if (old_selected_objects.selected_map.Contains(node))
continue;
const SelectionState new_state =
node->GetLayoutObject()->GetSelectionState();
DCHECK_NE(new_state, SelectionState::kContain) << node;
DCHECK_NE(new_state, SelectionState::kNone) << node;
SetShouldInvalidateIfNeeded(*node);
}
// For LayoutObject in old SelectionPaintRange, we invalidate LayoutObjects
// each of:
// 1. LayoutObject was painted and would not be painted.
// 2. LayoutObject was not painted and would be painted.
for (const auto& key_value : old_selected_objects.selected_map) {
const Node* const node = key_value.key;
const SelectionState old_state = key_value.value;
const SelectionState new_state =
node->GetLayoutObject()->GetSelectionState();
if (new_state == old_state)
continue;
DCHECK(new_state != SelectionState::kNone ||
old_state != SelectionState::kNone)
<< node;
DCHECK_NE(new_state, SelectionState::kContain) << node;
DCHECK_NE(old_state, SelectionState::kContain) << node;
SetShouldInvalidateIfNeeded(*node);
}
// Invalidate Selection start/end is moving on a same node.
const SelectionPaintRange& new_paint_range = *new_range.paint_range;
const SelectionPaintRange& old_paint_range =
*old_selected_objects.paint_range;
if (new_paint_range.IsNull())
return;
if (new_paint_range.start_node->IsTextNode() &&
new_paint_range.start_node == old_paint_range.start_node &&
new_paint_range.start_offset != old_paint_range.start_offset)
SetShouldInvalidateIfNeeded(*new_paint_range.start_node);
if (new_paint_range.end_node->IsTextNode() &&
new_paint_range.end_node == old_paint_range.end_node &&
new_paint_range.end_offset != old_paint_range.end_offset)
SetShouldInvalidateIfNeeded(*new_paint_range.end_node);
}
static bool IsDisplayContentElement(const Node& node) {
if (!node.IsElementNode())
return false;
const ComputedStyle* const style = node.GetComputedStyle();
return style && style->Display() == EDisplay::kContents;
}
template <typename Visitor>
static void VisitSelectedInclusiveDescendantsOfInternal(const Node& node,
Visitor* visitor) {
// Display:content element appears in a flat tree even it doesn't have
// a LayoutObject but we need to visit its children.
if (!IsDisplayContentElement(node)) {
LayoutObject* layout_object = node.GetLayoutObject();
if (!layout_object)
return;
if (layout_object->GetSelectionState() == SelectionState::kNone)
return;
visitor->Visit(node);
}
for (Node& child : FlatTreeTraversal::ChildrenOf(node))
VisitSelectedInclusiveDescendantsOfInternal(child, visitor);
}
static inline bool IsFlatTreeClean(const Node& node) {
return !node.GetDocument().IsSlotAssignmentOrLegacyDistributionDirty();
}
template <typename Visitor>
static void VisitSelectedInclusiveDescendantsOf(const Node& node,
Visitor* visitor) {
DCHECK(IsFlatTreeClean(node));
return VisitSelectedInclusiveDescendantsOfInternal(node, visitor);
}
static OldSelectedNodes ResetOldSelectedNodes(
const Node& root,
absl::optional<unsigned> old_start_offset,
absl::optional<unsigned> old_end_offset) {
class OldSelectedVisitor {
STACK_ALLOCATED();
public:
OldSelectedVisitor(absl::optional<unsigned> passed_old_start_offset,
absl::optional<unsigned> passed_old_end_offset)
: old_start_offset(passed_old_start_offset),
old_end_offset(passed_old_end_offset) {}
void Visit(const Node& node) {
LayoutObject* layout_object = node.GetLayoutObject();
const SelectionState old_state = layout_object->GetSelectionState();
DCHECK_NE(old_state, SelectionState::kNone) << node;
layout_object->SetSelectionState(SelectionState::kNone);
if (old_state == SelectionState::kContain)
return;
old_selected_objects.selected_map.insert(&node, old_state);
if (old_state == SelectionState::kInside)
return;
switch (old_state) {
case SelectionState::kStart: {
DCHECK(!old_selected_objects.paint_range->start_node);
old_selected_objects.paint_range->start_node = node;
old_selected_objects.paint_range->start_offset = old_start_offset;
break;
}
case SelectionState::kEnd: {
DCHECK(!old_selected_objects.paint_range->end_node);
old_selected_objects.paint_range->end_node = node;
old_selected_objects.paint_range->end_offset = old_end_offset;
break;
}
case SelectionState::kStartAndEnd: {
DCHECK(!old_selected_objects.paint_range->start_node);
DCHECK(!old_selected_objects.paint_range->end_node);
old_selected_objects.paint_range->start_node = node;
old_selected_objects.paint_range->start_offset = old_start_offset;
old_selected_objects.paint_range->end_node = node;
old_selected_objects.paint_range->end_offset = old_end_offset;
break;
}
default: {
NOTREACHED();
break;
}
}
}
OldSelectedNodes old_selected_objects;
const absl::optional<unsigned> old_start_offset;
const absl::optional<unsigned> old_end_offset;
} visitor(old_start_offset, old_end_offset);
VisitSelectedInclusiveDescendantsOf(root, &visitor);
return std::move(visitor.old_selected_objects);
}
static absl::optional<unsigned> ComputeStartOffset(
const Node& node,
const PositionInFlatTree& selection_start) {
if (!node.IsTextNode())
return absl::nullopt;
if (&node == selection_start.AnchorNode())
return selection_start.OffsetInContainerNode();
return 0;
}
static absl::optional<unsigned> ComputeEndOffset(
const Node& node,
const PositionInFlatTree& selection_end) {
auto* text_node = DynamicTo<Text>(node);
if (!text_node)
return absl::nullopt;
if (&node == selection_end.AnchorNode())
return selection_end.OffsetInContainerNode();
return text_node->length();
}
#if DCHECK_IS_ON()
// Position should be offset on text or before/after a break element.
static bool IsPositionValidText(const Position& position) {
if (position.AnchorNode()->IsTextNode() && position.IsOffsetInAnchor())
return true;
if ((IsA<HTMLBRElement>(position.AnchorNode()) ||
IsA<HTMLWBRElement>(position.AnchorNode())) &&
(position.IsBeforeAnchor() || position.IsAfterAnchor()))
return true;
return false;
}
#endif
static absl::optional<unsigned> GetTextContentOffset(const Position& position) {
if (position.IsNull())
return absl::nullopt;
#if DCHECK_IS_ON()
DCHECK(IsPositionValidText(position));
#endif
DCHECK(ShouldUseLayoutNGTextContent(*position.AnchorNode()));
const NGOffsetMapping* const offset_mapping =
NGOffsetMapping::GetFor(position);
DCHECK(offset_mapping);
const absl::optional<unsigned>& ng_offset =
offset_mapping->GetTextContentOffset(position);
return ng_offset;
}
// Computes text content offset of selection start if |layout_object| is
// LayoutText.
static absl::optional<unsigned> GetTextContentOffsetStart(
const Node& node,
absl::optional<unsigned> node_offset) {
if (!node.GetLayoutObject()->IsText())
return absl::nullopt;
if (node.IsTextNode()) {
DCHECK(node_offset.has_value()) << node;
return GetTextContentOffset(Position(node, node_offset.value()));
}
DCHECK(IsA<HTMLWBRElement>(node) || IsA<HTMLBRElement>(node)) << node;
DCHECK(!node_offset.has_value()) << node;
return GetTextContentOffset(Position::BeforeNode(node));
}
// Computes text content offset of selection end if |layout_object| is
// LayoutText.
static absl::optional<unsigned> GetTextContentOffsetEnd(
const Node& node,
absl::optional<unsigned> node_offset) {
if (!node.GetLayoutObject()->IsText())
return {};
if (node.IsTextNode()) {
DCHECK(node_offset.has_value()) << node;
return GetTextContentOffset(Position(node, node_offset.value()));
}
DCHECK(IsA<HTMLWBRElement>(node) || IsA<HTMLBRElement>(node)) << node;
DCHECK(!node_offset.has_value()) << node;
return GetTextContentOffset(Position::AfterNode(node));
}
static SelectionPaintRange* ComputeNewPaintRange(
const SelectionPaintRange& paint_range) {
DCHECK(!paint_range.IsNull());
const Node& start_node = *paint_range.start_node;
// If LayoutObject is not in NG, use legacy offset.
const absl::optional<unsigned> start_offset =
ShouldUseLayoutNGTextContent(start_node)
? GetTextContentOffsetStart(start_node, paint_range.start_offset)
: paint_range.start_offset;
const Node& end_node = *paint_range.end_node;
const absl::optional<unsigned> end_offset =
ShouldUseLayoutNGTextContent(end_node)
? GetTextContentOffsetEnd(end_node, paint_range.end_offset)
: paint_range.end_offset;
return MakeGarbageCollected<SelectionPaintRange>(
*paint_range.start_node, start_offset, *paint_range.end_node, end_offset);
}
static unsigned ClampOffset(unsigned offset,
unsigned start_offset,
unsigned end_offset) {
DCHECK_LE(start_offset, end_offset);
return std::min(std::max(offset, start_offset), end_offset);
}
static Text* AssociatedTextNode(const LayoutText& text) {
if (const auto* fragment = DynamicTo<LayoutTextFragment>(text))
return fragment->AssociatedTextNode();
if (Node* node = text.GetNode())
return DynamicTo<Text>(node);
return nullptr;
}
static SelectionState GetSelectionStateFor(const LayoutText& layout_text) {
if (const auto* text_fragment = DynamicTo<LayoutTextFragment>(layout_text)) {
Node* node = text_fragment->AssociatedTextNode();
if (!node)
return SelectionState::kNone;
return node->GetLayoutObject()->GetSelectionState();
}
return layout_text.GetSelectionState();
}
static SelectionState GetSelectionStateFor(
const NGInlineCursorPosition& position) {
DCHECK(position.GetLayoutObject());
return GetSelectionStateFor(To<LayoutText>(*position.GetLayoutObject()));
}
bool LayoutSelection::IsSelected(const LayoutObject& layout_object) {
if (const auto* layout_text = DynamicTo<LayoutText>(layout_object))
return GetSelectionStateFor(*layout_text) != SelectionState::kNone;
return layout_object.GetSelectionState() != SelectionState::kNone;
}
static inline unsigned ClampOffset(unsigned node_offset,
const LayoutTextFragment& fragment) {
if (fragment.Start() > node_offset)
return 0;
return std::min(node_offset - fragment.Start(), fragment.FragmentLength());
}
static LayoutTextSelectionStatus ComputeSelectionStatusForNode(
const Text& text,
SelectionState selection_state,
absl::optional<unsigned> start_offset,
absl::optional<unsigned> end_offset) {
switch (selection_state) {
case SelectionState::kInside:
return {0, text.length(), SelectionIncludeEnd::kInclude};
case SelectionState::kStart:
return {start_offset.value(), text.length(),
SelectionIncludeEnd::kInclude};
case SelectionState::kEnd:
return {0, end_offset.value(), SelectionIncludeEnd::kNotInclude};
case SelectionState::kStartAndEnd:
return {start_offset.value(), end_offset.value(),
SelectionIncludeEnd::kNotInclude};
default:
NOTREACHED();
return {0, 0, SelectionIncludeEnd::kNotInclude};
}
}
LayoutTextSelectionStatus LayoutSelection::ComputeSelectionStatus(
const LayoutText& layout_text) const {
AssertIsValid();
const SelectionState selection_state = GetSelectionStateFor(layout_text);
if (selection_state == SelectionState::kNone)
return {0, 0, SelectionIncludeEnd::kNotInclude};
if (Text* text = AssociatedTextNode(layout_text)) {
const LayoutTextSelectionStatus text_status = ComputeSelectionStatusForNode(
*text, selection_state, paint_range_->start_offset,
paint_range_->end_offset);
if (const auto* text_fragment =
DynamicTo<LayoutTextFragment>(layout_text)) {
return {ClampOffset(text_status.start, *text_fragment),
ClampOffset(text_status.end, *text_fragment),
text_status.include_end};
}
return text_status;
}
// TODO(yoichio): This is really weird legacy behavior. Remove this.
if (layout_text.IsBR() && selection_state == SelectionState::kEnd)
return {0, 0, SelectionIncludeEnd::kNotInclude};
return {0, layout_text.TextLength(), SelectionIncludeEnd::kInclude};
}
LayoutTextSelectionStatus FrameSelection::ComputeLayoutSelectionStatus(
const LayoutText& text) const {
return layout_selection_->ComputeSelectionStatus(text);
}
// FrameSelection holds selection offsets in layout block flow at
// LayoutSelection::Commit() if selection starts/ends within Text that
// each LayoutObject::SelectionState indicates.
// These offset can be out of fragment because SelectionState is of each
// LayoutText and not of each fragment for it.
LayoutSelectionStatus LayoutSelection::ComputeSelectionStatus(
const NGInlineCursor& cursor) const {
const NGInlineCursorPosition& current = cursor.Current();
if (!current.IsLayoutGeneratedText())
return ComputeSelectionStatus(cursor, current.TextOffset());
// We don't paint selection on ellipsis.
if (current.IsEllipsis())
return {0, 0, SelectSoftLineBreak::kNotSelected};
// Layout-generated text does not have corresponding text in the DOM. Find if
// the previous character is selected. This is a soft-hyphen character if the
// hyphen is generated from it, or the character before the hyphen if
// automatic hyphenation.
const unsigned offset = current->StartOffsetInContainer(cursor);
DCHECK_GT(offset, 0u);
LayoutSelectionStatus status =
ComputeSelectionStatus(cursor, {offset - 1, offset});
if (!status.HasValidRange())
return status;
// Make |LayoutSelectionStatus| to select the whole text of the hyphen.
status.start = 0;
status.end = current->TextLength();
return status;
}
LayoutSelectionStatus LayoutSelection::ComputeSelectionStatus(
const NGInlineCursor& cursor,
const NGTextOffset& offset) const {
const unsigned start_offset = offset.start;
const unsigned end_offset = offset.end;
switch (GetSelectionStateFor(cursor.Current())) {
case SelectionState::kStart: {
const unsigned start_in_block = paint_range_->start_offset.value();
const bool is_continuous = start_in_block <= end_offset;
return {ClampOffset(start_in_block, start_offset, end_offset), end_offset,
(is_continuous && cursor.IsBeforeSoftLineBreak())
? SelectSoftLineBreak::kSelected
: SelectSoftLineBreak::kNotSelected};
}
case SelectionState::kEnd: {
const unsigned end_in_block = paint_range_->end_offset.value();
const unsigned end_in_fragment =
ClampOffset(end_in_block, start_offset, end_offset);
const bool is_continuous = end_offset < end_in_block;
return {start_offset, end_in_fragment,
(is_continuous && cursor.IsBeforeSoftLineBreak())
? SelectSoftLineBreak::kSelected
: SelectSoftLineBreak::kNotSelected};
}
case SelectionState::kStartAndEnd: {
const unsigned start_in_block = paint_range_->start_offset.value();
const unsigned end_in_block = paint_range_->end_offset.value();
const unsigned end_in_fragment =
ClampOffset(end_in_block, start_offset, end_offset);
const bool is_continuous =
start_in_block <= end_offset && end_offset < end_in_block;
return {ClampOffset(start_in_block, start_offset, end_offset),
end_in_fragment,
(is_continuous && cursor.IsBeforeSoftLineBreak())
? SelectSoftLineBreak::kSelected
: SelectSoftLineBreak::kNotSelected};
}
case SelectionState::kInside: {
return {start_offset, end_offset,
cursor.IsBeforeSoftLineBreak()
? SelectSoftLineBreak::kSelected
: SelectSoftLineBreak::kNotSelected};
}
default:
// This block is not included in selection.
return {0, 0, SelectSoftLineBreak::kNotSelected};
}
}
// Given |state| that describes the provided offsets relationship to the
// |paint_range_| (and thus which comparisons are valid), returns a
// SelectionState that reflects where the endpoints of the selection fall,
// relative to the range expressed by the offsets.
SelectionState LayoutSelection::ComputeSelectionStateFromOffsets(
SelectionState state,
unsigned start_offset,
unsigned end_offset) const {
switch (state) {
case SelectionState::kStart: {
const unsigned start_in_block =
paint_range_->start_offset.value_or(start_offset);
return start_offset <= start_in_block && start_in_block <= end_offset
? SelectionState::kStart
: SelectionState::kNone;
}
case SelectionState::kEnd: {
const unsigned end_in_block =
paint_range_->end_offset.value_or(end_offset);
return start_offset <= end_in_block && end_in_block <= end_offset
? SelectionState::kEnd
: SelectionState::kNone;
}
case SelectionState::kStartAndEnd: {
const unsigned start_in_block =
paint_range_->start_offset.value_or(start_offset);
const unsigned end_in_block =
paint_range_->end_offset.value_or(end_offset);
const bool is_start_in_current_cursor =
start_offset <= start_in_block && start_in_block <= end_offset;
const bool is_end_in_current_cursor =
start_offset <= end_in_block && end_in_block <= end_offset;
if (is_start_in_current_cursor && is_end_in_current_cursor)
return SelectionState::kStartAndEnd;
else if (is_start_in_current_cursor)
return SelectionState::kStart;
else if (is_end_in_current_cursor)
return SelectionState::kEnd;
else
return SelectionState::kInside;
}
case SelectionState::kInside: {
return SelectionState::kInside;
}
default:
return SelectionState::kNone;
}
}
SelectionState LayoutSelection::ComputeSelectionStateForCursor(
const NGInlineCursorPosition& position) const {
if (!position)
return SelectionState::kNone;
DCHECK(position.IsText());
// Selection on ellipsis is not supported.
if (position.IsEllipsis())
return SelectionState::kNone;
const NGTextOffset offset = position.TextOffset();
const unsigned start_offset = offset.start;
const unsigned end_offset = offset.end;
// Determine the state of the overall selection, relative to the LayoutObject
// associated with the current cursor position. This state will allow us know
// which offset comparisons are valid, and determine if the selection
// endpoints fall within the current cursor position.
SelectionState state = GetSelectionStateFor(position);
return ComputeSelectionStateFromOffsets(state, start_offset, end_offset);
}
SelectionState LayoutSelection::ComputeSelectionStateForInlineTextBox(
const InlineTextBox& text_box) const {
AssertIsValid();
unsigned start_offset = static_cast<unsigned>(text_box.CaretMinOffset());
unsigned end_offset = static_cast<unsigned>(text_box.CaretMaxOffset());
// Determine the state of the overall selection, relative to the
// InlineTextBox. This state will allow us know which offset comparisons are
// valid, and determine if the selection endpoints fall within InlineTextBox.
const LayoutText* text = To<LayoutText>(
LineLayoutAPIShim::ConstLayoutObjectFrom(text_box.GetLineLayoutItem()));
SelectionState state = GetSelectionStateFor(*text);
return ComputeSelectionStateFromOffsets(state, start_offset, end_offset);
}
static NewPaintRangeAndSelectedNodes CalcSelectionRangeAndSetSelectionState(
const FrameSelection& frame_selection) {
const SelectionInDOMTree& selection_in_dom =
frame_selection.GetSelectionInDOMTree();
if (selection_in_dom.IsNone())
return {};
const EphemeralRangeInFlatTree& selection =
CalcSelectionInFlatTree(frame_selection);
if (selection.IsCollapsed() || frame_selection.IsHidden())
return {};
// Find first/last Node which has a visible LayoutObject while
// marking SelectionState and collecting invalidation candidate LayoutObjects.
const Node* start_node = nullptr;
const Node* end_node = nullptr;
HeapHashSet<Member<const Node>> selected_objects;
for (Node& node : selection.Nodes()) {
LayoutObject* const layout_object = node.GetLayoutObject();
if (!layout_object || !layout_object->CanBeSelectionLeaf())
continue;
if (!start_node) {
DCHECK(!end_node);
start_node = end_node = &node;
continue;
}
// In this loop, |end_node| is pointing current last candidate
// LayoutObject and if it is not start and we find next, we mark the
// current one as kInside.
if (end_node != start_node) {
SetSelectionStateIfNeeded(*end_node, SelectionState::kInside);
selected_objects.insert(end_node);
}
end_node = &node;
}
// No valid LayOutObject found.
if (!start_node) {
DCHECK(!end_node);
return {};
}
// Compute offset. It has value iff start/end is text.
const absl::optional<unsigned> start_offset = ComputeStartOffset(
*start_node, selection.StartPosition().ToOffsetInAnchor());
const absl::optional<unsigned> end_offset =
ComputeEndOffset(*end_node, selection.EndPosition().ToOffsetInAnchor());
if (start_node == end_node) {
SetSelectionStateIfNeeded(*start_node, SelectionState::kStartAndEnd);
selected_objects.insert(start_node);
} else {
SetSelectionStateIfNeeded(*start_node, SelectionState::kStart);
selected_objects.insert(start_node);
SetSelectionStateIfNeeded(*end_node, SelectionState::kEnd);
selected_objects.insert(end_node);
}
SelectionPaintRange* new_range = MakeGarbageCollected<SelectionPaintRange>(
*start_node, start_offset, *end_node, end_offset);
if (!RuntimeEnabledFeatures::LayoutNGEnabled())
return {new_range, std::move(selected_objects)};
return {ComputeNewPaintRange(*new_range), std::move(selected_objects)};
}
void LayoutSelection::SetHasPendingSelection() {
has_pending_selection_ = true;
}
void LayoutSelection::Commit() {
if (!has_pending_selection_)
return;
has_pending_selection_ = false;
DCHECK(!frame_selection_->GetDocument().NeedsLayoutTreeUpdate());
DCHECK_GE(frame_selection_->GetDocument().Lifecycle().GetState(),
DocumentLifecycle::kLayoutClean);
DocumentLifecycle::DisallowTransitionScope disallow_transition(
frame_selection_->GetDocument().Lifecycle());
const OldSelectedNodes& old_selected_objects = ResetOldSelectedNodes(
frame_selection_->GetDocument(), paint_range_->start_offset,
paint_range_->end_offset);
const NewPaintRangeAndSelectedNodes& new_range =
CalcSelectionRangeAndSetSelectionState(*frame_selection_);
new_range.AssertSanity();
DCHECK(frame_selection_->GetDocument().GetLayoutView()->GetFrameView());
SetShouldInvalidateSelection(new_range, old_selected_objects);
paint_range_ = new_range.paint_range;
}
void LayoutSelection::ContextDestroyed() {
has_pending_selection_ = false;
paint_range_->start_node = nullptr;
paint_range_->start_offset = absl::nullopt;
paint_range_->end_node = nullptr;
paint_range_->end_offset = absl::nullopt;
}
static PhysicalRect SelectionRectForLayoutObject(const LayoutObject* object) {
if (!object->IsRooted())
return PhysicalRect();
if (!object->CanUpdateSelectionOnRootLineBoxes())
return PhysicalRect();
return object->AbsoluteSelectionRect();
}
template <typename Visitor>
static void VisitLayoutObjectsOf(const Node& node, Visitor* visitor) {
LayoutObject* layout_object = node.GetLayoutObject();
if (!layout_object)
return;
if (layout_object->GetSelectionState() == SelectionState::kContain)
return;
if (LayoutTextFragment* first_letter = FirstLetterPartFor(layout_object))
visitor->Visit(first_letter);
visitor->Visit(layout_object);
}
gfx::Rect LayoutSelection::AbsoluteSelectionBounds() {
Commit();
if (paint_range_->IsNull())
return gfx::Rect();
// Create a single bounding box rect that encloses the whole selection.
class SelectionBoundsVisitor {
STACK_ALLOCATED();
public:
void Visit(const Node& node) { VisitLayoutObjectsOf(node, this); }
void Visit(LayoutObject* layout_object) {
selected_rect.Unite(SelectionRectForLayoutObject(layout_object));
}
PhysicalRect selected_rect;
} visitor;
VisitSelectedInclusiveDescendantsOf(frame_selection_->GetDocument(),
&visitor);
return ToPixelSnappedRect(visitor.selected_rect);
}
void LayoutSelection::InvalidatePaintForSelection() {
if (paint_range_->IsNull())
return;
class InvalidatingVisitor {
STACK_ALLOCATED();
public:
void Visit(const Node& node) { VisitLayoutObjectsOf(node, this); }
void Visit(LayoutObject* layout_object) {
layout_object->SetShouldInvalidateSelection();
}
} visitor;
VisitSelectedInclusiveDescendantsOf(frame_selection_->GetDocument(),
&visitor);
}
void LayoutSelection::Trace(Visitor* visitor) const {
visitor->Trace(frame_selection_);
visitor->Trace(paint_range_);
}
void PrintSelectionStatus(std::ostream& ostream, const Node& node) {
ostream << (void*)&node;
if (node.IsTextNode())
ostream << "#text";
else if (const auto* element = DynamicTo<Element>(node))
ostream << element->tagName().Utf8();
LayoutObject* layout_object = node.GetLayoutObject();
if (!layout_object) {
ostream << " <null LayoutObject>";
return;
}
ostream << ' ' << layout_object->GetSelectionState();
}
#if DCHECK_IS_ON()
std::ostream& operator<<(std::ostream& ostream,
const absl::optional<unsigned>& offset) {
if (offset.has_value())
ostream << offset.value();
else
ostream << "<nullopt>";
return ostream;
}
std::ostream& operator<<(std::ostream& ostream,
const SelectionPaintRange& range) {
ostream << range.start_node << ": " << range.start_offset << ", "
<< range.end_node << ": " << range.end_offset;
return ostream;
}
std::ostream& operator<<(
std::ostream& ostream,
const HeapHashMap<Member<const Node>, SelectionState>& map) {
ostream << "[";
const char* comma = "";
for (const auto& key_value : map) {
const Node* const node = key_value.key;
const SelectionState old_state = key_value.value;
ostream << comma << node << "." << old_state;
comma = ", ";
}
ostream << "]";
return ostream;
}
std::ostream& operator<<(std::ostream& ostream,
const OldSelectedNodes& old_node) {
ostream << old_node.paint_range << ". " << old_node.selected_map;
return ostream;
}
void PrintOldSelectedNodes(const OldSelectedNodes& old_node) {
std::stringstream stream;
stream << std::endl << old_node;
LOG(INFO) << stream.str();
}
std::ostream& operator<<(
std::ostream& ostream,
const HeapHashSet<Member<const Node>>& selected_objects) {
ostream << "[";
const char* comma = "";
for (const Node* node : selected_objects) {
ostream << comma;
PrintSelectionStatus(ostream, *node);
comma = ", ";
}
ostream << "]";
return ostream;
}
std::ostream& operator<<(std::ostream& ostream,
const NewPaintRangeAndSelectedNodes& new_range) {
ostream << new_range.paint_range << ". " << new_range.selected_objects;
return ostream;
}
void PrintSelectedNodes(const NewPaintRangeAndSelectedNodes& new_range) {
std::stringstream stream;
stream << std::endl << new_range;
LOG(INFO) << stream.str();
}
void PrintSelectionStateInDocument(const FrameSelection& selection) {
class PrintVisitor {
STACK_ALLOCATED();
public:
void Visit(const Node& node) { PrintSelectionStatus(stream, node); }
std::stringstream stream;
} visitor;
VisitSelectedInclusiveDescendantsOf(selection.GetDocument(), &visitor);
LOG(INFO) << std::endl << visitor.stream.str();
}
#endif
} // namespace blink
| 37.587629 | 91 | 0.724181 |
chromium
|
e91ae89244ea57fb12b75ad7443543f1ad1c40a1
| 17,668 |
cpp
|
C++
|
src/CommandSet.cpp
|
jacobussystems/IoTJackAC1
|
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
|
[
"MIT"
] | null | null | null |
src/CommandSet.cpp
|
jacobussystems/IoTJackAC1
|
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
|
[
"MIT"
] | null | null | null |
src/CommandSet.cpp
|
jacobussystems/IoTJackAC1
|
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
|
[
"MIT"
] | null | null | null |
/*
CommandSet.cpp
By Jim Davies
Jacobus Systems, Brighton & Hove, UK
http://www.jacobus.co.uk
Provided under the MIT license: https://github.com/jacobussystems/ArdJack/blob/master/LICENSE
Copyright (c) 2019 James Davies, Jacobus Systems, Brighton & Hove, UK
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 "pch.h"
#ifdef ARDUINO
#else
#include "stdafx.h"
#endif
#include "Beacon.h"
#include "BeaconManager.h"
#include "Bridge.h"
#include "BridgeManager.h"
#include "CmdInterpreter.h"
#include "DeviceCodec1.h"
#include "CommandSet.h"
#include "Connection.h"
#include "ConnectionManager.h"
#include "Device.h"
#include "DeviceManager.h"
#include "Displayer.h"
#include "Globals.h"
#include "IoTMessage.h"
#include "Log.h"
#include "Part.h"
#include "Utils.h"
#ifdef ARDJACK_INCLUDE_PERSISTENCE
#include "PersistentFile.h"
#include "PersistentFileManager.h"
#endif
#ifdef ARDJACK_NETWORK_AVAILABLE
#include "NetworkInterface.h"
#include "NetworkManager.h"
#endif
#ifdef ARDJACK_INCLUDE_TESTS
#include "Tests.h"
#endif
CommandSet::CommandSet()
{
if (Globals::Verbosity > 7)
Log::LogInfo(PRM("CommandSet ctor"));
_CommandCount = 0;
#ifdef ARDJACK_INCLUDE_PERSISTENCE
_CurrentPersistentFile = NULL;
#endif
for (int i = 0; i < ARDJACK_MAX_COMMANDS; i++)
_Commands[i] = NULL;
AddCommand(PRM("ACTIVATE"), &CommandSet::command_activate);
AddCommand(PRM("ADD"), &CommandSet::command_add);
AddCommand(PRM("BEEP"), &CommandSet::command_beep);
AddCommand(PRM("CONFIGURE"), &CommandSet::command_configure);
AddCommand(PRM("CONNECTION"), &CommandSet::command_connection);
AddCommand(PRM("DEACTIVATE"), &CommandSet::command_deactivate);
AddCommand(PRM("DEFINE"), &CommandSet::command_define);
AddCommand(PRM("DELAY"), &CommandSet::command_delay);
AddCommand(PRM("DELETE"), &CommandSet::command_delete);
AddCommand(PRM("DEVICE"), &CommandSet::command_device);
AddCommand(PRM("DISPLAY"), &CommandSet::command_display);
AddCommand(PRM("EXIT"), &CommandSet::command_exit);
#ifdef ARDJACK_INCLUDE_PERSISTENCE
AddCommand(PRM("FILE"), &CommandSet::command_file);
#endif
AddCommand(PRM("HELP"), &CommandSet::command_help);
AddCommand(PRM("MEM"), &CommandSet::command_mem);
#ifdef ARDJACK_NETWORK_AVAILABLE
AddCommand(PRM("NET"), &CommandSet::command_net);
#endif
//AddCommand(PRM("PING"), &CommandSet::command_nyi); //&command_ping);
AddCommand(PRM("REACTIVATE"), &CommandSet::command_reactivate);
AddCommand(PRM("REPEAT"), &CommandSet::command_repeat);
AddCommand(PRM("RESET"), &CommandSet::command_reset);
#ifdef ARDJACK_INCLUDE_PERSISTENCE
AddCommand(PRM("RESTORE"), &CommandSet::command_restore);
AddCommand(PRM("SAVE"), &CommandSet::command_save);
#endif
AddCommand(PRM("SEND"), &CommandSet::command_send);
AddCommand(PRM("SET"), &CommandSet::command_set);
AddCommand(PRM("TEST"), &CommandSet::command_test);
#ifdef ARDJACK_INCLUDE_TESTS
AddCommand(PRM("TESTS"), &CommandSet::command_tests);
#endif
}
CommandSet::~CommandSet()
{
for (int i = 0; i < ARDJACK_MAX_COMMANDS; i++)
{
if (NULL != _Commands[i])
{
delete _Commands[i];
_Commands[i] = NULL;
}
}
}
CommandInfo* CommandSet::AddCommand(const char* name, CommandSetCallback callback)
{
if (_CommandCount >= ARDJACK_MAX_COMMANDS)
{
return NULL;
}
CommandInfo *result = _Commands[_CommandCount];
if (NULL == result)
{
result = new CommandInfo();
_Commands[_CommandCount] = result;
}
_CommandCount++;
strcpy(result->Name, name);
result->Callback = callback;
return result;
}
bool CommandSet::Handle(const char* line, const char* verb, const char* remainder)
{
if (_CommandCount == 0)
{
Log::LogWarning(PRM("Command Set has no commands: '"), line, "'");
return false;
}
// Is this command in '_Commands'?
if (strlen(verb) >= ARDJACK_MAX_VERB_LENGTH)
return false;
char ucVerb[ARDJACK_MAX_VERB_LENGTH];
strcpy(ucVerb, verb);
_strupr(ucVerb);
bool (CommandSet::*pCallback)(const char* args);
for (int i = 0; i < _CommandCount; i++)
{
CommandInfo* info = _Commands[i];
if (strcmp(ucVerb, info->Name) == 0)
{
pCallback = info->Callback;
if (pCallback == &CommandSet::command_nyi)
Log::LogWarning("NOT YET IMPLEMENTED:", ucVerb);
else
(*this.*pCallback)(remainder);
return true;
}
}
return false;
}
bool CommandSet::command_activate(const char* args)
{
// Activate zero or more 'IoTObjects'.
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("ACTIVATE command: No arguments"));
return true;
}
return Globals::ActivateObjects(args, true);
}
bool CommandSet::command_add(const char* args)
{
// Add an 'IoTObject'.
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("ADD command: No arguments"));
return true;
}
IoTObject* obj = Globals::AddObject(args);
if (NULL == obj) return false;
return true;
}
bool CommandSet::command_beep(const char* args)
{
// beep 1800 200 3
int freqHz = 1000;
int durMs = 200;
int beepCount = 1;
char fields[3][ARDJACK_MAX_VALUE_LENGTH];
int count = Utils::SplitText2Array(args, ' ', fields, 3, ARDJACK_MAX_VALUE_LENGTH);
if (count >= 1)
freqHz = Utils::String2Int(fields[0], freqHz);
if (count >= 2)
durMs = Utils::String2Int(fields[1], durMs);
if (count >= 3)
beepCount = Utils::String2Int(fields[2], beepCount);
for (int i = 0; i < beepCount; i++)
Utils::DoBeep(freqHz, durMs);
return true;
}
bool CommandSet::command_configure(const char* args)
{
// Configure an Object (Bridge, Connection, DataLogger or Device), -or- a Device's Part(s).
// Syntax:
// configure object item1=value1 item2=value2
// configure device.part item1=value1 item2=value2
// E.g.
// 'configure ard shield=thinker'
// 'configure ard.button0 name=value'
// 'configure udp0 inputport=2390'
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("CONFIGURE command: No arguments"));
return true;
}
StringList fields;
int count = Utils::SplitText(args, ' ', &fields, ARDJACK_MAX_VALUES, ARDJACK_MAX_VALUE_LENGTH);
// TEMPORARY: why?
if (count < 2)
{
Log::LogError(PRM("Configure: Less than 2 fields: "), args);
return false;
}
// Parse the first field - is it in 'obj.partExpr' format?
char fields2[2][ARDJACK_MAX_VALUE_LENGTH];
int count2 = Utils::SplitText2Array(fields.Get(0), '.', fields2, 2, ARDJACK_MAX_VALUE_LENGTH);
bool dotSyntax = (count2 > 1);
char objName[ARDJACK_MAX_NAME_LENGTH];
char partExpr[ARDJACK_MAX_NAME_LENGTH];
if (dotSyntax)
{
strcpy(objName, fields2[0]);
strcpy(partExpr, fields2[1]);
}
else
{
strcpy(objName, fields2[0]);
partExpr[0] = NULL;
}
// Check the Object name.
IoTObject* obj = Globals::ObjectRegister->LookupName(objName);
if (NULL == obj)
{
Log::LogError(PRM("Configure: Unknown object: '"), objName, "'");
return false;
}
if (Globals::Verbosity > 6)
{
char temp[102];
Log::LogInfoF(PRM("Configure: '%s', partExpr '%s'"), obj->ToString(temp), partExpr);
}
return obj->Configure(partExpr, &fields, 1, count - 1);
}
bool CommandSet::command_connection(const char* args)
{
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("CONNECTION command: No arguments"));
return true;
}
return Globals::ConnectionMgr->Interact(args);
}
bool CommandSet::command_deactivate(const char* args)
{
// Deactivate zero or more 'IoTObjects'.
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("DEACTIVATE command: No arguments"));
return true;
}
return Globals::ActivateObjects(args, false);
}
bool CommandSet::command_define(const char* args)
{
// Define a Macro.
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("DEFINE command: No arguments"));
return true;
}
char name[ARDJACK_MAX_NAME_LENGTH];
const char* content = NULL;
Utils::GetArgs(args, name, &content);
if (Utils::StringIsNullOrEmpty(content))
Globals::Interpreter->RemoveMacro(name);
else
Globals::Interpreter->AddMacro(name, content);
return true;
}
bool CommandSet::command_delay(const char* args)
{
// Delay for a number of milliseconds.
int delay_ms;
char fields[2][ARDJACK_MAX_VALUE_LENGTH];
int count = Utils::SplitText2Array(args, ' ', fields, 2, ARDJACK_MAX_VALUE_LENGTH);
if (count == 0) return false;
delay_ms = Utils::String2Int(fields[0], 1000);
Utils::DelayMs(delay_ms);
return true;
}
bool CommandSet::command_delete(const char* args)
{
// Delete zero or more 'IoTObjects'.
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("DELETE command: No arguments"));
return true;
}
return Globals::DeleteObjects(args);
}
bool CommandSet::command_device(const char* args)
{
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("DEVICE command: No arguments"));
return true;
}
return Globals::DeviceMgr->Interact(args);
}
bool CommandSet::command_display(const char* args)
{
return Displayer::DisplayItem(args);
}
bool CommandSet::command_exit(const char* args)
{
Globals::UserExit = true;
return true;
}
#ifdef ARDJACK_INCLUDE_PERSISTENCE
bool CommandSet::command_file(const char* args)
{
// file open settings open file 'settings' for writing
// file write name1=value1
// file write "name2=value 2"
// file close
// file open startup open file 'startup' for writing
// file write "command1 yy zz"
// file write "command2 yy zz"
// file close
// file clear clears all files
// file list list the current files
// file scan scan the flash storage (Arduino) / disk folder (Windows)
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("FILE command: No arguments"));
return true;
}
StringList fields;
int count = Utils::SplitText(args, ' ', &fields, ARDJACK_MAX_VALUES, ARDJACK_MAX_VALUE_LENGTH);
if (count == 0)
{
Log::LogError(PRM("FILE command: No arguments"));
return false;
}
char action[20];
strcpy(action, fields.Get(0));
_strupr(action);
if (Utils::StringEquals(action, "CLEAR", true))
{
return Globals::PersistentFileMgr->Clear();
}
if (Utils::StringEquals(action, "CLOSE", true))
{
if (NULL == _CurrentPersistentFile)
{
Log::LogError(PRM("FILE CLOSE command: No file open"));
return false;
}
return _CurrentPersistentFile->Close();
}
if (Utils::StringEquals(action, "LIST", true))
{
return Globals::PersistentFileMgr->List();
}
if (Utils::StringEquals(action, "LOADINI", true))
{
// Load the specified INI file.
if (count < 2)
{
Log::LogError(PRM("FILE LOAD command: Insufficient arguments in '"), args, "'");
return false;
}
return Globals::PersistentFileMgr->LoadIniFile(fields.Get(1));
}
if (Utils::StringEquals(action, "OPEN", true))
{
if (count < 2)
{
Log::LogError(PRM("FILE OPEN command: Insufficient arguments in '"), args, "'");
return false;
}
if (NULL != _CurrentPersistentFile)
{
_CurrentPersistentFile->Close();
_CurrentPersistentFile = NULL;
}
char name[ARDJACK_MAX_NAME_LENGTH];
strcpy(name, fields.Get(1));
_CurrentPersistentFile = Globals::PersistentFileMgr->Lookup(name, true);
if (NULL == _CurrentPersistentFile)
{
Log::LogError(PRM("FILE OPEN command: No such file: "), name);
return false;
}
return _CurrentPersistentFile->Open("w");
}
if (Utils::StringEquals(action, "SCAN", true))
{
#ifdef ARDUINO
return Globals::PersistentFileMgr->Scan();
#else
return Globals::PersistentFileMgr->Scan(Globals::AppDocsFolder);
#endif
}
if (Utils::StringEquals(action, "WRITE", true))
{
if (NULL == _CurrentPersistentFile)
{
Log::LogError(PRM("FILE WRITE command: No file open"));
return false;
}
if (!_CurrentPersistentFile->IsOpen())
{
Log::LogError(PRM("FILE WRITE command: File not open: "), _CurrentPersistentFile->Name);
return false;
}
if (count < 2)
return _CurrentPersistentFile->Puts("");
else
return _CurrentPersistentFile->Puts(fields.Get(1));
}
Log::LogError(PRM("FILE command: Invalid option: "), action);
return false;
}
#endif
bool CommandSet::command_help(const char* args)
{
Log::LogInfo(PRM("Available commands:"));
for (int i = 0; i < _CommandCount; i++)
{
CommandInfo* info = _Commands[i];
Log::LogInfo(" ", info->Name);
}
return true;
}
bool CommandSet::command_mem(const char* args)
{
return Displayer::DisplayMemory();
}
#ifdef ARDJACK_NETWORK_AVAILABLE
bool CommandSet::command_net(const char* args)
{
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("NET command: No arguments"));
return true;
}
return Globals::NetworkMgr->Interact(args);
}
#endif
bool CommandSet::command_nyi(const char* args)
{
// NOT YET IMPLEMENTED.
return false;
}
bool CommandSet::command_reactivate(const char* args)
{
// Rectivate zero or more 'IoTObjects' (reactivate = deactivate + activate).
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("REACTIVATE command: No arguments"));
return true;
}
return Globals::ReactivateObjects(args);
}
bool CommandSet::command_repeat(const char* args)
{
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("REPEAT command: No arguments"));
return true;
}
char firstPart[ARDJACK_MAX_VERB_LENGTH];
const char* remainder = NULL;
Utils::GetArgs(args, firstPart, &remainder);
int count = atoi(firstPart);
char temp[20];
for (int i = 1; i <= count; i++)
{
if (Globals::Verbosity > 3)
{
sprintf(temp, PRM("%d of %d"), i, count);
Log::LogInfo(PRM("command_repeat: Cycle "), temp);
}
Globals::Interpreter->Execute(remainder);
}
return true;
}
bool CommandSet::command_reset(const char* args)
{
Log::LogInfo(PRM("command_reset"));
void(*resetFunc) (void) = 0; // declare reset function at address 0
resetFunc();
return true;
}
#ifdef ARDJACK_INCLUDE_PERSISTENCE
bool CommandSet::command_restore(const char* args)
{
// Reload the configuration file (if any).
return Globals::LoadIniFile("configuration");
}
bool CommandSet::command_save(const char* args)
{
// Save some basic items of the current configuration to file "configuration".
return Globals::SaveIniFile("configuration");
}
#endif
bool CommandSet::command_send(const char* args)
{
// Send text via the specified Connection.
// Syntax:
// send conn "text"
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("SEND command: No arguments"));
return true;
}
char fields[2][ARDJACK_MAX_VALUE_LENGTH];
int count = Utils::SplitText2Array(args, ' ', fields, 2, ARDJACK_MAX_VALUE_LENGTH);
if (count < 2)
{
Log::LogError(PRM("Insufficient fields for SEND command: '"), args, "'");
return false;
}
Connection* conn = Globals::ConnectionMgr->LookupConnection(fields[0]);
if (NULL == conn)
{
Log::LogError(PRM("No such Connection: '"), fields[0], "'");
return false;
}
return conn->SendText(fields[1]);
}
bool CommandSet::command_set(const char* args)
{
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("SET command: No arguments"));
return true;
}
char fields[2][ARDJACK_MAX_VALUE_LENGTH];
bool handled;
int count = Utils::SplitText2Array(args, ' ', fields, 2, ARDJACK_MAX_VALUE_LENGTH);
return Globals::Set(fields[0], fields[1], &handled);
}
#ifdef ARDJACK_INCLUDE_TESTS
bool CommandSet::command_test(const char* args)
{
if (Utils::StringIsNullOrEmpty(args))
{
Log::LogWarning(PRM("TEST command: No arguments"));
return true;
}
// "test number arg1 arg2 verbosity"
char fields[4][ARDJACK_MAX_VALUE_LENGTH];
int count = Utils::SplitText2Array(args, ' ', fields, 4, ARDJACK_MAX_VALUE_LENGTH);
int number = 1;
int arg1 = 0;
int arg2 = 0;
int verbosity = 10;
if (count >= 1)
{
number = atoi(fields[0]);
if (count >= 2)
{
arg1 = atoi(fields[1]);
if (count >= 3)
{
arg2 = atoi(fields[2]);
if (count >= 4)
verbosity = atoi(fields[3]);
}
}
}
RunTest(number, arg1, arg2, verbosity);
return true;
}
bool CommandSet::command_tests(const char* args)
{
// TEMPORARY:
RunTests(10);
return true;
}
#else
bool CommandSet::command_test(const char* args)
{
Log::LogInfoF(PRM("Entry"));
int save = Globals::Verbosity;
Globals::Verbosity = 10;
Log::LogInfoF(PRM("--- STRING LISTS ---"));
StringList* sl1 = new StringList();
for (int i = 0; i < 3; i++)
{
StringList* sl2 = new StringList();
delete sl2;
StringList* sl3 = new StringList();
delete sl3;
}
delete sl1;
Log::LogInfoF(PRM("--- MESSAGES ---"));
IoTMessage* msg = new IoTMessage();
delete msg;
Log::LogInfoF(PRM("--- BEACONS ---"));
Beacon* beacon = new Beacon("beacon");
delete beacon;
Globals::Verbosity = save;
Log::LogInfoF(PRM("Exit"));
return true;
}
#endif
| 21.467801 | 114 | 0.698325 |
jacobussystems
|
e91b95a988d5806fc6591bb8e7c17a03fe79ecec
| 2,716 |
cpp
|
C++
|
src/Interpreters/InterpreterExternalDDLQuery.cpp
|
athom/ClickHouse
|
4f4cc9d7404fd489a7229633b22b5ea1889bd8c0
|
[
"Apache-2.0"
] | 15,577 |
2019-09-23T11:57:53.000Z
|
2022-03-31T18:21:48.000Z
|
src/Interpreters/InterpreterExternalDDLQuery.cpp
|
athom/ClickHouse
|
4f4cc9d7404fd489a7229633b22b5ea1889bd8c0
|
[
"Apache-2.0"
] | 16,476 |
2019-09-23T11:47:00.000Z
|
2022-03-31T23:06:01.000Z
|
src/Interpreters/InterpreterExternalDDLQuery.cpp
|
athom/ClickHouse
|
4f4cc9d7404fd489a7229633b22b5ea1889bd8c0
|
[
"Apache-2.0"
] | 3,633 |
2019-09-23T12:18:28.000Z
|
2022-03-31T15:55:48.000Z
|
#if !defined(ARCADIA_BUILD)
# include "config_core.h"
#endif
#include <Interpreters/InterpreterExternalDDLQuery.h>
#include <Interpreters/Context.h>
#include <Parsers/IAST.h>
#include <Parsers/ASTDropQuery.h>
#include <Parsers/ASTRenameQuery.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTExternalDDLQuery.h>
#ifdef USE_MYSQL
# include <Interpreters/MySQL/InterpretersMySQLDDLQuery.h>
# include <Parsers/MySQL/ASTAlterQuery.h>
# include <Parsers/MySQL/ASTCreateQuery.h>
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int SYNTAX_ERROR;
extern const int BAD_ARGUMENTS;
}
InterpreterExternalDDLQuery::InterpreterExternalDDLQuery(const ASTPtr & query_, ContextMutablePtr context_)
: WithMutableContext(context_), query(query_)
{
}
BlockIO InterpreterExternalDDLQuery::execute()
{
const ASTExternalDDLQuery & external_ddl_query = query->as<ASTExternalDDLQuery &>();
if (getContext()->getClientInfo().query_kind != ClientInfo::QueryKind::SECONDARY_QUERY)
throw Exception("Cannot parse and execute EXTERNAL DDL FROM.", ErrorCodes::SYNTAX_ERROR);
if (external_ddl_query.from->name == "MySQL")
{
#ifdef USE_MYSQL
const ASTs & arguments = external_ddl_query.from->arguments->children;
if (arguments.size() != 2 || !arguments[0]->as<ASTIdentifier>() || !arguments[1]->as<ASTIdentifier>())
throw Exception("MySQL External require two identifier arguments.", ErrorCodes::BAD_ARGUMENTS);
if (external_ddl_query.external_ddl->as<ASTDropQuery>())
return MySQLInterpreter::InterpreterMySQLDropQuery(
external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]),
getIdentifierName(arguments[1])).execute();
else if (external_ddl_query.external_ddl->as<ASTRenameQuery>())
return MySQLInterpreter::InterpreterMySQLRenameQuery(
external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]),
getIdentifierName(arguments[1])).execute();
else if (external_ddl_query.external_ddl->as<MySQLParser::ASTAlterQuery>())
return MySQLInterpreter::InterpreterMySQLAlterQuery(
external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]),
getIdentifierName(arguments[1])).execute();
else if (external_ddl_query.external_ddl->as<MySQLParser::ASTCreateQuery>())
return MySQLInterpreter::InterpreterMySQLCreateQuery(
external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]),
getIdentifierName(arguments[1])).execute();
#endif
}
return BlockIO();
}
}
| 37.722222 | 110 | 0.716495 |
athom
|
e91bb7ad2417fd19f53f460456ea1f1c77480762
| 15,625 |
cc
|
C++
|
test/cctest/compiler/test-run-jsops.cc
|
guillermomolina/v8-sparc
|
40f43c91a59835819cdd544b25d0ea415a753bbb
|
[
"BSD-3-Clause"
] | null | null | null |
test/cctest/compiler/test-run-jsops.cc
|
guillermomolina/v8-sparc
|
40f43c91a59835819cdd544b25d0ea415a753bbb
|
[
"BSD-3-Clause"
] | null | null | null |
test/cctest/compiler/test-run-jsops.cc
|
guillermomolina/v8-sparc
|
40f43c91a59835819cdd544b25d0ea415a753bbb
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(jochen): Remove this after the setting is turned on globally.
#define V8_IMMINENT_DEPRECATION_WARNINGS
#include "test/cctest/compiler/function-tester.h"
using namespace v8::internal;
using namespace v8::internal::compiler;
TEST(BinopAdd) {
FunctionTester T("(function(a,b) { return a + b; })");
T.CheckCall(3, 1, 2);
T.CheckCall(-11, -2, -9);
T.CheckCall(-11, -1.5, -9.5);
T.CheckCall(T.Val("AB"), T.Val("A"), T.Val("B"));
T.CheckCall(T.Val("A11"), T.Val("A"), T.Val(11));
T.CheckCall(T.Val("12B"), T.Val(12), T.Val("B"));
T.CheckCall(T.Val("38"), T.Val("3"), T.Val("8"));
T.CheckCall(T.Val("31"), T.Val("3"), T.NewObject("([1])"));
T.CheckCall(T.Val("3[object Object]"), T.Val("3"), T.NewObject("({})"));
}
TEST(BinopSubtract) {
FunctionTester T("(function(a,b) { return a - b; })");
T.CheckCall(3, 4, 1);
T.CheckCall(3.0, 4.5, 1.5);
T.CheckCall(T.Val(-9), T.Val("0"), T.Val(9));
T.CheckCall(T.Val(-9), T.Val(0.0), T.Val("9"));
T.CheckCall(T.Val(1), T.Val("3"), T.Val("2"));
T.CheckCall(T.nan(), T.Val("3"), T.Val("B"));
T.CheckCall(T.Val(2), T.Val("3"), T.NewObject("([1])"));
T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})"));
}
TEST(BinopMultiply) {
FunctionTester T("(function(a,b) { return a * b; })");
T.CheckCall(6, 3, 2);
T.CheckCall(4.5, 2.0, 2.25);
T.CheckCall(T.Val(6), T.Val("3"), T.Val(2));
T.CheckCall(T.Val(4.5), T.Val(2.0), T.Val("2.25"));
T.CheckCall(T.Val(6), T.Val("3"), T.Val("2"));
T.CheckCall(T.nan(), T.Val("3"), T.Val("B"));
T.CheckCall(T.Val(3), T.Val("3"), T.NewObject("([1])"));
T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})"));
}
TEST(BinopDivide) {
FunctionTester T("(function(a,b) { return a / b; })");
T.CheckCall(2, 8, 4);
T.CheckCall(2.1, 8.4, 4);
T.CheckCall(V8_INFINITY, 8, 0);
T.CheckCall(-V8_INFINITY, -8, 0);
T.CheckCall(T.infinity(), T.Val(8), T.Val("0"));
T.CheckCall(T.minus_infinity(), T.Val("-8"), T.Val(0.0));
T.CheckCall(T.Val(1.5), T.Val("3"), T.Val("2"));
T.CheckCall(T.nan(), T.Val("3"), T.Val("B"));
T.CheckCall(T.Val(1.5), T.Val("3"), T.NewObject("([2])"));
T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})"));
}
TEST(BinopModulus) {
FunctionTester T("(function(a,b) { return a % b; })");
T.CheckCall(3, 8, 5);
T.CheckCall(T.Val(3), T.Val("8"), T.Val(5));
T.CheckCall(T.Val(3), T.Val(8), T.Val("5"));
T.CheckCall(T.Val(1), T.Val("3"), T.Val("2"));
T.CheckCall(T.nan(), T.Val("3"), T.Val("B"));
T.CheckCall(T.Val(1), T.Val("3"), T.NewObject("([2])"));
T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})"));
}
TEST(BinopShiftLeft) {
FunctionTester T("(function(a,b) { return a << b; })");
T.CheckCall(4, 2, 1);
T.CheckCall(T.Val(4), T.Val("2"), T.Val(1));
T.CheckCall(T.Val(4), T.Val(2), T.Val("1"));
}
TEST(BinopShiftRight) {
FunctionTester T("(function(a,b) { return a >> b; })");
T.CheckCall(4, 8, 1);
T.CheckCall(-4, -8, 1);
T.CheckCall(T.Val(4), T.Val("8"), T.Val(1));
T.CheckCall(T.Val(4), T.Val(8), T.Val("1"));
}
TEST(BinopShiftRightLogical) {
FunctionTester T("(function(a,b) { return a >>> b; })");
T.CheckCall(4, 8, 1);
T.CheckCall(0x7ffffffc, -8, 1);
T.CheckCall(T.Val(4), T.Val("8"), T.Val(1));
T.CheckCall(T.Val(4), T.Val(8), T.Val("1"));
}
TEST(BinopAnd) {
FunctionTester T("(function(a,b) { return a & b; })");
T.CheckCall(7, 7, 15);
T.CheckCall(7, 15, 7);
T.CheckCall(T.Val(7), T.Val("15"), T.Val(7));
T.CheckCall(T.Val(7), T.Val(15), T.Val("7"));
}
TEST(BinopOr) {
FunctionTester T("(function(a,b) { return a | b; })");
T.CheckCall(6, 4, 2);
T.CheckCall(6, 2, 4);
T.CheckCall(T.Val(6), T.Val("2"), T.Val(4));
T.CheckCall(T.Val(6), T.Val(2), T.Val("4"));
}
TEST(BinopXor) {
FunctionTester T("(function(a,b) { return a ^ b; })");
T.CheckCall(7, 15, 8);
T.CheckCall(7, 8, 15);
T.CheckCall(T.Val(7), T.Val("8"), T.Val(15));
T.CheckCall(T.Val(7), T.Val(8), T.Val("15"));
}
TEST(BinopStrictEqual) {
FunctionTester T("(function(a,b) { return a === b; })");
T.CheckTrue(7, 7);
T.CheckFalse(7, 8);
T.CheckTrue(7.1, 7.1);
T.CheckFalse(7.1, 8.1);
T.CheckTrue(T.Val("7.1"), T.Val("7.1"));
T.CheckFalse(T.Val(7.1), T.Val("7.1"));
T.CheckFalse(T.Val(7), T.undefined());
T.CheckFalse(T.undefined(), T.Val(7));
CompileRun("var o = { desc : 'I am a singleton' }");
T.CheckFalse(T.NewObject("([1])"), T.NewObject("([1])"));
T.CheckFalse(T.NewObject("({})"), T.NewObject("({})"));
T.CheckTrue(T.NewObject("(o)"), T.NewObject("(o)"));
}
TEST(BinopEqual) {
FunctionTester T("(function(a,b) { return a == b; })");
T.CheckTrue(7, 7);
T.CheckFalse(7, 8);
T.CheckTrue(7.1, 7.1);
T.CheckFalse(7.1, 8.1);
T.CheckTrue(T.Val("7.1"), T.Val("7.1"));
T.CheckTrue(T.Val(7.1), T.Val("7.1"));
CompileRun("var o = { desc : 'I am a singleton' }");
T.CheckFalse(T.NewObject("([1])"), T.NewObject("([1])"));
T.CheckFalse(T.NewObject("({})"), T.NewObject("({})"));
T.CheckTrue(T.NewObject("(o)"), T.NewObject("(o)"));
}
TEST(BinopNotEqual) {
FunctionTester T("(function(a,b) { return a != b; })");
T.CheckFalse(7, 7);
T.CheckTrue(7, 8);
T.CheckFalse(7.1, 7.1);
T.CheckTrue(7.1, 8.1);
T.CheckFalse(T.Val("7.1"), T.Val("7.1"));
T.CheckFalse(T.Val(7.1), T.Val("7.1"));
CompileRun("var o = { desc : 'I am a singleton' }");
T.CheckTrue(T.NewObject("([1])"), T.NewObject("([1])"));
T.CheckTrue(T.NewObject("({})"), T.NewObject("({})"));
T.CheckFalse(T.NewObject("(o)"), T.NewObject("(o)"));
}
TEST(BinopLessThan) {
FunctionTester T("(function(a,b) { return a < b; })");
T.CheckTrue(7, 8);
T.CheckFalse(8, 7);
T.CheckTrue(-8.1, -8);
T.CheckFalse(-8, -8.1);
T.CheckFalse(0.111, 0.111);
T.CheckFalse(T.Val("7.1"), T.Val("7.1"));
T.CheckFalse(T.Val(7.1), T.Val("6.1"));
T.CheckFalse(T.Val(7.1), T.Val("7.1"));
T.CheckTrue(T.Val(7.1), T.Val("8.1"));
}
TEST(BinopLessThanOrEqual) {
FunctionTester T("(function(a,b) { return a <= b; })");
T.CheckTrue(7, 8);
T.CheckFalse(8, 7);
T.CheckTrue(-8.1, -8);
T.CheckFalse(-8, -8.1);
T.CheckTrue(0.111, 0.111);
T.CheckTrue(T.Val("7.1"), T.Val("7.1"));
T.CheckFalse(T.Val(7.1), T.Val("6.1"));
T.CheckTrue(T.Val(7.1), T.Val("7.1"));
T.CheckTrue(T.Val(7.1), T.Val("8.1"));
}
TEST(BinopGreaterThan) {
FunctionTester T("(function(a,b) { return a > b; })");
T.CheckFalse(7, 8);
T.CheckTrue(8, 7);
T.CheckFalse(-8.1, -8);
T.CheckTrue(-8, -8.1);
T.CheckFalse(0.111, 0.111);
T.CheckFalse(T.Val("7.1"), T.Val("7.1"));
T.CheckTrue(T.Val(7.1), T.Val("6.1"));
T.CheckFalse(T.Val(7.1), T.Val("7.1"));
T.CheckFalse(T.Val(7.1), T.Val("8.1"));
}
TEST(BinopGreaterThanOrEqual) {
FunctionTester T("(function(a,b) { return a >= b; })");
T.CheckFalse(7, 8);
T.CheckTrue(8, 7);
T.CheckFalse(-8.1, -8);
T.CheckTrue(-8, -8.1);
T.CheckTrue(0.111, 0.111);
T.CheckTrue(T.Val("7.1"), T.Val("7.1"));
T.CheckTrue(T.Val(7.1), T.Val("6.1"));
T.CheckTrue(T.Val(7.1), T.Val("7.1"));
T.CheckFalse(T.Val(7.1), T.Val("8.1"));
}
TEST(BinopIn) {
FunctionTester T("(function(a,b) { return a in b; })");
T.CheckTrue(T.Val("x"), T.NewObject("({x:23})"));
T.CheckFalse(T.Val("y"), T.NewObject("({x:42})"));
T.CheckFalse(T.Val(123), T.NewObject("({x:65})"));
T.CheckTrue(T.Val(1), T.NewObject("([1,2,3])"));
}
TEST(BinopInstanceOf) {
FunctionTester T("(function(a,b) { return a instanceof b; })");
T.CheckTrue(T.NewObject("(new Number(23))"), T.NewObject("Number"));
T.CheckFalse(T.NewObject("(new Number(23))"), T.NewObject("String"));
T.CheckFalse(T.NewObject("(new String('a'))"), T.NewObject("Number"));
T.CheckTrue(T.NewObject("(new String('b'))"), T.NewObject("String"));
T.CheckFalse(T.Val(1), T.NewObject("Number"));
T.CheckFalse(T.Val("abc"), T.NewObject("String"));
CompileRun("var bound = (function() {}).bind(undefined)");
T.CheckTrue(T.NewObject("(new bound())"), T.NewObject("bound"));
T.CheckTrue(T.NewObject("(new bound())"), T.NewObject("Object"));
T.CheckFalse(T.NewObject("(new bound())"), T.NewObject("Number"));
}
TEST(UnopNot) {
FunctionTester T("(function(a) { return !a; })");
T.CheckCall(T.true_value(), T.false_value(), T.undefined());
T.CheckCall(T.false_value(), T.true_value(), T.undefined());
T.CheckCall(T.true_value(), T.Val(0.0), T.undefined());
T.CheckCall(T.false_value(), T.Val(123), T.undefined());
T.CheckCall(T.false_value(), T.Val("x"), T.undefined());
T.CheckCall(T.true_value(), T.undefined(), T.undefined());
T.CheckCall(T.true_value(), T.nan(), T.undefined());
}
TEST(UnopCountPost) {
FunctionTester T("(function(a) { return a++; })");
T.CheckCall(T.Val(0.0), T.Val(0.0), T.undefined());
T.CheckCall(T.Val(2.3), T.Val(2.3), T.undefined());
T.CheckCall(T.Val(123), T.Val(123), T.undefined());
T.CheckCall(T.Val(7), T.Val("7"), T.undefined());
T.CheckCall(T.nan(), T.Val("x"), T.undefined());
T.CheckCall(T.nan(), T.undefined(), T.undefined());
T.CheckCall(T.Val(1.0), T.true_value(), T.undefined());
T.CheckCall(T.Val(0.0), T.false_value(), T.undefined());
T.CheckCall(T.nan(), T.nan(), T.undefined());
}
TEST(UnopCountPre) {
FunctionTester T("(function(a) { return ++a; })");
T.CheckCall(T.Val(1.0), T.Val(0.0), T.undefined());
T.CheckCall(T.Val(3.3), T.Val(2.3), T.undefined());
T.CheckCall(T.Val(124), T.Val(123), T.undefined());
T.CheckCall(T.Val(8), T.Val("7"), T.undefined());
T.CheckCall(T.nan(), T.Val("x"), T.undefined());
T.CheckCall(T.nan(), T.undefined(), T.undefined());
T.CheckCall(T.Val(2.0), T.true_value(), T.undefined());
T.CheckCall(T.Val(1.0), T.false_value(), T.undefined());
T.CheckCall(T.nan(), T.nan(), T.undefined());
}
TEST(PropertyNamedLoad) {
FunctionTester T("(function(a,b) { return a.x; })");
T.CheckCall(T.Val(23), T.NewObject("({x:23})"), T.undefined());
T.CheckCall(T.undefined(), T.NewObject("({y:23})"), T.undefined());
}
TEST(PropertyKeyedLoad) {
FunctionTester T("(function(a,b) { return a[b]; })");
T.CheckCall(T.Val(23), T.NewObject("({x:23})"), T.Val("x"));
T.CheckCall(T.Val(42), T.NewObject("([23,42,65])"), T.Val(1));
T.CheckCall(T.undefined(), T.NewObject("({x:23})"), T.Val("y"));
T.CheckCall(T.undefined(), T.NewObject("([23,42,65])"), T.Val(4));
}
TEST(PropertyNamedStore) {
FunctionTester T("(function(a) { a.x = 7; return a.x; })");
T.CheckCall(T.Val(7), T.NewObject("({})"), T.undefined());
T.CheckCall(T.Val(7), T.NewObject("({x:23})"), T.undefined());
}
TEST(PropertyKeyedStore) {
FunctionTester T("(function(a,b) { a[b] = 7; return a.x; })");
T.CheckCall(T.Val(7), T.NewObject("({})"), T.Val("x"));
T.CheckCall(T.Val(7), T.NewObject("({x:23})"), T.Val("x"));
T.CheckCall(T.Val(9), T.NewObject("({x:9})"), T.Val("y"));
}
TEST(PropertyNamedDelete) {
FunctionTester T("(function(a) { return delete a.x; })");
CompileRun("var o = Object.create({}, { x: { value:23 } });");
T.CheckTrue(T.NewObject("({x:42})"), T.undefined());
T.CheckTrue(T.NewObject("({})"), T.undefined());
T.CheckFalse(T.NewObject("(o)"), T.undefined());
}
TEST(PropertyKeyedDelete) {
FunctionTester T("(function(a, b) { return delete a[b]; })");
CompileRun("function getX() { return 'x'; }");
CompileRun("var o = Object.create({}, { x: { value:23 } });");
T.CheckTrue(T.NewObject("({x:42})"), T.Val("x"));
T.CheckFalse(T.NewObject("(o)"), T.Val("x"));
T.CheckFalse(T.NewObject("(o)"), T.NewObject("({toString:getX})"));
}
TEST(GlobalLoad) {
FunctionTester T("(function() { return g; })");
T.CheckThrows(T.undefined(), T.undefined());
CompileRun("var g = 23;");
T.CheckCall(T.Val(23));
}
TEST(GlobalStoreSloppy) {
FunctionTester T("(function(a,b) { g = a + b; return g; })");
T.CheckCall(T.Val(33), T.Val(22), T.Val(11));
CompileRun("delete g");
CompileRun("const g = 23");
T.CheckCall(T.Val(23), T.Val(55), T.Val(44));
}
TEST(GlobalStoreStrict) {
FunctionTester T("(function(a,b) { 'use strict'; g = a + b; return g; })");
T.CheckThrows(T.Val(22), T.Val(11));
CompileRun("var g = 'a global variable';");
T.CheckCall(T.Val(33), T.Val(22), T.Val(11));
}
TEST(ContextLoad) {
FunctionTester T("(function(a,b) { (function(){a}); return a + b; })");
T.CheckCall(T.Val(65), T.Val(23), T.Val(42));
T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b"));
}
TEST(ContextStore) {
FunctionTester T("(function(a,b) { (function(){x}); var x = a; return x; })");
T.CheckCall(T.Val(23), T.Val(23), T.undefined());
T.CheckCall(T.Val("a"), T.Val("a"), T.undefined());
}
TEST(LookupLoad) {
FunctionTester T("(function(a,b) { with(a) { return x + b; } })");
T.CheckCall(T.Val(24), T.NewObject("({x:23})"), T.Val(1));
T.CheckCall(T.Val(32), T.NewObject("({x:23, b:9})"), T.Val(2));
T.CheckCall(T.Val(45), T.NewObject("({__proto__:{x:42}})"), T.Val(3));
T.CheckCall(T.Val(69), T.NewObject("({get x() { return 65; }})"), T.Val(4));
}
TEST(LookupStore) {
FunctionTester T("(function(a,b) { var x; with(a) { x = b; } return x; })");
T.CheckCall(T.undefined(), T.NewObject("({x:23})"), T.Val(1));
T.CheckCall(T.Val(2), T.NewObject("({y:23})"), T.Val(2));
T.CheckCall(T.Val(23), T.NewObject("({b:23})"), T.Val(3));
T.CheckCall(T.undefined(), T.NewObject("({__proto__:{x:42}})"), T.Val(4));
}
TEST(BlockLoadStore) {
FunctionTester T("(function(a) { 'use strict'; { let x = a+a; return x; }})");
T.CheckCall(T.Val(46), T.Val(23));
T.CheckCall(T.Val("aa"), T.Val("a"));
}
TEST(BlockLoadStoreNested) {
const char* src =
"(function(a,b) {"
"'use strict';"
"{ let x = a, y = a;"
" { let y = b;"
" return x + y;"
" }"
"}})";
FunctionTester T(src);
T.CheckCall(T.Val(65), T.Val(23), T.Val(42));
T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b"));
}
TEST(ObjectLiteralComputed) {
FunctionTester T("(function(a,b) { o = { x:a+b }; return o.x; })");
T.CheckCall(T.Val(65), T.Val(23), T.Val(42));
T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b"));
}
TEST(ObjectLiteralNonString) {
FunctionTester T("(function(a,b) { o = { 7:a+b }; return o[7]; })");
T.CheckCall(T.Val(65), T.Val(23), T.Val(42));
T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b"));
}
TEST(ObjectLiteralPrototype) {
FunctionTester T("(function(a) { o = { __proto__:a }; return o.x; })");
T.CheckCall(T.Val(23), T.NewObject("({x:23})"), T.undefined());
T.CheckCall(T.undefined(), T.NewObject("({y:42})"), T.undefined());
}
TEST(ObjectLiteralGetter) {
FunctionTester T("(function(a) { o = { get x() {return a} }; return o.x; })");
T.CheckCall(T.Val(23), T.Val(23), T.undefined());
T.CheckCall(T.Val("x"), T.Val("x"), T.undefined());
}
TEST(ArrayLiteral) {
FunctionTester T("(function(a,b) { o = [1, a + b, 3]; return o[1]; })");
T.CheckCall(T.Val(65), T.Val(23), T.Val(42));
T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b"));
}
TEST(RegExpLiteral) {
FunctionTester T("(function(a) { o = /b/; return o.test(a); })");
T.CheckTrue(T.Val("abc"));
T.CheckFalse(T.Val("xyz"));
}
TEST(ClassLiteral) {
FLAG_harmony_sloppy = true;
const char* src =
"(function(a,b) {"
" class C {"
" x() { return a; }"
" static y() { return b; }"
" get z() { return 0; }"
" constructor() {}"
" }"
" return new C().x() + C.y();"
"})";
FunctionTester T(src);
T.CheckCall(T.Val(65), T.Val(23), T.Val(42));
T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b"));
}
| 28.775322 | 80 | 0.574848 |
guillermomolina
|
e91e00225954bf4ddeab940c29899f540699a0db
| 7,822 |
cpp
|
C++
|
lib/DxilDia/DxcPixLiveVariables.cpp
|
seanbaxter/DirectXShaderCompiler
|
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
|
[
"NCSA"
] | null | null | null |
lib/DxilDia/DxcPixLiveVariables.cpp
|
seanbaxter/DirectXShaderCompiler
|
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
|
[
"NCSA"
] | null | null | null |
lib/DxilDia/DxcPixLiveVariables.cpp
|
seanbaxter/DirectXShaderCompiler
|
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
|
[
"NCSA"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// //
// DxcPixLiveVariables.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// Defines the mapping between instructions and the set of live variables //
// for it. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/Support/WinIncludes.h"
#include "DxcPixDxilDebugInfo.h"
#include "DxcPixLiveVariables.h"
#include "DxcPixLiveVariables_FragmentIterator.h"
#include "DxilDiaSession.h"
#include "dxc/Support/Global.h"
#include "llvm37/ADT/SmallVector.h"
#include "llvm37/IR/DebugInfo.h"
#include "llvm37/IR/DebugInfoMetadata.h"
#include "llvm37/IR/Dominators.h"
#include "llvm37/IR/Instructions.h"
#include "llvm37/IR/Intrinsics.h"
#include "llvm37/IR/IntrinsicInst.h"
#include "llvm37/IR/Module.h"
#include <unordered_map>
// ValidateDbgDeclare ensures that all of the bits in
// [FragmentSizeInBits, FragmentOffsetInBits) are currently
// not assigned to a dxil alloca register -- i.e., it
// tries to find overlapping alloca registers -- which should
// never happen -- to report the issue.
void ValidateDbgDeclare(
dxil_debug_info::VariableInfo *VarInfo,
unsigned FragmentSizeInBits,
unsigned FragmentOffsetInBits
)
{
#ifndef NDEBUG
for (unsigned i = 0; i < FragmentSizeInBits; ++i)
{
const unsigned BitNum = FragmentOffsetInBits + i;
VarInfo->m_DbgDeclareValidation.resize(
std::max<unsigned>(VarInfo->m_DbgDeclareValidation.size(),
BitNum + 1));
assert(!VarInfo->m_DbgDeclareValidation[BitNum]);
VarInfo->m_DbgDeclareValidation[BitNum] = true;
}
#endif // !NDEBUG
}
struct dxil_debug_info::LiveVariables::Impl
{
using VariableInfoMap = std::unordered_map<
llvm37::DIVariable *,
std::unique_ptr<VariableInfo>>;
using LiveVarsMap =
std::unordered_map<llvm37::DIScope*, VariableInfoMap>;
IMalloc *m_pMalloc;
DxcPixDxilDebugInfo *m_pDxilDebugInfo;
llvm37::Module *m_pModule;
LiveVarsMap m_LiveVarsDbgDeclare;
void Init(
IMalloc *pMalloc,
DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm37::Module *pModule);
void Init_DbgDeclare(llvm37::DbgDeclareInst *DbgDeclare);
VariableInfo *AssignValueToOffset(
VariableInfoMap *VarInfoMap,
llvm37::DIVariable *Var,
llvm37::Value *Address,
unsigned FragmentIndex,
unsigned FragmentOffsetInBits);
};
void dxil_debug_info::LiveVariables::Impl::Init(
IMalloc *pMalloc,
DxcPixDxilDebugInfo *pDxilDebugInfo,
llvm37::Module *pModule)
{
m_pMalloc = pMalloc;
m_pDxilDebugInfo = pDxilDebugInfo;
m_pModule = pModule;
llvm37::Function* DbgDeclareFn = llvm37::Intrinsic::getDeclaration(
m_pModule,
llvm37::Intrinsic::dbg_declare);
for (llvm37::User* U : DbgDeclareFn->users())
{
if (auto* DbgDeclare = llvm37::dyn_cast<llvm37::DbgDeclareInst>(U))
{
Init_DbgDeclare(DbgDeclare);
}
}
}
void dxil_debug_info::LiveVariables::Impl::Init_DbgDeclare(
llvm37::DbgDeclareInst *DbgDeclare
)
{
llvm37::Value *Address = DbgDeclare->getAddress();
auto *Variable = DbgDeclare->getVariable();
auto *Expression = DbgDeclare->getExpression();
if (Address == nullptr || Variable == nullptr || Expression == nullptr)
{
return;
}
auto* AddressAsAlloca = llvm37::dyn_cast<llvm37::AllocaInst>(Address);
if (AddressAsAlloca == nullptr)
{
return;
}
auto *S = Variable->getScope();
if (S == nullptr)
{
return;
}
auto Iter = CreateMemberIterator(
DbgDeclare,
m_pModule->getDataLayout(),
AddressAsAlloca,
Expression);
if (!Iter)
{
// MemberIterator creation failure, this skip this var.
return;
}
unsigned FragmentIndex;
while (Iter->Next(&FragmentIndex))
{
const unsigned FragmentSizeInBits =
Iter->SizeInBits(FragmentIndex);
const unsigned FragmentOffsetInBits =
Iter->OffsetInBits(FragmentIndex);
VariableInfo* VarInfo = AssignValueToOffset(
&m_LiveVarsDbgDeclare[S],
Variable,
Address,
FragmentIndex,
FragmentOffsetInBits);
// SROA can split structs so that multiple allocas back the same variable.
// In this case the expression will be empty
if (Expression->getNumElements() != 0)
{
ValidateDbgDeclare(
VarInfo,
FragmentSizeInBits,
FragmentOffsetInBits);
}
}
}
dxil_debug_info::VariableInfo* dxil_debug_info::LiveVariables::Impl::AssignValueToOffset(
VariableInfoMap *VarInfoMap,
llvm37::DIVariable *Variable,
llvm37::Value *Address,
unsigned FragmentIndex,
unsigned FragmentOffsetInBits
)
{
// FragmentIndex is the index within the alloca'd value
// FragmentOffsetInBits is the offset within the HLSL variable
// that maps to Address[FragmentIndex]
auto it = VarInfoMap->find(Variable);
if (it == VarInfoMap->end())
{
auto InsertIt = VarInfoMap->emplace(
Variable,
std::make_unique<VariableInfo>(Variable));
assert(InsertIt.second);
it = InsertIt.first;
}
auto *VarInfo = it->second.get();
auto &FragmentLocation =
VarInfo->m_ValueLocationMap[FragmentOffsetInBits];
FragmentLocation.m_V = Address;
FragmentLocation.m_FragmentIndex = FragmentIndex;
return VarInfo;
}
dxil_debug_info::LiveVariables::LiveVariables() = default;
dxil_debug_info::LiveVariables::~LiveVariables() = default;
HRESULT dxil_debug_info::LiveVariables::Init(DxcPixDxilDebugInfo *pDxilDebugInfo) {
Clear();
m_pImpl->Init(pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, pDxilDebugInfo->GetModuleRef());
return S_OK;
}
void dxil_debug_info::LiveVariables::Clear() {
m_pImpl.reset(new dxil_debug_info::LiveVariables::Impl());
}
HRESULT dxil_debug_info::LiveVariables::GetLiveVariablesAtInstruction(
llvm37::Instruction *IP,
IDxcPixDxilLiveVariables **ppResult) const {
DXASSERT(IP != nullptr, "else IP should not be nullptr");
DXASSERT(ppResult != nullptr, "else Result should not be nullptr");
std::vector<const VariableInfo *> LiveVars;
std::set<std::string> LiveVarsName;
const llvm37::DebugLoc &DL = IP->getDebugLoc();
if (!DL)
{
return E_FAIL;
}
llvm37::DIScope *S = DL->getScope();
if (S == nullptr)
{
return E_FAIL;
}
const llvm37::DITypeIdentifierMap EmptyMap;
while (S != nullptr)
{
auto it = m_pImpl->m_LiveVarsDbgDeclare.find(S);
if (it != m_pImpl->m_LiveVarsDbgDeclare.end())
{
for (const auto &VarAndInfo : it->second)
{
auto *Var = VarAndInfo.first;
llvm37::StringRef VarName = Var->getName();
if (Var->getLine() > DL.getLine())
{
// Defined later in the HLSL source.
continue;
}
if (VarName.empty())
{
// No name?...
continue;
}
if (!LiveVarsName.insert(VarName).second)
{
// There's a variable with the same name; use the
// previous one instead.
continue;
}
LiveVars.emplace_back(VarAndInfo.second.get());
}
}
S = S->getScope().resolve(EmptyMap);
}
return CreateDxilLiveVariables(
m_pImpl->m_pDxilDebugInfo,
std::move(LiveVars),
ppResult);
}
| 28.34058 | 98 | 0.634748 |
seanbaxter
|
e91eca6dca5931a7a428435ee48946a8912f5bc1
| 8,039 |
cpp
|
C++
|
src/IECore/ClientDisplayDriver.cpp
|
gcodebackups/cortex-vfx
|
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
|
[
"BSD-3-Clause"
] | 5 |
2016-07-26T06:09:28.000Z
|
2022-03-07T03:58:51.000Z
|
src/IECore/ClientDisplayDriver.cpp
|
turbosun/cortex
|
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
|
[
"BSD-3-Clause"
] | null | null | null |
src/IECore/ClientDisplayDriver.cpp
|
turbosun/cortex
|
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
|
[
"BSD-3-Clause"
] | 3 |
2015-03-25T18:45:24.000Z
|
2020-02-15T15:37:18.000Z
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/asio.hpp"
#include "boost/bind.hpp"
#include "IECore/ClientDisplayDriver.h"
#include "IECore/private/DisplayDriverServerHeader.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/MemoryIndexedIO.h"
using namespace boost;
using namespace std;
using namespace Imath;
using namespace IECore;
using boost::asio::ip::tcp;
struct ClientDisplayDriver::PrivateData : public RefCounted
{
public :
PrivateData() :
m_service(), m_host(""), m_port(""), m_scanLineOrderOnly(false), m_acceptsRepeatedData(false), m_socket( m_service )
{
}
~PrivateData()
{
m_socket.close();
}
boost::asio::io_service m_service;
std::string m_host;
std::string m_port;
bool m_scanLineOrderOnly;
bool m_acceptsRepeatedData;
boost::asio::ip::tcp::socket m_socket;
};
IE_CORE_DEFINERUNTIMETYPED( ClientDisplayDriver );
const DisplayDriver::DisplayDriverDescription<ClientDisplayDriver> ClientDisplayDriver::g_description;
ClientDisplayDriver::ClientDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, IECore::ConstCompoundDataPtr parameters ) :
DisplayDriver( displayWindow, dataWindow, channelNames, parameters ),
m_data( new PrivateData() )
{
// expects three custom StringData parameters : displayHost, displayPort and displayType
const StringData *displayHostData = parameters->member<StringData>( "displayHost", true /* throw if missing */ );
const StringData *displayPortData = parameters->member<StringData>( "displayPort", true /* throw if missing */ );
m_data->m_host = displayHostData->readable();
m_data->m_port = displayPortData->readable();
tcp::resolver resolver(m_data->m_service);
tcp::resolver::query query(m_data->m_host, m_data->m_port);
boost::system::error_code error;
tcp::resolver::iterator iterator = resolver.resolve( query, error );
if( !error )
{
error = boost::asio::error::host_not_found;
while( error && iterator != tcp::resolver::iterator() )
{
m_data->m_socket.close();
m_data->m_socket.connect( *iterator++, error );
}
}
if( error )
{
throw Exception( std::string( "Could not connect to remote display driver server : " ) + error.message() );
}
MemoryIndexedIOPtr io;
ConstCharVectorDataPtr buf;
Box2iDataPtr displayWindowData = new Box2iData( displayWindow );
Box2iDataPtr dataWindowData = new Box2iData( dataWindow );
StringVectorDataPtr channelNamesData = new StringVectorData( channelNames );
IECore::CompoundDataPtr tmpParameters = parameters->copy();
tmpParameters->writable()[ "clientPID" ] = new IntData( getpid() );
// build the data block
io = new MemoryIndexedIO( ConstCharVectorDataPtr(), IndexedIO::rootPath, IndexedIO::Exclusive | IndexedIO::Write );
displayWindowData->Object::save( io, "displayWindow" );
dataWindowData->Object::save( io, "dataWindow" );
channelNamesData->Object::save( io, "channelNames" );
tmpParameters->Object::save( io, "parameters" );
buf = io->buffer();
size_t dataSize = buf->readable().size();
sendHeader( DisplayDriverServerHeader::imageOpen, dataSize );
m_data->m_socket.send( boost::asio::buffer( &(buf->readable()[0]), dataSize ) );
if ( receiveHeader( DisplayDriverServerHeader::imageOpen ) != sizeof(m_data->m_scanLineOrderOnly) )
{
throw Exception( "Invalid returned scanLineOrder from display driver server!" );
}
m_data->m_socket.receive( boost::asio::buffer( &m_data->m_scanLineOrderOnly, sizeof(m_data->m_scanLineOrderOnly) ) );
if ( receiveHeader( DisplayDriverServerHeader::imageOpen ) != sizeof(m_data->m_acceptsRepeatedData) )
{
throw Exception( "Invalid returned acceptsRepeatedData from display driver server!" );
}
m_data->m_socket.receive( boost::asio::buffer( &m_data->m_acceptsRepeatedData, sizeof(m_data->m_acceptsRepeatedData) ) );
}
ClientDisplayDriver::~ClientDisplayDriver()
{
}
std::string ClientDisplayDriver::host() const
{
return m_data->m_host;
}
std::string ClientDisplayDriver::port() const
{
return m_data->m_port;
}
bool ClientDisplayDriver::scanLineOrderOnly() const
{
return m_data->m_scanLineOrderOnly;
}
bool ClientDisplayDriver::acceptsRepeatedData() const
{
return m_data->m_acceptsRepeatedData;
}
void ClientDisplayDriver::sendHeader( int msg, size_t dataSize )
{
DisplayDriverServerHeader header( (DisplayDriverServerHeader::MessageType)msg, dataSize );
m_data->m_socket.send( boost::asio::buffer( header.buffer(), header.headerLength ) );
}
size_t ClientDisplayDriver::receiveHeader( int msg )
{
DisplayDriverServerHeader header;
m_data->m_socket.receive( boost::asio::buffer( header.buffer(), header.headerLength ) );
if ( !header.valid() )
{
throw Exception( "Invalid display driver header block on socket package." );
}
size_t bytesAhead = header.getDataSize();
if ( header.messageType() == DisplayDriverServerHeader::exception )
{
vector<char> txt;
txt.resize( bytesAhead );
m_data->m_socket.receive( boost::asio::buffer( &(txt[0]), bytesAhead ) );
throw Exception( std::string("Error on remote display driver: ") + &(txt[0]) );
}
if ( header.messageType() != msg )
{
throw Exception( "Unexpected message type on display driver socket package." );
}
return bytesAhead;
}
void ClientDisplayDriver::imageData( const Box2i &box, const float *data, size_t dataSize )
{
MemoryIndexedIOPtr io;
ConstCharVectorDataPtr buf;
// build the data block
Box2iDataPtr boxData = new Box2iData( box );
FloatVectorDataPtr dataData = new FloatVectorData( std::vector<float>( data, data+dataSize ) );
io = new MemoryIndexedIO( ConstCharVectorDataPtr(), IndexedIO::rootPath, IndexedIO::Exclusive | IndexedIO::Write );
staticPointerCast<Object>(boxData)->save( io, "box" );
staticPointerCast<Object>(dataData)->save( io, "data" );
buf = io->buffer();
size_t blockSize = buf->readable().size();
sendHeader( DisplayDriverServerHeader::imageData, blockSize );
m_data->m_socket.send( boost::asio::buffer( &(buf->readable()[0]), blockSize) );
}
void ClientDisplayDriver::imageClose()
{
sendHeader( DisplayDriverServerHeader::imageClose, 0 );
receiveHeader( DisplayDriverServerHeader::imageClose );
m_data->m_socket.close();
}
| 36.211712 | 198 | 0.729942 |
gcodebackups
|
11e8215b2b9ab33162d6c0be79765fb86481e4c3
| 5,260 |
cpp
|
C++
|
examples/freverb.cpp
|
vlazzarini/aurora
|
4990d81a6873beace4a39d6584cc77afbda82cf4
|
[
"BSD-3-Clause"
] | 11 |
2021-11-26T16:23:40.000Z
|
2022-01-19T21:36:35.000Z
|
examples/freverb.cpp
|
vlazzarini/aurora
|
4990d81a6873beace4a39d6584cc77afbda82cf4
|
[
"BSD-3-Clause"
] | null | null | null |
examples/freverb.cpp
|
vlazzarini/aurora
|
4990d81a6873beace4a39d6584cc77afbda82cf4
|
[
"BSD-3-Clause"
] | null | null | null |
// freverb.cpp:
// reverb processing example
// depends on libsndfile
//
// (c) V Lazzarini, 2021
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE
#include "Del.h"
#include <array>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <sndfile.h>
#include <vector>
using namespace Aurora;
template <typename S> inline S scl(S a, S b) { return a * b; }
template <typename S> struct Reverb {
static constexpr S dt[4] = {0.037, 0.031, 0.029, 0.023};
static constexpr S adt[2] = {0.01, 0.0017};
std::array<Del<S, lp_delay>, 4> combs;
std::array<Del<S>, 2> apfs;
Mix<S> mix;
BinOp<S, scl> gain;
std::array<std::vector<S>, 4> mem;
std::array<S, 4> g;
S rvt;
void reverb_time(S rvt) {
std::size_t n = 0;
for (auto &gs : g)
gs = std::pow(.001, dt[n++] / rvt);
}
void lp_freq(S lpf, S fs) {
for (auto &m : mem) {
m[0] = 0;
double c = 2. - std::cos(2 * M_PI * lpf / fs);
m[1] = sqrt(c * c - 1.f) - c;
}
}
void reset(S rvt, S lpf, S fs) {
std::size_t n = 0;
for (auto &obj : combs)
obj.reset(dt[n++], fs);
apfs[0].reset(adt[0], fs);
apfs[1].reset(adt[1], fs);
reverb_time(rvt);
lp_freq(lpf, fs);
}
Reverb(S rvt, S lpf, S fs = def_sr, std::size_t vsize = def_vsize)
: combs({Del<S, lp_delay>(dt[0], fs, vsize),
Del<S, lp_delay>(dt[1], fs, vsize),
Del<S, lp_delay>(dt[2], fs, vsize),
Del<S, lp_delay>(dt[3], fs, vsize)}),
apfs({Del<S>(adt[0], fs, vsize), Del<S>(adt[1], fs, vsize)}),
mix(vsize), gain(vsize), mem({std::vector<S>(2), std::vector<S>(2),
std::vector<S>(2), std::vector<S>(2)}),
g({0, 0, 0, 0}) {
reverb_time(rvt);
lp_freq(lpf, fs);
};
const std::vector<S> &operator()(const std::vector<S> &in, S rmx) {
S ga0 = 0.7;
S ga1 = 0.7;
auto &s = gain(0.25, mix(combs[0](in, 0, g[0], 0, &mem[0]),
combs[1](in, 0, g[1], 0, &mem[1]),
combs[2](in, 0, g[2], 0, &mem[2]),
combs[3](in, 0, g[3], 0, &mem[3])));
return mix(in, gain(rmx, apfs[1](apfs[0](s, 0, ga0, -ga0), 0, ga1, -ga1)));
}
};
int main(int argc, const char **argv) {
SF_INFO sfinfo;
SNDFILE *fpin, *fpout;
int n;
if (argc > 5) {
if ((fpin = sf_open(argv[1], SFM_READ, &sfinfo)) != NULL) {
if (sfinfo.channels < 2) {
fpout = sf_open(argv[2], SFM_WRITE, &sfinfo);
float rvt = atof(argv[3]);
float rmx = atof(argv[4]);
float cf = atof(argv[5]);
std::vector<float> buffer(def_vsize);
Reverb<float> reverb(rvt, cf, sfinfo.samplerate);
do {
std::fill(buffer.begin(), buffer.end(), 0);
n = sf_read_float(fpin, buffer.data(), def_vsize);
if (n) {
buffer.resize(n);
auto &out = reverb(buffer, rmx);
sf_write_float(fpout, out.data(), n);
} else
break;
} while (1);
std::cout << buffer.size() << std::endl;
buffer.resize(def_vsize);
std::cout << buffer.size() << std::endl;
n = sfinfo.samplerate * rvt;
std::fill(buffer.begin(), buffer.end(), 0);
do {
auto &out = reverb(buffer, rmx);
sf_write_float(fpout, out.data(), def_vsize);
n -= def_vsize;
} while (n > 0);
sf_close(fpin);
sf_close(fpout);
return 0;
} else
std::cout << "only mono soundfiles permitted\n";
sf_close(fpin);
return 1;
} else
std::cout << "could not open " << argv[1] << std::endl;
return 1;
}
std::cout << "usage: " << argv[0]
<< " infile outfile reverb_time reverb_amount lpf \n"
<< std::endl;
return -1;
}
| 35.066667 | 80 | 0.585551 |
vlazzarini
|
11e891310680f0eb1585c118d56651afab914aaa
| 11,927 |
cc
|
C++
|
modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.cc
|
berthu/apollo
|
5da49a293e3ad60856448fd61bf6548714cde854
|
[
"Apache-2.0"
] | 22 |
2018-10-10T14:46:32.000Z
|
2022-02-28T12:43:43.000Z
|
modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.cc
|
berthu/apollo
|
5da49a293e3ad60856448fd61bf6548714cde854
|
[
"Apache-2.0"
] | 1 |
2021-03-09T16:46:45.000Z
|
2021-03-09T16:46:45.000Z
|
modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.cc
|
berthu/apollo
|
5da49a293e3ad60856448fd61bf6548714cde854
|
[
"Apache-2.0"
] | 12 |
2018-12-24T02:17:19.000Z
|
2021-12-06T01:54:09.000Z
|
/******************************************************************************
* Copyright 2017 The Apollo 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 "modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.h"
#include "modules/common/log.h"
#include "modules/perception/common/geometry_util.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/obstacle/base/types.h"
namespace apollo {
namespace perception {
PbfKalmanMotionFusion::PbfKalmanMotionFusion() {
initialized_ = false;
name_ = "PbfKalmanMotionFusion";
}
PbfKalmanMotionFusion::~PbfKalmanMotionFusion() {}
void PbfKalmanMotionFusion::Initialize(const Eigen::Vector3d &anchor_point,
const Eigen::Vector3d &velocity) {
belief_anchor_point_ = anchor_point;
belief_velocity_ = velocity;
belief_acceleration_ = Eigen::Vector3d(0, 0, 0);
}
void PbfKalmanMotionFusion::Initialize(
const std::shared_ptr<PbfSensorObject> new_object) {
ACHECK(new_object != nullptr && new_object->object != nullptr)
<< "Initialize PbfKalmanMotionFusion with null sensor object";
if (is_lidar(new_object->sensor_type)) {
belief_anchor_point_ = new_object->object->anchor_point;
belief_velocity_ = new_object->object->velocity;
belief_acceleration_ = Eigen::Vector3d(0, 0, 0);
initialized_ = true;
} else if (is_radar(new_object->sensor_type)) {
belief_anchor_point_ = new_object->object->anchor_point;
belief_velocity_ = new_object->object->velocity;
belief_acceleration_ = Eigen::Vector3d(0, 0, 0);
initialized_ = true;
} else if (is_camera(new_object->sensor_type)) {
belief_anchor_point_ = new_object->object->anchor_point;
belief_velocity_ = new_object->object->velocity;
belief_acceleration_ = Eigen::Vector3d(0, 0, 0);
initialized_ = true;
}
a_matrix_.setIdentity();
a_matrix_(0, 2) = FLAGS_a_matrix_covariance_coeffcient_1;
a_matrix_(1, 3) = FLAGS_a_matrix_covariance_coeffcient_2;
// initialize states to the states of the detected obstacle
posteriori_state_(0) = belief_anchor_point_(0);
posteriori_state_(1) = belief_anchor_point_(1);
posteriori_state_(2) = belief_velocity_(0);
posteriori_state_(3) = belief_velocity_(1);
priori_state_ = posteriori_state_;
q_matrix_.setIdentity();
q_matrix_ *= FLAGS_q_matrix_coefficient_amplifier;
r_matrix_.setIdentity();
r_matrix_.topLeftCorner(2, 2) =
FLAGS_r_matrix_amplifier *
new_object->object->position_uncertainty.topLeftCorner(2, 2);
r_matrix_.block<2, 2>(2, 2) =
FLAGS_r_matrix_amplifier *
new_object->object->velocity_uncertainty.topLeftCorner(2, 2);
p_matrix_.setIdentity();
p_matrix_.topLeftCorner(2, 2) =
FLAGS_p_matrix_amplifier *
new_object->object->position_uncertainty.topLeftCorner(2, 2);
p_matrix_.block<2, 2>(2, 2) =
FLAGS_p_matrix_amplifier *
new_object->object->velocity_uncertainty.topLeftCorner(2, 2);
c_matrix_.setIdentity();
}
void PbfKalmanMotionFusion::Predict(Eigen::Vector3d *anchor_point,
Eigen::Vector3d *velocity,
const double time_diff) {
*anchor_point = belief_anchor_point_ + belief_velocity_ * time_diff;
*velocity = belief_velocity_;
}
void PbfKalmanMotionFusion::UpdateWithObject(
const std::shared_ptr<PbfSensorObject> new_object, const double time_diff) {
ACHECK(new_object != nullptr && new_object->object != nullptr)
<< "update PbfKalmanMotionFusion with null sensor object";
// predict and then correct
a_matrix_.setIdentity();
a_matrix_(0, 2) = time_diff;
a_matrix_(1, 3) = time_diff;
priori_state_ = a_matrix_ * posteriori_state_;
priori_state_(2) += belief_acceleration_(0) * time_diff;
priori_state_(3) += belief_acceleration_(1) * time_diff;
p_matrix_ = ((a_matrix_ * p_matrix_) * a_matrix_.transpose()) + q_matrix_;
p_matrix_.block<2, 2>(2, 0) = Eigen::Matrix2d::Zero();
p_matrix_.block<2, 2>(0, 2) = Eigen::Matrix2d::Zero();
Eigen::Vector3d measured_acceleration = Eigen::Vector3d::Zero();
if (new_object->sensor_type == SensorType::VELODYNE_64) {
belief_anchor_point_ = new_object->object->center;
belief_velocity_ = new_object->object->velocity;
if (GetLidarHistoryLength() >= 3) {
int old_velocity_index = GetLidarHistoryIndex(3);
Eigen::Vector3d old_velocity = history_velocity_[old_velocity_index];
double old_timediff =
GetHistoryTimediff(old_velocity_index, new_object->timestamp);
measured_acceleration = (belief_velocity_ - old_velocity) / old_timediff;
}
if ((GetLidarHistoryLength() >= 3 && GetRadarHistoryLength() >= 3) ||
history_velocity_.size() > 20) {
history_velocity_.pop_front();
history_time_diff_.pop_front();
history_velocity_is_radar_.pop_front();
}
history_velocity_.push_back(belief_velocity_);
history_time_diff_.push_back(new_object->timestamp);
history_velocity_is_radar_.push_back(false);
} else if (new_object->sensor_type == SensorType::RADAR) {
belief_anchor_point_(0) = new_object->object->center(0);
belief_anchor_point_(1) = new_object->object->center(1);
belief_velocity_(0) = new_object->object->velocity(0);
belief_velocity_(1) = new_object->object->velocity(1);
if (GetRadarHistoryLength() >= 3) {
int old_velocity_index = GetRadarHistoryIndex(3);
Eigen::Vector3d old_velocity = history_velocity_[old_velocity_index];
double old_timediff =
GetHistoryTimediff(old_velocity_index, new_object->timestamp);
measured_acceleration = (belief_velocity_ - old_velocity) / old_timediff;
}
if ((GetLidarHistoryLength() >= 3 && GetRadarHistoryLength() >= 3) ||
history_velocity_.size() > 20) {
history_velocity_.pop_front();
history_time_diff_.pop_front();
history_velocity_is_radar_.pop_front();
}
history_velocity_.push_back(belief_velocity_);
history_time_diff_.push_back(new_object->timestamp);
history_velocity_is_radar_.push_back(true);
} else if (new_object->sensor_type == SensorType::CAMERA) {
belief_anchor_point_(0) = new_object->object->center(0);
belief_anchor_point_(1) = new_object->object->center(1);
belief_velocity_(0) = new_object->object->velocity(0);
belief_velocity_(1) = new_object->object->velocity(1);
history_velocity_.push_back(belief_velocity_);
history_time_diff_.push_back(new_object->timestamp);
history_velocity_is_radar_.push_back(false);
} else {
AERROR << "unsupported sensor type for PbfKalmanMotionFusion: "
<< static_cast<int>(new_object->sensor_type);
return;
}
Eigen::Vector4d measurement;
measurement(0) = belief_anchor_point_(0);
measurement(1) = belief_anchor_point_(1);
measurement(2) = belief_velocity_(0);
measurement(3) = belief_velocity_(1);
// r_matrix_ = new_object.uncertainty_mat;
r_matrix_.setIdentity();
r_matrix_.topLeftCorner(2, 2) =
new_object->object->position_uncertainty.topLeftCorner(2, 2);
r_matrix_.block<2, 2>(2, 2) =
new_object->object->velocity_uncertainty.topLeftCorner(2, 2);
// Use lidar when there is no radar yet
if (GetRadarHistoryLength() == 0 && GetLidarHistoryLength() > 1) {
r_matrix_.setIdentity();
r_matrix_ *= 0.01;
}
k_matrix_ =
p_matrix_ * c_matrix_.transpose() *
(c_matrix_ * p_matrix_ * c_matrix_.transpose() + r_matrix_).inverse();
Eigen::Vector4d predict_measurement(priori_state_(0), priori_state_(1),
priori_state_(2), priori_state_(3));
posteriori_state_ =
priori_state_ + k_matrix_ * (measurement - predict_measurement);
p_matrix_ =
(Eigen::Matrix4d::Identity() - k_matrix_ * c_matrix_) * p_matrix_ *
(Eigen::Matrix4d::Identity() - k_matrix_ * c_matrix_).transpose() +
k_matrix_ * r_matrix_ * k_matrix_.transpose();
belief_anchor_point_(0) = posteriori_state_(0);
belief_anchor_point_(1) = posteriori_state_(1);
belief_velocity_(0) = posteriori_state_(2);
belief_velocity_(1) = posteriori_state_(3);
UpdateAcceleration(measured_acceleration);
if (belief_velocity_.head(2).norm() < 0.05) {
belief_velocity_ = Eigen::Vector3d(0, 0, 0);
}
}
void PbfKalmanMotionFusion::UpdateWithoutObject(const double time_diff) {
belief_anchor_point_ = belief_anchor_point_ + belief_velocity_ * time_diff;
}
void PbfKalmanMotionFusion::GetState(Eigen::Vector3d *anchor_point,
Eigen::Vector3d *velocity) {
*anchor_point = belief_anchor_point_;
*velocity = belief_velocity_;
}
void PbfKalmanMotionFusion::SetState(const Eigen::Vector3d &anchor_point,
const Eigen::Vector3d &velocity) {
belief_anchor_point_ = anchor_point;
belief_velocity_ = velocity;
}
int PbfKalmanMotionFusion::GetRadarHistoryLength() {
int history_length = 0;
for (size_t i = 0; i < history_velocity_is_radar_.size(); ++i) {
if (history_velocity_is_radar_[i]) {
history_length++;
}
}
return history_length;
}
int PbfKalmanMotionFusion::GetLidarHistoryLength() {
int history_length = history_velocity_is_radar_.size();
history_length -= GetRadarHistoryLength();
return history_length;
}
int PbfKalmanMotionFusion::GetLidarHistoryIndex(const int &history_seq) {
int history_index = 0;
int history_count = 0;
for (size_t i = 1; i <= history_velocity_is_radar_.size(); ++i) {
history_index = history_velocity_is_radar_.size() - i;
if (!history_velocity_is_radar_[history_index]) {
history_count++;
}
if (history_count == history_seq) {
break;
}
}
return history_index;
}
int PbfKalmanMotionFusion::GetRadarHistoryIndex(const int &history_seq) {
int history_index = 0;
int history_count = 0;
for (size_t i = 1; i <= history_velocity_is_radar_.size(); ++i) {
history_index = history_velocity_is_radar_.size() - i;
if (history_velocity_is_radar_[history_index]) {
history_count++;
}
if (history_count == history_seq) {
break;
}
}
return history_index;
}
double PbfKalmanMotionFusion::GetHistoryTimediff(
const int &history_index, const double ¤t_timestamp) {
double history_timestamp = history_time_diff_[history_index];
double history_timediff = current_timestamp - history_timestamp;
return history_timediff;
}
void PbfKalmanMotionFusion::UpdateAcceleration(
const Eigen::VectorXd &measured_acceleration) {
Eigen::Matrix2d mat_c = Eigen::Matrix2d::Identity();
Eigen::Matrix2d mat_q = Eigen::Matrix2d::Identity() * 0.5;
Eigen::Matrix2d mat_k =
p_matrix_.block<2, 2>(2, 2) * mat_c.transpose() *
(mat_c * p_matrix_.block<2, 2>(2, 2) * mat_c.transpose() + mat_q)
.inverse();
Eigen::Vector2d acceleration_gain =
mat_k *
(measured_acceleration.head(2) - mat_c * belief_acceleration_.head(2));
// breakdown
float breakdown_threshold = 2;
if (acceleration_gain.norm() > breakdown_threshold) {
acceleration_gain.normalize();
acceleration_gain *= breakdown_threshold;
}
belief_acceleration_(0) += acceleration_gain(0);
belief_acceleration_(1) += acceleration_gain(1);
}
} // namespace perception
} // namespace apollo
| 38.598706 | 93 | 0.707722 |
berthu
|
11e89ae4be449dc35bba4162b7bcf602238a19b9
| 1,469 |
cpp
|
C++
|
Libraries/LibC/mman.cpp
|
ZKing1000/serenity
|
cc68654a44be00deb5edf3b2d2319a663012f015
|
[
"BSD-2-Clause"
] | 3 |
2019-09-22T11:38:04.000Z
|
2020-01-21T19:09:27.000Z
|
Libraries/LibC/mman.cpp
|
ZKing1000/serenity
|
cc68654a44be00deb5edf3b2d2319a663012f015
|
[
"BSD-2-Clause"
] | 8 |
2019-08-25T12:52:40.000Z
|
2019-09-08T14:46:11.000Z
|
Libraries/LibC/mman.cpp
|
ZKing1000/serenity
|
cc68654a44be00deb5edf3b2d2319a663012f015
|
[
"BSD-2-Clause"
] | 1 |
2021-08-03T13:04:49.000Z
|
2021-08-03T13:04:49.000Z
|
#include <Kernel/Syscall.h>
#include <errno.h>
#include <mman.h>
#include <stdio.h>
extern "C" {
void* mmap(void* addr, size_t size, int prot, int flags, int fd, off_t offset)
{
Syscall::SC_mmap_params params { (u32)addr, size, prot, flags, fd, offset, nullptr };
int rc = syscall(SC_mmap, ¶ms);
if (rc < 0 && -rc < EMAXERRNO) {
errno = -rc;
return (void*)-1;
}
return (void*)rc;
}
void* mmap_with_name(void* addr, size_t size, int prot, int flags, int fd, off_t offset, const char* name)
{
Syscall::SC_mmap_params params { (u32)addr, size, prot, flags, fd, offset, name };
int rc = syscall(SC_mmap, ¶ms);
if (rc < 0 && -rc < EMAXERRNO) {
errno = -rc;
return (void*)-1;
}
return (void*)rc;
}
int munmap(void* addr, size_t size)
{
int rc = syscall(SC_munmap, addr, size);
__RETURN_WITH_ERRNO(rc, rc, -1);
}
int mprotect(void* addr, size_t size, int prot)
{
int rc = syscall(SC_mprotect, addr, size, prot);
__RETURN_WITH_ERRNO(rc, rc, -1);
}
int set_mmap_name(void* addr, size_t size, const char* name)
{
int rc = syscall(SC_set_mmap_name, addr, size, name);
__RETURN_WITH_ERRNO(rc, rc, -1);
}
int shm_open(const char* name, int flags, mode_t mode)
{
int rc = syscall(SC_shm_open, name, flags, mode);
__RETURN_WITH_ERRNO(rc, rc, -1);
}
int shm_unlink(const char* name)
{
int rc = syscall(SC_unlink, name);
__RETURN_WITH_ERRNO(rc, rc, -1);
}
}
| 24.483333 | 106 | 0.632403 |
ZKing1000
|
11eadbad492afe970e53ec4cb9da196688a0abca
| 27,642 |
cpp
|
C++
|
OpenSim/Actuators/Schutte1993Muscle_Deprecated.cpp
|
MariaHammer/opensim-core_HaeufleMuscle
|
96257e9449d9ac430bbb54e56cd13aaebeee1242
|
[
"Apache-2.0"
] | 532 |
2015-03-13T18:51:10.000Z
|
2022-03-27T08:08:29.000Z
|
OpenSim/Actuators/Schutte1993Muscle_Deprecated.cpp
|
MariaHammer/opensim-core_HaeufleMuscle
|
96257e9449d9ac430bbb54e56cd13aaebeee1242
|
[
"Apache-2.0"
] | 2,701 |
2015-01-03T21:33:34.000Z
|
2022-03-30T07:13:41.000Z
|
OpenSim/Actuators/Schutte1993Muscle_Deprecated.cpp
|
MariaHammer/opensim-core_HaeufleMuscle
|
96257e9449d9ac430bbb54e56cd13aaebeee1242
|
[
"Apache-2.0"
] | 271 |
2015-02-16T23:25:29.000Z
|
2022-03-30T20:12:17.000Z
|
/* -------------------------------------------------------------------------- *
* OpenSim: Schutte1993Muscle_Deprecated.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Peter Loan, Jeffrey A. Reinbolt *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Schutte1993Muscle_Deprecated.h"
#include <OpenSim/Common/SimmSpline.h>
#include <OpenSim/Common/SimmMacros.h>
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
Schutte1993Muscle_Deprecated::Schutte1993Muscle_Deprecated()
{
constructProperties();
}
//_____________________________________________________________________________
/**
* Constructor.
*/
Schutte1993Muscle_Deprecated::Schutte1993Muscle_Deprecated
(const std::string& aName, double aMaxIsometricForce,
double aOptimalFiberLength, double aTendonSlackLength,
double aPennationAngle)
{
constructProperties();
setName(aName);
setMaxIsometricForce(aMaxIsometricForce);
setOptimalFiberLength(aOptimalFiberLength);
setTendonSlackLength(aTendonSlackLength);
setPennationAngleAtOptimalFiberLength(aPennationAngle);
}
//=============================================================================
// CONSTRUCTION METHODS
//=============================================================================
//_____________________________________________________________________________
// Allocate and initialize properties.
void Schutte1993Muscle_Deprecated::constructProperties()
{
constructProperty_time_scale(0.1);
constructProperty_activation1(7.667);
constructProperty_activation2(1.459854);
constructProperty_damping(0.1);
int tendonForceLengthCurvePoints = 17;
double tendonForceLengthCurveX[] = {-10.00000000, -0.00200000, -0.00100000, 0.00000000, 0.00131000, 0.00281000, 0.00431000, 0.00581000, 0.00731000, 0.00881000, 0.01030000, 0.01180000, 0.01230000, 9.20000000, 9.20100000, 9.20200000, 20.00000000};
double tendonForceLengthCurveY[] = {0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.01080000, 0.02570000, 0.04350000, 0.06520000, 0.09150000, 0.12300000, 0.16100000, 0.20800000, 0.22700000, 345.00000000, 345.00000000, 345.00000000, 345.00000000};
SimmSpline tendonForceLengthCurve
(tendonForceLengthCurvePoints, tendonForceLengthCurveX,
tendonForceLengthCurveY);
constructProperty_tendon_force_length_curve(tendonForceLengthCurve);
int activeForceLengthCurvePoints = 21;
double activeForceLengthCurveX[] = {-5.30769200, -4.30769200, -1.92307700, -0.88461500, -0.26923100, 0.23076900, 0.46153800, 0.52725000, 0.62875000, 0.71875000, 0.86125000, 1.04500000, 1.21750000, 1.43875000, 1.50000000, 1.61538500, 2.00000000, 2.96153800, 3.69230800, 5.46153800, 9.90190200};
double activeForceLengthCurveY[] = {0.01218800, 0.02189900, 0.03646600, 0.05249300, 0.07531200, 0.11415800, 0.15785900, 0.22666700, 0.63666700, 0.85666700, 0.95000000, 0.99333300, 0.77000000, 0.24666700, 0.19382100, 0.13325200, 0.07268300, 0.04441700, 0.03634100, 0.02189900, 0.00733200};
SimmSpline activeForceLengthCurve
(activeForceLengthCurvePoints, activeForceLengthCurveX,
activeForceLengthCurveY);
constructProperty_active_force_length_curve(activeForceLengthCurve);
int passiveForceLengthCurvePoints = 13;
double passiveForceLengthCurveX[] = {-5.00000000, 0.99800000, 0.99900000, 1.00000000, 1.10000000, 1.20000000, 1.30000000, 1.40000000, 1.50000000, 1.60000000, 1.60100000, 1.60200000, 5.00000000};
double passiveForceLengthCurveY[] = {0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.03500000, 0.12000000, 0.26000000, 0.55000000, 1.17000000, 2.00000000, 2.00000000, 2.00000000, 2.00000000};
SimmSpline passiveForceLengthCurve
(passiveForceLengthCurvePoints, passiveForceLengthCurveX,
passiveForceLengthCurveY);
constructProperty_passive_force_length_curve(passiveForceLengthCurve);
}
//_____________________________________________________________________________
/**
* Perform some set up functions that happen after the
* object has been deserialized or copied.
*
* @param aModel model containing this Schutte1993Muscle_Deprecated.
*/
void Schutte1993Muscle_Deprecated::extendConnectToModel(Model& aModel)
{
// Base class
Super::extendConnectToModel(aModel);
}
//=============================================================================
// GET
//=============================================================================
//-----------------------------------------------------------------------------
// TIME SCALE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Set the scale factor for normalizing time.
*
* @param aTimeScale The scale factor for normalizing time.
* @return Whether the scale factor was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::setTimeScale(double aTimeScale)
{
set_time_scale(aTimeScale);
return true;
}
//-----------------------------------------------------------------------------
// ACTIVATION 1
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Set the time constant of ramping up of muscle force.
*
* @param aActivation1 The time constant of ramping up of muscle force.
* @return Whether the time constant was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::setActivation1(double aActivation1)
{
set_activation1(aActivation1);
return true;
}
//-----------------------------------------------------------------------------
// ACTIVATION 2
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Set the time constant of ramping up and ramping down of muscle force.
*
* @param aActivation1 The time constant of ramping up and ramping down of muscle force.
* @return Whether the time constant was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::setActivation2(double aActivation2)
{
set_activation2(aActivation2);
return true;
}
//-----------------------------------------------------------------------------
// DAMPING
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Set the damping factor related to maximum contraction velocity.
*
* @param aDamping The damping factor related to maximum contraction velocity.
* @return Whether the damping factor was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::setDamping(double aDamping)
{
set_damping(aDamping);
return true;
}
//_____________________________________________________________________________
/**
* Compute the actuation for the muscle. This function assumes
* that computeDerivatives has already been called.
*/
double Schutte1993Muscle_Deprecated::computeActuation(const SimTK::State& s) const
{
double tendonForce;
double passiveForce;
double activeForce;
double activationDeriv;
double fiberLengthDeriv;
double norm_tendon_length, ca;
double norm_muscle_tendon_length, pennation_angle;
double excitation = getExcitation(s);
/* Normalize the muscle states */
double activation = getActivation(s);
double normFiberLength = getFiberLength(s) / _optimalFiberLength;
/* Compute normalized muscle state derivatives */
if (excitation >= activation)
activationDeriv = (excitation - activation) * (get_activation1() * excitation + get_activation2());
else
activationDeriv = (excitation - activation) * get_activation2();
pennation_angle = calcPennation(normFiberLength, 1.0, _pennationAngleAtOptimal);
ca = cos(pennation_angle);
norm_muscle_tendon_length = getLength(s) / _optimalFiberLength;
norm_tendon_length = norm_muscle_tendon_length - normFiberLength * ca;
tendonForce = calcTendonForce(s,norm_tendon_length);
passiveForce = calcNonzeroPassiveForce(s,normFiberLength, 0.0);
activeForce = getActiveForceLengthCurve().calcValue(SimTK::Vector(1, normFiberLength) );
if (activeForce < 0.0) activeForce = 0.0;
/* If pennation equals 90 degrees, fiber length equals muscle width and fiber
* velocity goes to zero. Pennation will stay at 90 until tendon starts to
* pull, then "stiff tendon" approximation is used to calculate approximate
* fiber velocity.
*/
if (EQUAL_WITHIN_ERROR(ca, 0.0)) {
if (EQUAL_WITHIN_ERROR(tendonForce, 0.0)) {
fiberLengthDeriv = 0.0;;
} else {
double h = norm_muscle_tendon_length - _tendonSlackLength;
double w = _optimalFiberLength * sin(_pennationAngleAtOptimal);
double new_fiber_length = sqrt(h*h + w*w) / _optimalFiberLength;
double new_pennation_angle = calcPennation(new_fiber_length, 1.0, _pennationAngleAtOptimal);
double new_ca = cos(new_pennation_angle);
fiberLengthDeriv = getLengtheningSpeed(s) * get_time_scale() / _optimalFiberLength * new_ca;
}
} else {
double velocity_dependent_force = tendonForce / ca - passiveForce;
if (velocity_dependent_force < 0.0) velocity_dependent_force = 0.0;
fiberLengthDeriv = calcFiberVelocity(s,activation, activeForce, velocity_dependent_force);
}
/* Un-normalize the muscle state derivatives and forces. */
setActivationDeriv(s, activationDeriv / get_time_scale());
setFiberLengthDeriv(s, fiberLengthDeriv * _optimalFiberLength / get_time_scale());
tendonForce = tendonForce * _maxIsometricForce;
setActuation(s, tendonForce);
setTendonForce(s, tendonForce);
setPassiveForce(s, passiveForce * _maxIsometricForce);
return( tendonForce );
}
//=============================================================================
// GET AND SET
//=============================================================================
//_____________________________________________________________________________
/**
* Get the active force-length curve.
*
* @return Pointer to the active force-length curve (Function).
*/
const Function& Schutte1993Muscle_Deprecated::getActiveForceLengthCurve() const
{
return get_active_force_length_curve();
}
//_____________________________________________________________________________
/**
* Set the active force-length curve.
*
* @param aActiveForceLengthCurve Pointer to an active force-length curve (Function).
* @return Whether active force-length curve was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::
setActiveForceLengthCurve(const Function& aActiveForceLengthCurve)
{
set_active_force_length_curve(aActiveForceLengthCurve);
return true;
}
//_____________________________________________________________________________
/**
* Get the passive force-length curve.
*
* @return Pointer to the passive force-length curve (Function).
*/
const Function& Schutte1993Muscle_Deprecated::getPassiveForceLengthCurve() const
{
return get_passive_force_length_curve();
}
//_____________________________________________________________________________
/**
* Get the passive force-length curve.
*
* @param aPassiveForceLengthCurve Pointer to a passive force-length curve (Function).
* @return Whether passive force-length curve was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::
setPassiveForceLengthCurve(const Function& aPassiveForceLengthCurve)
{
set_passive_force_length_curve(aPassiveForceLengthCurve);
return true;
}
//_____________________________________________________________________________
/**
* Get the tendon force-length curve.
*
* @return Pointer to the tendon force-length curve (Function).
*/
const Function& Schutte1993Muscle_Deprecated::getTendonForceLengthCurve() const
{
return get_tendon_force_length_curve();
}
//_____________________________________________________________________________
/**
* Get the tendon force-length curve.
*
* @param aTendonForceLengthCurve Pointer to a tendon force-length curve (Function).
* @return Whether tendon force-length curve was successfully changed.
*/
bool Schutte1993Muscle_Deprecated::
setTendonForceLengthCurve(const Function& aTendonForceLengthCurve)
{
set_tendon_force_length_curve(aTendonForceLengthCurve);
return true;
}
//_____________________________________________________________________________
/**
* Calculate the force in tendon by finding tendon strain
* and using it to interpolate the tendon force-length curve.
*
* @param aNormTendonLength Normalized length of the tendon.
* @return The force in the tendon.
*/
double Schutte1993Muscle_Deprecated::calcTendonForce(const SimTK::State& s, double aNormTendonLength) const
{
double tendon_force;
double norm_resting_length = _tendonSlackLength / _optimalFiberLength;
double tendon_strain = (aNormTendonLength - norm_resting_length) / norm_resting_length;
if (tendon_strain < 0.0)
tendon_force = 0.0;
else
tendon_force = getTendonForceLengthCurve().calcValue(SimTK::Vector(1, tendon_strain));
return tendon_force;
}
//_____________________________________________________________________________
/**
* calcNonzeroPassiveForce: written by Chris Raasch and Lisa Schutte.
* This function calculates the passive force in the muscle fibers using
* an exponential instead of cubic splines. This results in non-zero passive
* force for any fiber length (and thus prevents "slack" muscle/tendon problems).
* It includes the contribution of an exponential passive force-length curve
* (which equals 1.0 at norm_fiber_length = 1.5) as well as the damping effects
* due to contraction velocity. It should someday be replaced by a new
* passive-force spline in the muscle input file, but for now it includes
* constants as Chris and Lisa derived them for their specific muscle model.
*
* @param aNormTendonLength Normalized length of the tendon.
* @return The passive force in the muscle fibers.
*/
double Schutte1993Muscle_Deprecated::calcNonzeroPassiveForce(const SimTK::State& s, double aNormFiberLength, double aNormFiberVelocity) const
{
double flcomponent = 0.0;
if (getProperty_passive_force_length_curve().getValueIsDefault())
flcomponent = exp(8.0*(aNormFiberLength - 1.0)) / exp(4.0);
else
flcomponent = getPassiveForceLengthCurve().calcValue(SimTK::Vector(1, aNormFiberLength) );
return flcomponent + get_damping() * aNormFiberVelocity;
}
//_________ ____________________________________________________________________
/**
* calcFiberVelocity: written by Chris Raasch and Lisa Schutte.
* This function calculates the fiber velocity using an inverse
* muscle force-velocity relationship with damping. It should
* someday be replaced by a new force-velocity spline in the muscle input
* file, but for now it includes constants as Chris and Lisa derived them
* for their specific muscle model.
*
* @param aActivation Activation of the muscle.
* @param aActiveForce Active force in the muscle fibers.
* @param aVelocityDependentForce Force value that depends on fiber velocity.
* @return The velocity of the muscle fibers.
*/
double Schutte1993Muscle_Deprecated::calcFiberVelocity(const SimTK::State& s, double aActivation, double aActiveForce, double aVelocityDependentForce) const
{
double b, c, fiber_velocity;
double kv = 0.15, slope_k = 0.13, fmax = 1.4;
if (aVelocityDependentForce < -get_damping())
{
fiber_velocity = aVelocityDependentForce / get_damping();
}
else if (aVelocityDependentForce < aActivation * aActiveForce)
{
c = kv * (aVelocityDependentForce - aActivation * aActiveForce) / get_damping();
b = -kv * (aVelocityDependentForce / kv + aActivation * aActiveForce +
get_damping()) / get_damping();
fiber_velocity = (-b - sqrt(b * b - 4 * c)) / 2.0;
}
else
{
c = -(slope_k * kv / ((get_damping() * (kv + 1)))) *
(aVelocityDependentForce - aActivation * aActiveForce);
b = -(aVelocityDependentForce / get_damping()
-fmax * aActivation * aActiveForce / get_damping() - slope_k * kv / (kv + 1));
fiber_velocity = (-b + sqrt(b * b - 4 * c)) / 2.0;
}
return fiber_velocity;
}
//_____________________________________________________________________________
/**
* computeIsometricForce: this function finds the force in a muscle, assuming
* static equilibrium. Using the total muscle-tendon length, it finds the
* fiber and tendon lengths so that the forces in each match. This routine
* takes pennation angle into account, so its definition of static equilibrium
* is when tendon_force = fiber_force * cos(pennation_angle). This function
* will modify the object's values for length, fiberLength,
* and passiveForce.
*
* @param aActivation Activation of the muscle.
* @return The isometric force in the muscle.
*/
double Schutte1993Muscle_Deprecated::computeIsometricForce(SimTK::State& s, double aActivation) const
{
#define MAX_ITERATIONS 100
#define ERROR_LIMIT 0.01
int i;
double length,tendon_length, fiber_force, tmp_fiber_length, min_tendon_stiffness;
double cos_factor, fiber_stiffness;
double old_fiber_length{SimTK::NaN}, length_change, tendon_stiffness, percent;
double error_force = 0.0, old_error_force, tendon_force, tendon_strain;
double passiveForce, activeForce, tendonForce, fiberLength;
if (_optimalFiberLength < ROUNDOFF_ERROR) {
setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, 0.0);
setPassiveForce(s, 0.0);
setActuation(s, 0.0);
setTendonForce(s, 0.0);
return 0.0;
}
length = getLength(s);
// Make first guess of fiber and tendon lengths. Make fiber length equal to
// optimal_fiber_length so that you start in the middle of the active+passive
// force-length curve. Muscle_width is the width, or thickness, of the
// muscle-tendon unit. It is the shortest allowable fiber length because if
// the muscle-tendon length is very short, the pennation angle will be 90
// degrees and the fibers will be vertical (assuming the tendon is horizontal).
// When this happens, the fibers are as long as the muscle is wide.
// If the resting tendon length is zero, then set the fiber length equal to
// the muscle tendon length / cosine_factor, and find its force directly.
double muscle_width = _optimalFiberLength * sin(_pennationAngleAtOptimal);
if (_tendonSlackLength < ROUNDOFF_ERROR) {
tendon_length = 0.0;
cos_factor = cos(atan(muscle_width / length));
fiberLength = length / cos_factor;
activeForce = getActiveForceLengthCurve().calcValue(SimTK::Vector(1, fiberLength / _optimalFiberLength)) * aActivation * _maxIsometricForce;
if (activeForce < 0.0) activeForce = 0.0;
passiveForce = calcNonzeroPassiveForce(s, fiberLength / _optimalFiberLength, 0.0) * _maxIsometricForce;
setPassiveForce(s, passiveForce );
setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, fiberLength);
tendonForce = (activeForce + passiveForce) * cos_factor;
setActuation(s, tendonForce);
setTendonForce(s, tendonForce);
return tendonForce;
} else if (length < _tendonSlackLength) {
setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, muscle_width);
setPassiveForce(s, 0.0);
setActuation(s, 0.0);
setTendonForce(s, 0.0);
return 0.0;
} else {
fiberLength = _optimalFiberLength;
cos_factor = cos(calcPennation(fiberLength, _optimalFiberLength, _pennationAngleAtOptimal));
tendon_length = length - fiberLength * cos_factor;
/* Check to make sure tendon is not shorter than its slack length. If it
* is, set the length to its slack length and re-compute fiber length.
*/
if (tendon_length < _tendonSlackLength) {
tendon_length = _tendonSlackLength;
cos_factor = cos(atan(muscle_width / (length - tendon_length)));
fiberLength = (length - tendon_length) / cos_factor;
if (fiberLength < muscle_width) fiberLength = muscle_width;
}
}
// Muscle-tendon force is found using an iterative method. First, you guess
// the length of the muscle fibers and the length of the tendon, and
// calculate their respective forces. If the forces match (are within
// ERROR_LIMIT of each other), stop; else change the length guesses based
// on the error and try again.
for (i = 0; i < MAX_ITERATIONS; i++) {
activeForce = getActiveForceLengthCurve().calcValue(SimTK::Vector(1, fiberLength / _optimalFiberLength)) * aActivation;
if (activeForce < 0.0) activeForce = 0.0;
passiveForce = calcNonzeroPassiveForce(s, fiberLength / _optimalFiberLength, 0.0);
if (passiveForce < 0.0) passiveForce = 0.0;
fiber_force = (activeForce + passiveForce ) * _maxIsometricForce * cos_factor;
tendon_strain = (tendon_length / _tendonSlackLength - 1.0);
if (tendon_strain < 0.0)
tendon_force = 0.0;
else
tendon_force = getTendonForceLengthCurve().calcValue(SimTK::Vector(1, tendon_strain)) * _maxIsometricForce;
setActuation(s, tendon_force);
setTendonForce(s, tendon_force);
old_error_force = error_force;
error_force = tendon_force - fiber_force;
if (DABS(error_force) <= ERROR_LIMIT) // muscle-tendon force found!
break;
if (i == 0)
old_error_force = error_force;
if (DSIGN(error_force) != DSIGN(old_error_force)) {
percent = DABS(error_force) / (DABS(error_force) + DABS(old_error_force));
tmp_fiber_length = old_fiber_length;
old_fiber_length = fiberLength;
fiberLength += percent * (tmp_fiber_length - fiberLength);
} else {
// Estimate the stiffnesses of the tendon and the fibers. If tendon
// stiffness is too low, then the next length guess will overshoot
// the equilibrium point. So we artificially raise it using the
// normalized muscle force. (_activeForce+_passiveForce) is the
// normalized force for the current fiber length, and we assume that
// the equilibrium length is close to this current length. So we want
// to get force = (_activeForce+_passiveForce) from the tendon as well.
// We hope this will happen by setting the tendon stiffness to
// (_activeForce+_passiveForce) times its maximum stiffness.
double tendon_elastic_modulus = 1200.0;
double tendon_max_stress = 32.0;
tendon_stiffness = getTendonForceLengthCurve().calcValue(SimTK::Vector(1, tendon_strain)) *
_maxIsometricForce / _tendonSlackLength;
min_tendon_stiffness = (activeForce + passiveForce) *
tendon_elastic_modulus * _maxIsometricForce /
(tendon_max_stress * _tendonSlackLength);
if (tendon_stiffness < min_tendon_stiffness)
tendon_stiffness = min_tendon_stiffness;
fiber_stiffness = _maxIsometricForce / _optimalFiberLength *
(getActiveForceLengthCurve().calcValue(SimTK::Vector(1, fiberLength / _optimalFiberLength)) +
calcNonzeroPassiveForce(s, fiberLength / _optimalFiberLength, 0.0));
// determine how much the fiber and tendon lengths have to
// change to make the error_force zero. But don't let the
// length change exceed half the optimal fiber length because
// that's too big a change to make all at once.
length_change = fabs(error_force/(fiber_stiffness / cos_factor + tendon_stiffness));
if (fabs(length_change / _optimalFiberLength) > 0.5)
length_change = 0.5 * _optimalFiberLength;
// now change the fiber length depending on the sign of the error
// and the sign of the fiber stiffness (which equals the sign of
// the slope of the muscle's force-length curve).
old_fiber_length = fiberLength;
if (error_force > 0.0)
fiberLength += length_change;
else
fiberLength -= length_change;
}
cos_factor = cos(calcPennation(fiberLength, _optimalFiberLength, _pennationAngleAtOptimal));
tendon_length = length - fiberLength * cos_factor;
// Check to make sure tendon is not shorter than its slack length. If it is,
// set the length to its slack length and re-compute fiber length.
if (tendon_length < _tendonSlackLength) {
tendon_length = _tendonSlackLength;
cos_factor = cos(atan(muscle_width / (length - tendon_length)));
fiberLength = (length - tendon_length) / cos_factor;
}
}
setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, fiberLength);
setPassiveForce(s, passiveForce * _maxIsometricForce);
return tendon_force;
}
// Satisfy the ActivationFiberLengthMuscle_Deprecated interface
double Schutte1993Muscle_Deprecated::calcPassiveForce(const SimTK::State& s, double aNormFiberLength) const
{
return calcNonzeroPassiveForce(s,aNormFiberLength, 0.0);
}
double Schutte1993Muscle_Deprecated::calcActiveForce(const SimTK::State& s, double aNormFiberLength) const
{
return getActiveForceLengthCurve().calcValue(SimTK::Vector(1, aNormFiberLength) );
}
| 44.015924 | 313 | 0.678714 |
MariaHammer
|
11ec6438742eeb4119f26905fc2b29bcf4313a3c
| 10,387 |
cpp
|
C++
|
src/ZeroHalfSystem.cpp
|
DanielKowalczyk1984/PM
|
0738c662f7bf95792c86f493525d868d7b7346d8
|
[
"MIT"
] | null | null | null |
src/ZeroHalfSystem.cpp
|
DanielKowalczyk1984/PM
|
0738c662f7bf95792c86f493525d868d7b7346d8
|
[
"MIT"
] | null | null | null |
src/ZeroHalfSystem.cpp
|
DanielKowalczyk1984/PM
|
0738c662f7bf95792c86f493525d868d7b7346d8
|
[
"MIT"
] | null | null | null |
// MIT License
// Copyright (c) 2021 Daniel Kowalczyk
// 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 "ZeroHalfSystem.hpp"
#include <boost/container_hash/extensions.hpp> // for hash_combine
#include <boost/dynamic_bitset/dynamic_bitset.hpp> // for dynamic_bitset
#include <cmath> // for ceil
#include <cstddef> // for size_t
#include <limits> // for numeric_limits
#include <range/v3/algorithm/any_of.hpp> // for any_of, any_of_fn
#include <range/v3/algorithm/for_each.hpp> // for for_each, for_...
#include <range/v3/algorithm/min.hpp> // for min, min_fn
#include <range/v3/numeric/inner_product.hpp> // for inner_product
#include <range/v3/range/conversion.hpp> // for to, operator|
#include <range/v3/utility/swap.hpp> // for swap
#include <range/v3/view/all.hpp> // for all_t, all_fn
#include <range/v3/view/drop.hpp> // for drop_view, drop
#include <range/v3/view/enumerate.hpp> // for enumerate_fn
#include <range/v3/view/iota.hpp> // for iota_view, ints
#include <range/v3/view/join.hpp> // for join_view, joi...
#include <range/v3/view/stride.hpp> // for stride_view
#include <range/v3/view/transform.hpp> // for transform_view
#include <range/v3/view/view.hpp> // for operator|, vie...
#include <range/v3/view/zip.hpp> // for zip_view, zip
#include <range/v3/view/zip_with.hpp> // for iter_zip_with_...
#include <unordered_map> // for unordered_map
#include <vector> // for vector, allocator
namespace vs = ranges::views;
ZeroHalfSystem::ZeroHalfSystem(const MatrixDouble& A,
[[maybe_unused]] const VectorDouble& _b,
const VectorDouble& _x)
: x_star(_x),
row_index(A.size(), boost::dynamic_bitset{A.size()}) {
// auto min_elem =
// ranges::min(ranges::min(ranges::views::transform(
// A, [](auto& row) { return ranges::min(row); })),
// ranges::min(_b));
// auto add_elem = 0.0;
// if (min_elem < 0.0) {
// add_elem = std::ceil(-min_elem / HALF) * HALF;
// }
// auto func_add_value = [&add_elem](auto& it) -> int {
// return static_cast<int>(add_elem + it) % 2;
// };
// A_bar = vs::transform(A,
// [&func_add_value](auto& row) {
// return vs::transform(row, func_add_value) |
// ranges::to<std::vector>();
// }) |
// ranges::to<std::vector>();
// b_bar = vs::transform(_b, func_add_value) | ranges::to<std::vector>;
// auto tmp = vs::transform(
// A, [&_x](auto& row) { return ranges::inner_product(row, _x, 0.0); });
// slack =
// vs::zip_with([](auto lhs, auto rhs) { return lhs - rhs; }, _b, tmp) |
// ranges::to<std::vector>();
// for (auto&& [i, set] : row_index | vs::enumerate) {
// set[i] = true;
// }
// reduce_system();
}
void ZeroHalfSystem::remove_row(size_t _row) {
ranges::swap(A_bar[_row], A_bar[nb_rows - 1]);
ranges::swap(slack[_row], slack[nb_rows - 1]);
ranges::swap(b_bar[_row], b_bar[nb_rows - 1]);
ranges::swap(row_index[_row], row_index[nb_rows - 1]);
--nb_rows;
// A_bar.pop_back();
}
void ZeroHalfSystem::remove_col(size_t _col) {
for (auto& it : A_bar) {
ranges::swap(it[_col], it[nb_columns - 1]);
}
ranges::swap(x_star[_col], x_star[nb_columns - 1]);
--nb_columns;
}
void ZeroHalfSystem::reduce_system() {
// auto col = 0UL;
// /** Rule 1 */
// while (col < nb_columns) {
// if (x_star[col] < EPS) {
// remove_col(col);
// } else {
// ++col;
// }
// }
// /** Rule 2 */
// auto row = 0UL;
// while (row < nb_rows) {
// auto any_one =
// ranges::any_of(A_bar[row], [](auto& a) { return a == 1; }) ||
// (b_bar[row] == 1);
// if (any_one) {
// ++row;
// } else {
// remove_row(row);
// }
// }
// /** Rule 3,4,5 */
// std::unordered_map<size_t, int> column_dict{};
// col = 0UL;
// while (col < nb_columns) {
// size_t key = 0UL;
// int counter{};
// int last_one{-1};
// for (auto&& [r, a] : A_bar | vs::enumerate) {
// if (a[col]) {
// boost::hash_combine(key, r);
// ++counter;
// last_one = static_cast<int>(r);
// }
// }
// if (counter == 0) {
// remove_col(col);
// } else if (counter == 1) {
// slack[last_one] += x_star[col];
// remove_col(col);
// } else if (column_dict.find(key) != column_dict.end()) {
// auto aux = column_dict[key];
// x_star[aux] += x_star[col];
// remove_col(col);
// } else {
// column_dict[key] = col;
// ++col;
// }
// }
// /** Rule 6 */
// row = 0UL;
// while (row < nb_rows) {
// if (slack[row] >= 1.0) {
// remove_row(row);
// } else {
// ++row;
// }
// }
// /** Use hash combine to detect equivalent columns */
// /** Rule 7 Dekoster et al. */
// std::unordered_map<size_t, int> row_dict;
// row = 0UL;
// while (row < nb_rows) {
// size_t key = 0UL;
// ranges::for_each(A_bar[row], [&key](auto& it_col) {
// if (it_col) {
// boost::hash_combine(key, it_col);
// }
// });
// if (b_bar[row]) {
// boost::hash_combine(key, nb_columns);
// }
// if (row_dict.find(key) == row_dict.end()) {
// row_dict[key] = row;
// ++row;
// } else {
// auto tmp = row_dict[key];
// if (slack[tmp] < slack[row]) {
// remove_row(row);
// } else {
// ranges::swap(row_index[tmp], row_index[row]);
// ranges::swap(slack[tmp], slack[row]);
// remove_row(row);
// }
// }
// }
}
void ZeroHalfSystem::reduce_gauss() {
// auto row = 0UL;
// while (row < nb_rows) {
// if (slack[row] < EPS) {
// auto high_x = std::numeric_limits<double>::min();
// auto best_col = -1;
// auto counter = 0;
// for (auto j = 0UL; j < nb_columns; ++j) {
// if (A_bar[row][j]) {
// ++counter;
// if (x_star[j] > high_x) {
// high_x = x_star[j];
// best_col = j;
// }
// }
// }
// if (counter == 0) {
// if (b_bar[row]) {
// /** construct ineq */
// }
// remove_row(row);
// } else {
// for (auto&& [r, x] : vs::enumerate(A_bar)) {
// if (r != row && x[best_col] == 1) {
// add_to_row(row, r);
// }
// slack[row] += x_star[best_col];
// remove_col(best_col);
// ++row;
// }
// }
// } else {
// ++row;
// }
// }
}
void ZeroHalfSystem::evaluate_rows(const std::vector<int>& _rows) {
auto sum_slack = 0.0;
ranges::for_each(_rows, [&](int idx) { sum_slack += slack[idx]; });
if (sum_slack <= 1.0 - HALF * EPS) {
std::vector<int> v(nb_rows, 0);
ranges::for_each(_rows, [&](int idx) { v[idx] = 1; });
auto odd = (ranges::inner_product(v, b_bar, 0) % 2) == 1;
if (odd) {
auto left =
vs::ints(size_t{}, nb_columns) | vs::transform([&](int i) {
return ranges::inner_product(v | vs::all,
A_bar | vs::join |
vs::drop(i) |
vs::stride(nb_columns),
0) %
2;
});
auto val = ranges::inner_product(left, x_star, 0.0);
if (val < 1 - HALF * EPS) {
auto result = row_index[0];
for (auto& it : row_index | vs::drop(0)) {
result ^= it;
}
/** construct ineq */
}
}
}
}
void ZeroHalfSystem::add_to_row(size_t i, size_t j) {
for (auto&& [lhs, rhs] : vs::zip(A_bar[i], A_bar[j])) {
rhs = (lhs + rhs) % 2;
}
b_bar[j] = (b_bar[i] + b_bar[j]) % 2;
row_index[j] = row_index[i] ^ row_index[j];
slack[j] = slack[i] + slack[j];
}
ZeroHalfSystem::ZeroHalfSystem([[maybe_unused]]const DdStructure<NodeBdd>& bdd) {
// auto& table = bdd.getDiagram();
}
| 36.318182 | 81 | 0.476654 |
DanielKowalczyk1984
|
11efde7b5950be22407b08107a2a50dd10497eb5
| 3,137 |
cc
|
C++
|
src/canvas/canvas/Persistency/Provenance/EventAuxiliary.cc
|
JeffersonLab/ARIEL
|
49054ac62a84d48e269f7171daabb98e12a0be90
|
[
"BSD-3-Clause"
] | null | null | null |
src/canvas/canvas/Persistency/Provenance/EventAuxiliary.cc
|
JeffersonLab/ARIEL
|
49054ac62a84d48e269f7171daabb98e12a0be90
|
[
"BSD-3-Clause"
] | null | null | null |
src/canvas/canvas/Persistency/Provenance/EventAuxiliary.cc
|
JeffersonLab/ARIEL
|
49054ac62a84d48e269f7171daabb98e12a0be90
|
[
"BSD-3-Clause"
] | 2 |
2020-09-26T01:37:11.000Z
|
2021-05-03T13:02:24.000Z
|
#include "canvas/Persistency/Provenance/EventAuxiliary.h"
// vim: set sw=2 expandtab :
#include <ostream>
#include <utility>
using namespace std;
namespace art {
EventAuxiliary::~EventAuxiliary() {}
EventAuxiliary::EventAuxiliary()
: id_{}, time_{}, isRealData_{false}, experimentType_{Any}
{}
EventAuxiliary::EventAuxiliary(EventID const& theId,
Timestamp const& theTime,
bool isReal,
ExperimentType eType /*= Any*/)
: id_{theId}, time_{theTime}, isRealData_{isReal}, experimentType_{eType}
{}
EventAuxiliary::EventAuxiliary(EventAuxiliary const& rhs)
: id_{rhs.id_}
, time_{rhs.time_}
, isRealData_{rhs.isRealData_}
, experimentType_{rhs.experimentType_}
{}
EventAuxiliary::EventAuxiliary(EventAuxiliary&& rhs)
: id_{move(rhs.id_)}
, time_{move(rhs.time_)}
, isRealData_{move(rhs.isRealData_)}
, experimentType_{move(rhs.experimentType_)}
{}
EventAuxiliary&
EventAuxiliary::operator=(EventAuxiliary const& rhs)
{
if (this != &rhs) {
id_ = rhs.id_;
time_ = rhs.time_;
isRealData_ = rhs.isRealData_;
experimentType_ = rhs.experimentType_;
}
return *this;
}
EventAuxiliary&
EventAuxiliary::operator=(EventAuxiliary&& rhs)
{
id_ = move(rhs.id_);
time_ = move(rhs.time_);
isRealData_ = move(rhs.isRealData_);
experimentType_ = move(rhs.experimentType_);
return *this;
}
Timestamp const&
EventAuxiliary::time() const noexcept
{
auto const& ret = time_;
return ret;
}
EventID const&
EventAuxiliary::id() const noexcept
{
auto const& ret = id_;
return ret;
}
EventID const&
EventAuxiliary::eventID() const noexcept
{
auto const& ret = id_;
return ret;
}
RunID const&
EventAuxiliary::runID() const noexcept
{
auto const& ret = id_.runID();
return ret;
}
SubRunID const&
EventAuxiliary::subRunID() const noexcept
{
auto const& ret = id_.subRunID();
return ret;
}
RunNumber_t
EventAuxiliary::run() const noexcept
{
auto ret = id_.run();
return ret;
}
SubRunNumber_t
EventAuxiliary::subRun() const noexcept
{
auto ret = id_.subRun();
return ret;
}
EventNumber_t
EventAuxiliary::event() const noexcept
{
auto ret = id_.event();
return ret;
}
bool
EventAuxiliary::isRealData() const noexcept
{
auto ret = isRealData_;
return ret;
}
EventAuxiliary::ExperimentType
EventAuxiliary::experimentType() const noexcept
{
auto ret = experimentType_;
return ret;
}
bool
EventAuxiliary::operator==(EventAuxiliary const& other) const noexcept
{
auto ret = (id_ == other.id_) && (time_ == other.time_) &&
(isRealData_ == other.isRealData_) &&
(experimentType_ == other.experimentType_);
return ret;
}
void
EventAuxiliary::write(ostream& os) const
{
os << id_ << endl;
}
ostream&
operator<<(ostream& os, const EventAuxiliary& p)
{
p.write(os);
return os;
}
} // namespace art
| 20.503268 | 77 | 0.630539 |
JeffersonLab
|
11f3cbe46634b80efade80446aa4ed7b5742fe26
| 8,136 |
hpp
|
C++
|
include/dca/io/hdf5/hdf5_reader.hpp
|
gonidelis/DCA
|
b219350a335b96c85b74de9a88bd00d4f37f0ce2
|
[
"BSD-3-Clause"
] | null | null | null |
include/dca/io/hdf5/hdf5_reader.hpp
|
gonidelis/DCA
|
b219350a335b96c85b74de9a88bd00d4f37f0ce2
|
[
"BSD-3-Clause"
] | 11 |
2020-04-22T14:50:27.000Z
|
2021-09-10T05:43:51.000Z
|
include/dca/io/hdf5/hdf5_reader.hpp
|
weilewei/DCA
|
b219350a335b96c85b74de9a88bd00d4f37f0ce2
|
[
"BSD-3-Clause"
] | 1 |
2019-09-22T16:33:19.000Z
|
2019-09-22T16:33:19.000Z
|
// Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Peter Staar (taa@zurich.ibm.com)
//
// HDF5 reader.
#ifndef DCA_IO_HDF5_HDF5_READER_HPP
#define DCA_IO_HDF5_HDF5_READER_HPP
#include <complex>
#include <string>
#include <vector>
#include "H5Cpp.h"
#include "dca/io/buffer.hpp"
#include "dca/function/domains.hpp"
#include "dca/function/function.hpp"
#include "dca/io/hdf5/hdf5_types.hpp"
#include "dca/linalg/matrix.hpp"
#include "dca/linalg/vector.hpp"
namespace dca {
namespace io {
// dca::io::
class HDF5Reader {
public:
typedef H5::H5File file_type;
// In: verbose. If true, the reader outputs a short log whenever it is executed.
HDF5Reader(bool verbose = true) : verbose_(verbose) {}
~HDF5Reader();
constexpr static bool is_reader = true;
constexpr static bool is_writer = false;
void open_file(std::string file_name);
void close_file();
void open_group(std::string name) {
paths_.push_back(name);
}
void close_group() {
paths_.pop_back();
}
std::string get_path();
template <typename arbitrary_struct_t>
static void from_file(arbitrary_struct_t& arbitrary_struct, std::string file_name);
// `execute` returns true if the object is read correctly.
template <typename Scalartype>
bool execute(const std::string& name, Scalartype& value);
template <typename Scalar>
bool execute(const std::string& name, std::vector<Scalar>& value);
template <typename Scalar>
bool execute(const std::string& name, std::vector<std::vector<Scalar>>& value);
template <typename Scalar, std::size_t n>
bool execute(const std::string& name, std::vector<std::array<Scalar, n>>& value);
bool execute(const std::string& name, std::string& value);
bool execute(const std::string& name, std::vector<std::string>& value);
// TODO: Remove? (only thing that depends on domains.hpp)
template <typename domain_type>
bool execute(std::string /*name*/, func::dmn_0<domain_type>& /*dmn*/) {
return false;
}
template <typename Scalartype, typename domain_type>
bool execute(func::function<Scalartype, domain_type>& f);
template <typename Scalartype, typename domain_type>
bool execute(const std::string& name, func::function<Scalartype, domain_type>& f);
template <typename Scalar>
bool execute(const std::string& name, dca::linalg::Vector<Scalar, dca::linalg::CPU>& A);
template <typename Scalar>
bool execute(const std::string& name, dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A);
template <typename Scalar>
bool execute(dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A);
bool execute(const std::string& name, io::Buffer& buff) {
return execute(name, static_cast<io::Buffer::Container&>(buff));
}
private:
bool exists(const std::string& name) const;
void read(const std::string& name, H5::DataType type, void* data) const;
std::vector<hsize_t> readSize(const std::string& name) const;
std::unique_ptr<H5::H5File> file_;
std::vector<std::string> paths_;
bool verbose_;
};
template <typename arbitrary_struct_t>
void HDF5Reader::from_file(arbitrary_struct_t& arbitrary_struct, std::string file_name) {
HDF5Reader reader_obj;
reader_obj.open_file(file_name);
arbitrary_struct.read_write(reader_obj);
reader_obj.close_file();
}
template <typename Scalar>
bool HDF5Reader::execute(const std::string& name, Scalar& value) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
return false;
}
read(full_name, HDF5_TYPE<Scalar>::get_PredType(), &value);
return true;
}
template <typename Scalar>
bool HDF5Reader::execute(const std::string& name, std::vector<Scalar>& value) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
return false;
}
auto dims = readSize(full_name);
assert(dims.size() == 1);
value.resize(dims.at(0));
read(full_name, HDF5_TYPE<Scalar>::get_PredType(), value.data());
return true;
}
template <typename Scalar>
bool HDF5Reader::execute(const std::string& name, std::vector<std::vector<Scalar>>& value) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
return false;
}
auto size = readSize(full_name)[0];
const auto type = H5::VarLenType(HDF5_TYPE<Scalar>::get_PredType());
std::vector<hvl_t> data(size);
H5::DataSet dataset = file_->openDataSet(name.c_str());
dataset.read(data.data(), type);
value.resize(size);
for (int i = 0; i < size; ++i) {
value[i].resize(data[i].len);
std::copy_n(static_cast<Scalar*>(data[i].p), data[i].len, value[i].data());
}
dataset.vlenReclaim(data.data(), type, dataset.getSpace());
return true;
}
template <typename Scalar, std::size_t n>
bool HDF5Reader::execute(const std::string& name, std::vector<std::array<Scalar, n>>& value) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
return false;
}
auto dims = readSize(full_name);
assert(dims.size() == 2);
if (dims.at(1) != n) {
throw(std::length_error("Wrong array size"));
}
value.resize(dims[0]);
read(full_name, HDF5_TYPE<Scalar>::get_PredType(), value.data());
return true;
}
template <typename Scalartype, typename domain_type>
bool HDF5Reader::execute(func::function<Scalartype, domain_type>& f) {
return execute(f.get_name(), f);
}
template <typename Scalartype, typename domain_type>
bool HDF5Reader::execute(const std::string& name, func::function<Scalartype, domain_type>& f) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
std::cout << "\n\n\t the function (" + name + ") does not exist in path : " + get_path() +
"\n\n";
return false;
}
std::cout << "\n\tstart reading function : " << name;
H5::DataSet dataset = file_->openDataSet(full_name.c_str());
try {
// Read sizes.
std::vector<hsize_t> dims;
auto domain_attribute = dataset.openAttribute("domain-sizes");
hsize_t n_dims;
domain_attribute.getSpace().getSimpleExtentDims(&n_dims);
dims.resize(n_dims);
domain_attribute.read(HDF5_TYPE<hsize_t>::get_PredType(), dims.data());
// Check sizes.
if (dims.size() != f.signature())
throw(std::length_error("The number of domains is different"));
for (int i = 0; i < f.signature(); ++i) {
if (dims[i] != f[i])
throw(std::length_error("The size of domain " + std::to_string(i) + " is different"));
}
}
catch (H5::Exception& err) {
std::cerr << "Could not perform a size check on the function " << name << std::endl;
}
read(full_name, HDF5_TYPE<Scalartype>::get_PredType(), f.values());
return true;
}
template <typename Scalar>
bool HDF5Reader::execute(const std::string& name, dca::linalg::Vector<Scalar, dca::linalg::CPU>& V) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
return false;
}
auto dims = readSize(full_name);
assert(dims.size() == 1);
V.resize(dims.at(0));
read(full_name, HDF5_TYPE<Scalar>::get_PredType(), V.ptr());
return true;
}
template <typename Scalar>
bool HDF5Reader::execute(const std::string& name, dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) {
std::string full_name = get_path() + "/" + name;
if (!exists(full_name)) {
return false;
}
auto dims = readSize(full_name);
assert(dims.size() == 2);
std::vector<Scalar> linearized(dims[0] * dims[1]);
read(full_name, HDF5_TYPE<Scalar>::get_PredType(), linearized.data());
// HDF5 is column major, while Matrix is row major.
A.resizeNoCopy(std::make_pair(dims[0], dims[1]));
for (int i = 0, linindex = 0; i < A.nrRows(); ++i) {
for (int j = 0; j < A.nrCols(); ++j)
A(i, j) = linearized[linindex++];
}
A.set_name(name);
return true;
}
template <typename Scalar>
bool HDF5Reader::execute(dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) {
return execute(A.get_name(), A);
}
} // namespace io
} // namespace dca
#endif // DCA_IO_HDF5_HDF5_READER_HPP
| 28.055172 | 101 | 0.678343 |
gonidelis
|
11f561c54c4c77935addf7364cc459c6526ab83b
| 7,305 |
hpp
|
C++
|
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/state_machine/enum_state_machine.hpp
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 5 |
2019-11-11T07:57:26.000Z
|
2022-03-28T08:26:53.000Z
|
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/state_machine/enum_state_machine.hpp
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 3 |
2019-09-05T21:47:07.000Z
|
2019-09-17T18:10:45.000Z
|
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/state_machine/enum_state_machine.hpp
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 11 |
2019-07-20T00:16:32.000Z
|
2022-01-11T14:17:48.000Z
|
/*!
* @copyright
* Copyright (c) 2016-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file state_machine/enum_state_machine.hpp
* @brief Declaration of the EnumStateMachine template
* */
#pragma once
#include <functional>
#include <vector>
#include "wrap.hpp"
namespace agent_framework {
namespace state_machine {
/*!
* Class representing a simple enum-based state machine. It uses enums to represent states and events, therefore
* states cannot really store their own data. State machine is parametrized with two types: STATE which is a type of
* machine states and EVENT representing Events type.
* */
template <typename STATE, typename EVENT>
class EnumStateMachine {
public:
struct Transition;
/*!
* Type definition of the functions used in state machines - used for guards and actions. They accept one
* parameter that describe the transition and return bool value: for actions, true means that action was
* successful, for guards, true means that the transition may be started.
* */
using StateMachineFunction = std::function<bool(const Transition&)>;
/*! Type declaration of the TransitionTable */
using TransitionTable = std::vector<Transition>;
/*! Struct representing single transition of the state machine */
struct Transition final {
public:
/*!
* @brief Constructor
* @param[in] i_s Initial state before the transition
* @param[in] e Event that triggers the transition
* @param[in] e_s End state after the transition
* @param[in] a Action triggered by the transition (default action = no action)
* @param[in] g Guard checking if transition should be performed (default guard = always)
* */
Transition(const STATE& i_s, const EVENT& e, const STATE& e_s,
StateMachineFunction a = do_nothing, StateMachineFunction g = always):
init_state(i_s), event(e), end_state(e_s), action(a), guard(g) {}
/*!
* @brief Default action during transitions - does nothing
* @return Always returns true
* */
static constexpr bool do_nothing(const Transition&) { return true; }
/*!
* @brief Default guard - always true
* @return Always returns true
* */
static constexpr bool always(const Transition&) { return true; }
/*! Initial state required for the transition */
STATE init_state;
/*! Event triggering the transition */
EVENT event;
/*! End state after the transition */
STATE end_state;
/*! Action triggered by the transition */
StateMachineFunction action;
/*! Additional condition for transition to take place */
StateMachineFunction guard;
};
/*!
* @brief Constructor
* @param[in] init_state Initial state of the machine
* @param[in] transition_table Transition table describing transitions allowed in the
* state machine (default = no transitions, empty table)
* */
EnumStateMachine(const STATE& init_state, const TransitionTable& transition_table = {}):
m_current_state(init_state), m_transition_table(transition_table) {}
/*! Copy constructor */
EnumStateMachine(const EnumStateMachine&) = default;
/*! Move constructor */
EnumStateMachine(EnumStateMachine&&) = default;
/*! Copy Assignment operators */
EnumStateMachine& operator=(const EnumStateMachine&) = default;
/*! Move Assignment operators */
EnumStateMachine& operator=(EnumStateMachine&&) = default;
/*!
* @brief Destructor
* */
virtual ~EnumStateMachine() {}
/*!
* @brief Adds a transition to the state machine
* @param[in] init_state Initial state before the transition
* @param[in] event Event that triggers the transition
* @param[in] end_state End state after the transition
* @param[in] action Action triggered by the transition (default action = no action)
* @param[in] guard Guard checking if transition should be performed (default guard = always)
* @return Reference to the state machine
* */
EnumStateMachine& add_transition(const STATE& init_state, const EVENT& event, const STATE& end_state,
StateMachineFunction action = Transition::do_nothing, StateMachineFunction guard = Transition::always) {
m_transition_table.emplace_back(Transition{init_state, event, end_state, action, guard});
return *this;
}
/*!
* @brief Returns current machine state
* @return Current machine state
* */
STATE get_current_state() const {
return m_current_state;
}
/*!
* @brief Sends specific event to the machine
* @param[in] event Event sent to the state machine
* @return False if the event would cause state machine to change its state, but due to state machine action
* failure, state was not changed and transition did not happen.
* */
bool send_event(const EVENT& event) {
do_on_event_action(event);
for (const auto& transition : m_transition_table) {
if (transition.init_state == m_current_state && transition.event == event && do_guard_check(transition)) {
if (!do_transition(transition)) {
return false;
}
m_current_state = transition.end_state;
return true;
}
}
return true;
}
protected:
/*!
* @brief Method used to check guards of the transition.
* Should be overriden in derived classes if change of the behaviour is desired.
* @param[in] transition Information about the transition
* @return True if the guard returned true
* */
virtual bool do_guard_check(const Transition& transition) {
return transition.guard(transition);
}
/*!
* @brief Method used to perform transition action.
* Should be overriden in derived classes if change of the behaviour is desired.
* @param[in] transition Information about the transition
* @return True if action was successful
* */
virtual bool do_transition(const Transition& transition) {
return transition.action(transition);
}
/*!
* @brief Method called as a first method in send_event call
* Should be overriden in derived classes if change of the behaviour is desired.
* */
virtual void do_on_event_action(const EVENT&) {
}
private:
/*! Current state of the state machine */
STATE m_current_state{};
/*! Transition table of the state machine */
TransitionTable m_transition_table{};
};
}
}
| 34.620853 | 118 | 0.665161 |
opencomputeproject
|
11f72ce0b197f74c326bdb0e5b8762a804b43bbb
| 27 |
cpp
|
C++
|
lib/STD/Ostream.cpp
|
hlp2/EnjoLib
|
6bb69d0b00e367a800b0ef2804808fd1303648f4
|
[
"BSD-3-Clause"
] | 3 |
2021-06-14T15:36:46.000Z
|
2022-02-28T15:16:08.000Z
|
lib/STD/Ostream.cpp
|
hlp2/EnjoLib
|
6bb69d0b00e367a800b0ef2804808fd1303648f4
|
[
"BSD-3-Clause"
] | 1 |
2021-07-17T07:52:15.000Z
|
2021-07-17T07:52:15.000Z
|
lib/STD/Ostream.cpp
|
hlp2/EnjoLib
|
6bb69d0b00e367a800b0ef2804808fd1303648f4
|
[
"BSD-3-Clause"
] | 3 |
2021-07-12T14:52:38.000Z
|
2021-11-28T17:10:33.000Z
|
#include <STD/Ostream.hpp>
| 13.5 | 26 | 0.740741 |
hlp2
|
11f87b43e5fe24fbaf37fc6f98f9b1a8f343fbb9
| 1,321 |
cpp
|
C++
|
SelfLearningFromVideo/imooc-DatastructureAndAlgorithm/AllCodeFromTeacher/08-Minimum-Span-Trees/06-Kruskal-Algorithm/main.cpp
|
YaKaiLi/YaKaiLi-PAT-Related
|
5eca2d90a6e7fc069fd8c320721d337676200ade
|
[
"MIT"
] | 1 |
2018-08-22T15:12:39.000Z
|
2018-08-22T15:12:39.000Z
|
SelfLearningFromVideo/imooc-DatastructureAndAlgorithm/AllCodeFromTeacher/08-Minimum-Span-Trees/06-Kruskal-Algorithm/main.cpp
|
YaKaiLi/YaKaiLi-PAT-Related
|
5eca2d90a6e7fc069fd8c320721d337676200ade
|
[
"MIT"
] | 1 |
2020-08-31T09:32:56.000Z
|
2020-08-31T09:32:56.000Z
|
C++/08-Minimum-Span-Trees/06-Kruskal-Algorithm/main.cpp
|
DragonYong/Happy-Algorithm
|
7ca585d5990f5c4587ab4e22178ecb88e5d57d91
|
[
"Apache-2.0"
] | 2 |
2018-08-09T13:59:29.000Z
|
2018-08-23T15:02:40.000Z
|
#include <iostream>
#include <iomanip>
#include "DenseGraph.h"
#include "SparseGraph.h"
#include "ReadGraph.h"
#include "LazyPrimMST.h"
#include "PrimMST.h"
#include "KruskalMST.h"
using namespace std;
int main() {
string filename = "testG1.txt";
int V = 8;
SparseGraph<double> g = SparseGraph<double>(V, false);
ReadGraph<SparseGraph<double>, double> readGraph(g, filename);
// Test Lazy Prim MST
cout<<"Test Lazy Prim MST:"<<endl;
LazyPrimMST<SparseGraph<double>, double> lazyPrimMST(g);
vector<Edge<double>> mst = lazyPrimMST.mstEdges();
for( int i = 0 ; i < mst.size() ; i ++ )
cout<<mst[i]<<endl;
cout<<"The MST weight is: "<<lazyPrimMST.result()<<endl;
cout<<endl;
// Test Prim MST
cout<<"Test Prim MST:"<<endl;
PrimMST<SparseGraph<double>, double> primMST(g);
mst = primMST.mstEdges();
for( int i = 0 ; i < mst.size() ; i ++ )
cout<<mst[i]<<endl;
cout<<"The MST weight is: "<<primMST.result()<<endl;
cout<<endl;
// Test Kruskal MST
cout<<"Test Kruskal MST:"<<endl;
KruskalMST<SparseGraph<double>, double> kruskalMST(g);
mst = kruskalMST.mstEdges();
for( int i = 0 ; i < mst.size() ; i ++ )
cout<<mst[i]<<endl;
cout<<"The MST weight is: "<<kruskalMST.result()<<endl;
return 0;
}
| 25.403846 | 66 | 0.612415 |
YaKaiLi
|
11fa69c4678eecb2a577cd77411fee1a390e1c6c
| 9,612 |
cc
|
C++
|
Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 1 |
2019-08-09T08:42:11.000Z
|
2019-08-09T08:42:11.000Z
|
Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | null | null | null |
Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.cc
|
nistefan/cmssw
|
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
|
[
"Apache-2.0"
] | 1 |
2019-03-19T13:44:54.000Z
|
2019-03-19T13:44:54.000Z
|
/*
* See header file for a description of this class.
*
* \author S. Bolognesi and G. Cerminara - INFN Torino
*/
#include <iostream>
#include <map>
#include "DataFormats/DTRecHit/interface/DTRecHitCollection.h"
#include "DataFormats/DTRecHit/interface/DTRecSegment4DCollection.h"
#include "DataFormats/MuonDetId/interface/DTWireId.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "Geometry/DTGeometry/interface/DTChamber.h"
#include "Geometry/DTGeometry/interface/DTGeometry.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h"
#include "Validation/DTRecHits/interface/DTHitQualityUtils.h"
#include "DTSegment2DSLPhiQuality.h"
#include "Histograms.h"
using namespace std;
using namespace edm;
namespace dtsegment2dsl {
struct Histograms {
std::unique_ptr<HRes2DHit> h2DHitSuperPhi;
std::unique_ptr<HEff2DHit> h2DHitEff_SuperPhi;
};
}
using namespace dtsegment2dsl;
// Constructor
DTSegment2DSLPhiQuality::DTSegment2DSLPhiQuality(const ParameterSet& pset) {
// Get the debug parameter for verbose output
debug_ = pset.getUntrackedParameter<bool>("debug");
DTHitQualityUtils::debug = debug_;
// the name of the simhit collection
simHitLabel_ = pset.getUntrackedParameter<InputTag>("simHitLabel");
simHitToken_ = consumes<PSimHitContainer>(pset.getUntrackedParameter<InputTag>("simHitLabel"));
// the name of the 2D rec hit collection
segment4DLabel_ = pset.getUntrackedParameter<InputTag>("segment4DLabel");
segment4DToken_ = consumes<DTRecSegment4DCollection>(pset.getUntrackedParameter<InputTag>("segment4DLabel"));
// sigma resolution on position
sigmaResPos_ = pset.getParameter<double>("sigmaResPos");
// sigma resolution on angle
sigmaResAngle_ = pset.getParameter<double>("sigmaResAngle");
doall_ = pset.getUntrackedParameter<bool>("doall", false);
local_ = pset.getUntrackedParameter<bool>("local", false);
}
void DTSegment2DSLPhiQuality::bookHistograms(DQMStore::ConcurrentBooker & booker, edm::Run const& run, edm::EventSetup const& setup, Histograms & histograms) const {
// Book the histos
histograms.h2DHitSuperPhi = std::make_unique<HRes2DHit> ("SuperPhi", booker, doall_, local_);
if (doall_) { histograms.h2DHitEff_SuperPhi = std::make_unique<HEff2DHit> ("SuperPhi", booker);
}
}
// The real analysis
void DTSegment2DSLPhiQuality::dqmAnalyze(edm::Event const& event, edm::EventSetup const& setup, Histograms const& histograms) const {
// Get the DT Geometry
ESHandle<DTGeometry> dtGeom;
setup.get<MuonGeometryRecord>().get(dtGeom);
// Get the SimHit collection from the event
edm::Handle<PSimHitContainer> simHits;
event.getByToken(simHitToken_, simHits); // FIXME: second string to be removed
// Map simHits by chamber
map<DTChamberId, PSimHitContainer > simHitsPerCh;
for (const auto & simHit : *simHits) {
// Create the id of the chamber (the simHits in the DT known their wireId)
DTChamberId chamberId = (((DTWireId(simHit.detUnitId())).layerId()).superlayerId()).chamberId();
// Fill the map
simHitsPerCh[chamberId].push_back(simHit);
}
// Get the 4D rechits from the event
Handle<DTRecSegment4DCollection> segment4Ds;
event.getByToken(segment4DToken_, segment4Ds);
if (!segment4Ds.isValid()) {
if (debug_) {
cout << "[DTSegment2DSLPhiQuality]**Warning: no 4D Segments with label: " << segment4DLabel_
<< " in this event, skipping!" << endl;
}
return;
}
// Loop over all chambers containing a segment
DTRecSegment4DCollection::id_iterator chamberId;
for (chamberId = segment4Ds->id_begin();
chamberId != segment4Ds->id_end();
++chamberId) {
//------------------------- simHits ---------------------------//
// Get simHits of each chamber
PSimHitContainer simHits = simHitsPerCh[(*chamberId)];
// Map simhits per wire
map<DTWireId, PSimHitContainer > simHitsPerWire = DTHitQualityUtils::mapSimHitsPerWire(simHits);
map<DTWireId, const PSimHit*> muSimHitPerWire = DTHitQualityUtils::mapMuSimHitsPerWire(simHitsPerWire);
int nMuSimHit = muSimHitPerWire.size();
if (nMuSimHit == 0 || nMuSimHit == 1) {
if (debug_ && nMuSimHit == 1) {
cout << "[DTSegment2DSLPhiQuality] Only " << nMuSimHit << " mu SimHit in this chamber, skipping!" << endl;
}
continue; // If no or only one mu SimHit is found skip this chamber
}
if (debug_) {
cout << "=== Chamber " << (*chamberId) << " has " << nMuSimHit << " SimHits" << endl;
}
// Find outer and inner mu SimHit to build a segment
pair<const PSimHit*, const PSimHit*> inAndOutSimHit = DTHitQualityUtils::findMuSimSegment(muSimHitPerWire);
// Find direction and position of the sim Segment in Chamber RF
pair<LocalVector, LocalPoint> dirAndPosSimSegm = DTHitQualityUtils::findMuSimSegmentDirAndPos(inAndOutSimHit,
(*chamberId),&(*dtGeom));
LocalVector simSegmLocalDir = dirAndPosSimSegm.first;
LocalPoint simSegmLocalPos = dirAndPosSimSegm.second;
const DTChamber* chamber = dtGeom->chamber(*chamberId);
GlobalPoint simSegmGlobalPos = chamber->toGlobal(simSegmLocalPos);
// Atan(x/z) angle and x position in SL RF
float angleSimSeg = DTHitQualityUtils::findSegmentAlphaAndBeta(simSegmLocalDir).first;
float posSimSeg = simSegmLocalPos.x();
// Position (in eta, phi coordinates) in lobal RF
float etaSimSeg = simSegmGlobalPos.eta();
float phiSimSeg = simSegmGlobalPos.phi();
if (debug_) {
cout << " Simulated segment: local direction " << simSegmLocalDir << endl
<< " local position " << simSegmLocalPos << endl
<< " angle " << angleSimSeg << endl;
}
//---------------------------- recHits --------------------------//
// Get the range of rechit for the corresponding chamberId
bool recHitFound = false;
DTRecSegment4DCollection::range range = segment4Ds->get(*chamberId);
int nsegm = distance(range.first, range.second);
if (debug_) {
cout << " Chamber: " << *chamberId << " has " << nsegm
<< " 4D segments" << endl;
}
if (nsegm!= 0) {
// Find the best RecHit: look for the 4D RecHit with the phi angle closest
// to that of segment made of SimHits.
// RecHits must have delta alpha and delta position within 5 sigma of
// the residual distribution (we are looking for residuals of segments
// usefull to the track fit) for efficency purpose
const DTRecSegment2D* bestRecHit = nullptr;
bool bestRecHitFound = false;
double deltaAlpha = 99999;
// Loop over the recHits of this chamberId
for (DTRecSegment4DCollection::const_iterator segment4D = range.first;
segment4D!= range.second;
++segment4D) {
// Check the dimension
if ((*segment4D).dimension() != 4) {
if (debug_) { cout << "[DTSegment2DSLPhiQuality]***Error: This is not 4D segment!!!" << endl;
}
continue;
}
// Get 2D superPhi segments from 4D segments
const DTChamberRecSegment2D* phiSegment2D = (*segment4D).phiSegment();
if ((*phiSegment2D).dimension() != 2) {
if (debug_) { cout << "[DTSegment2DQuality]***Error: This is not 2D segment!!!" << endl;
}
abort();
}
// Segment Local Direction and position (in Chamber RF)
LocalVector recSegDirection = (*phiSegment2D).localDirection();
float recSegAlpha = DTHitQualityUtils::findSegmentAlphaAndBeta(recSegDirection).first;
if (debug_) {
cout << " RecSegment direction: " << recSegDirection << endl
<< " position : " << (*phiSegment2D).localPosition() << endl
<< " alpha : " << recSegAlpha << endl;
}
if (fabs(recSegAlpha - angleSimSeg) < deltaAlpha) {
deltaAlpha = fabs(recSegAlpha - angleSimSeg);
bestRecHit = &(*phiSegment2D);
bestRecHitFound = true;
}
} // End of Loop over all 4D RecHits of this chambers
if (bestRecHitFound) {
// Best rechit direction and position in Chamber RF
LocalPoint bestRecHitLocalPos = bestRecHit->localPosition();
LocalVector bestRecHitLocalDir = bestRecHit->localDirection();
LocalError bestRecHitLocalPosErr = bestRecHit->localPositionError();
LocalError bestRecHitLocalDirErr = bestRecHit->localDirectionError();
float angleBestRHit = DTHitQualityUtils::findSegmentAlphaAndBeta(bestRecHitLocalDir).first;
if (fabs(angleBestRHit - angleSimSeg) < 5*sigmaResAngle_ &&
fabs(bestRecHitLocalPos.x() - posSimSeg) < 5*sigmaResPos_) {
recHitFound = true;
}
// Fill Residual histos
histograms.h2DHitSuperPhi->fill(angleSimSeg,
angleBestRHit,
posSimSeg,
bestRecHitLocalPos.x(),
etaSimSeg,
phiSimSeg,
sqrt(bestRecHitLocalPosErr.xx()),
sqrt(bestRecHitLocalDirErr.xx())
);
}
} // end of if (nsegm!= 0)
// Fill Efficiency plot
if (doall_) {
histograms.h2DHitEff_SuperPhi->fill(etaSimSeg,
phiSimSeg,
posSimSeg,
angleSimSeg,
recHitFound);
}
} // End of loop over chambers
}
// declare this as a framework plugin
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(DTSegment2DSLPhiQuality);
| 39.719008 | 165 | 0.675198 |
nistefan
|
11fe3791e770cdf9ea0e90baba1f10810b5b35bc
| 23,298 |
cpp
|
C++
|
src/Solver/SolverNonLinear.cpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 12 |
2020-09-07T11:19:10.000Z
|
2022-02-17T17:40:19.000Z
|
src/Solver/SolverNonLinear.cpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 110 |
2020-09-02T15:29:24.000Z
|
2022-03-09T09:50:01.000Z
|
src/Solver/SolverNonLinear.cpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 3 |
2021-05-21T13:24:31.000Z
|
2022-02-11T14:43:12.000Z
|
/**
* Implementation of a custom Newton solver which only utilizes
* the linear solvers of PETSc.
*/
#include <iostream>
#include <string>
#include <vector>
#include "DREAM/IO.hpp"
#include "DREAM/OutputGeneratorSFile.hpp"
#include "DREAM/Solver/SolverNonLinear.hpp"
using namespace DREAM;
using namespace std;
/**
* Constructor.
*/
SolverNonLinear::SolverNonLinear(
FVM::UnknownQuantityHandler *unknowns,
vector<UnknownQuantityEquation*> *unknown_equations,
EquationSystem *eqsys,
enum OptionConstants::linear_solver ls,
enum OptionConstants::linear_solver bk,
const int_t maxiter, const real_t reltol,
bool verbose
) : Solver(unknowns, unknown_equations, ls, bk), eqsys(eqsys),
maxiter(maxiter), reltol(reltol), verbose(verbose) {
this->timeKeeper = new FVM::TimeKeeper("Solver non-linear");
this->timerTot = this->timeKeeper->AddTimer("total", "Total time");
this->timerRebuild = this->timeKeeper->AddTimer("rebuildtot", "Rebuild coefficients");
this->timerResidual = this->timeKeeper->AddTimer("residual", "Construct residual");
this->timerJacobian = this->timeKeeper->AddTimer("jacobian", "Construct jacobian");
this->timerInvert = this->timeKeeper->AddTimer("invert", "Invert jacobian");
}
/**
* Destructor.
*/
SolverNonLinear::~SolverNonLinear() {
Deallocate();
delete this->timeKeeper;
}
/**
* "Accept" the current solution and prepare for taking
* another Newton step.
*/
void SolverNonLinear::AcceptSolution() {
real_t *x = this->x1;
this->x1 = this->x0;
this->x0 = x;
this->StoreSolution(x);
}
/**
* Allocate memory for all objects used by this solver.
*/
void SolverNonLinear::Allocate() {
this->AllocateJacobianMatrix();
const len_t N = jacobian->GetNRows();
// Select linear solver
this->SelectLinearSolver(N);
VecCreateSeq(PETSC_COMM_WORLD, N, &this->petsc_F);
VecCreateSeq(PETSC_COMM_WORLD, N, &this->petsc_dx);
this->x0 = new real_t[N];
this->x1 = new real_t[N];
this->dx = new real_t[N];
this->xinit = new real_t[N];
this->x_2norm = new real_t[this->unknown_equations->size()];
this->dx_2norm = new real_t[this->unknown_equations->size()];
}
/**
* Allocates memory for and properly sets up the jacobian matrix.
* If the jacobian matrix has previously been allocated, it will
* first be deleted.
*
* WHY DO WE CALL THIS METHOD MORE THAN ONCE?
* In the very first iteration, many elements of the jacobian matrix are often
* identically zero. If we don't insert the zeros explicitly, PETSc will remove
* the memory we allocated for them on the first call to 'Assemble()' requiring
* the memory to be reallocated in the next iteration (which may take a _very_
* long time). However, if we insert the zeros explicitly, the linear solver
* will not be able to tell that the elements are in fact non-zero and will
* take ages to solve the system. As a compromise, we would like to use the
* non-zero pattern obtained in the second Newton iteration of the simulation,
* we should be very close to the non-zero pattern of the remainder of the
* simulation. Hence, we call this method after the first iteration is finished
* to completely reset the matrix, including the non-zero pattern. Reallocating
* all the memory in one go is significantly faster than asking PETSc to
* allocate memory specifically for all the elements we would like to add in the
* second iteration.
*/
void SolverNonLinear::AllocateJacobianMatrix() {
if (this->jacobian != nullptr)
delete this->jacobian;
this->jacobian = new FVM::BlockMatrix();
for (len_t i = 0; i < nontrivial_unknowns.size(); i++) {
len_t id = nontrivial_unknowns[i];
UnknownQuantityEquation *eqn = this->unknown_equations->at(id);
unknownToMatrixMapping[id] =
this->jacobian->CreateSubEquation(eqn->NumberOfElements(), eqn->NumberOfNonZeros_jac(), id);
}
this->jacobian->ConstructSystem();
}
/**
* Deallocate memory used by this solver.
*/
void SolverNonLinear::Deallocate() {
if (backupInverter != nullptr)
delete backupInverter;
delete mainInverter;
delete jacobian;
delete [] this->x_2norm;
delete [] this->dx_2norm;
delete [] this->x0;
delete [] this->x1;
delete [] this->dx;
delete [] this->xinit;
VecDestroy(&this->petsc_F);
VecDestroy(&this->petsc_dx);
}
/**
* Returns the name of the specified non-trivial unknown quantity.
*
* idx: Index into 'this->nontrivial_unknowns' of the non-trivial unknown
* to return the name of.
*/
const string& SolverNonLinear::GetNonTrivialName(const len_t idx) {
return this->unknowns->GetUnknown(this->nontrivial_unknowns[idx])->GetName();
}
/**
* Initialize the solver.
*/
void SolverNonLinear::initialize_internal(
const len_t, vector<len_t>&
) {
this->Allocate();
if (this->convChecker == nullptr)
this->SetConvergenceChecker(
new ConvergenceChecker(unknowns, this->nontrivial_unknowns, this->reltol)
);
}
/**
* Check if the solver has converged.
*/
bool SolverNonLinear::IsConverged(const real_t *x, const real_t *dx) {
if (this->GetIteration() >= this->MaxIter()){
throw SolverException(
"Non-linear solver reached the maximum number of allowed "
"iterations: " LEN_T_PRINTF_FMT ".",
this->MaxIter()
);
}
// always print verbose for the last few iterations before reaching max
const len_t numVerboseBeforeMax = 3;
bool printVerbose = this->Verbose() || (this->MaxIter() - this->GetIteration())<=numVerboseBeforeMax;
if (printVerbose)
DREAM::IO::PrintInfo("ITERATION %d", this->GetIteration());
return convChecker->IsConverged(x, dx, printVerbose);
}
/**
* Set the initial guess for the solver.
*
* guess: Vector containing values of initial guess.
*/
void SolverNonLinear::SetInitialGuess(const real_t *guess) {
if (guess != nullptr) {
for (len_t i = 0; i < this->matrix_size; i++)
this->x0[i] = guess[i];
} else {
for (len_t i = 0; i < this->matrix_size; i++)
this->x0[i] = 0;
}
}
/**
* Revert the solution to the initial guess.
*/
void SolverNonLinear::ResetSolution() {
this->unknowns->GetLongVectorPrevious(this->nontrivial_unknowns, this->x0);
this->StoreSolution(this->x0);
}
/**
* Solve the equation system (advance the system in time
* by one step).
*
* t: Time at which the current solution is given.
* dt: Time step to take.
*
* (the obtained solution will correspond to time t'=t+dt)
*/
void SolverNonLinear::Solve(const real_t t, const real_t dt) {
// Return to main matrix inverter (in case backup inverter
// was used to complete last time step)
this->SwitchToMainInverter();
this->nTimeStep++;
this->t = t;
this->dt = dt;
this->timeKeeper->StartTimer(timerTot);
try {
this->_InternalSolve();
} catch (FVM::FVMException &ex) {
// Retry with backup-solver (if allowed and not already used)
if (this->backupInverter != nullptr && this->inverter != this->backupInverter) {
if (this->Verbose()) {
DREAM::IO::PrintInfo(
"Main inverter failed to converge. Switching to backup inverter."
);
DREAM::IO::PrintError(ex.what());
}
// Retry solve
this->SwitchToBackupInverter();
this->_InternalSolve();
} else // Rethrow exception
throw ex;
}
// Save basic statistics for step
this->nIterations.push_back(this->iteration);
this->usedBackupInverter.push_back(this->inverter == this->backupInverter);
this->timeKeeper->StopTimer(timerTot);
}
void SolverNonLinear::_InternalSolve() {
// Take Newton steps
len_t iter = 0;
const real_t *x, *dx;
do {
iter++;
this->SetIteration(iter);
REDO_ITER:
dx = this->TakeNewtonStep();
// Solution rejected (solver likely switched)
if (dx == nullptr) {
if (iter < this->MaxIter())
goto REDO_ITER;
else
throw SolverException("Maximum number of iterations reached while dx=nullptr.");
}
x = UpdateSolution(dx);
// TODO backtracking...
AcceptSolution();
} while (!IsConverged(x, dx));
}
/**
* Debugging routine for saving both the "analytically" computed
* Jacobian, as well as the Jacobian evaluated numerically using
* finite differences, to file. When this method is called, the
* 'jacobian' variable is assumed to contain the "analytical"
* Jacobian matrix for the current time/iteration. This routine
* will then save that matrix, compute the corresponding numerical
* Jacobian, and save that.
*
* name: Base name to use for files.
*/
void SolverNonLinear::SaveNumericalJacobian(const std::string& name) {
this->_EvaluateJacobianNumerically(this->jacobian);
this->jacobian->View(FVM::Matrix::BINARY_MATLAB, name + "_num");
abort();
}
void SolverNonLinear::SaveJacobian() {
this->jacobian->View(FVM::Matrix::BINARY_MATLAB, "petsc_jacobian");
}
void SolverNonLinear::SaveJacobian(const std::string& name) {
this->jacobian->View(FVM::Matrix::BINARY_MATLAB, name);
}
/**
* Store the current solution to the UnknownQuantityHandler.
*/
void SolverNonLinear::StoreSolution(const real_t *x) {
this->unknowns->Store(this->nontrivial_unknowns, x);
}
/**
* Calculate the next Newton step to take.
*/
const real_t *SolverNonLinear::TakeNewtonStep() {
this->timeKeeper->StartTimer(timerRebuild);
this->RebuildTerms(this->t, this->dt);
this->timeKeeper->StopTimer(timerRebuild);
// Evaluate function vector
this->timeKeeper->StartTimer(timerResidual);
real_t *fvec;
VecGetArray(this->petsc_F, &fvec);
this->BuildVector(this->t, this->dt, fvec, this->jacobian);
VecRestoreArray(this->petsc_F, &fvec);
this->timeKeeper->StopTimer(timerResidual);
// Reconstruct the jacobian matrix after taking the first
// iteration.
// (See the comment above 'AllocateJacobianMatrix()' for
// details about why we do this...)
if (this->nTimeStep == 1 && this->iteration == 2)
this->AllocateJacobianMatrix();
// Evaluate jacobian
this->timeKeeper->StartTimer(timerJacobian);
this->BuildJacobian(this->t, this->dt, this->jacobian);
this->timeKeeper->StopTimer(timerJacobian);
// Print/save debug info and apply preconditioner (if enabled)
if (this->debugrescaled) {
this->Precondition(this->jacobian, this->petsc_F);
this->SaveDebugInfoBefore(this->nTimeStep, this->iteration);
} else {
this->SaveDebugInfoBefore(this->nTimeStep, this->iteration);
this->Precondition(this->jacobian, this->petsc_F);
}
// Solve J*dx = F
this->timeKeeper->StartTimer(timerInvert);
inverter->Invert(this->jacobian, &this->petsc_F, &this->petsc_dx);
if (inverter->GetReturnCode() != 0) {
if (this->Verbose())
DREAM::IO::PrintInfo("Switching to backup inverter... " INT_T_PRINTF_FMT, inverter->GetReturnCode());
this->SwitchToBackupInverter();
return nullptr;
}
this->timeKeeper->StopTimer(timerInvert);
// Undo preconditioner and save additional debug info (if requested)
if (this->debugrescaled) {
this->SaveDebugInfoAfter(this->nTimeStep, this->iteration);
this->UnPrecondition(this->petsc_dx);
} else {
this->UnPrecondition(this->petsc_dx);
this->SaveDebugInfoAfter(this->nTimeStep, this->iteration);
}
// Copy dx
VecGetArray(this->petsc_dx, &fvec);
for (len_t i = 0; i < this->matrix_size; i++)
this->dx[i] = fvec[i];
VecRestoreArray(this->petsc_dx, &fvec);
return this->dx;
}
/**
* Helper function to damping factor calculation; given a quantity
* X0 and its change dX in the iteration, returns the maximal step
* length (damping) such that X>threshold*X0 after the iteration
*/
const real_t MaximalStepLengthAtGridPoint(
real_t X0, real_t dX, real_t threshold
){
real_t maxStepAtI = 1.0;
if(dX>X0*std::numeric_limits<real_t>::min()) // dX positive, with check to avoid overflow
maxStepAtI = (1-threshold) * X0 / dX;
return maxStepAtI;
}
/**
* Returns a dampingFactor such that x1 = x0 - dampingFactor*dx satisfies
* physically-motivated constraints, such as positivity of temperature.
* If initial guess dx from Newton step satisfies all constraints, returns 1.
*/
const real_t MaximalPhysicalStepLength(real_t *x0, const real_t *dx, len_t iteration, std::vector<len_t> nontrivial_unknowns, FVM::UnknownQuantityHandler *unknowns, IonHandler *ionHandler, len_t &id_uqn){
real_t maxStepLength = 1.0;
real_t threshold = 0.1;
std::vector<len_t> ids_nonNegativeQuantities;
// add those quantities which we expect to be non-negative
// T_cold and n_cold will crash the simulation if negative, so they should always be added
ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_T_COLD));
ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_N_TOT));
ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_N_COLD));
if(unknowns->HasUnknown(OptionConstants::UQTY_W_COLD))
ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_W_COLD));
if(unknowns->HasUnknown(OptionConstants::UQTY_WI_ENER))
ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_WI_ENER));
if(unknowns->HasUnknown(OptionConstants::UQTY_NI_DENS))
ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_NI_DENS));
bool nonNegativeZeff = true;
const len_t id_ni = unknowns->GetUnknownID(OptionConstants::UQTY_ION_SPECIES);
const len_t N = nontrivial_unknowns.size();
const len_t N_nn = ids_nonNegativeQuantities.size();
len_t offset = 0;
// sum over non-trivial unknowns
for (len_t it=0; it<N; it++) {
const len_t id = nontrivial_unknowns[it];
FVM::UnknownQuantity *uq = unknowns->GetUnknown(id);
len_t NCells = uq->NumberOfElements();
// check whether unknown it is a non-negative quantity
bool isNonNegativeQuantity = false;
for (len_t it_nn = 0; it_nn < N_nn; it_nn++)
if(id==ids_nonNegativeQuantities[it_nn])
isNonNegativeQuantity = true;
// Quantities which physically cannot be negative, require that they cannot
// be reduced by more than some threshold in each iteration.
if(isNonNegativeQuantity)
for(len_t i=0; i<NCells; i++){
// require x1 > threshold*x0
real_t maxStepAtI = MaximalStepLengthAtGridPoint(x0[offset+i], dx[offset+i], threshold);
// if this is a stronger constaint than current maxlength, override
if(maxStepAtI < maxStepLength && maxStepAtI>0){
maxStepLength = maxStepAtI;
id_uqn = id;
}
}
if(nonNegativeZeff && id==id_ni){
len_t nZ = ionHandler->GetNZ();
const len_t *Zs = ionHandler->GetZs();
len_t nr = NCells/uq->NumberOfMultiples();
for(len_t ir=0; ir<nr; ir++){
real_t nZ0Z0=0;
real_t dnZ0Z0=0;
for(len_t iz=0; iz<nZ; iz++)
for(len_t Z0=0; Z0<=Zs[iz]; Z0++){
len_t ind = ionHandler->GetIndex(iz,Z0);
nZ0Z0 += Z0*Z0*x0[offset+ind*nr+ir];
dnZ0Z0 += Z0*Z0*dx[offset+ind*nr+ir];
}
real_t maxStepAtI = MaximalStepLengthAtGridPoint(nZ0Z0, dnZ0Z0, threshold);
if(maxStepAtI < maxStepLength && maxStepAtI>0){
maxStepLength = maxStepAtI;
id_uqn = id;
}
}
}
offset += NCells;
}
// Add automatic damping for abnormally high number of iterations to force convergence
bool automaticDampingWithItertion = false; // skip the below for now; the method did not seem to stabilize ill-posed cases
if(automaticDampingWithItertion){
real_t minDamping = 0.1;
len_t itMax = 100;
len_t itThresh = 30;
if(iteration>itThresh)
maxStepLength *= std::max(minDamping,
1.0 - ((1.0-minDamping)*(iteration-itThresh))/(itMax-itThresh));
}
return maxStepLength;
}
/**
* Update the current solution with the Newton step 'dx'.
*
* dx: Newton step to take.
*/
const real_t *SolverNonLinear::UpdateSolution(const real_t *dx) {
len_t id_uqn;
real_t dampingFactor = MaximalPhysicalStepLength(x0,dx,iteration,nontrivial_unknowns,unknowns,ionHandler,id_uqn);
if(dampingFactor < 1 && this->Verbose()) {
DREAM::IO::PrintInfo();
DREAM::IO::PrintInfo("Newton iteration dynamically damped for unknown quantity: %s",unknowns->GetUnknown(id_uqn)->GetName().c_str());
DREAM::IO::PrintInfo("to conserve positivity, by a factor: %e", dampingFactor);
DREAM::IO::PrintInfo();
}
for (len_t i = 0; i < this->matrix_size; i++)
this->x1[i] = this->x0[i] - dampingFactor*dx[i];
return this->x1;
}
/**
* Print timing information after the solve.
*/
void SolverNonLinear::PrintTimings() {
this->timeKeeper->PrintTimings(true, 0);
this->Solver::PrintTimings_rebuild();
}
/**
* Save timing information to the given SFile object.
*
* sf: SFile object to save timing information to.
* path: Path in file to save timing information to.
*/
void SolverNonLinear::SaveTimings(SFile *sf, const string& path) {
this->timeKeeper->SaveTimings(sf, path);
sf->CreateStruct(path+"/rebuild");
this->Solver::SaveTimings_rebuild(sf, path+"/rebuild");
}
/**
* Save debugging information for the current iteration,
* _before_ the new solution has been calculated.
*
* iTimeStep: Current time step index.
* iIteration: Current iteration index.
*/
void SolverNonLinear::SaveDebugInfoBefore(
len_t iTimeStep, len_t iIteration
) {
if ((this->savetimestep == iTimeStep &&
(this->saveiteration == iIteration || this->saveiteration == 0)) ||
this->savetimestep == 0) {
string suffix = "_" + to_string(iTimeStep) + "_" + to_string(iIteration);
if (this->savejacobian) {
string jacname;
if (this->savetimestep == 0 || this->saveiteration == 0)
jacname = "petsc_jac" + suffix;
else
jacname = "petsc_jac";
SaveJacobian(jacname);
}
if (this->savevector) {
string resname;
if (this->savetimestep == 0 || this->saveiteration == 0)
resname = "residual" + suffix + ".mat";
else
resname = "residual.mat";
real_t *fvec;
VecGetArray(this->petsc_F, &fvec);
SFile *sf = SFile::Create(resname, SFILE_MODE_WRITE);
sf->WriteList("F", fvec, this->jacobian->GetNRows());
sf->Close();
VecRestoreArray(this->petsc_F, &fvec);
}
if (this->savenumjac) {
string jacname;
if (this->savetimestep == 0 || this->saveiteration == 0)
jacname = "petsc_jac" + suffix;
else
jacname = "petsc_jac";
SaveNumericalJacobian(jacname);
}
if (this->printjacobianinfo)
this->jacobian->PrintInfo();
}
}
/**
* Save debugging information for the current iteration,
* _after_ the new solution has been calculated.
*
* iTimeStep: Current time step index.
* iIteration: Current iteration index.
*/
void SolverNonLinear::SaveDebugInfoAfter(
len_t iTimeStep, len_t iIteration
) {
if ((this->savetimestep == iTimeStep &&
(this->saveiteration == iIteration || this->saveiteration == 0)) ||
this->savetimestep == 0) {
string suffix = "_" + to_string(iTimeStep) + "_" + to_string(iIteration);
if (this->savesolution) {
string solname = "solution_dx";
if (this->savetimestep == 0 || this->saveiteration == 0)
solname += suffix;
solname += ".mat";
real_t *xvec;
VecGetArray(this->petsc_dx, &xvec);
SFile *sf = SFile::Create(solname, SFILE_MODE_WRITE);
sf->WriteList("dx", xvec, this->jacobian->GetNRows());
sf->Close();
VecRestoreArray(this->petsc_dx, &xvec);
}
// Save full output?
if (this->savesystem) {
string outname = "debugout";
if (this->savetimestep == 0 || this->saveiteration == 0)
outname += suffix;
outname += ".h5";
OutputGeneratorSFile *outgen = new OutputGeneratorSFile(this->eqsys, outname);
outgen->SaveCurrent();
delete outgen;
}
}
}
/**
* Enable or disable debug mode.
*
* printjacobianinfo: If true, prints detailed debug information about the
* PETSc matrix for the jacobian in every iteration.
* savejacobian: If true, saves the jacobian using a PETSc viewer in
* the specified time step(s).
* savesolution: If true, saves the solution vector in the specified
* time step(s).
* savevector: If true, saves the residual vector in the specified
* time step(s).
* savenumjac: If true, calculates the jacobian numerically and saves
* it using a PETSc viewer in the specified time step(s).
* timestep: Time step index to save debug info for. If 0, saves
* the information in every iteration of every time step.
* iteration: Iteration of specified time step to save debug info for.
* savesystem: If true, saves the full equation system, including grid information,
* to a proper DREAMOutput file. However, only the most recently obtained
* solution is saved.
* rescaled: If true, saves the rescaled version of the jacobian/solution/residual.
*/
void SolverNonLinear::SetDebugMode(
bool printjacobianinfo, bool savesolution, bool savejacobian, bool savevector,
bool savenumjac, int_t timestep, int_t iteration, bool savesystem, bool rescaled
) {
this->printjacobianinfo = printjacobianinfo;
this->savejacobian = savejacobian;
this->savesolution = savesolution;
this->savevector = savevector;
this->savenumjac = savenumjac;
this->savetimestep = timestep;
this->saveiteration = iteration;
this->savesystem = savesystem;
this->debugrescaled = rescaled;
}
/**
* Override switch to backup inverter.
*/
void SolverNonLinear::SwitchToBackupInverter() {
// Switch inverter to use
this->Solver::SwitchToBackupInverter();
// Restore solution to initial guess for time step
this->ResetSolution();
}
/**
* Write basic data from the solver to the output file.
* This data is mainly statistics about the solution.
*
* sf: SFile object to use for writing.
* name: Name of group within file to store data in.
*/
void SolverNonLinear::WriteDataSFile(SFile *sf, const std::string& name) {
sf->CreateStruct(name);
int32_t type = (int32_t)OptionConstants::SOLVER_TYPE_NONLINEAR;
sf->WriteList(name+"/type", &type, 1);
// Number of iterations per time step
sf->WriteList(name+"/iterations", this->nIterations.data(), this->nIterations.size());
// Whether or not backup inverter was used for a given time step
len_t nubi = this->usedBackupInverter.size();
int32_t *ubi = new int32_t[nubi];
for (len_t i = 0; i < nubi; i++)
ubi[i] = this->usedBackupInverter[i] ? 1 : 0;
sf->WriteList(name+"/backupinverter", ubi, nubi);
delete [] ubi;
}
| 32.72191 | 204 | 0.671646 |
chalmersplasmatheory
|
11fe9a58a48bcc51367fa66399833a89d61dfc03
| 10,976 |
cpp
|
C++
|
bindings/c/test/mako/operations.cpp
|
BearerPipelineTest/foundationdb
|
02fc80f12eb7bbb94a12469b2ca066f33bd23aa8
|
[
"Apache-2.0"
] | 1 |
2022-02-23T07:17:32.000Z
|
2022-02-23T07:17:32.000Z
|
bindings/c/test/mako/operations.cpp
|
BearerPipelineTest/foundationdb
|
02fc80f12eb7bbb94a12469b2ca066f33bd23aa8
|
[
"Apache-2.0"
] | null | null | null |
bindings/c/test/mako/operations.cpp
|
BearerPipelineTest/foundationdb
|
02fc80f12eb7bbb94a12469b2ca066f33bd23aa8
|
[
"Apache-2.0"
] | 1 |
2022-03-01T12:28:03.000Z
|
2022-03-01T12:28:03.000Z
|
/*
* operations.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2022 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "blob_granules.hpp"
#include "operations.hpp"
#include "mako.hpp"
#include "logger.hpp"
#include "utils.hpp"
#include <array>
extern thread_local mako::Logger logr;
namespace mako {
using namespace fdb;
const std::array<Operation, MAX_OP> opTable{
{ { "GRV",
{ { StepKind::READ,
[](Transaction& tx, Arguments const&, ByteString&, ByteString&, ByteString&) {
return tx.getReadVersion().eraseType();
},
[](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString&) {
if (f && !f.error()) {
f.get<future_var::Int64>();
}
} } },
1,
false },
{ "GET",
{ { StepKind::READ,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) {
return tx.get(key, false /*snapshot*/).eraseType();
},
[](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) {
if (f && !f.error()) {
f.get<future_var::Value>();
}
} } },
1,
false },
{ "GETRANGE",
{ { StepKind::READ,
[](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) {
return tx
.getRange(key_select::firstGreaterOrEqual(begin),
key_select::lastLessOrEqual(end, 1),
0 /*limit*/,
0 /*target_bytes*/,
args.streaming_mode,
0 /*iteration*/,
false /*snapshot*/,
args.txnspec.ops[OP_GETRANGE][OP_REVERSE])
.eraseType();
},
[](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) {
if (f && !f.error()) {
f.get<future_var::KeyValueArray>();
}
} } },
1,
false },
{ "SGET",
{ { StepKind::READ,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) {
return tx.get(key, true /*snapshot*/).eraseType();
},
[](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) {
if (f && !f.error()) {
f.get<future_var::Value>();
}
} } },
1,
false },
{ "SGETRANGE",
{ {
StepKind::READ,
[](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) {
return tx
.getRange(key_select::firstGreaterOrEqual(begin),
key_select::lastLessOrEqual(end, 1),
0 /*limit*/,
0 /*target_bytes*/,
args.streaming_mode,
0 /*iteration*/,
true /*snapshot*/,
args.txnspec.ops[OP_GETRANGE][OP_REVERSE])
.eraseType();
},
[](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) {
if (f && !f.error()) {
f.get<future_var::KeyValueArray>();
}
} } },
1,
false },
{ "UPDATE",
{ { StepKind::READ,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) {
return tx.get(key, false /*snapshot*/).eraseType();
},
[](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) {
if (f && !f.error()) {
f.get<future_var::Value>();
}
} },
{ StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) {
randomString(value.data(), args.value_length);
tx.set(key, value);
return Future();
} } },
2,
true },
{ "INSERT",
{ { StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) {
// key[0..args.key_length] := concat(key_prefix, random_string)
randomString(key.data() + intSize(KEY_PREFIX), args.key_length - intSize(KEY_PREFIX));
randomString(value.data(), args.value_length);
tx.set(key, value);
return Future();
} } },
1,
true },
{ "INSERTRANGE",
{ { StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) {
randomString(value.data(), args.value_length);
// key[0..args.key_length] := concat(prefix, random_string, num[0..range_digits])
const auto range = args.txnspec.ops[OP_INSERTRANGE][OP_RANGE];
assert(range > 0);
const auto range_digits = digits(range);
const auto random_len = args.key_length - intSize(KEY_PREFIX) - range_digits;
randomString(&key[intSize(KEY_PREFIX)], random_len);
for (auto i = 0; i < range; i++) {
numericWithFill(&key[args.key_length - range_digits], range_digits, i);
tx.set(key, value);
}
return Future();
} } },
1,
true },
{ "OVERWRITE",
{ { StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) {
randomString(value.data(), args.value_length);
tx.set(key, value);
return Future();
} } },
1,
true },
{ "CLEAR",
{ { StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) {
tx.clear(key);
return Future();
} } },
1,
true },
{ "SETCLEAR",
{ { StepKind::COMMIT,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) {
randomString(&key[KEY_PREFIX.size()], args.key_length - intSize(KEY_PREFIX));
randomString(value.data(), args.value_length);
tx.set(key, value);
return tx.commit().eraseType();
} },
{ StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) {
tx.reset(); // assuming commit from step 0 worked.
tx.clear(key); // key should forward unchanged from step 0
return Future();
} } },
2,
true },
{ "CLEARRANGE",
{ { StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) {
tx.clearRange(begin, end);
return Future();
} } },
1,
true },
{ "SETCLEARRANGE",
{ { StepKind::COMMIT,
[](Transaction& tx, Arguments const& args, ByteString& key_begin, ByteString& key, ByteString& value) {
randomString(value.data(), args.value_length);
// key[0..args.key_length] := concat(prefix, random_string, num[0..range_digits])
const auto range = args.txnspec.ops[OP_SETCLEARRANGE][OP_RANGE];
assert(range > 0);
const auto range_digits = digits(range);
const auto random_len = args.key_length - intSize(KEY_PREFIX) - range_digits;
randomString(&key[KEY_PREFIX.size()], random_len);
for (auto i = 0; i < range; i++) {
numericWithFill(&key[args.key_length - range_digits], range_digits, i);
tx.set(key, value);
if (i == 0)
key_begin.assign(key);
}
return tx.commit().eraseType();
} },
{ StepKind::IMM,
[](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) {
tx.reset();
tx.clearRange(begin, end);
return Future();
} } },
2,
true },
{ "COMMIT", { { StepKind::NONE, nullptr } }, 0, false },
{ "TRANSACTION", { { StepKind::NONE, nullptr } }, 0, false },
{ "READBLOBGRANULE",
{ { StepKind::ON_ERROR,
[](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) {
auto err = Error{};
err = tx.setOptionNothrow(FDB_TR_OPTION_READ_YOUR_WRITES_DISABLE, BytesRef());
if (err) {
// Issuing read/writes before disabling RYW results in error.
// Possible malformed workload?
// As workloads execute in sequence, retrying would likely repeat this error.
fmt::print(stderr, "ERROR: TR_OPTION_READ_YOUR_WRITES_DISABLE: {}", err.what());
return Future();
}
// Allocate a separate context per call to avoid multiple threads accessing
auto user_context = blob_granules::local_file::UserContext(args.bg_file_path);
auto api_context = blob_granules::local_file::createApiContext(user_context, args.bg_materialize_files);
auto r = tx.readBlobGranules(begin,
end,
0 /* beginVersion*/,
-2, /* endVersion. -2 (latestVersion) is use txn read version */
api_context);
user_context.clear();
auto out = Result::KeyValueArray{};
err = r.getKeyValueArrayNothrow(out);
if (!err || err.is(2037 /*blob_granule_not_materialized*/))
return Future();
const auto level = (err.is(1020 /*not_committed*/) || err.is(1021 /*commit_unknown_result*/) ||
err.is(1213 /*tag_throttled*/))
? VERBOSE_WARN
: VERBOSE_NONE;
logr.printWithLogLevel(level, "ERROR", "get_keyvalue_array() after readBlobGranules(): {}", err.what());
return tx.onError(err).eraseType();
} } },
1,
false } }
};
} // namespace mako
| 39.768116 | 117 | 0.52961 |
BearerPipelineTest
|
11fef5edd78a78f36c6e940c3d169c9fa005b273
| 5,082 |
cc
|
C++
|
ecs/src/model/DescribeSnapshotGroupsRequest.cc
|
aliyun/aliyun-openapi-cpp-sdk
|
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
|
[
"Apache-2.0"
] | 89 |
2018-02-02T03:54:39.000Z
|
2021-12-13T01:32:55.000Z
|
ecs/src/model/DescribeSnapshotGroupsRequest.cc
|
aliyun/aliyun-openapi-cpp-sdk
|
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
|
[
"Apache-2.0"
] | 89 |
2018-03-14T07:44:54.000Z
|
2021-11-26T07:43:25.000Z
|
ecs/src/model/DescribeSnapshotGroupsRequest.cc
|
aliyun/aliyun-openapi-cpp-sdk
|
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
|
[
"Apache-2.0"
] | 69 |
2018-01-22T09:45:52.000Z
|
2022-03-28T07:58:38.000Z
|
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ecs/model/DescribeSnapshotGroupsRequest.h>
using AlibabaCloud::Ecs::Model::DescribeSnapshotGroupsRequest;
DescribeSnapshotGroupsRequest::DescribeSnapshotGroupsRequest()
: RpcServiceRequest("ecs", "2014-05-26", "DescribeSnapshotGroups") {
setMethod(HttpRequest::Method::Post);
}
DescribeSnapshotGroupsRequest::~DescribeSnapshotGroupsRequest() {}
long DescribeSnapshotGroupsRequest::getResourceOwnerId() const {
return resourceOwnerId_;
}
void DescribeSnapshotGroupsRequest::setResourceOwnerId(long resourceOwnerId) {
resourceOwnerId_ = resourceOwnerId;
setParameter(std::string("ResourceOwnerId"), std::to_string(resourceOwnerId));
}
std::string DescribeSnapshotGroupsRequest::getResourceGroupId() const {
return resourceGroupId_;
}
void DescribeSnapshotGroupsRequest::setResourceGroupId(const std::string &resourceGroupId) {
resourceGroupId_ = resourceGroupId;
setParameter(std::string("ResourceGroupId"), resourceGroupId);
}
std::string DescribeSnapshotGroupsRequest::getRegionId() const {
return regionId_;
}
void DescribeSnapshotGroupsRequest::setRegionId(const std::string ®ionId) {
regionId_ = regionId;
setParameter(std::string("RegionId"), regionId);
}
std::string DescribeSnapshotGroupsRequest::getNextToken() const {
return nextToken_;
}
void DescribeSnapshotGroupsRequest::setNextToken(const std::string &nextToken) {
nextToken_ = nextToken;
setParameter(std::string("NextToken"), nextToken);
}
std::vector<DescribeSnapshotGroupsRequest::Tag> DescribeSnapshotGroupsRequest::getTag() const {
return tag_;
}
void DescribeSnapshotGroupsRequest::setTag(const std::vector<DescribeSnapshotGroupsRequest::Tag> &tag) {
tag_ = tag;
for(int dep1 = 0; dep1 != tag.size(); dep1++) {
auto tagObj = tag.at(dep1);
std::string tagObjStr = std::string("Tag") + "." + std::to_string(dep1 + 1);
setParameter(tagObjStr + ".Key", tagObj.key);
setParameter(tagObjStr + ".Value", tagObj.value);
}
}
std::string DescribeSnapshotGroupsRequest::getResourceOwnerAccount() const {
return resourceOwnerAccount_;
}
void DescribeSnapshotGroupsRequest::setResourceOwnerAccount(const std::string &resourceOwnerAccount) {
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter(std::string("ResourceOwnerAccount"), resourceOwnerAccount);
}
std::string DescribeSnapshotGroupsRequest::getOwnerAccount() const {
return ownerAccount_;
}
void DescribeSnapshotGroupsRequest::setOwnerAccount(const std::string &ownerAccount) {
ownerAccount_ = ownerAccount;
setParameter(std::string("OwnerAccount"), ownerAccount);
}
std::vector<std::string> DescribeSnapshotGroupsRequest::getSnapshotGroupId() const {
return snapshotGroupId_;
}
void DescribeSnapshotGroupsRequest::setSnapshotGroupId(const std::vector<std::string> &snapshotGroupId) {
snapshotGroupId_ = snapshotGroupId;
}
long DescribeSnapshotGroupsRequest::getOwnerId() const {
return ownerId_;
}
void DescribeSnapshotGroupsRequest::setOwnerId(long ownerId) {
ownerId_ = ownerId;
setParameter(std::string("OwnerId"), std::to_string(ownerId));
}
std::vector<std::string> DescribeSnapshotGroupsRequest::getAdditionalAttributes() const {
return additionalAttributes_;
}
void DescribeSnapshotGroupsRequest::setAdditionalAttributes(const std::vector<std::string> &additionalAttributes) {
additionalAttributes_ = additionalAttributes;
}
std::string DescribeSnapshotGroupsRequest::getInstanceId() const {
return instanceId_;
}
void DescribeSnapshotGroupsRequest::setInstanceId(const std::string &instanceId) {
instanceId_ = instanceId;
setParameter(std::string("InstanceId"), instanceId);
}
std::string DescribeSnapshotGroupsRequest::getName() const {
return name_;
}
void DescribeSnapshotGroupsRequest::setName(const std::string &name) {
name_ = name;
setParameter(std::string("Name"), name);
}
int DescribeSnapshotGroupsRequest::getMaxResults() const {
return maxResults_;
}
void DescribeSnapshotGroupsRequest::setMaxResults(int maxResults) {
maxResults_ = maxResults;
setParameter(std::string("MaxResults"), std::to_string(maxResults));
}
std::vector<std::string> DescribeSnapshotGroupsRequest::getStatus() const {
return status_;
}
void DescribeSnapshotGroupsRequest::setStatus(const std::vector<std::string> &status) {
status_ = status;
}
| 32.576923 | 116 | 0.757182 |
aliyun
|
f502ee1deac07713d6f8eac80c65fe975c84cea6
| 1,976 |
cpp
|
C++
|
avx512-string/speed_strrchr.cpp
|
demonMOE-s/Toys
|
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
|
[
"BSD-2-Clause"
] | 2 |
2019-01-06T05:32:18.000Z
|
2019-12-12T04:54:56.000Z
|
avx512-string/speed_strrchr.cpp
|
demonMOE-s/Toys
|
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
|
[
"BSD-2-Clause"
] | null | null | null |
avx512-string/speed_strrchr.cpp
|
demonMOE-s/Toys
|
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
|
[
"BSD-2-Clause"
] | null | null | null |
#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <immintrin.h>
#include "gettime.cpp"
#include "avx512f-strrchr.cpp"
class TestCase {
private:
char* buffer;
size_t size;
volatile size_t count;
public:
TestCase(size_t s)
: size(s) {
buffer = new char[s + 64];
memset(buffer, '?', s + 64);
buffer[s - 1] = 0;
}
~TestCase() {
delete[] buffer;
}
public:
template <typename STRCHR>
void run(STRCHR strrchr_function) {
for (size_t i=0; i < size; i++) {
buffer[i] = 'X';
count += int(strrchr_function(buffer, 'X') != NULL);
buffer[i] = '?';
}
}
void run_std_function() {
for (size_t i=0; i < size; i++) {
buffer[i] = 'X';
count += int(strrchr(buffer, 'X') != NULL);
buffer[i] = '?';
}
}
};
class Test {
size_t size;
size_t iterations;
uint32_t ref_time;
public:
Test(size_t size, size_t iterations)
: size(size)
, iterations(iterations)
, ref_time(0) {}
template <typename STRCHR>
void measure(const char* name, STRCHR strrchr_function) {
printf("%-20s [", name); fflush(stdout);
TestCase test(size);
const uint32_t t1 = get_time();
for (size_t i=0; i < iterations; i++) {
putchar('.'); fflush(stdout);
test.run(strrchr_function);
}
const uint32_t t2 = get_time();
const uint32_t time = t2 - t1;
printf("] %0.4f s", time/1000000.0);
if (ref_time == 0) {
ref_time = time;
} else {
printf(" (%0.2f)", ref_time/double(time));
}
putchar('\n');
}
};
int main() {
Test test(10*1024, 5);
test.measure("std::strrchr", [](const char* s, int c){return strrchr(s, c);});
test.measure("AVX512F", avx512f_strrchr);
}
| 19.76 | 82 | 0.520243 |
demonMOE-s
|
f5034e6203be2938ccfe99db5b1475da39f48d1c
| 10,595 |
cpp
|
C++
|
QtMainWindow.cpp
|
nvoronin1337/Qt-Database-Management-System
|
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
|
[
"MIT"
] | null | null | null |
QtMainWindow.cpp
|
nvoronin1337/Qt-Database-Management-System
|
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
|
[
"MIT"
] | null | null | null |
QtMainWindow.cpp
|
nvoronin1337/Qt-Database-Management-System
|
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
|
[
"MIT"
] | null | null | null |
#include "QtMainWindow.h"
QtMainWindow::QtMainWindow(const std::string username, QWidget* parent)
: QMainWindow(parent)
{
setupUi(this);
this->username = username;
this->user = new GuiUser(username);
std::string fileName = username + "_form_gui.txt";
std::string title = "Data Hive | User: " + username;
setWindowTitle(QString::fromStdString(title));
QStringList headers;
headers << tr("Title") << tr("Description") << tr("Date Modified");
QFile file(QString::fromStdString(fileName));
file.open(QIODevice::ReadOnly);
tree_model = new TreeModel(headers, file.readAll());
tree_model_selection = new QItemSelectionModel(tree_model);
file.close();
treeView->header()->setStyleSheet("::section{ background-color: #424242;}");
treeView->setHeaderHidden(false);
treeView->setModel(tree_model);
treeView->setSelectionModel(tree_model_selection);
for (int column = 0; column < tree_model->columnCount(); ++column)
treeView->resizeColumnToContents(column);
setupSlots();
}
QtMainWindow::~QtMainWindow()
{
saveModelData(true);
}
void QtMainWindow::populateSimpleTreeFromStorage() const
{
QStandardItem* db_item;
QStandardItem* table_item;
QStandardItem* action1;
QList<QStandardItem*> items;
QStandardItemModel *tree_model = new QStandardItemModel();
/**
* Loop through the Storage. For each database add an item to the tree.
*/
for (size_t i = 0; i < user->getStorageManager()->getStorage()->databases.size(); i++) {
db_item = new QStandardItem(QIcon("dbIcon.png"), QString::fromStdString(user->getStorageManager()->getStorage()->databases[i]->databaseName));
action1 = new QStandardItem(QIcon("deleteIcon.png"), QString::fromStdString(""));
items.append(db_item);
items.append(action1);
tree_model->appendRow(items);
items.clear();
// Loop through the database. For each table add an item to the tree.
for (size_t k = 0; k < user->getStorageManager()->getStorage()->databases[i]->tables.size(); k++) {
table_item = new QStandardItem(QIcon("tableIcon.png"), QString::fromStdString(user->getStorageManager()->getStorage()->databases[i]->tables[k]->tableName));
action1 = new QStandardItem(QIcon("deleteIcon.png"), QString::fromStdString(""));
items.append(table_item);
items.append(action1);
db_item->appendRow(items);
items.clear();
}
}
treeView->setModel(tree_model);
QModelIndex child_index = tree_model->index(0,0);
tree_model->item(0, 0)->removeRow(0);
}
void QtMainWindow::setupSlots() noexcept
{
connect(readMeAction, &QAction::triggered, this, &QtMainWindow::openUrl);
connect(treeView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &QtMainWindow::updateActions);
connect(menuActions, &QMenu::aboutToShow, this, &QtMainWindow::updateActions);
connect(insertRowAction, &QAction::triggered, this, &QtMainWindow::insertRow);
connect(insertColumnAction, &QAction::triggered, this, &QtMainWindow::insertColumn);
connect(removeRowAction, &QAction::triggered, this, &QtMainWindow::removeRow);
connect(removeColumnAction, &QAction::triggered, this, &QtMainWindow::removeColumn);
connect(insertChildAction, &QAction::triggered, this, &QtMainWindow::insertChild);
connect(btnSave, SIGNAL(pressed()), this, SLOT(saveModelData()));
connect(btnDetails, SIGNAL(pressed()), this, SLOT(btn_details_pressed()));
updateActions();
}
void QtMainWindow::writeItemData(QVector<QVariant> item_data, bool isChild) const noexcept
{
std::string filename_str = user->getUsername() + "_form_gui.txt";
QString filename = QString::fromStdString(filename_str);
QFile fileout(filename);
if (fileout.open(QFile::ReadWrite | QFile::Text | QFile::Append)) {
QTextStream out(&fileout);
for (QVector<QVariant>::iterator iter = item_data.begin(); iter < item_data.end(); iter++) {
if(!isChild)
out << iter->toString() << " ";
else
out << " " << iter->toString() << " ";
}
out << "\n";
fileout.close();
}
}
void QtMainWindow::updateUsersStorage(TreeItem* parent,TreeItem* child) const noexcept
{
auto parent_data = parent->getItemData();
QVector<QVariant>::iterator parent_iter = parent_data.begin();
std::string database_name = parent_iter->toString().toStdString();
// if database -> add database
if (child == nullptr) {
user->getStorageManager()->addDatabase(database_name);
}
// if table -> addTable
else {
auto child_data = child->getItemData();
QVector<QVariant>::iterator child_iter = child_data.begin();
std::string table_name = child_iter->toString().toStdString();
//empty columns for now (better change)
std::vector<std::string> cols = { "test" };
user->getStorageManager()->addTableToDatabase(database_name, table_name, cols);
}
}
void QtMainWindow::saveModelData(bool isQuitting) const
{
user->getStorageManager()->getStorage()->databases.clear();
std::string filename_str = user->getUsername() + "_form_gui.txt";
std::ofstream ofs;
ofs.open(filename_str, std::ofstream::out | std::ofstream::trunc);
ofs.close();
auto row_max = tree_model->rowCount();
auto column = 0;
TreeItem* tree_item;
QModelIndex model_index;
for (int row = 0; row < row_max; row++) {
model_index = tree_model->index(row, column);
tree_item = tree_model->getItem(model_index);
auto item_data = tree_item->getItemData();
writeItemData(item_data, false);
updateUsersStorage(tree_item);
if (tree_item->childCount() > 0) {
for (int child_num = 0; child_num < tree_item->childCount(); child_num++) {
auto childItem = tree_item->child(child_num);
writeItemData(childItem->getItemData(), true);
updateUsersStorage(tree_item, childItem);
}
}
}
auto helper = std::make_unique<dbms::FileIOHelper>();
helper->saveStorageText(user->getStorageManager()->getStorage(), this->user->getUsername() + ".txt");
if (!isQuitting) {
QMessageBox msgbox;
msgbox.setText("Data is saved!");
msgbox.setStyleSheet("QMessageBox { background-color: #424242; font: 75 italic 12pt \"Gill Sans MT\"; color: rgb(1, 223, 165);}");
msgbox.exec();
}
}
// DETAILS PRESSED
void QtMainWindow::btn_details_pressed() const
{
QModelIndex index = treeView->selectionModel()->currentIndex();
auto item = tree_model->getItem(index);
if (item->childCount() != 0) {
QMessageBox msgbox;
msgbox.setText("Please select a table!");
msgbox.setStyleSheet("QMessageBox { background-color: #424242; font: 75 italic 12pt \"Gill Sans MT\"; color: rgb(1, 223, 165);}");
msgbox.exec();
return;
}
auto parent_item = item->parent();
auto parent_item_data = parent_item->getItemData();
auto iter_parent = parent_item_data.begin();
std::string database = iter_parent->toString().toStdString();
auto item_data = item->getItemData();
auto iter = item_data.begin();
std::string table_name = iter->toString().toStdString();
std::unique_ptr<QtTableDetailsDialog> details_dialog = std::make_unique<QtTableDetailsDialog>(database, table_name, user);
//Qt::WindowFlags flags(Qt::WindowTitleHint);
//details_dialog->setWindowFlags(flags);
details_dialog->exec();
}
// SLOTS
void QtMainWindow::insertChild()
{
QModelIndex index = treeView->selectionModel()->currentIndex();
QAbstractItemModel* model = treeView->model();
if (model->columnCount(index) == 0) {
if (!model->insertColumn(0, index))
return;
}
if (!model->insertRow(0, index))
return;
for (int column = 0; column < model->columnCount(index); ++column) {
QModelIndex child = model->index(0, column, index);
model->setData(child, QVariant("[No data]"), Qt::EditRole);
if (!model->headerData(column, Qt::Horizontal).isValid())
model->setHeaderData(column, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole);
}
treeView->selectionModel()->setCurrentIndex(model->index(0, 0, index),
QItemSelectionModel::ClearAndSelect);
updateActions();
}
bool QtMainWindow::insertColumn()
{
QAbstractItemModel* model = treeView->model();
int column = treeView->selectionModel()->currentIndex().column();
// Insert a column in the parent item.
bool changed = model->insertColumn(column + 1);
if (changed)
model->setHeaderData(column + 1, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole);
updateActions();
return changed;
}
void QtMainWindow::insertRow()
{
QModelIndex index = treeView->selectionModel()->currentIndex();
QAbstractItemModel* model = treeView->model();
if (!model->insertRow(index.row() + 1, index.parent()))
return;
updateActions();
for (int column = 0; column < model->columnCount(index.parent()); ++column) {
QModelIndex child = model->index(index.row() + 1, column, index.parent());
model->setData(child, QVariant("[No data]"), Qt::EditRole);
}
}
bool QtMainWindow::removeColumn()
{
QAbstractItemModel* model = treeView->model();
int column = treeView->selectionModel()->currentIndex().column();
// Insert columns in each child of the parent item.
bool changed = model->removeColumn(column);
if (changed)
updateActions();
return changed;
}
void QtMainWindow::removeRow()
{
QModelIndex index = treeView->selectionModel()->currentIndex();
QAbstractItemModel* model = treeView->model();
if (model->removeRow(index.row(), index.parent()))
updateActions();
}
bool QtMainWindow::openUrl()
{
return QDesktopServices::openUrl(QUrl("file:///C:/Users/Nikita/source/repos/QtGuiDBMS_v4_0/QtGuiApplication1/html/annotated.html", QUrl::TolerantMode));
}
void QtMainWindow::updateActions()
{
bool hasSelection = !treeView->selectionModel()->selection().isEmpty();
removeRowAction->setEnabled(hasSelection);
removeColumnAction->setEnabled(hasSelection);
bool hasCurrent = treeView->selectionModel()->currentIndex().isValid();
insertRowAction->setEnabled(hasCurrent);
insertColumnAction->setEnabled(hasCurrent);
if (hasCurrent) {
treeView->closePersistentEditor(treeView->selectionModel()->currentIndex());
int row = treeView->selectionModel()->currentIndex().row();
int column = treeView->selectionModel()->currentIndex().column();
if (treeView->selectionModel()->currentIndex().parent().isValid())
Ui::QtGuiApplication1Class::statusBar->showMessage(tr("Position: (%1,%2)").arg(row).arg(column));
else
Ui::QtGuiApplication1Class::statusBar->showMessage(tr("Position: (%1,%2) in top level").arg(row).arg(column));
}
}
| 32.400612 | 160 | 0.695422 |
nvoronin1337
|
f50379b3edb9761db1e8ac54cdd79386bea95457
| 8,374 |
cpp
|
C++
|
android/android_9/frameworks/native/libs/gui/BufferItem.cpp
|
yakuizhao/intel-vaapi-driver
|
b2bb0383352694941826543a171b557efac2219b
|
[
"MIT"
] | null | null | null |
android/android_9/frameworks/native/libs/gui/BufferItem.cpp
|
yakuizhao/intel-vaapi-driver
|
b2bb0383352694941826543a171b557efac2219b
|
[
"MIT"
] | null | null | null |
android/android_9/frameworks/native/libs/gui/BufferItem.cpp
|
yakuizhao/intel-vaapi-driver
|
b2bb0383352694941826543a171b557efac2219b
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gui/BufferItem.h>
#include <ui/Fence.h>
#include <ui/GraphicBuffer.h>
#include <system/window.h>
namespace android {
template<typename T>
static inline constexpr uint32_t low32(const T n) {
return static_cast<uint32_t>(static_cast<uint64_t>(n));
}
template<typename T>
static inline constexpr uint32_t high32(const T n) {
return static_cast<uint32_t>(static_cast<uint64_t>(n)>>32);
}
template<typename T>
static inline constexpr T to64(const uint32_t lo, const uint32_t hi) {
return static_cast<T>(static_cast<uint64_t>(hi)<<32 | lo);
}
BufferItem::BufferItem() :
mGraphicBuffer(NULL),
mFence(NULL),
mCrop(Rect::INVALID_RECT),
mTransform(0),
mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
mTimestamp(0),
mIsAutoTimestamp(false),
mDataSpace(HAL_DATASPACE_UNKNOWN),
mFrameNumber(0),
mSlot(INVALID_BUFFER_SLOT),
mIsDroppable(false),
mAcquireCalled(false),
mTransformToDisplayInverse(false),
mSurfaceDamage(),
mAutoRefresh(false),
mQueuedBuffer(true),
mIsStale(false),
mApi(0) {
}
BufferItem::~BufferItem() {}
template <typename T>
static void addAligned(size_t& size, T /* value */) {
size = FlattenableUtils::align<sizeof(T)>(size);
size += sizeof(T);
}
size_t BufferItem::getPodSize() const {
size_t size = 0;
addAligned(size, mCrop);
addAligned(size, mTransform);
addAligned(size, mScalingMode);
addAligned(size, low32(mTimestamp));
addAligned(size, high32(mTimestamp));
addAligned(size, mIsAutoTimestamp);
addAligned(size, mDataSpace);
addAligned(size, low32(mFrameNumber));
addAligned(size, high32(mFrameNumber));
addAligned(size, mSlot);
addAligned(size, mIsDroppable);
addAligned(size, mAcquireCalled);
addAligned(size, mTransformToDisplayInverse);
addAligned(size, mAutoRefresh);
addAligned(size, mQueuedBuffer);
addAligned(size, mIsStale);
addAligned(size, mApi);
return size;
}
size_t BufferItem::getFlattenedSize() const {
size_t size = sizeof(uint32_t); // Flags
if (mGraphicBuffer != 0) {
size += mGraphicBuffer->getFlattenedSize();
size = FlattenableUtils::align<4>(size);
}
if (mFence != 0) {
size += mFence->getFlattenedSize();
size = FlattenableUtils::align<4>(size);
}
size += mSurfaceDamage.getFlattenedSize();
size += mHdrMetadata.getFlattenedSize();
size = FlattenableUtils::align<8>(size);
return size + getPodSize();
}
size_t BufferItem::getFdCount() const {
size_t count = 0;
if (mGraphicBuffer != 0) {
count += mGraphicBuffer->getFdCount();
}
if (mFence != 0) {
count += mFence->getFdCount();
}
return count;
}
template <typename T>
static void writeAligned(void*& buffer, size_t& size, T value) {
size -= FlattenableUtils::align<alignof(T)>(buffer);
FlattenableUtils::write(buffer, size, value);
}
status_t BufferItem::flatten(
void*& buffer, size_t& size, int*& fds, size_t& count) const {
// make sure we have enough space
if (size < BufferItem::getFlattenedSize()) {
return NO_MEMORY;
}
// content flags are stored first
uint32_t& flags = *static_cast<uint32_t*>(buffer);
// advance the pointer
FlattenableUtils::advance(buffer, size, sizeof(uint32_t));
flags = 0;
if (mGraphicBuffer != 0) {
status_t err = mGraphicBuffer->flatten(buffer, size, fds, count);
if (err) return err;
size -= FlattenableUtils::align<4>(buffer);
flags |= 1;
}
if (mFence != 0) {
status_t err = mFence->flatten(buffer, size, fds, count);
if (err) return err;
size -= FlattenableUtils::align<4>(buffer);
flags |= 2;
}
status_t err = mSurfaceDamage.flatten(buffer, size);
if (err) return err;
FlattenableUtils::advance(buffer, size, mSurfaceDamage.getFlattenedSize());
err = mHdrMetadata.flatten(buffer, size);
if (err) return err;
FlattenableUtils::advance(buffer, size, mHdrMetadata.getFlattenedSize());
// Check we still have enough space
if (size < getPodSize()) {
return NO_MEMORY;
}
writeAligned(buffer, size, mCrop);
writeAligned(buffer, size, mTransform);
writeAligned(buffer, size, mScalingMode);
writeAligned(buffer, size, low32(mTimestamp));
writeAligned(buffer, size, high32(mTimestamp));
writeAligned(buffer, size, mIsAutoTimestamp);
writeAligned(buffer, size, mDataSpace);
writeAligned(buffer, size, low32(mFrameNumber));
writeAligned(buffer, size, high32(mFrameNumber));
writeAligned(buffer, size, mSlot);
writeAligned(buffer, size, mIsDroppable);
writeAligned(buffer, size, mAcquireCalled);
writeAligned(buffer, size, mTransformToDisplayInverse);
writeAligned(buffer, size, mAutoRefresh);
writeAligned(buffer, size, mQueuedBuffer);
writeAligned(buffer, size, mIsStale);
writeAligned(buffer, size, mApi);
return NO_ERROR;
}
template <typename T>
static void readAligned(const void*& buffer, size_t& size, T& value) {
size -= FlattenableUtils::align<alignof(T)>(buffer);
FlattenableUtils::read(buffer, size, value);
}
status_t BufferItem::unflatten(
void const*& buffer, size_t& size, int const*& fds, size_t& count) {
if (size < sizeof(uint32_t)) {
return NO_MEMORY;
}
uint32_t flags = 0;
FlattenableUtils::read(buffer, size, flags);
if (flags & 1) {
mGraphicBuffer = new GraphicBuffer();
status_t err = mGraphicBuffer->unflatten(buffer, size, fds, count);
if (err) return err;
size -= FlattenableUtils::align<4>(buffer);
}
if (flags & 2) {
mFence = new Fence();
status_t err = mFence->unflatten(buffer, size, fds, count);
if (err) return err;
size -= FlattenableUtils::align<4>(buffer);
mFenceTime = std::make_shared<FenceTime>(mFence);
}
status_t err = mSurfaceDamage.unflatten(buffer, size);
if (err) return err;
FlattenableUtils::advance(buffer, size, mSurfaceDamage.getFlattenedSize());
err = mHdrMetadata.unflatten(buffer, size);
if (err) return err;
FlattenableUtils::advance(buffer, size, mHdrMetadata.getFlattenedSize());
// Check we still have enough space
if (size < getPodSize()) {
return NO_MEMORY;
}
uint32_t timestampLo = 0, timestampHi = 0;
uint32_t frameNumberLo = 0, frameNumberHi = 0;
readAligned(buffer, size, mCrop);
readAligned(buffer, size, mTransform);
readAligned(buffer, size, mScalingMode);
readAligned(buffer, size, timestampLo);
readAligned(buffer, size, timestampHi);
mTimestamp = to64<int64_t>(timestampLo, timestampHi);
readAligned(buffer, size, mIsAutoTimestamp);
readAligned(buffer, size, mDataSpace);
readAligned(buffer, size, frameNumberLo);
readAligned(buffer, size, frameNumberHi);
mFrameNumber = to64<uint64_t>(frameNumberLo, frameNumberHi);
readAligned(buffer, size, mSlot);
readAligned(buffer, size, mIsDroppable);
readAligned(buffer, size, mAcquireCalled);
readAligned(buffer, size, mTransformToDisplayInverse);
readAligned(buffer, size, mAutoRefresh);
readAligned(buffer, size, mQueuedBuffer);
readAligned(buffer, size, mIsStale);
readAligned(buffer, size, mApi);
return NO_ERROR;
}
const char* BufferItem::scalingModeName(uint32_t scalingMode) {
switch (scalingMode) {
case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
default: return "Unknown";
}
}
} // namespace android
| 31.246269 | 82 | 0.682708 |
yakuizhao
|
f5045c748160ad1a6302eed469cc2b9f98bc8aeb
| 228 |
cpp
|
C++
|
src/matlab.cpp
|
git-steb/structural-deformable-models
|
4706a65e0dc031d16e259e526fd6a55e805855d1
|
[
"MIT"
] | 2 |
2017-03-01T20:07:09.000Z
|
2020-07-12T11:02:21.000Z
|
src/matlab.cpp
|
git-steb/structural-deformable-models
|
4706a65e0dc031d16e259e526fd6a55e805855d1
|
[
"MIT"
] | null | null | null |
src/matlab.cpp
|
git-steb/structural-deformable-models
|
4706a65e0dc031d16e259e526fd6a55e805855d1
|
[
"MIT"
] | null | null | null |
#include <stdlib.h>
#include "common.h"
#include "matlab.h"
static string matlabprog = "matlab -nojvw -nosplash -nodesktop -r ";
int matlabCall(const std::string& cmd)
{
return system((matlabprog+cmd+", exit").c_str());
}
| 20.727273 | 68 | 0.688596 |
git-steb
|
f505bb79f1133b578d55b81df8ad29303067731f
| 3,325 |
cpp
|
C++
|
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
|
mauzey1/scream
|
d12eb1b13039a09d9c031236af74e04262066bfc
|
[
"zlib-acknowledgement",
"RSA-MD",
"FTL"
] | null | null | null |
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
|
mauzey1/scream
|
d12eb1b13039a09d9c031236af74e04262066bfc
|
[
"zlib-acknowledgement",
"RSA-MD",
"FTL"
] | null | null | null |
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
|
mauzey1/scream
|
d12eb1b13039a09d9c031236af74e04262066bfc
|
[
"zlib-acknowledgement",
"RSA-MD",
"FTL"
] | null | null | null |
#include "catch2/catch.hpp"
#include "share/scream_types.hpp"
#include "ekat/ekat_pack.hpp"
#include "ekat/kokkos/ekat_kokkos_utils.hpp"
#include "physics/p3/p3_functions.hpp"
#include "physics/p3/p3_functions_f90.hpp"
#include "p3_unit_tests_common.hpp"
namespace scream {
namespace p3 {
namespace unit_test {
template <typename D>
struct UnitWrap::UnitTest<D>::TestNiConservation {
static void run_bfb()
{
NiConservationData f90_data[max_pack_size];
static constexpr Int num_runs = sizeof(f90_data) / sizeof(NiConservationData);
// Generate random input data
// Alternatively, you can use the f90_data construtors/initializer lists to hardcode data
for (auto& d : f90_data) {
d.randomize();
}
// Create copies of data for use by cxx and sync it to device. Needs to happen before fortran calls so that
// inout data is in original state
view_1d<NiConservationData> cxx_device("cxx_device", max_pack_size);
const auto cxx_host = Kokkos::create_mirror_view(cxx_device);
std::copy(&f90_data[0], &f90_data[0] + max_pack_size, cxx_host.data());
Kokkos::deep_copy(cxx_device, cxx_host);
// Get data from fortran
for (auto& d : f90_data) {
ni_conservation(d);
}
// Get data from cxx. Run ni_conservation from a kernel and copy results back to host
Kokkos::parallel_for(num_test_itrs, KOKKOS_LAMBDA(const Int& i) {
const Int offset = i * Spack::n;
// Init pack inputs
Spack nc2ni_immers_freeze_tend, ni, ni2nr_melt_tend, ni_nucleat_tend, ni_selfcollect_tend, ni_sublim_tend, nr2ni_immers_freeze_tend;
for (Int s = 0, vs = offset; s < Spack::n; ++s, ++vs) {
nc2ni_immers_freeze_tend[s] = cxx_device(vs).nc2ni_immers_freeze_tend;
ni[s] = cxx_device(vs).ni;
ni2nr_melt_tend[s] = cxx_device(vs).ni2nr_melt_tend;
ni_nucleat_tend[s] = cxx_device(vs).ni_nucleat_tend;
ni_selfcollect_tend[s] = cxx_device(vs).ni_selfcollect_tend;
ni_sublim_tend[s] = cxx_device(vs).ni_sublim_tend;
nr2ni_immers_freeze_tend[s] = cxx_device(vs).nr2ni_immers_freeze_tend;
}
Functions::ni_conservation(ni, ni_nucleat_tend, nr2ni_immers_freeze_tend, nc2ni_immers_freeze_tend, cxx_device(0).dt, ni2nr_melt_tend, ni_sublim_tend, ni_selfcollect_tend);
// Copy spacks back into cxx_device view
for (Int s = 0, vs = offset; s < Spack::n; ++s, ++vs) {
cxx_device(vs).ni2nr_melt_tend = ni2nr_melt_tend[s];
cxx_device(vs).ni_selfcollect_tend = ni_selfcollect_tend[s];
cxx_device(vs).ni_sublim_tend = ni_sublim_tend[s];
}
});
Kokkos::deep_copy(cxx_host, cxx_device);
// Verify BFB results
for (Int i = 0; i < num_runs; ++i) {
NiConservationData& d_f90 = f90_data[i];
NiConservationData& d_cxx = cxx_host[i];
REQUIRE(d_f90.ni2nr_melt_tend == d_cxx.ni2nr_melt_tend);
REQUIRE(d_f90.ni_sublim_tend == d_cxx.ni_sublim_tend);
REQUIRE(d_f90.ni_selfcollect_tend == d_cxx.ni_selfcollect_tend);
}
} // run_bfb
};
} // namespace unit_test
} // namespace p3
} // namespace scream
namespace {
TEST_CASE("ni_conservation_bfb", "[p3]")
{
using TestStruct = scream::p3::unit_test::UnitWrap::UnitTest<scream::DefaultDevice>::TestNiConservation;
TestStruct::run_bfb();
}
} // empty namespace
| 33.928571 | 178 | 0.704662 |
mauzey1
|