hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
507212fb6d082be3fe5cec1aa03ec792737ef9e3 | 838 | cpp | C++ | Desarrollo(VS2017)/Motor2D/j1GUIlabel.cpp | Sanmopre/DESARROLLO | 4b601ca0862c6cf5831ec7fbe226fd97d52cf11b | [
"MIT"
] | null | null | null | Desarrollo(VS2017)/Motor2D/j1GUIlabel.cpp | Sanmopre/DESARROLLO | 4b601ca0862c6cf5831ec7fbe226fd97d52cf11b | [
"MIT"
] | null | null | null | Desarrollo(VS2017)/Motor2D/j1GUIlabel.cpp | Sanmopre/DESARROLLO | 4b601ca0862c6cf5831ec7fbe226fd97d52cf11b | [
"MIT"
] | 1 | 2019-12-27T20:26:49.000Z | 2019-12-27T20:26:49.000Z | #include "j1GUIlabel.h"
#include "j1App.h"
#include "j1Fonts.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Input.h"
j1GUIlabel::j1GUIlabel()
{
this->type = GUItype::GUI_LABEL;
}
j1GUIlabel::~j1GUIlabel() {
}
bool j1GUIlabel::Awake(pugi::xml_node&)
{
return true;
}
bool j1GUIlabel::Start()
{
texture = App->fonts->Print(text);
return true;
}
bool j1GUIlabel::PreUpdate()
{
App->fonts->CalcSize(App->input->GetText().GetString(), rect.w, rect.h);
return true;
}
bool j1GUIlabel::Update(float dt)
{
if (enabled)
App->render->Blit_UI(texture, Map_Position.x + Inside_Position.x, Map_Position.y + Inside_Position.y - App->render->camera.y/2, nullptr, 0.0f);
return true;
}
bool j1GUIlabel::PostUpdate()
{
return true;
}
bool j1GUIlabel::CleanUp()
{
App->tex->Unload(texture);
return true;
}
| 14.964286 | 145 | 0.684964 | [
"render"
] |
507454bc385a7ea78af532998872725fb5bf9d8d | 4,692 | cc | C++ | tests/test_getattr.cc | gerrymanoim/libpy | ffe19d53aa9602893aecc2dd8c9feda90e06b262 | [
"Apache-2.0"
] | 71 | 2020-06-26T00:36:33.000Z | 2021-12-02T13:57:02.000Z | tests/test_getattr.cc | stefan-jansen/libpy | e174ee103db76a9d0fcd29165d54c676ed1f2629 | [
"Apache-2.0"
] | 32 | 2020-06-26T18:59:15.000Z | 2022-03-01T19:02:44.000Z | tests/test_getattr.cc | gerrymanoim/libpy | ffe19d53aa9602893aecc2dd8c9feda90e06b262 | [
"Apache-2.0"
] | 24 | 2020-06-26T17:01:57.000Z | 2022-02-15T00:25:27.000Z | #include <string>
#include <vector>
#include "gtest/gtest.h"
#include "libpy/detail/python.h"
#include "libpy/getattr.h"
#include "test_utils.h"
namespace test_getattr {
class getattr : public with_python_interpreter {};
TEST_F(getattr, simple) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
b = 1
expected = A.b
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
py::owned_ref<> actual = py::getattr(A, "b");
ASSERT_TRUE(actual);
py::borrowed_ref expected = PyDict_GetItemString(ns.get(), "expected");
ASSERT_TRUE(expected);
// compare them using object identity
EXPECT_EQ(actual, expected);
}
TEST_F(getattr, attribute_error) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
pass
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
py::owned_ref<> actual = py::getattr(A, "b");
ASSERT_FALSE(actual);
expect_pyerr_type_and_message(PyExc_AttributeError,
"type object 'A' has no attribute 'b'");
PyErr_Clear();
}
TEST_F(getattr, nested) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
class B(object):
class C(object):
d = 1
expected = A.B.C.d
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
py::owned_ref<> actual = py::nested_getattr(A, "B", "C", "d");
ASSERT_TRUE(actual);
py::borrowed_ref expected = PyDict_GetItemString(ns.get(), "expected");
ASSERT_TRUE(expected);
// compare them using object identity
EXPECT_EQ(actual, expected);
}
TEST_F(getattr, nested_failure) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
class B(object):
class C(object):
pass
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
// attempt to access a few fields past the end of the real attribute chain.
py::owned_ref<> actual = py::nested_getattr(A, "B", "C", "D", "E");
ASSERT_FALSE(actual);
expect_pyerr_type_and_message(PyExc_AttributeError,
"type object 'C' has no attribute 'D'");
PyErr_Clear();
}
class getattr_throws : public with_python_interpreter {};
TEST_F(getattr_throws, simple) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
b = 1
expected = A.b
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
py::owned_ref<> actual = py::getattr_throws(A, "b");
ASSERT_TRUE(actual);
py::borrowed_ref expected = PyDict_GetItemString(ns.get(), "expected");
ASSERT_TRUE(expected);
// compare them using object identity
EXPECT_EQ(actual, expected);
}
TEST_F(getattr_throws, attribute_error) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
pass
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
EXPECT_THROW(py::getattr_throws(A, "b"), py::exception);
expect_pyerr_type_and_message(PyExc_AttributeError,
"type object 'A' has no attribute 'b'");
PyErr_Clear();
}
TEST_F(getattr_throws, nested) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
class B(object):
class C(object):
d = 1
expected = A.B.C.d
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
py::owned_ref<> actual = py::nested_getattr_throws(A, "B", "C", "d");
ASSERT_TRUE(actual);
py::borrowed_ref expected = PyDict_GetItemString(ns.get(), "expected");
ASSERT_TRUE(expected);
// compare them using object identity
EXPECT_EQ(actual, expected);
}
TEST_F(getattr_throws, nested_failure) {
py::owned_ref ns = RUN_PYTHON(R"(
class A(object):
class B(object):
class C(object):
pass
)");
ASSERT_TRUE(ns);
py::borrowed_ref A = PyDict_GetItemString(ns.get(), "A");
ASSERT_TRUE(A);
// attempt to access a few fields past the end of the real attribute chain.
EXPECT_THROW(py::nested_getattr_throws(A, "B", "C", "D", "E"), py::exception);
expect_pyerr_type_and_message(PyExc_AttributeError,
"type object 'C' has no attribute 'D'");
PyErr_Clear();
}
} // namespace test_getattr
| 26.212291 | 82 | 0.598039 | [
"object",
"vector"
] |
50763c0997cc922902f82d16b735763d7e319494 | 593 | cpp | C++ | edpc/b.cpp | dashimaki360/atcoder | 1462150d59d50f270145703df579dba8c306376c | [
"MIT"
] | null | null | null | edpc/b.cpp | dashimaki360/atcoder | 1462150d59d50f270145703df579dba8c306376c | [
"MIT"
] | null | null | null | edpc/b.cpp | dashimaki360/atcoder | 1462150d59d50f270145703df579dba8c306376c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// #include <atcoder/all>
// using namespace atcoder;
#define rep(i,n) for (int i = 0; i < (n); ++i)
using ll = long long;
using P = pair<int,int>;
void chmin(int& x, int y){x = min(x,y);}
void chmax(int& x, int y){x = max(x,y);}
const int INF = 1001001001;
int main() {
int n, k;
cin >> n >> k;
vector<int> a(n);
rep(i,n) cin >> a[i];
vector<int> dp(n, INF);
dp[0] = 0;
rep(i,n){
for(int j=1; i+j<n&&j<=k; j++){
chmin(dp[i+j], dp[i] + abs(a[i]-a[i+j]));
}
}
int ans = dp[n-1];
cout << ans << endl;
return 0;
} | 21.962963 | 47 | 0.531197 | [
"vector"
] |
507795eec702c09967dff6a2c80944cc00f81227 | 9,149 | cpp | C++ | tests/matrix.cpp | indianajohn/basic-matrix | 51f0b8cf712e61010acb39687deb6dc633394563 | [
"MIT"
] | null | null | null | tests/matrix.cpp | indianajohn/basic-matrix | 51f0b8cf712e61010acb39687deb6dc633394563 | [
"MIT"
] | null | null | null | tests/matrix.cpp | indianajohn/basic-matrix | 51f0b8cf712e61010acb39687deb6dc633394563 | [
"MIT"
] | null | null | null | #include "matrix.hpp"
#include "matrix_helpers.hpp"
#include "test_helpers.hpp"
#include <iostream>
#include <random>
#include <sstream>
using namespace basic_matrix;
void emptyMatrix() {
Matrix mat;
ASSERT_EQ(mat.width(), 0);
ASSERT_EQ(mat.height(), 0);
// make sure ostream operator handles empty matrices well
std::stringstream ss;
ss << mat;
}
void initWorks() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(std::numeric_limits<double>::min(),
std::numeric_limits<double>::max());
for (size_t width = 0; width < 10; width++) {
for (size_t height = 0; height < 20; height++) {
Matrix test(width, height);
ASSERT_EQ(test.width(), width);
ASSERT_EQ(test.height(), height);
for (size_t x = 0; x < test.width(); x++) {
for (size_t y = 0; y < test.height(); y++) {
ASSERT_NEAR(test(x, y), 0);
double val = dis(gen);
test(x, y) = val;
ASSERT_NEAR(test(x, y), val);
}
}
}
}
}
void initWithValue() {
std::vector<std::vector<double>> vec = {{1, 2, 4}, {3.5, 4.2, 1.2}};
Matrix test(vec);
ASSERT_EQ(test.width(), 3);
ASSERT_EQ(test.height(), 2);
Matrix test2({{2.320359359, 9.2, 0.3}});
ASSERT_EQ(test2.width(), 3);
ASSERT_EQ(test2.height(), 1);
Matrix test3 = {{0.5, 10.4, 4.3}, {0.2, 4.4, 1.1}};
ASSERT_EQ(test3.width(), 3);
ASSERT_EQ(test3.height(), 2);
Matrix test4 = {0.3, 0.5, 0.19, 0.55};
ASSERT_EQ(test4.height(), 1);
ASSERT_EQ(test4.width(), 4);
}
void boundingBoxWorks() {
BoundingBox bb;
bb.extend(std::make_pair(1, 1));
ASSERT_EQ(bb.minX(), 1);
ASSERT_EQ(bb.minY(), 1);
ASSERT_EQ(bb.maxX(), 1);
ASSERT_EQ(bb.maxY(), 1);
bb.extend(std::make_pair(5, 2));
ASSERT_EQ(bb.minX(), 1);
ASSERT_EQ(bb.minY(), 1);
ASSERT_EQ(bb.maxX(), 5);
ASSERT_EQ(bb.maxY(), 2);
bb.extend(std::make_pair(5, 1));
ASSERT_EQ(bb.minX(), 1);
ASSERT_EQ(bb.minY(), 1);
ASSERT_EQ(bb.maxX(), 5);
ASSERT_EQ(bb.maxY(), 2);
bb.extend(std::make_pair(5, 4));
ASSERT_EQ(bb.minX(), 1);
ASSERT_EQ(bb.minY(), 1);
ASSERT_EQ(bb.maxX(), 5);
ASSERT_EQ(bb.maxY(), 4);
bb.extend(std::make_pair(6, 3));
ASSERT_EQ(bb.minX(), 1);
ASSERT_EQ(bb.minY(), 1);
ASSERT_EQ(bb.maxX(), 6);
ASSERT_EQ(bb.maxY(), 4);
bb.extend(std::make_pair(7, 8));
ASSERT_EQ(bb.minX(), 1);
ASSERT_EQ(bb.minY(), 1);
ASSERT_EQ(bb.maxX(), 7);
ASSERT_EQ(bb.maxY(), 8);
bb.extend(std::make_pair(0, 0));
ASSERT_EQ(bb.minX(), 0);
ASSERT_EQ(bb.minY(), 0);
ASSERT_EQ(bb.maxX(), 7);
ASSERT_EQ(bb.maxY(), 8);
}
void roisWork() {
size_t x_dst, y_dst;
size_t x_src, y_src;
// Basic usage
MatrixROI roi(0, 0, 3, 4, nullptr, 0, 0, false);
roi.srcToDst(0, 0, x_dst, y_dst);
ASSERT_EQ(x_dst, 0);
ASSERT_EQ(y_dst, 0);
roi.srcToDst(2, 3, x_dst, y_dst);
ASSERT_EQ(x_dst, 2);
ASSERT_EQ(y_dst, 3);
ASSERT_EQ(roi.isInside(2, 3), true);
ASSERT_EQ(roi.isInside(3, 4), false);
// offset src
roi = MatrixROI(1, 1, 3, 4, nullptr, 0, 0, false);
roi.srcToDst(1, 1, x_dst, y_dst);
ASSERT_EQ(x_dst, 0);
ASSERT_EQ(y_dst, 0);
roi.srcToDst(2, 1, x_dst, y_dst);
ASSERT_EQ(x_dst, 1);
ASSERT_EQ(y_dst, 0);
roi.srcToDst(1, 2, x_dst, y_dst);
ASSERT_EQ(x_dst, 0);
ASSERT_EQ(y_dst, 1);
ASSERT_EQ(roi.isInside(2, 3), true);
ASSERT_EQ(roi.isInside(3, 4), false);
// offset dst
roi = MatrixROI(1, 1, 3, 4, nullptr, 2, 3, false);
ASSERT_EQ(roi.isInside(0, 0), false);
ASSERT_EQ(roi.isInside(1, 2), false);
ASSERT_EQ(roi.isInside(2, 3), true);
ASSERT_EQ(roi.isInside(3, 3), true);
ASSERT_EQ(roi.isInside(2, 4), true);
ASSERT_EQ(roi.isInside(4, 6), true);
ASSERT_EQ(roi.isInside(5, 6), false);
ASSERT_EQ(roi.isInside(4, 7), false);
ASSERT_EQ(roi.isInside(5, 7), false);
// Transpose
roi = MatrixROI(1, 1, 3, 4, nullptr, 2, 3, true);
roi.dstToSrc(2, 3, x_src, y_src);
ASSERT_EQ(x_src, 1);
ASSERT_EQ(y_src, 1);
roi.dstToSrc(3, 3, x_src, y_src);
ASSERT_EQ(x_src, 1);
ASSERT_EQ(y_src, 2);
roi.dstToSrc(2, 4, x_src, y_src);
ASSERT_EQ(x_src, 2);
ASSERT_EQ(y_src, 1);
roi.srcToDst(1, 1, x_dst, y_dst);
ASSERT_EQ(x_dst, 2);
ASSERT_EQ(y_dst, 3);
roi.srcToDst(2, 1, x_dst, y_dst);
ASSERT_EQ(x_dst, 2);
ASSERT_EQ(y_dst, 4);
roi.srcToDst(1, 2, x_dst, y_dst);
ASSERT_EQ(x_dst, 3);
ASSERT_EQ(y_dst, 3);
ASSERT_EQ(roi.isInside(0, 0), false);
ASSERT_EQ(roi.isInside(2, 1), false);
ASSERT_EQ(roi.isInside(2, 3), true);
ASSERT_EQ(roi.isInside(5, 5), true);
ASSERT_EQ(roi.isInside(6, 5), false);
ASSERT_EQ(roi.isInside(5, 6), false);
ASSERT_EQ(roi.isInside(6, 6), false);
}
void wrappedMatricesWork() {
// Simple test
{
Matrix test = {{1, 2, 4}, {3.5, 4.2, 1.2}};
Matrix wrapped(MatrixROI(0, 0, test.width(), test.height(), &test));
ASSERT_MATRIX_NEAR(wrapped, test);
std::stringstream ss;
// Make sure stream works on wrapped matrices
ss << wrapped << std::endl;
wrapped(1, 1) = 5.5;
ASSERT_NEAR(wrapped(1, 1), 5.5);
ASSERT_NEAR(wrapped(1, 1), test(1, 1));
}
// Wrapping 2 matrices in one empty wrapper
{
Matrix test0 = {{1, 2, 4}, {3.5, 4.2, 1.2}};
Matrix test1 = {{3, 5, 9}};
Matrix test2;
Matrix wrapped(
MatrixROI(0, 0, test0.width(), test0.height(), &test0, 0, 0));
wrapped.addROI(
MatrixROI(0, 0, test1.width(), test1.height(), &test1, 0, 2));
Matrix wrapped_expected = test0.concatDown(test1);
std::stringstream ss;
// Make sure stream works on wrapped matrices
ss << wrapped << std::endl;
ASSERT_MATRIX_NEAR(wrapped, wrapped_expected);
wrapped(1, 1) = 5.5;
ASSERT_NEAR(wrapped(1, 1), 5.5);
ASSERT_NEAR(wrapped(1, 1), test0(1, 1));
wrapped(1, 2) = 10.5;
ASSERT_NEAR(wrapped(1, 2), 10.5);
ASSERT_NEAR(wrapped(1, 2), test1(1, 0));
}
{
// Transpose
Matrix test = {{1, 2, 4}, {3.5, 4.2, 1.2}};
Matrix test_transposed = test.transpose();
ASSERT_MATRIX_NEAR(test_transposed, test.transposeROI());
}
{
// const transpose ROI
const Matrix test = {{1, 2, 4}, {3.5, 4.2, 1.2}};
Matrix test_transposed = test.transpose();
ASSERT_MATRIX_NEAR(test_transposed, test.transposeROI());
}
}
void detWorksOn1x1() {
Matrix mat = {2.2};
double det = mat.det();
ASSERT_NEAR(det, 2.2);
}
void detWorksOn2x2() {
Matrix mat = {{1, 2}, {3, 4}};
double det = mat.det();
ASSERT_NEAR(det, -2.0);
}
void detWorksOn3x3() {
Matrix mat = {{1, 4, 11}, {4, 59, 63}, {7, 18, 9}};
double det = mat.det();
ASSERT_NEAR(det, -2734.0);
}
void detWorksOn4x4() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
double det = mat.det();
ASSERT_NEAR(det, -54.0);
}
void equalsWorks() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
// Wrapping part of a matrix and using the equals operator to set the
// submatrix to the result of a calculation is useful in many situations.
Matrix wrapped(MatrixROI(0, 0, 2, 2, &mat));
Matrix mat_to_set = {{9, 9}, {10, 10}};
wrapped = mat_to_set;
ASSERT_MATRIX_NEAR(wrapped, mat_to_set);
Matrix expected = {
{9, 9, 11, 12}, {10, 10, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
ASSERT_MATRIX_NEAR(mat, expected);
}
void rowWorks() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
ASSERT_MATRIX_NEAR(mat.row(0), Matrix({1, 4, 11, 12}));
ASSERT_MATRIX_NEAR(mat.row(1), Matrix({4, 59, 63, 64}));
ASSERT_MATRIX_NEAR(mat.row(2), Matrix({7, 18, 9, 10}));
ASSERT_MATRIX_NEAR(mat.row(3), Matrix({12, 49, 19, 19}));
}
void colWorks() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
ASSERT_MATRIX_NEAR(mat.col(0), Matrix({1, 4, 7, 12}).transposeROI());
ASSERT_MATRIX_NEAR(mat.col(1), Matrix({4, 59, 18, 49}).transposeROI());
ASSERT_MATRIX_NEAR(mat.col(2), Matrix({11, 63, 9, 19}).transposeROI());
ASSERT_MATRIX_NEAR(mat.col(3), Matrix({12, 64, 10, 19}).transposeROI());
}
void reshapeWorks() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
Matrix mat_expected = {{1, 4, 11, 12, 4, 59, 63, 64},
{7, 18, 9, 10, 12, 49, 19, 19}};
mat.reshape(8, 2);
ASSERT_MATRIX_NEAR(mat, mat_expected);
}
void sumRowsWorks() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
Matrix mat_expected = {24, 130, 102, 105};
Matrix row_sum = mat.sumRows();
ASSERT_MATRIX_NEAR(row_sum, mat_expected);
}
void sumColsWorks() {
Matrix mat = {
{1, 4, 11, 12}, {4, 59, 63, 64}, {7, 18, 9, 10}, {12, 49, 19, 19}};
Matrix mat_expected = Matrix({28, 190, 44, 99}).transpose();
Matrix col_sum = mat.sumCols();
ASSERT_MATRIX_NEAR(col_sum, mat_expected);
}
int main() {
emptyMatrix();
initWorks();
initWithValue();
boundingBoxWorks();
roisWork();
wrappedMatricesWork();
detWorksOn1x1();
detWorksOn2x2();
detWorksOn3x3();
detWorksOn4x4();
equalsWorks();
rowWorks();
colWorks();
reshapeWorks();
sumRowsWorks();
sumColsWorks();
}
| 29.323718 | 75 | 0.602689 | [
"vector"
] |
508cbbf4c8492eb845e217d890a1831e49258c28 | 14,899 | cpp | C++ | Sources/LibVulkan/source/VKScreenshot.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/LibVulkan/source/VKScreenshot.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/LibVulkan/source/VKScreenshot.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | /// https://github.com/Rominitch/MouCaLab
/// \author Rominitch
/// \license No license
#include "Dependencies.h"
#include "LibVulkan/include/VKScreenshot.h"
#include "LibRT/include/RTBufferCPU.h"
#include "LibRT/include/RTImage.h"
#include "LibVulkan/include/VKContextDevice.h"
#include "LibVulkan/include/VKContextWindow.h"
#include "LibVulkan/include/VKCommand.h"
#include "LibVulkan/include/VKCommandBuffer.h"
#include "LibVulkan/include/VKFence.h"
#include "LibVulkan/include/VKSequence.h"
#include "LibVulkan/include/VKSubmitInfo.h"
#include "LibVulkan/include/VKSurfaceFormat.h"
namespace Vulkan
{
void GPUImageReader::initialize(const ContextWindow& context, const RT::ComponentDescriptor& component)
{
// Get format properties for the swapchain color format
VkFormatProperties formatProps;
// Check blit support for source and destination
_supportsBlit = true;
VkFormat imageFormat = VK_FORMAT_UNDEFINED;
if (component.getNbComponents() == 4 && component.getFormatType() == RT::Type::UnsignedChar)
{
imageFormat = VK_FORMAT_R8G8B8A8_UNORM;
}
else if (component.getNbComponents() == 1 && component.getFormatType() == RT::Type::Int)
{
imageFormat = VK_FORMAT_R32_SINT;
}
MOUCA_ASSERT(imageFormat != VK_FORMAT_UNDEFINED); //DEV Issue: unsupported format.
const auto& device = context.getContextDevice().getDevice();
// Check if the device supports blitting from optimal images (the swapchain images are in optimal format)
device.readFormatProperties(context.getFormat().getConfiguration()._format.format, formatProps);
if (!(formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT))
{
_supportsBlit = false;
//MOUCA_THROW_ERROR("Vulkan", "blitSourceError");
}
else
{
// Check if the device supports blitting to linear images
device.readFormatProperties(imageFormat, formatProps);
if (!(formatProps.linearTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT))
{
_supportsBlit = false;
//MOUCA_THROW_ERROR("Vulkan", "blitDestinationError");
}
}
// Source for the copy is the last rendered swapchain image
Image::Size size;
size._extent =
{
context.getFormat().getConfiguration()._extent.width,
context.getFormat().getConfiguration()._extent.height,
1
};
// Descriptor must be equal to imageFormat
_descriptor.addDescriptor(component);
// Create local image
_image.initialize(device, size, VK_IMAGE_TYPE_2D, imageFormat,
VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_DST_BIT,
VK_SHARING_MODE_EXCLUSIVE, VK_IMAGE_LAYOUT_UNDEFINED,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
_fenceSync.initialize(device, 16000000000ull, 0);
}
void GPUImageReader::release(const ContextWindow& context)
{
const auto& device = context.getContextDevice().getDevice();
// Clean local image
_image.release(device);
_fenceSync.release(device);
}
void GPUImageReader::extractTo(const VkImage& srcImage, const ContextDevice& contextDevice, const RT::Array3ui& positionSrc, const RT::Array3ui& positionDst, const RT::Array3ui& sizes)
{
MOUCA_PRE_CONDITION(!contextDevice.isNull()); //DEV Issue: Need a valid context.
const auto& device = contextDevice.getDevice();
auto commandBuffer = std::make_shared<CommandBuffer>();
auto pool = std::make_shared<CommandPool>();
pool->initialize(device, device.getQueueFamilyGraphicId());
commandBuffer->initialize(device, pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 0);
Commands commands;
// Do the actual blit from the swapchain image to our host visible destination image
CommandPipelineBarrier::ImageMemoryBarriers barrierDst
{
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, //VkStructureType sType;
nullptr, //const void* pNext;
0, //VkAccessFlags srcAccessMask;
VK_ACCESS_TRANSFER_WRITE_BIT, //VkAccessFlags dstAccessMask;
VK_IMAGE_LAYOUT_UNDEFINED, //VkImageLayout oldLayout;
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, //VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, //uint32_t srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, //uint32_t dstQueueFamilyIndex;
_image.getImage(), //VkImage image;
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } //VkImageSubresourceRange subresourceRange;
}
};
commands.emplace_back(std::make_unique<CommandPipelineBarrier>(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_DEPENDENCY_BY_REGION_BIT,
CommandPipelineBarrier::MemoryBarriers(), CommandPipelineBarrier::BufferMemoryBarriers(), std::move(barrierDst)));
CommandPipelineBarrier::ImageMemoryBarriers barrierSrc
{
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, //VkStructureType sType;
nullptr, //const void* pNext;
VK_ACCESS_MEMORY_READ_BIT, //VkAccessFlags srcAccessMask;
VK_ACCESS_TRANSFER_READ_BIT, //VkAccessFlags dstAccessMask;
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, //VkImageLayout oldLayout;
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, //VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, //uint32_t srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, //uint32_t dstQueueFamilyIndex;
srcImage, //VkImage image;
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } //VkImageSubresourceRange subresourceRange;
}
};
commands.emplace_back(std::make_unique<CommandPipelineBarrier>(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_DEPENDENCY_BY_REGION_BIT,
CommandPipelineBarrier::MemoryBarriers(), CommandPipelineBarrier::BufferMemoryBarriers(), std::move(barrierSrc)));
// // Define the region to blit (we will blit the whole swapchain image)
// const VkOffset3D offset{ static_cast<int32_t>(sizes.x), static_cast<int32_t>(sizes.y), static_cast<int32_t>(sizes.z) };
// const VkImageBlit imageBlitRegion
// {
// { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, // VkImageSubresourceLayers srcSubresource;
// { { 0, 0, 0 }, offset }, // VkOffset3D srcOffsets[2];
// { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, // VkImageSubresourceLayers dstSubresource;
// { { 0, 0, 0 }, offset } // VkOffset3D dstOffsets[2];
// };
// CommandBlit blit(srcImage, _image, imageBlitRegion);
// Otherwise use image copy (requires us to manually flip components)
const VkImageCopy imageCopyRegion
{
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
{ static_cast<int32_t>(positionSrc.x), static_cast<int32_t>(positionSrc.y), static_cast<int32_t>(positionSrc.z) },
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
{ static_cast<int32_t>(positionDst.x), static_cast<int32_t>(positionDst.y), static_cast<int32_t>(positionDst.z) },
{ sizes.x, sizes.y, sizes.z }
};
commands.emplace_back(std::make_unique<CommandCopyImage>(srcImage, _image.getImage(), imageCopyRegion));
//Command* copyCommand = ©Image;
// if (_supportsBlit)
// copyCommand = &blit;
// Transition destination image to general layout, which is the required layout for mapping the image memory later on
CommandPipelineBarrier::ImageMemoryBarriers barrierTransitionDst
{
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, //VkStructureType sType;
nullptr, //const void* pNext;
VK_ACCESS_TRANSFER_WRITE_BIT, //VkAccessFlags srcAccessMask;
VK_ACCESS_MEMORY_READ_BIT, //VkAccessFlags dstAccessMask;
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, //VkImageLayout oldLayout;
VK_IMAGE_LAYOUT_GENERAL, //VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, //uint32_t srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, //uint32_t dstQueueFamilyIndex;
_image.getImage(), //VkImage image;
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } //VkImageSubresourceRange subresourceRange;
}
};
commands.emplace_back(std::make_unique<CommandPipelineBarrier>(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_DEPENDENCY_BY_REGION_BIT,
CommandPipelineBarrier::MemoryBarriers(), CommandPipelineBarrier::BufferMemoryBarriers(), std::move(barrierTransitionDst)));
// Transition back the swap chain image after the blit is done
CommandPipelineBarrier::ImageMemoryBarriers barrierRestoreSrc
{
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, //VkStructureType sType;
nullptr, //const void* pNext;
VK_ACCESS_TRANSFER_READ_BIT, //VkAccessFlags srcAccessMask;
VK_ACCESS_MEMORY_READ_BIT, //VkAccessFlags dstAccessMask;
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, //VkImageLayout oldLayout;
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, //VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, //uint32_t srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, //uint32_t dstQueueFamilyIndex;
srcImage, //VkImage image;
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } //VkImageSubresourceRange subresourceRange;
}
};
commands.emplace_back(std::make_unique<CommandPipelineBarrier>(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_DEPENDENCY_BY_REGION_BIT,
CommandPipelineBarrier::MemoryBarriers(), CommandPipelineBarrier::BufferMemoryBarriers(), std::move(barrierRestoreSrc)));
commandBuffer->registerCommands(std::move(commands));
commandBuffer->execute();
// Build submit data
Vulkan::SubmitInfos infos;
infos.resize(1);
infos[0] = std::make_unique<Vulkan::SubmitInfo>();
std::vector<Vulkan::ICommandBufferWPtr> commandBuffers
{
commandBuffer
};
infos[0]->initialize(std::move(commandBuffers));
// Build Fence
auto fence = std::make_shared<Vulkan::Fence>();
fence->initialize(device, Vulkan::Fence::infinityTimeout, 0);
// Execute sequence
{
// Submit
Vulkan::SequenceSubmit submit(std::move(infos), fence);
submit.execute(device);
// Wait fence
const std::vector<Vulkan::FenceWPtr> fences{ fence };
Vulkan::SequenceWaitFence waitFence(fences, Vulkan::Fence::infinityTimeout, VK_TRUE);
waitFence.execute(device);
// Sync device
device.waitIdle();
}
fence->release(device);
commandBuffer->release(device);
pool->release(device);
}
void GPUImageReader::extractTo(const VkImage& srcImage, const ContextWindow& context, const RT::Array3ui& positionSrc, const RT::Array3ui& positionDst, const RT::Array3ui& sizes, RT::Image& diskImage)
{
const auto& contextDevice = context.getContextDevice();
MOUCA_PRE_CONDITION(!contextDevice.isNull()); //DEV Issue: Need a valid context.
MOUCA_PRE_CONDITION(diskImage.isNull()); //DEV Issue:
extractTo(srcImage, contextDevice, positionSrc, positionDst, sizes);
const auto& device = contextDevice.getDevice();
// Get layout of the image (including row pitch)
const VkImageSubresource subResource
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0 };
VkSubresourceLayout subResourceLayout;
_image.readSubresourceLayout(device, subResource, subResourceLayout);
// Map image memory so we can start copying from it
_image.getMemory().map(device);
uint8_t* data = _image.getMemory().getMappedMemory<uint8_t>();
MOUCA_ASSERT(data != nullptr);
data += subResourceLayout.offset;
// Copy to image buffer CPU
RT::BufferLinkedCPU buffer(u8"linkedScreenshot");
const size_t memorySize = static_cast<size_t>(sizes.x) * static_cast<size_t>(sizes.y);
buffer.create(_descriptor, memorySize, data, subResourceLayout.rowPitch);
diskImage.createFill(buffer, sizes.x, sizes.y);
_image.getMemory().unmap(device);
}
void GPUImageReader::extractTo(const VkImage& srcImage, const ContextDevice& contextDevice, const RT::Array3ui& positionSrc, const RT::Array3ui& positionDst, const RT::Array3ui& sizes, RT::BufferCPU& output)
{
MOUCA_PRE_CONDITION(!contextDevice.isNull()); //DEV Issue: Need a valid context.
MOUCA_PRE_CONDITION(output.getData() != nullptr); //DEV Issue:
extractTo(srcImage, contextDevice, positionSrc, positionDst, sizes);
const auto& device = contextDevice.getDevice();
// Get layout of the image (including row pitch)
const VkImageSubresource subResource
{ VK_IMAGE_ASPECT_COLOR_BIT, 0, 0 };
VkSubresourceLayout subResourceLayout;
_image.readSubresourceLayout(device, subResource, subResourceLayout);
// Map image memory so we can start copying from it
_image.getMemory().map(device);
char* data = _image.getMemory().getMappedMemory<char>();
MOUCA_ASSERT(data != nullptr);
data += subResourceLayout.offset;
int32_t* widgetID = reinterpret_cast<int32_t*>(data);
int32_t* dst = reinterpret_cast<int32_t*>(output.lock());
// Remove padding
for (uint64_t y = 0; y < sizes.y; ++y)
{
for (uint64_t x = 0; x < sizes.x; ++x)
{
const uint64_t idxSrc = y * (subResourceLayout.rowPitch / _descriptor.getByteSize()) + x;
const uint64_t idxDst = y * sizes.x + x;
dst[idxDst] = widgetID[idxSrc];
}
}
output.unlock();
_image.getMemory().unmap(device);
}
} | 47.906752 | 207 | 0.642795 | [
"vector"
] |
5090abd971eadea52ce13dd6a5b7593d7a36e080 | 21,830 | cpp | C++ | src/qt/qtwebkit/Source/WebKit2/UIProcess/WebProcessProxy.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebKit2/UIProcess/WebProcessProxy.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebKit2/UIProcess/WebProcessProxy.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T13:03:23.000Z | 2017-03-19T13:03:23.000Z | /*
* Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "WebProcessProxy.h"
#include "DataReference.h"
#include "DownloadProxyMap.h"
#include "PluginInfoStore.h"
#include "PluginProcessManager.h"
#include "TextChecker.h"
#include "TextCheckerState.h"
#include "WebBackForwardListItem.h"
#include "WebContext.h"
#include "WebNavigationDataStore.h"
#include "WebNotificationManagerProxy.h"
#include "WebPageProxy.h"
#include "WebPluginSiteDataManager.h"
#include "WebProcessMessages.h"
#include "WebProcessProxyMessages.h"
#include <WebCore/KURL.h>
#include <WebCore/SuddenTermination.h>
#include <stdio.h>
#include <wtf/MainThread.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#if PLATFORM(MAC)
#include "SimplePDFPlugin.h"
#if ENABLE(PDFKIT_PLUGIN)
#include "PDFPlugin.h"
#endif
#endif
#if ENABLE(CUSTOM_PROTOCOLS)
#include "CustomProtocolManagerProxyMessages.h"
#endif
#if USE(SECURITY_FRAMEWORK)
#include "SecItemShimProxy.h"
#endif
using namespace WebCore;
#define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection())
#define MESSAGE_CHECK_URL(url) MESSAGE_CHECK_BASE(checkURLReceivedFromWebProcess(url), connection())
namespace WebKit {
static uint64_t generatePageID()
{
static uint64_t uniquePageID;
return ++uniquePageID;
}
static WebProcessProxy::WebPageProxyMap& globalPageMap()
{
ASSERT(isMainThread());
DEFINE_STATIC_LOCAL(WebProcessProxy::WebPageProxyMap, pageMap, ());
return pageMap;
}
PassRefPtr<WebProcessProxy> WebProcessProxy::create(PassRefPtr<WebContext> context)
{
return adoptRef(new WebProcessProxy(context));
}
WebProcessProxy::WebProcessProxy(PassRefPtr<WebContext> context)
: m_responsivenessTimer(this)
, m_context(context)
, m_mayHaveUniversalFileReadSandboxExtension(false)
#if ENABLE(CUSTOM_PROTOCOLS)
, m_customProtocolManagerProxy(this)
#endif
#if PLATFORM(MAC)
, m_processSuppressionEnabled(false)
#endif
{
connect();
}
WebProcessProxy::~WebProcessProxy()
{
if (m_webConnection)
m_webConnection->invalidate();
}
void WebProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
{
launchOptions.processType = ProcessLauncher::WebProcess;
platformGetLaunchOptions(launchOptions);
}
void WebProcessProxy::connectionWillOpen(CoreIPC::Connection* connection)
{
ASSERT(this->connection() == connection);
#if USE(SECURITY_FRAMEWORK)
SecItemShimProxy::shared().initializeConnection(connection);
#endif
for (WebPageProxyMap::iterator it = m_pageMap.begin(), end = m_pageMap.end(); it != end; ++it)
it->value->connectionWillOpen(connection);
m_context->processWillOpenConnection(this);
}
void WebProcessProxy::connectionWillClose(CoreIPC::Connection* connection)
{
ASSERT(this->connection() == connection);
for (WebPageProxyMap::iterator it = m_pageMap.begin(), end = m_pageMap.end(); it != end; ++it)
it->value->connectionWillClose(connection);
m_context->processWillCloseConnection(this);
}
void WebProcessProxy::disconnect()
{
clearConnection();
if (m_webConnection) {
m_webConnection->invalidate();
m_webConnection = nullptr;
}
m_responsivenessTimer.invalidate();
Vector<RefPtr<WebFrameProxy> > frames;
copyValuesToVector(m_frameMap, frames);
for (size_t i = 0, size = frames.size(); i < size; ++i)
frames[i]->disconnect();
m_frameMap.clear();
if (m_downloadProxyMap)
m_downloadProxyMap->processDidClose();
m_context->disconnectProcess(this);
}
WebPageProxy* WebProcessProxy::webPage(uint64_t pageID)
{
return globalPageMap().get(pageID);
}
PassRefPtr<WebPageProxy> WebProcessProxy::createWebPage(PageClient* pageClient, WebContext*, WebPageGroup* pageGroup)
{
uint64_t pageID = generatePageID();
RefPtr<WebPageProxy> webPage = WebPageProxy::create(pageClient, this, pageGroup, pageID);
m_pageMap.set(pageID, webPage.get());
globalPageMap().set(pageID, webPage.get());
#if PLATFORM(MAC)
if (pageIsProcessSuppressible(webPage.get()))
m_processSuppressiblePages.add(pageID);
updateProcessSuppressionState();
#endif
return webPage.release();
}
void WebProcessProxy::addExistingWebPage(WebPageProxy* webPage, uint64_t pageID)
{
m_pageMap.set(pageID, webPage);
globalPageMap().set(pageID, webPage);
#if PLATFORM(MAC)
if (pageIsProcessSuppressible(webPage))
m_processSuppressiblePages.add(pageID);
updateProcessSuppressionState();
#endif
}
void WebProcessProxy::removeWebPage(uint64_t pageID)
{
m_pageMap.remove(pageID);
globalPageMap().remove(pageID);
#if PLATFORM(MAC)
m_processSuppressiblePages.remove(pageID);
updateProcessSuppressionState();
#endif
// If this was the last WebPage open in that web process, and we have no other reason to keep it alive, let it go.
// We only allow this when using a network process, as otherwise the WebProcess needs to preserve its session state.
if (m_context->usesNetworkProcess() && canTerminateChildProcess()) {
abortProcessLaunchIfNeeded();
disconnect();
}
}
Vector<WebPageProxy*> WebProcessProxy::pages() const
{
Vector<WebPageProxy*> result;
copyValuesToVector(m_pageMap, result);
return result;
}
WebBackForwardListItem* WebProcessProxy::webBackForwardItem(uint64_t itemID) const
{
return m_backForwardListItemMap.get(itemID);
}
void WebProcessProxy::registerNewWebBackForwardListItem(WebBackForwardListItem* item)
{
// This item was just created by the UIProcess and is being added to the map for the first time
// so we should not already have an item for this ID.
ASSERT(!m_backForwardListItemMap.contains(item->itemID()));
m_backForwardListItemMap.set(item->itemID(), item);
}
void WebProcessProxy::assumeReadAccessToBaseURL(const String& urlString)
{
KURL url(KURL(), urlString);
if (!url.isLocalFile())
return;
// There's a chance that urlString does not point to a directory.
// Get url's base URL to add to m_localPathsWithAssumedReadAccess.
KURL baseURL(KURL(), url.baseAsString());
// Client loads an alternate string. This doesn't grant universal file read, but the web process is assumed
// to have read access to this directory already.
m_localPathsWithAssumedReadAccess.add(baseURL.fileSystemPath());
}
bool WebProcessProxy::checkURLReceivedFromWebProcess(const String& urlString)
{
return checkURLReceivedFromWebProcess(KURL(KURL(), urlString));
}
bool WebProcessProxy::checkURLReceivedFromWebProcess(const KURL& url)
{
// FIXME: Consider checking that the URL is valid. Currently, WebProcess sends invalid URLs in many cases, but it probably doesn't have good reasons to do that.
// Any other non-file URL is OK.
if (!url.isLocalFile())
return true;
// Any file URL is also OK if we've loaded a file URL through API before, granting universal read access.
if (m_mayHaveUniversalFileReadSandboxExtension)
return true;
// If we loaded a string with a file base URL before, loading resources from that subdirectory is fine.
// There are no ".." components, because all URLs received from WebProcess are parsed with KURL, which removes those.
String path = url.fileSystemPath();
for (HashSet<String>::const_iterator iter = m_localPathsWithAssumedReadAccess.begin(); iter != m_localPathsWithAssumedReadAccess.end(); ++iter) {
if (path.startsWith(*iter))
return true;
}
// Items in back/forward list have been already checked.
// One case where we don't have sandbox extensions for file URLs in b/f list is if the list has been reinstated after a crash or a browser restart.
for (WebBackForwardListItemMap::iterator iter = m_backForwardListItemMap.begin(), end = m_backForwardListItemMap.end(); iter != end; ++iter) {
if (KURL(KURL(), iter->value->url()).fileSystemPath() == path)
return true;
if (KURL(KURL(), iter->value->originalURL()).fileSystemPath() == path)
return true;
}
// A Web process that was never asked to load a file URL should not ever ask us to do anything with a file URL.
WTFLogAlways("Received an unexpected URL from the web process: '%s'\n", url.string().utf8().data());
return false;
}
#if !PLATFORM(MAC)
bool WebProcessProxy::fullKeyboardAccessEnabled()
{
return false;
}
#endif
void WebProcessProxy::addBackForwardItem(uint64_t itemID, const String& originalURL, const String& url, const String& title, const CoreIPC::DataReference& backForwardData)
{
MESSAGE_CHECK_URL(originalURL);
MESSAGE_CHECK_URL(url);
WebBackForwardListItemMap::AddResult result = m_backForwardListItemMap.add(itemID, 0);
if (result.isNewEntry) {
result.iterator->value = WebBackForwardListItem::create(originalURL, url, title, backForwardData.data(), backForwardData.size(), itemID);
return;
}
// Update existing item.
result.iterator->value->setOriginalURL(originalURL);
result.iterator->value->setURL(url);
result.iterator->value->setTitle(title);
result.iterator->value->setBackForwardData(backForwardData.data(), backForwardData.size());
}
#if ENABLE(NETSCAPE_PLUGIN_API)
void WebProcessProxy::getPlugins(bool refresh, Vector<PluginInfo>& plugins)
{
if (refresh)
m_context->pluginInfoStore().refresh();
Vector<PluginModuleInfo> pluginModules = m_context->pluginInfoStore().plugins();
for (size_t i = 0; i < pluginModules.size(); ++i)
plugins.append(pluginModules[i].info);
#if PLATFORM(MAC)
// Add built-in PDF last, so that it's not used when a real plug-in is installed.
if (!m_context->omitPDFSupport()) {
#if ENABLE(PDFKIT_PLUGIN)
plugins.append(PDFPlugin::pluginInfo());
#endif
plugins.append(SimplePDFPlugin::pluginInfo());
}
#endif
}
#endif // ENABLE(NETSCAPE_PLUGIN_API)
#if ENABLE(PLUGIN_PROCESS)
void WebProcessProxy::getPluginProcessConnection(uint64_t pluginProcessToken, PassRefPtr<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply> reply)
{
PluginProcessManager::shared().getPluginProcessConnection(pluginProcessToken, reply);
}
#elif ENABLE(NETSCAPE_PLUGIN_API)
void WebProcessProxy::didGetSitesWithPluginData(const Vector<String>& sites, uint64_t callbackID)
{
m_context->pluginSiteDataManager()->didGetSitesWithData(sites, callbackID);
}
void WebProcessProxy::didClearPluginSiteData(uint64_t callbackID)
{
m_context->pluginSiteDataManager()->didClearSiteData(callbackID);
}
#endif
#if ENABLE(SHARED_WORKER_PROCESS)
void WebProcessProxy::getSharedWorkerProcessConnection(const String& /* url */, const String& /* name */, PassRefPtr<Messages::WebProcessProxy::GetSharedWorkerProcessConnection::DelayedReply>)
{
// FIXME: Implement
}
#endif // ENABLE(SHARED_WORKER_PROCESS)
#if ENABLE(NETWORK_PROCESS)
void WebProcessProxy::getNetworkProcessConnection(PassRefPtr<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply> reply)
{
m_context->getNetworkProcessConnection(reply);
}
#endif // ENABLE(NETWORK_PROCESS)
void WebProcessProxy::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder)
{
if (dispatchMessage(connection, decoder))
return;
if (m_context->dispatchMessage(connection, decoder))
return;
if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) {
didReceiveWebProcessProxyMessage(connection, decoder);
return;
}
// FIXME: Add unhandled message logging.
}
void WebProcessProxy::didReceiveSyncMessage(CoreIPC::Connection* connection, CoreIPC::MessageDecoder& decoder, OwnPtr<CoreIPC::MessageEncoder>& replyEncoder)
{
if (dispatchSyncMessage(connection, decoder, replyEncoder))
return;
if (m_context->dispatchSyncMessage(connection, decoder, replyEncoder))
return;
if (decoder.messageReceiverName() == Messages::WebProcessProxy::messageReceiverName()) {
didReceiveSyncWebProcessProxyMessage(connection, decoder, replyEncoder);
return;
}
// FIXME: Add unhandled message logging.
}
void WebProcessProxy::didClose(CoreIPC::Connection*)
{
// Protect ourselves, as the call to disconnect() below may otherwise cause us
// to be deleted before we can finish our work.
RefPtr<WebProcessProxy> protect(this);
webConnection()->didClose();
Vector<RefPtr<WebPageProxy> > pages;
copyValuesToVector(m_pageMap, pages);
disconnect();
for (size_t i = 0, size = pages.size(); i < size; ++i)
pages[i]->processDidCrash();
}
void WebProcessProxy::didReceiveInvalidMessage(CoreIPC::Connection* connection, CoreIPC::StringReference messageReceiverName, CoreIPC::StringReference messageName)
{
WTFLogAlways("Received an invalid message \"%s.%s\" from the web process.\n", messageReceiverName.toString().data(), messageName.toString().data());
WebContext::didReceiveInvalidMessage(messageReceiverName, messageName);
// Terminate the WebProcess.
terminate();
// Since we've invalidated the connection we'll never get a CoreIPC::Connection::Client::didClose
// callback so we'll explicitly call it here instead.
didClose(connection);
}
void WebProcessProxy::didBecomeUnresponsive(ResponsivenessTimer*)
{
Vector<RefPtr<WebPageProxy> > pages;
copyValuesToVector(m_pageMap, pages);
for (size_t i = 0, size = pages.size(); i < size; ++i)
pages[i]->processDidBecomeUnresponsive();
}
void WebProcessProxy::interactionOccurredWhileUnresponsive(ResponsivenessTimer*)
{
Vector<RefPtr<WebPageProxy> > pages;
copyValuesToVector(m_pageMap, pages);
for (size_t i = 0, size = pages.size(); i < size; ++i)
pages[i]->interactionOccurredWhileProcessUnresponsive();
}
void WebProcessProxy::didBecomeResponsive(ResponsivenessTimer*)
{
Vector<RefPtr<WebPageProxy> > pages;
copyValuesToVector(m_pageMap, pages);
for (size_t i = 0, size = pages.size(); i < size; ++i)
pages[i]->processDidBecomeResponsive();
}
void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, CoreIPC::Connection::Identifier connectionIdentifier)
{
ChildProcessProxy::didFinishLaunching(launcher, connectionIdentifier);
m_webConnection = WebConnectionToWebProcess::create(this);
m_context->processDidFinishLaunching(this);
#if PLATFORM(MAC)
updateProcessSuppressionState();
#endif
}
WebFrameProxy* WebProcessProxy::webFrame(uint64_t frameID) const
{
if (!WebFrameProxyMap::isValidKey(frameID))
return 0;
return m_frameMap.get(frameID);
}
bool WebProcessProxy::canCreateFrame(uint64_t frameID) const
{
return WebFrameProxyMap::isValidKey(frameID) && !m_frameMap.contains(frameID);
}
void WebProcessProxy::frameCreated(uint64_t frameID, WebFrameProxy* frameProxy)
{
ASSERT(canCreateFrame(frameID));
m_frameMap.set(frameID, frameProxy);
}
void WebProcessProxy::didDestroyFrame(uint64_t frameID)
{
// If the page is closed before it has had the chance to send the DidCreateMainFrame message
// back to the UIProcess, then the frameDestroyed message will still be received because it
// gets sent directly to the WebProcessProxy.
ASSERT(WebFrameProxyMap::isValidKey(frameID));
m_frameMap.remove(frameID);
}
void WebProcessProxy::disconnectFramesFromPage(WebPageProxy* page)
{
Vector<RefPtr<WebFrameProxy> > frames;
copyValuesToVector(m_frameMap, frames);
for (size_t i = 0, size = frames.size(); i < size; ++i) {
if (frames[i]->page() == page)
frames[i]->disconnect();
}
}
size_t WebProcessProxy::frameCountInPage(WebPageProxy* page) const
{
size_t result = 0;
for (HashMap<uint64_t, RefPtr<WebFrameProxy> >::const_iterator iter = m_frameMap.begin(); iter != m_frameMap.end(); ++iter) {
if (iter->value->page() == page)
++result;
}
return result;
}
bool WebProcessProxy::canTerminateChildProcess()
{
if (!m_pageMap.isEmpty())
return false;
if (m_downloadProxyMap && !m_downloadProxyMap->isEmpty())
return false;
if (!m_context->shouldTerminate(this))
return false;
return true;
}
void WebProcessProxy::shouldTerminate(bool& shouldTerminate)
{
shouldTerminate = canTerminateChildProcess();
if (shouldTerminate) {
// We know that the web process is going to terminate so disconnect it from the context.
disconnect();
}
}
void WebProcessProxy::updateTextCheckerState()
{
if (canSendMessage())
send(Messages::WebProcess::SetTextCheckerState(TextChecker::state()), 0);
}
DownloadProxy* WebProcessProxy::createDownloadProxy()
{
#if ENABLE(NETWORK_PROCESS)
ASSERT(!m_context->usesNetworkProcess());
#endif
if (!m_downloadProxyMap)
m_downloadProxyMap = adoptPtr(new DownloadProxyMap(this));
return m_downloadProxyMap->createDownloadProxy(m_context.get());
}
void WebProcessProxy::didNavigateWithNavigationData(uint64_t pageID, const WebNavigationDataStore& store, uint64_t frameID)
{
WebPageProxy* page = webPage(pageID);
if (!page)
return;
WebFrameProxy* frame = webFrame(frameID);
MESSAGE_CHECK(frame);
MESSAGE_CHECK(frame->page() == page);
m_context->historyClient().didNavigateWithNavigationData(m_context.get(), page, store, frame);
}
void WebProcessProxy::didPerformClientRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID)
{
WebPageProxy* page = webPage(pageID);
if (!page)
return;
if (sourceURLString.isEmpty() || destinationURLString.isEmpty())
return;
WebFrameProxy* frame = webFrame(frameID);
MESSAGE_CHECK(frame);
MESSAGE_CHECK(frame->page() == page);
MESSAGE_CHECK_URL(sourceURLString);
MESSAGE_CHECK_URL(destinationURLString);
m_context->historyClient().didPerformClientRedirect(m_context.get(), page, sourceURLString, destinationURLString, frame);
}
void WebProcessProxy::didPerformServerRedirect(uint64_t pageID, const String& sourceURLString, const String& destinationURLString, uint64_t frameID)
{
WebPageProxy* page = webPage(pageID);
if (!page)
return;
if (sourceURLString.isEmpty() || destinationURLString.isEmpty())
return;
WebFrameProxy* frame = webFrame(frameID);
MESSAGE_CHECK(frame);
MESSAGE_CHECK(frame->page() == page);
MESSAGE_CHECK_URL(sourceURLString);
MESSAGE_CHECK_URL(destinationURLString);
m_context->historyClient().didPerformServerRedirect(m_context.get(), page, sourceURLString, destinationURLString, frame);
}
void WebProcessProxy::didUpdateHistoryTitle(uint64_t pageID, const String& title, const String& url, uint64_t frameID)
{
WebPageProxy* page = webPage(pageID);
if (!page)
return;
WebFrameProxy* frame = webFrame(frameID);
MESSAGE_CHECK(frame);
MESSAGE_CHECK(frame->page() == page);
MESSAGE_CHECK_URL(url);
m_context->historyClient().didUpdateHistoryTitle(m_context.get(), page, title, url, frame);
}
void WebProcessProxy::pageVisibilityChanged(WebKit::WebPageProxy *page)
{
#if PLATFORM(MAC)
if (pageIsProcessSuppressible(page))
m_processSuppressiblePages.add(page->pageID());
else
m_processSuppressiblePages.remove(page->pageID());
updateProcessSuppressionState();
#else
UNUSED_PARAM(page);
#endif
}
void WebProcessProxy::pagePreferencesChanged(WebKit::WebPageProxy *page)
{
#if PLATFORM(MAC)
if (pageIsProcessSuppressible(page))
m_processSuppressiblePages.add(page->pageID());
else
m_processSuppressiblePages.remove(page->pageID());
updateProcessSuppressionState();
#else
UNUSED_PARAM(page);
#endif
}
void WebProcessProxy::didSaveToPageCache()
{
m_context->processDidCachePage(this);
}
void WebProcessProxy::releasePageCache()
{
if (canSendMessage())
send(Messages::WebProcess::ReleasePageCache(), 0);
}
void WebProcessProxy::requestTermination()
{
if (!isValid())
return;
ChildProcessProxy::terminate();
if (webConnection())
webConnection()->didClose();
disconnect();
}
void WebProcessProxy::enableSuddenTermination()
{
if (!isValid())
return;
WebCore::enableSuddenTermination();
}
void WebProcessProxy::disableSuddenTermination()
{
if (!isValid())
return;
WebCore::disableSuddenTermination();
}
} // namespace WebKit
| 31.683599 | 192 | 0.733715 | [
"vector"
] |
50934708bf966e5fb254a7e3dc35f5d5fd89a063 | 31,899 | cpp | C++ | dialog/dialogflightplan.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | 5 | 2018-01-08T22:20:07.000Z | 2021-06-19T17:42:29.000Z | dialog/dialogflightplan.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | null | null | null | dialog/dialogflightplan.cpp | ignmiz/ATC_Console | 549dd67a007cf54b976e33fed1581f30beb08b06 | [
"Intel",
"MIT"
] | 2 | 2017-08-07T23:07:42.000Z | 2021-05-09T13:02:39.000Z | #include "dialogflightplan.h"
#include "ui_dialogflightplan.h"
DialogFlightPlan::DialogFlightPlan(ATCFlight *flight, ATCAirspace *airspace, ATCSimulation *simulation, ATCFlightFactory *flightFactory, QWidget *parent) :
ATCDialog(parent, "Flight Plan", 600, 650),
flight(flight),
airspace(airspace),
simulation(simulation),
flightFactory(flightFactory),
model(new QStandardItemModel(this)),
uiInner(new Ui::DialogFlightPlan)
{
uiInner->setupUi(this);
windowSetup();
getFlightPlanSnapshot();
for(int i = 0; i < flightFactory->getAircraftTypeFactory().getTypeVectorSize(); i++)
{
QString type = flightFactory->getAircraftTypeFactory().getType(i)->getAcType().ICAOcode;
uiInner->comboBoxAcftType->addItem(type, Qt::DisplayRole);
}
uiInner->lineEditCallsign->setInputMask(">AAAxxxxxxx");
uiInner->lineEditDeparture->setInputMask(">AAAA");
uiInner->lineEditDestination->setInputMask(">AAAA");
uiInner->lineEditAlternate->setInputMask(">AAAA");
uiInner->lineEditAltitude->setInputMask(">A999");
uiInner->lineEditTAS->setInputMask("9990");
uiInner->lineEditSquawk->setInputMask("9999");
uiInner->lineEditCallsign->setText(flight->getFlightPlan()->getCompany()->getCode() + flight->getFlightPlan()->getFlightNumber());
if(flight->getFlightPlan()->getFlightRules() == ATC::IFR)
{
uiInner->comboBoxFlightRules->setCurrentIndex(uiInner->comboBoxFlightRules->findText("IFR"));
}
else if(flight->getFlightPlan()->getFlightRules() == ATC::VFR)
{
uiInner->comboBoxFlightRules->setCurrentIndex(uiInner->comboBoxFlightRules->findText("VFR"));
}
else
{
uiInner->comboBoxFlightRules->setCurrentIndex(uiInner->comboBoxFlightRules->findText("SVFR"));
}
QString acftType = flight->getFlightPlan()->getType()->getAcType().ICAOcode;
uiInner->comboBoxAcftType->setCurrentIndex(uiInner->comboBoxAcftType->findText(acftType));
uiInner->comboBoxAcftType->setEnabled(false);
uiInner->lineEditDeparture->setText(flight->getFlightPlan()->getRoute().getDeparture());
uiInner->lineEditDestination->setText(flight->getFlightPlan()->getRoute().getDestination());
uiInner->lineEditAlternate->setText(flight->getFlightPlan()->getRoute().getAlternate());
uiInner->lineEditTAS->setText(QString::number(flight->getFlightPlan()->getTAS()));
uiInner->lineEditAltitude->setText(flight->getFlightPlan()->getAltitude());
uiInner->lineEditSquawk->setText(flight->getAssignedSquawk());
QStringList route = flight->getFlightPlan()->getRoute().getRoute();
QString routeStr;
for(int i = 0; i < route.size() - 1; i++)
{
routeStr = routeStr + route.at(i) + " ";
}
if(route.size() >= 1)routeStr = routeStr + route.at(route.size() - 1);
uiInner->plainTextEditRoute->setPlainText(routeStr);
uiInner->timeEditDepTime->setEnabled(false);
uiInner->timeEditEnrTime->setEnabled(false);
uiInner->timeEditFuelTime->setEnabled(false);
uiInner->labelError->setVisible(false);
model->setColumnCount(3);
uiInner->tableViewValidator->setModel(model);
uiInner->tableViewValidator->setGridStyle(Qt::NoPen);
uiInner->tableViewValidator->horizontalHeader()->setHidden(true);
uiInner->tableViewValidator->verticalHeader()->setHidden(true);
}
DialogFlightPlan::~DialogFlightPlan()
{
if(model != nullptr) delete model;
delete uiInner;
}
void DialogFlightPlan::on_plainTextEditRoute_textChanged()
{
routeValid = validateRoute();
}
bool DialogFlightPlan::validateRoute()
{
bool error = false;
model->clear();
QStringList routeStr = uiInner->plainTextEditRoute->toPlainText().toUpper().split(" ", QString::SkipEmptyParts);
if(routeStr.isEmpty())
{
errorMessage("Route is empty");
error = true;
}
else
{
QList<QStandardItem*> row;
QStandardItem *emptyAirway = new QStandardItem();
emptyAirway->setFlags(Qt::NoItemFlags);
row.append(emptyAirway);
QStandardItem *firstFix = new QStandardItem(routeStr.at(0));
firstFix->setFlags(Qt::NoItemFlags);
firstFix->setTextAlignment(Qt::AlignCenter);
row.append(firstFix);
if(airspace->isValidNavaid(routeStr.at(0)) || ((routeStr.at(0) == "DCT") && (routeStr.size() == 1)))
{
firstFix->setBackground(QBrush(Qt::darkGreen));
QStandardItem *description = new QStandardItem("Correct");
description->setFlags(Qt::NoItemFlags);
description->setTextAlignment(Qt::AlignCenter);
description->setForeground(Qt::green);
row.append(description);
}
else
{
firstFix->setBackground(QBrush(Qt::darkRed));
QStandardItem *description = new QStandardItem(routeStr.at(0) + " not found");
description->setFlags(Qt::NoItemFlags);
description->setTextAlignment(Qt::AlignCenter);
description->setForeground(Qt::red);
row.append(description);
error = true;
}
model->appendRow(row);
row.clear();
for(int i = 1; i < routeStr.size(); i++)
{
QStandardItem *descriptionAirway;
QStandardItem *descriptionFix;
if(i % 2 == 1)
{
QStandardItem *airway = new QStandardItem(routeStr.at(i));
airway->setFlags(Qt::NoItemFlags);
airway->setTextAlignment(Qt::AlignCenter);
ATCAbstractAirway *aw = airspace->findAirway(routeStr.at(i));
bool previousFixConnected = false;
if(aw != nullptr)
{
for(int j = 0; j < aw->getRouteFixes().size(); j++)
{
if(aw->getRouteFixes().at(j) == routeStr.at(i - 1)) previousFixConnected = true;
}
}
bool isAirway = airspace->isAirwayLow(routeStr.at(i)) || airspace->isAirwayHigh(routeStr.at(i));
if((isAirway && previousFixConnected) || (routeStr.at(i) == "DCT"))
{
descriptionAirway = new QStandardItem();
airway->setBackground(QBrush(Qt::darkGreen));
}
else
{
if(!isAirway)
{
descriptionAirway = new QStandardItem(routeStr.at(i) + " not found");
descriptionAirway->setFlags(Qt::NoItemFlags);
descriptionAirway->setTextAlignment(Qt::AlignCenter);
descriptionAirway->setForeground(Qt::red);
}
else if(!previousFixConnected)
{
descriptionAirway = new QStandardItem(routeStr.at(i - 1) + " not connected to " + routeStr.at(i));
descriptionAirway->setFlags(Qt::NoItemFlags);
descriptionAirway->setTextAlignment(Qt::AlignCenter);
descriptionAirway->setForeground(Qt::red);
}
airway->setBackground(QBrush(Qt::darkRed));
error = true;
}
row.append(airway);
}
else
{
ATCAbstractAirway *airway = airspace->findAirway(routeStr.at(i - 1));
QStringList fixList;
int firstFix = -1;
int secondFix = -1;
if(airway != nullptr)
{
fixList = airway->getRouteFixes();
for(int j = 0; j < fixList.size(); j++)
{
if(fixList.at(j) == routeStr.at(i - 2)) firstFix = j;
if(fixList.at(j) == routeStr.at(i)) secondFix = j;
}
if((qFabs(firstFix - secondFix) > 1) && (firstFix >= 0) && (secondFix >= 0))
{
if(firstFix < secondFix)
{
for(int j = firstFix + 1; j < secondFix; j++)
{
QList<QStandardItem*> tempRow;
QStandardItem *airway = new QStandardItem(routeStr.at(i - 1));
airway->setFlags(Qt::NoItemFlags);
airway->setTextAlignment(Qt::AlignCenter);
airway->setBackground(QBrush(Qt::darkGreen));
QStandardItem *fix = new QStandardItem(fixList.at(j));
fix->setFlags(Qt::NoItemFlags);
fix->setTextAlignment(Qt::AlignCenter);
fix->setBackground(QBrush(Qt::darkGreen));
QStandardItem *description = new QStandardItem("Correct");
description->setFlags(Qt::NoItemFlags);
description->setTextAlignment(Qt::AlignCenter);
description->setForeground(Qt::green);
tempRow.append(airway);
tempRow.append(fix);
tempRow.append(description);
model->appendRow(tempRow);
}
}
else if(firstFix > secondFix)
{
for(int j = firstFix - 1; j > secondFix; j--)
{
QList<QStandardItem*> tempRow;
QStandardItem *airway = new QStandardItem(routeStr.at(i - 1));
airway->setFlags(Qt::NoItemFlags);
airway->setTextAlignment(Qt::AlignCenter);
airway->setBackground(QBrush(Qt::darkGreen));
QStandardItem *fix = new QStandardItem(fixList.at(j));
fix->setFlags(Qt::NoItemFlags);
fix->setTextAlignment(Qt::AlignCenter);
fix->setBackground(QBrush(Qt::darkGreen));
QStandardItem *description = new QStandardItem("Correct");
description->setFlags(Qt::NoItemFlags);
description->setTextAlignment(Qt::AlignCenter);
description->setForeground(Qt::green);
tempRow.append(airway);
tempRow.append(fix);
tempRow.append(description);
model->appendRow(tempRow);
}
}
}
}
QStandardItem *fix = new QStandardItem(routeStr.at(i));
fix->setFlags(Qt::NoItemFlags);
fix->setTextAlignment(Qt::AlignCenter);
row.append(fix);
bool isValidNavaid = airspace->isValidNavaid(routeStr.at(i));
if(isValidNavaid && ((secondFix >= 0) || (routeStr.at(i - 1) == "DCT")))
{
fix->setBackground(QBrush(Qt::darkGreen));
descriptionFix = new QStandardItem("Correct");
descriptionFix->setFlags(Qt::NoItemFlags);
descriptionFix->setTextAlignment(Qt::AlignCenter);
descriptionFix->setForeground(Qt::green);
}
else
{
fix->setBackground(QBrush(Qt::darkRed));
error = true;
if(!isValidNavaid)
{
descriptionFix = new QStandardItem(routeStr.at(i) + " not found");
descriptionFix->setFlags(Qt::NoItemFlags);
descriptionFix->setTextAlignment(Qt::AlignCenter);
descriptionFix->setForeground(Qt::red);
}
else if(secondFix == -1)
{
descriptionFix = new QStandardItem(routeStr.at(i) + " not connected to " + routeStr.at(i - 1));
descriptionFix->setFlags(Qt::NoItemFlags);
descriptionFix->setTextAlignment(Qt::AlignCenter);
descriptionFix->setForeground(Qt::red);
}
}
if(descriptionAirway->text().isEmpty())
{
row.append(descriptionFix);
}
else
{
row.append(descriptionAirway);
}
}
if(i % 2 == 0)
{
model->appendRow(row);
row.clear();
}
}
uiInner->tableViewValidator->setModel(model);
for(int i = 0; i < model->rowCount(); i++)
{
uiInner->tableViewValidator->setRowHeight(i, 20);
}
uiInner->tableViewValidator->scrollToBottom();
}
uiInner->tableViewValidator->setColumnWidth(0, 75);
uiInner->tableViewValidator->setColumnWidth(1, 75);
uiInner->tableViewValidator->setColumnWidth(2, 260);
return !error;
}
void DialogFlightPlan::errorMessage(QString msg)
{
uiInner->labelError->setText(msg);
uiInner->labelError->setVisible(true);
}
void DialogFlightPlan::setRoute()
{
QString departure = uiInner->lineEditDeparture->text();
QString destination = uiInner->lineEditDestination->text();
ATCRoute *route = flightFactory->getRouteFactory().getRoute(departure, destination);
if(route != nullptr)
{
QString strRoute = route->getRoute().at(0);
for(int i = 1; i < route->getRoute().size(); i++)
{
strRoute = strRoute + " " + route->getRoute().at(i);
}
uiInner->plainTextEditRoute->setPlainText(strRoute);
}
else
{
errorMessage("ERROR: Route not found!");
}
}
void DialogFlightPlan::setCallsign()
{
QString company = flightFactory->getCompanyFactory().getCompany()->getCode();
QString flightNumber = ATCFlightNumberFactory::getFlightNumber();
QString callsign = company + flightNumber;
uiInner->lineEditCallsign->setText(callsign);
}
void DialogFlightPlan::setSquawk()
{
QString squawk = ATCFlightFactory::generateSquawk();
if((squawk != "7500") || (squawk != "7500") || (squawk != "7600") || (squawk != "7700"))
{
uiInner->lineEditSquawk->setText(squawk);
}
else
{
setSquawk();
}
}
void DialogFlightPlan::setTAS()
{
QString altitude = uiInner->lineEditAltitude->text();
double alt = altitude.right(altitude.size() - 1).toDouble() * 100;
alt = ATCMath::ft2m(alt);
ISA isa = ATCMath::atmosISA(alt);
QString typeStr = uiInner->comboBoxAcftType->currentText();
ATCAircraftType *type = flightFactory->getAircraftTypeFactory().getType(typeStr);
double mach = type->getVelocity().M_CR_AV;
double cas = type->getVelocity().V_CR2_AV;
double crossoverAlt = ATCMath::crossoverAltitude(cas, mach);
crossoverAlt = ATCMath::m2ft(crossoverAlt);
int tas;
if(alt >= crossoverAlt)
{
tas = qFabs(ATCMath::mps2kt(ATCMath::mach2tas(mach, isa.a)));
}
else
{
tas = qFabs(ATCMath::mps2kt(ATCMath::cas2tas(ATCMath::kt2mps(cas), isa.p, isa.rho)));
}
uiInner->lineEditTAS->setText(QString::number(tas));
}
void DialogFlightPlan::on_buttonFillAll_clicked()
{
setCallsign();
setTAS();
setRoute();
setSquawk();
}
void DialogFlightPlan::on_buttonSetCallsign_clicked()
{
setCallsign();
}
void DialogFlightPlan::on_buttonSetTAS_clicked()
{
setTAS();
}
void DialogFlightPlan::on_buttonSetSquawk_clicked()
{
setSquawk();
}
void DialogFlightPlan::on_buttonSetRoute_clicked()
{
setRoute();
}
void DialogFlightPlan::on_buttonOK_clicked()
{
bool filledOK = verifyForm();
if(filledOK)
{
//Flight plan - Flight rules
QString rulesStr = uiInner->comboBoxFlightRules->currentText();
ATC::FlightRules rules;
if(rulesStr == "IFR")
{
rules = ATC::IFR;
}
else if(rulesStr == "VFR")
{
rules = ATC::VFR;
}
else if(rulesStr == "SVFR")
{
rules = ATC::SVFR;
}
flight->getFlightPlan()->setFlightRules(rules);
//Flight plan - company & flight number
QString callsign = uiInner->lineEditCallsign->text();
ATCCompany *company;
QString flightNo;
if(callsign.at(3).isLetter())
{
company = new ATCCompany(callsign, "UNKNOWN", "Unknown Airline");
flightFactory->getCompanyFactory().appendCompany(company);
flightNo = "";
}
else
{
if(flightFactory->getCompanyFactory().getCompany(callsign.left(3)) != nullptr)
{
company = flightFactory->getCompanyFactory().getCompany(callsign.left(3));
flightNo = callsign.right(callsign.size() - 3);
}
else
{
company = new ATCCompany(callsign.left(3), "UNKNOWN", "Unknown Airline");
flightNo = callsign.right(callsign.size() - 3);
}
}
flight->getFlightPlan()->setCompany(company);
flight->getFlightPlan()->setFlightNumber(flightNo);
//Flight plan - route
QString departure = uiInner->lineEditDeparture->text();
QString destination = uiInner->lineEditDestination->text();
QStringList routeStr = uiInner->plainTextEditRoute->toPlainText().toUpper().split(" ", QString::SkipEmptyParts);
QString alternate = uiInner->lineEditAlternate->text();
ATCRoute route(departure, routeStr, destination);
route.setAlternate(alternate);
flight->getFlightPlan()->setRoute(route);
//Flight plan - tas
int tas = uiInner->lineEditTAS->text().toInt();
flight->getFlightPlan()->setTAS(tas);
//Flight plan - altitude
QString altitude = uiInner->lineEditAltitude->text();
flight->getFlightPlan()->setAltitude(altitude);
//Flight plan - departure time
QTime depTime = uiInner->timeEditDepTime->time();
flight->getFlightPlan()->setDepartureTime(depTime);
//Flight plan - enroute time
QTime enrTime = uiInner->timeEditEnrTime->time();
flight->getFlightPlan()->setEnrouteTime(enrTime);
//Flight plan - fuel time
QTime fuelTime = uiInner->timeEditFuelTime->time();
flight->getFlightPlan()->setFuelTime(fuelTime);
//Check changes in route
bool SIDchanged = isSIDchanged();
bool STARchanged = isSTARchanged();
bool ADEPchanged = isADEPchanged();
bool ADESchanged = isADESchanged();
//Reset sid and star
if(SIDchanged) flight->setSID("");
if(STARchanged) flight->setSTAR("");
//Flight - fix list
QStringList fixList;
ATCProcedureSID *sid = airspace->findSID(flight->getSID());
ATCProcedureSTAR *star = airspace->findSTAR(flight->getSTAR());
fixList.append(departure);
if(sid != nullptr)
{
for(int i = 0; i < sid->getFixListSize(); i++)
{
if(sid->getFixName(i) != routeStr.at(0)) fixList.append(sid->getFixName(i));
}
}
for(int i = 0; i < model->rowCount(); i++)
{
QString fix = model->data(model->index(i, 1), Qt::DisplayRole).toString();
if(fix != "DCT") fixList.append(fix);
}
if(star != nullptr)
{
for(int i = 0; i < star->getFixListSize(); i++)
{
if(star->getFixName(i) != routeStr.last()) fixList.append(star->getFixName(i));
}
}
fixList.append(destination);
if(!alternate.isEmpty()) fixList.append(alternate);
flight->setFixList(fixList);
//Rebuild waypoints list
flight->clearWaypoints();
fixList = flight->getFixList();
bool foundWP = false;
for(int i = 0; i < fixList.size(); i++)
{
ATCNavFix *fix = nullptr;
ATCBeaconVOR *vor = nullptr;
ATCAirport *airport = nullptr;
ATCBeaconNDB *ndb = nullptr;
double lat;
double lon;
double x;
double y;
if((fix = airspace->findFix(fixList.at(i))) != nullptr)
{
lat = fix->latitude();
lon = fix->longitude();
x = fix->getScenePosition()->x();
y = fix->getScenePosition()->y();
}
else if((airport = airspace->findAirport(fixList.at(i))) != nullptr)
{
lat = airport->latitude();
lon = airport->longitude();
x = airport->getScenePosition()->x();
y = airport->getScenePosition()->y();
}
else if((vor = airspace->findVOR(fixList.at(i))) != nullptr)
{
lat = vor->latitude();
lon = vor->longitude();
x = vor->getScenePosition()->x();
y = vor->getScenePosition()->y();
}
else if((ndb = airspace->findNDB(fixList.at(i))) != nullptr)
{
lat = ndb->latitude();
lon = ndb->longitude();
x = ndb->getScenePosition()->x();
y = ndb->getScenePosition()->y();
}
flight->appendWaypoint(QPair<double, double>(lat, lon));
flight->appendProjectedWaypoint(QPair<double, double>(x, y));
if(fixList.at(i) == flight->getNextFix())
{
flight->setWaypointIndex(i);
foundWP = true;
}
else if(!foundWP && (i == fixList.size() - 1)) flight->setWaypointIndex(-1);
}
//Assign leg distances and angle changes
flight->clearLegAngleChanges();
flight->clearLegDistances();
double previousForwardAzimuth;
for(int i = 0; i < flight->getWaypointsVectorSize() - 1; i++)
{
GeographicLib::Geodesic geo = GeographicLib::Geodesic::WGS84();
QPair<double, double> fix1 = flight->getWaypoint(i);
QPair<double, double> fix2 = flight->getWaypoint(i + 1);
double distance;
double azimuth1to2;
double azimuth2to1;
geo.Inverse(fix1.first, fix1.second, fix2.first, fix2.second, distance, azimuth1to2, azimuth2to1);
if(i != 0)
{
double hdgChange = ATCMath::normalizeHdgChange(ATCMath::deg2rad(azimuth1to2 - previousForwardAzimuth));
flight->appendLegAngleChange(hdgChange);
}
previousForwardAzimuth = azimuth2to1;
flight->appendLegDistance(distance);
}
//Check if waypoint index found. If not, change mode to heading & update tag
if(flight->getWaypointIndex() == -1)
{
flight->setNavMode(ATC::Hdg);
flight->setHdgRestriction(ATCMath::normalizeAngle(ATCMath::rad2deg(flight->getState().hdg) - ATCConst::AVG_DECLINATION, ATC::Deg));
flight->setDCT(false);
QString shortEtiquette = flight->getFlightTag()->getTagBox()->getShortEtiquette();
QString longEtiquette = flight->getFlightTag()->getTagBox()->getLongEtiquette();
QString headingString;
if(flight->getHdgRestriction() < 10)
{
headingString = "00" + QString::number(flight->getHdgRestriction());
}
else if(flight->getHdgRestriction() < 100)
{
headingString = "0" + QString::number(flight->getHdgRestriction());
}
else
{
headingString = QString::number(flight->getHdgRestriction());
}
for(int i = 0; i < headingString.size(); i++)
{
longEtiquette[i + 39] = headingString.at(i);
}
for(int i = 0; i < 5; i++)
{
shortEtiquette[i + 24] = QChar(' ');
longEtiquette[i + 24] = QChar(' ');
}
if(flight->getFlightTag()->getTagType() == ATC::Short)
{
flight->getFlightTag()->getTagBox()->setShortEtiquette(shortEtiquette);
flight->getFlightTag()->getTagBox()->setLongEtiquette(longEtiquette);
flight->getFlightTag()->getTagBox()->rectShort2Long();
flight->getFlightTag()->setTagType(ATC::Full);
flight->getFlightTag()->getTagBox()->setLong();
}
else
{
flight->getFlightTag()->getTagBox()->setShortEtiquette(shortEtiquette);
flight->getFlightTag()->getTagBox()->setLongEtiquette(longEtiquette);
flight->getFlightTag()->getTagBox()->setLong();
}
if(flight->isFinalApp())
{
flight->setCldFinalApp(false);
flight->setFinalApp(false);
flight->setGlidePath(false);
}
}
//Flight - main fix list
QStringList mainFixList;
for(int i = 0; i < model->rowCount(); i++)
{
QString fix = model->data(model->index(i, 1), Qt::DisplayRole).toString();
if(fix != "DCT") mainFixList.append(fix);
}
flight->setMainFixList(mainFixList);
//Assign assigned SSR
flight->setAssignedSquawk(uiInner->lineEditSquawk->text());
//Assign departure & destination runway
if(ADEPchanged || ADESchanged)
{
QVector<ActiveAirport> activeAirports = simulation->getActiveRunways()->getActiveAirports();
if(ADEPchanged) flight->setRunwayDeparture("");
if(ADESchanged) flight->setRunwayDestination("");
for(int i = 0; i < activeAirports.size(); i++)
{
ActiveAirport current = activeAirports.at(i);
if(ADEPchanged)
{
if((departure == current.airportCode) && (!current.depRwys.isEmpty())) flight->setRunwayDeparture(current.depRwys.at(0));
}
if(ADESchanged)
{
if((destination == current.airportCode) && (!current.arrRwys.isEmpty())) flight->setRunwayDestination(current.arrRwys.at(0));
}
}
}
//Modify callsign on data tag
QString shortEtiquette = flight->getFlightTag()->getTagBox()->getShortEtiquette();
QString longEtiquette = flight->getFlightTag()->getTagBox()->getLongEtiquette();
for(int i = 0; i < 9; i++)
{
shortEtiquette[i] = ' ';
longEtiquette[i] = ' ';
}
for(int i = 0; i < callsign.left(9).size(); i++)
{
shortEtiquette[i] = callsign.at(i);
longEtiquette[i] = callsign.at(i);
}
flight->getFlightTag()->getTagBox()->setShortEtiquette(shortEtiquette);
flight->getFlightTag()->getTagBox()->setLongEtiquette(longEtiquette);
if(flight->getFlightTag()->getTagType() == ATC::Short)
{
flight->getFlightTag()->getTagBox()->setShort();
}
else
{
flight->getFlightTag()->getTagBox()->setLong();
}
if(flight->getRoutePrediction() != nullptr) emit signalUpdateRoute(flight);
emit signalUpdateFlightList();
emit closed();
close();
}
}
void DialogFlightPlan::on_buttonCancel_clicked()
{
emit closed();
close();
}
void DialogFlightPlan::getFlightPlanSnapshot()
{
ATCRoute route(flight->getFlightPlan()->getRoute());
temp.dep = route.getDeparture();
temp.des = route.getDestination();
temp.alt = route.getAlternate();
temp.route = route.getRoute();
}
bool DialogFlightPlan::isSIDchanged()
{
QString depUI = uiInner->lineEditDeparture->text();
QString firstFix = uiInner->plainTextEditRoute->toPlainText().split(' ', QString::SkipEmptyParts).at(0);
return ((depUI != temp.dep) || (firstFix != temp.route.at(0)));
}
bool DialogFlightPlan::isSTARchanged()
{
QString desUI = uiInner->lineEditDestination->text();
QString lastFix = uiInner->plainTextEditRoute->toPlainText().split(' ', QString::SkipEmptyParts).last();
return ((desUI != temp.des) || (lastFix != temp.route.last()));
}
bool DialogFlightPlan::isADEPchanged()
{
QString depUI = uiInner->lineEditDeparture->text();
return (depUI != temp.dep);
}
bool DialogFlightPlan::isADESchanged()
{
QString desUI = uiInner->lineEditDestination->text();
return (desUI != temp.des);
}
bool DialogFlightPlan::isAALTchanged()
{
QString altUI = uiInner->lineEditAlternate->text();
return (altUI != temp.alt);
}
bool DialogFlightPlan::verifyForm()
{
if(!uiInner->lineEditCallsign->text().isEmpty())
{
ATCFlight *flt = simulation->getFlight(uiInner->lineEditCallsign->text());
if((flt != nullptr) && (flt != flight))
{
errorMessage("ERROR: Callsign already in use!");
return false;
}
}
if(uiInner->lineEditCallsign->text().isEmpty())
{
errorMessage("ERROR: Callsign not specified!");
return false;
}
else if(uiInner->lineEditDeparture->text().isEmpty())
{
errorMessage("ERROR: Departure airfield not specified!");
return false;
}
else if(uiInner->lineEditDeparture->text().size() != 4)
{
errorMessage("ERROR: Departure ICAO code not correct!");
return false;
}
else if(uiInner->lineEditDestination->text().isEmpty())
{
errorMessage("ERROR: Destination airfield not specified!");
return false;
}
else if(uiInner->lineEditDestination->text().size() != 4)
{
errorMessage("ERROR: Destination ICAO code not correct!");
return false;
}
else if(uiInner->lineEditTAS->text().isEmpty())
{
errorMessage("ERROR: TAS not specified!");
return false;
}
else if(uiInner->lineEditAltitude->text().isEmpty())
{
errorMessage("ERROR: Altitude not specified!");
return false;
}
else if((uiInner->lineEditAltitude->text().left(1) != "A") &&
(uiInner->lineEditAltitude->text().left(1) != "F"))
{
errorMessage("ERROR: Incorrect altitude fomat!");
return false;
}
else if((uiInner->lineEditSquawk->text().at(0) == '8') ||
(uiInner->lineEditSquawk->text().at(1) == '8') ||
(uiInner->lineEditSquawk->text().at(2) == '8') ||
(uiInner->lineEditSquawk->text().at(3) == '8') ||
(uiInner->lineEditSquawk->text().at(0) == '9') ||
(uiInner->lineEditSquawk->text().at(1) == '9') ||
(uiInner->lineEditSquawk->text().at(2) == '9') ||
(uiInner->lineEditSquawk->text().at(3) == '9'))
{
errorMessage("ERROR: Incorrect squawk format!");
return false;
}
else if(!routeValid)
{
errorMessage("ERROR: Route incorrect! See route validator.");
return false;
}
else
{
uiInner->labelError->setVisible(false);
return true;
}
}
| 34.080128 | 155 | 0.548481 | [
"model"
] |
5094b710cea4c6b6fbe9ed5ea686e020095f3321 | 29,774 | cc | C++ | lib/wabt/src/binary-reader-ir.cc | rekhadpr/demoazure1 | 394d777e507b171876734d871d50e47254636b9d | [
"MIT"
] | null | null | null | lib/wabt/src/binary-reader-ir.cc | rekhadpr/demoazure1 | 394d777e507b171876734d871d50e47254636b9d | [
"MIT"
] | null | null | null | lib/wabt/src/binary-reader-ir.cc | rekhadpr/demoazure1 | 394d777e507b171876734d871d50e47254636b9d | [
"MIT"
] | null | null | null | /*
* 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 "binary-reader-ir.h"
#include <cassert>
#include <cinttypes>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <vector>
#include "binary-error-handler.h"
#include "binary-reader-nop.h"
#include "common.h"
#include "ir.h"
#define CHECK_RESULT(expr) \
do { \
if (WABT_FAILED(expr)) \
return Result::Error; \
} while (0)
namespace wabt {
namespace {
struct LabelNode {
LabelNode(LabelType, Expr** first);
LabelType label_type;
Expr** first;
Expr* last;
};
LabelNode::LabelNode(LabelType label_type, Expr** first)
: label_type(label_type), first(first), last(nullptr) {}
class BinaryReaderIR : public BinaryReaderNop {
public:
BinaryReaderIR(Module* out_module, BinaryErrorHandler* error_handler);
bool OnError(const char* message) override;
Result OnTypeCount(Index count) override;
Result OnType(Index index,
Index param_count,
Type* param_types,
Index result_count,
Type* result_types) override;
Result OnImportCount(Index count) override;
Result OnImport(Index index,
StringSlice module_name,
StringSlice field_name) override;
Result OnImportFunc(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index func_index,
Index sig_index) override;
Result OnImportTable(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index table_index,
Type elem_type,
const Limits* elem_limits) override;
Result OnImportMemory(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index memory_index,
const Limits* page_limits) override;
Result OnImportGlobal(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index global_index,
Type type,
bool mutable_) override;
Result OnFunctionCount(Index count) override;
Result OnFunction(Index index, Index sig_index) override;
Result OnTableCount(Index count) override;
Result OnTable(Index index,
Type elem_type,
const Limits* elem_limits) override;
Result OnMemoryCount(Index count) override;
Result OnMemory(Index index, const Limits* limits) override;
Result OnGlobalCount(Index count) override;
Result BeginGlobal(Index index, Type type, bool mutable_) override;
Result BeginGlobalInitExpr(Index index) override;
Result EndGlobalInitExpr(Index index) override;
Result OnExportCount(Index count) override;
Result OnExport(Index index,
ExternalKind kind,
Index item_index,
StringSlice name) override;
Result OnStartFunction(Index func_index) override;
Result OnFunctionBodyCount(Index count) override;
Result BeginFunctionBody(Index index) override;
Result OnLocalDecl(Index decl_index, Index count, Type type) override;
Result OnBinaryExpr(Opcode opcode) override;
Result OnBlockExpr(Index num_types, Type* sig_types) override;
Result OnBrExpr(Index depth) override;
Result OnBrIfExpr(Index depth) override;
Result OnBrTableExpr(Index num_targets,
Index* target_depths,
Index default_target_depth) override;
Result OnCallExpr(Index func_index) override;
Result OnCallIndirectExpr(Index sig_index) override;
Result OnCompareExpr(Opcode opcode) override;
Result OnConvertExpr(Opcode opcode) override;
Result OnDropExpr() override;
Result OnElseExpr() override;
Result OnEndExpr() override;
Result OnF32ConstExpr(uint32_t value_bits) override;
Result OnF64ConstExpr(uint64_t value_bits) override;
Result OnGetGlobalExpr(Index global_index) override;
Result OnGetLocalExpr(Index local_index) override;
Result OnGrowMemoryExpr() override;
Result OnI32ConstExpr(uint32_t value) override;
Result OnI64ConstExpr(uint64_t value) override;
Result OnIfExpr(Index num_types, Type* sig_types) override;
Result OnLoadExpr(Opcode opcode,
uint32_t alignment_log2,
Address offset) override;
Result OnLoopExpr(Index num_types, Type* sig_types) override;
Result OnCurrentMemoryExpr() override;
Result OnNopExpr() override;
Result OnReturnExpr() override;
Result OnSelectExpr() override;
Result OnSetGlobalExpr(Index global_index) override;
Result OnSetLocalExpr(Index local_index) override;
Result OnStoreExpr(Opcode opcode,
uint32_t alignment_log2,
Address offset) override;
Result OnTeeLocalExpr(Index local_index) override;
Result OnUnaryExpr(Opcode opcode) override;
Result OnUnreachableExpr() override;
Result EndFunctionBody(Index index) override;
Result OnElemSegmentCount(Index count) override;
Result BeginElemSegment(Index index, Index table_index) override;
Result BeginElemSegmentInitExpr(Index index) override;
Result EndElemSegmentInitExpr(Index index) override;
Result OnElemSegmentFunctionIndexCount(Index index,
Index count) override;
Result OnElemSegmentFunctionIndex(Index index,
Index func_index) override;
Result OnDataSegmentCount(Index count) override;
Result BeginDataSegment(Index index, Index memory_index) override;
Result BeginDataSegmentInitExpr(Index index) override;
Result EndDataSegmentInitExpr(Index index) override;
Result OnDataSegmentData(Index index,
const void* data,
Address size) override;
Result OnFunctionNamesCount(Index num_functions) override;
Result OnFunctionName(Index function_index,
StringSlice function_name) override;
Result OnLocalNameLocalCount(Index function_index,
Index num_locals) override;
Result OnLocalName(Index function_index,
Index local_index,
StringSlice local_name) override;
Result OnInitExprF32ConstExpr(Index index, uint32_t value) override;
Result OnInitExprF64ConstExpr(Index index, uint64_t value) override;
Result OnInitExprGetGlobalExpr(Index index, Index global_index) override;
Result OnInitExprI32ConstExpr(Index index, uint32_t value) override;
Result OnInitExprI64ConstExpr(Index index, uint64_t value) override;
private:
bool HandleError(Offset offset, const char* message);
void PrintError(const char* format, ...);
void PushLabel(LabelType label_type, Expr** first);
Result PopLabel();
Result GetLabelAt(LabelNode** label, Index depth);
Result TopLabel(LabelNode** label);
Result AppendExpr(Expr* expr);
BinaryErrorHandler* error_handler = nullptr;
Module* module = nullptr;
Func* current_func = nullptr;
std::vector<LabelNode> label_stack;
Expr** current_init_expr = nullptr;
};
BinaryReaderIR::BinaryReaderIR(Module* out_module,
BinaryErrorHandler* error_handler)
: error_handler(error_handler), module(out_module) {}
void WABT_PRINTF_FORMAT(2, 3) BinaryReaderIR::PrintError(const char* format,
...) {
WABT_SNPRINTF_ALLOCA(buffer, length, format);
HandleError(kInvalidOffset, buffer);
}
void BinaryReaderIR::PushLabel(LabelType label_type, Expr** first) {
label_stack.emplace_back(label_type, first);
}
Result BinaryReaderIR::PopLabel() {
if (label_stack.size() == 0) {
PrintError("popping empty label stack");
return Result::Error;
}
label_stack.pop_back();
return Result::Ok;
}
Result BinaryReaderIR::GetLabelAt(LabelNode** label, Index depth) {
if (depth >= label_stack.size()) {
PrintError("accessing stack depth: %" PRIindex " >= max: %" PRIzd, depth,
label_stack.size());
return Result::Error;
}
*label = &label_stack[label_stack.size() - depth - 1];
return Result::Ok;
}
Result BinaryReaderIR::TopLabel(LabelNode** label) {
return GetLabelAt(label, 0);
}
Result BinaryReaderIR::AppendExpr(Expr* expr) {
LabelNode* label;
if (WABT_FAILED(TopLabel(&label))) {
delete expr;
return Result::Error;
}
if (*label->first) {
label->last->next = expr;
label->last = expr;
} else {
*label->first = label->last = expr;
}
return Result::Ok;
}
bool BinaryReaderIR::HandleError(Offset offset, const char* message) {
return error_handler->OnError(offset, message);
}
bool BinaryReaderIR::OnError(const char* message) {
return HandleError(state->offset, message);
}
Result BinaryReaderIR::OnTypeCount(Index count) {
module->func_types.reserve(count);
return Result::Ok;
}
Result BinaryReaderIR::OnType(Index index,
Index param_count,
Type* param_types,
Index result_count,
Type* result_types) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::FuncType;
field->func_type = new FuncType();
FuncType* func_type = field->func_type;
func_type->sig.param_types.assign(param_types, param_types + param_count);
func_type->sig.result_types.assign(result_types, result_types + result_count);
module->func_types.push_back(func_type);
return Result::Ok;
}
Result BinaryReaderIR::OnImportCount(Index count) {
module->imports.reserve(count);
return Result::Ok;
}
Result BinaryReaderIR::OnImport(Index index,
StringSlice module_name,
StringSlice field_name) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Import;
field->import = new Import();
Import* import = field->import;
import->module_name = dup_string_slice(module_name);
import->field_name = dup_string_slice(field_name);
module->imports.push_back(import);
return Result::Ok;
}
Result BinaryReaderIR::OnImportFunc(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index func_index,
Index sig_index) {
assert(import_index == module->imports.size() - 1);
Import* import = module->imports[import_index];
import->kind = ExternalKind::Func;
import->func = new Func();
import->func->decl.has_func_type = true;
import->func->decl.type_var.type = VarType::Index;
import->func->decl.type_var.index = sig_index;
import->func->decl.sig = module->func_types[sig_index]->sig;
module->funcs.push_back(import->func);
module->num_func_imports++;
return Result::Ok;
}
Result BinaryReaderIR::OnImportTable(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index table_index,
Type elem_type,
const Limits* elem_limits) {
assert(import_index == module->imports.size() - 1);
Import* import = module->imports[import_index];
import->kind = ExternalKind::Table;
import->table = new Table();
import->table->elem_limits = *elem_limits;
module->tables.push_back(import->table);
module->num_table_imports++;
return Result::Ok;
}
Result BinaryReaderIR::OnImportMemory(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index memory_index,
const Limits* page_limits) {
assert(import_index == module->imports.size() - 1);
Import* import = module->imports[import_index];
import->kind = ExternalKind::Memory;
import->memory = new Memory();
import->memory->page_limits = *page_limits;
module->memories.push_back(import->memory);
module->num_memory_imports++;
return Result::Ok;
}
Result BinaryReaderIR::OnImportGlobal(Index import_index,
StringSlice module_name,
StringSlice field_name,
Index global_index,
Type type,
bool mutable_) {
assert(import_index == module->imports.size() - 1);
Import* import = module->imports[import_index];
import->kind = ExternalKind::Global;
import->global = new Global();
import->global->type = type;
import->global->mutable_ = mutable_;
module->globals.push_back(import->global);
module->num_global_imports++;
return Result::Ok;
}
Result BinaryReaderIR::OnFunctionCount(Index count) {
module->funcs.reserve(module->num_func_imports + count);
return Result::Ok;
}
Result BinaryReaderIR::OnFunction(Index index, Index sig_index) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Func;
field->func = new Func();
Func* func = field->func;
func->decl.has_func_type = true;
func->decl.type_var.type = VarType::Index;
func->decl.type_var.index = sig_index;
func->decl.sig = module->func_types[sig_index]->sig;
module->funcs.push_back(func);
return Result::Ok;
}
Result BinaryReaderIR::OnTableCount(Index count) {
module->tables.reserve(module->num_table_imports + count);
return Result::Ok;
}
Result BinaryReaderIR::OnTable(Index index,
Type elem_type,
const Limits* elem_limits) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Table;
field->table = new Table();
field->table->elem_limits = *elem_limits;
module->tables.push_back(field->table);
return Result::Ok;
}
Result BinaryReaderIR::OnMemoryCount(Index count) {
module->memories.reserve(module->num_memory_imports + count);
return Result::Ok;
}
Result BinaryReaderIR::OnMemory(Index index, const Limits* page_limits) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Memory;
field->memory = new Memory();
field->memory->page_limits = *page_limits;
module->memories.push_back(field->memory);
return Result::Ok;
}
Result BinaryReaderIR::OnGlobalCount(Index count) {
module->globals.reserve(module->num_global_imports + count);
return Result::Ok;
}
Result BinaryReaderIR::BeginGlobal(Index index, Type type, bool mutable_) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Global;
field->global = new Global();
field->global->type = type;
field->global->mutable_ = mutable_;
module->globals.push_back(field->global);
return Result::Ok;
}
Result BinaryReaderIR::BeginGlobalInitExpr(Index index) {
assert(index == module->globals.size() - 1);
Global* global = module->globals[index];
current_init_expr = &global->init_expr;
return Result::Ok;
}
Result BinaryReaderIR::EndGlobalInitExpr(Index index) {
current_init_expr = nullptr;
return Result::Ok;
}
Result BinaryReaderIR::OnExportCount(Index count) {
module->exports.reserve(count);
return Result::Ok;
}
Result BinaryReaderIR::OnExport(Index index,
ExternalKind kind,
Index item_index,
StringSlice name) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Export;
field->export_ = new Export();
Export* export_ = field->export_;
export_->name = dup_string_slice(name);
switch (kind) {
case ExternalKind::Func:
assert(item_index < module->funcs.size());
break;
case ExternalKind::Table:
assert(item_index < module->tables.size());
break;
case ExternalKind::Memory:
assert(item_index < module->memories.size());
break;
case ExternalKind::Global:
assert(item_index < module->globals.size());
break;
case ExternalKind::Except:
WABT_FATAL("OnExport(except) not implemented\n");
break;
}
export_->var.type = VarType::Index;
export_->var.index = item_index;
export_->kind = kind;
module->exports.push_back(export_);
return Result::Ok;
}
Result BinaryReaderIR::OnStartFunction(Index func_index) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::Start;
field->start.type = VarType::Index;
assert(func_index < module->funcs.size());
field->start.index = func_index;
module->start = &field->start;
return Result::Ok;
}
Result BinaryReaderIR::OnFunctionBodyCount(Index count) {
assert(module->num_func_imports + count == module->funcs.size());
return Result::Ok;
}
Result BinaryReaderIR::BeginFunctionBody(Index index) {
current_func = module->funcs[index];
PushLabel(LabelType::Func, ¤t_func->first_expr);
return Result::Ok;
}
Result BinaryReaderIR::OnLocalDecl(Index decl_index, Index count, Type type) {
TypeVector& types = current_func->local_types;
types.reserve(types.size() + count);
for (size_t i = 0; i < count; ++i)
types.push_back(type);
return Result::Ok;
}
Result BinaryReaderIR::OnBinaryExpr(Opcode opcode) {
Expr* expr = Expr::CreateBinary(opcode);
return AppendExpr(expr);
}
Result BinaryReaderIR::OnBlockExpr(Index num_types, Type* sig_types) {
Expr* expr = Expr::CreateBlock(new Block());
expr->block->sig.assign(sig_types, sig_types + num_types);
AppendExpr(expr);
PushLabel(LabelType::Block, &expr->block->first);
return Result::Ok;
}
Result BinaryReaderIR::OnBrExpr(Index depth) {
Expr* expr = Expr::CreateBr(Var(depth));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnBrIfExpr(Index depth) {
Expr* expr = Expr::CreateBrIf(Var(depth));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnBrTableExpr(Index num_targets,
Index* target_depths,
Index default_target_depth) {
VarVector* targets = new VarVector();
targets->resize(num_targets);
for (Index i = 0; i < num_targets; ++i) {
(*targets)[i] = Var(target_depths[i]);
}
Expr* expr = Expr::CreateBrTable(targets, Var(default_target_depth));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnCallExpr(Index func_index) {
assert(func_index < module->funcs.size());
Expr* expr = Expr::CreateCall(Var(func_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnCallIndirectExpr(Index sig_index) {
assert(sig_index < module->func_types.size());
Expr* expr = Expr::CreateCallIndirect(Var(sig_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnCompareExpr(Opcode opcode) {
Expr* expr = Expr::CreateCompare(opcode);
return AppendExpr(expr);
}
Result BinaryReaderIR::OnConvertExpr(Opcode opcode) {
Expr* expr = Expr::CreateConvert(opcode);
return AppendExpr(expr);
}
Result BinaryReaderIR::OnCurrentMemoryExpr() {
Expr* expr = Expr::CreateCurrentMemory();
return AppendExpr(expr);
}
Result BinaryReaderIR::OnDropExpr() {
Expr* expr = Expr::CreateDrop();
return AppendExpr(expr);
}
Result BinaryReaderIR::OnElseExpr() {
LabelNode* label;
CHECK_RESULT(TopLabel(&label));
if (label->label_type != LabelType::If) {
PrintError("else expression without matching if");
return Result::Error;
}
LabelNode* parent_label;
CHECK_RESULT(GetLabelAt(&parent_label, 1));
assert(parent_label->last->type == ExprType::If);
label->label_type = LabelType::Else;
label->first = &parent_label->last->if_.false_;
label->last = nullptr;
return Result::Ok;
}
Result BinaryReaderIR::OnEndExpr() {
return PopLabel();
}
Result BinaryReaderIR::OnF32ConstExpr(uint32_t value_bits) {
Expr* expr = Expr::CreateConst(Const(Const::F32(), value_bits));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnF64ConstExpr(uint64_t value_bits) {
Expr* expr = Expr::CreateConst(Const(Const::F64(), value_bits));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnGetGlobalExpr(Index global_index) {
Expr* expr = Expr::CreateGetGlobal(Var(global_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnGetLocalExpr(Index local_index) {
Expr* expr = Expr::CreateGetLocal(Var(local_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnGrowMemoryExpr() {
Expr* expr = Expr::CreateGrowMemory();
return AppendExpr(expr);
}
Result BinaryReaderIR::OnI32ConstExpr(uint32_t value) {
Expr* expr = Expr::CreateConst(Const(Const::I32(), value));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnI64ConstExpr(uint64_t value) {
Expr* expr = Expr::CreateConst(Const(Const::I64(), value));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnIfExpr(Index num_types, Type* sig_types) {
Expr* expr = Expr::CreateIf(new Block());
expr->if_.true_->sig.assign(sig_types, sig_types + num_types);
expr->if_.false_ = nullptr;
AppendExpr(expr);
PushLabel(LabelType::If, &expr->if_.true_->first);
return Result::Ok;
}
Result BinaryReaderIR::OnLoadExpr(Opcode opcode,
uint32_t alignment_log2,
Address offset) {
Expr* expr = Expr::CreateLoad(opcode, 1 << alignment_log2, offset);
return AppendExpr(expr);
}
Result BinaryReaderIR::OnLoopExpr(Index num_types, Type* sig_types) {
Expr* expr = Expr::CreateLoop(new Block());
expr->loop->sig.assign(sig_types, sig_types + num_types);
AppendExpr(expr);
PushLabel(LabelType::Loop, &expr->loop->first);
return Result::Ok;
}
Result BinaryReaderIR::OnNopExpr() {
Expr* expr = Expr::CreateNop();
return AppendExpr(expr);
}
Result BinaryReaderIR::OnReturnExpr() {
Expr* expr = Expr::CreateReturn();
return AppendExpr(expr);
}
Result BinaryReaderIR::OnSelectExpr() {
Expr* expr = Expr::CreateSelect();
return AppendExpr(expr);
}
Result BinaryReaderIR::OnSetGlobalExpr(Index global_index) {
Expr* expr = Expr::CreateSetGlobal(Var(global_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnSetLocalExpr(Index local_index) {
Expr* expr = Expr::CreateSetLocal(Var(local_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnStoreExpr(Opcode opcode,
uint32_t alignment_log2,
Address offset) {
Expr* expr = Expr::CreateStore(opcode, 1 << alignment_log2, offset);
return AppendExpr(expr);
}
Result BinaryReaderIR::OnTeeLocalExpr(Index local_index) {
Expr* expr = Expr::CreateTeeLocal(Var(local_index));
return AppendExpr(expr);
}
Result BinaryReaderIR::OnUnaryExpr(Opcode opcode) {
Expr* expr = Expr::CreateUnary(opcode);
return AppendExpr(expr);
}
Result BinaryReaderIR::OnUnreachableExpr() {
Expr* expr = Expr::CreateUnreachable();
return AppendExpr(expr);
}
Result BinaryReaderIR::EndFunctionBody(Index index) {
CHECK_RESULT(PopLabel());
current_func = nullptr;
return Result::Ok;
}
Result BinaryReaderIR::OnElemSegmentCount(Index count) {
module->elem_segments.reserve(count);
return Result::Ok;
}
Result BinaryReaderIR::BeginElemSegment(Index index, Index table_index) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::ElemSegment;
field->elem_segment = new ElemSegment();
field->elem_segment->table_var.type = VarType::Index;
field->elem_segment->table_var.index = table_index;
module->elem_segments.push_back(field->elem_segment);
return Result::Ok;
}
Result BinaryReaderIR::BeginElemSegmentInitExpr(Index index) {
assert(index == module->elem_segments.size() - 1);
ElemSegment* segment = module->elem_segments[index];
current_init_expr = &segment->offset;
return Result::Ok;
}
Result BinaryReaderIR::EndElemSegmentInitExpr(Index index) {
current_init_expr = nullptr;
return Result::Ok;
}
Result BinaryReaderIR::OnElemSegmentFunctionIndexCount(Index index,
Index count) {
assert(index == module->elem_segments.size() - 1);
ElemSegment* segment = module->elem_segments[index];
segment->vars.reserve(count);
return Result::Ok;
}
Result BinaryReaderIR::OnElemSegmentFunctionIndex(Index segment_index,
Index func_index) {
assert(segment_index == module->elem_segments.size() - 1);
ElemSegment* segment = module->elem_segments[segment_index];
segment->vars.emplace_back();
Var* var = &segment->vars.back();
var->type = VarType::Index;
var->index = func_index;
return Result::Ok;
}
Result BinaryReaderIR::OnDataSegmentCount(Index count) {
module->data_segments.reserve(count);
return Result::Ok;
}
Result BinaryReaderIR::BeginDataSegment(Index index, Index memory_index) {
ModuleField* field = module->AppendField();
field->type = ModuleFieldType::DataSegment;
field->data_segment = new DataSegment();
field->data_segment->memory_var.type = VarType::Index;
field->data_segment->memory_var.index = memory_index;
module->data_segments.push_back(field->data_segment);
return Result::Ok;
}
Result BinaryReaderIR::BeginDataSegmentInitExpr(Index index) {
assert(index == module->data_segments.size() - 1);
DataSegment* segment = module->data_segments[index];
current_init_expr = &segment->offset;
return Result::Ok;
}
Result BinaryReaderIR::EndDataSegmentInitExpr(Index index) {
current_init_expr = nullptr;
return Result::Ok;
}
Result BinaryReaderIR::OnDataSegmentData(Index index,
const void* data,
Address size) {
assert(index == module->data_segments.size() - 1);
DataSegment* segment = module->data_segments[index];
segment->data = new char[size];
segment->size = size;
memcpy(segment->data, data, size);
return Result::Ok;
}
Result BinaryReaderIR::OnFunctionNamesCount(Index count) {
if (count > module->funcs.size()) {
PrintError("expected function name count (%" PRIindex
") <= function count (%" PRIzd ")",
count, module->funcs.size());
return Result::Error;
}
return Result::Ok;
}
Result BinaryReaderIR::OnFunctionName(Index index, StringSlice name) {
if (string_slice_is_empty(&name))
return Result::Ok;
Func* func = module->funcs[index];
std::string dollar_name = std::string("$") + string_slice_to_string(name);
func->name = dup_string_slice(string_to_string_slice(dollar_name));
module->func_bindings.emplace(dollar_name, Binding(index));
return Result::Ok;
}
Result BinaryReaderIR::OnLocalNameLocalCount(Index index, Index count) {
assert(index < module->funcs.size());
Func* func = module->funcs[index];
Index num_params_and_locals = func->GetNumParamsAndLocals();
if (count > num_params_and_locals) {
PrintError("expected local name count (%" PRIindex
") <= local count (%" PRIindex ")",
count, num_params_and_locals);
return Result::Error;
}
return Result::Ok;
}
Result BinaryReaderIR::OnInitExprF32ConstExpr(Index index, uint32_t value) {
*current_init_expr = Expr::CreateConst(Const(Const::F32(), value));
return Result::Ok;
}
Result BinaryReaderIR::OnInitExprF64ConstExpr(Index index, uint64_t value) {
*current_init_expr = Expr::CreateConst(Const(Const::F64(), value));
return Result::Ok;
}
Result BinaryReaderIR::OnInitExprGetGlobalExpr(Index index,
Index global_index) {
*current_init_expr = Expr::CreateGetGlobal(Var(global_index));
return Result::Ok;
}
Result BinaryReaderIR::OnInitExprI32ConstExpr(Index index, uint32_t value) {
*current_init_expr = Expr::CreateConst(Const(Const::I32(), value));
return Result::Ok;
}
Result BinaryReaderIR::OnInitExprI64ConstExpr(Index index, uint64_t value) {
*current_init_expr = Expr::CreateConst(Const(Const::I64(), value));
return Result::Ok;
}
Result BinaryReaderIR::OnLocalName(Index func_index,
Index local_index,
StringSlice name) {
if (string_slice_is_empty(&name))
return Result::Ok;
Func* func = module->funcs[func_index];
Index num_params = func->GetNumParams();
BindingHash* bindings;
Index index;
if (local_index < num_params) {
/* param name */
bindings = &func->param_bindings;
index = local_index;
} else {
/* local name */
bindings = &func->local_bindings;
index = local_index - num_params;
}
bindings->emplace(std::string("$") + string_slice_to_string(name),
Binding(index));
return Result::Ok;
}
} // namespace
Result read_binary_ir(const void* data,
size_t size,
const ReadBinaryOptions* options,
BinaryErrorHandler* error_handler,
struct Module* out_module) {
BinaryReaderIR reader(out_module, error_handler);
Result result = read_binary(data, size, &reader, options);
return result;
}
} // namespace wabt
| 32.790749 | 80 | 0.676597 | [
"vector"
] |
509c72e5eef28a94ce6fbd507a99a1650c01dd23 | 6,105 | cpp | C++ | javascript/binding.cpp | Sleen/FlexLayout | 4daacd256d5b4ef7b76b04a85c8bfa66bf10a8f1 | [
"MIT"
] | 68 | 2017-09-20T09:29:30.000Z | 2022-01-28T02:18:45.000Z | javascript/binding.cpp | amendgit/FlexLayout | 4daacd256d5b4ef7b76b04a85c8bfa66bf10a8f1 | [
"MIT"
] | 3 | 2019-04-04T06:28:55.000Z | 2021-08-05T10:24:18.000Z | javascript/binding.cpp | amendgit/FlexLayout | 4daacd256d5b4ef7b76b04a85c8bfa66bf10a8f1 | [
"MIT"
] | 6 | 2018-01-25T15:56:04.000Z | 2021-02-22T03:06:40.000Z | extern "C" {
#include "../src/FlexLayout.c"
}
#include <vector>
#include <memory>
#include <functional>
template<typename T, bool isEnum = false> struct _WrapType { using type = T; };
template<typename T> struct _WrapType<T, true> { using type = typename std::underlying_type<T>::type; };
template<typename T> struct WrapType {
using type = typename _WrapType<T, std::is_enum<T>::value>::type;
};
typedef struct Size {
float width;
float height;
Size(float width, float height) {
this->width = width;
this->height = height;
}
Size(): Size(0, 0) {}
float getWidth() { return width; }
void setWidth(float width) { this->width = width; }
float getHeight() { return height; }
void setHeight(float height) { this->height = height; }
} Size;
struct Length {
using LengthType = typename WrapType<FlexLengthType>::type;
float value;
LengthType type;
Length(float value, LengthType type) {
this->value = value;
this->type = type;
}
Length(float value): Length(value, (LengthType)FlexLengthTypePoint) {}
Length(): Length(0, (LengthType)FlexLengthTypePoint) {}
float getValue() { return value; }
void setValue(float value) { this->value = value; }
LengthType getType() { return type; }
void setType(LengthType type) { this->type = type; }
};
class Node {
private:
FlexNodeRef _node;
std::vector<std::shared_ptr<Node>> children;
typedef std::function<Size (Size)> MeasureCallback;
typedef std::function<float (Size)> BaselineCallback;
MeasureCallback measure;
BaselineCallback baseline;
static FlexSize static_measure(void* context, FlexSize constrainedSize) {
Node* node = (Node*)context;
Size size = node->measure(Size{constrainedSize.width, constrainedSize.height});
return FlexSize{size.width, size.height};
}
static float static_baseline(void* context, FlexSize constrainedSize) {
Node* node = (Node*)context;
return node->baseline(Size{constrainedSize.width, constrainedSize.height});
}
public:
Node() {
// printf("%x\n", this);
_node = Flex_newNode();
Flex_setContext(_node, this);
}
Node(const Node& node) {
// printf("%x -> %x\n", &node, this);
_node = node._node;
Flex_setContext(_node, this);
children = node.children;
measure = node.measure;
baseline = node.baseline;
}
~Node() {
// printf("%x free\n", this);
Flex_freeNode(_node);
}
void setMeasure(MeasureCallback measure) {
this->measure = measure;
Flex_setMeasureFunc(_node, measure ? Node::static_measure : NULL);
}
void setBaseline(BaselineCallback baseline) {
this->baseline = baseline;
Flex_setBaselineFunc(_node, baseline ? Node::static_baseline : NULL);
}
#define FLEX_GETTER(TYPE, Name, field) WrapType<TYPE>::type get##Name() { return (WrapType<TYPE>::type)Flex_get##Name(_node); }
#define FLEX_SETTER(TYPE, Name, field) void set##Name(WrapType<TYPE>::type Name) { Flex_set##Name(_node, (TYPE)Name); }
#define FLEX_LENGTH_PROPERTY(Name, field) \
Length get##Name() { FlexLength ret = Flex_get##Name(_node); return *(Length*)&ret; } \
void set##Name(Length Name) { Flex_set##Name##_Length(_node, *(FlexLength*)&Name); }
#define FLEX_SETTER_LENGTH_VALUE(Name, field, Type)
#define FLEX_SETTER_LENGTH_TYPE(Name, field, Type)
FLEX_PROPERTYES()
FLEX_EXT_PROPERTYES()
FLEX_RESULT_PROPERTYES()
#undef FLEX_GETTER
#undef FLEX_SETTER
#undef FLEX_LENGTH_PROPERTY
#undef FLEX_SETTER_LENGTH_VALUE
#undef FLEX_SETTER_LENGTH_TYPE
void layout(float constrainedWidth, float constrainedHeight, float scale) {
Flex_layout(_node, constrainedWidth, constrainedHeight, scale);
}
void layout(float constrainedWidth, float constrainedHeight) {
layout(constrainedWidth, constrainedHeight, 1);
}
void print() {
Flex_print(_node, (FlexPrintOptions)0);
}
void add(std::shared_ptr<Node> node) {
children.push_back(node);
Flex_addChild(_node, node->_node);
}
void insert(std::shared_ptr<Node> node, size_t index) {
children.insert(children.begin() + index, node);
Flex_insertChild(_node, node->_node, index);
}
void remove(std::shared_ptr<Node> node) {
for (auto it = children.begin(); it != children.end(); it++) {
if ((*it)->_node == node->_node) {
children.erase(it);
Flex_removeChild(_node, node->_node);
return;
}
}
}
std::shared_ptr<Node> childAt(size_t index) {
return children[index];
}
size_t getChildrenCount() {
return children.size();
}
};
#include "nbind/nbind.h"
NBIND_CLASS(Size) {
construct<>();
construct<float, float>();
getset(getWidth, setWidth);
getset(getHeight, setHeight);
}
NBIND_CLASS(Length) {
construct<>();
construct<float>();
construct<float, Length::LengthType>();
getset(getValue, setValue);
getset(getType, setType);
}
NBIND_CLASS(Node) {
#define FLEX_PROPERTY(type, Name, field) getset(get##Name, set##Name)
#define FLEX_LENGTH_PROPERTY(Name, field) getset(get##Name, set##Name)
#define FLEX_RESULT_PROPERTY(Name, field) getter(getResult##Name)
#define FLEX_SETTER_LENGTH_VALUE(Name, field, Type)
#define FLEX_SETTER_LENGTH_TYPE(Name, field, Type)
FLEX_PROPERTYES()
FLEX_EXT_PROPERTYES()
FLEX_RESULT_PROPERTYES()
#undef FLEX_PROPERTY
#undef FLEX_LENGTH_PROPERTY
#undef FLEX_RESULT_PROPERTY
#undef FLEX_SETTER_LENGTH_VALUE
#undef FLEX_SETTER_LENGTH_TYPE
construct<>();
method(setMeasure);
method(setBaseline);
multimethod(layout, args(float, float));
multimethod(layout, args(float, float, float), "layoutWithScale");
method(add);
method(insert);
method(remove);
method(childAt);
getter(getChildrenCount);
method(print);
}
| 28.263889 | 144 | 0.649959 | [
"vector"
] |
50a5f4d6aa88acd54ec794c4f74d83c572808114 | 1,118 | cpp | C++ | informatics.mccme.ru/p165.cpp | bolatov/contests | 39654ec36e1b7ff62052e324428141a9564fd576 | [
"MIT"
] | null | null | null | informatics.mccme.ru/p165.cpp | bolatov/contests | 39654ec36e1b7ff62052e324428141a9564fd576 | [
"MIT"
] | null | null | null | informatics.mccme.ru/p165.cpp | bolatov/contests | 39654ec36e1b7ff62052e324428141a9564fd576 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int n, m;
cin >> n >> m;
vector<vector<int>> vvi(n, vector<int>());
int p, q;
for (int i = 0; i < m; ++i) {
cin >> p >> q;
p--;
q--;
vvi[p].push_back(q);
vvi[q].push_back(p);
}
vector<int> vc(n, -1);
for (int i = 0; i < n; ++i) {
if (vc[i] > -1) {
continue;
}
queue<int> qu;
qu.push(i);
vc[i] = 1;
while (!qu.empty()) {
int k = qu.front();
qu.pop();
for (int child : vvi[k]) {
if (vc[child] == -1) {
vc[child] = 1 - vc[k];
qu.push(child);
} else if (vc[child] == vc[k]) {
puts("NO");
return 0;
}
}
}
}
printf("YES\n");
for (int i = 0; i < n; ++i) {
if (vc[i] <= 0) {
printf("%d ", i + 1);
}
}
printf("\n");
return 0;
} | 20.327273 | 48 | 0.345259 | [
"vector"
] |
50a655f8208515be6edb54b6f1c20c4e8c8f2dbd | 5,288 | cpp | C++ | src/plugins/robots/builderbot/control_interface/ci_builderbot_rangefinders_sensor.cpp | dcat52/argos3 | 16b1e1e36e33b01aa58154ef4cdda5f341dcd158 | [
"MIT"
] | 211 | 2015-01-27T20:16:40.000Z | 2022-02-25T03:11:13.000Z | src/plugins/robots/builderbot/control_interface/ci_builderbot_rangefinders_sensor.cpp | dcat52/argos3 | 16b1e1e36e33b01aa58154ef4cdda5f341dcd158 | [
"MIT"
] | 154 | 2015-02-09T20:32:38.000Z | 2022-03-30T21:35:24.000Z | src/plugins/robots/builderbot/control_interface/ci_builderbot_rangefinders_sensor.cpp | dcat52/argos3 | 16b1e1e36e33b01aa58154ef4cdda5f341dcd158 | [
"MIT"
] | 128 | 2015-02-09T10:21:49.000Z | 2022-03-31T22:24:51.000Z | /**
* @file <argos3/plugins/robots/builderbot/control_interface/ci_builderbot_rangefinders_sensor.cpp>
*
* @author Michael Allwright <allsey87@gmail.com>
*/
#include "ci_builderbot_rangefinders_sensor.h"
#ifdef ARGOS_WITH_LUA
#include <argos3/core/wrappers/lua/lua_utility.h>
#endif
namespace argos {
/****************************************/
/****************************************/
const CCI_BuilderBotRangefindersSensor::SInterface::TVector& CCI_BuilderBotRangefindersSensor::GetInterfaces() const {
return m_vecInterfaces;
}
/****************************************/
/****************************************/
#ifdef ARGOS_WITH_LUA
void CCI_BuilderBotRangefindersSensor::CreateLuaState(lua_State* pt_lua_state) {
CLuaUtility::OpenRobotStateTable(pt_lua_state, "rangefinders");
for(SInterface* ps_interface : m_vecInterfaces) {
CLuaUtility::StartTable(pt_lua_state, ps_interface->Label);
CLuaUtility::AddToTable(pt_lua_state, "proximity", ps_interface->Proximity);
CLuaUtility::AddToTable(pt_lua_state, "illuminance", ps_interface->Illuminance);
CLuaUtility::StartTable(pt_lua_state, "transform");
CLuaUtility::AddToTable(pt_lua_state, "position", ps_interface->PositionOffset);
CLuaUtility::AddToTable(pt_lua_state, "orientation", ps_interface->OrientationOffset);
CLuaUtility::AddToTable(pt_lua_state, "anchor", ps_interface->Anchor);
CLuaUtility::EndTable(pt_lua_state);
CLuaUtility::EndTable(pt_lua_state);
}
CLuaUtility::CloseRobotStateTable(pt_lua_state);
}
#endif
/****************************************/
/****************************************/
#ifdef ARGOS_WITH_LUA
void CCI_BuilderBotRangefindersSensor::ReadingsToLuaState(lua_State* pt_lua_state) {
lua_getfield(pt_lua_state, -1, "rangefinders");
for(SInterface* ps_interface : m_vecInterfaces) {
lua_getfield(pt_lua_state, -1, ps_interface->Label.c_str());
CLuaUtility::AddToTable(pt_lua_state, "proximity", ps_interface->Proximity);
CLuaUtility::AddToTable(pt_lua_state, "illuminance", ps_interface->Illuminance);
lua_pop(pt_lua_state, 1);
}
lua_pop(pt_lua_state, 1);
}
#endif
/****************************************/
/****************************************/
const std::map<std::string, std::tuple<std::string, CVector3, CQuaternion> >
CCI_BuilderBotRangefindersSensor::m_mapSensorConfig = {
std::make_pair("7", std::make_tuple("origin", CVector3( 0.0440, -0.0175, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, 1.0000, 0)))),
std::make_pair("8", std::make_tuple("origin", CVector3( 0.0323, -0.0522, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 0.7071, 0.7071, 0)))),
std::make_pair("9", std::make_tuple("origin", CVector3(-0.0025, -0.0640, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 1.0000, 0.0000, 0)))),
std::make_pair("10", std::make_tuple("origin", CVector3(-0.0375, -0.0640, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 1.0000, 0.0000, 0)))),
std::make_pair("11", std::make_tuple("origin", CVector3(-0.0722, -0.0523, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 0.7071, -0.7071, 0)))),
std::make_pair("12", std::make_tuple("origin", CVector3(-0.0840, -0.0175, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, -1.0000, 0)))),
std::make_pair("1", std::make_tuple("origin", CVector3(-0.0840, 0.0175, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, -1.0000, 0)))),
std::make_pair("2", std::make_tuple("origin", CVector3(-0.0722, 0.0523, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3(-0.7071, -0.7071, 0)))),
std::make_pair("3", std::make_tuple("origin", CVector3(-0.0375, 0.0640, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3(-1.0000, 0.0000, 0)))),
std::make_pair("4", std::make_tuple("origin", CVector3(-0.0025, 0.0640, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3(-1.0000, 0.0000, 0)))),
std::make_pair("5", std::make_tuple("origin", CVector3( 0.0323, 0.0522, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3(-0.7071, 0.7071, 0)))),
std::make_pair("6", std::make_tuple("origin", CVector3( 0.0440, 0.0175, 0.0515), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, 1.0000, 0)))),
std::make_pair("left", std::make_tuple("end_effector", CVector3(-0.0343, 0.016, -0.0288), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, 1.0000, 0)))),
std::make_pair("right", std::make_tuple("end_effector", CVector3(-0.0343, -0.016, -0.0288), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, 1.0000, 0)))),
std::make_pair("underneath", std::make_tuple("end_effector", CVector3(-0.0025, 0.000, 0.0010), CQuaternion(1.0 * CRadians::PI, CVector3( 0.0000, 1.0000, 0)))),
std::make_pair("front", std::make_tuple("end_effector", CVector3( 0.0244, 0.000, 0.0086), CQuaternion(0.5 * CRadians::PI, CVector3( 0.0000, 1.0000, 0)))),
};
/****************************************/
/****************************************/
}
| 61.488372 | 171 | 0.600227 | [
"transform"
] |
50ad0b30406e244694035bfeec30566252cf636e | 13,981 | cpp | C++ | modules/tachyon/Viewer.cpp | mathstuf/ospray | 5c34884317b5bb84346e4e1e2e2bf8c7f50d307c | [
"Apache-2.0"
] | 1 | 2016-05-24T19:27:01.000Z | 2016-05-24T19:27:01.000Z | modules/tachyon/Viewer.cpp | mathstuf/ospray | 5c34884317b5bb84346e4e1e2e2bf8c7f50d307c | [
"Apache-2.0"
] | null | null | null | modules/tachyon/Viewer.cpp | mathstuf/ospray | 5c34884317b5bb84346e4e1e2e2bf8c7f50d307c | [
"Apache-2.0"
] | null | null | null | // ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#undef NDEBUG
// viewer widget
#include "apps/common/widgets/glut3D.h"
// ospray, for rendering
#include "ospray/ospray.h"
// tachyon module
#include "Model.h"
namespace ospray {
namespace tachyon {
using std::cout;
using std::endl;
float lightScale = 1.f;
const char *renderType = "tachyon";
// const char *renderType = "ao16";
float defaultRadius = .1f;
struct TimeStep {
std::string modelName;
tachyon::Model tm; // tachyon model
OSPModel om; // ospray model
TimeStep(const std::string &modelName) : modelName(modelName), om(NULL) {};
};
std::vector<TimeStep *> timeStep;
int timeStepID = 0;
bool doShadows = true;
void error(const std::string &vol)
{
if (vol != "") {
cout << "=======================================================" << endl;
cout << "ospray::tachView fatal error : " << vol << endl;
cout << "=======================================================" << endl;
}
cout << endl;
cout << "Proper usage: " << endl;
cout << " ./ospTachyon <inputfile.tach> <options>" << std::endl;
cout << "options:" << endl;
cout << " <none>" << endl;
cout << endl;
exit(1);
}
OSPModel specifyModel(tachyon::Model &tm)
{
OSPModel ospModel = ospNewModel();
if (tm.numSpheres()) {
OSPData sphereData = ospNewData(tm.numSpheres()*sizeof(Sphere)/sizeof(float),
OSP_FLOAT,tm.getSpheresPtr());
ospCommit(sphereData);
OSPGeometry sphereGeom = ospNewGeometry("spheres");
ospSetData(sphereGeom,"spheres",sphereData);
ospSet1i(sphereGeom,"bytes_per_sphere",sizeof(Sphere));
ospSet1i(sphereGeom,"offset_materialID",0*sizeof(float));
ospSet1i(sphereGeom,"offset_center",1*sizeof(float));
ospSet1i(sphereGeom,"offset_radius",4*sizeof(float));
ospCommit(sphereGeom);
ospAddGeometry(ospModel,sphereGeom);
}
if (tm.numCylinders()) {
OSPData cylinderData = ospNewData(tm.numCylinders()*sizeof(Cylinder)/sizeof(float),
OSP_FLOAT,tm.getCylindersPtr());
ospCommit(cylinderData);
OSPGeometry cylinderGeom = ospNewGeometry("cylinders");
ospSetData(cylinderGeom,"cylinders",cylinderData);
ospSet1i(cylinderGeom,"bytes_per_cylinder",sizeof(Cylinder));
ospSet1i(cylinderGeom,"offset_materialID",0*sizeof(float));
ospSet1i(cylinderGeom,"offset_v0",1*sizeof(float));
ospSet1i(cylinderGeom,"offset_v1",4*sizeof(float));
ospSet1i(cylinderGeom,"offset_radius",7*sizeof(float));
ospCommit(cylinderGeom);
ospAddGeometry(ospModel,cylinderGeom);
}
cout << "#osp:tachyon: creating " << tm.numVertexArrays() << " vertex arrays" << endl;
long numTriangles = 0;
for (int vaID=0;vaID<tm.numVertexArrays();vaID++) {
const VertexArray *va = tm.getVertexArray(vaID);
// if (va != tm.getSTriVA())
// continue;
Assert(va);
OSPGeometry geom = ospNewGeometry("trianglemesh");
numTriangles += va->triangle.size();
if (va->triangle.size()) {
OSPData data = ospNewData(va->triangle.size(),OSP_INT3,&va->triangle[0]);
ospCommit(data);
ospSetData(geom,"triangle",data);
}
if (va->coord.size()) {
OSPData data = ospNewData(va->coord.size(),OSP_FLOAT3A,&va->coord[0]);
ospCommit(data);
ospSetData(geom,"vertex",data);
}
if (va->normal.size()) {
OSPData data = ospNewData(va->normal.size(),OSP_FLOAT3A,&va->normal[0]);
ospCommit(data);
ospSetData(geom,"vertex.normal",data);
}
if (va->color.size()) {
OSPData data = ospNewData(va->color.size(),OSP_FLOAT3A,&va->color[0]);
ospCommit(data);
ospSetData(geom,"vertex.color",data);
}
if (va->perTriTextureID.size()) {
OSPData data = ospNewData(va->perTriTextureID.size(),OSP_UINT,
&va->perTriTextureID[0]);
ospCommit(data);
ospSetData(geom,"prim.materialID",data);
} else {
ospSet1i(geom,"geom.materialID",va->textureID);
}
ospCommit(geom);
ospAddGeometry(ospModel,geom);
}
cout << "#osp:tachyon: specifying " << tm.numTextures() << " materials..." << endl;
{
OSPData data = ospNewData(tm.numTextures()*sizeof(Texture),
OSP_UCHAR,tm.getTexturesPtr());
ospCommit(data);
ospSetData(ospModel,"textureArray",data);
}
cout << "#osp:tachyon: specifying " << tm.numPointLights()
<< " point lights..." << endl;
if (tm.numPointLights() > 0)
{
OSPData data
= ospNewData(tm.numPointLights()*sizeof(PointLight),
OSP_UCHAR,tm.getPointLightsPtr());
ospCommit(data);
ospSetData(ospModel,"pointLights",data);
}
cout << "#osp:tachyon: specifying " << tm.numDirLights()
<< " dir lights..." << endl;
if (tm.numDirLights() > 0)
{
OSPData data
= ospNewData(tm.numDirLights()*sizeof(DirLight),
OSP_UCHAR,tm.getDirLightsPtr());
ospCommit(data);
ospSetData(ospModel,"dirLights",data);
}
std::cout << "=======================================" << std::endl;
std::cout << "Tachyon Renderer: Done specifying model" << std::endl;
std::cout << "num spheres: " << tm.numSpheres() << std::endl;
std::cout << "num cylinders: " << tm.numCylinders() << std::endl;
std::cout << "num triangles: " << numTriangles << std::endl;
std::cout << "=======================================" << std::endl;
ospCommit(ospModel);
return ospModel;
}
using ospray::glut3D::Glut3DWidget;
//! volume viewer widget.
/*! \internal Note that all handling of camera is almost exactly
similar to the code in msgView; might make sense to move that into
a common class! */
struct TACHViewer : public Glut3DWidget {
/*! construct volume from file name and dimensions \see volview_notes_on_volume_interface */
TACHViewer(OSPModel model, const std::string &modelName)
: Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE),
fb(NULL), renderer(NULL), model(model), modelName(modelName)
{
camera = ospNewCamera("perspective");
Assert2(camera,"could not create camera");
ospSet3f(camera,"pos",-1,1,-1);
ospSet3f(camera,"dir",+1,-1,+1);
ospCommit(camera);
ospCommit(camera);
renderer = ospNewRenderer(renderType);
ospSet1i(renderer, "aoSamples", 1);
ospSet1i(renderer, "shadowsEnabled", 1);
Assert2(renderer,"could not create renderer");
ospSetObject(renderer,"model",model);
ospSetObject(renderer,"camera",camera);
ospSet1i(renderer,"do_shadows",doShadows);
ospCommit(renderer);
}
void keypress(char key, const vec2i &where) override
{
switch (key) {
case 'X':
if (viewPort.up == vec3f(1,0,0) || viewPort.up == vec3f(-1.f,0,0))
viewPort.up = - viewPort.up;
else
viewPort.up = vec3f(1,0,0);
viewPort.modified = true;
break;
case 'Y':
if (viewPort.up == vec3f(0,1,0) || viewPort.up == vec3f(0,-1.f,0))
viewPort.up = - viewPort.up;
else
viewPort.up = vec3f(0,1,0);
viewPort.modified = true;
break;
case 'Z':
if (viewPort.up == vec3f(0,0,1) || viewPort.up == vec3f(0,0,-1.f))
viewPort.up = - viewPort.up;
else
viewPort.up = vec3f(0,0,1);
viewPort.modified = true;
break;
case 'S':
doShadows = !doShadows;
cout << "Switching shadows " << (doShadows?"ON":"OFF") << endl;
ospSet1i(renderer,"do_shadows",doShadows);
ospCommit(renderer);
break;
case 'L':
lightScale *= 1.5f;
ospSet1f(renderer,"lightScale",lightScale);
PRINT(lightScale);
PRINT(renderer);
ospCommit(renderer);
break;
case 'l':
lightScale /= 1.5f;
PRINT(lightScale);
PRINT(renderer);
ospSet1f(renderer,"lightScale",lightScale);
ospCommit(renderer);
break;
case '<':
setTimeStep((timeStepID+timeStep.size()-1)%timeStep.size());
break;
case '>':
setTimeStep((timeStepID+1)%timeStep.size());
break;
default:
Glut3DWidget::keypress(key,where);
}
}
void setTimeStep(size_t newTSID)
{
timeStepID = newTSID;
modelName = timeStep[timeStepID]->modelName;
cout << "#osp:tachyon: switching to time step " << timeStepID
<< " (" << modelName << ")" << endl;
model = timeStep[timeStepID]->om;
ospSetObject(renderer,"model",model);
ospCommit(renderer);
}
virtual void reshape(const ospray::vec2i &_newSize)
{
Glut3DWidget::reshape(_newSize);
if (fb) ospFreeFrameBuffer(fb);
const auto &newSize = reinterpret_cast<const osp::vec2i&>(_newSize);
fb = ospNewFrameBuffer(newSize, OSP_FB_SRGBA, OSP_FB_COLOR|OSP_FB_ACCUM);
ospSetf(camera,"aspect",viewPort.aspect);
ospCommit(camera);
}
virtual void display()
{
if (!fb || !renderer) return;
if (viewPort.modified) {
Assert2(camera,"ospray camera is null");
// PRINT(viewPort);
auto from = reinterpret_cast<osp::vec3f&>(viewPort.from);
auto dir = viewPort.at-viewPort.from;
auto up = reinterpret_cast<osp::vec3f&>(viewPort.up);
ospSetVec3f(camera,"pos",from);
ospSetVec3f(camera,"dir",reinterpret_cast<osp::vec3f&>(dir));
ospSetVec3f(camera,"up",up);
ospSetf(camera,"aspect",viewPort.aspect);
ospCommit(camera);
viewPort.modified = false;
ospFrameBufferClear(fb,OSP_FB_COLOR|OSP_FB_ACCUM);
}
fps.startRender();
ospRenderFrame(fb,renderer,OSP_FB_COLOR|OSP_FB_ACCUM);
fps.doneRender();
ucharFB = (unsigned int *)ospMapFrameBuffer(fb);
frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR;
Glut3DWidget::display();
ospUnmapFrameBuffer(ucharFB,fb);
#if 1
char title[10000];
sprintf(title,"ospray Tachyon viewer (%s) [%f fps]",
modelName.c_str(),fps.getFPS());
setTitle(title);
#endif
forceRedraw();
}
OSPModel model;
OSPFrameBuffer fb;
OSPRenderer renderer;
OSPCamera camera;
ospray::glut3D::FPSCounter fps;
std::string modelName;
};
void ospTACHMain(int &ac, const char **&av)
{
ospLoadModule("tachyon");
for (int i=1;i<ac;i++) {
std::string arg = av[i];
if (arg[0] != '-') {
timeStep.push_back(new TimeStep(arg));
} else
throw std::runtime_error("unknown parameter "+arg);
}
if (timeStep.empty())
error("no input geometry specifies!?");
std::vector<OSPModel> modelHandle;
for (int i=0;i<timeStep.size();i++) {
TimeStep *ts = timeStep[i];
importFile(ts->tm,ts->modelName);
if (ts->tm.empty())
error(ts->modelName+": no input geometry specified!?");
ts->om = specifyModel(ts->tm);
}
// -------------------------------------------------------
// parse and set up input(s)
// -------------------------------------------------------
// -------------------------------------------------------
// create viewer window
// -------------------------------------------------------
TACHViewer window(timeStep[0]->om,timeStep[0]->modelName);
window.create("ospTACH: OSPRay Tachyon-model viewer");
printf("Viewer created. Press 'Q' to quit.\n");
window.setWorldBounds(timeStep[0]->tm.getBounds());
ospray::tachyon::Camera *camera = timeStep[0]->tm.getCamera();
if (camera) {
window.viewPort.from = camera->center;
window.viewPort.at = camera->center+camera->viewDir;
window.viewPort.up = camera->upDir;
window.computeFrame();
}
ospray::glut3D::runGLUT();
}
}
}
int main(int ac, const char **av)
{
ospInit(&ac,av);
ospray::glut3D::initGLUT(&ac,av);
ospray::tachyon::ospTACHMain(ac,av);
}
| 35.665816 | 98 | 0.536299 | [
"geometry",
"vector",
"model"
] |
2708893117f83711d3638194ddd0b2e17f283a0d | 1,140 | cpp | C++ | src/sim/src/plugins/model/sensors/IMU.cpp | jiangchenzhu/crates_zhejiang | 711c9fafbdc775114345ab0ca389656db9d20df7 | [
"BSD-3-Clause"
] | 1 | 2016-03-29T00:15:47.000Z | 2016-03-29T00:15:47.000Z | src/sim/src/plugins/model/sensors/IMU.cpp | jiangchenzhu/crates_zhejiang | 711c9fafbdc775114345ab0ca389656db9d20df7 | [
"BSD-3-Clause"
] | null | null | null | src/sim/src/plugins/model/sensors/IMU.cpp | jiangchenzhu/crates_zhejiang | 711c9fafbdc775114345ab0ca389656db9d20df7 | [
"BSD-3-Clause"
] | null | null | null | #include "IMU.h"
using namespace gazebo;
// Constructor
IMU::IMU() {}
// All sensors must be configured using the current model information and the SDF
bool IMU::Configure(physics::LinkPtr link, sdf::ElementPtr root)
{
// Backup the link
linkPtr = link;
// Initialise the noise distribution
nLinAcc = NoiseFactory::Create(root->GetElement("errors")->GetElement("linacc"));
nAngVel = NoiseFactory::Create(root->GetElement("errors")->GetElement("angvel"));
// Succes!
return true;
}
// All sensors must be resettable
void IMU::Reset()
{
// Initialise the noise distribution
nLinAcc->Reset();
nAngVel->Reset();
}
// Get the current altitude
bool IMU::GetMeasurement(double t, hal_sensor_imu::Data& msg)
{
// Get the quantities we want
math::Vector3 linAcc = linkPtr->GetRelativeLinearAccel();
math::Vector3 angVel = linkPtr->GetRelativeAngularVel();
// Perturb acceleration
linAcc += nLinAcc->DrawVector(t);
angVel += nAngVel->DrawVector(t);
// Package
msg.t = t;
msg.du = linAcc.x;
msg.dv = linAcc.y;
msg.dw = linAcc.z;
msg.p = angVel.x;
msg.q = angVel.y;
msg.r = angVel.z;
// Success!
return true;
}
| 21.509434 | 82 | 0.699123 | [
"model"
] |
2709a0f2af98ef92baaaee47d335b442aebffb4f | 14,756 | cc | C++ | src/mytest/parseBody_test.cc | swaroop0707/TinyWeb | 79d20f2bb858581cc5a0ea229bba3a54e5d1bd3e | [
"MIT"
] | 352 | 2018-02-07T08:24:43.000Z | 2022-03-31T12:35:17.000Z | src/mytest/parseBody_test.cc | zhouq3405/TinyWeb | 79d20f2bb858581cc5a0ea229bba3a54e5d1bd3e | [
"MIT"
] | 6 | 2018-02-08T11:52:12.000Z | 2022-01-20T03:37:41.000Z | src/mytest/parseBody_test.cc | zhouq3405/TinyWeb | 79d20f2bb858581cc5a0ea229bba3a54e5d1bd3e | [
"MIT"
] | 75 | 2018-02-07T08:24:42.000Z | 2021-10-03T08:20:24.000Z | /*
*Author:GeneralSandman
*Code:https://github.com/GeneralSandman/TinyWeb
*E-mail:generalsandman@163.com
*Web:www.dissigil.cn
*/
/*---XXX---
*
****************************************
*
*/
#include <tiny_http/http_parser.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef struct testBody {
const char* str;
bool valid;
const char* body;
} testBody;
testBody bodys[] = {
// 0
{
.str = "GET /index.html HTTP/1.0\r\n"
"\r\n",
.valid = true,
.body = "",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"\r\n"
"helloworld",
.valid = true,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/0.9\r\n"
"\r\n"
"helloworld",
.valid = true,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: 10\r\n"
"\r\n"
"helloworld",
.valid = true,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: 20\r\n"
"\r\n"
"helloworld",
.valid = true,
.body = "helloworld",
},
// 5
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: 5\r\n"
"\r\n"
"helloworld",
.valid = true,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: 10.\r\n"
"\r\n"
"helloworld",
.valid = false,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: 1-0\r\n"
"\r\n"
"helloworld",
.valid = false,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: bbb\r\n"
"\r\n"
"helloworld",
.valid = false,
.body = "helloworld",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: -10\r\n"
"\r\n"
"helloworld",
.valid = false,
.body = "helloworld",
},
// 10
{
.str = "GET /index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk78\r\n"
"1C\r\n"
"and this is the second one??\r\n"
"2\r\n"
"bo\r\n"
"2\r\n"
"dy\r\n"
"0\r\n"
"\r\n"
"2\r\n"
"OK\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "This is the data in the first chunk78\r\n"
"and this is the second one??"
"bo"
"dy",
},
{
.str = "GET /index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk78\r\n"
"1C\r\n"
"and this is the second one??\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "This is the data in the first chunk78"
"and this is the second one??",
},
{
.str = "GET /index.html HTTP/1.1\r\n"
"Transfer-Encoding: chunke\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk78\r\n"
"1C\r\n"
"and this is the second one??\r\n"
"0\r\n"
"\r\n",
.valid = false,
.body = "",
},
{
.str = "GET /index.html HTTP/1.1\r\n"
"Transfer-Encoding: -----\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk78\r\n"
"1C\r\n"
"and this is the second one??\r\n"
"0\r\n"
"\r\n",
.valid = false,
.body = "",
},
{
.str = "GET /index.html HTTP/1.1\r\n"
"Transfer-Encoding: chunked\r\n"
"Content-Length: 12345\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk78\r\n"
"1C\r\n"
"and this is the second one??\r\n"
"0\r\n"
"\r\n",
.valid = false,
.body = "",
},
// 15
{
.str = "GET /index.html HTTP/1.0\r\n"
"Content-Length: 10\r\n"
"Host: 127.0.0.1:9090\r\n"
"User-Agent: curl/7.54.0\r\n"
"Accept: */*\r\n"
"\r\n"
"helloworld",
.valid = true,
.body = "",
},
{
.str = "GET /index.html HTTP/1.1\r\n"
"Host: 127.0.0.1:9090\r\n"
"User-Agent: curl/7.54.0\r\n"
"Accept: */*\r\n"
"\r\n",
.valid = true,
.body = "",
},
{
.str = "GET /index.html HTTP/1.1\r\n"
"Host: 127.0.0.1:9090\r\n"
"User-Agent: curl/7.54.0\r\n"
"Accept: */*\r\n"
"\r\n",
.valid = true,
.body = "",
},
{
.str = "GET http://127.0.0.1:9999/index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk..\r\n"
"1C\r\n"
"and this is the second one..\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "This is the data in the first chunk.."
"and this is the second one..",
},
{
.str = "GET http://127.0.0.1:9999/index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk\r\n"
"\r\n"
"1C\r\n"
"and this is the second one\r\n"
"\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "",
},
// 20
{
.str = "GET http://127.0.0.1:9999/index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk\r\n"
"\r\n"
"1C\r\n"
"and this is the second one\r\n"
"\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "",
},
{
.str = "GET http://127.0.0.1:9999/index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk\r\n"
"\r\n"
"1C\r\n"
"and this is the second one\r\n"
"\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "",
},
{
.str = "GET http://127.0.0.1:9999/index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"2\r\n"
"OK\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "",
},
{
.str = "GET http://127.0.0.1:9999/index.html HTTP/1.0\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"25\r\n"
"This is the data in the first chunk78\r\n"
"1C\r\n"
"and this is the second one??\r\n"
"2\r\n"
"bo\r\n"
"2\r\n"
"dy\r\n"
"0\r\n"
"\r\n"
"2\r\n"
"OK\r\n"
"0\r\n"
"\r\n",
.valid = true,
.body = "",
},
};
testBody bodys_post_request[] = {
{
.str = "POST /test/dynamic_post.php HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 243\r\n"
"Content-Type: multipart/form-data;boundary=----WebKitFormBoundaryk6KRh71N5xaURy12\r\n"
"\r\n"
"------WebKitFormBoundaryk6KRh71N5xaURy12\r\n"
"Content-Disposition: form-data;name =\"name\"\r\n"
"\r\n"
"7a68656e68756c69"
"------WebKitFormBoundaryk6KRh71N5xaURy12\r\n"
"Content-Disposition: form-data;name =\"email\"\r\n"
"\r\n"
"7a68656e68756c69"
"------WebKitFormBoundaryk6KRh71N5xaURy12--\r\n",
.valid = true,
.body = "",
},
{
.str = "POST /test/dynamic_post.php HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 243\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"\r\n"
.valid
= true,
.body = "",
},
};
testBody bodys_fcgi_response[] = {
{
.str = "X-Powered-By: PHP/5.6.39\r\n"
"Content-type: text/html; charset=UTF-8\r\n"
"\r\n"
"{\"name\":\"zhenhuli\",\"age\":\"99\"}",
.valid = true,
.body = "",
},
{
.str = "X-Powered-By: PHP/5.6.39\r\n"
"Content-type: text/html; charset=UTF-8\r\n"
"\r\n"
"{\"name\":\"zhenhuli\",\"age\":\"99\"}",
.valid = true,
.body = "",
},
{
.str = "X-Powered-By: PHP/5.6.39\r\n"
"Content-type: text/html; charset=UTF-8\r\n"
"\r\n"
"{\"name\":\"zhenhuli\",\"age\":\"99\"}",
.valid = true,
.body = "",
},
{
.str = "X-Powered-By: PHP/5.6.39\r\n"
"Content-type: text/html; charset=UTF-8\r\n"
"\r\n"
"{\"name\":\"zhenhuli\",\"age\":\"99\"}",
.valid = true,
.body = "",
},
{
.str = "X-Powered-By: PHP/5.6.39\r\n"
"Content-type: text/html; charset=UTF-8\r\n"
"\r\n"
"{\"name\":\"zhenhuli\",\"age\":\"99\"}",
.valid = true,
.body = "",
},
};
void testPraseBody()
{
HttpParserSettings settings;
vector<int> notPass;
int alltest = 0;
int passtest = 0;
int len = sizeof(bodys) / sizeof(bodys[0]);
for (int i = 10; i < 20; i++) {
std::cout << i << ")" << std::endl;
alltest++;
int begin = 0;
HttpParser parser(&settings);
parser.setType(HTTP_TYPE_REQUEST);
HttpRequest* result = new HttpRequest;
int tmp = parser.execute(bodys[i].str,
begin,
strlen(bodys[i].str),
result);
bool res = (tmp == -1) ? false : true;
if (res == bodys[i].valid) {
if (res) {
bool sameBody = true;
if (sameBody) {
passtest++;
} else {
notPass.push_back(i);
}
} else {
passtest++;
}
} else {
notPass.push_back(i);
}
delete result;
}
std::cout << "[Parse Http Body Test] pass/all = " << passtest << "/" << alltest << std::endl;
if (!notPass.empty()) {
cout << "not pass body index:\t";
for (auto t : notPass)
std::cout << t << " ";
std::cout << std::endl;
}
}
void testPraseBody_PostRequest()
{
HttpParserSettings settings;
vector<int> notPass;
int alltest = 0;
int passtest = 0;
int len = sizeof(bodys_post_request) / sizeof(bodys_post_request[0]);
for (int i = 0; i < len; i++) {
std::cout << i << ")" << std::endl;
alltest++;
int begin = 0;
HttpParser parser(&settings);
parser.setType(HTTP_TYPE_REQUEST);
HttpRequest* result = new HttpRequest;
int tmp = parser.execute(bodys_post_request[i].str,
begin,
strlen(bodys_post_request[i].str),
result);
bool res = (tmp == -1) ? false : true;
if (res == bodys_post_request[i].valid) {
if (res) {
bool sameBody = true;
if (sameBody) {
passtest++;
} else {
notPass.push_back(i);
}
} else {
passtest++;
}
} else {
notPass.push_back(i);
}
delete result;
}
std::cout << "[Parse Http Post-Request Body Test] pass/all = " << passtest << "/" << alltest << std::endl;
if (!notPass.empty()) {
cout << "not pass body index:\t";
for (auto t : notPass)
std::cout << t << " ";
std::cout << std::endl;
}
}
void testPraseBody_FcgiResponse()
{
HttpParserSettings settings;
vector<int> notPass;
int alltest = 0;
int passtest = 0;
int len = sizeof(bodys_fcgi_response) / sizeof(bodys_fcgi_response[0]);
for (int i = 0; i < len; i++) {
std::cout << i << ")" << std::endl;
alltest++;
int begin = 0;
HttpParser parser(&settings);
parser.setType(HTTP_TYPE_FCGI_RESPONSE);
HttpRequest* result = new HttpRequest;
int tmp = parser.execute(bodys_fcgi_response[i].str,
begin,
strlen(bodys_fcgi_response[i].str),
result);
bool res = (tmp == -1) ? false : true;
if (res == bodys_fcgi_response[i].valid) {
if (res) {
bool sameBody = true;
if (sameBody) {
passtest++;
} else {
notPass.push_back(i);
}
} else {
passtest++;
}
} else {
notPass.push_back(i);
}
delete result;
}
std::cout << "[Parse Fcgi-Response Body Test] pass/all = " << passtest << "/" << alltest << std::endl;
if (!notPass.empty()) {
cout << "not pass body index:\t";
for (auto t : notPass)
std::cout << t << " ";
std::cout << std::endl;
}
}
int main()
{
headerMeaningInit();
// testPraseBody();
testPraseBody_PostRequest();
// testPraseBody_FcgiResponse();
return 0;
}
| 25.267123 | 110 | 0.399634 | [
"vector"
] |
2712d89bd9b247f52ca03cb9b89f67293e3d7b85 | 1,838 | cpp | C++ | Atcoder/Beginner172/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Atcoder/Beginner172/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Atcoder/Beginner172/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | // Optimise
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
const int NAX = 2e5 + 5, MOD = 1000000007;
class Solution
{
private:
public:
Solution() {}
~Solution() {}
void solveCase()
{
int n, m, k;
cin >> n >> m >> k;
vector<ll> a(n), b(m);
for (size_t i = 0; i < n; i++)
{
int x;
cin >> x;
if (i > 0)
a[i] = a[i - 1];
a[i] += x;
}
for (size_t i = 0; i < m; i++)
{
int x;
cin >> x;
if (i > 0)
b[i] = b[i - 1];
b[i] += x;
}
ll ret = 0;
for (ll i = 0; i < n; ++i)
{
if (k < a[i])
break;
ll extra = k - a[i];
ll it = upper_bound(all(b), extra) - b.begin();
ret = max(ret, it + i + 1);
}
a.swap(b);
swap(n, m);
for (ll i = 0; i < n; ++i)
{
if (k < a[i])
break;
ll extra = k - a[i];
ll it = upper_bound(all(b), extra) - b.begin();
ret = max(ret, it + i + 1);
}
cout << ret << '\n';
}
};
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
Solution mySolver;
for (int i = 1; i <= t; ++i)
{
mySolver.solveCase();
#ifdef LOCAL
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
}
| 20.886364 | 131 | 0.409684 | [
"vector"
] |
271971396c28dddb40c897a09b2e37804a038bc3 | 271 | hpp | C++ | Injector/pch.hpp | wilricknl/ACE | 53737d758827b609909844eed1bc964a734ce234 | [
"MIT"
] | null | null | null | Injector/pch.hpp | wilricknl/ACE | 53737d758827b609909844eed1bc964a734ce234 | [
"MIT"
] | null | null | null | Injector/pch.hpp | wilricknl/ACE | 53737d758827b609909844eed1bc964a734ce234 | [
"MIT"
] | null | null | null | #pragma once
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <Windows.h>
#include <TlHelp32.h>
| 19.357143 | 45 | 0.767528 | [
"vector"
] |
271af36f82095508d59ff830e3533c7f5e75ab85 | 1,609 | cc | C++ | src/developer/debug/unwinder/unwind_local.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/developer/debug/unwinder/unwind_local.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | src/developer/debug/unwinder/unwind_local.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/debug/unwinder/unwind_local.h"
#include <link.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <memory>
#include <vector>
#include "src/developer/debug/unwinder/memory.h"
#include "src/developer/debug/unwinder/third_party/libunwindstack/context.h"
namespace unwinder {
std::vector<Frame> UnwindLocal() {
struct Data {
std::vector<uint64_t> modules;
BoundedLocalMemory memory;
} data;
// Initialize the memory with proper start/end boundaries.
using CallbackType = int (*)(dl_phdr_info * info, size_t size, void* modules);
CallbackType dl_iterate_phdr_callback = [](dl_phdr_info* info, size_t, void* data_v) {
auto data = reinterpret_cast<Data*>(data_v);
data->modules.push_back(info->dlpi_addr);
for (size_t i = 0; i < info->dlpi_phnum; i++) {
const Elf64_Phdr& phdr = info->dlpi_phdr[i];
if (phdr.p_type == PT_LOAD) {
data->memory.AddRegion(info->dlpi_addr + phdr.p_vaddr, phdr.p_memsz);
}
}
return 0;
};
dl_iterate_phdr(dl_iterate_phdr_callback, &data);
std::map<uint64_t, Memory*> module_map;
for (auto base : data.modules) {
module_map.emplace(base, &data.memory);
}
LocalMemory stack;
auto frames = Unwind(&stack, module_map, GetContext());
if (frames.empty()) {
return {};
}
// Drop the first frame.
return {frames.begin() + 1, frames.end()};
}
} // namespace unwinder
| 27.741379 | 88 | 0.692356 | [
"vector"
] |
272095af36ae0736adfe7535fc78c342ec993216 | 1,467 | cpp | C++ | Source/Azura/RenderSystem/Src/Vulkan/Windows/VkWin32Platform.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 12 | 2019-01-08T23:10:37.000Z | 2021-06-04T09:48:42.000Z | Source/Azura/RenderSystem/Src/Vulkan/Windows/VkWin32Platform.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 38 | 2017-04-05T00:27:24.000Z | 2018-12-25T08:34:04.000Z | Source/Azura/RenderSystem/Src/Vulkan/Windows/VkWin32Platform.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 4 | 2019-03-27T10:07:32.000Z | 2021-07-15T03:22:27.000Z | #include "Vulkan/VkPlatform.h"
#include <Windows.h>
#include <vulkan/vulkan_win32.h>
#include "Vulkan/VkMacros.h"
namespace Azura {
namespace Vulkan {
VkSurfaceKHR VkPlatform::CreateSurface(const void* windowHandle, VkInstance instance, const Log& log_VulkanRenderSystem) {
VkWin32SurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
createInfo.hwnd = *reinterpret_cast<const HWND*>(windowHandle);
createInfo.hinstance = GetModuleHandle(nullptr);
const auto CreateWin32SurfaceKHR =
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
reinterpret_cast<PFN_vkCreateWin32SurfaceKHR>(vkGetInstanceProcAddr(instance, "vkCreateWin32SurfaceKHR"));
FAIL_IF(log_VulkanRenderSystem, CreateWin32SurfaceKHR == nullptr, "Cannot find PFN_vkCreateWin32SurfaceKHR");
VkSurfaceKHR surface;
VERIFY_VK_OP(log_VulkanRenderSystem, CreateWin32SurfaceKHR(instance, &createInfo, nullptr, &surface), "Failed to create window surface");
return surface;
}
void VkPlatform::GetInstanceExtensions(Containers::Vector<const char*>& extensions) {
extensions.PushBack(VK_KHR_SURFACE);
extensions.PushBack("VK_KHR_win32_surface");
#ifdef BUILD_DEBUG
extensions.PushBack(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
#endif
}
} // namespace Vulkan
} // namespace Azura
| 37.615385 | 140 | 0.76619 | [
"vector"
] |
27217251946098d18feb219086d5da986f82035f | 1,874 | cpp | C++ | Algorithms/Warmup/Plus_Minus.cpp | whitehatty/HackerRank | 6b0f5716ccd69cdf5857ba2d00740eef2b6520af | [
"MIT"
] | null | null | null | Algorithms/Warmup/Plus_Minus.cpp | whitehatty/HackerRank | 6b0f5716ccd69cdf5857ba2d00740eef2b6520af | [
"MIT"
] | null | null | null | Algorithms/Warmup/Plus_Minus.cpp | whitehatty/HackerRank | 6b0f5716ccd69cdf5857ba2d00740eef2b6520af | [
"MIT"
] | null | null | null | /**
Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Print the decimal value of each fraction on a new line.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to 10^−4 are acceptable.
Input Format
The first line contains an integer, N, denoting the size of the array.
The second line contains N space-separated integers describing an array of numbers (a0,a1,a2,...,an−1)(a0,a1,a2,...,an−1).
Output Format
You must print the following 3 lines:
A decimal representing of the fraction of positive numbers in the array.
A decimal representing of the fraction of negative numbers in the array.
A decimal representing of the fraction of zeroes in the array.
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
There are 3 positive numbers, 2 negative numbers, and 1 zero in the array.
The respective fractions of positive numbers, negative numbers and zeroes are 3/6=0.500000, 2/6=0.333333 and 1/6=0.166667, respectively.
**/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> arr(n);
unsigned pos = 0;
unsigned neg = 0;
unsigned nul = 0;
for(int arr_i = 0;arr_i < n;arr_i++){
cin >> arr[arr_i];
if(arr[arr_i] == 0){
nul++;
}
if(arr[arr_i] < 0){
neg++;
}
if(arr[arr_i] > 0){
pos++;
}
}
cout << static_cast<double>(pos) / n << endl;
cout << static_cast<double>(neg) / n << endl;
cout << static_cast<double>(nul) / n << endl;
return 0;
}
| 27.558824 | 244 | 0.666489 | [
"vector"
] |
27251e8b943fcb6d46fa22e7563745d20fda763b | 802 | cpp | C++ | codeforces/511div2/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | codeforces/511div2/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | 19 | 2016-05-04T02:46:31.000Z | 2021-11-27T06:18:33.000Z | codeforces/511div2/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template <typename P, typename Q>
ostream& operator<<(ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
template <typename T>
ostream& operator<<(ostream& os, vector<T> v)
{
os << "(";
each(i, v) os << i << ",";
os << ")";
return os;
}
int main(int argc, char* argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
while (cin >> n) {
vector<pair<int, int>> v(n);
each(i, v) cin >> i.first >> i.second;
int mx = 0;
each(i, v) { mx = max(mx, i.first + i.second); }
cout << mx << endl;
}
return 0;
}
| 17.822222 | 52 | 0.564838 | [
"vector"
] |
272684fb1828c5d9f18a1ebacfd4e7e0a4b42b4f | 46,740 | cpp | C++ | released_plugins/v3d_plugins/terastitcher/src/presentation/PTabMergeTiles.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/terastitcher/src/presentation/PTabMergeTiles.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/terastitcher/src/presentation/PTabMergeTiles.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------------------------
// Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome).
// All rights reserved.
//------------------------------------------------------------------------------------------------
/*******************************************************************************************************************************************************************************************
* LICENSE NOTICE
********************************************************************************************************************************************************************************************
* By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change
* this code.
********************************************************************************************************************************************************************************************
* 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at
* g.iannello@unicampus.it for further details.
* 2. You agree to appropriately cite this work in your related studies and publications.
*
* Bria, A., et al., (2012) "Stitching Terabyte-sized 3D Images Acquired in Confocal Ultramicroscopy", Proceedings of the 9th IEEE International Symposium on Biomedical Imaging.
* Bria, A., Iannello, G., "A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Datasets", submitted on July 2012 to IEEE Transactions on Information Technology in Biomedicine.
*
* 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war-
* ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the
* copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused and on any theory of liabil-
* ity, 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.
* 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without
* specific prior written permission.
********************************************************************************************************************************************************************************************/
#include "PTabMergeTiles.h"
#include "iomanager.config.h"
#include "vmStackedVolume.h"
#include "vmBlockVolume.h"
#include "PMain.h"
#include "src/control/CImport.h"
#include "src/control/CMergeTiles.h"
#include "StackStitcher.h"
#include "S_config.h"
#include "IOPluginAPI.h"
using namespace terastitcher;
/*********************************************************************************
* Singleton design pattern: this class can have one instance only, which must be
* instantiated by calling static method "istance(...)"
**********************************************************************************/
PTabMergeTiles* PTabMergeTiles::uniqueInstance = 0;
void PTabMergeTiles::uninstance()
{
if(uniqueInstance)
{
delete uniqueInstance;
uniqueInstance = NULL;
}
}
PTabMergeTiles::PTabMergeTiles(QMyTabWidget* _container, int _tab_index, V3DPluginCallback *_V3D_env) : QWidget(), container(_container), tab_index(_tab_index)
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles created\n", this->thread()->currentThreadId());
#endif
V3D_env = _V3D_env;
//basic panel widgets
basic_panel = new QWidget();
savedir_label = new QLabel("Save to:");
savedir_field = new QLineEdit();
savedir_field->setFont(QFont("",8));
browse_button = new QPushButton("...");
resolutions_label = new QLabel(QString("Resolution (X ").append(QChar(0x00D7)).append(" Y ").append(QChar(0x00D7)).append(" Z)"));
resolutions_label->setFont(QFont("",8));
resolutions_label->setAlignment(Qt::AlignCenter);
resolutions_size_label = new QLabel("Size (GVoxels)");
resolutions_size_label->setFont(QFont("",8));
resolutions_size_label->setAlignment(Qt::AlignCenter);
resolutions_save_label = new QLabel("Save to disk");
resolutions_save_label->setFont(QFont("",8));
resolutions_save_label->setAlignment(Qt::AlignCenter);
resolutions_view_label = new QLabel("Open");
resolutions_view_label->setFont(QFont("",8));
resolutions_view_label->setAlignment(Qt::AlignCenter);
outputs_label = new QLabel("Outputs:");
outputs_label->setAlignment(Qt::AlignVCenter);
resolutions_save_selection = new QButtonGroup();
resolutions_save_selection->setExclusive(false);
for(int i=0; i<S_MAX_MULTIRES; i++)
{
resolutions_fields[i] = new QLabel();
resolutions_fields[i]->setAlignment(Qt::AlignCenter);
resolutions_sizes[i] = new QLabel();
resolutions_sizes[i]->setAlignment(Qt::AlignCenter);
resolutions_save_cboxs[i] = new QCheckBox("");
resolutions_save_cboxs[i]->setChecked(true);
resolutions_save_cboxs[i]->setStyleSheet("::indicator {subcontrol-position: center; subcontrol-origin: padding;}");
resolutions_save_selection->addButton(resolutions_save_cboxs[i]);
resolutions_view_cboxs[i] = new QCheckBox("");
resolutions_view_cboxs[i]->setStyleSheet("::indicator {subcontrol-position: center; subcontrol-origin: padding;}");
}
volumeformat_label = new QLabel("Format:");
vol_format_cbox = new QComboBox();
vol_format_cbox->setFont(QFont("", 8));
vol_format_cbox->setEditable(true);
vol_format_cbox->lineEdit()->setReadOnly(true);
vol_format_cbox->lineEdit()->setAlignment(Qt::AlignCenter);
vol_format_cbox->addItem("--- Volume format ---");
vol_format_cbox->addItem("2Dseries");
vol_format_cbox->addItem("3Dseries");
std::vector <std::string> volformats = vm::VirtualVolumeFactory::registeredPluginsList();
for(int i=0; i<volformats.size(); i++)
vol_format_cbox->addItem(volformats[i].c_str());
for(int i = 0; i < vol_format_cbox->count(); i++)
vol_format_cbox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
PMain::setEnabledComboBoxItem(vol_format_cbox, 0, false);
imout_plugin_cbox = new QComboBox();
imout_plugin_cbox->setFont(QFont("", 8));
std::vector<std::string> ioplugins = iom::IOPluginFactory::registeredPluginsList();
imout_plugin_cbox->addItem("--- I/O plugin: ---");
for(int i=0; i<ioplugins.size(); i++)
imout_plugin_cbox->addItem(ioplugins[i].c_str());
imout_plugin_cbox->setEditable(true);
imout_plugin_cbox->lineEdit()->setReadOnly(true);
imout_plugin_cbox->lineEdit()->setAlignment(Qt::AlignCenter);
for(int i = 0; i < imout_plugin_cbox->count(); i++)
imout_plugin_cbox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
PMain::setEnabledComboBoxItem(imout_plugin_cbox, 0, false);
block_height_field = new QSpinBox();
block_height_field->setAlignment(Qt::AlignCenter);
block_height_field->setMinimum(-1);
block_height_field->setMaximum(4096);
block_height_field->setValue(512);
block_height_field->setSuffix(" (height)");
block_height_field->setFont(QFont("", 9));
block_width_field = new QSpinBox();
block_width_field->setAlignment(Qt::AlignCenter);
block_width_field->setMinimum(-1);
block_width_field->setMaximum(4096);
block_width_field->setValue(512);
block_width_field->setSuffix(" (width)");
block_width_field->setFont(QFont("", 9));
block_depth_field = new QSpinBox();
block_depth_field->setAlignment(Qt::AlignCenter);
block_depth_field->setMinimum(-1);
block_depth_field->setMaximum(1024);
block_depth_field->setValue(256);
block_depth_field->setSuffix(" (depth)");
block_depth_field->setFont(QFont("", 9));
memocc_field = new QLineEdit();
memocc_field->setReadOnly(true);
memocc_field->setAlignment(Qt::AlignLeft);
memocc_field->setFont(QFont("", 9));
memocc_field->setStyleSheet("background-color: #ACDCA5");
memocc_field->setTextMargins(5,0,0,0);
showAdvancedButton = new QPushButton(QString("Advanced options ").append(QChar(0x00BB)), this);
showAdvancedButton->setCheckable(true);
//advanced panel widgets
advanced_panel = new QWidget();
volumeportion_label = new QLabel("Portion to be stitched:");
row0_field = new QSpinBox();
row0_field->setAlignment(Qt::AlignCenter);
row0_field->setMinimum(-1);
row0_field->setValue(-1);
row0_field->setFont(QFont("", 9));
row0_field->setPrefix("[");
row1_field = new QSpinBox();
row1_field->setAlignment(Qt::AlignCenter);
row1_field->setMinimum(-1);
row1_field->setValue(-1);
row1_field->setFont(QFont("", 9));
row1_field->setSuffix("]");
col0_field = new QSpinBox();
col0_field->setAlignment(Qt::AlignCenter);
col0_field->setMinimum(-1);
col0_field->setValue(-1);
col0_field->setFont(QFont("", 9));
col0_field->setPrefix("[");
col1_field = new QSpinBox();
col1_field->setAlignment(Qt::AlignCenter);
col1_field->setMinimum(-1);
col1_field->setValue(-1);
col1_field->setFont(QFont("", 9));
col1_field->setSuffix("]");
slice0_field = new QSpinBox();
slice0_field->setAlignment(Qt::AlignCenter);
slice0_field->setMinimum(-1);
slice0_field->setMaximum(-1);
slice0_field->setValue(-1);
slice0_field->setFont(QFont("", 9));
slice0_field->setPrefix("[");
slice1_field = new QSpinBox();
slice1_field->setAlignment(Qt::AlignCenter);
slice1_field->setMinimum(-1);
slice1_field->setMaximum(-1);
slice1_field->setValue(-1);
slice1_field->setFont(QFont("", 9));
slice1_field->setSuffix("]");
excludenonstitchables_cbox = new QCheckBox("stitchables only");
excludenonstitchables_cbox->setFont(QFont("", 9));
blendingalgo_label = new QLabel("Blending:");
blendingalbo_cbox = new QComboBox();
blendingalbo_cbox->insertItem(0, "No Blending");
blendingalbo_cbox->insertItem(1, "Sinusoidal Blending");
blendingalbo_cbox->insertItem(2, "No Blending with emphasized stacks borders");
blendingalbo_cbox->setEditable(true);
blendingalbo_cbox->lineEdit()->setReadOnly(true);
blendingalbo_cbox->lineEdit()->setAlignment(Qt::AlignCenter);
for(int i = 0; i < blendingalbo_cbox->count(); i++)
blendingalbo_cbox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
blendingalbo_cbox->setCurrentIndex(1);
blendingalbo_cbox->setFont(QFont("", 9));
restoreSPIM_label = new QLabel("remove SPIM artifacts: ");
restoreSPIM_label->setFont(QFont("", 9));
restoreSPIM_cbox = new QComboBox();
restoreSPIM_cbox->insertItem(0, "None");
restoreSPIM_cbox->insertItem(1, "Zebrated pattern (Y)");
restoreSPIM_cbox->insertItem(2, "Zebrated pattern (X)");
restoreSPIM_cbox->insertItem(3, "Zebrated pattern (Z)");
restoreSPIM_cbox->setEditable(true);
restoreSPIM_cbox->lineEdit()->setReadOnly(true);
restoreSPIM_cbox->lineEdit()->setAlignment(Qt::AlignCenter);
for(int i = 0; i < restoreSPIM_cbox->count(); i++)
restoreSPIM_cbox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
restoreSPIM_cbox->setFont(QFont("", 9));
imgformat_label = new QLabel("");
img_format_cbox = new QComboBox();
img_format_cbox->insertItem(0, "tif");
img_format_cbox->insertItem(1, "tiff");
img_format_cbox->insertItem(2, "v3draw");
img_format_cbox->insertItem(3, "png");
img_format_cbox->insertItem(4, "bmp");
img_format_cbox->insertItem(5, "jpeg");
img_format_cbox->insertItem(6, "jpg");
img_format_cbox->insertItem(7, "dib");
img_format_cbox->insertItem(8, "pbm");
img_format_cbox->insertItem(9, "pgm");
img_format_cbox->insertItem(10, "ppm");
img_format_cbox->insertItem(11, "sr");
img_format_cbox->insertItem(12, "ras");
img_format_cbox->setFont(QFont("", 9));
img_format_cbox->setEditable(true);
img_format_cbox->lineEdit()->setReadOnly(true);
img_format_cbox->lineEdit()->setAlignment(Qt::AlignCenter);
for(int i = 0; i < img_format_cbox->count(); i++)
img_format_cbox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
imgdepth_cbox = new QComboBox();
imgdepth_cbox->insertItem(0, "8 bits");
imgdepth_cbox->insertItem(1, "16 bits");
imgdepth_cbox->setFont(QFont("", 9));
imgdepth_cbox->setEditable(true);
imgdepth_cbox->lineEdit()->setReadOnly(true);
imgdepth_cbox->lineEdit()->setAlignment(Qt::AlignCenter);
for(int i = 0; i < imgdepth_cbox->count(); i++)
imgdepth_cbox->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
channel_selection = new QComboBox();
channel_selection->addItem("all channels");
channel_selection->addItem("channel R");
channel_selection->addItem("channel G");
channel_selection->addItem("channel B");
channel_selection->setFont(QFont("", 8));
channel_selection->setEditable(true);
channel_selection->lineEdit()->setReadOnly(true);
channel_selection->lineEdit()->setAlignment(Qt::AlignCenter);
for(int i = 0; i < channel_selection->count(); i++)
channel_selection->setItemData(i, Qt::AlignCenter, Qt::TextAlignmentRole);
connect(channel_selection, SIGNAL(currentIndexChanged(int)),this, SLOT(channelSelectedChanged(int)));
/*** LAYOUT SECTIONS ***/
//basic settings panel
QVBoxLayout* basicpanel_layout = new QVBoxLayout();
basicpanel_layout->setContentsMargins(0,0,0,0);
int left_margin = 80;
/**/
QHBoxLayout* basic_panel_row_1 = new QHBoxLayout();
basic_panel_row_1->setContentsMargins(0,0,0,0);
basic_panel_row_1->setSpacing(0);
savedir_label->setFixedWidth(left_margin);
browse_button->setFixedWidth(80);
basic_panel_row_1->addWidget(savedir_label);
basic_panel_row_1->addWidget(savedir_field,1);
basic_panel_row_1->addWidget(browse_button);
basicpanel_layout->addLayout(basic_panel_row_1);
/**/
basicpanel_layout->addSpacing(10);
/**/
QGridLayout* basic_panel_row_2 = new QGridLayout();
basic_panel_row_2->setContentsMargins(0,0,0,0);
basic_panel_row_2->setSpacing(0);
basic_panel_row_2->setVerticalSpacing(0);
basic_panel_row_2->addWidget(resolutions_label, 0, 1, 1, 6);
resolutions_label->setFixedWidth(200);
basic_panel_row_2->addWidget(resolutions_size_label, 0, 7, 1, 3);
resolutions_size_label->setFixedWidth(120);
basic_panel_row_2->addWidget(resolutions_save_label, 0, 10, 1, 1);
basic_panel_row_2->addWidget(resolutions_view_label, 0, 11, 1, 1);
outputs_label->setFixedWidth(left_margin);
basic_panel_row_2->addWidget(outputs_label, 1, 0, S_MAX_MULTIRES, 1);
for(int i=0; i<S_MAX_MULTIRES; i++)
{
resolutions_fields[i]->setFont(QFont("", 9));
resolutions_fields[i]->setFixedWidth(200);
resolutions_sizes[i]->setFont(QFont("", 9));
resolutions_sizes[i]->setFixedWidth(120);
basic_panel_row_2->addWidget(resolutions_fields[i], 1+i, 1, 1, 6);
basic_panel_row_2->addWidget(resolutions_sizes[i], 1+i, 7, 1, 3);
basic_panel_row_2->addWidget(resolutions_save_cboxs[i], 1+i, 10, 1, 1);
basic_panel_row_2->addWidget(resolutions_view_cboxs[i], 1+i, 11, 1, 1);
}
basicpanel_layout->addLayout(basic_panel_row_2);
/**/
basicpanel_layout->addSpacing(10);
/**/
QHBoxLayout* basic_panel_row_3 = new QHBoxLayout();
basic_panel_row_3->setContentsMargins(0,0,0,0);
basic_panel_row_3->setSpacing(0);
volumeformat_label->setFixedWidth(left_margin);
basic_panel_row_3->addWidget(volumeformat_label);
vol_format_cbox->setFixedWidth(150);
basic_panel_row_3->addWidget(vol_format_cbox);
imout_plugin_cbox->setFixedWidth(130);
basic_panel_row_3->addSpacing(10);
basic_panel_row_3->addWidget(imout_plugin_cbox);
basic_panel_row_3->addSpacing(20);
basic_panel_row_3->addWidget(block_height_field, 1);
basic_panel_row_3->addSpacing(5);
basic_panel_row_3->addWidget(block_width_field, 1);
basic_panel_row_3->addSpacing(5);
basic_panel_row_3->addWidget(block_depth_field, 1);
basicpanel_layout->addLayout(basic_panel_row_3);
/**/
QHBoxLayout* basic_panel_row_4 = new QHBoxLayout();
basic_panel_row_4->setContentsMargins(0,0,0,0);
basic_panel_row_4->setSpacing(0);
imgformat_label->setFixedWidth(left_margin);
basic_panel_row_4->addWidget(imgformat_label);
img_format_cbox->setFixedWidth(80);
basic_panel_row_4->addWidget(img_format_cbox);
basic_panel_row_4->addSpacing(5);
imgdepth_cbox->setFixedWidth(90);
basic_panel_row_4->addWidget(imgdepth_cbox);
basic_panel_row_4->addSpacing(5);
channel_selection->setFixedWidth(110);
basic_panel_row_4->addWidget(channel_selection);
basic_panel_row_4->addSpacing(20);
basic_panel_row_4->addWidget(memocc_field, 1);
basicpanel_layout->addLayout(basic_panel_row_4);
basicpanel_layout->addSpacing(5);
/**/
basicpanel_layout->addWidget(showAdvancedButton);
/**/
basicpanel_layout->setContentsMargins(10,0,10,0);
basic_panel->setLayout(basicpanel_layout);
//advanced settings panel
QVBoxLayout* advancedpanel_layout = new QVBoxLayout();
/**/
QHBoxLayout* advancedpanel_row1 = new QHBoxLayout();
advancedpanel_row1->setSpacing(0);
advancedpanel_row1->setContentsMargins(0,0,0,0);
QLabel* selection_label = new QLabel("Selection:");
selection_label->setFixedWidth(left_margin);
advancedpanel_row1->addWidget(selection_label);
QLabel* rowLabel = new QLabel(" (rows)");
rowLabel->setFont(QFont("", 8));
QLabel* colLabel = new QLabel(" (cols)");
colLabel->setFont(QFont("", 8));
QLabel* sliceLabel = new QLabel(" (slices)");
sliceLabel->setFont(QFont("", 8));
rowLabel->setFixedWidth(60);
colLabel->setFixedWidth(60);
sliceLabel->setFixedWidth(60);
row0_field->setFixedWidth(50);
row1_field->setFixedWidth(50);
col0_field->setFixedWidth(50);
col1_field->setFixedWidth(50);
slice0_field->setFixedWidth(75);
slice1_field->setFixedWidth(75);
advancedpanel_row1->addWidget(row0_field);
advancedpanel_row1->addWidget(row1_field);
advancedpanel_row1->addWidget(rowLabel);
advancedpanel_row1->addWidget(col0_field);
advancedpanel_row1->addWidget(col1_field);
advancedpanel_row1->addWidget(colLabel);
advancedpanel_row1->addWidget(slice0_field);
advancedpanel_row1->addWidget(slice1_field);
advancedpanel_row1->addWidget(sliceLabel);
advancedpanel_row1->addStretch(1);
advancedpanel_row1->addWidget(excludenonstitchables_cbox);
advancedpanel_layout->addLayout(advancedpanel_row1);
/**/
QHBoxLayout* advancedpanel_row2 = new QHBoxLayout();
advancedpanel_row2->setSpacing(0);
advancedpanel_row2->setContentsMargins(0,0,0,0);
blendingalgo_label->setFixedWidth(left_margin);
advancedpanel_row2->addWidget(blendingalgo_label);
blendingalbo_cbox->setFixedWidth(260);
advancedpanel_row2->addWidget(blendingalbo_cbox);
advancedpanel_row2->addSpacing(60);
advancedpanel_row2->addWidget(restoreSPIM_label);
advancedpanel_row2->addWidget(restoreSPIM_cbox);
advancedpanel_layout->addLayout(advancedpanel_row2);
/**/
advanced_panel->setLayout(advancedpanel_layout);
//overall
QVBoxLayout* layout = new QVBoxLayout();
layout->setAlignment(Qt::AlignTop);
layout->addWidget(basic_panel);
layout->addWidget(advanced_panel);
layout->setSpacing(0);
setLayout(layout);
//wait animated GIF tab icon
wait_movie = new QMovie(":/icons/wait.gif");
wait_label = new QLabel(this);
wait_label->setMovie(wait_movie);
// signals and slots
connect(browse_button, SIGNAL(clicked()), this, SLOT(browse_button_clicked()));
connect(row0_field, SIGNAL(valueChanged(int)), this, SLOT(stacksinterval_changed()));
connect(row0_field, SIGNAL(valueChanged(int)), this, SLOT(row0_field_changed(int)));
connect(row1_field, SIGNAL(valueChanged(int)), this, SLOT(stacksinterval_changed()));
connect(row1_field, SIGNAL(valueChanged(int)), this, SLOT(row1_field_changed(int)));
connect(col0_field, SIGNAL(valueChanged(int)), this, SLOT(stacksinterval_changed()));
connect(col0_field, SIGNAL(valueChanged(int)), this, SLOT(col0_field_changed(int)));
connect(col1_field, SIGNAL(valueChanged(int)), this, SLOT(stacksinterval_changed()));
connect(col1_field, SIGNAL(valueChanged(int)), this, SLOT(col1_field_changed(int)));
connect(slice0_field, SIGNAL(valueChanged(int)), this, SLOT(updateContent()));
connect(slice0_field, SIGNAL(valueChanged(int)), this, SLOT(slice0_field_changed(int)));
connect(slice1_field, SIGNAL(valueChanged(int)), this, SLOT(updateContent()));
connect(slice1_field, SIGNAL(valueChanged(int)), this, SLOT(slice1_field_changed(int)));
connect(excludenonstitchables_cbox, SIGNAL(stateChanged(int)),this, SLOT(excludenonstitchables_changed()));
connect(vol_format_cbox, SIGNAL(currentIndexChanged(QString)), this, SLOT(volumeformat_changed(QString)));
connect(imout_plugin_cbox, SIGNAL(currentIndexChanged(QString)), this, SLOT(imout_plugin_changed(QString)));
for(int i=0; i<S_MAX_MULTIRES; i++)
{
connect(resolutions_save_cboxs[i], SIGNAL(stateChanged(int)), this, SLOT(updateContent()));
connect(resolutions_save_cboxs[i], SIGNAL(stateChanged(int)), this, SLOT(save_changed(int)));
connect(resolutions_view_cboxs[i], SIGNAL(stateChanged(int)), this, SLOT(viewinVaa3D_changed(int)));
}
connect(CMergeTiles::instance(), SIGNAL(sendOperationOutcome(iom::exception*, Image4DSimple*)), this, SLOT(merging_done(iom::exception*, Image4DSimple*)), Qt::QueuedConnection);
connect(showAdvancedButton, SIGNAL(toggled(bool)), this, SLOT(showAdvancedChanged(bool)));
reset();
}
PTabMergeTiles::~PTabMergeTiles()
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles destroyed\n", this->thread()->currentThreadId());
#endif
}
//reset method
void PTabMergeTiles::reset()
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles::reset()\n", this->thread()->currentThreadId());
#endif
savedir_field->setText("Enter or select the directory where to save the stitched volume.");
for(int i=0; i<S_MAX_MULTIRES; i++)
{
resolutions_fields[i]->setText(QString("n.a. ").append(QChar(0x00D7)).append(QString(" n.a. ").append(QChar(0x00D7)).append(" n.a.")));
resolutions_sizes[i]->setText("n.a.");
resolutions_save_cboxs[i]->setChecked(true);
resolutions_view_cboxs[i]->setChecked(false);
}
vol_format_cbox->setCurrentIndex(0);
imout_plugin_cbox->setCurrentIndex(0);
// int index = vol_format_cbox->findText(BlockVolume::id.c_str());
// if ( index != -1 )
// vol_format_cbox->setCurrentIndex(index);
// index = imout_plugin_cbox->findText("tiff3D");
// if ( index != -1 )
// imout_plugin_cbox->setCurrentIndex(index);
block_height_field->setMinimum(-1);
block_height_field->setMaximum(4096);
block_height_field->setValue(512);
block_width_field->setMinimum(-1);
block_width_field->setMaximum(4096);
block_width_field->setValue(512);
block_depth_field->setMinimum(-1);
block_depth_field->setMaximum(1024);
block_depth_field->setValue(256);
memocc_field->setText("Memory usage: ");
excludenonstitchables_cbox->setChecked(false);
row0_field->setMinimum(-1);
row0_field->setValue(-1);
row1_field->setMinimum(-1);
row1_field->setValue(-1);
col0_field->setMinimum(-1);
col0_field->setValue(-1);
col1_field->setMinimum(-1);
col1_field->setValue(-1);
slice0_field->setMinimum(-1);
slice0_field->setMaximum(-1);
slice0_field->setValue(-1);
slice1_field->setMinimum(-1);
slice1_field->setMaximum(-1);
slice1_field->setValue(-1);
row0_field->setMinimum(-1);
row0_field->setMaximum(-1);
row0_field->setValue(-1);
row1_field->setMinimum(-1);
row1_field->setMaximum(-1);
row1_field->setValue(-1);
col0_field->setMinimum(-1);
col0_field->setMaximum(-1);
col0_field->setValue(-1);
col1_field->setMinimum(-1);
col1_field->setMaximum(-1);
col1_field->setValue(-1);
showAdvancedButton->setChecked(false);
advanced_panel->setVisible(false);
setEnabled(false);
}
/*********************************************************************************
* Start/Stop methods associated to the current step.
* They are called by the startButtonClicked/stopButtonClicked methods of <PMain>
**********************************************************************************/
void PTabMergeTiles::start()
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles start() launched\n", this->thread()->currentThreadId());
#endif
try
{
//first checking that a volume has been properly imported
if(!CImport::instance()->getVolume())
throw iom::exception("A volume must be properly imported first. Please perform the Import step.");
// check user input
if(imout_plugin_cbox->currentIndex() == 0)
throw iom::exception("Please select an image I/O plugin from the combolist");
if(vol_format_cbox->currentIndex() == 0)
throw iom::exception("Please select the volume format from the combolist");
//verifying that directory is readable
QDir directory(savedir_field->text());
if(!directory.isReadable())
throw iom::exception(QString("Cannot open directory\n \"").append(savedir_field->text()).append("\"").toStdString().c_str());
//asking confirmation to continue when saving to a non-empty dir
QStringList dir_entries = directory.entryList();
if(dir_entries.size() > 2 && QMessageBox::information(this, "Warning", "The directory you selected is NOT empty. \n\nIf you continue, the merging "
"process could fail if the directories to be created already exist in the given path.", "Continue", "Cancel"))
{
PMain::instance()->setToReady();
return;
}
//if basic mode is active, automatically performing the hidden steps (Projecting, Thresholding, Placing) if necessary
// if(PMain::instance()->modeBasicAction->isChecked())
// {
// //asking confirmation to continue if no displacements were found
// if(PMain::instance()->tabDisplProj->total_displ_number_field->text().toInt() == 0 &&
// QMessageBox::information(this, "Warning", "No computed displacements found. \n\nDisplacements will be generated using nominal stage coordinates.", "Continue", "Cancel"))
// {
// PMain::instance()->setToReady();
// return;
// }
// //performing operation
// StackedVolume* volume = CImport::instance()->getVolume();
// if(!volume)
// throw iom::exception("Unable to start this step. A volume must be properly imported first.");
// //Alessandro 2013-07-08: this causes crash and it is not needed (nominal stage coordinates are already ready for merging)
//// StackStitcher stitcher(volume);
//// stitcher.projectDisplacements();
//// stitcher.thresholdDisplacements(PMain::instance()->tabDisplThres->threshold_field->value());
//// stitcher.computeTilesPlacement(PMain::instance()->tabPlaceTiles->algo_cbox->currentIndex());
// //enabling (and updating) other tabs
// PTabDisplProj::getInstance()->setEnabled(true);
// PTabDisplThresh::getInstance()->setEnabled(true);
// PTabPlaceTiles::getInstance()->setEnabled(true);
// PTabMergeTiles::getInstance()->setEnabled(true);
// }
//disabling import form and enabling progress bar animation and tab wait animation
PMain::instance()->getProgressBar()->setEnabled(true);
PMain::instance()->getProgressBar()->setMinimum(0);
PMain::instance()->getProgressBar()->setMaximum(100);
PMain::instance()->closeVolumeAction->setEnabled(false);
PMain::instance()->exitAction->setEnabled(false);
wait_movie->start();
if(PMain::instance()->modeBasicAction->isChecked())
container->getTabBar()->setTabButton(2, QTabBar::LeftSide, wait_label);
else
container->getTabBar()->setTabButton(tab_index, QTabBar::LeftSide, wait_label);
//propagating options and parameters and launching task
CMergeTiles::instance()->setPMergeTiles(this);
for(int i=0; i<S_MAX_MULTIRES; i++)
{
CMergeTiles::instance()->setResolution(i, resolutions_save_cboxs[i]->isChecked());
if(vol_format_cbox->currentText().compare("2Dseries")==0 && resolutions_view_cboxs[i]->isChecked())
CMergeTiles::instance()->setResolutionToShow(i);
}
CMergeTiles::instance()->start();
}
catch(iom::exception &ex)
{
QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok"));
PMain::instance()->setToReady();
}
catch(...)
{
QMessageBox::critical(this,QObject::tr("Error"), "Unknown error has occurred",QObject::tr("Ok"));
PMain::instance()->setToReady();
}
}
void PTabMergeTiles::stop()
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles stop() launched\n", this->thread()->currentThreadId());
#endif
// ----- terminating CMergeTiles's thread is UNSAFE ==> this feature should be disabled or a warning should be displayed ------
//terminating thread
try
{
CMergeTiles::instance()->terminate();
CMergeTiles::instance()->wait();
}
catch(iom::exception &ex) {QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok"));}
catch(...) {QMessageBox::critical(this,QObject::tr("Error"), QObject::tr("Unable to determine error's type"),QObject::tr("Ok"));}
//disabling progress bar and wait animations
PMain::instance()->setToReady();
wait_movie->stop();
if(PMain::instance()->modeBasicAction->isChecked())
container->getTabBar()->setTabButton(2, QTabBar::LeftSide, 0);
else
container->getTabBar()->setTabButton(tab_index, QTabBar::LeftSide, 0);
PMain::instance()->closeVolumeAction->setEnabled(true);
PMain::instance()->exitAction->setEnabled(true);
}
/**********************************************************************************
* Overrides QWidget's setEnabled(bool).
* If the widget is enabled, its fields are filled with the informations provided by
* the <StackedVolume> object of <CImport> instance.
***********************************************************************************/
void PTabMergeTiles::setEnabled(bool enabled)
{
/**/tsp::debug(tsp::LEV_MAX, 0, __tsp__current__function__);
//then filling widget fields
if(enabled && CImport::instance()->getVolume())
{
vm::VirtualVolume* volume = CImport::instance()->getVolume();
//inserting volume dimensions
QWidget::setEnabled(false);
row0_field->setMinimum(0);
row0_field->setMaximum(volume->getN_ROWS()-1);
row0_field->setValue(0);
row1_field->setMinimum(0);
row1_field->setMaximum(volume->getN_ROWS()-1);
row1_field->setValue(volume->getN_ROWS()-1);
col0_field->setMinimum(0);
col0_field->setMaximum(volume->getN_COLS()-1);
col0_field->setValue(0);
col1_field->setMinimum(0);
col1_field->setMaximum(volume->getN_COLS()-1);
col1_field->setValue(volume->getN_COLS()-1);
slice0_field->setMaximum(volume->getN_SLICES()-1);
slice0_field->setMinimum(0);
slice0_field->setValue(0);
slice1_field->setMaximum(volume->getN_SLICES()-1);
slice1_field->setMinimum(0);
slice1_field->setValue(volume->getN_SLICES()-1);
volumeformat_changed(vol_format_cbox->currentText());
QWidget::setEnabled(true);
//updating content
updateContent();
}
else
QWidget::setEnabled(enabled);
}
/**********************************************************************************
* Opens the dialog to select the directory where the stitched volume has to be saved.
* Called when user clicks on "browse_button".
***********************************************************************************/
void PTabMergeTiles::browse_button_clicked()
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles browse_button_clicked() launched\n", this->thread()->currentThreadId());
#endif
//obtaining volume's directory
QFileDialog dialog(0);
dialog.setFileMode(QFileDialog::DirectoryOnly);
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setWindowFlags(Qt::WindowStaysOnTopHint);
dialog.setDirectory(CImport::instance()->getVolume()->getSTACKS_DIR());
dialog.setWindowTitle("Please select an EMPTY directory");
if (dialog.exec())
{
QStringList fileNames = dialog.selectedFiles();
QString xmlpath = fileNames.first();
QDir directory(xmlpath);
QStringList dir_entries = directory.entryList();
if(dir_entries.size() <= 2)
savedir_field->setText(xmlpath);
else
{
if(!QMessageBox::information(this, "Warning", "The directory you selected is NOT empty. \n\nIf you continue, the merging "
"process could fail if the directories to be created already exist in the given path.", "Continue", "Cancel"))
savedir_field->setText(xmlpath);
}
}
}
/**********************************************************************************
* Called when <excludenonstitchables_cbox> combobox state changed.
* Inferior and superior limits of spinboxes are recomputed.
***********************************************************************************/
void PTabMergeTiles::excludenonstitchables_changed()
{
try
{
if(this->isEnabled() && CImport::instance()->getVolume())
updateContent();
}
catch(iom::exception &ex)
{
QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok"));
}
}
/**********************************************************************************
* Called when <row0_field>, <row1_field>, <col0_field> or <col1_field> changed.
* Inferior and superior limits of <slice_[]_cbox> spinboxes are recomputed.
***********************************************************************************/
void PTabMergeTiles::stacksinterval_changed()
{
try
{
if(this->isEnabled() && CImport::instance()->getVolume())
updateContent();
}
catch(iom::exception &ex)
{
QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok"));
}
}
/**********************************************************************************
* Updates widgets contents
***********************************************************************************/
void PTabMergeTiles::updateContent()
{
/**/tsp::debug(tsp::LEV_MAX, 0, __tsp__current__function__);
try
{
if(this->isEnabled() && CImport::instance()->getVolume())
{
vm::VirtualVolume* volume = CImport::instance()->getVolume();
StackStitcher stitcher(volume);
stitcher.computeVolumeDims(excludenonstitchables_cbox->isChecked(), row0_field->value(), row1_field->value(),
col0_field->value(), col1_field->value(), slice0_field->value(), slice1_field->value()+1);
int max_res = 0;
for(int i=0; i<S_MAX_MULTIRES; i++)
{
int height = (stitcher.getV1()-stitcher.getV0())/pow(2.0f, i);
int width = (stitcher.getH1()-stitcher.getH0())/pow(2.0f, i);
int depth = (stitcher.getD1()-stitcher.getD0())/pow(2.0f, i);
float GVoxels = (height/1024.0f)*(width/1024.0f)*(depth/1024.0f);
resolutions_fields[i]->setText(QString::number(width).append(" ").append(QChar(0x00D7)).append(" ").append(QString::number(height)).append(" ").append(QChar(0x00D7)).append(" ").append(QString::number(depth)));
resolutions_sizes[i]->setText(QString::number(GVoxels,'f',3));
if(resolutions_save_cboxs[i]->isChecked())
max_res = std::max(max_res, i);
}
//updating RAM usage estimation
int layer_height = stitcher.getV1()-stitcher.getV0();
int layer_width = stitcher.getH1()-stitcher.getH0();
int layer_depth = pow(2.0f, max_res);
float MBytes = (layer_height/1024.0f)*(layer_width/1024.0f)*layer_depth*4;
memocc_field->setText(QString("Memory usage: ")+QString::number(MBytes, 'f', 0).append(" MB"));
// update ranges
slice0_field->setValue(stitcher.getD0());
slice1_field->setValue(stitcher.getD1()-1);
row0_field->setValue(stitcher.getROW0());
row1_field->setValue(stitcher.getROW1());
col0_field->setValue(stitcher.getCOL0());
col1_field->setValue(stitcher.getCOL1());
}
}
catch(iom::exception &ex)
{
QMessageBox::critical(this,QObject::tr("Error"), strprintf("An error occurred while preparing the stitcher for the Merging step: \n\n\"%s\"\n\nPlease check the previous steps before you can perform the Merging step.", ex.what()).c_str(),QObject::tr("Ok"));
this->setEnabled(false);
}
}
/**********************************************************************************
* Called when the corresponding spinboxes changed.
* New maximum/minimum values are set according to the status of spinboxes.
***********************************************************************************/
void PTabMergeTiles::row0_field_changed(int val){row1_field->setMinimum(val);}
void PTabMergeTiles::row1_field_changed(int val){row0_field->setMaximum(val);}
void PTabMergeTiles::col0_field_changed(int val){col1_field->setMinimum(val);}
void PTabMergeTiles::col1_field_changed(int val){col0_field->setMaximum(val);}
void PTabMergeTiles::slice0_field_changed(int val){slice1_field->setMinimum(val);}
void PTabMergeTiles::slice1_field_changed(int val){slice0_field->setMaximum(val);}
/**********************************************************************************
* Called when <multistack_cbox> or <signlestack_cbox> state changed.
***********************************************************************************/
void PTabMergeTiles::volumeformat_changed(QString str)
{
if(str.compare("2Dseries") == 0)
{
vm::VOLUME_OUTPUT_FORMAT_PLUGIN = vm::StackedVolume::id;
block_height_field->setEnabled(false);
block_height_field->setValue(-1);
block_width_field->setEnabled(false);
block_width_field->setValue(-1);
block_depth_field->setEnabled(false);
block_depth_field->setValue(-1);
}
else if(str.compare("3Dseries") == 0)
{
vm::VOLUME_OUTPUT_FORMAT_PLUGIN = vm::BlockVolume::id;
block_height_field->setEnabled(false);
block_height_field->setValue(-1);
block_width_field->setEnabled(false);
block_width_field->setValue(-1);
block_depth_field->setEnabled(true);
block_depth_field->setValue(256);
}
else if(str.compare(vm::StackedVolume::id.c_str()) == 0)
{
vm::VOLUME_OUTPUT_FORMAT_PLUGIN = vm::StackedVolume::id;
block_height_field->setEnabled(true);
block_height_field->setValue(512);
block_width_field->setEnabled(true);
block_width_field->setValue(512);
block_depth_field->setEnabled(false);
block_depth_field->setValue(-1);
}
else if(str.compare(vm::BlockVolume::id.c_str()) == 0)
{
vm::VOLUME_OUTPUT_FORMAT_PLUGIN = vm::BlockVolume::id;
block_height_field->setEnabled(true);
block_height_field->setValue(512);
block_width_field->setEnabled(true);
block_width_field->setValue(512);
block_depth_field->setEnabled(true);
block_depth_field->setValue(256);
}
for(int i=0; i<S_MAX_MULTIRES; i++)
resolutions_view_cboxs[i]->setEnabled(vol_format_cbox->currentText().compare("2Dseries")==0);
// PMain::setEnabledComboBoxItem(img_format_cbox, 2, i == 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 3, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 4, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 5, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 6, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 7, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 8, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 9, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 10, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 11, i != 2);
// PMain::setEnabledComboBoxItem(img_format_cbox, 12, i != 2);
// if(i == 2 && img_format_cbox->currentIndex() >= 3)
// img_format_cbox->setCurrentIndex(0);
// else if(i < 2 && img_format_cbox->currentIndex() == 2)
// img_format_cbox->setCurrentIndex(0);
}
/**********************************************************************************
* Called when <imout_plugin_cbox> state changed
***********************************************************************************/
void PTabMergeTiles::imout_plugin_changed(QString str)
{
iom::IMOUT_PLUGIN = str.toStdString();
}
/**********************************************************************************
* Called when <resolutions_view_cboxs[i]> changed
***********************************************************************************/
void PTabMergeTiles::viewinVaa3D_changed(int checked)
{
QCheckBox* sender = (QCheckBox*) QObject::sender();
//unchecking other checkboxes
if(checked)
for(int i=0; i<S_MAX_MULTIRES; i++)
if(resolutions_view_cboxs[i]->isChecked())
{
if(resolutions_view_cboxs[i] == sender)
resolutions_save_cboxs[i]->setChecked(true);
else
resolutions_view_cboxs[i]->setChecked(false);
}
}
/**********************************************************************************
* Called when <resolutions_save_cboxs[i]> changed
***********************************************************************************/
void PTabMergeTiles::save_changed(int checked)
{
//unchecking other checkboxes
if(!checked)
for(int i=0; i<S_MAX_MULTIRES; i++)
if(!resolutions_save_cboxs[i]->isChecked())
resolutions_view_cboxs[i]->setChecked(false);
}
/**********************************************************************************
* Called by <CMergeTiles> when the associated operation has been performed.
* If an exception has occurred in the <CMergeTiles> thread,it is propagated and man-
* aged in the current thread (ex != 0). Otherwise, if a valid 3D image is passed,
* it is shown in Vaa3D.
***********************************************************************************/
void PTabMergeTiles::merging_done(iom::exception *ex, Image4DSimple* img)
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles merging_done(%s) launched\n", this->thread()->currentThreadId(), (ex? "ex" : "NULL"));
#endif
//if an exception has occurred, showing a message error
if(ex)
QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex->what()),QObject::tr("Ok"));
else
{
if(img)
{
v3dhandle new_win = PMain::instance()->getV3D_env()->newImageWindow(img->getFileName());
PMain::instance()->getV3D_env()->setImage(new_win, img);
//showing operation successful message
QMessageBox::information(this, "Operation successful", "Step successfully performed!", QMessageBox::Ok);
}
}
//resetting some widgets
PMain::instance()->closeVolumeAction->setEnabled(true);
PMain::instance()->exitAction->setEnabled(true);
PMain::instance()->setToReady();
wait_movie->stop();
if(PMain::instance()->modeBasicAction->isChecked())
container->getTabBar()->setTabButton(2, QTabBar::LeftSide, 0);
else
container->getTabBar()->setTabButton(tab_index, QTabBar::LeftSide, 0);
}
/**********************************************************************************
* Called when <showAdvancedButton> status changed
***********************************************************************************/
void PTabMergeTiles::showAdvancedChanged(bool status)
{
#ifdef TSP_DEBUG
printf("TeraStitcher plugin [thread %d] >> PTabMergeTiles::showAdvancedChanged(%s)\n", this->thread()->currentThreadId(), (status? "true" : "false"));
#endif
advanced_panel->setVisible(status);
}
/**********************************************************************************
* Called when "channel_selection" state has changed.
***********************************************************************************/
void PTabMergeTiles::channelSelectedChanged(int c)
{
iom::CHANS = iom::channel(c);
}
| 46.786787 | 264 | 0.632199 | [
"object",
"vector",
"3d"
] |
27293254e526172dbea941542625405434dc3ca8 | 6,360 | cpp | C++ | src/Engine/Time.cpp | Jino42/stf | f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db | [
"Unlicense"
] | null | null | null | src/Engine/Time.cpp | Jino42/stf | f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db | [
"Unlicense"
] | null | null | null | src/Engine/Time.cpp | Jino42/stf | f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db | [
"Unlicense"
] | null | null | null | #include "Time.hpp"
#include <iomanip>
#include <iostream>
#include <algorithm>
Timer::Timer(bool canStart)
: started_(false),
paused_(false),
speed_(1.0f),
timePointTimerCreated_(std::chrono::steady_clock::now()),
reference_(std::chrono::steady_clock::now()),
accumulated_(std::chrono::duration<long double>(0)) {
if (canStart)
start();
Timer::addTimer_(this);
}
Timer::~Timer() {
Timer::deleteTimer_(this);
}
void Timer::start() {
if (!started_) {
started_ = true;
paused_ = false;
accumulated_ = std::chrono::duration<long double>(0);
reference_ = std::chrono::steady_clock::now();
} else if (paused_) {
reference_ = std::chrono::steady_clock::now();
paused_ = false;
}
}
void Timer::stop() {
if (started_ && !paused_) {
if (!Time::Get().isPause()) {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
accumulated_ = accumulated_ + std::chrono::duration_cast<std::chrono::duration<long double>>(now - reference_) * speed_;
}
paused_ = true;
}
}
void Timer::reset() {
if (started_) {
started_ = false;
paused_ = false;
speed_ = 1.0f;
reference_ = std::chrono::steady_clock::now();
accumulated_ = std::chrono::duration<long double>(0);
}
}
void Timer::setSpeed(float speed) {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
accumulated_ = accumulated_ + std::chrono::duration_cast<std::chrono::duration<long double>>(now - reference_) * speed_;
reference_ = std::chrono::steady_clock::now();
speed_ = speed;
}
float Timer::getSpeed() const {
return speed_;
}
void Timer::applyWorldStart_() {
if (!started_)
return;
if (!Time::Get().isPause()) {
if (!paused_)
reference_ = std::chrono::steady_clock::now();
}
}
void Timer::applyWorldStop_() {
if (!started_ || paused_)
return;
if (Time::Get().isPause()) {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
accumulated_ = accumulated_ + std::chrono::duration_cast<std::chrono::duration<long double>>(now - reference_) * speed_;
}
}
void Timer::worldStart_() {
for (auto *timer: Timer::timers_)
timer->applyWorldStart_();
}
void Timer::worldStop_() {
for (auto *timer: Timer::timers_)
timer->applyWorldStop_();
}
void Timer::addTimer_(Timer *timer) {
Timer::timers_.push_back(timer);
}
void Timer::deleteTimer_(Timer *timer) {
auto position = std::find(Timer::timers_.begin(), Timer::timers_.end(), timer);
if (position == Timer::timers_.end())
throw std::runtime_error("Timer not found in timers_ vector.");
Timer::timers_.erase(position);
}
std::chrono::steady_clock::time_point Timer::getReference_() {
return reference_;
}
std::vector<Timer *> Timer::timers_;
///
///
///
Time::Time()
: pause_(false),
elapsedTimeInPause_(0),
timeStep_(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(16))),
lag_(std::chrono::nanoseconds(0)),
deltaTime_(std::chrono::milliseconds(0)) {
}
void Time::update() {
std::chrono::high_resolution_clock::duration deltaTime = std::chrono::steady_clock::now() -
sinceWorldStartFrame.getReference_();
sinceWorldStartFrame.reset();
sinceWorldStartFrame.start();
lag_ += std::chrono::duration_cast<std::chrono::nanoseconds>(deltaTime);
}
bool Time::shouldUpdateLogic() {
if (lag_ >= timeStep_) {
lag_ -= timeStep_;
return true;
}
return false;
}
void Time::pause(bool b) {
pause_ = b;
if (b) {
startPause_ = std::chrono::steady_clock::now();
Timer::worldStop_();
} else {
elapsedTimeInPause_ += std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startPause_);
Timer::worldStart_();
}
}
bool Time::isPause() const {
return pause_;
}
void Time::endFrame() {
deltaTime_ = sinceWorldStartFrame.getDuration<std::chrono::milliseconds>();
}
std::chrono::milliseconds Time::getDeltaTime() {
return deltaTime_;
}
std::chrono::milliseconds Time::getTimeStep() {
return std::chrono::duration_cast<std::chrono::milliseconds>(timeStep_);
}
Time &Time::Get() {
if (!Time::instance_) {
Time::instance_ = std::make_unique<Time>();
}
return *Time::instance_;
}
std::unique_ptr<Time> Time::instance_ = nullptr;
bool Timer::debug_ = false;
time_t steady_clock_to_time_t(std::chrono::steady_clock::time_point const &t) {
return std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now() + std::chrono::duration_cast<std::chrono::system_clock::duration>(t - std::chrono::steady_clock::now()));
}
std::ostream &operator<<(std::ostream &os, Timer const &timer) {
os << std::boolalpha;
time_t timeCratedTimer = steady_clock_to_time_t(timer.timePointTimerCreated_);
time_t timeReferenceTimer = steady_clock_to_time_t(timer.reference_);
#ifdef __APPLE__
std::string strTimeCreatedTimer(std::ctime(&timeCratedTimer));
strTimeCreatedTimer.erase(std::remove(strTimeCreatedTimer.begin(), strTimeCreatedTimer.end(), '\n'), strTimeCreatedTimer.end());
std::string strTimeReferenceTimer(std::ctime(&timeReferenceTimer));
strTimeReferenceTimer.erase(std::remove(strTimeReferenceTimer.begin(), strTimeReferenceTimer.end(), '\n'), strTimeReferenceTimer.end());
#endif
os << "Timer {";
os << "World pause [" << Time::Get().isPause() << "]," << std::endl;
#ifdef __APPLE__
os << "Timer created at : [" << strTimeCreatedTimer << "]," << std::endl;
#endif
os << "Started_[" << timer.started_ << "]," << std::endl;
os << "paused_ [" << timer.paused_ << "], " << std::endl;
#ifdef __APPLE__
os << "reference_ [" << strTimeReferenceTimer << "]," << std::endl;
#endif
os << "accumulated_ [ms:" << (std::chrono::duration_cast<std::chrono::milliseconds>(timer.accumulated_).count() / 1000.f) << "] }" << std::endl;
os << "Timer actual ms : [" << timer.count() << "]" << std::endl;
os << "Speed : [" << timer.speed_ << "]" << std::endl;
os << "}" << std::endl;
return os;
}
| 30.873786 | 148 | 0.631132 | [
"vector"
] |
2732d238091976859563e5f7a9a65e1a61bd46b9 | 3,611 | hpp | C++ | applications/CANDLE/pilot2/tools/common.hpp | jonesholger/lbann | 3214f189a1438565d695542e076c4fa8e7332d34 | [
"Apache-2.0"
] | 194 | 2016-07-19T15:40:21.000Z | 2022-03-19T08:06:10.000Z | applications/CANDLE/pilot2/tools/common.hpp | jonesholger/lbann | 3214f189a1438565d695542e076c4fa8e7332d34 | [
"Apache-2.0"
] | 1,021 | 2016-07-19T12:56:31.000Z | 2022-03-29T00:41:47.000Z | applications/CANDLE/pilot2/tools/common.hpp | jonesholger/lbann | 3214f189a1438565d695542e076c4fa8e7332d34 | [
"Apache-2.0"
] | 74 | 2016-07-28T18:24:00.000Z | 2022-01-24T19:41:04.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); you
// may not use this file except in compliance with the License. You may
// obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the license.
//
////////////////////////////////////////////////////////////////////////////////
#ifndef __PILOT2_TOOLS_COMMON_HPP_
#define __PILOT2_TOOLS_COMMON_HPP_
namespace lbann {
const int Num_beads = 184;
const int Dims = 3;
const int Word_size = 4;
const int Num_dist = 16836;
// 16836 is number of euclid distances
// for j in range(0, 183):
// for k in range(j+1, 184):
// t += 1
//=======================================================================
struct xyz {
xyz() {}
xyz(float xx, float yy, float zz) : x(xx), y(yy), z(zz) { }
float x;
float y;
float z;
float dist(const xyz &p) {
return sqrt(
(pow( (x-p.x), 2)
+ pow( (x-p.x), 2)
+ pow( (x-p.x), 2))
);
}
friend std::ostream& operator<<(std::ostream& os, const xyz& p);
};
std::ostream& operator<<(std::ostream& os, const xyz &p) {
os << p.x << "," << p.y << "," << p.z << " ";
return os;
}
//=======================================================================
//void testme();
bool sanity_check_npz_file(std::map<std::string, cnpy::NpyArray> &a, const std::string filename) {
const std::vector<size_t> shape = a["bbs"].shape;
const float num_samples = static_cast<float>(shape[0]);
const int word_size = static_cast<int>(a["bbs"].word_size);
bool is_good = true;
if (shape[1] != Num_beads || shape[2] != Dims || word_size != Word_size) {
is_good = false;
std::stringstream s3;
for (auto t : shape) { s3 << t << " "; }
LBANN_WARNING("Bad file: ", filename, " word_size: ", word_size, " dinum_samples: ", num_samples, " shape: ", s3.str());
}
return is_good;
}
void read_sample(
int id,
std::vector<float> &data,
std::vector<float> &z_coordinates,
std::vector<float> &distances) {
size_t offset = 2 /* n_frames, n_beads */ + id * (Num_beads + Num_dist);
z_coordinates.resize(Num_beads);
for (size_t j=offset; j < offset + Num_beads; j++) {
z_coordinates[j-offset] = data[j];
}
offset += Num_beads;
for (size_t j = offset; j < offset + Num_dist; j++) {
if (j >= data.size()) {
LBANN_ERROR("j >= data.size(); j: ",j, " datalsize: ", data.size(), " offset: ", offset, " Num_beads: ",Num_beads, " Num_dist: ", Num_dist);
}
if (j-offset >= distances.size()) {
LBANN_ERROR("j-offset >= data.size(); j-offset: ", j-offset, " data.size: ", data.size());
}
distances[j-offset] = data[j];
}
}
} //namespace lbann
#endif // __PILOT2_TOOLS_COMMON_HPP_
| 31.955752 | 146 | 0.580449 | [
"shape",
"vector"
] |
274afb2321cca759488e0917b30e525918fe895e | 19,000 | cpp | C++ | adapters/ns3/ns-allinone-3.26/ns-3.26/src/seed/model/seed-parser.cpp | kit-tm/seed | c6d4eaffbe25615b396aeabeae7305b724260d92 | [
"BSD-2-Clause"
] | null | null | null | adapters/ns3/ns-allinone-3.26/ns-3.26/src/seed/model/seed-parser.cpp | kit-tm/seed | c6d4eaffbe25615b396aeabeae7305b724260d92 | [
"BSD-2-Clause"
] | null | null | null | adapters/ns3/ns-allinone-3.26/ns-3.26/src/seed/model/seed-parser.cpp | kit-tm/seed | c6d4eaffbe25615b396aeabeae7305b724260d92 | [
"BSD-2-Clause"
] | null | null | null | #include "seed-parser.h"
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <map>
#include <unordered_map>
#include "seed-interface.h"
#include "seed-interface-group.h"
#include "seed-node-types.h"
#include "seed-node.h"
#include "seed-node-group.h"
#include "seed-link.h"
#include "seed-link-group.h"
#include "seed-event-types.h"
#include "seed-event.h"
#include "seed-event-traffic-bulk.h"
#include "seed-event-link-change.h"
using namespace seed;
// using namespace std;
using namespace rapidxml;
namespace seed
{
SeedParser::SeedParser(string fileName)
: fileName (fileName)
{}
unordered_map<string, SeedNode>&
SeedParser::getNodes()
{
return this->seedNodes;
}
unordered_map<string, SeedNodeGroup>&
SeedParser::getNodeGroups()
{
return this->seedNodeGroups;
}
unordered_map<string, SeedLink>&
SeedParser::getLinks()
{
return this->seedLinks;
}
unordered_map<string, SeedLinkGroup>&
SeedParser::getLinkGroups()
{
return this->seedLinkGroups;
}
// unordered_map<uint32_t, SeedInterface>&
// SeedParser::getInterfaces()
// {
// return this->seedInterfaces;
// }
unordered_map<string, SeedInterfaceGroup>&
SeedParser::getInterfaceGroups()
{
return this->seedInterfaceGroups;
}
vector<shared_ptr<SeedEvent>>&
SeedParser::getEvents()
{
return this->seedEvents;
}
void
SeedParser::parse()
{
this->initParse();
this->parseInterfaceGroups(this->rootNode);
this->parseLinkGroups(this->rootNode);
this->parseNodeGroups(this->rootNode);
this->parseNodes(this->rootNode);
this->parseSchedule(this->rootNode);
this->parseLinks(this->rootNode);
// this->parseInterfaces(this->rootNode);
}
void
SeedParser::initParse()
{
ifstream fin( this->fileName );
ostringstream sstr;
sstr << fin.rdbuf();
sstr.flush();
fin.close();
source = sstr.str();
rapidxml::xml_document<> doc;
doc.parse<0> (&source[0]);
// rapidxml::xml_node<> *rootNode = doc.first_node("bundle");
this->rootNode = doc.first_node("bundle");
if(!this->rootNode){
// TODO print to stderr
std::cout << "Error reading XML-File \"" << this->fileName << "\"" << std::endl;
std::cout << "Stop." << std::endl;
}
std::cout << std::endl;
string bundleName = this->getAttribute(this->rootNode, "name");
if(bundleName == ""){
std::cout << "Error: Bundle has no name" << std::endl;
}
std::cout << " ==> Initializing bundle \"" << bundleName << "\"" << std::endl;
std::cout << std::endl;
std::cout << "===============================================" << std::endl;
std::cout << "==> SEED: Parsing Bundle" << std::endl;
}
// TODO save params
// void SeedParser::parseParams(xml_node<> *rootNode)
// {
// //std::cout << "===============================================" << std::endl;
// //std::cout << "==> SEED: Parsing Parameters" << std::endl;
// // NS_LOG_INFO ("Parsing Parameters.");
// // for (xml_node<> * tmpNode = rootNode->first_node("parameters")->first_node("parameter"); tmpNode; tmpNode = tmpNode->next_sibling())
// // {
// // string key = tmpNode->first_attribute("name")->value();
// // string value = tmpNode->first_attribute("value")->value();
// // std::cout << " --> Creating Parameter \"" << key << "\" with value \"" << value << "\"" << std::endl;
// // }
// //std::cout << std::endl;
// }
void
SeedParser::parseNodeGroups(xml_node<> *rootNode)
{
for (xml_node<> * tmpNode = rootNode->first_node("topology")->first_node("nodegroups")->first_node("group"); tmpNode; tmpNode = tmpNode->next_sibling())
{
string tmpName = this->getAttribute(tmpNode, "name");
SeedNodeGroup sng = SeedNodeGroup(tmpName);
if (tmpNode->first_attribute("type"))
{
NodeType tmpNodeType = NodeType::HOST;
string tmpType = tmpNode->first_attribute("type")->value();
if(tmpType == "ofSwitch"){
tmpNodeType = NodeType::OF_SWITCH;
}else if(tmpType == "ofController"){
tmpNodeType = NodeType::OF_CONTROLLER;
}else if(tmpType == "genericSwitch"){
tmpNodeType = NodeType::GENERIC_SWITCH;
}else if(tmpType == "host"){
tmpNodeType = NodeType::HOST;
}else{
std::cout << "Error undefinded NodeGroup-Type \"" << tmpType << "\"" << std::endl;
std::cout << "Stop." << std::endl;
}
sng.setType(tmpNodeType);
}
//std::cout << "Parsed NodeGroup: " << sng.getName() << std::endl;
this->seedNodeGroups.insert(std::make_pair(tmpName, sng));
}
std::cout << " ==> " << this->seedNodeGroups.size() << " NodeGroups parsed" << std::endl;
}
void
SeedParser::parseNodes(xml_node<> *rootNode)
{
uint32_t index = 0;
for (xml_node<> * tmpNode = rootNode->first_node("topology")->first_node("nodes")->first_node("node"); tmpNode; tmpNode = tmpNode->next_sibling())
{
string tmpName = this->getAttribute(tmpNode, "name");
string tmpGroups = "";
if (tmpNode->first_attribute("groups"))
{
tmpGroups = tmpNode->first_attribute("groups")->value();
}
NodeType tmpNodeType = NodeType::HOST;
if (tmpNode->first_attribute("type"))
{
string tmpType = tmpNode->first_attribute("type")->value();
if(tmpType == "ofSwitch"){
tmpNodeType = NodeType::OF_SWITCH;
}else if(tmpType == "ofController"){
tmpNodeType = NodeType::OF_CONTROLLER;
}else if(tmpType == "genericSwitch"){
tmpNodeType = NodeType::GENERIC_SWITCH;
}else{
tmpNodeType = NodeType::HOST;
}
}
// TODO:
// parse node's "groups"-attribute
std::string s = tmpGroups;
for(auto const &it : split(tmpGroups, " "))
{
auto itAccess = this->seedNodeGroups.find(it);
if (itAccess != this->seedNodeGroups.end())
{
// node has group (which exists)
if(itAccess->second.getType() != NodeType::UNDEFINED)
{
tmpNodeType = itAccess->second.getType();
//std::cout << "true" << std::endl;
}
//std::cout << "node has existing group " << it << std::endl;
}
}
auto nodeCopy = tmpNode;
auto interfaces = this->parseInterfaces(nodeCopy);
// for(auto const& si : interfaces)
// {
// // auto si = &interfacesIt.second;
// // this->seedInterfaces.insert(std::make_pair(si->getName(), si));
// // cout << " ---> with Interface: " << si->getName() << endl;
// }
SeedNode sn = SeedNode(tmpName, tmpGroups, tmpNodeType);
sn.setInterfaces(interfaces);
if (tmpNode->first_attribute("pos-x"))
{
sn.setPosX( stod( tmpNode->first_attribute("pos-x")->value() ) );
}
if (tmpNode->first_attribute("pos-y"))
{
sn.setPosY( stod( tmpNode->first_attribute("pos-y")->value() ) );
}
string controllerName = this->getAttribute(tmpNode, "controller");
sn.setControllerName(controllerName);
this->seedNodes.insert(std::make_pair(tmpName, sn));
index++;
}
std::cout << " ==> " << this->seedNodes.size() << " Nodes parsed" << std::endl;
//std::cout << " ===> with " << this->seedInterfaces.size() << " Interfaces parsed" << std::endl;
}
void
SeedParser::parseLinkGroups(xml_node<> *rootNode)
{
for (xml_node<> * tmpNode = rootNode->first_node("topology")->first_node("linkgroups")->first_node("group"); tmpNode; tmpNode = tmpNode->next_sibling())
{
string tmpName = this->getAttribute(tmpNode, "name");
SeedLinkGroup sng = SeedLinkGroup(tmpName);
//std::cout << "Parsed LinkGroup: " << sng.getName() << std::endl;
this->seedLinkGroups.insert(std::make_pair(tmpName, sng));
}
std::cout << " ==> " << this->seedLinkGroups.size() << " LinkGroups parsed" << std::endl;
}
void
SeedParser::parseLinks(xml_node<> *rootNode)
{
for (xml_node<> * tmpNode = rootNode->first_node("topology")->first_node("links")->first_node("link"); tmpNode; tmpNode = tmpNode->next_sibling())
{
string fooType = tmpNode->name();
// string tmpName = this->getAttribute(tmpNode, "name");
// std::cout << "blub: " << fooType << std::endl;
string tmpName = tmpNode->first_attribute("name")->value();
string tmpGroups = "";
if (tmpNode->first_attribute("groups"))
{
tmpGroups = tmpNode->first_attribute("groups")->value();
}
string source = "";
if (tmpNode->first_attribute("a"))
{
source = tmpNode->first_attribute("a")->value();
}
string destination = "";
if (tmpNode->first_attribute("b"))
{
destination = tmpNode->first_attribute("b")->value();
}
string bandwidth = "";
if (tmpNode->first_attribute("bandwidth"))
{
bandwidth = tmpNode->first_attribute("bandwidth")->value();
}
string delay = "";
if (tmpNode->first_attribute("delay"))
{
delay = tmpNode->first_attribute("delay")->value();
}
double errorRate = 0;
if (tmpNode->first_attribute("error-rate"))
{
errorRate = (double) (stod( tmpNode->first_attribute("error-rate")->value() ) / 100);
}
string state = "";
if (tmpNode->first_attribute("state"))
{
state = tmpNode->first_attribute("state")->value();
}
// TODO: inherit group-props
// // parse node's "groups"-attribute
// std::string s = tmpGroups;
// for(auto const &it : split(tmpGroups, " "))
// {
// auto itAccess = this->seedNodeGroups.find(it);
// if (itAccess != this->seedNodeGroups.end())
// {
// // node has group (which exists)
// if(itAccess->second.getType() != NodeType::UNDEFINED)
// {
// tmpNodeType = itAccess->second.getType();
// std::cout << "true" << std::endl;
// }
// std::cout << "node has existing group " << it << std::endl;
// }
// }
SeedLink sl = SeedLink(tmpName, tmpGroups, source, destination, bandwidth, delay, errorRate, state);
this->seedLinks.insert(std::make_pair(tmpName, sl));
}
std::cout << " ==> " << this->seedLinks.size() << " Links parsed" << std::endl;
}
vector<shared_ptr<SeedInterface>>
SeedParser::parseInterfaces(xml_node<> *rootNode)
{
vector<shared_ptr<SeedInterface>> nodesSeedInterfaces;
for (xml_node<> * tmpNode = rootNode->first_node("interface"); tmpNode; tmpNode = tmpNode->next_sibling())
{
string tmpName = this->getAttribute(tmpNode, "name");
string tmpGroups = "";
if (tmpNode->first_attribute("groups"))
{
tmpGroups = tmpNode->first_attribute("groups")->value();
}
string type = this->getAttribute(tmpNode, "type");
// SeedInterface si = SeedInterface(tmpName, tmpGroups);
// std::cout << "Parsed Interface: " << tmpName << " with group \"" << tmpGroups << "\"" << std::endl;
// nodesSeedInterfaces.insert(std::make_pair(tmpName, si));
shared_ptr<SeedInterface> interfacePtr(new SeedInterface(tmpName, tmpGroups));
interfacePtr->setType(type);
nodesSeedInterfaces.push_back( interfacePtr );
// nodesSeedInterfaces.push_back( si );
}
return nodesSeedInterfaces;
}
void
SeedParser::parseInterfaceGroups(xml_node<> *rootNode)
{
for (xml_node<> * tmpNode = rootNode->first_node("topology")->first_node("interfacegroups")->first_node("group"); tmpNode; tmpNode = tmpNode->next_sibling())
{
string tmpName = this->getAttribute(tmpNode, "name");
SeedInterfaceGroup sng = SeedInterfaceGroup(tmpName);
//std::cout << "Parsed InterfaceGroup: " << sng.getName() << std::endl;
this->seedInterfaceGroups.insert(std::make_pair(tmpName, sng));
}
std::cout << " ==> " << this->seedInterfaceGroups.size() << " InterfaceGroups parsed" << std::endl;
}
void
SeedParser::parseSchedule(xml_node<> *rootNode)
{
for (xml_node<> * tmpNode = rootNode->first_node("schedule")->first_node(); tmpNode; tmpNode = tmpNode->next_sibling())
{
string eventType = tmpNode->name();
double startTime = 0;
if(this->getAttribute(tmpNode, "start") != ""){
startTime = stod(this->getAttribute(tmpNode, "start"));
}
//std::cout << "eventType " << eventType << std::endl;
//std::cout << "event " << startTime << std::endl;
if(eventType == "bulk-event"){
//std::cout << "bulk event" << std::endl;
string source = tmpNode->first_attribute("source")->value();
string destination = tmpNode->first_attribute("destination")->value();
string sizeAsString = tmpNode->first_attribute("max-size")->value();
long size = 0;
SeedParser::parseSize(sizeAsString, size);
//std::cout << "a: " << sizeAsString << " b: " << size << std::endl;
shared_ptr<SeedBulkTrafficEvent> sbtePtr(new SeedBulkTrafficEvent(EventType::TRAFFIC_BULK, startTime, source, destination, size));
this->seedEvents.push_back( sbtePtr );
}else if(eventType == "link-state-change-event"){
//std::cout << "link event" << std::endl;
string link = tmpNode->first_attribute("link")->value();
string newStateString = tmpNode->first_attribute("state")->value();
bool newState = (newStateString == "on") ? true : false;
shared_ptr<SeedLinkChangeEvent> slcePtr(new SeedLinkChangeEvent(EventType::LINK_CHANGE_STATE, startTime, link, newState));
this->seedEvents.push_back( slcePtr );
}else{
// TODO error handling
std::cout << "Error: Unknown event-type!" << std::endl;
}
}
std::cout << " ==> " << this->seedEvents.size() << " events parsed" << std::endl;
}
vector<string>
SeedParser::split(const string& str, const string& delim)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
std::pair<std::string, std::string>
SeedParser::splitNumber(std::string str)
{
auto it = str.begin();
for (; it != str.end() && (('0' <= *it && *it <= '9') || *it == '.'); ++it);
return std::make_pair(std::string(str.begin(), it),
std::string(it, str.end()));
}
bool
SeedParser::parseSize(std::string size, long &res)
{
auto pair = SeedParser::splitNumber(size);
if (!(std::istringstream(pair.first) >> res))
return false;
if (pair.second == "Tbyte")
res *= (long) (1025*1024) * (long) (1024*1024);
else if (pair.second == "Gbyte")
res *= 1024*1024*1024;
else if (pair.second == "Mbyte")
res *= 1024*1024;
else if (pair.second == "Kbyte")
res *= 1024;
else if (pair.second == "byte")
res *= 1;
else return false;
return true;
}
std::string SeedParser::getAttribute(rapidxml::xml_node<>* node,
const std::string &name) {
rapidxml::xml_attribute<> *attr = node->first_attribute(name.c_str());
if(attr){
return attr->value();
}else{
return std::string();
}
}
}
| 38.934426 | 169 | 0.484842 | [
"vector"
] |
27591b45447f58860ffc1832ae5b11d353640311 | 452 | cpp | C++ | exercises/pascals-triangle/example.cpp | marko213/cpp | 871529cd9c10d7c9c0b52d7e35e10ef2b9b4758f | [
"MIT"
] | 1 | 2019-07-14T18:07:13.000Z | 2019-07-14T18:07:13.000Z | exercises/pascals-triangle/example.cpp | marko213/cpp | 871529cd9c10d7c9c0b52d7e35e10ef2b9b4758f | [
"MIT"
] | 4 | 2019-09-08T15:56:22.000Z | 2021-12-03T00:53:01.000Z | exercises/pascals-triangle/example.cpp | marko213/cpp | 871529cd9c10d7c9c0b52d7e35e10ef2b9b4758f | [
"MIT"
] | 1 | 2020-03-25T15:53:16.000Z | 2020-03-25T15:53:16.000Z | #include "pascals_triangle.h"
namespace pascals_triangle
{
std::vector<std::vector<int>> generate_rows(size_t n)
{
std::vector<std::vector<int>> res;
for (size_t i = 0; i < n; i++)
{
std::vector<int> rowNum;
int val = 1;
for (size_t k = 0; k <= i; k++)
{
rowNum.push_back(val);
val = val * (i - k) / (k + 1);
}
res.push_back(rowNum);
}
return res;
}
}
| 15.586207 | 53 | 0.49115 | [
"vector"
] |
2763aa6e036be7f720a8a71f9882e1a7bc6408b8 | 1,390 | cpp | C++ | cpp/dataStructure/segment/knightTournament.cpp | HieuuuLeee/WorldFinal | ea1b1e697e6e7987018a5a79402d1a2659270591 | [
"MIT"
] | null | null | null | cpp/dataStructure/segment/knightTournament.cpp | HieuuuLeee/WorldFinal | ea1b1e697e6e7987018a5a79402d1a2659270591 | [
"MIT"
] | null | null | null | cpp/dataStructure/segment/knightTournament.cpp | HieuuuLeee/WorldFinal | ea1b1e697e6e7987018a5a79402d1a2659270591 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define pf push_front
#define pp push
#define et empty
#define mp make_pair
#define For(i,a,b) for (int i=a;i<=b;i++)
#define Fod(i,b,a) for (int i=b;i>=a;i--)
#define Forl(i,a,b) for (ll i=a;i<=b;i++)
#define Fodl(i,b,a) for (ll i=b;i>=a;i--)
typedef int64_t ll;
typedef uint64_t ull;
#define prno cout<<"NO\n"
#define pryes cout<<"YES\n"
#define pryon pryes; else prno;
#define brln cout << "\n";
#define el "\n"
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define bitcount(n) __builtin_popcountll(n)
#define INFILE(name) freopen(name, "r", stdin)
#define OUFILE(name) freopen(name, "w", stdout)
const int inf = 1e6+5;
int a[inf],n,t;
vector<int> st (2000001,1);
int update(int n,int l,int r,int ql,int qr,int v){
if(st[n]==0) return 0;
if(l>qr||r<ql) return st[n];
if(l==r && l<=qr && l>=ql){
if(l==v)return st[n]=1;
else{
a[l]=v;
return st[n]=0;
}
}
return st[n]=update(n*2,l,(l+r)/2,ql,qr,v) | update(n*2+1,(l+r)/2+1,r,ql,qr,v);
}
int main(){
cin>>n>>t;
// int tmp = build(1,1,n);
while(t--){
int x,y,z;
cin>>x>>y>>z;
update(1,1,n,x,y,z);
}
For(i,1,n) cout<<a[i]<<" ";
} | 23.559322 | 80 | 0.543165 | [
"vector"
] |
27653af32a4ea1cf59a80d42962431ac83b5da40 | 9,305 | cpp | C++ | WechatExporter/core/AsyncTask.cpp | Fu-XDU/WechatExporter | eebb7375712ed5f9708348aa3205466451e5c6de | [
"Apache-2.0"
] | 1,469 | 2020-11-17T06:53:15.000Z | 2022-03-31T08:53:02.000Z | WechatExporter/core/AsyncTask.cpp | Fu-XDU/WechatExporter | eebb7375712ed5f9708348aa3205466451e5c6de | [
"Apache-2.0"
] | 80 | 2020-12-13T16:07:03.000Z | 2022-03-31T01:20:40.000Z | WechatExporter/core/AsyncTask.cpp | Fu-XDU/WechatExporter | eebb7375712ed5f9708348aa3205466451e5c6de | [
"Apache-2.0"
] | 201 | 2020-11-17T06:53:16.000Z | 2022-03-29T02:04:53.000Z | //
// AsyncTask.cpp
// WechatExporter
//
// Created by Matthew on 2021/4/20.
// Copyright © 2021 Matthew. All rights reserved.
//
#include "AsyncTask.h"
#include <curl/curl.h>
#include <iostream>
#include <fstream>
#ifdef _WIN32
#include <atlstr.h>
#ifndef NDEBUG
#include <cassert>
#endif
#endif
#include "FileSystem.h"
#include "Utils.h"
// #define FAKE_DOWNLOAD
size_t writeHttpDataToBuffer(void *buffer, size_t size, size_t nmemb, void *user_p)
{
std::vector<unsigned char>* body = reinterpret_cast<std::vector<unsigned char> *>(user_p);
if (NULL != body)
{
size_t bytes = size * nmemb;
unsigned char *ptr = reinterpret_cast<unsigned char *>(buffer);
std::copy(ptr, ptr + bytes, back_inserter(*body));
return bytes;
}
return 0;
}
void DownloadTask::initialize()
{
curl_global_init(CURL_GLOBAL_ALL);
}
void DownloadTask::uninitialize()
{
curl_global_cleanup();
}
bool DownloadTask::httpGet(const std::string& url, const std::vector<std::pair<std::string, std::string>>& headers, long& httpStatus, std::vector<unsigned char>& body)
{
httpStatus = 0;
CURLcode res = CURLE_OK;
CURL *curl = NULL;
body.clear();
#ifndef FAKE_DOWNLOAD
// User-Agent: WeChat/7.0.15.33 CFNetwork/978.0.7 Darwin/18.6.0
curl = curl_easy_init();
#ifndef NDEBUG
struct curl_slist *host = NULL;
#endif
struct curl_slist *chunk = NULL;
for (std::vector<std::pair<std::string, std::string>>::const_iterator it = headers.cbegin(); it != headers.cend(); ++it)
{
if (it->first == "User-Agent")
{
curl_easy_setopt(curl, CURLOPT_USERAGENT, it->second.c_str());
}
#ifndef NDEBUG
else if (it->first == "RESOLVE")
{
host = curl_slist_append(host, it->second.c_str());
}
#endif
else
{
std::string header = it->first + ": " + it->second;
chunk = curl_slist_append(chunk, header.c_str());
}
}
#ifndef NDEBUG
if (NULL != host)
{
curl_easy_setopt(curl, CURLOPT_RESOLVE, host);
}
#endif
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
if (NULL != chunk)
{
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
}
// curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &::writeHttpDataToBuffer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void *>(&body));
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStatus);
// m_error = curl_easy_strerror(res);
}
curl_easy_cleanup(curl);
#ifndef NDEBUG
if (NULL != host)
{
curl_slist_free_all(host);
}
#endif
if (NULL != chunk)
{
curl_slist_free_all(chunk);
}
#endif // no FAKE_DOWNLOAD
return res == CURLE_OK;
}
size_t writeTaskHttpData(void *buffer, size_t size, size_t nmemb, void *user_p)
{
DownloadTask *task = reinterpret_cast<DownloadTask *>(user_p);
if (NULL != task)
{
return task->writeData(buffer, size, nmemb);
}
return 0;
}
DownloadTask::DownloadTask(const std::string &url, const std::string& output, const std::string& defaultFile, time_t mtime, const std::string& name/* = ""*/) : m_url(url), m_output(output), m_default(defaultFile), m_mtime(mtime), m_retries(0), m_name(name)
{
#ifndef NDEBUG
if (m_output.empty())
{
assert(false);
}
#endif
}
unsigned int DownloadTask::getRetries() const
{
return m_retries;
}
bool DownloadTask::run()
{
std::string* urls[] = { &m_url, &m_urlBackup };
for (int item = 0; item < sizeof(urls) / sizeof(std::string*); ++item)
{
if (urls[item]->empty())
{
continue;
}
for (int idx = 0; idx < DEFAULT_RETRIES; idx++)
{
if (downloadFile(*urls[item]))
{
return true;
}
}
if (startsWith(*urls[item], "http://"))
{
std::string url = *urls[item];
url.replace(0, 7, "https://");
if (downloadFile(url))
{
return true;
}
}
}
if (!m_default.empty())
{
if (copyFile(m_default, m_output))
{
return true;
}
else
{
m_error += "\r\nFailed to copy default file: " + m_default + " => " + m_output;
}
}
return false;
}
bool DownloadTask::downloadFile(const std::string& url)
{
++m_retries;
m_outputTmp = m_output + ".tmp";
deleteFile(m_outputTmp);
CURLcode res = CURLE_OK;
CURL *curl = NULL;
#ifndef NDEBUG
std::string logPath = m_output + ".http.log";
#ifdef _WIN32
CA2W pszW(logPath.c_str(), CP_UTF8);
FILE* logFile = _wfopen((LPCWSTR)pszW, L"wb");
#else
FILE* logFile = fopen(logPath.c_str(), "wb");
#endif
#endif
std::string userAgent = m_userAgent.empty() ? "WeChat/7.0.15.33 CFNetwork/978.0.7 Darwin/18.6.0" : m_userAgent;
#ifndef FAKE_DOWNLOAD
// User-Agent: WeChat/7.0.15.33 CFNetwork/978.0.7 Darwin/18.6.0
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str());
curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &::writeTaskHttpData);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
#ifndef NDEBUG
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_STDERR, logFile);
#endif
long httpStatus = 0;
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
m_error = "Failed " + m_name + "\r\n";
m_error += curl_easy_strerror(res);
if (m_retries >= DEFAULT_RETRIES)
{
fprintf(stderr, "%s: %s\n", m_error.c_str(), m_url.c_str());
}
}
else
{
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStatus);
#ifndef NDEBUG
char *lastUrl = NULL;
CURLcode res2 = curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &lastUrl);
if((CURLE_OK == res2) && lastUrl && m_url != lastUrl)
{
m_error += " \r\nRedirect: ";
m_error += lastUrl;
}
#endif
}
curl_easy_cleanup(curl);
#endif // no FAKE_DOWNLOAD
#ifndef NDEBUG
if (NULL != logFile)
{
fclose(logFile);
}
#endif
if (res == CURLE_OK && httpStatus == 200)
{
::moveFile(m_outputTmp, m_output);
if (m_mtime > 0)
{
updateFileTime(m_output, m_mtime);
}
#ifndef NDEBUG
::deleteFile(logPath);
#endif
return true;
}
if (m_error.empty())
{
m_error = "HTTP Status:" + std::to_string(httpStatus);
}
return false;
}
size_t DownloadTask::writeData(void *buffer, size_t size, size_t nmemb)
{
size_t bytesToWrite = size * nmemb;
if (appendFile(m_outputTmp, reinterpret_cast<const unsigned char *>(buffer), bytesToWrite))
{
return bytesToWrite;
}
return 0;
}
CopyTask::CopyTask(const std::string &src, const std::string& dest, const std::string& name) : m_src(src), m_dest(dest), m_name(name)
{
}
bool CopyTask::run()
{
if (::copyFile(m_src, m_dest))
{
return true;
}
if (!existsFile(m_src))
{
m_error = "Failed CP: " + m_src + "(not existed) => " + m_dest;
}
else
{
m_error = "Failed CP: " + m_src + " => " + m_dest;
#ifdef _WIN32
DWORD lastError = ::GetLastError();
m_error += "LastError:" + std::to_string(lastError);
#endif
}
return false;
}
Mp3Task::Mp3Task(const std::string &pcm, const std::string& mp3, unsigned int mtime) : m_pcm(pcm), m_mp3(mp3), m_mtime(mtime)
{
}
void Mp3Task::swapBuffer(std::vector<unsigned char>& buffer)
{
m_pcmData.swap(buffer);
}
bool Mp3Task::run()
{
std::vector<unsigned char> pcmData;
if (silkToPcm(m_pcm, pcmData) && !pcmData.empty())
{
if (pcmToMp3(pcmData, m_mp3))
{
updateFileTime(m_mp3, m_mtime);
// std::this_thread::sleep_for(std::chrono::milliseconds(192));
return true;
}
else
{
m_error = "Failed pcmToMp3: " + m_pcm + " => " + m_mp3;
}
}
else
{
m_error = "Failed silkTpPcm: " + m_pcm;
}
return false;
}
PdfTask::PdfTask(PdfConverter* pdfConveter, const std::string &src, const std::string& dest, const std::string& name) : m_pdfConverter(pdfConveter), m_src(src), m_dest(dest), m_name(name)
{
}
bool PdfTask::run()
{
return m_pdfConverter->convert(m_src, m_dest);
}
| 25.148649 | 256 | 0.603009 | [
"vector"
] |
276a99369e04064c25003045d45b621108b640d5 | 11,160 | cpp | C++ | NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/RVUPHistogramFeature.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/RVUPHistogramFeature.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | null | null | null | NFIQ2/NFIQ2/NFIQ2Algorithm/src/features/RVUPHistogramFeature.cpp | mahizhvannan/PYNFIQ2 | 56eac2d780c9b5becd0ca600ffa6198d3a0115a7 | [
"MIT"
] | 1 | 2022-02-14T03:16:05.000Z | 2022-02-14T03:16:05.000Z | #include "RVUPHistogramFeature.h"
#include "FeatureFunctions.h"
#include "include/NFIQException.h"
#include "include/Timer.hpp"
#include <sstream>
#include <opencv2/core/core.hpp>
#if defined WINDOWS || defined WIN32
#include <windows.h>
#include <float.h>
#define isnan _isnan // re-define isnan
#else
#ifndef isnan
#define isnan(x) ((x) != (x))
#endif
#endif
using namespace NFIQ;
using namespace cv;
void rvuhist(Mat block, const double orientation, const int v1sz_x, const int v1sz_y,
bool padFlag, std::vector<double>& ratios, std::vector<uint8_t>& Nans);
#define HISTOGRAM_FEATURES 1
RVUPHistogramFeature::~RVUPHistogramFeature()
{
}
std::list<NFIQ::QualityFeatureResult> RVUPHistogramFeature::computeFeatureData(
const NFIQ::FingerprintImageData & fingerprintImage)
{
std::list<NFIQ::QualityFeatureResult> featureDataList;
// check if input image has 500 dpi
if (fingerprintImage.m_ImageDPI != NFIQ::e_ImageResolution_500dpi)
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, "Only 500 dpi fingerprint images are supported!");
Mat img;
try
{
// get matrix from fingerprint image
img = Mat(fingerprintImage.m_ImageHeight, fingerprintImage.m_ImageWidth, CV_8UC1, (void*)fingerprintImage.data());
}
catch (cv::Exception & e)
{
std::stringstream ssErr;
ssErr << "Cannot get matrix from fingerprint image: " << e.what();
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, ssErr.str());
}
// ----------
// compute RVU
// ----------
NFIQ::Timer timerRVU;
double timeRVU = 0.0;
try
{
timerRVU.startTimer();
Mat maskim;
const int blksize = this->blocksize;
const int v1sz_x = this->slantedBlockSizeX;
const int v1sz_y = this->slantedBlockSizeY;
assert((blksize > 0) && (this->threshold > 0));
ridgesegment(img, blksize, this->threshold, noArray(), maskim, noArray());
int rows = img.rows;
int cols = img.cols;
double blk = static_cast<double>(blksize);
double sumSQ = static_cast<double>((v1sz_x*v1sz_x) + (v1sz_y*v1sz_y));
double eblksz = ceil(sqrt(sumSQ)); // block size for extraction of slanted block
double diff = (eblksz - blk);
int blkoffset = static_cast<int>(ceil(diff/2)); // overlapping border
int mapRows = static_cast<int>((static_cast<double>(rows) - diff)/blk);
int mapCols = static_cast<int>((static_cast<double>(cols) - diff)/blk);
Mat maskBseg = Mat::zeros(mapRows, mapCols, CV_8UC1);
Mat blkorient = Mat::zeros(mapRows, mapCols, CV_64F);
Mat im_roi, blkwim;
Mat maskB1;
double cova, covb, covc;
// Image processed NOT from beg to end but with a border around - can't be vectorized:(
int br = 0; int bc = 0;
std::vector<double>rvures;
std::vector<uint8_t> NanVec;
for (int r = blkoffset; r < rows-(blksize+blkoffset-1); r += blksize) {
for (int c = blkoffset; c < cols-(blksize+blkoffset-1); c += blksize) {
im_roi = img(Range(r, min(r+blksize, img.rows)),
Range(c, min(c+blksize, img.cols)));
maskB1 = maskim(Range(r, min(r+blksize, maskim.rows)),
Range(c, min(c+blksize, maskim.cols)));
maskBseg.at<uint8_t>(br,bc) = allfun(maskB1);
covcoef(im_roi, cova, covb, covc, CENTERED_DIFFERENCES);
// ridge ORIENT local
blkorient.at<double>(br,bc) = ridgeorient(cova, covb, covc);
// overlapping windows (border = blkoffset)
blkwim = img(Range(r-blkoffset, min(r+blksize+blkoffset, img.rows)),
Range(c-blkoffset, min(c+blksize+blkoffset, img.cols)));
if (maskBseg.at<uint8_t>(br,bc) == 1) {
rvuhist(blkwim, blkorient.at<double>(br,bc), v1sz_x, v1sz_y, this->padFlag,
rvures, NanVec);
}
bc = bc+1;
}
br = br+1; bc = 0;
}
// RIDGE-VALLEY UNIFORMITY
#if HISTOGRAM_FEATURES
std::vector<double> histogramBins10;
histogramBins10.push_back(RVUPHISTLIMITS[0]);
histogramBins10.push_back(RVUPHISTLIMITS[1]);
histogramBins10.push_back(RVUPHISTLIMITS[2]);
histogramBins10.push_back(RVUPHISTLIMITS[3]);
histogramBins10.push_back(RVUPHISTLIMITS[4]);
histogramBins10.push_back(RVUPHISTLIMITS[5]);
histogramBins10.push_back(RVUPHISTLIMITS[6]);
histogramBins10.push_back(RVUPHISTLIMITS[7]);
histogramBins10.push_back(RVUPHISTLIMITS[8]);
addHistogramFeatures(featureDataList, "RVUP_Bin10_", histogramBins10, rvures, 10);
#endif
timeRVU = timerRVU.endTimerAndGetElapsedTime();
if (m_bOutputSpeed)
{
NFIQ::QualityFeatureSpeed speed;
speed.featureIDGroup = "Ridge valley uniformity";
#if HISTOGRAM_FEATURES
addHistogramFeatureNames(speed.featureIDs, "RVUP_Bin10_", 10);
#endif
speed.featureSpeed = timeRVU;
m_lSpeedValues.push_back(speed);
}
}
catch (cv::Exception & e)
{
std::stringstream ssErr;
ssErr << "Cannot compute RVU: " << e.what();
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, ssErr.str());
}
catch (NFIQ::NFIQException & e)
{
throw e;
}
catch (...)
{
throw NFIQ::NFIQException(NFIQ::e_Error_FeatureCalculationError, "Unknown exception occurred!");
}
return featureDataList;
}
std::string RVUPHistogramFeature::getModuleID()
{
return "NFIQ2_RVUPHistogram";
}
std::list<std::string> RVUPHistogramFeature::getAllFeatureIDs()
{
std::list<std::string> featureIDs;
#if HISTOGRAM_FEATURES
addHistogramFeatureNames(featureIDs, "RVUP_Bin10_", 10);
#endif
return featureIDs;
}
///////////////////////////////////////////////////////////////////////
/***
function [ratios, blockRotated, blockCropped, v3, x, dt1, dt, ridval, change, ridvalComplete] = rvu(block, orientation, v1sz, scanResolution)
% RVU computes ridge/valley ratios for a given block.
%
% TODO: - code could be refactored
%
% Syntax: - ratios = rvu(block, orientation, v1sz, scanResolution)
%
% Inputs:
% block - square block of image (orientation block + border to fully cover rotated img)
% orientation - angle of the orientation line perpendicular to the ridge direction
% within the block [rad]
% v1sz - size of slanted square to extract from block [px] (recommended 32x16)
% scanResolution - scanner resolution [ppi]
%
% Outputs:
% ratios - local ratios (ridge/valley) of the ridge valley structure
%
% Examples:
% ratios = rvu([36 36], ang_in_deg, [32 16], 500);
%
% Code parts by Vladimir Smida.
%
% 2011 Biometric Systems, Kenneth Skovhus Andersen & Lasse Bach Nielsen
% The Technical University of Denmark, DTU
***/
void rvuhist(Mat block, const double orientation, const int v1sz_x, const int v1sz_y,
bool padFlag, std::vector<double>& rvures, std::vector<uint8_t>& NaNvec)
{
// sanity check: check block size
float cBlock = static_cast<float>(block.rows)/2; // square block
int icBlock = static_cast<int>(cBlock);
if (icBlock != cBlock) {
std::cerr << "block rows = " << block.rows << std::endl;
std::cerr << "warning: Wrong block size! Consider block with size of even number" << std::endl;
}
Mat blockRotated;
getRotatedBlock (block, orientation, padFlag, blockRotated);
//% set x and y
int xoff = v1sz_x/2;
int yoff = v1sz_y/2;
// extract slanted block by cropping the rotated image: To ensure that rotated image does
// not contain any invalid regions.
// Matlab: blockCropped = blockRotated(cBlock-(yoff-1):cBlock+yoff,cBlock-(xoff-1):cBlock+xoff); % v2
// Note: Matlab uses matrix indices starting at 1, OpenCV starts at 0. Also, OpenCV ranges
// are open-ended on the upper end.
Mat blockCropped = blockRotated(Range((icBlock-(yoff-1)-1), (icBlock+yoff)),
Range((icBlock-(xoff-1)-1),(icBlock+xoff))); // v2
std::vector<uint8_t> ridval;
std::vector<double> dt;
getRidgeValleyStructure(blockCropped, ridval, dt);
// Ridge-valley thickness
// change = xor(ridval,circshift(ridval,1)); // find the bin change
//change(1) = []; % there can't be change in 1. element (circshift)
//changeIndex = find(change == 1); % find indices where changes
std::vector<uint8_t> change;
int j;
for (int i = 0; i < ridval.size()-1; i++) {
// circular shift from back to front
if (i == 0) j = ridval.size()-1;
else j = i-1;
if (ridval[i] != ridval[j]) {
change.push_back(1);
}
else {
change.push_back(0);
}
}
std::vector<uint8_t> changeIndex;
for (int i = 1; i < change.size(); i++) { // skip the first element, same effect
// as "change(1) = []" in Matlab.
if(change[i] == 1) {
changeIndex.push_back(i-1);
}
}
// if ~isempty(changeIndex) ==> changes found = ridge-val structure
if (!changeIndex.empty()) {
//% non complete ridges/valleys are removed from ridval and changeIndex
// ridvalComplete = ridval(changeIndex(1)+1:changeIndex(end));
// That is, remove the first and last parts to remove incomplete ridges/valleys
// occurring at the border of the original block.
std::vector<uint8_t> ridvalComplete;
for (int i = changeIndex[0]+1; i < changeIndex[changeIndex.size()-1]; i++) {
ridvalComplete.push_back(ridval[i]);
}
// Likewise, remove corresponding changes from the change index vector.
// Matlab: changeIndexComplete = changeIndex - changeIndex(1);
// changeIndexComplete(1) = [];// % removing first value
std::vector<uint8_t> changeIndexComplete;
for (int i = 1; i < changeIndex.size(); i++) { // skip the first value
changeIndexComplete.push_back(changeIndex[i] - changeIndex[0]);
}
// if isempty(ridvalComplete)
//% not ridge/valley structure, skip computation
// return
// end;
if (ridvalComplete.empty())
{
return;
}
else
{
std::vector<double>ratios;
uint8_t begrid = ridvalComplete[0]; //% begining with ridge?
//% do the magic
//% changeIndex now represents the change values...
//changeIndexComplete(end:-1:2) = changeIndexComplete(end:-1:2)-changeIndexComplete(end-1:-1:1);
int changesize = changeIndexComplete.size();
// If there is only one change index at this point, then there aren't any ridge/valley structures
// to compare, so leave the ratios vector empty. (This is the same result that Matlab gives, even
// though it is handled differently, i.e., Matlab handles this edge case within the operations
// themselves, rather than testing the length of changeIndexComplete directly.
if (changesize > 1) {
std::vector<uint8_t> changeComplete2;
uint8_t tmpc;
for (int i = changesize-1; i > 0; i--) {
tmpc = changeIndexComplete[i] - changeIndexComplete[i-1];
changeComplete2.push_back(tmpc);
}
// for m=1:length(changeIndexComplete)-1,
// ratios(m) = changeIndexComplete(m)/changeIndexComplete(m+1);
// end;
double r;
for (int m=0; m < changeComplete2.size()-1; m++) {
r = static_cast<double>(changeComplete2[m])/static_cast<double>(changeComplete2[m+1]);
ratios.push_back(r);
//Create a mask vector that is a 1 if r is not a NaN, 0 if it is.
if (isnan(r))
NaNvec.push_back(0);
else
NaNvec.push_back(1);
}
// ratios(begrid+1:2:end) = 1 ./ ratios(begrid+1:2:end);
for (int i = begrid; i < ratios.size(); i+=2) {
ratios[i] = 1/ratios[i];
}
}
if (!ratios.empty()) {
for (int i = 0; i < ratios.size(); i++)
rvures.push_back(ratios[i]);
}
}
}
return;
}
| 32.727273 | 141 | 0.682796 | [
"vector"
] |
2776bb38d7f3cd09e58fc6ff5483e45c9730693a | 6,793 | cpp | C++ | Source/Atomic/Metrics/Metrics.cpp | phinoox/AtomicGameEngineExp | 3eb9e65e13ecf101e9fbfae8afd8517c524bd3c7 | [
"Apache-2.0",
"MIT"
] | null | null | null | Source/Atomic/Metrics/Metrics.cpp | phinoox/AtomicGameEngineExp | 3eb9e65e13ecf101e9fbfae8afd8517c524bd3c7 | [
"Apache-2.0",
"MIT"
] | 1 | 2017-02-05T16:54:00.000Z | 2017-02-05T16:54:00.000Z | Source/Atomic/Metrics/Metrics.cpp | phinoox/AtomicGameEngineExp | 3eb9e65e13ecf101e9fbfae8afd8517c524bd3c7 | [
"Apache-2.0",
"MIT"
] | null | null | null | //
// Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
//
// 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 "../IO/Log.h"
#include "../Metrics/Metrics.h"
#ifdef ATOMIC_PLATFORM_WEB
#include <stdio.h>
#include <stdlib.h>
#endif
namespace Atomic
{
Metrics* Metrics::metrics_ = 0;
bool Metrics::everEnabled_ = false;
bool MetricsSnapshot::CompareInstanceMetrics(const MetricsSnapshot::InstanceMetric& lhs, const MetricsSnapshot::InstanceMetric& rhs)
{
// TODO: Introduce various sorting modes, for now alphabetical is best "only" option
return lhs.classname < rhs.classname;
/*
if (lhs.count == rhs.count)
return lhs.classname < rhs.classname;
return lhs.count > rhs.count;
*/
}
void MetricsSnapshot::Clear()
{
instanceMetrics_.Clear();
nodeMetrics_.Clear();
resourceMetrics_.Clear();
}
String MetricsSnapshot::PrintData(unsigned columns, unsigned minCount)
{
String output;
Vector<MetricsSnapshot::InstanceMetric> instanceSort;
HashMap<StringHash, InstanceMetric>::ConstIterator instanceItr = instanceMetrics_.Begin();
while (instanceItr != instanceMetrics_.End())
{
instanceSort.Push(instanceItr->second_);
instanceItr++;
}
Sort(instanceSort.Begin(), instanceSort.End(), CompareInstanceMetrics);
Vector<MetricsSnapshot::InstanceMetric>::ConstIterator instanceSortItr = instanceSort.Begin();
static const int NAME_MAX_LENGTH = 20;
static const int ENTRY_MAX_LENGTH = 128;
char name[NAME_MAX_LENGTH];
char entry[ENTRY_MAX_LENGTH];
String line;
String header = "Class Total ( Native / JS / C# ) ";
for (unsigned i = 0; i < columns; i++)
output += header;
output += "\n\n";
unsigned column = 0;
while (instanceSortItr != instanceSort.End())
{
const InstanceMetric& metric = *instanceSortItr;
if (metric.count < minCount)
continue;
snprintf(name, NAME_MAX_LENGTH, "%-20s", metric.classname.CString());
// We use snprintf here as ToString doesn't seem to cover the unsigned %5u format
snprintf(entry, ENTRY_MAX_LENGTH, "%s : %5u ( %5u, %5u, %5u )", name , metric.count, metric.nativeInstances, metric.jsInstances, metric.netInstances);
if (columns == 1 || column == columns)
{
line += "\n";
output += line;
line.Clear();
column = 0;
}
line += String(entry);
column++;
line += " ";
instanceSortItr++;
}
if (line.Length())
output += line;
return output;
}
Metrics::Metrics(Context* context) :
Object(context),
enabled_(false)
{
Metrics::metrics_ = this;
}
Metrics::~Metrics()
{
Disable();
Metrics::metrics_ = 0;
}
void Metrics::CaptureInstances(MetricsSnapshot* snapshot)
{
PruneExpiredInstances();
const String unkClassName("-Unknown Class-");
for (unsigned i = 0; i < instances_.Size(); i++)
{
RefCounted* r = instances_[i];
const String& name = r->GetTypeName();
MetricsSnapshot::InstanceMetric& metric = snapshot->instanceMetrics_[name];
metric.classname = name;
metric.count++;
if (r->GetInstantiationType() == INSTANTIATION_NATIVE)
metric.nativeInstances++;
else if (r->GetInstantiationType() == INSTANTIATION_JAVASCRIPT)
metric.jsInstances++;
else if (r->GetInstantiationType() == INSTANTIATION_NET)
metric.netInstances++;
}
}
void Metrics::Capture(MetricsSnapshot* snapshot)
{
if (!enabled_)
{
ATOMIC_LOGERROR("Metrics::Capture - Metrics subsystem is not enabled");
return;
}
if (!snapshot)
return;
snapshot->Clear();
CaptureInstances(snapshot);
}
bool Metrics::Enable()
{
if (enabled_)
return false;
if (everEnabled_)
{
ATOMIC_LOGERROR("Metrics::Enable - Metrics subsystem is not designed to be restarted");
return false;
}
enabled_ = everEnabled_ = true;
RefCounted::AddRefCountedCreatedFunction(Metrics::OnRefCountedCreated);
RefCounted::AddRefCountedDeletedFunction(Metrics::OnRefCountedDeleted);
return true;
}
void Metrics::Disable()
{
if (!enabled_)
return;
enabled_ = false;
instances_.Clear();
RefCounted::RemoveRefCountedCreatedFunction(Metrics::OnRefCountedCreated);
RefCounted::RemoveRefCountedDeletedFunction(Metrics::OnRefCountedDeleted);
}
void Metrics::PruneExpiredInstances()
{
Vector<WeakPtr<RefCounted>> cinstances = instances_;
instances_.Clear();
for (unsigned i = 0; i < cinstances.Size(); i++)
{
if (!cinstances[i].Expired())
{
instances_.Push(cinstances[i]);
}
}
}
void Metrics::OnRefCountedCreated(RefCounted* refCounted)
{
if (!metrics_)
{
ATOMIC_LOGERROR("Metrics::OnRefCountedCreated - null instance");
return;
}
// We're called from the RefCounted constructor, so we don't know whether we're an object, etc
metrics_->instances_.Push(WeakPtr<RefCounted>(refCounted));
// prune expired whenever 8k boundry is crossed
if (!(metrics_->instances_.Size() % 8192))
{
metrics_->PruneExpiredInstances();
}
}
void Metrics::OnRefCountedDeleted(RefCounted* refCounted)
{
if (!metrics_)
{
ATOMIC_LOGERROR("Metrics::OnRefCountedDeleted - null instance");
return;
}
Vector<WeakPtr<RefCounted>>::Iterator itr = metrics_->instances_.Find(WeakPtr<RefCounted>(refCounted));
if (itr != metrics_->instances_.End())
{
metrics_->instances_.Erase(itr);
}
}
}
| 25.066421 | 158 | 0.656117 | [
"object",
"vector"
] |
27805eb321498ae3c07ede48a03348b7ecd292a4 | 348 | cpp | C++ | Bit Algorithm/Find Non-Repeated Element/SolutionByAbhay.cpp | rajethanm4/Programmers-Community | d16083eb0e84403159d999d4d1a8bbf652ca51f6 | [
"MIT"
] | 8 | 2020-11-07T10:29:21.000Z | 2020-12-26T16:54:13.000Z | Bit Algorithm/Find Non-Repeated Element/SolutionByAbhay.cpp | rajethanm4/Programmers-Community | d16083eb0e84403159d999d4d1a8bbf652ca51f6 | [
"MIT"
] | null | null | null | Bit Algorithm/Find Non-Repeated Element/SolutionByAbhay.cpp | rajethanm4/Programmers-Community | d16083eb0e84403159d999d4d1a8bbf652ca51f6 | [
"MIT"
] | 2 | 2019-12-18T13:06:19.000Z | 2021-01-05T18:47:18.000Z | #include <bits/stdc++.h>
using namespace std;
int nonRepeated(vector<int> &v){
int x=v[0];
for(int i=1;i<v.size();i++){
x^=v[i];
}
return x;
}
int main(int argc, char const *argv[])
{
int n;
cin>>n;
vector<int> v1(n);
for(int i=0;i<n;i++){
cin >> v1[i];
}
cout << "\nNon Repeated Element\t:\t" << nonRepeated(v1) <<endl;
return 0;
}
| 16.571429 | 65 | 0.577586 | [
"vector"
] |
95984235b7b38e7365b73b29a2c5d13eda443202 | 7,862 | cc | C++ | src/core/utils/json/webjson.cc | ilariom/wildcat | 814f054e0cf3ef0def1f6481005ffd3f0ac42d1b | [
"MIT"
] | 11 | 2018-11-07T08:54:21.000Z | 2022-02-20T22:40:47.000Z | src/core/utils/json/webjson.cc | ilariom/wildcat | 814f054e0cf3ef0def1f6481005ffd3f0ac42d1b | [
"MIT"
] | null | null | null | src/core/utils/json/webjson.cc | ilariom/wildcat | 814f054e0cf3ef0def1f6481005ffd3f0ac42d1b | [
"MIT"
] | 1 | 2020-07-24T09:18:48.000Z | 2020-07-24T09:18:48.000Z | #include "webjson.h"
#include "gason.h"
#include "webstrings.h"
#include <cstring>
#include <functional>
namespace webjson
{
namespace
{
Object buildObjects(JsonValue& jsonValue)
{
Object obj;
switch(jsonValue.getTag())
{
case JSON_NUMBER:
obj = jsonValue.toNumber();
break;
case JSON_STRING:
obj = jsonValue.toString();
break;
case JSON_ARRAY:
{
int k = 0;
for(auto i : jsonValue)
{
obj[k++] = buildObjects(i->value);
}
break;
}
case JSON_OBJECT:
{
for(auto i : jsonValue)
{
obj[i->key] = buildObjects(i->value);
}
break;
}
case JSON_TRUE:
obj = "true";
break;
case JSON_FALSE:
obj = "false";
break;
default:
case JSON_NULL:
break;
}
return obj;
};
}
Object parse(const std::string& text, std::string* error /* = nullptr */)
{
int N = static_cast<int>(text.size());
char source[N + 1];
strncpy(source, text.c_str(), N);
source[N] = '\0';
char* endptr;
JsonValue value;
JsonAllocator allocator;
int status = jsonParse(source, &endptr, &value, allocator);
if(status != JSON_OK)
{
if (error)
{
*error = jsonStrError(status);
}
return Object();
}
return buildObjects(value);
}
std::string stringify(const Object& json)
{
return json.toStyledString();
}
Object::Object(const Object& other)
{
this->objType = other.objType;
this->value = other.value;
for(auto p : other.omap)
this->omap[p.first] = std::make_shared<Object>(*p.second);
for(auto o : other.vect)
this->vect.push_back(std::make_shared<Object>(*o));
}
Object& Object::operator=(const Object& other)
{
this->objType = other.objType;
this->value = other.value;
for(auto p : other.omap)
this->omap[p.first] = std::make_shared<Object>(*p.second);
for(auto o : other.vect)
this->vect.push_back(std::make_shared<Object>(*o));
return *this;
}
Object& Object::operator[](const std::string& key)
{
setAsMap();
if(this->omap.find(key) == this->omap.end())
{
this->omap[key] = std::make_shared<Object>();
}
return *this->omap[key];
}
Object& Object::operator[](unsigned int index)
{
setAsArray();
while(index >= this->vect.size())
{
this->vect.push_back(std::make_shared<Object>());
}
return *this->vect[index];
}
const Object& Object::operator[](const std::string& key) const
{
return this->at(key);
}
const Object& Object::operator[](unsigned int index) const
{
return this->at(index);
}
const Object& Object::at(const std::string& key) const
{
Object& self = *(const_cast<Object*>(this));
return static_cast<const Object&>(self[key]);
}
const Object& Object::at(unsigned int index) const
{
Object& self = *(const_cast<Object*>(this));
return static_cast<const Object&>(self[index]);
}
bool Object::has(const std::string& key) const
{
if (!isMap())
{
return false;
}
return this->omap.find(key) != this->omap.end();
}
std::vector<std::string> Object::getKeys() const
{
if (!isMap())
{
return {};
}
std::vector<std::string> keys = {};
for (auto it = this->omap.cbegin(); it != this->omap.cend(); it++)
{
keys.push_back(it->first);
}
return keys;
}
void Object::push(const Object& obj)
{
setAsArray();
this->vect.push_back(std::make_shared<Object>(obj));
}
void Object::operator=(const std::string& value)
{
setAsValue(value);
}
void Object::operator=(float value)
{
setAsValue(webstrings::to_string(value));
}
std::string Object::asString() const
{
if(!isValue())
{
return "";
}
return this->value;
}
float Object::asNumber() const
{
if(!(isValue() && isNumber()))
{
return 0;
}
return webstrings::from_string<float>(this->value);
}
void Object::setAsMap()
{
if(isMap())
{
return;
}
if(isArray())
{
this->vect.clear();
}
setType(Type::MAP);
this->value = "";
}
void Object::setAsValue(const std::string& value)
{
if(isMap())
{
this->omap.clear();
}
if(isArray())
{
this->vect.clear();
}
setType(Type::VALUE);
this->value = value;
}
void Object::setAsArray()
{
if(isArray())
{
return;
}
if(isMap())
{
this->omap.clear();
}
setType(Type::ARRAY);
this->value = "";
}
bool Object::isNumber() const
{
return webstrings::is_number(this->value);
}
size_t Object::size() const
{
if(isEmpty())
{
return 0;
}
switch(type())
{
case Type::VALUE:
return 1;
case Type::ARRAY:
return this->vect.size();
case Type::MAP:
return this->omap.size();
default:
return 0;
}
}
std::string Object::toStyledString(const std::string& tabs) const
{
const std::string emptyObject = "{}";
const std::string emptyArray = "[]";
if(this->isEmpty())
{
return isArray() ? emptyArray : emptyObject;
}
if(isValue())
{
return std::move(asString());
}
auto wrapInQuotes = [] (const std::string& str) -> std::string {
std::string res;
res += "\"";
res += str;
res += "\"";
return res;
};
auto addTabs = [&tabs] (const std::string& str) -> std::string {
std::string res = tabs + "\t";
res += str;
return res;
};
auto buildRecursively = [&tabs, wrapInQuotes] (const Object& value, std::function<std::string(const std::string&)> addTabs = nullptr) {
addTabs = addTabs ? addTabs : [] (const std::string& s) { return s; };
std::string res;
if(value.isValue())
{
res = value.isNumber() ? value.asString() : wrapInQuotes(value.asString());
}
else
{
res = std::move(value.toStyledString(tabs + "\t"));
}
return addTabs(res);
};
if(isMap())
{
std::string res = "{\n";
for(auto it = this->omap.begin(); it != this->omap.end(); ++it)
{
if(it != this->omap.begin())
{
res += ",\n";
}
const std::string& key = it->first;
const Object& value = *it->second;
res += addTabs(wrapInQuotes(key));
res += ": ";
res += buildRecursively(value);
}
res += "\n" + tabs + "}";
return res;
}
if(isArray())
{
std::string res = "[\n";
for(auto it = this->vect.begin(); it != this->vect.end(); ++it)
{
if(it != this->vect.begin())
{
res += ",\n";
}
const Object& value = **it;
res += buildRecursively(value, addTabs);
}
res += "\n" + tabs + "]";
return res;
}
return emptyObject;
}
} // namespace json
| 19.803526 | 139 | 0.480158 | [
"object",
"vector"
] |
959cc526957fd621cbbabbcdf8a1f1db83506cf2 | 185,972 | cpp | C++ | singleheader/simdjson.cpp | easyaspi314/simdjson | 94bc1a5e67420ed5b5a543732d2cfb274f273f80 | [
"Apache-2.0"
] | null | null | null | singleheader/simdjson.cpp | easyaspi314/simdjson | 94bc1a5e67420ed5b5a543732d2cfb274f273f80 | [
"Apache-2.0"
] | null | null | null | singleheader/simdjson.cpp | easyaspi314/simdjson | 94bc1a5e67420ed5b5a543732d2cfb274f273f80 | [
"Apache-2.0"
] | null | null | null | /* auto-generated on Sun Oct 6 13:23:03 DST 2019. Do not edit! */
#include "simdjson.h"
/* used for http://dmalloc.com/ Dmalloc - Debug Malloc Library */
#ifdef DMALLOC
#include "dmalloc.h"
#endif
/* begin file src/simdjson.cpp */
#include <map>
namespace simdjson {
const std::map<int, const std::string> error_strings = {
{SUCCESS, "No errors"},
{CAPACITY, "This ParsedJson can't support a document that big"},
{MEMALLOC, "Error allocating memory, we're most likely out of memory"},
{TAPE_ERROR, "Something went wrong while writing to the tape"},
{STRING_ERROR, "Problem while parsing a string"},
{T_ATOM_ERROR,
"Problem while parsing an atom starting with the letter 't'"},
{F_ATOM_ERROR,
"Problem while parsing an atom starting with the letter 'f'"},
{N_ATOM_ERROR,
"Problem while parsing an atom starting with the letter 'n'"},
{NUMBER_ERROR, "Problem while parsing a number"},
{UTF8_ERROR, "The input is not valid UTF-8"},
{UNITIALIZED, "Unitialized"},
{EMPTY, "Empty"},
{UNESCAPED_CHARS, "Within strings, some characters must be escaped, we "
"found unescaped characters"},
{UNCLOSED_STRING, "A string is opened, but never closed."},
{UNEXPECTED_ERROR, "Unexpected error, consider reporting this problem as "
"you may have found a bug in simdjson"},
};
// string returned when the error code is not recognized
const std::string unexpected_error_msg {"Unexpected error"};
// returns a string matching the error code
const std::string &error_message(const int error_code) {
auto keyvalue = error_strings.find(error_code);
if(keyvalue == error_strings.end()) {
return unexpected_error_msg;
}
return keyvalue->second;
}
} // namespace simdjson
/* end file src/simdjson.cpp */
/* begin file src/jsonioutil.cpp */
#include <cstdlib>
#include <cstring>
namespace simdjson {
char *allocate_padded_buffer(size_t length) {
// we could do a simple malloc
// return (char *) malloc(length + SIMDJSON_PADDING);
// However, we might as well align to cache lines...
size_t totalpaddedlength = length + SIMDJSON_PADDING;
char *padded_buffer = aligned_malloc_char(64, totalpaddedlength);
return padded_buffer;
}
padded_string get_corpus(const std::string &filename) {
std::FILE *fp = std::fopen(filename.c_str(), "rb");
if (fp != nullptr) {
std::fseek(fp, 0, SEEK_END);
size_t len = std::ftell(fp);
padded_string s(len);
if (s.data() == nullptr) {
std::fclose(fp);
throw std::runtime_error("could not allocate memory");
}
std::rewind(fp);
size_t readb = std::fread(s.data(), 1, len, fp);
std::fclose(fp);
if (readb != len) {
throw std::runtime_error("could not read the data");
}
return s;
}
throw std::runtime_error("could not load corpus");
}
} // namespace simdjson
/* end file src/jsonioutil.cpp */
/* begin file src/jsonminifier.cpp */
#include <cstdint>
#ifndef __AVX2__
namespace simdjson {
static uint8_t jump_table[256 * 3] = {
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
};
size_t json_minify(const unsigned char *bytes, size_t how_many,
unsigned char *out) {
size_t i = 0, pos = 0;
uint8_t quote = 0;
uint8_t nonescape = 1;
while (i < how_many) {
unsigned char c = bytes[i];
uint8_t *meta = jump_table + 3 * c;
quote = quote ^ (meta[0] & nonescape);
out[pos] = c;
pos += meta[2] | quote;
i += 1;
nonescape = (~nonescape) | (meta[1]);
}
return pos;
}
} // namespace simdjson
#else
#include <cstring>
namespace simdjson {
// some intrinsics are missing under GCC?
#ifndef __clang__
#ifndef _MSC_VER
static __m256i inline _mm256_loadu2_m128i(__m128i const *__addr_hi,
__m128i const *__addr_lo) {
__m256i __v256 = _mm256_castsi128_si256(_mm_loadu_si128(__addr_lo));
return _mm256_insertf128_si256(__v256, _mm_loadu_si128(__addr_hi), 1);
}
static inline void _mm256_storeu2_m128i(__m128i *__addr_hi, __m128i *__addr_lo,
__m256i __a) {
__m128i __v128;
__v128 = _mm256_castsi256_si128(__a);
_mm_storeu_si128(__addr_lo, __v128);
__v128 = _mm256_extractf128_si256(__a, 1);
_mm_storeu_si128(__addr_hi, __v128);
}
#endif
#endif
// a straightforward comparison of a mask against input.
static uint64_t cmp_mask_against_input_mini(__m256i input_lo, __m256i input_hi,
__m256i mask) {
__m256i cmp_res_0 = _mm256_cmpeq_epi8(input_lo, mask);
uint64_t res_0 = static_cast<uint32_t>(_mm256_movemask_epi8(cmp_res_0));
__m256i cmp_res_1 = _mm256_cmpeq_epi8(input_hi, mask);
uint64_t res_1 = _mm256_movemask_epi8(cmp_res_1);
return res_0 | (res_1 << 32);
}
// take input from buf and remove useless whitespace, input and output can be
// the same, result is null terminated, return the string length (minus the null
// termination)
size_t json_minify(const uint8_t *buf, size_t len, uint8_t *out) {
// Useful constant masks
const uint64_t even_bits = 0x5555555555555555ULL;
const uint64_t odd_bits = ~even_bits;
uint8_t *initout(out);
uint64_t prev_iter_ends_odd_backslash =
0ULL; // either 0 or 1, but a 64-bit value
uint64_t prev_iter_inside_quote = 0ULL; // either all zeros or all ones
size_t idx = 0;
if (len >= 64) {
size_t avx_len = len - 63;
for (; idx < avx_len; idx += 64) {
__m256i input_lo =
_mm256_loadu_si256(reinterpret_cast<const __m256i *>(buf + idx + 0));
__m256i input_hi =
_mm256_loadu_si256(reinterpret_cast<const __m256i *>(buf + idx + 32));
uint64_t bs_bits = cmp_mask_against_input_mini(input_lo, input_hi,
_mm256_set1_epi8('\\'));
uint64_t start_edges = bs_bits & ~(bs_bits << 1);
uint64_t even_start_mask = even_bits ^ prev_iter_ends_odd_backslash;
uint64_t even_starts = start_edges & even_start_mask;
uint64_t odd_starts = start_edges & ~even_start_mask;
uint64_t even_carries = bs_bits + even_starts;
uint64_t odd_carries;
bool iter_ends_odd_backslash =
add_overflow(bs_bits, odd_starts, &odd_carries);
odd_carries |= prev_iter_ends_odd_backslash;
prev_iter_ends_odd_backslash = iter_ends_odd_backslash ? 0x1ULL : 0x0ULL;
uint64_t even_carry_ends = even_carries & ~bs_bits;
uint64_t odd_carry_ends = odd_carries & ~bs_bits;
uint64_t even_start_odd_end = even_carry_ends & odd_bits;
uint64_t odd_start_even_end = odd_carry_ends & even_bits;
uint64_t odd_ends = even_start_odd_end | odd_start_even_end;
uint64_t quote_bits = cmp_mask_against_input_mini(input_lo, input_hi,
_mm256_set1_epi8('"'));
quote_bits = quote_bits & ~odd_ends;
uint64_t quote_mask = _mm_cvtsi128_si64(_mm_clmulepi64_si128(
_mm_set_epi64x(0ULL, quote_bits), _mm_set1_epi8(0xFF), 0));
quote_mask ^= prev_iter_inside_quote;
prev_iter_inside_quote = static_cast<uint64_t>(
static_cast<int64_t>(quote_mask) >>
63); // might be undefined behavior, should be fully defined in C++20,
// ok according to John Regher from Utah University
const __m256i low_nibble_mask = _mm256_setr_epi8(
// 0 9 a b c d
16, 0, 0, 0, 0, 0, 0, 0, 0, 8, 12, 1, 2, 9, 0, 0, 16, 0, 0, 0, 0, 0,
0, 0, 0, 8, 12, 1, 2, 9, 0, 0);
const __m256i high_nibble_mask = _mm256_setr_epi8(
// 0 2 3 5 7
8, 0, 18, 4, 0, 1, 0, 1, 0, 0, 0, 3, 2, 1, 0, 0, 8, 0, 18, 4, 0, 1, 0,
1, 0, 0, 0, 3, 2, 1, 0, 0);
__m256i whitespace_shufti_mask = _mm256_set1_epi8(0x18);
__m256i v_lo = _mm256_and_si256(
_mm256_shuffle_epi8(low_nibble_mask, input_lo),
_mm256_shuffle_epi8(high_nibble_mask,
_mm256_and_si256(_mm256_srli_epi32(input_lo, 4),
_mm256_set1_epi8(0x7f))));
__m256i v_hi = _mm256_and_si256(
_mm256_shuffle_epi8(low_nibble_mask, input_hi),
_mm256_shuffle_epi8(high_nibble_mask,
_mm256_and_si256(_mm256_srli_epi32(input_hi, 4),
_mm256_set1_epi8(0x7f))));
__m256i tmp_ws_lo = _mm256_cmpeq_epi8(
_mm256_and_si256(v_lo, whitespace_shufti_mask), _mm256_set1_epi8(0));
__m256i tmp_ws_hi = _mm256_cmpeq_epi8(
_mm256_and_si256(v_hi, whitespace_shufti_mask), _mm256_set1_epi8(0));
uint64_t ws_res_0 =
static_cast<uint32_t>(_mm256_movemask_epi8(tmp_ws_lo));
uint64_t ws_res_1 = _mm256_movemask_epi8(tmp_ws_hi);
uint64_t whitespace = ~(ws_res_0 | (ws_res_1 << 32));
whitespace &= ~quote_mask;
int mask1 = whitespace & 0xFFFF;
int mask2 = (whitespace >> 16) & 0xFFFF;
int mask3 = (whitespace >> 32) & 0xFFFF;
int mask4 = (whitespace >> 48) & 0xFFFF;
int pop1 = hamming((~whitespace) & 0xFFFF);
int pop2 = hamming((~whitespace) & UINT64_C(0xFFFFFFFF));
int pop3 = hamming((~whitespace) & UINT64_C(0xFFFFFFFFFFFF));
int pop4 = hamming((~whitespace));
__m256i vmask1 = _mm256_loadu2_m128i(
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask2 & 0x7FFF),
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask1 & 0x7FFF));
__m256i vmask2 = _mm256_loadu2_m128i(
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask4 & 0x7FFF),
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask3 & 0x7FFF));
__m256i result1 = _mm256_shuffle_epi8(input_lo, vmask1);
__m256i result2 = _mm256_shuffle_epi8(input_hi, vmask2);
_mm256_storeu2_m128i(reinterpret_cast<__m128i *>(out + pop1),
reinterpret_cast<__m128i *>(out), result1);
_mm256_storeu2_m128i(reinterpret_cast<__m128i *>(out + pop3),
reinterpret_cast<__m128i *>(out + pop2), result2);
out += pop4;
}
}
// we finish off the job... copying and pasting the code is not ideal here,
// but it gets the job done.
if (idx < len) {
uint8_t buffer[64];
memset(buffer, 0, 64);
memcpy(buffer, buf + idx, len - idx);
__m256i input_lo =
_mm256_loadu_si256(reinterpret_cast<const __m256i *>(buffer));
__m256i input_hi =
_mm256_loadu_si256(reinterpret_cast<const __m256i *>(buffer + 32));
uint64_t bs_bits =
cmp_mask_against_input_mini(input_lo, input_hi, _mm256_set1_epi8('\\'));
uint64_t start_edges = bs_bits & ~(bs_bits << 1);
uint64_t even_start_mask = even_bits ^ prev_iter_ends_odd_backslash;
uint64_t even_starts = start_edges & even_start_mask;
uint64_t odd_starts = start_edges & ~even_start_mask;
uint64_t even_carries = bs_bits + even_starts;
uint64_t odd_carries;
// bool iter_ends_odd_backslash =
add_overflow(bs_bits, odd_starts, &odd_carries);
odd_carries |= prev_iter_ends_odd_backslash;
// prev_iter_ends_odd_backslash = iter_ends_odd_backslash ? 0x1ULL : 0x0ULL;
// // we never use it
uint64_t even_carry_ends = even_carries & ~bs_bits;
uint64_t odd_carry_ends = odd_carries & ~bs_bits;
uint64_t even_start_odd_end = even_carry_ends & odd_bits;
uint64_t odd_start_even_end = odd_carry_ends & even_bits;
uint64_t odd_ends = even_start_odd_end | odd_start_even_end;
uint64_t quote_bits =
cmp_mask_against_input_mini(input_lo, input_hi, _mm256_set1_epi8('"'));
quote_bits = quote_bits & ~odd_ends;
uint64_t quote_mask = _mm_cvtsi128_si64(_mm_clmulepi64_si128(
_mm_set_epi64x(0ULL, quote_bits), _mm_set1_epi8(0xFF), 0));
quote_mask ^= prev_iter_inside_quote;
// prev_iter_inside_quote = (uint64_t)((int64_t)quote_mask >> 63);// we
// don't need this anymore
__m256i mask_20 = _mm256_set1_epi8(0x20); // c==32
__m256i mask_70 =
_mm256_set1_epi8(0x70); // adding 0x70 does not check low 4-bits
// but moves any value >= 16 above 128
__m256i lut_cntrl = _mm256_setr_epi8(
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00,
0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00);
__m256i tmp_ws_lo = _mm256_or_si256(
_mm256_cmpeq_epi8(mask_20, input_lo),
_mm256_shuffle_epi8(lut_cntrl, _mm256_adds_epu8(mask_70, input_lo)));
__m256i tmp_ws_hi = _mm256_or_si256(
_mm256_cmpeq_epi8(mask_20, input_hi),
_mm256_shuffle_epi8(lut_cntrl, _mm256_adds_epu8(mask_70, input_hi)));
uint64_t ws_res_0 = static_cast<uint32_t>(_mm256_movemask_epi8(tmp_ws_lo));
uint64_t ws_res_1 = _mm256_movemask_epi8(tmp_ws_hi);
uint64_t whitespace = (ws_res_0 | (ws_res_1 << 32));
whitespace &= ~quote_mask;
if (len - idx < 64) {
whitespace |= UINT64_C(0xFFFFFFFFFFFFFFFF) << (len - idx);
}
int mask1 = whitespace & 0xFFFF;
int mask2 = (whitespace >> 16) & 0xFFFF;
int mask3 = (whitespace >> 32) & 0xFFFF;
int mask4 = (whitespace >> 48) & 0xFFFF;
int pop1 = hamming((~whitespace) & 0xFFFF);
int pop2 = hamming((~whitespace) & UINT64_C(0xFFFFFFFF));
int pop3 = hamming((~whitespace) & UINT64_C(0xFFFFFFFFFFFF));
int pop4 = hamming((~whitespace));
__m256i vmask1 = _mm256_loadu2_m128i(
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask2 & 0x7FFF),
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask1 & 0x7FFF));
__m256i vmask2 = _mm256_loadu2_m128i(
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask4 & 0x7FFF),
reinterpret_cast<const __m128i *>(mask128_epi8) + (mask3 & 0x7FFF));
__m256i result1 = _mm256_shuffle_epi8(input_lo, vmask1);
__m256i result2 = _mm256_shuffle_epi8(input_hi, vmask2);
_mm256_storeu2_m128i(reinterpret_cast<__m128i *>(buffer + pop1),
reinterpret_cast<__m128i *>(buffer), result1);
_mm256_storeu2_m128i(reinterpret_cast<__m128i *>(buffer + pop3),
reinterpret_cast<__m128i *>(buffer + pop2), result2);
memcpy(out, buffer, pop4);
out += pop4;
}
*out = '\0'; // NULL termination
return out - initout;
}
} // namespace simdjson
#endif
/* end file src/jsonminifier.cpp */
/* begin file src/jsonparser.cpp */
#include <atomic>
namespace simdjson {
// The function that users are expected to call is json_parse.
// We have more than one such function because we want to support several
// instruction sets.
// function pointer type for json_parse
using json_parse_functype = int(const uint8_t *buf, size_t len, ParsedJson &pj,
bool realloc);
// Pointer that holds the json_parse implementation corresponding to the
// available SIMD instruction set
extern std::atomic<json_parse_functype *> json_parse_ptr;
int json_parse(const uint8_t *buf, size_t len, ParsedJson &pj,
bool realloc) {
return json_parse_ptr.load(std::memory_order_relaxed)(buf, len, pj, realloc);
}
int json_parse(const char *buf, size_t len, ParsedJson &pj,
bool realloc) {
return json_parse_ptr.load(std::memory_order_relaxed)(reinterpret_cast<const uint8_t *>(buf), len, pj,
realloc);
}
Architecture find_best_supported_implementation() {
constexpr uint32_t haswell_flags =
instruction_set::AVX2 | instruction_set::PCLMULQDQ |
instruction_set::BMI1 | instruction_set::BMI2;
constexpr uint32_t westmere_flags =
instruction_set::SSE42 | instruction_set::PCLMULQDQ;
uint32_t supports = detect_supported_architectures();
// Order from best to worst (within architecture)
if ((haswell_flags & supports) == haswell_flags)
return Architecture::HASWELL;
if ((westmere_flags & supports) == westmere_flags)
return Architecture::WESTMERE;
if (instruction_set::NEON)
return Architecture::ARM64;
return Architecture::NONE;
}
// Responsible to select the best json_parse implementation
int json_parse_dispatch(const uint8_t *buf, size_t len, ParsedJson &pj,
bool realloc) {
Architecture best_implementation = find_best_supported_implementation();
// Selecting the best implementation
switch (best_implementation) {
#ifdef IS_X86_64
case Architecture::HASWELL:
json_parse_ptr.store(&json_parse_implementation<Architecture::HASWELL>, std::memory_order_relaxed);
break;
case Architecture::WESTMERE:
json_parse_ptr.store(&json_parse_implementation<Architecture::WESTMERE>, std::memory_order_relaxed);
break;
#endif
#ifdef IS_ARM64
case Architecture::ARM64:
json_parse_ptr.store(&json_parse_implementation<Architecture::ARM64>, std::memory_order_relaxed);
break;
#endif
default:
std::cerr << "The processor is not supported by simdjson." << std::endl;
return simdjson::UNEXPECTED_ERROR;
}
return json_parse_ptr.load(std::memory_order_relaxed)(buf, len, pj, realloc);
}
std::atomic<json_parse_functype *> json_parse_ptr = &json_parse_dispatch;
WARN_UNUSED
ParsedJson build_parsed_json(const uint8_t *buf, size_t len,
bool realloc) {
ParsedJson pj;
bool ok = pj.allocate_capacity(len);
if (ok) {
json_parse(buf, len, pj, realloc);
} else {
std::cerr << "failure during memory allocation " << std::endl;
}
return pj;
}
} // namespace simdjson
/* end file src/jsonparser.cpp */
/* begin file src/arm64/simd_input.h */
#ifndef SIMDJSON_ARM64_SIMD_INPUT_H
#define SIMDJSON_ARM64_SIMD_INPUT_H
#ifdef IS_ARM64
namespace simdjson::arm64 {
really_inline uint16_t neon_movemask(uint8x16_t input) {
const uint8x16_t bit_mask = {0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80,
0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
uint8x16_t minput = vandq_u8(input, bit_mask);
uint8x16_t tmp = vpaddq_u8(minput, minput);
tmp = vpaddq_u8(tmp, tmp);
tmp = vpaddq_u8(tmp, tmp);
return vgetq_lane_u16(vreinterpretq_u16_u8(tmp), 0);
}
really_inline uint64_t neon_movemask_bulk(uint8x16_t p0, uint8x16_t p1,
uint8x16_t p2, uint8x16_t p3) {
const uint8x16_t bit_mask = {0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80,
0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
uint8x16_t t0 = vandq_u8(p0, bit_mask);
uint8x16_t t1 = vandq_u8(p1, bit_mask);
uint8x16_t t2 = vandq_u8(p2, bit_mask);
uint8x16_t t3 = vandq_u8(p3, bit_mask);
uint8x16_t sum0 = vpaddq_u8(t0, t1);
uint8x16_t sum1 = vpaddq_u8(t2, t3);
sum0 = vpaddq_u8(sum0, sum1);
sum0 = vpaddq_u8(sum0, sum0);
return vgetq_lane_u64(vreinterpretq_u64_u8(sum0), 0);
}
struct simd_input {
const uint8x16_t chunks[4];
really_inline simd_input()
: chunks{uint8x16_t(), uint8x16_t(), uint8x16_t(), uint8x16_t() } {}
really_inline simd_input(const uint8x16_t chunk0, const uint8x16_t chunk1, const uint8x16_t chunk2, const uint8x16_t chunk3)
: chunks{chunk0, chunk1, chunk2, chunk3 } {}
really_inline simd_input(const uint8_t *ptr)
: chunks{
vld1q_u8(ptr + 0*16),
vld1q_u8(ptr + 1*16),
vld1q_u8(ptr + 2*16),
vld1q_u8(ptr + 3*16)
} {}
template <typename F>
really_inline void each(F const& each_chunk) const {
each_chunk(this->chunks[0]);
each_chunk(this->chunks[1]);
each_chunk(this->chunks[2]);
each_chunk(this->chunks[3]);
}
template <typename F>
really_inline simd_input map(F const& map_chunk) const {
return simd_input(
map_chunk(this->chunks[0]),
map_chunk(this->chunks[1]),
map_chunk(this->chunks[2]),
map_chunk(this->chunks[3])
);
}
template <typename F>
really_inline simd_input map(simd_input b, F const& map_chunk) const {
return simd_input(
map_chunk(this->chunks[0], b.chunks[0]),
map_chunk(this->chunks[1], b.chunks[1]),
map_chunk(this->chunks[2], b.chunks[2]),
map_chunk(this->chunks[3], b.chunks[3])
);
}
template <typename F>
really_inline uint8x16_t reduce(F const& reduce_pair) const {
uint8x16_t r01 = reduce_pair(this->chunks[0], this->chunks[1]);
uint8x16_t r23 = reduce_pair(this->chunks[2], this->chunks[3]);
return reduce_pair(r01, r23);
}
really_inline uint64_t to_bitmask() const {
return neon_movemask_bulk(this->chunks[0], this->chunks[1], this->chunks[2], this->chunks[3]);
}
really_inline simd_input bit_or(const uint8_t m) const {
const uint8x16_t mask = vmovq_n_u8(m);
return this->map( [&](auto a) {
return vorrq_u8(a, mask);
});
}
really_inline uint64_t eq(const uint8_t m) const {
const uint8x16_t mask = vmovq_n_u8(m);
return this->map( [&](auto a) {
return vceqq_u8(a, mask);
}).to_bitmask();
}
really_inline uint64_t lteq(const uint8_t m) const {
const uint8x16_t mask = vmovq_n_u8(m);
return this->map( [&](auto a) {
return vcleq_u8(a, mask);
}).to_bitmask();
}
}; // struct simd_input
} // namespace simdjson::arm64
#endif // IS_ARM64
#endif // SIMDJSON_ARM64_SIMD_INPUT_H
/* end file src/arm64/simd_input.h */
/* begin file src/haswell/simd_input.h */
#ifndef SIMDJSON_HASWELL_SIMD_INPUT_H
#define SIMDJSON_HASWELL_SIMD_INPUT_H
#ifdef IS_X86_64
TARGET_HASWELL
namespace simdjson::haswell {
struct simd_input {
const __m256i chunks[2];
really_inline simd_input() : chunks{__m256i(), __m256i()} {}
really_inline simd_input(const __m256i chunk0, const __m256i chunk1)
: chunks{chunk0, chunk1} {}
really_inline simd_input(const uint8_t *ptr)
: chunks{
_mm256_loadu_si256(reinterpret_cast<const __m256i *>(ptr + 0*32)),
_mm256_loadu_si256(reinterpret_cast<const __m256i *>(ptr + 1*32))
} {}
template <typename F>
really_inline void each(F const& each_chunk) const
{
each_chunk(this->chunks[0]);
each_chunk(this->chunks[1]);
}
template <typename F>
really_inline simd_input map(F const& map_chunk) const {
return simd_input(
map_chunk(this->chunks[0]),
map_chunk(this->chunks[1])
);
}
template <typename F>
really_inline simd_input map(const simd_input b, F const& map_chunk) const {
return simd_input(
map_chunk(this->chunks[0], b.chunks[0]),
map_chunk(this->chunks[1], b.chunks[1])
);
}
template <typename F>
really_inline __m256i reduce(F const& reduce_pair) const {
return reduce_pair(this->chunks[0], this->chunks[1]);
}
really_inline uint64_t to_bitmask() const {
uint64_t r_lo = static_cast<uint32_t>(_mm256_movemask_epi8(this->chunks[0]));
uint64_t r_hi = _mm256_movemask_epi8(this->chunks[1]);
return r_lo | (r_hi << 32);
}
really_inline simd_input bit_or(const uint8_t m) const {
const __m256i mask = _mm256_set1_epi8(m);
return this->map( [&](auto a) {
return _mm256_or_si256(a, mask);
});
}
really_inline uint64_t eq(const uint8_t m) const {
const __m256i mask = _mm256_set1_epi8(m);
return this->map( [&](auto a) {
return _mm256_cmpeq_epi8(a, mask);
}).to_bitmask();
}
really_inline uint64_t lteq(const uint8_t m) const {
const __m256i maxval = _mm256_set1_epi8(m);
return this->map( [&](auto a) {
return _mm256_cmpeq_epi8(_mm256_max_epu8(maxval, a), maxval);
}).to_bitmask();
}
}; // struct simd_input
} // namespace simdjson::haswell
UNTARGET_REGION
#endif // IS_X86_64
#endif // SIMDJSON_HASWELL_SIMD_INPUT_H
/* end file src/haswell/simd_input.h */
/* begin file src/westmere/simd_input.h */
#ifndef SIMDJSON_WESTMERE_SIMD_INPUT_H
#define SIMDJSON_WESTMERE_SIMD_INPUT_H
#ifdef IS_X86_64
TARGET_WESTMERE
namespace simdjson::westmere {
struct simd_input {
const __m128i chunks[4];
really_inline simd_input()
: chunks { __m128i(), __m128i(), __m128i(), __m128i() } {}
really_inline simd_input(const __m128i chunk0, const __m128i chunk1, const __m128i chunk2, const __m128i chunk3)
: chunks{chunk0, chunk1, chunk2, chunk3} {}
really_inline simd_input(const uint8_t *ptr)
: simd_input(
_mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr + 0)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr + 16)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr + 32)),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr + 48))
) {}
template <typename F>
really_inline void each(F const& each_chunk) const {
each_chunk(this->chunks[0]);
each_chunk(this->chunks[1]);
each_chunk(this->chunks[2]);
each_chunk(this->chunks[3]);
}
template <typename F>
really_inline simd_input map(F const& map_chunk) const {
return simd_input(
map_chunk(this->chunks[0]),
map_chunk(this->chunks[1]),
map_chunk(this->chunks[2]),
map_chunk(this->chunks[3])
);
}
template <typename F>
really_inline simd_input map(const simd_input b, F const& map_chunk) const {
return simd_input(
map_chunk(this->chunks[0], b.chunks[0]),
map_chunk(this->chunks[1], b.chunks[1]),
map_chunk(this->chunks[2], b.chunks[2]),
map_chunk(this->chunks[3], b.chunks[3])
);
}
template <typename F>
really_inline __m128i reduce(F const& reduce_pair) const {
__m128i r01 = reduce_pair(this->chunks[0], this->chunks[1]);
__m128i r23 = reduce_pair(this->chunks[2], this->chunks[3]);
return reduce_pair(r01, r23);
}
really_inline uint64_t to_bitmask() const {
uint64_t r0 = static_cast<uint32_t>(_mm_movemask_epi8(this->chunks[0]));
uint64_t r1 = _mm_movemask_epi8(this->chunks[1]);
uint64_t r2 = _mm_movemask_epi8(this->chunks[2]);
uint64_t r3 = _mm_movemask_epi8(this->chunks[3]);
return r0 | (r1 << 16) | (r2 << 32) | (r3 << 48);
}
really_inline simd_input bit_or(const uint8_t m) const {
const __m128i mask = _mm_set1_epi8(m);
return this->map( [&](auto a) {
return _mm_or_si128(a, mask);
});
}
really_inline uint64_t eq(const uint8_t m) const {
const __m128i mask = _mm_set1_epi8(m);
return this->map( [&](auto a) {
return _mm_cmpeq_epi8(a, mask);
}).to_bitmask();
}
really_inline uint64_t lteq(const uint8_t m) const {
const __m128i maxval = _mm_set1_epi8(m);
return this->map( [&](auto a) {
return _mm_cmpeq_epi8(_mm_max_epu8(maxval, a), maxval);
}).to_bitmask();
}
}; // struct simd_input
} // namespace simdjson::westmere
UNTARGET_REGION
#endif // IS_X86_64
#endif // SIMDJSON_WESTMERE_SIMD_INPUT_H
/* end file src/westmere/simd_input.h */
/* begin file src/arm64/simdutf8check.h */
// From https://github.com/cyb70289/utf8/blob/master/lemire-neon.c
// Adapted from https://github.com/lemire/fastvalidate-utf-8
#ifndef SIMDJSON_ARM64_SIMDUTF8CHECK_H
#define SIMDJSON_ARM64_SIMDUTF8CHECK_H
// TODO this is different from IS_ARM64 in portability.h, which we use in other places ...
#if defined(_ARM_NEON) || defined(__aarch64__) || \
(defined(_MSC_VER) && defined(_M_ARM64))
#include <arm_neon.h>
#include <cinttypes>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
/*
* legal utf-8 byte sequence
* http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf - page 94
*
* Code Points 1st 2s 3s 4s
* U+0000..U+007F 00..7F
* U+0080..U+07FF C2..DF 80..BF
* U+0800..U+0FFF E0 A0..BF 80..BF
* U+1000..U+CFFF E1..EC 80..BF 80..BF
* U+D000..U+D7FF ED 80..9F 80..BF
* U+E000..U+FFFF EE..EF 80..BF 80..BF
* U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
* U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
* U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
*
*/
namespace simdjson::arm64 {
static const int8_t _nibbles[] = {
1, 1, 1, 1, 1, 1, 1, 1, // 0xxx (ASCII)
0, 0, 0, 0, // 10xx (continuation)
2, 2, // 110x
3, // 1110
4, // 1111, next should be 0 (not checked here)
};
static const int8_t _initial_mins[] = {
-128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, // 10xx => false
(int8_t)0xC2, -128, // 110x
(int8_t)0xE1, // 1110
(int8_t)0xF1,
};
static const int8_t _second_mins[] = {
-128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, // 10xx => false
127, 127, // 110x => true
(int8_t)0xA0, // 1110
(int8_t)0x90,
};
struct processed_utf_bytes {
int8x16_t raw_bytes;
int8x16_t high_nibbles;
int8x16_t carried_continuations;
};
struct utf8_checker {
int8x16_t has_error{};
processed_utf_bytes previous{};
really_inline void add_errors(uint8x16_t errors) {
this->has_error = vorrq_s8(this->has_error, errors);
}
// all byte values must be no larger than 0xF4
really_inline void check_smaller_than_0xF4(int8x16_t current_bytes) {
// unsigned, saturates to 0 below max
this->has_error = vreinterpretq_s8_u8(vqsubq_u8(
vreinterpretq_u8_s8(current_bytes), vdupq_n_u8(0xF4)));
}
really_inline int8x16_t continuation_lengths(int8x16_t high_nibbles) {
return vqtbl1q_s8(vld1q_s8(_nibbles), vreinterpretq_u8_s8(high_nibbles));
}
really_inline int8x16_t carry_continuations(int8x16_t initial_lengths,
int8x16_t previous_carries) {
int8x16_t right1 = vreinterpretq_s8_u8(vqsubq_u8(
vreinterpretq_u8_s8(vextq_s8(previous_carries, initial_lengths, 16 - 1)),
vdupq_n_u8(1)));
int8x16_t sum = vaddq_s8(initial_lengths, right1);
int8x16_t right2 = vreinterpretq_s8_u8(
vqsubq_u8(vreinterpretq_u8_s8(vextq_s8(previous_carries, sum, 16 - 2)),
vdupq_n_u8(2)));
return vaddq_s8(sum, right2);
}
really_inline void check_continuations(int8x16_t initial_lengths,
int8x16_t carries) {
// overlap || underlap
// carry > length && length > 0 || !(carry > length) && !(length > 0)
// (carries > length) == (lengths > 0)
uint8x16_t overunder = vceqq_u8(vcgtq_s8(carries, initial_lengths),
vcgtq_s8(initial_lengths, vdupq_n_s8(0)));
this->add_errors( vreinterpretq_s8_u8(overunder) );
}
// when 0xED is found, next byte must be no larger than 0x9F
// when 0xF4 is found, next byte must be no larger than 0x8F
// next byte must be continuation, ie sign bit is set, so signed < is ok
really_inline void check_first_continuation_max(int8x16_t current_bytes,
int8x16_t off1_current_bytes) {
uint8x16_t maskED = vceqq_s8(off1_current_bytes, vdupq_n_s8(0xED));
uint8x16_t maskF4 = vceqq_s8(off1_current_bytes, vdupq_n_s8(0xF4));
uint8x16_t badfollowED =
vandq_u8(vcgtq_s8(current_bytes, vdupq_n_s8(0x9F)), maskED);
uint8x16_t badfollowF4 =
vandq_u8(vcgtq_s8(current_bytes, vdupq_n_s8(0x8F)), maskF4);
this->add_errors( vreinterpretq_s8_u8(vorrq_u8(badfollowED, badfollowF4)) );
}
// map off1_hibits => error condition
// hibits off1 cur
// C => < C2 && true
// E => < E1 && < A0
// F => < F1 && < 90
// else false && false
really_inline void check_overlong(int8x16_t current_bytes,
int8x16_t off1_current_bytes,
int8x16_t high_nibbles) {
int8x16_t off1_hibits = vextq_s8(this->previous.high_nibbles, high_nibbles, 16 - 1);
int8x16_t initial_mins =
vqtbl1q_s8(vld1q_s8(_initial_mins), vreinterpretq_u8_s8(off1_hibits));
uint8x16_t initial_under = vcgtq_s8(initial_mins, off1_current_bytes);
int8x16_t second_mins =
vqtbl1q_s8(vld1q_s8(_second_mins), vreinterpretq_u8_s8(off1_hibits));
uint8x16_t second_under = vcgtq_s8(second_mins, current_bytes);
this->add_errors( vreinterpretq_s8_u8(vandq_u8(initial_under, second_under)) );
}
really_inline void count_nibbles(int8x16_t bytes, struct processed_utf_bytes *answer) {
answer->raw_bytes = bytes;
answer->high_nibbles = vreinterpretq_s8_u8(vshrq_n_u8(vreinterpretq_u8_s8(bytes), 4));
}
// check whether the current bytes are valid UTF-8
// at the end of the function, previous gets updated
really_inline void check_utf8_bytes(int8x16_t current_bytes) {
struct processed_utf_bytes pb;
this->count_nibbles(current_bytes, &pb);
this->check_smaller_than_0xF4(current_bytes);
int8x16_t initial_lengths = this->continuation_lengths(pb.high_nibbles);
pb.carried_continuations = this->carry_continuations(initial_lengths);
this->check_continuations(initial_lengths, pb.carried_continuations);
int8x16_t off1_current_bytes =
vextq_s8(this->previous.raw_bytes, pb.raw_bytes, 16 - 1);
this->check_first_continuation_max(current_bytes, off1_current_bytes);
this->check_overlong(current_bytes, off1_current_bytes, pb.high_nibbles);
this->previous = pb;
}
// Checks that all bytes are ascii
really_inline bool check_ascii_neon(simd_input in) {
// checking if the most significant bit is always equal to 0.
uint8x16_t high_bit = vdupq_n_u8(0x80);
uint8x16_t any_bits_on = in.reduce([&](auto a, auto b) {
return vorrq_u8(a, b);
});
uint8x16_t high_bit_on = vandq_u8(any_bits_on, high_bit);
uint64x2_t v64 = vreinterpretq_u64_u8(high_bit_on);
uint32x2_t v32 = vqmovn_u64(v64);
uint64x1_t result = vreinterpret_u64_u32(v32);
return vget_lane_u64(result, 0) == 0;
}
really_inline void check_carried_continuations() {
const int8x16_t verror =
(int8x16_t){9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1};
this->add_errors(
vreinterpretq_s8_u8(vcgtq_s8(this->previous.carried_continuations, verror))
);
}
really_inline void check_next_input(uint8x16_t in) {
if (this->check_ascii_neon(in)) {
// All bytes are ascii. Therefore the byte that was just before must be
// ascii too. We only check the byte that was just before simd_input. Nines
// are arbitrary values.
this->check_carried_continuations();
} else {
// it is not ascii so we have to do heavy work
this->check_utf8_bytes(vreinterpretq_s8_u8(in));
}
}
really_inline void check_next_input(simd_input in) {
if (this->check_ascii_neon(in)) {
// All bytes are ascii. Therefore the byte that was just before must be
// ascii too. We only check the byte that was just before simd_input. Nines
// are arbitrary values.
this->check_carried_continuations();
} else {
// it is not ascii so we have to do heavy work
in.each([&](auto _in) { this->check_utf8_bytes(vreinterpretq_s8_u8(_in)); });
}
}
really_inline ErrorValues errors() {
uint64x2_t v64 = vreinterpretq_u64_s8(this->has_error);
uint32x2_t v32 = vqmovn_u64(v64);
uint64x1_t result = vreinterpret_u64_u32(v32);
return vget_lane_u64(result, 0) != 0 ? simdjson::UTF8_ERROR
: simdjson::SUCCESS;
}
}; // struct utf8_checker
} // namespace simdjson::arm64
#endif // ARM_NEON
#endif // SIMDJSON_ARM64_SIMDUTF8CHECK_H
/* end file src/arm64/simdutf8check.h */
/* begin file src/haswell/simdutf8check.h */
#ifndef SIMDJSON_HASWELL_SIMDUTF8CHECK_H
#define SIMDJSON_HASWELL_SIMDUTF8CHECK_H
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifdef IS_X86_64
/*
* legal utf-8 byte sequence
* http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf - page 94
*
* Code Points 1st 2s 3s 4s
* U+0000..U+007F 00..7F
* U+0080..U+07FF C2..DF 80..BF
* U+0800..U+0FFF E0 A0..BF 80..BF
* U+1000..U+CFFF E1..EC 80..BF 80..BF
* U+D000..U+D7FF ED 80..9F 80..BF
* U+E000..U+FFFF EE..EF 80..BF 80..BF
* U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
* U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
* U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
*
*/
// all byte values must be no larger than 0xF4
TARGET_HASWELL
namespace simdjson::haswell {
static inline __m256i push_last_byte_of_a_to_b(__m256i a, __m256i b) {
return _mm256_alignr_epi8(b, _mm256_permute2x128_si256(a, b, 0x21), 15);
}
static inline __m256i push_last_2bytes_of_a_to_b(__m256i a, __m256i b) {
return _mm256_alignr_epi8(b, _mm256_permute2x128_si256(a, b, 0x21), 14);
}
struct processed_utf_bytes {
__m256i raw_bytes;
__m256i high_nibbles;
__m256i carried_continuations;
};
struct utf8_checker {
__m256i has_error;
processed_utf_bytes previous;
utf8_checker() {
has_error = _mm256_setzero_si256();
previous.raw_bytes = _mm256_setzero_si256();
previous.high_nibbles = _mm256_setzero_si256();
previous.carried_continuations = _mm256_setzero_si256();
}
really_inline void add_errors(__m256i errors) {
this->has_error = _mm256_or_si256(this->has_error, errors);
}
// all byte values must be no larger than 0xF4
really_inline void check_smaller_than_0xF4(__m256i current_bytes) {
// unsigned, saturates to 0 below max
this->add_errors( _mm256_subs_epu8(current_bytes, _mm256_set1_epi8(0xF4u)) );
}
really_inline __m256i continuation_lengths(__m256i high_nibbles) {
return _mm256_shuffle_epi8(
_mm256_setr_epi8(1, 1, 1, 1, 1, 1, 1, 1, // 0xxx (ASCII)
0, 0, 0, 0, // 10xx (continuation)
2, 2, // 110x
3, // 1110
4, // 1111, next should be 0 (not checked here)
1, 1, 1, 1, 1, 1, 1, 1, // 0xxx (ASCII)
0, 0, 0, 0, // 10xx (continuation)
2, 2, // 110x
3, // 1110
4), // 1111, next should be 0 (not checked here)
high_nibbles);
}
really_inline __m256i carry_continuations(__m256i initial_lengths) {
__m256i right1 = _mm256_subs_epu8(
push_last_byte_of_a_to_b(this->previous.carried_continuations, initial_lengths),
_mm256_set1_epi8(1));
__m256i sum = _mm256_add_epi8(initial_lengths, right1);
__m256i right2 = _mm256_subs_epu8(
push_last_2bytes_of_a_to_b(this->previous.carried_continuations, sum), _mm256_set1_epi8(2));
return _mm256_add_epi8(sum, right2);
}
really_inline void check_continuations(__m256i initial_lengths,
__m256i carries) {
// overlap || underlap
// carry > length && length > 0 || !(carry > length) && !(length > 0)
// (carries > length) == (lengths > 0)
__m256i overunder = _mm256_cmpeq_epi8(
_mm256_cmpgt_epi8(carries, initial_lengths),
_mm256_cmpgt_epi8(initial_lengths, _mm256_setzero_si256()));
this->add_errors( overunder );
}
really_inline void check_carried_continuations() {
this->add_errors(
_mm256_cmpgt_epi8(this->previous.carried_continuations,
_mm256_setr_epi8(9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 1))
);
}
// when 0xED is found, next byte must be no larger than 0x9F
// when 0xF4 is found, next byte must be no larger than 0x8F
// next byte must be continuation, ie sign bit is set, so signed < is ok
really_inline void check_first_continuation_max(__m256i current_bytes,
__m256i off1_current_bytes) {
__m256i maskED =
_mm256_cmpeq_epi8(off1_current_bytes, _mm256_set1_epi8(0xEDu));
__m256i maskF4 =
_mm256_cmpeq_epi8(off1_current_bytes, _mm256_set1_epi8(0xF4u));
__m256i badfollowED = _mm256_and_si256(
_mm256_cmpgt_epi8(current_bytes, _mm256_set1_epi8(0x9Fu)), maskED);
__m256i badfollowF4 = _mm256_and_si256(
_mm256_cmpgt_epi8(current_bytes, _mm256_set1_epi8(0x8Fu)), maskF4);
this->add_errors( _mm256_or_si256(badfollowED, badfollowF4) );
}
// map off1_hibits => error condition
// hibits off1 cur
// C => < C2 && true
// E => < E1 && < A0
// F => < F1 && < 90
// else false && false
really_inline void check_overlong(__m256i current_bytes,
__m256i off1_current_bytes,
__m256i high_nibbles) {
__m256i off1_high_nibbles = push_last_byte_of_a_to_b(this->previous.high_nibbles, high_nibbles);
__m256i initial_mins = _mm256_shuffle_epi8(
_mm256_setr_epi8(-128, -128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, // 10xx => false
0xC2u, -128, // 110x
0xE1u, // 1110
0xF1u, // 1111
-128, -128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, // 10xx => false
0xC2u, -128, // 110x
0xE1u, // 1110
0xF1u), // 1111
off1_high_nibbles);
__m256i initial_under = _mm256_cmpgt_epi8(initial_mins, off1_current_bytes);
__m256i second_mins = _mm256_shuffle_epi8(
_mm256_setr_epi8(-128, -128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, // 10xx => false
127, 127, // 110x => true
0xA0u, // 1110
0x90u, // 1111
-128, -128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, // 10xx => false
127, 127, // 110x => true
0xA0u, // 1110
0x90u), // 1111
off1_high_nibbles);
__m256i second_under = _mm256_cmpgt_epi8(second_mins, current_bytes);
this->add_errors( _mm256_and_si256(initial_under, second_under) );
}
really_inline void count_nibbles(__m256i bytes, struct processed_utf_bytes *answer) {
answer->raw_bytes = bytes;
answer->high_nibbles = _mm256_and_si256(_mm256_srli_epi16(bytes, 4), _mm256_set1_epi8(0x0F));
}
// check whether the current bytes are valid UTF-8
// at the end of the function, previous gets updated
really_inline void check_utf8_bytes(__m256i current_bytes) {
struct processed_utf_bytes pb {};
this->count_nibbles(current_bytes, &pb);
this->check_smaller_than_0xF4(current_bytes);
__m256i initial_lengths = this->continuation_lengths(pb.high_nibbles);
pb.carried_continuations = this->carry_continuations(initial_lengths);
this->check_continuations(initial_lengths, pb.carried_continuations);
__m256i off1_current_bytes =
push_last_byte_of_a_to_b(this->previous.raw_bytes, pb.raw_bytes);
this->check_first_continuation_max(current_bytes, off1_current_bytes);
this->check_overlong(current_bytes, off1_current_bytes, pb.high_nibbles);
this->previous = pb;
}
really_inline void check_next_input(__m256i in) {
__m256i high_bit = _mm256_set1_epi8(0x80u);
if (likely(_mm256_testz_si256(in, high_bit) == 1)) {
this->check_carried_continuations();
} else {
this->check_utf8_bytes(in);
}
}
really_inline void check_next_input(simd_input in) {
__m256i high_bit = _mm256_set1_epi8(0x80u);
__m256i any_bits_on = in.reduce([&](auto a, auto b) {
return _mm256_or_si256(a, b);
});
if (likely(_mm256_testz_si256(any_bits_on, high_bit) == 1)) {
// it is ascii, we just check carried continuations.
this->check_carried_continuations();
} else {
// it is not ascii so we have to do heavy work
in.each([&](auto _in) { check_utf8_bytes(_in); });
}
}
really_inline ErrorValues errors() {
return _mm256_testz_si256(this->has_error, this->has_error) == 0
? simdjson::UTF8_ERROR
: simdjson::SUCCESS;
}
}; // struct utf8_checker
}; // namespace simdjson::haswell
UNTARGET_REGION // haswell
#endif // IS_X86_64
#endif // SIMDJSON_HASWELL_SIMDUTF8CHECK_H
/* end file src/haswell/simdutf8check.h */
/* begin file src/westmere/simdutf8check.h */
#ifndef SIMDJSON_WESTMERE_SIMDUTF8CHECK_H
#define SIMDJSON_WESTMERE_SIMDUTF8CHECK_H
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifdef IS_X86_64
/*
* legal utf-8 byte sequence
* http://www.unicode.org/versions/Unicode6.0.0/ch03.pdf - page 94
*
* Code Points 1st 2s 3s 4s
* U+0000..U+007F 00..7F
* U+0080..U+07FF C2..DF 80..BF
* U+0800..U+0FFF E0 A0..BF 80..BF
* U+1000..U+CFFF E1..EC 80..BF 80..BF
* U+D000..U+D7FF ED 80..9F 80..BF
* U+E000..U+FFFF EE..EF 80..BF 80..BF
* U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
* U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
* U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
*
*/
// all byte values must be no larger than 0xF4
/********** sse code **********/
TARGET_WESTMERE
namespace simdjson::westmere {
struct processed_utf_bytes {
__m128i raw_bytes;
__m128i high_nibbles;
__m128i carried_continuations;
};
struct utf8_checker {
__m128i has_error = _mm_setzero_si128();
processed_utf_bytes previous{
_mm_setzero_si128(), // raw_bytes
_mm_setzero_si128(), // high_nibbles
_mm_setzero_si128() // carried_continuations
};
really_inline void add_errors(__m128i errors) {
this->has_error = _mm_or_si128(errors, this->has_error);
}
// all byte values must be no larger than 0xF4
really_inline void check_smaller_than_0xF4(__m128i current_bytes) {
// unsigned, saturates to 0 below max
this->add_errors( _mm_subs_epu8(current_bytes, _mm_set1_epi8(0xF4u)) );
}
really_inline __m128i continuation_lengths(__m128i high_nibbles) {
return _mm_shuffle_epi8(
_mm_setr_epi8(1, 1, 1, 1, 1, 1, 1, 1, // 0xxx (ASCII)
0, 0, 0, 0, // 10xx (continuation)
2, 2, // 110x
3, // 1110
4), // 1111, next should be 0 (not checked here)
high_nibbles);
}
really_inline __m128i carry_continuations(__m128i initial_lengths) {
__m128i right1 =
_mm_subs_epu8(_mm_alignr_epi8(initial_lengths, this->previous.carried_continuations, 16 - 1),
_mm_set1_epi8(1));
__m128i sum = _mm_add_epi8(initial_lengths, right1);
__m128i right2 = _mm_subs_epu8(_mm_alignr_epi8(sum, this->previous.carried_continuations, 16 - 2),
_mm_set1_epi8(2));
return _mm_add_epi8(sum, right2);
}
really_inline void check_continuations(__m128i initial_lengths, __m128i carries) {
// overlap || underlap
// carry > length && length > 0 || !(carry > length) && !(length > 0)
// (carries > length) == (lengths > 0)
__m128i overunder =
_mm_cmpeq_epi8(_mm_cmpgt_epi8(carries, initial_lengths),
_mm_cmpgt_epi8(initial_lengths, _mm_setzero_si128()));
this->add_errors( overunder );
}
// when 0xED is found, next byte must be no larger than 0x9F
// when 0xF4 is found, next byte must be no larger than 0x8F
// next byte must be continuation, ie sign bit is set, so signed < is ok
really_inline void check_first_continuation_max(__m128i current_bytes, __m128i off1_current_bytes) {
__m128i maskED = _mm_cmpeq_epi8(off1_current_bytes, _mm_set1_epi8(0xEDu));
__m128i maskF4 = _mm_cmpeq_epi8(off1_current_bytes, _mm_set1_epi8(0xF4u));
__m128i badfollowED = _mm_and_si128(
_mm_cmpgt_epi8(current_bytes, _mm_set1_epi8(0x9Fu)), maskED);
__m128i badfollowF4 = _mm_and_si128(
_mm_cmpgt_epi8(current_bytes, _mm_set1_epi8(0x8Fu)), maskF4);
this->add_errors( _mm_or_si128(badfollowED, badfollowF4) );
}
// map off1_hibits => error condition
// hibits off1 cur
// C => < C2 && true
// E => < E1 && < A0
// F => < F1 && < 90
// else false && false
really_inline void check_overlong(__m128i current_bytes,
__m128i off1_current_bytes, __m128i high_nibbles) {
__m128i off1_hibits = _mm_alignr_epi8(high_nibbles, this->previous.high_nibbles, 16 - 1);
__m128i initial_mins = _mm_shuffle_epi8(
_mm_setr_epi8(-128, -128, -128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, // 10xx => false
0xC2u, -128, // 110x
0xE1u, // 1110
0xF1u),
off1_hibits);
__m128i initial_under = _mm_cmpgt_epi8(initial_mins, off1_current_bytes);
__m128i second_mins = _mm_shuffle_epi8(
_mm_setr_epi8(-128, -128, -128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, // 10xx => false
127, 127, // 110x => true
0xA0u, // 1110
0x90u),
off1_hibits);
__m128i second_under = _mm_cmpgt_epi8(second_mins, current_bytes);
this->add_errors( _mm_and_si128(initial_under, second_under) );
}
really_inline void count_nibbles(__m128i bytes, struct processed_utf_bytes *answer) {
answer->raw_bytes = bytes;
answer->high_nibbles = _mm_and_si128(_mm_srli_epi16(bytes, 4), _mm_set1_epi8(0x0F));
}
// check whether the current bytes are valid UTF-8
// at the end of the function, previous gets updated
really_inline void check_utf8_bytes(__m128i current_bytes) {
struct processed_utf_bytes pb;
this->count_nibbles(current_bytes, &pb);
this->check_smaller_than_0xF4(current_bytes);
__m128i initial_lengths = this->continuation_lengths(pb.high_nibbles);
pb.carried_continuations = this->carry_continuations(initial_lengths);
this->check_continuations(initial_lengths, pb.carried_continuations);
__m128i off1_current_bytes =
_mm_alignr_epi8(pb.raw_bytes, this->previous.raw_bytes, 16 - 1);
this->check_first_continuation_max(current_bytes, off1_current_bytes);
this->check_overlong(current_bytes, off1_current_bytes, pb.high_nibbles);
this->previous = pb;
}
really_inline void check_carried_continuations() {
this->has_error = _mm_cmpgt_epi8(this->previous.carried_continuations,
_mm_setr_epi8(9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 1));
}
really_inline void check_next_input(__m128i in) {
__m128i high_bit = _mm_set1_epi8(0x80u);
if (_mm_testz_si128( in, high_bit) == 1) {
// it is ascii, we just check continuations
this->check_carried_continuations();
} else {
// it is not ascii so we have to do heavy work
this->check_utf8_bytes(in);
}
}
really_inline void check_next_input(simd_input in) {
__m128i high_bit = _mm_set1_epi8(0x80u);
__m128i any_bits_on = in.reduce([&](auto a, auto b) {
return _mm_or_si128(a, b);
});
if (_mm_testz_si128(any_bits_on, high_bit) == 1) {
// it is ascii, we just check continuations
this->check_carried_continuations();
} else {
// it is not ascii so we have to do heavy work
in.each([&](auto _in) { this->check_utf8_bytes(_in); });
}
}
really_inline ErrorValues errors() {
return _mm_testz_si128(this->has_error, this->has_error) == 0
? simdjson::UTF8_ERROR
: simdjson::SUCCESS;
}
}; // struct utf8_checker
} // namespace simdjson::westmere
UNTARGET_REGION // westmere
#endif // IS_X86_64
#endif
/* end file src/westmere/simdutf8check.h */
/* begin file src/arm64/stage1_find_marks.h */
#ifndef SIMDJSON_ARM64_STAGE1_FIND_MARKS_H
#define SIMDJSON_ARM64_STAGE1_FIND_MARKS_H
#ifdef IS_ARM64
namespace simdjson::arm64 {
really_inline uint64_t compute_quote_mask(const uint64_t quote_bits) {
#ifdef __ARM_FEATURE_CRYPTO // some ARM processors lack this extension
return vmull_p64(-1ULL, quote_bits);
#else
return portable_compute_quote_mask(quote_bits);
#endif
}
really_inline void find_whitespace_and_operators(
const simd_input in,
uint64_t &whitespace, uint64_t &op) {
const uint8x16_t low_nibble_mask =
(uint8x16_t){16, 0, 0, 0, 0, 0, 0, 0, 0, 8, 12, 1, 2, 9, 0, 0};
const uint8x16_t high_nibble_mask =
(uint8x16_t){8, 0, 18, 4, 0, 1, 0, 1, 0, 0, 0, 3, 2, 1, 0, 0};
const uint8x16_t low_nib_and_mask = vmovq_n_u8(0xf);
auto v = in.map([&](auto chunk) {
uint8x16_t nib_lo = vandq_u8(chunk, low_nib_and_mask);
uint8x16_t nib_hi = vshrq_n_u8(chunk, 4);
uint8x16_t shuf_lo = vqtbl1q_u8(low_nibble_mask, nib_lo);
uint8x16_t shuf_hi = vqtbl1q_u8(high_nibble_mask, nib_hi);
return vandq_u8(shuf_lo, shuf_hi);
});
const uint8x16_t operator_shufti_mask = vmovq_n_u8(0x7);
op = v.map([&](auto _v) {
return vtstq_u8(_v, operator_shufti_mask);
}).to_bitmask();
const uint8x16_t whitespace_shufti_mask = vmovq_n_u8(0x18);
whitespace = v.map([&](auto _v) {
return vtstq_u8(_v, whitespace_shufti_mask);
}).to_bitmask();
}
// This file contains a non-architecture-specific version of "flatten" used in stage1.
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "simdjson/stage1_find_marks.h" (this simplifies amalgation)
#ifdef SIMDJSON_NAIVE_FLATTEN // useful for benchmarking
// This is just a naive implementation. It should be normally
// disable, but can be used for research purposes to compare
// again our optimized version.
really_inline void flatten_bits(uint32_t *base_ptr, uint32_t &base, uint32_t idx, uint64_t bits) {
uint32_t *out_ptr = base_ptr + base;
idx -= 64;
while (bits != 0) {
out_ptr[0] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
out_ptr++;
}
base = (out_ptr - base_ptr);
}
#else // SIMDJSON_NAIVE_FLATTEN
// flatten out values in 'bits' assuming that they are are to have values of idx
// plus their position in the bitvector, and store these indexes at
// base_ptr[base] incrementing base as we go
// will potentially store extra values beyond end of valid bits, so base_ptr
// needs to be large enough to handle this
really_inline void flatten_bits(uint32_t *&base_ptr, uint32_t idx, uint64_t bits) {
// In some instances, the next branch is expensive because it is mispredicted.
// Unfortunately, in other cases,
// it helps tremendously.
if (bits == 0)
return;
uint32_t cnt = hamming(bits);
idx -= 64;
// Do the first 8 all together
for (int i=0; i<8; i++) {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
}
// Do the next 8 all together (we hope in most cases it won't happen at all
// and the branch is easily predicted).
if (unlikely(cnt > 8)) {
for (int i=8; i<16; i++) {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
}
// Most files don't have 16+ structurals per block, so we take several basically guaranteed
// branch mispredictions here. 16+ structurals per block means either punctuation ({} [] , :)
// or the start of a value ("abc" true 123) every 4 characters.
if (unlikely(cnt > 16)) {
uint32_t i = 16;
do {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
i++;
} while (i < cnt);
}
}
base_ptr += cnt;
}
#endif // SIMDJSON_NAIVE_FLATTEN
// This file contains the common code every implementation uses in stage1
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is included already includes
// "simdjson/stage1_find_marks.h" (this simplifies amalgation)
// return a bitvector indicating where we have characters that end an odd-length
// sequence of backslashes (and thus change the behavior of the next character
// to follow). A even-length sequence of backslashes, and, for that matter, the
// largest even-length prefix of our odd-length sequence of backslashes, simply
// modify the behavior of the backslashes themselves.
// We also update the prev_iter_ends_odd_backslash reference parameter to
// indicate whether we end an iteration on an odd-length sequence of
// backslashes, which modifies our subsequent search for odd-length
// sequences of backslashes in an obvious way.
really_inline uint64_t follows_odd_sequence_of(const uint64_t match, uint64_t &overflow) {
const uint64_t even_bits = 0x5555555555555555ULL;
const uint64_t odd_bits = ~even_bits;
uint64_t start_edges = match & ~(match << 1);
/* flip lowest if we have an odd-length run at the end of the prior
* iteration */
uint64_t even_start_mask = even_bits ^ overflow;
uint64_t even_starts = start_edges & even_start_mask;
uint64_t odd_starts = start_edges & ~even_start_mask;
uint64_t even_carries = match + even_starts;
uint64_t odd_carries;
/* must record the carry-out of our odd-carries out of bit 63; this
* indicates whether the sense of any edge going to the next iteration
* should be flipped */
bool new_overflow = add_overflow(match, odd_starts, &odd_carries);
odd_carries |= overflow; /* push in bit zero as a
* potential end if we had an
* odd-numbered run at the
* end of the previous
* iteration */
overflow = new_overflow ? 0x1ULL : 0x0ULL;
uint64_t even_carry_ends = even_carries & ~match;
uint64_t odd_carry_ends = odd_carries & ~match;
uint64_t even_start_odd_end = even_carry_ends & odd_bits;
uint64_t odd_start_even_end = odd_carry_ends & even_bits;
uint64_t odd_ends = even_start_odd_end | odd_start_even_end;
return odd_ends;
}
//
// Check if the current character immediately follows a matching character.
//
// For example, this checks for quotes with backslashes in front of them:
//
// const uint64_t backslashed_quote = in.eq('"') & immediately_follows(in.eq('\'), prev_backslash);
//
really_inline uint64_t follows(const uint64_t match, uint64_t &overflow) {
const uint64_t result = match << 1 | overflow;
overflow = match >> 63;
return result;
}
//
// Check if the current character follows a matching character, with possible "filler" between.
// For example, this checks for empty curly braces, e.g.
//
// in.eq('}') & follows(in.eq('['), in.eq(' '), prev_empty_array) // { <whitespace>* }
//
really_inline uint64_t follows(const uint64_t match, const uint64_t filler, uint64_t &overflow ) {
uint64_t follows_match = follows(match, overflow);
uint64_t result;
overflow |= add_overflow(follows_match, filler, &result);
return result;
}
really_inline ErrorValues detect_errors_on_eof(
uint64_t &unescaped_chars_error,
const uint64_t prev_in_string) {
if (prev_in_string) {
return UNCLOSED_STRING;
}
if (unescaped_chars_error) {
return UNESCAPED_CHARS;
}
return SUCCESS;
}
//
// Return a mask of all string characters plus end quotes.
//
// prev_escaped is overflow saying whether the next character is escaped.
// prev_in_string is overflow saying whether we're still in a string.
//
// Backslash sequences outside of quotes will be detected in stage 2.
//
really_inline uint64_t find_strings(const simd_input in, uint64_t &prev_escaped, uint64_t &prev_in_string) {
const uint64_t backslash = in.eq('\\');
const uint64_t escaped = follows_odd_sequence_of(backslash, prev_escaped);
const uint64_t quote = in.eq('"') & ~escaped;
// compute_quote_mask returns start quote plus string contents.
const uint64_t in_string = compute_quote_mask(quote) ^ prev_in_string;
/* right shift of a signed value expected to be well-defined and standard
* compliant as of C++20,
* John Regher from Utah U. says this is fine code */
prev_in_string = static_cast<uint64_t>(static_cast<int64_t>(in_string) >> 63);
// Use ^ to turn the beginning quote off, and the end quote on.
return in_string ^ quote;
}
really_inline uint64_t invalid_string_bytes(const uint64_t unescaped, const uint64_t quote_mask) {
/* All Unicode characters may be placed within the
* quotation marks, except for the characters that MUST be escaped:
* quotation mark, reverse solidus, and the control characters (U+0000
* through U+001F).
* https://tools.ietf.org/html/rfc8259 */
return quote_mask & unescaped;
}
//
// Determine which characters are *structural*:
// - braces: [] and {}
// - the start of primitives (123, true, false, null)
// - the start of invalid non-whitespace (+, &, ture, UTF-8)
//
// Also detects value sequence errors:
// - two values with no separator between ("hello" "world")
// - separators with no values ([1,] [1,,]and [,2])
//
// This method will find all of the above whether it is in a string or not.
//
// To reduce dependency on the expensive "what is in a string" computation, this method treats the
// contents of a string the same as content outside. Errors and structurals inside the string or on
// the trailing quote will need to be removed later when the correct string information is known.
//
really_inline uint64_t find_potential_structurals(const simd_input in, uint64_t &prev_primitive) {
// These use SIMD so let's kick them off before running the regular 64-bit stuff ...
uint64_t whitespace, op;
find_whitespace_and_operators(in, whitespace, op);
// Detect the start of a run of primitive characters. Includes numbers, booleans, and strings (").
// Everything except whitespace, braces, colon and comma.
const uint64_t primitive = ~(op | whitespace);
const uint64_t follows_primitive = follows(primitive, prev_primitive);
const uint64_t start_primitive = primitive & ~follows_primitive;
// Return final structurals
return op | start_primitive;
}
static const size_t STEP_SIZE = 128;
//
// Find the important bits of JSON in a 128-byte chunk, and add them to :
//
//
//
// PERF NOTES:
// We pipe 2 inputs through these stages:
// 1. Load JSON into registers. This takes a long time and is highly parallelizable, so we load
// 2 inputs' worth at once so that by the time step 2 is looking for them input, it's available.
// 2. Scan the JSON for critical data: strings, primitives and operators. This is the critical path.
// The output of step 1 depends entirely on this information. These functions don't quite use
// up enough CPU: the second half of the functions is highly serial, only using 1 execution core
// at a time. The second input's scans has some dependency on the first ones finishing it, but
// they can make a lot of progress before they need that information.
// 3. Step 1 doesn't use enough capacity, so we run some extra stuff while we're waiting for that
// to finish: utf-8 checks and generating the output from the last iteration.
//
// The reason we run 2 inputs at a time, is steps 2 and 3 are *still* not enough to soak up all
// available capacity with just one input. Running 2 at a time seems to give the CPU a good enough
// workout.
//
really_inline void find_structural_bits_128(
const uint8_t *buf, const size_t idx, uint32_t *&base_ptr,
uint64_t &prev_escaped, uint64_t &prev_in_string,
uint64_t &prev_primitive,
uint64_t &prev_structurals,
uint64_t &unescaped_chars_error,
utf8_checker &utf8_state) {
//
// Load up all 128 bytes into SIMD registers
//
simd_input in_1(buf);
simd_input in_2(buf+64);
//
// Find the strings and potential structurals (operators / primitives).
//
// This will include false structurals that are *inside* strings--we'll filter strings out
// before we return.
//
uint64_t string_1 = find_strings(in_1, prev_escaped, prev_in_string);
uint64_t structurals_1 = find_potential_structurals(in_1, prev_primitive);
uint64_t string_2 = find_strings(in_2, prev_escaped, prev_in_string);
uint64_t structurals_2 = find_potential_structurals(in_2, prev_primitive);
//
// Do miscellaneous work while the processor is busy calculating strings and structurals.
//
// After that, weed out structurals that are inside strings and find invalid string characters.
//
uint64_t unescaped_1 = in_1.lteq(0x1F);
utf8_state.check_next_input(in_1);
flatten_bits(base_ptr, idx, prev_structurals); // Output *last* iteration's structurals to ParsedJson
prev_structurals = structurals_1 & ~string_1;
unescaped_chars_error |= unescaped_1 & string_1;
uint64_t unescaped_2 = in_2.lteq(0x1F);
utf8_state.check_next_input(in_2);
flatten_bits(base_ptr, idx+64, prev_structurals); // Output *last* iteration's structurals to ParsedJson
prev_structurals = structurals_2 & ~string_2;
unescaped_chars_error |= unescaped_2 & string_2;
}
int find_structural_bits(const uint8_t *buf, size_t len, simdjson::ParsedJson &pj) {
if (unlikely(len > pj.byte_capacity)) {
std::cerr << "Your ParsedJson object only supports documents up to "
<< pj.byte_capacity << " bytes but you are trying to process "
<< len << " bytes" << std::endl;
return simdjson::CAPACITY;
}
uint32_t *base_ptr = pj.structural_indexes;
utf8_checker utf8_state;
// Whether the first character of the next iteration is escaped.
uint64_t prev_escaped = 0ULL;
// Whether the last iteration was still inside a string (all 1's = true, all 0's = false).
uint64_t prev_in_string = 0ULL;
// Whether the last character of the previous iteration is a primitive value character
// (anything except whitespace, braces, comma or colon).
uint64_t prev_primitive = 0ULL;
// Mask of structural characters from the last iteration.
// Kept around for performance reasons, so we can call flatten_bits to soak up some unused
// CPU capacity while the next iteration is busy with an expensive clmul in compute_quote_mask.
uint64_t structurals = 0;
size_t lenminusstep = len < STEP_SIZE ? 0 : len - STEP_SIZE;
size_t idx = 0;
// Errors with unescaped characters in strings (ASCII codepoints < 0x20)
uint64_t unescaped_chars_error = 0;
for (; idx < lenminusstep; idx += STEP_SIZE) {
find_structural_bits_128(&buf[idx], idx, base_ptr,
prev_escaped, prev_in_string, prev_primitive,
structurals, unescaped_chars_error, utf8_state);
}
/* If we have a final chunk of less than 64 bytes, pad it to 64 with
* spaces before processing it (otherwise, we risk invalidating the UTF-8
* checks). */
if (likely(idx < len)) {
uint8_t tmp_buf[STEP_SIZE];
memset(tmp_buf, 0x20, STEP_SIZE);
memcpy(tmp_buf, buf + idx, len - idx);
find_structural_bits_128(&tmp_buf[0], idx, base_ptr,
prev_escaped, prev_in_string, prev_primitive,
structurals, unescaped_chars_error, utf8_state);
idx += STEP_SIZE;
}
/* finally, flatten out the remaining structurals from the last iteration */
flatten_bits(base_ptr, idx, structurals);
simdjson::ErrorValues error = detect_errors_on_eof(unescaped_chars_error, prev_in_string);
if (unlikely(error != simdjson::SUCCESS)) {
return error;
}
pj.n_structural_indexes = base_ptr - pj.structural_indexes;
/* a valid JSON file cannot have zero structural indexes - we should have
* found something */
if (unlikely(pj.n_structural_indexes == 0u)) {
return simdjson::EMPTY;
}
if (unlikely(pj.structural_indexes[pj.n_structural_indexes - 1] > len)) {
return simdjson::UNEXPECTED_ERROR;
}
if (len != pj.structural_indexes[pj.n_structural_indexes - 1]) {
/* the string might not be NULL terminated, but we add a virtual NULL
* ending character. */
pj.structural_indexes[pj.n_structural_indexes++] = len;
}
/* make it safe to dereference one beyond this array */
pj.structural_indexes[pj.n_structural_indexes] = 0;
return utf8_state.errors();
}
} // namespace simdjson::arm64
namespace simdjson {
template <>
int find_structural_bits<Architecture::ARM64>(const uint8_t *buf, size_t len, simdjson::ParsedJson &pj) {
return arm64::find_structural_bits(buf, len, pj);
}
} // namespace simdjson
#endif // IS_ARM64
#endif // SIMDJSON_ARM64_STAGE1_FIND_MARKS_H
/* end file src/arm64/stage1_find_marks.h */
/* begin file src/haswell/stage1_find_marks.h */
#ifndef SIMDJSON_HASWELL_STAGE1_FIND_MARKS_H
#define SIMDJSON_HASWELL_STAGE1_FIND_MARKS_H
#ifdef IS_X86_64
TARGET_HASWELL
namespace simdjson::haswell {
really_inline uint64_t compute_quote_mask(const uint64_t quote_bits) {
// There should be no such thing with a processing supporting avx2
// but not clmul.
uint64_t quote_mask = _mm_cvtsi128_si64(_mm_clmulepi64_si128(
_mm_set_epi64x(0ULL, quote_bits), _mm_set1_epi8(0xFFu), 0));
return quote_mask;
}
really_inline void find_whitespace_and_operators(
const simd_input in,
uint64_t &whitespace, uint64_t &op) {
#ifdef SIMDJSON_NAIVE_STRUCTURAL
// You should never need this naive approach, but it can be useful
// for research purposes
const __m256i mask_open_brace = _mm256_set1_epi8(0x7b);
const __m256i mask_close_brace = _mm256_set1_epi8(0x7d);
const __m256i mask_open_bracket = _mm256_set1_epi8(0x5b);
const __m256i mask_close_bracket = _mm256_set1_epi8(0x5d);
const __m256i mask_column = _mm256_set1_epi8(0x3a);
const __m256i mask_comma = _mm256_set1_epi8(0x2c);
op = in.map([&](auto in) {
__m256i op = _mm256_cmpeq_epi8(in, mask_open_brace);
op = _mm256_or_si256(op, _mm256_cmpeq_epi8(in, mask_close_brace));
op = _mm256_or_si256(op, _mm256_cmpeq_epi8(in, mask_open_bracket));
op = _mm256_or_si256(op, _mm256_cmpeq_epi8(in, mask_close_bracket));
op = _mm256_or_si256(op, _mm256_cmpeq_epi8(in, mask_column));
op = _mm256_or_si256(op, _mm256_cmpeq_epi8(in, mask_comma));
return op;
}).to_bitmask();
const __m256i mask_space = _mm256_set1_epi8(0x20);
const __m256i mask_linefeed = _mm256_set1_epi8(0x0a);
const __m256i mask_tab = _mm256_set1_epi8(0x09);
const __m256i mask_carriage = _mm256_set1_epi8(0x0d);
whitespace = in.map([&](auto in) {
__m256i space = _mm256_cmpeq_epi8(in, mask_space);
space = _mm256_or_si256(space, _mm256_cmpeq_epi8(in, mask_linefeed));
space = _mm256_or_si256(space, _mm256_cmpeq_epi8(in, mask_tab));
space = _mm256_or_si256(space, _mm256_cmpeq_epi8(in, mask_carriage));
return space;
}).to_bitmask();
// end of naive approach
#else // SIMDJSON_NAIVE_STRUCTURAL
// clang-format off
const __m256i operator_table =
_mm256_setr_epi8(44, 125, 0, 0, 0xc0u, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 123,
44, 125, 0, 0, 0xc0u, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 123);
const __m256i white_table = _mm256_setr_epi8(
32, 100, 100, 100, 17, 100, 113, 2, 100, 9, 10, 112, 100, 13, 100, 100,
32, 100, 100, 100, 17, 100, 113, 2, 100, 9, 10, 112, 100, 13, 100, 100);
// clang-format on
const __m256i op_offset = _mm256_set1_epi8(0xd4u);
const __m256i op_mask = _mm256_set1_epi8(32);
whitespace = in.map([&](auto _in) {
return _mm256_cmpeq_epi8(_in, _mm256_shuffle_epi8(white_table, _in));
}).to_bitmask();
op = in.map([&](auto _in) {
const __m256i r1 = _mm256_add_epi8(op_offset, _in);
const __m256i r2 = _mm256_or_si256(_in, op_mask);
const __m256i r3 = _mm256_shuffle_epi8(operator_table, r1);
return _mm256_cmpeq_epi8(r2, r3);
}).to_bitmask();
#endif // else SIMDJSON_NAIVE_STRUCTURAL
}
// flatten out values in 'bits' assuming that they are are to have values of idx
// plus their position in the bitvector, and store these indexes at
// base_ptr[base] incrementing base as we go
// will potentially store extra values beyond end of valid bits, so base_ptr
// needs to be large enough to handle this
really_inline void flatten_bits(uint32_t *&base_ptr, uint32_t idx, uint64_t bits) {
// In some instances, the next branch is expensive because it is mispredicted.
// Unfortunately, in other cases,
// it helps tremendously.
if (bits == 0)
return;
uint32_t cnt = _mm_popcnt_u64(bits);
idx -= 64;
// Do the first 8 all together
for (int i=0; i<8; i++) {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = _blsr_u64(bits);
}
// Do the next 8 all together (we hope in most cases it won't happen at all
// and the branch is easily predicted).
if (unlikely(cnt > 8)) {
for (int i=8; i<16; i++) {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = _blsr_u64(bits);
}
// Most files don't have 16+ structurals per block, so we take several basically guaranteed
// branch mispredictions here. 16+ structurals per block means either punctuation ({} [] , :)
// or the start of a value ("abc" true 123) every four characters.
if (unlikely(cnt > 16)) {
uint32_t i = 16;
do {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = _blsr_u64(bits);
i++;
} while (i < cnt);
}
}
base_ptr += cnt;
}
// This file contains the common code every implementation uses in stage1
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is included already includes
// "simdjson/stage1_find_marks.h" (this simplifies amalgation)
// return a bitvector indicating where we have characters that end an odd-length
// sequence of backslashes (and thus change the behavior of the next character
// to follow). A even-length sequence of backslashes, and, for that matter, the
// largest even-length prefix of our odd-length sequence of backslashes, simply
// modify the behavior of the backslashes themselves.
// We also update the prev_iter_ends_odd_backslash reference parameter to
// indicate whether we end an iteration on an odd-length sequence of
// backslashes, which modifies our subsequent search for odd-length
// sequences of backslashes in an obvious way.
really_inline uint64_t follows_odd_sequence_of(const uint64_t match, uint64_t &overflow) {
const uint64_t even_bits = 0x5555555555555555ULL;
const uint64_t odd_bits = ~even_bits;
uint64_t start_edges = match & ~(match << 1);
/* flip lowest if we have an odd-length run at the end of the prior
* iteration */
uint64_t even_start_mask = even_bits ^ overflow;
uint64_t even_starts = start_edges & even_start_mask;
uint64_t odd_starts = start_edges & ~even_start_mask;
uint64_t even_carries = match + even_starts;
uint64_t odd_carries;
/* must record the carry-out of our odd-carries out of bit 63; this
* indicates whether the sense of any edge going to the next iteration
* should be flipped */
bool new_overflow = add_overflow(match, odd_starts, &odd_carries);
odd_carries |= overflow; /* push in bit zero as a
* potential end if we had an
* odd-numbered run at the
* end of the previous
* iteration */
overflow = new_overflow ? 0x1ULL : 0x0ULL;
uint64_t even_carry_ends = even_carries & ~match;
uint64_t odd_carry_ends = odd_carries & ~match;
uint64_t even_start_odd_end = even_carry_ends & odd_bits;
uint64_t odd_start_even_end = odd_carry_ends & even_bits;
uint64_t odd_ends = even_start_odd_end | odd_start_even_end;
return odd_ends;
}
//
// Check if the current character immediately follows a matching character.
//
// For example, this checks for quotes with backslashes in front of them:
//
// const uint64_t backslashed_quote = in.eq('"') & immediately_follows(in.eq('\'), prev_backslash);
//
really_inline uint64_t follows(const uint64_t match, uint64_t &overflow) {
const uint64_t result = match << 1 | overflow;
overflow = match >> 63;
return result;
}
//
// Check if the current character follows a matching character, with possible "filler" between.
// For example, this checks for empty curly braces, e.g.
//
// in.eq('}') & follows(in.eq('['), in.eq(' '), prev_empty_array) // { <whitespace>* }
//
really_inline uint64_t follows(const uint64_t match, const uint64_t filler, uint64_t &overflow ) {
uint64_t follows_match = follows(match, overflow);
uint64_t result;
overflow |= add_overflow(follows_match, filler, &result);
return result;
}
really_inline ErrorValues detect_errors_on_eof(
uint64_t &unescaped_chars_error,
const uint64_t prev_in_string) {
if (prev_in_string) {
return UNCLOSED_STRING;
}
if (unescaped_chars_error) {
return UNESCAPED_CHARS;
}
return SUCCESS;
}
//
// Return a mask of all string characters plus end quotes.
//
// prev_escaped is overflow saying whether the next character is escaped.
// prev_in_string is overflow saying whether we're still in a string.
//
// Backslash sequences outside of quotes will be detected in stage 2.
//
really_inline uint64_t find_strings(const simd_input in, uint64_t &prev_escaped, uint64_t &prev_in_string) {
const uint64_t backslash = in.eq('\\');
const uint64_t escaped = follows_odd_sequence_of(backslash, prev_escaped);
const uint64_t quote = in.eq('"') & ~escaped;
// compute_quote_mask returns start quote plus string contents.
const uint64_t in_string = compute_quote_mask(quote) ^ prev_in_string;
/* right shift of a signed value expected to be well-defined and standard
* compliant as of C++20,
* John Regher from Utah U. says this is fine code */
prev_in_string = static_cast<uint64_t>(static_cast<int64_t>(in_string) >> 63);
// Use ^ to turn the beginning quote off, and the end quote on.
return in_string ^ quote;
}
really_inline uint64_t invalid_string_bytes(const uint64_t unescaped, const uint64_t quote_mask) {
/* All Unicode characters may be placed within the
* quotation marks, except for the characters that MUST be escaped:
* quotation mark, reverse solidus, and the control characters (U+0000
* through U+001F).
* https://tools.ietf.org/html/rfc8259 */
return quote_mask & unescaped;
}
//
// Determine which characters are *structural*:
// - braces: [] and {}
// - the start of primitives (123, true, false, null)
// - the start of invalid non-whitespace (+, &, ture, UTF-8)
//
// Also detects value sequence errors:
// - two values with no separator between ("hello" "world")
// - separators with no values ([1,] [1,,]and [,2])
//
// This method will find all of the above whether it is in a string or not.
//
// To reduce dependency on the expensive "what is in a string" computation, this method treats the
// contents of a string the same as content outside. Errors and structurals inside the string or on
// the trailing quote will need to be removed later when the correct string information is known.
//
really_inline uint64_t find_potential_structurals(const simd_input in, uint64_t &prev_primitive) {
// These use SIMD so let's kick them off before running the regular 64-bit stuff ...
uint64_t whitespace, op;
find_whitespace_and_operators(in, whitespace, op);
// Detect the start of a run of primitive characters. Includes numbers, booleans, and strings (").
// Everything except whitespace, braces, colon and comma.
const uint64_t primitive = ~(op | whitespace);
const uint64_t follows_primitive = follows(primitive, prev_primitive);
const uint64_t start_primitive = primitive & ~follows_primitive;
// Return final structurals
return op | start_primitive;
}
static const size_t STEP_SIZE = 128;
//
// Find the important bits of JSON in a 128-byte chunk, and add them to :
//
//
//
// PERF NOTES:
// We pipe 2 inputs through these stages:
// 1. Load JSON into registers. This takes a long time and is highly parallelizable, so we load
// 2 inputs' worth at once so that by the time step 2 is looking for them input, it's available.
// 2. Scan the JSON for critical data: strings, primitives and operators. This is the critical path.
// The output of step 1 depends entirely on this information. These functions don't quite use
// up enough CPU: the second half of the functions is highly serial, only using 1 execution core
// at a time. The second input's scans has some dependency on the first ones finishing it, but
// they can make a lot of progress before they need that information.
// 3. Step 1 doesn't use enough capacity, so we run some extra stuff while we're waiting for that
// to finish: utf-8 checks and generating the output from the last iteration.
//
// The reason we run 2 inputs at a time, is steps 2 and 3 are *still* not enough to soak up all
// available capacity with just one input. Running 2 at a time seems to give the CPU a good enough
// workout.
//
really_inline void find_structural_bits_128(
const uint8_t *buf, const size_t idx, uint32_t *&base_ptr,
uint64_t &prev_escaped, uint64_t &prev_in_string,
uint64_t &prev_primitive,
uint64_t &prev_structurals,
uint64_t &unescaped_chars_error,
utf8_checker &utf8_state) {
//
// Load up all 128 bytes into SIMD registers
//
simd_input in_1(buf);
simd_input in_2(buf+64);
//
// Find the strings and potential structurals (operators / primitives).
//
// This will include false structurals that are *inside* strings--we'll filter strings out
// before we return.
//
uint64_t string_1 = find_strings(in_1, prev_escaped, prev_in_string);
uint64_t structurals_1 = find_potential_structurals(in_1, prev_primitive);
uint64_t string_2 = find_strings(in_2, prev_escaped, prev_in_string);
uint64_t structurals_2 = find_potential_structurals(in_2, prev_primitive);
//
// Do miscellaneous work while the processor is busy calculating strings and structurals.
//
// After that, weed out structurals that are inside strings and find invalid string characters.
//
uint64_t unescaped_1 = in_1.lteq(0x1F);
utf8_state.check_next_input(in_1);
flatten_bits(base_ptr, idx, prev_structurals); // Output *last* iteration's structurals to ParsedJson
prev_structurals = structurals_1 & ~string_1;
unescaped_chars_error |= unescaped_1 & string_1;
uint64_t unescaped_2 = in_2.lteq(0x1F);
utf8_state.check_next_input(in_2);
flatten_bits(base_ptr, idx+64, prev_structurals); // Output *last* iteration's structurals to ParsedJson
prev_structurals = structurals_2 & ~string_2;
unescaped_chars_error |= unescaped_2 & string_2;
}
int find_structural_bits(const uint8_t *buf, size_t len, simdjson::ParsedJson &pj) {
if (unlikely(len > pj.byte_capacity)) {
std::cerr << "Your ParsedJson object only supports documents up to "
<< pj.byte_capacity << " bytes but you are trying to process "
<< len << " bytes" << std::endl;
return simdjson::CAPACITY;
}
uint32_t *base_ptr = pj.structural_indexes;
utf8_checker utf8_state;
// Whether the first character of the next iteration is escaped.
uint64_t prev_escaped = 0ULL;
// Whether the last iteration was still inside a string (all 1's = true, all 0's = false).
uint64_t prev_in_string = 0ULL;
// Whether the last character of the previous iteration is a primitive value character
// (anything except whitespace, braces, comma or colon).
uint64_t prev_primitive = 0ULL;
// Mask of structural characters from the last iteration.
// Kept around for performance reasons, so we can call flatten_bits to soak up some unused
// CPU capacity while the next iteration is busy with an expensive clmul in compute_quote_mask.
uint64_t structurals = 0;
size_t lenminusstep = len < STEP_SIZE ? 0 : len - STEP_SIZE;
size_t idx = 0;
// Errors with unescaped characters in strings (ASCII codepoints < 0x20)
uint64_t unescaped_chars_error = 0;
for (; idx < lenminusstep; idx += STEP_SIZE) {
find_structural_bits_128(&buf[idx], idx, base_ptr,
prev_escaped, prev_in_string, prev_primitive,
structurals, unescaped_chars_error, utf8_state);
}
/* If we have a final chunk of less than 64 bytes, pad it to 64 with
* spaces before processing it (otherwise, we risk invalidating the UTF-8
* checks). */
if (likely(idx < len)) {
uint8_t tmp_buf[STEP_SIZE];
memset(tmp_buf, 0x20, STEP_SIZE);
memcpy(tmp_buf, buf + idx, len - idx);
find_structural_bits_128(&tmp_buf[0], idx, base_ptr,
prev_escaped, prev_in_string, prev_primitive,
structurals, unescaped_chars_error, utf8_state);
idx += STEP_SIZE;
}
/* finally, flatten out the remaining structurals from the last iteration */
flatten_bits(base_ptr, idx, structurals);
simdjson::ErrorValues error = detect_errors_on_eof(unescaped_chars_error, prev_in_string);
if (unlikely(error != simdjson::SUCCESS)) {
return error;
}
pj.n_structural_indexes = base_ptr - pj.structural_indexes;
/* a valid JSON file cannot have zero structural indexes - we should have
* found something */
if (unlikely(pj.n_structural_indexes == 0u)) {
return simdjson::EMPTY;
}
if (unlikely(pj.structural_indexes[pj.n_structural_indexes - 1] > len)) {
return simdjson::UNEXPECTED_ERROR;
}
if (len != pj.structural_indexes[pj.n_structural_indexes - 1]) {
/* the string might not be NULL terminated, but we add a virtual NULL
* ending character. */
pj.structural_indexes[pj.n_structural_indexes++] = len;
}
/* make it safe to dereference one beyond this array */
pj.structural_indexes[pj.n_structural_indexes] = 0;
return utf8_state.errors();
}
} // namespace haswell
UNTARGET_REGION
TARGET_HASWELL
namespace simdjson {
template <>
int find_structural_bits<Architecture::HASWELL>(const uint8_t *buf, size_t len, simdjson::ParsedJson &pj) {
return haswell::find_structural_bits(buf, len, pj);
}
} // namespace simdjson
UNTARGET_REGION
#endif // IS_X86_64
#endif // SIMDJSON_HASWELL_STAGE1_FIND_MARKS_H
/* end file src/haswell/stage1_find_marks.h */
/* begin file src/westmere/stage1_find_marks.h */
#ifndef SIMDJSON_WESTMERE_STAGE1_FIND_MARKS_H
#define SIMDJSON_WESTMERE_STAGE1_FIND_MARKS_H
#ifdef IS_X86_64
TARGET_WESTMERE
namespace simdjson::westmere {
really_inline uint64_t compute_quote_mask(const uint64_t quote_bits) {
return _mm_cvtsi128_si64(_mm_clmulepi64_si128(
_mm_set_epi64x(0ULL, quote_bits), _mm_set1_epi8(0xFFu), 0));
}
really_inline void find_whitespace_and_operators(
const simd_input in,
uint64_t &whitespace, uint64_t &op) {
const __m128i operator_table =
_mm_setr_epi8(44, 125, 0, 0, 0xc0u, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 123);
const __m128i white_table = _mm_setr_epi8(32, 100, 100, 100, 17, 100, 113, 2,
100, 9, 10, 112, 100, 13, 100, 100);
const __m128i op_offset = _mm_set1_epi8(0xd4u);
const __m128i op_mask = _mm_set1_epi8(32);
whitespace = in.map([&](auto _in) {
return _mm_cmpeq_epi8(_in, _mm_shuffle_epi8(white_table, _in));
}).to_bitmask();
op = in.map([&](auto _in) {
const __m128i r1 = _mm_add_epi8(op_offset, _in);
const __m128i r2 = _mm_or_si128(_in, op_mask);
const __m128i r3 = _mm_shuffle_epi8(operator_table, r1);
return _mm_cmpeq_epi8(r2, r3);
}).to_bitmask();
}
// This file contains a non-architecture-specific version of "flatten" used in stage1.
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "simdjson/stage1_find_marks.h" (this simplifies amalgation)
#ifdef SIMDJSON_NAIVE_FLATTEN // useful for benchmarking
// This is just a naive implementation. It should be normally
// disable, but can be used for research purposes to compare
// again our optimized version.
really_inline void flatten_bits(uint32_t *base_ptr, uint32_t &base, uint32_t idx, uint64_t bits) {
uint32_t *out_ptr = base_ptr + base;
idx -= 64;
while (bits != 0) {
out_ptr[0] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
out_ptr++;
}
base = (out_ptr - base_ptr);
}
#else // SIMDJSON_NAIVE_FLATTEN
// flatten out values in 'bits' assuming that they are are to have values of idx
// plus their position in the bitvector, and store these indexes at
// base_ptr[base] incrementing base as we go
// will potentially store extra values beyond end of valid bits, so base_ptr
// needs to be large enough to handle this
really_inline void flatten_bits(uint32_t *&base_ptr, uint32_t idx, uint64_t bits) {
// In some instances, the next branch is expensive because it is mispredicted.
// Unfortunately, in other cases,
// it helps tremendously.
if (bits == 0)
return;
uint32_t cnt = hamming(bits);
idx -= 64;
// Do the first 8 all together
for (int i=0; i<8; i++) {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
}
// Do the next 8 all together (we hope in most cases it won't happen at all
// and the branch is easily predicted).
if (unlikely(cnt > 8)) {
for (int i=8; i<16; i++) {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
}
// Most files don't have 16+ structurals per block, so we take several basically guaranteed
// branch mispredictions here. 16+ structurals per block means either punctuation ({} [] , :)
// or the start of a value ("abc" true 123) every 4 characters.
if (unlikely(cnt > 16)) {
uint32_t i = 16;
do {
base_ptr[i] = idx + trailing_zeroes(bits);
bits = bits & (bits - 1);
i++;
} while (i < cnt);
}
}
base_ptr += cnt;
}
#endif // SIMDJSON_NAIVE_FLATTEN
// This file contains the common code every implementation uses in stage1
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is included already includes
// "simdjson/stage1_find_marks.h" (this simplifies amalgation)
// return a bitvector indicating where we have characters that end an odd-length
// sequence of backslashes (and thus change the behavior of the next character
// to follow). A even-length sequence of backslashes, and, for that matter, the
// largest even-length prefix of our odd-length sequence of backslashes, simply
// modify the behavior of the backslashes themselves.
// We also update the prev_iter_ends_odd_backslash reference parameter to
// indicate whether we end an iteration on an odd-length sequence of
// backslashes, which modifies our subsequent search for odd-length
// sequences of backslashes in an obvious way.
really_inline uint64_t follows_odd_sequence_of(const uint64_t match, uint64_t &overflow) {
const uint64_t even_bits = 0x5555555555555555ULL;
const uint64_t odd_bits = ~even_bits;
uint64_t start_edges = match & ~(match << 1);
/* flip lowest if we have an odd-length run at the end of the prior
* iteration */
uint64_t even_start_mask = even_bits ^ overflow;
uint64_t even_starts = start_edges & even_start_mask;
uint64_t odd_starts = start_edges & ~even_start_mask;
uint64_t even_carries = match + even_starts;
uint64_t odd_carries;
/* must record the carry-out of our odd-carries out of bit 63; this
* indicates whether the sense of any edge going to the next iteration
* should be flipped */
bool new_overflow = add_overflow(match, odd_starts, &odd_carries);
odd_carries |= overflow; /* push in bit zero as a
* potential end if we had an
* odd-numbered run at the
* end of the previous
* iteration */
overflow = new_overflow ? 0x1ULL : 0x0ULL;
uint64_t even_carry_ends = even_carries & ~match;
uint64_t odd_carry_ends = odd_carries & ~match;
uint64_t even_start_odd_end = even_carry_ends & odd_bits;
uint64_t odd_start_even_end = odd_carry_ends & even_bits;
uint64_t odd_ends = even_start_odd_end | odd_start_even_end;
return odd_ends;
}
//
// Check if the current character immediately follows a matching character.
//
// For example, this checks for quotes with backslashes in front of them:
//
// const uint64_t backslashed_quote = in.eq('"') & immediately_follows(in.eq('\'), prev_backslash);
//
really_inline uint64_t follows(const uint64_t match, uint64_t &overflow) {
const uint64_t result = match << 1 | overflow;
overflow = match >> 63;
return result;
}
//
// Check if the current character follows a matching character, with possible "filler" between.
// For example, this checks for empty curly braces, e.g.
//
// in.eq('}') & follows(in.eq('['), in.eq(' '), prev_empty_array) // { <whitespace>* }
//
really_inline uint64_t follows(const uint64_t match, const uint64_t filler, uint64_t &overflow ) {
uint64_t follows_match = follows(match, overflow);
uint64_t result;
overflow |= add_overflow(follows_match, filler, &result);
return result;
}
really_inline ErrorValues detect_errors_on_eof(
uint64_t &unescaped_chars_error,
const uint64_t prev_in_string) {
if (prev_in_string) {
return UNCLOSED_STRING;
}
if (unescaped_chars_error) {
return UNESCAPED_CHARS;
}
return SUCCESS;
}
//
// Return a mask of all string characters plus end quotes.
//
// prev_escaped is overflow saying whether the next character is escaped.
// prev_in_string is overflow saying whether we're still in a string.
//
// Backslash sequences outside of quotes will be detected in stage 2.
//
really_inline uint64_t find_strings(const simd_input in, uint64_t &prev_escaped, uint64_t &prev_in_string) {
const uint64_t backslash = in.eq('\\');
const uint64_t escaped = follows_odd_sequence_of(backslash, prev_escaped);
const uint64_t quote = in.eq('"') & ~escaped;
// compute_quote_mask returns start quote plus string contents.
const uint64_t in_string = compute_quote_mask(quote) ^ prev_in_string;
/* right shift of a signed value expected to be well-defined and standard
* compliant as of C++20,
* John Regher from Utah U. says this is fine code */
prev_in_string = static_cast<uint64_t>(static_cast<int64_t>(in_string) >> 63);
// Use ^ to turn the beginning quote off, and the end quote on.
return in_string ^ quote;
}
really_inline uint64_t invalid_string_bytes(const uint64_t unescaped, const uint64_t quote_mask) {
/* All Unicode characters may be placed within the
* quotation marks, except for the characters that MUST be escaped:
* quotation mark, reverse solidus, and the control characters (U+0000
* through U+001F).
* https://tools.ietf.org/html/rfc8259 */
return quote_mask & unescaped;
}
//
// Determine which characters are *structural*:
// - braces: [] and {}
// - the start of primitives (123, true, false, null)
// - the start of invalid non-whitespace (+, &, ture, UTF-8)
//
// Also detects value sequence errors:
// - two values with no separator between ("hello" "world")
// - separators with no values ([1,] [1,,]and [,2])
//
// This method will find all of the above whether it is in a string or not.
//
// To reduce dependency on the expensive "what is in a string" computation, this method treats the
// contents of a string the same as content outside. Errors and structurals inside the string or on
// the trailing quote will need to be removed later when the correct string information is known.
//
really_inline uint64_t find_potential_structurals(const simd_input in, uint64_t &prev_primitive) {
// These use SIMD so let's kick them off before running the regular 64-bit stuff ...
uint64_t whitespace, op;
find_whitespace_and_operators(in, whitespace, op);
// Detect the start of a run of primitive characters. Includes numbers, booleans, and strings (").
// Everything except whitespace, braces, colon and comma.
const uint64_t primitive = ~(op | whitespace);
const uint64_t follows_primitive = follows(primitive, prev_primitive);
const uint64_t start_primitive = primitive & ~follows_primitive;
// Return final structurals
return op | start_primitive;
}
static const size_t STEP_SIZE = 128;
//
// Find the important bits of JSON in a 128-byte chunk, and add them to :
//
//
//
// PERF NOTES:
// We pipe 2 inputs through these stages:
// 1. Load JSON into registers. This takes a long time and is highly parallelizable, so we load
// 2 inputs' worth at once so that by the time step 2 is looking for them input, it's available.
// 2. Scan the JSON for critical data: strings, primitives and operators. This is the critical path.
// The output of step 1 depends entirely on this information. These functions don't quite use
// up enough CPU: the second half of the functions is highly serial, only using 1 execution core
// at a time. The second input's scans has some dependency on the first ones finishing it, but
// they can make a lot of progress before they need that information.
// 3. Step 1 doesn't use enough capacity, so we run some extra stuff while we're waiting for that
// to finish: utf-8 checks and generating the output from the last iteration.
//
// The reason we run 2 inputs at a time, is steps 2 and 3 are *still* not enough to soak up all
// available capacity with just one input. Running 2 at a time seems to give the CPU a good enough
// workout.
//
really_inline void find_structural_bits_128(
const uint8_t *buf, const size_t idx, uint32_t *&base_ptr,
uint64_t &prev_escaped, uint64_t &prev_in_string,
uint64_t &prev_primitive,
uint64_t &prev_structurals,
uint64_t &unescaped_chars_error,
utf8_checker &utf8_state) {
//
// Load up all 128 bytes into SIMD registers
//
simd_input in_1(buf);
simd_input in_2(buf+64);
//
// Find the strings and potential structurals (operators / primitives).
//
// This will include false structurals that are *inside* strings--we'll filter strings out
// before we return.
//
uint64_t string_1 = find_strings(in_1, prev_escaped, prev_in_string);
uint64_t structurals_1 = find_potential_structurals(in_1, prev_primitive);
uint64_t string_2 = find_strings(in_2, prev_escaped, prev_in_string);
uint64_t structurals_2 = find_potential_structurals(in_2, prev_primitive);
//
// Do miscellaneous work while the processor is busy calculating strings and structurals.
//
// After that, weed out structurals that are inside strings and find invalid string characters.
//
uint64_t unescaped_1 = in_1.lteq(0x1F);
utf8_state.check_next_input(in_1);
flatten_bits(base_ptr, idx, prev_structurals); // Output *last* iteration's structurals to ParsedJson
prev_structurals = structurals_1 & ~string_1;
unescaped_chars_error |= unescaped_1 & string_1;
uint64_t unescaped_2 = in_2.lteq(0x1F);
utf8_state.check_next_input(in_2);
flatten_bits(base_ptr, idx+64, prev_structurals); // Output *last* iteration's structurals to ParsedJson
prev_structurals = structurals_2 & ~string_2;
unescaped_chars_error |= unescaped_2 & string_2;
}
int find_structural_bits(const uint8_t *buf, size_t len, simdjson::ParsedJson &pj) {
if (unlikely(len > pj.byte_capacity)) {
std::cerr << "Your ParsedJson object only supports documents up to "
<< pj.byte_capacity << " bytes but you are trying to process "
<< len << " bytes" << std::endl;
return simdjson::CAPACITY;
}
uint32_t *base_ptr = pj.structural_indexes;
utf8_checker utf8_state;
// Whether the first character of the next iteration is escaped.
uint64_t prev_escaped = 0ULL;
// Whether the last iteration was still inside a string (all 1's = true, all 0's = false).
uint64_t prev_in_string = 0ULL;
// Whether the last character of the previous iteration is a primitive value character
// (anything except whitespace, braces, comma or colon).
uint64_t prev_primitive = 0ULL;
// Mask of structural characters from the last iteration.
// Kept around for performance reasons, so we can call flatten_bits to soak up some unused
// CPU capacity while the next iteration is busy with an expensive clmul in compute_quote_mask.
uint64_t structurals = 0;
size_t lenminusstep = len < STEP_SIZE ? 0 : len - STEP_SIZE;
size_t idx = 0;
// Errors with unescaped characters in strings (ASCII codepoints < 0x20)
uint64_t unescaped_chars_error = 0;
for (; idx < lenminusstep; idx += STEP_SIZE) {
find_structural_bits_128(&buf[idx], idx, base_ptr,
prev_escaped, prev_in_string, prev_primitive,
structurals, unescaped_chars_error, utf8_state);
}
/* If we have a final chunk of less than 64 bytes, pad it to 64 with
* spaces before processing it (otherwise, we risk invalidating the UTF-8
* checks). */
if (likely(idx < len)) {
uint8_t tmp_buf[STEP_SIZE];
memset(tmp_buf, 0x20, STEP_SIZE);
memcpy(tmp_buf, buf + idx, len - idx);
find_structural_bits_128(&tmp_buf[0], idx, base_ptr,
prev_escaped, prev_in_string, prev_primitive,
structurals, unescaped_chars_error, utf8_state);
idx += STEP_SIZE;
}
/* finally, flatten out the remaining structurals from the last iteration */
flatten_bits(base_ptr, idx, structurals);
simdjson::ErrorValues error = detect_errors_on_eof(unescaped_chars_error, prev_in_string);
if (unlikely(error != simdjson::SUCCESS)) {
return error;
}
pj.n_structural_indexes = base_ptr - pj.structural_indexes;
/* a valid JSON file cannot have zero structural indexes - we should have
* found something */
if (unlikely(pj.n_structural_indexes == 0u)) {
return simdjson::EMPTY;
}
if (unlikely(pj.structural_indexes[pj.n_structural_indexes - 1] > len)) {
return simdjson::UNEXPECTED_ERROR;
}
if (len != pj.structural_indexes[pj.n_structural_indexes - 1]) {
/* the string might not be NULL terminated, but we add a virtual NULL
* ending character. */
pj.structural_indexes[pj.n_structural_indexes++] = len;
}
/* make it safe to dereference one beyond this array */
pj.structural_indexes[pj.n_structural_indexes] = 0;
return utf8_state.errors();
}
} // namespace westmere
UNTARGET_REGION
TARGET_WESTMERE
namespace simdjson {
template <>
int find_structural_bits<Architecture::WESTMERE>(const uint8_t *buf, size_t len, simdjson::ParsedJson &pj) {
return westmere::find_structural_bits(buf, len, pj);
}
} // namespace simdjson
UNTARGET_REGION
#endif // IS_X86_64
#endif // SIMDJSON_WESTMERE_STAGE1_FIND_MARKS_H
/* end file src/westmere/stage1_find_marks.h */
/* begin file src/stage1_find_marks.cpp */
namespace {
// for when clmul is unavailable
[[maybe_unused]] uint64_t portable_compute_quote_mask(uint64_t quote_bits) {
uint64_t quote_mask = quote_bits ^ (quote_bits << 1);
quote_mask = quote_mask ^ (quote_mask << 2);
quote_mask = quote_mask ^ (quote_mask << 4);
quote_mask = quote_mask ^ (quote_mask << 8);
quote_mask = quote_mask ^ (quote_mask << 16);
quote_mask = quote_mask ^ (quote_mask << 32);
return quote_mask;
}
} // namespace
/* end file src/stage1_find_marks.cpp */
/* begin file src/arm64/stringparsing.h */
#ifndef SIMDJSON_ARM64_STRINGPARSING_H
#define SIMDJSON_ARM64_STRINGPARSING_H
#ifdef IS_ARM64
#ifdef JSON_TEST_STRINGS
void found_string(const uint8_t *buf, const uint8_t *parsed_begin,
const uint8_t *parsed_end);
void found_bad_string(const uint8_t *buf);
#endif
namespace simdjson::arm64 {
// Holds backslashes and quotes locations.
struct parse_string_helper {
uint32_t bs_bits;
uint32_t quote_bits;
really_inline uint32_t bytes_processed() const { return sizeof(uint8x16_t); }
};
really_inline parse_string_helper find_bs_bits_and_quote_bits(const uint8_t *src, uint8_t *dst) {
// this can read up to 31 bytes beyond the buffer size, but we require
// SIMDJSON_PADDING of padding
static_assert(2 * sizeof(uint8x16_t) - 1 <= SIMDJSON_PADDING);
uint8x16_t v0 = vld1q_u8(src);
uint8x16_t v1 = vld1q_u8(src + 16);
vst1q_u8(dst, v0);
vst1q_u8(dst + 16, v1);
uint8x16_t bs_mask = vmovq_n_u8('\\');
uint8x16_t qt_mask = vmovq_n_u8('"');
const uint8x16_t bit_mask = {0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80,
0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
uint8x16_t cmp_bs_0 = vceqq_u8(v0, bs_mask);
uint8x16_t cmp_bs_1 = vceqq_u8(v1, bs_mask);
uint8x16_t cmp_qt_0 = vceqq_u8(v0, qt_mask);
uint8x16_t cmp_qt_1 = vceqq_u8(v1, qt_mask);
cmp_bs_0 = vandq_u8(cmp_bs_0, bit_mask);
cmp_bs_1 = vandq_u8(cmp_bs_1, bit_mask);
cmp_qt_0 = vandq_u8(cmp_qt_0, bit_mask);
cmp_qt_1 = vandq_u8(cmp_qt_1, bit_mask);
uint8x16_t sum0 = vpaddq_u8(cmp_bs_0, cmp_bs_1);
uint8x16_t sum1 = vpaddq_u8(cmp_qt_0, cmp_qt_1);
sum0 = vpaddq_u8(sum0, sum1);
sum0 = vpaddq_u8(sum0, sum0);
return {
vgetq_lane_u32(vreinterpretq_u32_u8(sum0), 0), // bs_bits
vgetq_lane_u32(vreinterpretq_u32_u8(sum0), 1) // quote_bits
};
}
// This file contains the common code every implementation uses
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "stringparsing.h" (this simplifies amalgation)
// begin copypasta
// These chars yield themselves: " \ /
// b -> backspace, f -> formfeed, n -> newline, r -> cr, t -> horizontal tab
// u not handled in this table as it's complex
static const uint8_t escape_map[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x0.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0x22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2f,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x4.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x5c, 0, 0, 0, // 0x5.
0, 0, 0x08, 0, 0, 0, 0x0c, 0, 0, 0, 0, 0, 0, 0, 0x0a, 0, // 0x6.
0, 0, 0x0d, 0, 0x09, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x7.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
// handle a unicode codepoint
// write appropriate values into dest
// src will advance 6 bytes or 12 bytes
// dest will advance a variable amount (return via pointer)
// return true if the unicode codepoint was valid
// We work in little-endian then swap at write time
WARN_UNUSED
really_inline bool handle_unicode_codepoint(const uint8_t **src_ptr,
uint8_t **dst_ptr) {
// hex_to_u32_nocheck fills high 16 bits of the return value with 1s if the
// conversion isn't valid; we defer the check for this to inside the
// multilingual plane check
uint32_t code_point = hex_to_u32_nocheck(*src_ptr + 2);
*src_ptr += 6;
// check for low surrogate for characters outside the Basic
// Multilingual Plane.
if (code_point >= 0xd800 && code_point < 0xdc00) {
if (((*src_ptr)[0] != '\\') || (*src_ptr)[1] != 'u') {
return false;
}
uint32_t code_point_2 = hex_to_u32_nocheck(*src_ptr + 2);
// if the first code point is invalid we will get here, as we will go past
// the check for being outside the Basic Multilingual plane. If we don't
// find a \u immediately afterwards we fail out anyhow, but if we do,
// this check catches both the case of the first code point being invalid
// or the second code point being invalid.
if ((code_point | code_point_2) >> 16) {
return false;
}
code_point =
(((code_point - 0xd800) << 10) | (code_point_2 - 0xdc00)) + 0x10000;
*src_ptr += 6;
}
size_t offset = codepoint_to_utf8(code_point, *dst_ptr);
*dst_ptr += offset;
return offset > 0;
}
WARN_UNUSED really_inline bool parse_string(UNUSED const uint8_t *buf,
UNUSED size_t len, ParsedJson &pj,
UNUSED const uint32_t depth,
UNUSED uint32_t offset) {
pj.write_tape(pj.current_string_buf_loc - pj.string_buf, '"');
const uint8_t *src = &buf[offset + 1]; /* we know that buf at offset is a " */
uint8_t *dst = pj.current_string_buf_loc + sizeof(uint32_t);
const uint8_t *const start_of_string = dst;
while (1) {
parse_string_helper helper = find_bs_bits_and_quote_bits(src, dst);
if (((helper.bs_bits - 1) & helper.quote_bits) != 0) {
/* we encountered quotes first. Move dst to point to quotes and exit
*/
/* find out where the quote is... */
uint32_t quote_dist = trailing_zeroes(helper.quote_bits);
/* NULL termination is still handy if you expect all your strings to
* be NULL terminated? */
/* It comes at a small cost */
dst[quote_dist] = 0;
uint32_t str_length = (dst - start_of_string) + quote_dist;
memcpy(pj.current_string_buf_loc, &str_length, sizeof(uint32_t));
/*****************************
* Above, check for overflow in case someone has a crazy string
* (>=4GB?) _
* But only add the overflow check when the document itself exceeds
* 4GB
* Currently unneeded because we refuse to parse docs larger or equal
* to 4GB.
****************************/
/* we advance the point, accounting for the fact that we have a NULL
* termination */
pj.current_string_buf_loc = dst + quote_dist + 1;
return true;
}
if (((helper.quote_bits - 1) & helper.bs_bits) != 0) {
/* find out where the backspace is */
uint32_t bs_dist = trailing_zeroes(helper.bs_bits);
uint8_t escape_char = src[bs_dist + 1];
/* we encountered backslash first. Handle backslash */
if (escape_char == 'u') {
/* move src/dst up to the start; they will be further adjusted
within the unicode codepoint handling code. */
src += bs_dist;
dst += bs_dist;
if (!handle_unicode_codepoint(&src, &dst)) {
return false;
}
} else {
/* simple 1:1 conversion. Will eat bs_dist+2 characters in input and
* write bs_dist+1 characters to output
* note this may reach beyond the part of the buffer we've actually
* seen. I think this is ok */
uint8_t escape_result = escape_map[escape_char];
if (escape_result == 0u) {
return false; /* bogus escape value is an error */
}
dst[bs_dist] = escape_result;
src += bs_dist + 2;
dst += bs_dist + 1;
}
} else {
/* they are the same. Since they can't co-occur, it means we
* encountered neither. */
src += helper.bytes_processed();
dst += helper.bytes_processed();
}
}
/* can't be reached */
return true;
}
}
// namespace simdjson::amd64
#endif // IS_ARM64
#endif
/* end file src/arm64/stringparsing.h */
/* begin file src/haswell/stringparsing.h */
#ifndef SIMDJSON_HASWELL_STRINGPARSING_H
#define SIMDJSON_HASWELL_STRINGPARSING_H
#ifdef IS_X86_64
#ifdef JSON_TEST_STRINGS
void found_string(const uint8_t *buf, const uint8_t *parsed_begin,
const uint8_t *parsed_end);
void found_bad_string(const uint8_t *buf);
#endif
TARGET_HASWELL
namespace simdjson::haswell {
// Holds backslashes and quotes locations.
struct parse_string_helper {
uint32_t bs_bits;
uint32_t quote_bits;
really_inline uint32_t bytes_processed() const { return sizeof(__m256i); }
};
really_inline parse_string_helper find_bs_bits_and_quote_bits(const uint8_t *src, uint8_t *dst) {
// this can read up to 31 bytes beyond the buffer size, but we require
// SIMDJSON_PADDING of padding
static_assert(sizeof(__m256i) - 1 <= SIMDJSON_PADDING);
__m256i v = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(src));
// store to dest unconditionally - we can overwrite the bits we don't like
// later
_mm256_storeu_si256(reinterpret_cast<__m256i *>(dst), v);
auto quote_mask = _mm256_cmpeq_epi8(v, _mm256_set1_epi8('"'));
return {
static_cast<uint32_t>(_mm256_movemask_epi8(
_mm256_cmpeq_epi8(v, _mm256_set1_epi8('\\')))), // bs_bits
static_cast<uint32_t>(_mm256_movemask_epi8(quote_mask)) // quote_bits
};
}
// This file contains the common code every implementation uses
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "stringparsing.h" (this simplifies amalgation)
// begin copypasta
// These chars yield themselves: " \ /
// b -> backspace, f -> formfeed, n -> newline, r -> cr, t -> horizontal tab
// u not handled in this table as it's complex
static const uint8_t escape_map[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x0.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0x22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2f,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x4.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x5c, 0, 0, 0, // 0x5.
0, 0, 0x08, 0, 0, 0, 0x0c, 0, 0, 0, 0, 0, 0, 0, 0x0a, 0, // 0x6.
0, 0, 0x0d, 0, 0x09, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x7.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
// handle a unicode codepoint
// write appropriate values into dest
// src will advance 6 bytes or 12 bytes
// dest will advance a variable amount (return via pointer)
// return true if the unicode codepoint was valid
// We work in little-endian then swap at write time
WARN_UNUSED
really_inline bool handle_unicode_codepoint(const uint8_t **src_ptr,
uint8_t **dst_ptr) {
// hex_to_u32_nocheck fills high 16 bits of the return value with 1s if the
// conversion isn't valid; we defer the check for this to inside the
// multilingual plane check
uint32_t code_point = hex_to_u32_nocheck(*src_ptr + 2);
*src_ptr += 6;
// check for low surrogate for characters outside the Basic
// Multilingual Plane.
if (code_point >= 0xd800 && code_point < 0xdc00) {
if (((*src_ptr)[0] != '\\') || (*src_ptr)[1] != 'u') {
return false;
}
uint32_t code_point_2 = hex_to_u32_nocheck(*src_ptr + 2);
// if the first code point is invalid we will get here, as we will go past
// the check for being outside the Basic Multilingual plane. If we don't
// find a \u immediately afterwards we fail out anyhow, but if we do,
// this check catches both the case of the first code point being invalid
// or the second code point being invalid.
if ((code_point | code_point_2) >> 16) {
return false;
}
code_point =
(((code_point - 0xd800) << 10) | (code_point_2 - 0xdc00)) + 0x10000;
*src_ptr += 6;
}
size_t offset = codepoint_to_utf8(code_point, *dst_ptr);
*dst_ptr += offset;
return offset > 0;
}
WARN_UNUSED really_inline bool parse_string(UNUSED const uint8_t *buf,
UNUSED size_t len, ParsedJson &pj,
UNUSED const uint32_t depth,
UNUSED uint32_t offset) {
pj.write_tape(pj.current_string_buf_loc - pj.string_buf, '"');
const uint8_t *src = &buf[offset + 1]; /* we know that buf at offset is a " */
uint8_t *dst = pj.current_string_buf_loc + sizeof(uint32_t);
const uint8_t *const start_of_string = dst;
while (1) {
parse_string_helper helper = find_bs_bits_and_quote_bits(src, dst);
if (((helper.bs_bits - 1) & helper.quote_bits) != 0) {
/* we encountered quotes first. Move dst to point to quotes and exit
*/
/* find out where the quote is... */
uint32_t quote_dist = trailing_zeroes(helper.quote_bits);
/* NULL termination is still handy if you expect all your strings to
* be NULL terminated? */
/* It comes at a small cost */
dst[quote_dist] = 0;
uint32_t str_length = (dst - start_of_string) + quote_dist;
memcpy(pj.current_string_buf_loc, &str_length, sizeof(uint32_t));
/*****************************
* Above, check for overflow in case someone has a crazy string
* (>=4GB?) _
* But only add the overflow check when the document itself exceeds
* 4GB
* Currently unneeded because we refuse to parse docs larger or equal
* to 4GB.
****************************/
/* we advance the point, accounting for the fact that we have a NULL
* termination */
pj.current_string_buf_loc = dst + quote_dist + 1;
return true;
}
if (((helper.quote_bits - 1) & helper.bs_bits) != 0) {
/* find out where the backspace is */
uint32_t bs_dist = trailing_zeroes(helper.bs_bits);
uint8_t escape_char = src[bs_dist + 1];
/* we encountered backslash first. Handle backslash */
if (escape_char == 'u') {
/* move src/dst up to the start; they will be further adjusted
within the unicode codepoint handling code. */
src += bs_dist;
dst += bs_dist;
if (!handle_unicode_codepoint(&src, &dst)) {
return false;
}
} else {
/* simple 1:1 conversion. Will eat bs_dist+2 characters in input and
* write bs_dist+1 characters to output
* note this may reach beyond the part of the buffer we've actually
* seen. I think this is ok */
uint8_t escape_result = escape_map[escape_char];
if (escape_result == 0u) {
return false; /* bogus escape value is an error */
}
dst[bs_dist] = escape_result;
src += bs_dist + 2;
dst += bs_dist + 1;
}
} else {
/* they are the same. Since they can't co-occur, it means we
* encountered neither. */
src += helper.bytes_processed();
dst += helper.bytes_processed();
}
}
/* can't be reached */
return true;
}
} // namespace simdjson::haswell
UNTARGET_REGION
#endif // IS_X86_64
#endif
/* end file src/haswell/stringparsing.h */
/* begin file src/westmere/stringparsing.h */
#ifndef SIMDJSON_WESTMERE_STRINGPARSING_H
#define SIMDJSON_WESTMERE_STRINGPARSING_H
#ifdef IS_X86_64
#ifdef JSON_TEST_STRINGS
void found_string(const uint8_t *buf, const uint8_t *parsed_begin,
const uint8_t *parsed_end);
void found_bad_string(const uint8_t *buf);
#endif
TARGET_WESTMERE
namespace simdjson::westmere {
// Holds backslashes and quotes locations.
struct parse_string_helper {
uint32_t bs_bits;
uint32_t quote_bits;
really_inline uint32_t bytes_processed() const { return sizeof(__m128i); }
};
really_inline parse_string_helper find_bs_bits_and_quote_bits(const uint8_t *src, uint8_t *dst) {
// this can read up to 31 bytes beyond the buffer size, but we require
// SIMDJSON_PADDING of padding
__m128i v = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src));
// store to dest unconditionally - we can overwrite the bits we don't like
// later
_mm_storeu_si128(reinterpret_cast<__m128i *>(dst), v);
auto quote_mask = _mm_cmpeq_epi8(v, _mm_set1_epi8('"'));
return {
static_cast<uint32_t>(
_mm_movemask_epi8(_mm_cmpeq_epi8(v, _mm_set1_epi8('\\')))), // bs_bits
static_cast<uint32_t>(_mm_movemask_epi8(quote_mask)) // quote_bits
};
}
// This file contains the common code every implementation uses
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "stringparsing.h" (this simplifies amalgation)
// begin copypasta
// These chars yield themselves: " \ /
// b -> backspace, f -> formfeed, n -> newline, r -> cr, t -> horizontal tab
// u not handled in this table as it's complex
static const uint8_t escape_map[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x0.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0x22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2f,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x4.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x5c, 0, 0, 0, // 0x5.
0, 0, 0x08, 0, 0, 0, 0x0c, 0, 0, 0, 0, 0, 0, 0, 0x0a, 0, // 0x6.
0, 0, 0x0d, 0, 0x09, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x7.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
// handle a unicode codepoint
// write appropriate values into dest
// src will advance 6 bytes or 12 bytes
// dest will advance a variable amount (return via pointer)
// return true if the unicode codepoint was valid
// We work in little-endian then swap at write time
WARN_UNUSED
really_inline bool handle_unicode_codepoint(const uint8_t **src_ptr,
uint8_t **dst_ptr) {
// hex_to_u32_nocheck fills high 16 bits of the return value with 1s if the
// conversion isn't valid; we defer the check for this to inside the
// multilingual plane check
uint32_t code_point = hex_to_u32_nocheck(*src_ptr + 2);
*src_ptr += 6;
// check for low surrogate for characters outside the Basic
// Multilingual Plane.
if (code_point >= 0xd800 && code_point < 0xdc00) {
if (((*src_ptr)[0] != '\\') || (*src_ptr)[1] != 'u') {
return false;
}
uint32_t code_point_2 = hex_to_u32_nocheck(*src_ptr + 2);
// if the first code point is invalid we will get here, as we will go past
// the check for being outside the Basic Multilingual plane. If we don't
// find a \u immediately afterwards we fail out anyhow, but if we do,
// this check catches both the case of the first code point being invalid
// or the second code point being invalid.
if ((code_point | code_point_2) >> 16) {
return false;
}
code_point =
(((code_point - 0xd800) << 10) | (code_point_2 - 0xdc00)) + 0x10000;
*src_ptr += 6;
}
size_t offset = codepoint_to_utf8(code_point, *dst_ptr);
*dst_ptr += offset;
return offset > 0;
}
WARN_UNUSED really_inline bool parse_string(UNUSED const uint8_t *buf,
UNUSED size_t len, ParsedJson &pj,
UNUSED const uint32_t depth,
UNUSED uint32_t offset) {
pj.write_tape(pj.current_string_buf_loc - pj.string_buf, '"');
const uint8_t *src = &buf[offset + 1]; /* we know that buf at offset is a " */
uint8_t *dst = pj.current_string_buf_loc + sizeof(uint32_t);
const uint8_t *const start_of_string = dst;
while (1) {
parse_string_helper helper = find_bs_bits_and_quote_bits(src, dst);
if (((helper.bs_bits - 1) & helper.quote_bits) != 0) {
/* we encountered quotes first. Move dst to point to quotes and exit
*/
/* find out where the quote is... */
uint32_t quote_dist = trailing_zeroes(helper.quote_bits);
/* NULL termination is still handy if you expect all your strings to
* be NULL terminated? */
/* It comes at a small cost */
dst[quote_dist] = 0;
uint32_t str_length = (dst - start_of_string) + quote_dist;
memcpy(pj.current_string_buf_loc, &str_length, sizeof(uint32_t));
/*****************************
* Above, check for overflow in case someone has a crazy string
* (>=4GB?) _
* But only add the overflow check when the document itself exceeds
* 4GB
* Currently unneeded because we refuse to parse docs larger or equal
* to 4GB.
****************************/
/* we advance the point, accounting for the fact that we have a NULL
* termination */
pj.current_string_buf_loc = dst + quote_dist + 1;
return true;
}
if (((helper.quote_bits - 1) & helper.bs_bits) != 0) {
/* find out where the backspace is */
uint32_t bs_dist = trailing_zeroes(helper.bs_bits);
uint8_t escape_char = src[bs_dist + 1];
/* we encountered backslash first. Handle backslash */
if (escape_char == 'u') {
/* move src/dst up to the start; they will be further adjusted
within the unicode codepoint handling code. */
src += bs_dist;
dst += bs_dist;
if (!handle_unicode_codepoint(&src, &dst)) {
return false;
}
} else {
/* simple 1:1 conversion. Will eat bs_dist+2 characters in input and
* write bs_dist+1 characters to output
* note this may reach beyond the part of the buffer we've actually
* seen. I think this is ok */
uint8_t escape_result = escape_map[escape_char];
if (escape_result == 0u) {
return false; /* bogus escape value is an error */
}
dst[bs_dist] = escape_result;
src += bs_dist + 2;
dst += bs_dist + 1;
}
} else {
/* they are the same. Since they can't co-occur, it means we
* encountered neither. */
src += helper.bytes_processed();
dst += helper.bytes_processed();
}
}
/* can't be reached */
return true;
}
} // namespace simdjson::westmere
UNTARGET_REGION
#endif // IS_X86_64
#endif
/* end file src/westmere/stringparsing.h */
/* begin file src/arm64/stage2_build_tape.h */
#ifndef SIMDJSON_ARM64_STAGE2_BUILD_TAPE_H
#define SIMDJSON_ARM64_STAGE2_BUILD_TAPE_H
#ifdef IS_ARM64
namespace simdjson::arm64 {
// This file contains the common code every implementation uses for stage2
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "simdjson/stage2_build_tape.h" (this simplifies amalgation)
// this macro reads the next structural character, updating idx, i and c.
#define UPDATE_CHAR() \
{ \
idx = pj.structural_indexes[i++]; \
c = buf[idx]; \
}
#ifdef SIMDJSON_USE_COMPUTED_GOTO
#define SET_GOTO_ARRAY_CONTINUE() pj.ret_address[depth] = &&array_continue;
#define SET_GOTO_OBJECT_CONTINUE() pj.ret_address[depth] = &&object_continue;
#define SET_GOTO_START_CONTINUE() pj.ret_address[depth] = &&start_continue;
#define GOTO_CONTINUE() goto *pj.ret_address[depth];
#else
#define SET_GOTO_ARRAY_CONTINUE() pj.ret_address[depth] = 'a';
#define SET_GOTO_OBJECT_CONTINUE() pj.ret_address[depth] = 'o';
#define SET_GOTO_START_CONTINUE() pj.ret_address[depth] = 's';
#define GOTO_CONTINUE() \
{ \
if (pj.ret_address[depth] == 'a') { \
goto array_continue; \
} else if (pj.ret_address[depth] == 'o') { \
goto object_continue; \
} else { \
goto start_continue; \
} \
}
#endif
/************
* The JSON is parsed to a tape, see the accompanying tape.md file
* for documentation.
***********/
WARN_UNUSED int
unified_machine(const uint8_t *buf, size_t len, ParsedJson &pj) {
uint32_t i = 0; /* index of the structural character (0,1,2,3...) */
uint32_t idx; /* location of the structural character in the input (buf) */
uint8_t c; /* used to track the (structural) character we are looking at,
updated */
/* by UPDATE_CHAR macro */
uint32_t depth = 0; /* could have an arbitrary starting depth */
pj.init(); /* sets is_valid to false */
if (pj.byte_capacity < len) {
pj.error_code = simdjson::CAPACITY;
return pj.error_code;
}
/*//////////////////////////// START STATE /////////////////////////////
*/
SET_GOTO_START_CONTINUE()
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, 'r'); /* r for root, 0 is going to get overwritten */
/* the root is used, if nothing else, to capture the size of the tape */
depth++; /* everything starts at depth = 1, depth = 0 is just for the
root, the root may contain an object, an array or something
else. */
if (depth >= pj.depth_capacity) {
goto fail;
}
UPDATE_CHAR();
switch (c) {
case '{':
pj.containing_scope_offset[depth] = pj.get_current_loc();
SET_GOTO_START_CONTINUE();
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
pj.write_tape(
0, c); /* strangely, moving this to object_begin slows things down */
goto object_begin;
case '[':
pj.containing_scope_offset[depth] = pj.get_current_loc();
SET_GOTO_START_CONTINUE();
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
pj.write_tape(0, c);
goto array_begin;
/* #define SIMDJSON_ALLOWANYTHINGINROOT
* A JSON text is a serialized value. Note that certain previous
* specifications of JSON constrained a JSON text to be an object or an
* array. Implementations that generate only objects or arrays where a
* JSON text is called for will be interoperable in the sense that all
* implementations will accept these as conforming JSON texts.
* https://tools.ietf.org/html/rfc8259
* #ifdef SIMDJSON_ALLOWANYTHINGINROOT */
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the true value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_true_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case 'f': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the false
* value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_false_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case 'n': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the null value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_null_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this is done only for JSON documents made of a sole number
* this will almost never be called in practice. We terminate with a
* space
* because we do not want to allow NULLs in the middle of a number
* (whereas a
* space in the middle of a number would be identified in stage 1). */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!parse_number(reinterpret_cast<const uint8_t *>(copy), pj, idx,
false)) {
free(copy);
goto fail;
}
free(copy);
break;
}
case '-': {
/* we need to make a copy to make sure that the string is NULL
* terminated.
* this is done only for JSON documents made of a sole number
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!parse_number(reinterpret_cast<const uint8_t *>(copy), pj, idx, true)) {
free(copy);
goto fail;
}
free(copy);
break;
}
default:
goto fail;
}
start_continue:
/* the string might not be NULL terminated. */
if (i + 1 == pj.n_structural_indexes) {
goto succeed;
} else {
goto fail;
}
/*//////////////////////////// OBJECT STATES ///////////////////////////*/
object_begin:
UPDATE_CHAR();
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
goto object_key_state;
}
case '}':
goto scope_end; /* could also go to object_continue */
default:
goto fail;
}
object_key_state:
UPDATE_CHAR();
if (c != ':') {
goto fail;
}
UPDATE_CHAR();
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't':
if (!is_valid_true_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'f':
if (!is_valid_false_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'n':
if (!is_valid_null_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
if (!parse_number(buf, pj, idx, false)) {
goto fail;
}
break;
}
case '-': {
if (!parse_number(buf, pj, idx, true)) {
goto fail;
}
break;
}
case '{': {
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
/* we have not yet encountered } so we need to come back for it */
SET_GOTO_OBJECT_CONTINUE()
/* we found an object inside an object, so we need to increment the
* depth */
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto object_begin;
}
case '[': {
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
/* we have not yet encountered } so we need to come back for it */
SET_GOTO_OBJECT_CONTINUE()
/* we found an array inside an object, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto array_begin;
}
default:
goto fail;
}
object_continue:
UPDATE_CHAR();
switch (c) {
case ',':
UPDATE_CHAR();
if (c != '"') {
goto fail;
} else {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
goto object_key_state;
}
case '}':
goto scope_end;
default:
goto fail;
}
/*//////////////////////////// COMMON STATE ///////////////////////////*/
scope_end:
/* write our tape location to the header scope */
depth--;
pj.write_tape(pj.containing_scope_offset[depth], c);
pj.annotate_previous_loc(pj.containing_scope_offset[depth],
pj.get_current_loc());
/* goto saved_state */
GOTO_CONTINUE()
/*//////////////////////////// ARRAY STATES ///////////////////////////*/
array_begin:
UPDATE_CHAR();
if (c == ']') {
goto scope_end; /* could also go to array_continue */
}
main_array_switch:
/* we call update char on all paths in, so we can peek at c on the
* on paths that can accept a close square brace (post-, and at start) */
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't':
if (!is_valid_true_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'f':
if (!is_valid_false_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'n':
if (!is_valid_null_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break; /* goto array_continue; */
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
if (!parse_number(buf, pj, idx, false)) {
goto fail;
}
break; /* goto array_continue; */
}
case '-': {
if (!parse_number(buf, pj, idx, true)) {
goto fail;
}
break; /* goto array_continue; */
}
case '{': {
/* we have not yet encountered ] so we need to come back for it */
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
SET_GOTO_ARRAY_CONTINUE()
/* we found an object inside an array, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto object_begin;
}
case '[': {
/* we have not yet encountered ] so we need to come back for it */
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
SET_GOTO_ARRAY_CONTINUE()
/* we found an array inside an array, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto array_begin;
}
default:
goto fail;
}
array_continue:
UPDATE_CHAR();
switch (c) {
case ',':
UPDATE_CHAR();
goto main_array_switch;
case ']':
goto scope_end;
default:
goto fail;
}
/*//////////////////////////// FINAL STATES ///////////////////////////*/
succeed:
depth--;
if (depth != 0) {
fprintf(stderr, "internal bug\n");
abort();
}
if (pj.containing_scope_offset[depth] != 0) {
fprintf(stderr, "internal bug\n");
abort();
}
pj.annotate_previous_loc(pj.containing_scope_offset[depth],
pj.get_current_loc());
pj.write_tape(pj.containing_scope_offset[depth], 'r'); /* r is root */
pj.valid = true;
pj.error_code = simdjson::SUCCESS;
return pj.error_code;
fail:
/* we do not need the next line because this is done by pj.init(),
* pessimistically.
* pj.is_valid = false;
* At this point in the code, we have all the time in the world.
* Note that we know exactly where we are in the document so we could,
* without any overhead on the processing code, report a specific
* location.
* We could even trigger special code paths to assess what happened
* carefully,
* all without any added cost. */
if (depth >= pj.depth_capacity) {
pj.error_code = simdjson::DEPTH_ERROR;
return pj.error_code;
}
switch (c) {
case '"':
pj.error_code = simdjson::STRING_ERROR;
return pj.error_code;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
pj.error_code = simdjson::NUMBER_ERROR;
return pj.error_code;
case 't':
pj.error_code = simdjson::T_ATOM_ERROR;
return pj.error_code;
case 'n':
pj.error_code = simdjson::N_ATOM_ERROR;
return pj.error_code;
case 'f':
pj.error_code = simdjson::F_ATOM_ERROR;
return pj.error_code;
default:
break;
}
pj.error_code = simdjson::TAPE_ERROR;
return pj.error_code;
}
} // namespace simdjson::arm64
namespace simdjson {
template <>
WARN_UNUSED int
unified_machine<Architecture::ARM64>(const uint8_t *buf, size_t len, ParsedJson &pj) {
return arm64::unified_machine(buf, len, pj);
}
} // namespace simdjson
#endif // IS_ARM64
#endif // SIMDJSON_ARM64_STAGE2_BUILD_TAPE_H
/* end file src/arm64/stage2_build_tape.h */
/* begin file src/haswell/stage2_build_tape.h */
#ifndef SIMDJSON_HASWELL_STAGE2_BUILD_TAPE_H
#define SIMDJSON_HASWELL_STAGE2_BUILD_TAPE_H
#ifdef IS_X86_64
TARGET_HASWELL
namespace simdjson::haswell {
// This file contains the common code every implementation uses for stage2
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "simdjson/stage2_build_tape.h" (this simplifies amalgation)
// this macro reads the next structural character, updating idx, i and c.
#define UPDATE_CHAR() \
{ \
idx = pj.structural_indexes[i++]; \
c = buf[idx]; \
}
#ifdef SIMDJSON_USE_COMPUTED_GOTO
#define SET_GOTO_ARRAY_CONTINUE() pj.ret_address[depth] = &&array_continue;
#define SET_GOTO_OBJECT_CONTINUE() pj.ret_address[depth] = &&object_continue;
#define SET_GOTO_START_CONTINUE() pj.ret_address[depth] = &&start_continue;
#define GOTO_CONTINUE() goto *pj.ret_address[depth];
#else
#define SET_GOTO_ARRAY_CONTINUE() pj.ret_address[depth] = 'a';
#define SET_GOTO_OBJECT_CONTINUE() pj.ret_address[depth] = 'o';
#define SET_GOTO_START_CONTINUE() pj.ret_address[depth] = 's';
#define GOTO_CONTINUE() \
{ \
if (pj.ret_address[depth] == 'a') { \
goto array_continue; \
} else if (pj.ret_address[depth] == 'o') { \
goto object_continue; \
} else { \
goto start_continue; \
} \
}
#endif
/************
* The JSON is parsed to a tape, see the accompanying tape.md file
* for documentation.
***********/
WARN_UNUSED int
unified_machine(const uint8_t *buf, size_t len, ParsedJson &pj) {
uint32_t i = 0; /* index of the structural character (0,1,2,3...) */
uint32_t idx; /* location of the structural character in the input (buf) */
uint8_t c; /* used to track the (structural) character we are looking at,
updated */
/* by UPDATE_CHAR macro */
uint32_t depth = 0; /* could have an arbitrary starting depth */
pj.init(); /* sets is_valid to false */
if (pj.byte_capacity < len) {
pj.error_code = simdjson::CAPACITY;
return pj.error_code;
}
/*//////////////////////////// START STATE /////////////////////////////
*/
SET_GOTO_START_CONTINUE()
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, 'r'); /* r for root, 0 is going to get overwritten */
/* the root is used, if nothing else, to capture the size of the tape */
depth++; /* everything starts at depth = 1, depth = 0 is just for the
root, the root may contain an object, an array or something
else. */
if (depth >= pj.depth_capacity) {
goto fail;
}
UPDATE_CHAR();
switch (c) {
case '{':
pj.containing_scope_offset[depth] = pj.get_current_loc();
SET_GOTO_START_CONTINUE();
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
pj.write_tape(
0, c); /* strangely, moving this to object_begin slows things down */
goto object_begin;
case '[':
pj.containing_scope_offset[depth] = pj.get_current_loc();
SET_GOTO_START_CONTINUE();
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
pj.write_tape(0, c);
goto array_begin;
/* #define SIMDJSON_ALLOWANYTHINGINROOT
* A JSON text is a serialized value. Note that certain previous
* specifications of JSON constrained a JSON text to be an object or an
* array. Implementations that generate only objects or arrays where a
* JSON text is called for will be interoperable in the sense that all
* implementations will accept these as conforming JSON texts.
* https://tools.ietf.org/html/rfc8259
* #ifdef SIMDJSON_ALLOWANYTHINGINROOT */
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the true value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_true_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case 'f': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the false
* value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_false_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case 'n': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the null value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_null_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this is done only for JSON documents made of a sole number
* this will almost never be called in practice. We terminate with a
* space
* because we do not want to allow NULLs in the middle of a number
* (whereas a
* space in the middle of a number would be identified in stage 1). */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!parse_number(reinterpret_cast<const uint8_t *>(copy), pj, idx,
false)) {
free(copy);
goto fail;
}
free(copy);
break;
}
case '-': {
/* we need to make a copy to make sure that the string is NULL
* terminated.
* this is done only for JSON documents made of a sole number
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!parse_number(reinterpret_cast<const uint8_t *>(copy), pj, idx, true)) {
free(copy);
goto fail;
}
free(copy);
break;
}
default:
goto fail;
}
start_continue:
/* the string might not be NULL terminated. */
if (i + 1 == pj.n_structural_indexes) {
goto succeed;
} else {
goto fail;
}
/*//////////////////////////// OBJECT STATES ///////////////////////////*/
object_begin:
UPDATE_CHAR();
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
goto object_key_state;
}
case '}':
goto scope_end; /* could also go to object_continue */
default:
goto fail;
}
object_key_state:
UPDATE_CHAR();
if (c != ':') {
goto fail;
}
UPDATE_CHAR();
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't':
if (!is_valid_true_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'f':
if (!is_valid_false_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'n':
if (!is_valid_null_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
if (!parse_number(buf, pj, idx, false)) {
goto fail;
}
break;
}
case '-': {
if (!parse_number(buf, pj, idx, true)) {
goto fail;
}
break;
}
case '{': {
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
/* we have not yet encountered } so we need to come back for it */
SET_GOTO_OBJECT_CONTINUE()
/* we found an object inside an object, so we need to increment the
* depth */
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto object_begin;
}
case '[': {
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
/* we have not yet encountered } so we need to come back for it */
SET_GOTO_OBJECT_CONTINUE()
/* we found an array inside an object, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto array_begin;
}
default:
goto fail;
}
object_continue:
UPDATE_CHAR();
switch (c) {
case ',':
UPDATE_CHAR();
if (c != '"') {
goto fail;
} else {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
goto object_key_state;
}
case '}':
goto scope_end;
default:
goto fail;
}
/*//////////////////////////// COMMON STATE ///////////////////////////*/
scope_end:
/* write our tape location to the header scope */
depth--;
pj.write_tape(pj.containing_scope_offset[depth], c);
pj.annotate_previous_loc(pj.containing_scope_offset[depth],
pj.get_current_loc());
/* goto saved_state */
GOTO_CONTINUE()
/*//////////////////////////// ARRAY STATES ///////////////////////////*/
array_begin:
UPDATE_CHAR();
if (c == ']') {
goto scope_end; /* could also go to array_continue */
}
main_array_switch:
/* we call update char on all paths in, so we can peek at c on the
* on paths that can accept a close square brace (post-, and at start) */
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't':
if (!is_valid_true_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'f':
if (!is_valid_false_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'n':
if (!is_valid_null_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break; /* goto array_continue; */
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
if (!parse_number(buf, pj, idx, false)) {
goto fail;
}
break; /* goto array_continue; */
}
case '-': {
if (!parse_number(buf, pj, idx, true)) {
goto fail;
}
break; /* goto array_continue; */
}
case '{': {
/* we have not yet encountered ] so we need to come back for it */
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
SET_GOTO_ARRAY_CONTINUE()
/* we found an object inside an array, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto object_begin;
}
case '[': {
/* we have not yet encountered ] so we need to come back for it */
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
SET_GOTO_ARRAY_CONTINUE()
/* we found an array inside an array, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto array_begin;
}
default:
goto fail;
}
array_continue:
UPDATE_CHAR();
switch (c) {
case ',':
UPDATE_CHAR();
goto main_array_switch;
case ']':
goto scope_end;
default:
goto fail;
}
/*//////////////////////////// FINAL STATES ///////////////////////////*/
succeed:
depth--;
if (depth != 0) {
fprintf(stderr, "internal bug\n");
abort();
}
if (pj.containing_scope_offset[depth] != 0) {
fprintf(stderr, "internal bug\n");
abort();
}
pj.annotate_previous_loc(pj.containing_scope_offset[depth],
pj.get_current_loc());
pj.write_tape(pj.containing_scope_offset[depth], 'r'); /* r is root */
pj.valid = true;
pj.error_code = simdjson::SUCCESS;
return pj.error_code;
fail:
/* we do not need the next line because this is done by pj.init(),
* pessimistically.
* pj.is_valid = false;
* At this point in the code, we have all the time in the world.
* Note that we know exactly where we are in the document so we could,
* without any overhead on the processing code, report a specific
* location.
* We could even trigger special code paths to assess what happened
* carefully,
* all without any added cost. */
if (depth >= pj.depth_capacity) {
pj.error_code = simdjson::DEPTH_ERROR;
return pj.error_code;
}
switch (c) {
case '"':
pj.error_code = simdjson::STRING_ERROR;
return pj.error_code;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
pj.error_code = simdjson::NUMBER_ERROR;
return pj.error_code;
case 't':
pj.error_code = simdjson::T_ATOM_ERROR;
return pj.error_code;
case 'n':
pj.error_code = simdjson::N_ATOM_ERROR;
return pj.error_code;
case 'f':
pj.error_code = simdjson::F_ATOM_ERROR;
return pj.error_code;
default:
break;
}
pj.error_code = simdjson::TAPE_ERROR;
return pj.error_code;
}
} // namespace simdjson::haswell
UNTARGET_REGION
TARGET_HASWELL
namespace simdjson {
template <>
WARN_UNUSED int
unified_machine<Architecture::HASWELL>(const uint8_t *buf, size_t len, ParsedJson &pj) {
return haswell::unified_machine(buf, len, pj);
}
} // namespace simdjson
UNTARGET_REGION
#endif // IS_X86_64
#endif // SIMDJSON_HASWELL_STAGE2_BUILD_TAPE_H
/* end file src/haswell/stage2_build_tape.h */
/* begin file src/westmere/stage2_build_tape.h */
#ifndef SIMDJSON_WESTMERE_STAGE2_BUILD_TAPE_H
#define SIMDJSON_WESTMERE_STAGE2_BUILD_TAPE_H
#ifdef IS_X86_64
TARGET_WESTMERE
namespace simdjson::westmere {
// This file contains the common code every implementation uses for stage2
// It is intended to be included multiple times and compiled multiple times
// We assume the file in which it is include already includes
// "simdjson/stage2_build_tape.h" (this simplifies amalgation)
// this macro reads the next structural character, updating idx, i and c.
#define UPDATE_CHAR() \
{ \
idx = pj.structural_indexes[i++]; \
c = buf[idx]; \
}
#ifdef SIMDJSON_USE_COMPUTED_GOTO
#define SET_GOTO_ARRAY_CONTINUE() pj.ret_address[depth] = &&array_continue;
#define SET_GOTO_OBJECT_CONTINUE() pj.ret_address[depth] = &&object_continue;
#define SET_GOTO_START_CONTINUE() pj.ret_address[depth] = &&start_continue;
#define GOTO_CONTINUE() goto *pj.ret_address[depth];
#else
#define SET_GOTO_ARRAY_CONTINUE() pj.ret_address[depth] = 'a';
#define SET_GOTO_OBJECT_CONTINUE() pj.ret_address[depth] = 'o';
#define SET_GOTO_START_CONTINUE() pj.ret_address[depth] = 's';
#define GOTO_CONTINUE() \
{ \
if (pj.ret_address[depth] == 'a') { \
goto array_continue; \
} else if (pj.ret_address[depth] == 'o') { \
goto object_continue; \
} else { \
goto start_continue; \
} \
}
#endif
/************
* The JSON is parsed to a tape, see the accompanying tape.md file
* for documentation.
***********/
WARN_UNUSED int
unified_machine(const uint8_t *buf, size_t len, ParsedJson &pj) {
uint32_t i = 0; /* index of the structural character (0,1,2,3...) */
uint32_t idx; /* location of the structural character in the input (buf) */
uint8_t c; /* used to track the (structural) character we are looking at,
updated */
/* by UPDATE_CHAR macro */
uint32_t depth = 0; /* could have an arbitrary starting depth */
pj.init(); /* sets is_valid to false */
if (pj.byte_capacity < len) {
pj.error_code = simdjson::CAPACITY;
return pj.error_code;
}
/*//////////////////////////// START STATE /////////////////////////////
*/
SET_GOTO_START_CONTINUE()
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, 'r'); /* r for root, 0 is going to get overwritten */
/* the root is used, if nothing else, to capture the size of the tape */
depth++; /* everything starts at depth = 1, depth = 0 is just for the
root, the root may contain an object, an array or something
else. */
if (depth >= pj.depth_capacity) {
goto fail;
}
UPDATE_CHAR();
switch (c) {
case '{':
pj.containing_scope_offset[depth] = pj.get_current_loc();
SET_GOTO_START_CONTINUE();
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
pj.write_tape(
0, c); /* strangely, moving this to object_begin slows things down */
goto object_begin;
case '[':
pj.containing_scope_offset[depth] = pj.get_current_loc();
SET_GOTO_START_CONTINUE();
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
pj.write_tape(0, c);
goto array_begin;
/* #define SIMDJSON_ALLOWANYTHINGINROOT
* A JSON text is a serialized value. Note that certain previous
* specifications of JSON constrained a JSON text to be an object or an
* array. Implementations that generate only objects or arrays where a
* JSON text is called for will be interoperable in the sense that all
* implementations will accept these as conforming JSON texts.
* https://tools.ietf.org/html/rfc8259
* #ifdef SIMDJSON_ALLOWANYTHINGINROOT */
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the true value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_true_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case 'f': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the false
* value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_false_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case 'n': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this only applies to the JSON document made solely of the null value.
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!is_valid_null_atom(reinterpret_cast<const uint8_t *>(copy) + idx)) {
free(copy);
goto fail;
}
free(copy);
pj.write_tape(0, c);
break;
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
/* we need to make a copy to make sure that the string is space
* terminated.
* this is done only for JSON documents made of a sole number
* this will almost never be called in practice. We terminate with a
* space
* because we do not want to allow NULLs in the middle of a number
* (whereas a
* space in the middle of a number would be identified in stage 1). */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!parse_number(reinterpret_cast<const uint8_t *>(copy), pj, idx,
false)) {
free(copy);
goto fail;
}
free(copy);
break;
}
case '-': {
/* we need to make a copy to make sure that the string is NULL
* terminated.
* this is done only for JSON documents made of a sole number
* this will almost never be called in practice */
char *copy = static_cast<char *>(malloc(len + SIMDJSON_PADDING));
if (copy == nullptr) {
goto fail;
}
memcpy(copy, buf, len);
copy[len] = ' ';
if (!parse_number(reinterpret_cast<const uint8_t *>(copy), pj, idx, true)) {
free(copy);
goto fail;
}
free(copy);
break;
}
default:
goto fail;
}
start_continue:
/* the string might not be NULL terminated. */
if (i + 1 == pj.n_structural_indexes) {
goto succeed;
} else {
goto fail;
}
/*//////////////////////////// OBJECT STATES ///////////////////////////*/
object_begin:
UPDATE_CHAR();
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
goto object_key_state;
}
case '}':
goto scope_end; /* could also go to object_continue */
default:
goto fail;
}
object_key_state:
UPDATE_CHAR();
if (c != ':') {
goto fail;
}
UPDATE_CHAR();
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't':
if (!is_valid_true_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'f':
if (!is_valid_false_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'n':
if (!is_valid_null_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
if (!parse_number(buf, pj, idx, false)) {
goto fail;
}
break;
}
case '-': {
if (!parse_number(buf, pj, idx, true)) {
goto fail;
}
break;
}
case '{': {
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
/* we have not yet encountered } so we need to come back for it */
SET_GOTO_OBJECT_CONTINUE()
/* we found an object inside an object, so we need to increment the
* depth */
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto object_begin;
}
case '[': {
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
/* we have not yet encountered } so we need to come back for it */
SET_GOTO_OBJECT_CONTINUE()
/* we found an array inside an object, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto array_begin;
}
default:
goto fail;
}
object_continue:
UPDATE_CHAR();
switch (c) {
case ',':
UPDATE_CHAR();
if (c != '"') {
goto fail;
} else {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
goto object_key_state;
}
case '}':
goto scope_end;
default:
goto fail;
}
/*//////////////////////////// COMMON STATE ///////////////////////////*/
scope_end:
/* write our tape location to the header scope */
depth--;
pj.write_tape(pj.containing_scope_offset[depth], c);
pj.annotate_previous_loc(pj.containing_scope_offset[depth],
pj.get_current_loc());
/* goto saved_state */
GOTO_CONTINUE()
/*//////////////////////////// ARRAY STATES ///////////////////////////*/
array_begin:
UPDATE_CHAR();
if (c == ']') {
goto scope_end; /* could also go to array_continue */
}
main_array_switch:
/* we call update char on all paths in, so we can peek at c on the
* on paths that can accept a close square brace (post-, and at start) */
switch (c) {
case '"': {
if (!parse_string(buf, len, pj, depth, idx)) {
goto fail;
}
break;
}
case 't':
if (!is_valid_true_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'f':
if (!is_valid_false_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break;
case 'n':
if (!is_valid_null_atom(buf + idx)) {
goto fail;
}
pj.write_tape(0, c);
break; /* goto array_continue; */
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
if (!parse_number(buf, pj, idx, false)) {
goto fail;
}
break; /* goto array_continue; */
}
case '-': {
if (!parse_number(buf, pj, idx, true)) {
goto fail;
}
break; /* goto array_continue; */
}
case '{': {
/* we have not yet encountered ] so we need to come back for it */
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
SET_GOTO_ARRAY_CONTINUE()
/* we found an object inside an array, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto object_begin;
}
case '[': {
/* we have not yet encountered ] so we need to come back for it */
pj.containing_scope_offset[depth] = pj.get_current_loc();
pj.write_tape(0, c); /* here the compilers knows what c is so this gets
optimized */
SET_GOTO_ARRAY_CONTINUE()
/* we found an array inside an array, so we need to increment the depth
*/
depth++;
if (depth >= pj.depth_capacity) {
goto fail;
}
goto array_begin;
}
default:
goto fail;
}
array_continue:
UPDATE_CHAR();
switch (c) {
case ',':
UPDATE_CHAR();
goto main_array_switch;
case ']':
goto scope_end;
default:
goto fail;
}
/*//////////////////////////// FINAL STATES ///////////////////////////*/
succeed:
depth--;
if (depth != 0) {
fprintf(stderr, "internal bug\n");
abort();
}
if (pj.containing_scope_offset[depth] != 0) {
fprintf(stderr, "internal bug\n");
abort();
}
pj.annotate_previous_loc(pj.containing_scope_offset[depth],
pj.get_current_loc());
pj.write_tape(pj.containing_scope_offset[depth], 'r'); /* r is root */
pj.valid = true;
pj.error_code = simdjson::SUCCESS;
return pj.error_code;
fail:
/* we do not need the next line because this is done by pj.init(),
* pessimistically.
* pj.is_valid = false;
* At this point in the code, we have all the time in the world.
* Note that we know exactly where we are in the document so we could,
* without any overhead on the processing code, report a specific
* location.
* We could even trigger special code paths to assess what happened
* carefully,
* all without any added cost. */
if (depth >= pj.depth_capacity) {
pj.error_code = simdjson::DEPTH_ERROR;
return pj.error_code;
}
switch (c) {
case '"':
pj.error_code = simdjson::STRING_ERROR;
return pj.error_code;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
pj.error_code = simdjson::NUMBER_ERROR;
return pj.error_code;
case 't':
pj.error_code = simdjson::T_ATOM_ERROR;
return pj.error_code;
case 'n':
pj.error_code = simdjson::N_ATOM_ERROR;
return pj.error_code;
case 'f':
pj.error_code = simdjson::F_ATOM_ERROR;
return pj.error_code;
default:
break;
}
pj.error_code = simdjson::TAPE_ERROR;
return pj.error_code;
}
} // namespace simdjson::westmere
UNTARGET_REGION
TARGET_WESTMERE
namespace simdjson {
template <>
WARN_UNUSED int
unified_machine<Architecture::WESTMERE>(const uint8_t *buf, size_t len, ParsedJson &pj) {
return westmere::unified_machine(buf, len, pj);
}
} // namespace simdjson
UNTARGET_REGION
#endif // IS_X86_64
#endif // SIMDJSON_WESTMERE_STAGE2_BUILD_TAPE_H
/* end file src/westmere/stage2_build_tape.h */
/* begin file src/stage2_build_tape.cpp */
/* end file src/stage2_build_tape.cpp */
/* begin file src/parsedjson.cpp */
namespace simdjson {
ParsedJson::ParsedJson()
: structural_indexes(nullptr), tape(nullptr),
containing_scope_offset(nullptr), ret_address(nullptr),
string_buf(nullptr), current_string_buf_loc(nullptr) {}
ParsedJson::~ParsedJson() { deallocate(); }
ParsedJson::ParsedJson(ParsedJson &&p)
: byte_capacity(p.byte_capacity), depth_capacity(p.depth_capacity),
tape_capacity(p.tape_capacity), string_capacity(p.string_capacity),
current_loc(p.current_loc), n_structural_indexes(p.n_structural_indexes),
structural_indexes(p.structural_indexes), tape(p.tape),
containing_scope_offset(p.containing_scope_offset),
ret_address(p.ret_address), string_buf(p.string_buf),
current_string_buf_loc(p.current_string_buf_loc), valid(p.valid) {
p.structural_indexes = nullptr;
p.tape = nullptr;
p.containing_scope_offset = nullptr;
p.ret_address = nullptr;
p.string_buf = nullptr;
p.current_string_buf_loc = nullptr;
}
WARN_UNUSED
bool ParsedJson::allocate_capacity(size_t len, size_t max_depth) {
if (max_depth <= 0) {
max_depth = 1; // don't let the user allocate nothing
}
if (len <= 0) {
len = 64; // allocating 0 bytes is wasteful.
}
if (len > SIMDJSON_MAXSIZE_BYTES) {
return false;
}
if ((len <= byte_capacity) && (max_depth <= depth_capacity)) {
return true;
}
deallocate();
valid = false;
byte_capacity = 0; // will only set it to len after allocations are a success
n_structural_indexes = 0;
uint32_t max_structures = ROUNDUP_N(len, 64) + 2 + 7;
structural_indexes = new (std::nothrow) uint32_t[max_structures];
// a pathological input like "[[[[..." would generate len tape elements, so
// need a capacity of len + 1
size_t local_tape_capacity = ROUNDUP_N(len + 1, 64);
// a document with only zero-length strings... could have len/3 string
// and we would need len/3 * 5 bytes on the string buffer
size_t local_string_capacity = ROUNDUP_N(5 * len / 3 + 32, 64);
string_buf = new (std::nothrow) uint8_t[local_string_capacity];
tape = new (std::nothrow) uint64_t[local_tape_capacity];
containing_scope_offset = new (std::nothrow) uint32_t[max_depth];
#ifdef SIMDJSON_USE_COMPUTED_GOTO
ret_address = new (std::nothrow) void *[max_depth];
#else
ret_address = new (std::nothrow) char[max_depth];
#endif
if ((string_buf == nullptr) || (tape == nullptr) ||
(containing_scope_offset == nullptr) || (ret_address == nullptr) ||
(structural_indexes == nullptr)) {
std::cerr << "Could not allocate memory" << std::endl;
delete[] ret_address;
delete[] containing_scope_offset;
delete[] tape;
delete[] string_buf;
delete[] structural_indexes;
return false;
}
/*
// We do not need to initialize this content for parsing, though we could
// need to initialize it for safety.
memset(string_buf, 0 , local_string_capacity);
memset(structural_indexes, 0, max_structures * sizeof(uint32_t));
memset(tape, 0, local_tape_capacity * sizeof(uint64_t));
*/
byte_capacity = len;
depth_capacity = max_depth;
tape_capacity = local_tape_capacity;
string_capacity = local_string_capacity;
return true;
}
bool ParsedJson::is_valid() const { return valid; }
int ParsedJson::get_error_code() const { return error_code; }
std::string ParsedJson::get_error_message() const {
return error_message(error_code);
}
void ParsedJson::deallocate() {
byte_capacity = 0;
depth_capacity = 0;
tape_capacity = 0;
string_capacity = 0;
delete[] ret_address;
delete[] containing_scope_offset;
delete[] tape;
delete[] string_buf;
delete[] structural_indexes;
valid = false;
}
void ParsedJson::init() {
current_string_buf_loc = string_buf;
current_loc = 0;
valid = false;
}
WARN_UNUSED
bool ParsedJson::print_json(std::ostream &os) const {
if (!valid) {
return false;
}
uint32_t string_length;
size_t tape_idx = 0;
uint64_t tape_val = tape[tape_idx];
uint8_t type = (tape_val >> 56);
size_t how_many = 0;
if (type == 'r') {
how_many = tape_val & JSON_VALUE_MASK;
} else {
fprintf(stderr, "Error: no starting root node?");
return false;
}
if (how_many > tape_capacity) {
fprintf(
stderr,
"We may be exceeding the tape capacity. Is this a valid document?\n");
return false;
}
tape_idx++;
bool *in_object = new bool[depth_capacity];
auto *in_object_idx = new size_t[depth_capacity];
int depth = 1; // only root at level 0
in_object_idx[depth] = 0;
in_object[depth] = false;
for (; tape_idx < how_many; tape_idx++) {
tape_val = tape[tape_idx];
uint64_t payload = tape_val & JSON_VALUE_MASK;
type = (tape_val >> 56);
if (!in_object[depth]) {
if ((in_object_idx[depth] > 0) && (type != ']')) {
os << ",";
}
in_object_idx[depth]++;
} else { // if (in_object) {
if ((in_object_idx[depth] > 0) && ((in_object_idx[depth] & 1) == 0) &&
(type != '}')) {
os << ",";
}
if (((in_object_idx[depth] & 1) == 1)) {
os << ":";
}
in_object_idx[depth]++;
}
switch (type) {
case '"': // we have a string
os << '"';
memcpy(&string_length, string_buf + payload, sizeof(uint32_t));
print_with_escapes(
(const unsigned char *)(string_buf + payload + sizeof(uint32_t)),
string_length);
os << '"';
break;
case 'l': // we have a long int
if (tape_idx + 1 >= how_many) {
delete[] in_object;
delete[] in_object_idx;
return false;
}
os << static_cast<int64_t>(tape[++tape_idx]);
break;
case 'u':
if (tape_idx + 1 >= how_many) {
delete[] in_object;
delete[] in_object_idx;
return false;
}
os << tape[++tape_idx];
break;
case 'd': // we have a double
if (tape_idx + 1 >= how_many) {
delete[] in_object;
delete[] in_object_idx;
return false;
}
double answer;
memcpy(&answer, &tape[++tape_idx], sizeof(answer));
os << answer;
break;
case 'n': // we have a null
os << "null";
break;
case 't': // we have a true
os << "true";
break;
case 'f': // we have a false
os << "false";
break;
case '{': // we have an object
os << '{';
depth++;
in_object[depth] = true;
in_object_idx[depth] = 0;
break;
case '}': // we end an object
depth--;
os << '}';
break;
case '[': // we start an array
os << '[';
depth++;
in_object[depth] = false;
in_object_idx[depth] = 0;
break;
case ']': // we end an array
depth--;
os << ']';
break;
case 'r': // we start and end with the root node
fprintf(stderr, "should we be hitting the root node?\n");
delete[] in_object;
delete[] in_object_idx;
return false;
default:
fprintf(stderr, "bug %c\n", type);
delete[] in_object;
delete[] in_object_idx;
return false;
}
}
delete[] in_object;
delete[] in_object_idx;
return true;
}
WARN_UNUSED
bool ParsedJson::dump_raw_tape(std::ostream &os) const {
if (!valid) {
return false;
}
uint32_t string_length;
size_t tape_idx = 0;
uint64_t tape_val = tape[tape_idx];
uint8_t type = (tape_val >> 56);
os << tape_idx << " : " << type;
tape_idx++;
size_t how_many = 0;
if (type == 'r') {
how_many = tape_val & JSON_VALUE_MASK;
} else {
fprintf(stderr, "Error: no starting root node?");
return false;
}
os << "\t// pointing to " << how_many << " (right after last node)\n";
uint64_t payload;
for (; tape_idx < how_many; tape_idx++) {
os << tape_idx << " : ";
tape_val = tape[tape_idx];
payload = tape_val & JSON_VALUE_MASK;
type = (tape_val >> 56);
switch (type) {
case '"': // we have a string
os << "string \"";
memcpy(&string_length, string_buf + payload, sizeof(uint32_t));
print_with_escapes(
(const unsigned char *)(string_buf + payload + sizeof(uint32_t)),
string_length);
os << '"';
os << '\n';
break;
case 'l': // we have a long int
if (tape_idx + 1 >= how_many) {
return false;
}
os << "integer " << static_cast<int64_t>(tape[++tape_idx]) << "\n";
break;
case 'u': // we have a long uint
if (tape_idx + 1 >= how_many) {
return false;
}
os << "unsigned integer " << tape[++tape_idx] << "\n";
break;
case 'd': // we have a double
os << "float ";
if (tape_idx + 1 >= how_many) {
return false;
}
double answer;
memcpy(&answer, &tape[++tape_idx], sizeof(answer));
os << answer << '\n';
break;
case 'n': // we have a null
os << "null\n";
break;
case 't': // we have a true
os << "true\n";
break;
case 'f': // we have a false
os << "false\n";
break;
case '{': // we have an object
os << "{\t// pointing to next tape location " << payload
<< " (first node after the scope) \n";
break;
case '}': // we end an object
os << "}\t// pointing to previous tape location " << payload
<< " (start of the scope) \n";
break;
case '[': // we start an array
os << "[\t// pointing to next tape location " << payload
<< " (first node after the scope) \n";
break;
case ']': // we end an array
os << "]\t// pointing to previous tape location " << payload
<< " (start of the scope) \n";
break;
case 'r': // we start and end with the root node
printf("end of root\n");
return false;
default:
return false;
}
}
tape_val = tape[tape_idx];
payload = tape_val & JSON_VALUE_MASK;
type = (tape_val >> 56);
os << tape_idx << " : " << type << "\t// pointing to " << payload
<< " (start root)\n";
return true;
}
} // namespace simdjson
/* end file src/parsedjson.cpp */
/* begin file src/parsedjsoniterator.cpp */
namespace simdjson {
template class ParsedJson::BasicIterator<DEFAULT_MAX_DEPTH>;
} // namespace simdjson
/* end file src/parsedjsoniterator.cpp */
| 35.208633 | 126 | 0.634058 | [
"object"
] |
959d99eeac90f6f984653fda3ee80a559e9a1c36 | 1,116 | cpp | C++ | src/EvaluateReversePolishNotation.cpp | harborn/LeetCode | 8488c0bcf306b8672492fd6220e496e335e2b9fe | [
"MIT"
] | null | null | null | src/EvaluateReversePolishNotation.cpp | harborn/LeetCode | 8488c0bcf306b8672492fd6220e496e335e2b9fe | [
"MIT"
] | 1 | 2021-12-14T15:56:11.000Z | 2021-12-14T15:56:11.000Z | src/EvaluateReversePolishNotation.cpp | harborn/LeetCode | 8488c0bcf306b8672492fd6220e496e335e2b9fe | [
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
int evalRPN(vector<string> &tokens) {
stack<int> st;
int size = tokens.size();
int i = 0;
while (i < size) {
if (tokens[i] == "+") {
if (st.size() >= 2) {
int i1 = st.top(); st.pop();
int i2 = st.top(); st.pop();
st.push(i1 + i2);
}
}
else if (tokens[i] == "-") {
if (st.size() >= 2) {
int i1 = st.top(); st.pop();
int i2 = st.top(); st.pop();
st.push(i2 - i1);
}
}
else if (tokens[i] == "*") {
if (st.size() >= 2) {
int i1 = st.top(); st.pop();
int i2 = st.top(); st.pop();
st.push(i1 * i2);
}
}
else if (tokens[i] == "/") {
if (st.size() >= 2) {
int i1 = st.top(); st.pop();
int i2 = st.top(); st.pop();
st.push(i2 / i1);
}
}
else {
st.push(atoi(tokens[i].c_str()));
}
i++;
}
return st.top();
}
int main(void)
{
//string t[] = { "2", "1", "+", "3", "*" };
string t[] = { "4", "13", "5", "/", "+" };
vector<string> tokens;
tokens.insert(tokens.begin(), t, t + 5);
int res = evalRPN(tokens);
return 0;
} | 18 | 44 | 0.469534 | [
"vector"
] |
95a0498d5dbc1c105900dc74aa1a013d801373fe | 9,907 | cpp | C++ | airsim_ros_interface/src/kitti_utils.cpp | JonathanSchmalhofer/RecursiveStereoUAV | 005642f5afbfe719c632ce81411af9ac5e8522f5 | [
"MIT"
] | 15 | 2018-04-07T18:07:23.000Z | 2022-02-14T11:48:34.000Z | airsim_ros_interface/src/kitti_utils.cpp | JonathanSchmalhofer/RecursiveStereoUAV | 005642f5afbfe719c632ce81411af9ac5e8522f5 | [
"MIT"
] | 1 | 2017-10-21T12:55:07.000Z | 2017-10-21T14:33:09.000Z | airsim_ros_interface/src/kitti_utils.cpp | JonathanSchmalhofer/RecursiveStereoUAV | 005642f5afbfe719c632ce81411af9ac5e8522f5 | [
"MIT"
] | 8 | 2017-10-11T09:10:51.000Z | 2021-05-04T06:28:24.000Z | ///
/// @file
/// @copyright Copyright (C) 2017-2018, Jonathan Bryan Schmalhofer
///
/// @brief KITTI DataSet Utils
///
#include "kitti_utils.hpp"
namespace kitti_utils
{
// Source for GetFileList(): https://gist.github.com/vivithemage/9517678
std::vector<std::string> GetFileList(const std::string& path, const std::string extension)
{
std::vector<std::string> file_list;
if (!path.empty())
{
boost::filesystem::path apk_path(path);
boost::filesystem::recursive_directory_iterator end;
for (boost::filesystem::recursive_directory_iterator i(apk_path); i != end; ++i)
{
const boost::filesystem::path cp = (*i);
if (extension == boost::filesystem::extension(cp.string()))
{
file_list.push_back(cp.string());
}
}
}
std::sort(file_list.begin(), file_list.end());
return file_list;
}
/**
* Read the oxts-Textfile according to the frame number/index idx.
*
* Copied from: https://github.com/rpng/kitti_parser/blob/master/src/kitti_parser/util/Loader.cpp
*/
oxts_data KittiUtils::GetOxtsData(std::vector<std::string> filelist, std::vector<long> timestamps, std::size_t idx)
{
// Make new measurement
oxts_data datapoint;
datapoint.timestamp = timestamps.at(idx);
// Read in file of doubles
std::vector<double> values;
std::ifstream file_at_idx(filelist.at(idx), std::ios::in);
// Keep storing values from the text file so long as data exists:
double num = 0.0;
while (file_at_idx >> num)
{
values.push_back(num);
}
// Set values, see the file 'dataformat.txt' for details on each one
datapoint.lat = values.at(0);
datapoint.lon = values.at(1);
datapoint.alt = values.at(2);
datapoint.roll = values.at(3);
datapoint.pitch = values.at(4);
datapoint.yaw = values.at(5);
datapoint.vn = values.at(6);
datapoint.ve = values.at(7);
datapoint.vf = values.at(8);
datapoint.vl = values.at(9);
datapoint.vu = values.at(10);
datapoint.ax = values.at(11);
datapoint.ay = values.at(12);
datapoint.az = values.at(13);
datapoint.af = values.at(14);
datapoint.al = values.at(15);
datapoint.au = values.at(16);
datapoint.wx = values.at(17);
datapoint.wy = values.at(18);
datapoint.wz = values.at(19);
datapoint.wf = values.at(20);
datapoint.wl = values.at(21);
datapoint.wu = values.at(22);
datapoint.pos_accuracy = values.at(23);
datapoint.vel_accuracy = values.at(24);
datapoint.navstat = (int)values.at(25);
datapoint.numsats = (int)values.at(26);
datapoint.posmode = (int)values.at(27);
datapoint.velmode = (int)values.at(28);
datapoint.orimode = (int)values.at(29);
// Return it
return datapoint;
}
double KittiUtils::GetScale(std::vector<std::string> filelist)
{
// also read first file
std::vector<double> values;
std::ifstream first_file(filelist.at(0), std::ios::in);
// Keep storing values from the text file so long as data exists
double num = 0.0;
while (first_file >> num)
{
values.push_back(num);
}
// compute mercator scale from latitude - always use first (!) latitude value for this, not idx
// see also convertOxtsToPose.m in MATLAB dev kit from KITTI dataset
double scale = std::cos(values.at(0) * boost::math::constants::pi<double>() / 180.0f);
// Return it
return scale;
}
boost::numeric::ublas::matrix<double> KittiUtils::GetTr0(std::vector<std::string> filelist, double scale)
{
boost::numeric::ublas::matrix<double> Tr_0(4, 4);
std::vector<long> empty_timestamps;
empty_timestamps.push_back(0);
// Get the first point of the oxts data...
oxts_data first_data_point = GetOxtsData(filelist, empty_timestamps, 0);
// ...and convert the oxts-data into the Transformation of the first point
Tr_0 = GetTransformation(first_data_point, scale);
return Tr_0;
}
boost::numeric::ublas::matrix<double> KittiUtils::GetTransformation(oxts_data datapoint, double scale)
{
// Compare convertOxtsToPose.m from MATLAB DevKit of KITTI Dataset
boost::numeric::ublas::matrix<double> Tr(4, 4);
boost::numeric::ublas::matrix<double> Rx(3, 3);
boost::numeric::ublas::matrix<double> Ry(3, 3);
boost::numeric::ublas::matrix<double> Rz(3, 3);
boost::numeric::ublas::matrix<double> R(3, 3);
// converts lat/lon coordinates to mercator coordinates using mercator scale
// see latlonToMercator.m from MATLAB DevKit of KITTI Dataset
double er = 6378137;
double mx = scale * datapoint.lon * boost::math::constants::pi<double>() * er / 180.0f;
double my = scale * er * std::log( std::tan((90.0f+datapoint.lat) * boost::math::constants::pi<double>() / 360.0f) );
double mz = datapoint.alt;
// rotation matrix (OXTS RT3000 user manual, page 71/92)
//
// base => nav (level oxts => rotated oxts)
Rx(0,0) = 1; Rx(0,1) = 0; Rx(0,2) = 0;
Rx(1,0) = 0; Rx(1,1) = std::cos(datapoint.roll); Rx(1,2) = -std::sin(datapoint.roll);
Rx(2,0) = 0; Rx(2,1) = std::sin(datapoint.roll); Rx(2,2) = std::cos(datapoint.roll);
// base => nav (level oxts => rotated oxts)
Ry(0,0) = std::cos(datapoint.pitch); Ry(0,1) = 0; Ry(0,2) = std::sin(datapoint.pitch);
Ry(1,0) = 0; Ry(1,1) = 1; Ry(1,2) = 0;
Ry(2,0) = -std::sin(datapoint.pitch); Ry(2,1) = 0; Ry(2,2) = std::cos(datapoint.pitch);
// base => nav (level oxts => rotated oxts)
Rz(0,0) = std::cos(datapoint.yaw); Rz(0,1) = -std::sin(datapoint.yaw); Rz(0,2) = 0;
Rz(1,0) = std::sin(datapoint.yaw); Rz(1,1) = std::cos(datapoint.yaw); Rz(1,2) = 0;
Rz(2,0) = 0; Rz(2,1) = 0; Rz(2,2) = 1;
// R = Rz*Ry*Rx;
std::cout << "Rx = " << Rx << std::endl;
std::cout << "Ry = " << Ry << std::endl;
std::cout << "Rz = " << Rz << std::endl;
std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
R = boost::numeric::ublas::prod(Ry, Rx); std::cout << "Ry*Rx = " << R << std::endl;
R = boost::numeric::ublas::prod(Rz, R); std::cout << "Rz*Ry*Rx = " << R << std::endl;
// in Matlab notation: Tr = [R t;0 0 0 1];
// DOES NOT WORK: boost::numeric::ublas::project(Tr, boost::numeric::ublas::range(0,2), boost::numeric::ublas::range(0,2)) = R;
Tr(0,0) = R(0,0); Tr(0,1) = R(0,1); Tr(0,2) = R(0,2); Tr(0,3) = mx;
Tr(1,0) = R(1,0); Tr(1,1) = R(1,1); Tr(1,2) = R(1,2); Tr(1,3) = my;
Tr(2,0) = R(2,0); Tr(2,1) = R(2,1); Tr(2,2) = R(2,2); Tr(2,3) = mz;
Tr(3,0) = 0; Tr(3,1) = 0; Tr(3,2) = 0; Tr(3,3) = 1;
return Tr;
}
boost::numeric::ublas::matrix<double> KittiUtils::ConvertOxtsToPose(oxts_data datapoint, double scale, boost::numeric::ublas::matrix<double> Tr_0_inv)
{
boost::numeric::ublas::matrix<double> pose(4, 4);
boost::numeric::ublas::matrix<double> Tr(4, 4);
// in Matlab notation: pose = inv(Tr_0) * [R t;0 0 0 1]
// with Tr = [R t;0 0 0 1]
Tr = GetTransformation(datapoint, scale);
pose = boost::numeric::ublas::prod(Tr_0_inv, Tr);
return pose;
}
void KittiUtils::GetEulerAngles(boost::numeric::ublas::matrix<double> pose, double &roll, double &pitch, double &yaw)
{
// Normalize
pose /= pose(3,3);
Eigen::Matrix3d rot_matrix;
rot_matrix(0,0) = pose(0,0); rot_matrix(0,1) = pose(0,1); rot_matrix(0,2) = pose(0,2);
rot_matrix(1,0) = pose(1,0); rot_matrix(1,1) = pose(1,1); rot_matrix(1,2) = pose(1,2);
rot_matrix(2,0) = pose(2,0); rot_matrix(2,1) = pose(2,1); rot_matrix(2,2) = pose(2,2);
Eigen::Vector3d rot = rot_matrix.eulerAngles(0, 1, 2); // order: roll - pitch - yaw
roll = rot(0);
pitch = rot(1);
yaw = rot(2);
}
void KittiUtils::GetPosition(boost::numeric::ublas::matrix<double> pose, double &x, double &y, double &z)
{
// Normalize
pose /= pose(3,3);
x = pose(0,3);
y = pose(1,3);
z = pose(2,3);
}
KittiUtils::KittiUtils()
{
}
KittiUtils::~KittiUtils()
{
}
/**
* Loads a timestamp file based on the path given
*
* Copied from: https://github.com/rpng/kitti_parser/blob/master/src/kitti_parser/util/Loader.cpp
*/
void KittiUtils::LoadTimestamps(std::string path_timestamp_file, std::vector<long>& time, int& counter)
{
// Open the timestamp file
std::string line;
std::ifstream file_time(path_timestamp_file);
// Load the timestamps
while(getline(file_time, line))
{
// Skip empty lines
if(line.empty())
continue;
// Parse data
// http://www.boost.org/doc/libs/1_55_0/doc/html/date_time/posix_time.html#posix_ex
boost::posix_time::ptime posix_timestamp(boost::posix_time::time_from_string(line));
// Convert to long, subtract
long timestamp = (posix_timestamp - boost::posix_time::ptime{{1970,1,1}, {}}).total_milliseconds();
// Append
time.push_back(timestamp);
// Incrememt
counter++;
// Debug
//cout << line << " => " << timestamp << endl;
}
// Close file
file_time.close();
}
/**
* This will read in the GPS/IMU timestamp file
* From this it will also create the paths needed
*/
void KittiUtils::LoadOxtsLitePaths(std::string path_oxts_folder, std::vector<long>& time, std::vector<std::string>& filelist)
{
// Load the timestamps for this type
int count = 0;
LoadTimestamps(path_oxts_folder+"timestamps.txt", time, count);
filelist = GetFileList(path_oxts_folder+"data/", ".txt");
}
} // namespace kitti_utils
| 35.765343 | 150 | 0.595841 | [
"vector"
] |
95a68ba8cbe8c32972bc1a0b731f5797bf0b925e | 14,194 | cpp | C++ | FlingEngine/Graphics/src/OffscreenSubpass.cpp | BenjaFriend/EngineBay | 402d49dc4378f0672fb66053effa49867b8c6726 | [
"MIT"
] | 315 | 2019-07-27T23:24:26.000Z | 2022-03-23T18:55:31.000Z | FlingEngine/Graphics/src/OffscreenSubpass.cpp | flingengine/FlingEngine | 402d49dc4378f0672fb66053effa49867b8c6726 | [
"MIT"
] | 109 | 2019-07-14T19:47:03.000Z | 2022-02-23T21:34:45.000Z | FlingEngine/Graphics/src/OffscreenSubpass.cpp | BenjaFriend/EngineBay | 402d49dc4378f0672fb66053effa49867b8c6726 | [
"MIT"
] | 18 | 2019-11-03T16:06:26.000Z | 2022-01-23T03:32:19.000Z | #include "OffscreenSubpass.h"
#include "FrameBuffer.h"
#include "CommandBuffer.h"
#include "PhyscialDevice.h"
#include "LogicalDevice.h"
#include "GraphicsHelpers.h"
#include "Components/Transform.h"
#include "MeshRenderer.h"
#include "SwapChain.h"
#include "UniformBufferObject.h"
#include "FirstPersonCamera.h"
#include "FlingVulkan.h"
namespace Fling
{
OffscreenSubpass::OffscreenSubpass(
const LogicalDevice* t_Dev,
const Swapchain* t_Swap,
entt::registry& t_reg,
FirstPersonCamera* t_Cam,
std::shared_ptr<Fling::Shader> t_Vert,
std::shared_ptr<Fling::Shader> t_Frag)
: Subpass(t_Dev, t_Swap, t_Vert, t_Frag)
, m_Camera(t_Cam)
{
t_reg.on_construct<MeshRenderer>().connect<&OffscreenSubpass::OnMeshRendererAdded>(*this);
// Set the clear values for the G Buffer
m_ClearValues.resize(6);
m_ClearValues[0].color = m_ClearValues[1].color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
m_ClearValues[2].color = m_ClearValues[3].color = m_ClearValues[4].color = { { 0.0f, 0.0f, 0.0f, 0.0f } };
m_ClearValues[5].depthStencil = { 1.0f, 0 };
// Build offscreen semaphores -------
m_OffscreenSemaphores.resize(VkConfig::MAX_FRAMES_IN_FLIGHT);
for (int32 i = 0; i < VkConfig::MAX_FRAMES_IN_FLIGHT; i++)
{
m_OffscreenSemaphores[i] = GraphicsHelpers::CreateSemaphore(m_Device->GetVkDevice());
}
GraphicsHelpers::CreateCommandPool(&m_CommandPool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
// Build offscreen command buffers
m_OffscreenCmdBufs.resize(m_SwapChain->GetImageCount());
for (size_t i = 0; i < m_OffscreenCmdBufs.size(); ++i)
{
m_OffscreenCmdBufs[i] = new Fling::CommandBuffer(m_Device, m_CommandPool);
assert(m_OffscreenCmdBufs[i] != nullptr);
}
// Tell the Vulkan app that the draw command buffers need to WAIT on this offscreen semaphore
PrepareAttachments();
}
OffscreenSubpass::~OffscreenSubpass()
{
// Destroy any allocated semaphores
for (size_t i = 0; i < m_OffscreenSemaphores.size(); ++i)
{
vkDestroySemaphore(m_Device->GetVkDevice(), m_OffscreenSemaphores[i], nullptr);
}
// Clean up command buffers we used
for (CommandBuffer* CmdBuf : m_OffscreenCmdBufs)
{
if (CmdBuf)
{
delete CmdBuf;
CmdBuf = nullptr;
}
}
m_OffscreenCmdBufs.clear();
vkDestroyCommandPool(m_Device->GetVkDevice(), m_CommandPool, nullptr);
if (m_OffscreenFrameBuf)
{
delete m_OffscreenFrameBuf;
m_OffscreenFrameBuf = nullptr;
}
}
void OffscreenSubpass::Draw(
CommandBuffer& t_CmdBuf,
uint32 t_ActiveSwapImage,
entt::registry& t_reg,
float DeltaTime)
{
assert(m_GraphicsPipeline);
// Don't use the given command buffer, instead build the OFFSCREEN command buffer
CommandBuffer* OffscreenCmdBuf = m_OffscreenCmdBufs[t_ActiveSwapImage];
assert(OffscreenCmdBuf);
// Set viewport and scissors to the offscreen frame buffer
VkViewport viewport = Initializers::Viewport(
static_cast<float>(m_OffscreenFrameBuf->GetWidth()),
static_cast<float>(m_OffscreenFrameBuf->GetHeight()),
0.0f, 1.0f
);
VkRect2D scissor = Initializers::Rect2D(
m_OffscreenFrameBuf->GetWidth(),
m_OffscreenFrameBuf->GetHeight(),
/** offsetX */ 0,
/** offsetY */ 0
);
OffscreenCmdBuf->Begin();
OffscreenCmdBuf->BeginRenderPass(*m_OffscreenFrameBuf, m_ClearValues);
OffscreenCmdBuf->SetViewport(0, { viewport });
OffscreenCmdBuf->SetScissor(0, { scissor });
vkCmdBindPipeline(OffscreenCmdBuf->GetHandle(), VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline->GetPipeline());
VkDeviceSize offsets[1] = { 0 };
OffscreenUBO CurrentUBO = {};
// Invert the project value to match the proper coordinate space compared to OpenGL
CurrentUBO.Projection = m_Camera->GetProjectionMatrix();
CurrentUBO.Projection[1][1] *= -1.0f;
CurrentUBO.View = m_Camera->GetViewMatrix();
// #TODO This is where a lot of the cost of our engine loop comes from
// We can improve this by doing some kind of dirty bit tracking to only
// update the UBO's on MeshRenders if they have changed
auto RenderGroup = t_reg.group<Transform>(entt::get<MeshRenderer, entt::tag<"Default"_hs>>);
RenderGroup.less([&](entt::entity ent, Transform& t_trans, MeshRenderer& t_MeshRend)
{
Fling::Model* Model = t_MeshRend.m_Model;
if (!Model)
{
return;
}
// UPDATE UNIFORM BUF of the mesh --------
Transform::CalculateWorldMatrix(t_trans);
CurrentUBO.Model = t_trans.GetWorldMatrix();
CurrentUBO.ObjPos = t_trans.GetPos();
// Memcpy to the buffer
Buffer* buf = t_MeshRend.m_UniformBuffer;
memcpy(
buf->m_MappedMem,
&CurrentUBO,
buf->GetSize()
);
// Bind the descriptor set for rendering a mesh using the dynamic offset
vkCmdBindDescriptorSets(
OffscreenCmdBuf->GetHandle(),
VK_PIPELINE_BIND_POINT_GRAPHICS,
m_GraphicsPipeline->GetPipelineLayout(),
0,
1,
&t_MeshRend.m_DescriptorSet,
0,
nullptr);
VkBuffer vertexBuffers[1] = { Model->GetVertexBuffer()->GetVkBuffer() };
// Render the mesh
vkCmdBindVertexBuffers(OffscreenCmdBuf->GetHandle(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(OffscreenCmdBuf->GetHandle(), Model->GetIndexBuffer()->GetVkBuffer(), 0, Model->GetIndexType());
vkCmdDrawIndexed(OffscreenCmdBuf->GetHandle(), Model->GetIndexCount(), 1, 0, 0, 0);
});
OffscreenCmdBuf->EndRenderPass();
OffscreenCmdBuf->End();
}
void OffscreenSubpass::CreateMeshDescriptorSet(MeshRenderer& t_MeshRend)
{
// Only allocate new descriptor sets if there are none
// Some may exist if entt decides to re-use the component
if (t_MeshRend.m_DescriptorSet == VK_NULL_HANDLE)
{
VkDescriptorSetLayout layout = m_GraphicsPipeline->GetDescriptorSetLayout();
VkDescriptorSetAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
// If we have specified a specific pool then use that, otherwise use the one on the mesh
allocInfo.descriptorPool = m_DescriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &layout;
VK_CHECK_RESULT(vkAllocateDescriptorSets(m_Device->GetVkDevice(), &allocInfo, &t_MeshRend.m_DescriptorSet));
}
// Ensure that we have a material to try and sample from
if (t_MeshRend.m_Material == nullptr)
{
t_MeshRend.m_Material = Material::GetDefaultMat().get();
}
std::vector<VkWriteDescriptorSet> writeDescriptorSets =
{
// 0: UBO
Initializers::WriteDescriptorSetUniform(
t_MeshRend.m_UniformBuffer,
t_MeshRend.m_DescriptorSet,
0
),
// 1: Color map
Initializers::WriteDescriptorSetImage(
t_MeshRend.m_Material->GetPBRTextures().m_AlbedoTexture,
t_MeshRend.m_DescriptorSet,
1),
// 2: Normal map
Initializers::WriteDescriptorSetImage(
t_MeshRend.m_Material->GetPBRTextures().m_NormalTexture,
t_MeshRend.m_DescriptorSet,
2),
// 3: Metal map
Initializers::WriteDescriptorSetImage(
t_MeshRend.m_Material->GetPBRTextures().m_MetalTexture,
t_MeshRend.m_DescriptorSet,
3),
// 4: Roughness map
Initializers::WriteDescriptorSetImage(
t_MeshRend.m_Material->GetPBRTextures().m_RoughnessTexture,
t_MeshRend.m_DescriptorSet,
4)
// Any other PBR textures or other samplers go HERE and you add to the MRT shader
};
vkUpdateDescriptorSets(m_Device->GetVkDevice(), static_cast<uint32>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
}
void OffscreenSubpass::BuildOffscreenCommandBuffer(entt::registry& t_reg, uint32 t_ActiveFrameInFlight)
{
}
void OffscreenSubpass::PrepareAttachments()
{
assert(m_OffscreenFrameBuf == nullptr);
VkExtent2D Extents = m_SwapChain->GetExtents();
m_OffscreenFrameBuf = new FrameBuffer(m_Device, Extents.width, Extents.height);
AttachmentCreateInfo attachmentInfo = {};
// Four attachments (3 color, 1 depth)
attachmentInfo.Width = Extents.width;
attachmentInfo.Height = Extents.height;
attachmentInfo.LayerCount = 1;
attachmentInfo.Usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
// Color attachments
// Attachment 0: (World space) Positions
attachmentInfo.Format = VK_FORMAT_R16G16B16A16_SFLOAT;
m_OffscreenFrameBuf->AddAttachment(attachmentInfo);
// Attachment 1: (World space) Normals
attachmentInfo.Format = VK_FORMAT_R16G16B16A16_SFLOAT;
m_OffscreenFrameBuf->AddAttachment(attachmentInfo);
// Attachment 2: Albedo (color)
attachmentInfo.Format = VK_FORMAT_R8G8B8A8_UNORM;
m_OffscreenFrameBuf->AddAttachment(attachmentInfo);
// Attachment 3: Metal
attachmentInfo.Format = VK_FORMAT_R8G8B8A8_UNORM;
m_OffscreenFrameBuf->AddAttachment(attachmentInfo);
// Attachment 4: Roughness
attachmentInfo.Format = VK_FORMAT_R8G8B8A8_UNORM;
m_OffscreenFrameBuf->AddAttachment(attachmentInfo);
// Depth attachment
// Find a suitable depth format
VkFormat attDepthFormat;
const PhysicalDevice* PhysDevice = m_Device->GetPhysicalDevice();
assert(PhysDevice);
PhysDevice->GetSupportedDepthFormat(&attDepthFormat);
// Attachment 3: Depth
attachmentInfo.Format = attDepthFormat;
attachmentInfo.Usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
m_OffscreenFrameBuf->AddAttachment(attachmentInfo);
// Create sampler to sample from the color attachments
VK_CHECK_RESULT(m_OffscreenFrameBuf->CreateSampler(VK_FILTER_NEAREST, VK_FILTER_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE));
VK_CHECK_RESULT(m_OffscreenFrameBuf->CreateRenderPass());
F_LOG_TRACE("Offscreen render pass created...");
// Create the descriptor pool for off screen things
uint32 DescriptorCount = 2000 * m_SwapChain->GetImageViewCount();
static std::vector<VkDescriptorPoolSize> poolSizes =
{
Initializers::DescriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, DescriptorCount),
Initializers::DescriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, DescriptorCount),
Initializers::DescriptorPoolSize(VK_DESCRIPTOR_TYPE_SAMPLER, DescriptorCount),
Initializers::DescriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, DescriptorCount),
Initializers::DescriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, DescriptorCount)
};
VkDescriptorPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = to_u32(1000 * m_SwapChain->GetImageViewCount());
if (vkCreateDescriptorPool(m_Device->GetVkDevice(), &poolInfo, nullptr, &m_DescriptorPool) != VK_SUCCESS)
{
F_LOG_FATAL("Failed to create descriptor pool");
}
}
void OffscreenSubpass::CreateGraphicsPipeline()
{
assert(m_OffscreenFrameBuf);
VkRenderPass RenderPass = m_OffscreenFrameBuf->GetRenderPassHandle();
assert(RenderPass != VK_NULL_HANDLE);
m_GraphicsPipeline->m_RasterizationState =
Initializers::PipelineRasterizationStateCreateInfo(
VK_POLYGON_MODE_FILL,
VK_CULL_MODE_BACK_BIT,
VK_FRONT_FACE_COUNTER_CLOCKWISE
);
// Color Attachment --------
// Blend attachment states required for all color attachments
// This is important, as color write mask will otherwise be 0x0 and you
// won't see anything rendered to the attachment
m_GraphicsPipeline->m_ColorBlendAttachmentStates =
{
Initializers::PipelineColorBlendAttachmentState(0xf, VK_FALSE),
Initializers::PipelineColorBlendAttachmentState(0xf, VK_FALSE),
Initializers::PipelineColorBlendAttachmentState(0xf, VK_FALSE),
Initializers::PipelineColorBlendAttachmentState(0xf, VK_FALSE),
Initializers::PipelineColorBlendAttachmentState(0xf, VK_FALSE)
};
m_GraphicsPipeline->m_ColorBlendState.attachmentCount =
static_cast<uint32_t>(m_GraphicsPipeline->m_ColorBlendAttachmentStates.size());
m_GraphicsPipeline->m_ColorBlendState.pAttachments =
m_GraphicsPipeline->m_ColorBlendAttachmentStates.data();
m_GraphicsPipeline->m_MultisampleState =
Initializers::PipelineMultiSampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0);
std::vector<VkDynamicState> dynamicStateEnables =
{
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR
};
m_GraphicsPipeline->m_DynamicState =
Initializers::PipelineDynamicStateCreateInfo(
dynamicStateEnables.data(),
dynamicStateEnables.size(),
0);
m_GraphicsPipeline->CreateGraphicsPipeline(RenderPass, nullptr);
}
void OffscreenSubpass::GatherPresentDependencies(std::vector<CommandBuffer*>& t_CmdBuffs, std::vector<VkSemaphore>& t_Deps, uint32 t_ActiveFrameIndex, uint32 t_CurrentFrameInFlight)
{
t_CmdBuffs.emplace_back(m_OffscreenCmdBufs[t_ActiveFrameIndex]);
t_Deps.emplace_back(m_OffscreenSemaphores[t_CurrentFrameInFlight]);
}
void OffscreenSubpass::CleanUp(entt::registry& t_reg)
{
assert(m_Device != nullptr);
t_reg.view<MeshRenderer>().each([](MeshRenderer& t_Mesh)
{
t_Mesh.Release();
});
if (m_DescriptorPool != VK_NULL_HANDLE)
{
vkDestroyDescriptorPool(m_Device->GetVkDevice(), m_DescriptorPool, nullptr);
m_DescriptorPool = VK_NULL_HANDLE;
}
}
void OffscreenSubpass::OnSwapchainResized(entt::registry& t_reg)
{
const VkExtent2D NewSize = m_SwapChain->GetExtents();
if (m_OffscreenFrameBuf)
{
m_OffscreenFrameBuf->ResizeAndRecreate(NewSize.width, NewSize.height);
}
}
void OffscreenSubpass::OnMeshRendererAdded(entt::entity t_Ent, entt::registry& t_Reg, MeshRenderer& t_MeshRend)
{
if (t_MeshRend.m_Material && t_MeshRend.m_Material->GetType() != Material::Type::Default)
{
return;
}
t_Reg.assign<entt::tag<"Default"_hs >>(t_Ent);
// Initialize and map the UBO of each mesh renderer
if (t_MeshRend.m_UniformBuffer == nullptr)
{
VkDeviceSize bufferSize = sizeof(OffscreenUBO);
t_MeshRend.m_UniformBuffer = new Buffer(bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
t_MeshRend.m_UniformBuffer->MapMemory(bufferSize);
}
// I would love to create some descriptor sets here
CreateMeshDescriptorSet(t_MeshRend);
}
void OffscreenSubpass::OnMeshRendererDestroyed(entt::registry& t_Reg, MeshRenderer& t_MeshRend)
{
//t_MeshRend.Release();
}
} // namespace Fling | 33.635071 | 182 | 0.756376 | [
"mesh",
"render",
"vector",
"model",
"transform"
] |
95a6e25aff298ffc646e508458a4cb715b7b2796 | 1,036 | cpp | C++ | 1002.cpp | zhulk3/leetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | 2 | 2020-03-13T08:14:01.000Z | 2021-09-03T15:27:49.000Z | 1002.cpp | zhulk3/LeetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | null | null | null | 1002.cpp | zhulk3/LeetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
vector<string>ans;
int len = A.size();
string temp;
string::iterator it;
string first = A[0];
for (int i = 0; i < first.length(); i++) {
temp = first[i];
int c = 1;
for (int j = 1; j < len; j++) {
for (it = A[j].begin(); it != A[j].end(); it++) {
if (first[i] == *it) {
c++;
}
}
}
if (c >= len) {
ans.push_back(temp);
string::iterator two;
char t = temp[0];
for (int j = 1; j < len; j++) {
for (two = A[j].begin(); two != A[j].end(); two++) {
if (*two==t) {
A[j].erase(two);
break;
}
}
}
}
temp.clear();
}
return ans;
}
};
int main() {
Solution a;
vector<string>test{ "cool","lock","cook" };
vector<string>ans = a.commonChars(test);
int len = ans.size();
for (int i = 0; i < len; i++) {
cout << ans[i] << ' ';
}
return 0;
} | 17.266667 | 57 | 0.482625 | [
"vector"
] |
95b28aff1c2448abbfdf1b1dd5c500dce8af85b9 | 60,325 | cpp | C++ | Samples/Win7Samples/netds/fax/outboundrouting/cpp/OutboundRouting.cpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/netds/fax/outboundrouting/cpp/OutboundRouting.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/netds/fax/outboundrouting/cpp/OutboundRouting.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | //==========================================================================
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//--------------------------------------------------------------------------
#include "OutboundRouting.h"
#include <faxcomex_i.c>
//+---------------------------------------------------------------------------
//
// function: GiveUsage
//
// Synopsis: prints the usage of the application
//
// Arguments: [AppName] - Name of the application whose usage has to be printed
//
// Returns: void
//
//----------------------------------------------------------------------------
void GiveUsage(LPTSTR AppName)
{
_tprintf( TEXT("Usage : %s \n \
/s Fax Server Name \n \
/o <listGroups/ListRules/RemoveGroup/AddGroup/RemoveRule/AddRule> \n \
/i index of the group or rule to be removed. valid values 0 to n \n \
/n name of the new routing rule or group \n \
/c country code for the new routing rule \n \
/a area code for the new routing rule \n \
/b 1 to use the device id for the new routing rule else 0 \n \
/d device id for the routing rule and list of device ids separated by \";\" for routing group \n" ),AppName);
_tprintf( TEXT("Usage : %s /? -- help message\n"),AppName);
}
//+---------------------------------------------------------------------------
//
// function: IsOSVersionCompatible
//
// Synopsis: finds whether the target OS supports this functionality.
//
// Arguments: [dwVersion] - Minimum Version of the OS required for the Sample to run.
//
// Returns: bool - true if the Sample can run on this OS
//
//----------------------------------------------------------------------------
bool IsOSVersionCompatible(DWORD dwVersion)
{
OSVERSIONINFOEX osvi;
BOOL bOsVersionInfoEx;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi);
if( !bOsVersionInfoEx )
{
osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
return false;
}
bOsVersionInfoEx = (osvi.dwMajorVersion >= dwVersion );
return (bOsVersionInfoEx == TRUE);
}
//+---------------------------------------------------------------------------
//
// function: listDeviceIds
//
// Synopsis: lists the set of devices on for a routing group
//
// Arguments: [IFaxDeviceIds] - FaxDevIds object pointing to the list of device ids are part of the routing group
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool listDeviceIds(IFaxDeviceIds* pFaxDevIds)
{
HRESULT hr = S_OK;
long lDevId = 0;
long count = 0;
bool bRetVal = false;
//check for NULL
if(pFaxDevIds == NULL)
{
_tprintf(_T("listDevices: Parameter passed is NULL"));
goto Exit;
}
hr = pFaxDevIds->get_Count(&count);
if(FAILED(hr))
{
_tprintf(_T("listDevices: get_Count Failed. Error. 0x%x \n"), hr);
goto Exit;
}
long lDeviceId = 0;
for(int i =1; i<= count; i++)
{
hr = pFaxDevIds->get_Item(i,&lDevId);
if(FAILED(hr))
{
_tprintf(_T("listDevices: get_Item Failed. Error. 0x%x \n"), hr);
goto Exit;
}
_tprintf(_T("Device No: %d Device Id = %d \n"), i, lDevId);
}
bRetVal = true;
Exit:
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: listGroups
//
// Synopsis: list of Routing Groups on the Server
//
// Arguments: [pFaxOutRoutGrps] - FaxOutboundRoutingGroups object pointing to the Routing Groups of the current server
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool listGroups(IFaxOutboundRoutingGroups* pFaxOutRoutGrps)
{
HRESULT hr = S_OK;
bool bRetVal = true;
long lCount =0;
IFaxOutboundRoutingGroup* pFaxOutRoutGrp = NULL;
BSTR bstrGrpName = NULL;
//check for NULL
if (pFaxOutRoutGrps == NULL)
{
_tprintf(_T("listGroups: Parameter passed is NULL"));
goto Exit;
}
_tprintf(_T("\n Listing Routing Group details....\n \n"));
hr = pFaxOutRoutGrps->get_Count(&lCount);
if(FAILED(hr))
{
_tprintf(_T("Count failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//enumerate
for(int i =1; i<= lCount; i++)
{
VARIANT varDevice;
IFaxDeviceIds* pFaxDevIds = NULL;
FAX_GROUP_STATUS_ENUM enumStatus;
VariantInit(&varDevice);
varDevice.vt = VT_I4;
varDevice.lVal = i;
hr = pFaxOutRoutGrps->get_Item(varDevice,&pFaxOutRoutGrp);
if(FAILED(hr))
{
_tprintf(_T("listGroups: get_Item Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutGrp->get_DeviceIds(&pFaxDevIds);
if(FAILED(hr))
{
_tprintf(_T("listGroups: get_DeviceIds Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutGrp->get_Name(&bstrGrpName);
if(FAILED(hr))
{
_tprintf(_T("listGroups: get_Name Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutGrp->get_Status(&enumStatus);
if(FAILED(hr))
{
_tprintf(_T("listGroups: get_Status Failed. Error. 0x%x \n"), hr);
goto Exit;
}
//print all the details
_tprintf(_T(" ===================================================\n"));
_tprintf(_T("Group No: %d Group Name = %s \n"), i, bstrGrpName);
if(enumStatus == fgsALL_DEV_VALID )
_tprintf(TEXT("Status : All the devices in the routing group are valid and available for sending outgoing faxes. \n") );
if(enumStatus == fgsEMPTY )
_tprintf(TEXT("Status : The routing group does not contain any devices. \n") );
if(enumStatus == fgsALL_DEV_NOT_VALID)
_tprintf(TEXT("Status : The routing group does not contain any available devices for sending faxes. (Devices can be \"unavailable\" when they are offline and when they do not exist.) \n") );
if(enumStatus == fgsSOME_DEV_NOT_VALID)
_tprintf(TEXT("Status : The routing group contains some devices that are unavailable for sending faxes. (Devices can be \"unavailable\" when they are offline and when they do not exist.) \n") );
if(!listDeviceIds(pFaxDevIds))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
if(bstrGrpName)
SysFreeString(bstrGrpName);
}
Exit:
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: removeGroup
//
// Synopsis: removes a routing group from FaxOutboundRoutingGroups based on index
//
// Arguments: [pFaxOutRoutGrps] - FaxOutboundRoutingGroups object pointing to the Routing Groups of the current server
// [index] - index of the group to be removed
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool removeGroup(IFaxOutboundRoutingGroups* pFaxOutRoutGrps, int index)
{
HRESULT hr = S_OK;
bool bRetVal = false;
long lCount =0;
//check for NULL
if (pFaxOutRoutGrps == NULL)
{
_tprintf(_T("removeGroup: Parameter passed is NULL"));
bRetVal = false;
goto Exit;
}
//get count of groups
hr = pFaxOutRoutGrps->get_Count(&lCount);
if(FAILED(hr))
{
_tprintf(_T("removeGroup: Count failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//invalid index
if(index > lCount || index <=0)
{
_tprintf(_T("removeGroup: Invalid index value. It can be from 1 to %d.\n" ), lCount);
bRetVal = false;
goto Exit;
}
VARIANT varDevice;
VariantInit(&varDevice);
varDevice.vt = VT_I4;
varDevice.lVal = index;
//remove group
hr = pFaxOutRoutGrps->Remove(varDevice);
if(FAILED(hr))
{
_tprintf(_T("removeGroup: Remove Failed. Error. 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
_tprintf(_T("Group removed successfully. \n"));
bRetVal = true;
Exit:
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: SplitDevIds
//
// Synopsis: Splits the sting of ";" separated Device Ids in to String array
//
// Arguments: [inputDevIdList] - The list of device ids in string format separated by semicolon
// [numDevIds] - The number of device ids
// [lptstrDevIdArr] - Array of strings each containing a single device id
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool SplitDevIds(const LPTSTR inputDevIdList, int* numDevIds, LPTSTR** lptstrDevIdArr)
{
bool bRetVal = false;
if(NULL == inputDevIdList || NULL == numDevIds || NULL == lptstrDevIdArr )
{
return false;
}
HRESULT hr = S_OK;
int numDevs = 0;
int count =0;
size_t iStrLen = 0;
hr = StringCchLength( inputDevIdList, 2056 , &iStrLen);
if(FAILED(hr))
{
_tprintf(_T("StringCchLength of inputDevIdList failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit;
}
LPTSTR devListString = (TCHAR*) malloc(sizeof(TCHAR) * (iStrLen+1));
if(devListString == NULL)
{
hr = E_OUTOFMEMORY;
_tprintf(_T("malloc of devListString failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit;
}
memset(devListString, 0, iStrLen+1);
hr = StringCchCopy(devListString, (iStrLen+1),inputDevIdList );
if(FAILED(hr))
{
_tprintf(_T("StringCchCopy of devListString failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//Get the number of DevIds first.
size_t i = 0;
while(i < iStrLen)
{
if(devListString[i] == ';')
{
numDevs= numDevs + 1;
}
i++;
}
numDevs = numDevs+1;
*lptstrDevIdArr = new LPTSTR [numDevs];
if(*lptstrDevIdArr == NULL)
{
hr = E_OUTOFMEMORY;
_tprintf(_T("New of lptstrDevIdArr failed. Error 0x%x"),hr);
bRetVal = false;
goto Exit;
}
memset(*lptstrDevIdArr, 0, numDevs);
i = 0;
size_t end = 0;
size_t start = 0;
//get the array
while(i <= iStrLen)
{
if(devListString[i] == ';' || i == iStrLen)
{
end = i;
size_t len = end - start ;
if(len == 0)
{
_tprintf(_T("Input string is not properly separated \n"));
bRetVal = false;
goto Exit1;
}
TCHAR* strTemp = &devListString[start];
(*lptstrDevIdArr)[count] = (TCHAR*)malloc((len+1) * sizeof(TCHAR));
if((*lptstrDevIdArr)[count] == NULL)
{
hr = E_OUTOFMEMORY;
_tprintf(_T("malloc of (*lptstrDevIdArr)[count] failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit1;
}
memset((*lptstrDevIdArr)[count], 0, (len+1));
hr = StringCchCopyN((*lptstrDevIdArr)[count], len+1, strTemp, len);
if(FAILED(hr))
{
_tprintf(_T("StringCchCopyN of lptstrDevIdArr on count %i failed. Error 0x%x "), count, hr);
bRetVal = false;
goto Exit1;
}
start = i+1;
count++;
}
i++;
}
*numDevIds = numDevs;
bRetVal = true;
goto Exit;
Exit1:
for(int j =0;j < count; j++)
{
if((*lptstrDevIdArr) != NULL)
{
if((*lptstrDevIdArr)[j])
free((*lptstrDevIdArr)[j]);
}
}
if((*lptstrDevIdArr) != NULL)
delete[] (*lptstrDevIdArr);
Exit:
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: addGroup
//
// Synopsis: adds a routing group to FaxOutboundRoutingGroups
//
// Arguments: [pFaxOutRoutGrps] - FaxOutboundRoutingGroups object pointing to the Routing Groups of the current server
// [lptstrGrpName] - Routing Group Name
// [lptstrDevIds] - device ids for the new group
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool addGroup(IFaxOutboundRoutingGroups* pFaxOutRoutGrps, LPTSTR lptstrGrpName, LPTSTR lptstrDevIds)
{
HRESULT hr = S_OK;
bool bRetVal = false;
long lCount =0;
int iDevCount=0;
LPTSTR* devArr = NULL;
BSTR bstrGrpName = SysAllocString(lptstrGrpName);
IFaxOutboundRoutingGroup* pFaxOutRoutGrp = NULL;
IFaxDeviceIds* pFaxDevIds = NULL;
//check for NULL
if (pFaxOutRoutGrps == NULL || lptstrGrpName == NULL || lptstrDevIds == NULL)
{
_tprintf(_T("addGroup: Parameter passed is NULL"));
bRetVal = false;
goto Exit;
}
//check for NULL
if (bstrGrpName == NULL )
{
_tprintf(_T("addRule: bstrGrpName is NULL"));
bRetVal = false;
goto Exit;
}
hr = pFaxOutRoutGrps->Add(bstrGrpName, &pFaxOutRoutGrp);
if(FAILED(hr))
{
_tprintf(_T("addGroup: Add failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
SplitDevIds(lptstrDevIds, &iDevCount, &devArr);
hr = pFaxOutRoutGrp->get_DeviceIds(&pFaxDevIds);
if(FAILED(hr))
{
_tprintf(_T("addGroup: get_DeviceIds Failed. Error. 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
for(int i = 0; i < iDevCount ; i++)
{
hr = pFaxDevIds->Add(_ttoi(devArr[i]));
if(FAILED(hr))
{
_tprintf(_T("addGroup: Add failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
}
_tprintf(_T("Group added successfully. \n"));
bRetVal = true;
Exit:
for(int i =0;i < iDevCount; i++)
{
if((devArr)[i])
free((devArr)[i]);
}
if(devArr)
delete devArr;
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: listRules
//
// Synopsis: list of Routing Rules on the Server
//
// Arguments: [pFaxOutRoutRules] - FaxOutboundRoutingRules object pointing to the Routing Rules of the current server
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool listRules(IFaxOutboundRoutingRules* pFaxOutRoutRules)
{
HRESULT hr = S_OK;
bool bRetVal = true;
long lCount =0;
IFaxOutboundRoutingRule* pFaxOutRoutRule = NULL;
//check for NULL
if (pFaxOutRoutRules == NULL)
{
_tprintf(_T("listRules: Parameter passed is NULL"));
goto Exit;
}
_tprintf(_T("\n Listing Routing Rule details....\n \n"));
hr = pFaxOutRoutRules->get_Count(&lCount);
if(FAILED(hr))
{
_tprintf(_T("Count failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
for(int i =1; i<= lCount; i++)
{
long lDeviceId = 0;
long lAreaCode = 0;
long lCountryCode = 0;
VARIANT_BOOL bUseDevice = VARIANT_FALSE;
FAX_RULE_STATUS_ENUM enumStatus;
BSTR bstrGrpName = NULL;
hr = pFaxOutRoutRules->get_Item(i,&pFaxOutRoutRule);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_Item Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutRule->get_AreaCode(&lAreaCode);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_AreaCode Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutRule->get_CountryCode(&lCountryCode);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_CountryCode Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutRule->get_DeviceId(&lDeviceId);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_DeviceId Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutRule->get_GroupName(&bstrGrpName);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_GroupName Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutRule->get_UseDevice(&bUseDevice);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_UseDevice Failed. Error. 0x%x \n"), hr);
goto Exit;
}
hr = pFaxOutRoutRule->get_Status(&enumStatus);
if(FAILED(hr))
{
_tprintf(_T("listRules: get_Status Failed. Error. 0x%x \n"), hr);
goto Exit;
}
_tprintf(_T(" ===================================================\n"));
_tprintf(_T("Rule No: %d Group Name = %s \n"), i, bstrGrpName);
if(lAreaCode == frrcANY_CODE)
_tprintf(_T("Area Code: The outbound routing rule applies to all area codes. \n"));
else
_tprintf(_T("Area Code: = %d \n"), lAreaCode);
if(lCountryCode == frrcANY_CODE)
_tprintf(_T("Country Code: The outbound routing rule applies to all area codes. \n"));
else
_tprintf(_T("Country Code: = %d \n"), lCountryCode);
_tprintf(_T("Associated Device Id: = %d \n"), lDeviceId);
if(bUseDevice == VARIANT_TRUE)
_tprintf(_T("Applies to single device \n"));
else
_tprintf(_T("Applies to group of devices. \n"));
if(enumStatus == frsVALID )
_tprintf(TEXT("Status : The routing rule is valid and can be applied to outbound faxes. \n"));
if(enumStatus == frsEMPTY_GROUP )
_tprintf(TEXT("Status : The routing rule cannot be applied because the rule uses an outbound routing group for its destination and the group is empty. \n") );
if(enumStatus == frsALL_GROUP_DEV_NOT_VALID)
_tprintf(TEXT("Status : The routing rule cannot be applied because the rule uses an existing outbound routing group for its destination and the group does not contain devices that are valid for sending faxes. \n"));
if(enumStatus == frsSOME_GROUP_DEV_NOT_VALID)
_tprintf(TEXT("Status : The routing rule uses an existing outbound routing group for its destination but the group contains devices that are not valid for sending faxes. \n") );
if(enumStatus == frsBAD_DEVICE)
_tprintf(TEXT("Status : The routing rule cannot be applied because the rule uses a single device for its destination and that device is not valid for sending faxes. \n") );
if(bstrGrpName)
SysFreeString(bstrGrpName);
}
Exit:
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: removeRule
//
// Synopsis: removes a routing rule from FaxOutboundRoutingRules based on index
//
// Arguments: [pFaxOutRoutRules] - FaxOutboundRoutingRules object pointing to the Routing Rules of the current server
// [index] - index of the group to be removed
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool removeRule(IFaxOutboundRoutingRules* pFaxOutRoutRules, int index)
{
HRESULT hr = S_OK;
bool bRetVal = false;
long lCount =0;
//check for NULL
if (pFaxOutRoutRules == NULL)
{
_tprintf(_T("removeRule: Parameter passed is NULL"));
bRetVal = false;
goto Exit;
}
//get the count
hr = pFaxOutRoutRules->get_Count(&lCount);
if(FAILED(hr))
{
_tprintf(_T("removeRule: Count failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//check if valid
if(index > lCount || index <=0)
{
_tprintf(_T("removeRule: Invalid index value. It can be from 1 to %d.\n" ), lCount);
bRetVal = false;
goto Exit;
}
//remove rule
hr = pFaxOutRoutRules->Remove(index);
if(FAILED(hr))
{
_tprintf(_T("removeRule: Remove Failed. Error. 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
_tprintf(_T("Rule removed successfully. \n"));
bRetVal = true;
Exit:
return bRetVal;
}
//+---------------------------------------------------------------------------
//
// function: addRule
//
// Synopsis: adds a routing rule to FaxOutboundRoutingRules
//
// Arguments: [pFaxOutRoutRules] - FaxOutboundRoutingRules object pointing to the Routing Rules of the current server
// [lptstrGrpName] - Routing Group Name
// [lptstrDevIds] - device ids for the new group
//
// Returns: bool: true if passed successfully
//
//----------------------------------------------------------------------------
bool addRule(IFaxOutboundRoutingRules* pFaxOutRoutRules, LPTSTR lptstrGrpName, LPTSTR lptstrDevId, LPTSTR lptstrCountryCode, LPTSTR lptstrAreaCode, VARIANT_BOOL bUseDevice )
{
HRESULT hr = S_OK;
bool bRetVal = false;
long lCount =0;
int iDevCount=0;
int iDevId = -1;
LPTSTR* devArr = NULL;
BSTR bstrGrpName = SysAllocString(lptstrGrpName);
IFaxOutboundRoutingRule* pFaxOutRoutRule = NULL;
IFaxDeviceIds* pFaxDevIds = NULL;
//check for NULL
if (pFaxOutRoutRules == NULL || lptstrCountryCode == NULL || lptstrAreaCode == NULL || (lptstrGrpName == NULL && lptstrDevId == NULL ) )
{
_tprintf(_T("addRule: Parameter passed is NULL"));
bRetVal = false;
goto Exit;
}
//check for NULL
if ((bstrGrpName != NULL && !bUseDevice) || ( lptstrDevId != NULL && bUseDevice) )
{
if(lptstrDevId != NULL)
iDevId = _ttoi(lptstrDevId);
//Set Area Code and Country Code for all codes
hr = pFaxOutRoutRules->Add(_ttoi(lptstrCountryCode),_ttoi(lptstrAreaCode),bUseDevice,bstrGrpName, iDevId, &pFaxOutRoutRule);
if(FAILED(hr))
{
_tprintf(_T("addRule: Add failed. Error = 0x%x"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
_tprintf(_T("addRule: Parameter is NULL"));
bRetVal = false;
goto Exit;
}
_tprintf(_T("Rule added successfully. \n"));
bRetVal = true;
Exit:
return bRetVal;
}
int __cdecl _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = S_OK;
bool bRetVal = true;
LPTSTR lptstrServerName = NULL;
LPTSTR lptstrIndex = NULL;
LPTSTR lptstrName = NULL;
LPTSTR lptstrCountryCode = NULL;
LPTSTR lptstrAreaCode = NULL;
LPTSTR lptstrIds = NULL;
LPTSTR lptstrOption = NULL;
BSTR bstrServerName = NULL;
LPTSTR lptstrUseDev = NULL;
bool bConnected = false;
size_t argSize = 0;
VARIANT_BOOL vbState = VARIANT_FALSE;
bool bVersion = IsOSVersionCompatible(VISTA);
//Check is OS is Vista
if(bVersion == false)
{
_tprintf(_T("OS Version does not support this feature"));
bRetVal = false;
goto Exit1;
}
//introducing an artifical scope here so that the COm objects are destroyed before CoInitialize is called
{
//COM objects
IFaxServer2* pFaxServer = NULL;
IFaxOutboundRouting* pFaxOutRout = NULL;
IFaxOutboundRoutingGroups* pFaxOutRoutGrps =NULL;
IFaxOutboundRoutingRules* pFaxOutRoutRules = NULL;
int argcount = 0;
#ifdef UNICODE
argv = CommandLineToArgvW( GetCommandLine(), &argc );
#else
argv = argvA;
#endif
if (argc == 1)
{
_tprintf( TEXT("Missing args.\n") );
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
// check for commandline switches
for (argcount=1; argcount<argc; argcount++)
{
if(argcount + 1 < argc)
{
hr = StringCbLength(argv[argcount + 1],1024 * sizeof(TCHAR),&argSize);
if(!FAILED(hr))
{
if ((argv[argcount][0] == L'/') || (argv[argcount][0] == L'-'))
{
switch (towlower(argv[argcount][1]))
{
case 's':
if(lptstrServerName == NULL)
{
lptstrServerName = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrServerName == NULL)
{
_tprintf(_T("lptstrServerName: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrServerName, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrServerName,argSize+1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrServerName: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'o':
if(lptstrOption == NULL)
{
lptstrOption = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrOption == NULL)
{
_tprintf(_T("lptstrOption: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrOption, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrOption,argSize +1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrOption: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'n':
if(lptstrName == NULL)
{
lptstrName = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrName == NULL)
{
_tprintf(_T("lptstrName: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrName, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrName, argSize + 1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrName: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'd':
if(lptstrIds == NULL)
{
lptstrIds = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrIds == NULL)
{
_tprintf(_T("lptstrIds: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrIds, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrIds, argSize + 1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrIds: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'i':
if(lptstrIndex == NULL)
{
lptstrIndex = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrIndex == NULL)
{
_tprintf(_T("lptstrIndex: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrIndex, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrIndex, argSize + 1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrIndex: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'c':
if(lptstrCountryCode == NULL)
{
lptstrCountryCode = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrCountryCode == NULL)
{
_tprintf(_T("lptstrCountryCode: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrCountryCode, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrCountryCode, argSize + 1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrCountryCode: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'a':
if(lptstrAreaCode == NULL)
{
lptstrAreaCode = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrAreaCode == NULL)
{
_tprintf(_T("lptstrAreaCode: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrAreaCode, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrAreaCode, argSize + 1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrAreaCode: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case 'b':
if(lptstrUseDev == NULL)
{
lptstrUseDev = (TCHAR*) malloc((argSize+1)* sizeof(TCHAR));
if(lptstrUseDev == NULL)
{
_tprintf(_T("lptstrUseDev: malloc failed. Error %d \n"), GetLastError());
bRetVal = false;
goto Exit;
}
memset(lptstrUseDev, 0, (argSize+1)* sizeof(TCHAR));
hr = StringCchCopyN(lptstrUseDev, argSize + 1, argv[argcount+1],argSize);
if(FAILED(hr))
{
_tprintf(_T("lptstrUseDev: StringCchCopyN failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
}
else
{
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
argcount++;
break;
case '?':
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
default:
break;
}//switch
}//if
}
}
}//for
if (lptstrOption == NULL)
{
_tprintf( TEXT("Missing/Invalid Value.\n") );
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
if ((lptstrIndex == NULL ) && ((_tcscmp(_T("removegroup"), CharLower(lptstrOption)) == 0) || ((_tcscmp(_T("removerule"), CharLower(lptstrOption)) == 0))))
{
_tprintf( TEXT("Missing/Invalid Value.\n") );
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
if (((lptstrName == NULL ) || (lptstrIds == NULL ) ) && ((_tcscmp(_T("addgroup"), CharLower(lptstrOption)) == 0)))
{
_tprintf( TEXT("Missing/Invalid Value.\n") );
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
//if addrule and lptstrUseDev is not set
if (((lptstrUseDev == NULL ) || ((_tcscmp(_T("1"), lptstrUseDev) != 0) && (_tcscmp(_T("0"), lptstrUseDev) != 0)) ) && (((_tcscmp(_T("addrule"), CharLower(lptstrOption)) == 0))))
{
_tprintf( TEXT("Set /b tag to 0 or 1.\n") );
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
//if UseDev = 1 then set lptstrIds
//if UseDev = 0 then set lptstrName
if(lptstrUseDev != NULL )
{
if ((((_tcscmp(_T("0"), lptstrUseDev) == 0) && lptstrName == NULL ) || ((_tcscmp(_T("1"), lptstrUseDev) == 0) && (lptstrIds == NULL)) || (lptstrAreaCode == NULL ) || (lptstrCountryCode == NULL ) ) && (((_tcscmp(_T("addrule"), CharLower(lptstrOption)) == 0))))
{
_tprintf( TEXT("Missing/Invalid Value.\n") );
GiveUsage(argv[0]);
bRetVal = false;
goto Exit;
}
}
//initialize COM
hr = CoInitialize(NULL);
if(FAILED(hr))
{
//failed to init com
_tprintf(_T("Failed to init com. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
hr = CoCreateInstance (CLSID_FaxServer,
NULL,
CLSCTX_ALL,
__uuidof(IFaxServer),
(void **)&pFaxServer);
if(FAILED(hr))
{
//CoCreateInstance failed.
_tprintf(_T("CoCreateInstance failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
//connect to fax server.
bstrServerName = SysAllocString(lptstrServerName);
hr = pFaxServer->Connect(bstrServerName);
if(FAILED(hr))
{
_tprintf(_T("Connect failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
bConnected = true;
FAX_SERVER_APIVERSION_ENUM enumFaxAPIVersion;
hr = pFaxServer->get_APIVersion(&enumFaxAPIVersion);
if(FAILED(hr))
{
//get_APIVersion failed.
_tprintf(_T("get_APIVersion failed. Error 0x%x \n"), hr);
bRetVal = false;
goto Exit;
}
if (enumFaxAPIVersion < fsAPI_VERSION_3)
{
bRetVal = false;
_tprintf(_T("OS Version does not support this feature"));
goto Exit;
}
//Get Routing object
hr = pFaxServer->get_OutboundRouting(&pFaxOutRout);
if(FAILED(hr))
{
_tprintf(_T("get_OutboundRouting failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//Get Groups object
hr = pFaxOutRout->GetGroups(&pFaxOutRoutGrps);
if(FAILED(hr))
{
_tprintf(_T("GetGroups failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//Get Rules object
hr = pFaxOutRout->GetRules(&pFaxOutRoutRules);
if(FAILED(hr))
{
_tprintf(_T("GetRules failed. Error 0x%x"), hr);
bRetVal = false;
goto Exit;
}
//list groups
if(_tcscmp(_T("listgroups"), CharLower(lptstrOption)) == 0)
{
if(!listGroups(pFaxOutRoutGrps))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
}
//list rules
if(_tcscmp(_T("listrules"), CharLower(lptstrOption)) == 0)
{
if(!listRules(pFaxOutRoutRules))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
}
//remove group
if(_tcscmp(_T("removegroup"), CharLower(lptstrOption)) == 0)
{
if(!removeGroup(pFaxOutRoutGrps,_ttoi(lptstrIndex)))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
}
//remove rules
if(_tcscmp(_T("removerule"), CharLower(lptstrOption)) == 0)
{
if(!removeRule(pFaxOutRoutRules, _ttoi(lptstrIndex)))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
}
//add groups
if(_tcscmp(_T("addgroup"), CharLower(lptstrOption)) == 0)
{
if(!addGroup(pFaxOutRoutGrps, lptstrName, lptstrIds))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
}
//add rules
VARIANT_BOOL bUseDevice;
if(_tcscmp(_T("addrule"), CharLower(lptstrOption)) == 0)
{
if(_tcscmp(_T("0"), lptstrUseDev) == 0)
{
bUseDevice = VARIANT_FALSE;
}
else
{
bUseDevice = VARIANT_TRUE;
}
if(!addRule(pFaxOutRoutRules, lptstrName, lptstrIds, lptstrCountryCode, lptstrAreaCode, bUseDevice))
{
//we dont want to log any error here as the error will be logged in the function itself
bRetVal = false;
}
}
Exit:
if(bConnected)
{
pFaxServer->Disconnect();
}
if(lptstrServerName)
free(lptstrServerName);
if(lptstrOption)
free(lptstrOption);
if(lptstrName)
free(lptstrName);
if(lptstrIds)
free(lptstrIds);
if(lptstrIndex)
free(lptstrIndex);
if(lptstrUseDev)
free(lptstrUseDev );
if(lptstrAreaCode )
free(lptstrAreaCode);
if(lptstrCountryCode)
free(lptstrCountryCode);
if(bstrServerName)
SysFreeString(bstrServerName);
}
CoUninitialize();
Exit1:
return bRetVal;
}
| 47.991249 | 285 | 0.337903 | [
"object"
] |
95becb7402065b65394db0251f3fff3cc10ea09c | 8,117 | cpp | C++ | test/stringutil_test.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 5 | 2015-09-10T08:53:41.000Z | 2020-05-30T18:42:20.000Z | test/stringutil_test.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 20 | 2015-09-29T16:16:07.000Z | 2021-06-13T08:08:05.000Z | test/stringutil_test.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 3 | 2015-09-09T22:51:44.000Z | 2020-11-11T13:19:42.000Z | //
// csvsqldb test
//
// BSD 3-Clause License
// Copyright (c) 2015, Lars-Christian Fürstenberg
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "test.h"
#include "libcsvsqldb/base/string_helper.h"
#include <vector>
namespace csvsqldb
{
namespace testspace
{
class Test
{
};
}
static std::string callTimeStream(const std::chrono::system_clock::time_point& tp)
{
std::ostringstream os;
os << tp;
return os.str();
}
}
class StringHelperTestCase
{
public:
void setUp()
{
}
void tearDown()
{
}
void tokenizer()
{
std::string s("This is my glorious test string");
std::vector<std::string> tokens;
csvsqldb::split(s, ' ', tokens);
MPF_TEST_ASSERTEQUAL(8u, tokens.size());
MPF_TEST_ASSERTEQUAL("This", tokens[0]);
MPF_TEST_ASSERTEQUAL("is", tokens[1]);
MPF_TEST_ASSERTEQUAL("my", tokens[2]);
MPF_TEST_ASSERTEQUAL("glorious", tokens[3]);
MPF_TEST_ASSERTEQUAL("test", tokens[4]);
MPF_TEST_ASSERTEQUAL("", tokens[5]);
MPF_TEST_ASSERTEQUAL("", tokens[6]);
MPF_TEST_ASSERTEQUAL("string", tokens[7]);
s = "This,is,my,glorious,test,,,string";
csvsqldb::split(s, ' ', tokens);
MPF_TEST_ASSERTEQUAL(1u, tokens.size());
MPF_TEST_ASSERTEQUAL("This,is,my,glorious,test,,,string", tokens[0]);
s = "This,is,my,glorious,test,,,string";
csvsqldb::split(s, ',', tokens);
MPF_TEST_ASSERTEQUAL(8u, tokens.size());
MPF_TEST_ASSERTEQUAL("This", tokens[0]);
MPF_TEST_ASSERTEQUAL("is", tokens[1]);
MPF_TEST_ASSERTEQUAL("my", tokens[2]);
MPF_TEST_ASSERTEQUAL("glorious", tokens[3]);
MPF_TEST_ASSERTEQUAL("test", tokens[4]);
MPF_TEST_ASSERTEQUAL("", tokens[5]);
MPF_TEST_ASSERTEQUAL("", tokens[6]);
MPF_TEST_ASSERTEQUAL("string", tokens[7]);
s = "This,is,my,glorious,test,,,string";
csvsqldb::split(s, ',', tokens, false);
MPF_TEST_ASSERTEQUAL(6u, tokens.size());
MPF_TEST_ASSERTEQUAL("This", tokens[0]);
MPF_TEST_ASSERTEQUAL("is", tokens[1]);
MPF_TEST_ASSERTEQUAL("my", tokens[2]);
MPF_TEST_ASSERTEQUAL("glorious", tokens[3]);
MPF_TEST_ASSERTEQUAL("test", tokens[4]);
MPF_TEST_ASSERTEQUAL("string", tokens[5]);
}
void joinTest()
{
std::vector<std::string> tokens;
tokens.push_back("This");
tokens.push_back("is");
tokens.push_back("my");
tokens.push_back("glorious");
tokens.push_back("test");
tokens.push_back("string");
MPF_TEST_ASSERTEQUAL("This,is,my,glorious,test,string", csvsqldb::join(tokens, ","));
}
void upperTest()
{
std::string s("Not All upper");
csvsqldb::toupper(s);
MPF_TEST_ASSERTEQUAL("NOT ALL UPPER", s);
std::string s1("Not All upper");
std::string s2 = csvsqldb::toupper_copy(s1);
MPF_TEST_ASSERTEQUAL("NOT ALL UPPER", s2);
MPF_TEST_ASSERTEQUAL("Not All upper", s1);
}
void lowerTest()
{
std::string s("Not All upper");
csvsqldb::tolower(s);
MPF_TEST_ASSERTEQUAL("not all upper", s);
std::string s1("Not All upper");
std::string s2 = csvsqldb::tolower_copy(s1);
MPF_TEST_ASSERTEQUAL("not all upper", s2);
MPF_TEST_ASSERTEQUAL("Not All upper", s1);
}
void stripTypeNameTest()
{
MPF_TEST_ASSERTEQUAL("csvsqldb::testspace::Test", csvsqldb::stripTypeName(typeid(csvsqldb::testspace::Test).name()));
}
void stringCompareTest()
{
MPF_TEST_ASSERTEQUAL(0, csvsqldb::stricmp("Test it", "TEST IT"));
MPF_TEST_ASSERTEQUAL(1, csvsqldb::stricmp("Txst it", "TEST IT"));
MPF_TEST_ASSERTEQUAL(0, csvsqldb::strnicmp("Test it", "TEST IT", 5));
MPF_TEST_ASSERTEQUAL(1, csvsqldb::strnicmp("Txst it", "TEST IT", 5));
}
void timeFormatTest()
{
std::chrono::duration<int, std::mega> megaSecs(22);
std::chrono::duration<int, std::kilo> kiloSecs(921);
std::chrono::duration<int, std::deca> decaSecs(20);
std::chrono::system_clock::time_point tp;
tp += megaSecs;
tp += kiloSecs;
tp += decaSecs;
struct tm ts;
ts.tm_hour = 7;
ts.tm_min = 0;
ts.tm_sec = 0;
ts.tm_year = 1970 - 1900;
ts.tm_mon = 8;
ts.tm_mday = 23;
ts.tm_isdst = 0;
char utc[] = "UTC";
ts.tm_zone = &utc[0];
char buffer[20];
time_t tt = timegm(&ts);
struct tm* lt = ::localtime(&tt);
::strftime(buffer, 20, "%FT%T", lt);
MPF_TEST_ASSERTEQUAL(buffer, csvsqldb::callTimeStream(tp));
MPF_TEST_ASSERTEQUAL("Wed, 23 Sep 1970 07:00:00 GMT", csvsqldb::formatDateRfc1123(tp));
}
void trimTest()
{
std::string s(" left whitespace");
MPF_TEST_ASSERTEQUAL("left whitespace", csvsqldb::trim_left(s));
s = "no left whitespace";
MPF_TEST_ASSERTEQUAL("no left whitespace", csvsqldb::trim_left(s));
s = "right whitespace ";
MPF_TEST_ASSERTEQUAL("right whitespace", csvsqldb::trim_right(s));
s = "no right whitespace";
MPF_TEST_ASSERTEQUAL("no right whitespace", csvsqldb::trim_right(s));
}
void decodeTest()
{
std::string encoded(
"wikiPageName=Testpage&wikiPageMarkdown=Markdown%0D%0A%3D%3D%3D%3D%3D%3D%3D%3D%0D%0A%0D%0A-+some+tests%0D%0A-+and+more%"
"0D%0A%0D%0A");
std::string decoded;
MPF_TEST_ASSERT(csvsqldb::decode(encoded, decoded));
MPF_TEST_ASSERTEQUAL(
"wikiPageName=Testpage&wikiPageMarkdown=Markdown\r\n========\r\n\r\n- some tests\r\n- and more\r\n\r\n", decoded);
encoded =
"wikiPageName=Testpage&wikiPageMarkdown=Markdown% "
"%0A%3D%3D%3D%3D%3D%3D%3D%3D%0D%0A%0D%0A-+some+tests%0D%0A-+and+more%0D%0A%0D%0A";
MPF_TEST_ASSERT(!csvsqldb::decode(encoded, decoded));
}
};
MPF_REGISTER_TEST_START("ApplicationTestSuite", StringHelperTestCase);
MPF_REGISTER_TEST(StringHelperTestCase::tokenizer);
MPF_REGISTER_TEST(StringHelperTestCase::joinTest);
MPF_REGISTER_TEST(StringHelperTestCase::upperTest);
MPF_REGISTER_TEST(StringHelperTestCase::lowerTest);
MPF_REGISTER_TEST(StringHelperTestCase::stripTypeNameTest);
MPF_REGISTER_TEST(StringHelperTestCase::timeFormatTest);
MPF_REGISTER_TEST(StringHelperTestCase::trimTest);
MPF_REGISTER_TEST(StringHelperTestCase::decodeTest);
MPF_REGISTER_TEST_END();
| 33.962343 | 128 | 0.646667 | [
"vector",
"3d"
] |
95c5c81a8720bd79fa992fe356cb5a52f0e3b701 | 1,934 | hpp | C++ | src/libs/daemonlib/sc_heartbeatthread.hpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | src/libs/daemonlib/sc_heartbeatthread.hpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | src/libs/daemonlib/sc_heartbeatthread.hpp | suggitpe/RPMS | 7a12da0128f79b8b0339fd7146105ba955079b8c | [
"Apache-2.0"
] | null | null | null | #ifndef __sc_heartbeatthread_hpp
#define __sc_heartbeatthread_hpp
#include <base/sa_threadbase.hpp>
#include <base/st_spointer.hpp>
namespace rpms
{
// pre decl
class SA_Socket;
/**
* Heartbeater thread just replies to any incoming heartbeats
*
* @author Peter Suggitt (2005)
* @note <b>Concrete Daemon class</b>
* */
class SC_HeartbeatThread : public SA_ThreadBase
{
public:
/** Static methid to create the heartbeat thread (this is the only access to a new one) */
static ST_SPointer<SC_HeartbeatThread> create();
/** This is used to stop the thread when it is running */
virtual void stop();
/** virtual dtor */
virtual ~SC_HeartbeatThread();
/** Reset the thread and all the object contents ready for it to be restarted */
void reset();
protected:
/** Main ctor
* @param aName The name of the thread*/
SC_HeartbeatThread( const std::string &aName );
/** The main runnable method for the thread */
virtual void run();
private:
/** Hidden copy ctor */
SC_HeartbeatThread( const SC_HeartbeatThread &aRhs );
/** Hidden assignment operator */
SC_HeartbeatThread& operator=( const SC_HeartbeatThread &aRhs );
/** Initialisation method */
void init();
private:// members
/** Flag denoting whether the thread should run */
bool mShouldRun;
/** The UDP port to listen for incoming heartbeats */
int mHeartbeatPort;
/** The underlying socket object */
ST_SPointer<SA_Socket> mSocket;
/** Maximum socket stimeouts allowed before we presume the director is not running */
int mMaxFailedAttempts;
};
} // namespace
#endif
| 32.779661 | 102 | 0.58635 | [
"object"
] |
95cf44c852c843fda661d8e60393545fa8925856 | 816 | cpp | C++ | Leetcode/Array/count-number-of-teams.cpp | rajnishmsrit/technical-interview-coding | 0a2a72b54d4865ee38b85184425d4a4875d95f01 | [
"MIT"
] | null | null | null | Leetcode/Array/count-number-of-teams.cpp | rajnishmsrit/technical-interview-coding | 0a2a72b54d4865ee38b85184425d4a4875d95f01 | [
"MIT"
] | null | null | null | Leetcode/Array/count-number-of-teams.cpp | rajnishmsrit/technical-interview-coding | 0a2a72b54d4865ee38b85184425d4a4875d95f01 | [
"MIT"
] | null | null | null | # include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numTeams(vector<int>& rating) {
int smaller=0,larger=0;
int frequency=0;
// small|med|large or large|med|small
for (int i = 0; i < rating.size(); i++)
{
int smaller=0,larger=0;
for (int j = 0; j < i; j++)
{
if(rating[j]<rating[i]){
smaller++;
}else if(rating[j]>rating[i]){
larger++;
}
}
frequency = smaller*larger;
}
return frequency;
}
};
void test(){
vector<int> v{1,2,3,4};
cout << "Program starts \n";
Solution s;
cout << "The no is: " << s.numTeams(v) << endl;
}
int main(){
test();
return 0;
} | 21.473684 | 51 | 0.446078 | [
"vector"
] |
95d1e17af972bbf9929ee95f79a5a29fd135b004 | 4,528 | cpp | C++ | bazaar/Uniq/Posix.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | bazaar/Uniq/Posix.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | bazaar/Uniq/Posix.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "Uniq.h"
NAMESPACE_UPP
#ifdef PLATFORM_POSIX
// send command line to callback handler
bool Uniq::SendCmdLine(int pipe)
{
char buf[256];
Vector<String>v;
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(pipe, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 2000;
if(!select(pipe+1, &rfds, NULL, NULL, &tv))
return false;
// FILE gets handy for fgets() &C....
FILE *f = fdopen(pipe, "r");
// gets number of elements in vector
if(fgets(buf, 256, f))
{
int count = ScanInt(buf);
// get the strings
for(int i = 0; i < count; i++)
{
if(!fgets(buf, 256, f))
break;
String s = buf;
if(s.GetCount() && s[s.GetCount() - 1] == '\n')
s = s.Left(s.GetCount() - 1);
v.Add(s);
}
}
fclose(f);
// posts the callback to handle new instance's command line
PostCallback(callback1(WhenInstance, v));
return true;
}
// polling callback
void Uniq::pollCb(void)
{
// dont block on open, that would make thread shutdown impossible
int pipe = open(pipePath, O_RDONLY | O_NDELAY);
if(pipe == -1)
return;
#ifdef flagMT
// multithread makes it easy... just open receiving pipe
// and wait for data from it -- it can do blocking reads
// and no need for wait cycles
while(!Thread::IsShutdownThreads())
{
// if there's no data waiting on pipe
// just sleep a bit and try again
if(!SendCmdLine(pipe))
{
Sleep(200);
continue;
}
// select doesn't handle well closed fifos on second call
// the solution is close and reopen it again
close(pipe);
pipe = open(pipePath, O_RDONLY | O_NDELAY);
}
#else
// non multithreaded -- we shall check for data from pipe
// in non-blocking mode and read it if available
SendCmdLine(pipe);
// respawn itself by aid of another timed callback
SetTimeCallback(200, THISBACK(pollCb));
#endif
close(pipe);
}
Uniq::Uniq()
{
// we still don't know if we're inside first app instance
// so we default for NOT
isFirstInstance = false;
pipePath = Format("/tmp/%s_%d_UNIQ", GetExeTitle(), (int64)getuid());
lockPath = Format("/tmp/%s_%d_UNIQ_LCK", GetExeTitle(), (int64)getuid());
// we check first if the lock file is there AND locked by main instance
// if it is, we're on a secondary instance; if not, we're main
if(FileExists(lockPath))
{
// lock file does exist, try to open and lock it
lockFile = open(lockPath, O_RDWR);
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
int lock = fcntl(lockFile, F_SETLK, &fl);
close(lockFile);
if(lock != -1)
{
// we could lock the file, it was a stray pipe
// so we remove both
unlink(lockPath);
unlink(pipePath);
}
}
// try to open pipe for write; if succeed, pipe is there
// so we're on a new app instance
int p = open(pipePath, O_WRONLY /* | O_NDELAY */);
if(p != -1)
{
// pipe already there, we should write command line to it and leave
FILE *f = fdopen(p, "w");
fprintf(f, "%d\n", CommandLine().GetCount());
for(int i = 0; i < CommandLine().GetCount(); i++)
fprintf(f, "%s\n", ~CommandLine()[i]);
fclose(f);
close(p);
}
else
{
// pipe doesn't exist, create it and allow writing for other processes
// we also create the lock file
if(mkfifo(pipePath, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH))
{
Cerr() << t_("Error creating interprocess pipe") << "\n";
exit(1);
}
lockFile = open(lockPath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
int lock = fcntl(lockFile, F_SETLK, &fl);
if(lock == -1)
{
Cerr() << t_("Error locking lock file") << "\n";
unlink(pipePath);
unlink(lockPath);
exit(1);
}
// remember we're inside first app instance
isFirstInstance = true;
// now, if we do multithreading, we use a listening thread
// for other's instances communications
// otherwise we use a timed callback (which is less efficient)
#ifdef flagMT
pollThread.Run(THISBACK(pollCb));
#else
// use a 200 ms delayed callback to check if another instance
// gave its command line
SetTimeCallback(200, THISBACK(pollCb));
#endif
}
}
Uniq::~Uniq()
{
if(isFirstInstance)
{
#ifdef flagMT
Thread::ShutdownThreads();
pollThread.Wait();
#endif
close(lockFile);
unlink(lockPath);
unlink(pipePath);
}
}
#endif
END_UPP_NAMESPACE
| 23.831579 | 75 | 0.628534 | [
"vector"
] |
95e45a994b464bb7c2bc72b72d5c7c27696e764c | 2,084 | cpp | C++ | AlgorithmStudyCpp/TIMETRIP_upsk1.cpp | waltechel/AlgorithmCpp | 5a02d1c25d987e6cb0e9953aa87c181f659c8e7c | [
"MIT"
] | 2 | 2021-08-01T13:43:00.000Z | 2021-12-08T10:02:55.000Z | AlgorithmStudyCpp/TIMETRIP_upsk1.cpp | waltechel/AlgorithmStudyCpp | c0557c2cd847ca9113bbb094403ea2e922787eda | [
"MIT"
] | null | null | null | AlgorithmStudyCpp/TIMETRIP_upsk1.cpp | waltechel/AlgorithmStudyCpp | c0557c2cd847ca9113bbb094403ea2e922787eda | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int V, V2;
const int INF = 10000000;
vector<pair<int, int>> adj[101];
pair<int, int> bellman2(int src, int target) {
vector<int> Upper(V, INF);
vector<int> Lower(V, INF);
Upper[src] = 0; Lower[src] = 0;
bool Uflag = false, Lflag = false;
for (int iter = 1; iter <= V2; iter++) {
for (int here = 0; here < V; here++) {
for (int i = 0; i < adj[here].size(); i++) {
int there = adj[here][i].first;
int cost = adj[here][i].second;
if (Upper[here] != INF) {
if (Upper[there] > Upper[here] + cost) {
Upper[there] = Upper[here] + cost;
if (iter >= V && there == 1) {
Uflag = true;
}
}
}
if (Lower[here] != INF) {
if (Lower[there] > Lower[here] - cost) {
Lower[there] = Lower[here] - cost;
if (iter >= V && there == 1) {
Lflag = true;
}
}
}
}
}
}
pair<int, int> ret = { Upper[1],-Lower[1] };
if (Uflag)ret.first = INF + 1;
if (Lflag)ret.second = INF + 1;
return ret;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int T;
cin >> T;
while (T--) {
int m;
cin >> V >> m;
V2 = V * 2;
for (int i = 0; i < V; i++)adj[i].clear();
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
adj[x].push_back({ y,z });
}
auto ans = bellman2(0, 1);
if (ans.first == INF) {
cout << "UNREACHABLE\n";
}
else {
if (ans.first > INF)cout << "INFINITY ";
else cout << ans.first << ' ';
if (ans.second > INF)cout << "INFINITY\n";
else cout << ans.second << '\n';
}
}
} | 31.575758 | 68 | 0.390115 | [
"vector"
] |
95f2b3f0e3e3406b6ae65e529c2150ada8902f0e | 2,523 | cc | C++ | src/texture.cc | webbbn/realtime_network_av | 973307babd44b0bb5908b688c60b1d3c40a0762d | [
"Apache-2.0"
] | 4 | 2019-03-13T14:37:12.000Z | 2019-11-07T07:11:53.000Z | src/texture.cc | webbbn/realtime-network-av | 973307babd44b0bb5908b688c60b1d3c40a0762d | [
"Apache-2.0"
] | null | null | null | src/texture.cc | webbbn/realtime-network-av | 973307babd44b0bb5908b688c60b1d3c40a0762d | [
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <SDL_image.h>
#include "texture.hh"
Texture::Texture(SDL_Renderer *renderer) : m_renderer(renderer) {
// Initialize
m_texture = NULL;
m_width = 0;
m_height = 0;
}
Texture::~Texture() {
// Deallocate
free();
}
bool Texture::load_from_file(const std::string &path) {
// Get rid of preexisting texture
free();
// The final texture
SDL_Texture* new_texture = NULL;
// Load image at specified path
SDL_Surface* loaded_surface = IMG_Load(path.c_str());
if(!loaded_surface) {
std::cerr << "Unable to load image " << path << "! SDL_image Error: " << IMG_GetError()
<< std::endl;
} else {
// Color key image
SDL_SetColorKey(loaded_surface, SDL_TRUE, SDL_MapRGB(loaded_surface->format, 0, 0xFF, 0xFF));
// Create texture from surface pixels
new_texture = SDL_CreateTextureFromSurface(m_renderer, loaded_surface);
if(new_texture == NULL) {
std::cerr << "Unable to create texture from " << path << " SDL Error: " << SDL_GetError()
<< std::endl;
} else {
// Get image dimensions
m_width = loaded_surface->w;
m_height = loaded_surface->h;
}
// Get rid of old loaded surface
SDL_FreeSurface(loaded_surface);
}
// Return success
m_texture = new_texture;
return m_texture != NULL;
}
void Texture::free() {
// Free texture if it exists
if(m_texture != NULL) {
SDL_DestroyTexture(m_texture);
m_texture = NULL;
m_width = 0;
m_height = 0;
}
}
void Texture::render(int x, int y, SDL_Rect* clip, double angle, SDL_Point* center,
uint8_t alphamod, SDL_RendererFlip flip) {
// Set rendering space and render to screen
SDL_Rect render_quad = { x, y, m_width, m_height };
// Set clip rendering dimensions
if (clip != NULL) {
render_quad.x += clip->x;
render_quad.y += clip->y;
render_quad.w = clip->w;
render_quad.h = clip->h;
}
// Adjust the location to adjust for the expanded bounding box size after rotation
SDL_Point ac = { m_width / 2, m_height / 2 };
if (center) {
ac.x = center->x;
ac.y = center->y;
} else if (clip) {
ac.x -= clip->x;
ac.y -= clip->y;
}
// Render to screen
SDL_SetTextureAlphaMod(m_texture, alphamod);
SDL_RenderCopyEx(m_renderer, m_texture, clip, &render_quad, angle, &ac, flip);
}
int Texture::width() {
return m_width;
}
int Texture::height() {
return m_height;
}
| 23.801887 | 98 | 0.619897 | [
"render"
] |
95fac1a8e5a2ce75d992a6ae6098c72b42637207 | 2,188 | cpp | C++ | aws-cpp-sdk-sagemaker/source/model/RStudioServerProUserGroup.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-sagemaker/source/model/RStudioServerProUserGroup.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-sagemaker/source/model/RStudioServerProUserGroup.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sagemaker/model/RStudioServerProUserGroup.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace SageMaker
{
namespace Model
{
namespace RStudioServerProUserGroupMapper
{
static const int R_STUDIO_ADMIN_HASH = HashingUtils::HashString("R_STUDIO_ADMIN");
static const int R_STUDIO_USER_HASH = HashingUtils::HashString("R_STUDIO_USER");
RStudioServerProUserGroup GetRStudioServerProUserGroupForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == R_STUDIO_ADMIN_HASH)
{
return RStudioServerProUserGroup::R_STUDIO_ADMIN;
}
else if (hashCode == R_STUDIO_USER_HASH)
{
return RStudioServerProUserGroup::R_STUDIO_USER;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<RStudioServerProUserGroup>(hashCode);
}
return RStudioServerProUserGroup::NOT_SET;
}
Aws::String GetNameForRStudioServerProUserGroup(RStudioServerProUserGroup enumValue)
{
switch(enumValue)
{
case RStudioServerProUserGroup::R_STUDIO_ADMIN:
return "R_STUDIO_ADMIN";
case RStudioServerProUserGroup::R_STUDIO_USER:
return "R_STUDIO_USER";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace RStudioServerProUserGroupMapper
} // namespace Model
} // namespace SageMaker
} // namespace Aws
| 30.816901 | 94 | 0.652651 | [
"model"
] |
95fe70403dce3ca1369932172d5b9159549d7397 | 19,385 | cpp | C++ | doomtool/cefclient_osr_widget_win.cpp | teaegg/cef3-windows-sample | 253e3f00cb3c82ca3ce4bcc5cb6cc56f026c40c0 | [
"MIT"
] | 23 | 2015-03-26T02:23:22.000Z | 2021-12-06T05:53:40.000Z | doomtool/cefclient_osr_widget_win.cpp | mapduty/cef3-windows-sample | 253e3f00cb3c82ca3ce4bcc5cb6cc56f026c40c0 | [
"MIT"
] | null | null | null | doomtool/cefclient_osr_widget_win.cpp | mapduty/cef3-windows-sample | 253e3f00cb3c82ca3ce4bcc5cb6cc56f026c40c0 | [
"MIT"
] | 10 | 2015-04-17T10:37:18.000Z | 2019-09-06T18:56:04.000Z | // Copyright (c) 2011 The Chromium Embedded Framework 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 "cefclient_osr_widget_win.h"
#include <windowsx.h>
#include "include/cef_runnable.h"
#include "resource.h"
#include "util.h"
// static
CefRefPtr<OSRWindow> OSRWindow::Create(HINSTANCE hInst,
OSRBrowserProvider* browser_provider,
bool transparent) {
ASSERT(browser_provider);
if (!browser_provider)
return NULL;
return new OSRWindow(hInst, browser_provider, transparent);
}
// static
CefRefPtr<OSRWindow> OSRWindow::From(
CefRefPtr<ClientHandler::RenderHandler> renderHandler) {
return static_cast<OSRWindow*>(renderHandler.get());
}
HWND OSRWindow::CreateWidget(HWND hWndParent, const RECT& rect, LPCTSTR windowName, LPCTSTR className) {
//ASSERT(hInst_ == NULL);
RegisterOSRClass(hInst_, className);
HWND hWnd = ::CreateWindowEx(WS_EX_LAYERED, className, windowName,
WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_MINIMIZEBOX | WS_VISIBLE,
rect.left, rect.top, rect.right, rect.bottom,
hWndParent, 0, hInst_, 0);
if (!hWnd)
return 0;
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
// Reference released in OnDestroyed().
AddRef();
return hWnd;
}
void OSRWindow::DestroyWidget() {
//if (IsWindow(hWnd_))
//DestroyWindow(hWnd_);
}
void OSRWindow::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
PostMessage(browser->GetHost()->GetWindowHandle(), WM_CLOSE, 0, 0);
}
bool OSRWindow::GetRootScreenRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) {
RECT window_rect = {0};
HWND root_window = GetAncestor(browser->GetHost()->GetWindowHandle(), GA_ROOT);
if (::GetWindowRect(root_window, &window_rect)) {
rect = CefRect(window_rect.left,
window_rect.top,
window_rect.right - window_rect.left,
window_rect.bottom - window_rect.top);
return true;
}
return false;
}
bool OSRWindow::GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) {
RECT clientRect;
if (!::GetClientRect(browser->GetHost()->GetWindowHandle(), &clientRect))
return false;
rect.x = rect.y = 0;
rect.width = clientRect.right;
rect.height = clientRect.bottom;
return true;
}
bool OSRWindow::GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX,
int viewY,
int& screenX,
int& screenY) {
if (!::IsWindow(browser->GetHost()->GetWindowHandle()))
return false;
// Convert the point from view coordinates to actual screen coordinates.
POINT screen_pt = {viewX, viewY};
ClientToScreen(browser->GetHost()->GetWindowHandle(), &screen_pt);
screenX = screen_pt.x;
screenY = screen_pt.y;
return true;
}
void OSRWindow::OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) {
if (!show) {
CefRect dirty_rect = renderer_.popup_rect();
renderer_.ClearPopupRects();
browser->GetHost()->Invalidate(dirty_rect, PET_VIEW);
}
renderer_.OnPopupShow(browser, show);
}
void OSRWindow::OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) {
renderer_.OnPopupSize(browser, rect);
}
void OSRWindow::OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type,
const RectList& dirtyRects,
const void* buffer,
int width, int height) {
/*if (painting_popup_) {
renderer_.OnPaint(browser, type, dirtyRects, buffer, width, height);
return;
}
if (!hDC_)
EnableGL();
wglMakeCurrent(hDC_, hRC_);
renderer_.OnPaint(browser, type, dirtyRects, buffer, width, height);
if (type == PET_VIEW && !renderer_.popup_rect().IsEmpty()) {
painting_popup_ = true;
CefRect client_popup_rect(0, 0,
renderer_.popup_rect().width,
renderer_.popup_rect().height);
browser->GetHost()->Invalidate(client_popup_rect, PET_POPUP);
painting_popup_ = false;
}
renderer_.Render();
SwapBuffers(hDC_);*/
//::OutputDebugStringA("ON PAINT");
SIZE sz = {width, height};
HWND hWnd = browser->GetHost()->GetWindowHandle();
HDC hdc = GetDC(hWnd);
HDC hMemDc = CreateCompatibleDC(hdc);
HBITMAP hBitmap = CreateBitmap(width, height, 1, 32, buffer);
HGDIOBJ hOldBitmap = SelectObject(hMemDc, hBitmap);
BLENDFUNCTION _Blend;
_Blend.BlendOp=AC_SRC_OVER;
_Blend.BlendFlags=0;
_Blend.AlphaFormat= AC_SRC_ALPHA;
_Blend.SourceConstantAlpha=255;
POINT pt = {0, 0};
::UpdateLayeredWindow(hWnd, NULL, NULL, &sz, hMemDc, &pt, 0, &_Blend, ULW_ALPHA);
SelectObject(hMemDc, hOldBitmap);
DeleteObject(hBitmap);
DeleteDC(hMemDc);
}
void OSRWindow::OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) {
HWND hWnd = browser->GetHost()->GetWindowHandle();
if (!::IsWindow(hWnd))
return;
// Change the plugin window's cursor.
SetClassLongPtr(hWnd, GCLP_HCURSOR,
static_cast<LONG>(reinterpret_cast<LONG_PTR>(cursor)));
SetCursor(cursor);
}
void OSRWindow::Invalidate() {
if (!CefCurrentlyOn(TID_UI)) {
CefPostTask(TID_UI, NewCefRunnableMethod(this, &OSRWindow::Invalidate));
return;
}
// Don't post another task if the previous task is still pending.
if (render_task_pending_)
return;
render_task_pending_ = true;
// Render at 30fps.
static const int kRenderDelay = 1000 / 30;
CefPostDelayedTask(TID_UI, NewCefRunnableMethod(this, &OSRWindow::Render),
kRenderDelay);
}
OSRWindow::OSRWindow(HINSTANCE hInst, OSRBrowserProvider* browser_provider, bool transparent)
: renderer_(transparent),
browser_provider_(browser_provider),
//hWnd_(NULL),
hDC_(NULL),
hRC_(NULL),
hInst_(hInst),
painting_popup_(false),
render_task_pending_(false) {
}
OSRWindow::~OSRWindow() {
DestroyWidget();
}
void OSRWindow::Render() {
ASSERT(CefCurrentlyOn(TID_UI));
if (render_task_pending_)
render_task_pending_ = false;
if (!hDC_)
EnableGL();
wglMakeCurrent(hDC_, hRC_);
renderer_.Render();
SwapBuffers(hDC_);
}
void OSRWindow::EnableGL() {
/*ASSERT(CefCurrentlyOn(TID_UI));
PIXELFORMATDESCRIPTOR pfd;
int format;
// Get the device context.
hDC_ = GetDC(hWnd_);
// Set the pixel format for the DC.
ZeroMemory(&pfd, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
format = ChoosePixelFormat(hDC_, &pfd);
SetPixelFormat(hDC_, format, &pfd);
// Create and enable the render context.
hRC_ = wglCreateContext(hDC_);
wglMakeCurrent(hDC_, hRC_);
renderer_.Initialize();*/
}
void OSRWindow::DisableGL() {
/*ASSERT(CefCurrentlyOn(TID_UI));
if (!hDC_)
return;
renderer_.Cleanup();
if (IsWindow(hWnd_)) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hRC_);
ReleaseDC(hWnd_, hDC_);
}
hDC_ = NULL;
hRC_ = NULL;*/
}
void OSRWindow::OnDestroyed(HWND hWnd) {
SetWindowLongPtr(hWnd, GWLP_USERDATA, 0L);
CefRefPtr<CefBrowser> browser = browser_provider_->GetBrowser(hWnd);
if (browser.get()) {
// Notify the browser window that we would like to close it. This
// will result in a call to ClientHandler::DoClose() if the
// JavaScript 'onbeforeunload' event handler allows it.
browser->GetHost()->CloseBrowser(false);
}
Release();
}
ATOM OSRWindow::RegisterOSRClass(HINSTANCE hInstance, LPCTSTR className) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC;
wcex.lpfnWndProc = &OSRWindow::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = className;
wcex.hIconSm = NULL;
return RegisterClassEx(&wcex);
}
bool OSRWindow::isKeyDown(WPARAM wparam) {
return (GetKeyState(wparam) & 0x8000) != 0;
}
int OSRWindow::GetCefMouseModifiers(WPARAM wparam) {
int modifiers = 0;
if (wparam & MK_CONTROL)
modifiers |= EVENTFLAG_CONTROL_DOWN;
if (wparam & MK_SHIFT)
modifiers |= EVENTFLAG_SHIFT_DOWN;
if (isKeyDown(VK_MENU))
modifiers |= EVENTFLAG_ALT_DOWN;
if (wparam & MK_LBUTTON)
modifiers |= EVENTFLAG_LEFT_MOUSE_BUTTON;
if (wparam & MK_MBUTTON)
modifiers |= EVENTFLAG_MIDDLE_MOUSE_BUTTON;
if (wparam & MK_RBUTTON)
modifiers |= EVENTFLAG_RIGHT_MOUSE_BUTTON;
// Low bit set from GetKeyState indicates "toggled".
if (::GetKeyState(VK_NUMLOCK) & 1)
modifiers |= EVENTFLAG_NUM_LOCK_ON;
if (::GetKeyState(VK_CAPITAL) & 1)
modifiers |= EVENTFLAG_CAPS_LOCK_ON;
return modifiers;
}
int OSRWindow::GetCefKeyboardModifiers(WPARAM wparam, LPARAM lparam) {
int modifiers = 0;
if (isKeyDown(VK_SHIFT))
modifiers |= EVENTFLAG_SHIFT_DOWN;
if (isKeyDown(VK_CONTROL))
modifiers |= EVENTFLAG_CONTROL_DOWN;
if (isKeyDown(VK_MENU))
modifiers |= EVENTFLAG_ALT_DOWN;
// Low bit set from GetKeyState indicates "toggled".
if (::GetKeyState(VK_NUMLOCK) & 1)
modifiers |= EVENTFLAG_NUM_LOCK_ON;
if (::GetKeyState(VK_CAPITAL) & 1)
modifiers |= EVENTFLAG_CAPS_LOCK_ON;
switch (wparam) {
case VK_RETURN:
if ((lparam >> 16) & KF_EXTENDED)
modifiers |= EVENTFLAG_IS_KEY_PAD;
break;
case VK_INSERT:
case VK_DELETE:
case VK_HOME:
case VK_END:
case VK_PRIOR:
case VK_NEXT:
case VK_UP:
case VK_DOWN:
case VK_LEFT:
case VK_RIGHT:
if (!((lparam >> 16) & KF_EXTENDED))
modifiers |= EVENTFLAG_IS_KEY_PAD;
break;
case VK_NUMLOCK:
case VK_NUMPAD0:
case VK_NUMPAD1:
case VK_NUMPAD2:
case VK_NUMPAD3:
case VK_NUMPAD4:
case VK_NUMPAD5:
case VK_NUMPAD6:
case VK_NUMPAD7:
case VK_NUMPAD8:
case VK_NUMPAD9:
case VK_DIVIDE:
case VK_MULTIPLY:
case VK_SUBTRACT:
case VK_ADD:
case VK_DECIMAL:
case VK_CLEAR:
modifiers |= EVENTFLAG_IS_KEY_PAD;
break;
case VK_SHIFT:
if (isKeyDown(VK_LSHIFT))
modifiers |= EVENTFLAG_IS_LEFT;
else if (isKeyDown(VK_RSHIFT))
modifiers |= EVENTFLAG_IS_RIGHT;
break;
case VK_CONTROL:
if (isKeyDown(VK_LCONTROL))
modifiers |= EVENTFLAG_IS_LEFT;
else if (isKeyDown(VK_RCONTROL))
modifiers |= EVENTFLAG_IS_RIGHT;
break;
case VK_MENU:
if (isKeyDown(VK_LMENU))
modifiers |= EVENTFLAG_IS_LEFT;
else if (isKeyDown(VK_RMENU))
modifiers |= EVENTFLAG_IS_RIGHT;
break;
case VK_LWIN:
modifiers |= EVENTFLAG_IS_LEFT;
break;
case VK_RWIN:
modifiers |= EVENTFLAG_IS_RIGHT;
break;
}
return modifiers;
}
bool OSRWindow::IsOverPopupWidget(int x, int y) const {
const CefRect& rc = renderer_.popup_rect();
int popup_right = rc.x + rc.width;
int popup_bottom = rc.y + rc.height;
return (x >= rc.x) && (x < popup_right) &&
(y >= rc.y) && (y < popup_bottom);
}
int OSRWindow::GetPopupXOffset() const {
return renderer_.original_popup_rect().x - renderer_.popup_rect().x;
}
int OSRWindow::GetPopupYOffset() const {
return renderer_.original_popup_rect().y - renderer_.popup_rect().y;
}
void OSRWindow::ApplyPopupOffset(int& x, int& y) const {
if (IsOverPopupWidget(x, y)) {
x += GetPopupXOffset();
y += GetPopupYOffset();
}
}
// Plugin window procedure.
// static
LRESULT CALLBACK OSRWindow::WndProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam) {
static POINT lastMousePos, curMousePos;
static bool mouseRotation = false;
static bool mouseTracking = false;
static int lastClickX = 0;
static int lastClickY = 0;
static CefBrowserHost::MouseButtonType lastClickButton = MBT_LEFT;
static int gLastClickCount = 0;
static double gLastClickTime = 0;
static bool gLastMouseDownOnView = false;
OSRWindow* window =
reinterpret_cast<OSRWindow*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
CefRefPtr<CefBrowserHost> browser;
if (window && window->browser_provider_->GetBrowser(hWnd).get())
browser = window->browser_provider_->GetBrowser(hWnd)->GetHost();
LONG currentTime = 0;
bool cancelPreviousClick = false;
if (message == WM_LBUTTONDOWN || message == WM_RBUTTONDOWN ||
message == WM_MBUTTONDOWN || message == WM_MOUSEMOVE ||
message == WM_MOUSELEAVE) {
currentTime = GetMessageTime();
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
cancelPreviousClick =
(abs(lastClickX - x) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2))
|| (abs(lastClickY - y) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2))
|| ((currentTime - gLastClickTime) > GetDoubleClickTime());
if (cancelPreviousClick &&
(message == WM_MOUSEMOVE || message == WM_MOUSELEAVE)) {
gLastClickCount = 0;
lastClickX = 0;
lastClickY = 0;
gLastClickTime = 0;
}
}
switch (message) {
case WM_SYSCOMMAND: {
switch(wParam) {
case SC_MINIMIZE: {
::MessageBox(NULL, L"minimize", NULL, 0);
return 0;
}
case SC_MAXIMIZE: {
::MessageBox(NULL, L"maximize", NULL, 0);
}
}
}
break;
case WM_GETMINMAXINFO:
{
MINMAXINFO *lpMMI = (MINMAXINFO*)lParam;
lpMMI->ptMaxSize.x = GetSystemMetrics(SM_CXFULLSCREEN);
lpMMI->ptMaxSize.y = GetSystemMetrics(SM_CYFULLSCREEN) + GetSystemMetrics(SM_CYCAPTION);
}
break;
case WM_DESTROY:
if (window)
window->OnDestroyed(hWnd);
return 0;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN: {
SetCapture(hWnd);
SetFocus(hWnd);
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
if (wParam & MK_SHIFT) {
// Start rotation effect.
lastMousePos.x = curMousePos.x = x;
lastMousePos.y = curMousePos.y = y;
mouseRotation = true;
} else {
CefBrowserHost::MouseButtonType btnType =
(message == WM_LBUTTONDOWN ? MBT_LEFT : (
message == WM_RBUTTONDOWN ? MBT_RIGHT : MBT_MIDDLE));
if (!cancelPreviousClick && (btnType == lastClickButton)) {
++gLastClickCount;
} else {
gLastClickCount = 1;
lastClickX = x;
lastClickY = y;
}
gLastClickTime = currentTime;
lastClickButton = btnType;
if (browser.get()) {
CefMouseEvent mouse_event;
mouse_event.x = x;
mouse_event.y = y;
gLastMouseDownOnView = !window->IsOverPopupWidget(x, y);
window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = GetCefMouseModifiers(wParam);
browser->SendMouseClickEvent(mouse_event, btnType, false,
gLastClickCount);
}
}
break;
}
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
if (GetCapture() == hWnd)
ReleaseCapture();
if (mouseRotation) {
// End rotation effect.
mouseRotation = false;
window->renderer_.SetSpin(0, 0);
window->Invalidate();
} else {
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
CefBrowserHost::MouseButtonType btnType =
(message == WM_LBUTTONUP ? MBT_LEFT : (
message == WM_RBUTTONUP ? MBT_RIGHT : MBT_MIDDLE));
if (browser.get()) {
CefMouseEvent mouse_event;
mouse_event.x = x;
mouse_event.y = y;
if (gLastMouseDownOnView &&
window->IsOverPopupWidget(x, y) &&
(window->GetPopupXOffset() || window->GetPopupYOffset())) {
break;
}
window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = GetCefMouseModifiers(wParam);
browser->SendMouseClickEvent(mouse_event, btnType, true,
gLastClickCount);
}
}
break;
case WM_MOUSEMOVE: {
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
if (mouseRotation) {
// Apply rotation effect.
curMousePos.x = x;
curMousePos.y = y;
window->renderer_.IncrementSpin((curMousePos.x - lastMousePos.x),
(curMousePos.y - lastMousePos.y));
lastMousePos.x = curMousePos.x;
lastMousePos.y = curMousePos.y;
window->Invalidate();
} else {
if (!mouseTracking) {
// Start tracking mouse leave. Required for the WM_MOUSELEAVE event to
// be generated.
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = hWnd;
TrackMouseEvent(&tme);
mouseTracking = true;
}
if (browser.get()) {
CefMouseEvent mouse_event;
mouse_event.x = x;
mouse_event.y = y;
window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = GetCefMouseModifiers(wParam);
browser->SendMouseMoveEvent(mouse_event, false);
}
}
break;
}
case WM_MOUSELEAVE:
if (mouseTracking) {
// Stop tracking mouse leave.
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE & TME_CANCEL;
tme.hwndTrack = hWnd;
TrackMouseEvent(&tme);
mouseTracking = false;
}
if (browser.get()) {
CefMouseEvent mouse_event;
mouse_event.x = 0;
mouse_event.y = 0;
mouse_event.modifiers = GetCefMouseModifiers(wParam);
browser->SendMouseMoveEvent(mouse_event, true);
}
break;
case WM_MOUSEWHEEL:
if (browser.get()) {
POINT screen_point = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
HWND scrolled_wnd = ::WindowFromPoint(screen_point);
if (scrolled_wnd != hWnd) {
break;
}
ScreenToClient(hWnd, &screen_point);
int delta = GET_WHEEL_DELTA_WPARAM(wParam);
CefMouseEvent mouse_event;
mouse_event.x = screen_point.x;
mouse_event.y = screen_point.y;
window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = GetCefMouseModifiers(wParam);
browser->SendMouseWheelEvent(mouse_event,
isKeyDown(VK_SHIFT) ? delta : 0,
!isKeyDown(VK_SHIFT) ? delta : 0);
}
break;
case WM_SIZE:
if (browser.get())
browser->WasResized();
break;
case WM_SETFOCUS:
case WM_KILLFOCUS:
if (browser.get())
browser->SendFocusEvent(message == WM_SETFOCUS);
break;
case WM_CAPTURECHANGED:
case WM_CANCELMODE:
if (!mouseRotation) {
if (browser.get())
browser->SendCaptureLostEvent();
}
break;
case WM_SYSCHAR:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_KEYDOWN:
case WM_KEYUP:
case WM_CHAR: {
CefKeyEvent event;
event.windows_key_code = wParam;
event.native_key_code = lParam;
event.is_system_key = message == WM_SYSCHAR ||
message == WM_SYSKEYDOWN ||
message == WM_SYSKEYUP;
if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
event.type = KEYEVENT_RAWKEYDOWN;
else if (message == WM_KEYUP || message == WM_SYSKEYUP)
event.type = KEYEVENT_KEYUP;
else
event.type = KEYEVENT_CHAR;
event.modifiers = GetCefKeyboardModifiers(wParam, lParam);
if (browser.get())
browser->SendKeyEvent(event);
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
RECT rc;
BeginPaint(hWnd, &ps);
rc = ps.rcPaint;
EndPaint(hWnd, &ps);
if (browser.get()) {
browser->Invalidate(CefRect(rc.left,
rc.top,
rc.right - rc.left,
rc.bottom - rc.top), PET_VIEW);
}
return 0;
}
case WM_ERASEBKGND:
return 0;
case ID_OPENMAINWINDOW: {
RECT rect;
rect.right = GetSystemMetrics(SM_CXFULLSCREEN);
rect.bottom = GetSystemMetrics(SM_CYFULLSCREEN) + GetSystemMetrics(SM_CYCAPTION);
rect.left = 0;
rect.top = 0;
HWND hWnd = window->CreateWidget(NULL, rect, L"DoomTool", L"DoomToolWnd");
CefWindowInfo info;
CefBrowserSettings browser_settings;
info.SetAsOffScreen(hWnd);
info.SetTransparentPainting(TRUE);
CefBrowserHost::CreateBrowser(info, browser->GetClient().get(),
L"http://localhost/", browser_settings, NULL);
return 0;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
| 26.701102 | 104 | 0.698942 | [
"render"
] |
2503da297b138cecf33429d0016d6e477d6f6cc3 | 2,634 | cpp | C++ | Hacker-Rank/Algorithms/implementation/bomber-man21.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | 1 | 2019-05-20T14:38:05.000Z | 2019-05-20T14:38:05.000Z | Hacker-Rank/Algorithms/implementation/bomber-man21.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | null | null | null | Hacker-Rank/Algorithms/implementation/bomber-man21.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int ax[]={1,0,-1,0};
int by[]={0,1,0,-1};
vector<vector<int>> v;
int m,n;
bool isvalid(int x,int y)
{
if(x>=0&&x<m&&y>=0&&y<n) return true;
return false;
}
void blast()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(v[i][j]==2)
{
v[i][j]=0;
for(int k=0;k<4;k++)
{
if(isvalid(i+ax[k],j+by[k]))
{
if(v[i+ax[k]][j+by[k]]==1) v[i+ax[k]][j+by[k]]=0;
}
}
}
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(v[i][j]==1)
{
v[i][j]=2;
}
}
}
}
void setall()
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(v[i][j]==0) v[i][j]=1;
}
}
}
void onesecond(){
}
void print(vector<vector<int>> &v)
{
// cout<<'\n';
for(auto &i:v)
{
for(auto &j:i)
{
if(j==0) cout<<'.';
else cout<<'O';
}
cout<<'\n';
}
// cout<<'\n';
}
void print1()
{
cout<<'\n';
for(auto &i:v)
{
for(auto &j:i)
{
cout<<j;
}
cout<<'\n';
}
cout<<'\n';
}
int main(int argc, char const *argv[])
{
int k,p=0;
cin>>m>>n>>k;
v.resize(m);
string s;
for(int i=0;i<m;i++)
{
cin>>s;
v[i].resize(n);
for(int j=0;j<n;j++)
{
if(s[j]=='O') v[i][j]=2;
else v[i][j]=0;
}
}
map<vector<vector<int>>,int> myset;
map<int,vector<vector<int>>> index;
if(k%2==0)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++) cout<<'O';
cout<<'\n';
}
return 0;
}
int pos=1,targetpos=1;
index[pos]=v;
myset[v]=pos++;
while(1)
{
setall();
blast();
auto it=myset.find(v);
if(it==myset.end())
{
index[pos]=v;
myset[v]=pos++;
}
else{
targetpos=it->second;
break;
}
}
// for(auto &a:myset)
// {
// auto my=a.first;
// for(auto &row:my)
// {
// for(auto &el:row) cout<<el;
// cout<<'\n';
// }
// }
int cycle_size=pos-targetpos;
k=k/2+1;
if(k>=targetpos)
{
k-=targetpos;
k=k%cycle_size+targetpos;
}
auto ans=index[k];
print(ans);
return 0;
}
| 16.670886 | 73 | 0.345103 | [
"vector"
] |
250dfc1642735dce17dc6b1d07692049747547d9 | 5,370 | hpp | C++ | include/GlobalNamespace/SliderControllerBase.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/SliderControllerBase.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/SliderControllerBase.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: MaterialPropertyBlockController
class MaterialPropertyBlockController;
// Forward declaring type: CutoutAnimateEffect
class CutoutAnimateEffect;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: SliderControllerBase
class SliderControllerBase;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::SliderControllerBase);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::SliderControllerBase*, "", "SliderControllerBase");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x29
#pragma pack(push, 1)
// Autogenerated type: SliderControllerBase
// [TokenAttribute] Offset: FFFFFFFF
class SliderControllerBase : public ::UnityEngine::MonoBehaviour {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// protected MaterialPropertyBlockController _materialPropertyBlockController
// Size: 0x8
// Offset: 0x18
::GlobalNamespace::MaterialPropertyBlockController* materialPropertyBlockController;
// Field size check
static_assert(sizeof(::GlobalNamespace::MaterialPropertyBlockController*) == 0x8);
// protected CutoutAnimateEffect _cutoutAnimateEffect
// Size: 0x8
// Offset: 0x20
::GlobalNamespace::CutoutAnimateEffect* cutoutAnimateEffect;
// Field size check
static_assert(sizeof(::GlobalNamespace::CutoutAnimateEffect*) == 0x8);
// protected System.Boolean _dissolving
// Size: 0x1
// Offset: 0x28
bool dissolving;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: protected MaterialPropertyBlockController _materialPropertyBlockController
::GlobalNamespace::MaterialPropertyBlockController*& dyn__materialPropertyBlockController();
// Get instance field reference: protected CutoutAnimateEffect _cutoutAnimateEffect
::GlobalNamespace::CutoutAnimateEffect*& dyn__cutoutAnimateEffect();
// Get instance field reference: protected System.Boolean _dissolving
bool& dyn__dissolving();
// protected System.Void AnimateCutout(System.Single cutoutStart, System.Single cutoutEnd, System.Single duration)
// Offset: 0x2A9F7E4
void AnimateCutout(float cutoutStart, float cutoutEnd, float duration);
// public System.Void .ctor()
// Offset: 0x2AA0068
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static SliderControllerBase* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::SliderControllerBase::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<SliderControllerBase*, creationType>()));
}
}; // SliderControllerBase
#pragma pack(pop)
static check_size<sizeof(SliderControllerBase), 40 + sizeof(bool)> __GlobalNamespace_SliderControllerBaseSizeCheck;
static_assert(sizeof(SliderControllerBase) == 0x29);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::SliderControllerBase::AnimateCutout
// Il2CppName: AnimateCutout
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::SliderControllerBase::*)(float, float, float)>(&GlobalNamespace::SliderControllerBase::AnimateCutout)> {
static const MethodInfo* get() {
static auto* cutoutStart = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* cutoutEnd = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::SliderControllerBase*), "AnimateCutout", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{cutoutStart, cutoutEnd, duration});
}
};
// Writing MetadataGetter for method: GlobalNamespace::SliderControllerBase::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 47.522124 | 201 | 0.75121 | [
"object",
"vector"
] |
2512364703976b72e25dc027aa9663f39124242d | 3,744 | cpp | C++ | src/ADT/SharedArray.cpp | mishazharov/caffeine | a1a8ad5bd2d69b5378d71d15ddec4658ea34f057 | [
"MIT"
] | 17 | 2021-03-04T01:10:22.000Z | 2022-03-30T18:33:14.000Z | src/ADT/SharedArray.cpp | mishazharov/caffeine | a1a8ad5bd2d69b5378d71d15ddec4658ea34f057 | [
"MIT"
] | 320 | 2020-11-16T02:42:50.000Z | 2022-03-31T16:43:26.000Z | src/ADT/SharedArray.cpp | mishazharov/caffeine | a1a8ad5bd2d69b5378d71d15ddec4658ea34f057 | [
"MIT"
] | 6 | 2020-11-10T02:37:10.000Z | 2021-12-25T06:58:44.000Z |
#include "caffeine/ADT/SharedArray.h"
#include "caffeine/Support/Assert.h"
namespace caffeine {
SharedArray::SharedArray(const std::vector<char>& data)
: data_(data), size_(data.size()) {}
SharedArray::SharedArray(std::vector<char>&& data) : data_(std::move(data)) {
size_ = std::get<std::vector<char>>(data_).size();
}
SharedArray::SharedArray(const char* data, size_t size)
: data_(std::vector<char>(data, data + size)), size_(size) {}
SharedArray::SharedArray(const SharedArray& array) {
*this = array;
}
SharedArray::SharedArray(SharedArray&& array)
: data_(std::move(array.data_)), modcnt_(array.modcnt_),
size_(array.size_) {
array.data_ = std::vector<char>();
array.size_ = 0;
array.modcnt_ = 0;
}
SharedArray& SharedArray::operator=(const SharedArray& array) {
if (auto* data = std::get_if<std::vector<char>>(&array.data_)) {
if (data->size() <= min_copy_size) {
data_ = *data;
} else {
auto variant = std::make_shared<Variant>(std::move(array.data_));
array.data_ = Modified(variant);
data_ = Modified(variant);
}
} else {
auto& mod = std::get<Modified>(array.data_);
if (mod.changes.size() <= min_copy_size) {
data_ = mod;
} else {
auto variant = std::make_shared<Variant>(std::move(array.data_));
array.data_ = Modified(variant);
data_ = Modified(variant);
}
}
modcnt_ = array.modcnt_;
size_ = array.size_;
return *this;
}
SharedArray& SharedArray::operator=(SharedArray&& array) {
data_ = std::move(array.data_);
size_ = array.size_;
modcnt_ = array.modcnt_;
array.data_ = std::vector<char>();
array.size_ = 0;
array.modcnt_ = 0;
return *this;
}
void SharedArray::store(size_t idx, char value) {
CAFFEINE_ASSERT(idx < size(), "index out of bounds");
std::visit(
[=](auto& data) {
using type = std::decay_t<decltype(data)>;
if constexpr (std::is_same_v<type, std::vector<char>>) {
data.at(idx) = value;
} else {
auto it = data.changes.find(idx);
if (it != data.changes.end()) {
it->second = value;
return;
}
if (data[idx] == value)
return;
data.changes.insert({idx, value});
modcnt_ += 1;
if (modcnt_ > size() * flatten_threshold)
flatten();
}
},
data_);
}
char SharedArray::load(size_t idx) const {
CAFFEINE_ASSERT(idx < size(), "index out of bounds");
return std::visit([=](const auto& val) -> char { return val[idx]; }, data_);
}
void SharedArray::flatten() {
if (is_flat())
return;
std::vector<char> newdata;
newdata.reserve(size());
for (size_t i = 0; i < size(); ++i)
newdata.push_back(load(i));
data_ = std::move(newdata);
}
char* SharedArray::data() {
flatten();
return std::get<std::vector<char>>(data_).data();
}
char SharedArray::operator[](size_t idx) const {
return load(idx);
}
SharedArray::IndexAccessor SharedArray::operator[](size_t idx) {
CAFFEINE_ASSERT(idx < size(), "index out of bounds");
return IndexAccessor(this, idx);
}
bool operator==(const SharedArray& lhs, const SharedArray& rhs) {
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); ++i) {
if (lhs[i] != rhs[i])
return false;
}
return true;
}
bool operator!=(const SharedArray& lhs, const SharedArray& rhs) {
return !(lhs == rhs);
}
llvm::hash_code hash_value(const SharedArray& array) {
if (const auto* vec = std::get_if<std::vector<char>>(&array.data_)) {
return llvm::hash_combine_range(vec->begin(), vec->end());
} else {
return llvm::hash_combine_range(array.begin(), array.end());
}
}
} // namespace caffeine
| 25.297297 | 78 | 0.615652 | [
"vector"
] |
2515101249f8b4f23d7b1894a181b94f42a31865 | 3,220 | cpp | C++ | tests/Mutators/ScalarValueMutatorTest.cpp | clagah/mull | 9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99 | [
"Apache-2.0"
] | null | null | null | tests/Mutators/ScalarValueMutatorTest.cpp | clagah/mull | 9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99 | [
"Apache-2.0"
] | null | null | null | tests/Mutators/ScalarValueMutatorTest.cpp | clagah/mull | 9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99 | [
"Apache-2.0"
] | 1 | 2019-06-10T02:43:04.000Z | 2019-06-10T02:43:04.000Z | #include "mull/Mutators/ScalarValueMutator.h"
#include "FixturePaths.h"
#include "TestModuleFactory.h"
#include "mull/Config/Configuration.h"
#include "mull/Filter.h"
#include "mull/ModuleLoader.h"
#include "mull/MutationPoint.h"
#include "mull/MutationsFinder.h"
#include "mull/Program/Program.h"
#include "mull/Testee.h"
#include "mull/Toolchain/Compiler.h"
#include "mull/Toolchain/Toolchain.h"
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include "gtest/gtest.h"
using namespace mull;
using namespace llvm;
TEST(ScalarValueMutator, getMutationPoint) {
LLVMContext llvmContext;
ModuleLoader loader;
auto mullModule = loader.loadModuleAtPath(
fixtures::mutators_scalar_value_module_bc_path(), llvmContext);
std::vector<std::unique_ptr<MullModule>> modules;
modules.push_back(std::move(mullModule));
Program program({}, {}, std::move(modules));
auto scalarValueFunction = program.lookupDefinedFunction("scalar_value");
std::vector<std::unique_ptr<Testee>> testees;
testees.emplace_back(make_unique<Testee>(scalarValueFunction, nullptr, 1));
auto mergedTestees = mergeTestees(testees);
Configuration configuration;
std::vector<std::unique_ptr<Mutator>> mutators;
mutators.emplace_back(make_unique<ScalarValueMutator>());
MutationsFinder finder(std::move(mutators), configuration);
Filter filter;
std::vector<MutationPoint *> mutationPoints =
finder.getMutationPoints(program, mergedTestees, filter);
ASSERT_EQ(mutationPoints.size(), 4U);
ASSERT_TRUE(isa<StoreInst>(mutationPoints[0]->getOriginalValue()));
ASSERT_TRUE(isa<StoreInst>(mutationPoints[1]->getOriginalValue()));
ASSERT_TRUE(isa<BinaryOperator>(mutationPoints[2]->getOriginalValue()));
ASSERT_TRUE(isa<BinaryOperator>(mutationPoints[3]->getOriginalValue()));
ASSERT_EQ(mutationPoints[0]->getAddress().getFnIndex(), 0);
ASSERT_EQ(mutationPoints[0]->getAddress().getBBIndex(), 0);
ASSERT_EQ(mutationPoints[0]->getAddress().getIIndex(), 4);
ASSERT_EQ(mutationPoints[1]->getAddress().getFnIndex(), 0);
ASSERT_EQ(mutationPoints[1]->getAddress().getBBIndex(), 0);
ASSERT_EQ(mutationPoints[1]->getAddress().getIIndex(), 5);
ASSERT_EQ(mutationPoints[2]->getAddress().getFnIndex(), 0);
ASSERT_EQ(mutationPoints[2]->getAddress().getBBIndex(), 0);
ASSERT_EQ(mutationPoints[2]->getAddress().getIIndex(), 9);
ASSERT_EQ(mutationPoints[3]->getAddress().getFnIndex(), 0);
ASSERT_EQ(mutationPoints[3]->getAddress().getBBIndex(), 0);
ASSERT_EQ(mutationPoints[3]->getAddress().getIIndex(), 12);
}
TEST(DISABLED_ScalarValueMutator, failingMutationPoint) {
LLVMContext llvmContext;
ModuleLoader loader;
auto mullModule = loader.loadModuleAtPath(
fixtures::hardcode_openssl_bio_enc_test_oll_path(), llvmContext);
MutationPointAddress address(15, 10, 7);
ScalarValueMutator mutator;
MutationPoint point(&mutator, address, nullptr, nullptr, "diagnostics",
SourceLocation::nullSourceLocation(), mullModule.get());
Configuration configuration;
Toolchain toolchain(configuration);
// auto mutant = point.cloneModuleAndApplyMutation();
// toolchain.compiler().compileModule(mutant.get());
}
| 37.011494 | 78 | 0.75559 | [
"vector"
] |
2516763e6b029746cf53e4421fef9169c533a3c3 | 9,785 | cpp | C++ | src/gsbn/Database.cpp | herenvarno/gsbn | 47ed0932b605d8b3cf9661f9308908364ad5892e | [
"MIT"
] | 2 | 2016-08-12T15:06:02.000Z | 2021-10-05T08:12:17.000Z | src/gsbn/Database.cpp | herenvarno/gsbn | 47ed0932b605d8b3cf9661f9308908364ad5892e | [
"MIT"
] | 2 | 2017-04-23T17:22:23.000Z | 2017-05-25T14:22:51.000Z | src/gsbn/Database.cpp | herenvarno/gsbn | 47ed0932b605d8b3cf9661f9308908364ad5892e | [
"MIT"
] | null | null | null | #include "gsbn/Database.hpp"
namespace gsbn{
Database::Database() : _initialized(false){
}
Database::~Database(){
for(map<string, void*>::iterator it=_sync_vectors.begin(); it!=_sync_vectors.end(); it++){
if(it->first.substr(it->first.length()-2) == "_i"){
delete (SyncVector<int>*)(it->second);
}else if(it->first.substr(it->first.length()-2) == "_f"){
delete (SyncVector<float>*)(it->second);
}else{
delete (SyncVector<double>*)(it->second);
}
}
}
void Database::init_new(SolverParam solver_param){
if(_initialized){
LOG(WARNING) << "Multiple initializetion of Database detected, ignore!";
return;
}
_initialized = true;
}
void Database::init_copy(SolverParam solver_param, SolverState solver_state){
if(_initialized){
LOG(WARNING) << "Multiple initializetion of Database detected, ignore!";
return;
}
int v_st_size;
v_st_size = solver_state.vector_state_i8_size();
for(int i=0; i<v_st_size; i++){
VectorStateI8 vst = solver_state.vector_state_i8(i);
SyncVector<int8_t> *v;
CHECK(v = create_sync_vector_i8(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
v_st_size = solver_state.vector_state_i16_size();
for(int i=0; i<v_st_size; i++){
VectorStateI16 vst = solver_state.vector_state_i16(i);
SyncVector<int16_t> *v;
CHECK(v = create_sync_vector_i16(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
v_st_size = solver_state.vector_state_i32_size();
for(int i=0; i<v_st_size; i++){
VectorStateI32 vst = solver_state.vector_state_i32(i);
SyncVector<int32_t> *v;
CHECK(v = create_sync_vector_i32(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
v_st_size = solver_state.vector_state_i64_size();
for(int i=0; i<v_st_size; i++){
VectorStateI64 vst = solver_state.vector_state_i64(i);
SyncVector<int64_t> *v;
CHECK(v = create_sync_vector_i64(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
v_st_size = solver_state.vector_state_f16_size();
for(int i=0; i<v_st_size; i++){
VectorStateF16 vst = solver_state.vector_state_f16(i);
SyncVector<fp16> *v;
CHECK(v = create_sync_vector_f16(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
v_st_size = solver_state.vector_state_f32_size();
for(int i=0; i<v_st_size; i++){
VectorStateF32 vst = solver_state.vector_state_f32(i);
SyncVector<float> *v;
CHECK(v = create_sync_vector_f32(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
v_st_size = solver_state.vector_state_f64_size();
for(int i=0; i<v_st_size; i++){
VectorStateF64 vst = solver_state.vector_state_f64(i);
SyncVector<double> *v;
CHECK(v = create_sync_vector_f64(vst.name()));
int ds=vst.data_size();
for(int j=0; j<ds; j++){
v->mutable_cpu_vector()->push_back(vst.data(j));
}
v->set_ld(vst.ld());
}
_initialized = true;
}
SyncVector<int8_t>* Database::create_sync_vector_i8(const string name){
if(sync_vector_i8(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<int8_t> *v = new SyncVector<int8_t>();
register_sync_vector_i8(name, v);
return v;
}
SyncVector<int16_t>* Database::create_sync_vector_i16(const string name){
if(sync_vector_i16(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<int16_t> *v = new SyncVector<int16_t>();
register_sync_vector_i16(name, v);
return v;
}
SyncVector<int32_t>* Database::create_sync_vector_i32(const string name){
if(sync_vector_i32(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<int32_t> *v = new SyncVector<int32_t>();
register_sync_vector_i32(name, v);
return v;
}
SyncVector<int64_t>* Database::create_sync_vector_i64(const string name){
if(sync_vector_i64(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<int64_t> *v = new SyncVector<int64_t>();
register_sync_vector_i64(name, v);
return v;
}
SyncVector<fp16>* Database::create_sync_vector_f16(const string name){
if(sync_vector_f16(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<fp16> *v = new SyncVector<fp16>();
register_sync_vector_f16(name, v);
return v;
}
SyncVector<float>* Database::create_sync_vector_f32(const string name){
if(sync_vector_f32(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<float> *v = new SyncVector<float>();
register_sync_vector_f32(name, v);
return v;
}
SyncVector<double>* Database::create_sync_vector_f64(const string name){
if(sync_vector_f64(name)){
LOG(WARNING)<< "sync vector ["<< name << "] already existed!";
return NULL;
}
SyncVector<double> *v = new SyncVector<double>();
register_sync_vector_f64(name, v);
return v;
}
SyncVector<int8_t>* Database::sync_vector_i8(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_i08");
if(it!=_sync_vectors.end()){
return (SyncVector<int8_t>*)(it->second);
}
return NULL;
}
SyncVector<int16_t>* Database::sync_vector_i16(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_i16");
if(it!=_sync_vectors.end()){
return (SyncVector<int16_t>*)(it->second);
}
return NULL;
}
SyncVector<int32_t>* Database::sync_vector_i32(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_i32");
if(it!=_sync_vectors.end()){
return (SyncVector<int32_t>*)(it->second);
}
return NULL;
}
SyncVector<int64_t>* Database::sync_vector_i64(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_i64");
if(it!=_sync_vectors.end()){
return (SyncVector<int64_t>*)(it->second);
}
return NULL;
}
SyncVector<fp16>* Database::sync_vector_f16(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_f16");
if(it!=_sync_vectors.end()){
return (SyncVector<fp16>*)(it->second);
}
return NULL;
}
SyncVector<float>* Database::sync_vector_f32(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_f32");
if(it!=_sync_vectors.end()){
return (SyncVector<float>*)(it->second);
}
return NULL;
}
SyncVector<double>* Database::sync_vector_f64(const string name){
map<string, void*>::iterator it = _sync_vectors.find(name+"_f64");
if(it!=_sync_vectors.end()){
return (SyncVector<double>*)(it->second);
}
return NULL;
}
void Database::register_sync_vector_i8(const string name, SyncVector<int8_t> *v){
_sync_vectors[name+"_i08"] = (void*)(v);
}
void Database::register_sync_vector_i16(const string name, SyncVector<int16_t> *v){
_sync_vectors[name+"_i16"] = (void*)(v);
}
void Database::register_sync_vector_i32(const string name, SyncVector<int32_t> *v){
_sync_vectors[name+"_i32"] = (void*)(v);
}
void Database::register_sync_vector_i64(const string name, SyncVector<int64_t> *v){
_sync_vectors[name+"_i64"] = (void*)(v);
}
void Database::register_sync_vector_f16(const string name, SyncVector<fp16> *v){
_sync_vectors[name+"_f16"] = (void*)(v);
}
void Database::register_sync_vector_f32(const string name, SyncVector<float> *v){
_sync_vectors[name+"_f32"] = (void*)(v);
}
void Database::register_sync_vector_f64(const string name, SyncVector<double> *v){
_sync_vectors[name+"_f64"] = (void*)(v);
}
SolverState Database::state_to_proto(){
SolverState st;
for(map<string, void*>::iterator it=_sync_vectors.begin(); it!=_sync_vectors.end(); it++){
if((it->first)[0]!='.'){
if(it->first.substr(it->first.length()-4) == "_i08"){
VectorStateI8 *vec_st = st.add_vector_state_i8();
*vec_st=static_cast<SyncVector<int8_t>*>(it->second)->state_i8();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}else if(it->first.substr(it->first.length()-4) == "_i16"){
VectorStateI16 *vec_st = st.add_vector_state_i16();
*vec_st=static_cast<SyncVector<int16_t>*>(it->second)->state_i16();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}else if(it->first.substr(it->first.length()-4) == "_i32"){
VectorStateI32 *vec_st = st.add_vector_state_i32();
*vec_st=static_cast<SyncVector<int32_t>*>(it->second)->state_i32();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}else if(it->first.substr(it->first.length()-4) == "_i64"){
VectorStateI64 *vec_st = st.add_vector_state_i64();
*vec_st=static_cast<SyncVector<int64_t>*>(it->second)->state_i64();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}else if(it->first.substr(it->first.length()-4) == "_f16"){
VectorStateF16 *vec_st = st.add_vector_state_f16();
*vec_st=static_cast<SyncVector<fp16>*>(it->second)->state_f16();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}else if(it->first.substr(it->first.length()-4) == "_f32"){
VectorStateF32 *vec_st = st.add_vector_state_f32();
*vec_st=static_cast<SyncVector<float>*>(it->second)->state_f32();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}else if(it->first.substr(it->first.length()-4) == "_f64"){
VectorStateF64 *vec_st = st.add_vector_state_f64();
*vec_st=static_cast<SyncVector<double>*>(it->second)->state_f64();
vec_st->set_name(it->first.substr(0, it->first.length()-4));
}
}
}
return st;
}
}
| 32.83557 | 91 | 0.692591 | [
"vector"
] |
2522005b7a2cafbf43c3107e88c8441ed1d0c9a8 | 439 | cpp | C++ | HashTables/Intersection of 2 Arrays.cpp | LynX-gh/LeetCode_Solutions | a0d03f8df0e120907bcdde94800587fcd4f05b60 | [
"MIT"
] | null | null | null | HashTables/Intersection of 2 Arrays.cpp | LynX-gh/LeetCode_Solutions | a0d03f8df0e120907bcdde94800587fcd4f05b60 | [
"MIT"
] | null | null | null | HashTables/Intersection of 2 Arrays.cpp | LynX-gh/LeetCode_Solutions | a0d03f8df0e120907bcdde94800587fcd4f05b60 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
std::unordered_set<int> nums1_set{nums1.begin(),nums1.end()};
std::unordered_set<int> nums2_set{nums2.begin(),nums2.end()};
std::vector<int> intersect;
for (int& i: nums1_set)
if (nums2_set.count(i)!=0)
intersect.push_back(i);
return intersect;
}
}; | 31.357143 | 70 | 0.567198 | [
"vector"
] |
25264a5cd19683ed50eada350025caf2a3b8dc17 | 4,174 | cc | C++ | src/commands.cc | varqox/img2tex | 526b6f07d49d03eab40b3ad1d5e58fc91fc33a0e | [
"MIT"
] | 4 | 2019-09-06T22:40:20.000Z | 2021-10-10T10:20:26.000Z | src/commands.cc | varqox/img2tex | 526b6f07d49d03eab40b3ad1d5e58fc91fc33a0e | [
"MIT"
] | null | null | null | src/commands.cc | varqox/img2tex | 526b6f07d49d03eab40b3ad1d5e58fc91fc33a0e | [
"MIT"
] | null | null | null | #include "commands.h"
#include "symbol_database.h"
#include "untex_img.h"
#include "utilities.h"
#include <algorithm>
#include <filesystem>
#include <unistd.h>
using std::cerr;
using std::cin;
using std::cout;
using std::deque;
using std::endl;
using std::fixed;
using std::ifstream;
using std::max;
using std::min;
using std::ofstream;
using std::optional;
using std::setprecision;
using std::string;
using std::vector;
constexpr const char* GENERATED_SYMBOLS_DB_FILE = "generated_symbols.db";
constexpr const char* MANUAL_SYMBOLS_DB_FILE = "manual_symbols.db";
inline string failed_symbol_file(int group) {
return "symbol_" + std::to_string(group);
}
int compare_command(int argc, char** argv) {
if (argc != 2) {
cerr << "compare commands needs exactly two arguments\n";
return 1;
}
auto fir = teximg_to_matrix(argv[0]);
auto sec = teximg_to_matrix(argv[1]);
SymbolDatabase sdb;
if (access(GENERATED_SYMBOLS_DB_FILE, F_OK) == 0)
sdb.add_from_file(GENERATED_SYMBOLS_DB_FILE);
if (access(MANUAL_SYMBOLS_DB_FILE, F_OK) == 0)
sdb.add_from_file(MANUAL_SYMBOLS_DB_FILE);
double diff = sdb.statistics().img_diff(fir, sec);
cerr << setprecision(6) << fixed << "\033[32;1m" << diff << "\033[m"
<< endl;
return 0;
}
int gen_command(int argc, char**) {
if (argc > 0) {
cerr << "gen command takes no arguments\n";
return 1;
}
SymbolDatabase sdb;
sdb.generate_symbols();
sdb.save_to_file(GENERATED_SYMBOLS_DB_FILE);
return 0;
}
int learn_command(int argc, char** argv) {
if (argc != 1) {
cerr << "learn command needs an argument\n";
return 1;
}
const char* symbol_file = argv[0];
string symbol;
ifstream file(symbol_file);
if (not file.good())
throw std::runtime_error("Failed to open specified symbol file");
for (char c; (c = file.get()), file;)
symbol += c;
string tex;
for (char c; (c = cin.get()), cin;)
tex += c;
if (not tex.empty() and tex.back() == '\n')
tex.pop_back();
SymbolDatabase sdb;
if (access(MANUAL_SYMBOLS_DB_FILE, F_OK) == 0)
sdb.add_from_file(MANUAL_SYMBOLS_DB_FILE);
sdb.add_symbol_and_append_file(
SymbolDatabase::text_img_to_symbol(symbol), tex, MANUAL_SYMBOLS_DB_FILE);
return 0;
}
int tex_command(int argc, char** argv) {
if (argc != 1) {
cerr << "tex command needs an argument\n";
return 1;
}
const char* out_file = argv[0];
string tex;
char c;
while ((c = cin.get()), cin)
tex += c;
using namespace std::filesystem;
auto png_file = tex_to_png_file(tex, false);
if (not copy_file(png_file, out_file, copy_options::overwrite_existing))
throw std::runtime_error("Failed to copy file");
return 0;
}
int untex_command(int argc, char** argv) {
bool save_candidates = false;
if (argc == 2 and strcmp(argv[1], "--save-candidates") == 0) {
--argc;
save_candidates = true;
}
if (argc != 1) {
cerr << "untex command needs an argument\n";
return 1;
}
const char* png_file = argv[0];
if (access(GENERATED_SYMBOLS_DB_FILE, F_OK) != 0) {
cerr << "generated symbols database does not exist. Run \"gen\" "
"command first\n";
return 1;
}
SymbolDatabase symbol_db;
if (access(GENERATED_SYMBOLS_DB_FILE, F_OK) == 0)
symbol_db.add_from_file(GENERATED_SYMBOLS_DB_FILE);
if (access(MANUAL_SYMBOLS_DB_FILE, F_OK) == 0)
symbol_db.add_from_file(MANUAL_SYMBOLS_DB_FILE);
Matrix<int> img = teximg_to_matrix(png_file);
if (img.rows() * img.cols() == 0) {
cerr << "Cannot read image\n";
return 1;
}
return std::visit(
overloaded {
[](string tex) {
cout << tex << '\n';
return 0;
},
[&](UntexFailure failure) {
cerr << "\033[1;31mCannot match any of the candidates:\033[m\n";
int next_candidate_no = 0;
for (auto& candidate : failure.unmatched_symbol_candidates) {
if (save_candidates) {
auto fsym_file = failed_symbol_file(next_candidate_no++);
ofstream(fsym_file)
<< SymbolDatabase::symbol_to_text_img(candidate.img);
cerr << "Candidate saved to file " << fsym_file << ":\n";
}
binshow_matrix(candidate.img);
}
return 1;
}},
untex_img(img, symbol_db, true));
}
| 23.851429 | 77 | 0.666747 | [
"vector"
] |
2527e0809ae8eaeb2efe7ab0028642a8298f4eab | 8,677 | cpp | C++ | src/populate_grasp_dataset.cpp | lia2790/grasp-learning | e32c58eff37c1a951e914705a916452044c1d019 | [
"BSD-3-Clause"
] | 5 | 2017-11-08T12:51:50.000Z | 2021-01-26T12:17:22.000Z | src/populate_grasp_dataset.cpp | lia2790/grasp-learning | e32c58eff37c1a951e914705a916452044c1d019 | [
"BSD-3-Clause"
] | null | null | null | src/populate_grasp_dataset.cpp | lia2790/grasp-learning | e32c58eff37c1a951e914705a916452044c1d019 | [
"BSD-3-Clause"
] | 3 | 2017-05-30T14:59:28.000Z | 2019-12-11T13:34:27.000Z | /*
Software License Agreement (BSD License)
Copyright (c) 2016--, Liana Bertoni (liana.bertoni@gmail.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* 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(s) 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.
Contact GitHub API Training Shop Blog About
*/
#include <ros/ros.h>
#include <ros/package.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Geometry>
#include <kdl/chain.hpp>
#include <kdl/chainfksolver.hpp>
#include <kdl/chainfksolverpos_recursive.hpp>
#include <kdl/frames_io.hpp>
#include <boost/scoped_ptr.hpp>
#include <kdl/chainjnttojacsolver.hpp>
#include <kdl/chainfksolverpos_recursive.hpp>
#include <kdl_parser/kdl_parser.hpp>
#include <urdf/model.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <string>
#include <math.h>
#include <stdio.h>
#include <ctime>
#include <time.h>
#include "PGR_5.h"
#include "quality.h"
#include "normal_box_surface.h"
using namespace std;
using namespace Eigen;
using namespace KDL;
int main (int argc, char **argv)
{
ros::init(argc, argv, "grasp_dataset_populate"); // ROS node
ros::NodeHandle nh;
string relative_path_file_in;
string relative_path_file_out;
string file_name_in;
string file_name_out;
//int set = 0;
nh.param<std::string>("file_name_in", relative_path_file_in, "/box_db_2/box_db_quality_PGR_matlab" );
nh.param<std::string>("file_name_out", relative_path_file_out, "/box_db_2/" );
//nh.param<std::string>("set", set, 0);
///////////////////// load the data_base ////////////////////////////////////
std::string path = ros::package::getPath("grasp_learning");
file_name_in = path + relative_path_file_in;
ifstream file(file_name_in);
double q = 0;
double xb = 0;
double yb = 0;
double zb = 0;
double xp = 0;
double yp = 0;
double zp = 0;
double qx = 0;
double qy = 0;
double qz = 0;
double qw = 0;
file_name_out = path + relative_path_file_out;
ofstream file_output; //output file for matlab
std::string name = "box_db_pop";
file_output.open( file_name_out + name, ofstream::app);
ofstream file_output_1; //output file for klampt
std::string name_csv = "box_db_pop.csv";
file_output_1.open(file_name_out + name_csv, ofstream::app);
///////////////////////////////// get values from file for each line //////////////////////////////////
for(std::string line; getline( file, line, '\n' ); ) // for each line
{
std::vector<double> values_inline;
std::istringstream iss_line(line);
for(std::string value; getline(iss_line, value, ' ' ); )
values_inline.push_back(stod(value));
//if( values_inline[0] > 0 )
//{
q = values_inline[0];
xb = values_inline[1];
yb = values_inline[2];
zb = values_inline[3];
xp = values_inline[4];
yp = values_inline[5];
zp = values_inline[6];
qx = values_inline[7];
qy = values_inline[8];
qz = values_inline[9];
qw = values_inline[10];
Eigen::MatrixXd T_point = MatrixXd::Identity(4,4);
T_point(0,3) = xp;
T_point(1,3) = yp;
T_point(2,3) = zp;
KDL::Rotation Rot_point = Rotation::Quaternion(qx,qy,qz,qw);
T_point(0,0) = Rot_point.data[0];
T_point(0,1) = Rot_point.data[1];
T_point(0,2) = Rot_point.data[2];
T_point(1,0) = Rot_point.data[3];
T_point(1,1) = Rot_point.data[4];
T_point(1,2) = Rot_point.data[5];
T_point(2,0) = Rot_point.data[6];
T_point(2,1) = Rot_point.data[7];
T_point(2,2) = Rot_point.data[8];
Eigen::MatrixXd T_rot_same_face = MatrixXd::Identity(4,4);
Eigen::MatrixXd T_rot_opposite1 = MatrixXd::Identity(4,4);
Eigen::MatrixXd T_rot_opposite2 = MatrixXd::Identity(4,4);
Eigen::MatrixXd R0 = MatrixXd::Identity(3,3);
Eigen::MatrixXd R1 = MatrixXd::Identity(3,3);
Eigen::MatrixXd R2 = MatrixXd::Identity(3,3);
R1 << 1.0, 0.0, 0.0,
0.0, cos(180.0*M_PI/180.0), -sin(180.0*M_PI/180.0),
0.0, sin(180.0*M_PI/180.0), cos(180.0*M_PI/180.0);
R0 << cos(180.0*(M_PI/180.0)), sin(180.0*(M_PI/180.0)), 0.0,
-sin(180.0*(M_PI/180.0)), cos(180.0*(M_PI/180.0)), 0.0,
0.0, 0.0, 1.0;
R2 << cos(180.0*(M_PI/180.0)), 0.0, sin(180.0*(M_PI/180.0)),
0.0 , 1.0, 0.0 ,
-sin(180.0*(M_PI/180.0)), 0.0, cos(180.0*(M_PI/180.0));
T_rot_same_face.block<3,3>(0,0) = R0;
T_rot_opposite1.block<3,3>(0,0) = R1;
T_rot_opposite2.block<3,3>(0,0) = R2;
cout << T_rot_same_face << endl;
cout << T_rot_opposite1 << endl;
cout << T_rot_opposite2 << endl;
cout << T_point << endl;
Eigen::MatrixXd T0 = MatrixXd::Identity(4,4);
Eigen::MatrixXd T1 = MatrixXd::Identity(4,4);
Eigen::MatrixXd T2 = MatrixXd::Identity(4,4);
T0 = T_rot_same_face * T_point; //around z
T1 = T_rot_opposite1 * T_point; //around x
T2 = T_rot_opposite2 * T_point; //around y
cout << "-------------- T0 - Z - 1----------------"<< endl;
cout << T0 << endl;
cout << "-------------- T1 - X - 3----------------"<< endl;
cout << T1 << endl;
cout << "-------------- T2 - Y - 2----------------"<< endl;
cout << T2 << endl;
Eigen::Matrix3f TR0(3,3);
Eigen::Matrix3f TR1(3,3);
Eigen::Matrix3f TR2(3,3);
Eigen::Matrix3f TRpoint(3,3);
for(int i = 0 ; i <3 ; i++)
{ for(int j = 0 ; j <3 ; j++)
{
TR0(i,j) = T0(i,j);
TR1(i,j) = T1(i,j);
TR2(i,j) = T2(i,j);
TRpoint(i,j) = T_point(i,j);
}
}
Eigen::Quaternionf q0(TR0);
Eigen::Quaternionf q1(TR1);
Eigen::Quaternionf q2(TR2);
Eigen::Quaternionf qp(TRpoint);
file_output<<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<xp<<' '<<yp<<' '<<zp<<' '<<qx<<' '<<qy<<' '<<qz<<' '<<qw<<endl;
file_output<<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<T0(0,3)<<' '<<T0(1,3)<<' '<<T0(2,3)<<' '<<q0.x()<<' '<<q0.y()<<' '<<q0.z()<<' '<<q0.w()<<endl;
file_output<<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<T1(0,3)<<' '<<T1(1,3)<<' '<<T1(2,3)<<' '<<q1.x()<<' '<<q1.y()<<' '<<q1.z()<<' '<<q1.w()<<endl;
file_output<<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<T2(0,3)<<' '<<T2(1,3)<<' '<<T2(2,3)<<' '<<q2.x()<<' '<<q2.y()<<' '<<q2.z()<<' '<<q2.w()<<endl;
file_output_1<<xb<<','<<yb<<','<<zb<<','<<xp<<','<<yp<<','<<zp<<','<<qx<<','<<qy<<','<<qz<<','<<qw<<endl;
file_output_1<<xb<<','<<yb<<','<<zb<<','<<T0(0,3)<<','<<T0(1,3)<<','<<T0(2,3)<<','<<q0.x()<<','<<q0.y()<<','<<q0.z()<<','<<q0.w()<<endl;
file_output_1<<xb<<','<<yb<<','<<zb<<','<<T1(0,3)<<','<<T1(1,3)<<','<<T1(2,3)<<','<<q1.x()<<','<<q1.y()<<','<<q1.z()<<','<<q1.w()<<endl;
file_output_1<<xb<<','<<yb<<','<<zb<<','<<T2(0,3)<<','<<T2(1,3)<<','<<T2(2,3)<<','<<q2.x()<<','<<q2.y()<<','<<q2.z()<<','<<q2.w()<<endl;
cout <<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<xp<<' '<<yp<<' '<<zp<<' '<<qx<<' '<<qy<<' '<<qz<<' '<<qw<<endl;
cout <<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<T0(0,3)<<' '<<T0(1,3)<<' '<<T0(2,3)<<' '<<q0.x()<<' '<<q0.y()<<' '<<q0.z()<<' '<<q0.w()<<endl;
cout <<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<T1(0,3)<<' '<<T1(1,3)<<' '<<T1(2,3)<<' '<<q1.x()<<' '<<q1.y()<<' '<<q1.z()<<' '<<q1.w()<<endl;
cout <<q<<' '<<xb<<' '<<yb<<' '<<zb<<' '<<T2(0,3)<<' '<<T2(1,3)<<' '<<T2(2,3)<<' '<<q2.x()<<' '<<q2.y()<<' '<<q2.z()<<' '<<q2.w()<<endl;
}
ros::spinOnce();
return 0;
} | 31.21223 | 145 | 0.590527 | [
"geometry",
"vector",
"model"
] |
252c65602756a466c6e5ac96f3df6f1067d930ce | 95,736 | cpp | C++ | dev/floyd_speak/llvm_pipeline/floyd_llvm_runtime.cpp | PavelVozenilek/floyd | debc34005bb85000f78d08aa979bcf6a2dad4fb0 | [
"MIT"
] | null | null | null | dev/floyd_speak/llvm_pipeline/floyd_llvm_runtime.cpp | PavelVozenilek/floyd | debc34005bb85000f78d08aa979bcf6a2dad4fb0 | [
"MIT"
] | null | null | null | dev/floyd_speak/llvm_pipeline/floyd_llvm_runtime.cpp | PavelVozenilek/floyd | debc34005bb85000f78d08aa979bcf6a2dad4fb0 | [
"MIT"
] | null | null | null | //
// floyd_llvm_runtime.cpp
// floyd_speak
//
// Created by Marcus Zetterquist on 2019-04-24.
// Copyright © 2019 Marcus Zetterquist. All rights reserved.
//
#include "floyd_llvm_runtime.h"
#include "floyd_llvm_codegen.h"
#include "floyd_runtime.h"
#include "sha1_class.h"
#include "text_parser.h"
#include "bytecode_host_functions.h"
#include "file_handling.h"
#include "os_process.h"
#include "compiler_helpers.h"
#include "pass3.h"
#include "floyd_filelib.h"
#include <llvm/ADT/APInt.h>
#include <llvm/IR/Verifier.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/IR/Argument.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/InstrTypes.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Support/Casting.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IR/DataLayout.h>
#include "llvm/Bitcode/BitstreamWriter.h"
#include <iostream>
#include <fstream>
#include <thread>
#include <deque>
#include <future>
#include <condition_variable>
namespace floyd {
static void retain_value(llvm_execution_engine_t& runtime, runtime_value_t value, const typeid_t& type);
static void release_deep(llvm_execution_engine_t& runtime, runtime_value_t value, const typeid_t& type);
llvm_execution_engine_t& get_floyd_runtime(floyd_runtime_t* frp);
value_t from_runtime_value(const llvm_execution_engine_t& runtime, const runtime_value_t encoded_value, const typeid_t& type);
runtime_value_t to_runtime_value(llvm_execution_engine_t& runtime, const value_t& value);
const function_def_t& find_function_def2(const std::vector<function_def_t>& function_defs, const std::string& function_name){
auto it = std::find_if(function_defs.begin(), function_defs.end(), [&] (const function_def_t& e) { return e.def_name == function_name; } );
QUARK_ASSERT(it != function_defs.end());
QUARK_ASSERT(it->llvm_f != nullptr);
return *it;
}
void copy_elements(runtime_value_t dest[], runtime_value_t source[], uint64_t count){
for(auto i = 0 ; i < count ; i++){
dest[i] = source[i];
}
}
void* get_global_ptr(llvm_execution_engine_t& ee, const std::string& name){
QUARK_ASSERT(ee.check_invariant());
QUARK_ASSERT(name.empty() == false);
const auto addr = ee.ee->getGlobalValueAddress(name);
return (void*)addr;
}
void* get_global_function(llvm_execution_engine_t& ee, const std::string& name){
QUARK_ASSERT(ee.check_invariant());
QUARK_ASSERT(name.empty() == false);
const auto addr = ee.ee->getFunctionAddress(name);
return (void*)addr;
}
std::pair<void*, typeid_t> bind_function(llvm_execution_engine_t& ee, const std::string& name){
QUARK_ASSERT(ee.check_invariant());
QUARK_ASSERT(name.empty() == false);
const auto f = reinterpret_cast<FLOYD_RUNTIME_F*>(get_global_function(ee, name));
if(f != nullptr){
const function_def_t def = find_function_def2(ee.function_defs, std::string() + "floyd_funcdef__" + name);
const auto function_type = def.floyd_fundef._function_type;
return { f, function_type };
}
else{
return { nullptr, typeid_t::make_undefined() };
}
}
std::pair<void*, typeid_t> bind_global(llvm_execution_engine_t& ee, const std::string& name){
QUARK_ASSERT(ee.check_invariant());
QUARK_ASSERT(name.empty() == false);
const auto global_ptr = get_global_ptr(ee, name);
if(global_ptr != nullptr){
auto symbol = find_symbol(ee.global_symbols, name);
QUARK_ASSERT(symbol != nullptr);
return { global_ptr, symbol->get_type() };
}
else{
return { nullptr, typeid_t::make_undefined() };
}
}
value_t load_via_ptr(const llvm_execution_engine_t& runtime, const void* value_ptr, const typeid_t& type){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(value_ptr != nullptr);
QUARK_ASSERT(type.check_invariant());
const auto result = load_via_ptr2(value_ptr, type);
const auto result2 = from_runtime_value(runtime, result, type);
return result2;
}
value_t load_global(llvm_execution_engine_t& ee, const std::pair<void*, typeid_t>& v){
QUARK_ASSERT(v.first != nullptr);
QUARK_ASSERT(v.second.is_undefined() == false);
return load_via_ptr(ee, v.first, v.second);
}
void store_via_ptr(llvm_execution_engine_t& runtime, const typeid_t& member_type, void* value_ptr, const value_t& value){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(member_type.check_invariant());
QUARK_ASSERT(value_ptr != nullptr);
QUARK_ASSERT(value.check_invariant());
const auto value2 = to_runtime_value(runtime, value);
store_via_ptr2(value_ptr, member_type, value2);
}
llvm_bind_t bind_function2(llvm_execution_engine_t& ee, const std::string& name){
std::pair<void*, typeid_t> a = bind_function(ee, name);
return llvm_bind_t {
name,
a.first,
a.second
};
}
/*
value_t call_function(llvm_execution_engine_t& ee, llvm_bind_t& f){
//value_t call_function(llvm_execution_engine_t& ee, const std::pair<void*, typeid_t>& f);
const auto result = call_function(ee, std::pair<void*, typeid_t>(f.address, f.type));
return result;
}
*/
int64_t llvm_call_main(llvm_execution_engine_t& ee, const std::pair<void*, typeid_t>& f, const std::vector<std::string>& main_args){
QUARK_ASSERT(f.first != nullptr);
//??? Check this earlier.
if(f.second == get_main_signature_arg_impure() || f.second == get_main_signature_arg_pure()){
const auto f2 = *reinterpret_cast<FLOYD_RUNTIME_MAIN_ARGS_IMPURE*>(f.first);
//??? Slow path via value_t
std::vector<value_t> main_args2;
for(const auto& e: main_args){
main_args2.push_back(value_t::make_string(e));
}
const auto main_args3 = value_t::make_vector_value(typeid_t::make_string(), main_args2);
const auto main_args4 = to_runtime_value(ee, main_args3);
const auto main_result_int = (*f2)(reinterpret_cast<floyd_runtime_t*>(&ee), main_args4);
release_deep(ee, main_args4, typeid_t::make_vector(typeid_t::make_string()));
return main_result_int;
}
else if(f.second == get_main_signature_no_arg_impure() || f.second == get_main_signature_no_arg_pure()){
const auto f2 = *reinterpret_cast<FLOYD_RUNTIME_MAIN_NO_ARGS_IMPURE*>(f.first);
const auto main_result_int = (*f2)(reinterpret_cast<floyd_runtime_t*>(&ee));
return main_result_int;
}
else{
throw std::exception();
}
}
// TO RUNTIME_VALUE_T AND BACK
///////////////////////////////////////////////////////////////////////////////////////
runtime_value_t to_runtime_string(llvm_execution_engine_t& r, const std::string& s){
QUARK_ASSERT(r.check_invariant());
const auto count = static_cast<uint64_t>(s.size());
const auto allocation_count = size_to_allocation_blocks(s.size());
auto v = alloc_vec(r.heap, allocation_count, count);
auto result = runtime_value_t{ .vector_ptr = v };
char* char_ptr = get_vec_chars(result);
for(int i = 0 ; i < count ; i++){
char_ptr[i] = s[i];
}
return result;
}
std::string from_runtime_string(const llvm_execution_engine_t& r, runtime_value_t encoded_value){
QUARK_ASSERT(r.check_invariant());
QUARK_ASSERT(encoded_value.vector_ptr != nullptr);
const auto ptr = get_vec_chars(encoded_value);
const auto size = get_vec_string_size(encoded_value);
return std::string(ptr, ptr + size);
}
runtime_value_t to_runtime_struct(llvm_execution_engine_t& runtime, const typeid_t::struct_t& exact_type, const value_t& value){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(value.check_invariant());
const llvm::DataLayout& data_layout = runtime.ee->getDataLayout();
auto t2 = get_exact_struct_type(runtime.type_interner, value.get_type());
const llvm::StructLayout* layout = data_layout.getStructLayout(t2);
const auto struct_bytes = layout->getSizeInBytes();
auto s = alloc_struct(runtime.heap, struct_bytes);
const auto struct_base_ptr = s->get_data_ptr();
int member_index = 0;
const auto& struct_data = value.get_struct_value();
for(const auto& e: struct_data->_member_values){
const auto offset = layout->getElementOffset(member_index);
const auto member_ptr = reinterpret_cast<void*>(struct_base_ptr + offset);
store_via_ptr(runtime, e.get_type(), member_ptr, e);
member_index++;
}
return make_runtime_struct(s);
}
value_t from_runtime_struct(const llvm_execution_engine_t& runtime, const runtime_value_t encoded_value, const typeid_t& type){
QUARK_ASSERT(type.check_invariant());
const auto& struct_def = type.get_struct();
const auto struct_base_ptr = encoded_value.struct_ptr->get_data_ptr();
const llvm::DataLayout& data_layout = runtime.ee->getDataLayout();
auto t2 = get_exact_struct_type(runtime.type_interner, type);
const llvm::StructLayout* layout = data_layout.getStructLayout(t2);
std::vector<value_t> members;
int member_index = 0;
for(const auto& e: struct_def._members){
const auto offset = layout->getElementOffset(member_index);
const auto member_ptr = reinterpret_cast<const runtime_value_t*>(struct_base_ptr + offset);
const auto member_value = from_runtime_value(runtime, *member_ptr, e._type);
members.push_back(member_value);
member_index++;
}
return value_t::make_struct_value(type, members);
}
runtime_value_t to_runtime_vector(llvm_execution_engine_t& r, const value_t& value){
QUARK_ASSERT(r.check_invariant());
QUARK_ASSERT(value.check_invariant());
QUARK_ASSERT(value.get_type().is_vector());
const auto& v0 = value.get_vector_value();
const auto count = v0.size();
auto v = alloc_vec(r.heap, count, count);
auto result = runtime_value_t{ .vector_ptr = v };
const auto element_type = value.get_type().get_vector_element_type();
auto p = v->get_element_ptr();
for(int i = 0 ; i < count ; i++){
const auto& e = v0[i];
const auto a = to_runtime_value(r, e);
// retain_value(r, a, element_type);
p[i] = a;
}
return result;
}
value_t from_runtime_vector(const llvm_execution_engine_t& runtime, const runtime_value_t encoded_value, const typeid_t& type){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(type.check_invariant());
const auto element_type = type.get_vector_element_type();
const auto vec = encoded_value.vector_ptr;
std::vector<value_t> elements;
const auto count = vec->get_element_count();
auto p = vec->get_element_ptr();
for(int i = 0 ; i < count ; i++){
const auto value_encoded = p[i];
const auto value = from_runtime_value(runtime, value_encoded, element_type);
elements.push_back(value);
}
const auto val = value_t::make_vector_value(element_type, elements);
return val;
}
runtime_value_t to_runtime_dict(const llvm_execution_engine_t& runtime, const typeid_t::dict_t& exact_type, const value_t& value){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(value.check_invariant());
QUARK_ASSERT(value.get_type().is_dict());
NOT_IMPLEMENTED_YET();
return runtime_value_t{ .vector_ptr = nullptr };
}
value_t from_runtime_dict(const llvm_execution_engine_t& runtime, const runtime_value_t encoded_value, const typeid_t& type){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(encoded_value.check_invariant());
QUARK_ASSERT(type.check_invariant());
const auto value_type = type.get_dict_value_type();
const auto dict = encoded_value.dict_ptr;
std::map<std::string, value_t> values;
const auto& map2 = dict->get_map();
for(const auto& e: map2){
const auto value = from_runtime_value(runtime, e.second, value_type);
values.insert({ e.first, value} );
}
const auto val = value_t::make_dict_value(type, values);
return val;
}
runtime_value_t to_runtime_value(llvm_execution_engine_t& runtime, const value_t& value){
QUARK_ASSERT(runtime.check_invariant());
QUARK_ASSERT(value.check_invariant());
const auto type = value.get_type();
struct visitor_t {
llvm_execution_engine_t& runtime;
const value_t& value;
runtime_value_t operator()(const typeid_t::undefined_t& e) const{
UNSUPPORTED();
}
runtime_value_t operator()(const typeid_t::any_t& e) const{
UNSUPPORTED();
}
runtime_value_t operator()(const typeid_t::void_t& e) const{
UNSUPPORTED();
}
runtime_value_t operator()(const typeid_t::bool_t& e) const{
return { .bool_value = (uint8_t)(value.get_bool_value() ? 1 : 0) };
}
runtime_value_t operator()(const typeid_t::int_t& e) const{
return { .int_value = value.get_int_value() };
}
runtime_value_t operator()(const typeid_t::double_t& e) const{
return { .double_value = value.get_double_value() };
}
runtime_value_t operator()(const typeid_t::string_t& e) const{
return to_runtime_string(runtime, value.get_string_value());
}
runtime_value_t operator()(const typeid_t::json_type_t& e) const{
// auto result = new json_t(value.get_json_value());
// return runtime_value_t { .json_ptr = result };
auto result = alloc_json(runtime.heap, value.get_json_value());
return runtime_value_t { .json_ptr = result };
}
runtime_value_t operator()(const typeid_t::typeid_type_t& e) const{
const auto t0 = value.get_typeid_value();
const auto t1 = lookup_runtime_type(runtime.type_interner.interner, t0);
return make_runtime_typeid(t1);
}
runtime_value_t operator()(const typeid_t::struct_t& e) const{
return to_runtime_struct(runtime, e, value);
}
runtime_value_t operator()(const typeid_t::vector_t& e) const{
return to_runtime_vector(runtime, value);
}
runtime_value_t operator()(const typeid_t::dict_t& e) const{
return to_runtime_dict(runtime, e, value);
}
runtime_value_t operator()(const typeid_t::function_t& e) const{
NOT_IMPLEMENTED_YET();
QUARK_ASSERT(false);
}
runtime_value_t operator()(const typeid_t::unresolved_t& e) const{
UNSUPPORTED();
}
};
return std::visit(visitor_t{ runtime, value }, type._contents);
}
value_t from_runtime_value(const llvm_execution_engine_t& runtime, const runtime_value_t encoded_value, const typeid_t& type){
QUARK_ASSERT(type.check_invariant());
struct visitor_t {
const llvm_execution_engine_t& runtime;
const runtime_value_t& encoded_value;
const typeid_t& type;
value_t operator()(const typeid_t::undefined_t& e) const{
UNSUPPORTED();
}
value_t operator()(const typeid_t::any_t& e) const{
UNSUPPORTED();
}
value_t operator()(const typeid_t::void_t& e) const{
UNSUPPORTED();
}
value_t operator()(const typeid_t::bool_t& e) const{
return value_t::make_bool(encoded_value.bool_value == 0 ? false : true);
}
value_t operator()(const typeid_t::int_t& e) const{
return value_t::make_int(encoded_value.int_value);
}
value_t operator()(const typeid_t::double_t& e) const{
return value_t::make_double(encoded_value.double_value);
}
value_t operator()(const typeid_t::string_t& e) const{
return value_t::make_string(from_runtime_string(runtime, encoded_value));
}
value_t operator()(const typeid_t::json_type_t& e) const{
if(encoded_value.json_ptr == nullptr){
return value_t::make_json_value(json_t());
}
else{
const auto& j = encoded_value.json_ptr->get_json();
return value_t::make_json_value(j);
}
}
value_t operator()(const typeid_t::typeid_type_t& e) const{
const auto type1 = lookup_type(runtime.type_interner.interner, encoded_value.typeid_itype);
const auto type2 = value_t::make_typeid_value(type1);
return type2;
}
value_t operator()(const typeid_t::struct_t& e) const{
return from_runtime_struct(runtime, encoded_value, type);
}
value_t operator()(const typeid_t::vector_t& e) const{
return from_runtime_vector(runtime, encoded_value, type);
}
value_t operator()(const typeid_t::dict_t& e) const{
return from_runtime_dict(runtime, encoded_value, type);
}
value_t operator()(const typeid_t::function_t& e) const{
QUARK_ASSERT(sizeof(function_id_t) == sizeof(void*));
return value_t::make_function_value(type, reinterpret_cast<function_id_t>(encoded_value.function_ptr));
}
value_t operator()(const typeid_t::unresolved_t& e) const{
UNSUPPORTED();
}
};
return std::visit(visitor_t{ runtime, encoded_value, type }, type._contents);
}
//////////////////////////////// HELPERS FOR RUNTIME CALLBACKS
/*
@variable = global i32 21
define i32 @main() {
%1 = load i32, i32* @variable ; load the global variable
%2 = mul i32 %1, 2
store i32 %2, i32* @variable ; store instruction to write to global variable
ret i32 %2
}
*/
llvm_execution_engine_t& get_floyd_runtime(floyd_runtime_t* frp){
QUARK_ASSERT(frp != nullptr);
auto ptr = reinterpret_cast<llvm_execution_engine_t*>(frp);
QUARK_ASSERT(ptr != nullptr);
QUARK_ASSERT(ptr->debug_magic == k_debug_magic);
QUARK_ASSERT(ptr->check_invariant());
return *ptr;
}
void hook(const std::string& s, floyd_runtime_t* frp, runtime_value_t arg){
auto& r = get_floyd_runtime(frp);
throw std::runtime_error("HOST FUNCTION NOT IMPLEMENTED FOR LLVM");
}
std::string gen_to_string(llvm_execution_engine_t& runtime, runtime_value_t arg_value, runtime_type_t arg_type){
QUARK_ASSERT(runtime.check_invariant());
const auto type = lookup_type(runtime.type_interner.interner, arg_type);
const auto value = from_runtime_value(runtime, arg_value, type);
const auto a = to_compact_string2(value);
return a;
}
static void retain_value(llvm_execution_engine_t& runtime, runtime_value_t value, const typeid_t& type){
if(is_rc_value(type)){
if(type.is_string()){
inc_rc(value.vector_ptr->alloc);
}
else if(type.is_vector()){
inc_rc(value.vector_ptr->alloc);
}
else if(type.is_dict()){
inc_rc(value.dict_ptr->alloc);
}
else if(type.is_json_value()){
inc_rc(value.json_ptr->alloc);
}
else if(type.is_struct()){
inc_rc(value.struct_ptr->alloc);
}
else{
QUARK_ASSERT(false);
}
}
}
static void release_dict_deep(llvm_execution_engine_t& runtime, DICT_T* dict, const typeid_t& type);
static void release_vec_deep(llvm_execution_engine_t& runtime, VEC_T* vec, const typeid_t& type);
static void release_struct_deep(llvm_execution_engine_t& runtime, STRUCT_T* s, const typeid_t& type);
static void release_deep(llvm_execution_engine_t& runtime, runtime_value_t value, const typeid_t& type){
if(is_rc_value(type)){
if(type.is_string()){
release_vec_deep(runtime, value.vector_ptr, type);
}
else if(type.is_vector()){
release_vec_deep(runtime, value.vector_ptr, type);
}
else if(type.is_dict()){
release_dict_deep(runtime, value.dict_ptr, type);
}
else if(type.is_json_value()){
if(dec_rc(value.json_ptr->alloc) == 0){
dispose_json(*value.json_ptr);
}
}
else if(type.is_struct()){
release_struct_deep(runtime, value.struct_ptr, type);
}
else{
QUARK_ASSERT(false);
}
}
}
static void release_dict_deep(llvm_execution_engine_t& runtime, DICT_T* dict, const typeid_t& type){
QUARK_ASSERT(dict != nullptr);
QUARK_ASSERT(type.is_dict());
if(dec_rc(dict->alloc) == 0){
// Release all elements.
const auto element_type = type.get_dict_value_type();
if(is_rc_value(element_type)){
auto m = dict->get_map();
for(const auto& e: m){
release_deep(runtime, e.second, element_type);
}
}
dispose_dict(*dict);
}
}
static void release_vec_deep(llvm_execution_engine_t& runtime, VEC_T* vec, const typeid_t& type){
QUARK_ASSERT(vec != nullptr);
QUARK_ASSERT(type.is_string() || type.is_vector());
if(dec_rc(vec->alloc) == 0){
if(type.is_string()){
// String has no elements to release.
}
else if(type.is_vector()){
// Release all elements.
const auto element_type = type.get_vector_element_type();
if(is_rc_value(element_type)){
auto element_ptr = vec->get_element_ptr();
for(int i = 0 ; i < vec->get_element_count() ; i++){
const auto& element = element_ptr[i];
release_deep(runtime, element, element_type);
}
}
}
else{
QUARK_ASSERT(false);
}
dispose_vec(*vec);
}
}
static void release_struct_deep(llvm_execution_engine_t& runtime, STRUCT_T* s, const typeid_t& type){
QUARK_ASSERT(s != nullptr);
if(dec_rc(s->alloc) == 0){
const auto& struct_def = type.get_struct();
const auto struct_base_ptr = s->get_data_ptr();
const llvm::DataLayout& data_layout = runtime.ee->getDataLayout();
auto t2 = get_exact_struct_type(runtime.type_interner, type);
const llvm::StructLayout* layout = data_layout.getStructLayout(t2);
int member_index = 0;
for(const auto& e: struct_def._members){
if(is_rc_value(e._type)){
const auto offset = layout->getElementOffset(member_index);
const auto member_ptr = reinterpret_cast<const runtime_value_t*>(struct_base_ptr + offset);
release_deep(runtime, *member_ptr, e._type);
member_index++;
}
}
dispose_struct(*s);
}
}
// Host functions, automatically called by the LLVM execution engine.
// The names of these are computed from the host-id in the symbol table, not the names of the functions/symbols.
// They must use C calling convention so llvm JIT can find them.
// Make sure they are not dead-stripped out of binary!
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////// fr_retain_vec()
void fr_retain_vec(floyd_runtime_t* frp, VEC_T* vec, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
#if DEBUG
QUARK_ASSERT(vec != nullptr);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(type.is_string() || type.is_vector());
QUARK_ASSERT(is_rc_value(type));
#endif
inc_rc(vec->alloc);
}
host_func_t fr_retain_vec__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
make_generic_vec_type(interner)->getPointerTo(),
make_runtime_type_type(context)
},
false
);
return { "fr_retain_vec", function_type, reinterpret_cast<void*>(fr_retain_vec) };
}
//////////////////////////////// fr_release_vec()
void fr_release_vec(floyd_runtime_t* frp, VEC_T* vec, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(vec != nullptr);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(type.is_string() || type.is_vector());
release_vec_deep(r, vec, type);
}
host_func_t fr_release_vec__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
make_generic_vec_type(interner)->getPointerTo(),
make_runtime_type_type(context)
},
false
);
return { "fr_release_vec", function_type, reinterpret_cast<void*>(fr_release_vec) };
}
//////////////////////////////// fr_retain_dict()
void fr_retain_dict(floyd_runtime_t* frp, DICT_T* dict, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(dict != nullptr);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(is_rc_value(type));
QUARK_ASSERT(type.is_dict());
inc_rc(dict->alloc);
}
host_func_t fr_retain_dict__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
make_generic_dict_type(interner)->getPointerTo(),
make_runtime_type_type(context)
},
false
);
return { "fr_retain_dict", function_type, reinterpret_cast<void*>(fr_retain_dict) };
}
//////////////////////////////// fr_release_dict()
void fr_release_dict(floyd_runtime_t* frp, DICT_T* dict, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(dict != nullptr);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(type.is_dict());
release_dict_deep(r, dict, type);
}
host_func_t fr_release_dict__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
make_generic_dict_type(interner)->getPointerTo(),
make_runtime_type_type(context)
},
false
);
return { "fr_release_dict", function_type, reinterpret_cast<void*>(fr_release_dict) };
}
//////////////////////////////// fr_retain_json()
void fr_retain_json(floyd_runtime_t* frp, JSON_T* json, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(is_rc_value(type));
// NOTICE: Floyd runtime() init will destruct globals, including json_value::null.
if(json == nullptr){
}
else{
QUARK_ASSERT(type.is_json_value());
inc_rc(json->alloc);
}
}
host_func_t fr_retain_json__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
get_exact_llvm_type(interner, typeid_t::make_json_value()),
make_runtime_type_type(context)
},
false
);
return { "fr_retain_json", function_type, reinterpret_cast<void*>(fr_retain_json) };
}
//////////////////////////////// fr_release_json()
void fr_release_json(floyd_runtime_t* frp, JSON_T* json, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(type.is_json_value());
// NOTICE: Floyd runtime() init will destruct globals, including json_value::null.
if(json == nullptr){
}
else{
QUARK_ASSERT(json != nullptr);
if(dec_rc(json->alloc) == 0){
dispose_json(*json);
}
}
}
host_func_t fr_release_json__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
get_exact_llvm_type(interner, typeid_t::make_json_value()),
make_runtime_type_type(context)
},
false
);
return { "fr_release_json", function_type, reinterpret_cast<void*>(fr_release_json) };
}
//////////////////////////////// fr_retain_struct()
void fr_retain_struct(floyd_runtime_t* frp, STRUCT_T* v, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(is_rc_value(type));
QUARK_ASSERT(type.is_struct());
inc_rc(v->alloc);
}
host_func_t fr_retain_struct__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
get_generic_struct_type(interner)->getPointerTo(),
make_runtime_type_type(context)
},
false
);
return { "fr_retain_struct", function_type, reinterpret_cast<void*>(fr_retain_struct) };
}
//////////////////////////////// fr_release_struct()
void fr_release_struct(floyd_runtime_t* frp, STRUCT_T* v, runtime_type_t type0){
auto& r = get_floyd_runtime(frp);
const auto type = lookup_type(r.type_interner.interner, type0);
QUARK_ASSERT(type.is_struct());
QUARK_ASSERT(v != nullptr);
release_struct_deep(r, v, type);
}
host_func_t fr_release_struct__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
get_generic_struct_type(interner)->getPointerTo(),
make_runtime_type_type(context)
},
false
);
return { "fr_release_struct", function_type, reinterpret_cast<void*>(fr_release_struct) };
}
//////////////////////////////// allocate_vector()
// Creates a new VEC_T with element_count. All elements are blank. Caller owns the result.
VEC_T* floyd_runtime__allocate_vector(floyd_runtime_t* frp, uint64_t element_count){
auto& r = get_floyd_runtime(frp);
auto v = alloc_vec(r.heap, element_count, element_count);
return v;
}
host_func_t floyd_runtime__allocate_vector__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
make_generic_vec_type(interner)->getPointerTo(),
{
make_frp_type(interner),
llvm::Type::getInt64Ty(context)
},
false
);
return { "floyd_runtime__allocate_vector", function_type, reinterpret_cast<void*>(floyd_runtime__allocate_vector) };
}
//////////////////////////////// allocate_string_from_strptr()
// Creates a new VEC_T with element_count. All elements are blank. Caller owns the result.
VEC_T* fr_alloc_kstr(floyd_runtime_t* frp, const char* s, uint64_t size){
auto& r = get_floyd_runtime(frp);
const auto a = to_runtime_string(r, std::string(s, s + size));
return a.vector_ptr;
}
host_func_t fr_alloc_kstr__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
make_generic_vec_type(interner)->getPointerTo(),
{
make_frp_type(interner),
llvm::Type::getInt8PtrTy(context),
llvm::Type::getInt64Ty(context)
},
false
);
return { "fr_alloc_kstr", function_type, reinterpret_cast<void*>(fr_alloc_kstr) };
}
//////////////////////////////// floyd_runtime__concatunate_vectors()
VEC_T* floyd_runtime__concatunate_vectors(floyd_runtime_t* frp, runtime_type_t type, VEC_T* lhs, VEC_T* rhs){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(lhs != nullptr);
QUARK_ASSERT(lhs->check_invariant());
QUARK_ASSERT(rhs != nullptr);
QUARK_ASSERT(rhs->check_invariant());
const auto type0 = lookup_type(r.type_interner.interner, type);
if(type0.is_string()){
const auto result = from_runtime_string(r, runtime_value_t{ .vector_ptr = lhs }) + from_runtime_string(r, runtime_value_t{ .vector_ptr = rhs } );
return to_runtime_string(r, result).vector_ptr;
}
else{
auto count2 = lhs->get_element_count() + rhs->get_element_count();
auto result = alloc_vec(r.heap, count2, count2);
const auto element_type = type0.get_vector_element_type();
auto dest_ptr = result->get_element_ptr();
auto dest_ptr2 = dest_ptr + lhs->get_element_count();
auto lhs_ptr = lhs->get_element_ptr();
auto rhs_ptr = rhs->get_element_ptr();
if(is_rc_value(element_type)){
for(int i = 0 ; i < lhs->get_element_count() ; i++){
retain_value(r, lhs_ptr[i], element_type);
dest_ptr[i] = lhs_ptr[i];
}
for(int i = 0 ; i < rhs->get_element_count() ; i++){
retain_value(r, rhs_ptr[i], element_type);
dest_ptr2[i] = rhs_ptr[i];
}
}
else{
for(int i = 0 ; i < lhs->get_element_count() ; i++){
dest_ptr[i] = lhs_ptr[i];
}
for(int i = 0 ; i < rhs->get_element_count() ; i++){
dest_ptr2[i] = rhs_ptr[i];
}
}
return result;
}
}
host_func_t floyd_runtime__concatunate_vectors__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
make_generic_vec_type(interner)->getPointerTo(),
{
make_frp_type(interner),
make_runtime_type_type(context),
make_generic_vec_type(interner)->getPointerTo(),
make_generic_vec_type(interner)->getPointerTo()
},
false
);
return { "floyd_runtime__concatunate_vectors", function_type, reinterpret_cast<void*>(floyd_runtime__concatunate_vectors) };
}
//////////////////////////////// allocate_dict()
void* floyd_runtime__allocate_dict(floyd_runtime_t* frp){
auto& r = get_floyd_runtime(frp);
auto v = alloc_dict(r.heap);
return v;
}
host_func_t floyd_runtime__allocate_dict__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
make_generic_dict_type(interner)->getPointerTo(),
{
make_frp_type(interner)
},
false
);
return { "floyd_runtime__allocate_dict", function_type, reinterpret_cast<void*>(floyd_runtime__allocate_dict) };
}
//////////////////////////////// store_dict()
void floyd_runtime__store_dict_mutable(floyd_runtime_t* frp, DICT_T* dict, runtime_value_t key, runtime_value_t element_value, runtime_type_t element_type){
auto& r = get_floyd_runtime(frp);
const auto key_string = from_runtime_string(r, key);
dict->get_map_mut().insert_or_assign(key_string, element_value);
}
host_func_t floyd_runtime__store_dict_mutable__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context),
{
make_frp_type(interner),
make_generic_dict_type(interner)->getPointerTo(),
get_exact_llvm_type(interner, typeid_t::make_string()),
make_runtime_value_type(context),
make_runtime_type_type(context)
},
false
);
return { "floyd_runtime__store_dict_mutable", function_type, reinterpret_cast<void*>(floyd_runtime__store_dict_mutable) };
}
//////////////////////////////// lookup_dict()
runtime_value_t floyd_runtime__lookup_dict(floyd_runtime_t* frp, DICT_T* dict, runtime_value_t s){
auto& r = get_floyd_runtime(frp);
const auto& m = dict->get_map();
const auto key_string = from_runtime_string(r, s);
const auto it = m.find(key_string);
if(it == m.end()){
throw std::exception();
}
else{
return it->second;
}
}
host_func_t floyd_runtime__lookup_dict__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
make_runtime_value_type(context),
{
make_frp_type(interner),
make_generic_dict_type(interner)->getPointerTo(),
get_exact_llvm_type(interner, typeid_t::make_string())
},
false
);
return { "floyd_runtime__lookup_dict", function_type, reinterpret_cast<void*>(floyd_runtime__lookup_dict) };
}
//////////////////////////////// allocate_json()
//??? Make named types for all function-argument / return types, like: typedef int16_t* native_json_ptr
JSON_T* floyd_runtime__allocate_json(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto value = from_runtime_value(r, arg0_value, type0);
const auto a = value_to_ast_json(value, json_tags::k_plain);
auto result = alloc_json(r.heap, a);
return result;
}
host_func_t floyd_runtime__allocate_json__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
get_exact_llvm_type(interner, typeid_t::make_json_value()),
{
make_frp_type(interner),
make_runtime_value_type(context),
make_runtime_type_type(context)
},
false
);
return { "floyd_runtime__allocate_json", function_type, reinterpret_cast<void*>(floyd_runtime__allocate_json) };
}
//////////////////////////////// lookup_json()
JSON_T* floyd_runtime__lookup_json(floyd_runtime_t* frp, JSON_T* json_ptr, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto& json = json_ptr->get_json();
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto value = from_runtime_value(r, arg0_value, type0);
if(json.is_object()){
if(type0.is_string() == false){
quark::throw_runtime_error("Attempting to lookup a json-object with a key that is not a string.");
}
const auto result = json.get_object_element(value.get_string_value());
return alloc_json(r.heap, result);
}
else if(json.is_array()){
if(type0.is_int() == false){
quark::throw_runtime_error("Attempting to lookup a json-object with a key that is not a number.");
}
const auto result = json.get_array_n(value.get_int_value());
auto result2 = alloc_json(r.heap, result);
return result2;
}
else{
quark::throw_runtime_error("Attempting to lookup a json value -- lookup requires json-array or json-object.");
}
}
host_func_t floyd_runtime__lookup_json__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
get_exact_llvm_type(interner, typeid_t::make_json_value()),
{
make_frp_type(interner),
get_exact_llvm_type(interner, typeid_t::make_json_value()),
make_runtime_value_type(context),
make_runtime_type_type(context)
},
false
);
return { "floyd_runtime__lookup_json", function_type, reinterpret_cast<void*>(floyd_runtime__lookup_json) };
}
//////////////////////////////// json_to_string()
runtime_value_t floyd_runtime__json_to_string(floyd_runtime_t* frp, JSON_T* json_ptr){
auto& r = get_floyd_runtime(frp);
const auto& json = json_ptr->get_json();
if(json.is_string()){
return to_runtime_string(r, json.get_string());
}
else{
quark::throw_runtime_error("Attempting to assign a non-string JSON to a string.");
}
}
host_func_t floyd_runtime__json_to_string__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
get_exact_llvm_type(interner, typeid_t::make_string()),
{
make_frp_type(interner),
get_exact_llvm_type(interner, typeid_t::make_json_value())
},
false
);
return { "floyd_runtime__json_to_string", function_type, reinterpret_cast<void*>(floyd_runtime__json_to_string) };
}
//////////////////////////////// compare_values()
int8_t floyd_runtime__compare_values(floyd_runtime_t* frp, int64_t op, const runtime_type_t type, runtime_value_t lhs, runtime_value_t rhs){
auto& r = get_floyd_runtime(frp);
const auto value_type = lookup_type(r.type_interner.interner, type);
const auto left_value = from_runtime_value(r, lhs, value_type);
const auto right_value = from_runtime_value(r, rhs, value_type);
const int result = value_t::compare_value_true_deep(left_value, right_value);
// int result = runtime_compare_value_true_deep((const uint64_t)lhs, (const uint64_t)rhs, vector_type);
const auto op2 = static_cast<expression_type>(op);
if(op2 == expression_type::k_comparison_smaller_or_equal__2){
return result <= 0 ? 1 : 0;
}
else if(op2 == expression_type::k_comparison_smaller__2){
return result < 0 ? 1 : 0;
}
else if(op2 == expression_type::k_comparison_larger_or_equal__2){
return result >= 0 ? 1 : 0;
}
else if(op2 == expression_type::k_comparison_larger__2){
return result > 0 ? 1 : 0;
}
else if(op2 == expression_type::k_logical_equal__2){
return result == 0 ? 1 : 0;
}
else if(op2 == expression_type::k_logical_nonequal__2){
return result != 0 ? 1 : 0;
}
else{
QUARK_ASSERT(false);
throw std::exception();
}
}
host_func_t floyd_runtime__compare_values__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
llvm::Type::getInt1Ty(context),
{
make_frp_type(interner),
llvm::Type::getInt64Ty(context),
make_runtime_type_type(context),
make_runtime_value_type(context),
make_runtime_value_type(context)
},
false
);
return { "floyd_runtime__compare_values", function_type, reinterpret_cast<void*>(floyd_runtime__compare_values) };
}
//////////////////////////////// allocate_vector()
// Creates a new VEC_T with element_count. All elements are blank. Caller owns the result.
STRUCT_T* floyd_runtime__allocate_struct(floyd_runtime_t* frp, uint64_t size){
auto& r = get_floyd_runtime(frp);
auto v = alloc_struct(r.heap, size);
return v;
}
host_func_t floyd_runtime__allocate_struct__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
get_generic_struct_type(interner)->getPointerTo(),
{
make_frp_type(interner),
llvm::Type::getInt64Ty(context)
},
false
);
return { "floyd_runtime__allocate_struct", function_type, reinterpret_cast<void*>(floyd_runtime__allocate_vector) };
}
//??? optimize for speed. Most things can be precalculated.
//??? Generate an add_ref-function for each struct type.
const WIDE_RETURN_T fr_update_struct_member(floyd_runtime_t* frp, STRUCT_T* s, runtime_type_t struct_type, int64_t member_index, runtime_value_t new_value, runtime_type_t new_value_type){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(s != nullptr);
QUARK_ASSERT(member_index != -1);
const auto type0 = lookup_type(r.type_interner.interner, struct_type);
const auto new_value_type0 = lookup_type(r.type_interner.interner, new_value_type);
QUARK_ASSERT(type0.is_struct());
const auto source_struct_ptr = s;
const auto& struct_def = type0.get_struct();
const auto member_value = from_runtime_value(r, new_value, new_value_type0);
// Make copy of struct, overwrite member in copy.
auto& struct_type_llvm = *get_exact_struct_type(r.type_interner, type0);
const llvm::DataLayout& data_layout = r.ee->getDataLayout();
const llvm::StructLayout* layout = data_layout.getStructLayout(&struct_type_llvm);
const auto struct_bytes = layout->getSizeInBytes();
//??? Touches memory twice.
auto struct_ptr = alloc_struct(r.heap, struct_bytes);
auto struct_base_ptr = struct_ptr->get_data_ptr();
std::memcpy(struct_base_ptr, source_struct_ptr->get_data_ptr(), struct_bytes);
const auto member_offset = layout->getElementOffset(member_index);
const auto member_ptr = reinterpret_cast<void*>(struct_base_ptr + member_offset);
store_via_ptr(r, new_value_type0, member_ptr, member_value);
// Retain every member of new struct.
{
int member_index = 0;
for(const auto& e: struct_def._members){
if(is_rc_value(e._type)){
const auto offset = layout->getElementOffset(member_index);
const auto member_ptr = reinterpret_cast<const runtime_value_t*>(struct_base_ptr + offset);
retain_value(r, *member_ptr, e._type);
member_index++;
}
}
}
return make_wide_return_structptr(struct_ptr);
}
host_func_t fr_update_struct_member__make(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
llvm::FunctionType* function_type = llvm::FunctionType::get(
get_generic_struct_type(interner)->getPointerTo(),
{
make_frp_type(interner),
get_generic_struct_type(interner)->getPointerTo(),
make_runtime_type_type(context),
llvm::Type::getInt64Ty(context),
make_runtime_value_type(context),
make_runtime_type_type(context)
},
false
);
return { "fr_update_struct_member", function_type, reinterpret_cast<void*>(fr_update_struct_member) };
}
std::vector<host_func_t> get_runtime_functions(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
std::vector<host_func_t> result = {
fr_retain_vec__make(context, interner),
fr_release_vec__make(context, interner),
fr_retain_dict__make(context, interner),
fr_release_dict__make(context, interner),
fr_retain_json__make(context, interner),
fr_release_json__make(context, interner),
fr_retain_struct__make(context, interner),
fr_release_struct__make(context, interner),
floyd_runtime__allocate_vector__make(context, interner),
fr_alloc_kstr__make(context, interner),
floyd_runtime__concatunate_vectors__make(context, interner),
floyd_runtime__allocate_dict__make(context, interner),
floyd_runtime__store_dict_mutable__make(context, interner),
floyd_runtime__lookup_dict__make(context, interner),
floyd_runtime__allocate_json__make(context, interner),
floyd_runtime__lookup_json__make(context, interner),
floyd_runtime__json_to_string__make(context, interner),
floyd_runtime__compare_values__make(context, interner),
floyd_runtime__allocate_struct__make(context, interner),
fr_update_struct_member__make(context, interner)
};
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HOST FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct native_binary_t {
VEC_T* ascii40;
};
struct native_sha1_t {
VEC_T* ascii40;
};
void floyd_funcdef__assert(floyd_runtime_t* frp, runtime_value_t arg){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(arg.bool_value == 0 || arg.bool_value == 1);
bool ok = arg.bool_value == 0 ? false : true;
if(!ok){
r._print_output.push_back("Assertion failed.");
quark::throw_runtime_error("Floyd assertion failed.");
}
}
WIDE_RETURN_T floyd_host_function__erase(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
QUARK_ASSERT(type0.is_dict());
QUARK_ASSERT(type1.is_string());
const auto& dict = unpack_dict_arg(r.type_interner.interner, arg0_value, arg0_type);
const auto value_type = type0.get_dict_value_type();
// Deep copy dict.
auto dict2 = alloc_dict(r.heap);
auto& m = dict2->get_map_mut();
m = dict->get_map();
const auto key_string = from_runtime_string(r, arg1_value);
m.erase(key_string);
if(is_rc_value(value_type)){
for(auto& e: m){
retain_value(r, e.second, value_type);
}
}
return make_wide_return_dict(dict2);
}
uint32_t floyd_funcdef__exists(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
QUARK_ASSERT(type0.is_dict());
const auto& dict = unpack_dict_arg(r.type_interner.interner, arg0_value, arg0_type);
const auto key_string = from_runtime_string(r, arg1_value);
const auto& m = dict->get_map();
const auto it = m.find(key_string);
return it != m.end() ? 1 : 0;
}
typedef runtime_value_t (*FILTER_F)(floyd_runtime_t* frp, runtime_value_t element_value);
// [E] filter([E], bool f(E e))
WIDE_RETURN_T floyd_funcdef__filter(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
QUARK_ASSERT(type0.is_vector());
QUARK_ASSERT(type1.is_function());
QUARK_ASSERT(type1.get_function_args().size() == 1);
const auto& vec = *arg0_value.vector_ptr;
const auto f = reinterpret_cast<FILTER_F>(arg1_value.function_ptr);
auto count = vec.get_element_count();
const auto e_element_type = type0.get_vector_element_type();
std::vector<runtime_value_t> acc;
for(int i = 0 ; i < count ; i++){
const auto element_value = vec.get_element_ptr()[i];
const auto keep = (*f)(frp, element_value);
if(keep.bool_value != 0){
acc.push_back(element_value);
if(is_rc_value(e_element_type)){
retain_value(r, element_value, e_element_type);
}
}
else{
}
}
const auto count2 = (int32_t)acc.size();
auto result_vec = alloc_vec(r.heap, count2, count2);
if(count2 > 0){
// Count > 0 required to get address to first element in acc.
copy_elements(result_vec->get_element_ptr(), &acc[0], count2);
}
return make_wide_return_vec(result_vec);
}
int64_t floyd_funcdef__find(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, const runtime_value_t arg1_value, runtime_type_t arg1_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
if(type0.is_string()){
QUARK_ASSERT(type1.is_string());
const auto str = from_runtime_string(r, arg0_value);
const auto wanted2 = from_runtime_string(r, arg1_value);
const auto pos = str.find(wanted2);
const auto result = pos == std::string::npos ? -1 : static_cast<int64_t>(pos);
return result;
}
else if(type0.is_vector()){
QUARK_ASSERT(type1 == type0.get_vector_element_type());
const auto vec = unpack_vec_arg(r.type_interner.interner, arg0_value, arg0_type);
// auto it = std::find_if(function_defs.begin(), function_defs.end(), [&] (const function_def_t& e) { return e.def_name == function_name; } );
const auto it = std::find_if(
vec->get_element_ptr(),
vec->get_element_ptr() + vec->get_element_count(),
[&] (const runtime_value_t& e) {
return floyd_runtime__compare_values(frp, static_cast<int64_t>(expression_type::k_logical_equal__2), arg1_type, e, arg1_value) == 1;
}
);
if(it == vec->get_element_ptr() + vec->get_element_count()){
return -1;
}
else{
const auto pos = it - vec->get_element_ptr();
return pos;
}
}
else{
// No other types allowed.
UNSUPPORTED();
}
}
int64_t floyd_host_function__get_json_type(floyd_runtime_t* frp, JSON_T* json_ptr){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(json_ptr != nullptr);
const auto& json = json_ptr->get_json();
const auto result = get_json_type(json);
return result;
}
runtime_value_t floyd_funcdef__jsonvalue_to_script(floyd_runtime_t* frp, JSON_T* json_ptr){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(json_ptr != nullptr);
const auto& json = json_ptr->get_json();
const std::string s = json_to_compact_string(json);
return to_runtime_string(r, s);
}
runtime_value_t floyd_funcdef__jsonvalue_to_value(floyd_runtime_t* frp, JSON_T* json_ptr, runtime_type_t target_type){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(json_ptr != nullptr);
const auto& json_value = json_ptr->get_json();
const auto target_type2 = lookup_type(r.type_interner.interner, target_type);
const auto result = unflatten_json_to_specific_type(json_value, target_type2);
const auto result2 = to_runtime_value(r, result);
return result2;
}
//??? No need to call lookup_type() to check which basic type it is!
typedef WIDE_RETURN_T (*MAP_F)(floyd_runtime_t* frp, runtime_value_t arg0_value);
WIDE_RETURN_T floyd_funcdef__map(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
QUARK_ASSERT(type0.is_vector());
QUARK_ASSERT(type1.is_function());
const auto element_type = type0.get_vector_element_type();
const auto f_arg_types = type1.get_function_args();
const auto r_type = type1.get_function_return();
QUARK_ASSERT(f_arg_types.size() == 1);
QUARK_ASSERT(f_arg_types[0] == element_type);
const auto input_element_type = f_arg_types[0];
const auto output_element_type = r_type;
const auto f = reinterpret_cast<MAP_F>(arg1_value.function_ptr);
const auto count = arg0_value.vector_ptr->get_element_count();
auto result_vec = alloc_vec(r.heap, count, count);
for(int i = 0 ; i < count ; i++){
const auto wide_result1 = (*f)(frp, arg0_value.vector_ptr->get_element_ptr()[i]);
result_vec->get_element_ptr()[i] = wide_result1.a;
}
return make_wide_return_vec(result_vec);
}
//??? Can mutate the acc string internally.
typedef runtime_value_t (*MAP_STRING_F)(floyd_runtime_t* frp, runtime_value_t s);
runtime_value_t floyd_funcdef__map_string(floyd_runtime_t* frp, runtime_value_t input_string0, runtime_value_t func){
auto& r = get_floyd_runtime(frp);
const auto f = reinterpret_cast<MAP_STRING_F>(func.function_ptr);
const auto input_string = from_runtime_string(r, input_string0);
auto count = input_string.size();
std::string acc;
for(int i = 0 ; i < count ; i++){
const std::string element = { input_string[i] };
const auto x = to_runtime_string(r, element);
const auto temp = (*f)(frp, x);
release_vec_deep(r, x.vector_ptr, typeid_t::make_string());
const auto temp2 = from_runtime_string(r, temp);
acc.insert(acc.end(), temp2.begin(), temp2.end());
release_vec_deep(r, temp.vector_ptr, typeid_t::make_string());
}
return to_runtime_string(r, acc);
}
void floyd_funcdef__print(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto s = gen_to_string(r, arg0_value, arg0_type);
printf("%s\n", s.c_str());
r._print_output.push_back(s);
}
WIDE_RETURN_T floyd_funcdef__push_back(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
if(type0.is_string()){
auto value = from_runtime_string(r, arg0_value);
QUARK_ASSERT(type1.is_int());
value.push_back((char)arg1_value.int_value);
const auto result2 = to_runtime_string(r, value);
return make_wide_return_1x64(result2);
}
else if(type0.is_vector()){
const auto vs = unpack_vec_arg(r.type_interner.interner, arg0_value, arg0_type);
QUARK_ASSERT(type1 == type0.get_vector_element_type());
const auto element = arg1_value;
const auto element_type = type1;
auto v2 = floyd_runtime__allocate_vector(frp, vs->get_element_count() + 1);
auto dest_ptr = v2->get_element_ptr();
auto source_ptr = vs->get_element_ptr();
if(is_rc_value(element_type)){
retain_value(r, element, element_type);
for(int i = 0 ; i < vs->get_element_count() ; i++){
retain_value(r, source_ptr[i], element_type);
dest_ptr[i] = source_ptr[i];
}
dest_ptr[vs->get_element_count()] = element;
}
else{
for(int i = 0 ; i < vs->get_element_count() ; i++){
dest_ptr[i] = source_ptr[i];
}
dest_ptr[vs->get_element_count()] = element;
}
return make_wide_return_vec(v2);
}
else{
// No other types allowed.
UNSUPPORTED();
}
}
void floyd_host_function_1022(floyd_runtime_t* frp, runtime_value_t arg){
hook(__FUNCTION__, frp, arg);
}
typedef runtime_value_t (*REDUCE_F)(floyd_runtime_t* frp, runtime_value_t acc_value, runtime_value_t element_value);
// R map([E] elements, R init, R f(R acc, E e))
WIDE_RETURN_T floyd_funcdef__reduce(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type, runtime_value_t arg2_value, runtime_type_t arg2_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
const auto type2 = lookup_type(r.type_interner.interner, arg2_type);
QUARK_ASSERT(type0.is_vector());
QUARK_ASSERT(type2.is_function());
QUARK_ASSERT(type2.get_function_args().size () == 2);
const auto& vec = *arg0_value.vector_ptr;
const auto& init = arg1_value;
const auto f = reinterpret_cast<REDUCE_F>(arg2_value.function_ptr);
auto count = vec.get_element_count();
runtime_value_t acc = init;
retain_value(r, acc, type1);
for(int i = 0 ; i < count ; i++){
const auto element_value = vec.get_element_ptr()[i];
const auto acc2 = (*f)(frp, acc, element_value);
release_deep(r, acc, type1);
acc = acc2;
}
return make_wide_return_2x64(acc, {} );
}
std::string floyd_funcdef__replace__string(llvm_execution_engine_t& frp, const std::string& s, std::size_t start, std::size_t end, const std::string& replace){
auto s_len = s.size();
auto replace_len = replace.size();
auto end2 = std::min(end, s_len);
auto start2 = std::min(start, end2);
const std::size_t len2 = start2 + replace_len + (s_len - end2);
auto s2 = reinterpret_cast<char*>(std::malloc(len2 + 1));
std::memcpy(&s2[0], &s[0], start2);
std::memcpy(&s2[start2], &replace[0], replace_len);
std::memcpy(&s2[start2 + replace_len], &s[end2], s_len - end2);
const std::string result(s2, &s2[start2 + replace_len + (s_len - end2)]);
return result;
}
const WIDE_RETURN_T floyd_funcdef__replace(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, uint64_t start, uint64_t end, runtime_value_t arg3_value, runtime_type_t arg3_type){
auto& r = get_floyd_runtime(frp);
if(start < 0 || end < 0){
quark::throw_runtime_error("replace() requires start and end to be non-negative.");
}
if(start > end){
quark::throw_runtime_error("replace() requires start <= end.");
}
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type3 = lookup_type(r.type_interner.interner, arg3_type);
QUARK_ASSERT(type3 == type0);
if(type0.is_string()){
const auto s = from_runtime_string(r, arg0_value);
const auto replace = from_runtime_string(r, arg3_value);
auto ret = floyd_funcdef__replace__string(r, s, (std::size_t)start, (std::size_t)end, replace);
const auto result2 = to_runtime_string(r, ret);
return make_wide_return_1x64(result2);
}
else if(type0.is_vector()){
const auto element_type = type0.get_vector_element_type();
const auto vec = unpack_vec_arg(r.type_interner.interner, arg0_value, arg0_type);
const auto replace_vec = unpack_vec_arg(r.type_interner.interner, arg3_value, arg3_type);
auto end2 = std::min(end, vec->get_element_count());
auto start2 = std::min(start, end2);
const auto section1_len = start2;
const auto section2_len = replace_vec->get_element_count();
const auto section3_len = vec->get_element_count() - end2;
const auto len2 = section1_len + section2_len + section3_len;
auto vec2 = alloc_vec(r.heap, len2, len2);
copy_elements(&vec2->get_element_ptr()[0], &vec->get_element_ptr()[0], section1_len);
copy_elements(&vec2->get_element_ptr()[section1_len], &replace_vec->get_element_ptr()[0], section2_len);
copy_elements(&vec2->get_element_ptr()[section1_len + section2_len], &vec->get_element_ptr()[end2], section3_len);
if(is_rc_value(element_type)){
for(int i = 0 ; i < len2 ; i++){
retain_value(r, vec2->get_element_ptr()[i], element_type);
}
}
return make_wide_return_vec(vec2);
}
else{
// No other types allowed.
UNSUPPORTED();
}
}
JSON_T* floyd_funcdef__script_to_jsonvalue(floyd_runtime_t* frp, runtime_value_t string_s0){
auto& r = get_floyd_runtime(frp);
const auto string_s = from_runtime_string(r, string_s0);
std::pair<json_t, seq_t> result0 = parse_json(seq_t(string_s));
auto result = alloc_json(r.heap, result0.first);
return result;
}
void floyd_funcdef__send(floyd_runtime_t* frp, runtime_value_t process_id0, const JSON_T* message_json_ptr){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(message_json_ptr != nullptr);
const auto& process_id = from_runtime_string(r, process_id0);
const auto& message_json = message_json_ptr->get_json();
QUARK_TRACE_SS("send(\"" << process_id << "\"," << json_to_pretty_string(message_json) <<")");
r._handler->on_send(process_id, message_json);
}
//??? all all host functions are now checked at codegen -- remove runtime test here!
int64_t floyd_funcdef__size(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
if(type0.is_string()){
return get_vec_string_size(arg0_value);
}
else if(type0.is_json_value()){
const auto& json_value = arg0_value.json_ptr->get_json();
if(json_value.is_object()){
return json_value.get_object_size();
}
else if(json_value.is_array()){
return json_value.get_array_size();
}
else if(json_value.is_string()){
return json_value.get_string().size();
}
else{
quark::throw_runtime_error("Calling size() on unsupported type of value.");
}
}
else if(type0.is_vector()){
const auto vs = unpack_vec_arg(r.type_interner.interner, arg0_value, arg0_type);
return vs->get_element_count();
}
else if(type0.is_dict()){
DICT_T* dict = unpack_dict_arg(r.type_interner.interner, arg0_value, arg0_type);
return dict->size();
}
else{
// No other types allowed.
UNSUPPORTED();
}
}
const WIDE_RETURN_T floyd_funcdef__subset(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, uint64_t start, uint64_t end){
auto& r = get_floyd_runtime(frp);
if(start < 0 || end < 0){
quark::throw_runtime_error("subset() requires start and end to be non-negative.");
}
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
if(type0.is_string()){
const auto value = from_runtime_string(r, arg0_value);
const auto len = get_vec_string_size(arg0_value);
const auto end2 = std::min(end, len);
const auto start2 = std::min(start, end2);
const auto len2 = end2 - start2;
const auto s = std::string(&value[start2], &value[start2 + len2]);
const auto result = to_runtime_string(r, s);
return make_wide_return_1x64(result);
}
else if(type0.is_vector()){
const auto element_type = type0.get_vector_element_type();
const auto vec = unpack_vec_arg(r.type_interner.interner, arg0_value, arg0_type);
const auto end2 = std::min(end, vec->get_element_count());
const auto start2 = std::min(start, end2);
const auto len2 = end2 - start2;
if(len2 >= INT32_MAX){
throw std::exception();
}
VEC_T* vec2 = alloc_vec(r.heap, len2, len2);
if(is_rc_value(element_type)){
for(int i = 0 ; i < len2 ; i++){
vec2->get_element_ptr()[i] = vec->get_element_ptr()[start2 + i];
retain_value(r, vec2->get_element_ptr()[i], element_type);
}
}
else{
for(int i = 0 ; i < len2 ; i++){
vec2->get_element_ptr()[i] = vec->get_element_ptr()[start2 + i];
}
}
return make_wide_return_vec(vec2);
}
else{
// No other types allowed.
UNSUPPORTED();
}
}
typedef WIDE_RETURN_T (*SUPERMAP_F)(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_value_t arg1_value);
WIDE_RETURN_T floyd_funcdef__supermap(
floyd_runtime_t* frp,
runtime_value_t arg0_value,
runtime_type_t arg0_type,
runtime_value_t arg1_value,
runtime_type_t arg1_type,
runtime_value_t arg2_value,
runtime_type_t arg2_type
){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
const auto type2 = lookup_type(r.type_interner.interner, arg2_type);
// Check topology.
QUARK_ASSERT(type0.is_vector());
QUARK_ASSERT(type1 == typeid_t::make_vector(typeid_t::make_int()));
QUARK_ASSERT(type2.is_function());
QUARK_ASSERT(type2.get_function_args().size () == 2);
const auto& elements = arg0_value;
const auto& e_type = type0.get_vector_element_type();
const auto& parents = arg1_value;
const auto& f = arg2_value;
const auto& r_type = type2.get_function_return();
QUARK_ASSERT(e_type == type2.get_function_args()[0] && r_type == type2.get_function_args()[1].get_vector_element_type());
const auto f2 = reinterpret_cast<SUPERMAP_F>(f.function_ptr);
const auto elements2 = elements.vector_ptr;
const auto parents2 = parents.vector_ptr;
if(elements2->get_element_count() != parents2->get_element_count()) {
quark::throw_runtime_error("supermap() requires elements and parents be the same count.");
}
auto elements_todo = elements2->get_element_count();
std::vector<int> rcs(elements2->get_element_count(), 0);
std::vector<runtime_value_t> complete(elements2->get_element_count(), runtime_value_t());
for(int i = 0 ; i < parents2->get_element_count() ; i++){
const auto& e = parents2->get_element_ptr()[i];
const auto parent_index = e.int_value;
const auto count = static_cast<int64_t>(elements2->get_element_count());
QUARK_ASSERT(parent_index >= -1);
QUARK_ASSERT(parent_index < count);
if(parent_index != -1){
rcs[parent_index]++;
}
}
while(elements_todo > 0){
// Find all elements that are free to process -- they are not blocked on a depenency.
std::vector<int> pass_ids;
for(int i = 0 ; i < elements2->get_element_count() ; i++){
const auto rc = rcs[i];
if(rc == 0){
pass_ids.push_back(i);
rcs[i] = -1;
}
}
if(pass_ids.empty()){
quark::throw_runtime_error("supermap() dependency cycle error.");
}
for(const auto element_index: pass_ids){
const auto& e = elements2->get_element_ptr()[element_index];
// Make list of the element's inputs -- they must all be complete now.
std::vector<runtime_value_t> solved_deps;
for(int element_index2 = 0 ; element_index2 < parents2->get_element_count() ; element_index2++){
const auto& p = parents2->get_element_ptr()[element_index2];
const auto parent_index = p.int_value;
if(parent_index == element_index){
QUARK_ASSERT(element_index2 != -1);
QUARK_ASSERT(element_index2 >= -1 && element_index2 < elements2->get_element_count());
QUARK_ASSERT(rcs[element_index2] == -1);
const auto& solved = complete[element_index2];
solved_deps.push_back(solved);
}
}
auto solved_deps2 = alloc_vec(r.heap, solved_deps.size(), solved_deps.size());
for(int i = 0 ; i < solved_deps.size() ; i++){
solved_deps2->get_element_ptr()[i] = solved_deps[i];
}
runtime_value_t solved_deps3 { .vector_ptr = solved_deps2 };
const auto wide_result = (*f2)(frp, e, solved_deps3);
// Release just the vec, **not the elements**. The elements are aliases for complete-vector.
if(dec_rc(solved_deps2->alloc) == 0){
dispose_vec(*solved_deps2);
}
const auto result1 = wide_result.a;
const auto parent_index = parents2->get_element_ptr()[element_index].int_value;
if(parent_index != -1){
rcs[parent_index]--;
}
complete[element_index] = result1;
elements_todo--;
}
}
//??? No need to copy all elements -- could store them directly into the VEC_T.
const auto count = complete.size();
auto result_vec = alloc_vec(r.heap, count, count);
for(int i = 0 ; i < count ; i++){
// retain_value(r, complete[i], r_type);
result_vec->get_element_ptr()[i] = complete[i];
}
#if 0
const auto vec_r = runtime_value_t{ .vector_ptr = result_vec };
const auto result_value = from_runtime_value(r, vec_r, typeid_t::make_vector(r_type));
const auto debug = value_and_type_to_ast_json(result_value);
QUARK_TRACE(json_to_pretty_string(debug));
#endif
return make_wide_return_vec(result_vec);
}
runtime_value_t floyd_funcdef__to_pretty_string(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto& value = from_runtime_value(r, arg0_value, type0);
const auto json = value_to_ast_json(value, json_tags::k_plain);
const auto s = json_to_pretty_string(json, 0, pretty_t{ 80, 4 });
return to_runtime_string(r, s);
}
runtime_value_t floyd_host__to_string(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto s = gen_to_string(r, arg0_value, arg0_type);
return to_runtime_string(r, s);
}
runtime_type_t floyd_host__typeof(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
#if DEBUG
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
QUARK_ASSERT(type0.check_invariant());
#endif
return arg0_type;
}
//??? Split into string/vector/dict versions.
const WIDE_RETURN_T floyd_funcdef__update(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type, runtime_value_t arg1_value, runtime_type_t arg1_type, runtime_value_t arg2_value, runtime_type_t arg2_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto type1 = lookup_type(r.type_interner.interner, arg1_type);
const auto type2 = lookup_type(r.type_interner.interner, arg2_type);
if(type0.is_string()){
QUARK_ASSERT(type1.is_int());
QUARK_ASSERT(type2.is_int());
const auto str = from_runtime_string(r, arg0_value);
const auto index = arg1_value.int_value;
const auto new_char = (char)arg2_value.int_value;
const auto len = str.size();
if(index < 0 || index >= len){
throw std::runtime_error("Position argument to update() is outside collection span.");
}
auto result = str;
result[index] = new_char;
const auto result2 = to_runtime_string(r, result);
return make_wide_return_1x64(result2);
}
else if(type0.is_vector()){
QUARK_ASSERT(type1.is_int());
const auto vec = unpack_vec_arg(r.type_interner.interner, arg0_value, arg0_type);
const auto element_type = type0.get_vector_element_type();
const auto index = arg1_value.int_value;
QUARK_ASSERT(element_type == type2);
if(index < 0 || index >= vec->get_element_count()){
throw std::runtime_error("Position argument to update() is outside collection span.");
}
auto result = alloc_vec(r.heap, vec->get_element_count(), vec->get_element_count());
auto dest_ptr = result->get_element_ptr();
auto source_ptr = vec->get_element_ptr();
if(is_rc_value(element_type)){
retain_value(r, arg2_value, element_type);
for(int i = 0 ; i < result->get_element_count() ; i++){
retain_value(r, source_ptr[i], element_type);
dest_ptr[i] = source_ptr[i];
}
release_vec_deep(r, dest_ptr[index].vector_ptr, element_type);
dest_ptr[index] = arg2_value;
}
else{
for(int i = 0 ; i < result->get_element_count() ; i++){
dest_ptr[i] = source_ptr[i];
}
dest_ptr[index] = arg2_value;
}
return make_wide_return_vec(result);
}
else if(type0.is_dict()){
QUARK_ASSERT(type1.is_string());
const auto key = from_runtime_string(r, arg1_value);
const auto dict = unpack_dict_arg(r.type_interner.interner, arg0_value, arg0_type);
const auto value_type = type0.get_dict_value_type();
// Deep copy dict.
auto dict2 = alloc_dict(r.heap);
dict2->get_map_mut() = dict->get_map();
dict2->get_map_mut().insert_or_assign(key, arg2_value);
if(is_rc_value(value_type)){
for(const auto& e: dict2->get_map()){
retain_value(r, e.second, value_type);
}
}
return make_wide_return_dict(dict2);
}
else if(type0.is_struct()){
QUARK_ASSERT(false);
}
else{
// No other types allowed.
UNSUPPORTED();
}
}
JSON_T* floyd_funcdef__value_to_jsonvalue(floyd_runtime_t* frp, runtime_value_t arg0_value, runtime_type_t arg0_type){
auto& r = get_floyd_runtime(frp);
const auto type0 = lookup_type(r.type_interner.interner, arg0_type);
const auto value0 = from_runtime_value(r, arg0_value, type0);
const auto j = value_to_ast_json(value0, json_tags::k_plain);
auto result = alloc_json(r.heap, j);
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FILELIB FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
STRUCT_T* floyd_funcdef__calc_binary_sha1(floyd_runtime_t* frp, STRUCT_T* binary_ptr){
auto& r = get_floyd_runtime(frp);
QUARK_ASSERT(binary_ptr != nullptr);
const auto& binary = *reinterpret_cast<const native_binary_t*>(binary_ptr->get_data_ptr());
const auto& s = from_runtime_string(r, runtime_value_t { .vector_ptr = binary.ascii40 });
const auto sha1 = CalcSHA1(s);
const auto ascii40 = SHA1ToStringPlain(sha1);
const auto a = value_t::make_struct_value(
typeid_t::make_struct2({ member_t{ typeid_t::make_string(), "ascii40" } }),
{ value_t::make_string(ascii40) }
);
auto result = to_runtime_value(r, a);
return result.struct_ptr;
}
STRUCT_T* floyd_funcdef__calc_string_sha1(floyd_runtime_t* frp, runtime_value_t s0){
auto& r = get_floyd_runtime(frp);
const auto& s = from_runtime_string(r, s0);
const auto sha1 = CalcSHA1(s);
const auto ascii40 = SHA1ToStringPlain(sha1);
const auto a = value_t::make_struct_value(
typeid_t::make_struct2({ member_t{ typeid_t::make_string(), "ascii40" } }),
{ value_t::make_string(ascii40) }
);
auto result = to_runtime_value(r, a);
return result.struct_ptr;
}
void floyd_funcdef__create_directory_branch(floyd_runtime_t* frp, runtime_value_t path0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
if(is_valid_absolute_dir_path(path) == false){
quark::throw_runtime_error("create_directory_branch() illegal input path.");
}
MakeDirectoriesDeep(path);
}
void floyd_funcdef__delete_fsentry_deep(floyd_runtime_t* frp, runtime_value_t path0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
if(is_valid_absolute_dir_path(path) == false){
quark::throw_runtime_error("delete_fsentry_deep() illegal input path.");
}
DeleteDeep(path);
}
uint8_t floyd_funcdef__does_fsentry_exist(floyd_runtime_t* frp, runtime_value_t path0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
if(is_valid_absolute_dir_path(path) == false){
quark::throw_runtime_error("does_fsentry_exist() illegal input path.");
}
bool exists = DoesEntryExist(path);
const auto result = value_t::make_bool(exists);
#if 1
const auto debug = value_and_type_to_ast_json(result);
QUARK_TRACE(json_to_pretty_string(debug));
#endif
return exists ? 0x01 : 0x00;
}
static void write_text_file(const std::string& abs_path, const std::string& data){
const auto up = UpDir2(abs_path);
MakeDirectoriesDeep(up.first);
std::ofstream outputFile;
outputFile.open(abs_path);
if (outputFile.fail()) {
quark::throw_exception();
}
outputFile << data;
outputFile.close();
}
void floyd_funcdef__write_text_file(floyd_runtime_t* frp, runtime_value_t path0, runtime_value_t data0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
const auto file_contents = from_runtime_string(r, data0);
write_text_file(path, file_contents);
}
runtime_value_t floyd_funcdef__get_fs_environment(floyd_runtime_t* frp){
auto& r = get_floyd_runtime(frp);
const auto dirs = GetDirectories();
const auto result = value_t::make_struct_value(
make__fs_environment_t__type(),
{
value_t::make_string(dirs.home_dir),
value_t::make_string(dirs.documents_dir),
value_t::make_string(dirs.desktop_dir),
value_t::make_string(dirs.application_support),
value_t::make_string(dirs.preferences_dir),
value_t::make_string(dirs.cache_dir),
value_t::make_string(dirs.temp_dir),
value_t::make_string(dirs.process_dir)
}
);
#if 1
const auto debug = value_and_type_to_ast_json(result);
QUARK_TRACE(json_to_pretty_string(debug));
#endif
const auto v = to_runtime_value(r, result);
return v;
}
VEC_T* floyd_funcdef__get_fsentries_deep(floyd_runtime_t* frp, runtime_value_t path0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
if(is_valid_absolute_dir_path(path) == false){
quark::throw_runtime_error("get_fsentries_deep() illegal input path.");
}
const auto a = GetDirItemsDeep(path);
const auto elements = directory_entries_to_values(a);
const auto k_fsentry_t__type = make__fsentry_t__type();
const auto vec2 = value_t::make_vector_value(k_fsentry_t__type, elements);
#if 1
const auto debug = value_and_type_to_ast_json(vec2);
QUARK_TRACE(json_to_pretty_string(debug));
#endif
const auto v = to_runtime_value(r, vec2);
return v.vector_ptr;
}
VEC_T* floyd_funcdef__get_fsentries_shallow(floyd_runtime_t* frp, runtime_value_t path0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
if(is_valid_absolute_dir_path(path) == false){
quark::throw_runtime_error("get_fsentries_shallow() illegal input path.");
}
const auto a = GetDirItems(path);
const auto elements = directory_entries_to_values(a);
const auto k_fsentry_t__type = make__fsentry_t__type();
const auto vec2 = value_t::make_vector_value(k_fsentry_t__type, elements);
#if 1
const auto debug = value_and_type_to_ast_json(vec2);
QUARK_TRACE(json_to_pretty_string(debug));
#endif
const auto v = to_runtime_value(r, vec2);
return v.vector_ptr;
}
STRUCT_T* floyd_funcdef__get_fsentry_info(floyd_runtime_t* frp, runtime_value_t path0){
auto& r = get_floyd_runtime(frp);
const auto result = impl__get_fsentry_info(from_runtime_string(r, path0));
const auto v = to_runtime_value(r, result);
return v.struct_ptr;
}
int64_t floyd_funcdef__get_time_of_day(floyd_runtime_t* frp){
auto& r = get_floyd_runtime(frp);
std::chrono::time_point<std::chrono::high_resolution_clock> t = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = t - r._start_time;
const auto ms = elapsed_seconds.count() * 1000.0;
return static_cast<int64_t>(ms);
}
void floyd_funcdef__rename_fsentry(floyd_runtime_t* frp, runtime_value_t path0, runtime_value_t name0){
auto& r = get_floyd_runtime(frp);
const auto path = from_runtime_string(r, path0);
if(is_valid_absolute_dir_path(path) == false){
quark::throw_runtime_error("rename_fsentry() illegal input path.");
}
const auto n = from_runtime_string(r, name0);
if(n.empty()){
quark::throw_runtime_error("rename_fsentry() illegal input name.");
}
RenameEntry(path, n);
}
std::map<std::string, void*> get_host_functions_map2(){
//////////////////////////////// CORE FUNCTIONS AND HOST FUNCTIONS
const std::map<std::string, void*> host_functions_map = {
//////////////////////////////// CORECALLS
{ "floyd_funcdef__assert", reinterpret_cast<void *>(&floyd_funcdef__assert) },
{ "floyd_funcdef__to_string", reinterpret_cast<void *>(&floyd_host__to_string) },
{ "floyd_funcdef__to_pretty_string", reinterpret_cast<void *>(&floyd_funcdef__to_pretty_string) },
{ "floyd_funcdef__typeof", reinterpret_cast<void *>(&floyd_host__typeof) },
{ "floyd_funcdef__update", reinterpret_cast<void *>(&floyd_funcdef__update) },
{ "floyd_funcdef__size", reinterpret_cast<void *>(&floyd_funcdef__size) },
{ "floyd_funcdef__find", reinterpret_cast<void *>(&floyd_funcdef__find) },
{ "floyd_funcdef__exists", reinterpret_cast<void *>(&floyd_funcdef__exists) },
{ "floyd_funcdef__erase", reinterpret_cast<void *>(&floyd_host_function__erase) },
{ "floyd_funcdef__push_back", reinterpret_cast<void *>(&floyd_funcdef__push_back) },
{ "floyd_funcdef__subset", reinterpret_cast<void *>(&floyd_funcdef__subset) },
{ "floyd_funcdef__replace", reinterpret_cast<void *>(&floyd_funcdef__replace) },
{ "floyd_funcdef__jsonvalue_to_script", reinterpret_cast<void *>(&floyd_funcdef__jsonvalue_to_script) },
{ "floyd_funcdef__jsonvalue_to_value", reinterpret_cast<void *>(&floyd_funcdef__jsonvalue_to_value) },
{ "floyd_funcdef__script_to_jsonvalue", reinterpret_cast<void *>(&floyd_funcdef__script_to_jsonvalue) },
{ "floyd_funcdef__value_to_jsonvalue", reinterpret_cast<void *>(&floyd_funcdef__value_to_jsonvalue) },
{ "floyd_funcdef__get_json_type", reinterpret_cast<void *>(&floyd_host_function__get_json_type) },
{ "floyd_funcdef__map", reinterpret_cast<void *>(&floyd_funcdef__map) },
{ "floyd_funcdef__map_string", reinterpret_cast<void *>(&floyd_funcdef__map_string) },
{ "floyd_funcdef__filter", reinterpret_cast<void *>(&floyd_funcdef__filter) },
{ "floyd_funcdef__reduce", reinterpret_cast<void *>(&floyd_funcdef__reduce) },
{ "floyd_funcdef__supermap", reinterpret_cast<void *>(&floyd_funcdef__supermap) },
{ "floyd_funcdef__print", reinterpret_cast<void *>(&floyd_funcdef__print) },
{ "floyd_funcdef__send", reinterpret_cast<void *>(&floyd_funcdef__send) },
//////////////////////////////// FILE LIB
{ "floyd_funcdef__write_text_file", reinterpret_cast<void *>(&floyd_funcdef__write_text_file) },
{ "floyd_funcdef__read_text_file", reinterpret_cast<void *>(&floyd_host_function_1022) },
{ "floyd_funcdef__rename_fsentry", reinterpret_cast<void *>(&floyd_funcdef__rename_fsentry) },
{ "floyd_funcdef__calc_binary_sha1", reinterpret_cast<void *>(&floyd_funcdef__calc_binary_sha1) },
{ "floyd_funcdef__calc_string_sha1", reinterpret_cast<void *>(&floyd_funcdef__calc_string_sha1) },
{ "floyd_funcdef__create_directory_branch", reinterpret_cast<void *>(&floyd_funcdef__create_directory_branch) },
{ "floyd_funcdef__delete_fsentry_deep", reinterpret_cast<void *>(&floyd_funcdef__delete_fsentry_deep) },
{ "floyd_funcdef__does_fsentry_exist", reinterpret_cast<void *>(&floyd_funcdef__does_fsentry_exist) },
{ "floyd_funcdef__get_fs_environment", reinterpret_cast<void *>(&floyd_funcdef__get_fs_environment) },
{ "floyd_funcdef__get_fsentries_deep", reinterpret_cast<void *>(&floyd_funcdef__get_fsentries_deep) },
{ "floyd_funcdef__get_fsentries_shallow", reinterpret_cast<void *>(&floyd_funcdef__get_fsentries_shallow) },
{ "floyd_funcdef__get_fsentry_info", reinterpret_cast<void *>(&floyd_funcdef__get_fsentry_info) },
{ "floyd_funcdef__get_time_of_day", reinterpret_cast<void *>(&floyd_funcdef__get_time_of_day) }
};
return host_functions_map;
}
uint64_t call_floyd_runtime_init(llvm_execution_engine_t& ee){
QUARK_ASSERT(ee.check_invariant());
auto a_func = reinterpret_cast<FLOYD_RUNTIME_INIT>(get_global_function(ee, "floyd_runtime_init"));
QUARK_ASSERT(a_func != nullptr);
int64_t a_result = (*a_func)(reinterpret_cast<floyd_runtime_t*>(&ee));
QUARK_ASSERT(a_result == 667);
return a_result;
}
uint64_t call_floyd_runtime_deinit(llvm_execution_engine_t& ee){
QUARK_ASSERT(ee.check_invariant());
auto a_func = reinterpret_cast<FLOYD_RUNTIME_INIT>(get_global_function(ee, "floyd_runtime_deinit"));
QUARK_ASSERT(a_func != nullptr);
int64_t a_result = (*a_func)(reinterpret_cast<floyd_runtime_t*>(&ee));
QUARK_ASSERT(a_result == 668);
return a_result;
}
////////////////////////////////////// llvm_process_runtime_t
/*
We use only one LLVM execution engine to run main() and all Floyd processes.
They each have a separate llvm_process_t-instance and their own runtime-pointer.
*/
/*
Try using C++ multithreading maps etc?
Explore std::packaged_task
*/
// https://en.cppreference.com/w/cpp/thread/condition_variable/wait
struct process_interface {
virtual ~process_interface(){};
virtual void on_message(const json_t& message) = 0;
virtual void on_init() = 0;
};
// NOTICE: Each process inbox has its own mutex + condition variable.
// No mutex protects cout.
struct llvm_process_t {
std::condition_variable _inbox_condition_variable;
std::mutex _inbox_mutex;
std::deque<json_t> _inbox;
std::string _name_key;
std::string _function_key;
std::thread::id _thread_id;
// std::shared_ptr<interpreter_t> _interpreter;
std::shared_ptr<llvm_bind_t> _init_function;
std::shared_ptr<llvm_bind_t> _process_function;
value_t _process_state;
std::shared_ptr<process_interface> _processor;
};
struct llvm_process_runtime_t {
container_t _container;
std::map<std::string, std::string> _process_infos;
std::thread::id _main_thread_id;
llvm_execution_engine_t* ee;
std::vector<std::shared_ptr<llvm_process_t>> _processes;
std::vector<std::thread> _worker_threads;
};
/*
??? have ONE runtime PER computer or one per interpreter?
??? Separate system-interpreter (all processes and many clock busses) vs ONE thread of execution?
*/
static void send_message(llvm_process_runtime_t& runtime, int process_id, const json_t& message){
auto& process = *runtime._processes[process_id];
{
std::lock_guard<std::mutex> lk(process._inbox_mutex);
process._inbox.push_front(message);
QUARK_TRACE("Notifying...");
}
process._inbox_condition_variable.notify_one();
// process._inbox_condition_variable.notify_all();
}
static void run_process(llvm_process_runtime_t& runtime, int process_id){
auto& process = *runtime._processes[process_id];
bool stop = false;
const auto thread_name = get_current_thread_name();
const typeid_t process_state_type = process._init_function != nullptr ? process._init_function->type.get_function_return() : typeid_t::make_undefined();
if(process._processor){
process._processor->on_init();
}
if(process._init_function != nullptr){
// !!! This validation should be done earlier in the startup process / compilation process.
if(process._init_function->type != make_process_init_type(process_state_type)){
quark::throw_runtime_error("Invalid function prototype for process-init");
}
auto f = *reinterpret_cast<FLOYD_RUNTIME_PROCESS_INIT*>(process._init_function->address);
const auto result = (*f)(reinterpret_cast<floyd_runtime_t*>(runtime.ee));
process._process_state = from_runtime_value(*runtime.ee, result, process._init_function->type.get_function_return());
}
while(stop == false){
json_t message;
{
std::unique_lock<std::mutex> lk(process._inbox_mutex);
QUARK_TRACE_SS(thread_name << ": waiting......");
process._inbox_condition_variable.wait(lk, [&]{ return process._inbox.empty() == false; });
QUARK_TRACE_SS(thread_name << ": continue");
// Pop message.
QUARK_ASSERT(process._inbox.empty() == false);
message = process._inbox.back();
process._inbox.pop_back();
}
QUARK_TRACE_SS("RECEIVED: " << json_to_pretty_string(message));
if(message.is_string() && message.get_string() == "stop"){
stop = true;
QUARK_TRACE_SS(thread_name << ": STOP");
}
else{
if(process._processor){
process._processor->on_message(message);
}
if(process._process_function != nullptr){
// !!! This validation should be done earlier in the startup process / compilation process.
if(process._process_function->type != make_process_message_handler_type(process_state_type)){
quark::throw_runtime_error("Invalid function prototype for process message handler");
}
auto f = *reinterpret_cast<FLOYD_RUNTIME_PROCESS_MESSAGE*>(process._process_function->address);
const auto state2 = to_runtime_value(*runtime.ee, process._process_state);
const auto message2 = to_runtime_value(*runtime.ee, value_t::make_json_value(message));
const auto result = (*f)(reinterpret_cast<floyd_runtime_t*>(runtime.ee), state2, message2);
process._process_state = from_runtime_value(*runtime.ee, result, process._process_function->type.get_function_return());
}
}
}
}
static std::map<std::string, value_t> run_container_int(llvm_ir_program_t& program_breaks, const std::vector<std::string>& main_args, const std::string& container_key){
QUARK_ASSERT(container_key.empty() == false);
llvm_execution_engine_t ee = make_engine_run_init(*program_breaks.instance, program_breaks);
llvm_process_runtime_t runtime;
runtime._main_thread_id = std::this_thread::get_id();
runtime.ee = ⅇ
//??? Confusing. Support several containers!
if(std::find(program_breaks.software_system._containers.begin(), program_breaks.software_system._containers.end(), container_key) == program_breaks.software_system._containers.end()){
quark::throw_runtime_error("Unknown container-key");
}
if(program_breaks.container_def._name != container_key){
quark::throw_runtime_error("Unknown container-key");
}
runtime._container = program_breaks.container_def;
runtime._process_infos = reduce(runtime._container._clock_busses, std::map<std::string, std::string>(), [](const std::map<std::string, std::string>& acc, const std::pair<std::string, clock_bus_t>& e){
auto acc2 = acc;
acc2.insert(e.second._processes.begin(), e.second._processes.end());
return acc2;
});
struct my_interpreter_handler_t : public runtime_handler_i {
my_interpreter_handler_t(llvm_process_runtime_t& runtime) : _runtime(runtime) {}
virtual void on_send(const std::string& process_id, const json_t& message){
const auto it = std::find_if(_runtime._processes.begin(), _runtime._processes.end(), [&](const std::shared_ptr<llvm_process_t>& process){ return process->_name_key == process_id; });
if(it != _runtime._processes.end()){
const auto process_index = it - _runtime._processes.begin();
send_message(_runtime, static_cast<int>(process_index), message);
}
}
llvm_process_runtime_t& _runtime;
};
auto my_interpreter_handler = my_interpreter_handler_t{runtime};
//??? We need to pass unique runtime-object to each Floyd process -- not the ee!
ee._handler = &my_interpreter_handler;
for(const auto& t: runtime._process_infos){
auto process = std::make_shared<llvm_process_t>();
process->_name_key = t.first;
process->_function_key = t.second;
// process->_interpreter = std::make_shared<interpreter_t>(program, &my_interpreter_handler);
process->_init_function = std::make_shared<llvm_bind_t>(bind_function2(*runtime.ee, t.second + "__init"));
process->_process_function = std::make_shared<llvm_bind_t>(bind_function2(*runtime.ee, t.second));
runtime._processes.push_back(process);
}
// Remember that current thread (main) is also a thread, no need to create a worker thread for one process.
runtime._processes[0]->_thread_id = runtime._main_thread_id;
for(int process_id = 1 ; process_id < runtime._processes.size() ; process_id++){
runtime._worker_threads.push_back(std::thread([&](int process_id){
// const auto native_thread = thread::native_handle();
std::stringstream thread_name;
thread_name << std::string() << "process " << process_id << " thread";
#ifdef __APPLE__
pthread_setname_np(/*pthread_self(),*/ thread_name.str().c_str());
#endif
run_process(runtime, process_id);
}, process_id));
}
run_process(runtime, 0);
for(auto &t: runtime._worker_threads){
t.join();
}
call_floyd_runtime_deinit(ee);
return {};
}
std::map<std::string, value_t> run_llvm_container(llvm_ir_program_t& program_breaks, const std::vector<std::string>& main_args, const std::string& container_key){
if(container_key.empty()){
// ??? instance is already known via program_breaks.
llvm_execution_engine_t ee = make_engine_run_init(*program_breaks.instance, program_breaks);
const auto main_function = bind_function(ee, "main");
if(main_function.first != nullptr){
const auto main_result_int = llvm_call_main(ee, main_function, main_args);
const auto result = value_t::make_int(main_result_int);
call_floyd_runtime_deinit(ee);
detect_leaks(ee.heap);
return {{ "main()", result }};
}
else{
call_floyd_runtime_deinit(ee);
return {{ "global", value_t::make_void() }};
}
}
else{
return run_container_int(program_breaks, main_args, container_key);
}
}
#if DEBUG && 1
// Verify that all global functions can be accessed. If *one* is unresolved, then all return NULL!?
void check_nulls(llvm_execution_engine_t& ee2, const llvm_ir_program_t& p){
int index = 0;
for(const auto& e: p.debug_globals._symbols){
if(e.second.get_type().is_function()){
const auto global_var = (FLOYD_RUNTIME_HOST_FUNCTION*)floyd::get_global_ptr(ee2, e.first);
QUARK_ASSERT(global_var != nullptr);
const auto f = *global_var;
// QUARK_ASSERT(f != nullptr);
const std::string suffix = f == nullptr ? " NULL POINTER" : "";
// const uint64_t addr = reinterpret_cast<uint64_t>(f);
// QUARK_TRACE_SS(index << " " << e.first << " " << addr << suffix);
}
else{
}
index++;
}
}
#endif
static std::map<std::string, void*> register_c_functions(llvm::LLVMContext& context, const llvm_type_interner_t& interner){
const auto runtime_functions = get_runtime_functions(context, interner);
std::map<std::string, void*> runtime_functions_map;
for(const auto& e: runtime_functions){
const auto e2 = std::pair<std::string, void*>(e.name_key, e.implementation_f);
runtime_functions_map.insert(e2);
}
const auto host_functions_map = get_host_functions_map2();
std::map<std::string, void*> function_map = runtime_functions_map;
function_map.insert(host_functions_map.begin(), host_functions_map.end());
return function_map;
}
//??? Move init functions to runtime source file.
// Destroys program, can only run it once!
static llvm_execution_engine_t make_engine_no_init(llvm_instance_t& instance, llvm_ir_program_t& program_breaks){
QUARK_ASSERT(instance.check_invariant());
QUARK_ASSERT(program_breaks.check_invariant());
std::string collectedErrors;
// WARNING: Destroys p -- uses std::move().
llvm::ExecutionEngine* exeEng = llvm::EngineBuilder(std::move(program_breaks.module))
.setErrorStr(&collectedErrors)
.setOptLevel(llvm::CodeGenOpt::Level::None)
.setVerifyModules(true)
.setEngineKind(llvm::EngineKind::JIT)
.create();
if (exeEng == nullptr){
std::string error = "Unable to construct execution engine: " + collectedErrors;
perror(error.c_str());
throw std::exception();
}
QUARK_ASSERT(collectedErrors.empty());
const auto start_time = std::chrono::high_resolution_clock::now();
auto ee1 = std::shared_ptr<llvm::ExecutionEngine>(exeEng);
auto ee2 = llvm_execution_engine_t{
k_debug_magic,
&instance,
ee1,
program_breaks.type_interner,
program_breaks.debug_globals,
program_breaks.function_defs,
{},
nullptr,
start_time
};
QUARK_ASSERT(ee2.check_invariant());
auto function_map = register_c_functions(instance.context, program_breaks.type_interner);
// Resolve all unresolved functions.
{
// https://stackoverflow.com/questions/33328562/add-mapping-to-c-lambda-from-llvm
auto lambda = [&](const std::string& s) -> void* {
QUARK_ASSERT(s.empty() == false);
QUARK_ASSERT(s[0] == '_');
const auto s2 = s.substr(1);
const auto it = function_map.find(s2);
if(it != function_map.end()){
return it->second;
}
else{
}
return nullptr;
};
std::function<void*(const std::string&)> on_lazy_function_creator2 = lambda;
// NOTICE! Patch during finalizeObject() only, then restore!
ee2.ee->InstallLazyFunctionCreator(on_lazy_function_creator2);
ee2.ee->finalizeObject();
ee2.ee->InstallLazyFunctionCreator(nullptr);
// ee2.ee->DisableGVCompilation(false);
// ee2.ee->DisableSymbolSearching(false);
}
#if DEBUG
check_nulls(ee2, program_breaks);
#endif
// llvm::WriteBitcodeToFile(exeEng->getVerifyModules(), raw_ostream &Out);
return ee2;
}
// Destroys program, can only run it once!
// Automatically runs floyd_runtime_init() to execute Floyd's global functions and initialize global constants.
llvm_execution_engine_t make_engine_run_init(llvm_instance_t& instance, llvm_ir_program_t& program_breaks){
QUARK_ASSERT(instance.check_invariant());
QUARK_ASSERT(program_breaks.check_invariant());
llvm_execution_engine_t ee = make_engine_no_init(instance, program_breaks);
trace_heap(ee.heap);
#if DEBUG
{
const auto print_global_ptr = (FLOYD_RUNTIME_HOST_FUNCTION*)floyd::get_global_ptr(ee, "print");
QUARK_ASSERT(print_global_ptr != nullptr);
const auto print_f = *print_global_ptr;
QUARK_ASSERT(print_f != nullptr);
if(print_f){
// (*print_f)(&ee, 109);
}
}
{
auto a_func = reinterpret_cast<FLOYD_RUNTIME_INIT>(get_global_function(ee, "floyd_runtime_init"));
QUARK_ASSERT(a_func != nullptr);
}
#endif
const auto init_result = call_floyd_runtime_init(ee);
QUARK_ASSERT(init_result == 667);
// check_nulls(ee, program_breaks);
trace_heap(ee.heap);
return ee;
}
} // namespace floyd
//////////////////////////////// TESTS
QUARK_UNIT_TEST("", "From source: Check that floyd_runtime_init() runs and sets 'result' global", "", ""){
const auto cu = floyd::make_compilation_unit_nolib("let int result = 1 + 2 + 3", "myfile.floyd");
const auto pass3 = compile_to_sematic_ast__errors(cu);
floyd::llvm_instance_t instance;
auto program = generate_llvm_ir_program(instance, pass3, "myfile.floyd");
auto ee = make_engine_run_init(instance, *program);
const auto result = *static_cast<uint64_t*>(floyd::get_global_ptr(ee, "result"));
QUARK_ASSERT(result == 6);
call_floyd_runtime_deinit(ee);
// QUARK_TRACE_SS("result = " << floyd::print_program(*program));
}
// BROKEN!
QUARK_UNIT_TEST("", "From JSON: Simple function call, call print() from floyd_runtime_init()", "", ""){
const auto cu = floyd::make_compilation_unit_nolib("print(5)", "myfile.floyd");
const auto pass3 = compile_to_sematic_ast__errors(cu);
floyd::llvm_instance_t instance;
auto program = generate_llvm_ir_program(instance, pass3, "myfile.floyd");
auto ee = make_engine_run_init(instance, *program);
QUARK_ASSERT(ee._print_output == std::vector<std::string>{"5"});
call_floyd_runtime_deinit(ee);
}
| 31.933289 | 226 | 0.736076 | [
"object",
"vector"
] |
252f9d02ef58ea05308aaf0595c526681b26c87a | 2,445 | cc | C++ | src/route_path_utils.cc | comrob/tspns | 976875a7d180a72e8a341d404cded5ebd327b76c | [
"BSD-2-Clause"
] | null | null | null | src/route_path_utils.cc | comrob/tspns | 976875a7d180a72e8a341d404cded5ebd327b76c | [
"BSD-2-Clause"
] | null | null | null | src/route_path_utils.cc | comrob/tspns | 976875a7d180a72e8a341d404cded5ebd327b76c | [
"BSD-2-Clause"
] | null | null | null | /*
* File name: route_path_utils.cc
* Date: 2016/12/10 18:13
* Author: Jan Faigl
*/
#include <cmath>
#include <cstdio>
#include "route_path_utils.h"
/// - function -----------------------------------------------------------------
double get_path_length(const CoordsVector &pts, const double R, bool closed)
{
double len = 0.;
for (int i = 1; i < pts.size(); ++i)
{
double l = (pts[i - 1].geom_distance(pts[i], R));
// std::cout << pts[i-1] << "->" << pts[i] << " = " << l << std::endl;
len += l ;//(pts[i - 1].geom_distance(pts[i], R));
}
if (closed and pts.size() > 1)
{
double l = (pts.back().geom_distance(pts.front(), R));
// std::cout << pts.back() << "->" << pts.front() << " = " << l << std::endl;
len += (pts.back().geom_distance(pts.front(), R));
}
return len;
}
// #define dist(i, j) sqrt(path[i].squared_distance(path[j]))
#define dist(i, j, R) path[i].geom_distance(path[j], R)
/// - function -----------------------------------------------------------------
void two_opt(CoordsVector &path, std::vector<int> &sequence, const double R)
{
const int N = path.size();
int counter = 0;
double mchange;
do
{
mchange = 0.0;
int mi = -1;
int mj = -1;
for (int i = 1; i < N; ++i)
{
for (int j = i + 1; j < N - 1; ++j)
{
// double change= dist(i - 1, j) + dist(i, j + 1) - dist(i - 1, i) - dist(j, j + 1);
double change= dist(i - 1, j, R) + dist(i, j + 1, R) - dist(i - 1, i, R) - dist(j, j + 1, R);
if (mchange > change)
{
mchange = change;
mi = i;
mj = j;
}
counter += 1;
}
}
if (mi > 0 and mj > 0)
{
CoordsVector newPath;
std::vector<int> newSequence;
for (int i = 0; i < mi; ++i)
{
newPath.push_back(path[i]);
newSequence.push_back(sequence[i]);
}
for (int i = mj; i >= mi; --i)
{
newPath.push_back(path[i]);
newSequence.push_back(sequence[i]);
}
for (int i = mj + 1; i < N; ++i)
{
newPath.push_back(path[i]);
newSequence.push_back(sequence[i]);
}
path = newPath;
sequence = newSequence;
}
} while (mchange < -1e-5);
}
/* end of route_path_utils.cc */
| 28.430233 | 107 | 0.441309 | [
"vector"
] |
25349655d05413a88546197628fdfd29048fa7ce | 2,093 | cc | C++ | media/gpu/windows/hresult_status_debug_device.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | media/gpu/windows/hresult_status_debug_device.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | media/gpu/windows/hresult_status_debug_device.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 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 "media/gpu/windows/hresult_status_debug_device.h"
#include "media/base/media_serializers.h"
#include "media/base/win/hresult_status_helper.h"
namespace media {
// Only define this method in debug mode.
#if !defined(NDEBUG)
Status AddDebugMessages(Status error, ComD3D11Device device) {
// MSDN says that this needs to be casted twice, then GetMessage should
// be called with a malloc.
Microsoft::WRL::ComPtr<ID3D11Debug> debug_layer;
if (!SUCCEEDED(device.As(&debug_layer)))
return error;
Microsoft::WRL::ComPtr<ID3D11InfoQueue> message_layer;
if (!SUCCEEDED(debug_layer.As(&message_layer)))
return error;
uint64_t messages_count = message_layer->GetNumStoredMessages();
if (messages_count == 0)
return error;
std::vector<std::string> messages(messages_count, "");
for (uint64_t i = 0; i < messages_count; i++) {
SIZE_T size;
message_layer->GetMessage(i, nullptr, &size);
D3D11_MESSAGE* message = reinterpret_cast<D3D11_MESSAGE*>(malloc(size));
if (!message) // probably OOM - so just stop trying to get more.
return error;
message_layer->GetMessage(i, message, &size);
messages.emplace_back(message->pDescription);
free(message);
}
return std::move(error).WithData("debug_info", messages);
}
#endif // !defined(NDEBUG)
Status D3D11HresultToStatus(HRESULT hresult,
ComD3D11Device device,
const char* message,
const base::Location& location) {
if (SUCCEEDED(hresult))
return OkStatus();
#if !defined(NDEBUG)
return AddDebugMessages(
HresultToStatus(hresult, message, StatusCode::kWindowsD3D11Error,
location),
device);
#else // !defined(NDEBUG)
return HresultToStatus(hresult, message, StatusCode::kWindowsD3D11Error,
location);
#endif // !defined(NDEBUG)
}
} // namespace media
| 32.703125 | 76 | 0.684663 | [
"vector"
] |
253aae7183e1151c72286350ae40a2177483b71f | 14,425 | cpp | C++ | ffmpeg_output.cpp | iwo/SCR-Screen-Recorder-native | 7c136d2835fa7163b2e7576602d05c3d7cba9417 | [
"Apache-2.0"
] | 7 | 2017-02-28T03:49:49.000Z | 2020-07-31T19:03:53.000Z | ffmpeg_output.cpp | iwo/SCR-Screen-Recorder-native | 7c136d2835fa7163b2e7576602d05c3d7cba9417 | [
"Apache-2.0"
] | null | null | null | ffmpeg_output.cpp | iwo/SCR-Screen-Recorder-native | 7c136d2835fa7163b2e7576602d05c3d7cba9417 | [
"Apache-2.0"
] | 10 | 2017-02-04T07:01:59.000Z | 2020-11-12T10:20:37.000Z | #include "ffmpeg_output.h"
void FFmpegOutput::setupOutput() {
int ret;
loadFFmpegComponents();
setupOutputContext();
setupVideoStream();
setupFrames();
if (audioSource != SCR_AUDIO_MUTE) {
setupAudioOutput();
}
setupOutputFile();
if (audioSource != SCR_AUDIO_MUTE) {
startAudioInput();
}
startTimeMs = getTimeMs();
mrRunning = true;
pthread_mutex_lock(&frameReadyMutex);
pthread_create(&encodingThread, NULL, FFmpegOutput::encodingThreadStart, this);
}
void FFmpegOutput::loadFFmpegComponents() {
extern AVCodec ff_mpeg4_encoder;
avcodec_register(&ff_mpeg4_encoder);
if (audioSource != SCR_AUDIO_MUTE) {
extern AVCodec ff_aac_encoder;
avcodec_register(&ff_aac_encoder);
}
extern AVOutputFormat ff_mp4_muxer;
av_register_output_format(&ff_mp4_muxer);
extern URLProtocol ff_file_protocol;
ffurl_register_protocol(&ff_file_protocol, sizeof(ff_file_protocol));
}
void FFmpegOutput::setupOutputContext() {
avformat_alloc_output_context2(&oc, NULL, NULL, outputName);
if (!oc) {
stop(234, "Can't alloc output context");
}
}
void FFmpegOutput::setupVideoStream() {
AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_MPEG4);
if (!codec) {
stop(235, "Video codec not found");
}
videoStream = avformat_new_stream(oc, codec);
if (!videoStream) {
stop(234, "Could not allocate video stream");
}
AVCodecContext *c = videoStream->codec;
c->bit_rate = videoBitrate;
c->width = videoWidth;
c->height = videoHeight;
/* frames per second */
c->time_base= (AVRational){1,10};
c->gop_size = 10; /* emit one intra frame every ten frames */
c->max_b_frames=1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
c->thread_count = 4;
c->mb_decision = 2;
int rot = rotation;
if (rot) {
char value[16];
sprintf(value, "%d", rot);
av_dict_set(&videoStream->metadata, "rotate", value, 0);
}
/* Some formats want stream headers to be separate. */
if (oc->oformat->flags & AVFMT_GLOBALHEADER)
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
if (avcodec_open2(c, codec, NULL) < 0) {
ALOGE("Could not open video codec");
stop(235, "Could not open video codec");
}
}
void FFmpegOutput::setupFrames() {
frames[0] = createFrame();
frames[1] = createFrame();
}
AVFrame *FFmpegOutput::createFrame() {
int ret;
AVCodecContext *c = videoStream->codec;
AVFrame * frame = avcodec_alloc_frame();
if (!frame) {
stop(234, "Could not allocate video frame");
}
frame->format = c->pix_fmt;
frame->width = c->width;
frame->height = c->height;
ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height, c->pix_fmt, 32);
if (ret < 0) {
stop(234, "Could not allocate raw picture buffer");
}
memset(frame->data[1], 128, c->height / 2 * frame->linesize[1]);
memset(frame->data[2], 128, c->height / 2 * frame->linesize[2]);
return frame;
}
void FFmpegOutput::setupAudioOutput() {
int ret;
AVCodec *audioCodec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if (!audioCodec) {
stop(235, "AAC Codec not found");
}
audioStream = avformat_new_stream(oc, audioCodec);
if (!audioStream) {
stop(236, "Could not allocate audio stream");
}
AVCodecContext *c = audioStream->codec;
c->sample_fmt = AV_SAMPLE_FMT_FLTP;
c->bit_rate = audioChannels * 64000;
c->sample_rate = audioSamplingRate;
c->channels = audioChannels;
c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
/* Some formats want stream headers to be separate. */
if (oc->oformat->flags & AVFMT_GLOBALHEADER)
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
/* open it */
ret = avcodec_open2(c, audioCodec, NULL);
if (ret < 0) {
stop(235, "Could not open audio codec");
}
audioFrameSize = c->frame_size;
outSamples = (float*) av_malloc(audioFrameSize *
av_get_bytes_per_sample(c->sample_fmt) *
c->channels);
if (!outSamples) {
stop(236, "Could not allocate audio samples buffer");
}
audioStream->time_base= (AVRational){1,audioSamplingRate};
}
void FFmpegOutput::setupOutputFile() {
int ret;
ret = avio_open(&oc->pb, outputName, AVIO_FLAG_WRITE);
if (ret < 0 && fixOutputName()) {
ret = avio_open(&oc->pb, outputName, AVIO_FLAG_WRITE);
}
if (ret < 0) {
stop(201, "Could not open the output file");
}
/* Write the stream header, if any. */
ret = avformat_write_header(oc, NULL);
if (ret < 0) {
stop(247, "Error occurred when writing file header");
}
}
void FFmpegOutput::startAudioInput() {
int err;
inSamplesSize = audioSamplingRate; // buffer up to one second of input audio data
inSamples = new float[inSamplesSize];
audioRecord = new AudioRecord(AUDIO_SOURCE_MIC,
audioSamplingRate,
AUDIO_FORMAT_PCM_16_BIT,
audioChannels == 2 ? AUDIO_CHANNEL_IN_STEREO : AUDIO_CHANNEL_IN_MONO,
#if SCR_SDK_VERSION >= 23
String16("com.iwobanas.screenrecorder.pro"),
#endif // SCR_SDK_VERSION >= 23
0,
#if SCR_SDK_VERSION < 17
(AudioRecord::record_flags) 0,
#endif // SCR_SDK_VERSION < 17
&staticAudioRecordCallback,
this);
err = audioRecord->initCheck();
if (err != NO_ERROR) {
stop(250, "audioRecord->initCheck() failed");
return;
}
err = audioRecord->start();
if (err != NO_ERROR) {
stop(237, "Can't start audio source");
}
audioRecordStarted = true;
}
static void staticAudioRecordCallback(int event, void* user, void *info) {
FFmpegOutput *output = (FFmpegOutput*)user;
output->audioRecordCallback(event, info);
}
void FFmpegOutput::audioRecordCallback(int event, void *info) {
if (event != 0) return;
AudioRecord::Buffer *buffer = (AudioRecord::Buffer*) info;
pthread_mutex_lock(&inSamplesMutex);
for (unsigned int i = 0; i < buffer->frameCount * audioChannels; i++) {
inSamples[inSamplesEnd++] = (float)buffer->i16[i] / 32769.0;
inSamplesEnd %= inSamplesSize;
if (inSamplesEnd == inSamplesStart) {
ALOGE("SCR audio buffer overrun");
//TODO: handle overrun
}
}
pthread_mutex_unlock(&inSamplesMutex);
}
inline int FFmpegOutput::availableSamplesCount() {
return ((inSamplesSize + inSamplesEnd - inSamplesStart) % inSamplesSize) / audioChannels;
}
void FFmpegOutput::getAudioFrame()
{
int samplesWritten = 0;
pthread_mutex_lock(&inSamplesMutex);
while (samplesWritten < audioFrameSize && availableSamplesCount() > 0) {
outSamples[samplesWritten] = inSamples[inSamplesStart++];
inSamplesStart %= inSamplesSize;
if (audioChannels == 2) {
outSamples[audioFrameSize + samplesWritten] = inSamples[inSamplesStart++];
inSamplesStart %= inSamplesSize;
}
samplesWritten++;
}
pthread_mutex_unlock(&inSamplesMutex);
}
void FFmpegOutput::writeAudioFrame() {
AVCodecContext *c;
AVPacket pkt;
AVFrame *frame = avcodec_alloc_frame();
int pktReceived, ret;
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
c = audioStream->codec;
getAudioFrame();
frame->nb_samples = audioFrameSize;
frame->pts = sampleCount;
sampleCount += audioFrameSize;
avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt, (uint8_t *)outSamples,
audioFrameSize * av_get_bytes_per_sample(c->sample_fmt) * c->channels, 1);
ret = avcodec_encode_audio2(c, &pkt, frame, &pktReceived);
if (ret < 0) {
stop(238, "Error encoding audio frame");
}
if (pktReceived) {
pkt.stream_index = audioStream->index;
pthread_mutex_lock(&outputWriteMutex);
/* Write the compressed frame to the media file. */
ret = av_interleaved_write_frame(oc, &pkt);
pthread_mutex_unlock(&outputWriteMutex);
if (ret != 0) {
stop(246, "Error while writing audio frame");
}
}
avcodec_free_frame(&frame);
av_free_packet(&pkt);
}
void FFmpegOutput::writeVideoFrame() {
pthread_mutex_lock(&frameEncMutex);
videoFrame = frames[frameCount % 2];
//fprintf(stderr, "Populate frame %d\n", (videoFrame == frames[0]) ? 0 : 1);fflush(stderr);
int64_t ptsMs = getTimeMs() - startTimeMs;
videoFrame->pts = av_rescale_q(ptsMs, (AVRational){1,1000}, videoStream->time_base);
if (inputBase != NULL) {
if (rotateView) {
copyRotateYUVBuf(videoFrame->data, (uint8_t*)inputBase, videoFrame->linesize);
} else {
copyYUVBuf(videoFrame->data, (uint8_t*)inputBase, videoFrame->linesize);
}
}
//fprintf(stderr, "Frame ready %d\n", (videoFrame == frames[0]) ? 0 : 1);fflush(stderr);
pthread_mutex_unlock(&frameReadyMutex);
}
void* FFmpegOutput::encodingThreadStart(void* args) {
FFmpegOutput *output = static_cast<FFmpegOutput*>(args);
while (1) {
pthread_mutex_lock(&output->frameReadyMutex);
if (!mrRunning) {
break;
}
AVFrame *f = output->videoFrame;
pthread_mutex_unlock(&output->frameEncMutex);
//fprintf(stderr, "Encode frame %d\n", (f == frames[0]) ? 0 : 1);fflush(stderr);
output->encodeAndSaveVideoFrame(f);
//fprintf(stderr, "Frame encoded %d\n", (f == frames[0]) ? 0 : 1);fflush(stderr);
}
pthread_exit(NULL);
return NULL;
}
void FFmpegOutput::encodeAndSaveVideoFrame(AVFrame *frame) {
int ret, pktReceived;
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
/* encode the image */
ret = avcodec_encode_video2(videoStream->codec, &pkt, frame, &pktReceived);
if (ret < 0) {
stop(239, "Error encoding video frame");
}
if (pktReceived) {
//fprintf(stderr, "VIDEO frame %3d (size=%5d)\n", frameCount, pkt.size);
if (videoStream->codec->coded_frame->key_frame)
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.stream_index = videoStream->index;
pthread_mutex_lock(&outputWriteMutex);
/* Write the compressed frame to the media file. */
ret = av_interleaved_write_frame(oc, &pkt);
pthread_mutex_unlock(&outputWriteMutex);
if (ret != 0) {
stop(240, "Error while writing video frame");
}
}
av_free_packet(&pkt);
}
void FFmpegOutput::renderFrame() {
updateInput();
writeVideoFrame();
while (audioSource != SCR_AUDIO_MUTE && availableSamplesCount() >= audioFrameSize) {
writeAudioFrame();
}
}
void FFmpegOutput::closeOutput(bool fromMainThread) {
ALOGV("Closing FFmpeg output %d", fromMainThread);
if (mrRunning) {
mrRunning = false;
pthread_mutex_unlock(&frameReadyMutex);
pthread_join(encodingThread, NULL);
}
if (oc) {
if (oc->pb) {
ALOGV("Writing trailer");
av_write_trailer(oc);
avio_close(oc->pb);
}
if (videoStream) {
ALOGV("streams and codecs cleanup");
avcodec_close(videoStream->codec);
}
/* The process will terminate soon anyway we don't bother freeing this
as it requires checking what's allocated to avoid SIGSEGV
av_freep(&frames[0]->data[0]);
avcodec_free_frame(&frames[0]);
av_freep(&frames[1]->data[0]);
avcodec_free_frame(&frames[1]); */
/* free the stream */
avformat_free_context(oc);
}
if (audioRecordStarted) {
ALOGV("Stopping audio");
audioRecord->stop();
// don't free audioRecord as the destructor causes SIGSEGV on many devices
}
ALOGV("FFmpeg output closed");
}
void FFmpegOutput::copyRotateYUVBuf(uint8_t** yuvPixels, uint8_t* screen, int* stride) {
for (int x = paddingWidth; x < videoWidth - paddingWidth; x++) {
for (int y = videoHeight - paddingHeight - 1; y >= paddingHeight; y--) {
int idx = ((x - paddingWidth) * inputStride + videoHeight - paddingHeight - y - 1) * 4;
uint8_t r,g,b;
if (useBGRA) {
b = screen[idx];
g = screen[idx + 1];
r = screen[idx + 2];
} else {
r = screen[idx];
g = screen[idx + 1];
b = screen[idx + 2];
}
uint16_t Y = ( ( 66 * r + 129 * g + 25 * b + 128) >> 8) + 16;
yuvPixels[0][y * stride[0] + x] = Y;
if (y % 2 == 0 && x % 2 == 0) {
uint16_t U = ( ( -38 * r - 74 * g + 112 * b + 128) >> 8) + 128;
uint16_t V = ( ( 112 * r - 94 * g - 18 * b + 128) >> 8) + 128;
yuvPixels[1][y * stride[1] / 2 + x / 2 ] = U;
yuvPixels[2][y * stride[2] / 2 + x / 2 ] = V;
}
}
}
}
void FFmpegOutput::copyYUVBuf(uint8_t** yuvPixels, uint8_t* screen, int* stride) {
for (int y = paddingHeight; y < videoHeight - paddingHeight; y++) {
for (int x = paddingWidth; x < videoWidth - paddingWidth; x++) {
int idx = ((y - paddingHeight) * inputStride + x - paddingWidth) * 4;
uint8_t r,g,b;
if (useBGRA) {
b = screen[idx];
g = screen[idx + 1];
r = screen[idx + 2];
} else {
r = screen[idx];
g = screen[idx + 1];
b = screen[idx + 2];
}
uint16_t Y = ( ( 66 * r + 129 * g + 25 * b + 128) >> 8) + 16;
yuvPixels[0][y * stride[0] + x] = Y;
if (y % 2 == 0 && x % 2 == 0) {
uint16_t U = ( ( -38 * r - 74 * g + 112 * b + 128) >> 8) + 128;
uint16_t V = ( ( 112 * r - 94 * g - 18 * b + 128) >> 8) + 128;
yuvPixels[1][y * stride[1] / 2 + x / 2 ] = U;
yuvPixels[2][y * stride[2] / 2 + x / 2 ] = V;
}
}
}
}
| 30.82265 | 102 | 0.589185 | [
"3d"
] |
253d4e2c08d7685107382cdd3c82da3c1a34b9a7 | 5,015 | cpp | C++ | src/main/util/common.cpp | sykhro/vgmtrans-qt | 6d0780bdaaac29ffe118b9be2e2ad87401b426fe | [
"Zlib"
] | 18 | 2018-01-04T17:42:15.000Z | 2021-05-26T02:52:22.000Z | src/main/util/common.cpp | sykhro/vgmtrans-qt | 6d0780bdaaac29ffe118b9be2e2ad87401b426fe | [
"Zlib"
] | 6 | 2017-10-19T16:47:19.000Z | 2021-09-10T15:26:24.000Z | src/main/util/common.cpp | sykhro/vgmtrans-qt | 6d0780bdaaac29ffe118b9be2e2ad87401b426fe | [
"Zlib"
] | 1 | 2017-10-19T16:40:12.000Z | 2017-10-19T16:40:12.000Z | /*
* VGMTrans (c) 2002-2019
* Licensed under the zlib license,
* refer to the included LICENSE.txt file
*/
#include "common.h"
#include <string>
#include <cstring>
#include <array>
#include <gsl-lite.hpp>
#define ZLIB_CONST
#include <zlib.h>
std::string removeExtFromPath(const std::string &s) {
size_t i = s.rfind('.', s.length());
if (i != std::string::npos) {
return (s.substr(0, i));
}
return s;
}
std::string StringToUpper(std::string myString) {
const size_t length = myString.length();
for (size_t i = 0; i != length; ++i) {
myString[i] = toupper(myString[i]);
}
return myString;
}
std::string StringToLower(std::string myString) {
const size_t length = myString.length();
for (size_t i = 0; i != length; ++i) {
myString[i] = tolower(myString[i]);
}
return myString;
}
uint32_t StringToHex(const std::string &str) {
uint32_t value;
std::stringstream convert(str);
convert >> std::hex >> value; // read seq_table as hexadecimal value
return value;
}
std::string ConvertToSafeFileName(const std::string &str) {
std::string filename;
filename.reserve(str.length());
const char *forbiddenChars = "\\/:,;*?\"<>|";
size_t pos_begin = 0;
size_t pos_end;
while ((pos_end = str.find_first_of(forbiddenChars, pos_begin)) != std::string::npos) {
filename += str.substr(pos_begin, pos_end - pos_begin);
if (filename[filename.length() - 1] != L' ') {
filename += " ";
}
pos_begin = pos_end + 1;
}
filename += str.substr(pos_begin);
// right trim
filename.erase(filename.find_last_not_of(" \n\r\t") + 1);
return filename;
}
char *GetFileWithBase(const char *f, const char *newfile) {
static char *ret;
char *tp1;
#if PSS_STYLE == 1
tp1 = ((char *)strrchr(f, '/'));
#else
tp1 = ((char *)std::strrchr(f, '\\'));
#if PSS_STYLE != 3
{
char *tp3;
tp3 = ((char *)std::strrchr(f, '/'));
if (tp1 < tp3)
tp1 = tp3;
}
#endif
#endif
if (!tp1) {
ret = (char *)malloc(strlen(newfile) + 1);
strcpy(ret, newfile);
} else {
ret = (char *)malloc((tp1 - f + 2 + strlen(newfile)) * sizeof(char)); // 1(NULL), 1(/).
memcpy(ret, f, (tp1 - f) * sizeof(char));
ret[tp1 - f] = L'/';
ret[tp1 - f + 1] = 0;
strcpy(ret, newfile);
}
return (ret);
}
std::vector<char> zdecompress(gsl::span<const char> src) {
std::vector<char> result;
/* allocate inflate state */
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
int ret = inflateInit(&strm);
if (ret != Z_OK) {
throw std::runtime_error("Failed to init decompression");
}
strm.avail_in = src.size();
strm.next_in = reinterpret_cast<z_const Bytef *>(src.data());
unsigned actual_size = 0;
constexpr int CHUNK = 4096;
std::array<char, CHUNK> out;
do {
strm.avail_out = CHUNK;
strm.next_out = reinterpret_cast<Bytef *>(out.data());
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR);
switch (ret) {
case Z_NEED_DICT:
[[fallthrough]];
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
throw std::runtime_error("Decompression failed");
}
actual_size = CHUNK - strm.avail_out;
result.insert(result.end(), out.begin(), out.begin() + actual_size);
} while (strm.avail_out == 0);
assert(ret == Z_STREAM_END);
(void)inflateEnd(&strm);
return result;
}
std::vector<char> zdecompress(std::vector<char> &src) {
std::vector<char> result;
/* allocate inflate state */
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
int ret = inflateInit(&strm);
if (ret != Z_OK) {
throw std::runtime_error("Failed to init decompression");
}
strm.avail_in = src.size();
strm.next_in = reinterpret_cast<const Bytef *>(src.data());
unsigned actual_size = 0;
constexpr int CHUNK = 4096;
std::array<char, CHUNK> out;
do {
strm.avail_out = CHUNK;
strm.next_out = reinterpret_cast<Bytef *>(out.data());
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR);
switch (ret) {
case Z_NEED_DICT:
[[fallthrough]];
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
throw std::runtime_error("Decompression failed");
}
actual_size = CHUNK - strm.avail_out;
result.insert(result.end(), out.begin(), out.begin() + actual_size);
} while (strm.avail_out == 0);
assert(ret == Z_STREAM_END);
(void)inflateEnd(&strm);
return result;
}
| 25.850515 | 96 | 0.575673 | [
"vector"
] |
85916f728748015fdaaecc25acbdc0693d9c18d2 | 3,039 | cpp | C++ | call-by-cpp/call.cpp | meixiansen/ECO-pytorch | 31a1b8fc9c41351eae3fba7c81a4af4f658d0a40 | [
"BSD-2-Clause"
] | null | null | null | call-by-cpp/call.cpp | meixiansen/ECO-pytorch | 31a1b8fc9c41351eae3fba7c81a4af4f658d0a40 | [
"BSD-2-Clause"
] | null | null | null | call-by-cpp/call.cpp | meixiansen/ECO-pytorch | 31a1b8fc9c41351eae3fba7c81a4af4f658d0a40 | [
"BSD-2-Clause"
] | null | null | null | #include <torch/script.h> // One-stop header.
#include <iostream>
#include <memory>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <ATen/ATen.h>
#include <torch/torch.h>
int main(){
// Deserialize the ScriptModule from a file using torch::jit::load().
std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("../eco_finetune_ucf101.pt");
assert(module != nullptr);
std::cout << "ok\n";
double time1 = static_cast<double>( cv::getTickCount());
// Create a vector of inputs.
const int numSegments = 8;
std::string videoName = "v_ApplyEyeMakeup_g01_c01.avi";
int frameNum = 0;
cv::VideoCapture cap;
cap.open(videoName);
cv::Mat frame;
std::vector<cv::Mat> images;
while (true)
{
cap >> frame;
if (!frame.empty()) {
frameNum++;
cv::resize(frame, frame, cv::Size(frame.cols*0.5, frame.rows*0.5));
images.push_back(frame);
}
else
{
break;
}
}
int step = frameNum / numSegments;
std::vector<torch::jit::IValue> inputs;
float *test = new float[8*3*224*224]();
auto tensor = torch::CPU(torch::kFloat32).tensorFromBlob(test,{8,3,224,224});
for (int i = 0; i < numSegments; i++)
{
cv::Mat image = images[i*step].clone();
cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
cv::Mat img_float;
image.convertTo(img_float, CV_32F, 1);
cv::resize(img_float, img_float, cv::Size(224, 224));
auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, { 224, 224, 3 });
img_tensor = img_tensor.permute({ 2,0,1 });
img_tensor[0] = img_tensor[0].sub_(128).div_(1);
img_tensor[1] = img_tensor[1].sub_(117).div_(1);
img_tensor[2] = img_tensor[2].sub_(104).div_(1);
tensor[i] = img_tensor;
}
auto img_var = torch::autograd::make_variable(tensor, false);
inputs.push_back(img_var);
std::vector<cv::Mat>().swap(images);
// Execute the model and turn its output into a tensor.
module->forward(inputs);
auto out_tensor = module->forward(inputs).toTensor();
//std::cout << out_tensor.slice(/*dim=*/1, /*start=*/0, /*end=*/109) << '\n';
//std::cout <<out_tensor<<std::endl;
std::tuple<torch::Tensor,torch::Tensor> result = out_tensor.sort(-1, true);
torch::Tensor top_scores = std::get<0>(result)[0];
torch::Tensor top_idxs = std::get<1>(result)[0].toType(torch::kInt32);
// Load labels
std::string label_file = "../classInd.txt";
std::ifstream rf(label_file.c_str());
CHECK(rf) << "Unable to open labels file " << label_file;
std::string line;
std::vector<std::string> labels;
while (std::getline(rf, line))
labels.push_back(line);
auto top_scores_a = top_scores.accessor<float,1>();
auto top_idxs_a = top_idxs.accessor<int,1>();
for (int i = 0; i < 5; ++i) {
int idx = top_idxs_a[i];
std::cout << "top-" << i+1 << " label: ";
std::cout <<idx<<" "<<labels[idx] << ", score: " << top_scores_a[i] << std::endl;
}
double time2 = (static_cast<double>( cv::getTickCount()) - time1)/cv::getTickFrequency();
std::cout<<"单次处理:"<< time2 <<"秒"<<std::endl;//输出运行时间
return 0;
}
| 33.395604 | 101 | 0.654821 | [
"vector",
"model"
] |
859eb08f6ef4e0869dfe85da3e4bf3b4c57b8911 | 1,382 | cxx | C++ | test/common_test.cxx | amarps/amaynet | 58d3c3fddfaf410eaf86da5df22773b5cab9c004 | [
"MIT"
] | null | null | null | test/common_test.cxx | amarps/amaynet | 58d3c3fddfaf410eaf86da5df22773b5cab9c004 | [
"MIT"
] | null | null | null | test/common_test.cxx | amarps/amaynet | 58d3c3fddfaf410eaf86da5df22773b5cab9c004 | [
"MIT"
] | null | null | null | #include "common.hxx"
#include <gtest/gtest.h>
TEST(CommonTest, URL_Ttest)
{
// Call to default constructor will return empty object
AMAYNET::URL_T url0;
ASSERT_TRUE(url0.protocol.empty());
ASSERT_TRUE(url0.host.empty());
ASSERT_TRUE(url0.path.empty());
// test url without specifying protocol and path
AMAYNET::URL_T url1("example.com");
ASSERT_EQ(url1.protocol, "80");
ASSERT_EQ(url1.host, "example.com");
ASSERT_EQ(url1.path, "/");
// test http url
AMAYNET::URL_T url2("http://example.com");
ASSERT_EQ(url2.protocol, "80");
ASSERT_EQ(url2.host, "example.com");
ASSERT_EQ(url2.path, "/");
// test http url with path
AMAYNET::URL_T url3("http://example.com/page2.html");
ASSERT_EQ(url3.protocol, "80");
ASSERT_EQ(url3.host, "example.com");
ASSERT_EQ(url3.path, "/page2.html");
// test https url with path
AMAYNET::URL_T url4("https://example.com/page2.html");
ASSERT_EQ(url4.protocol, "443");
ASSERT_EQ(url4.host, "example.com");
ASSERT_EQ(url4.path, "/page2.html");
/** @Note invalid url is accepted at URL_t. i will fix it later.
* for now invalid url is handled by getaddrinfo()
*/
// test url without specifying protocol and path
AMAYNET::URL_T invalid_url("cqwrryc8oyacayy3");
ASSERT_EQ(invalid_url.protocol, "80");
ASSERT_EQ(invalid_url.host, "cqwrryc8oyacayy3");
ASSERT_EQ(invalid_url.path, "/");
}
| 30.711111 | 66 | 0.695369 | [
"object"
] |
85a41b7b3e0dd5a155176ef2f2c2f164411d6ff6 | 2,128 | hpp | C++ | lib/percy/include/percy/tt_utils.hpp | hriener/copycat | caae1899e88ad3726061903d319b97eff7a684b6 | [
"MIT"
] | 2 | 2019-04-25T13:42:09.000Z | 2019-05-17T08:21:45.000Z | lib/percy/include/percy/tt_utils.hpp | hriener/copycat | caae1899e88ad3726061903d319b97eff7a684b6 | [
"MIT"
] | 1 | 2019-06-03T16:43:01.000Z | 2019-06-03T18:28:55.000Z | lib/percy/include/percy/tt_utils.hpp | hriener/copycat | caae1899e88ad3726061903d319b97eff7a684b6 | [
"MIT"
] | 1 | 2019-05-31T10:23:12.000Z | 2019-05-31T10:23:12.000Z | #pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#include <kitty/bit_operations.hpp>
#include <kitty/constructors.hpp>
#include <kitty/dynamic_truth_table.hpp>
#include <kitty/npn.hpp>
#include <kitty/operations.hpp>
#include <kitty/static_truth_table.hpp>
#include <unordered_set>
#pragma GCC diagnostic pop
namespace percy
{
template<typename TT>
static inline bool is_normal(const TT& tt)
{
return !kitty::get_bit(tt, 0);
}
/***************************************************************************
We consider a truth table to be trivial if it is equal to (or the
complement of) a primary input or constant zero.
***************************************************************************/
template<typename TT>
static inline bool is_trivial(const TT& tt)
{
TT tt_check = tt;
if (kitty::is_const0(tt) || kitty::is_const0(~tt)) {
return true;
}
for (auto i = 0; i < tt.num_vars(); i++) {
kitty::create_nth_var(tt_check, i);
if (tt == tt_check || tt == ~tt_check) {
return true;
}
}
return false;
}
template<int nr_in>
static inline std::unordered_set<kitty::static_truth_table<nr_in>, kitty::hash<kitty::static_truth_table<nr_in>>> generate_npn_classes()
{
using truth_table = kitty::static_truth_table<nr_in>;
kitty::dynamic_truth_table map(truth_table::NumBits);
std::transform( map.cbegin(), map.cend(), map.begin(), []( auto word ) { return ~word; } );
std::unordered_set<truth_table, kitty::hash<truth_table>> classes;
int64_t index = 0;
truth_table tt;
while (index != -1) {
kitty::create_from_words( tt, &index, &index + 1 );
const auto res = kitty::exact_npn_canonization( tt, [&map]( const auto& tt ) { kitty::clear_bit( map, *tt.cbegin() ); } );
classes.insert( std::get<0>( res ) );
index = find_first_one_bit( map );
}
return classes;
}
}
| 31.294118 | 140 | 0.56062 | [
"transform"
] |
85aa9ac165d686f3cd162917afb60e9b2449d49f | 2,227 | hpp | C++ | Includes/Core/Math/CG.hpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 216 | 2017-01-25T04:34:30.000Z | 2021-07-15T12:36:06.000Z | Includes/Core/Math/CG.hpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 323 | 2017-01-26T13:53:13.000Z | 2021-07-14T16:03:38.000Z | Includes/Core/Math/CG.hpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 33 | 2017-01-25T05:05:49.000Z | 2021-06-17T17:30:56.000Z | // This code is based on Jet framework.
// Copyright (c) 2018 Doyub Kim
// CubbyFlow is voxel-based fluid simulation engine for computer games.
// Copyright (c) 2020 CubbyFlow Team
// Core Part: Chris Ohk, Junwoo Hwang, Jihong Sin, Seungwoo Yoo
// AI Part: Dongheon Cho, Minseo Kim
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#ifndef CUBBYFLOW_CG_HPP
#define CUBBYFLOW_CG_HPP
#include <Core/Math/BLAS.hpp>
namespace CubbyFlow
{
//!
//! \brief No-op pre-conditioner for conjugate gradient.
//!
//! This pre-conditioner does nothing but simply copies the input vector to the
//! output vector. Thus, it can be considered as an identity matrix.
//!
template <typename BLASType>
struct NullCGPreconditioner final
{
static void Build(const typename BLASType::MatrixType&)
{
// Do nothing
}
void Solve(const typename BLASType::VectorType& b,
typename BLASType::VectorType* x)
{
BLASType::Set(b, x);
}
};
//!
//! \brief Solves conjugate gradient.
//!
template <typename BLASType>
void CG(const typename BLASType::MatrixType& A,
const typename BLASType::VectorType& b,
unsigned int maxNumberOfIterations, double tolerance,
typename BLASType::VectorType* x, typename BLASType::VectorType* r,
typename BLASType::VectorType* d, typename BLASType::VectorType* q,
typename BLASType::VectorType* s, unsigned int* lastNumberOfIterations,
double* lastResidualNorm);
//!
//! \brief Solves pre-conditioned conjugate gradient.
//!
template <typename BLASType, typename PrecondType>
void PCG(const typename BLASType::MatrixType& A,
const typename BLASType::VectorType& b,
unsigned int maxNumberOfIterations, double tolerance, PrecondType* M,
typename BLASType::VectorType* x, typename BLASType::VectorType* r,
typename BLASType::VectorType* d, typename BLASType::VectorType* q,
typename BLASType::VectorType* s, unsigned int* lastNumberOfIterations,
double* lastResidualNorm);
} // namespace CubbyFlow
#include <Core/Math/CG-Impl.hpp>
#endif | 33.742424 | 80 | 0.717557 | [
"vector"
] |
85ac474c201f3c151648d520f704ecf8cf95f452 | 746 | cc | C++ | leet_code/Ugly_Number_II/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | 1 | 2020-04-11T22:04:23.000Z | 2020-04-11T22:04:23.000Z | leet_code/Ugly_Number_II/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | leet_code/Ugly_Number_II/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int nthUglyNumber(int n) {
priority_queue<long long, vector<long long>, greater<long long> > pq;
vector<long long> candidate({2, 3, 5});
unordered_set<long long> exist;
pq.push(1);
exist.insert(1);
int ret = 0;
for (int i = n; i > 0; --i) {
ret = pq.top();
pq.pop();
for_each(candidate.begin(), candidate.end(), [&ret, &exist, &pq](const auto val) {
long long input = val * (long long)ret;
if (exist.find(input) == exist.end()) {
exist.insert(input);
pq.push(input);
}
});
}
return ret;
}
};
| 29.84 | 94 | 0.451743 | [
"vector"
] |
85aee34e2e26b4758690c1a2a5261ce9d574cdb7 | 776 | cc | C++ | leetcode/Array/find_all_numbers_disappeared_in_an_array.cc | LIZHICHAOUNICORN/Toolkits | db45dac4de14402a21be0c40ba8e87b4faeda1b6 | [
"Apache-2.0"
] | null | null | null | leetcode/Array/find_all_numbers_disappeared_in_an_array.cc | LIZHICHAOUNICORN/Toolkits | db45dac4de14402a21be0c40ba8e87b4faeda1b6 | [
"Apache-2.0"
] | null | null | null | leetcode/Array/find_all_numbers_disappeared_in_an_array.cc | LIZHICHAOUNICORN/Toolkits | db45dac4de14402a21be0c40ba8e87b4faeda1b6 | [
"Apache-2.0"
] | null | null | null | // Author: Zhichao Li
// Time: 2021年06月19日
#include <vector>
using std::vector;
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
for (auto& num : nums) {
int x = (num - 1) % n;
nums[x] += n;
}
vector<int> ret;
for (int i = 0; i < n; i++) {
if (nums[i] <= n) {
ret.push_back(i + 1);
}
}
return ret;
}
};
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> mem(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); ++i) {
mem[nums[i]] += 1;
}
vector<int> ret;
for (int j = 1; j < mem.size(); ++j) {
if (mem[j] == 0) {
ret.push_back(j);
}
}
return ret;
}
};
| 18.926829 | 57 | 0.496134 | [
"vector"
] |
85b810fc6bc911832a29bcb2bb7c7bce71fb6125 | 1,484 | hpp | C++ | qipython/pyfuture.hpp | Maelic/libqi-python | d5e250a7ce1b6039bb1f57f750cab51412dfecca | [
"BSD-3-Clause"
] | 7 | 2015-08-12T01:25:11.000Z | 2021-07-15T11:08:34.000Z | qipython/pyfuture.hpp | Maelic/libqi-python | d5e250a7ce1b6039bb1f57f750cab51412dfecca | [
"BSD-3-Clause"
] | 10 | 2015-10-01T11:33:53.000Z | 2022-03-23T10:19:33.000Z | qipython/pyfuture.hpp | Maelic/libqi-python | d5e250a7ce1b6039bb1f57f750cab51412dfecca | [
"BSD-3-Clause"
] | 7 | 2015-02-24T10:38:52.000Z | 2022-03-14T10:18:26.000Z | /*
** Copyright (C) 2020 SoftBank Robotics Europe
** See COPYING for the license
*/
#pragma once
#ifndef QIPYTHON_PYFUTURE_HPP
#define QIPYTHON_PYFUTURE_HPP
#include <qipython/common.hpp>
#include <qipython/pyguard.hpp>
#include <qi/future.hpp>
#include <qi/anyvalue.hpp>
namespace qi
{
namespace py
{
using Future = qi::Future<AnyValue>;
using Promise = qi::Promise<AnyValue>;
// Depending on whether we want an asynchronous result or not, returns the
// future or its value.
inline pybind11::object resultObject(const Future& fut, bool async)
{
pybind11::gil_scoped_acquire lock;
if (async)
return castToPyObject(fut);
// Wait for the future outside of the GIL.
auto res = invokeGuarded<pybind11::gil_scoped_release>(qi::SrcFuture{}, fut);
return castToPyObject(res);
}
inline Future toFuture(qi::Future<void> f)
{
return f.andThen(FutureCallbackType_Sync,
[](void*) { return AnyValue::makeVoid(); });
}
inline Future toFuture(qi::Future<AnyValue> f) { return f; }
inline Future toFuture(qi::Future<AnyReference> f)
{
return f.andThen(FutureCallbackType_Sync,
[](const AnyReference& ref) { return AnyValue(ref); });
}
template<typename T>
inline Future toFuture(qi::Future<T> f)
{
return f.andThen(FutureCallbackType_Sync,
[](const T& val) { return AnyValue::from(val); });
}
void exportFuture(pybind11::module& module);
} // namespace py
} // namespace qi
#endif // QIPYTHON_PYFUTURE_HPP
| 23.555556 | 79 | 0.704178 | [
"object"
] |
85c6124db8817b6fff4a069bfce860e697de41c8 | 45,401 | cc | C++ | atomicz.cc | shawwn/atomicz | c81693fe18bbbeccabbae24019c1f8a2e5596798 | [
"Apache-2.0"
] | null | null | null | atomicz.cc | shawwn/atomicz | c81693fe18bbbeccabbae24019c1f8a2e5596798 | [
"Apache-2.0"
] | null | null | null | atomicz.cc | shawwn/atomicz | c81693fe18bbbeccabbae24019c1f8a2e5596798 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 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.
==============================================================================*/
/* Modified by martin.croome@greenwaves-technologies.com - Modifications to allow a standalone build
and remove requirements for pybind11 and other tensorflow dependencies
Add support for scalar operations and python numeric types
*/
#include <iostream>
#include <array>
#include <locale>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
// #define DEBUG_CALLS
#include <Python.h>
#include <cinttypes>
#include <vector>
#include <atomic>
#ifdef DEBUG_CALLS
#include <iostream>
#endif
#include <fenv.h>
namespace greenwaves
{
// Initializes the module.
bool Initialize()
{
bool ok = true;
return ok;
}
static PyObject *AtomiczError;
template<typename T>
void store(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
static_cast<std::atomic<T>*>(ptr)->store(val, order);
}
template<typename T>
T load(const void* ptr, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<const std::atomic<T>*>(ptr)->load(order);
}
template<typename T>
T exchange(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<std::atomic<T>*>(ptr)->exchange(val, order);
}
template<typename T>
T compare_exchange(void* ptr, T* expected, const T desired, std::memory_order succ = std::memory_order_seq_cst, std::memory_order fail = std::memory_order_seq_cst)
{
return std::atomic_compare_exchange_strong_explicit(static_cast<std::atomic<T>*>(ptr), expected, desired, succ, fail);
}
template<typename T>
T fetch_add(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<std::atomic<T>*>(ptr)->fetch_add(val, order);
}
template<typename T>
T fetch_sub(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<std::atomic<T>*>(ptr)->fetch_sub(val, order);
}
template<typename T>
T fetch_or(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<std::atomic<T>*>(ptr)->fetch_or(val, order);
}
template<typename T>
T fetch_xor(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<std::atomic<T>*>(ptr)->fetch_xor(val, order);
}
template<typename T>
T fetch_and(void* ptr, const T val, std::memory_order order = std::memory_order_seq_cst)
{
return static_cast<std::atomic<T>*>(ptr)->fetch_and(val, order);
}
void do_store(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return store<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return store<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return store<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return store<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only exchange 1, 2, 4, or 8 bytes\n");
return;
}
}
unsigned long long do_load(const void *source_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return load<unsigned char>(source_p);
case 2: return load<unsigned short>(source_p);
case 4: return load<unsigned int>(source_p);
case 8: return load<unsigned long long>(source_p);
default:
fprintf(stderr, "Can only exchange 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_exchange(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return exchange<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return exchange<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return exchange<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return exchange<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only exchange 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_compare_exchange(const void *desired_p, void* expected_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return compare_exchange<unsigned char>(sink_p, reinterpret_cast<unsigned char*>(expected_p), *reinterpret_cast<const unsigned char*>(desired_p));
case 2: return compare_exchange<unsigned short>(sink_p, reinterpret_cast<unsigned short*>(expected_p), *reinterpret_cast<const unsigned short*>(desired_p));
case 4: return compare_exchange<unsigned int>(sink_p, reinterpret_cast<unsigned int*>(expected_p), *reinterpret_cast<const unsigned int*>(desired_p));
case 8: return compare_exchange<unsigned long long>(sink_p, reinterpret_cast<unsigned long long*>(expected_p), *reinterpret_cast<const unsigned long long*>(desired_p));
default:
fprintf(stderr, "Can only compare_exchange 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_fetch_add(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return fetch_add<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return fetch_add<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return fetch_add<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return fetch_add<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only fetch_add 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_fetch_sub(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return fetch_sub<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return fetch_sub<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return fetch_sub<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return fetch_sub<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only fetch_sub 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_fetch_or(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return fetch_or<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return fetch_or<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return fetch_or<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return fetch_or<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only fetch_or 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_fetch_xor(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return fetch_xor<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return fetch_xor<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return fetch_xor<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return fetch_xor<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only fetch_xor 1, 2, 4, or 8 bytes\n");
return 0;
}
}
unsigned long long do_fetch_and(const void *source_p, void *sink_p, unsigned long long nbytes)
{
switch(nbytes) {
case 1: return fetch_and<unsigned char>(sink_p, *reinterpret_cast<const unsigned char*>(source_p));
case 2: return fetch_and<unsigned short>(sink_p, *reinterpret_cast<const unsigned short*>(source_p));
case 4: return fetch_and<unsigned int>(sink_p, *reinterpret_cast<const unsigned int*>(source_p));
case 8: return fetch_and<unsigned long long>(sink_p, *reinterpret_cast<const unsigned long long*>(source_p));
default:
fprintf(stderr, "Can only fetch_and 1, 2, 4, or 8 bytes\n");
return 0;
}
}
static PyObject *
load_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
int got_source_view = 0;
/* read the args */
PyObject *obj_source;
do {
if (!PyArg_ParseTuple(args, "O", &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
/* get the element count */
for (i = 0; i < source_view.ndim; i++) {
nelems *= source_view.shape[i];
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
switch (source_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only load itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_load(source_view.buf, source_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
store_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only store itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
do_store(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return Py_BuildValue("");
}
}
static PyObject *
exchange_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only exchange itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_exchange(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
compare_exchange_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer desired_view;
Py_buffer expected_view;
Py_buffer sink_view;
int got_desired_view = 0;
int got_expected_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_desired;
PyObject *obj_expected;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OOO", &obj_sink, &obj_expected, &obj_desired)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_desired)) {
PyErr_SetString(AtomiczError,
"the desired object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_expected)) {
PyErr_SetString(AtomiczError,
"the expected object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_desired, &desired_view, flags) < 0) {
except = 1; break;
} else {
got_desired_view = 1;
}
if (PyObject_GetBuffer(obj_expected, &expected_view, flags) < 0) {
except = 1; break;
} else {
got_expected_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,expected_view.ndim) != std::max(1,sink_view.ndim) || std::max(1,desired_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the expected, desired and sink buffers should be the same rank, got expected.ndim == %d, desired.ndim == %d, and sink.ndim == %d", expected_view.ndim, desired_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < desired_view.ndim; i++) {
if (expected_view.shape[i] != sink_view.shape[i] || desired_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the expected, desired, and sink buffers should be the same shape");
except = 1; break;
}
nelems *= desired_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (expected_view.itemsize != sink_view.itemsize || desired_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the expected, desired, and sink buffers should be the same itemsize, got expected.itemsize == %llu, desired.itemsize == %llu, and sink.itemsize == %llu", (unsigned long long)&expected_view.itemsize, (unsigned long long)desired_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (expected_view.buf == NULL) {
PyErr_SetString(AtomiczError, "expected buffer is NULL");
except = 1; break;
}
if (desired_view.buf == NULL) {
PyErr_SetString(AtomiczError, "desired buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
if (expected_view.readonly) {
PyErr_SetString(AtomiczError, "expected buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only compare_exchange sink itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
switch (expected_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only compare_exchange expected itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_compare_exchange(desired_view.buf, expected_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_desired_view) {
PyBuffer_Release(&desired_view);
}
if (got_expected_view) {
PyBuffer_Release(&expected_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
fetch_add_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only fetch_add itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_fetch_add(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
fetch_sub_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only fetch_sub itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_fetch_sub(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
fetch_or_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only fetch_or itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_fetch_or(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
fetch_xor_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only fetch_xor itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_fetch_xor(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyObject *
fetch_and_python (PyObject *self, PyObject *args)
{
int i;
unsigned long long ret = 0;
unsigned long long nelems = 1;
int except = 0;
/* buffer views */
Py_buffer source_view;
Py_buffer sink_view;
int got_source_view = 0;
int got_sink_view = 0;
/* read the args */
PyObject *obj_source;
PyObject *obj_sink;
do {
if (!PyArg_ParseTuple(args, "OO", &obj_sink, &obj_source)) {
except = 1; break;
}
/* both objects should support the buffer interface */
if (!PyObject_CheckBuffer(obj_source)) {
PyErr_SetString(AtomiczError,
"the source object does not support the buffer interface");
except = 1; break;
}
if (!PyObject_CheckBuffer(obj_sink)) {
PyErr_SetString(AtomiczError,
"the sink object does not support the buffer interface");
except = 1; break;
}
/* get the buffer view for each object */
int flags = PyBUF_ND | PyBUF_FORMAT | PyBUF_C_CONTIGUOUS | PyBUF_WRITABLE;
if (PyObject_GetBuffer(obj_source, &source_view, flags) < 0) {
except = 1; break;
} else {
got_source_view = 1;
}
if (PyObject_GetBuffer(obj_sink, &sink_view, flags) < 0) {
except = 1; break;
} else {
got_sink_view = 1;
}
/* the buffers should be the same rank */
if (std::max(1,source_view.ndim) != std::max(1,sink_view.ndim)) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same rank, got source.ndim == %d and sink.ndim == %d", source_view.ndim, sink_view.ndim);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* the buffers should be the same shape */
for (i = 0; i < source_view.ndim; i++) {
if (source_view.shape[i] != sink_view.shape[i]) {
PyErr_SetString(AtomiczError,
"the source and sink buffers should be the same shape");
except = 1; break;
}
nelems *= source_view.shape[i];
}
if (except) {
break;
}
/* the buffers should be the itemsize */
if (source_view.itemsize != sink_view.itemsize) {
char msg[4096];
snprintf(msg, sizeof(msg), "the source and sink buffers should be the same itemsize, got source.itemsize == %llu and sink.itemsize == %llu", (unsigned long long)source_view.itemsize, (unsigned long long)sink_view.itemsize);
PyErr_SetString(AtomiczError, msg);
except = 1; break;
}
/* buffers should be non-null */
if (source_view.buf == NULL) {
PyErr_SetString(AtomiczError, "source buffer is NULL");
except = 1; break;
}
if (sink_view.buf == NULL) {
PyErr_SetString(AtomiczError, "sink buffer is NULL");
except = 1; break;
}
/* buffers should point to exactly one item */
if (nelems != 1) {
PyErr_SetString(AtomiczError, "total element count must be 1, i.e. max(1,product(shape)) == 1");
except = 1; break;
}
if (sink_view.readonly) {
PyErr_SetString(AtomiczError, "sink buffer is readonly");
except = 1; break;
}
switch (sink_view.itemsize)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
PyErr_SetString(AtomiczError, "can only fetch_and itemsize of 1, 2, 4, or 8");
except = 1;
break;
}
if (except) break;
ret = do_fetch_and(source_view.buf, sink_view.buf, sink_view.itemsize);
} while(0);
//end:
/* clean up the buffer views */
if (got_source_view) {
PyBuffer_Release(&source_view);
}
if (got_sink_view) {
PyBuffer_Release(&sink_view);
}
/* return an appropriate value */
if (except) {
return NULL;
} else {
return PyLong_FromLong(ret);
}
}
static PyMethodDef AtomiczModuleMethods[] = {
{"load", load_python, METH_VARARGS,
"std::atomic::load from C++'s <atomic> library"},
{"store", store_python, METH_VARARGS,
"std::atomic::store from C++'s <atomic> library"},
{"exchange", exchange_python, METH_VARARGS,
"std::atomic::exchange from C++'s <atomic> library"},
{"compare_exchange", compare_exchange_python, METH_VARARGS,
"std::atomic_compare_exchange_strong from C++'s <atomic> library"},
{"fetch_add", fetch_add_python, METH_VARARGS,
"std::atomic::fetch_add from C++'s <atomic> library"},
{"fetch_sub", fetch_sub_python, METH_VARARGS,
"std::atomic::fetch_sub from C++'s <atomic> library"},
{"fetch_or", fetch_or_python, METH_VARARGS,
"std::atomic::fetch_or from C++'s <atomic> library"},
{"fetch_xor", fetch_xor_python, METH_VARARGS,
"std::atomic::fetch_xor from C++'s <atomic> library"},
{"fetch_and", fetch_and_python, METH_VARARGS,
"std::atomic::fetch_and from C++'s <atomic> library"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef AtomiczModule = {
PyModuleDef_HEAD_INIT,
"numpy_atomicz",
NULL,
-1,
AtomiczModuleMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_atomicz(void)
{
PyObject *m;
m = PyModule_Create(&AtomiczModule);
if (m == NULL)
return NULL;
AtomiczError = PyErr_NewException("atomicz.error", NULL, NULL);
Py_INCREF(AtomiczError);
PyModule_AddObject(m, "error", AtomiczError);
#if 0
RegisterNumpyAtomicz();
Py_INCREF(&atomicz_type);
Py_XINCREF(&NPyAtomicz_Descr);
if (PyModule_AddObject(m, "atomicz", AtomiczDtype()) < 0)
{
Py_DECREF(&atomicz_type);
Py_DECREF(m);
return NULL;
}
#endif
return m;
}
} // namespace greenwaves
| 34.342663 | 318 | 0.619788 | [
"object",
"shape",
"vector"
] |
85c671fffdbd7af4f55263fb15bb2a660fd8f789 | 1,353 | cpp | C++ | OpenGL_S/OpenGL_S/Button.cpp | CreoDen-dev/COSMO | 1603c734fc592dad58b553625e5ce90046d99758 | [
"Apache-2.0"
] | null | null | null | OpenGL_S/OpenGL_S/Button.cpp | CreoDen-dev/COSMO | 1603c734fc592dad58b553625e5ce90046d99758 | [
"Apache-2.0"
] | null | null | null | OpenGL_S/OpenGL_S/Button.cpp | CreoDen-dev/COSMO | 1603c734fc592dad58b553625e5ce90046d99758 | [
"Apache-2.0"
] | null | null | null | #include "Button.h"
Button::Button() {
}
Button::Button(vec2 pos, vec2 size, ButtonType type) {
this->pos = pos;
this->size = size;
if (type == START) {
this->texture = HUDElement("resources/textures/button_START.png", pos, size, vec4(1, 2, 0, 0));
}
if (type == QUIT) {
this->texture = HUDElement("resources/textures/button_QUIT.png", pos, size, vec4(1, 2, 0, 0));
}
if (type == RESUME) {
this->texture = HUDElement("resources/textures/button_RESUME.png", pos, size, vec4(1, 2, 0, 0));
}
if (type == MENU) {
this->texture = HUDElement("resources/textures/button_MENU.png", pos, size, vec4(1, 2, 0, 0));
}
if (type == PREV) {
this->texture = HUDElement("resources/textures/button_NEXT.png", pos + vec2(size.x, 0), vec2(-size.x, size.y), vec4(1, 2, 0, 0));
}
if (type == NEXT) {
this->texture = HUDElement("resources/textures/button_NEXT.png", pos, size, vec4(1, 2, 0, 0));
}
}
GLboolean Button::update(Shader & shader) {
if (Input::mousePosNormalized.x > this->pos.x && Input::mousePosNormalized.y > this->pos.y && Input::mousePosNormalized.x < (this->pos + this->size).x && Input::mousePosNormalized.y < (this->pos + this->size).y) {
this->texture.offset2(vec2(0, 0.5f));
this->texture.render(shader);
return true;
}
else {
this->texture.offset2(vec2(0, 0));
this->texture.render(shader);
return false;
}
}
| 33 | 214 | 0.648189 | [
"render"
] |
85c6dfcf345e2d34d32f3c9b974a6ccd0a8e2985 | 712 | cpp | C++ | 438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp | AmrutanshuDash/LeetCode-Run | 07a4b552eadc528fb9346cfc5c6462239e3da467 | [
"Apache-2.0"
] | 1 | 2021-10-31T13:57:03.000Z | 2021-10-31T13:57:03.000Z | 438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp | AmrutanshuDash/LeetCode-Run | 07a4b552eadc528fb9346cfc5c6462239e3da467 | [
"Apache-2.0"
] | null | null | null | 438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.cpp | AmrutanshuDash/LeetCode-Run | 07a4b552eadc528fb9346cfc5c6462239e3da467 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int len_s = s.size();
int len_p = p.size();
if(len_s < len_p) return {};
vector<int> p_freq(26,0);
vector<int> window(26,0);
//first window
for(int i=0;i<len_p;i++){
p_freq[p[i]-'a']++;
window[s[i]-'a']++;
}
vector<int> ans;
if(p_freq == window) ans.push_back(0);
for(int i=len_p;i<len_s;i++){
window[s[i-len_p] - 'a']--;
window[s[i] - 'a']++;
if(p_freq == window) ans.push_back(i-len_p+1);
}
return ans;
}
}; | 24.551724 | 58 | 0.422753 | [
"vector"
] |
85dcb76712f6aab654bbe2327466603406f5f725 | 15,294 | cpp | C++ | src/test/model_cache_test.cpp | IntelAI/OpenVINO-model-server | 281cffcc358013afcec0d810331acc66c18297f7 | [
"Apache-2.0"
] | 305 | 2018-10-01T12:41:28.000Z | 2020-04-24T10:36:08.000Z | src/test/model_cache_test.cpp | IntelAI/OpenVINO-model-server | 281cffcc358013afcec0d810331acc66c18297f7 | [
"Apache-2.0"
] | 61 | 2018-11-15T09:23:01.000Z | 2020-04-23T09:29:56.000Z | src/test/model_cache_test.cpp | IntelAI/OpenVINO-model-server | 281cffcc358013afcec0d810331acc66c18297f7 | [
"Apache-2.0"
] | 67 | 2018-10-13T14:33:48.000Z | 2020-04-22T19:01:32.000Z | //*****************************************************************************
// Copyright 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <filesystem>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "../modelconfig.hpp"
#include "../modelmanager.hpp"
#include "test_utils.hpp"
using namespace ovms;
class ModelCacheTest : public TestWithTempDir {
protected:
void SetUp() override {
TestWithTempDir::SetUp();
modelCacheDirectory = this->directoryPath;
dummyModelConfigWithCache = DUMMY_MODEL_CONFIG;
dummyModelConfigWithCache.setCacheDir(modelCacheDirectory);
dummyModelConfigWithCache.setBatchSize(std::nullopt);
imageModelConfigWithCache = INCREMENT_1x3x4x5_MODEL_CONFIG;
imageModelConfigWithCache.setCacheDir(modelCacheDirectory);
imageModelConfigWithCache.setBatchSize(std::nullopt);
}
size_t getCachedFileCount() {
auto it = std::filesystem::directory_iterator(this->directoryPath);
return std::count_if(std::filesystem::begin(it), std::filesystem::end(it), [](auto& entry) { return entry.is_regular_file(); });
}
void prepareDummyCachedRun() {
ModelConfig config = dummyModelConfigWithCache;
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
}
void prepareImageModelCachedRun() {
ModelConfig config = imageModelConfigWithCache;
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
}
std::string modelCacheDirectory;
ModelConfig dummyModelConfigWithCache;
ModelConfig imageModelConfigWithCache;
};
// This test imitates reloading configuration at service runtime.
TEST_F(ModelCacheTest, FlowTestOnlineModifications) {
ModelConfig config = dummyModelConfigWithCache;
ASSERT_EQ(config.parseShapeParameter("(1,10)"), StatusCode::OK);
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
// Check if cache files were created.
size_t currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, 0);
// Reload dummy with no change.
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK);
// Check that no cache files were created.
ASSERT_EQ(this->getCachedFileCount(), currentCacheFileCount);
// Restart manager with cache directory specified.
// Load dummy model with changed shape.
ModelConfig config_1x100 = dummyModelConfigWithCache;
ASSERT_EQ(config_1x100.parseShapeParameter("(1,100)"), StatusCode::OK);
ASSERT_EQ(manager->reloadModelWithVersions(config_1x100), StatusCode::OK_RELOADED);
// Check if new cache files were created.
size_t previousCacheFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, previousCacheFileCount);
// Start manager with cache directory specified.
// Load dummy model with initial shape.
config = dummyModelConfigWithCache;
ASSERT_EQ(config.parseShapeParameter("(1,10)"), StatusCode::OK);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
// TODO: Uncomment once bug is resolved.
// https://jira.devtools.intel.com/browse/CVS-68254
// Check below is disabled due to OpenVINO bug.
// OpenVINO caches 2 similar models even though underlying network is the same.
// 1. Model with no reshape operation executed
// 2. Model with reshape operation executed to original shape value.
// Therefore new cache files are created when we fall back to original (1,10) shape.
// // Check if no new cache file was created.
// previousCacheFileCount = currentCacheFileCount;
// currentCacheFileCount = this->getCachedFileCount();
// ASSERT_EQ(currentCacheFileCount, previousCacheFileCount);
}
// This test imitates restarting the service.
TEST_F(ModelCacheTest, FlowTestOfflineModifications) {
ModelConfig config = DUMMY_MODEL_CONFIG;
// Start manager with no cache directory specified.
auto manager = std::make_unique<ConstructorEnabledModelManager>();
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
// Check if no cache files were created.
ASSERT_EQ(this->getCachedFileCount(), 0);
manager.reset();
// Start manager with cache directory specified.
manager.reset(new ConstructorEnabledModelManager(modelCacheDirectory));
config = dummyModelConfigWithCache;
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
// Check if any cache file was created.
size_t currentCacheFileCount = this->getCachedFileCount();
ASSERT_GE(currentCacheFileCount, 1);
manager.reset();
// Restart manager with cache directory specified.
manager.reset(new ConstructorEnabledModelManager(modelCacheDirectory));
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
// Check if no cache file was created.
ASSERT_EQ(this->getCachedFileCount(), currentCacheFileCount);
manager.reset();
// Restart manager with cache directory specified.
// Load dummy model with changed shape.
ModelConfig config_1x100 = dummyModelConfigWithCache;
ASSERT_EQ(config_1x100.parseShapeParameter("(1,100)"), StatusCode::OK);
manager.reset(new ConstructorEnabledModelManager(modelCacheDirectory));
ASSERT_EQ(manager->reloadModelWithVersions(config_1x100), StatusCode::OK_RELOADED);
// Check if new cache files were created.
size_t previousCacheFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, previousCacheFileCount);
// Start manager with cache directory specified.
// Load dummy model with initial shape.
manager.reset(new ConstructorEnabledModelManager(modelCacheDirectory));
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
// Check if no new cache file was created.
previousCacheFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_EQ(currentCacheFileCount, previousCacheFileCount);
}
TEST_F(ModelCacheTest, BatchSizeChangeImpactsCache) {
this->prepareDummyCachedRun();
size_t currentCacheFileCount = this->getCachedFileCount();
ModelConfig config = dummyModelConfigWithCache;
config.setBatchSize(5);
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
size_t lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, lastCachedFileCount);
manager.reset();
manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_EQ(currentCacheFileCount, lastCachedFileCount);
}
TEST_F(ModelCacheTest, ShapeChangeImpactsCache) {
this->prepareDummyCachedRun();
size_t currentCacheFileCount = this->getCachedFileCount();
ModelConfig config = dummyModelConfigWithCache;
config.setBatchSize(std::nullopt);
config.parseShapeParameter("(1,100)");
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
size_t lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, lastCachedFileCount);
manager.reset();
manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_EQ(currentCacheFileCount, lastCachedFileCount);
}
TEST_F(ModelCacheTest, NireqChangeDoesNotImpactCache) {
this->prepareDummyCachedRun();
size_t currentCacheFileCount = this->getCachedFileCount();
ModelConfig config = dummyModelConfigWithCache;
config.setNireq(12);
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
ASSERT_EQ(this->getCachedFileCount(), currentCacheFileCount);
}
TEST_F(ModelCacheTest, LayoutChangeDoesImpactCache) {
this->prepareImageModelCachedRun();
size_t currentCacheFileCount = this->getCachedFileCount();
ModelConfig config = imageModelConfigWithCache;
config.parseLayoutParameter("nhwc:nchw");
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
size_t lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, lastCachedFileCount);
manager.reset();
manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_EQ(currentCacheFileCount, lastCachedFileCount);
}
TEST_F(ModelCacheTest, PluginConfigChangeDoesImpactCache) {
this->prepareImageModelCachedRun();
size_t currentCacheFileCount = this->getCachedFileCount();
ModelConfig config = imageModelConfigWithCache;
config.setPluginConfig({{"CPU_THROUGHPUT_STREAMS", "21"}});
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
size_t lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_GT(currentCacheFileCount, lastCachedFileCount);
manager.reset();
manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_EQ(currentCacheFileCount, lastCachedFileCount);
}
TEST_F(ModelCacheTest, CacheDisabledModelConfig) {
this->prepareDummyCachedRun();
size_t currentCacheFileCount = this->getCachedFileCount();
ModelConfig config = dummyModelConfigWithCache;
config.setBatchSize(ovms::Mode::AUTO);
auto manager = std::make_unique<ConstructorEnabledModelManager>(modelCacheDirectory);
ASSERT_EQ(manager->reloadModelWithVersions(config), StatusCode::OK_RELOADED);
size_t lastCachedFileCount = currentCacheFileCount;
currentCacheFileCount = this->getCachedFileCount();
ASSERT_EQ(currentCacheFileCount, lastCachedFileCount);
}
class TestModelCacheSetting : public TestWithTempDir {
protected:
std::unique_ptr<ov::Core> ieCore;
void SetUp() override {
TestWithTempDir::SetUp();
ieCore = std::make_unique<ov::Core>();
modelCacheDirectory = this->directoryPath;
config = DUMMY_MODEL_CONFIG;
config.setCacheDir(modelCacheDirectory);
config.setBatchSize(std::nullopt);
}
ovms::ModelConfig config;
std::string modelCacheDirectory;
};
TEST_F(TestModelCacheSetting, CacheNotDisabledWithDefaultConfig) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.setCacheDir("");
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_FALSE(modelInstance.isCacheDisabled());
}
TEST_F(TestModelCacheSetting, CacheDisabledWithCustomLoader) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.addCustomLoaderOption("test", "loader");
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_TRUE(modelInstance.isCacheDisabled());
config.setAllowCache(false);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_TRUE(modelInstance.isCacheDisabled());
}
TEST_F(TestModelCacheSetting, CacheDisabledWithBatchAuto) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.setBatchingMode(ovms::Mode::AUTO);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_TRUE(modelInstance.isCacheDisabled());
config.setAllowCache(false);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_TRUE(modelInstance.isCacheDisabled());
}
TEST_F(TestModelCacheSetting, CacheDisabledWithAnyShapeAuto) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.parseShapeParameter("auto");
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_TRUE(modelInstance.isCacheDisabled());
config.setAllowCache(false);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_TRUE(modelInstance.isCacheDisabled());
}
TEST_F(TestModelCacheSetting, CacheCannotBeEnabledWithCustomLoader) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.addCustomLoaderOption("test", "loader");
config.setAllowCache(true);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::ALLOW_CACHE_WITH_CUSTOM_LOADER);
}
TEST_F(TestModelCacheSetting, CacheCanBeEnabledWithBatchAuto) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.setBatchingMode(ovms::Mode::AUTO);
config.setAllowCache(true);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_FALSE(modelInstance.isCacheDisabled());
}
TEST_F(TestModelCacheSetting, CacheCanBeEnabledWithAnyShapeAuto) {
ovms::ModelInstance modelInstance("UNUSED_NAME", UNUSED_MODEL_VERSION, *ieCore);
config.parseShapeParameter("auto");
config.setAllowCache(true);
EXPECT_EQ(modelInstance.setCacheOptions(config), ovms::StatusCode::OK);
EXPECT_FALSE(modelInstance.isCacheDisabled());
}
| 42.132231 | 136 | 0.760233 | [
"shape",
"model"
] |
85dcee9c6e7e6815fb6d79bb9c3c19fa20c361d9 | 12,240 | cpp | C++ | ZEngine/src/Common/System.cpp | AarnoldGad/ZucchiniEngine | cb27d2a534a3f21ec59eaa116f052a169a811c06 | [
"Zlib"
] | 1 | 2020-12-04T17:56:22.000Z | 2020-12-04T17:56:22.000Z | ZEngine/src/Common/System.cpp | AarnoldGad/ZEngine | cb27d2a534a3f21ec59eaa116f052a169a811c06 | [
"Zlib"
] | 1 | 2022-02-02T23:24:34.000Z | 2022-02-02T23:24:34.000Z | ZEngine/src/Common/System.cpp | AarnoldGad/ZucchiniEngine | cb27d2a534a3f21ec59eaa116f052a169a811c06 | [
"Zlib"
] | null | null | null | // Inspired by https://github.com/ThePhD/infoware
#include "zepch.hpp"
#include "zengine/Common/System.hpp"
#include "zengine/Common/Backtrace/CallStack.hpp"
#include <bitset>
#include <csignal>
#include <cstdlib>
#if defined(_WIN32)
#include <lmcons.h>
#elif defined(__linux__)
#include <unistd.h>
#elif defined(__MACH__) || defined(__APPLE__)
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <mach/vm_statistics.h>
#include <mach/mach.h>
#endif
#include "zengine/Memory/New.hpp"
namespace ze
{
namespace
{
std::string GetSystemName()
{
std::string name;
#if defined(_WIN32)
name.resize(MAX_COMPUTERNAME_LENGTH + 1); // TODO Not sure about this +1
DWORD x = MAX_COMPUTERNAME_LENGTH;
GetComputerNameA(&name[0], &x);
#else
const size_t hostNameSize = static_cast<size_t>(sysconf(_SC_HOST_NAME_MAX)) + 1;
name.resize(hostNameSize);
if (gethostname(&name[0], hostNameSize)) return "";
#endif
return name;
}
std::string GetSystemUserName()
{
#if defined(_WIN32)
std::string name;
name.resize(UNLEN + 1); // TODO Not sure about this +1
DWORD x = UNLEN;
GetUserNameA(&name[0], &x);
return name;
#else
std::string name;
size_t loginNameSize = static_cast<size_t>(sysconf(_SC_LOGIN_NAME_MAX)) + 1;
name.resize(loginNameSize);
if (getlogin_r(&name[0], loginNameSize)) return "";
return name;
#endif
}
std::string GetKernelName()
{
#if defined(_WIN32)
return "Windows";
#else
utsname sysInfo;
uname(&sysInfo);
return sysInfo.sysname;
#endif
}
System::OS::Version GetKernelVersion()
{
#if defined(_WIN32)
// return "\"Windows is a mess to get the version (and you don't even care), gfy\"";
std::string path;
path.resize(GetSystemDirectoryA(nullptr, 0) - 1);
GetSystemDirectoryA(&path[0], static_cast<uint32_t>(path.size() + 1));
path += "\\kernel32.dll";
uint32_t const verBufSize = GetFileVersionInfoSizeA(path.c_str(), nullptr);
auto verBuf = std::make_unique<uint8_t[]>(verBufSize);
GetFileVersionInfoA(path.c_str(), 0, verBufSize, verBuf.get());
VS_FIXEDFILEINFO* version;
uint32_t verSize;
VerQueryValueA(verBuf.get(), "", reinterpret_cast<void**>(&version), &verSize);
return { HIWORD(version->dwProductVersionMS), LOWORD(version->dwProductVersionMS), HIWORD(version->dwProductVersionLS), LOWORD(version->dwProductVersionLS) };
#else
utsname sysInfo;
uname(&sysInfo);
System::OS::Version version;
char* cursor = sysInfo.release;
version.major = static_cast<uint32_t>(std::strtoul(cursor, &cursor, 10));
version.minor = static_cast<uint32_t>(std::strtoul(cursor + 1, &cursor, 10));
version.patch = static_cast<uint32_t>(std::strtoul(cursor + 1, &cursor, 10));
version.rev = static_cast<uint32_t>(std::strtoul(cursor + 1, nullptr, 10));
return version;
#endif
}
std::string GetSystemVersionName([[maybe_unused]] System::OS::Version version)
{
#if defined(_WIN32)
std::stringstream ss;
ss << "v" << version.major << "." << version.minor << "." << version.patch << " rev" << version.rev;
return ss.str();
#else
utsname sysInfo;
uname(&sysInfo);
return sysInfo.release;
#endif
}
Architecture GetSystemArchitecture()
{
#if defined(_WIN32)
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
switch (sysInfo.wProcessorArchitecture)
{
case PROCESSOR_ARCHITECTURE_INTEL:
return Architecture::x86;
case PROCESSOR_ARCHITECTURE_AMD64:
return Architecture::x64;
case PROCESSOR_ARCHITECTURE_ARM:
return Architecture::ARM;
case PROCESSOR_ARCHITECTURE_ARM64:
return Architecture::ARM64;
case PROCESSOR_ARCHITECTURE_IA64:
return Architecture::IA64;
default:
return Architecture::Unknown;
}
#else
utsname sysInfo;
uname(&sysInfo);
if (!strcmp(sysInfo.machine, "i686") ||
!strcmp(sysInfo.machine, "i386"))
return Architecture::x86;
else if (!strcmp(sysInfo.machine, "x86_64"))
return Architecture::x64;
else if (!strcmp(sysInfo.machine, "arm") ||
!strcmp(sysInfo.machine, "armv7l"))
return Architecture::ARM;
else if (!strcmp(sysInfo.machine, "aarch64") ||
!strcmp(sysInfo.machine, "armv8l") ||
!strcmp(sysInfo.machine, "arm64"))
return Architecture::ARM64;
else if (!strcmp(sysInfo.machine, "ia64"))
return Architecture::IA64;
else
return Architecture::Unknown;
#endif
}
Endianess GetSystemEndianess()
{
union
{
uint32_t a;
char b[4];
} c = { 0x01020304 }; // I have absolutely no idea what names I could give to these things
return c.b[0] == 1 ? Endianess::Big : Endianess::Little;
}
Processor::Cores GetCPUCores()
{
#if defined(_WIN32)
std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> infoList;
DWORD size = 0;
GetLogicalProcessorInformation(nullptr, &size);
infoList.resize(size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
GetLogicalProcessorInformation(infoList.data(), &size);
uint32_t physic = 0;
uint32_t logic = 0;
for (auto&& info : infoList)
{
switch (info.Relationship)
{
case RelationProcessorCore:
++physic;
logic += static_cast<uint32_t>(std::bitset<sizeof(uint64_t) * 8>(info.ProcessorMask).count());
break;
default:
break;
}
}
return { physic, logic };
#elsif defined(__linux__)
std::ifstream cpuinfo("/proc/cpuinfo");
if (!cpuinfo) return {};
uint32_t physic = 0;
uint32_t logic = static_cast<uint32_t>(sysconf(_SC_NPROCESSORS_ONLN));
for (std::string line; std::getline(cpuinfo, line);)
{
if (line.find("cpu cores") != std::string::npos) // TODO Test on other unix platforms
{
physic = static_cast<uint32_t>(std::strtoul(line.c_str() + line.find_first_of("0123456789"), nullptr, 10));
break;
}
}
return { physic, logic };
#elif defined(__MACH__) || defined(__APPLE__)
int physic = 0, logic = 0;
size_t length = sizeof(int);
sysctlbyname("machdep.cpu.core_count", &physic, &length, nullptr, 0);
sysctlbyname("machdep.cpu.thread_count", &logic, &length, nullptr, 0);
return { static_cast<uint32_t>(physic), static_cast<uint32_t>(logic) };
#endif
}
std::string GetCPUModel()
{
#if defined(_WIN32)
HKEY hkey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, R"(HARDWARE\DESCRIPTION\System\CentralProcessor\0)", 0, KEY_READ, &hkey))
return {};
char model[64];
DWORD size = sizeof(model);
if (RegQueryValueExA(hkey, "ProcessorNameString", nullptr, nullptr, static_cast<LPBYTE>(static_cast<void*>(&model[0])), &size))
return {};
return model;
#elif defined(__linux__)
std::ifstream cpuinfo("/proc/cpuinfo");
if (!cpuinfo) return {};
std::string model;
for (std::string line; std::getline(cpuinfo, line);)
{
if (line.find("model name") != std::string::npos)
{
model = line.substr(line.find(":") + 1); // TODO Test on other unix platforms
break;
}
}
return model;
#elif defined(__APPLE__) || defined(__MACH__)
char name[64];
size_t namelen = sizeof(name);
sysctlbyname("machdep.cpu.brand_string", &name, &namelen, nullptr, 0);
return name;
#endif
}
}
void (*SetSignalHandler(StdSignal signal, void (*handler)(int)))(int)
{
return std::signal(static_cast<int>(signal), handler);
}
int CallAtExit(void (*fn)(void))
{
return std::atexit(fn);
}
[[noreturn]] void RaiseCritical(int code, char const* description) noexcept
{
LOG_TRACE(description);
std::exit(code);
}
System GetSystemInfo()
{
System sysInfo{};
sysInfo.systemName = GetSystemName();
sysInfo.userName = GetSystemUserName();
sysInfo.os.name = GetKernelName();
sysInfo.os.version = GetKernelVersion();
sysInfo.os.versionString = GetSystemVersionName(sysInfo.os.version);
return sysInfo;
}
Processor GetProcessorInfo()
{
Processor cpuInfo{};
cpuInfo.arch = GetSystemArchitecture();
cpuInfo.endian = GetSystemEndianess();
cpuInfo.cores = GetCPUCores();
cpuInfo.model = GetCPUModel();
return cpuInfo;
}
Memory GetMemoryInfo()
{
#if defined(_WIN32)
Memory memoryInfo{};
MEMORYSTATUSEX memStat;
memStat.dwLength = sizeof(memStat);
GlobalMemoryStatusEx(&memStat);
memoryInfo.total = memStat.ullTotalPhys;
memoryInfo.available = memStat.ullAvailPhys;
memoryInfo.used = memStat.ullTotalPhys - memStat.ullAvailPhys;
return memoryInfo;
#elif defined(__linux__)
Memory memoryInfo{};
std::ifstream meminfo("/proc/meminfo");
if (!meminfo) return {};
for (std::string line; std::getline(meminfo, line);)
{
if (line.find("MemTotal") != std::string::npos)
memoryInfo.total = std::strtoul(line.c_str() + line.find_first_of("0123456789"), nullptr, 10);
if (line.find("MemAvailable") != std::string::npos)
memoryInfo.available= std::strtoul(line.c_str() + line.find_first_of("0123456789"), nullptr, 10);
}
memoryInfo.used = memoryInfo.total - memoryInfo.available;
return memoryInfo;
#elif defined(__MACH__) || defined(__APPLE__)
uint64_t total = 0, available = 0;
size_t length = sizeof(uint64_t);
vm_statistics64 stats;
natural_t count = HOST_VM_INFO64_COUNT;
mach_port_t host = mach_host_self();
sysctlbyname("hw.memsize", &total, &length, nullptr, 0);
host_statistics64(host, HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&stats), &count);
available = stats.free_count * static_cast<unsigned>(getpagesize());
return { total, available, total - available };
#endif
}
std::string ArchToString(Architecture arch)
{
switch (arch)
{
case Architecture::x64:
return "x64";
case Architecture::x86:
return "x86";
case Architecture::ARM:
return "ARM";
case Architecture::ARM64:
return "ARM64";
case Architecture::IA64:
return "IA64";
case Architecture::Unknown:
default:
return "UNKNOWN";
}
}
}
| 28.465116 | 170 | 0.552369 | [
"vector",
"model"
] |
85e2d8b2e28b410a3224da515c88517a2481a183 | 257 | cpp | C++ | dataset/test/1624A/14.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/1624A/14.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/1624A/14.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{int t;
cin>>t;
while(t--)
{int n;
cin>>n;vector<int>v;int k;
for(int i=0;i<n;i++)
{cin>>k;v.push_back(k);}
sort(v.begin(),v.end());
cout<<v[n-1]-v[0]<<"\n";
}
} | 12.85 | 27 | 0.490272 | [
"vector"
] |
85e3230ee74a2c0f2867bd2156330a805e735614 | 255 | cpp | C++ | LeetCode/C++/0239._Sliding_Window_Maximum/example.cpp | icgw/LeetCode | cb70ca87aa4604d1aec83d4224b3489eacebba75 | [
"MIT"
] | 4 | 2018-09-12T09:32:17.000Z | 2018-12-06T03:17:38.000Z | LeetCode/C++/0239._Sliding_Window_Maximum/example.cpp | icgw/algorithm | cb70ca87aa4604d1aec83d4224b3489eacebba75 | [
"MIT"
] | null | null | null | LeetCode/C++/0239._Sliding_Window_Maximum/example.cpp | icgw/algorithm | cb70ca87aa4604d1aec83d4224b3489eacebba75 | [
"MIT"
] | null | null | null | #include <iostream>
#include "solution.hpp"
void run_example() {
Solution s;
vector<int> nums { 1, 3, -1, -3, 5, 3, 6, 7 };
vector<int> ans = s.maxSlidingWindow(nums, 3);
for (auto n : ans) std::cout << n << " ";
std::cout << "\n";
}
| 23.181818 | 50 | 0.545098 | [
"vector"
] |
85eea172d79299c5bfbd49cfc99383b524f0c733 | 29,018 | cpp | C++ | request/datesCalendarsRequest.cpp | thulio/quantraserver | 07dd319fcdefd052db9bc7c0979c7e583b47a546 | [
"BSD-3-Clause"
] | 7 | 2018-01-06T12:44:58.000Z | 2020-09-22T10:35:04.000Z | request/datesCalendarsRequest.cpp | thulio/quantraserver | 07dd319fcdefd052db9bc7c0979c7e583b47a546 | [
"BSD-3-Clause"
] | 2 | 2020-05-10T14:29:27.000Z | 2020-12-09T01:34:00.000Z | request/datesCalendarsRequest.cpp | thulio/quantraserver | 07dd319fcdefd052db9bc7c0979c7e583b47a546 | [
"BSD-3-Clause"
] | 7 | 2018-01-05T16:04:37.000Z | 2021-07-17T05:48:05.000Z | //
// Created by Josep Rubio on 7/19/17.
//
#include "datesCalendarsRequest.h"
void datesCalendarsRequest::isLeapYear(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
bool isLeap = false;
QuantraParser parser("Is Leap", errorLog);
try {
int year;
tmpBool = parser.qGetInt(d, "Year", &year, true);
if (!tmpBool) {
isLeap = Date::isLeap(year);
}
}catch (Error re) {
tmpBool = true;
erroros << "IsLeap: " << re.what();
CROW_LOG_DEBUG << "IsLeap: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["message"]["IsLeap"]= isLeap;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::endOfMonth(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
Date endOfMonth;
QuantraParser parser("Is Leap", errorLog);
try {
Date date;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
if (!tmpBool) {
endOfMonth = Date::endOfMonth(date);
}
}catch (Error re) {
tmpBool = true;
erroros << "IsLeap: " << re.what();
CROW_LOG_DEBUG << "IsLeap: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
std::ostringstream os;
os << QuantLib::io::iso_date(endOfMonth);
(*response)["response"] = "ok";
(*response)["message"]["EndOfMonth"]= os.str();
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::isEndOfMonth(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
bool isEndOfMonth = false;
QuantraParser parser("Is Leap", errorLog);
try {
Date date;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
if (!tmpBool) {
isEndOfMonth = Date::isEndOfMonth(date);
}
}catch (Error re) {
tmpBool = true;
erroros << "IsLeap: " << re.what();
CROW_LOG_DEBUG << "IsLeap: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["message"]["IsEndOfMonth"]= isEndOfMonth;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::nextWeekDay(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
Date nextWeekDay;
Weekday weekday;
QuantraParser parser("Next Week Day", errorLog);
try {
Date date;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
tmpBool = tmpBool || parser.qGetWeekDay(d, "Weekday", &weekday, true);
if (!tmpBool) {
nextWeekDay = Date::nextWeekday(date, weekday);
}
}catch (Error re) {
tmpBool = true;
erroros << "NextWeekDay: " << re.what();
CROW_LOG_DEBUG << "NextWeekDay: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
std::ostringstream os;
os << QuantLib::io::iso_date(nextWeekDay);
(*response)["response"] = "ok";
(*response)["message"]["NextWeekDay"]= os.str();
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::nthWeekDay(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
int nth;
Weekday weekday;
Month m;
Year y;
Date date;
QuantraParser parser("Nth Week Day", errorLog);
try {
tmpBool = parser.qGetInt(d, "Nth", &nth, true);
tmpBool = tmpBool || parser.qGetWeekDay(d, "Weekday", &weekday, true);
tmpBool = tmpBool || parser.qGetMonth(d, "Month", &m, true);
tmpBool = tmpBool ||parser.qGetInt(d, "Year", &y, true);
if (!tmpBool) {
date = Date::nthWeekday(nth, weekday, m, y);
}
}catch (Error re) {
tmpBool = true;
erroros << "nthWeekDay: " << re.what();
CROW_LOG_DEBUG << "nthWeekDay: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
std::ostringstream os;
os << QuantLib::io::iso_date(date);
(*response)["response"] = "ok";
(*response)["message"]["NthWeekDay"]= os.str();
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::isBusinessDay(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
bool isBusinessDate = false;
QuantraParser parser("Is Business Day", errorLog);
try {
Date date;
Calendar calendar;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
tmpBool = tmpBool || parser.qGetCalendar(d, "Calendar", &calendar, true);
if (!tmpBool) {
isBusinessDate = calendar.isBusinessDay(date);
}
}catch (Error re) {
tmpBool = true;
erroros << "IsBusinessDay: " << re.what();
CROW_LOG_DEBUG << "IsBusinessDay: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["message"]["IsBusinessDay"]= isBusinessDate;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::isHoliday(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
bool isBusinessDate = false;
QuantraParser parser("Is Holiday", errorLog);
try {
Date date;
Calendar calendar;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
tmpBool = tmpBool || parser.qGetCalendar(d, "Calendar", &calendar, true);
if (!tmpBool) {
isBusinessDate = calendar.isHoliday(date);
}
}catch (Error re) {
tmpBool = true;
erroros << "IsHoliday: " << re.what();
CROW_LOG_DEBUG << "IsHoliday: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["message"]["IsHoliday"]= isBusinessDate;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::holidayList(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
std::vector<Date> holidayList;
QuantraParser parser("HolidayList", errorLog);
try {
Date from;
Date to;
bool includeWeekends;
Calendar calendar;
tmpBool = parser.qGetRawDate(d, "From", &from, true);
tmpBool = parser.qGetRawDate(d, "To", &to, true);
tmpBool = parser.qBool(d, "IncludeWeekends", &includeWeekends, true);
tmpBool = tmpBool || parser.qGetCalendar(d, "Calendar", &calendar, true);
if (!tmpBool) {
holidayList = Calendar::holidayList(calendar, from, to, includeWeekends);
}
}catch (Error re) {
tmpBool = true;
erroros << "HolidayList: " << re.what();
CROW_LOG_DEBUG << "HolidayList: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
std::ostringstream os;
for (int i = 0; i < holidayList.size(); i++) {
os << QuantLib::io::iso_date(holidayList[i]);
(*response)["message"]["HolidayList"][i] = os.str();
os.str("");
os.clear();
}
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::adjust(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
Date adjustedDate;
QuantraParser parser("AdjustDate", errorLog);
try {
Date date;
Calendar calendar;
BusinessDayConvention convention;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
tmpBool = tmpBool || parser.qGetCalendar(d, "Calendar", &calendar, true);
tmpBool = tmpBool || parser.qGetConvention(d, "Convention", &convention, true);
if (!tmpBool) {
adjustedDate = calendar.adjust(date, convention);
}
}catch (Error re) {
tmpBool = true;
erroros << "AdjustDate: " << re.what();
CROW_LOG_DEBUG << "AdjustDate: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
std::ostringstream os;
os << QuantLib::io::iso_date(adjustedDate);
(*response)["response"] = "ok";
(*response)["message"]["AdjustedDate"]= os.str();
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::advance(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
Date adjustedDate;
QuantraParser parser("AdvancedDate", errorLog);
try {
Date date;
Calendar calendar;
BusinessDayConvention convention;
Integer n;
TimeUnit unit;
bool endOfMonth;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
tmpBool = tmpBool || parser.qGetCalendar(d, "Calendar", &calendar, true);
tmpBool = tmpBool || parser.qGetConvention(d, "Convention", &convention, true);
tmpBool = tmpBool || parser.qGetInt(d, "Number", &n, true);
tmpBool = tmpBool || parser.qTimeUnit(d, "TimeUnit", &unit, true);
tmpBool = tmpBool || parser.qBool(d, "EndOfMonth", &endOfMonth, true);
if (!tmpBool) {
adjustedDate = calendar.advance(date,n,unit,convention,endOfMonth);
}
}catch (Error re) {
tmpBool = true;
erroros << "AdvancedDate: " << re.what();
CROW_LOG_DEBUG << "AdvancedDate: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
std::ostringstream os;
os << QuantLib::io::iso_date(adjustedDate);
(*response)["response"] = "ok";
(*response)["message"]["AdvancedDate"]= os.str();
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::businessDaysBetween(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
int daysBetween;
QuantraParser parser("BusinessDaysBetween", errorLog);
try {
Date from;
Date to;
bool includeFirst;
bool includeLast;
Calendar calendar;
tmpBool = parser.qGetRawDate(d, "From", &from, true);
tmpBool = tmpBool || parser.qGetRawDate(d, "To", &to, true);
tmpBool = tmpBool || parser.qBool(d, "IncludeFirst", &includeFirst, true);
tmpBool = tmpBool || parser.qBool(d, "IncludeLast", &includeLast, true);
tmpBool = tmpBool || parser.qGetCalendar(d, "Calendar", &calendar, true);
if (!tmpBool) {
daysBetween = calendar.businessDaysBetween(from,to,includeFirst,includeLast);
}
}catch (Error re) {
tmpBool = true;
erroros << "BusinessDaysBetween: " << re.what();
CROW_LOG_DEBUG << "BusinessDaysBetween: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["response"] = "ok";
(*response)["message"]["BusinessDaysBetween"]= daysBetween;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::isIMMdate(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
bool isIMMdate = false;
QuantraParser parser("IsIMMdate", errorLog);
try {
Date date;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
if (!tmpBool) {
isIMMdate = IMM::isIMMdate(date,true);
}
}catch (Error re) {
tmpBool = true;
erroros << "IsIMMdate: " << re.what();
CROW_LOG_DEBUG << "IsIMMdate: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["message"]["IsIMMdate"]= isIMMdate;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::nextIMMdate(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
Date IMMdate;
QuantraParser parser("nextIMMdate", errorLog);
try {
Date date;
tmpBool = parser.qGetRawDate(d, "Date", &date, true);
if (!tmpBool) {
IMMdate = IMM::nextDate(date,true);
}
}catch (Error re) {
tmpBool = true;
erroros << "nextIMMdate: " << re.what();
CROW_LOG_DEBUG << "nextIMMdate: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
std::ostringstream os;
os << QuantLib::io::iso_date(IMMdate);
(*response)["response"] = "ok";
(*response)["message"]["NextIMMdate"]= os.str();
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
}
void datesCalendarsRequest::yearFraction(crow::request req, boost::shared_ptr<crow::json::wvalue> response) {
auto x = crow::json::load(req.body);
bool error = false;
bool tmpBool = false;
std::ostringstream erroros;
(*response)["response"] = "ok";
std::vector<std::string> *errorLog = new std::vector<std::string>();
/*Temporary to solve "{\"\"}" issue*/
if(req.body.at(0) == '"'){
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = "Wrong format";
return;
}
Document d;
ParseResult ok = d.Parse(req.body.c_str());
if (!ok) {
fprintf(stderr, "JSON parse error: %s (%u)",
GetParseError_En(ok.Code()), ok.Offset());
erroros << "JSON parse error: " << GetParseError_En(ok.Code()) << " " << ok.Offset();
(*response)["response"] = "ko";
(*response)["message"]["Errors"] = erroros.str();
return;
}
Time fraction;
QuantraParser parser("yearFraction", errorLog);
try {
Date startDate;
Date endDate;
DayCounter dayCounter;
tmpBool = parser.qGetRawDate(d, "StartDate", &startDate, true);
tmpBool = tmpBool || parser.qGetRawDate(d, "EndDate", &endDate, true);
tmpBool = tmpBool || parser.qGetDayCounter(d, "DayCounter", &dayCounter, true);
if (!tmpBool) {
fraction = dayCounter.yearFraction(startDate, endDate);
}
}catch (Error re) {
tmpBool = true;
erroros << "yearFraction: " << re.what();
CROW_LOG_DEBUG << "yearFraction: " << re.what();
errorLog->push_back(erroros.str());
erroros.str("");
erroros.clear();
}
if(!tmpBool){
(*response)["response"] = "ok";
(*response)["message"]["YearFraction"]= fraction;
}else{
(*response)["response"] = "ko";
int i = 0;
for (std::vector<string>::iterator it = errorLog->begin(); it != errorLog->end(); ++it) {
(*response)["message"]["Errors"][i] = *it;
i++;
}
}
} | 26.025112 | 116 | 0.5326 | [
"vector"
] |
85ef37d99b14264a7e5b760769bd8e3e26cd29b8 | 76,526 | cpp | C++ | llvm/lib/Target/R600/SIISelLowering.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 58 | 2016-08-27T03:19:14.000Z | 2022-01-05T17:33:44.000Z | llvm/lib/Target/R600/SIISelLowering.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 14 | 2017-12-01T17:16:59.000Z | 2020-12-21T12:16:35.000Z | llvm/lib/Target/R600/SIISelLowering.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 22 | 2016-11-27T09:53:31.000Z | 2021-11-22T00:22:53.000Z | //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// \brief Custom DAG lowering for SI
//
//===----------------------------------------------------------------------===//
#ifdef _MSC_VER
// Provide M_PI.
#define _USE_MATH_DEFINES
#include <cmath>
#endif
#include "SIISelLowering.h"
#include "AMDGPU.h"
#include "AMDGPUIntrinsicInfo.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "SIMachineFunctionInfo.h"
#include "SIRegisterInfo.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/IR/Function.h"
#include "llvm/ADT/SmallString.h"
using namespace llvm;
SITargetLowering::SITargetLowering(TargetMachine &TM) :
AMDGPUTargetLowering(TM) {
addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
computeRegisterProperties();
// Condition Codes
setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
setOperationAction(ISD::ADD, MVT::i32, Legal);
setOperationAction(ISD::ADDC, MVT::i32, Legal);
setOperationAction(ISD::ADDE, MVT::i32, Legal);
setOperationAction(ISD::SUBC, MVT::i32, Legal);
setOperationAction(ISD::SUBE, MVT::i32, Legal);
setOperationAction(ISD::FSIN, MVT::f32, Custom);
setOperationAction(ISD::FCOS, MVT::f32, Custom);
setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
// We need to custom lower vector stores from local memory
setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
setOperationAction(ISD::STORE, MVT::v8i32, Custom);
setOperationAction(ISD::STORE, MVT::v16i32, Custom);
setOperationAction(ISD::STORE, MVT::i1, Custom);
setOperationAction(ISD::STORE, MVT::i32, Custom);
setOperationAction(ISD::STORE, MVT::v2i32, Custom);
setOperationAction(ISD::STORE, MVT::v4i32, Custom);
setOperationAction(ISD::SELECT, MVT::f32, Promote);
AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
setOperationAction(ISD::SELECT, MVT::i64, Custom);
setOperationAction(ISD::SELECT, MVT::f64, Promote);
AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
setOperationAction(ISD::BSWAP, MVT::i32, Legal);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
setOperationAction(ISD::BRCOND, MVT::Other, Custom);
setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
setTruncStoreAction(MVT::i32, MVT::i8, Custom);
setTruncStoreAction(MVT::i32, MVT::i16, Custom);
setTruncStoreAction(MVT::f64, MVT::f32, Expand);
setTruncStoreAction(MVT::i64, MVT::i32, Expand);
setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
setOperationAction(ISD::LOAD, MVT::i1, Custom);
setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
// These should use UDIVREM, so set them to expand
setOperationAction(ISD::UDIV, MVT::i64, Expand);
setOperationAction(ISD::UREM, MVT::i64, Expand);
// We only support LOAD/STORE and vector manipulation ops for vectors
// with > 4 elements.
MVT VecTypes[] = {
MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
};
setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
setOperationAction(ISD::SELECT, MVT::i1, Promote);
for (MVT VT : VecTypes) {
for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
switch(Op) {
case ISD::LOAD:
case ISD::STORE:
case ISD::BUILD_VECTOR:
case ISD::BITCAST:
case ISD::EXTRACT_VECTOR_ELT:
case ISD::INSERT_VECTOR_ELT:
case ISD::INSERT_SUBVECTOR:
case ISD::EXTRACT_SUBVECTOR:
break;
case ISD::CONCAT_VECTORS:
setOperationAction(Op, VT, Custom);
break;
default:
setOperationAction(Op, VT, Expand);
break;
}
}
}
for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
setOperationAction(ISD::FTRUNC, VT, Expand);
setOperationAction(ISD::FCEIL, VT, Expand);
setOperationAction(ISD::FFLOOR, VT, Expand);
}
if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
setOperationAction(ISD::FCEIL, MVT::f64, Legal);
setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
setOperationAction(ISD::FRINT, MVT::f64, Legal);
}
setOperationAction(ISD::FDIV, MVT::f32, Custom);
setTargetDAGCombine(ISD::FADD);
setTargetDAGCombine(ISD::FSUB);
setTargetDAGCombine(ISD::FMINNUM);
setTargetDAGCombine(ISD::FMAXNUM);
setTargetDAGCombine(ISD::SELECT_CC);
setTargetDAGCombine(ISD::SETCC);
setTargetDAGCombine(ISD::UINT_TO_FP);
// All memory operations. Some folding on the pointer operand is done to help
// matching the constant offsets in the addressing modes.
setTargetDAGCombine(ISD::LOAD);
setTargetDAGCombine(ISD::STORE);
setTargetDAGCombine(ISD::ATOMIC_LOAD);
setTargetDAGCombine(ISD::ATOMIC_STORE);
setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
setTargetDAGCombine(ISD::ATOMIC_SWAP);
setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
setSchedulingPreference(Sched::RegPressure);
}
//===----------------------------------------------------------------------===//
// TargetLowering queries
//===----------------------------------------------------------------------===//
bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
EVT) const {
// SI has some legal vector types, but no legal vector operations. Say no
// shuffles are legal in order to prefer scalarizing some vector operations.
return false;
}
// FIXME: This really needs an address space argument. The immediate offset
// size is different for different sets of memory instruction sets.
// The single offset DS instructions have a 16-bit unsigned byte offset.
//
// MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
// r + i with addr64. 32-bit has more addressing mode options. Depending on the
// resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
//
// SMRD instructions have an 8-bit, dword offset.
//
bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
Type *Ty) const {
// No global is ever allowed as a base.
if (AM.BaseGV)
return false;
// Allow a 16-bit unsigned immediate field, since this is what DS instructions
// use.
if (!isUInt<16>(AM.BaseOffs))
return false;
// Only support r+r,
switch (AM.Scale) {
case 0: // "r+i" or just "i", depending on HasBaseReg.
break;
case 1:
if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
return false;
// Otherwise we have r+r or r+i.
break;
case 2:
if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
return false;
// Allow 2*r as r+r.
break;
default: // Don't allow n * r
return false;
}
return true;
}
bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
unsigned AddrSpace,
unsigned Align,
bool *IsFast) const {
if (IsFast)
*IsFast = false;
// TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
// which isn't a simple VT.
if (!VT.isSimple() || VT == MVT::Other)
return false;
// XXX - CI changes say "Support for unaligned memory accesses" but I don't
// see what for specifically. The wording everywhere else seems to be the
// same.
// XXX - The only mention I see of this in the ISA manual is for LDS direct
// reads the "byte address and must be dword aligned". Is it also true for the
// normal loads and stores?
if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
// ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
// aligned, 8 byte access in a single operation using ds_read2/write2_b32
// with adjacent offsets.
return Align % 4 == 0;
}
// 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
// byte-address are ignored, thus forcing Dword alignment.
// This applies to private, global, and constant memory.
if (IsFast)
*IsFast = true;
return VT.bitsGT(MVT::i32);
}
EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
unsigned SrcAlign, bool IsMemset,
bool ZeroMemset,
bool MemcpyStrSrc,
MachineFunction &MF) const {
// FIXME: Should account for address space here.
// The default fallback uses the private pointer size as a guess for a type to
// use. Make sure we switch these to 64-bit accesses.
if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
return MVT::v4i32;
if (Size >= 8 && DstAlign >= 4)
return MVT::v2i32;
// Use the default.
return MVT::Other;
}
TargetLoweringBase::LegalizeTypeAction
SITargetLowering::getPreferredVectorAction(EVT VT) const {
if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
return TypeSplitVector;
return TargetLoweringBase::getPreferredVectorAction(VT);
}
bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
Type *Ty) const {
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
return TII->isInlineConstant(Imm);
}
SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
SDLoc SL, SDValue Chain,
unsigned Offset, bool Signed) const {
const DataLayout *DL = getDataLayout();
MachineFunction &MF = DAG.getMachineFunction();
const SIRegisterInfo *TRI =
static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
Type *Ty = VT.getTypeForEVT(*DAG.getContext());
MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
DAG.getConstant(Offset, MVT::i64));
SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
false, // isVolatile
true, // isNonTemporal
true, // isInvariant
DL->getABITypeAlignment(Ty)); // Alignment
}
SDValue SITargetLowering::LowerFormalArguments(
SDValue Chain,
CallingConv::ID CallConv,
bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
SDLoc DL, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const {
const TargetMachine &TM = getTargetMachine();
const SIRegisterInfo *TRI =
static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
MachineFunction &MF = DAG.getMachineFunction();
FunctionType *FType = MF.getFunction()->getFunctionType();
SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
assert(CallConv == CallingConv::C);
SmallVector<ISD::InputArg, 16> Splits;
BitVector Skipped(Ins.size());
for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
const ISD::InputArg &Arg = Ins[i];
// First check if it's a PS input addr
if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
!Arg.Flags.isByVal()) {
assert((PSInputNum <= 15) && "Too many PS inputs!");
if (!Arg.Used) {
// We can savely skip PS inputs
Skipped.set(i);
++PSInputNum;
continue;
}
Info->PSInputAddr |= 1 << PSInputNum++;
}
// Second split vertices into their elements
if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
ISD::InputArg NewArg = Arg;
NewArg.Flags.setSplit();
NewArg.VT = Arg.VT.getVectorElementType();
// We REALLY want the ORIGINAL number of vertex elements here, e.g. a
// three or five element vertex only needs three or five registers,
// NOT four or eigth.
Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
unsigned NumElements = ParamType->getVectorNumElements();
for (unsigned j = 0; j != NumElements; ++j) {
Splits.push_back(NewArg);
NewArg.PartOffset += NewArg.VT.getStoreSize();
}
} else if (Info->getShaderType() != ShaderType::COMPUTE) {
Splits.push_back(Arg);
}
}
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
*DAG.getContext());
// At least one interpolation mode must be enabled or else the GPU will hang.
if (Info->getShaderType() == ShaderType::PIXEL &&
(Info->PSInputAddr & 0x7F) == 0) {
Info->PSInputAddr |= 1;
CCInfo.AllocateReg(AMDGPU::VGPR0);
CCInfo.AllocateReg(AMDGPU::VGPR1);
}
// The pointer to the list of arguments is stored in SGPR0, SGPR1
// The pointer to the scratch buffer is stored in SGPR2, SGPR3
if (Info->getShaderType() == ShaderType::COMPUTE) {
if (Subtarget->isAmdHsaOS())
Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
else
Info->NumUserSGPRs = 4;
unsigned InputPtrReg =
TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
unsigned InputPtrRegLo =
TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
unsigned InputPtrRegHi =
TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
unsigned ScratchPtrReg =
TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
unsigned ScratchPtrRegLo =
TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
unsigned ScratchPtrRegHi =
TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
CCInfo.AllocateReg(InputPtrRegLo);
CCInfo.AllocateReg(InputPtrRegHi);
CCInfo.AllocateReg(ScratchPtrRegLo);
CCInfo.AllocateReg(ScratchPtrRegHi);
MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
}
if (Info->getShaderType() == ShaderType::COMPUTE) {
getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
Splits);
}
AnalyzeFormalArguments(CCInfo, Splits);
for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
const ISD::InputArg &Arg = Ins[i];
if (Skipped[i]) {
InVals.push_back(DAG.getUNDEF(Arg.VT));
continue;
}
CCValAssign &VA = ArgLocs[ArgIdx++];
MVT VT = VA.getLocVT();
if (VA.isMemLoc()) {
VT = Ins[i].VT;
EVT MemVT = Splits[i].VT;
const unsigned Offset = 36 + VA.getLocMemOffset();
// The first 36 bytes of the input buffer contains information about
// thread group and global sizes.
SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
Offset, Ins[i].Flags.isSExt());
const PointerType *ParamTy =
dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
// On SI local pointers are just offsets into LDS, so they are always
// less than 16-bits. On CI and newer they could potentially be
// real pointers, so we can't guarantee their size.
Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
DAG.getValueType(MVT::i16));
}
InVals.push_back(Arg);
Info->ABIArgOffset = Offset + MemVT.getStoreSize();
continue;
}
assert(VA.isRegLoc() && "Parameter must be in a register!");
unsigned Reg = VA.getLocReg();
if (VT == MVT::i64) {
// For now assume it is a pointer
Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
&AMDGPU::SReg_64RegClass);
Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
continue;
}
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
Reg = MF.addLiveIn(Reg, RC);
SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
if (Arg.VT.isVector()) {
// Build a vector from the registers
Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
unsigned NumElements = ParamType->getVectorNumElements();
SmallVector<SDValue, 4> Regs;
Regs.push_back(Val);
for (unsigned j = 1; j != NumElements; ++j) {
Reg = ArgLocs[ArgIdx++].getLocReg();
Reg = MF.addLiveIn(Reg, RC);
Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
}
// Fill up the missing vector elements
NumElements = Arg.VT.getVectorNumElements() - NumElements;
for (unsigned j = 0; j != NumElements; ++j)
Regs.push_back(DAG.getUNDEF(VT));
InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
continue;
}
InVals.push_back(Val);
}
return Chain;
}
MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
MachineInstr * MI, MachineBasicBlock * BB) const {
MachineBasicBlock::iterator I = *MI;
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
switch (MI->getOpcode()) {
default:
return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
case AMDGPU::BRANCH: return BB;
case AMDGPU::V_SUB_F64: {
unsigned DestReg = MI->getOperand(0).getReg();
BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
.addImm(0) // SRC0 modifiers
.addReg(MI->getOperand(1).getReg())
.addImm(1) // SRC1 modifiers
.addReg(MI->getOperand(2).getReg())
.addImm(0) // CLAMP
.addImm(0); // OMOD
MI->eraseFromParent();
break;
}
case AMDGPU::SI_RegisterStorePseudo: {
MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
MachineInstrBuilder MIB =
BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
Reg);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
MIB.addOperand(MI->getOperand(i));
MI->eraseFromParent();
break;
}
}
return BB;
}
EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
if (!VT.isVector()) {
return MVT::i1;
}
return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
}
MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
return MVT::i32;
}
bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
VT = VT.getScalarType();
if (!VT.isSimple())
return false;
switch (VT.getSimpleVT().SimpleTy) {
case MVT::f32:
return false; /* There is V_MAD_F32 for f32 */
case MVT::f64:
return true;
default:
break;
}
return false;
}
//===----------------------------------------------------------------------===//
// Custom DAG Lowering Operations
//===----------------------------------------------------------------------===//
SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
switch (Op.getOpcode()) {
default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
case ISD::BRCOND: return LowerBRCOND(Op, DAG);
case ISD::LOAD: {
SDValue Result = LowerLOAD(Op, DAG);
assert((!Result.getNode() ||
Result.getNode()->getNumValues() == 2) &&
"Load should return a value and a chain");
return Result;
}
case ISD::FSIN:
case ISD::FCOS:
return LowerTrig(Op, DAG);
case ISD::SELECT: return LowerSELECT(Op, DAG);
case ISD::FDIV: return LowerFDIV(Op, DAG);
case ISD::STORE: return LowerSTORE(Op, DAG);
case ISD::GlobalAddress: {
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
return LowerGlobalAddress(MFI, Op, DAG);
}
case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
}
return SDValue();
}
/// \brief Helper function for LowerBRCOND
static SDNode *findUser(SDValue Value, unsigned Opcode) {
SDNode *Parent = Value.getNode();
for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
I != E; ++I) {
if (I.getUse().get() != Value)
continue;
if (I->getOpcode() == Opcode)
return *I;
}
return nullptr;
}
SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
unsigned FrameIndex = FINode->getIndex();
return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
}
/// This transforms the control flow intrinsics to get the branch destination as
/// last parameter, also switches branch target with BR if the need arise
SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
SelectionDAG &DAG) const {
SDLoc DL(BRCOND);
SDNode *Intr = BRCOND.getOperand(1).getNode();
SDValue Target = BRCOND.getOperand(2);
SDNode *BR = nullptr;
if (Intr->getOpcode() == ISD::SETCC) {
// As long as we negate the condition everything is fine
SDNode *SetCC = Intr;
assert(SetCC->getConstantOperandVal(1) == 1);
assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
ISD::SETNE);
Intr = SetCC->getOperand(0).getNode();
} else {
// Get the target from BR if we don't negate the condition
BR = findUser(BRCOND, ISD::BR);
Target = BR->getOperand(1);
}
assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
// Build the result and
SmallVector<EVT, 4> Res;
for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
Res.push_back(Intr->getValueType(i));
// operands of the new intrinsic call
SmallVector<SDValue, 4> Ops;
Ops.push_back(BRCOND.getOperand(0));
for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
Ops.push_back(Intr->getOperand(i));
Ops.push_back(Target);
// build the new intrinsic call
SDNode *Result = DAG.getNode(
Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
DAG.getVTList(Res), Ops).getNode();
if (BR) {
// Give the branch instruction our target
SDValue Ops[] = {
BR->getOperand(0),
BRCOND.getOperand(2)
};
SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
BR = NewBR.getNode();
}
SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
// Copy the intrinsic results to registers
for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
if (!CopyToReg)
continue;
Chain = DAG.getCopyToReg(
Chain, DL,
CopyToReg->getOperand(1),
SDValue(Result, i - 1),
SDValue());
DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
}
// Remove the old intrinsic from the chain
DAG.ReplaceAllUsesOfValueWith(
SDValue(Intr, Intr->getNumValues() - 1),
Intr->getOperand(0));
return Chain;
}
SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
SDValue Op,
SelectionDAG &DAG) const {
GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
SDLoc DL(GSD);
const GlobalValue *GV = GSD->getGlobal();
MVT PtrVT = getPointerTy(GSD->getAddressSpace());
SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
DAG.getConstant(0, MVT::i32));
SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
DAG.getConstant(1, MVT::i32));
SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
PtrLo, GA);
SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
PtrHi, DAG.getConstant(0, MVT::i32),
SDValue(Lo.getNode(), 1));
return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
}
SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
const SIRegisterInfo *TRI =
static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
EVT VT = Op.getValueType();
SDLoc DL(Op);
unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
switch (IntrinsicID) {
case Intrinsic::r600_read_ngroups_x:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::NGROUPS_X, false);
case Intrinsic::r600_read_ngroups_y:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::NGROUPS_Y, false);
case Intrinsic::r600_read_ngroups_z:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::NGROUPS_Z, false);
case Intrinsic::r600_read_global_size_x:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
case Intrinsic::r600_read_global_size_y:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
case Intrinsic::r600_read_global_size_z:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
case Intrinsic::r600_read_local_size_x:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::LOCAL_SIZE_X, false);
case Intrinsic::r600_read_local_size_y:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
case Intrinsic::r600_read_local_size_z:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
case Intrinsic::AMDGPU_read_workdim:
return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
false);
case Intrinsic::r600_read_tgid_x:
return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
case Intrinsic::r600_read_tgid_y:
return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
case Intrinsic::r600_read_tgid_z:
return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
case Intrinsic::r600_read_tidig_x:
return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
case Intrinsic::r600_read_tidig_y:
return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
case Intrinsic::r600_read_tidig_z:
return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
case AMDGPUIntrinsic::SI_load_const: {
SDValue Ops[] = {
Op.getOperand(1),
Op.getOperand(2)
};
MachineMemOperand *MMO = MF.getMachineMemOperand(
MachinePointerInfo(),
MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
VT.getStoreSize(), 4);
return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
Op->getVTList(), Ops, VT, MMO);
}
case AMDGPUIntrinsic::SI_sample:
return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
case AMDGPUIntrinsic::SI_sampleb:
return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
case AMDGPUIntrinsic::SI_sampled:
return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
case AMDGPUIntrinsic::SI_samplel:
return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
case AMDGPUIntrinsic::SI_vs_load_input:
return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
Op.getOperand(1),
Op.getOperand(2),
Op.getOperand(3));
default:
return AMDGPUTargetLowering::LowerOperation(Op, DAG);
}
}
SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
SDValue Chain = Op.getOperand(0);
unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
switch (IntrinsicID) {
case AMDGPUIntrinsic::SI_tbuffer_store: {
SDLoc DL(Op);
SDValue Ops[] = {
Chain,
Op.getOperand(2),
Op.getOperand(3),
Op.getOperand(4),
Op.getOperand(5),
Op.getOperand(6),
Op.getOperand(7),
Op.getOperand(8),
Op.getOperand(9),
Op.getOperand(10),
Op.getOperand(11),
Op.getOperand(12),
Op.getOperand(13),
Op.getOperand(14)
};
EVT VT = Op.getOperand(3).getValueType();
MachineMemOperand *MMO = MF.getMachineMemOperand(
MachinePointerInfo(),
MachineMemOperand::MOStore,
VT.getStoreSize(), 4);
return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
Op->getVTList(), Ops, VT, MMO);
}
default:
return SDValue();
}
}
SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
SDLoc DL(Op);
LoadSDNode *Load = cast<LoadSDNode>(Op);
if (Op.getValueType().isVector()) {
assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
"Custom lowering for non-i32 vectors hasn't been implemented.");
unsigned NumElements = Op.getValueType().getVectorNumElements();
assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
switch (Load->getAddressSpace()) {
default: break;
case AMDGPUAS::GLOBAL_ADDRESS:
case AMDGPUAS::PRIVATE_ADDRESS:
// v4 loads are supported for private and global memory.
if (NumElements <= 4)
break;
// fall-through
case AMDGPUAS::LOCAL_ADDRESS:
return ScalarizeVectorLoad(Op, DAG);
}
}
return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
}
SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
const SDValue &Op,
SelectionDAG &DAG) const {
return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
Op.getOperand(2),
Op.getOperand(3),
Op.getOperand(4));
}
SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
if (Op.getValueType() != MVT::i64)
return SDValue();
SDLoc DL(Op);
SDValue Cond = Op.getOperand(0);
SDValue Zero = DAG.getConstant(0, MVT::i32);
SDValue One = DAG.getConstant(1, MVT::i32);
SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
}
// Catch division cases where we can use shortcuts with rcp and rsq
// instructions.
SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
SDLoc SL(Op);
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
EVT VT = Op.getValueType();
bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
CLHS->isExactlyValue(1.0)) {
// v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
// the CI documentation has a worst case error of 1 ulp.
// OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
// use it as long as we aren't trying to use denormals.
// 1.0 / sqrt(x) -> rsq(x)
//
// XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
// error seems really high at 2^29 ULP.
if (RHS.getOpcode() == ISD::FSQRT)
return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
// 1.0 / x -> rcp(x)
return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
}
}
if (Unsafe) {
// Turn into multiply by the reciprocal.
// x / y -> x * (1.0 / y)
SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
}
return SDValue();
}
SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
SDValue FastLowered = LowerFastFDIV(Op, DAG);
if (FastLowered.getNode())
return FastLowered;
// This uses v_rcp_f32 which does not handle denormals. Let this hit a
// selection error for now rather than do something incorrect.
if (Subtarget->hasFP32Denormals())
return SDValue();
SDLoc SL(Op);
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
const APFloat K0Val(BitsToFloat(0x6f800000));
const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
const APFloat K1Val(BitsToFloat(0x2f800000));
const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
}
SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
return SDValue();
}
SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
if (VT == MVT::f32)
return LowerFDIV32(Op, DAG);
if (VT == MVT::f64)
return LowerFDIV64(Op, DAG);
llvm_unreachable("Unexpected type for fdiv");
}
SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
SDLoc DL(Op);
StoreSDNode *Store = cast<StoreSDNode>(Op);
EVT VT = Store->getMemoryVT();
// These stores are legal.
if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
VT.isVector() && VT.getVectorNumElements() == 2 &&
VT.getVectorElementType() == MVT::i32)
return SDValue();
if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
if (VT.isVector() && VT.getVectorNumElements() > 4)
return ScalarizeVectorStore(Op, DAG);
return SDValue();
}
SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
if (Ret.getNode())
return Ret;
if (VT.isVector() && VT.getVectorNumElements() >= 8)
return ScalarizeVectorStore(Op, DAG);
if (VT == MVT::i1)
return DAG.getTruncStore(Store->getChain(), DL,
DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
Store->getBasePtr(), MVT::i1, Store->getMemOperand());
return SDValue();
}
SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
SDValue Arg = Op.getOperand(0);
SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
DAG.getConstantFP(0.5 / M_PI, VT)));
switch (Op.getOpcode()) {
case ISD::FCOS:
return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
case ISD::FSIN:
return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
default:
llvm_unreachable("Wrong trig opcode");
}
}
//===----------------------------------------------------------------------===//
// Custom DAG optimizations
//===----------------------------------------------------------------------===//
SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
DAGCombinerInfo &DCI) {
EVT VT = N->getValueType(0);
EVT ScalarVT = VT.getScalarType();
if (ScalarVT != MVT::f32)
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDLoc DL(N);
SDValue Src = N->getOperand(0);
EVT SrcVT = Src.getValueType();
// TODO: We could try to match extracting the higher bytes, which would be
// easier if i8 vectors weren't promoted to i32 vectors, particularly after
// types are legalized. v4i8 -> v4f32 is probably the only case to worry
// about in practice.
if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
DCI.AddToWorklist(Cvt.getNode());
return Cvt;
}
}
// We are primarily trying to catch operations on illegal vector types
// before they are expanded.
// For scalars, we can use the more flexible method of checking masked bits
// after legalization.
if (!DCI.isBeforeLegalize() ||
!SrcVT.isVector() ||
SrcVT.getVectorElementType() != MVT::i8) {
return SDValue();
}
assert(DCI.isBeforeLegalize() && "Unexpected legal type");
// Weird sized vectors are a pain to handle, but we know 3 is really the same
// size as 4.
unsigned NElts = SrcVT.getVectorNumElements();
if (!SrcVT.isSimple() && NElts != 3)
return SDValue();
// Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
// prevent a mess from expanding to v4i32 and repacking.
if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
LoadSDNode *Load = cast<LoadSDNode>(Src);
SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
Load->getChain(),
Load->getBasePtr(),
LoadVT,
Load->getMemOperand());
// Make sure successors of the original load stay after it by updating
// them to use the new Chain.
DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
SmallVector<SDValue, 4> Elts;
if (RegVT.isVector())
DAG.ExtractVectorElements(NewLoad, Elts);
else
Elts.push_back(NewLoad);
SmallVector<SDValue, 4> Ops;
unsigned EltIdx = 0;
for (SDValue Elt : Elts) {
unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
for (unsigned I = 0; I < ComponentsInElt; ++I) {
unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
DCI.AddToWorklist(Cvt.getNode());
Ops.push_back(Cvt);
}
++EltIdx;
}
assert(Ops.size() == NElts);
return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
}
return SDValue();
}
// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
// This is a variant of
// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
//
// The normal DAG combiner will do this, but only if the add has one use since
// that would increase the number of instructions.
//
// This prevents us from seeing a constant offset that can be folded into a
// memory instruction's addressing mode. If we know the resulting add offset of
// a pointer can be folded into an addressing offset, we can replace the pointer
// operand with the add of new constant offset. This eliminates one of the uses,
// and may allow the remaining use to also be simplified.
//
SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
unsigned AddrSpace,
DAGCombinerInfo &DCI) const {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
if (N0.getOpcode() != ISD::ADD)
return SDValue();
const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
if (!CN1)
return SDValue();
const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (!CAdd)
return SDValue();
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
// If the resulting offset is too large, we can't fold it into the addressing
// mode offset.
APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
EVT VT = N->getValueType(0);
SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
SDValue COffset = DAG.getConstant(Offset, MVT::i32);
return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
}
static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
switch (Opc) {
case ISD::FMAXNUM:
return AMDGPUISD::FMAX3;
case AMDGPUISD::SMAX:
return AMDGPUISD::SMAX3;
case AMDGPUISD::UMAX:
return AMDGPUISD::UMAX3;
case ISD::FMINNUM:
return AMDGPUISD::FMIN3;
case AMDGPUISD::SMIN:
return AMDGPUISD::SMIN3;
case AMDGPUISD::UMIN:
return AMDGPUISD::UMIN3;
default:
llvm_unreachable("Not a min/max opcode");
}
}
SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
unsigned Opc = N->getOpcode();
SDValue Op0 = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
// Only do this if the inner op has one use since this will just increases
// register pressure for no benefit.
// max(max(a, b), c)
if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
SDLoc DL(N);
return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
DL,
N->getValueType(0),
Op0.getOperand(0),
Op0.getOperand(1),
Op1);
}
// max(a, max(b, c))
if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
SDLoc DL(N);
return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
DL,
N->getValueType(0),
Op0,
Op1.getOperand(0),
Op1.getOperand(1));
}
return SDValue();
}
SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
SDLoc DL(N);
EVT VT = N->getValueType(0);
switch (N->getOpcode()) {
default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
case ISD::SETCC: {
SDValue Arg0 = N->getOperand(0);
SDValue Arg1 = N->getOperand(1);
SDValue CC = N->getOperand(2);
ConstantSDNode * C = nullptr;
ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
// i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
if (VT == MVT::i1
&& Arg0.getOpcode() == ISD::SIGN_EXTEND
&& Arg0.getOperand(0).getValueType() == MVT::i1
&& (C = dyn_cast<ConstantSDNode>(Arg1))
&& C->isNullValue()
&& CCOp == ISD::SETNE) {
return SimplifySetCC(VT, Arg0.getOperand(0),
DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
}
break;
}
case ISD::FMAXNUM: // TODO: What about fmax_legacy?
case ISD::FMINNUM:
case AMDGPUISD::SMAX:
case AMDGPUISD::SMIN:
case AMDGPUISD::UMAX:
case AMDGPUISD::UMIN: {
if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
getTargetMachine().getOptLevel() > CodeGenOpt::None)
return performMin3Max3Combine(N, DCI);
break;
}
case AMDGPUISD::CVT_F32_UBYTE0:
case AMDGPUISD::CVT_F32_UBYTE1:
case AMDGPUISD::CVT_F32_UBYTE2:
case AMDGPUISD::CVT_F32_UBYTE3: {
unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
SDValue Src = N->getOperand(0);
APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
APInt KnownZero, KnownOne;
TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
!DCI.isBeforeLegalizeOps());
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
DCI.CommitTargetLoweringOpt(TLO);
}
break;
}
case ISD::UINT_TO_FP: {
return performUCharToFloatCombine(N, DCI);
case ISD::FADD: {
if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
break;
EVT VT = N->getValueType(0);
if (VT != MVT::f32)
break;
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
// These should really be instruction patterns, but writing patterns with
// source modiifiers is a pain.
// fadd (fadd (a, a), b) -> mad 2.0, a, b
if (LHS.getOpcode() == ISD::FADD) {
SDValue A = LHS.getOperand(0);
if (A == LHS.getOperand(1)) {
const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
}
}
// fadd (b, fadd (a, a)) -> mad 2.0, a, b
if (RHS.getOpcode() == ISD::FADD) {
SDValue A = RHS.getOperand(0);
if (A == RHS.getOperand(1)) {
const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
}
}
break;
}
case ISD::FSUB: {
if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
break;
EVT VT = N->getValueType(0);
// Try to get the fneg to fold into the source modifier. This undoes generic
// DAG combines and folds them into the mad.
if (VT == MVT::f32) {
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
if (LHS.getOpcode() == ISD::FMUL) {
// (fsub (fmul a, b), c) -> mad a, b, (fneg c)
SDValue A = LHS.getOperand(0);
SDValue B = LHS.getOperand(1);
SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
}
if (RHS.getOpcode() == ISD::FMUL) {
// (fsub c, (fmul a, b)) -> mad (fneg a), b, c
SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
SDValue B = RHS.getOperand(1);
SDValue C = LHS;
return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
}
if (LHS.getOpcode() == ISD::FADD) {
// (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
SDValue A = LHS.getOperand(0);
if (A == LHS.getOperand(1)) {
const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
}
}
if (RHS.getOpcode() == ISD::FADD) {
// (fsub c, (fadd a, a)) -> mad -2.0, a, c
SDValue A = RHS.getOperand(0);
if (A == RHS.getOperand(1)) {
const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
}
}
}
break;
}
}
case ISD::LOAD:
case ISD::STORE:
case ISD::ATOMIC_LOAD:
case ISD::ATOMIC_STORE:
case ISD::ATOMIC_CMP_SWAP:
case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
case ISD::ATOMIC_SWAP:
case ISD::ATOMIC_LOAD_ADD:
case ISD::ATOMIC_LOAD_SUB:
case ISD::ATOMIC_LOAD_AND:
case ISD::ATOMIC_LOAD_OR:
case ISD::ATOMIC_LOAD_XOR:
case ISD::ATOMIC_LOAD_NAND:
case ISD::ATOMIC_LOAD_MIN:
case ISD::ATOMIC_LOAD_MAX:
case ISD::ATOMIC_LOAD_UMIN:
case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
if (DCI.isBeforeLegalize())
break;
MemSDNode *MemNode = cast<MemSDNode>(N);
SDValue Ptr = MemNode->getBasePtr();
// TODO: We could also do this for multiplies.
unsigned AS = MemNode->getAddressSpace();
if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
if (NewPtr) {
SmallVector<SDValue, 8> NewOps;
for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
NewOps.push_back(MemNode->getOperand(I));
NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
}
}
break;
}
}
return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
}
/// \brief Test if RegClass is one of the VSrc classes
static bool isVSrc(unsigned RegClass) {
switch(RegClass) {
default: return false;
case AMDGPU::VSrc_32RegClassID:
case AMDGPU::VCSrc_32RegClassID:
case AMDGPU::VSrc_64RegClassID:
case AMDGPU::VCSrc_64RegClassID:
return true;
}
}
/// \brief Test if RegClass is one of the SSrc classes
static bool isSSrc(unsigned RegClass) {
return AMDGPU::SSrc_32RegClassID == RegClass ||
AMDGPU::SSrc_64RegClassID == RegClass;
}
/// \brief Analyze the possible immediate value Op
///
/// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
/// and the immediate value if it's a literal immediate
int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
union {
int32_t I;
float F;
} Imm;
if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
if (Node->getZExtValue() >> 32) {
return -1;
}
Imm.I = Node->getSExtValue();
} else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
if (N->getValueType(0) != MVT::f32)
return -1;
Imm.F = Node->getValueAPF().convertToFloat();
} else
return -1; // It isn't an immediate
if ((Imm.I >= -16 && Imm.I <= 64) ||
Imm.F == 0.5f || Imm.F == -0.5f ||
Imm.F == 1.0f || Imm.F == -1.0f ||
Imm.F == 2.0f || Imm.F == -2.0f ||
Imm.F == 4.0f || Imm.F == -4.0f)
return 0; // It's an inline immediate
return Imm.I; // It's a literal immediate
}
/// \brief Try to fold an immediate directly into an instruction
bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
bool &ScalarSlotUsed) const {
MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
return false;
const SDValue &Op = Mov->getOperand(0);
int32_t Value = analyzeImmediate(Op.getNode());
if (Value == -1) {
// Not an immediate at all
return false;
} else if (Value == 0) {
// Inline immediates can always be fold
Operand = Op;
return true;
} else if (Value == Immediate) {
// Already fold literal immediate
Operand = Op;
return true;
} else if (!ScalarSlotUsed && !Immediate) {
// Fold this literal immediate
ScalarSlotUsed = true;
Immediate = Value;
Operand = Op;
return true;
}
return false;
}
const TargetRegisterClass *SITargetLowering::getRegClassForNode(
SelectionDAG &DAG, const SDValue &Op) const {
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
const SIRegisterInfo &TRI = TII->getRegisterInfo();
if (!Op->isMachineOpcode()) {
switch(Op->getOpcode()) {
case ISD::CopyFromReg: {
MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg)) {
return MRI.getRegClass(Reg);
}
return TRI.getPhysRegClass(Reg);
}
default: return nullptr;
}
}
const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
if (OpClassID != -1) {
return TRI.getRegClass(OpClassID);
}
switch(Op.getMachineOpcode()) {
case AMDGPU::COPY_TO_REGCLASS:
// Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
// If the COPY_TO_REGCLASS instruction is copying to a VSrc register
// class, then the register class for the value could be either a
// VReg or and SReg. In order to get a more accurate
if (isVSrc(OpClassID))
return getRegClassForNode(DAG, Op.getOperand(0));
return TRI.getRegClass(OpClassID);
case AMDGPU::EXTRACT_SUBREG: {
int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
const TargetRegisterClass *SuperClass =
getRegClassForNode(DAG, Op.getOperand(0));
return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
}
case AMDGPU::REG_SEQUENCE:
// Operand 0 is the register class id for REG_SEQUENCE instructions.
return TRI.getRegClass(
cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
default:
return getRegClassFor(Op.getSimpleValueType());
}
}
/// \brief Does "Op" fit into register class "RegClass" ?
bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
unsigned RegClass) const {
const TargetRegisterInfo *TRI =
getTargetMachine().getSubtargetImpl()->getRegisterInfo();
const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
if (!RC) {
return false;
}
return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
}
/// \returns true if \p Node's operands are different from the SDValue list
/// \p Ops
static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
return true;
}
}
return false;
}
/// TODO: This needs to be removed. It's current primary purpose is to fold
/// immediates into operands when legal. The legalization parts are redundant
/// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
SelectionDAG &DAG) const {
// Original encoding (either e32 or e64)
int Opcode = Node->getMachineOpcode();
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
const MCInstrDesc *Desc = &TII->get(Opcode);
unsigned NumDefs = Desc->getNumDefs();
unsigned NumOps = Desc->getNumOperands();
// Commuted opcode if available
int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
assert(!DescRev || DescRev->getNumDefs() == NumDefs);
assert(!DescRev || DescRev->getNumOperands() == NumOps);
int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
bool HaveVSrc = false, HaveSSrc = false;
// First figure out what we already have in this instruction.
for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
i != e && Op < NumOps; ++i, ++Op) {
unsigned RegClass = Desc->OpInfo[Op].RegClass;
if (isVSrc(RegClass))
HaveVSrc = true;
else if (isSSrc(RegClass))
HaveSSrc = true;
else
continue;
int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
if (Imm != -1 && Imm != 0) {
// Literal immediate
Immediate = Imm;
}
}
// If we neither have VSrc nor SSrc, it makes no sense to continue.
if (!HaveVSrc && !HaveSSrc)
return Node;
// No scalar allowed when we have both VSrc and SSrc
bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
// If this instruction has an implicit use of VCC, then it can't use the
// constant bus.
for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
ScalarSlotUsed = true;
break;
}
}
// Second go over the operands and try to fold them
std::vector<SDValue> Ops;
for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
i != e && Op < NumOps; ++i, ++Op) {
const SDValue &Operand = Node->getOperand(i);
Ops.push_back(Operand);
// Already folded immediate?
if (isa<ConstantSDNode>(Operand.getNode()) ||
isa<ConstantFPSDNode>(Operand.getNode()))
continue;
// Is this a VSrc or SSrc operand?
unsigned RegClass = Desc->OpInfo[Op].RegClass;
if (isVSrc(RegClass) || isSSrc(RegClass)) {
// Try to fold the immediates. If this ends up with multiple constant bus
// uses, it will be legalized later.
foldImm(Ops[i], Immediate, ScalarSlotUsed);
continue;
}
if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
// Test if it makes sense to swap operands
if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
(!fitsRegClass(DAG, Ops[1], RegClass) &&
fitsRegClass(DAG, Ops[1], OtherRegClass))) {
// Swap commutable operands
std::swap(Ops[0], Ops[1]);
Desc = DescRev;
DescRev = nullptr;
continue;
}
}
}
// Add optional chain and glue
for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
Ops.push_back(Node->getOperand(i));
// Nodes that have a glue result are not CSE'd by getMachineNode(), so in
// this case a brand new node is always be created, even if the operands
// are the same as before. So, manually check if anything has been changed.
if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
return Node;
}
// Create a complete new instruction
return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
}
/// \brief Helper function for adjustWritemask
static unsigned SubIdx2Lane(unsigned Idx) {
switch (Idx) {
default: return 0;
case AMDGPU::sub0: return 0;
case AMDGPU::sub1: return 1;
case AMDGPU::sub2: return 2;
case AMDGPU::sub3: return 3;
}
}
/// \brief Adjust the writemask of MIMG instructions
void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
SelectionDAG &DAG) const {
SDNode *Users[4] = { };
unsigned Lane = 0;
unsigned OldDmask = Node->getConstantOperandVal(0);
unsigned NewDmask = 0;
// Try to figure out the used register components
for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
I != E; ++I) {
// Abort if we can't understand the usage
if (!I->isMachineOpcode() ||
I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
return;
// Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
// Note that subregs are packed, i.e. Lane==0 is the first bit set
// in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
// set, etc.
Lane = SubIdx2Lane(I->getConstantOperandVal(1));
// Set which texture component corresponds to the lane.
unsigned Comp;
for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
assert(Dmask);
Comp = countTrailingZeros(Dmask);
Dmask &= ~(1 << Comp);
}
// Abort if we have more than one user per component
if (Users[Lane])
return;
Users[Lane] = *I;
NewDmask |= 1 << Comp;
}
// Abort if there's no change
if (NewDmask == OldDmask)
return;
// Adjust the writemask in the node
std::vector<SDValue> Ops;
Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
Ops.push_back(Node->getOperand(i));
Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
// If we only got one lane, replace it with a copy
// (if NewDmask has only one bit set...)
if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
SDLoc(), Users[Lane]->getValueType(0),
SDValue(Node, 0), RC);
DAG.ReplaceAllUsesWith(Users[Lane], Copy);
return;
}
// Update the users of the node with the new indices
for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
SDNode *User = Users[i];
if (!User)
continue;
SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
switch (Idx) {
default: break;
case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
}
}
}
/// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
/// with frame index operands.
/// LLVM assumes that inputs are to these instructions are registers.
void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
SelectionDAG &DAG) const {
SmallVector<SDValue, 8> Ops;
for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
Ops.push_back(Node->getOperand(i));
continue;
}
SDLoc DL(Node);
Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
Node->getOperand(i).getValueType(),
Node->getOperand(i)), 0));
}
DAG.UpdateNodeOperands(Node, Ops);
}
/// \brief Fold the instructions after selecting them.
SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
SelectionDAG &DAG) const {
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
Node = AdjustRegClass(Node, DAG);
if (TII->isMIMG(Node->getMachineOpcode()))
adjustWritemask(Node, DAG);
if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
legalizeTargetIndependentNode(Node, DAG);
return Node;
}
return legalizeOperands(Node, DAG);
}
/// \brief Assign the register class depending on the number of
/// bits set in the writemask
void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
SDNode *Node) const {
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
TII->legalizeOperands(MI);
if (TII->isMIMG(MI->getOpcode())) {
unsigned VReg = MI->getOperand(0).getReg();
unsigned Writemask = MI->getOperand(1).getImm();
unsigned BitsSet = 0;
for (unsigned i = 0; i < 4; ++i)
BitsSet += Writemask & (1 << i) ? 1 : 0;
const TargetRegisterClass *RC;
switch (BitsSet) {
default: return;
case 1: RC = &AMDGPU::VReg_32RegClass; break;
case 2: RC = &AMDGPU::VReg_64RegClass; break;
case 3: RC = &AMDGPU::VReg_96RegClass; break;
}
unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
MI->setDesc(TII->get(NewOpcode));
MRI.setRegClass(VReg, RC);
return;
}
// Replace unused atomics with the no return version.
int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
if (NoRetAtomicOp != -1) {
if (!Node->hasAnyUseOfValue(0)) {
MI->setDesc(TII->get(NoRetAtomicOp));
MI->RemoveOperand(0);
}
return;
}
}
static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
SDValue K = DAG.getTargetConstant(Val, MVT::i32);
return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
}
MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
SDLoc DL,
SDValue Ptr) const {
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
#if 1
// XXX - Workaround for moveToVALU not handling different register class
// inserts for REG_SEQUENCE.
// Build the half of the subregister with the constants.
const SDValue Ops0[] = {
DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
buildSMovImm32(DAG, DL, 0),
DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
};
SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
MVT::v2i32, Ops0), 0);
// Combine the constants and the pointer.
const SDValue Ops1[] = {
DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
Ptr,
DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
SubRegHi,
DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
};
return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
#else
const SDValue Ops[] = {
DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
Ptr,
DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
buildSMovImm32(DAG, DL, 0),
DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
};
return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
#endif
}
/// \brief Return a resource descriptor with the 'Add TID' bit enabled
/// The TID (Thread ID) is multipled by the stride value (bits [61:48]
/// of the resource descriptor) to create an offset, which is added to the
/// resource ponter.
MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
SDLoc DL,
SDValue Ptr,
uint32_t RsrcDword1,
uint64_t RsrcDword2And3) const {
SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
if (RsrcDword1) {
PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
DAG.getConstant(RsrcDword1, MVT::i32)), 0);
}
SDValue DataLo = buildSMovImm32(DAG, DL,
RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
const SDValue Ops[] = {
DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
PtrLo,
DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
PtrHi,
DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
DataLo,
DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
DataHi,
DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
};
return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
}
MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
SDLoc DL,
SDValue Ptr) const {
const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
getTargetMachine().getSubtargetImpl()->getInstrInfo());
uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
0xffffffff; // Size
return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
}
MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
SelectionDAG &DAG) const {
SDLoc DL(N);
unsigned NewOpcode = N->getMachineOpcode();
switch (N->getMachineOpcode()) {
default: return N;
case AMDGPU::S_LOAD_DWORD_IMM:
NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
// Fall-through
case AMDGPU::S_LOAD_DWORDX2_SGPR:
if (NewOpcode == N->getMachineOpcode()) {
NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
}
// Fall-through
case AMDGPU::S_LOAD_DWORDX4_IMM:
case AMDGPU::S_LOAD_DWORDX4_SGPR: {
if (NewOpcode == N->getMachineOpcode()) {
NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
}
if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
return N;
}
ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
SmallVector<SDValue, 8> Ops;
Ops.push_back(SDValue(RSrc, 0));
Ops.push_back(N->getOperand(0));
Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
// Copy remaining operands so we keep any chain and glue nodes that follow
// the normal operands.
for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
Ops.push_back(N->getOperand(I));
return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
}
}
}
SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
const TargetRegisterClass *RC,
unsigned Reg, EVT VT) const {
SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
cast<RegisterSDNode>(VReg)->getReg(), VT);
}
| 35.11978 | 83 | 0.639247 | [
"vector"
] |
c8018bcd47657bc2f5bce68b6a54e97385a7bfdb | 2,801 | cpp | C++ | Isetta/IsettaEngine/Scene/Component.cpp | LukeMcCulloch/IsettaGameEngine | 9f112d7d088623607a19175707824c5b65662e03 | [
"MIT"
] | 2 | 2018-09-05T17:51:47.000Z | 2018-09-05T19:35:25.000Z | Isetta/IsettaEngine/Scene/Component.cpp | LukeMcCulloch/IsettaGameEngine | 9f112d7d088623607a19175707824c5b65662e03 | [
"MIT"
] | null | null | null | Isetta/IsettaEngine/Scene/Component.cpp | LukeMcCulloch/IsettaGameEngine | 9f112d7d088623607a19175707824c5b65662e03 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Isetta
*/
#include "Scene/Component.h"
#include "Scene/Entity.h"
#include "Scene/Transform.h"
namespace Isetta {
bool Component::isFlattened = false;
bool Component::RegisterComponent(std::type_index curr, std::type_index base,
bool isUnique) {
if (isUnique) uniqueComponents().insert(curr);
std::unordered_map<std::type_index, std::list<std::type_index>>& children =
childrenTypes();
if (children.count(curr) > 0) {
children.at(curr).push_front(curr);
} else {
children.insert({curr, std::list<std::type_index>{curr}});
}
if (children.count(base) > 0) {
children.at(base).emplace_back(curr);
} else {
children.insert({base, std::list<std::type_index>{curr}});
}
return true;
}
void Component::FlattenComponentList() {
if (isFlattened) return;
isFlattened = true;
std::unordered_map<std::type_index, std::list<std::type_index>>& children =
childrenTypes();
std::type_index componentIndex{typeid(Component)};
std::list<std::type_index>* componentList = &children.at(componentIndex);
for (auto& childList : *componentList) {
if (childList != componentIndex) {
FlattenHelper(componentIndex, childList);
}
}
}
void Component::FlattenHelper(std::type_index parent, std::type_index curr) {
std::unordered_map<std::type_index, std::list<std::type_index>>& children =
childrenTypes();
std::list<std::type_index>* parentList = &children.at(parent);
std::list<std::type_index>* componentList = &children.at(curr);
for (auto& childList : *componentList) {
if (childList != curr) {
parentList->push_back(childList);
FlattenHelper(curr, childList);
}
}
}
Component::Component()
: attributes{0b1111001}, entity{nullptr}, transform(nullptr) {
if (!isFlattened) {
FlattenComponentList();
}
}
void Component::SetAttribute(ComponentAttributes attr, bool value) {
attributes.set(static_cast<int>(attr), value);
}
bool Component::GetAttribute(ComponentAttributes attr) const {
return attributes.test(static_cast<int>(attr));
}
void Component::SetActive(bool value) {
bool isActive = GetAttribute(ComponentAttributes::IS_ACTIVE);
SetAttribute(ComponentAttributes::IS_ACTIVE, value);
if (!isActive && value) {
if (!GetAttribute(ComponentAttributes::HAS_AWAKEN)) {
Awake();
SetAttribute(ComponentAttributes::HAS_AWAKEN, true);
}
OnEnable();
} else if (isActive && !value &&
GetAttribute(ComponentAttributes::HAS_AWAKEN)) {
OnDisable();
}
}
bool Component::GetActive() const {
return GetAttribute(ComponentAttributes::IS_ACTIVE);
}
void Component::Destroy(Component* component) {
component->SetAttribute(ComponentAttributes::NEED_DESTROY, true);
}
} // namespace Isetta
| 28.876289 | 77 | 0.691182 | [
"transform"
] |
65a5de88e06a5b448a37015397d51db3095214da | 23,394 | cpp | C++ | src/xeus_sqlite_interpreter.cpp | DerThorsten/xeus-sqlite | 9bcca6676623a43841423cc21e9a737ac9da6637 | [
"BSD-3-Clause"
] | 135 | 2020-04-01T11:51:41.000Z | 2022-03-26T09:59:03.000Z | src/xeus_sqlite_interpreter.cpp | DerThorsten/xeus-sqlite | 9bcca6676623a43841423cc21e9a737ac9da6637 | [
"BSD-3-Clause"
] | 78 | 2020-04-01T11:19:09.000Z | 2022-02-11T16:39:13.000Z | src/xeus_sqlite_interpreter.cpp | DerThorsten/xeus-sqlite | 9bcca6676623a43841423cc21e9a737ac9da6637 | [
"BSD-3-Clause"
] | 25 | 2020-04-01T11:52:30.000Z | 2021-10-04T11:36:32.000Z | /***************************************************************************
* Copyright (c) 2020, QuantStack and Xeus-SQLite contributors *
* *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include <cctype>
#include <cstdio>
#include <fstream>
#include <memory>
#include <sstream>
#include <stack>
#include <vector>
#include <tuple>
#include "xvega-bindings/xvega_bindings.hpp"
#include "xeus/xinterpreter.hpp"
#include "tabulate/table.hpp"
#include "xeus-sqlite/xeus_sqlite_interpreter.hpp"
#include <SQLiteCpp/VariadicBind.h>
#include <SQLiteCpp/SQLiteCpp.h>
namespace xeus_sqlite
{
inline bool startswith(const std::string& str, const std::string& cmp)
{
return str.compare(0, cmp.length(), cmp) == 0;
}
inline static bool is_identifier(char c)
{
return std::isalpha(c) || std::isdigit(c) || c == '_';
}
void interpreter::load_db(const std::vector<std::string> tokenized_input)
{
/*
Loads the database. If the open mode is not specified it defaults
to read and write mode.
*/
if (tokenized_input.back().find("rw") != std::string::npos)
{
m_bd_is_loaded = true;
m_db = std::make_unique<SQLite::Database>(m_db_path,
SQLite::OPEN_READWRITE);
}
else if (tokenized_input.back().find("r") != std::string::npos)
{
m_bd_is_loaded = true;
m_db = std::make_unique<SQLite::Database>(m_db_path,
SQLite::OPEN_READONLY);
}
/* Opening as read and write because mode is unspecified */
else if (tokenized_input.size() < 4)
{
m_bd_is_loaded = true;
m_db = std::make_unique<SQLite::Database>(m_db_path,
SQLite::OPEN_READWRITE);
}
else
{
throw std::runtime_error("Wasn't able to load the database correctly.");
}
}
void interpreter::create_db(const std::vector<std::string> tokenized_input)
{
m_bd_is_loaded = true;
m_db_path = tokenized_input[2];
/* Creates the file */
std::ofstream(m_db_path.c_str()).close();
/* Creates the database */
m_db = std::make_unique<SQLite::Database>(m_db_path,
SQLite::OPEN_READWRITE |
SQLite::OPEN_CREATE);
}
void interpreter::delete_db()
{
/*
Deletes the database.
*/
if(std::remove(m_db_path.c_str()) != 0)
{
throw std::runtime_error("Error deleting file.");
}
}
nl::json interpreter::table_exists(const std::string table_name)
{
nl::json pub_data;
if (m_db->SQLite::Database::tableExists(table_name.c_str()))
{
pub_data["text/plain"] = "The table " + table_name + " exists.";
return pub_data;
}
else
{
pub_data["text/plain"] = "The table " + table_name + " doesn't exist.";
return pub_data;
}
}
nl::json interpreter::is_unencrypted()
{
nl::json pub_data;
if (SQLite::Database::isUnencrypted(m_db_path))
{
pub_data["text/plain"] = "The database is unencrypted.";
return pub_data;
}
else
{
pub_data["text/plain"] = "The database is encrypted.";
return pub_data;
}
}
nl::json interpreter::get_header_info()
{
SQLite::Header header;
header = SQLite::Database::getHeaderInfo(m_db_path);
/* Official documentation for fields can be found here:
https://www.sqlite.org/fileformat.html#the_database_header*/
nl::json pub_data;
pub_data["text/plain"] =
"Magic header string: " + std::string(&header.headerStr[0], &header.headerStr[15]) + "\n" +
"Page size bytes: " + std::to_string(header.pageSizeBytes) + "\n" +
"File format write version: " + std::to_string(header.fileFormatWriteVersion) + "\n" +
"File format read version: " + std::to_string(header.fileFormatReadVersion) + "\n" +
"Reserved space bytes: " + std::to_string(header.reservedSpaceBytes) + "\n" +
"Max embedded payload fraction " + std::to_string(header.maxEmbeddedPayloadFrac) + "\n" +
"Min embedded payload fraction: " + std::to_string(header.minEmbeddedPayloadFrac) + "\n" +
"Leaf payload fraction: " + std::to_string(header.leafPayloadFrac) + "\n" +
"File change counter: " + std::to_string(header.fileChangeCounter) + "\n" +
"Database size pages: " + std::to_string(header.databaseSizePages) + "\n" +
"First freelist trunk page: " + std::to_string(header.firstFreelistTrunkPage) + "\n" +
"Total freelist trunk pages: " + std::to_string(header.totalFreelistPages) + "\n" +
"Schema cookie: " + std::to_string(header.schemaCookie) + "\n" +
"Schema format number: " + std::to_string(header.schemaFormatNumber) + "\n" +
"Default page cache size bytes: " + std::to_string(header.defaultPageCacheSizeBytes) + "\n" +
"Largest B tree page number: " + std::to_string(header.largestBTreePageNumber) + "\n" +
"Database text encoding: " + std::to_string(header.databaseTextEncoding) + "\n" +
"User version: " + std::to_string(header.userVersion) + "\n" +
"Incremental vaccum mode: " + std::to_string(header.incrementalVaccumMode) + "\n" +
"Application ID: " + std::to_string(header.applicationId) + "\n" +
"Version valid for: " + std::to_string(header.versionValidFor) + "\n" +
"SQLite version: " + std::to_string(header.sqliteVersion) + "\n";
return pub_data;
}
void interpreter::backup(std::string backup_type)
{
if (backup_type.size() > 1 && (int)backup_type[0] <= 1)
{
throw std::runtime_error("This is not a valid backup type.");
}
else
{
m_backup_db->SQLite::Database::backup(m_db_path.c_str(),
(SQLite::Database::BackupType)backup_type[0]);
}
}
void interpreter::parse_SQLite_magic(int execution_counter,
const std::vector<
std::string>& tokenized_input)
{
if (xv_bindings::case_insentive_equals(tokenized_input[0], "LOAD"))
{
m_db_path = tokenized_input[1];
std::ifstream path_is_valid(m_db_path);
if (!path_is_valid.is_open())
{
throw std::runtime_error("The path doesn't exist.");
}
else
{
return load_db(tokenized_input);
}
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "CREATE"))
{
return create_db(tokenized_input);
}
if (m_bd_is_loaded)
{
if (xv_bindings::case_insentive_equals(tokenized_input[0], "DELETE"))
{
delete_db();
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "TABLE_EXISTS"))
{
publish_execution_result(execution_counter,
std::move(table_exists(tokenized_input[1])),
nl::json::object());
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "LOAD_EXTENSION"))
{
//TODO: add a try catch to treat all void functions
m_db->SQLite::Database::loadExtension(tokenized_input[1].c_str(),
tokenized_input[2].c_str());
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "SET_KEY"))
{
m_db->SQLite::Database::key(tokenized_input[1]);
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "REKEY"))
{
m_db->SQLite::Database::rekey(tokenized_input[1]);
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "IS_UNENCRYPTED"))
{
publish_execution_result(execution_counter,
std::move(is_unencrypted()),
nl::json::object());
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "GET_INFO"))
{
publish_execution_result(execution_counter,
std::move(get_header_info()),
nl::json::object());
}
else if (xv_bindings::case_insentive_equals(tokenized_input[0], "BACKUP"))
{
backup(tokenized_input[1]);
}
}
else
{
throw SQLite::Exception("Load a database to run this command.");
}
}
void interpreter::configure_impl()
{
}
void interpreter::process_SQLite_input(int execution_counter,
std::unique_ptr<SQLite::Database> &m_db,
const std::string& code,
xv::df_type& xv_sqlite_df)
{
if (m_db == nullptr)
{
throw SQLite::Exception("Please load a database to perform operations");
}
SQLite::Statement query(*m_db, code);
nl::json pub_data;
/* Builds text/plain output */
tabulate::Table plain_table;
/* Builds text/html output */
std::stringstream html_table("");
/* The error handling on SQLite commands are being taken care of by SQLiteCpp*/
if (query.getColumnCount() != 0)
{
std::vector<std::variant<
std::string,
const char*,
tabulate::Table>> col_names;
/* Builds text/html output */
html_table << "<table>\n<tr>\n";
/* Iterates through cols name and build table's title row */
for (int col = 0; col < query.getColumnCount(); col++) {
std::string name = query.getColumnName(col);
/* Builds text/plain output */
col_names.push_back(name);
/* Builds text/html output */
html_table << "<th>" << name << "</th>\n";
/* Build application/vnd.vegalite.v3+json output */
xv_sqlite_df[name] = { "name" };
}
/* Builds text/plain output */
plain_table.add_row(col_names);
/* Builds text/html output */
html_table << "</tr>\n";
/* Iterates through cols' rows and builds different kinds of
outputs
*/
while (query.executeStep())
{
/* Builds text/html output */
html_table << "<tr>\n";
std::vector<std::variant<
std::string,
const char*,
tabulate::Table>> row;
for (int col = 0; col < query.getColumnCount(); col++) {
std::string col_name;
col_name = query.getColumnName(col);
std::string cell = query.getColumn(col);
/* Builds text/plain output */
row.push_back(cell);
/* Builds text/html output */
html_table << "<td>" << cell << "</td>\n";
/* Build application/vnd.vegalite.v3+json output */
xv_sqlite_df[col_name].push_back(cell);
}
/* Builds text/html output */
html_table << "</tr>\n";
/* Builds text/plain output */
plain_table.add_row(row);
}
/* Builds text/html output */
html_table << "</table>";
pub_data["text/plain"] = plain_table.str();
pub_data["text/html"] = html_table.str();
publish_execution_result(execution_counter,
std::move(pub_data),
nl::json::object());
}
else
{
query.exec();
}
}
nl::json interpreter::execute_request_impl(int execution_counter,
const std::string& code,
bool /*silent*/,
bool /*store_history*/,
nl::json /*user_expressions*/,
bool /*allow_stdin*/)
{
std::vector<std::string> traceback;
nl::json jresult;
std::string sanitized_code = xv_bindings::sanitize_string(code);
std::vector<std::string> tokenized_input = xv_bindings::tokenizer(sanitized_code);
/* This structure is only used when xvega code is run */
//TODO: but it ends up being used in process_SQLite_input, that's why
//it's initialized here. Not the best approach, this should be
//compartimentilized under xvega domain.
xv::df_type xv_sqlite_df;
try
{
/* Runs magic */
if(xv_bindings::is_magic(tokenized_input))
{
/* Removes "%" symbol */
tokenized_input[0].erase(0, 1);
/* Runs SQLite magic */
parse_SQLite_magic(execution_counter, tokenized_input);
/* Runs xvega magic and SQLite code */
if(xv_bindings::is_xvega(tokenized_input))
{
/* Removes XVEGA_PLOT command */
tokenized_input.erase(tokenized_input.begin());
nl::json chart;
std::vector<std::string> xvega_input, sqlite_input;
std::tie(xvega_input, sqlite_input) =
xv_sqlite::split_xv_sqlite_input(tokenized_input);
/* Stringfies SQLite code again */
std::stringstream stringfied_sqlite_input;
for (size_t i = 0; i < sqlite_input.size(); i++) {
stringfied_sqlite_input << " " << sqlite_input[i];
}
process_SQLite_input(execution_counter,
m_db,
stringfied_sqlite_input.str(),
xv_sqlite_df);
chart = xv_bindings::process_xvega_input(xvega_input,
xv_sqlite_df);
publish_execution_result(execution_counter,
std::move(chart),
nl::json::object());
}
}
/* Runs SQLite code */
else
{
process_SQLite_input(execution_counter, m_db, code, xv_sqlite_df);
}
jresult["status"] = "ok";
jresult["payload"] = nl::json::array();
jresult["user_expressions"] = nl::json::object();
}
catch (const std::exception& err)
{
jresult["status"] = "error";
jresult["ename"] = "Error";
jresult["evalue"] = err.what();
traceback.push_back((std::string)jresult["ename"] + ": " + (std::string)err.what());
publish_execution_error(jresult["ename"], jresult["evalue"], traceback);
traceback.clear();
}
return jresult;
}
nl::json interpreter::complete_request_impl(const std::string& raw_code,
int cursor_pos)
{
static const std::array<std::string,147> keywords =
{
"ABORT",
"ACTION",
"ADD",
"AFTER",
"ALL",
"ALTER",
"ALWAYS",
"ANALYZE",
"AND",
"AS",
"ASC",
"ATTACH",
"AUTOINCREMENT",
"BEFORE",
"BEGIN",
"BETWEEN",
"BY",
"CASCADE",
"CASE",
"CAST",
"CHECK",
"COLLATE",
"COLUMN",
"COMMIT",
"CONFLICT",
"CONSTRAINT",
"CREATE",
"CROSS",
"CURRENT",
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"DATABASE",
"DEFAULT",
"DEFERRABLE",
"DEFERRED",
"DELETE",
"DESC",
"DETACH",
"DISTINCT",
"DO",
"DROP",
"EACH",
"ELSE",
"END",
"ESCAPE",
"EXCEPT",
"EXCLUDE",
"EXCLUSIVE",
"EXISTS",
"EXPLAIN",
"FAIL",
"FILTER",
"FIRST",
"FOLLOWING",
"FOR",
"FOREIGN",
"FROM",
"FULL",
"GENERATED",
"GLOB",
"GROUP",
"GROUPS",
"HAVING",
"IF",
"IGNORE",
"IMMEDIATE",
"IN",
"INDEX",
"INDEXED",
"INITIALLY",
"INNER",
"INSERT",
"INSTEAD",
"INTERSECT",
"INTO",
"IS",
"ISNULL",
"JOIN",
"KEY",
"LAST",
"LEFT",
"LIKE",
"LIMIT",
"MATCH",
"MATERIALIZED",
"NATURAL",
"NO",
"NOT",
"NOTHING",
"NOTNULL",
"NULL",
"NULLS",
"OF",
"OFFSET",
"ON",
"OR",
"ORDER",
"OTHERS",
"OUTER",
"OVER",
"PARTITION",
"PLAN",
"PRAGMA",
"PRECEDING",
"PRIMARY",
"QUERY",
"RAISE",
"RANGE",
"RECURSIVE",
"REFERENCES",
"REGEXP",
"REINDEX",
"RELEASE",
"RENAME",
"REPLACE",
"RESTRICT",
"RETURNING",
"RIGHT",
"ROLLBACK",
"ROW",
"ROWS",
"SAVEPOINT",
"SELECT",
"SET",
"TABLE",
"TEMP",
"TEMPORARY",
"THEN",
"TIES",
"TO",
"TRANSACTION",
"TRIGGER",
"UNBOUNDED",
"UNION",
"UNIQUE",
"UPDATE",
"USING",
"VACUUM",
"VALUES",
"VIEW",
"VIRTUAL",
"WHEN",
"WHERE",
"WINDOW",
"WITH",
"WITHOUT",
};
nl::json result;
nl::json matches = nl::json::array();
// first we get a substring from string[0:curser_pos+1]std
// and discard the right side of the curser pos
const auto code = raw_code.substr(0, cursor_pos);
// keyword matches
// ............................
{
auto pos = -1;
for(int i=code.size()-1; i>=0; --i)
{
if(!is_identifier(code[i]))
{
pos = i;
break;
}
}
result["cursor_start"] = pos == -1 ? 0 : pos +1;
auto to_match = pos == -1 ? code : code.substr(pos+1, code.size() -(pos+1));
// check for kw matches
for(auto kw : keywords)
{
if(startswith(kw, to_match))
{
matches.push_back(kw);
}
}
}
result["status"] = "ok";
result["cursor_end"] = cursor_pos;
result["matches"] =matches;
return result;
};
nl::json interpreter::inspect_request_impl(const std::string& /*code*/,
int /*cursor_pos*/,
int /*detail_level*/)
{
nl::json jresult;
jresult["status"] = "ok";
jresult["found"] = false;
jresult["data"] = nl::json::object();
jresult["metadata"] = nl::json::object();
return jresult;
};
nl::json interpreter::is_complete_request_impl(const std::string& /*code*/)
{
nl::json jresult;
jresult["status"] = "complete";
jresult["indent"] = "";
return jresult;
};
nl::json interpreter::kernel_info_request_impl()
{
nl::json result;
result["implementation"] = "xsqlite";
result["implementation_version"] = XSQLITE_VERSION;
/* The jupyter-console banner for xeus-sqlite is the following:
_ _ ____ _ _ ____ ____ ____ _ _ ___ ____
\/ |___ | | [__ __ [__ | | | | | |___
_/\_ |___ |__| ___] ___] |_\| |___ | | |___
xeus-SQLite: a Jupyter kernel for SQLite
SQLite version: x.x.x
*/
std::string banner = ""
"_ _ ____ _ _ ____ ____ ____ _ _ ___ ____\n"
" \\/ |___ | | [__ __ [__ | | | | | |___\n"
"_/\\_ |___ |__| ___] ___] |_\\| |___ | | |___\n"
" xeus-SQLite: a Jupyter kernel for SQLite\n"
" SQLite version: ";
banner.append(SQLite::VERSION);
result["banner"] = banner;
result["language_info"]["name"] = "sql";
result["language_info"]["codemirror_mode"] = "sql";
result["language_info"]["version"] = SQLite::VERSION;
result["language_info"]["mimetype"] = "";
result["language_info"]["file_extension"] = "";
return result;
}
void interpreter::shutdown_request_impl()
{
}
}
| 34.453608 | 113 | 0.452253 | [
"object",
"vector"
] |
65af994a099640dd5a6d9ea54c249204e55a9637 | 1,999 | cpp | C++ | test/Passes/Synthesis/diagonal_synth.cpp | zeta1999/tweedledum | f070bf582347668f96943a459e51e1a39572b7f4 | [
"MIT"
] | 1 | 2022-03-04T21:44:26.000Z | 2022-03-04T21:44:26.000Z | test/Passes/Synthesis/diagonal_synth.cpp | CQCL/tweedledum | f070bf582347668f96943a459e51e1a39572b7f4 | [
"MIT"
] | null | null | null | test/Passes/Synthesis/diagonal_synth.cpp | CQCL/tweedledum | f070bf582347668f96943a459e51e1a39572b7f4 | [
"MIT"
] | 1 | 2021-04-12T06:17:06.000Z | 2021-04-12T06:17:06.000Z | /*------------------------------------------------------------------------------
| Part of Tweedledum Project. This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
*-----------------------------------------------------------------------------*/
#include "tweedledum/Passes/Synthesis/diagonal_synth.h"
#include "tweedledum/IR/Circuit.h"
#include "tweedledum/IR/Wire.h"
#include "tweedledum/Operators/Standard.h"
#include "tweedledum/Utils/Angle.h"
#include "../check_unitary.h"
#include <catch.hpp>
#include <nlohmann/json.hpp>
#include <vector>
TEST_CASE("Trivial cases for diagonal_synth", "[diagonal_synth][synth]")
{
using namespace tweedledum;
nlohmann::json config;
SECTION("Double-control Z") {
Circuit expected;
WireRef q0 = expected.create_qubit();
WireRef q1 = expected.create_qubit();
WireRef q2 = expected.create_qubit();
expected.apply_operator(Op::P(sym_angle::pi), {q1, q2, q0});
std::vector<Angle> angles(7, sym_angle::zero);
angles.push_back(sym_angle::pi);
Circuit synthesized = diagonal_synth(angles, config);
CHECK(check_unitary(expected, synthesized));
}
SECTION("Double-control Rx ~ CX") {
Circuit expected;
WireRef q0 = expected.create_qubit();
WireRef q1 = expected.create_qubit();
WireRef q2 = expected.create_qubit();
expected.apply_operator(Op::Rx(sym_angle::pi), {q1, q2, q0});
std::vector<Angle> angles(6, sym_angle::zero);
angles.push_back(-sym_angle::pi_half);
angles.push_back(sym_angle::pi_half);
Circuit synthesized;
synthesized.create_qubit();
synthesized.create_qubit();
synthesized.create_qubit();
synthesized.apply_operator(Op::H(), {q0});
diagonal_synth(synthesized, {q1, q2, q0}, angles, config);
synthesized.apply_operator(Op::H(), {q0});
CHECK(check_unitary(expected, synthesized));
}
} | 37.716981 | 80 | 0.613807 | [
"vector"
] |
65b7da57d02a466c59a22bb5788d95b9dba17244 | 2,248 | hpp | C++ | laser_mapper/include/laser_mapper/laser_mapper.hpp | shibowing/segmatch | 4c93c465108f0a6e103526486aae894ea3d2ae9f | [
"BSD-3-Clause"
] | 13 | 2018-11-28T12:02:48.000Z | 2021-12-22T01:04:49.000Z | laser_mapper/include/laser_mapper/laser_mapper.hpp | yuekaka/segmatch | c662324d23b9e049fbb49b52cda7895d1a4d2798 | [
"BSD-3-Clause"
] | 2 | 2019-03-03T01:50:51.000Z | 2019-08-19T08:06:41.000Z | laser_mapper/include/laser_mapper/laser_mapper.hpp | yuekaka/segmatch | c662324d23b9e049fbb49b52cda7895d1a4d2798 | [
"BSD-3-Clause"
] | 8 | 2019-06-18T19:40:35.000Z | 2020-06-15T17:43:06.000Z | #ifndef LASER_MAPPER_LASER_MAPPER_HPP_
#define LASER_MAPPER_LASER_MAPPER_HPP_
#include <string>
#include <vector>
#include <laser_slam/parameters.hpp>
#include <laser_slam/incremental_estimator.hpp>
#include <laser_slam_ros/laser_slam_worker.hpp>
#include <segmatch/common.hpp>
#include <segmatch_ros/common.hpp>
#include <segmatch_ros/segmatch_worker.hpp>
#include <std_srvs/Empty.h>
#include <tf/transform_broadcaster.h>
#include "laser_mapper/SaveMap.h"
struct LaserMapperParams {
bool clear_local_map_after_loop_closure = true;
// Enable publishing a tf transform from world to odom.
bool publish_world_to_odom;
std::string world_frame;
double tf_publication_rate_hz;
// Trajectory estimator parameters.
laser_slam::EstimatorParams online_estimator_params;
}; // struct LaserMapperParams
class LaserMapper {
public:
explicit LaserMapper(ros::NodeHandle& n);
~LaserMapper();
/// \brief A thread function for handling map publishing.
void publishMapThread();
/// \brief A thread function for updating the transform between world and odom.
void publishTfThread();
/// \brief A thread function for localizing and closing loops with SegMatch.
void segMatchThread();
protected:
/// \brief Call back of the save_map service.
bool saveMapServiceCall(laser_mapper::SaveMap::Request& request,
laser_mapper::SaveMap::Response& response);
private:
// Get ROS parameters.
void getParameters();
// Node handle.
ros::NodeHandle& nh_;
// Parameters.
LaserMapperParams params_;
tf::TransformBroadcaster tf_broadcaster_;
// Services.
ros::ServiceServer save_distant_map_;
ros::ServiceServer save_map_;
// Incremental estimator.
std::shared_ptr<laser_slam::IncrementalEstimator> incremental_estimator_;
// SegMatch objects.
segmatch_ros::SegMatchWorkerParams segmatch_worker_params_;
segmatch_ros::SegMatchWorker segmatch_worker_;
static constexpr double kSegMatchThreadRate_hz = 3.0;
unsigned int next_track_id_ = 0u;
// laser_slam objects.
std::unique_ptr<laser_slam_ros::LaserSlamWorker> laser_slam_worker_;
laser_slam_ros::LaserSlamWorkerParams laser_slam_worker_params_;
}; // LaserMapper
#endif /* LASER_MAPPER_LASER_MAPPER_HPP_ */
| 27.414634 | 81 | 0.771797 | [
"vector",
"transform"
] |
65ba0fa0d41b1eb8478f62b034e9c7fc393c8afe | 131 | cpp | C++ | RobWork/src/rw/geometry/OBBCollider.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | 1 | 2021-12-29T14:16:27.000Z | 2021-12-29T14:16:27.000Z | RobWork/src/rw/geometry/OBBCollider.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | RobWork/src/rw/geometry/OBBCollider.cpp | ZLW07/RobWork | e713881f809d866b9a0749eeb15f6763e64044b3 | [
"Apache-2.0"
] | null | null | null | #include "OBBCollider.hpp"
template class rw::geometry::OBBCollider< double >;
template class rw::geometry::OBBCollider< float >;
| 26.2 | 51 | 0.763359 | [
"geometry"
] |
65c4c6e33aef9e9edc07deb7d1ded4155812e30d | 8,574 | hpp | C++ | include/AnnGameObject.hpp | Ybalrid/Annwvyn | 30d63c722524c35a9054d51dcdd9f39af0599a3d | [
"MIT"
] | 39 | 2015-04-02T15:32:19.000Z | 2022-03-26T12:48:28.000Z | include/AnnGameObject.hpp | Ybalrid/Annwvyn | 30d63c722524c35a9054d51dcdd9f39af0599a3d | [
"MIT"
] | 136 | 2015-02-24T19:45:59.000Z | 2019-02-21T15:01:12.000Z | include/AnnGameObject.hpp | Ybalrid/Annwvyn | 30d63c722524c35a9054d51dcdd9f39af0599a3d | [
"MIT"
] | 12 | 2015-02-24T19:37:38.000Z | 2019-05-13T12:07:26.000Z | /**
* \file AnnGameObject.hpp
* \brief Game Object class
* \author A. Brainville (Ybalrid)
*/
#pragma once
#include "systemMacro.h"
#include <string>
#include <BtOgrePG.h>
//Annwvyn
#include "AnnTypes.h"
#include "AnnAbstractMovable.hpp"
#pragma warning(default : 4996)
namespace Annwvyn
{
class AnnDllExport AnnGameObjectManager;
class AnnBehaviorScript;
class AnnAudioSource;
///An object that exist in the game. Graphically and Potentially Physically
class AnnDllExport AnnGameObject : public AnnAbstractMovable
{
public:
///Class constructor
AnnGameObject();
///Deleted AnnGameObject Copy Constructor
AnnGameObject(const AnnGameObject&) = delete;
///Class Destructor. Virtual.
virtual ~AnnGameObject();
///Set position from spatial variables
/// \param x X component of the position vector
/// \param y Y component of the position vector
/// \param z Z component of the position vector
void setPosition(float x, float y, float z);
///Set position from Vector 3D
/// \param pos 3D position vector. Relative to scene root position
void setPosition(AnnVect3 pos) override;
///Set the world position from a vector
/// \param pos 3D position vector. Relative to scene root position
void setWorldPosition(AnnVect3 pos) const;
///Set the world position from a few floats
/// \param x X component of the position vector
/// \param y Y component of the position vector
/// \param z Z component of the position vector
void setWorldPosition(float x, float y, float z) const;
///Translate
/// \param x X component of the translation vector
/// \param y Y component of the translation vector
/// \param z Z component of the translation vector
void translate(float x, float y, float z) const;
///Set orientation from Quaternion components
/// \param w W component of the quaternion
/// \param x X component of the quaternion
/// \param y Y component of the quaternion
/// \param z Z component of the quaternion
void setOrientation(float w, float x, float y, float z);
///Set Orientation from Quaternion
/// \param orient Quaternion for absolute orientation
void setOrientation(AnnQuaternion orient) override;
///Set the world orientation as a quaternion
/// \param orient Quaternion for absolute orientation
void setWorldOrientation(AnnQuaternion orient) const;
///Set the world orientation as some floats
/// \param w W component of the quaternion
/// \param x X component of the quaternion
/// \param y Y component of the quaternion
/// \param z Z component of the quaternion
void setWorldOrientation(float w, float x, float y, float z) const;
///Set scale
/// \param x X component of the scale vector
/// \param y Y component of the scale vector
/// \param z Z component of the scale vector
/// \param scaleMass If set to true (by default) will update the mass of the rigid body to reflect the change in size (constant density)
void setScale(float x, float y, float z, bool scaleMass = true) const;
///Set scale from Vector 3D
/// \param scale Relative scaling factor
/// \param scaleMass will adjust the mass accoring to the scaling vector. true by default
void setScale(AnnVect3 scale, bool scaleMass = true) const;
///Get Position
AnnVect3 getPosition() override;
///Get the position in world
AnnVect3 getWorldPosition() const;
///Get Orientation
AnnQuaternion getOrientation() override;
///Get the world orientation
AnnQuaternion getWorldOrientation() const;
///Get scale
AnnVect3 getScale() const;
///Get Ogre Node
Ogre::SceneNode* getNode() const;
///Get the item of this object
Ogre::Item* getItem() const;
///Get Rigid rigidBody
btRigidBody* getBody() const;
///Get distance from another object
/// \param otherObject The object we're counting the distance from
float getDistance(AnnGameObject* otherObject) const;
///Play a sound file
/// \param name Name of the audio file in a resource location
/// \param loop If set to true, will play the sound in loop
/// \param volume Floating point number between 0 and 1 to set the loudness of the sound
void playSound(const std::string& name, bool loop = false, float volume = 1.0f) const;
///Set currently playing animation
/// \param name Name of the animation as defined by the 3D entity
void setAnimation(const std::string& name);
///Set if we want to play the animation
/// \param play the playing state we want to apply
void playAnimation(bool play = true) const;
///Loop the animation ?
/// \param loop the looping state of the animation
void loopAnimation(bool loop = true) const;
///Apply a physical force
/// \param force Force vector that will be applied to the center of mass of the object
void applyForce(AnnVect3 force) const;
///Apply a physical impulsion
/// \param impulse the impulsion force
void applyImpulse(AnnVect3 impulse) const;
///Set the linear speed of the object
/// \param v The linear speed
void setLinearSpeed(AnnVect3 v) const;
///Set the friction coefficient
///See the "Results" table from this page : https://www.thoughtspike.com/friction-coefficients-for-bullet-physics/
/// \param coef friction coef applied to this object's body
void setFrictionCoef(float coef) const;
///Set up Physics
/// \param mass The mass of the object
/// \param type The type of shape you want to define for the object
/// \praam hasPlayerCollision if set to true (by default) object can colide with the player body representation
void setupPhysics(float mass = 0, phyShapeType type = staticShape, bool hasPlayerCollision = true);
///Make the object visible
void setVisible() const;
///Make the object invisible
void setInvisible() const;
///Return the name of the object
std::string getName() const;
///Attach a script to this object
/// \param scriptName name of a script
void attachScript(const std::string& scriptName);
///Return true if node is attached to the node owned by another AnnGameObject
bool hasParent() const;
///Get the parent Game Object
std::shared_ptr<AnnGameObject> getParent() const;
///Attach an object to this object.
/// \param child The object you want to attach
void attachChildObject(std::shared_ptr<AnnGameObject> child) const;
///Make the node independent to any GameObject
void detachFromParent() const;
///Recursively check if any parent has a body, if one is found, returns true
bool checkForBodyInParent();
///Recursively check if any child has a body, if one is found, returns true
bool checkForBodyInChild();
private:
///The GameObjectManager populate the content of this object when it goes through it's initialization
friend class AnnEngine;
friend class AnnGameObjectManager;
//------------------ local utility
///Do the actual recursion of checkForBodyInParent
/// \param obj object to check (for recursion)
bool parentsHaveBody(AnnGameObject* obj) const;
///Do the actual recursion of checkForBodyInChild
/// \param obj object to check (for recursion)
static bool childrenHaveBody(AnnGameObject* obj);
//----------------- engine utility
///For engine : set node
/// \param node ogre SceneNode
void setNode(Ogre::SceneNode* node);
///For engine : set item
/// \param item Ogre::Item
void setItem(Ogre::Item* item);
///For engine : get elapsed time
/// \param offsetTime time to add to the animation
void addAnimationTime(double offsetTime) const;
///For engine : update OpenAL source position
void updateOpenAlPos() const;
///SceneNode. This also holds the position/orientation/scale of the object
Ogre::SceneNode* sceneNode;
///Entity
Ogre::Item* model3D;
///Currently selected animation
Ogre::SkeletonAnimation* currentAnimation;
///Bullet shape
btCollisionShape* collisionShape;
///Bullet rigid body
btRigidBody* rigidBody;
///Mass of the rigid body
float bodyMass;
///AnnAudioEngine audioSource;
std::shared_ptr<AnnAudioSource> audioSource;
///Name of the object
std::string name;
///RigidBodyState of this object
BtOgre::RigidBodyState* state;
///list of script objects
std::vector<std::shared_ptr<AnnBehaviorScript>> scripts;
public:
///Executed after object initialization
virtual void postInit() {}
///Executed at refresh time (each frames)
virtual void update() {}
///Call the update methods of all the script present in the scripts container
void callUpdateOnScripts();
};
using AnnGameObjectPtr = std::shared_ptr<AnnGameObject>;
}
| 31.638376 | 138 | 0.724049 | [
"object",
"shape",
"vector",
"3d"
] |
65c637630c21385dc253e7b676606ab7462747cc | 7,856 | cpp | C++ | Assassin/TransferTask.cpp | Jhovany200/Nagisa | b0197c50866883d53a029b6614decdc12975f7f4 | [
"MIT"
] | 1 | 2020-07-31T02:41:51.000Z | 2020-07-31T02:41:51.000Z | Assassin/TransferTask.cpp | MS-PC2/Nagisa | b0197c50866883d53a029b6614decdc12975f7f4 | [
"MIT"
] | null | null | null | Assassin/TransferTask.cpp | MS-PC2/Nagisa | b0197c50866883d53a029b6614decdc12975f7f4 | [
"MIT"
] | null | null | null | /******************************************************************************
Project: Assassin
Description: Implementation for TransferTask.
File Name: TransferTask.cpp
License: The MIT License
******************************************************************************/
#include "pch.h"
#include "TransferManager.h"
#include "TransferTask.h"
using namespace Assassin;
using namespace Platform;
using Windows::Networking::BackgroundTransfer::BackgroundDownloadProgress;
using Windows::Networking::BackgroundTransfer::BackgroundTransferStatus;
TransferTask::TransferTask(
String^ Guid,
ApplicationDataCompositeValue^ TaskConfig,
M2::CFutureAccessList& FutureAccessList,
std::map<String^, DownloadOperation^>& DownloadOperationMap) :
m_Guid(Guid),
m_TaskConfig(TaskConfig)
{
this->m_SourceUri = ref new Uri(dynamic_cast<String^>(
TaskConfig->Lookup(L"SourceUri")));
this->m_FileName = dynamic_cast<String^>(
TaskConfig->Lookup(L"FileName"));
this->m_Status = static_cast<TransferTaskStatus>(
dynamic_cast<Windows::Foundation::IPropertyValue^>(
TaskConfig->Lookup(L"Status"))->GetUInt8());
try
{
this->m_SaveFolder = dynamic_cast<IStorageFolder^>(M2AsyncWait(
FutureAccessList.GetItemAsync(dynamic_cast<String^>(
TaskConfig->Lookup(L"SaveFolder")))));
if (nullptr != this->m_SaveFolder)
{
this->m_SaveFile = M2AsyncWait(
this->m_SaveFolder->GetFileAsync(this->m_FileName));
}
std::map<String^, DownloadOperation^>::iterator iterator =
DownloadOperationMap.find(dynamic_cast<String^>(
TaskConfig->Lookup(L"BackgroundTransferGuid")));
this->m_Operation = (DownloadOperationMap.end() != iterator)
? iterator->second : nullptr;
if (nullptr == this->m_Operation)
{
M2ThrowPlatformException(E_FAIL);
}
BackgroundDownloadProgress Progress = this->m_Operation->Progress;
this->m_BytesReceived = Progress.BytesReceived;
this->m_TotalBytesToReceive = Progress.TotalBytesToReceive;
if (TransferTaskStatus::Running == this->Status)
{
this->m_Operation->AttachAsync();
}
}
catch (...)
{
switch (this->m_Status)
{
case TransferTaskStatus::Paused:
case TransferTaskStatus::Queued:
case TransferTaskStatus::Running:
this->m_Status = TransferTaskStatus::Error;
break;
default:
break;
}
}
}
void TransferTask::UpdateChangedProperties()
{
using Windows::Networking::BackgroundTransfer::BackgroundDownloadProgress;
if (nullptr != this->m_Operation)
{
switch (this->m_Operation->Progress.Status)
{
case BackgroundTransferStatus::Idle:
this->m_Status = TransferTaskStatus::Queued;
break;
case BackgroundTransferStatus::Running:
case BackgroundTransferStatus::PausedCostedNetwork:
case BackgroundTransferStatus::PausedNoNetwork:
case BackgroundTransferStatus::PausedSystemPolicy:
this->m_Status = TransferTaskStatus::Running;
break;
case BackgroundTransferStatus::PausedByApplication:
this->m_Status = TransferTaskStatus::Paused;
break;
case BackgroundTransferStatus::Completed:
this->m_Status = TransferTaskStatus::Completed;
break;
case BackgroundTransferStatus::Canceled:
this->m_Status = TransferTaskStatus::Canceled;
break;
case BackgroundTransferStatus::Error:
default:
this->m_Status = TransferTaskStatus::Error;
break;
}
if (TransferTaskStatus::Running != this->m_Status)
return;
BackgroundDownloadProgress Progress = this->m_Operation->Progress;
ULONGLONG LastTickCount = this->m_TickCount;
this->m_TickCount = M2GetTickCount();
uint64 LastBytesReceived = this->m_BytesReceived;
this->m_BytesReceived = Progress.BytesReceived;
this->m_TotalBytesToReceive = Progress.TotalBytesToReceive;
uint64 DeltaBytesReceived = this->m_BytesReceived - LastBytesReceived;
ULONGLONG DeltaPassedTime = this->m_TickCount - LastTickCount;
this->m_BytesReceivedSpeed =
DeltaBytesReceived * 1000 / DeltaPassedTime;
if (0 == this->m_BytesReceivedSpeed ||
0 == this->m_TotalBytesToReceive)
{
this->m_RemainTime = static_cast<uint64>(-1);
}
else
{
uint64 RemainBytesToReceive =
this->m_TotalBytesToReceive - this->m_BytesReceived;
this->m_RemainTime =
RemainBytesToReceive / this->m_BytesReceivedSpeed;
}
}
}
void TransferTask::RaisePropertyChanged(
String ^ PropertyName)
{
using Windows::UI::Xaml::Data::PropertyChangedEventArgs;
this->PropertyChanged(
this, ref new PropertyChangedEventArgs(PropertyName));
}
void TransferTask::NotifyPropertyChanged()
{
using Windows::Networking::BackgroundTransfer::BackgroundDownloadProgress;
if (nullptr != this->m_Operation)
{
this->RaisePropertyChanged(L"Status");
if (TransferTaskStatus::Running == this->m_Status)
{
this->RaisePropertyChanged(L"BytesReceived");
this->RaisePropertyChanged(L"TotalBytesToReceive");
this->RaisePropertyChanged(L"BytesReceivedSpeed");
this->RaisePropertyChanged(L"RemainTime");
}
}
}
ApplicationDataCompositeValue^ TransferTask::GetTaskConfig()
{
this->m_TaskConfig->Insert(
L"Status",
Windows::Foundation::PropertyValue::CreateUInt8(
static_cast<uint8>(this->Status)));
return this->m_TaskConfig;
}
// Gets the Guid string of the task.
String^ TransferTask::Guid::get()
{
return this->m_Guid;
}
// Gets the URI which to download the file.
Uri^ TransferTask::SourceUri::get()
{
return this->m_SourceUri;
}
// Gets the file name which to download the file.
String^ TransferTask::FileName::get()
{
return this->m_FileName;
}
// Gets the save file object which to download the file.
IStorageFile^ TransferTask::SaveFile::get()
{
return this->m_SaveFile;
}
// Gets the save folder object which to download the file.
IStorageFolder^ TransferTask::SaveFolder::get()
{
return this->m_SaveFolder;
}
// The current status of the task.
TransferTaskStatus TransferTask::Status::get()
{
return this->m_Status;
}
// The total number of bytes received. This value does not include
// bytes received as response headers. If the task has restarted,
// this value may be smaller than in the previous progress report.
uint64 TransferTask::BytesReceived::get()
{
return this->m_BytesReceived;
}
// The speed of bytes received in one second.
uint64 TransferTask::BytesReceivedSpeed::get()
{
return this->m_BytesReceivedSpeed;
}
// The remain time, in seconds.
uint64 TransferTask::RemainTime::get()
{
return this->m_RemainTime;
}
// The total number of bytes of data to download. If this number is
// unknown, this value is set to 0.
uint64 TransferTask::TotalBytesToReceive::get()
{
return this->m_TotalBytesToReceive;
}
// Pauses a download operation.
// Parameters:
// The function does not have parameters.
// Return value:
// The function does not return a value.
void TransferTask::Pause()
{
if (TransferTaskStatus::Running == this->Status)
{
if (nullptr != this->m_Operation)
{
this->m_Operation->Pause();
}
else
{
this->m_Status = TransferTaskStatus::Error;
}
}
}
// Resumes a paused download operation.
// Parameters:
// The function does not have parameters.
// Return value:
// The function does not return a value.
void TransferTask::Resume()
{
if (TransferTaskStatus::Paused == this->Status)
{
if (nullptr != this->m_Operation)
{
this->m_Operation->Resume();
this->m_Operation->AttachAsync();
}
else
{
this->m_Status = TransferTaskStatus::Error;
}
}
}
// Cancels a download operation.
// Parameters:
// The function does not have parameters.
// Return value:
// The function does not return a value.
void TransferTask::Cancel()
{
switch (this->Status)
{
case TransferTaskStatus::Paused:
case TransferTaskStatus::Queued:
case TransferTaskStatus::Running:
if (nullptr != this->m_Operation)
{
this->m_Operation->AttachAsync()->Cancel();
}
else
{
this->m_Status = TransferTaskStatus::Error;
}
break;
default:
break;
}
}
| 25.673203 | 80 | 0.724669 | [
"object"
] |
65c908c53e6a805223e3819d97b33120657241a5 | 5,008 | cpp | C++ | Examples/pbr/main.cpp | teamclouday/Render | c24eb5d5a51452cbb092ead61612559e57951755 | [
"MIT"
] | null | null | null | Examples/pbr/main.cpp | teamclouday/Render | c24eb5d5a51452cbb092ead61612559e57951755 | [
"MIT"
] | null | null | null | Examples/pbr/main.cpp | teamclouday/Render | c24eb5d5a51452cbb092ead61612559e57951755 | [
"MIT"
] | null | null | null | #include "Base.hpp"
#include <string>
#include <iostream>
using namespace RenderIt;
// a sphere
struct MyModel
{
StructVAO vao;
uint32_t vertexCount;
glm::vec3 color = glm::vec3(0.5f, 1.0f, 1.0f);
glm::vec2 metallicRoughness = glm::vec2(0.5f);
float radius = 1.0f;
float tessLevel = 20.0f;
float mixFactor = 1.0f;
bool roughNorm = false;
StructModelTransform transform;
StructShaderDescriptorPBR shaderDesc;
}* model;
Application* app;
Camera* camera;
Lights* lights;
void myUI()
{
if(camera && ImGui::BeginTabItem("Camera Config"))
{
camera->UI();
ImGui::EndTabItem();
}
if(lights && ImGui::BeginTabItem("Lights Config"))
{
lights->UI();
ImGui::EndTabItem();
}
if(model && ImGui::BeginTabItem("Model Config"))
{
ImGui::ColorEdit3("Color", &model->color[0]);
ImGui::DragFloat("Radius", &model->radius, 0.001f, 0.001f);
ImGui::DragFloat("Metallic", &model->metallicRoughness.x, 0.001f, 0.0f, 1.0f);
ImGui::DragFloat("Roughness", &model->metallicRoughness.y, 0.001f, 0.0f, 1.0f);
ImGui::DragFloat("TessLevel", &model->tessLevel, 1.0f, 1.0f, 100.0f, "%.0f");
ImGui::DragFloat("MixFactor", &model->mixFactor, 0.01f, 0.0f, 1.0f, "%.2f");
ImGui::Checkbox("Rough Normal", &model->roughNorm);
ImGui::SetNextTreeNodeOpen(false, ImGuiCond_FirstUseEver);
if(ImGui::CollapsingHeader("Transform"))
{
ImGui::DragFloat3("Translation", &model->transform.m_translate[0], 0.001f);
ImGui::DragFloat("Scale", &model->transform.m_scale, 0.001f, 0.001f);
ImGui::DragFloat("Rotate Axis", &model->transform.m_rotate_axis[0], 0.001f);
ImGui::DragFloat("Rotate Angle", &model->transform.m_rotate_angle, 0.5f);
}
ImGui::EndTabItem();
}
}
int main()
{
app = &Application::instance("PBR Example");
if(!app->initialized) return -1;
// app->toggleGLDebug();
// set camera
camera = &Camera::instance(
glm::vec3(0.0f, 0.0f, 4.0f),
glm::vec3(0.0f, 0.0f, 0.0f)
);
app->attachCamera(*camera);
// prepare shader
std::string shaderVertex =
#include "shader.vert.glsl"
;
std::string shaderFragment =
#include "shader.frag.glsl"
;
std::string shaderTessControl =
#include "shader.tesc.glsl"
;
std::string shaderTessEval =
#include "shader.tese.glsl"
;
std::string shaderGeom =
#include "shader.geom.glsl"
;
Shader shader;
shader.add(shaderVertex, GL_VERTEX_SHADER);
shader.add(shaderFragment, GL_FRAGMENT_SHADER);
shader.add(shaderTessControl, GL_TESS_CONTROL_SHADER);
shader.add(shaderTessEval, GL_TESS_EVALUATION_SHADER);
shader.add(shaderGeom, GL_GEOMETRY_SHADER);
if(!shader.compile()) return -1;
// prepare model
const float vertices[] =
{
#include "cube.txt"
};
model = new MyModel();
model->vertexCount = sizeof(vertices) / sizeof(float) / 3;
model->transform.m_scale = 0.5f;
model->metallicRoughness = glm::vec2(0.2f, 0.8f);
model->vao.bind();
StructBuffer VBO = StructBuffer(GL_ARRAY_BUFFER);
VBO.bind();
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
VBO.unbind();
model->vao.unbind();
// prepare lights
lights = new Lights();
lights->attach(shader);
lights->addDirLight();
glm::mat4 m_model(1.0f);
glm::mat4 m_view(1.0f);
glm::mat4 m_proj(1.0f);
StructShaderDescriptor shaderDescriptor;
while(!app->windowShouldClose())
{
app->loopLogic();
app->loopStartFrame();
app->loopConfigFrame();
camera->drawSkybox();
shader.bind();
camera->bindSkybox(shader);
lights->set();
m_model = model->transform.getMatrix();
m_view = camera->view();
m_proj = camera->projection();
shader.uniformMat4(shaderDescriptor.m_model.c_str(), m_model);
shader.uniformMat4(shaderDescriptor.m_view.c_str(), m_view);
shader.uniformMat4(shaderDescriptor.m_proj.c_str(), m_proj);
shader.uniformVec3(
shaderDescriptor.v_camera_pos.c_str(),
camera->getPos()
);
shader.uniformVec3("sphereColor", model->color);
shader.uniformVec2("metallicRoughness", model->metallicRoughness);
shader.uniformFloat("tessLevel", model->tessLevel);
shader.uniformFloat("sphereRadius", model->radius);
shader.uniformFloat("mixFactor", model->mixFactor);
shader.uniformBool("roughNorm", model->roughNorm);
model->vao.bind();
glDrawArrays(GL_PATCHES, 0, model->vertexCount);
model->vao.unbind();
shader.unbind();
app->loopTabUI(myUI);
app->loopEndFrame();
}
return 0;
}
| 29.28655 | 88 | 0.621206 | [
"model",
"transform"
] |
65c9374f3e1598a0867ea26b73291d6a0c9b5070 | 1,431 | cpp | C++ | aws-cpp-sdk-clouddirectory/source/model/ListOutgoingTypedLinksResult.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-clouddirectory/source/model/ListOutgoingTypedLinksResult.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-clouddirectory/source/model/ListOutgoingTypedLinksResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/clouddirectory/model/ListOutgoingTypedLinksResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::CloudDirectory::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListOutgoingTypedLinksResult::ListOutgoingTypedLinksResult()
{
}
ListOutgoingTypedLinksResult::ListOutgoingTypedLinksResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListOutgoingTypedLinksResult& ListOutgoingTypedLinksResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("TypedLinkSpecifiers"))
{
Array<JsonView> typedLinkSpecifiersJsonList = jsonValue.GetArray("TypedLinkSpecifiers");
for(unsigned typedLinkSpecifiersIndex = 0; typedLinkSpecifiersIndex < typedLinkSpecifiersJsonList.GetLength(); ++typedLinkSpecifiersIndex)
{
m_typedLinkSpecifiers.push_back(typedLinkSpecifiersJsonList[typedLinkSpecifiersIndex].AsObject());
}
}
if(jsonValue.ValueExists("NextToken"))
{
m_nextToken = jsonValue.GetString("NextToken");
}
return *this;
}
| 28.62 | 142 | 0.779874 | [
"model"
] |
65d451be05ef92b0f5eec655829f97be8a761f08 | 9,130 | hpp | C++ | nodes.hpp | flode/BwTree | c68015e9be3ddb3e4aa76983ce3a7cc75c6fa28c | [
"Apache-2.0"
] | 93 | 2015-06-12T21:29:44.000Z | 2022-01-09T13:21:13.000Z | nodes.hpp | flode/BwTree | c68015e9be3ddb3e4aa76983ce3a7cc75c6fa28c | [
"Apache-2.0"
] | 3 | 2016-04-02T18:29:52.000Z | 2020-05-10T14:04:05.000Z | nodes.hpp | flode/BwTree | c68015e9be3ddb3e4aa76983ce3a7cc75c6fa28c | [
"Apache-2.0"
] | 20 | 2016-02-13T23:41:35.000Z | 2021-04-04T14:26:04.000Z | #ifndef NODES_HPP
#define NODES_HPP
#include <algorithm>
#include <vector>
#include <tuple>
namespace BwTree {
using PID = std::size_t;
constexpr PID NotExistantPID = std::numeric_limits<PID>::max();
enum class PageType : std::int8_t {
leaf,
inner,
deltaInsert,
deltaDelete,
deltaIndex,
deltaSplit,
deltaSplitInner
};
template<typename Key, typename Data>
struct Node {
protected:
PageType type;
public:
const PageType &getType() const {
return type;
}
};
template<typename Key, typename Data>
struct LinkedNode : Node<Key, Data> {
PID prev;
PID next;
};
template<typename Key, typename Data>
struct KeyValue {
Key key;
const Data *data;
KeyValue(const Key &key, const Data *const & data) : key(key), data(data) { }
KeyValue operator=(const KeyValue &keyValue) {
key = keyValue.key;
data = keyValue.data;
return *this;
}
KeyValue() { }
};
template<typename Key, typename Data>
struct Leaf : LinkedNode<Key, Data> {
std::size_t recordCount;
// has to be last member for dynamic operator new() !!!
KeyValue<Key, Data> records[];
static Leaf<Key, Data> *create(std::size_t size, const PID &prev, const PID &next) {
size_t s = sizeof(Leaf<Key, Data>) + size * sizeof(std::tuple<Key, const Data *>);
Leaf<Key, Data> *output = (Leaf<Key, Data> *) operator new(s);
output->recordCount = size;
output->type = PageType::leaf;
output->next = next;
output->prev = prev;
return output;
}
private:
Leaf() = delete;
~Leaf() = delete;
};
template<typename Key, typename Data>
struct KeyPid {
Key key;
PID pid;
KeyPid(const Key key, const PID pid) : key(key), pid(pid) { }
};
template<typename Key, typename Data>
struct InnerNode : LinkedNode<Key, Data> {
std::size_t nodeCount;
// has to be last member for dynamic operator new() !!!
KeyPid<Key, Data> nodes[];
static InnerNode<Key, Data> *create(std::size_t size, const PID &prev, const PID &next) {
size_t s = sizeof(InnerNode<Key, Data>) + size * sizeof(std::tuple<Key, PID>);
InnerNode<Key, Data> *output = (InnerNode<Key, Data> *) operator new(s);
output->nodeCount = size;
output->type = PageType::inner;
output->next = next;
output->prev = prev;
return output;
}
private:
InnerNode() = delete;
~InnerNode() = delete;
};
template<typename Key, typename Data>
struct DeltaNode : Node<Key, Data> {
Node<Key, Data> *origin;
private:
DeltaNode() = delete;
~DeltaNode() = delete;
};
template<typename Key, typename Data>
struct DeltaInsert : DeltaNode<Key, Data> {
KeyValue<Key, Data> record;
bool keyExistedBefore;
static DeltaInsert<Key, Data> *create(Node<Key, Data> *origin, const KeyValue<Key, Data> record, bool keyExistedBefore) {
size_t s = sizeof(DeltaInsert<Key, Data>);
DeltaInsert<Key, Data> *output = (DeltaInsert<Key, Data> *) operator new(s);
output->type = PageType::deltaInsert;
output->origin = origin;
output->record = record;
output->keyExistedBefore = keyExistedBefore;
return output;
}
private:
DeltaInsert() = delete;
~DeltaInsert() = delete;
};
template<typename Key, typename Data>
struct DeltaDelete : DeltaNode<Key, Data> {
Key key;
static DeltaDelete<Key, Data> *create(Node<Key, Data> *origin, Key key) {
size_t s = sizeof(DeltaDelete<Key, Data>);
DeltaDelete<Key, Data> *output = (DeltaDelete<Key, Data> *) operator new(s);
output->type = PageType::deltaDelete;
output->origin = origin;
output->key = key;
return output;
}
private:
DeltaDelete() = delete;
~DeltaDelete() = delete;
};
template<typename Key, typename Data>
struct DeltaSplit : DeltaNode<Key, Data> {
Key key;
PID sidelink;
std::size_t removedElements;
static DeltaSplit<Key, Data> *create(Node<Key, Data> *origin, Key splitKey, PID sidelink, std::size_t removedElements, bool leaf) {
size_t s = sizeof(DeltaSplit<Key, Data>);
DeltaSplit<Key, Data> *output = (DeltaSplit<Key, Data> *) operator new(s);
if (leaf) {
output->type = PageType::deltaSplit;
} else {
output->type = PageType::deltaSplitInner;
}
output->origin = origin;
output->key = splitKey;
output->sidelink = sidelink;
output->removedElements = removedElements;
return output;
}
private:
DeltaSplit() = delete;
~DeltaSplit() = delete;
};
template<typename Key, typename Data>
struct DeltaIndex : DeltaNode<Key, Data> {
Key keyLeft; // greater than
Key keyRight; // less or equal than
PID child;
PID oldChild;
static DeltaIndex<Key, Data> *create(Node<Key, Data> *origin, Key splitKeyLeft, Key splitKeyRight, PID child, PID oldChild) {
size_t s = sizeof(DeltaIndex<Key, Data>);
DeltaIndex<Key, Data> *output = (DeltaIndex<Key, Data> *) operator new(s);
output->type = PageType::deltaIndex;
output->origin = origin;
output->keyLeft = splitKeyLeft;
output->keyRight = splitKeyRight;
output->child = child;
output->oldChild = oldChild;
return output;
}
private:
DeltaIndex() = delete;
~DeltaIndex() = delete;
};
template<typename Key, typename Data>
class Helper {
//InnerNode<Key, Data> *CreateInnerNodeFromUnsorted(std::vector<std::tuple<Key, PID>>::const_iterator begin, std::vector<std::tuple<Key, PID>>::const_iterator end, const PID &next, const PID &prev, bool infinityElement);
//template<typename Key, typename Data>
public:
typedef typename std::vector<KeyPid<Key, Data>>::iterator InnerIterator;
static InnerNode<Key, Data> *CreateInnerNodeFromUnsorted(InnerIterator begin, InnerIterator end, const PID &prev, const PID &next, bool infinityElement) {
// construct a new node
auto newNode = InnerNode<Key, Data>::create(std::distance(begin, end), prev, next);
std::sort(begin, end, [](const KeyPid<Key, Data> &t1, const KeyPid<Key, Data> &t2) {
return t1.key < t2.key;
});
int i = 0;
for (auto it = begin; it != end; ++it) {
newNode->nodes[i++] = *it;
}
if (infinityElement) {
newNode->nodes[newNode->nodeCount - 1].key = std::numeric_limits<Key>::max();
}
return newNode;
}
typedef typename std::vector<KeyValue<Key, Data>>::iterator LeafIterator;
static Leaf<Key, Data> *CreateLeafNodeFromSorted(LeafIterator begin, LeafIterator end, const PID &prev,
const PID &next) {
// construct a new node
auto newNode = Leaf<Key, Data>::create(std::distance(begin, end), prev, next);
int i = 0;
for (auto it = begin; it != end; ++it) {
newNode->records[i++] = *it;
}
return newNode;
}
};
template<typename Key, typename Data>
void freeNodeRecursively(Node<Key, Data> *node);
template<typename Key, typename Data>
void freeNodeSingle(Node<Key, Data> *node) {
operator delete(node);
}
template<typename Key, typename Data>
void freeNodeRecursively(Node<Key, Data> *node) {
while (node != nullptr) {
switch (node->getType()) {
case PageType::inner: /* fallthrough */
case PageType::leaf: {
freeNodeSingle<Key, Data>(node);
return;
}
case PageType::deltaIndex: /* fallthrough */
case PageType::deltaDelete: /* fallthrough */
case PageType::deltaSplitInner: /* fallthrough */
case PageType::deltaSplit: /* fallthrough */
case PageType::deltaInsert: {
auto node1 = static_cast<DeltaNode<Key, Data> *>(node);
node = node1->origin;
freeNodeSingle<Key, Data>(node1);
continue;
}
default: {
assert(false);//all nodes have to be handeled
}
}
node = nullptr;
}
}
}
#endif | 31.923077 | 228 | 0.550931 | [
"vector"
] |
65d637788615dab61213f870bf5960cba2e5cb39 | 2,624 | cpp | C++ | inheritance-students.cpp | aammeloot/hdcyb-cpp2020 | c5ebe57803a587008d4ee7437a00c3193e9e4d2f | [
"CC0-1.0"
] | null | null | null | inheritance-students.cpp | aammeloot/hdcyb-cpp2020 | c5ebe57803a587008d4ee7437a00c3193e9e4d2f | [
"CC0-1.0"
] | null | null | null | inheritance-students.cpp | aammeloot/hdcyb-cpp2020 | c5ebe57803a587008d4ee7437a00c3193e9e4d2f | [
"CC0-1.0"
] | null | null | null | //
// main.cpp
// inheritance
//
// Created by Aurélien Ammeloot on 12/11/2020.
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// This is the base class - Person
class Person {
// Protected instead of Private so derived classed can access
protected:
string name;
string surname;
public:
// Standard constructor and methods below
Person(string _name, string _surname)
{
name = _name;
surname = _surname;
}
auto getFullName() { return name + " " + surname; }
};
// This is a derived class: student
// It's inheriting the members and methods of person
// The declaration mentions a link to Person
// public here ensures the public methods of Person are preserved
class Student: public Person
{
// Declaration of private members, usual way
private:
string studentID;
vector<string> subjects;
public:
// The constructor has a longer signature:
// Class(types arguments):BaseClass(arguments)
// Make sure the arguments for the base class are received by the
// derivative class too
Student(string _name, string _surname, string _studentID): Person(_name, _surname)
{
studentID = _studentID;
}
// Declare other members the same way
void addSubject(string subject)
{
// Add something to a vector
subjects.push_back(subject);
}
void listSubjects()
{
// This is a "foreach" loop
for (auto &subject: subjects)
{
cout << subject << endl;
}
}
};
// Same rules as student apply here
class Lecturer: public Person
{
private:
string staffID;
string subject;
public:
Lecturer(string _name, string _surname, string _staffID, string _subject = "nothing"): Person(_name, _surname)
{
staffID = _staffID;
subject = _subject;
}
auto getSubject() { return subject; }
void setSubject(string _subject) { subject = _subject; }
auto getStaffID() { return staffID; }
};
int main(int argc, const char * argv[]) {
// Creating a student and a lecturer
Student john("John", "Smith", "123456");
Lecturer fred("Fred", "Dickson", "7890", "Programming");
john.addSubject("Programming");
john.addSubject("Networking");
// The call below will run the code from the Person base class
cout << john.getFullName() << endl;
john.listSubjects();
cout << fred.getFullName() << endl;
// The call below will run the code from the Person base class
cout << fred.getSubject() << endl;
return 0;
}
| 24.523364 | 114 | 0.637957 | [
"vector"
] |
65d97546c66e97cf0f487e05b7fba5e15d9b4376 | 2,471 | hpp | C++ | libserver/ram_compiler/tinyram_precompiler.hpp | alittlehorse/osprey | 22f290a7de3413a847e3dc33c96328752cc37f47 | [
"MIT"
] | 5 | 2021-03-04T08:28:38.000Z | 2021-04-20T11:50:40.000Z | libserver/ram_compiler/tinyram_precompiler.hpp | alittlehorse/osprey | 22f290a7de3413a847e3dc33c96328752cc37f47 | [
"MIT"
] | null | null | null | libserver/ram_compiler/tinyram_precompiler.hpp | alittlehorse/osprey | 22f290a7de3413a847e3dc33c96328752cc37f47 | [
"MIT"
] | 1 | 2021-05-22T15:50:15.000Z | 2021-05-22T15:50:15.000Z | /** @file
*****************************************************************************
Declaration of interfaces for compiling tinyram(source language) to immediate language.
*****************************************************************************
* @author This file is part of libserver, developed by alittlehorse
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef OSPREY_TINYRAM_PRECOMPILER_HPP
#define OSPREY_TINYRAM_PRECOMPILER_HPP
#include <string>
#include <unordered_map>
#include<vector>
#include<libserver/aux_struct/Log.hpp>
namespace libserver{
class tinyram_precompiler {
public:
/// complie the tinyram file to immediate format.
/// \arg:: file_path:std::string&&
/// \return: bool and write the immediate format to the same path
bool complie_tinyram(std::string &&file_path,std::string&& out_name);
bool compile_tinyram(const std::string& input_string,std::string* out_string);
private:
Log* log;
const std::unordered_map<std::string,std::vector<std::string>> instruction_types=
{ {"and",{"des","arg1","arg2"}},
{"or",{"des","arg1","arg2"}},
{"xor",{"des","arg1","arg2"}},
{"not",{"des","arg2"}},
{"add",{"des","arg1","arg2"}},
{"sub",{"des","arg1","arg2"}},
{"mull",{"des","arg1","arg2"}},
{"umulh",{"des","arg1","arg2"}},
{"smulh",{"des","arg1","arg2"}},
{"udiv",{"des","arg1","arg2"}},
{"umod",{"des","arg1","arg2"}},
{"shl",{"des","arg1","arg2"}},
{"shr",{"des","arg1","arg2"}},
{"cmpe",{"arg1","arg2"}},
{"cmpa",{"arg1","arg2"}},
{"cmpae",{"arg1","arg2"}},
{"cmpg",{"arg1","arg2"}},
{"cmpge",{"arg1","arg2"}},
{"mov",{"des","arg2"}},
{"cmov",{"des","arg2"}},
{"jmp",{"arg2"}},
{"cjmp",{"arg2"}},
{"cnjmp",{"arg2"}},
{"opcode_10111",{}},
{"opcode_11000",{}},
{"opcode_11001",{}},
{"store.b",{"arg2","des"}},
{"load.b",{"des","arg2"}},
{"store.w",{"arg2","des"}},
{"load.w",{"des","arg2"}},
{"read",{"des","arg2"}},
{"answer",{"arg2"}}};
};
}
#endif //OSPREY_TINYRAM_PRECOMPILER_HPP
| 34.802817 | 88 | 0.445569 | [
"vector"
] |
65e031c844ed7f6a4646540e24ac369a79945424 | 9,026 | cpp | C++ | goliath/graph/node.cpp | hoenirvili/CFGTrace | 0ccb0b2f11634976eb220ec4a9cba3b90560537f | [
"MIT"
] | 3 | 2019-01-19T20:18:50.000Z | 2020-09-25T20:13:58.000Z | goliath/graph/node.cpp | hoenirvili/goliath | 0ccb0b2f11634976eb220ec4a9cba3b90560537f | [
"MIT"
] | null | null | null | goliath/graph/node.cpp | hoenirvili/goliath | 0ccb0b2f11634976eb220ec4a9cba3b90560537f | [
"MIT"
] | null | null | null | #include "goliath/graph/node.h"
#include "goliath/assembly/instruction.h"
#include "goliath/error/error.h"
#include "goliath/format/string.h"
#include <string>
void Node::mark_done() noexcept
{
this->is_done = true;
}
bool Node::done() const noexcept
{
return this->is_done;
}
size_t Node::true_neighbour() const noexcept
{
return this->true_branch_address;
}
size_t Node::false_neighbour() const noexcept
{
return this->false_branch_address;
}
void Node::append_instruction(assembly::instruction instruction,
size_t iteration) noexcept
{
size_t eip = instruction.pointer_address();
if (this->done() && this->contains_address(eip)) {
// if we are at the same node creation iteration count
// that means we have a loop
if (this->_iteration == iteration) {
this->already_visited(eip);
return;
}
return;
}
this->block.push_back(instruction);
}
void Node::append_branch_instruction(assembly::instruction instruction,
size_t iteration) noexcept
{
if (this->done())
return;
this->append_instruction(instruction, iteration);
if (!instruction.is_ret()) {
this->true_branch_address = instruction.true_branch_address();
this->false_branch_address = instruction.false_branch_address();
}
this->mark_done();
}
void Node::already_visited(size_t eip) noexcept
{
auto instruction = this->block[0];
if (instruction.pointer_address() == eip)
this->occurrences++;
}
bool Node::contains_address(size_t eip) const noexcept
{
for (const auto &instruction : this->block)
if (instruction.pointer_address() == eip)
return true;
return false;
}
bool Node::no_branching() const noexcept
{
// TODO(): Modify this. terminal_node
return (!this->true_branch_address && !this->false_branch_address &&
this->block.size());
}
/**
* ARRAY_SIZE returns the number of elements that an array has
*/
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
// pallet contains all the blues9 color scheme pallet
static const unsigned int pallet[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
static double inline precent(double is, double of) noexcept
{
return ((is / of) * 100);
}
/**
* pick_color
* for a given number of max occurrences and a fixed value
* return the color pallet number in graphviz format
* TODO(hoenir): this is still broken in certain cases
*/
static unsigned int pick_color(unsigned int max, unsigned int value) noexcept
{
if ((max == 1) && (value == 1))
return 1;
size_t n = ARRAY_SIZE(pallet);
const double split_in = 100.0 / n;
auto interval = std::vector<double>(n);
for (size_t i = 0; i < n; i++) {
interval[i] = split_in * (i + 1);
if (interval[i] == 100.0) // don't make this 100.0f
interval[i]--;
}
const auto fvalue = static_cast<float>(value);
const auto fmax = static_cast<float>(max);
const auto p = precent(fvalue, fmax);
if (p <= interval[0])
return 1;
if (p >= interval[n - 1])
return 9;
for (size_t i = 0; i < n - 1; i++) {
auto low = interval[i];
auto high = interval[i + 1];
if (p >= low && p <= high) {
const auto half = (high + low) / 2;
const auto pr = precent(p, half);
if (pr > 50.0)
return pallet[i + 1];
else
return pallet[i];
}
}
return 1;
}
size_t Node::start_address() const noexcept
{
return this->_start_address;
}
std::string Node::graphviz_color() const noexcept
{
if (this->no_branching())
return "color = \"plum1\"";
auto color = pick_color(this->max_occurrences, this->occurrences);
auto str = "colorscheme = blues9\n\t\tcolor = " + std::to_string(color);
if (color >= 7)
str += "\n\t\tfontcolor = white";
str += "\n";
return str;
}
std::string Node::gdl_color() const noexcept
{
if (this->no_branching())
return "12";
auto color = pick_color(this->max_occurrences, this->occurrences);
return std::to_string(color);
}
std::string Node::name() const noexcept
{
auto start = this->start_address();
if (start)
return format::string("0x%08X", start);
return "";
}
std::string Node::graphviz_label() const noexcept
{
std::string code_block = this->name() + "\\l";
if (this->block.size())
code_block += "\\l";
for (const auto &instruction : this->block) {
std::string bl = instruction.str();
code_block += bl + "\\l";
}
return "label = \"" + code_block + "\"";
}
std::string Node::gdl_label() const noexcept
{
std::string code_block = this->name();
if (this->block.size())
code_block += "\n";
for (const auto &instruction : this->block) {
std::string bl = instruction.str();
code_block += bl + "\n";
}
return code_block;
}
static const char *graphviz_definition_template = R"(
"%s" [
%s
%s
]
)";
static const char *gdl_definition_template = R"(
node: {
title: "%s"
color: %s
label: "%s
"}
)";
std::string Node::graphviz_definition() const
{
const auto name = this->name();
const auto label = this->graphviz_label();
const auto color = this->graphviz_color();
const auto nm = name.c_str();
const auto blk = label.c_str();
const auto colr = color.c_str();
return format::string(graphviz_definition_template, nm, blk, colr);
}
std::string Node::gdl_definition() const
{
const auto name = this->name();
const auto color = this->gdl_color();
const auto label = this->gdl_label();
const auto nm = name.c_str();
const auto colr = color.c_str();
const auto blk = label.c_str();
return format::string(gdl_definition_template, nm, colr, blk);
}
static inline std::string relation(size_t start, size_t end)
{
return format::string("\"0x%08X\" -> \"0x%08X\"", start, end);
}
std::string Node::graphviz_relation() const
{
std::string str = "";
size_t start = this->start_address();
if (this->true_branch_address) {
str += relation(start, this->true_branch_address);
str += " [color=green penwidth=2.0] \n";
}
if (this->false_branch_address) {
str += relation(start, this->false_branch_address);
str += " [color=red penwidth=2.0] \n";
}
return str;
}
std::string Node::gdl_relation() const
{
std::string str = "";
size_t start = this->start_address();
if (this->true_branch_address) {
str += format::string("edge: { sourcename: \"0x%08X\" targetname: \"0x%08X\" color: 11}\n",
start, this->true_branch_address);
}
if (this->false_branch_address) {
str += format::string("edge: { sourcename: \"0x%08X\" targetname: \"0x%08X\" color: 10}\n",
start, this->false_branch_address);
}
return str;
}
bool Node::it_fits(size_t size) const noexcept
{
return (size >= this->mem_size());
}
void Node::load_from_memory(const std::byte *mem) noexcept
{
memcpy(&this->_start_address, mem, sizeof(this->_start_address));
mem += sizeof(this->_start_address);
memcpy(&this->_iteration, mem, sizeof(this->_iteration));
mem += sizeof(this->_iteration);
// how many instruction we have?
size_t n = 0;
memcpy(&n, mem, sizeof(n));
mem += sizeof(n);
for (auto i = 0u; i < n; i++) {
auto instr = assembly::instruction();
instr.load_from_memory(mem);
mem += instr.mem_size();
// push the newly completed instruction back
this->block.push_back(instr);
}
memcpy(&this->is_done, mem, sizeof(this->is_done));
mem += sizeof(this->is_done);
memcpy(&this->max_occurrences, mem, sizeof(this->max_occurrences));
mem += sizeof(this->max_occurrences);
memcpy(&this->true_branch_address, mem, sizeof(this->true_branch_address));
mem += sizeof(this->true_branch_address);
memcpy(&this->false_branch_address, mem,
sizeof(this->false_branch_address));
mem += sizeof(this->false_branch_address);
memcpy(&this->occurrences, mem, sizeof(this->occurrences));
mem += sizeof(this->occurrences);
}
void Node::load_to_memory(std::byte *mem) const noexcept
{
memcpy(mem, &this->_start_address, sizeof(this->_start_address));
mem += sizeof(this->_start_address);
memcpy(mem, &this->_iteration, sizeof(this->_iteration));
mem += sizeof(this->_iteration);
const size_t n = this->block.size();
memcpy(mem, &n, sizeof(n));
mem += sizeof(n);
for (const auto &item : this->block) {
item.load_to_memory(mem);
mem += item.mem_size();
}
memcpy(mem, &this->is_done, sizeof(this->is_done));
mem += sizeof(this->is_done);
memcpy(mem, &this->max_occurrences, sizeof(this->max_occurrences));
mem += sizeof(this->max_occurrences);
memcpy(mem, &this->true_branch_address, sizeof(this->true_branch_address));
mem += sizeof(this->true_branch_address);
memcpy(mem, &this->false_branch_address,
sizeof(this->false_branch_address));
mem += sizeof(this->false_branch_address);
memcpy(mem, &this->occurrences, sizeof(this->occurrences));
mem += sizeof(this->occurrences);
}
size_t Node::mem_size() const noexcept
{
size_t size = sizeof(this->_start_address);
size += sizeof(this->_iteration);
size += sizeof(this->block.size());
for (const auto &item : this->block) {
auto item_size = item.mem_size();
size += sizeof(item_size);
size += item_size;
}
size += sizeof(this->is_done);
size += sizeof(this->max_occurrences);
size += sizeof(this->true_branch_address);
size += sizeof(this->false_branch_address);
size += sizeof(this->occurrences);
return size;
}
| 23.444156 | 93 | 0.680589 | [
"vector"
] |
65e910af06d2d316a208a260963995cffd23a533 | 8,554 | cpp | C++ | Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Modules/DeformableRegistrationUI/QmitkDemonsRegistrationView.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDemonsRegistrationView.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "mitkITKImageImport.h"
#include "mitkProgressBar.h"
#include "ui_QmitkDemonsRegistrationViewControls.h"
#include <mitkImageCast.h>
#include <mitkLevelWindowProperty.h>
#include <mitkRenderingManager.h>
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <qvalidator.h>
#include <stdio.h>
#include <stdlib.h>
QmitkDemonsRegistrationView::QmitkDemonsRegistrationView(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f),
m_FixedNode(nullptr),
m_MovingNode(nullptr),
m_ResultImage(nullptr),
m_ResultDeformationField(nullptr)
{
m_Controls.setupUi(parent);
QValidator *validatorHistogramLevels = new QIntValidator(1, 20000000, this);
m_Controls.m_NumberOfHistogramLevels->setValidator(validatorHistogramLevels);
QValidator *validatorMatchPoints = new QIntValidator(1, 20000000, this);
m_Controls.m_NumberOfMatchPoints->setValidator(validatorMatchPoints);
QValidator *validatorIterations = new QIntValidator(1, 20000000, this);
m_Controls.m_Iterations->setValidator(validatorIterations);
QValidator *validatorStandardDeviation = new QDoubleValidator(0, 20000000, 2, this);
m_Controls.m_StandardDeviation->setValidator(validatorStandardDeviation);
}
QmitkDemonsRegistrationView::~QmitkDemonsRegistrationView()
{
}
int QmitkDemonsRegistrationView::GetNumberOfIterations()
{
return atoi(m_Controls.m_Iterations->text().toLatin1());
}
float QmitkDemonsRegistrationView::GetStandardDeviation()
{
return atof(m_Controls.m_StandardDeviation->text().toLatin1());
}
mitk::Image::Pointer QmitkDemonsRegistrationView::GetResultImage()
{
return m_ResultImage;
}
mitk::Image::Pointer QmitkDemonsRegistrationView::GetResultDeformationfield()
{
return m_ResultDeformationField;
}
void QmitkDemonsRegistrationView::CalculateTransformation()
{
if (m_FixedNode.IsNotNull() && m_MovingNode.IsNotNull())
{
mitk::Image::Pointer fimage = dynamic_cast<mitk::Image *>(m_FixedNode->GetData());
mitk::Image::Pointer mimage = dynamic_cast<mitk::Image *>(m_MovingNode->GetData());
// workaround to ensure that fimage covers a bigger region than mimage
mitk::Image::RegionType fimageRegion = fimage->GetLargestPossibleRegion();
mitk::Image::RegionType mimageRegion = mimage->GetLargestPossibleRegion();
if (!((fimageRegion.GetSize(0) >= mimageRegion.GetSize(0)) &&
(fimageRegion.GetSize(1) >= mimageRegion.GetSize(1)) && (fimageRegion.GetSize(2) >= mimageRegion.GetSize(2))))
{
QMessageBox::information(
nullptr, "Registration", "Fixed image must be equal or bigger in size than moving image.");
return;
}
if (m_Controls.m_RegistrationSelection->currentIndex() == 0)
{
mitk::DemonsRegistration::Pointer registration = mitk::DemonsRegistration::New();
registration->SetSaveDeformationField(false);
registration->SetSaveResult(false);
registration->SetReferenceImage(fimage);
registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));
registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));
if (m_Controls.m_UseHistogramMatching->isChecked())
{
mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();
histogramMatching->SetReferenceImage(fimage);
histogramMatching->SetInput(mimage);
histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));
histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));
histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());
histogramMatching->Update();
mitk::Image::Pointer histimage = histogramMatching->GetOutput();
if (histimage.IsNotNull())
{
registration->SetInput(histimage);
}
else
{
registration->SetInput(mimage);
}
}
else
{
registration->SetInput(mimage);
}
try
{
registration->Update();
}
catch (itk::ExceptionObject &excpt)
{
QMessageBox::information(this, "Registration exception", excpt.GetDescription(), QMessageBox::Ok);
mitk::ProgressBar::GetInstance()->Progress(4);
return;
}
m_ResultImage = registration->GetOutput();
typedef itk::Image<itk::Vector<float, 3>, 3> VectorImageType;
VectorImageType::Pointer deformationField = registration->GetDeformationField();
m_ResultDeformationField = mitk::ImportItkImage(deformationField)->Clone();
}
else if (m_Controls.m_RegistrationSelection->currentIndex() == 1)
{
mitk::SymmetricForcesDemonsRegistration::Pointer registration = mitk::SymmetricForcesDemonsRegistration::New();
registration->SetSaveDeformationField(false);
registration->SetSaveResult(false);
registration->SetReferenceImage(fimage);
registration->SetNumberOfIterations(atoi(m_Controls.m_Iterations->text().toLatin1()));
registration->SetStandardDeviation(atof(m_Controls.m_StandardDeviation->text().toLatin1()));
if (m_Controls.m_UseHistogramMatching->isChecked())
{
mitk::HistogramMatching::Pointer histogramMatching = mitk::HistogramMatching::New();
histogramMatching->SetReferenceImage(fimage);
histogramMatching->SetInput(mimage);
histogramMatching->SetNumberOfHistogramLevels(atoi(m_Controls.m_NumberOfHistogramLevels->text().toLatin1()));
histogramMatching->SetNumberOfMatchPoints(atoi(m_Controls.m_NumberOfMatchPoints->text().toLatin1()));
histogramMatching->SetThresholdAtMeanIntensity(m_Controls.m_ThresholdAtMeanIntensity->isChecked());
histogramMatching->Update();
mitk::Image::Pointer histimage = histogramMatching->GetOutput();
if (histimage.IsNotNull())
{
registration->SetInput(histimage);
}
else
{
registration->SetInput(mimage);
}
}
else
{
registration->SetInput(mimage);
}
try
{
registration->Update();
}
catch (itk::ExceptionObject &excpt)
{
QMessageBox::information(this, "Registration exception", excpt.GetDescription(), QMessageBox::Ok);
mitk::ProgressBar::GetInstance()->Progress(4);
return;
}
m_ResultImage = registration->GetOutput();
typedef itk::Image<itk::Vector<float, 3>, 3> VectorImageType;
VectorImageType::Pointer deformationField = registration->GetDeformationField();
m_ResultDeformationField = mitk::ImportItkImage(deformationField)->Clone();
}
}
}
void QmitkDemonsRegistrationView::SetFixedNode(mitk::DataNode *fixedNode)
{
m_FixedNode = fixedNode;
}
void QmitkDemonsRegistrationView::SetMovingNode(mitk::DataNode *movingNode)
{
m_MovingNode = movingNode;
}
void QmitkDemonsRegistrationView::UseHistogramMatching(bool useHM)
{
if (useHM)
{
m_Controls.numberOfHistogramLevels->setEnabled(true);
m_Controls.m_NumberOfHistogramLevels->setEnabled(true);
m_Controls.numberOfMatchPoints->setEnabled(true);
m_Controls.m_NumberOfMatchPoints->setEnabled(true);
m_Controls.thresholdAtMeanIntensity->setEnabled(true);
m_Controls.m_ThresholdAtMeanIntensity->setEnabled(true);
}
else
{
m_Controls.numberOfHistogramLevels->setEnabled(false);
m_Controls.m_NumberOfHistogramLevels->setEnabled(false);
m_Controls.numberOfMatchPoints->setEnabled(false);
m_Controls.m_NumberOfMatchPoints->setEnabled(false);
m_Controls.thresholdAtMeanIntensity->setEnabled(false);
m_Controls.m_ThresholdAtMeanIntensity->setEnabled(false);
}
}
| 39.059361 | 121 | 0.700959 | [
"vector"
] |
65ea39af67725f2bbc2d88965022d741137fe5af | 15,800 | cpp | C++ | src/App.cpp | leodlplq/IMACraft | 5fec1729238e7e428bd39543dfd1fad521e16047 | [
"MIT"
] | 1 | 2021-11-24T16:49:48.000Z | 2021-11-24T16:49:48.000Z | src/App.cpp | leodlplq/IMACraft | 5fec1729238e7e428bd39543dfd1fad521e16047 | [
"MIT"
] | null | null | null | src/App.cpp | leodlplq/IMACraft | 5fec1729238e7e428bd39543dfd1fad521e16047 | [
"MIT"
] | null | null | null | #include "App.hpp"
std::vector<Model> getAllModels(const FilePath& appPath){
std::vector<Model> models;
// MODEL OF THE GROUND -- 0
Model grass(((std::string)appPath.dirPath() + "/assets/obj/grass/scene.gltf").c_str());
models.push_back(grass);
// COBBLE TEXTURE MODEL -- 1
Model cobblestone(((std::string)appPath.dirPath() + "/assets/obj/cobblestone/scene.gltf").c_str());
models.push_back(cobblestone);
// GOLD TEXTURE MODEL -- 2
Model gold(((std::string)appPath.dirPath() + "/assets/obj/gold/scene.gltf").c_str());
models.push_back(gold);
// REDSTONE TEXTURE MODEL -- 3
Model redstone(((std::string)appPath.dirPath() + "/assets/obj/redstone/scene.gltf").c_str());
models.push_back(redstone);
//
return models;
}
std::vector<glm::vec3> getAllLight(Map &map){
std::vector<glm::vec3> light;
int total = 0;
for (auto &me: map.getSecondFloor()) {
if (me.getModel() == 1) {
total +=1;
}
}
int count = 0;
for (auto &me: map.getSecondFloor()) {
if (me.getModel() == 1) {
count+=1;
if(count == 1){
light.push_back(me.getPosition()+glm::vec3(0,1,0));
}
if(count == total/2){
light.push_back(me.getPosition()+glm::vec3(0,1,0));
}
if(count == total -1){
light.push_back(me.getPosition()+glm::vec3(0,1,0));
}
}
}
return light;
}
App::App(int window_width, int window_height, const FilePath& appPath) :
_models(),
_modelsMap(getAllModels(appPath)),
_map(appPath.dirPath() + "/assets/maps/map8.pgm", _modelsMap, 0.5),
_skyboxShader("assets/shaders/skybox.vs.glsl","assets/shaders/skybox.fs.glsl",appPath),
_shaderProgram("assets/shaders/shader.vs.glsl","assets/shaders/shader.fs.glsl" , appPath),
_hpShader("assets/shaders/hp.vs.glsl","assets/shaders/hp.fs.glsl",appPath),
_steveShader("assets/shaders/shaderSteve.vs.glsl","assets/shaders/shaderSteve.fs.glsl",appPath),
_textShader("assets/shaders/textShader.vs.glsl", "assets/shaders/textShader.fs.glsl", appPath),
_buttonShader("assets/shaders/buttonShader.vs.glsl", "assets/shaders/buttonShader.fs.glsl", appPath),
_appPath(appPath),
_textures(),
_width(window_width),
_height(window_height),
_player(Model(((std::string)appPath.dirPath() + "/assets/obj/steve/scene.gltf").c_str()), _map.getSpawnPoint(),0.026f, _map, Model(((std::string)appPath.dirPath() + "/assets/obj/skeleton/scene.gltf").c_str())),
_camera(_width,_height,_player, _map),
_hud(_width,_height),
_save((std::string)appPath.dirPath() + "/assets/savefiles/sauvegarde_score.txt", (std::string)appPath.dirPath() + "/assets/savefiles/sauvegarde_pseudo.txt", (std::string)appPath.dirPath() + "/assets/savefiles/sauvegarde.txt"),
_hpHUD(),
_textArial(appPath, _width, _height, "arial"),
_textMinecraft(appPath, _width, _height, "Minecraft"),
_light(_steveShader, _camera, getAllLight(_map)),
_buttons()
{
size_callback(window_width, window_height);
}
void App::init(){
// CAMERA
// configure global opengl state
// -----------------------------
glEnable(GL_DEPTH_TEST);
// load models
// -----------
Model steve(((std::string)_appPath.dirPath() + "/assets/obj/steve/scene.gltf").c_str());
_models.push_back(steve);
Model diamond (((std::string)_appPath.dirPath() + "/assets/obj/diamond/scene.gltf").c_str());
_models.push_back(diamond);
Model hud(((std::string)_appPath.dirPath() + "/assets/obj/hud/scene.gltf").c_str());
_models.push_back(hud);
Model glowstone(((std::string)_appPath.dirPath() + "/assets/obj/glowstone/scene.gltf").c_str());
_models.push_back(glowstone);
Enemy zombie(((std::string)_appPath.dirPath() + "/assets/obj/zombie/scene.gltf").c_str(),glm::vec3(1.3,0.1,-1),glm::vec3(0.06f, 0.06f, 0.06f));
_enemies.push_back(zombie);
Enemy creeper(((std::string)_appPath.dirPath() + "/assets/obj/creeper/scene.gltf").c_str(),glm::vec3(1,0.5,0),glm::vec3(0.06f, 0.06f, 0.06f));
_enemies.push_back(creeper);
Enemy enderMan(((std::string)_appPath.dirPath() + "/assets/obj/enderman/scene.gltf").c_str(),glm::vec3(1.8,-0.5,1),glm::vec3(0.05f, 0.05f, 0.05f));
_enemies.push_back(enderMan);
for (auto &me: _map.getFloor()) {
if (me.getModel() != -1 && me.isIntersection() == false) {
if(me.getRand()<0.13f){
_collectibles.emplace_back(((std::string)_appPath.dirPath() + "/assets/obj/diamond/scene.gltf").c_str(), me.getPosition()+glm::vec3(0,0.6,0), 0, 10);
}
if(me.getRand()>0.95f && me.getRand()<0.98f){
_collectibles.emplace_back(((std::string)_appPath.dirPath() + "/assets/obj/emerald/scene.gltf").c_str(), me.getPosition()+glm::vec3(0,0.6,0), 0, 50);
}
if(me.getRand()>0.98f){
_collectibles.emplace_back(((std::string)_appPath.dirPath() + "/assets/obj/apple/scene.gltf").c_str(), me.getPosition()+glm::vec3(0,0.6,0), 1,0);
}
}
}
initButtons();
// SKYBOX SHADER BINDING
_skyboxShader.activate();
glUniform1i(glGetUniformLocation(_skyboxShader._id,"skybox"),0);
_filePathHP = ((std::string)_appPath.dirPath() + "/assets/textures/hp/heart.png");
_hpHUD.genTexHP(_filePathHP);
}
void App::render(GLFWwindow* window, double FPS) {
//CODE IN GAMESCENE.cpp
switch (getScene()) {
case 0:
//mENU OF THE GAME
renderMainMenu(window, FPS);
break;
case 1:
//GAME ITSELF
renderGame(window, FPS);
break;
case 2:
//PAUSE MENU
renderPauseMenu(window, FPS);
break;
case 3:
//END GAME (LOOSE CASE)
renderLooseScreen(window, FPS);
break;
case 4:
//END GAME (WIN CASE)
renderWinScreen(window, FPS);
break;
case 5:
//SHOW SCORES
renderScoreScreen(window, FPS);
default:
assert((bool) "pas possible");
break;
}
}
void App::key_callback(int key, /*int scancode,*/ int action/*, int mods*/)
{
std::cout << key << std::endl;
if(key == 65 && action == GLFW_PRESS){
_player.turnLeft();
_camera.turnLeft();
}
if(key == 68 && action == GLFW_PRESS){
_player.turnRight();
_camera.turnRight();
}
if(key == 87 && (action == GLFW_PRESS)){
_player.startJump();
}
if(key == 83 && (action == GLFW_PRESS)){
_player.slide();
}
//L == LOCKING THE CAMERA
if(key == 76 && (action == GLFW_PRESS)){
_camera.invertCamLock();
}
//M == LOCKING THE CAMERA
if(key == 67 && (action == GLFW_PRESS)){
_camera.invertCamMode();
_camera.resetAngle();
}
if(key == 292 && action == GLFW_PRESS){
invertFPSShow();
}
if(key == 256 && action == GLFW_PRESS){
if(getScene() == 2){
setScene(1);
} else if(getScene()==1) {
setScene(2);
}
}
}
void App::mouse_button_callback(int button, int action, int mods, GLFWwindow* window)
{
if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
switch (getScene()) {
case 0:
//mENU OF THE GAME
handleClickEvent(window);
break;
case 1:
//GAME ITSELF
handleClickEvent(window);
break;
case 2:
//PAUSE MENU
handleClickEvent(window);
break;
case 3:
//END GAME (LOOSE CASE)
handleClickEvent(window);
break;
case 4:
//END GAME (WIN CASE)
handleClickEvent(window);
break;
case 5:
handleClickEvent(window);
break;
default:
assert((bool) "pas possible");
break;
}
}
}
void App::scroll_callback(double xOffset, double yOffset)
{
switch (getScene()) {
case 0:
//mENU OF THE GAME
break;
case 1:
//GAME ITSELF
if(!_camera.isCamLocked()) {
_camera.scrollCallback(xOffset, -yOffset);
}
break;
case 2:
//PAUSE MENU
break;
case 3:
//END GAME (LOOSE CASE)
break;
case 4:
//END GAME (WIN CASE)
break;
default:
assert((bool) "pas possible");
break;
}
}
void App::cursor_position_callback(double xPos, double yPos, GLFWwindow* window)
{
//yPos = _height - yPos;
switch (getScene()) {
case 0:
//MENU OF THE GAME
handleHoverEvent(xPos, yPos);
break;
case 1:
//GAME ITSELF
glfwSetCursorPos(window,(float)_width/2,(float)_height/2);
//IT CAN ONLY ROTATE WHEN THE USER WANT
if(!_camera.isCamLocked()){
float rotX = _camera.getSensitivity() * (float)(yPos - ((float)_height/2))/(float)_height;
float rotY = _camera.getSensitivity() * (float)(xPos- ((float)_width/2))/(float)_width;
_camera.rotateLeft(rotY);
_camera.rotateUp(rotX);
}
break;
case 2:
//PAUSE MENU
handleHoverEvent(xPos, yPos);
break;
case 3:
//END GAME (LOOSE CASE)
handleHoverEvent(xPos, yPos);
break;
case 4:
//END GAME (WIN CASE)
handleHoverEvent(xPos, yPos);
break;
case 5:
handleHoverEvent(xPos, yPos);
default:
assert((bool) "pas possible");
break;
}
}
void App::size_callback(int width, int height)
{
_width = width;
_height = height;
}
void App::initButtons(){
std::function<void (void)> functionPlay = [=]() {
this->setScene(1);
};
std::function<void (void)> functionLeave = [=]() {
this->closeGame();
};
std::function<void (void)> functionRestart = [=]() {
this->restart();
this->setScene(1);
};
std::function<void (void)> functionScore = [=]() {
this->setScene(5);
};
std::function<void (void)> functionGoBack = [=]() {
this->setScene(2);
};
float scaleBtn = 0.7f;
//MAIN MENU BUTTON
Button playButtonMain(0,"Launch game !",_height,_width,_width/2,250.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionPlay );
_buttons.push_back(playButtonMain);//BUTTON 0
Button leaveButtonMain(0,"Leave game !",_height,_width,_width/2,150.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionLeave );
_buttons.push_back(leaveButtonMain);//BUTTON 1
//PAUSE MENU BUTTONS
Button resumeButtonPause(2,"Go back to game",_height,_width,_width/2,250.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionPlay );
_buttons.push_back(resumeButtonPause); //BUTTON 2
Button leaveButtonPause(2,"Leave game !",_height,_width,_width/2,150.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionLeave );
_buttons.push_back(leaveButtonPause);//BUTTON 3
//LOOSE MENU
Button restartButtonLoose(3,"Restart game",_height,_width,_width/2,250.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionRestart );
_buttons.push_back(restartButtonLoose); //BUTTON 4
Button leaveButtonLoose(3,"Leave game !",_height,_width,_width/2,150.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionLeave );
_buttons.push_back(leaveButtonLoose);//BUTTON 5
//WIN MENU
Button restartButtonWin(4,"Restart game",_height,_width,_width/2,250.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionRestart );
_buttons.push_back(restartButtonWin); //BUTTON 6
Button leaveButtonWin(4,"Leave game !",_height,_width,_width/2,150.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionLeave );
_buttons.push_back(leaveButtonWin);//BUTTON 7
//PAUSE MENU AGAIN
Button restartButtonPause(2,"Restart",_height,_width,_width/2,350.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionRestart );
_buttons.push_back(restartButtonPause); //BUTTON 8
Button scoreButtonPause(2,"Show best scores",_height,_width,_width/2,450.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionScore );
_buttons.push_back(scoreButtonPause); //BUTTON 9
//SCORE MENU BUTTON
Button goBackButtonScore(5,"Back",_height,_width,_width/2,150.f,40.f,20.f,scaleBtn,glm::vec3(0.f,0.f,0.f),glm::vec3(1.f,1.f,1.f),_textArial,_textShader,_buttonShader, functionGoBack );
_buttons.push_back(goBackButtonScore); //BUTTON 10
}
void App::handleClickEvent(GLFWwindow* window){
double xPos, yPos;
//getting cursor position
glfwGetCursorPos(window, &xPos, &yPos);
for(auto &b:_buttons){
double y = _height - yPos;
if(b.isHovered(xPos, y) && b.getSceneNb() == getScene()){
b._clickCallback();
b.changeBackgroundColor(glm::vec3(1,0,0));
} else {
b.changeBackgroundColor(glm::vec3(0.f));
}
}
}
void App::handleHoverEvent(double xPos, double yPos) {
for(auto &b:_buttons){
double y = _height - yPos;
if(b.isHovered(xPos, y) && b.getSceneNb() == getScene()){
b.changeBackgroundColor(glm::vec3(0.5f));
} else {
b.changeBackgroundColor(glm::vec3(0.f));
}
}
}
App::~App(){
//DELETING EVERYTHING
//SHADERS
_shaderProgram.deleteShader();
_shaderProgram.~Shader();
_skyboxShader.deleteShader();
_skyboxShader.~Shader();
//APP PATH
_appPath.~FilePath();
//TEXTURES
for(auto &item : _textures){
item.deleteTex();
}
_textures.erase(_textures.begin(), _textures.end());
_textures.shrink_to_fit();
//MODELS
// for(auto &item : _modelsCube){
// item.del();
// }
_models.erase(_models.begin(), _models.end());
_models.shrink_to_fit();
//CAMERA
_camera.~Camera();
//SKYBOX
_skybox.~Skybox();
//PLAYER
_player.~Player();
}
// -------------------------------------------------------- PRESSE PAPIER ---------------------------------------------------------------
/*std::cout << "------------ PLAYER -------------" << std::endl;
_player.getHitbox().display();
std::cout << "------------ BLOCK -------------" << std::endl;
blockHitbox.display();
std::cout << (_player.getHitbox().intersect(blockHitbox) ? "collision" : "no collision")<< std::endl;
std::cout << "------------ OTHER BLOCK -------------" << std::endl;
neiBlockHitbox.display();
std::cout << (_player.getHitbox().intersect(neiBlockHitbox) ? "collision" : "no collision")<< std::endl;*/ | 34.051724 | 234 | 0.577152 | [
"render",
"vector",
"model"
] |
65f4cbb7d702012be1b127a3616360c0c446ded1 | 3,485 | cpp | C++ | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/Geometry/Simple/AnimatedStripComponent.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | 1 | 2022-01-28T11:43:47.000Z | 2022-01-28T11:43:47.000Z | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/Geometry/Simple/AnimatedStripComponent.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/Geometry/Simple/AnimatedStripComponent.cpp | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "AnimatedStripComponent.h"
#include <cassert>
#include "Mathematics/defines.h"
#include "Engine/Models/Plugins/Channels/Geometry/AttributeChannelTyped.h"
#include "Memory/MemoryLeaks.h"
namespace bv { namespace model {
// *******************************
//
AnimatedStripComponent::AnimatedStripComponent ( float w, float h, unsigned int numSegments, float z, float sclSine, float sclCosine, float speedX, float speedY, float sizeY, float sizeZ )
: m_sclSine( sclSine )
, m_sclCosine( sclCosine )
, m_speedX( speedX )
, m_speedY( speedY )
, m_h( h )
, m_z( z )
, m_sizeY( sizeY )
, m_sizeZ( sizeZ )
{
//FIXME: not null desc should be created via factory
auto desc = std::make_shared< AttributeChannelDescriptor >( AttributeType::AT_FLOAT3, AttributeSemantic::AS_POSITION, ChannelRole::CR_GENERATOR );
Float3AttributeChannelPtr vertArrtF3 = std::make_shared< Float3AttributeChannel >( desc, desc->SuggestedDefaultName( 0 ), false );
float xStart = -w * 0.5f;
float yStart = -h * 0.5f;
float dx = w / (float) numSegments;
float dy = h;
vertArrtF3->AddAttribute(glm::vec3( xStart, yStart + dy, z ) );
vertArrtF3->AddAttribute(glm::vec3( xStart, yStart, z ) );
vertArrtF3->AddAttribute(glm::vec3( xStart + dx, yStart + dy, z ) );
vertArrtF3->AddAttribute(glm::vec3( xStart + dx, yStart, z ) );
for ( unsigned int i = 1; i < numSegments; ++i )
{
xStart += dx;
vertArrtF3->AddAttribute(glm::vec3( xStart + dx, yStart + dy, z ) );
vertArrtF3->AddAttribute(glm::vec3( xStart + dx, yStart, z ) );
}
AddAttributeChannel( AttributeChannelPtr( vertArrtF3 ) ); // FIXME: Need to be sure that can take ownership
m_positions = vertArrtF3;
}
// *******************************
//
void AnimatedStripComponent::Update ( TimeType t )
{
float sclSine = m_sclSine;
float dSine = fmod( float( t ) * m_speedX , (float) TWOPI );
// float dSine = fmod( t * m_speedX , (float) TWOPI / m_sclSine );
float sclCosine = m_sclCosine;
float dCosine = fmod( float( t ) * m_speedY , (float) TWOPI );
// float dCosine = fmod( t * m_speedY , (float) TWOPI / m_sclCosine );
std::vector< glm::vec3 > & vx = m_positions->GetVertices();
float yStart = -m_h * 0.5f;
for( unsigned int i = 0; i < vx.size(); i += 2 )
{
glm::vec3 & vt = vx[ i ];
glm::vec3 & vb = vx[ i + 1 ];
float r = vt.x * sclSine + dSine;
float s = vt.x * sclCosine + dCosine;
float dy = m_sizeY * sin( r );
float dz = m_sizeZ * cos( s );
vt.y = yStart + m_h + dy;
vb.y = yStart + dy;
vt.z = vb.z = m_z + dz;
}
}
// *******************************
//
AnimatedStripComponent::~AnimatedStripComponent ()
{
}
// *******************************
//
AnimatedStripComponentPtr AnimatedStripComponent::Create ( float w, float h, unsigned int numSegments, float z, float sclSine, float sclCosine, float speedX, float speedY, float sizeY, float sizeZ )
{
assert( numSegments >= 1 );
return AnimatedStripComponentPtr( new AnimatedStripComponent( w, h, numSegments, z, sclSine, sclCosine, speedX, speedY, sizeY, sizeZ ) );
}
} //model
} //bv
| 31.681818 | 207 | 0.573888 | [
"geometry",
"vector",
"model"
] |
5a013436c438cc66d676e051d0fd384451cb054f | 12,558 | cpp | C++ | tests/src/gauss_newton.test.cpp | Rookfighter/optimization-cpp | 482122c9bef39f30e57af69c93d99853005f14f7 | [
"MIT"
] | null | null | null | tests/src/gauss_newton.test.cpp | Rookfighter/optimization-cpp | 482122c9bef39f30e57af69c93d99853005f14f7 | [
"MIT"
] | null | null | null | tests/src/gauss_newton.test.cpp | Rookfighter/optimization-cpp | 482122c9bef39f30e57af69c93d99853005f14f7 | [
"MIT"
] | null | null | null | /// gauss_newton.test.cpp
///
/// Author: Fabian Meyer
/// Created On: 05 Aug 2019
/// License: MIT
#include <lsqcpp/lsqcpp.hpp>
#include "eigen_require.hpp"
#include "parabolic_error.hpp"
using namespace lsqcpp;
TEMPLATE_TEST_CASE("gauss newton", "[algorithm]", float, double)
{
constexpr auto Inputs = Eigen::Dynamic;
using Scalar = TestType;
constexpr auto eps = static_cast<Scalar>(1e-3);
using Vector = Eigen::Matrix<Scalar, Inputs, 1>;
SECTION("with jacobian")
{
SECTION("constant step size converge")
{
GaussNewtonX<Scalar, ParabolicError, ConstantStepFactor> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.5)});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, static_cast<Scalar>(1e-1));
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
SECTION("armijo backtracking")
{
GaussNewtonX<Scalar, ParabolicError, ArmijoBacktracking> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.8),
static_cast<Scalar>(1e-4),
static_cast<Scalar>(1e-10),
static_cast<Scalar>(1.0),
50});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, static_cast<Scalar>(1e-1));
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
SECTION("wolfe backtracking")
{
GaussNewtonX<Scalar, ParabolicError, WolfeBacktracking> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.8),
static_cast<Scalar>(1e-4),
static_cast<Scalar>(0.1),
static_cast<Scalar>(1e-10),
static_cast<Scalar>(1.0),
100});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, eps);
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
SECTION("dogleg method")
{
GaussNewtonX<Scalar, ParabolicError, DoglegMethod> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(1),
static_cast<Scalar>(2),
static_cast<Scalar>(1e-9),
static_cast<Scalar>(0.25),
100});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, eps);
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
}
SECTION("without jacobian")
{
SECTION("constant step size converge")
{
GaussNewtonX<Scalar, ParabolicErrorNoJacobian, ConstantStepFactor> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.5)});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, 1e-1);
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
SECTION("armijo backtracking")
{
GaussNewtonX<Scalar, ParabolicErrorNoJacobian, ArmijoBacktracking> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.8),
static_cast<Scalar>(1e-4),
static_cast<Scalar>(1e-10),
static_cast<Scalar>(1.0),
50});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, 1e-1);
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
SECTION("wolfe backtracking")
{
GaussNewtonX<Scalar, ParabolicErrorNoJacobian, WolfeBacktracking> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.8),
static_cast<Scalar>(1e-4),
static_cast<Scalar>(0.1),
static_cast<Scalar>(1e-10),
static_cast<Scalar>(1.0),
100});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE(result.converged);
REQUIRE_MATRIX_APPROX(xvalExp, result.xval, eps);
REQUIRE_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
REQUIRE(Approx(errorExp).margin(eps) == result.error);
}
}
SECTION("inverse jacobian")
{
SECTION("constant step size converge")
{
GaussNewtonX<Scalar, ParabolicErrorInverseJacobian, ConstantStepFactor> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.5)});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE_FALSE(result.converged);
REQUIRE_NOT_MATRIX_APPROX(xvalExp, result.xval, eps);
REQUIRE_NOT_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) != result.error);
REQUIRE(Approx(errorExp).margin(eps) != result.error);
}
SECTION("armijo backtracking")
{
GaussNewtonX<Scalar, ParabolicErrorInverseJacobian, ArmijoBacktracking> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.8),
static_cast<Scalar>(1e-4),
static_cast<Scalar>(1e-10),
static_cast<Scalar>(1.0),
50});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE_FALSE(result.converged);
REQUIRE_NOT_MATRIX_APPROX(xvalExp, result.xval, eps);
REQUIRE_NOT_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) != result.error);
REQUIRE(Approx(errorExp).margin(eps) != result.error);
}
SECTION("wolfe backtracking")
{
GaussNewtonX<Scalar, ParabolicErrorInverseJacobian, WolfeBacktracking> optimizer;
optimizer.setRefinementParameters({static_cast<Scalar>(0.8),
static_cast<Scalar>(1e-4),
static_cast<Scalar>(0.1),
static_cast<Scalar>(1e-10),
static_cast<Scalar>(1.0),
100});
optimizer.setMinimumStepLength(static_cast<Scalar>(1e-10));
optimizer.setMinimumGradientLength(static_cast<Scalar>(1e-10));
optimizer.setMaximumIterations(100);
Vector initGuess(4);
initGuess << 2, 1, 3, 4;
Scalar errorExp = 0;
Vector fvalExp = Vector::Zero(2);
Vector xvalExp = Vector::Zero(4);
auto result = optimizer.minimize(initGuess);
REQUIRE_FALSE(result.converged);
REQUIRE_NOT_MATRIX_APPROX(xvalExp, result.xval, eps);
REQUIRE_NOT_MATRIX_APPROX(fvalExp, result.fval, eps);
REQUIRE(Approx(errorExp).margin(eps) != result.error);
REQUIRE(Approx(errorExp).margin(eps) != result.error);
}
}
}
| 40.379421 | 94 | 0.547858 | [
"vector"
] |
5a02b9f27ea82652b11056e71368aa2a7f476408 | 4,165 | cpp | C++ | main/src/Pymodules/PyMatrixContainer.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2020-10-06T08:06:25.000Z | 2020-10-06T08:06:25.000Z | main/src/Pymodules/PyMatrixContainer.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | main/src/Pymodules/PyMatrixContainer.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /** ***********************************************************************************************
* @brief implementation for PyMatrixContainer
*
* @author Gerstmayr Johannes
* @date 2020-05-11 (created)
* @copyright This file is part of Exudyn. Exudyn is free software: you can redistribute it and/or modify it under the terms of the Exudyn license. See 'LICENSE.txt' for more details.
* @note Bug reports, support and further information:
* - email: johannes.gerstmayr@uibk.ac.at
* - weblink: missing
*
*
************************************************************************************************ */
#include "PyMatrixContainer.h"
#include "PybindUtilities.h"
//! initialize container with py::array_t or with emtpy list (default value)
PyMatrixContainer::PyMatrixContainer(const py::object& matrix)
{
//pout << "PyMatrixContainer::PyMatrixContainer:";
//py::print(matrix);
if (py::isinstance<PyMatrixContainer>(matrix))
{
//pout << "works2: PyMatrixContainer::PyMatrixContainer:\n";
*this = py::cast<PyMatrixContainer>(matrix);
//pout << " denseFlag=" << useDenseMatrix << "\n";
//pout << " matrix=" << GetEXUdenseMatrix() << "\n";
}
else if (py::isinstance<py::list>(matrix) || py::isinstance<py::array>(matrix)) //process empty list, which is default in python constructor
{
std::vector<Real> stdlist = py::cast<std::vector<Real>>(matrix); //! # read out dictionary and cast to C++ type
if (stdlist.size() != 0)
{
CHECKandTHROWstring("MatrixContainer::Constructor list must be empty or numpy array");
}
useDenseMatrix = true;
denseMatrix = EPyUtils::NumPy2Matrix(py::cast<py::array_t<Real>>(matrix));
}
else
{
CHECKandTHROWstring("MatrixContainer: can only initialize with empty list or with 2D numpy array");
}
}
//! set with dense numpy array; array (=matrix) contains values and size information
void PyMatrixContainer::SetWithDenseMatrix(const py::array_t<Real>& pyArray, bool useDenseMatrixInit)
{
if (useDenseMatrixInit)
{
useDenseMatrix = true;
denseMatrix = EPyUtils::NumPy2Matrix(pyArray);
}
else
{
useDenseMatrix = false;
if (pyArray.size() == 0) //process empty arrays, which leads to empty matrix, but has no dimension 2
{
sparseTripletMatrix.SetAllZero(); //empty matrix
}
else if (pyArray.ndim() == 2)
{
auto mat = pyArray.unchecked<2>();
Index nrows = mat.shape(0);
Index ncols = mat.shape(1);
sparseTripletMatrix.SetNumberOfRowsAndColumns(nrows, ncols);
for (Index i = 0; i < nrows; i++)
{
for (Index j = 0; j < ncols; j++)
{
if (mat(i, j) != 0.)
{
sparseTripletMatrix.AddTriplet(EXUmath::Triplet(i, j, mat(i, j)));
}
}
}
}
else { CHECKandTHROWstring("MatrixContainer::SetWithDenseMatrix: illegal array format!"); }
}
}
//! set with sparse CSR matrix format: numpy array contains in every row [row, col, value]; numberOfRows and numberOfColumns given extra
void PyMatrixContainer::SetWithSparseMatrixCSR(Index numberOfRowsInit, Index numberOfColumnsInit, const py::array_t<Real>& pyArray, bool useDenseMatrixInit)
{
useDenseMatrix = useDenseMatrixInit;
if (pyArray.size() != 0)
{
if (pyArray.ndim() == 2)
{
auto mat = pyArray.unchecked<2>();
Index nrows = mat.shape(0);
Index ncols = mat.shape(1);
if (ncols != 3)
{
CHECKandTHROWstring("MatrixContainer::SetWithSparseMatrixCSR: array must have 3 columns: row, column and value!");
}
if (useDenseMatrixInit)
{
denseMatrix.SetNumberOfRowsAndColumns(numberOfRowsInit, numberOfColumnsInit);
denseMatrix.SetAll(0.);
for (Index i = 0; i < nrows; i++)
{
denseMatrix((Index)mat(i, 0), (Index)mat(i, 1)) += mat(i, 2); //use += in case that indices are duplicated
}
}
else
{
sparseTripletMatrix.SetNumberOfRowsAndColumns(numberOfRowsInit, numberOfColumnsInit);
sparseTripletMatrix.SetAllZero(); //empty matrix
for (Index i = 0; i < nrows; i++)
{
sparseTripletMatrix.AddTriplet(EXUmath::Triplet((Index)mat(i, 0), (Index)mat(i, 1), mat(i, 2)));
}
}
}
else { CHECKandTHROWstring("MatrixContainer::SetWithSparseMatrixCSR: illegal array format!"); }
}
}
| 33.58871 | 182 | 0.654742 | [
"object",
"shape",
"vector"
] |
5a08c9fc077b73bb315229ecce8dbfa236d71a34 | 3,075 | cc | C++ | src/kernel/application.cc | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | src/kernel/application.cc | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | src/kernel/application.cc | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | //
// Created by igor on 07/10/2021.
//
#include <neutrino/kernel/application.hh>
#include <neutrino/utils/exception.hh>
#include "systems_manager.hh"
#include "main_window.hh"
namespace neutrino::kernel {
static application* s_instance = nullptr;
struct application::impl {
impl() : m_paused(false) {};
explicit impl(hal::window_flags_t flags)
: m_main_window(flags) {}
void init() {
init_video();
}
void init_video() {
m_main_window.set_up (get_systems_manager()->get_video_system());
}
main_window m_main_window;
bool m_paused;
};
application::~application() {
release_systems_manager();
}
void application::on_terminating () {
get_systems_manager()->on_terminating();
}
void application::on_low_memory () {
get_systems_manager()->on_low_memory();
}
void application::on_will_enter_background () {
get_systems_manager()->on_will_enter_background();
}
void application::on_in_background () {
get_systems_manager()->on_in_background();
}
void application::on_in_foreground () {
get_systems_manager()->on_in_foreground();
}
void application::clear () {
if (!m_pimpl->m_paused) {
hal::application::clear ();
}
}
void application::update (std::chrono::milliseconds ms) {
if (!m_pimpl->m_paused) {
get_systems_manager ()->update (ms);
}
}
void application::render () {
get_systems_manager()->present();
hal::application::render();
}
void application::add_system(std::unique_ptr<base_input_system> input_sys) {
get_systems_manager()->add (std::move(input_sys));
}
void application::add_system(std::unique_ptr<video_system> video_sys) {
get_systems_manager()->add (std::move(video_sys));
}
[[maybe_unused]] void application::add_system(std::unique_ptr<system> sys) {
get_systems_manager()->add (std::move(sys));
}
void application::show (int w, int h) {
m_pimpl = spimpl::make_unique_impl<impl>();
m_pimpl->m_main_window.open (w, h);
m_pimpl->init();
}
void application::show (int w, int h, hal::window_flags_t flags) {
m_pimpl = spimpl::make_unique_impl<impl>(flags);
m_pimpl->m_main_window.open (w, h);
m_pimpl->init();
}
void application::show (int w, int h, int x, int y, hal::window_flags_t flags) {
m_pimpl = spimpl::make_unique_impl<impl>(flags);
m_pimpl->m_main_window.open (w, h, x, y);
m_pimpl->init();
}
void application::toggle_full_screen () {
m_pimpl->m_main_window.toggle_fullscreen();
}
void application::set_title (const std::string& title) {
m_pimpl->m_main_window.title (title);
}
void application::post_init () {
if (!s_instance) {
s_instance = this;
} else {
RAISE_EX("Application is already constructed");
}
}
void application::pause(bool v) {
m_pimpl->m_paused = v;
get_systems_manager()->on_paused (v);
}
bool application::paused() const noexcept {
return m_pimpl->m_paused;
}
application* get_application() {
return s_instance;
}
} | 23.295455 | 82 | 0.66374 | [
"render"
] |
5a115e455db6a0b69ab56d387f60ead609656682 | 4,467 | cpp | C++ | tc 160+/GuitarConcert.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/GuitarConcert.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/GuitarConcert.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
int bc[1<<10];
void make_cand(int m, const vector<string> &G, vector<string> &res) {
for (int i=0; i<(int)G.size(); ++i)
if (m & (1<<i))
res.push_back(G[i]);
sort(res.begin(), res.end());
}
int get_bc(long long x) {
int ret = 0;
while (x > 0) {
++ret;
x &= (x-1);
}
return ret;
}
class GuitarConcert {
public:
vector <string> buyGuitars(vector <string> G, vector <string> S) {
vector<string> sol(50, string(50, 'z'));
int scover = -1;
int n = G.size();
vector<long long> m(n, 0);
for (int i=0; i<n; ++i)
for (int j=0; j<(int)S[i].size(); ++j)
if (S[i][j] == 'Y')
m[i] |= (1LL<<j);
bc[0] = 0;
for (int M=1; M<(1<<n); ++M)
bc[M] = bc[M>>1] + (M&1);
for (int M=0; M<(1<<n); ++M) {
long long cover = 0;
for (int i=0; i<n; ++i)
if (M & (1<<i))
cover |= m[i];
cover = get_bc(cover);
vector<string> t;
if (cover>scover || cover==scover && (bc[M]<(int)sol.size() || bc[M]==(int)sol.size() && (make_cand(M, G, t), t)<sol)) {
scover = cover;
t.clear();
make_cand(M, G, t);
sol = t;
}
}
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { string Arr0[] = {"GIBSON","FENDER", "TAYLOR"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"YNYYN", "NNNYY", "YYYYY"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"TAYLOR" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, buyGuitars(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"GIBSON", "CRAFTER", "FENDER", "TAYLOR"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"YYYNN", "NNNYY", "YYNNY", "YNNNN"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"CRAFTER", "GIBSON" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, buyGuitars(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"AB", "AA", "BA"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"YN", "YN", "NN"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"AA" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, buyGuitars(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"FENDER", "GIBSON", "CRAFTER", "EPIPHONE", "BCRICH"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"YYNNYNN", "YYYNYNN", "NNNNNYY", "NNYNNNN", "NNNYNNN"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"BCRICH", "CRAFTER", "GIBSON" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, buyGuitars(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {"GIBSON","FENDER"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"NNNNNNNNNNNNNNNNNNNNNNNNN", "NNNNNNNNNNNNNNNNNNNNNNNNN"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = { }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, buyGuitars(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
GuitarConcert ___test;
___test.run_test(-1);
}
// END CUT HERE
| 47.521277 | 471 | 0.579136 | [
"vector"
] |
5a230ee09b11b3561511fd6fd923289e1c463e0a | 8,970 | cpp | C++ | pxr/imaging/hdSt/dependencySceneIndexPlugin.cpp | dgovil/USD | db8e3266dcaa24aa26b7201bc20ff4d8e81448d6 | [
"Apache-2.0"
] | 1 | 2021-09-25T12:49:37.000Z | 2021-09-25T12:49:37.000Z | pxr/imaging/hdSt/dependencySceneIndexPlugin.cpp | dgovil/USD | db8e3266dcaa24aa26b7201bc20ff4d8e81448d6 | [
"Apache-2.0"
] | null | null | null | pxr/imaging/hdSt/dependencySceneIndexPlugin.cpp | dgovil/USD | db8e3266dcaa24aa26b7201bc20ff4d8e81448d6 | [
"Apache-2.0"
] | 1 | 2020-10-24T00:43:14.000Z | 2020-10-24T00:43:14.000Z | //
// Copyright 2022 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
#include "pxr/imaging/hdSt/dependencySceneIndexPlugin.h"
#include "pxr/imaging/hd/dependenciesSchema.h"
#include "pxr/imaging/hd/filteringSceneIndex.h"
#include "pxr/imaging/hd/overlayContainerDataSource.h"
#include "pxr/imaging/hd/perfLog.h"
#include "pxr/imaging/hd/retainedDataSource.h"
#include "pxr/imaging/hd/sceneIndexPluginRegistry.h"
#include "pxr/imaging/hd/tokens.h"
#include "pxr/imaging/hd/volumeFieldBindingSchema.h"
#include "pxr/imaging/hd/volumeFieldSchema.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_DEFINE_PRIVATE_TOKENS(
_tokens,
((sceneIndexPluginName, "HdSt_DependencySceneIndexPlugin"))
);
static const char * const _pluginDisplayName = "GL";
TF_REGISTRY_FUNCTION(TfType)
{
HdSceneIndexPluginRegistry::Define<HdSt_DependencySceneIndexPlugin>();
}
TF_REGISTRY_FUNCTION(HdSceneIndexPlugin)
{
const HdSceneIndexPluginRegistry::InsertionPhase insertionPhase = 0;
HdSceneIndexPluginRegistry::GetInstance().RegisterSceneIndexForRenderer(
_pluginDisplayName,
_tokens->sceneIndexPluginName,
nullptr,
insertionPhase,
HdSceneIndexPluginRegistry::InsertionOrderAtStart);
}
namespace
{
/// Computes the dependencies for the volumeFieldBindings of a volume
/// prim. They need to be returned when the data source locator __dependencies
/// is querried.
HdRetainedContainerDataSourceHandle
_ComputeVolumeFieldBindingDependencies(
const SdfPath &primPath,
const HdContainerDataSourceHandle &primSource)
{
HD_TRACE_FUNCTION();
HdVolumeFieldBindingSchema schema =
HdVolumeFieldBindingSchema::GetFromParent(primSource);
TfTokenVector names = schema.GetVolumeFieldBindingNames();
std::vector<HdDataSourceBaseHandle> dependencies;
dependencies.reserve(names.size() + 1);
for (const TfToken &name : names) {
HdDependencySchema::Builder builder;
builder.SetDependedOnPrimPath(
schema.GetVolumeFieldBinding(name));
static HdLocatorDataSourceHandle dependedOnLocatorDataSource =
HdRetainedTypedSampledDataSource<HdDataSourceLocator>::New(
HdVolumeFieldSchema::GetDefaultLocator());
builder.SetDependedOnDataSourceLocator(
dependedOnLocatorDataSource);
static HdLocatorDataSourceHandle affectedLocatorDataSource =
HdRetainedTypedSampledDataSource<HdDataSourceLocator>::New(
HdVolumeFieldBindingSchema::GetDefaultLocator());
builder.SetAffectedDataSourceLocator(
affectedLocatorDataSource);
dependencies.push_back(builder.Build());
}
{
names.push_back(
HdVolumeFieldBindingSchemaTokens->volumeFieldBinding);
HdDependencySchema::Builder builder;
builder.SetDependedOnPrimPath(
HdRetainedTypedSampledDataSource<SdfPath>::New(
primPath));
static HdLocatorDataSourceHandle dependedOnLocatorDataSource =
HdRetainedTypedSampledDataSource<HdDataSourceLocator>::New(
HdVolumeFieldBindingSchema::GetDefaultLocator());
builder.SetDependedOnDataSourceLocator(
dependedOnLocatorDataSource);
static HdLocatorDataSourceHandle affectedLocatorDataSource =
HdRetainedTypedSampledDataSource<HdDataSourceLocator>::New(
HdDependenciesSchema::GetDefaultLocator());
builder.SetAffectedDataSourceLocator(
affectedLocatorDataSource);
dependencies.push_back(builder.Build());
}
return HdRetainedContainerDataSource::New(
names.size(), names.data(), dependencies.data());
}
/// Data source adding __dependencies given the data source of a
/// volume.
class _VolumePrimDataSource : public HdContainerDataSource
{
public:
HD_DECLARE_DATASOURCE(_VolumePrimDataSource);
_VolumePrimDataSource(
const SdfPath &primPath,
const HdContainerDataSourceHandle &primSource)
: _primPath(primPath)
, _primSource(primSource)
{
}
bool Has(const TfToken &name) override
{
if (!_primSource) {
return false;
}
if (name == HdDependenciesSchemaTokens->__dependencies) {
return true;
}
return _primSource->Has(name);
}
TfTokenVector GetNames() override
{
TfTokenVector result;
if (!_primSource) {
return result;
}
result = _primSource->GetNames();
result.push_back(HdDependenciesSchemaTokens->__dependencies);
return result;
}
HdDataSourceBaseHandle Get(const TfToken &name) override
{
if (!_primSource) {
return nullptr;
}
HdDataSourceBaseHandle src = _primSource->Get(name);
if (name == HdDependenciesSchemaTokens->__dependencies) {
HdContainerDataSourceHandle sources[] = {
_ComputeVolumeFieldBindingDependencies(_primPath, _primSource),
HdContainerDataSource::Cast(src) };
return HdOverlayContainerDataSource::New(
TfArraySize(sources),
sources);
}
return std::move(src);
}
private:
SdfPath _primPath;
HdContainerDataSourceHandle _primSource;
};
HD_DECLARE_DATASOURCE_HANDLES(_VolumePrimDataSource);
TF_DECLARE_REF_PTRS(_SceneIndex);
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/// \class _SceneIndex
///
/// The scene index feeding into HdDependencyForwardingSceneIndex constructed by
/// by the HdSt_DependencySceneIndexPlugin.
///
class _SceneIndex : public HdSingleInputFilteringSceneIndexBase
{
public:
static _SceneIndexRefPtr New(
const HdSceneIndexBaseRefPtr &inputSceneIndex)
{
return TfCreateRefPtr(new _SceneIndex(inputSceneIndex));
}
HdSceneIndexPrim GetPrim(const SdfPath &primPath) const override
{
const HdSceneIndexPrim prim = _GetInputSceneIndex()->GetPrim(primPath);
if (prim.primType == HdPrimTypeTokens->volume) {
return
{ prim.primType,
_VolumePrimDataSource::New(primPath, prim.dataSource) };
}
return prim;
}
SdfPathVector GetChildPrimPaths(const SdfPath &primPath) const override
{
return _GetInputSceneIndex()->GetChildPrimPaths(primPath);
}
protected:
_SceneIndex(
const HdSceneIndexBaseRefPtr &inputSceneIndex)
: HdSingleInputFilteringSceneIndexBase(inputSceneIndex)
{
}
void _PrimsAdded(
const HdSceneIndexBase &sender,
const HdSceneIndexObserver::AddedPrimEntries &entries) override
{
if (!_IsObserved()) {
return;
}
_SendPrimsAdded(entries);
}
void _PrimsRemoved(
const HdSceneIndexBase &sender,
const HdSceneIndexObserver::RemovedPrimEntries &entries) override
{
if (!_IsObserved()) {
return;
}
_SendPrimsRemoved(entries);
}
void _PrimsDirtied(
const HdSceneIndexBase &sender,
const HdSceneIndexObserver::DirtiedPrimEntries &entries) override
{
HD_TRACE_FUNCTION();
if (!_IsObserved()) {
return;
}
_SendPrimsDirtied(entries);
}
};
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Implementation of HdSt_DependencySceneIndexPlugin
HdSt_DependencySceneIndexPlugin::HdSt_DependencySceneIndexPlugin() = default;
HdSceneIndexBaseRefPtr
HdSt_DependencySceneIndexPlugin::_AppendSceneIndex(
const HdSceneIndexBaseRefPtr &inputScene,
const HdContainerDataSourceHandle &inputArgs)
{
return _SceneIndex::New(inputScene);
}
PXR_NAMESPACE_CLOSE_SCOPE
| 30.614334 | 80 | 0.677815 | [
"vector"
] |
5a2a7df2a923d2bfec666aaad597dacb03f6e979 | 760 | hpp | C++ | lib/sfml/include/sfml/ErrorMessage.hpp | Brukols/Epitech-Arcade | 5443d28169e9494f0c77abac23f4139e60b46365 | [
"MIT"
] | null | null | null | lib/sfml/include/sfml/ErrorMessage.hpp | Brukols/Epitech-Arcade | 5443d28169e9494f0c77abac23f4139e60b46365 | [
"MIT"
] | null | null | null | lib/sfml/include/sfml/ErrorMessage.hpp | Brukols/Epitech-Arcade | 5443d28169e9494f0c77abac23f4139e60b46365 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** OOP_arcade_2019
** File description:
** ErrorMessage
*/
#ifndef ERRORMESSAGE_HPP_
#define ERRORMESSAGE_HPP_
#include "Button.hpp"
#include "Text.hpp"
namespace arc
{
class ErrorMessage {
public:
ErrorMessage(const std::string &message, const std::function<void()> &event, const sf::Font &font);
~ErrorMessage();
void display(sf::RenderWindow &window);
bool isHoverButton(const sf::Vector2i &pos) const;
void click();
private:
std::vector<Button> _button;
std::vector<Text> _text;
sf::RectangleShape _rect;
std::function<void()> _event;
};
} // namespace arc
#endif /* !ERRORMESSAGE_HPP_ */
| 21.714286 | 111 | 0.603947 | [
"vector"
] |
5a2be96c33185a3a8dadff0da9cdb39ec6915e45 | 2,824 | cpp | C++ | old.cpp | FashGek/chazelle-triangulation | 3ef89edb225dbfdd09ce8fde103fe657d01bcc98 | [
"MIT"
] | 1 | 2020-10-20T04:19:49.000Z | 2020-10-20T04:19:49.000Z | old.cpp | FashGek/chazelle-triangulation | 3ef89edb225dbfdd09ce8fde103fe657d01bcc98 | [
"MIT"
] | null | null | null | old.cpp | FashGek/chazelle-triangulation | 3ef89edb225dbfdd09ce8fde103fe657d01bcc98 | [
"MIT"
] | 1 | 2020-10-20T04:20:18.000Z | 2020-10-20T04:20:18.000Z | #include "lipton-tarjan.h"
#include <iostream>
#include <fstream>
#include <csignal>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/planar_canonical_ordering.hpp>
#include <boost/graph/is_straight_line_drawing.hpp>
#include <boost/graph/chrobak_payne_drawing.hpp>
#include <boost/graph/boyer_myrvold_planar_test.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/graph/graphviz.hpp>
using namespace std;
using namespace boost;
Graph load_graph()
{
ifstream in("graph_in");
if( !in ){
cerr << "file \"in\" not found!\n";
exit(0);
}
string str;
Graph g;
while( getline(in, str) ){
uint colon = str.find(",");
string stra = str.substr(0, colon); trim(stra);
string strb = str.substr(colon+1 ); trim(strb);
uint a = lexical_cast<uint>(stra);
uint b = lexical_cast<uint>(strb);
add_edge(a, b, g);
}
return g;
}
struct Coord
{
size_t x, y;
};
typedef vector<Coord> StraightLineDrawingStorage;
Graph* gg;
struct pos_writer
{
template <class VertexOrEdge>
void operator() (ostream& out, const VertexOrEdge& v) const
{
Graph& g = *gg;
int x = g[v].x;
int y = g[v].y;
out << "[pos=\"" << lexical_cast<int>(x) << ',' << lexical_cast<int>(y) << "!\"]";
}
};
void save_graph(Graph g, Embedding* embedding, vector<VertexDescriptor> ordering)
{
typedef iterator_property_map<StraightLineDrawingStorage::iterator, property_map<Graph, vertex_index_t>::type> StraightLineDrawing;
StraightLineDrawingStorage straight_line_drawing_storage(num_vertices(g));
StraightLineDrawing straight_line_drawing (straight_line_drawing_storage.begin(), get(vertex_index,g));
chrobak_payne_straight_line_drawing(g, *embedding, ordering.begin(), ordering.end(), straight_line_drawing);
ofstream f2("out_graph.txt");
graph_traits<Graph>::vertex_iterator vi, vi_end;
int i = 0;
for( tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi ){
Coord coord(get(straight_line_drawing,*vi));
f2 << coord.x << ", " << coord.y << '\n';
g[i].x = coord.x;
g[i].y = coord.y;
i++;
}
gg = &g;
ofstream f("out_graph.dot");
write_graphviz(f, g, pos_writer());
}
int main()
{
auto g = load_graph();
auto p = lipton_tarjan(g);
save_graph(g, p.embedding, p.ordering);
}
| 29.726316 | 139 | 0.593484 | [
"vector"
] |
5a4a49c96e98f7f955191f999f7504a87b567cf6 | 5,042 | cpp | C++ | third_party/WebKit/Source/platform/audio/IIRFilter.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/platform/audio/IIRFilter.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/platform/audio/IIRFilter.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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 "platform/audio/IIRFilter.h"
#include "wtf/MathExtras.h"
#include <complex>
namespace blink {
// The length of the memory buffers for the IIR filter. This MUST be a power of
// two and must be greater than the possible length of the filter coefficients.
const int kBufferLength = 32;
static_assert(kBufferLength >= IIRFilter::kMaxOrder + 1,
"Internal IIR buffer length must be greater than maximum IIR "
"Filter order.");
IIRFilter::IIRFilter(const AudioDoubleArray* feedforward,
const AudioDoubleArray* feedback)
: m_bufferIndex(0), m_feedback(feedback), m_feedforward(feedforward) {
// These are guaranteed to be zero-initialized.
m_xBuffer.allocate(kBufferLength);
m_yBuffer.allocate(kBufferLength);
}
IIRFilter::~IIRFilter() {}
void IIRFilter::reset() {
m_xBuffer.zero();
m_yBuffer.zero();
}
static std::complex<double> evaluatePolynomial(const double* coef,
std::complex<double> z,
int order) {
// Use Horner's method to evaluate the polynomial P(z) = sum(coef[k]*z^k, k,
// 0, order);
std::complex<double> result = 0;
for (int k = order; k >= 0; --k)
result = result * z + std::complex<double>(coef[k]);
return result;
}
void IIRFilter::process(const float* sourceP,
float* destP,
size_t framesToProcess) {
// Compute
//
// y[n] = sum(b[k] * x[n - k], k = 0, M) - sum(a[k] * y[n - k], k = 1, N)
//
// where b[k] are the feedforward coefficients and a[k] are the feedback
// coefficients of the filter.
// This is a Direct Form I implementation of an IIR Filter. Should we
// consider doing a different implementation such as Transposed Direct Form
// II?
const double* feedback = m_feedback->data();
const double* feedforward = m_feedforward->data();
ASSERT(feedback);
ASSERT(feedforward);
// Sanity check to see if the feedback coefficients have been scaled
// appropriately. It must be EXACTLY 1!
ASSERT(feedback[0] == 1);
int feedbackLength = m_feedback->size();
int feedforwardLength = m_feedforward->size();
int minLength = std::min(feedbackLength, feedforwardLength);
double* xBuffer = m_xBuffer.data();
double* yBuffer = m_yBuffer.data();
for (size_t n = 0; n < framesToProcess; ++n) {
// To help minimize roundoff, we compute using double's, even though the
// filter coefficients only have single precision values.
double yn = feedforward[0] * sourceP[n];
// Run both the feedforward and feedback terms together, when possible.
for (int k = 1; k < minLength; ++k) {
int n = (m_bufferIndex - k) & (kBufferLength - 1);
yn += feedforward[k] * xBuffer[n];
yn -= feedback[k] * yBuffer[n];
}
// Handle any remaining feedforward or feedback terms.
for (int k = minLength; k < feedforwardLength; ++k)
yn += feedforward[k] * xBuffer[(m_bufferIndex - k) & (kBufferLength - 1)];
for (int k = minLength; k < feedbackLength; ++k)
yn -= feedback[k] * yBuffer[(m_bufferIndex - k) & (kBufferLength - 1)];
// Save the current input and output values in the memory buffers for the
// next output.
m_xBuffer[m_bufferIndex] = sourceP[n];
m_yBuffer[m_bufferIndex] = yn;
m_bufferIndex = (m_bufferIndex + 1) & (kBufferLength - 1);
destP[n] = yn;
}
}
void IIRFilter::getFrequencyResponse(int nFrequencies,
const float* frequency,
float* magResponse,
float* phaseResponse) {
// Evaluate the z-transform of the filter at the given normalized frequencies
// from 0 to 1. (One corresponds to the Nyquist frequency.)
//
// The z-tranform of the filter is
//
// H(z) = sum(b[k]*z^(-k), k, 0, M) / sum(a[k]*z^(-k), k, 0, N);
//
// The desired frequency response is H(exp(j*omega)), where omega is in [0,
// 1).
//
// Let P(x) = sum(c[k]*x^k, k, 0, P) be a polynomial of order P. Then each of
// the sums in H(z) is equivalent to evaluating a polynomial at the point
// 1/z.
for (int k = 0; k < nFrequencies; ++k) {
// zRecip = 1/z = exp(-j*frequency)
double omega = -piDouble * frequency[k];
std::complex<double> zRecip = std::complex<double>(cos(omega), sin(omega));
std::complex<double> numerator = evaluatePolynomial(
m_feedforward->data(), zRecip, m_feedforward->size() - 1);
std::complex<double> denominator =
evaluatePolynomial(m_feedback->data(), zRecip, m_feedback->size() - 1);
std::complex<double> response = numerator / denominator;
magResponse[k] = static_cast<float>(abs(response));
phaseResponse[k] =
static_cast<float>(atan2(imag(response), real(response)));
}
}
} // namespace blink
| 35.507042 | 80 | 0.631297 | [
"transform"
] |
5a4c57b6205d90ef3a222e1c4c68cf861d6564f8 | 5,260 | cpp | C++ | CuteEngine/Widgets/transformwidget.cpp | Code0100Food/CuteEngine | 8e8500c6414b94a8be6243a6b05334a27def7516 | [
"MIT"
] | null | null | null | CuteEngine/Widgets/transformwidget.cpp | Code0100Food/CuteEngine | 8e8500c6414b94a8be6243a6b05334a27def7516 | [
"MIT"
] | null | null | null | CuteEngine/Widgets/transformwidget.cpp | Code0100Food/CuteEngine | 8e8500c6414b94a8be6243a6b05334a27def7516 | [
"MIT"
] | null | null | null | #include "transformwidget.h"
#include <QLabel>
#include <QDoubleSpinBox>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QVector3D>
#include "transform.h"
TransformWidget::TransformWidget(QWidget* parent) : QWidget(parent)
{
//UI initialization
QVBoxLayout* main_layout = new QVBoxLayout();
//Window title
QLabel* title = new QLabel("Transform");
main_layout->addWidget(title);
//Grid
QGridLayout* grid = new QGridLayout();
//Labels
QLabel* position_label = new QLabel("Position");
QLabel* rotation_label = new QLabel("Rotation");
QLabel* scale_label = new QLabel("Scale");
QLabel* position_label_x = new QLabel("X");
QLabel* position_label_y = new QLabel("Y");
QLabel* position_label_z = new QLabel("Z");
QLabel* rotation_label_x = new QLabel("X");
QLabel* rotation_label_y = new QLabel("Y");
QLabel* rotation_label_z = new QLabel("Z");
QLabel* scale_label_x = new QLabel("X");
QLabel* scale_label_y = new QLabel("Y");
QLabel* scale_label_z = new QLabel("Z");
//Spin boxes
position_x = new QDoubleSpinBox();
position_x->setRange(-1000.0f,1000.0f);
position_y = new QDoubleSpinBox();
position_y->setRange(-1000.0f,1000.0f);
position_z = new QDoubleSpinBox();
position_z->setRange(-1000.0f,1000.0f);
rotation_x = new QDoubleSpinBox();
rotation_x->setRange(-360.0f,360.0f);
rotation_y = new QDoubleSpinBox();
rotation_y->setRange(-360.0f,360.0f);
rotation_z = new QDoubleSpinBox();
rotation_z->setRange(-360.0f,360.0f);
scale_x = new QDoubleSpinBox();
scale_x->setRange(0.0f,1000.0f);
scale_y = new QDoubleSpinBox();
scale_y->setRange(0.0f,1000.0f);
scale_z = new QDoubleSpinBox();
scale_z->setRange(0.0f,1000.0f);
//Position
grid->addWidget(position_label,0,0);
grid->addWidget(position_label_x,0,1);
grid->addWidget(position_x,0,2);
grid->addWidget(position_label_y,0,3);
grid->addWidget(position_y,0,4);
grid->addWidget(position_label_z,0,5);
grid->addWidget(position_z,0,6);
//Position connections
connect(position_x,SIGNAL(valueChanged(double)),this,SLOT(SetXPosition(double)));
connect(position_y,SIGNAL(valueChanged(double)),this,SLOT(SetYPosition(double)));
connect(position_z,SIGNAL(valueChanged(double)),this,SLOT(SetZPosition(double)));
//Rotation
grid->addWidget(rotation_label,1,0);
grid->addWidget(rotation_label_x,1,1);
grid->addWidget(rotation_x,1,2);
grid->addWidget(rotation_label_y,1,3);
grid->addWidget(rotation_y,1,4);
grid->addWidget(rotation_label_z,1,5);
grid->addWidget(rotation_z,1,6);
//Rotation connections
connect(rotation_x,SIGNAL(valueChanged(double)),this,SLOT(SetXRotation(double)));
connect(rotation_y,SIGNAL(valueChanged(double)),this,SLOT(SetYRotation(double)));
connect(rotation_z,SIGNAL(valueChanged(double)),this,SLOT(SetZRotation(double)));
//Scale
grid->addWidget(scale_label,2,0);
grid->addWidget(scale_label_x,2,1);
grid->addWidget(scale_x,2,2);
grid->addWidget(scale_label_y,2,3);
grid->addWidget(scale_y,2,4);
grid->addWidget(scale_label_z,2,5);
grid->addWidget(scale_z,2,6);
//Scale connections
connect(scale_x,SIGNAL(valueChanged(double)),this,SLOT(SetXScale(double)));
connect(scale_y,SIGNAL(valueChanged(double)),this,SLOT(SetYScale(double)));
connect(scale_z,SIGNAL(valueChanged(double)),this,SLOT(SetZScale(double)));
main_layout->addLayout(grid);
setLayout(main_layout);
}
void TransformWidget::GetEntityValues(QVector3D position, QVector3D rotation, QVector3D scale)
{
position_x->setValue(position.x());
position_y->setValue(position.y());
position_z->setValue(position.z());
rotation_x->setValue(rotation.x());
rotation_y->setValue(rotation.y());
rotation_z->setValue(rotation.z());
scale_x->setValue(scale.x());
scale_y->setValue(scale.y());
scale_z->setValue(scale.z());
}
void TransformWidget::SetXPosition(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetXPosition(value);
}
void TransformWidget::SetYPosition(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetYPosition(value);
}
void TransformWidget::SetZPosition(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetZPosition(value);
}
void TransformWidget::SetXRotation(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetXRotation(value);
}
void TransformWidget::SetYRotation(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetYRotation(value);
}
void TransformWidget::SetZRotation(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetZRotation(value);
}
void TransformWidget::SetXScale(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetXScale(value);
}
void TransformWidget::SetYScale(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetYScale(value);
}
void TransformWidget::SetZScale(double value)
{
if(selcted_entity_transform)
selcted_entity_transform->SetZScale(value);
}
| 30.229885 | 94 | 0.713878 | [
"transform"
] |
9905938368dd4dc1ea16a6460328ede375a4db91 | 28,478 | cpp | C++ | prototype/src/asf/plugin_execute.cpp | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 3 | 2017-12-31T05:33:28.000Z | 2021-07-28T01:51:22.000Z | prototype/src/asf/plugin_execute.cpp | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | null | null | null | prototype/src/asf/plugin_execute.cpp | glshort/MapReady | c9065400a64c87be46418ab32e3a251ca2f55fd5 | [
"BSD-3-Clause"
] | 7 | 2017-04-26T18:18:33.000Z | 2020-05-15T08:01:09.000Z | /**
Determine execution order for asf plugins.
Basically a compiler-like dependency analysis
and lazy execution system. This file is way too complicated
and buggy--need to figure out a cleaner, simpler approach.
The only external entry point is "execute_list" at the bottom.
External calls go out from here to the parameter_image classes,
and plugin::execute.
The flow of control inside this file is truly horrific, so here's the cheat sheet:
All these classes are shadows of the real working classes like
plugin and parameter_pixel_image.
execute_plugin shadows "plugin". It's used to keep track of dependencies.
It's got an "render" method, which loops over sub-tiles
to drive the rendering.
execute_image shadows "parameter_pixel_image". It
keeps track of the desired size and source of each image.
The key method is again "render", which loops over input images.
execute_block shadows "parameter_control_list". Its job is to keeps track
of everybody, and allow execute_plugins to find one another via their
shared parameters. Everything starts at the execute_block object.
See the comment at the bottom routine for overall control flow.
Orion Sky Lawlor, olawlor@acm.org, 2005/11/29.
*/
#include "asf/plugin.h"
#include "asf/plugin_control.h"
#include "asf/image.h"
/* Base execution logging level */
#define ex_loglevel 20
using namespace asf;
class execute_plugin; /* forward declaration */
class execute_image;
/**
Cover a rectangle with tiles of the given size.
*/
class rect_tiling {
public:
asf::pixel_rectangle r; ///< Region to cover (pixels)
pixel_size tile_size; ///< Pixel size of a tile
tile_location tile_count; ///< total number of tiles in each direction
pixel_location origin; ///< pixel coordinates of topleft corner of first tile
/** Create a tiling of the rectangle r, clipped to bounds, of this tile size */
rect_tiling(const asf::pixel_rectangle &r_,const asf::pixel_rectangle &bounds_,const pixel_size &tile_sz_);
// Return the outline of this tile:
asf::pixel_rectangle get_outline(const tile_location &t) {
asf::pixel_rectangle outer( /* entire region to potentially cover */
origin.x+tile_size.x*t.x,origin.y+tile_size.y*t.y,
origin.x+tile_size.x*(t.x+1),origin.y+tile_size.y*(t.y+1)
);
return outer.get_intersect(r);
}
};
/** Create a tiling of the rectangle r, clipped to bounds, of this tile size */
rect_tiling::rect_tiling(const asf::pixel_rectangle &r_,const asf::pixel_rectangle &bounds_,const pixel_size &sz_)
:r(bounds_.get_intersect(r_)), tile_size(sz_),
tile_count((r.width()+tile_size.x-1)/tile_size.x,
(r.height()+tile_size.y-1)/tile_size.y),
origin(r.get_min())
{
}
/**
Keeps a list of plugins, e.g., that read or write a particular parameter.
*/
class execute_plugins {
std::vector<execute_plugin *> l;
public:
inline execute_plugin *operator[](int i) const {return l[i];}
inline unsigned int size(void) const {return l.size();}
void push_back(execute_plugin *p) {
int s=size();
if (s>0 && l[s-1]==p) return; /* already there--don't bother */
l.push_back(p);
}
};
/// Describes desired properties of processing tiles
class set_size_param {
public:
/// Preferred size of a processing tile.
/// May actually end up bigger or smaller than this.
pixel_size size;
/// Preferred log-base-2 zoom factor of a tile.
int zoom;
};
/// Describes a region to be rendered
class render_request {
public:
/// Region in meta coordinates to be rendered
asf::pixel_rectangle rect;
/// Maximum zoom factor to use in rendering (detail requested)
int zoom;
render_request() {zoom=-1234;}
render_request(const asf::pixel_rectangle &r,int z) :rect(r), zoom(z) {}
};
/**
Lets plugins find each other through their shared parameters.
*/
class execute_block {
public:
/** Create a new empty top-level block */
execute_block(void);
/** Create a new sub-block for sub-plugins of this master.
The outer block is the master's context */
execute_block(execute_plugin *master,execute_block *outer);
/** Add this block of plugins */
void add(const parameter_control_list *list);
/** Add this plugin to our lists */
void add(plugin *pl);
/** This plugin creates this parameter */
void add_output(execute_plugin *pl,parameter *pa,parameter_constraint *constraint);
/** This plugin reads this parameter.
Return the image object if this turns out to be an image.
*/
execute_image *add_input(execute_plugin *pl,parameter *pa,parameter_constraint *constraint);
/** Set up the sizes of all our images */
void set_size(const set_size_param &preferred);
/** Execute all sink plugins to render at this size and detail */
void render(const render_request &req);
private:
/// Keeps a big list of all possible plugins
/// (for eventual cleanup)
execute_plugins plugins;
/// Keeps a list of plugins that have side effects (i.e., sink plugins)
/// These are plugins that might send stuff off to the outside world.
execute_plugins sink_plugins;
void add_sink(execute_plugin *ex);
/// Connects parameters to the plugins that create them.
typedef std::multimap<parameter *,execute_plugin *> creators_t;
creators_t creators;
/** Return the execute_image corresponding to this parameter, or NULL if not an image */
execute_image *if_image(parameter *);
/// Connects parameters to their execute_image objects.
typedef std::map<parameter *,execute_image *> images_t;
images_t images;
/// Used only for sub-registries:
execute_plugin *master; execute_block *outer;
};
/**
Represents an image parameter that is passed between two plugins.
Manages the conversions between:
1.) The image total size, which is readonly by us.
2.) The image's allocated size, which we control.
3.) The image's processing tile size, which is under plugin control.
*/
class execute_image {
public:
/** Datatype of images we deal with */
typedef parameter_float_image img_t;
execute_image(img_t *img_);
/**
"Plugin", or "Portal" image.
Image that all the plugins are pointing at.
Normally points to data stored in Aimg--that is,
Pimg is a plugin's "portal" to Aimg's data.
*/
img_t *Pimg;
/**
"Allocated", or "All" image.
Image used for allocating pixels. Different from Pimg because
sometimes we want to allocate a big piece (e.g., to pass to an I/O plugin)
but pass some plugins smaller chunks (e.g., for cache efficiency).
*/
img_t *Aimg;
/// Add a plugin that might read or write this image
void add_plugin(execute_plugin *p,parameter_constraint *constraint,bool isOutput);
/** Set up the allocated and per-plugin sizes of our image.
default_tile_size is the desired size of a processing tile, in pixels.
Small tile sizes will fit in cache better.
Large tile sizes have lower book-keeping overhead.
The best tile size must still be determined by experiment.
*/
void set_size(const set_size_param &preferred);
/**
Render this meta-coordinates region of us. Always:
- Allocates this region.
- Fills region with data from input plugins.
*/
void render(const render_request &req);
/**
An input plugin has changed-- now none of us is computed correctly.
*/
void flush(void);
/// The total finished size of our image (virtual region divided into tiles)
pixel_size total;
/// The size our image should be allocated to
pixel_size alloc;
int zoom; /* Zoom factor for our image */
/// The tile size our plugins should shoot for (during set_size only)
pixel_size preferred_tile;
/**
This rectangle stores the portion of us that is allocated and fully computed.
*/
asf::pixel_rectangle finished_rect;
/** Stores the relationship of a plugin to this image */
class plug_img {
public:
/// Plugin we represent
execute_plugin *p;
/// Constraint this plugin places on image size (may be NULL)
parameter_image_constraint *constraint;
/// Image size for use by this plugin. -1, -1 for unknown
pixel_size tile;
/// Zoom factor used by this plugin.
int zoom;
};
/// Return the plug_img for this plugin.
plug_img *get_img(execute_plugin *p) {
unsigned int i;
for (i=0;i<inp.size();i++) if (inp[i]->p==p) return inp[i];
for (i=0;i<outp.size();i++) if (outp[i]->p==p) return outp[i];
return 0;
}
/** List of plugins that (may) write to our image */
std::vector<plug_img *> inp;
/** List of plugins that (may) read from our output image */
std::vector<plug_img *> outp;
private:
void size_pass(plug_img *pi);
};
/**
Represents one execution of a plugin. Basically a wrapper
around a real plugin object, used to keep track of dependencies.
Possibly should be merged with asf::plugin.
Initial state: flushed.
After "execute", outputs become ready.
*/
class execute_plugin {
public:
execute_plugin(plugin *p,execute_block &r) {setup(p,r);}
virtual ~execute_plugin() {}
/// Compute this meta rectangle of our output image(s), which are already allocated.
virtual void render(const render_request &req);
/// Render self as a sink, covering yourself completely.
/// You need not leave output images allocated to the requested size.
virtual void sink_render(const render_request &req);
/**
One of our inputs has changed--invalidate all our outputs.
*/
virtual void flush(void);
/// State of this plugin:
typedef enum {
state_needy=0, /* Need inputs (initial state) */
state_busy=1, /* Actually computing outputs from inputs */
state_ready=2 /* Outputs are ready */
} state_t;
/// Current state of this plugin
state_t state;
/// Real plugin we will execute
plugin *pl;
/// Datatype for images we read or write
typedef parameter_pixel_image img_t;
/// List of plugins that create any of our input parameters
execute_plugins in_dep;
/// Our plugin's input image objects
std::vector<execute_image *> in_img;
/// The map from our output image to the corresponding input image above
std::vector<location_function *> in_map;
/// Add this input image
void add_in_img(execute_image *i);
/// Return true if we shouldn't bother with any image crap.
bool no_images(void) const {return in_img.size()==0 && out_img.size()==0;}
/// List of plugins that use any of our output parameters
execute_plugins out_dep;
/// Our plugin's output images
std::vector<execute_image *> out_img;
protected:
execute_plugin() {} /* MUST call setup afterwards! */
void setup(plugin *p,execute_block &r);
/// Render all inputs needed for this output rectangle.
void render_inputs(const render_request &req);
/// Indicate to all our output dependencies that we've been flushed
void out_flush(void);
};
/**
An execute_plugin wrapper around a parameter_control_flow plugin.
*/
class execute_plugin_control : public execute_plugin {
public:
execute_plugin_control(plugin_control_flow *plf,execute_block &r);
~execute_plugin_control();
virtual void render(const render_request &req);
private:
/** Registries used by our plugin's different control lists */
std::vector<execute_block *> subs;
/** Real plugin we're wrapping */
plugin_control_flow *plf;
};
/************* block *****************/
/** Create a new empty top-level block */
execute_block::execute_block(void) {
master=0; outer=0;
}
/** Create a new sub-block for sub-plugins of this master.
The outer block is the master's context */
execute_block::execute_block(execute_plugin *m,execute_block *o) {
master=m; outer=o;
}
void execute_block::add(const parameter_control_list *list)
{
for (unsigned int i=0;i<list->size();i++)
add(list->index(i));
}
/**
Add this plugin object to us, by wrapping it in an execute_plugin
(or execute_plugin_control).
*/
void execute_block::add(plugin *pl)
{
execute_plugin *ex;
plugin_control_flow *plf=dynamic_cast<plugin_control_flow *>(pl);
if (plf) ex=new execute_plugin_control(plf,*this);
else ex=new execute_plugin(pl,*this);
plugins.push_back(ex);
if (pl->has_side_effects()) {
add_sink(ex);
}
}
/**
Add a "sink" plugin (that writes files or creates output, and hence
has to be called on each execution).
*/
void execute_block::add_sink(execute_plugin *ex)
{
sink_plugins.push_back(ex);
if (outer) outer->add_sink(master); /* if we've got sinks, our master is a sink too */
}
/** This plugin creates this parameter */
void execute_block::add_output(execute_plugin *creator,parameter *pa,parameter_constraint *constraint)
{
execute_image *img=if_image(pa);
if (img) { /* creator's output is image's input */
creator->out_img.push_back(img);
img->add_plugin(creator,constraint,false);
}
creator->pl->log(ex_loglevel+5,"execute_block::add_output> I create parameter %p (%s)\n",pa,pa->get_type()->name());
creators.insert(std::make_pair(pa,creator));
if (master)
outer->add_output(master,pa,constraint); /* seen from outside, master creates this parameter */
}
/** This plugin reads this parameter */
execute_image *execute_block::add_input(execute_plugin *reader,parameter *pa,parameter_constraint *constraint)
{
execute_image *img=if_image(pa);
if (img) { /* image output is reader's input */
reader->in_img.push_back(img);
img->add_plugin(reader,constraint,true);
}
creators_t::iterator start=creators.equal_range(pa).first;
creators_t::iterator end=creators.equal_range(pa).second;
for (creators_t::iterator it=start;it!=end;++it)
{/* Somebody we know creates that input */
execute_plugin *creator=(*it).second;
if (creator!=reader && img==NULL) {
reader->pl->log(ex_loglevel+5,"execute_block::add_input> I depend on plugin %s via parameter %p (%s)\n",creator->pl->get_type()->name(),pa,pa->get_type()->name());
reader->in_dep.push_back(creator); /* he goes in our input dependency list */
creator->out_dep.push_back(reader); /* we go in his output dependency list */
}
}
if (outer) { /* Perhaps the parameter also comes from outside */
outer->add_input(master,pa,constraint); /* ... and master needs it too (so we get called). */
outer->add_input(reader,pa,constraint); /* ... we need to go in his out_dep lists. */
}
return img;
}
execute_image *execute_block::if_image(parameter *p)
{
if (outer) return outer->if_image(p); /* don't keep image lists in sub-registries; only at top level */
images_t::iterator it=images.find(p);
if (it!=images.end()) return (*it).second; /* found it! */
/* else nothing listed yet-- check if it's even an image */
execute_image::img_t *img=dynamic_cast<execute_image::img_t *>(p);
if (!img) return 0; /* not even an image */
/* else make a new execute_image to store this new image */
execute_image *i=new execute_image(img);
images[p]=i;
return i;
}
/// For "printf" on a rect object:
#define rect_fmt "rect (%d-%d, %d-%d)"
#define rect_args(rect) rect.lo_x,rect.hi_x,rect.lo_y,rect.hi_y
/// For "printf" on a render_request object:
#define req_fmt " region("rect_fmt ", zoom %d)"
#define req_args(req) rect_args(req.rect), req.zoom
void execute_block::set_size(const set_size_param &preferred) {
asf::log(ex_loglevel,"execute_block> set_size {\n");
for (images_t::iterator it=images.begin();it!=images.end();++it)
(*it).second->set_size(preferred);
asf::log(ex_loglevel,"execute_block> } set_size\n");
}
static int big_int=1999999999; /**< A big signed integer. Don't use (~0)>>1 because of wraparound problems. */
static asf::pixel_rectangle big_rect(-big_int,-big_int,big_int,big_int);
static asf::pixel_rectangle ok_rect(0,0,1,1);
static asf::pixel_rectangle empty_rect(0,0,0,0);
void execute_block::render(const render_request &req) {
asf::log(ex_loglevel,"execute_block> render { \n");
for (unsigned int i=0;i<sink_plugins.size();i++) {
asf::log(ex_loglevel+3," execute_block> rendering next sink\n");
sink_plugins[i]->sink_render(req); /* will recursively prep all required inputs */
}
asf::log(ex_loglevel,"execute_block> } render \n");
}
/***************** Images ********************/
execute_image::execute_image(img_t *img_)
:Pimg(img_), Aimg(0),
total(-1,-1), alloc(-1,-1), zoom(0),
finished_rect(empty_rect)
{
Aimg=(img_t *)(Pimg->clone());
}
void execute_image::add_plugin(execute_plugin *p,parameter_constraint *constraint,bool isOutput)
{
plug_img *i=new plug_img;
i->p=p;
i->constraint=dynamic_cast<parameter_image_constraint *>(constraint);
i->tile.x=i->tile.y=-1;
if (isOutput) outp.push_back(i);
else inp.push_back(i);
}
/** Round this rectangle up to a multiple of preferred.size */
pixel_rectangle roundup(const set_size_param &preferred,const pixel_rectangle &r) {
pixel_rectangle ret;
ret.lo_x=r.lo_x;
ret.lo_y=r.lo_y;
/* Round size up to a multiple of preferred.size */
ret.hi_x=r.lo_x+preferred.size.x*(int)ceil(r.width() /(double)preferred.size.x);
ret.hi_y=r.lo_y+preferred.size.y*(int)ceil(r.height()/(double)preferred.size.y);
return ret;
}
/** Set up the sizes of our image */
void execute_image::set_size(const set_size_param &preferred)
{
/* The image's total pixel size comes from the plugins--
it's not under our control.
*/
Aimg->meta_setsize(Pimg->bands(),roundup(preferred,Pimg->total_meta_bounds()));
total=Pimg->total_meta_bounds().size();
/* We *want* to allocate the smaller of the tile and total image sizes */
alloc.x=std::min(preferred.size.x,total.x);
alloc.y=std::min(preferred.size.y,total.y);
zoom=preferred.zoom;
bool alloc_changed=false;
do {
/* Don't bother tiling really small allocations--just bump up the allocation */
if (alloc.x*2>total.x) alloc.x=total.x;
if (alloc.y*2>total.y) alloc.y=total.y;
pixel_size old=alloc;
unsigned int i;
/* We *have* to allocate the largest tile size of any plugin */
for (i=0;i< inp.size();i++) size_pass( inp[i]);
for (i=0;i<outp.size();i++) size_pass(outp[i]);
alloc_changed=(old.x!=alloc.x || old.y!=alloc.y);
inp[0]->p->pl->log(ex_loglevel+1,"execute_image> set_size alloc loop: %d x %d total; %d x %d z=%d alloc\n",
total.x,total.y,alloc.x,alloc.y,zoom);
/* if alloc_changed, processed chunk got bigger-- try again */
} while (alloc_changed);
/* We now have the subimage size to allocate, and all tile sizes.
We don't actually allocate the subimage until it's first needed. */
}
/** Utility routine called only during set_size:
Set this plugin's processed tile size, and enlarge our
allocated size if needed. */
void execute_image::size_pass(plug_img *pi)
{
pi->tile=alloc; /* process the preferred tile size by default */
pi->zoom=zoom; /* process at standard zoom by default */
if (pi->constraint) {
pi->constraint->constrain_subimage(total.x,total.y,&pi->tile.x,&pi->tile.y,&pi->zoom);
if (alloc!=pi->tile || zoom!=pi->zoom)
pi->p->pl->log(ex_loglevel,"execute_image> set_size %d x %d image: constraint required %d x %d/%d instead of %d x %d/%d\n",
total.x,total.y,pi->tile.x,pi->tile.y,pi->zoom,alloc.x,alloc.y,zoom);
/* We must allocate the *largest* tile size needed by any plugin */
alloc.x=std::max(alloc.x,pi->tile.x);
alloc.y=std::max(alloc.y,pi->tile.y);
/* We need the *smallest* (finest) zoom factor used by any plugin */
zoom=std::min(zoom,pi->zoom);
}
}
/******** Execute_plugin ************/
void execute_plugin::setup(plugin *pl_,execute_block &r) {
pl=pl_;
state=state_needy;
/* Figure out what parameters this plugin takes, and where they come from */
const plugin_parameter_signature *sig=pl->get_signature();
plugin_parameters &ps=pl->get_parameters();
const plugin_parameter_signature::params *v;
unsigned int i;
parameter *pa=0;
v=&sig->inputs();
for (i=0;i<v->size();i++) {
ps.param((*v)[i]->name,(*v)[i]->t,&pa,0,0,plugin_parameters::dir_input);
add_in_img(r.add_input(this,pa,(*v)[i]->constraint));
}
v=&sig->optionals();
for (i=0;i<v->size();i++) {
ps.param((*v)[i]->name,(*v)[i]->t,&pa,0,0,plugin_parameters::dir_optional);
if (pa) add_in_img(r.add_input(this,pa,(*v)[i]->constraint));
}
v=&sig->outputs();
for (i=0;i<v->size();i++) {
ps.param((*v)[i]->name,(*v)[i]->t,&pa,0,0,plugin_parameters::dir_output);
r.add_output(this,pa,(*v)[i]->constraint);
}
}
void execute_plugin::add_in_img(execute_image *i)
{
if (i==0) return;
in_map.push_back(pl->image_in_from_out(in_map.size(),0));
}
/// Render self as a sink, covering yourself completely.
/// You need not leave output images allocated to the requested size.
void execute_plugin::sink_render(const render_request &req)
{
render(req);
}
/// Compute this meta rectangle of our output image(s).
void execute_plugin::render(const render_request &req)
{
pl->log(ex_loglevel,"execute_plugin> render { "req_fmt"\n",req_args(req));
if (no_images())
{ /* A non-image plugin-- just run once and we're done. */
if (state==state_ready) return; /* nothing to do */
pl->log(ex_loglevel,"execute_plugin> non-image run\n");
render_inputs(req);
pl->execute();
}
else
{ /* An image plugin-- loop over tiles */
execute_image *ei=0;
if (out_img.size()>0) ei=out_img[0]; /* Normal case: loop over output image */
else if (in_img.size()>0) ei=in_img[0]; /* for sinks: loop over input image */
else asf::die("Logic error in execute_plugin::render!"); /* should be no_images case */
/* Find the image's record for us */
execute_image::plug_img *p=ei->get_img(this);
/* Now loop over tiles.
SUBTLE: ei->Pimg gives the maximum region we should consider touching.
*/
rect_tiling tiles(req.rect,ei->Pimg->total_meta_bounds(),p->tile);
tile_location t;
for (t.y=0;t.y<tiles.tile_count.y;t.y++)
for (t.x=0;t.x<tiles.tile_count.x;t.x++)
{
pixel_rectangle tile_r=tiles.get_outline(t);
pl->log(ex_loglevel,"execute_plugin> rendering tile (%d,%d)\n",t.x,t.y);
state=state_needy; /* flush outputs; need output tile */
/* Prepare input images */
render_request t; t.rect=tile_r; t.zoom=req.zoom;
render_inputs(t);
/* Compute outputs from inputs */
ei->Pimg->pixel_pointat(ei->Aimg,t.rect,t.zoom);
pl->log(ex_loglevel-5,"execute_plugin> execute plugin "req_fmt"\n",req_args(t));
pl->execute();
pl->log(ex_loglevel,"execute_plugin> } execute plugin\n");
}
}
state=state_ready; /* our outputs are now ready */
pl->log(ex_loglevel,"execute_plugin> } render\n");
}
/* Make sure each input image is really there */
void execute_plugin::render_inputs(const render_request &req) {
unsigned int i;
pl->log(ex_loglevel,"execute_plugin> render_inputs { "req_fmt"\n",req_args(req));
if (state==state_busy) asf::die("Circular dependency? execute_plugin::execute called, but already running execute method!\n");
state=state_busy; /* busy computing input requirements */
/* Make sure each non-image input plugin is ready */
for (i=0;i<in_dep.size();i++) {
pl->log(ex_loglevel+3,"execute_plugin> rendering non-image input %d\n",i);
in_dep[i]->render(req); /* FIXME: same request OK? */
}
/* Make sure each input image is ready */
for (i=0;i<in_img.size();i++) {
render_request in;
/* Find the portion of the input image we'll need to cover this part of our output. */
if (in_map[i]) in.rect=in_map[i]->apply_rectangle(req.rect);
else in.rect=req.rect;
/* FIXME: adjust zoom factor for input */
in.zoom=req.zoom;
pl->log(ex_loglevel,"execute_plugin> my "req_fmt" is input image %d's "req_fmt"\n",
req_args(req), i, req_args(in));
execute_image *ei=in_img[i];
/* Ask the image to create that portion of its output.
This may involve recursive calls out to other plugins. */
ei->render(in);
/* Leave the image's pixels pointing where *we* need them */
ei->Pimg->pixel_pointat(ei->Aimg,in.rect,in.zoom);
}
pl->log(ex_loglevel,"execute_plugin> } render_inputs\n");
}
/**
Make sure this rectangle of us has been computed properly,
by allocating ourselves and calling our input plugins.
*/
void execute_image::render(const render_request &req)
{
inp[0]->p->pl->log(ex_loglevel,"execute_image> image render " req_fmt "\n",req_args(req));
if (finished_rect.contains(req.rect)) return; /* already computed */
/* else we need to ask our input plugins to compute us: */
/* FIXME: image shift & caching here? Or are overlapping requests rare? */
/* Allocate image to be big enough to handle the request *and* all our plugins */
int w=std::max(req.rect.width(),alloc.x);
int h=std::max(req.rect.height(),alloc.y);
int z=std::min(zoom,req.zoom);
pixel_rectangle r(
req.rect.lo_x ,req.rect.lo_y,
req.rect.lo_x+w,req.rect.lo_y+h);
Aimg->pixel_setsize(r,z); /* allocate ourselves on the requested rectangle */
inp[0]->p->pl->log(ex_loglevel,"execute_image> image allocated with (%d,%d) meta pixels, zoom %d\n",
w,h,z);
r=r.get_intersect(Pimg->total_meta_bounds());
for (unsigned int i=0;i<inp.size();i++) {
render_request in;
in.rect=r;
in.zoom=inp[i]->zoom;
inp[i]->p->render(in);
}
/* We've now finished calculating this part of ourselves. */
finished_rect=r;
}
void execute_plugin::flush(void)
{
if (state==state_needy) return; /* already flushed */
state=state_needy;
out_flush();
}
void execute_plugin::out_flush(void)
{
pl->log(ex_loglevel,"execute_plugin> out_flush {\n");
/* Make sure each output knows we're gone */
for (unsigned int i=0;i<out_dep.size();i++)
out_dep[i]->flush();
/* Make sure each outgoing image knows we're gone */
for (unsigned int i=0;i<out_img.size();i++)
out_img[i]->flush();
pl->log(ex_loglevel,"execute_plugin> } out_flush\n");
}
/// An input has changed-- set our valid region to empty
void execute_image::flush(void)
{
finished_rect=empty_rect;
}
/************* execute_plugin_control **************
Wraps plugins capable of control flow management, like loops.
*/
execute_plugin_control::execute_plugin_control(plugin_control_flow *p,execute_block &outer)
{
plf=p;
for (int i=0;i<plf->get_list_count();i++)
{ /* make a new execute_block for our plugin's i'th list */
execute_block *sub=new execute_block(this,&outer);
setup(p,*sub); /* Add our parameters to the sub-block */
/* Register this list's contents in the sub-block */
sub->add(plf->get_list(i));
subs.push_back(sub);
}
}
execute_plugin_control::~execute_plugin_control() {
for (int i=0;i<plf->get_list_count();i++)
delete subs[i];
}
/*
Execute our inner loop plugins.
*/
void execute_plugin_control::render(const render_request &req)
{
pl->log(ex_loglevel,"execute_plugin> plugin_control render {\n");
if (state==state_ready) return; /* nothing to do */
render_inputs(req);
// Idiomatic plugin_control_flow::execute, passing control to block
int step=0, list=-1;
while (0<=(list=plf->execute_iteration(step++))) {
state=state_ready; /* output for this iteration is ready */
out_flush(); /* because execute_iteration changed the loop index */
pl->log(ex_loglevel,"execute_plugin> plugin_control iteration {\n");
subs[list]->render(req); /* runs needy plugins inside the loop body */
pl->log(ex_loglevel,"execute_plugin> } plugin_control iteration\n");
}
pl->log(ex_loglevel,"execute_plugin> } plugin_control render\n");
}
/**
Execute the plugins in this list in some sensible order,
creating tiles as needed, and pruning useless branches.
*/
void asf::execute_list(const asf::parameter_control_list &list,int tile_size)
{
/**
Call the plugin's meta_execute routines. Since meta_execute
routines are called in dependency order, each plugin's input parameters
already have metadata by the time the plugin gets called.
meta_execute normally figures out the theoretical meta size of each
plugin's output images.
*/
asf::log(ex_loglevel-1,"plugin_execute> Finding meta image sizes\n");
list.meta_execute();
/**
Create execute_* shadows of the plugins and parameters in this control list.
*/
asf::log(ex_loglevel ,"plugin_execute> Building execute objects\n");
execute_block r;
r.add(&list);
/**
Figure out how big our image tiles should be at each stage of processing.
*/
asf::log(ex_loglevel-1,"plugin_execute> Finding tile sizes\n");
set_size_param preferred;
if (tile_size==0) tile_size=64; /* Default tile size */
preferred.size=pixel_size(tile_size,tile_size);
preferred.zoom=0;
r.set_size(preferred); /* find processed tile sizes */
/**
Actually render pixels. This process is demand-driven, starting at the *output*
required, and recursively bubbling requests up to the root inputs.
*/
asf::log(ex_loglevel-1,"plugin_execute> Executing plugins\n");
render_request req;
req.rect=big_rect;
req.zoom=0;
r.render(req); /* move pixels */
asf::log(ex_loglevel-1,"plugin_execute> All plugins executed\n");
}
| 33.781732 | 166 | 0.709671 | [
"render",
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.