hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ad2e5639aecfa16fcd70bc9b17e518eacc9fb232
| 655
|
cpp
|
C++
|
Chapter 3. Strings, Vectors, and Arrays/Codes/3.45.cpp
|
Yunxiang-Li/Cpp_Primer
|
b5c857e3f6be993b2ff8fc03f634141ae24925fc
|
[
"MIT"
] | null | null | null |
Chapter 3. Strings, Vectors, and Arrays/Codes/3.45.cpp
|
Yunxiang-Li/Cpp_Primer
|
b5c857e3f6be993b2ff8fc03f634141ae24925fc
|
[
"MIT"
] | null | null | null |
Chapter 3. Strings, Vectors, and Arrays/Codes/3.45.cpp
|
Yunxiang-Li/Cpp_Primer
|
b5c857e3f6be993b2ff8fc03f634141ae24925fc
|
[
"MIT"
] | 1
|
2021-09-30T14:08:03.000Z
|
2021-09-30T14:08:03.000Z
|
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int ia[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
// Use a range for to manage the iteration
// Use auto
for (auto& p : ia)
for (auto& q : p)
cout << q << " ";
cout << endl;
// Use ordinary for loop using subscripts
// Use auto
for (auto i = 0; i != 3; ++i)
for (auto j = 0; j != 4; ++j)
cout << ia[i][j] << " ";
cout << endl;
// Use pointers.
// Use auto
for (auto p = ia; p != ia + 3; ++p)
for (int* q = *p; q != *p + 4; ++q) cout << *q << " ";
cout << endl;
return 0;
}
| 20.46875
| 62
| 0.432061
|
Yunxiang-Li
|
ad330f3b84f5f441445ee356b83ff25d021f5abb
| 56,000
|
cpp
|
C++
|
tests/rtest_ac_chol_d.cpp
|
dgburnette/ac_math
|
518629af779ae26167462055ea4a3c30738ba5f9
|
[
"Apache-2.0"
] | 2
|
2018-03-22T08:46:54.000Z
|
2018-04-03T06:09:00.000Z
|
tests/rtest_ac_chol_d.cpp
|
dgburnette/ac_math
|
518629af779ae26167462055ea4a3c30738ba5f9
|
[
"Apache-2.0"
] | null | null | null |
tests/rtest_ac_chol_d.cpp
|
dgburnette/ac_math
|
518629af779ae26167462055ea4a3c30738ba5f9
|
[
"Apache-2.0"
] | null | null | null |
/**************************************************************************
* *
* Algorithmic C (tm) Math Library *
* *
* Software Version: 3.4 *
* *
* Release Date : Wed May 4 10:47:29 PDT 2022 *
* Release Type : Production Release *
* Release Build : 3.4.3 *
* *
* Copyright 2018 Siemens *
* *
**************************************************************************
* 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. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
// =========================TESTBENCH=======================================
// This testbench file contains a stand-alone testbench that exercises the
// ac_chol_d() function using a variety of data types and bit-
// widths.
// To compile standalone and run:
// $MGC_HOME/bin/c++ -std=c++11 -I$MGC_HOME/shared/include rtest_ac_chol_d.cpp -o design
// ./design
// Include the AC Math function that is exercised with this testbench
#include <ac_math/ac_chol_d.h>
using namespace ac_math;
// ==============================================================================
// Test Designs
// These simple functions allow executing the ac_chol_d() function
// using multiple data types at the same time. Template parameters are
// used to configure the bit-widths of the types.
// Test Design for real and complex fixed point values.
template <bool use_pwl, unsigned M, int Wfi, int Ifi, int outWfi, int outIfi, bool outSfi>
void test_ac_chol_d_fixed(
const ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP> A1[M][M],
ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> L1[M][M],
const ac_complex<ac_fixed<Wfi + 1, Ifi + 1, true, AC_TRN, AC_WRAP> > A2[M][M],
ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> > L2[M][M],
const ac_matrix<ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP>, M, M> &A3,
ac_matrix<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP>, M, M> &L3,
const ac_matrix<ac_complex<ac_fixed<Wfi + 1, Ifi + 1, true, AC_TRN, AC_WRAP> >, M, M> &A4,
ac_matrix<ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> >, M, M> &L4
)
{
ac_chol_d<use_pwl>(A1, L1);
ac_chol_d<use_pwl>(A2, L2);
ac_chol_d<use_pwl>(A3, L3);
ac_chol_d<use_pwl>(A4, L4);
}
// Test Design for real ac_float values.
template <bool use_pwl, unsigned M, int Wfl, int Ifl, int Efl, int outWfl, int outIfl, int outEfl>
void test_ac_chol_d_float(
const ac_float<Wfl, Ifl, Efl, AC_TRN> A1[M][M],
ac_float<outWfl, outIfl, outEfl, AC_TRN> L1[M][M],
const ac_matrix<ac_float<Wfl, Ifl, Efl, AC_TRN>, M, M> &A2,
ac_matrix<ac_float<outWfl, outIfl, outEfl, AC_TRN>, M, M> &L2
)
{
ac_chol_d<use_pwl>(A1, L1);
ac_chol_d<use_pwl>(A2, L2);
}
// Test Design for real ac_std_float values.
template <bool use_pwl, unsigned M, int Wstfl, int Estfl, int outWstfl, int outEstfl>
void test_ac_chol_d_stfloat(
const ac_std_float<Wstfl, Estfl> A1[M][M],
ac_std_float<outWstfl, outEstfl> L1[M][M],
const ac_matrix<ac_std_float<Wstfl, Estfl>, M, M> &A2,
ac_matrix<ac_std_float<outWstfl, outEstfl>, M, M> &L2
)
{
ac_chol_d<use_pwl>(A1, L1);
ac_chol_d<use_pwl>(A2, L2);
}
// Test Design for real ac_ieee_float values.
template <bool use_pwl, unsigned M, ac_ieee_float_format in_format, ac_ieee_float_format out_format>
void test_ac_chol_d_ifloat(
const ac_ieee_float<in_format> A1[M][M],
ac_ieee_float<out_format> L1[M][M],
const ac_matrix<ac_ieee_float<in_format>, M, M> &A2,
ac_matrix<ac_ieee_float<out_format>, M, M> &L2
)
{
ac_chol_d<use_pwl>(A1, L1);
ac_chol_d<use_pwl>(A2, L2);
}
// ==============================================================================
#include <ac_math/ac_normalize.h>
using namespace ac_math;
#include <math.h>
#include <string>
#include <fstream>
#include <limits>
#include <random>
#include <iostream>
using namespace std;
// ------------------------------------------------------------------------------
// Helper functions
// Helper structs for printing out type info for ac_std_float and ac_ieee_float
// Generic struct, enables template specialization
template <typename T>
struct type_string_st { };
// Specialized struct, handles ac_std_floats
template <int W, int E>
struct type_string_st<ac_std_float<W, E> > {
static string type_string() {
string format_string = "ac_std_float<";
format_string += ac_int<32,true>(W).to_string(AC_DEC);
format_string += ",";
format_string += ac_int<32,true>(E).to_string(AC_DEC);
format_string += ">";
return format_string;
}
};
// Specialized struct, handles ac_ieee_floats
template <ac_ieee_float_format Format>
struct type_string_st<ac_ieee_float<Format> > {
static string type_string() {
string format_string = "ac_ieee_float<";
if (Format == binary16) { format_string += "binary16"; }
if (Format == binary32) { format_string += "binary32"; }
if (Format == binary64) { format_string += "binary64"; }
if (Format == binary128) { format_string += "binary128"; }
if (Format == binary256) { format_string += "binary256"; }
format_string += ">";
return format_string;
}
};
#ifdef DEBUG
// print_matrix functions: Print 2D C-style matrix for debugging purposes.
// print_matrix for ac_fixed/ac_complex<ac_fixed>/ac_float matrix.
template<unsigned M, class T>
void print_matrix(const T mat[M][M])
{
cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {cout << "mat[" << i << "][" << j << "] = " << mat[i][j] << endl;}
}
}
// print_matrix for ac_std_float matrix.
template<unsigned M, int W, int E>
void print_matrix(const ac_std_float<W, E> mat[M][M])
{
cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {cout << "mat[" << i << "][" << j << "] = " << mat[i][j].to_ac_float().to_double() << endl;}
}
}
// print_matrix for ac_ieee_float matrix.
template<unsigned M, ac_ieee_float_format Format>
void print_matrix(const ac_ieee_float<Format> mat[M][M])
{
cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {cout << "mat[" << i << "][" << j << "] = " << mat[i][j].to_ac_float().to_double() << endl;}
}
}
#endif
// Generate positive definite matrix of ac_fixed values
template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
void gen_matrix(ac_fixed<W, I, S, Q, O> A[M][M])
{
static_assert(I - int(S) >= ac::nbits<M - 1>::val, "Not enough integer bits in input type.");
static_assert(W - I >= 2, "Input type must have at least 2 fractional bits.");
// Declare two MxM matrices, once of which (tbmatT) is the transpose of the other.
ac_fixed<(W - I)/2, 0, false> tbmat[M][M];
ac_fixed<(W - I)/2, 0, false> tbmatT[M][M];
// Make sure the minimum limit for the random number generator is the quantum double value.
double min_rand_limit = std::numeric_limits<double>::min();
// default_random_engine and uniform_real_distribution are libraries from the <random> header,
// packaged with C++11 and later standards.
default_random_engine generator;
// Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix.
// The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly
// selected value picked out of a uniform probability density in the range of (0, 1).
uniform_real_distribution<double> distribution(min_rand_limit, 1.0);
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
tbmat[i][j] = distribution(generator);
tbmatT[j][i] = tbmat[i][j];
}
}
#ifdef DEBUG
cout << "tbmat is : " << endl;
print_matrix(tbmat);
cout << "tbmatT is : " << endl;
print_matrix(tbmatT);
#endif
// Multiply tbmat by its transpose to get the positive definite input matrix
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
A[i][j] = 0;
for (int k = 0; k < (int)M; k++) {
A[i][j] += tbmat[i][k] * tbmatT[k][j];
}
}
}
#ifdef DEBUG
cout << "A in gen_matrix function is : " << endl;
print_matrix(A);
#endif
}
// Generate positive definite matrix of ac_complex<ac_fixed> values
template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
void gen_matrix(ac_complex<ac_fixed<W, I, S, Q, O> > A[M][M])
{
static_assert(S, "Input type must be signed");
static_assert(I - 1 >= ac::nbits<M - 1>::val, "Not enough integer bits in input type.");
static_assert(W - I >= 4, "Input type must have at least 4 fractional bits.");
// Declare two MxM matrices, once of which (tbmatT) is the conjugate transpose of the other.
ac_complex<ac_fixed<(W - I)/2, 0, true> > tbmat[M][M];
ac_complex<ac_fixed<(W - I)/2, 0, true> > tbmatT[M][M];
// Make sure the minimum limit for the random number generator is the quantum double value.
double min_rand_limit = std::numeric_limits<double>::min();
// default_random_engine and uniform_real_distribution are libraries from the <random> header,
// packaged with C++11 and later standards.
default_random_engine generator;
// Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix.
uniform_real_distribution<double> distribution(min_rand_limit, 0.5);
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
ac_fixed<(W - I)/2 - 1, -1, false> rand_val;
tbmat[i][j].r() = distribution(generator);
tbmat[i][j].i() = distribution(generator);
tbmatT[j][i] = tbmat[i][j].conj();
}
}
#ifdef DEBUG
cout << "tbmat is : " << endl;
print_matrix(tbmat);
cout << "tbmatT is : " << endl;
print_matrix(tbmatT);
#endif
// Multiply tbmat by its transpose to get the positive definite input matrix
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
A[i][j] = 0;
for (int k = 0; k < (int)M; k++) {
A[i][j] += tbmat[i][k] * tbmatT[k][j];
}
}
}
#ifdef DEBUG
cout << "A in gen_matrix function is : " << endl;
print_matrix(A);
#endif
}
// Generate positive definite matrix of ac_float values
template<unsigned M, int W, int I, int E, ac_q_mode Q>
void gen_matrix(ac_float<W, I, E, Q> A[M][M]) {
static_assert(I >= 1, "Input mantissa must have at least 1 integer bit.");
static_assert(W >= ac::nbits<M - 1>::val + 2 + 1, "Not enough bitwidth for mantissa.");
enum {
max_int_val = ac::nbits<M - 1>::val,
E_val_1 = ac::nbits<W - 1>::val,
val_2 = (max_int_val - (I - 1) < 0) ? -(max_int_val - (I - 1)) : max_int_val - (I - 1),
E_val_2 = ac::nbits<AC_MAX(val_2, 1)>::val,
E_min = AC_MAX(int(E_val_1), int(E_val_2)) + 1,
};
static_assert(E >= E_min, "Not enough exponent bits.");
// Make sure the minimum limit for the random number generator is the quantum double value.
double min_rand_limit = std::numeric_limits<double>::min();
// default_random_engine and uniform_real_distribution are libraries from the <random> header,
// packaged with C++11 and later standards.
default_random_engine generator;
// Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix.
// The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly
// selected value picked out of a uniform probability density in the range of (0, 1).
uniform_real_distribution<double> distribution(min_rand_limit, 1.0);
ac_fixed<(W - max_int_val - 1)/2, 0, false> tbmat[M][M], tbmatT[M][M];
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
tbmat[i][j] = distribution(generator);
tbmatT[j][i] = tbmat[i][j];
}
}
ac_fixed<W - 1, max_int_val, false> mac_val;
// Multiply tbmat by its transpose to get the positive definite input matrix
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
mac_val = 0;
for (int k = 0; k < (int)M; k++) {
mac_val += tbmat[i][k] * tbmatT[k][j];
}
A[i][j] = mac_val;
}
}
#ifdef DEBUG
cout << "tbmat:" << endl;
print_matrix(tbmat);
cout << "tbmatT:" << endl;
print_matrix(tbmatT);
cout << "A:" << endl;
print_matrix(A);
#endif
}
// Generate positive definite matrix of ac_std_float values
template<unsigned M, int W, int E>
void gen_matrix(ac_std_float<W, E> A[M][M])
{
static_assert(W - E - 1 >= ac::nbits<M - 1>::val + 2 + 1, "Not enough bitwidth for mantissa.");
enum {
max_int_val = ac::nbits<M - 1>::val,
E_val_1 = ac::nbits<W - E - 1>::val,
E_val_2 = ac::nbits<AC_MAX(max_int_val - 1, 1)>::val,
E_min = AC_MAX(int(E_val_1), int(E_val_2)) + 1,
};
static_assert(E >= E_min, "Not enough exponent bits.");
// Make sure the minimum limit for the random number generator is the quantum double value.
double min_rand_limit = std::numeric_limits<double>::min();
// default_random_engine and uniform_real_distribution are libraries from the <random> header,
// packaged with C++11 and later standards.
default_random_engine generator;
// Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix.
// The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly
// selected value picked out of a uniform probability density in the range of (0, 1).
uniform_real_distribution<double> distribution(min_rand_limit, 1.0);
ac_fixed<(W - E - max_int_val - 1)/2, 0, false> tbmat[M][M], tbmatT[M][M];
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
tbmat[i][j] = distribution(generator);
tbmatT[j][i] = tbmat[i][j];
}
}
ac_fixed<W - E - 1, max_int_val, false> mac_val;
// Multiply tbmat by its transpose to get the positive definite input matrix
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
mac_val = 0;
for (int k = 0; k < (int)M; k++) {
mac_val += tbmat[i][k] * tbmatT[k][j];
}
A[i][j] = ac_std_float<W, E>(mac_val);
}
}
#ifdef DEBUG
cout << "tbmat:" << endl;
print_matrix(tbmat);
cout << "tbmatT:" << endl;
print_matrix(tbmatT);
cout << "A_ac_fl:" << endl;
print_matrix(A_ac_fl);
#endif
}
// Generate positive definite matrix of ac_ieee_float values
template<unsigned M, ac_ieee_float_format Format>
void gen_matrix(ac_ieee_float<Format> A[M][M])
{
typedef ac_ieee_float<Format> T_in;
enum {
W = T_in::width,
E = T_in::e_width,
max_int_val = ac::nbits<M - 1>::val,
};
// Make sure the minimum limit for the random number generator is the quantum double value.
double min_rand_limit = std::numeric_limits<double>::min();
// default_random_engine and uniform_real_distribution are libraries from the <random> header,
// packaged with C++11 and later standards.
default_random_engine generator;
// Use a uniform distribution to maximize the chance of obtaining an invertible tbmat/tbmatT matrix.
// The output produced by this is similar to that of matlab's "rand" function, i.e. a randomly
// selected value picked out of a uniform probability density in the range of (0, 1).
uniform_real_distribution<double> distribution(min_rand_limit, 1.0);
ac_fixed<(W - E - max_int_val - 1)/2, 0, false> tbmat[M][M], tbmatT[M][M];
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
tbmat[i][j] = distribution(generator);
tbmatT[j][i] = tbmat[i][j];
}
}
ac_fixed<W - E - 1, max_int_val, false> mac_val;
// Multiply tbmat by its transpose to get the positive definite input matrix
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
mac_val = 0;
for (int k = 0; k < (int)M; k++) {
mac_val += tbmat[i][k] * tbmatT[k][j];
}
A[i][j] = ac_ieee_float<Format>(mac_val);
}
}
#ifdef DEBUG
cout << "tbmat:" << endl;
print_matrix(tbmat);
cout << "tbmatT:" << endl;
print_matrix(tbmatT);
cout << "A_ac_fl:" << endl;
print_matrix(A_ac_fl);
#endif
}
// Testbench for cholesky decomposition for ac_fixed matrix
// The testbench uses the cholesky-crout algorithm
template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
void chol_d_tb(
const ac_fixed<W, I, S, Q, O> A[M][M],
double L_tb[M][M]
)
{
double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk;
// All elements of output initialized to zero by default
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0;}
}
// L_tb = 0;
for (int j = 0; j < (int)M; j++) {
sum_Ajj_Ljk_sq = A[j][j].to_double();
for (int k = 0; k < j; k++) {
sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k];
}
// Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal
// element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the
// input matrix is positive definite
assert(sum_Ajj_Ljk_sq > 0);
// Assign value to diagonal elements.
L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq);
for (int i = (j+1); i < (int)M; i++) {
sum_Aij_Lik_Ljk = A[i][j].to_double();
for (int k = 0; k < j; k++) {
sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k];
}
// Assign value to non-diagonal elements below the diagonal.
L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j];
}
}
}
// Testbench for cholesky decomposition for ac_complex<ac_fixed> matrices
// The testbench uses the cholesky-crout algorithm
template<unsigned M, int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
void chol_d_tb(
ac_complex<ac_fixed<W, I, S, Q, O> > A[M][M],
ac_complex<double> L_tb[M][M]
)
{
typedef ac_complex<double> output_type;
output_type zero_complex(0, 0), sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk;
// All elements of output initialized to zero by default
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {L_tb[i][j] = zero_complex;}
}
// L_tb = zero_complex;
for (int j = 0; j < (int)M; j++) {
sum_Ajj_Ljk_sq.r() = A[j][j].r().to_double();
sum_Ajj_Ljk_sq.i() = A[j][j].i().to_double();
for (int k = 0; k < j; k++) {
sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k].conj();
}
// Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal
// element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the
// input matrix is positive definite
assert(sum_Ajj_Ljk_sq.r() > 0);
// Assign value to diagonal elements. Since the diagonal elements are real, only initialize the real part.
L_tb[j][j].r() = sqrt(sum_Ajj_Ljk_sq.r());
for (int i = (j+1); i < (int)M; i++) {
sum_Aij_Lik_Ljk.r() = A[i][j].r().to_double();
sum_Aij_Lik_Ljk.i() = A[i][j].i().to_double();
for (int k = 0; k < j; k++) {
sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k].conj();
}
// Assign value to non-diagonal elements below the diagonal.
L_tb[i][j].r() = (1 / L_tb[j][j].r())*sum_Aij_Lik_Ljk.r();
L_tb[i][j].i() = (1 / L_tb[j][j].r())*sum_Aij_Lik_Ljk.i();
}
}
}
// Testbench for cholesky decomposition for ac_float matrix
// The testbench uses the cholesky-crout algorithm
template<unsigned M, int W, int I, int E, ac_q_mode Q>
void chol_d_tb(
const ac_float<W, I, E, Q> A[M][M],
double L_tb[M][M]
)
{
double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk;
// All elements of output initialized to zero by default
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0.0;}
}
for (int j = 0; j < (int)M; j++) {
sum_Ajj_Ljk_sq = A[j][j].to_double();
for (int k = 0; k < j; k++) {
sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k];
}
// Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal
// element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the
// input matrix is positive definite
assert(sum_Ajj_Ljk_sq > 0);
// Assign value to diagonal elements.
L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq);
for (int i = (j+1); i < (int)M; i++) {
sum_Aij_Lik_Ljk = A[i][j].to_double();
for (int k = 0; k < j; k++) {
sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k];
}
// Assign value to non-diagonal elements below the diagonal.
L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j];
}
}
}
// Testbench for cholesky decomposition for ac_std_float matrix
// The testbench uses the cholesky-crout algorithm
template<unsigned M, int W, int E>
void chol_d_tb(
const ac_std_float<W, E> A[M][M],
double L_tb[M][M]
)
{
double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk;
// All elements of output initialized to zero by default
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0.0;}
}
for (int j = 0; j < (int)M; j++) {
sum_Ajj_Ljk_sq = A[j][j].to_ac_float().to_double();
for (int k = 0; k < j; k++) {
sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k];
}
// Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal
// element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the
// input matrix is positive definite
assert(sum_Ajj_Ljk_sq > 0);
// Assign value to diagonal elements.
L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq);
for (int i = (j+1); i < (int)M; i++) {
sum_Aij_Lik_Ljk = A[i][j].to_ac_float().to_double();
for (int k = 0; k < j; k++) {
sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k];
}
// Assign value to non-diagonal elements below the diagonal.
L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j];
}
}
}
// Testbench for cholesky decomposition for ac_ieee_float matrix
// The testbench uses the cholesky-crout algorithm
template<unsigned M, ac_ieee_float_format Format>
void chol_d_tb(
const ac_ieee_float<Format> A[M][M],
double L_tb[M][M]
) {
double sum_Ajj_Ljk_sq, sum_Aij_Lik_Ljk;
// All elements of output initialized to zero by default
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {L_tb[i][j] = 0.0;}
}
for (int j = 0; j < (int)M; j++) {
sum_Ajj_Ljk_sq = A[j][j].to_ac_float().to_double();
for (int k = 0; k < j; k++) {
sum_Ajj_Ljk_sq -= L_tb[j][k] * L_tb[j][k];
}
// Check to make sure that the matrix is positive definite. If "sum_Ajj_Ljk_sq" is negative/zero, then the diagonal
// element, i.e. L_tb(j, j) will be complex/zero, which is not valid. This condition will not be encountered if the
// input matrix is positive definite
assert(sum_Ajj_Ljk_sq > 0);
// Assign value to diagonal elements.
L_tb[j][j] = sqrt(sum_Ajj_Ljk_sq);
for (int i = (j+1); i < (int)M; i++) {
sum_Aij_Lik_Ljk = A[i][j].to_ac_float().to_double();
for (int k = 0; k < j; k++) {
sum_Aij_Lik_Ljk -= L_tb[i][k] * L_tb[j][k];
}
// Assign value to non-diagonal elements below the diagonal.
L_tb[i][j] = sum_Aij_Lik_Ljk / L_tb[j][j];
}
}
}
// Return the absolute value of the matrix element that has the
// maximum absolute value.
template<unsigned M>
double abs_mat_max(
const double L_tb[M][M]
)
{
double max_val = 0;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
if (abs(L_tb[i][j]) > max_val) {max_val = abs(L_tb[i][j]);}
}
}
return max_val;
}
// Return the absolute value of the matrix element that has the
// maximum absolute value.
template<unsigned M>
double abs_mat_max(
const ac_complex<double> L_tb[M][M]
)
{
double max_val = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
if (L_tb[i][j].mag_sqr() > max_val) {max_val = L_tb[i][j].mag_sqr();}
}
}
return max_val;
}
// Keep real, double element as it is (just kept in order to ensure that the error checking
// function is compatible even for real, double values)
double conv_val(double x)
{
return x;
}
// Convert real, ac_fixed element to double.
template<int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
double conv_val(ac_fixed<W, I, S, Q, O> x)
{
return x.to_double();
}
// Convert complex double element to mag_sqr.
double conv_val(ac_complex<double> x)
{
return x.mag_sqr();
}
// Convert complex ac_fixed element to the double of it's
// mag_sqr
template<int W, int I, bool S, ac_q_mode Q, ac_o_mode O>
double conv_val(ac_complex<ac_fixed<W, I, S, Q, O> > x)
{
return x.mag_sqr().to_double();
}
// Convert real, ac_float element to double.
template <int W, int I, int E, ac_q_mode Q>
double conv_val(ac_float<W, I, E, Q> x) {
return x.to_double();
}
// Convert real, ac_std_float element to double.
template <int W, int E>
double conv_val(ac_std_float<W, E> x) {
return x.to_ac_float().to_double();
}
// Convert real, ac_ieee_float element to double.
template <ac_ieee_float_format Format>
double conv_val(ac_ieee_float<Format> x) {
return x.to_ac_float().to_double();
}
// Compare DUT output matrix to testbench computed matrix and find error.
template<unsigned M, class T, class T_tb>
double compare_matrices(
const T L[M][M],
const T_tb L_tb[M][M],
const double allowed_error
)
{
double this_error, max_error = 0, max_val;
// Find the max. abs. value in the matrix. In case of complex matrices, this is the max.
// mag_sqr value. For real matrices, it's the max. absolute value stored in the matrix.
max_val = abs_mat_max(L_tb);
#ifdef DEBUG
cout << "max_val = " << max_val << endl;
#endif
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
// The error is calculated as the difference between the value of the expected
// vs. the actual value, normalized w.r.t. the max_value in the matrix. For complex
// numbers, the expected vs actual values are first converted to the their
// mag_sqr() representations. For real numbers, the values are passed as they are
// for the error calculation.
this_error = 100.0 * abs( conv_val(L[i][j]) - conv_val(L_tb[i][j]) ) / (max_val);
if (this_error > max_error) { max_error = this_error;}
#ifdef DEBUG
cout << "FILE : " << __FILE__ << ", LINE : " << __LINE__ << endl;
cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl;
cout << "L_tb[" << i << "][" << j << "] = " << L_tb[i][j] << endl;
cout << "this_error = " << this_error << endl;
assert(this_error < allowed_error);
#endif
}
}
return max_error;
}
// Check if real ac_fixed/ac_float matrix is zero matrix.
template<unsigned M, class T>
bool check_if_zero_matrix(
const T L[M][M]
)
{
bool is_zero_matrix = true;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
if (L[i][j] != 0) {
is_zero_matrix = false;
#ifdef DEBUG
cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl;
cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl;
assert(false);
#endif
}
}
}
return is_zero_matrix;
}
// Check if complex matrix is zero matrix.
template<unsigned M, class T>
bool check_if_zero_matrix(
const ac_complex<T> L[M][M]
)
{
bool is_zero_matrix = true;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
if (L[i][j].r() != 0 || L[i][j].i() != 0) {
is_zero_matrix = false;
#ifdef DEBUG
cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl;
cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl;
assert(false);
#endif
}
}
}
return is_zero_matrix;
}
// Check if ac_std_float matrix is zero matrix.
template <unsigned M, int W, int E>
bool check_if_zero_matrix(
const ac_std_float<W, E> L[M][M]
) {
typedef ac_std_float<W, E> T;
bool is_zero_matrix = true;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
if (L[i][j] != T::zero()) {
is_zero_matrix = false;
#ifdef DEBUG
cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl;
cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl;
assert(false);
#endif
}
}
}
return is_zero_matrix;
}
// Check if ac_ieee_float matrix is zero matrix.
template <unsigned M, ac_ieee_float_format Format>
bool check_if_zero_matrix(
const ac_ieee_float<Format> L[M][M]
) {
typedef ac_ieee_float<Format> T;
bool is_zero_matrix = true;
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {
if (L[i][j] != T::zero()) {
is_zero_matrix = false;
#ifdef DEBUG
cout << "Matrix was not zero for a non positive definite input. Non-zero element found:" << endl;
cout << "L[" << i << "][" << j << "] = " << L[i][j] << endl;
assert(false);
#endif
}
}
}
return is_zero_matrix;
}
// Copy a C-style array's contents over to an ac_matrix.
template<unsigned M, class T_matrix, class T_ac_matrix>
void copy_to_ac_matrix(
const T_matrix array_2D[M][M],
T_ac_matrix &output
)
{
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {output(i, j) = array_2D[i][j];}
}
}
// Copy an ac_matrix's contents over to a C-style array.
template<unsigned M, class T_matrix, class T_ac_matrix>
void copy_to_array_2D(
const T_ac_matrix &input,
T_matrix array_2D[M][M]
)
{
for (int i = 0; i < (int)M; i++) {
for (int j = 0; j < (int)M; j++) {array_2D[i][j] = input(i, j);}
}
}
// ==============================================================================
// Functions: test_driver functions
// Description: Templatized functions that can be configured for certain bit-
// widths of AC datatypes. They use the type information to iterate through a
// range of valid values on that type in order to compare the precision of the
// DUT cholesky decomposition with the computed cholesky decomposition using a
// standard C double type. The maximum error for each type is accumulated
// in variables defined in the calling function.
// ==============================================================================
// Function: test_driver_fixed()
// Description: test_driver function for ac_fixed and ac_complex<ac_fixed> inputs
// and outputs.
// FBfi = number of fractional bits in input type.
template <bool use_pwl, unsigned M, int FBfi, int outWfi, int outIfi, bool outSfi>
int test_driver_fixed(
double &cumulative_max_error,
double &cumulative_max_error_cmplx,
const double allowed_error
)
{
enum {
Ifi = ac::nbits<M - 1>::val,
Wfi = FBfi + Ifi,
Ifi_c = Ifi + 1,
Wfi_c = Wfi + 1
};
bool passed = true;
ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP> A_C_array[M][M];
ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> L_C_array[M][M];
ac_complex<ac_fixed<Wfi_c, Ifi_c, true, AC_TRN, AC_WRAP> > cmplx_A_C_array[M][M];
ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> > cmplx_L_C_array[M][M];
ac_matrix<ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP>, M, M> A_ac_matrix;
ac_matrix<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP>, M, M> L_ac_matrix;
ac_matrix<ac_complex<ac_fixed<Wfi_c, Ifi_c, true, AC_TRN, AC_WRAP> >, M, M> cmplx_A_ac_matrix;
ac_matrix<ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> >, M, M> cmplx_L_ac_matrix;
if (use_pwl) {
cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions.
} else {
cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions.
}
cout.width(2);
cout << left << M;
cout << ", INPUT: ";
cout.width(37);
cout << left << A_C_array[0][0].type_name();
cout << "OUTPUT: ";
cout.width(37);
cout << left << L_C_array[0][0].type_name();
cout << "RESULT: ";
double L_tb[M][M];
ac_complex<double> cmplx_L_tb[M][M];
// The gen_matrix function takes an MxM matrix, and multiplies it by its
// conjugate transpose to obtain a positive definite input matrix
gen_matrix(A_C_array);
gen_matrix(cmplx_A_C_array);
copy_to_ac_matrix(A_C_array, A_ac_matrix);
copy_to_ac_matrix(cmplx_A_C_array, cmplx_A_ac_matrix);
test_ac_chol_d_fixed<use_pwl>(A_C_array, L_C_array, cmplx_A_C_array, cmplx_L_C_array, A_ac_matrix, L_ac_matrix, cmplx_A_ac_matrix, cmplx_L_ac_matrix);
ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> L_ac_matrix_converted[M][M];
ac_complex<ac_fixed<outWfi, outIfi, outSfi, AC_TRN, AC_WRAP> > L_cmplx_ac_matrix_converted[M][M];
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
copy_to_array_2D(cmplx_L_ac_matrix, L_cmplx_ac_matrix_converted);
// Get output of testbench function for cholesky decomposition.
chol_d_tb(A_C_array, L_tb);
chol_d_tb(cmplx_A_C_array, cmplx_L_tb);
#ifdef DEBUG
cout << "A_C_array = " << endl;
print_matrix(A_C_array);
cout << "L_C_array = " << endl;
print_matrix(L_C_array);
cout << "L_tb = " << endl;
print_matrix(L_tb);
cout << "cmplx_A_C_array = " << endl;
print_matrix(cmplx_A_C_array);
cout << "cmplx_L_C_array = " << endl;
print_matrix(cmplx_L_C_array);
cout << "cmplx_L_tb = " << endl;
print_matrix(cmplx_L_tb);
cout << "A_ac_matrix = " << endl;
cout << A_ac_matrix << endl;
cout << "L_ac_matrix = " << endl;
cout << L_ac_matrix << endl;
cout << "cmplx_A_ac_matrix = " << endl;
cout << cmplx_A_ac_matrix << endl;
cout << "cmplx_L_ac_matrix = " << endl;
cout << cmplx_L_ac_matrix << endl;
#endif
// Compare matrices and get the max error
double max_error = compare_matrices(L_C_array, L_tb, allowed_error);
double max_error_cmplx = compare_matrices(cmplx_L_C_array, cmplx_L_tb, allowed_error);
double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error);
double max_error_cmplx_ac_matrix = compare_matrices(L_cmplx_ac_matrix_converted, cmplx_L_tb, allowed_error);
// Put max overall error in a separate variable.
double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix;
double max_error_cmplx_overall = max_error_cmplx > max_error_cmplx_ac_matrix ? max_error_cmplx : max_error_cmplx_ac_matrix;
passed = (max_error_overall < allowed_error) && (max_error_cmplx_overall < allowed_error);
// Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix
// with all the values set to the quantum values of the ac_fixed type as the input.
ac_fixed<Wfi, Ifi, false, AC_TRN, AC_WRAP> ac_fixed_quantum_value;
ac_fixed_quantum_value.template set_val<AC_VAL_QUANTUM>();
ac_complex<ac_fixed<Wfi_c, Ifi_c, false, AC_TRN, AC_WRAP> > ac_complex_quantum_value(ac_fixed_quantum_value, ac_fixed_quantum_value);
A_ac_matrix = ac_fixed_quantum_value;
cmplx_A_ac_matrix = ac_complex_quantum_value;
// Copy over a non-positive definite matrix to the standard C array inputs.
copy_to_array_2D(A_ac_matrix, A_C_array);
copy_to_array_2D(cmplx_A_ac_matrix, cmplx_A_C_array);
test_ac_chol_d_fixed<use_pwl>(A_C_array, L_C_array, cmplx_A_C_array, cmplx_L_C_array, A_ac_matrix, L_ac_matrix, cmplx_A_ac_matrix, cmplx_L_ac_matrix);
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
copy_to_array_2D(cmplx_L_ac_matrix, L_cmplx_ac_matrix_converted);
// Make sure that a zero matrix is returned at the output.
passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(cmplx_L_C_array) && check_if_zero_matrix(L_ac_matrix_converted) && check_if_zero_matrix(L_cmplx_ac_matrix_converted);
if (passed) { printf("PASSED , max err (%f) (%f complex)\n", max_error_overall, max_error_cmplx_overall); }
else { printf("FAILED , max err (%f) (%f complex)\n", max_error_overall, max_error_cmplx_overall); } // LCOV_EXCL_LINE
if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; }
if (max_error_cmplx_overall > cumulative_max_error_cmplx) { cumulative_max_error_cmplx = max_error_cmplx_overall; }
return 0;
}
// ==============================================================================
// Function: test_driver_float()
// Description: test_driver function for ac_float inputs and outputs.
// FBfl = number of fractional bits in input mantissa type.
template <bool use_pwl, unsigned M, int FBfl, int outWfl, int outIfl, int outEfl>
int test_driver_float(
double &cumulative_max_error,
const double allowed_error
)
{
bool passed = true;
enum {
Ifl = 1,
Wfl = Ifl + FBfl,
E_val_1 = ac::nbits<Wfl - 1>::val,
max_int_val = ac::nbits<M - 1>::val,
val_2 = (max_int_val - (Ifl - 1) < 0) ? -(max_int_val - (Ifl - 1)) : max_int_val - (Ifl - 1),
E_val_2 = ac::nbits<AC_MAX(int(val_2), 1)>::val,
Efl = AC_MAX(int(E_val_1), int(E_val_2)) + 1,
};
ac_float<Wfl, Ifl, Efl, AC_TRN> A_C_array[M][M];
ac_float<outWfl, outIfl, outEfl, AC_TRN> L_C_array[M][M];
ac_matrix<ac_float<Wfl, Ifl, Efl, AC_TRN>, M, M> A_ac_matrix;
ac_matrix<ac_float<outWfl, outIfl, outEfl, AC_TRN>, M, M> L_ac_matrix;
if (use_pwl) {
cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions.
} else {
cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions.
}
cout.width(2);
cout << left << M;
cout << ", INPUT: ";
cout.width(37);
cout << left << A_C_array[0][0].type_name();
cout << "OUTPUT: ";
cout.width(37);
cout << left << L_C_array[0][0].type_name();
cout << "RESULT: ";
double L_tb[M][M];
// The gen_matrix function takes an MxM matrix, and multiplies it by its
// transpose to obtain a positive definite input matrix
gen_matrix(A_C_array);
copy_to_ac_matrix(A_C_array, A_ac_matrix);
test_ac_chol_d_float<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix);
ac_float<outWfl, outIfl, outEfl, AC_TRN> L_ac_matrix_converted[M][M];
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
// Get output of testbench function for cholesky decomposition.
chol_d_tb(A_C_array, L_tb);
#ifdef DEBUG
cout << "A_C_array = " << endl;
print_matrix(A_C_array);
cout << "L_C_array = " << endl;
print_matrix(L_C_array);
cout << "L_tb = " << endl;
print_matrix(L_tb);
cout << "A_ac_matrix = " << endl;
cout << A_ac_matrix << endl;
cout << "L_ac_matrix = " << endl;
cout << L_ac_matrix << endl;
#endif
// Compare matrices and get the max error
double max_error = compare_matrices(L_C_array, L_tb, allowed_error);
double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error);
// Put max overall error in a separate variable.
double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix;
passed = (max_error_overall < allowed_error);
// Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix
// with all the values set to the quantum values of the ac_float type as the input.
ac_float<Wfl, Ifl, Efl, AC_TRN> ac_float_quantum_value;
ac_float_quantum_value.template set_val<AC_VAL_QUANTUM>();
A_ac_matrix = ac_float_quantum_value;
// Copy over a non-positive definite matrix to the standard C array inputs.
copy_to_array_2D(A_ac_matrix, A_C_array);
test_ac_chol_d_float<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix);
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
// Make sure that a zero matrix is returned at the output.
passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(L_ac_matrix_converted);
if (passed) { printf("PASSED , max err (%f)\n", max_error_overall); }
else { printf("FAILED , max err (%f)\n", max_error_overall); } // LCOV_EXCL_LINE
if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; }
return 0;
}
// ==============================================================================
// Function: test_driver_stfloat()
// Description: test_driver function for ac_std_float inputs and outputs.
// FBstfl: Number of fractional bits in input mantissa, i.e. number of bits in
// significand field of ac_std_float datatype.
template <bool use_pwl, unsigned M, int FBstfl, int outWstfl, int outEstfl>
int test_driver_stfloat(
double &cumulative_max_error,
const double allowed_error
)
{
bool passed = true;
enum {
E_val_1 = ac::nbits<FBstfl>::val,
E_val_2 = ac::nbits<AC_MAX(ac::nbits<M - 1>::val - 1, 1)>::val,
Estfl = AC_MAX(int(E_val_1), int(E_val_2)) + 1,
Wstfl = 1 + Estfl + FBstfl,
};
typedef ac_std_float<Wstfl, Estfl> T_in;
typedef ac_std_float<outWstfl, outEstfl> T_out;
T_in A_C_array[M][M];
T_out L_C_array[M][M];
ac_matrix<T_in, M, M> A_ac_matrix;
ac_matrix<T_out, M, M> L_ac_matrix;
if (use_pwl) {
cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions.
} else {
cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions.
}
cout.width(2);
cout << left << M;
cout << ", INPUT: ";
cout.width(37);
cout << left << type_string_st<T_in>::type_string();
cout << "OUTPUT: ";
cout.width(37);
cout << left << type_string_st<T_out>::type_string();
cout << "RESULT: ";
double L_tb[M][M];
// The gen_matrix function takes an MxN matrix, and multiplies it by its
// transpose to obtain a positive definite input matrix
gen_matrix(A_C_array);
copy_to_ac_matrix(A_C_array, A_ac_matrix);
test_ac_chol_d_stfloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix);
T_out L_ac_matrix_converted[M][M];
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
// Get output of testbench function for cholesky decomposition.
chol_d_tb(A_C_array, L_tb);
#ifdef DEBUG
cout << "A_C_array = " << endl;
print_matrix(A_C_array);
cout << "L_C_array = " << endl;
print_matrix(L_C_array);
cout << "L_tb = " << endl;
print_matrix(L_tb);
cout << "A_ac_matrix = " << endl;
cout << A_ac_matrix << endl;
cout << "L_ac_matrix = " << endl;
cout << L_ac_matrix << endl;
#endif
// Compare matrices and get the max error
double max_error = compare_matrices(L_C_array, L_tb, allowed_error);
double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error);
// Put max overall error in a separate variable.
double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix;
passed = (max_error_overall < allowed_error);
// Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix
// with all the values set to unity.
A_ac_matrix = T_in::one();
// Copy over a non-positive definite matrix to the standard C array inputs.
copy_to_array_2D(A_ac_matrix, A_C_array);
test_ac_chol_d_stfloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix);
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
// Make sure that a zero matrix is returned at the output.
passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(L_ac_matrix_converted);
if (passed) { printf("PASSED , max err (%f)\n", max_error_overall); }
else { printf("FAILED , max err (%f)\n", max_error_overall); } // LCOV_EXCL_LINE
if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; }
return 0;
}
// ==============================================================================
// Function: test_driver_ifloat()
// Description: test_driver function for ac_ieee_float inputs and outputs.
template <bool use_pwl, unsigned M, ac_ieee_float_format in_format, ac_ieee_float_format out_format>
int test_driver_ifloat(
double &cumulative_max_error,
const double allowed_error
)
{
bool passed = true;
typedef ac_ieee_float<in_format> T_in;
typedef ac_ieee_float<out_format> T_out;
T_in A_C_array[M][M];
T_out L_C_array[M][M];
ac_matrix<T_in, M, M> A_ac_matrix;
ac_matrix<T_out, M, M> L_ac_matrix;
if (use_pwl) {
cout << "TEST: ac_chol_d() with PWL fns. M = "; // ac_chol_d uses PWL functions.
} else {
cout << "TEST: ac_chol_d() with acc fns. M = "; // ac_chol_d uses accurate functions.
}
cout.width(2);
cout << left << M;
cout << ", INPUT: ";
cout.width(37);
cout << left << type_string_st<T_in>::type_string();
cout << "OUTPUT: ";
cout.width(37);
cout << left << type_string_st<T_out>::type_string();
cout << "RESULT: ";
double L_tb[M][M];
// The gen_matrix function takes an MxN matrix, and multiplies it by its
// transpose to obtain a positive definite input matrix
gen_matrix(A_C_array);
copy_to_ac_matrix(A_C_array, A_ac_matrix);
test_ac_chol_d_ifloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix);
T_out L_ac_matrix_converted[M][M];
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
// Get output of testbench function for cholesky decomposition.
chol_d_tb(A_C_array, L_tb);
#ifdef DEBUG
cout << "A_C_array = " << endl;
print_matrix(A_C_array);
cout << "L_C_array = " << endl;
print_matrix(L_C_array);
cout << "L_tb = " << endl;
print_matrix(L_tb);
cout << "A_ac_matrix = " << endl;
cout << A_ac_matrix << endl;
cout << "L_ac_matrix = " << endl;
cout << L_ac_matrix << endl;
#endif
// Compare matrices and get the max error
double max_error = compare_matrices(L_C_array, L_tb, allowed_error);
double max_error_ac_matrix = compare_matrices(L_ac_matrix_converted, L_tb, allowed_error);
// Put max overall error in a separate variable.
double max_error_overall = max_error > max_error_ac_matrix ? max_error : max_error_ac_matrix;
passed = (max_error_overall < allowed_error);
// Also, we must make sure that the output on passing a non-positive definite matrix is a zero matrix. To do this, we pass a matrix
// with all the values set to unity.
A_ac_matrix = T_in::one();
// Copy over a non-positive definite matrix to the standard C array inputs.
copy_to_array_2D(A_ac_matrix, A_C_array);
test_ac_chol_d_ifloat<use_pwl>(A_C_array, L_C_array, A_ac_matrix, L_ac_matrix);
copy_to_array_2D(L_ac_matrix, L_ac_matrix_converted);
// Make sure that a zero matrix is returned at the output.
passed = passed && check_if_zero_matrix(L_C_array) && check_if_zero_matrix(L_ac_matrix_converted);
if (passed) { printf("PASSED , max err (%f)\n", max_error_overall); }
else { printf("FAILED , max err (%f)\n", max_error_overall); } // LCOV_EXCL_LINE
if (max_error_overall > cumulative_max_error) { cumulative_max_error = max_error_overall; }
return 0;
}
int main(int argc, char *argv[])
{
double max_error_pwl = 0, cmplx_max_error_pwl = 0, max_error_acc = 0, cmplx_max_error_acc = 0;
double allowed_error_pwl = 4;
double allowed_error_acc = 0.005;
cout << "=============================================================================" << endl;
cout << "Testing function: ac_chol_d(), for scalar and complex datatypes - allowed_error_pwl = " << allowed_error_pwl << ", allowed_error_acc = " << allowed_error_acc << endl;
// template <bool use_pwl, unsigned M, int FBfi, int outWfi, int outIfi, bool outSfi>
test_driver_fixed< true, 7, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed< true, 8, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed< true, 10, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed< true, 11, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed< true, 12, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed< true, 13, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed< true, 14, 16, 64, 32, true>(max_error_pwl, cmplx_max_error_pwl, allowed_error_pwl);
test_driver_fixed<false, 7, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 8, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 9, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 10, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 11, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 12, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 13, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
test_driver_fixed<false, 14, 16, 64, 32, true>(max_error_acc, cmplx_max_error_acc, allowed_error_acc);
// template <bool use_pwl, unsigned M, int FBfl, int outWfl, int outIfl, int outEfl>
test_driver_float< true, 7, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float< true, 8, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float< true, 10, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float< true, 11, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float< true, 12, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float< true, 13, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float< true, 14, 16, 32, 2, 10>(max_error_pwl, allowed_error_pwl);
test_driver_float<false, 7, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 8, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 9, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 10, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 11, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 12, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 13, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
test_driver_float<false, 14, 16, 32, 2, 10>(max_error_acc, allowed_error_acc);
// template <bool use_pwl, unsigned M, int FBstfl, int outWstfl, int outEstfl>
test_driver_stfloat< true, 7, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat< true, 8, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat< true, 10, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat< true, 11, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat< true, 12, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat< true, 13, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat< true, 14, 23, 64, 11>(max_error_pwl, allowed_error_pwl);
test_driver_stfloat<false, 7, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 8, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 9, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 10, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 11, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 12, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 13, 23, 64, 11>(max_error_acc, allowed_error_acc);
test_driver_stfloat<false, 14, 23, 64, 11>(max_error_acc, allowed_error_acc);
// template <bool use_pwl, unsigned M, ac_ieee_float_format in_format, ac_ieee_float_format out_format>
test_driver_ifloat< true, 7, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat< true, 8, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat< true, 10, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat< true, 11, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat< true, 12, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat< true, 13, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat< true, 14, binary32, binary64>(max_error_pwl, allowed_error_pwl);
test_driver_ifloat<false, 7, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 8, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 9, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 10, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 11, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 12, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 13, binary32, binary64>(max_error_acc, allowed_error_acc);
test_driver_ifloat<false, 14, binary32, binary64>(max_error_acc, allowed_error_acc);
cout << "=============================================================================" << endl;
cout << " Testbench finished. Maximum errors observed across all data type / bit-width variations:" << endl;
cout << " max_error_pwl = " << max_error_pwl << endl;
cout << " cmplx_max_error_pwl = " << cmplx_max_error_pwl << endl;
cout << " max_error_acc = " << max_error_acc << endl;
cout << " cmplx_max_error_acc = " << cmplx_max_error_acc << endl;
// If error limits on any tested datatype have been crossed, the test has failed
bool test_fail = (max_error_pwl > allowed_error_pwl) || (cmplx_max_error_pwl > allowed_error_pwl) || (max_error_acc > allowed_error_acc) || (cmplx_max_error_acc > allowed_error_acc);
// Notify the user whether or not the test was a failure.
if (test_fail) {
cout << " ac_chol_d - FAILED - Error tolerance(s) exceeded" << endl; // LCOV_EXCL_LINE
cout << "=============================================================================" << endl; // LCOV_EXCL_LINE
return -1; // LCOV_EXCL_LINE
} else {
cout << " ac_chol_d - PASSED" << endl;
cout << "=============================================================================" << endl;
}
return 0;
}
| 38.251366
| 194
| 0.645357
|
dgburnette
|
ad356c7c8976183d272c49e659ce12c10a3104b4
| 1,019
|
cpp
|
C++
|
LeetCode/cpp/987.cpp
|
ZintrulCre/LeetCode_Archiver
|
de23e16ead29336b5ee7aa1898a392a5d6463d27
|
[
"MIT"
] | 279
|
2019-02-19T16:00:32.000Z
|
2022-03-23T12:16:30.000Z
|
LeetCode/cpp/987.cpp
|
ZintrulCre/LeetCode_Archiver
|
de23e16ead29336b5ee7aa1898a392a5d6463d27
|
[
"MIT"
] | 2
|
2019-03-31T08:03:06.000Z
|
2021-03-07T04:54:32.000Z
|
LeetCode/cpp/987.cpp
|
ZintrulCre/LeetCode_Crawler
|
de23e16ead29336b5ee7aa1898a392a5d6463d27
|
[
"MIT"
] | 12
|
2019-01-29T11:45:32.000Z
|
2019-02-04T16:31:46.000Z
|
class Solution {
public:
unordered_map<int, unordered_map<int, set<int>>> nums;
vector<vector<int>> verticalTraversal(TreeNode *root) {
if (!root)
return {};
nums.clear();
Traverse(root, 0, 0);
vector<vector<int>> ret;
for (int i = -1000; i <= 1000; ++i) {
if (nums.find(i) != nums.end()) {
ret.push_back(vector<int>());
for (int j = 0; j <= 1000; ++j) {
if (nums[i].find(j) != nums[i].end())
ret.back().insert(end(ret.back()), begin(nums[i][j]), end(nums[i][j]));
}
}
}
return ret;
}
void Traverse(TreeNode *node, int i, int j) {
if (nums.find(i) == nums.end())
nums[i] = unordered_map<int, set<int>>();
nums[i][j].insert(node->val);
if (node->left)
Traverse(node->left, i - 1, j + 1);
if (node->right)
Traverse(node->right, i + 1, j + 1);
}
};
| 31.84375
| 95
| 0.44946
|
ZintrulCre
|
ad37155c15863c09f98819ffa51767eeb2cdb9b1
| 1,959
|
cpp
|
C++
|
topic_wise/graphs/courseSchedule.cpp
|
archit-1997/LeetCode
|
7c0f74da0836d3b0855f09bae8960f81a384f3f3
|
[
"MIT"
] | 1
|
2021-01-27T16:37:36.000Z
|
2021-01-27T16:37:36.000Z
|
topic_wise/graphs/courseSchedule.cpp
|
archit-1997/LeetCode
|
7c0f74da0836d3b0855f09bae8960f81a384f3f3
|
[
"MIT"
] | null | null | null |
topic_wise/graphs/courseSchedule.cpp
|
archit-1997/LeetCode
|
7c0f74da0836d3b0855f09bae8960f81a384f3f3
|
[
"MIT"
] | null | null | null |
/**
* @author : archit
* @GitHub : archit-1997
* @Email : architsingh456@gmail.com
* @file : courseSchedule.cpp
* @created : Sunday Aug 01, 2021 17:31:53 IST
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> buildGraph(int numCourses,vector<vector<int>> &prerequisites){
vector<vector<int>> graph(numCourses);
for(int i=0;i<prerequisites.size();i++){
int a=prerequisites[i][0],b=prerequisites[i][1];
//complete course b before a
graph[b].push_back(a);
}
return graph;
}
bool detectCycle(vector<vector<int>> &graph,int numCourses,vector<int> &vis,vector<int> &rec,int x){
rec[x]=1;
vis[x]=1;
for(int i=0;i<graph[x].size();i++){
int cur=graph[x][i];
//already present in the recursion stack
if(rec[cur])
return true;
//if not visited, but there is a cylce later on
if(!vis[i] && detectCycle(graph,numCourses,vis,rec,cur))
return true;
}
//no cycles for this node
rec[x]=0;
return false;
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
//if there is only one course, then you can just say finished
if(numCourses==1)
return true;
//build the graph
vector<vector<int>> graph=buildGraph(numCourses,prerequisites);
vector<int> vis(numCourses,0);
//vector for recursion stack
vector<int> rec(numCourses,0);
//check for the existence of cycle in the graph
//need to apply dfs from each node
for(int i=0;i<numCourses;i++){
if(detectCycle(graph,numCourses,vis,rec,i))
return false;
}
//no cycle in the graph, then we can complete all the courses
return true;
}
};
| 29.681818
| 104
| 0.562532
|
archit-1997
|
ad3d2261d56ac74aa29612af22b45007cfa4c7ad
| 1,462
|
cpp
|
C++
|
MAze/Aliados.cpp
|
IzaguirreYamile/MAze
|
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
|
[
"MIT"
] | 1
|
2021-09-02T21:19:19.000Z
|
2021-09-02T21:19:19.000Z
|
MAze/Aliados.cpp
|
IzaguirreYamile/MAze
|
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
|
[
"MIT"
] | null | null | null |
MAze/Aliados.cpp
|
IzaguirreYamile/MAze
|
d6e0f0a0ef1231dd53c32514c5b7f940ff801890
|
[
"MIT"
] | null | null | null |
#include "Aliados.h"
Aliados::Aliados() {}
Aliados::Aliados(int px, int py, Bitmap^ aliados)
{
x = px;
y = py;
this->ancho = aliados->Width / 13;
this->alto = aliados->Height / 21;
dx = 4;
dy = 4;
direccion = Caminar2Derecha;
}
void Aliados::Mover(Graphics^ g)
{
switch(direccion)
{
case Caminar2Abajo: fila = 2;
break;
case Caminar2Izquierda: fila = 3;
break;
case Caminar2Derecha: fila = 1;
break;
case Caminar2Arriba: fila = 0;
break;
}
x += dx;
y += dy;
}
void Aliados::MoveType1(Graphics^ g)
{
if (x + dx < g->VisibleClipBounds.Left) {
direccion = Caminar2Derecha;
dx *= -1;
}
if (x + dx + ancho > g->VisibleClipBounds.Right)
{
direccion = Caminar2Izquierda;
dx = dx * -1;
}
if (y + dy < g->VisibleClipBounds.Top) {
dy *= -1;
}
if (y + dy + alto > g->VisibleClipBounds.Bottom) {
dy *= -1;
}
x += dx;
y += dy;
}
void Aliados::Dibujar(Graphics^ g, Bitmap^ aliados)
{
Rectangle corte = Rectangle(IDx * ancho, direccion * alto, ancho, alto);
Rectangle zoom = Rectangle(x, y, ancho, alto);
g->DrawImage(aliados, zoom, corte, GraphicsUnit::Pixel);
if ((direccion >= Caminar2Arriba && direccion <= Caminar2Derecha) && dx != 0 || dy != 0)
IDx = (IDx + 1) % 8;
else if (direccion == Morir_enemigo)
IDx = (IDx + 1) % 6;
}
int Aliados::Obtener_Ancho() { return ancho; }
int Aliados::Obtener_Alto() { return alto; }
void Aliados::Cambiar_direccion(SpriteEnemigo n) { direccion = n; }
Aliados::~Aliados() {}
| 21.5
| 89
| 0.634063
|
IzaguirreYamile
|
ad459393c1c02e07c2383cbf3d6be37ea27cb740
| 4,150
|
cpp
|
C++
|
src/AutonomousSystem/AutonomousManager.cpp
|
frc2081/2018-RobotCode
|
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
|
[
"MIT"
] | null | null | null |
src/AutonomousSystem/AutonomousManager.cpp
|
frc2081/2018-RobotCode
|
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
|
[
"MIT"
] | 5
|
2018-01-18T03:25:07.000Z
|
2018-03-16T13:27:53.000Z
|
src/AutonomousSystem/AutonomousManager.cpp
|
frc2081/2018-RobotCode
|
6eec5af9b42df4bbd9f43ae6bd0cedc8fa7e0019
|
[
"MIT"
] | null | null | null |
/*
* AutonomousManager.cpp
*
* Created on: Jan 17, 2018
* Author: Matthew
*/
#include "AutonomousManager.h"
namespace Autonomous
{
AutonomousManager::AutonomousManager(IO *io, RobotCommands *commands, CubeManager *cube) {
_io = io;
_commands = commands;
_actionselector = 0;
_stationselector = 0;
_waitleft = false;
_waitright = true;
_buildcommands = true;
_fielddata = "";
_polltimer = 100;
_cube = cube;
_gyro = gyroManager::Get();
//_action = NONE;
//_ourswitch = '';
//_scale = '';
//_station = NONE;
_team = NONE;
SmartDashboard::PutNumber("Auto Mode", 0);
SmartDashboard::PutNumber("Auto Station", 0);
SmartDashboard::PutNumber("Wait Side", 0);
}
void AutonomousManager::AutoInit() {
printf("Starting auto\n");
_gyro->start();
_fielddata = DriverStation::GetInstance().GetGameSpecificMessage();
if (DriverStation::GetInstance().GetAlliance() == DriverStation::kRed) _team = RED;
else if (DriverStation::GetInstance().GetAlliance() == DriverStation::kBlue) _team = BLUE;
else _team = NONE;
_actionselector = SmartDashboard::GetNumber("Auto Mode", 0);
_stationselector = SmartDashboard::GetNumber("Auto Station", 0);
_waitselector = SmartDashboard::GetNumber("Wait Side", 0);
if (_actionselector == 0) _action = SWITCH_SHOT;
else if (_actionselector == 1) _action = SCALE_SHOT;
else if (_actionselector == 2) _action = DRIVE_FORWARD;
else _action = NO_AUTO;
if (_stationselector == 1) _station = ONE;
else if (_stationselector == 2) _station = TWO;
else if (_stationselector == 3) _station = THREE;
else _station = UNKNOWN;
if (_waitselector == 0) {
_waitleft = true;
_waitright = false;
}
else if (_waitselector == 1) {
_waitright = true;
_waitleft = false;
} else {
_waitleft = false;
_waitright = false;
}
//if (_waitselector->getWaitSide()) {
// _waitleft = true;
//} else _waitright = true;
//_action = SWITCH_SHOT;
//Building commands in periodic to make sure the most up to date values are obtained
//for more information, visit http://wpilib.screenstepslive.com/s/currentCS/m/getting_started/l/826278-2018-game-data-details
}
void AutonomousManager::AutoPeriodic() {
printf("Entering Autoperiodic\n\n");
//if (_cube->armHome == false) _io->shooteranglmot->Set(ControlMode::Position, 50000);
if(_buildcommands) {
_fielddata = DriverStation::GetInstance().GetGameSpecificMessage();
printf("Checking for data\n");
if (_fielddata.length() > 0) {
if (_fielddata.length() >= 2) {
_ourswitch = _fielddata.at(0);
_scale = _fielddata.at(1);
}
printf("Building commands\n");
_autocommands = new CommandManager(_team, _station, _action, _ourswitch, _scale, _waitleft, _waitright);
_buildcommands = false;
}
}
_cominput.LFWhlDrvEnc = _io->encdrvlf->GetDistance() / 100;
_cominput.RFWhlDrvEnc = _io->encdrvrf->GetDistance() / 100;
_cominput.LBWhlDrvEnc = _io->encdrvlb->GetDistance() / 100;
_cominput.RBWhlDrvEnc = _io->encdrvrb->GetDistance() / 100;
_cominput.LFWhlTurnEnc = _io->steerencdrvlf->Get();
_cominput.RFWhlTurnEnc = _io->steerencdrvrf->Get();
_cominput.LBWhlTurnEnc = _io->steerencdrvlb->Get();
_cominput.RBWhlTurnEnc = _io->steerencdrvrb->Get();
_cominput.currentGyroReading = _gyro->getLastValue();
//printf("Gyro value %.2f", _gyro->getLastValue());
_comoutput = _autocommands->tick(_cominput);
//printf("Ticked\n");
//printf("Magnitude: %.2f Angle: %.2f Rotation: %.2\n", _commands->drvmag, _commands->drvang, _commands->drvrot);
//printf("LFDrive: %.2f RFDrive: %.2f LBDrive: %.2f, RBDrive: %.2f\n", _io->drvlfmot->Get(), _io->drvrfmot->Get(), _io->drvlbmot->Get(), _io->drvrbmot->Get());
_commands->drvang = _comoutput.autoAng;
_commands->drvrot = _comoutput.autoRot;
_commands->drvmag = _comoutput.autoSpeed;
_commands->cmdscaleshot = _comoutput.takeScaleShot;
_commands->cmdswitchshot = _comoutput.takeSwitchShot;
_commands->cmdarmtocarry = _comoutput.takeArmToCarry;
}
}
| 35.470085
| 164
| 0.673976
|
frc2081
|
ad493ad1a9322a3fd93a8e4a7bbc106271cdba67
| 381
|
hpp
|
C++
|
Source/Game/Match3Cell.fwd.hpp
|
gabr1e11/cornerstone
|
bc696e22af350b867219ef3ac99840b3e8a3f20a
|
[
"MIT"
] | null | null | null |
Source/Game/Match3Cell.fwd.hpp
|
gabr1e11/cornerstone
|
bc696e22af350b867219ef3ac99840b3e8a3f20a
|
[
"MIT"
] | null | null | null |
Source/Game/Match3Cell.fwd.hpp
|
gabr1e11/cornerstone
|
bc696e22af350b867219ef3ac99840b3e8a3f20a
|
[
"MIT"
] | null | null | null |
//
// Match3Cell.fwd.hpp
//
// @author Roberto Cano
//
#pragma once
#include <memory>
#include <glm/glm.hpp>
namespace Match3
{
namespace Game
{
class Cell;
}
namespace Types
{
namespace Cell
{
using PtrType = std::shared_ptr<Match3::Game::Cell>;
using Position = glm::ivec2;
enum class State : int
{
Normal,
Active,
Disabled
};
};
}
}
| 11.205882
| 55
| 0.611549
|
gabr1e11
|
ad49669b2083f2df29e59344d6dbd6bc414b0947
| 4,025
|
cpp
|
C++
|
src/clock.cpp
|
Cyberax/lstructural
|
3496e46fe7e671575ea9eaf9ce6063acad8d9006
|
[
"Apache-2.0"
] | null | null | null |
src/clock.cpp
|
Cyberax/lstructural
|
3496e46fe7e671575ea9eaf9ce6063acad8d9006
|
[
"Apache-2.0"
] | null | null | null |
src/clock.cpp
|
Cyberax/lstructural
|
3496e46fe7e671575ea9eaf9ce6063acad8d9006
|
[
"Apache-2.0"
] | null | null | null |
/*
MIT License
Copyright (c) 2013-2017 Evgeny Safronov <division494@gmail.com>
Copyright (c) 2013-2017 Other contributors as noted in the AUTHORS file.
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 <cstdio>
#include "clock.h"
#include "log_sink.h"
using namespace llog;
const llog::clock_t the_clock;
const llog::clock_t *llog::system_clock = &the_clock;
static auto fast_gmtime(time_t t, struct tm* tp) noexcept -> struct tm* {
int yday;
uintptr_t n, sec, min, hour, mday, mon, year, wday, days, leap;
// The calculation is valid for positive time_t only.
n = t;
days = n / 86400;
// Jaunary 1, 1970 was Thursday
wday = (4 + days) % 7;
n %= 86400;
hour = n / 3600;
n %= 3600;
min = n / 60;
sec = n % 60;
// The algorithm based on Gauss's formula, see src/http/ngx_http_parse_time.c.
// Days since March 1, 1 BC.
days = days - (31 + 28) + 719527;
// The "days" should be adjusted to 1 only, however, some March 1st's go to previous year, so
// we adjust them to 2. This causes also shift of the last Feburary days to next year, but we
// catch the case when "yday" becomes negative.
year = (days + 2) * 400 / (365 * 400 + 100 - 4 + 1);
yday = static_cast<int>(days - (365 * year + year / 4 - year / 100 + year / 400));
leap = (year % 4 == 0) && (year % 100 || (year % 400 == 0));
if (yday < 0) {
yday = static_cast<int>(365 + leap + static_cast<unsigned long>(yday));
year--;
}
// The empirical formula that maps "yday" to month. There are at least 10 variants, some of
// them are:
// mon = (yday + 31) * 15 / 459
// mon = (yday + 31) * 17 / 520
// mon = (yday + 31) * 20 / 612
mon = static_cast<uintptr_t>((yday + 31) * 10 / 306);
// The Gauss's formula that evaluates days before the month.
mday = static_cast<unsigned long>(yday)- (367 * mon / 12 - 30) + 1;
if (yday >= 306) {
year++;
mon -= 10;
yday -= 306;
} else {
mon += 2;
yday += 31 + 28 + static_cast<int>(leap);
}
tp->tm_sec = static_cast<int>(sec);
tp->tm_min = static_cast<int>(min);
tp->tm_hour = static_cast<int>(hour);
tp->tm_mday = static_cast<int>(mday);
tp->tm_mon = static_cast<int>(mon - 1);
tp->tm_year = static_cast<int>(year - 1900);
tp->tm_yday = yday;
tp->tm_wday = static_cast<int>(wday);
tp->tm_isdst = 0;
return tp;
}
class tzinit_t {
public:
tzinit_t() { tzset(); }
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
static const tzinit_t tz;
#pragma clang diagnostic pop
static auto localtime(time_t t, struct tm* tp) noexcept -> struct tm* {
time_t time = t - timezone;
gmtime_r(&time, tp);
tp->tm_gmtoff = timezone;
tp->tm_zone = *tzname;
return tp;
}
void llog::print_timestamp(const timespec &t, sink_t &sink) {
char buff[100];
tm gmt = {};
fast_gmtime(time_t(t.tv_sec), &gmt);
// size_t ln = snprintf(buff, sizeof(buff),"%4d-%2d-%2dT%2d:%2d:%2d.%ldZ",
// gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec,
// t.tv_nsec/1000);
// sink.write(buff, ln);
}
| 30.492424
| 95
| 0.680745
|
Cyberax
|
ad4b484f12f66e02542b58aa48c332f707c4ef57
| 3,258
|
cpp
|
C++
|
src/math/optimizer_math/sgd_momentum.cpp
|
Boxun-coder/magmadnn
|
76d23ff8ea9c63839da6965b9c5ab4aad07f9250
|
[
"MIT"
] | 2
|
2020-07-20T08:39:47.000Z
|
2020-07-20T08:40:06.000Z
|
src/math/optimizer_math/sgd_momentum.cpp
|
Boxun-coder/magmadnn
|
76d23ff8ea9c63839da6965b9c5ab4aad07f9250
|
[
"MIT"
] | null | null | null |
src/math/optimizer_math/sgd_momentum.cpp
|
Boxun-coder/magmadnn
|
76d23ff8ea9c63839da6965b9c5ab4aad07f9250
|
[
"MIT"
] | null | null | null |
/**
* @file sgd_momentum.cpp
* @author Sedrick Keh
* @version 1.0
* @date 2019-07-25
*
* @copyright Copyright (c) 2019
*/
#include "math/optimizer_math/sgd_momentum.h"
#include <cassert>
#include <vector>
#include "magmadnn/config.h"
namespace magmadnn {
namespace math {
template <typename T>
void sgd_momentum_cpu(
T learning_rate, T momentum, Tensor<T> *prev, Tensor<T> *grad,
std::vector<int> *idxs, Tensor<T> *out) {
assert(prev->get_size() == grad->get_size());
assert(grad->get_size() == out->get_size());
T *prev_ptr = prev->get_ptr();
T *grad_ptr = grad->get_ptr();
T *out_ptr = out->get_ptr();
// unsigned int size = out->get_size();
unsigned int sample_size = idxs->size();
for (unsigned int i = 0; i < sample_size; i++) {
int idx = (*idxs)[i];
prev_ptr[idx] = momentum * prev_ptr[idx] + (1 - momentum) * grad_ptr[idx];
out_ptr[idx] = out_ptr[idx] - learning_rate * prev_ptr[idx];
}
}
template void sgd_momentum_cpu<float>(
float learning_rate, float momentum, Tensor<float> *prev, Tensor<float> *grad,
std::vector<int> *idxs, Tensor<float> *out);
template void sgd_momentum_cpu<double>(
double learning_rate, double momentum, Tensor<double> *prev, Tensor<double> *grad,
std::vector<int> *idxs, Tensor<double> *out);
template <typename T>
void sgd_momentum_cpu(
T learning_rate, T momentum, Tensor<T> *prev, Tensor<T> *grad,
Tensor<T> *out) {
assert(prev->get_size() == grad->get_size());
assert(grad->get_size() == out->get_size());
T *prev_ptr = prev->get_ptr();
T *grad_ptr = grad->get_ptr();
T *out_ptr = out->get_ptr();
unsigned int size = out->get_size();
for (unsigned int i = 0; i < size; i++) {
prev_ptr[i] = momentum * prev_ptr[i] + (1 - momentum) * grad_ptr[i];
out_ptr[i] = out_ptr[i] - learning_rate * prev_ptr[i];
}
}
template void sgd_momentum_cpu(
int learning_rate, int momentum, Tensor<int> *prev, Tensor<int> *grad, Tensor<int> *out);
template void sgd_momentum_cpu(
float learning_rate, float momentum, Tensor<float> *prev, Tensor<float> *grad, Tensor<float> *out);
template void sgd_momentum_cpu(
double learning_rate, double momentum, Tensor<double> *prev, Tensor<double> *grad, Tensor<double> *out);
template <typename T>
void sgd_momentum(T learning_rate, T momentum, Tensor<T> *prev, Tensor<T> *grad, Tensor<T> *out) {
assert(prev->get_size() == grad->get_size());
assert(grad->get_size() == out->get_size());
if (out->get_memory_type() == HOST) {
sgd_momentum_cpu(learning_rate, momentum, prev, grad, out);
}
#if defined(MAGMADNN_HAVE_CUDA)
else {
sgd_momentum_device(learning_rate, momentum, prev, grad, out);
}
#endif
}
template void sgd_momentum(int learning_rate, int momentum, Tensor<int> *prev, Tensor<int> *grad, Tensor<int> *out);
template void sgd_momentum(float learning_rate, float momentum, Tensor<float> *prev, Tensor<float> *grad,
Tensor<float> *out);
template void sgd_momentum(double learning_rate, double momentum, Tensor<double> *prev, Tensor<double> *grad,
Tensor<double> *out);
} // namespace math
} // namespace magmadnn
| 34.659574
| 116
| 0.655617
|
Boxun-coder
|
ad4b5084a5651fac8d7da4f62a637f9a26abb93f
| 93
|
cpp
|
C++
|
IA/StupidAgent.cpp
|
GP-S/HOTS
|
85903015033184694e3b2b70af401a0ea5de11b7
|
[
"Unlicense",
"MIT"
] | 1
|
2021-05-30T02:13:37.000Z
|
2021-05-30T02:13:37.000Z
|
IA/StupidAgent.cpp
|
GP-S/HOTS
|
85903015033184694e3b2b70af401a0ea5de11b7
|
[
"Unlicense",
"MIT"
] | null | null | null |
IA/StupidAgent.cpp
|
GP-S/HOTS
|
85903015033184694e3b2b70af401a0ea5de11b7
|
[
"Unlicense",
"MIT"
] | null | null | null |
#include "StupidAgent.h"
StupidAgent::StupidAgent()
{
}
StupidAgent::~StupidAgent()
{
}
| 7.153846
| 27
| 0.677419
|
GP-S
|
ad4bff05071bbbce5bf15953b5213fc6cd5c2265
| 1,128
|
cpp
|
C++
|
src/tools/strong_cc_main.cpp
|
FantaApps/zgraph
|
9e25c6d52f8f730b9f65bbd92c3dea7aa20b7688
|
[
"MIT"
] | 1
|
2020-11-30T04:26:41.000Z
|
2020-11-30T04:26:41.000Z
|
src/tools/strong_cc_main.cpp
|
FantaApps/zgraph
|
9e25c6d52f8f730b9f65bbd92c3dea7aa20b7688
|
[
"MIT"
] | 9
|
2019-11-04T06:31:02.000Z
|
2019-11-28T16:19:23.000Z
|
src/tools/strong_cc_main.cpp
|
FantaApps/zgraph
|
9e25c6d52f8f730b9f65bbd92c3dea7aa20b7688
|
[
"MIT"
] | null | null | null |
#include "../lib/graph.h"
#include "../lib/graph_algo.h"
#include <omp.h>
#include <sys/resource.h>
#include <map>
#include <vector>
using namespace std;
using namespace apsara::odps::graph::query;
int main(int argc, char* argv[])
{
const rlim_t kStackSize = 2 * 1024 * 1024 * 1024; // min stack size = 16 MB
struct rlimit rl;
int result;
result = getrlimit(RLIMIT_STACK, &rl);
if (result == 0)
{
cout<<"Adjusting stack size......" <<endl;
if (rl.rlim_cur < kStackSize)
{
rl.rlim_cur = kStackSize;
result = setrlimit(RLIMIT_STACK, &rl);
if (result != 0)
{
fprintf(stderr, "setrlimit returned result = %d\n", result);
}
}
}
string graphFolder = "/apsarapangu/disk8/twitter-2010/bfs_query/test/CSR/uint32/";
shared_ptr<Graph<uint32_t>> g =
shared_ptr<Graph<uint32_t>>(new GraphCSR<uint32_t>());
g->Init(graphFolder);
GraphAlgo<uint32_t> algo(g);
algo.SetNumThreads(16);
map<uint32_t, vector<uint32_t>> sCC;
algo.StronglyCC(g, sCC);
return 0;
}
| 25.066667
| 86
| 0.590426
|
FantaApps
|
ad4de507bf1b2599fc4636a4d364f560474ca8d2
| 14,333
|
cpp
|
C++
|
external/soci/postgresql/statement.cpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | 5
|
2015-09-15T16:24:14.000Z
|
2021-08-12T11:05:55.000Z
|
external/soci/postgresql/statement.cpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | null | null | null |
external/soci/postgresql/statement.cpp
|
saga-project/saga-cpp
|
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
|
[
"BSL-1.0"
] | 3
|
2016-11-17T04:38:38.000Z
|
2021-04-10T17:23:52.000Z
|
//
// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#define SOCI_POSTGRESQL_SOURCE
#include "soci-postgresql.h"
#include <soci.h>
#include <libpq/libpq-fs.h> // libpq
#include <cctype>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <sstream>
#ifdef SOCI_PGSQL_NOPARAMS
#define SOCI_PGSQL_NOBINDBYNAME
#endif // SOCI_PGSQL_NOPARAMS
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
using namespace SOCI;
using namespace SOCI::details;
PostgreSQLStatementBackEnd::PostgreSQLStatementBackEnd(
PostgreSQLSessionBackEnd &session)
: session_(session), result_(NULL), justDescribed_(false),
hasIntoElements_(false), hasVectorIntoElements_(false),
hasUseElements_(false), hasVectorUseElements_(false)
{
}
void PostgreSQLStatementBackEnd::alloc()
{
// nothing to do here
}
void PostgreSQLStatementBackEnd::cleanUp()
{
if (result_ != NULL)
{
PQclear(result_);
result_ = NULL;
}
}
void PostgreSQLStatementBackEnd::prepare(std::string const &query,
eStatementType eType)
{
#ifdef SOCI_PGSQL_NOBINDBYNAME
query_ = query;
#else
// rewrite the query by transforming all named parameters into
// the PostgreSQL numbers ones (:abc -> $1, etc.)
enum { eNormal, eInQuotes, eInName } state = eNormal;
std::string name;
int position = 1;
for (std::string::const_iterator it = query.begin(), end = query.end();
it != end; ++it)
{
switch (state)
{
case eNormal:
if (*it == '\'')
{
query_ += *it;
state = eInQuotes;
}
else if (*it == ':')
{
state = eInName;
}
else // regular character, stay in the same state
{
query_ += *it;
}
break;
case eInQuotes:
if (*it == '\'')
{
query_ += *it;
state = eNormal;
}
else // regular quoted character
{
query_ += *it;
}
break;
case eInName:
if (std::isalnum(*it) || *it == '_')
{
name += *it;
}
else // end of name
{
names_.push_back(name);
name.clear();
std::ostringstream ss;
ss << '$' << position++;
query_ += ss.str();
query_ += *it;
state = eNormal;
}
break;
}
}
if (state == eInName)
{
names_.push_back(name);
std::ostringstream ss;
ss << '$' << position++;
query_ += ss.str();
}
#endif // SOCI_PGSQL_NOBINDBYNAME
#ifndef SOCI_PGSQL_NOPREPARE
if (eType == eRepeatableQuery)
{
statementName_ = session_.getNextStatementName();
PGresult *res = PQprepare(session_.conn_, statementName_.c_str(),
query_.c_str(), static_cast<int>(names_.size()), NULL);
if (res == NULL)
{
throw SOCIError("Cannot prepare statement.");
}
ExecStatusType status = PQresultStatus(res);
if (status != PGRES_COMMAND_OK)
{
throw SOCIError(PQresultErrorMessage(res));
}
PQclear(res);
}
eType_ = eType;
#endif // SOCI_PGSQL_NOPREPARE
}
StatementBackEnd::execFetchResult
PostgreSQLStatementBackEnd::execute(int number)
{
// If the statement was "just described", then we know that
// it was actually executed with all the use elements
// already bound and pre-used. This means that the result of the
// query is already on the client side, so there is no need
// to re-execute it.
if (justDescribed_ == false)
{
// This object could have been already filled with data before.
cleanUp();
if (number > 1 && hasIntoElements_)
{
throw SOCIError(
"Bulk use with single into elements is not supported.");
}
// Since the bulk operations are not natively supported by PostgreSQL,
// we have to explicitly loop to achieve the bulk operations.
// On the other hand, looping is not needed if there are single
// use elements, even if there is a bulk fetch.
// We know that single use and bulk use elements in the same query are
// not supported anyway, so in the effect the 'number' parameter here
// specifies the size of vectors (into/use), but 'numberOfExecutions'
// specifies the number of loops that need to be performed.
int numberOfExecutions = 1;
if (number > 0)
{
numberOfExecutions = hasUseElements_ ? 1 : number;
}
if (!useByPosBuffers_.empty() || !useByNameBuffers_.empty())
{
if (!useByPosBuffers_.empty() && !useByNameBuffers_.empty())
{
throw SOCIError(
"Binding for use elements must be either by position "
"or by name.");
}
for (int i = 0; i != numberOfExecutions; ++i)
{
std::vector<char *> paramValues;
if (!useByPosBuffers_.empty())
{
// use elements bind by position
// the map of use buffers can be traversed
// in its natural order
for (UseByPosBuffersMap::iterator
it = useByPosBuffers_.begin(),
end = useByPosBuffers_.end();
it != end; ++it)
{
char **buffers = it->second;
paramValues.push_back(buffers[i]);
}
}
else
{
// use elements bind by name
for (std::vector<std::string>::iterator
it = names_.begin(), end = names_.end();
it != end; ++it)
{
UseByNameBuffersMap::iterator b
= useByNameBuffers_.find(*it);
if (b == useByNameBuffers_.end())
{
std::string msg(
"Missing use element for bind by name (");
msg += *it;
msg += ").";
throw SOCIError(msg);
}
char **buffers = b->second;
paramValues.push_back(buffers[i]);
}
}
#ifdef SOCI_PGSQL_NOPARAMS
throw SOCIError("Queries with parameters are not supported.");
#else
#ifdef SOCI_PGSQL_NOPREPARE
result_ = PQexecParams(session_.conn_, query_.c_str(),
static_cast<int>(paramValues.size()),
NULL, ¶mValues[0], NULL, NULL, 0);
#else
if (eType_ == eRepeatableQuery)
{
// this query was separately prepared
result_ = PQexecPrepared(session_.conn_,
statementName_.c_str(),
static_cast<int>(paramValues.size()),
¶mValues[0], NULL, NULL, 0);
}
else // eType_ == eOneTimeQuery
{
// this query was not separately prepared and should
// be executed as a one-time query
result_ = PQexecParams(session_.conn_, query_.c_str(),
static_cast<int>(paramValues.size()),
NULL, ¶mValues[0], NULL, NULL, 0);
}
#endif // SOCI_PGSQL_NOPREPARE
#endif // SOCI_PGSQL_NOPARAMS
if (numberOfExecutions > 1)
{
// there are only bulk use elements (no intos)
if (result_ == NULL)
{
throw SOCIError("Cannot execute query.");
}
ExecStatusType status = PQresultStatus(result_);
if (status != PGRES_COMMAND_OK)
{
throw SOCIError(PQresultErrorMessage(result_));
}
PQclear(result_);
}
}
if (numberOfExecutions > 1)
{
// it was a bulk operation
result_ = NULL;
return eNoData;
}
// otherwise (no bulk), follow the code below
}
else
{
// there are no use elements
// - execute the query without parameter information
#ifdef SOCI_PGSQL_NOPREPARE
result_ = PQexec(session_.conn_, query_.c_str());
#else
if (eType_ == eRepeatableQuery)
{
// this query was separately prepared
result_ = PQexecPrepared(session_.conn_,
statementName_.c_str(), 0, NULL, NULL, NULL, 0);
}
else // eType_ == eOneTimeQuery
{
result_ = PQexec(session_.conn_, query_.c_str());
}
#endif // SOCI_PGSQL_NOPREPARE
if (result_ == NULL)
{
throw SOCIError("Cannot execute query.");
}
}
}
else
{
// The optimization based on the existing results
// from the row description can be performed only once.
// If the same statement is re-executed,
// it will be *really* re-executed, without reusing existing data.
justDescribed_ = false;
}
ExecStatusType status = PQresultStatus(result_);
if (status == PGRES_TUPLES_OK)
{
currentRow_ = 0;
rowsToConsume_ = 0;
numberOfRows_ = PQntuples(result_);
if (numberOfRows_ == 0)
{
return eNoData;
}
else
{
if (number > 0)
{
// prepare for the subsequent data consumption
return fetch(number);
}
else
{
// execute(0) was meant to only perform the query
return eSuccess;
}
}
}
else if (status == PGRES_COMMAND_OK)
{
return eNoData;
}
else
{
throw SOCIError(PQresultErrorMessage(result_));
}
}
StatementBackEnd::execFetchResult
PostgreSQLStatementBackEnd::fetch(int number)
{
// Note: This function does not actually fetch anything from anywhere
// - the data was already retrieved from the server in the execute()
// function, and the actual consumption of this data will take place
// in the postFetch functions, called for each into element.
// Here, we only prepare for this to happen (to emulate "the Oracle way").
// forward the "cursor" from the last fetch
currentRow_ += rowsToConsume_;
if (currentRow_ >= numberOfRows_)
{
// all rows were already consumed
return eNoData;
}
else
{
if (currentRow_ + number > numberOfRows_)
{
rowsToConsume_ = numberOfRows_ - currentRow_;
// this simulates the behaviour of Oracle
// - when EOF is hit, we return eNoData even when there are
// actually some rows fetched
return eNoData;
}
else
{
rowsToConsume_ = number;
return eSuccess;
}
}
}
int PostgreSQLStatementBackEnd::getNumberOfRows()
{
return numberOfRows_ - currentRow_;
}
std::string PostgreSQLStatementBackEnd::rewriteForProcedureCall(
std::string const &query)
{
std::string newQuery("select ");
newQuery += query;
return newQuery;
}
int PostgreSQLStatementBackEnd::prepareForDescribe()
{
execute(1);
justDescribed_ = true;
int columns = PQnfields(result_);
return columns;
}
void PostgreSQLStatementBackEnd::describeColumn(int colNum, eDataType &type,
std::string &columnName)
{
// In PostgreSQL column numbers start from 0
int pos = colNum - 1;
unsigned long typeOid = PQftype(result_, pos);
switch (typeOid)
{
// Note: the following list of OIDs was taken from the pg_type table
// we do not claim that this list is exchaustive or even correct.
// from pg_type:
case 25: // text
case 1043: // varchar
case 2275: // cstring
case 18: // char
case 1042: // bpchar
type = eString;
break;
case 702: // abstime
case 703: // reltime
case 1082: // date
case 1083: // time
case 1114: // timestamp
case 1184: // timestamptz
case 1266: // timetz
type = eDate;
break;
case 700: // float4
case 701: // float8
case 1700: // numeric
type = eDouble;
break;
case 16: // bool
case 21: // int2
case 23: // int4
case 20: // int8
type = eInteger;
break;
case 26: // oid
type = eUnsignedLong;
break;
default:
throw SOCIError("Unknown data type.");
}
columnName = PQfname(result_, pos);
}
PostgreSQLStandardIntoTypeBackEnd *
PostgreSQLStatementBackEnd::makeIntoTypeBackEnd()
{
hasIntoElements_ = true;
return new PostgreSQLStandardIntoTypeBackEnd(*this);
}
PostgreSQLStandardUseTypeBackEnd *
PostgreSQLStatementBackEnd::makeUseTypeBackEnd()
{
hasUseElements_ = true;
return new PostgreSQLStandardUseTypeBackEnd(*this);
}
PostgreSQLVectorIntoTypeBackEnd *
PostgreSQLStatementBackEnd::makeVectorIntoTypeBackEnd()
{
hasVectorIntoElements_ = true;
return new PostgreSQLVectorIntoTypeBackEnd(*this);
}
PostgreSQLVectorUseTypeBackEnd *
PostgreSQLStatementBackEnd::makeVectorUseTypeBackEnd()
{
hasVectorUseElements_ = true;
return new PostgreSQLVectorUseTypeBackEnd(*this);
}
| 27.777132
| 78
| 0.534431
|
saga-project
|
ad4e124c911f97684146a7fc6387892dbbcc24f0
| 8,465
|
cpp
|
C++
|
ScreenKeyboard/KeyboardHandler.cpp
|
jscipione/HaikuUtils
|
82cb2c1c1484244ab1041b71ca7632b4322bd643
|
[
"MIT"
] | 1
|
2021-05-23T18:03:58.000Z
|
2021-05-23T18:03:58.000Z
|
ScreenKeyboard/KeyboardHandler.cpp
|
jscipione/HaikuUtils
|
82cb2c1c1484244ab1041b71ca7632b4322bd643
|
[
"MIT"
] | null | null | null |
ScreenKeyboard/KeyboardHandler.cpp
|
jscipione/HaikuUtils
|
82cb2c1c1484244ab1041b71ca7632b4322bd643
|
[
"MIT"
] | null | null | null |
#include "KeyboardHandler.h"
#include <Message.h>
#include <malloc.h>
#include <string.h>
void PressKey(uint8 *state, uint32 code)
{
state[code/8] |= 1 << (code%8);
}
void ReleaseKey(uint8 *state, uint32 code)
{
state[code/8] &= ~(uint8)(1 << (code%8));
}
bool IsKeyPressed(uint8 *state, uint32 code)
{
return state[code/8] & (1 << (code%8));
}
void KeyboardHandler::StartRepeating(BMessage *msg)
{
if (repeatThread > 0) StopRepeating();
repeatMsg = *msg;
repeatThread = spawn_thread(RepeatThread, "repeat thread", B_REAL_TIME_PRIORITY, this);
repeatThreadSem = create_sem(0, "repeat thread sem");
if (repeatThread > 0)
resume_thread(repeatThread);
}
void KeyboardHandler::StopRepeating()
{
if (repeatThread > 0) {
status_t res;
sem_id sem = repeatThreadSem;
repeatThreadSem = B_BAD_SEM_ID;
delete_sem(sem);
wait_for_thread(repeatThread, &res);
repeatThread = 0;
}
}
status_t KeyboardHandler::RepeatThread(void *arg)
{
KeyboardHandler *h = (KeyboardHandler*)arg;
int32 count;
if (acquire_sem_etc(h->repeatThreadSem, 1, B_RELATIVE_TIMEOUT, h->repeatDelay) == B_BAD_SEM_ID) return B_OK;
while (true) {
h->repeatMsg.ReplaceInt64("when", system_time());
h->repeatMsg.FindInt32("be:key_repeat", &count);
h->repeatMsg.ReplaceInt32("be:key_repeat", count + 1);
BMessage *msg = new BMessage(h->repeatMsg);
if (msg != NULL)
if (h->dev->EnqueueMessage(msg) != B_OK)
delete msg;
if (acquire_sem_etc(h->repeatThreadSem, 1, B_RELATIVE_TIMEOUT, /* 1000000 / h->repeatRate */ 50000) == B_BAD_SEM_ID) return B_OK;
}
}
KeyboardHandler::KeyboardHandler(BInputServerDevice *dev, key_map *keyMap, char *chars, bigtime_t repeatDelay, int32 repeatRate)
: dev(dev), keyMap(keyMap), chars(chars), repeatDelay(repeatDelay), repeatRate(repeatRate)
{
repeatThread = 0;
memset(state, 0, sizeof(state));
notifiers = NULL;
}
KeyboardHandler::~KeyboardHandler()
{
StopRepeating();
if (keyMap != NULL) free((void*)keyMap);
if (chars != NULL) free((void*)chars);
}
void KeyboardHandler::SetKeyMap(key_map *keyMap, char *chars)
{
if (this->keyMap != NULL) free((void*)this->keyMap);
if (this->chars != NULL) free((void*)this->chars);
this->keyMap = keyMap;
this->chars = chars;
LocksChanged(keyMap->lock_settings);
for (KeyboardNotifier *i = notifiers; i != NULL; i = i->next) i->KeymapChanged();
}
void KeyboardHandler::SetRepeat(bigtime_t delay, int32 rate)
{
repeatDelay = delay;
repeatRate = rate;
}
void KeyboardHandler::InstallNotifier(KeyboardNotifier *notifier)
{
notifier->next = notifiers;
notifiers = notifier;
}
void KeyboardHandler::UninstallNotifier(KeyboardNotifier *notifier)
{
if (notifier == notifiers) {
notifiers = notifiers->next;
} else {
KeyboardNotifier *prev = notifiers;
while (prev->next != notifier)
prev = prev->next;
prev->next = notifier->next;
}
}
void KeyboardHandler::State(uint *state)
{
memcpy(state, this->state, sizeof(state));
}
uint32 KeyboardHandler::Modifiers()
{
return modifiers;
}
void KeyboardHandler::KeyString(uint32 code, char *str, size_t len)
{
uint32 i;
char *ch;
switch (modifiers & (B_SHIFT_KEY | B_CONTROL_KEY | B_OPTION_KEY | B_CAPS_LOCK)) {
case B_OPTION_KEY | B_CAPS_LOCK | B_SHIFT_KEY: ch = chars + keyMap->option_caps_shift_map[code]; break;
case B_OPTION_KEY | B_CAPS_LOCK: ch = chars + keyMap->option_caps_map[code]; break;
case B_OPTION_KEY | B_SHIFT_KEY: ch = chars + keyMap->option_shift_map[code]; break;
case B_OPTION_KEY: ch = chars + keyMap->option_map[code]; break;
case B_CAPS_LOCK | B_SHIFT_KEY: ch = chars + keyMap->caps_shift_map[code]; break;
case B_CAPS_LOCK: ch = chars + keyMap->caps_map[code]; break;
case B_SHIFT_KEY: ch = chars + keyMap->shift_map[code]; break;
default:
if (modifiers & B_CONTROL_KEY) ch = chars + keyMap->control_map[code];
else ch = chars + keyMap->normal_map[code];
}
if (len > 0) {
for (i = 0; (i < (uint32)ch[0]) && (i < len-1); ++i)
str[i] = ch[i+1];
str[i] = '\0';
}
}
void KeyboardHandler::KeyChanged(uint32 code, bool isDown)
{
uint8 state[16];
memcpy(state, this->state, sizeof(state));
if (isDown)
state[code/8] |= 1 << (code%8);
else
state[code/8] &= ~(uint8)(1 << (code%8));
StateChanged(state);
}
void KeyboardHandler::CodelessKeyChanged(const char *str, bool isDown, bool doRepeat)
{
BMessage *msg = new BMessage();
if (msg == NULL) return;
msg->AddInt64("when", system_time());
msg->AddInt32("key", 0);
msg->AddString("bytes", str);
msg->AddInt32("raw_char", 0xa);
if (isDown) {
msg->what = B_KEY_DOWN;
if (doRepeat) {
msg->AddInt32("be:key_repeat", 1);
StartRepeating(msg);
}
} else {
msg->what = B_KEY_UP;
if (doRepeat)
StopRepeating();
}
if (dev->EnqueueMessage(msg) != B_OK)
delete msg;
}
void KeyboardHandler::StateChanged(uint8 state[16])
{
uint32 i, j;
BMessage *msg;
uint32 modifiers = this->modifiers & (B_CAPS_LOCK | B_SCROLL_LOCK | B_NUM_LOCK);
if (IsKeyPressed(state, keyMap->left_shift_key)) modifiers |= B_SHIFT_KEY | B_LEFT_SHIFT_KEY;
if (IsKeyPressed(state, keyMap->right_shift_key)) modifiers |= B_SHIFT_KEY | B_RIGHT_SHIFT_KEY;
if (IsKeyPressed(state, keyMap->left_command_key)) modifiers |= B_COMMAND_KEY | B_LEFT_COMMAND_KEY;
if (IsKeyPressed(state, keyMap->right_command_key)) modifiers |= B_COMMAND_KEY | B_RIGHT_COMMAND_KEY;
if (IsKeyPressed(state, keyMap->left_control_key)) modifiers |= B_CONTROL_KEY | B_LEFT_CONTROL_KEY;
if (IsKeyPressed(state, keyMap->right_control_key)) modifiers |= B_CONTROL_KEY | B_RIGHT_CONTROL_KEY;
if (IsKeyPressed(state, keyMap->caps_key)) modifiers ^= B_CAPS_LOCK;
if (IsKeyPressed(state, keyMap->scroll_key)) modifiers ^= B_SCROLL_LOCK;
if (IsKeyPressed(state, keyMap->num_key)) modifiers ^= B_NUM_LOCK;
if (IsKeyPressed(state, keyMap->left_option_key)) modifiers |= B_OPTION_KEY | B_LEFT_OPTION_KEY;
if (IsKeyPressed(state, keyMap->right_option_key)) modifiers |= B_OPTION_KEY | B_RIGHT_OPTION_KEY;
if (IsKeyPressed(state, keyMap->menu_key)) modifiers |= B_MENU_KEY;
if (this->modifiers != modifiers) {
msg = new BMessage(B_MODIFIERS_CHANGED);
if (msg != NULL) {
msg->AddInt64("when", system_time());
msg->AddInt32("modifiers", modifiers);
msg->AddInt32("be:old_modifiers", this->modifiers);
msg->AddData("states", B_UINT8_TYPE, state, 16);
if (dev->EnqueueMessage(msg) == B_OK)
this->modifiers = modifiers;
else
delete msg;
}
}
uint8 diff[16];
char rawCh;
char str[5];
for (i = 0; i < 16; ++i)
diff[i] = this->state[i] ^ state[i];
for (i = 0; i < 128; ++i) {
if (diff[i/8] & (1 << (i%8))) {
msg = new BMessage();
if (msg) {
KeyString(i, str, sizeof(str));
msg->AddInt64("when", system_time());
msg->AddInt32("key", i);
msg->AddInt32("modifiers", modifiers);
msg->AddData("states", B_UINT8_TYPE, state, 16);
if (str[0] != '\0') {
if (chars[keyMap->normal_map[i]] != 0)
rawCh = chars[keyMap->normal_map[i] + 1];
else
rawCh = str[0];
for (j = 0; str[j] != '\0'; ++j)
msg->AddInt8("byte", str[j]);
msg->AddString("bytes", str);
msg->AddInt32("raw_char", rawCh);
}
if (state[i/8] & (1 << (i%8))) {
if (str[0] != '\0')
msg->what = B_KEY_DOWN;
else
msg->what = B_UNMAPPED_KEY_DOWN;
msg->AddInt32("be:key_repeat", 1);
StartRepeating(msg);
} else {
if (str[0] != '\0')
msg->what = B_KEY_UP;
else
msg->what = B_UNMAPPED_KEY_UP;
StopRepeating();
}
if (dev->EnqueueMessage(msg) == B_OK) {
for (j = 0; j < 16; ++j)
this->state[j] = state[j];
} else
delete msg;
}
}
}
}
void KeyboardHandler::LocksChanged(uint32 locks)
{
locks &= B_CAPS_LOCK | B_NUM_LOCK | B_SCROLL_LOCK;
if (modifiers != locks) {
BMessage *msg = new BMessage(B_MODIFIERS_CHANGED);
if (msg != NULL) {
msg->AddInt64("when", system_time());
msg->AddInt32("modifiers", locks);
msg->AddInt32("be:old_modifiers", modifiers);
msg->AddData("states", B_UINT8_TYPE, state, 16);
if (dev->EnqueueMessage(msg) == B_OK)
modifiers = locks;
else
delete msg;
}
}
}
| 27.57329
| 131
| 0.6443
|
jscipione
|
ad5073b098a914fab2c0838b03e8ebe936ff1f03
| 348
|
cpp
|
C++
|
leetcode/Two Sum II - Input array is sorted.cpp
|
ANONYMOUS609/Competitive-Programming
|
d3753eeee24a660963f1d8911bf887c8f41f5677
|
[
"MIT"
] | 2
|
2019-01-30T12:45:18.000Z
|
2021-05-06T19:02:51.000Z
|
leetcode/Two Sum II - Input array is sorted.cpp
|
ANONYMOUS609/Competitive-Programming
|
d3753eeee24a660963f1d8911bf887c8f41f5677
|
[
"MIT"
] | null | null | null |
leetcode/Two Sum II - Input array is sorted.cpp
|
ANONYMOUS609/Competitive-Programming
|
d3753eeee24a660963f1d8911bf887c8f41f5677
|
[
"MIT"
] | 3
|
2020-10-02T15:42:04.000Z
|
2022-03-27T15:14:16.000Z
|
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size()-1;
while(l<r) {
int sum = numbers[l] + numbers[r];
if(sum == target) return {l+1, r+1};
else if(sum < target) l++;
else r--;
}
return {l+1, r+1};
}
};
| 26.769231
| 58
| 0.454023
|
ANONYMOUS609
|
ad577e3639b783744ad2c4220e9095984ba8d610
| 3,573
|
cc
|
C++
|
src/messages/text_document_rename.cc
|
Gei0r/cquery
|
6ff8273e8b8624016f9363f444acfee30c4bbf64
|
[
"MIT"
] | 1,652
|
2018-01-24T03:19:58.000Z
|
2020-07-28T19:04:00.000Z
|
src/messages/text_document_rename.cc
|
Gei0r/cquery
|
6ff8273e8b8624016f9363f444acfee30c4bbf64
|
[
"MIT"
] | 490
|
2018-01-24T00:55:38.000Z
|
2020-07-03T19:44:16.000Z
|
src/messages/text_document_rename.cc
|
Gei0r/cquery
|
6ff8273e8b8624016f9363f444acfee30c4bbf64
|
[
"MIT"
] | 154
|
2018-01-31T05:57:33.000Z
|
2020-07-05T00:02:46.000Z
|
#include "message_handler.h"
#include "query_utils.h"
#include "queue_manager.h"
namespace {
MethodType kMethodType = "textDocument/rename";
lsWorkspaceEdit BuildWorkspaceEdit(QueryDatabase* db,
WorkingFiles* working_files,
QueryId::SymbolRef sym,
const std::string& new_text) {
std::unordered_map<QueryId::File, lsTextDocumentEdit> path_to_edit;
EachOccurrence(db, sym, true, [&](QueryId::LexicalRef ref) {
optional<lsLocation> ls_location = GetLsLocation(db, working_files, ref);
if (!ls_location)
return;
QueryId::File file_id = ref.file;
if (path_to_edit.find(file_id) == path_to_edit.end()) {
path_to_edit[file_id] = lsTextDocumentEdit();
QueryFile& file = db->files[file_id.id];
if (!file.def)
return;
const std::string& path = file.def->path;
path_to_edit[file_id].textDocument.uri = lsDocumentUri::FromPath(path);
WorkingFile* working_file = working_files->GetFileByFilename(path);
if (working_file)
path_to_edit[file_id].textDocument.version = working_file->version;
}
lsTextEdit edit;
edit.range = ls_location->range;
edit.newText = new_text;
// vscode complains if we submit overlapping text edits.
auto& edits = path_to_edit[file_id].edits;
if (std::find(edits.begin(), edits.end(), edit) == edits.end())
edits.push_back(edit);
});
lsWorkspaceEdit edit;
for (const auto& changes : path_to_edit)
edit.documentChanges.push_back(changes.second);
return edit;
}
struct In_TextDocumentRename : public RequestInMessage {
MethodType GetMethodType() const override { return kMethodType; }
struct Params {
// The document to format.
lsTextDocumentIdentifier textDocument;
// The position at which this request was sent.
lsPosition position;
// The new name of the symbol. If the given name is not valid the
// request must return a [ResponseError](#ResponseError) with an
// appropriate message set.
std::string newName;
};
Params params;
};
MAKE_REFLECT_STRUCT(In_TextDocumentRename::Params,
textDocument,
position,
newName);
MAKE_REFLECT_STRUCT(In_TextDocumentRename, id, params);
REGISTER_IN_MESSAGE(In_TextDocumentRename);
struct Out_TextDocumentRename : public lsOutMessage<Out_TextDocumentRename> {
lsRequestId id;
lsWorkspaceEdit result;
};
MAKE_REFLECT_STRUCT(Out_TextDocumentRename, jsonrpc, id, result);
struct Handler_TextDocumentRename : BaseMessageHandler<In_TextDocumentRename> {
MethodType GetMethodType() const override { return kMethodType; }
void Run(In_TextDocumentRename* request) override {
QueryId::File file_id;
QueryFile* file;
if (!FindFileOrFail(db, project, request->id,
request->params.textDocument.uri.GetAbsolutePath(),
&file, &file_id)) {
return;
}
WorkingFile* working_file =
working_files->GetFileByFilename(file->def->path);
Out_TextDocumentRename out;
out.id = request->id;
for (QueryId::SymbolRef sym :
FindSymbolsAtLocation(working_file, file, request->params.position)) {
// Found symbol. Return references to rename.
out.result =
BuildWorkspaceEdit(db, working_files, sym, request->params.newName);
break;
}
QueueManager::WriteStdout(kMethodType, out);
}
};
REGISTER_MESSAGE_HANDLER(Handler_TextDocumentRename);
} // namespace
| 32.481818
| 79
| 0.678701
|
Gei0r
|
ad5c5bc67ba224c112effaee5146319c6b05093c
| 45
|
cpp
|
C++
|
ml/src/Serv_Converters.cpp
|
georgephilipp/cppgstd_legacy
|
e130860da7700aae42b915bc36a7efa4cae06d56
|
[
"MIT"
] | null | null | null |
ml/src/Serv_Converters.cpp
|
georgephilipp/cppgstd_legacy
|
e130860da7700aae42b915bc36a7efa4cae06d56
|
[
"MIT"
] | null | null | null |
ml/src/Serv_Converters.cpp
|
georgephilipp/cppgstd_legacy
|
e130860da7700aae42b915bc36a7efa4cae06d56
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Converters.h"
| 11.25
| 23
| 0.711111
|
georgephilipp
|
ad5d2e7f67596381adaae88265de8f7f5103396c
| 1,536
|
cpp
|
C++
|
src/common/RNG.cpp
|
usc-csci-545/aikido
|
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/RNG.cpp
|
usc-csci-545/aikido
|
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/RNG.cpp
|
usc-csci-545/aikido
|
afd8b203c17cb0b05d7db436f8bffbbe2111a75a
|
[
"BSD-3-Clause"
] | null | null | null |
#include <aikido/common/RNG.hpp>
namespace aikido {
namespace common {
//==============================================================================
// This namespace-scoped definition is required to enable odr-use.
constexpr std::size_t RNG::NUM_BITS;
//==============================================================================
std::vector<std::unique_ptr<common::RNG>> cloneRNGsFrom(
RNG& _engine, std::size_t _numOutputs, std::size_t _numSeeds)
{
// Use the input RNG to create an initial batch of seeds.
std::vector<common::RNG::result_type> initialSeeds;
initialSeeds.reserve(_numSeeds);
for (std::size_t iseed = 0; iseed < _numSeeds; ++iseed)
initialSeeds.emplace_back(_engine());
// Use seed_seq to improve the quality of our seeds.
std::seed_seq seqSeeds(initialSeeds.begin(), initialSeeds.end());
std::vector<common::RNG::result_type> improvedSeeds(_numOutputs);
seqSeeds.generate(std::begin(improvedSeeds), std::end(improvedSeeds));
// Create the random number generators of the same type as the input _engine.
std::vector<std::unique_ptr<common::RNG>> output;
output.reserve(_numOutputs);
for (auto improvedSeed : improvedSeeds)
output.emplace_back(_engine.clone(improvedSeed));
return output;
}
//==============================================================================
std::vector<std::unique_ptr<common::RNG>> cloneRNGFrom(
RNG& _engine, std::size_t _numSeeds)
{
return cloneRNGsFrom(_engine, 1, _numSeeds);
}
} // namespace common
} // namespace aikido
| 34.133333
| 80
| 0.621094
|
usc-csci-545
|
ad5f309ec3a01966982ea48381ad8ad082354f9e
| 7,262
|
hpp
|
C++
|
src/shelly_hap_chars.hpp
|
lucaspinelli85/shelly-homekit
|
f22f5186284f5840fde5a595587a6957be2a15b0
|
[
"Apache-2.0"
] | 1
|
2020-11-17T13:46:48.000Z
|
2020-11-17T13:46:48.000Z
|
src/shelly_hap_chars.hpp
|
schemhad/shelly-homekit
|
82d8d64524af20ba30941a64c7ba060301512785
|
[
"Apache-2.0"
] | null | null | null |
src/shelly_hap_chars.hpp
|
schemhad/shelly-homekit
|
82d8d64524af20ba30941a64c7ba060301512785
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2020 Deomid "rojer" Ryabkov
* 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.
*/
#pragma once
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability-completeness"
#endif
#include <cstring>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "HAP.h"
namespace shelly {
namespace hap {
class Service;
class Characteristic {
public:
Characteristic(uint16_t iid, HAPCharacteristicFormat format,
const HAPUUID *type, const char *debug_description = nullptr);
virtual ~Characteristic();
const Service *parent() const;
void set_parent(const Service *parent);
virtual const HAPCharacteristic *GetHAPCharacteristic() {
return hap_charactristic();
}
const HAPCharacteristic *hap_charactristic();
void RaiseEvent();
protected:
struct HAPCharacteristicWithInstance {
union AllHAPCHaracteristicTypes {
HAPDataCharacteristic data;
HAPBoolCharacteristic bool_;
HAPUInt8Characteristic uint8;
HAPUInt16Characteristic uint16;
HAPUInt32Characteristic uint32;
HAPUInt64Characteristic uint64;
HAPIntCharacteristic int_;
HAPFloatCharacteristic float_;
HAPStringCharacteristic string;
HAPTLV8Characteristic tlv8;
} char_;
Characteristic *inst; // Pointer back to the instance.
} hap_char_;
private:
const Service *parent_ = nullptr;
Characteristic(const Characteristic &other) = delete;
};
class StringCharacteristic : public Characteristic {
public:
StringCharacteristic(uint16_t iid, const HAPUUID *type, uint16_t max_length,
const std::string &initial_value,
const char *debug_description = nullptr);
virtual ~StringCharacteristic();
const std::string &value() const;
void set_value(const std::string &value);
private:
static HAPError HandleReadCB(
HAPAccessoryServerRef *server,
const HAPStringCharacteristicReadRequest *request, char *value,
size_t maxValueBytes, void *context);
std::string value_;
};
// Template class that can be used to create scalar-value characteristics.
template <class ValType, class HAPBaseClass, class HAPReadRequestType,
class HAPWriteRequestType>
struct ScalarCharacteristic : public Characteristic {
public:
typedef std::function<HAPError(HAPAccessoryServerRef *server,
const HAPReadRequestType *request,
ValType *value)>
ReadHandler;
typedef std::function<HAPError(HAPAccessoryServerRef *server,
const HAPWriteRequestType *request,
ValType value)>
WriteHandler;
ScalarCharacteristic(HAPCharacteristicFormat format, uint16_t iid,
const HAPUUID *type, ReadHandler read_handler,
bool supports_notification,
WriteHandler write_handler = nullptr,
const char *debug_description = nullptr)
: Characteristic(iid, format, type, debug_description),
read_handler_(read_handler),
write_handler_(write_handler) {
HAPBaseClass *c = reinterpret_cast<HAPBaseClass *>(&hap_char_.char_);
if (read_handler) {
c->properties.readable = true;
c->callbacks.handleRead = ScalarCharacteristic::HandleReadCB;
c->properties.supportsEventNotification = supports_notification;
c->properties.ble.supportsBroadcastNotification = true;
c->properties.ble.supportsDisconnectedNotification = true;
}
if (write_handler) {
c->properties.writable = true;
c->callbacks.handleWrite = ScalarCharacteristic::HandleWriteCB;
}
}
virtual ~ScalarCharacteristic() {
}
private:
static HAPError HandleReadCB(HAPAccessoryServerRef *server,
const HAPReadRequestType *request,
ValType *value, void *context) {
auto *hci = reinterpret_cast<const HAPCharacteristicWithInstance *>(
request->characteristic);
auto *c = static_cast<const ScalarCharacteristic *>(hci->inst);
(void) context;
return const_cast<ScalarCharacteristic *>(c)->read_handler_(server, request,
value);
}
static HAPError HandleWriteCB(HAPAccessoryServerRef *server,
const HAPWriteRequestType *request,
ValType value, void *context) {
auto *hci = reinterpret_cast<const HAPCharacteristicWithInstance *>(
request->characteristic);
auto *c = static_cast<const ScalarCharacteristic *>(hci->inst);
(void) context;
return const_cast<ScalarCharacteristic *>(c)->write_handler_(
server, request, value);
}
const ReadHandler read_handler_;
const WriteHandler write_handler_;
};
struct BoolCharacteristic
: public ScalarCharacteristic<bool, HAPBoolCharacteristic,
HAPBoolCharacteristicReadRequest,
HAPBoolCharacteristicWriteRequest> {
public:
BoolCharacteristic(uint16_t iid, const HAPUUID *type,
ReadHandler read_handler, bool supports_notification,
WriteHandler write_handler = nullptr,
const char *debug_description = nullptr)
: ScalarCharacteristic(kHAPCharacteristicFormat_Bool, iid, type,
read_handler, supports_notification, write_handler,
debug_description) {
}
virtual ~BoolCharacteristic() {
}
};
class UInt8Characteristic
: public ScalarCharacteristic<uint8_t, HAPUInt8Characteristic,
HAPUInt8CharacteristicReadRequest,
HAPUInt8CharacteristicWriteRequest> {
public:
UInt8Characteristic(uint16_t iid, const HAPUUID *type, uint8_t min,
uint8_t max, uint8_t step, ReadHandler read_handler,
bool supports_notification,
WriteHandler write_handler = nullptr,
const char *debug_description = nullptr)
: ScalarCharacteristic(kHAPCharacteristicFormat_UInt8, iid, type,
read_handler, supports_notification, write_handler,
debug_description) {
HAPUInt8Characteristic *c = &hap_char_.char_.uint8;
c->constraints.minimumValue = min;
c->constraints.maximumValue = max;
c->constraints.stepValue = step;
}
virtual ~UInt8Characteristic() {
}
};
} // namespace hap
} // namespace shelly
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 35.252427
| 80
| 0.667585
|
lucaspinelli85
|
ad67028febc405a69bfae0a4d58fd3d60ff5fa07
| 2,973
|
cpp
|
C++
|
02/src/assignment/menu.cpp
|
KHN190/IGME-740
|
0e0321ceb7a2f2ade9a99caf15be16f916b12393
|
[
"Unlicense"
] | null | null | null |
02/src/assignment/menu.cpp
|
KHN190/IGME-740
|
0e0321ceb7a2f2ade9a99caf15be16f916b12393
|
[
"Unlicense"
] | null | null | null |
02/src/assignment/menu.cpp
|
KHN190/IGME-740
|
0e0321ceb7a2f2ade9a99caf15be16f916b12393
|
[
"Unlicense"
] | null | null | null |
void menu(int value) {
switch (value) {
// clear
case 0:
poly.clear();
poly_color.clear();
curr_poly.clear();
n_vertices = 0;
glutPostRedisplay();
break;
// exit
case 1:
exit(0);
// color seetting
case 2: // red
config.color[0] = 1.0f;
config.color[1] = 0.0f;
config.color[2] = 0.0f;
glutPostRedisplay();
break;
case 3: // green
config.color[0] = 0.0f;
config.color[1] = 1.0f;
config.color[2] = 0.0f;
glutPostRedisplay();
break;
case 4: // blue
config.color[0] = 0.0f;
config.color[1] = 0.0f;
config.color[2] = 1.0f;
glutPostRedisplay();
break;
// brush setting
case 5:
if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; }
else { config.type = brush_type::dot; }
break;
case 6:
config.type = brush_type::line;
if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; }
else { config.type = brush_type::line; }
break;
case 7:
if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; }
else { config.type = brush_type::tri; }
break;
case 8:
if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; }
else { config.type = brush_type::quad; }
break;
case 9:
if (n_vertices != 0) { std::cout << "must finish drawing before changing brush!\n"; }
else { config.type = brush_type::poly; }
break;
// cursor
case 10: // small
config.cursor_size = 1;
break;
case 11: // medium
config.cursor_size = 2;
break;
case 12: // large
config.cursor_size = 3;
break;
default:
break;
}
}
void createMenu() {
int color_menu = glutCreateMenu(menu);
glutAddMenuEntry("Red", 2);
glutAddMenuEntry("Green", 3);
glutAddMenuEntry("Blue", 4);
int brush_menu = glutCreateMenu(menu);
glutAddMenuEntry("Dot", 5);
glutAddMenuEntry("Line", 6);
glutAddMenuEntry("Tri", 7);
glutAddMenuEntry("Quad", 8);
glutAddMenuEntry("Poly", 9);
int cursor_menu = glutCreateMenu(menu);
glutAddMenuEntry("Small", 10);
glutAddMenuEntry("Medium", 11);
glutAddMenuEntry("Large", 12);
glutCreateMenu(menu);
glutAddMenuEntry("Clear", 0);
glutAddSubMenu("Colors", color_menu);
glutAddSubMenu("Brush", brush_menu);
glutAddSubMenu("Cursor", cursor_menu);
glutAddMenuEntry("Exit", 1);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
| 28.586538
| 97
| 0.510932
|
KHN190
|
ad67eaf99e802df0517537360e2027db6f1a45f6
| 2,296
|
cpp
|
C++
|
11_dynamic_1/6_coin_change.cpp
|
ShyamNandanKumar/coding-ninja2
|
a43a21575342261e573f71f7d8eff0572f075a17
|
[
"MIT"
] | 11
|
2021-01-02T10:07:17.000Z
|
2022-03-16T00:18:06.000Z
|
11_dynamic_1/6_coin_change.cpp
|
meyash/cp_master
|
316bf47db2a5b40891edd73cff834517993c3d2a
|
[
"MIT"
] | null | null | null |
11_dynamic_1/6_coin_change.cpp
|
meyash/cp_master
|
316bf47db2a5b40891edd73cff834517993c3d2a
|
[
"MIT"
] | 5
|
2021-05-19T11:17:18.000Z
|
2021-09-16T06:23:31.000Z
|
/*
You are given an infinite supply of coins of each of denominations D = {D0, D1, D2, D3, ...... Dn-1}. You need to figure out the total number of ways W, in which you can make change for Value V using coins of denominations D.
Note : Return 0, if change isn't possible.
Input Format
Line 1 : Integer n i.e. total number of denominations
Line 2 : N integers i.e. n denomination values
Line 3 : Value V
Output Format
Line 1 : Number of ways i.e. W
Constraints :
1<=n<=10
1<=V<=1000
Sample Input 1 :
3
1 2 3
4
Sample Output
4
Sample Output Explanation :
Number of ways are - 4 total i.e. (1,1,1,1), (1,1,2), (1,3) and (2,2).
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int find_ans(int den[],int start,int size,int curr_val,int goal,int **storage){
// base cases
// current val greater than goal
if(curr_val>goal){
return 0;
}
// goal value reached
if(curr_val==goal){
return 1;
}
// checked all denominations
if(start==size){
return 0;
}
if(storage[size-start][curr_val]>0){
return storage[size-start][curr_val];
}
// starting element of den included
int leftpossible=find_ans(den,start,size,curr_val+den[start],goal,storage);
// starting element of den not included
int rightpossible=find_ans(den,start+1,size,curr_val,goal,storage);
storage[size-start][curr_val]=leftpossible+rightpossible;
return leftpossible+rightpossible;
}
int countWaysToMakeChange(int denominations[], int numDenominations, int value){
sort(denominations,denominations+numDenominations);
int **storage=new int*[numDenominations+1];
for(int i=0;i<numDenominations+1;i++){
storage[i]=new int[value+1];
}
// set all storage elements to -1
for(int i=0;i<numDenominations+1;i++){
for(int j=0;j<value+1;j++){
storage[i][j]=-1;
}
}
int ans=find_ans(denominations,0,numDenominations,0,value,storage);
for(int i=0;i<numDenominations+1;i++){
delete storage[i];
}
delete storage;
return ans;
}
int main(){
int numDenominations;
cin >> numDenominations;
int* denominations = new int[numDenominations];
for(int i = 0; i < numDenominations; i++){
cin >> denominations[i];
}
int value;
cin >> value;
cout << countWaysToMakeChange(denominations, numDenominations, value);
return 0;
}
| 26.697674
| 225
| 0.692944
|
ShyamNandanKumar
|
ad6c2a49df9bc9bcb60ca1a02d36e2837e67b352
| 270
|
cpp
|
C++
|
tests/op/testdata/unknown_imports.cpp
|
PeaStew/contentos-go
|
dc6029153cda3969d4879f0af5e6c9407d33b031
|
[
"MIT"
] | 50
|
2018-10-22T08:12:35.000Z
|
2022-01-31T10:28:10.000Z
|
tests/op/testdata/unknown_imports.cpp
|
hassoon1986/contentos-go
|
5810123c4b353c8733e3b6fd2bb11229bc17bf6b
|
[
"MIT"
] | 12
|
2019-01-04T03:06:33.000Z
|
2022-01-05T09:42:17.000Z
|
tests/op/testdata/unknown_imports.cpp
|
hassoon1986/contentos-go
|
5810123c4b353c8733e3b6fd2bb11229bc17bf6b
|
[
"MIT"
] | 19
|
2019-04-28T04:46:28.000Z
|
2022-03-21T09:50:51.000Z
|
#include <cosiolib/contract.hpp>
extern "C" void unknown_func(uint32_t);
class unknown_imports : public cosio::contract {
public:
using cosio::contract::contract;
void hello(uint32_t n) {
unknown_func(n);
}
};
COSIO_ABI(unknown_imports, (hello))
| 18
| 48
| 0.696296
|
PeaStew
|
ad6c726c957eff3c2181f350da5bbc63fcd9f7de
| 5,517
|
cc
|
C++
|
src/lib/storage/fs_management/cpp/mount.cc
|
PlugFox/fuchsia
|
39afe5230d41628b3c736a6e384393df954968c8
|
[
"BSD-2-Clause"
] | 2
|
2021-12-29T10:11:08.000Z
|
2022-01-04T15:37:09.000Z
|
src/lib/storage/fs_management/cpp/mount.cc
|
PlugFox/fuchsia
|
39afe5230d41628b3c736a6e384393df954968c8
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/storage/fs_management/cpp/mount.cc
|
PlugFox/fuchsia
|
39afe5230d41628b3c736a6e384393df954968c8
|
[
"BSD-2-Clause"
] | null | null | null |
// Copyright 2016 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 <errno.h>
#include <fcntl.h>
#include <fidl/fuchsia.hardware.block/cpp/wire.h>
#include <fidl/fuchsia.io.admin/cpp/wire.h>
#include <fidl/fuchsia.io/cpp/wire.h>
#include <lib/fdio/cpp/caller.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/limits.h>
#include <lib/fdio/namespace.h>
#include <lib/fdio/vfs.h>
#include <lib/zx/channel.h>
#include <string.h>
#include <unistd.h>
#include <zircon/compiler.h>
#include <zircon/device/block.h>
#include <zircon/device/vfs.h>
#include <zircon/processargs.h>
#include <zircon/syscalls.h>
#include <iostream>
#include <utility>
#include <fbl/algorithm.h>
#include <fbl/alloc_checker.h>
#include <fbl/unique_fd.h>
#include <fbl/vector.h>
#include <fs-management/mount.h>
#include <pretty/hexdump.h>
#include "src/lib/storage/vfs/cpp/fuchsia_vfs.h"
namespace fs_management {
namespace {
namespace fio = fuchsia_io;
using DirectoryAdmin = fuchsia_io_admin::DirectoryAdmin;
zx::status<std::pair<fidl::ClientEnd<DirectoryAdmin>, fidl::ClientEnd<DirectoryAdmin>>>
StartFilesystem(fbl::unique_fd device_fd, DiskFormat df, const MountOptions& options,
LaunchCallback cb, zx::channel crypt_client) {
// get the device handle from the device_fd
zx_status_t status;
zx::channel device;
status = fdio_get_service_handle(device_fd.release(), device.reset_and_get_address());
if (status != ZX_OK) {
return zx::error(status);
}
// convert mount options to init options
InitOptions init_options = {
.readonly = options.readonly,
.verbose_mount = options.verbose_mount,
.collect_metrics = options.collect_metrics,
.wait_until_ready = options.wait_until_ready,
.write_compression_algorithm = options.write_compression_algorithm,
// TODO(jfsulliv): This is currently only used in tests. Plumb through mount options if
// needed.
.write_compression_level = -1,
.cache_eviction_policy = options.cache_eviction_policy,
.fsck_after_every_transaction = options.fsck_after_every_transaction,
.sandbox_decompression = options.sandbox_decompression,
.callback = cb,
};
// launch the filesystem process
auto export_root_or = FsInit(std::move(device), df, init_options, std::move(crypt_client));
if (export_root_or.is_error()) {
return export_root_or.take_error();
}
// Extract the handle to the root of the filesystem from the export root. The POSIX flags will
// cause the writable and executable rights to be inherited (if present).
uint32_t flags = fio::wire::kOpenRightReadable | fio::wire::kOpenFlagPosixWritable |
fio::wire::kOpenFlagPosixExecutable;
if (options.admin)
flags |= fio::wire::kOpenRightAdmin;
auto root_or = FsRootHandle(fidl::UnownedClientEnd<DirectoryAdmin>(*export_root_or), flags);
if (root_or.is_error())
return root_or.take_error();
return zx::ok(std::make_pair(*std::move(export_root_or), *std::move(root_or)));
}
std::string StripTrailingSlash(const std::string& in) {
if (!in.empty() && in.back() == '/') {
return in.substr(0, in.length() - 1);
} else {
return in;
}
}
} // namespace
MountedFilesystem::~MountedFilesystem() {
if (export_root_.is_valid()) [[maybe_unused]]
auto result = UnmountImpl();
}
zx::status<> MountedFilesystem::UnmountImpl() {
zx_status_t status = ZX_OK;
if (!mount_path_.empty()) {
// Ignore errors unbinding, since we still want to continue and try and shut down the
// filesystem.
fdio_ns_t* ns;
status = fdio_ns_get_installed(&ns);
if (status == ZX_OK)
status = fdio_ns_unbind(ns, StripTrailingSlash(mount_path_).c_str());
}
auto result = Shutdown(export_root_);
return status != ZX_OK ? zx::error(status) : result;
}
__EXPORT
zx::status<> Shutdown(fidl::UnownedClientEnd<DirectoryAdmin> export_root) {
auto admin_or = fidl::CreateEndpoints<fuchsia_fs::Admin>();
if (admin_or.is_error())
return admin_or.take_error();
if (zx_status_t status =
fdio_service_connect_at(export_root.channel()->get(),
fidl::DiscoverableProtocolDefaultPath<fuchsia_fs::Admin> + 1,
admin_or->server.TakeChannel().release());
status != ZX_OK) {
return zx::error(status);
}
auto resp = fidl::WireCall(admin_or->client)->Shutdown();
if (resp.status() != ZX_OK)
return zx::error(resp.status());
return zx::ok();
}
__EXPORT
zx::status<MountedFilesystem> Mount(fbl::unique_fd device_fd, const char* mount_path, DiskFormat df,
const MountOptions& options, LaunchCallback cb) {
zx::channel crypt_client(options.crypt_client);
auto result = StartFilesystem(std::move(device_fd), df, options, cb, std::move(crypt_client));
if (result.is_error())
return result.take_error();
auto [export_root, data_root] = *std::move(result);
if (mount_path) {
fdio_ns_t* ns;
if (zx_status_t status = fdio_ns_get_installed(&ns); status != ZX_OK)
return zx::error(status);
if (zx_status_t status = fdio_ns_bind(ns, mount_path, data_root.TakeChannel().release());
status != ZX_OK)
return zx::error(status);
}
return zx::ok(MountedFilesystem(std::move(export_root), mount_path ? mount_path : ""));
}
} // namespace fs_management
| 33.846626
| 100
| 0.699474
|
PlugFox
|
ad6cffae77963f86606f1bf89512a8d731965953
| 8,869
|
cpp
|
C++
|
openstudiocore/src/model/AirGap.cpp
|
hellok-coder/OS-Testing
|
e9e18ad9e99f709a3f992601ed8d2e0662175af4
|
[
"blessing"
] | 1
|
2019-11-12T02:07:03.000Z
|
2019-11-12T02:07:03.000Z
|
openstudiocore/src/model/AirGap.cpp
|
hellok-coder/OS-Testing
|
e9e18ad9e99f709a3f992601ed8d2e0662175af4
|
[
"blessing"
] | 1
|
2019-02-04T23:30:45.000Z
|
2019-02-04T23:30:45.000Z
|
openstudiocore/src/model/AirGap.cpp
|
hellok-coder/OS-Testing
|
e9e18ad9e99f709a3f992601ed8d2e0662175af4
|
[
"blessing"
] | null | null | null |
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (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 any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "AirGap.hpp"
#include "AirGap_Impl.hpp"
#include <utilities/idd/OS_Material_AirGap_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
AirGap_Impl::AirGap_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: OpaqueMaterial_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == AirGap::iddObjectType());
}
AirGap_Impl::AirGap_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: OpaqueMaterial_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == AirGap::iddObjectType());
}
AirGap_Impl::AirGap_Impl(const AirGap_Impl& other,
Model_Impl* model,
bool keepHandle)
: OpaqueMaterial_Impl(other,model,keepHandle)
{}
double AirGap_Impl::thickness() const {
return 0.0;
}
double AirGap_Impl::thermalConductivity() const {
LOG_AND_THROW("Unable to convert thermal resistance to thermal conductivity for AirGap "
<< briefDescription() << ".");
return 0.0;
}
double AirGap_Impl::thermalConductance() const {
OS_ASSERT(thermalResistance());
return 1.0/thermalResistance();
}
double AirGap_Impl::thermalResistivity() const {
LOG_AND_THROW("Unable to convert thermal resistance to thermal resistivity for AirGap "
<< briefDescription() << ".");
return 0.0;
}
double AirGap_Impl::thermalResistance() const {
OptionalDouble od = getDouble(OS_Material_AirGapFields::ThermalResistance,true);
if (!od) {
LOG_AND_THROW("Thermal resistance is not set for AirGap " << briefDescription() << ".");
}
return *od;
}
double AirGap_Impl::thermalAbsorptance() const {
OptionalDouble od(0.0);
return *od;
}
OptionalDouble AirGap_Impl::thermalReflectance() const {
OptionalDouble od(0.0);
return od;
}
double AirGap_Impl::solarAbsorptance() const {
OptionalDouble od(0.0);
return *od;
}
OptionalDouble AirGap_Impl::solarReflectance() const {
OptionalDouble od(0.0);
return od;
}
double AirGap_Impl::visibleTransmittance() const {
return 1.0;
}
double AirGap_Impl::visibleAbsorptance() const {
OptionalDouble od(0.0);
return *od;
}
OptionalDouble AirGap_Impl::visibleReflectance() const {
OptionalDouble od(0.0);
return od;
}
const std::vector<std::string>& AirGap_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
return result;
}
IddObjectType AirGap_Impl::iddObjectType() const {
return AirGap::iddObjectType();
}
bool AirGap_Impl::setThickness(double value) {
return false;
}
bool AirGap_Impl::setThermalConductivity(double value) {
return false;
}
bool AirGap_Impl::setThermalConductance(double value) {
return setThermalResistance(1.0/value);
}
bool AirGap_Impl::setThermalResistivity(double value) {
return false;
}
bool AirGap_Impl::setThermalResistance(double value) {
return setDouble(OS_Material_AirGapFields::ThermalResistance,value);
}
bool AirGap_Impl::setThermalAbsorptance(double value) {
return false;
}
bool AirGap_Impl::setThermalReflectance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setSolarAbsorptance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setSolarReflectance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setVisibleAbsorptance(OptionalDouble value) {
return false;
}
bool AirGap_Impl::setVisibleReflectance(OptionalDouble value) {
return false;
}
OSOptionalQuantity AirGap_Impl::getThermalResistance(bool returnIP) const {
double value = thermalResistance();
return getQuantityFromDouble(OS_Material_AirGapFields::ThermalResistance, value, returnIP);
}
bool AirGap_Impl::setThermalResistance(boost::optional<double> thermalResistance) {
bool result(false);
if (thermalResistance) {
result = setDouble(OS_Material_AirGapFields::ThermalResistance, thermalResistance.get());
}
else {
resetThermalResistance();
result = true;
}
return result;
}
bool AirGap_Impl::setThermalResistance(const OSOptionalQuantity& thermalResistance) {
bool result(false);
OptionalDouble value;
if (thermalResistance.isSet()) {
value = getDoubleFromQuantity(OS_Material_AirGapFields::ThermalResistance,thermalResistance.get());
if (value) {
result = setThermalResistance(value);
}
}
else {
result = setThermalResistance(value);
}
return result;
}
void AirGap_Impl::resetThermalResistance() {
bool result = setString(OS_Material_AirGapFields::ThermalResistance, "");
OS_ASSERT(result);
}
openstudio::OSOptionalQuantity AirGap_Impl::thermalResistance_SI() const {
return getThermalResistance(false);
}
openstudio::OSOptionalQuantity AirGap_Impl::thermalResistance_IP() const {
return getThermalResistance(true);
}
} // detail
AirGap::AirGap(const Model& model,
double thermalResistance)
: OpaqueMaterial(AirGap::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::AirGap_Impl>());
// TODO: Appropriately handle the following required object-list fields.
bool ok = true;
// ok = setHandle();
OS_ASSERT(ok);
ok = setThermalResistance(thermalResistance);
OS_ASSERT(ok);
}
IddObjectType AirGap::iddObjectType() {
return IddObjectType(IddObjectType::OS_Material_AirGap);
}
double AirGap::thermalResistance() const {
return getImpl<detail::AirGap_Impl>()->thermalResistance();
}
OSOptionalQuantity AirGap::getThermalResistance(bool returnIP) const {
return getImpl<detail::AirGap_Impl>()->getThermalResistance(returnIP);
}
bool AirGap::setThermalResistance(double thermalResistance) {
return getImpl<detail::AirGap_Impl>()->setThermalResistance(thermalResistance);
}
bool AirGap::setThermalResistance(const Quantity& thermalResistance) {
return getImpl<detail::AirGap_Impl>()->setThermalResistance(thermalResistance);
}
void AirGap::resetThermalResistance() {
getImpl<detail::AirGap_Impl>()->resetThermalResistance();
}
/// @cond
AirGap::AirGap(std::shared_ptr<detail::AirGap_Impl> impl)
: OpaqueMaterial(std::move(impl))
{}
/// @endcond
} // model
} // openstudio
| 31.78853
| 125
| 0.7038
|
hellok-coder
|
ad6f041656d64c087ad6bb0bfde7db987fc3e0f5
| 2,113
|
cpp
|
C++
|
blockchain/chain.cpp
|
p-shubham/resilientdb
|
8e69c28e73ddebdfca8359479be4499c1cb5de41
|
[
"MIT"
] | 1
|
2022-03-04T20:34:29.000Z
|
2022-03-04T20:34:29.000Z
|
blockchain/chain.cpp
|
p-shubham/resilientdb
|
8e69c28e73ddebdfca8359479be4499c1cb5de41
|
[
"MIT"
] | null | null | null |
blockchain/chain.cpp
|
p-shubham/resilientdb
|
8e69c28e73ddebdfca8359479be4499c1cb5de41
|
[
"MIT"
] | 1
|
2020-02-12T01:20:26.000Z
|
2020-02-12T01:20:26.000Z
|
#include "chain.h"
/* Set the identifier for the block. */
void BChainStruct::set_txn_id(uint64_t tid)
{
txn_id = tid;
}
/* Get the identifier of this block. */
uint64_t BChainStruct::get_txn_id()
{
return txn_id;
}
/* Store the BatchRequests to this block. */
void BChainStruct::add_batch(BatchRequests *msg) {
char *buf = create_msg_buffer(msg);
Message *deepMsg = deep_copy_msg(buf, msg);
batch_info = (BatchRequests *)deepMsg;
delete_msg_buffer(buf);
}
/* Store the commit messages to this block. */
void BChainStruct::add_commit_proof(Message *msg) {
char *buf = create_msg_buffer(msg);
Message *deepMsg = deep_copy_msg(buf, msg);
commit_proof.push_back(deepMsg);
delete_msg_buffer(buf);
}
/* Release the contents of the block. */
void BChainStruct::release_data() {
Message::release_message(this->batch_info);
PBFTCommitMessage *cmsg;
while(this->commit_proof.size()>0)
{
cmsg = (PBFTCommitMessage *)this->commit_proof[0];
this->commit_proof.erase(this->commit_proof.begin());
Message::release_message(cmsg);
}
}
/****************************************/
/* Add a block to the chain. */
void BChain::add_block(TxnManager *txn) {
BChainStruct *blk = (BChainStruct *)mem_allocator.alloc(sizeof(BChainStruct));
new (blk) BChainStruct();
blk->set_txn_id(txn->get_txn_id());
blk->add_batch(txn->batchreq);
for(uint64_t i=0; i<txn->commit_msgs.size(); i++) {
blk->add_commit_proof(txn->commit_msgs[i]);
}
chainLock.lock();
bchain_map.push_back(blk);
chainLock.unlock();
}
/* Remove a block from the chain bbased on its identifier. */
void BChain::remove_block(uint64_t tid)
{
BChainStruct *blk;
bool found = false;
chainLock.lock();
for (uint64_t i = 0; i < bchain_map.size(); i++)
{
blk = bchain_map[i];
if (blk->get_txn_id() == tid)
{
bchain_map.erase(bchain_map.begin() + i);
found = true;
break;
}
}
chainLock.unlock();
if(found) {
blk->release_data();
mem_allocator.free(blk, sizeof(BChainStruct));
}
}
/*****************************************/
BChain *BlockChain;
std::mutex chainLock;
| 22.72043
| 79
| 0.661619
|
p-shubham
|
ad70fb393035ed63f8a45bd219bceb896d6cfb10
| 2,263
|
hpp
|
C++
|
contracts/libraries/include/gxclib/token.hpp
|
Game-X-Coin/gxc-contracts-v1
|
cc5cc59cab0422238a44d2c4d909a31200817a35
|
[
"MIT"
] | 1
|
2019-07-01T01:41:02.000Z
|
2019-07-01T01:41:02.000Z
|
contracts/libraries/include/gxclib/token.hpp
|
Game-X-Coin/gxc-contracts-v1
|
cc5cc59cab0422238a44d2c4d909a31200817a35
|
[
"MIT"
] | null | null | null |
contracts/libraries/include/gxclib/token.hpp
|
Game-X-Coin/gxc-contracts-v1
|
cc5cc59cab0422238a44d2c4d909a31200817a35
|
[
"MIT"
] | null | null | null |
/**
* @file
* @copyright defined in gxc/LICENSE
*/
#pragma once
#include <eosio/name.hpp>
#include <eosio/asset.hpp>
#include <eosio/action.hpp>
#include <eoslib/crypto.hpp>
#include <eoslib/symbol.hpp>
#include <cmath>
namespace gxc {
using namespace eosio;
using namespace eosio::internal_use_do_not_use;
constexpr name token_account = "gxc.token"_n;
inline double get_float_amount(asset quantity) {
return quantity.amount / (double)pow(10, quantity.symbol.precision());
}
asset get_supply(name issuer, symbol_code sym_code) {
asset supply;
db_get_i64(db_find_i64(token_account.value, issuer.value, "stat"_n.value, sym_code.raw()),
reinterpret_cast<void*>(&supply), sizeof(asset));
return supply;
}
asset get_balance(name owner, name issuer, symbol_code sym_code) {
asset balance;
auto esc = extended_symbol_code(sym_code, issuer);
db_get_i64(db_find_i64(token_account.value, issuer.value, "accounts"_n.value,
#ifdef TARGET_TESTNET
fasthash64(reinterpret_cast<const char*>(&esc), sizeof(uint128_t))),
#else
xxh64(reinterpret_cast<const char*>(&esc), sizeof(uint128_t))),
#endif
reinterpret_cast<void*>(&balance), sizeof(asset));
return balance;
}
struct token_contract_mock {
token_contract_mock(name auth) {
auths.emplace_back(permission_level(auth, active_permission));
}
token_contract_mock& with(name auth) {
auths.emplace_back(permission_level(auth, active_permission));
return *this;
}
using key_value = std::pair<std::string, std::vector<int8_t>>;
void mint(extended_asset value, std::vector<key_value> opts) {
action_wrapper<"mint"_n, &token_contract_mock::mint>(std::move(name(token_account)), auths)
.send(value, opts);
}
void transfer(name from, name to, extended_asset value, std::string memo) {
action_wrapper<"transfer"_n, &token_contract_mock::transfer>(std::move(name(token_account)), auths)
.send(from, to, value, memo);
}
void burn(extended_asset value, std::string memo) {
action_wrapper<"burn"_n, &token_contract_mock::burn>(std::move(name(token_account)), auths)
.send(value, memo);
}
std::vector<permission_level> auths;
};
}
| 29.38961
| 105
| 0.699072
|
Game-X-Coin
|
ad7281476dc7e4bb30b4e2a95ff1a68dcbc9978d
| 1,699
|
hh
|
C++
|
src/elle/reactor/network/udp-server-socket.hh
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | null | null | null |
src/elle/reactor/network/udp-server-socket.hh
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | null | null | null |
src/elle/reactor/network/udp-server-socket.hh
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <elle/reactor/network/fwd.hh>
#include <elle/reactor/network/socket.hh>
#include <elle/reactor/signal.hh>
namespace elle
{
namespace reactor
{
namespace network
{
/// XXX[doc].
class UDPServerSocket
: public Socket
{
/*---------.
| Typedefs |
`---------*/
public:
using Super = Socket;
using EndPoint = boost::asio::ip::udp::endpoint;
/*-------------.
| Construction |
`-------------*/
public:
UDPServerSocket(Scheduler& sched,
UDPServer* server,
EndPoint const& peer);
virtual
~UDPServerSocket();
/*-----.
| Read |
`-----*/
public:
void
read(Buffer buffer,
DurationOpt timeout = DurationOpt(),
int* bytes_read = nullptr) override;
Size
read_some(Buffer buffer,
DurationOpt timeout = DurationOpt(),
int* bytes_read = nullptr) override;
private:
friend class UDPServer;
UDPServer* _server;
EndPoint _peer;
Byte* _read_buffer;
Size _read_buffer_capacity;
Size _read_buffer_size;
Signal _read_ready;
/*------.
| Write |
`------*/
public:
virtual
void
write(Buffer buffer);
using Super::write;
/*----------------.
| Pretty printing |
`----------------*/
public:
void
print(std::ostream& s) const override;
};
}
}
}
| 22.959459
| 58
| 0.446733
|
infinitio
|
ad89ce8726d1e335d53394bf745b277e22bc1fa0
| 26,897
|
cxx
|
C++
|
MUON/MUONmapping/AliMpTriggerReader.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
MUON/MUONmapping/AliMpTriggerReader.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
MUON/MUONmapping/AliMpTriggerReader.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpeateose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
// $MpId: AliMpTriggerReader.cxx,v 1.4 2006/05/24 13:58:52 ivana Exp $
#include "AliMpTriggerReader.h"
#include "AliLog.h"
#include "AliMpConstants.h"
#include "AliMpDataStreams.h"
#include "AliMpFiles.h"
#include "AliMpHelper.h"
#include "AliMpMotif.h"
#include "AliMpMotifPosition.h"
#include "AliMpMotifReader.h"
#include "AliMpMotifSpecial.h"
#include "AliMpMotifType.h"
#include "AliMpPCB.h"
#include "AliMpSlat.h"
#include "AliMpSlatMotifMap.h"
#include "AliMpSlatMotifMap.h"
#include "AliMpSt345Reader.h"
#include "AliMpTrigger.h"
#include "Riostream.h"
#include "TClass.h"
#include "TList.h"
#include "TObjString.h"
#include "TString.h"
#include <TArrayI.h>
#include <cstdlib>
#include <sstream>
//-----------------------------------------------------------------------------
/// \class AliMpTriggerReader
/// Read trigger slat ASCII files
/// Basically provides two methods:
/// - AliMpTrigger* ReadSlat()
/// - AliMpPCB* ReadPCB()
///
/// \author Laurent Aphecetche
//-----------------------------------------------------------------------------
/// \cond CLASSIMP
ClassImp(AliMpTriggerReader)
/// \endcond
//
// static private methods
//
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordLayer()
{
/// Keyword: LAYER
static const TString kKeywordLayer("LAYER");
return kKeywordLayer;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordScale()
{
/// Keyword: SCALE
static const TString kKeywordScale("SCALE");
return kKeywordScale;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordPcb()
{
/// Keyword : PCB
static const TString kKeywordPcb("PCB");
return kKeywordPcb;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordFlipX()
{
/// Keyword : FLIPX
static const TString kKeywordFlipX("FLIP_X");
return kKeywordFlipX;
}
//_____________________________________________________________________________
const TString& AliMpTriggerReader::GetKeywordFlipY()
{
/// Keyword : FLIPY
static const TString kKeywordFlipY("FLIP_Y");
return kKeywordFlipY;
}
//
// ctors, dtor
//
//_____________________________________________________________________________
AliMpTriggerReader::AliMpTriggerReader(AliMpSlatMotifMap* motifMap)
: TObject(),
fMotifMap(motifMap),
fLocalBoardMap()
{
///
/// Default ctor.
///
fLocalBoardMap.SetOwner(kTRUE);
}
//_____________________________________________________________________________
AliMpTriggerReader::~AliMpTriggerReader()
{
///
/// Dtor.
///
fLocalBoardMap.DeleteAll();
}
//_____________________________________________________________________________
AliMpSlat*
AliMpTriggerReader::BuildSlat(const AliMpDataStreams& dataStreams,
const char* slatName,
AliMp::PlaneType planeType,
const TList& lines,
Double_t scale)
{
/// Construct a slat from the list of lines, taking into account
/// the scale factor. The returned pointer must be deleted by the client
AliDebug(1,Form("slat %s %s scale %e",
slatName,PlaneTypeName(planeType).Data(),scale))
;
AliMpSlat* slat = new AliMpSlat(slatName, planeType);
TIter it(&lines);
// StdoutToAliDebug(3,lines.Print(););
TObjString* osline;
while ( ( osline = (TObjString*)it.Next() ) )
{
// note that at this stage lines should not be empty.
TString sline(osline->String());
TObjArray* tokens = sline.Tokenize(' ');
TString& keyword = ((TObjString*)tokens->At(0))->String();
if ( keyword == GetKeywordPcb() )
{
if ( tokens->GetEntriesFast() != 3 )
{
AliErrorClass(Form("Syntax error : expecting PCB type localboard-list"
" in following line:\n%s",sline.Data()));
delete slat;
delete tokens;
return 0;
}
TString pcbName = ((TObjString*)tokens->At(1))->String();
TObjArray* localBoardList = ((TObjString*)tokens->At(2))->String().Tokenize(',');
if ( scale != 1.0 )
{
std::ostringstream s;
s << pcbName.Data() << "x" << scale;
pcbName = s.str().c_str();
}
AliMpPCB* pcbType = ReadPCB(dataStreams, pcbName.Data());
if (!pcbType)
{
AliErrorClass(Form("Cannot read pcbType=%s",pcbName.Data()));
delete slat;
delete tokens;
return 0;
}
TArrayI allLocalBoards;
for ( Int_t ilb = 0; ilb < localBoardList->GetEntriesFast(); ++ilb)
{
TArrayI localBoardNumbers;
TString& localBoards = ((TObjString*)localBoardList->At(ilb))->String();
Ssiz_t pos = localBoards.First('-');
if ( pos < 0 )
{
pos = localBoards.Length();
}
AliMpHelper::DecodeName(localBoards(pos-1,localBoards.Length()-pos+1).Data(),
';',localBoardNumbers);
for ( int i = 0; i < localBoardNumbers.GetSize(); ++i )
{
std::ostringstream name;
name << localBoards(0,pos-1) << localBoardNumbers[i];
AliDebugClass(3,name.str().c_str());
localBoardNumbers[i] = LocalBoardNumber(dataStreams,name.str().c_str());
AliDebugClass(3,Form("LOCALBOARDNUMBER %d\n",localBoardNumbers[i]));
allLocalBoards.Set(allLocalBoards.GetSize()+1);
allLocalBoards[allLocalBoards.GetSize()-1] = localBoardNumbers[i];
if (localBoardNumbers[i] < 0 )
{
AliErrorClass(Form("Got a negative local board number in %s ? Unlikely"
" to be correct... : %s\n",slatName,name.str().c_str()));
}
}
}
AliDebug(3,"Deleting tokens");
delete tokens;
AliDebug(3,"Deleting localBoardList");
delete localBoardList;
AliDebug(3,"Adding pcb to slat");
slat->Add(*pcbType,allLocalBoards);
AliDebug(3,Form("Deleting pcbType=%p %s",pcbType,pcbName.Data()));
delete pcbType;
}
}
if ( slat->DX()== 0 || slat->DY() == 0 )
{
AliFatalClass(Form("Slat %s has invalid null size\n",slat->GetID()));
}
return slat;
}
//_____________________________________________________________________________
TString
AliMpTriggerReader::GetBoardNameFromPCBLine(const TString& s)
{
/// Decode the string to get the board name
TString boardName;
TObjArray* tokens = s.Tokenize(' ');
TString& keyword = ((TObjString*)tokens->At(0))->String();
if ( keyword == GetKeywordPcb() &&
tokens->GetEntriesFast() == 3 )
{
boardName = ((TObjString*)tokens->At(2))->String();
}
delete tokens;
return boardName;
}
//_____________________________________________________________________________
void
AliMpTriggerReader::FlipLines(const AliMpDataStreams& dataStreams,
TList& lines, Bool_t flipX, Bool_t flipY,
Int_t srcLine, Int_t destLine)
{
///
/// Change the local board names contained in lines,
/// to go from right to left, and/or
/// from top to bottom
///
if ( flipX )
{
// Simply swaps R(ight) and L(eft) in the first character of
// local board names
TObjString* oline;
TIter it(&lines);
while ( ( oline = (TObjString*)it.Next() ) )
{
TString& s = oline->String();
if ( s.Contains("RC") )
{
// Change right to left
s.ReplaceAll("RC","LC");
}
else if ( s.Contains("LC") )
{
// Change left to right
s.ReplaceAll("LC","RC");
}
}
}
if ( flipY )
{
// Change line number, according to parameters srcLine and destLine
// Note that because of road opening (for planes 3 and 4 at least),
// we loop for srcLine +-1
//
for ( Int_t line = -1; line <=1; ++line )
{
std::ostringstream src,dest;
src << "L" << srcLine+line;
dest << "L" << destLine-line;
if ( src.str() == dest.str() ) continue;
for ( Int_t i = 0; i < lines.GetSize(); ++i )
{
TObjString* oline = (TObjString*)lines.At(i);
TString& s = oline->String();
if ( !s.Contains(GetKeywordPcb()) )
{
// Only consider PCB lines.
continue;
}
if ( s.Contains(src.str().c_str()) )
{
AliDebugClass(4,Form("Replacing %s by %s in %s\n",
src.str().c_str(),dest.str().c_str(),s.Data()));
s.ReplaceAll(src.str().c_str(),dest.str().c_str());
AliDebugClass(4,s.Data());
TString boardName(GetBoardNameFromPCBLine(s));
if ( line )
{
// We must also change board numbers, with the tricky
// thing that up and down must be swapped...
// Up can only be 1 card so it must be B1
// Down must be the uppper card of the line before, so
// the biggest possible board number for this Line,Column
if (line>0)
{
// force to B1
AliDebugClass(4,Form("Forcing B1 in %s\n",s.Data()));
s.ReplaceAll(boardName(boardName.Length()-2,2),"B1");
AliDebugClass(4,s.Data());
}
else
{
// find the largest valid board number
for ( int b = 4; b>=1; --b )
{
std::ostringstream bs;
bs << boardName(0,boardName.Length()-1) << b;
if ( LocalBoardNumber(dataStreams,bs.str().c_str()) >= 0 )
{
AliDebugClass(4,Form("Replacing %s by %s in %s\n",
boardName(boardName.Length()-2,2).Data(),
Form("B%d",b),
s.Data()));
s.ReplaceAll(boardName(boardName.Length()-2,2),
Form("B%d",b));
AliDebugClass(4,s);
break;
}
}
}
// Check that the replacement we did is ok. If not,
// skip the line.
Int_t lbn = LocalBoardNumber(dataStreams,GetBoardNameFromPCBLine(s));
if ( lbn < 0 )
{
AliDebugClass(4,Form("Removing line %s\n",s.Data()));
lines.Remove(oline);
}
} // if (line)
}
}
}
}
}
//___________________________________________________________________________
Int_t
AliMpTriggerReader::IsLayerLine(const TString& sline) const
{
/// Whether sline contains LAYER keyword
if ( sline.BeginsWith(GetKeywordLayer()) )
{
return 1;
}
else
{
return 0;
}
}
//___________________________________________________________________________
Int_t
AliMpTriggerReader::DecodeFlipLine(const TString& sline,
TString& slatType2,
Bool_t& flipX, Bool_t& flipY)
{
/// Decode a line containing FLIP_X and/or FLIP_Y keywords
Ssiz_t blankPos = sline.First(' ');
if ( blankPos < 0 ) return 0;
TString keyword(sline(0,blankPos));
if ( keyword == GetKeywordFlipX() )
{
flipX = kTRUE;
} else if ( keyword == GetKeywordFlipY() )
{
flipY = kTRUE;
}
else
{
return 0;
}
slatType2 = sline(blankPos+1,sline.Length()-blankPos-1);
return 1;
}
//___________________________________________________________________________
Int_t
AliMpTriggerReader::DecodeScaleLine(const TString& sline,
Double_t& scale, TString& slatType)
{
/// Decode sline containing SCALE keyword
if ( sline(0,GetKeywordScale().Length()) == GetKeywordScale() )
{
TString tmp(sline(GetKeywordScale().Length()+1,
sline.Length()-GetKeywordScale().Length()-1));
Ssiz_t blankPos = tmp.First(' ');
if ( blankPos < 0 )
{
AliErrorClass(Form("Syntax error in slat file, should get a slatType after "
" SCALE keyword : %s\n",tmp.Data()));
return -1;
}
else
{
slatType = tmp(0,blankPos);
scale = TString(tmp(blankPos+1,tmp.Length()-blankPos-1)).Atof();
return 1;
}
}
scale = 1.0;
return 0;
}
//_____________________________________________________________________________
Int_t
AliMpTriggerReader::GetLine(const TString& slatType)
{
///
/// Assuming slatType is a 4 character string of the form XSLN
/// where X=1,2,3 or 4
/// S = R or L
/// N is the line number
/// returns N
if ( isdigit(slatType[0]) &&
( slatType[1] == 'R' || slatType[1] == 'L' ) &&
slatType[2] == 'L' )
{
return atoi(slatType(3,1).Data());
}
return -1;
}
//_____________________________________________________________________________
int
AliMpTriggerReader::LocalBoardNumber(const AliMpDataStreams& dataStreams,
const char* localBoardName)
{
/// From local board name to local board number
if ( !fLocalBoardMap.GetSize() )
{
ReadLocalBoardMapping(dataStreams);
}
TPair* pair = (TPair*)fLocalBoardMap.FindObject(localBoardName);
if (pair)
{
return atoi(((TObjString*)pair->Value())->String().Data());
}
return -1;
}
//_____________________________________________________________________________
void
AliMpTriggerReader::ReadLines(const AliMpDataStreams& dataStreams,
const char* slatType,
AliMp::PlaneType planeType,
TList& lines,
Double_t& scale,
Bool_t& flipX, Bool_t& flipY,
Int_t& srcLine, Int_t& destLine)
{
///
/// Reads in lines from file for a given slat
/// Returns the list of lines (lines), together with some global
/// information as the scale, whether to flip the lines, etc...
///
AliDebugClass(2,Form("SlatType %s Scale %e FlipX %d FlipY %d srcLine %d"
" destLine %d\n",slatType,scale,flipX,flipY,
srcLine,destLine));
istream& in
= dataStreams.
CreateDataStream(AliMpFiles::SlatFilePath(
AliMp::kStationTrigger,slatType, planeType));
char line[80];
while ( in.getline(line,80) )
{
TString sline(AliMpHelper::Normalize(line));
if ( sline.Length() == 0 || sline[0] == '#' ) continue;
Bool_t isKeywordThere =
sline.Contains(GetKeywordPcb()) ||
sline.Contains(GetKeywordLayer()) ||
sline.Contains(GetKeywordScale()) ||
sline.Contains(GetKeywordFlipX()) ||
sline.Contains(GetKeywordFlipY());
if ( !isKeywordThere )
{
AliErrorClass(Form("Got a line with no keyword : %s."
"That's not valid\n",line));
continue;
}
Double_t scale2;
TString slatType2;
Int_t isScaleLine = DecodeScaleLine(sline,scale2,slatType2);
scale *= scale2;
if ( isScaleLine < 0 )
{
AliFatalClass(Form("Syntax error near %s keyword\n",GetKeywordScale().Data()));
}
else if ( isScaleLine > 0 && slatType2 != slatType )
{
ReadLines(dataStreams,
slatType2.Data(),planeType,lines,scale,flipX,flipY,srcLine,destLine);
}
else
{
Bool_t fx(kFALSE);
Bool_t fy(kFALSE);
Int_t isFlipLine = DecodeFlipLine(sline,slatType2,fx,fy);
if ( isFlipLine )
{
if (fy)
{
srcLine = GetLine(slatType2);
destLine = GetLine(slatType);
}
flipX |= fx;
flipY |= fy;
ReadLines(dataStreams,
slatType2.Data(),planeType,lines,scale,flipX,flipY,srcLine,destLine);
}
else
{
lines.Add(new TObjString(sline.Data()));
}
}
}
delete ∈
}
//_____________________________________________________________________________
void
AliMpTriggerReader::ReadLocalBoardMapping(const AliMpDataStreams& dataStreams)
{
/// Reads the file that contains the mapping local board name <-> number
fLocalBoardMap.DeleteAll();
UShort_t mask;
istream& in
= dataStreams.
CreateDataStream(AliMpFiles::LocalTriggerBoardMapping());
char line[80];
Char_t localBoardName[20];
Int_t j,localBoardId;
UInt_t switches;
Int_t nofBoards;
while (!in.eof())
{
for (Int_t i = 0; i < 4; ++i)
if (!in.getline(line,80)) continue; //skip 4 first lines
// read mask
if (!in.getline(line,80)) break;
sscanf(line,"%hx",&mask);
// read # boards
if (!in.getline(line,80)) break;
sscanf(line,"%d",&nofBoards);
for ( Int_t i = 0; i < nofBoards; ++i )
{
if (!in.getline(line,80)) break;
sscanf(line,"%02d %19s %03d %03x", &j, localBoardName, &localBoardId, &switches);
if (localBoardId <= AliMpConstants::NofLocalBoards())
{
fLocalBoardMap.Add(new TObjString(localBoardName), new TObjString(Form("%d",localBoardId)));
AliDebugClass(10,Form("Board %s has number %d\n", localBoardName, localBoardId));
}
// skip 2 following lines
if (!in.getline(line,80)) break;
if (!in.getline(line,80)) break;
}
}
delete ∈
}
//_____________________________________________________________________________
AliMpPCB*
AliMpTriggerReader::ReadPCB(const AliMpDataStreams& dataStreams,
const char* pcbType)
{
///
/// Create a new AliMpPCB object, by reading it from file.
/// Returned pointer must be deleted by client.
AliDebugClass(2,Form("pcbType=%s\n",pcbType));
TString pcbName(pcbType);
Ssiz_t pos = pcbName.First('x');
Double_t scale = 1.0;
if ( pos > 0 )
{
scale = TString(pcbName(pos+1,pcbName.Length()-pos-1)).Atof();
pcbName = pcbName(0,pos);
}
istream& in
= dataStreams.
CreateDataStream(AliMpFiles::SlatPCBFilePath(
AliMp::kStationTrigger,pcbName));
AliMpMotifReader reader(AliMp::kStationTrigger, AliMq::kNotSt12, AliMp::kNonBendingPlane);
// note that the nonbending
// parameter is of no use for trigger, as far as reading motif is
// concerned, as all motifs are supposed to be in the same directory
// (as they are shared by bending/non-bending planes).
char line[80];
const TString kSizeKeyword("SIZES");
const TString kMotifKeyword("MOTIF");
const TString kMotifSpecialKeyword("SPECIAL_MOTIF");
AliMpPCB* pcb(0x0);
while ( in.getline(line,80) )
{
if ( line[0] == '#' ) continue;
TString sline(line);
if ( sline(0,kSizeKeyword.Length()) == kSizeKeyword )
{
std::istringstream sin(sline(kSizeKeyword.Length(),
sline.Length()-kSizeKeyword.Length()-1).Data());
float padSizeX = 0.0;
float padSizeY = 0.0;
float pcbSizeX = 0.0;
float pcbSizeY = 0.0;
sin >> padSizeX >> padSizeY >> pcbSizeX >> pcbSizeY;
if (pcb)
{
AliError("pcb not null as expected");
}
pcb = new AliMpPCB(fMotifMap,pcbType,padSizeX*scale,padSizeY*scale,
pcbSizeX*scale,pcbSizeY*scale);
}
if ( sline(0,kMotifSpecialKeyword.Length()) == kMotifSpecialKeyword )
{
std::istringstream sin(sline(kMotifSpecialKeyword.Length(),
sline.Length()-kMotifSpecialKeyword.Length()).Data());
TString sMotifSpecial;
TString sMotifType;
sin >> sMotifSpecial >> sMotifType;
TString id = reader.MotifSpecialName(sMotifSpecial,scale);
AliMpMotifSpecial* specialMotif =
dynamic_cast<AliMpMotifSpecial*>(fMotifMap->FindMotif(id));
if (!specialMotif)
{
AliDebug(1,Form("Reading motifSpecial %s (%s) from file",
sMotifSpecial.Data(),id.Data()));
AliMpMotifType* motifType = fMotifMap->FindMotifType(sMotifType.Data());
if ( !motifType)
{
AliDebug(1,Form("Reading motifType %s (%s) from file",
sMotifType.Data(),id.Data()));
motifType = reader.BuildMotifType(dataStreams,sMotifType.Data());
fMotifMap->AddMotifType(motifType);
}
else
{
AliDebug(1,Form("Got motifType %s (%s) from motifMap",
sMotifType.Data(),id.Data()));
}
specialMotif = reader.BuildMotifSpecial(dataStreams,sMotifSpecial,motifType,scale);
fMotifMap->AddMotif(specialMotif);
}
else
{
AliDebug(1,Form("Got motifSpecial %s from motifMap",sMotifSpecial.Data()));
}
if (pcb)
{
AliError("pcb not null as expected");
}
pcb = new AliMpPCB(pcbType,specialMotif);
}
if ( sline(0,kMotifKeyword.Length()) == kMotifKeyword )
{
std::istringstream sin(sline(kMotifKeyword.Length(),
sline.Length()-kMotifKeyword.Length()).Data());
TString sMotifType;
int ix;
int iy;
sin >> sMotifType >> ix >> iy;
AliMpMotifType* motifType = fMotifMap->FindMotifType(sMotifType.Data());
if ( !motifType)
{
AliDebug(1,Form("Reading motifType %s from file",sMotifType.Data()));
motifType = reader.BuildMotifType(dataStreams,sMotifType.Data());
fMotifMap->AddMotifType(motifType);
}
else
{
AliDebug(1,Form("Got motifType %s from motifMap",sMotifType.Data()));
}
if (! pcb)
{
AliError("pcb null");
continue;
}
pcb->Add(motifType,ix,iy);
}
}
delete ∈
return pcb;
}
//_____________________________________________________________________________
AliMpTrigger*
AliMpTriggerReader::ReadSlat(const AliMpDataStreams& dataStreams,
const char* slatType, AliMp::PlaneType planeType)
{
///
/// Create a new AliMpTrigger object, by reading it from file.
/// Returned object must be deleted by client.
Double_t scale = 1.0;
Bool_t flipX = kFALSE;
Bool_t flipY = kFALSE;
TList lines;
lines.SetOwner(kTRUE);
Int_t srcLine(-1);
Int_t destLine(-1);
// Read the file and its include (if any) and store the result
// in a TObjArray of TObjStrings.
ReadLines(dataStreams,
slatType,planeType,lines,scale,flipX,flipY,srcLine,destLine);
// Here some more sanity checks could be done.
// For the moment we only insure that the first line contains
// a layer keyword.
TString& firstLine = ((TObjString*)lines.First())->String();
if ( !IsLayerLine(firstLine) )
{
std::ostringstream s;
s << GetKeywordLayer();
lines.AddFirst(new TObjString(s.str().c_str()));
}
AliDebugClass(2,Form("Scale=%g\n",scale));
FlipLines(dataStreams,lines,flipX,flipY,srcLine,destLine);
// Now splits the lines in packets corresponding to different layers
// (if any), and create sub-slats.
TObjArray layers;
layers.SetOwner(kTRUE);
Int_t ilayer(-1);
TIter it(&lines);
TObjString* osline;
while ( ( osline = (TObjString*)it.Next() ) )
{
TString& s = osline->String();
if ( IsLayerLine(s) )
{
TList* list = new TList;
list->SetOwner(kTRUE);
layers.Add(list);
++ilayer;
}
else
{
((TList*)layers.At(ilayer))->Add(new TObjString(s));
}
}
AliDebugClass(2,Form("nlayers=%d\n",layers.GetEntriesFast()));
AliMpTrigger* triggerSlat = new AliMpTrigger(slatType, planeType);
for ( ilayer = 0; ilayer < layers.GetEntriesFast(); ++ilayer )
{
TList& lines1 = *((TList*)layers.At(ilayer));
std::ostringstream slatName;
slatName << slatType << "-LAYER" << ilayer;
AliMpSlat* slat = BuildSlat(dataStreams,
slatName.str().c_str(),planeType,lines1,scale);
if ( slat )
{
Bool_t ok = triggerSlat->AdoptLayer(slat);
if (!ok)
{
StdoutToAliError(cout << "could not add slat=" << endl;
slat->Print();
cout << "to the triggerSlat=" << endl;
triggerSlat->Print();
);
AliError("Slat is=");
for ( Int_t i = 0; i < slat->GetSize(); ++i )
{
AliMpPCB* pcb = slat->GetPCB(i);
AliError(Form("ERR pcb %d size %e,%e (unscaled is %e,%e)",
i,pcb->DX()*2,pcb->DY()*2,
pcb->DX()*2/scale,pcb->DY()*2/scale));
}
AliError("TriggerSlat is=");
for ( Int_t j = 0; j < triggerSlat->GetSize(); ++j )
{
AliMpSlat* slat1 = triggerSlat->GetLayer(j);
AliError(Form("Layer %d",j));
for ( Int_t i = 0; i < slat1->GetSize(); ++i )
{
AliMpPCB* pcb = slat1->GetPCB(i);
AliError(Form("ERR pcb %d size %e,%e (unscaled is %e,%e)",
i,pcb->DX()*2,pcb->DY()*2,
pcb->DX()*2/scale,pcb->DY()*2/scale));
}
}
StdoutToAliError(fMotifMap->Print(););
}
}
else
{
AliErrorClass(Form("Could not read %s\n",slatName.str().c_str()));
delete triggerSlat;
return 0;
}
}
return triggerSlat;
}
| 29.952116
| 93
| 0.57921
|
AllaMaevskaya
|
ad8edf10042df96058e2b21cb955b9ee51cf9501
| 1,710
|
cpp
|
C++
|
GRUT Engine/src/Scene/SceneManager.cpp
|
lggmonclar/GRUT
|
b7d06fd314141395b54a86122374f4f955f653cf
|
[
"MIT"
] | 2
|
2019-02-14T03:20:59.000Z
|
2019-03-12T01:34:59.000Z
|
GRUT Engine/src/Scene/SceneManager.cpp
|
lggmonclar/GRUT
|
b7d06fd314141395b54a86122374f4f955f653cf
|
[
"MIT"
] | null | null | null |
GRUT Engine/src/Scene/SceneManager.cpp
|
lggmonclar/GRUT
|
b7d06fd314141395b54a86122374f4f955f653cf
|
[
"MIT"
] | null | null | null |
#include "grutpch.h"
#include "Scene.h"
#include "Core/Parallelism/FrameParams.h"
#include "Core/Memory/MemoryManager.h"
#include "Core/Memory/ObjectHandle.h"
#include "SceneManager.h"
#include "Core/Jobs/JobManager.h"
#include "Components/Rendering/Camera.h"
namespace GRUT {
void SceneManager::Initialize() {
auto currScene = SceneManager::Instance().m_currentScene = MemoryManager::Instance().AllocOnFreeList<Scene>();
auto obj = SceneManager::Instance().m_currentScene->CreateGameObject();
obj->name = "Main Camera";
obj->AddComponent<Camera>();
currScene->mainCamera = obj;
currScene->m_handle = currScene;
}
void SceneManager::FixedUpdate(float p_deltaTime) {
m_currentScene->FixedUpdate(p_deltaTime);
}
void SceneManager::Update(FrameParams& p_prevFrame, FrameParams& p_currFrame) {
p_currFrame.updateJob = JobManager::Instance().KickJob([&]() {
JobManager::Instance().WaitForJobs({ p_currFrame.physicsJob, p_prevFrame.updateJob });
frameIndex = p_currFrame.index;
auto jobs = m_currentScene->Update(p_prevFrame, p_currFrame);
JobManager::Instance().WaitForJobs(jobs);
//Handle deferred object destructions
Scene::GetCurrent()->DestroyScheduledGameObjects();
});
}
ObjectHandle<GameObject> SceneManager::AllocateGameObject() {
return MemoryManager::Instance().AllocOnFreeList<GameObject>();
}
void SceneManager::FreeGameObject(GameObject* obj) {
MemoryManager::Instance().FreeFromFreeList(obj);
}
SceneManager::~SceneManager() {
}
}
| 36.382979
| 118
| 0.65848
|
lggmonclar
|
74e8170d79d8f40103d188b39789cda88b0b3f79
| 3,056
|
cpp
|
C++
|
plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | null | null | null |
plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | null | null | null |
plugins/core/qPCL/PclUtils/filters/dialogs/MLSDialog.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | 1
|
2019-02-03T12:19:42.000Z
|
2019-02-03T12:19:42.000Z
|
//##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: qPCL #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: Luca Penasa #
//# #
//##########################################################################
//
#include "MLSDialog.h"
#include "../MLSSmoothingUpsampling.h"
//PCL
//#include <pcl/surface/mls.h>
//Qt
#include <QVariant>
MLSDialog::MLSDialog(QWidget *parent)
: QDialog(parent)
, Ui::MLSDialog()
{
setupUi(this);
updateCombo();
connect (this->upsampling_method, SIGNAL(currentIndexChanged(QString)), this, SLOT(activateMenu(QString)) );
connect (this->search_radius, SIGNAL(valueChanged(double)), this, SLOT(updateSquaredGaussian(double)) );
deactivateAllMethods();
}
void MLSDialog::updateCombo()
{
this->upsampling_method->clear();
this->upsampling_method->addItem(QString("None"), QVariant(MLSParameters::NONE));
this->upsampling_method->addItem(QString("Sample Local Plane"), QVariant(MLSParameters::SAMPLE_LOCAL_PLANE));
this->upsampling_method->addItem(QString("Random Uniform Density"), QVariant(MLSParameters::RANDOM_UNIFORM_DENSITY));
this->upsampling_method->addItem(QString("Voxel Grid Dilation"), QVariant(MLSParameters::VOXEL_GRID_DILATION));
}
void MLSDialog::activateMenu(QString name)
{
deactivateAllMethods();
if (name == "Sample Local Plane")
{
this->sample_local_plane_method->setEnabled(true);
}
else if (name == "Random Uniform Density")
{
this->random_uniform_density_method->setEnabled(true);
}
else if (name == "Voxel Grid Dilation")
{
this->voxel_grid_dilation_method->setEnabled(true);
}
else
{
deactivateAllMethods();
}
}
void MLSDialog::deactivateAllMethods()
{
this->sample_local_plane_method->setEnabled(false);
this->random_uniform_density_method->setEnabled(false);
this->voxel_grid_dilation_method->setEnabled(false);
}
void MLSDialog::toggleMethods(bool status)
{
if (!status)
deactivateAllMethods();
}
void MLSDialog::updateSquaredGaussian(double radius)
{
this->squared_gaussian_parameter->setValue(radius * radius);
}
| 34.337079
| 118
| 0.578534
|
ohanlonl
|
74e983c73966096c53b2032c6bc0a7448a9b688b
| 1,766
|
cpp
|
C++
|
ToneArmEngine/OpenGLMaterial.cpp
|
GDAP/ToneArmEngine
|
85da7b8da30c714891bdadfe824bae1bbdd49f94
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
ToneArmEngine/OpenGLMaterial.cpp
|
GDAP/ToneArmEngine
|
85da7b8da30c714891bdadfe824bae1bbdd49f94
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
ToneArmEngine/OpenGLMaterial.cpp
|
GDAP/ToneArmEngine
|
85da7b8da30c714891bdadfe824bae1bbdd49f94
|
[
"Zlib",
"BSD-2-Clause"
] | null | null | null |
#include "OpenGLMaterial.h"
#include "OpenGLProgram.h"
namespace vgs {
/*
========
OpenGLMaterial::OpenGLMaterial
OpenGLMaterial default constructor
========
*/
OpenGLMaterial::OpenGLMaterial( void ) :
m_requiredFeatures( ProgramFeatures::NONE )
{}
/*
========
OpenGLMaterial::~OpenGLMaterial
OpenGLMaterial destructor
========
*/
OpenGLMaterial::~OpenGLMaterial( void )
{}
/*
========
OpenGLMaterial::OpenGLMaterial
OpenGLMaterial copy constructor
========
*/
OpenGLMaterial::OpenGLMaterial( const OpenGLMaterial& orig ) :
Material( orig )
{
m_requiredFeatures = orig.m_requiredFeatures;
}
/*
========
Material::CreateMaterialWithColor
Creates a material with the passed in diffuse color
========
*/
OpenGLMaterial* OpenGLMaterial::CreateMaterialWithColor( const glm::vec3& diffColor ) {
OpenGLMaterial* matPtr = new OpenGLMaterial();
if ( matPtr ) {
matPtr->m_diffuseColor = diffColor;
return matPtr;
} else {
return NULL;
}
}
void OpenGLMaterial::AddTexture( Texture* texture ) {
Material::AddTexture( texture );
if ( texture->IsDiffuseMap() ) {
m_requiredFeatures = ( ProgramFeatures::Value )( m_requiredFeatures | ProgramFeatures::DIFFUSE_TEXTURE );
} else if ( texture->IsNormalMap() ) {
m_requiredFeatures = ( ProgramFeatures::Value )( m_requiredFeatures | ProgramFeatures::NORMAL_MAP );
} else if ( texture->IsSpecularMap() ) {
m_requiredFeatures = ( ProgramFeatures::Value )( m_requiredFeatures | ProgramFeatures::SPEC_MAP );
}
}
void OpenGLMaterial::BindMaterial( void ) {
Material::BindMaterial();
OpenGLProgram* prog = OpenGLProgramManager::GetInstance()->GetActiveProgram();
prog->SetUniform( "u_DiffuseColor", m_diffuseColor );
}
void OpenGLMaterial::UnbindMaterial( void ) {
Material::UnbindMaterial();
}
}
| 23.236842
| 107
| 0.722537
|
GDAP
|
74e98437f534d06652bcc354c66ceadfd37a9e60
| 1,729
|
cpp
|
C++
|
ACM-ICPC/1238.cpp
|
KimBoWoon/ACM-ICPC
|
146c36999488af9234d73f7b4b0c10d78486604f
|
[
"MIT"
] | null | null | null |
ACM-ICPC/1238.cpp
|
KimBoWoon/ACM-ICPC
|
146c36999488af9234d73f7b4b0c10d78486604f
|
[
"MIT"
] | null | null | null |
ACM-ICPC/1238.cpp
|
KimBoWoon/ACM-ICPC
|
146c36999488af9234d73f7b4b0c10d78486604f
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#pragma warning(disable:4996)
#define INF 987654321
vector<pair<int, int> > v[10001], rv[10001];
// first는 거리, second는 다음 정점.
priority_queue<pair<int, int> > q;
int dist[10001], rdist[10001];
int n, m, x, maxDist;
void dijkstra(vector<pair<int, int> > v[10001], int *dist) {
dist[x] = 0;
q.push(make_pair(0, x));
while (!q.empty()) {
pair<int, int> value = q.top();
q.pop();
int current = value.second;
int cost = -value.first;
// 현재 정점까지의 거리가 더 짧은 경우 무시.
if (dist[current] < cost) {
continue;
}
for (int i = 0; i < v[current].size(); i++) {
int next = v[current][i].second;
int nextCost = v[current][i].first + dist[current];
if (dist[next] > nextCost) {
dist[next] = nextCost;
q.push(make_pair(-nextCost, next));
}
}
}
}
int main(void) {
scanf("%d %d %d", &n, &m, &x);
for (int i = 0; i < m; i++) {
int from, to, cost;
scanf("%d %d %d", &from, &to, &cost);
v[from].push_back(make_pair(cost, to));
rv[to].push_back(make_pair(cost, from));
}
// 시작 정점부터 next 정점까지의 최단거리를 빠르게 참조 및 갱신하기 위한 배열.
for (int i = 0; i < 10001; i++) {
dist[i] = rdist[i] = INF;
}
dijkstra(v, dist);
dijkstra(rv, rdist);
/*for (int i = 1; i <= n; i++) {
if (dist[i] == INF) {
printf("INF\n");
}
else {
printf("%d\n", dist[i]);
}
}
for (int i = 1; i <= n; i++) {
if (rdist[i] == INF) {
printf("INF\n");
}
else {
printf("%d\n", rdist[i]);
}
}*/
for (int i = 1; i <= n; i++) {
maxDist = max(maxDist, dist[i] + rdist[i]);
}
printf("%d\n", maxDist);
return 0;
}
| 19.647727
| 61
| 0.526894
|
KimBoWoon
|
74eb73259fc55722766192f5a0a1c89e6033143c
| 4,864
|
cpp
|
C++
|
src/fume/vr_field.cpp
|
ekhidbor/FUMe
|
de50357efcb6dbfd0114802bc72ad316daca0ce3
|
[
"CC0-1.0"
] | null | null | null |
src/fume/vr_field.cpp
|
ekhidbor/FUMe
|
de50357efcb6dbfd0114802bc72ad316daca0ce3
|
[
"CC0-1.0"
] | null | null | null |
src/fume/vr_field.cpp
|
ekhidbor/FUMe
|
de50357efcb6dbfd0114802bc72ad316daca0ce3
|
[
"CC0-1.0"
] | null | null | null |
/**
* This file is a part of the FUMe project.
*
* To the extent possible under law, the person who associated CC0 with
* FUMe has waived all copyright and related or neighboring rights
* to FUMe.
*
* You should have received a copy of the CC0 legalcode along with this
* work. If not, see http://creativecommons.org/publicdomain/zero/1.0/.
*/
// std
#include <cstdint>
#include <array>
#include <unordered_map>
#include <algorithm>
#include <iterator>
// boost
#include "boost/bimap.hpp"
// local public
#include "mc3msg.h"
#include "mcstatus.h"
// local private
#include "fume/vr_field.h"
using std::array;
using std::unordered_map;
using std::copy;
using boost::bimap;
namespace std
{
template<>
struct hash<std::array<char, 2u> >
{
typedef size_t result_type;
typedef std::array<char, 2u> argument_type;
result_type operator()( const argument_type& val )
{
const size_t v1 = val[0];
const size_t v2 = val[1];
return (v2 << 8) | v1;
}
};
}
namespace fume
{
typedef unordered_map<int, uint8_t> vr_size_map_t;
typedef bimap<int, vr_value_t> vr_value_map_t;
static const vr_size_map_t::value_type VR_SIZE_VALUES[] =
{
{ AE, 2u },
{ AS, 2u },
{ CS, 2u },
{ DA, 2u },
{ DS, 2u },
{ DT, 2u },
{ IS, 2u },
{ LO, 2u },
{ LT, 2u },
{ PN, 2u },
{ SH, 2u },
{ ST, 2u },
{ TM, 2u },
{ UC, 4u },
{ UR, 4u },
{ UT, 4u },
{ UI, 2u },
{ SS, 2u },
{ US, 2u },
{ AT, 2u },
{ SL, 2u },
{ UL, 2u },
{ FL, 2u },
{ FD, 2u },
{ UNKNOWN_VR, 4u },
{ OB, 4u },
{ OW, 4u },
{ OD, 4u },
{ OF, 4u },
{ SQ, 4u },
{ OL, 4u }
};
// Disable "extra braces" warning message. The extra braces
// are unnecessary
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-braces"
static const vr_value_map_t::value_type VR_VALUES[] =
{
{ AE, { 'A', 'E' } },
{ AS, { 'A', 'S' } },
{ CS, { 'C', 'S' } },
{ DA, { 'D', 'A' } },
{ DS, { 'D', 'S' } },
{ DT, { 'D', 'T' } },
{ IS, { 'I', 'S' } },
{ LO, { 'L', 'O' } },
{ LT, { 'L', 'T' } },
{ PN, { 'P', 'N' } },
{ SH, { 'S', 'H' } },
{ ST, { 'S', 'T' } },
{ TM, { 'T', 'M' } },
{ UC, { 'U', 'C' } },
{ UR, { 'U', 'R' } },
{ UT, { 'U', 'T' } },
{ UI, { 'U', 'I' } },
{ SS, { 'S', 'S' } },
{ US, { 'U', 'S' } },
{ AT, { 'A', 'T' } },
{ SL, { 'S', 'L' } },
{ UL, { 'U', 'L' } },
{ FL, { 'F', 'L' } },
{ FD, { 'F', 'D' } },
{ UNKNOWN_VR, { 'U', 'N' } },
{ OB, { 'O', 'B' } },
{ OW, { 'O', 'W' } },
{ OD, { 'O', 'D' } },
{ OF, { 'O', 'F' } },
{ SQ, { 'S', 'Q' } },
{ OL, { 'O', 'L' } }
};
#pragma GCC diagnostic pop
static const vr_value_map_t& vr_value_map()
{
static const vr_value_map_t ret( begin( VR_VALUES ), end( VR_VALUES ) );
return ret;
}
static const vr_size_map_t& vr_size_map()
{
static const vr_size_map_t ret( begin( VR_SIZE_VALUES ),
end( VR_SIZE_VALUES ) );
return ret;
}
static MC_STATUS get_vr_field_size( MC_VR vr, uint8_t& field_size )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
const vr_size_map_t::const_iterator itr = vr_size_map().find( vr );
if( itr != vr_size_map().cend() )
{
field_size = itr->second;
ret = MC_NORMAL_COMPLETION;
}
else
{
ret = MC_INVALID_VR_CODE;
}
return ret;
}
MC_STATUS get_vr_field_value( MC_VR vr, vr_value_t& value, uint8_t& field_size )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
const vr_value_map_t::left_map::const_iterator itr =
vr_value_map().left.find( vr );
if( itr != vr_value_map().left.end() )
{
copy( itr->second.cbegin(), itr->second.cend(), value.begin() );
ret = get_vr_field_size( vr, field_size );
}
else
{
ret = MC_INVALID_VR_CODE;
}
return ret;
}
MC_STATUS get_vr_code( const vr_value_t& value, MC_VR& vr, uint8_t& field_size )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
const vr_value_map_t::right_map::const_iterator itr =
vr_value_map().right.find( value );
if( itr != vr_value_map().right.end() )
{
vr = static_cast<MC_VR>( itr->second );
ret = get_vr_field_size( vr, field_size );
}
else
{
ret = MC_INVALID_VR_CODE;
}
return ret;
}
}
| 23.384615
| 80
| 0.4706
|
ekhidbor
|
74efc4e4a78fc6b3dcbb6d3bcfb4398025191cbe
| 1,375
|
cpp
|
C++
|
Uebungsaufgaben/ListenStrukturen/stack.cpp
|
TEL21D/Informatik2
|
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
|
[
"MIT"
] | null | null | null |
Uebungsaufgaben/ListenStrukturen/stack.cpp
|
TEL21D/Informatik2
|
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
|
[
"MIT"
] | null | null | null |
Uebungsaufgaben/ListenStrukturen/stack.cpp
|
TEL21D/Informatik2
|
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
struct element
{
/* data */
int _data;
element *_next;
element(int data = 0, element *next = nullptr)
{
_data = data;
_next = next;
}
bool empty()
{
return _next == nullptr;
}
};
struct s_stack
{
// Member Variablen
int _size = 0;
element *_head = new element();
// Methoden
void push(int data)
{
element *newEl = new element(data, _head);
_head = newEl;
_size++;
}
int pop()
{
/**
* gibt das oberste Elemente zurueck und entfernt es
*
*/
// pruefen ob der Stack Element hat ansonsten `-1`
if (_size > 0)
{
int temp = _head->_data;
element * curr_head = _head;
_head = curr_head->_next;
delete curr_head;
_size--;
return temp;
}
return -1;
}
int top()
{
if (_size > 0)
return _head->_data;
return -1;
}
int size()
{
return _size;
}
void print()
{
element * curr = _head;
while (!curr->empty())
{
std::cout << curr->_data << " ";
curr = curr->_next;
}
std::cout << "\n";
}
};
int main(int argc, char const *argv[])
{
s_stack stack;
std::cout << stack.pop() << "\n";
stack.push(3);
stack.push(2);
stack.push(1);
stack.push(6);
stack.print();
std::cout << stack.pop() << "\n";
stack.print();
return 0;
}
| 14.945652
| 56
| 0.528727
|
TEL21D
|
74f0c3868289fe5fece793fb2f91691eacd80877
| 3,136
|
cc
|
C++
|
dash/src/util/Trace.cc
|
RuhanDev/dash
|
c56193149c334e552df6f8439c3fb1510048b7f1
|
[
"BSD-3-Clause"
] | 1
|
2019-05-19T20:31:20.000Z
|
2019-05-19T20:31:20.000Z
|
dash/src/util/Trace.cc
|
RuhanDev/dash
|
c56193149c334e552df6f8439c3fb1510048b7f1
|
[
"BSD-3-Clause"
] | null | null | null |
dash/src/util/Trace.cc
|
RuhanDev/dash
|
c56193149c334e552df6f8439c3fb1510048b7f1
|
[
"BSD-3-Clause"
] | null | null | null |
#include <dash/util/Trace.h>
#include <dash/util/Config.h>
#include <dash/Team.h>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <unistd.h>
std::map<std::string, dash::util::TraceStore::trace_events_t>
dash::util::TraceStore::_traces
= {{ }};
bool dash::util::TraceStore::_trace_enabled
= false;
bool dash::util::TraceStore::on()
{
_trace_enabled = dash::util::Config::get<bool>("DASH_ENABLE_TRACE");
return _trace_enabled;
}
void dash::util::TraceStore::off()
{
_trace_enabled = false;
}
bool dash::util::TraceStore::enabled()
{
return _trace_enabled == true;
}
void dash::util::TraceStore::clear()
{
_traces.clear();
}
void dash::util::TraceStore::clear(const std::string & context)
{
_traces[context].clear();
}
void dash::util::TraceStore::add_context(const std::string & context)
{
if (_traces.count(context) == 0) {
_traces[context] = trace_events_t();
}
}
dash::util::TraceStore::trace_events_t &
dash::util::TraceStore::context_trace(const std::string & context)
{
return _traces[context];
}
void dash::util::TraceStore::write(std::ostream & out, bool printHeader)
{
if (!dash::util::Config::get<bool>("DASH_ENABLE_TRACE")) {
return;
}
std::ostringstream os;
auto unit = dash::Team::GlobalUnitID();
for (auto context_traces : _traces) {
std::string context = context_traces.first;
trace_events_t & events = context_traces.second;
// Master prints CSV headers:
if (printHeader && unit == 0) {
os << "-- [TRACE] "
<< std::setw(15) << "context" << ","
<< std::setw(5) << "unit" << ","
<< std::setw(15) << "start" << ","
<< std::setw(15) << "end" << ","
<< std::setw(12) << "state"
<< std::endl;
}
for (auto state_timespan : events) {
auto start = state_timespan.start;
auto end = state_timespan.end;
auto state = state_timespan.state;
os << "-- [TRACE] "
<< std::setw(15) << std::fixed << context << ", "
<< std::setw(5) << std::fixed << unit << ", "
<< std::setw(15) << std::fixed << start << ", "
<< std::setw(15) << std::fixed << end << ", "
<< std::setw(12) << std::fixed << state
<< std::endl;
}
}
out << os.str();
}
void dash::util::TraceStore::write(
const std::string & filename,
const std::string & path)
{
if (!dash::util::Config::get<bool>("DASH_ENABLE_TRACE")) {
return;
}
std::string trace_log_dir;
if (dash::util::Config::is_set("DASH_TRACE_LOG_PATH")) {
trace_log_dir = dash::util::Config::get<std::string>(
"DASH_TRACE_LOG_PATH");
if (path.length() > 0) {
trace_log_dir += "/";
}
}
trace_log_dir += path;
auto unit = dash::Team::GlobalUnitID();
std::ostringstream fn;
fn << trace_log_dir << "/"
<< "u" << std::setfill('0') << std::setw(5) << unit
<< "." << filename;
std::string trace_file = fn.str();
std::ofstream out(trace_file);
write(out);
out.close();
}
| 24.310078
| 72
| 0.583227
|
RuhanDev
|
74f1e7388a837ed992b18edab72ab69646eba10a
| 266
|
cpp
|
C++
|
Chess_2.1.1/Pieces/Empty.cpp
|
jeremy-pouzargues/Projet-Tutor-
|
fa20a5887235f754424087ea776efe608f9ec411
|
[
"CC-BY-4.0"
] | null | null | null |
Chess_2.1.1/Pieces/Empty.cpp
|
jeremy-pouzargues/Projet-Tutor-
|
fa20a5887235f754424087ea776efe608f9ec411
|
[
"CC-BY-4.0"
] | null | null | null |
Chess_2.1.1/Pieces/Empty.cpp
|
jeremy-pouzargues/Projet-Tutor-
|
fa20a5887235f754424087ea776efe608f9ec411
|
[
"CC-BY-4.0"
] | null | null | null |
#include <iostream>
#include "Pieces/Empty.h"
using namespace std;
Empty::Empty(const pairCoord & coord)
{
myCarac = KEMPTY;
myCoord = coord;
myColor = empty;
myName = "Empty";
myValue = 0;
myInitCoord = coord;
canCastling = false;
}
| 15.647059
| 37
| 0.631579
|
jeremy-pouzargues
|
74f70f7eebb5748585b252b47529fc89a447600e
| 1,558
|
cpp
|
C++
|
Hdu/hdu4738.cpp
|
Tunghohin/Competitive_coding
|
879238605d5525cda9fd0cfa1155ba67959179a6
|
[
"MIT"
] | 2
|
2021-09-06T08:34:00.000Z
|
2021-11-22T14:52:41.000Z
|
Hdu/hdu4738.cpp
|
Tunghohin/Competitive_coding
|
879238605d5525cda9fd0cfa1155ba67959179a6
|
[
"MIT"
] | null | null | null |
Hdu/hdu4738.cpp
|
Tunghohin/Competitive_coding
|
879238605d5525cda9fd0cfa1155ba67959179a6
|
[
"MIT"
] | null | null | null |
#include <cstring>
#include <iostream>
using namespace std;
const int N = 1010, M = 200;
struct edge
{
int to, next, val;
}e[M];
int head[N], tot = 0;
void add_edge(int from, int to, int val)
{
e[++tot].to = to;
e[tot].val = val;
e[tot].next = head[from];
head[from] = tot;
}
int inv_edge(int i)
{
return i - ((i ^ 1) - i);
}
int dfn[N], low[N], timestamp = 0;
bool is_bridge[M];
void tarjan(int u, int from)
{
dfn[u] = low[u] = ++timestamp;
for (int i = head[u]; i; i = e[i].next)
{
int j = e[i].to;
if (!dfn[j])
{
tarjan(j, i);
low[u] = min(low[u], low[j]);
if (dfn[u] < low[j]) is_bridge[i] = is_bridge[inv_edge(i)] = true;
}
else if (i != (inv_edge(from))) low[u] = min(low[u], dfn[j]);
}
}
void init(int n)
{
for (int i = 0; i <= n; i++)
{
dfn[i] = low[i] = 0;
head[i] = 0;
}
timestamp = tot = 0;
memset(is_bridge, false, sizeof(is_bridge));
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int n, m;
while (cin >> n >> m, n || m)
{
init(n);
for (int i = 1; i <= m; i++)
{
int a, b, v;
cin >> a >> b >> v;
add_edge(a, b, v), add_edge(b, a, v);
}
int cnt = 0;
for (int i = 1; i <= n; i++)
{
if (!dfn[i]) tarjan(i, -1), cnt++;
}
if (cnt > 1)
{
cout << 0 << '\n';
continue;
}
int res = 0x3f3f3f3f;
for (int i = 1; i <= tot; i += 2)
{
if (is_bridge[i])
{
res = min(res, e[i].val);
}
}
if (res == 0x3f3f3f3f) cout << -1 << '\n';
else if (res == 0) cout << 1 << '\n';
else cout << res << '\n';
}
}
| 15.126214
| 69
| 0.497433
|
Tunghohin
|
74f72855523f3b8a69ece22a604780126cb0d917
| 10,662
|
cpp
|
C++
|
src/ui-win/light/LightSpillCust.cpp
|
steptosky/3DsMax-X-Obj-Exporter
|
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
|
[
"BSD-3-Clause"
] | 20
|
2017-07-07T06:07:30.000Z
|
2022-03-09T12:00:57.000Z
|
src/ui-win/light/LightSpillCust.cpp
|
steptosky/3DsMax-X-Obj-Exporter
|
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
|
[
"BSD-3-Clause"
] | 28
|
2017-07-07T06:08:27.000Z
|
2022-03-09T12:09:23.000Z
|
src/ui-win/light/LightSpillCust.cpp
|
steptosky/3DsMax-X-Obj-Exporter
|
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
|
[
"BSD-3-Clause"
] | 7
|
2018-01-24T19:43:22.000Z
|
2020-01-06T00:05:40.000Z
|
/*
** Copyright(C) 2017, StepToSky
**
** 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 StepToSky 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.
**
** Contacts: www.steptosky.com
*/
#include "LightSpillCust.h"
#pragma warning(push, 0)
#include <3dsmaxport.h>
#pragma warning(pop)
#include "resource/resource.h"
#include "ui-win/Utils.h"
#include "resource/ResHelper.h"
#include "presenters/Datarefs.h"
namespace ui {
namespace win {
/**************************************************************************************************/
//////////////////////////////////////////* Static area *///////////////////////////////////////////
/**************************************************************************************************/
INT_PTR CALLBACK LightSpillCust::panelProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
LightSpillCust * theDlg;
if (msg == WM_INITDIALOG) {
theDlg = reinterpret_cast<LightSpillCust*>(lParam);
DLSetWindowLongPtr(hWnd, lParam);
theDlg->initWindow(hWnd);
}
else if (msg == WM_DESTROY) {
theDlg = DLGetWindowLongPtr<LightSpillCust*>(hWnd);
theDlg->destroyWindow(hWnd);
}
else {
theDlg = DLGetWindowLongPtr<LightSpillCust *>(hWnd);
if (!theDlg) {
return FALSE;
}
}
//--------------------------------------
switch (msg) {
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case IDC_BTN_DATAREF: {
MSTR str;
Utils::getText(theDlg->cEdtDataRef, str);
str = presenters::Datarefs::selectData(str);
theDlg->cEdtDataRef->SetText(str);
theDlg->mData->setDataRef(xobj::fromMStr(str));
theDlg->eventParamChanged(true);
break;
}
default: break;
}
break;
}
case WM_CUSTEDIT_ENTER: {
switch (LOWORD(wParam)) {
case IDC_EDIT_DATAREF: {
theDlg->mData->setDataRef(sts::toMbString(Utils::getText(theDlg->cEdtDataRef)));
theDlg->eventParamChanged(true);
break;
}
default: break;
}
break;
}
case CC_SPINNER_CHANGE: {
switch (LOWORD(wParam)) {
case IDC_R_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setRed(theDlg->mSpnR->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_G_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setGreen(theDlg->mSpnG->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_B_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setBlue(theDlg->mSpnB->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_A_SPIN: {
xobj::Color color = theDlg->mData->color();
color.setAlpha(theDlg->mSpnA->GetFVal());
theDlg->mData->setColor(color);
theDlg->eventParamChanged(true);
break;
}
case IDC_SIZE_SPIN: {
theDlg->mData->setSize(theDlg->mSpnSize->GetFVal());
theDlg->eventParamChanged(true);
break;
}
default: break;
}
break;
}
default: break;
}
return FALSE;
}
/**************************************************************************************************/
////////////////////////////////////* Constructors/Destructor */////////////////////////////////////
/**************************************************************************************************/
LightSpillCust::LightSpillCust() {
mData = nullptr;
}
LightSpillCust::~LightSpillCust() {
LightSpillCust::destroy();
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void LightSpillCust::show(xobj::ObjLightSpillCust * inData) {
mData = inData;
toWindow();
mHwnd.show();
}
void LightSpillCust::hide() {
mHwnd.hide();
}
void LightSpillCust::create(HWND inParent) {
assert(inParent);
mHwnd.setup(CreateDialogParam(ResHelper::hInstance,
MAKEINTRESOURCE(IDD_ROLL_LIGHT_SPILLCUST_OBJ),
inParent, panelProc,
reinterpret_cast<LPARAM>(this)));
assert(mHwnd);
}
void LightSpillCust::destroy() {
assert(mHwnd);
DestroyWindow(mHwnd.hwnd());
mHwnd.release();
mData = nullptr;
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void LightSpillCust::initWindow(HWND hWnd) {
mSpnR = SetupFloatSpinner(hWnd, IDC_R_SPIN, IDC_R_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnG = SetupFloatSpinner(hWnd, IDC_G_SPIN, IDC_G_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnB = SetupFloatSpinner(hWnd, IDC_B_SPIN, IDC_B_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnA = SetupFloatSpinner(hWnd, IDC_A_SPIN, IDC_A_EDIT, 0.0f, 1.0f, 0.5f, 0.1f);
mSpnSize = SetupFloatSpinner(hWnd, IDC_SIZE_SPIN, IDC_SIZE_EDIT, 0.0f, 100.0f, 1.0f, 0.1f);
cBtnDataRef.setup(hWnd, IDC_BTN_DATAREF);
cEdtDataRef = GetICustEdit(GetDlgItem(hWnd, IDC_EDIT_DATAREF));
assert(mSpnR);
assert(mSpnG);
assert(mSpnB);
assert(mSpnA);
assert(mSpnSize);
assert(cEdtDataRef);
assert(cBtnDataRef);
}
void LightSpillCust::destroyWindow(HWND /*hWnd*/) {
ReleaseISpinner(mSpnR);
ReleaseISpinner(mSpnG);
ReleaseISpinner(mSpnB);
ReleaseISpinner(mSpnA);
ReleaseISpinner(mSpnSize);
cBtnDataRef.release();
ReleaseICustEdit(cEdtDataRef);
}
void LightSpillCust::toWindow() {
if (mData) {
enableControls();
const xobj::Color & color = mData->color();
mSpnR->SetValue(color.red(), FALSE);
mSpnG->SetValue(color.green(), FALSE);
mSpnB->SetValue(color.blue(), FALSE);
mSpnA->SetValue(color.alpha(), FALSE);
mSpnSize->SetValue(mData->size(), FALSE);
cEdtDataRef->SetText(xobj::toMStr(mData->dataRef()));
}
else {
disableControls();
}
}
void LightSpillCust::toData() {
xobj::Color color(mSpnR->GetFVal(), mSpnG->GetFVal(), mSpnB->GetFVal(), mSpnA->GetFVal());
mData->setColor(color);
mData->setSize(mSpnSize->GetFVal());
mData->setDataRef(sts::toMbString(Utils::getText(cEdtDataRef)));
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void LightSpillCust::enableControls() {
mSpnR->Enable();
mSpnG->Enable();
mSpnB->Enable();
mSpnA->Enable();
mSpnSize->Enable();
cBtnDataRef.enable();
cEdtDataRef->Enable();
}
void LightSpillCust::disableControls() {
mSpnR->Disable();
mSpnG->Disable();
mSpnB->Disable();
mSpnA->Disable();
mSpnSize->Disable();
cBtnDataRef.disable();
cEdtDataRef->Disable();
}
/********************************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/********************************************************************************************************/
}
}
| 39.488889
| 110
| 0.450291
|
steptosky
|
74f880678a1f202c00c1f5643fcb9c6449eec575
| 699
|
cpp
|
C++
|
saori.cpp
|
Taromati2/OICQ-saori
|
179ade6088df59ad985909da8eb82161c46902c3
|
[
"WTFPL"
] | null | null | null |
saori.cpp
|
Taromati2/OICQ-saori
|
179ade6088df59ad985909da8eb82161c46902c3
|
[
"WTFPL"
] | null | null | null |
saori.cpp
|
Taromati2/OICQ-saori
|
179ade6088df59ad985909da8eb82161c46902c3
|
[
"WTFPL"
] | null | null | null |
#include <iostream>
// 使用静态库必须要在引入 mirai.h 前定义这个宏
#define MIRAICPP_STATICLIB
#include <mirai.h>
int main()
{
using namespace std;
using namespace Cyan;
using namespace SSTP_link_n;
system("chcp 65001");
SSTP_link_t linker({{L"Charset",L"UTF-8"},{L"Sender",L"OICQ-saori"}});
MiraiBot bot("127.0.0.1", 539);
bot.Auth("INITKEY7A3O1a9v", 1589588851_qq);
cout << "成功登录 bot" << endl;
GroupConfig group_config = bot.GetGroupConfig(1029259687_gid);
group_config.Name = "New Name 2";
bot.SetGroupConfig(1029259687_gid, group_config);
cout << group_config.Name << endl;
// 记录轮询事件时的错误
bot.EventLoop([](const char* errMsg)
{
cout << "获取事件时出错: " << errMsg << endl;
});
return 0;
}
| 18.394737
| 71
| 0.692418
|
Taromati2
|
2d0043b6fa999d1f02a31bcbaa29ec9b6160ace6
| 1,229
|
hpp
|
C++
|
lib/xpath_ctxt.hpp
|
timeout/xml_named_entity_miner
|
0d3c6f59b7cb1c2f585b25d86eb0cc8a6a532839
|
[
"0BSD"
] | null | null | null |
lib/xpath_ctxt.hpp
|
timeout/xml_named_entity_miner
|
0d3c6f59b7cb1c2f585b25d86eb0cc8a6a532839
|
[
"0BSD"
] | null | null | null |
lib/xpath_ctxt.hpp
|
timeout/xml_named_entity_miner
|
0d3c6f59b7cb1c2f585b25d86eb0cc8a6a532839
|
[
"0BSD"
] | null | null | null |
#pragma once
#include "xml_doc.hpp"
#include "libxml2_error_handlers.hpp"
#include <libxml/xpath.h>
#include <memory>
class XPathQuery;
class FreeXPathCtxt {
public:
auto operator( )( xmlXPathContext *xpathCtxt ) const -> void;
};
class XPathCtxt {
friend class XPathQuery;
public:
XPathCtxt( );
explicit XPathCtxt( const XmlDoc &xml );
XPathCtxt( const XPathCtxt &xpathCtxt );
XPathCtxt( XPathCtxt &&xpathCtxt );
auto operator=( const XPathCtxt &rhs ) -> XPathCtxt &;
auto operator=( XPathCtxt &&xpathCtxt ) -> XPathCtxt &;
explicit operator bool( ) const;
friend auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt &;
auto errorHandler( ) -> IErrorHandler &;
auto makeQuery( ) const -> XPathQuery;
private:
using XPathCtxtT = std::unique_ptr<xmlXPathContext, FreeXPathCtxt>;
XPathCtxtT xpathCtxt_;
XmlDoc xml_;
XPathErrorHandler xpathHandler_;
};
inline auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt & {
xpathCtxt.xml_ = xml;
xpathCtxt.xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xml_.get( ) ) );
xpathCtxt.xpathHandler_.registerHandler( xpathCtxt.xpathCtxt_.get( ) );
return xpathCtxt;
}
| 27.931818
| 85
| 0.702197
|
timeout
|
2d07795c7a925ca206dca3ca11fe4b2c197d1c5c
| 9,503
|
cpp
|
C++
|
src/planning/lanelet2_global_planner_nodes/src/lanelet2_global_planner_node.cpp
|
Nova-UTD/navigator
|
1db2c614f9c53fb012842b8653ae1bed58a7ffdf
|
[
"Apache-2.0"
] | 11
|
2021-11-26T14:06:51.000Z
|
2022-03-18T16:49:33.000Z
|
src/planning/lanelet2_global_planner_nodes/src/lanelet2_global_planner_node.cpp
|
Nova-UTD/navigator
|
1db2c614f9c53fb012842b8653ae1bed58a7ffdf
|
[
"Apache-2.0"
] | 222
|
2021-10-29T22:00:27.000Z
|
2022-03-29T20:56:34.000Z
|
src/planning/lanelet2_global_planner_nodes/src/lanelet2_global_planner_node.cpp
|
Nova-UTD/navigator
|
1db2c614f9c53fb012842b8653ae1bed58a7ffdf
|
[
"Apache-2.0"
] | 1
|
2021-12-10T18:05:03.000Z
|
2021-12-10T18:05:03.000Z
|
/*
* Package: lanelet2_global_planner_nodes
* Filename: lanelet2_global_planner_node.cpp
* Author: Egan Johnson
* Email: egan.johnson@utdallas.edu
* Copyright: 2021, Nova UTD
* License: MIT License
*/
#include <rclcpp/node_options.hpp>
#include <rclcpp_components/register_node_macro.hpp>
#include <tf2/buffer_core.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>
#include <tf2/utils.h>
#include <time_utils/time_utils.hpp>
#include <motion_common/motion_common.hpp>
#include <autoware_auto_msgs/msg/complex32.hpp>
#include <geometry_msgs/msg/quaternion.hpp>
#include <lanelet2_global_planner_nodes/lanelet2_global_planner_node.hpp>
#include <std_msgs/msg/string.hpp>
#include <common/types.hpp>
#include <chrono>
#include <cmath>
#include <string>
#include <memory>
#include <vector>
using namespace std::chrono_literals;
using autoware::common::types::bool8_t;
using autoware::common::types::float32_t;
using autoware::common::types::float64_t;
using autoware::common::types::TAU;
using autoware::planning::lanelet2_global_planner::Lanelet2GlobalPlanner;
using autoware::planning::lanelet2_global_planner::LaneRouteCosts;
using std::placeholders::_1;
using voltron_msgs::msg::RouteCost;
using voltron_msgs::msg::RouteCosts;
namespace autoware
{
namespace planning
{
namespace lanelet2_global_planner_nodes
{
autoware_auto_msgs::msg::TrajectoryPoint convertToTrajectoryPoint(
const geometry_msgs::msg::Pose &pose)
{
autoware_auto_msgs::msg::TrajectoryPoint pt;
pt.x = static_cast<float>(pose.position.x);
pt.y = static_cast<float>(pose.position.y);
const auto angle = tf2::getYaw(pose.orientation);
pt.heading = ::motion::motion_common::from_angle(angle);
return pt;
}
Lanelet2GlobalPlannerNode::Lanelet2GlobalPlannerNode(
const rclcpp::NodeOptions &node_options)
: Node("lanelet2_global_planner_node", node_options),
tf_listener(tf_buffer, std::shared_ptr<rclcpp::Node>(this, [](auto) {}), false)
{
current_pose_init = false;
// Global planner instance init
lanelet2_global_planner = std::make_shared<Lanelet2GlobalPlanner>();
// Subcribers Goal Pose
goal_pose_sub_ptr =
this->create_subscription<geometry_msgs::msg::PoseStamped>(
"goal_pose", rclcpp::QoS(10),
std::bind(&Lanelet2GlobalPlannerNode::goal_pose_cb, this, _1));
// Subcribers Current Pose
current_pose_sub_ptr =
this->create_subscription<autoware_auto_msgs::msg::VehicleKinematicState>(
"vehicle_kinematic_state", rclcpp::QoS(10),
std::bind(&Lanelet2GlobalPlannerNode::current_pose_cb, this, _1));
// Global path publisher
route_costs_pub_ptr = this->create_publisher<RouteCosts>("route_costs", rclcpp::QoS(10));
// Update loop
// TODO: pull timer period value from param file?
update_loop_timer = this->create_wall_timer(
1000ms, std::bind(&Lanelet2GlobalPlannerNode::update_loop_cb, this));
// Create map client
map_client = this->create_client<autoware_auto_msgs::srv::HADMapService>("HAD_Map_Client");
// Request binary map from the map loader node
this->request_osm_binary_map();
}
void Lanelet2GlobalPlannerNode::request_osm_binary_map()
{
while (rclcpp::ok() && !map_client->wait_for_service(1s))
{
RCLCPP_WARN(this->get_logger(), "HAD map service not available yet. Waiting...");
}
if (!rclcpp::ok())
{
RCLCPP_ERROR(
this->get_logger(),
"Client interrupted while waiting for map service to appear. Exiting.");
}
auto request = std::make_shared<autoware_auto_msgs::srv::HADMapService_Request>();
request->requested_primitives.push_back(
autoware_auto_msgs::srv::HADMapService_Request::FULL_MAP);
auto result = map_client->async_send_request(request);
if (rclcpp::spin_until_future_complete(this->get_node_base_interface(), result) !=
rclcpp::executor::FutureReturnCode::SUCCESS)
{
RCLCPP_ERROR(this->get_logger(), "Service call failed");
throw std::runtime_error("Lanelet2GlobalPlannerNode: Map service call fail");
}
// copy message to map
autoware_auto_msgs::msg::HADMapBin msg = result.get()->map;
// Convert binary map msg to lanelet2 map and set the map for global path planner
lanelet2_global_planner->osm_map = std::make_shared<lanelet::LaneletMap>();
autoware::common::had_map_utils::fromBinaryMsg(msg, lanelet2_global_planner->osm_map);
// parse lanelet global path planner elements
lanelet2_global_planner->parse_lanelet_element();
}
/**
* Called every time the route planner needs to send a new message
*
*/
void Lanelet2GlobalPlannerNode::update_loop_cb()
{
if (!goal_pose_init)
{
RCLCPP_WARN(this->get_logger(), "Awaiting goal pose before setting route");
return;
}
if (!current_pose_init)
{
RCLCPP_WARN(this->get_logger(), "Awaiting current pose before setting route");
return;
}
LaneRouteCosts costs;
auto start = convertToTrajectoryPoint(current_pose.pose);
lanelet2_global_planner->fetch_routing_costs(start, costs);
publish_route_costs(costs);
}
void Lanelet2GlobalPlannerNode::goal_pose_cb(
const geometry_msgs::msg::PoseStamped::SharedPtr msg)
{
// transform and set the starting and goal point in the map frame
goal_pose.header = msg->header;
goal_pose.pose = msg->pose;
geometry_msgs::msg::PoseStamped goal_pose_map = goal_pose;
if (goal_pose.header.frame_id != "map")
{
if (!transform_pose_to_map(goal_pose, goal_pose_map))
{
// return: nothing happen
return;
}
else
{
goal_pose = goal_pose_map;
}
}
auto end = convertToTrajectoryPoint(goal_pose.pose);
lanelet2_global_planner->set_destination(end);
goal_pose_init = true;
}
void Lanelet2GlobalPlannerNode::current_pose_cb(
const autoware_auto_msgs::msg::VehicleKinematicState::SharedPtr msg)
{
// convert msg to geometry_msgs::msg::Pose
current_pose.pose.position.x = msg->state.x;
current_pose.pose.position.y = msg->state.y;
current_pose.pose.position.z = 0.0;
current_pose.pose.orientation =
motion::motion_common::to_quat<geometry_msgs::msg::Quaternion>(
msg->state.heading);
current_pose.header = msg->header;
// transform to "map" frame if needed
if (current_pose.header.frame_id != "map")
{
geometry_msgs::msg::PoseStamped current_pose_map = current_pose;
if (transform_pose_to_map(current_pose, current_pose_map))
{
// transform ok: set current_pose to the pose in map
current_pose = current_pose_map;
current_pose_init = true;
}
else
{
// transform failed
current_pose_init = false;
}
}
else
{
// No transform required
current_pose_init = true;
}
}
void Lanelet2GlobalPlannerNode::publish_route_costs(LaneRouteCosts &costs)
{
RouteCosts route_msg;
route_msg.header.set__frame_id("map");
route_msg.header.set__stamp(now());
// add costs to msg
for (auto cost : costs)
{
RouteCost cost_msg;
cost_msg.lane_id = cost.first;
cost_msg.cost = cost.second;
route_msg.costs.push_back(cost_msg);
}
route_costs_pub_ptr->publish(route_msg);
}
bool8_t Lanelet2GlobalPlannerNode::transform_pose_to_map(
const geometry_msgs::msg::PoseStamped &pose_in,
geometry_msgs::msg::PoseStamped &pose_out)
{
std::string source_frame = pose_in.header.frame_id;
// lookup transform validity
if (!tf_buffer.canTransform("map", source_frame, tf2::TimePointZero))
{
RCLCPP_ERROR(this->get_logger(), "Failed to transform Pose to map frame");
return false;
}
// transform pose into map frame
geometry_msgs::msg::TransformStamped tf_map;
try
{
tf_map = tf_buffer.lookupTransform(
"map", source_frame,
time_utils::from_message(pose_in.header.stamp));
}
catch (const tf2::ExtrapolationException &)
{
// currently falls back to retrive newest transform available for availability,
// Do validation of time stamp in the future
tf_map = tf_buffer.lookupTransform("map", source_frame, tf2::TimePointZero);
}
// apply transform
tf2::doTransform(pose_in, pose_out, tf_map);
return true;
}
} // namespace lanelet2_global_planner_nodes
} // namespace planning
} // namespace autoware
RCLCPP_COMPONENTS_REGISTER_NODE(
autoware::planning::lanelet2_global_planner_nodes::Lanelet2GlobalPlannerNode)
| 34.183453
| 99
| 0.645901
|
Nova-UTD
|
2d0d85f2a0738acad3798b737d26b87ed2c72cce
| 23,249
|
cpp
|
C++
|
kuntar.cpp
|
ridgeware/dekaf2
|
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
|
[
"MIT"
] | null | null | null |
kuntar.cpp
|
ridgeware/dekaf2
|
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
|
[
"MIT"
] | null | null | null |
kuntar.cpp
|
ridgeware/dekaf2
|
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
|
[
"MIT"
] | 1
|
2021-08-20T16:15:01.000Z
|
2021-08-20T16:15:01.000Z
|
/*
//
// DEKAF(tm): Lighter, Faster, Smarter (tm)
//
// Copyright (c) 2018, Ridgeware, Inc.
//
// +-------------------------------------------------------------------------+
// | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\|
// |/+---------------------------------------------------------------------+/|
// |/| |/|
// |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\|
// |/| |/|
// |\| OPEN SOURCE LICENSE |\|
// |/| |/|
// |\| Permission is hereby granted, free of charge, to any person |\|
// |/| obtaining a copy of this software and associated |/|
// |\| documentation files (the "Software"), to deal in the |\|
// |/| Software without restriction, including without limitation |/|
// |\| the rights to use, copy, modify, merge, publish, |\|
// |/| distribute, sublicense, and/or sell copies of the Software, |/|
// |\| and to permit persons to whom the Software is furnished to |\|
// |/| do so, subject to the following conditions: |/|
// |\| |\|
// |/| The above copyright notice and this permission notice shall |/|
// |\| be included in all copies or substantial portions of the |\|
// |/| Software. |/|
// |\| |\|
// |/| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |/|
// |\| KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |\|
// |/| WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |/|
// |\| PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |\|
// |/| OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |/|
// |\| OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |\|
// |/| OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |/|
// |\| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |\|
// |/| |/|
// |/+---------------------------------------------------------------------+/|
// |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ |
// +-------------------------------------------------------------------------+
// large portions of this code are taken from
// https://github.com/JoachimSchurig/CppCDDB/blob/master/untar.cpp
// which is under a BSD style open source license
// Copyright © 2016 Joachim Schurig. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
*/
// I learned about the tar format and the various representations in the wild
// by reading through the code of the following fine projects:
//
// https://github.com/abergmeier/tarlib
//
// and
//
// https://techoverflow.net/blog/2013/03/29/reading-tar-files-in-c/
//
// The below code is another implementation, based on that information
// but following neither of the above implementations in the resulting
// code, particularly because this is a pure C++11 implementation for untar.
// So please do not blame those for any errors this code may cause or have.
#include "kuntar.h"
#include "kfilesystem.h"
#include "kstringutils.h"
#include "klog.h"
#include "kexception.h"
#include <cstring>
#include <array>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
namespace dekaf2 {
KUnTar::iterator::iterator(KUnTar* UnTar) noexcept
: m_UnTar(UnTar)
{
operator++();
}
//-----------------------------------------------------------------------------
KUnTar::iterator::reference KUnTar::iterator::operator*() const
//-----------------------------------------------------------------------------
{
if (m_UnTar)
{
return *m_UnTar;
}
else
{
throw KError("KUnTar::iterator out of range");
}
}
//-----------------------------------------------------------------------------
KUnTar::iterator& KUnTar::iterator::operator++() noexcept
//-----------------------------------------------------------------------------
{
if (m_UnTar)
{
if (m_UnTar->Next() == false)
{
m_UnTar = nullptr;
}
}
return *this;
} // operator++
//-----------------------------------------------------------------------------
void KUnTar::Decoded::Reset()
//-----------------------------------------------------------------------------
{
if (!m_bKeepMembersOnce)
{
m_sFilename.clear();
m_sLinkname.clear();
m_sUser.clear();
m_sGroup.clear();
m_iMode = 0;
m_iUserId = 0;
m_iGroupId = 0;
m_iFilesize = 0;
m_tModificationTime = 0;
m_bIsEnd = false;
m_bIsUstar = false;
m_EntryType = tar::Unknown;
}
else
{
m_bKeepMembersOnce = false;
}
} // Reset
//-----------------------------------------------------------------------------
void KUnTar::Decoded::clear()
//-----------------------------------------------------------------------------
{
m_bKeepMembersOnce = false;
Reset();
} // clear
//-----------------------------------------------------------------------------
uint64_t KUnTar::Decoded::FromNumbers(const char* pStart, uint16_t iSize)
//-----------------------------------------------------------------------------
{
// check if the null byte came before the end of the array
iSize = static_cast<uint16_t>(::strnlen(pStart, iSize));
KStringView sView(pStart, iSize);
auto chFirst = sView.front();
if (DEKAF2_UNLIKELY(m_bIsUstar && ((chFirst & 0x80) != 0)))
{
// MSB is set, this is a binary encoding
if (DEKAF2_UNLIKELY((chFirst & 0x7F) != 0))
{
// create a local copy with removed MSB bit
KString sBuffer(sView);
sBuffer[0] = (chFirst & 0x7f);
return kToInt<uint64_t>(sBuffer, 256);
}
else
{
sView.remove_prefix(1);
return kToInt<uint64_t>(sView, 256);
}
}
else
{
// this is an octal encoding
return kToInt<uint64_t>(sView, 8);
}
} // FromNumbers
#if (__GNUC__ > 10)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-overread"
#endif
//-----------------------------------------------------------------------------
bool KUnTar::Decoded::Decode(const tar::TarHeader& TarHeader)
//-----------------------------------------------------------------------------
{
Reset();
// check for end header
if (TarHeader.raw[0] == 0)
{
// check if full header is 0, then this is the end header of an archive
m_bIsEnd = true;
for (auto ch : TarHeader.raw)
{
if (ch)
{
m_bIsEnd = false;
break;
}
}
if (m_bIsEnd)
{
return true;
}
}
// keep this on top before calling FromNumbers(), which has a dependency
m_bIsUstar = (std::memcmp("ustar", TarHeader.extension.ustar.indicator, 5) == 0);
// validate checksum
{
uint64_t header_checksum = FromNumbers(TarHeader.checksum, 8);
uint64_t sum { 0 };
// we calculate with unsigned chars first, as that is what today's
// tars typically do
for (uint16_t iPos = 0; iPos < 148; ++iPos)
{
sum += static_cast<uint8_t>(TarHeader.raw[iPos]);
}
for (uint16_t iPos = 0; iPos < 8; ++iPos)
{
sum += ' ';
}
for (uint16_t iPos = 148 + 8; iPos < tar::HeaderLen; ++iPos)
{
sum += static_cast<uint8_t>(TarHeader.raw[iPos]);
}
if (header_checksum != sum)
{
// try again with signed chars, which were used by some implementations
sum = 0;
for (uint16_t iPos = 0; iPos < 148; ++iPos)
{
sum += TarHeader.raw[iPos];
}
for (uint16_t iPos = 0; iPos < 8; ++iPos)
{
sum += ' ';
}
for (uint16_t iPos = 148 + 8; iPos < tar::HeaderLen; ++iPos)
{
sum += TarHeader.raw[iPos];
}
if (header_checksum != sum)
{
// that failed, too
kDebug(2, "invalid header checksum");
return false;
}
}
}
m_iMode = static_cast<uint32_t>(FromNumbers(TarHeader.mode, 8));
m_iUserId = static_cast<uint32_t>(FromNumbers(TarHeader.owner_ids.user, 8));
m_iGroupId = static_cast<uint32_t>(FromNumbers(TarHeader.owner_ids.group, 8));
if (m_bIsUstar)
{
// copy user and group
m_sUser.assign(TarHeader.extension.ustar.owner_names.user,
::strnlen(TarHeader.extension.ustar.owner_names.user, 32));
m_sGroup.assign(TarHeader.extension.ustar.owner_names.group,
::strnlen(TarHeader.extension.ustar.owner_names.group, 32));
// check if there is a filename prefix
auto plen = ::strnlen(TarHeader.extension.ustar.filename_prefix, 155);
// insert the prefix before the existing filename
if (plen)
{
m_sFilename.assign(TarHeader.extension.ustar.filename_prefix, plen);
m_sFilename += '/';
}
}
// append file name to a prefix (or none)
m_sFilename.append(TarHeader.file_name, ::strnlen(TarHeader.file_name, 100));
auto TypeFlag = TarHeader.extension.ustar.type_flag;
if (!m_sFilename.empty() && m_sFilename.back() == '/')
{
// make sure we detect also pre-1988 directory names :)
if (!TypeFlag)
{
TypeFlag = '5';
}
}
// now analyze the entry type
switch (TypeFlag)
{
case 0:
case '0':
// treat contiguous file as normal
case '7':
// normal file
if (m_EntryType == tar::Longname1)
{
// this is a subsequent read on GNU tar long names
// the current block contains only the filename and the next block contains metadata
// set the filename from the current header
m_sFilename.assign(TarHeader.file_name,
::strnlen(TarHeader.file_name, tar::HeaderLen));
// the next header contains the metadata, so replace the header before reading the metadata
m_EntryType = tar::Longname2;
m_bKeepMembersOnce = true;
return true;
}
m_EntryType = tar::File;
m_iFilesize = FromNumbers(TarHeader.file_bytes, 12);
m_tModificationTime = FromNumbers(TarHeader.modification_time , 12);
break;
case '1':
// link
m_EntryType = tar::Hardlink;
m_sLinkname.assign(TarHeader.extension.ustar.linked_file_name,
::strnlen(TarHeader.file_name, 100));
break;
case '2':
// symlink
m_EntryType = tar::Symlink;
m_sLinkname.assign(TarHeader.extension.ustar.linked_file_name,
::strnlen(TarHeader.file_name, 100));
break;
case '5':
// directory
m_EntryType = tar::Directory;
m_iFilesize = 0;
m_tModificationTime = FromNumbers(TarHeader.modification_time, 12);
break;
case '6':
// fifo
m_EntryType = tar::Fifo;
break;
case 'L':
// GNU long filename
m_EntryType = tar::Longname1;
m_bKeepMembersOnce = true;
return true;
default:
m_EntryType = tar::Unknown;
break;
}
return true;
} // Decode
#if (__GNUC__ > 10)
#pragma GCC diagnostic pop
#endif
//-----------------------------------------------------------------------------
KUnTar::KUnTar(KInStream& Stream, int AcceptedTypes, bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: m_Stream(Stream)
, m_AcceptedTypes(AcceptedTypes)
, m_bSkipAppleResourceForks(bSkipAppleResourceForks)
{
}
//-----------------------------------------------------------------------------
KUnTar::KUnTar(KStringView sArchiveFilename, int AcceptedTypes, bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: m_File(std::make_unique<KInFile>(sArchiveFilename))
, m_Stream(*m_File)
, m_AcceptedTypes(AcceptedTypes)
, m_bSkipAppleResourceForks(bSkipAppleResourceForks)
{
}
//-----------------------------------------------------------------------------
bool KUnTar::Read(void* buf, size_t len)
//-----------------------------------------------------------------------------
{
size_t rb = m_Stream.Read(buf, len);
if (rb != len)
{
return SetError(kFormat("unexpected end of input stream, trying to read {} bytes, but got only {}", len, rb));
}
return true;
} // Read
//-----------------------------------------------------------------------------
size_t KUnTar::CalcPadding()
//-----------------------------------------------------------------------------
{
if (Filesize() > 0)
{
// check if we have to skip some padding bytes (tar files have a block size of 512)
return (tar::HeaderLen - (Filesize() % tar::HeaderLen)) % tar::HeaderLen;
}
return 0;
} // CalcPadding
//-----------------------------------------------------------------------------
bool KUnTar::ReadPadding()
//-----------------------------------------------------------------------------
{
size_t padding = CalcPadding();
if (padding)
{
std::array<char, tar::HeaderLen> Padding;
if (!Read(Padding.data(), padding))
{
return SetError("cannot read block padding");
}
}
return true;
} // ReadPadding
//-----------------------------------------------------------------------------
bool KUnTar::Next()
//-----------------------------------------------------------------------------
{
// delete a previous error
m_Error.clear();
do
{
if (!m_bIsConsumed && (Filesize() > 0))
{
if (!SkipCurrentFile())
{
return false;
}
}
tar::TarHeader TarHeader;
if (!Read(&TarHeader, tar::HeaderLen))
{
return SetError("cannot not read tar header");
}
if (!m_Header.Decode(TarHeader))
{
// the only false return from Decode happens on a bad checksum compare
return SetError("invalid tar header (bad checksum)");
}
// this is the only valid exit condition from reading a tar archive - end header reached
if (m_Header.IsEnd())
{
// no error!
return false;
}
if (Filesize() > 0)
{
m_bIsConsumed = false;
}
} while ((Type() & m_AcceptedTypes) == 0
|| (m_bSkipAppleResourceForks && kBasename(Filename()).starts_with("._")));
return true;
} // Entry
//-----------------------------------------------------------------------------
bool KUnTar::Skip(size_t iSize)
//-----------------------------------------------------------------------------
{
if (!iSize)
{
return true;
}
enum { SKIP_BUFSIZE = 4096 };
std::array<char, SKIP_BUFSIZE> sBuffer;
size_t iRead = 0;
for (auto iRemain = iSize; iRemain;)
{
auto iChunk = std::min(sBuffer.size(), iRemain);
if (!Read(sBuffer.data(), iChunk))
{
break;
}
iRead += iChunk;
iRemain -= iChunk;
}
if (iRead == iSize)
{
return true;
}
else
{
return SetError("cannot not skip file");
}
} // Skip
//-----------------------------------------------------------------------------
bool KUnTar::SkipCurrentFile()
//-----------------------------------------------------------------------------
{
return Skip(Filesize() + CalcPadding());
} // SkipCurrentFile
//-----------------------------------------------------------------------------
bool KUnTar::Read(KOutStream& OutStream)
//-----------------------------------------------------------------------------
{
if (Type() != tar::File)
{
return SetError("cannot read - current tar entry is not a file");
}
if (!OutStream.Write(m_Stream, Filesize()).Good())
{
return SetError("cannot write to output stream");
}
if (!ReadPadding())
{
return false;
}
m_bIsConsumed = true;
return true;
} // Read
//-----------------------------------------------------------------------------
bool KUnTar::Read(KString& sBuffer)
//-----------------------------------------------------------------------------
{
sBuffer.clear();
if (Type() != tar::File)
{
return SetError("cannot read - current tar entry is not a file");
}
// resize the buffer to be able to read the file size
sBuffer.resize_uninitialized(Filesize());
// read the file into the buffer
if (!Read(&sBuffer[0], Filesize()))
{
return false;
}
if (!ReadPadding())
{
return false;
}
m_bIsConsumed = true;
return true;
} // Read
//-----------------------------------------------------------------------------
bool KUnTar::ReadFile(KStringViewZ sFilename)
//-----------------------------------------------------------------------------
{
KOutFile File(sFilename, std::ios_base::out & std::ios_base::trunc);
if (!File.is_open())
{
return SetError(kFormat("cannot create file {}", sFilename));
}
return Read(File);
} // ReadFile
//-----------------------------------------------------------------------------
KString KUnTar::CreateTargetDirectory(KStringViewZ sBaseDir, KStringViewZ sEntry, bool bWithSubdirectories)
//-----------------------------------------------------------------------------
{
KString sName = sBaseDir;
sName += kDirSep;
if (bWithSubdirectories)
{
KString sSafePath = kMakeSafePathname(sEntry, false);
KStringView sDirname = kDirname(sSafePath);
if (sDirname != ".")
{
sName += sDirname;
if (!kCreateDir(sName))
{
SetError(kFormat("cannot create directory: {}", sName));
return KString{};
}
sName += kDirSep;
}
sName += kBasename(sSafePath);
}
else
{
sName += kMakeSafeFilename(kBasename(sEntry), false);
}
return sName;
} // CreateTargetDirectory
//-----------------------------------------------------------------------------
bool KUnTar::ReadAll(KStringViewZ sTargetDirectory, bool bWithSubdirectories)
//-----------------------------------------------------------------------------
{
if (!kDirExists(sTargetDirectory))
{
if (!kCreateDir(sTargetDirectory))
{
return SetError(kFormat("cannot create directory: {}", sTargetDirectory));
}
}
for (auto& File : *this)
{
switch (File.Type())
{
case tar::Directory:
case tar::File:
{
auto sName = CreateTargetDirectory(sTargetDirectory, SafePath(), bWithSubdirectories);
if (sName.empty())
{
// error is already set
return false;
}
if (File.Type() == tar::File)
{
if (!ReadFile(sName))
{
// error is already set
return false;
}
}
}
break;
case tar::Hardlink:
case tar::Symlink:
{
auto sLink = CreateTargetDirectory(sTargetDirectory, SafePath(), bWithSubdirectories);
if (sLink.empty())
{
// error is already set
return false;
}
KString sOrigin = (bWithSubdirectories) ? File.SafeLinkPath() : File.SafeLinkName();
if (File.Type() == tar::Symlink)
{
if (!kCreateSymlink(sOrigin, sLink))
{
return SetError(kFormat("cannot create symlink {} > {}", sOrigin, sLink));
}
}
else
{
if (!kCreateHardlink(sOrigin, sLink))
{
return SetError(kFormat("cannot create hardlink {} > {}", sOrigin, sLink));
}
}
}
break;
default:
break;
}
}
return true;
} // ReadAll
//-----------------------------------------------------------------------------
bool KUnTar::File(KString& sName, KString& sBuffer)
//-----------------------------------------------------------------------------
{
sName.clear();
sBuffer.clear();
if (!Next())
{
return false;
}
if (Type() == tar::File)
{
if (!Read(sBuffer))
{
return false;
}
}
sName = Filename();
return true;
} // File
//-----------------------------------------------------------------------------
bool KUnTar::SetError(KString sError)
//-----------------------------------------------------------------------------
{
m_Error = std::move(sError);
kDebug(2, m_Error);
return false;
} // SetError
//-----------------------------------------------------------------------------
KUnTarCompressed::KUnTarCompressed(COMPRESSION Compression,
KInStream& InStream,
int AcceptedTypes,
bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: KUnTar(m_FilteredInStream, AcceptedTypes, bSkipAppleResourceForks)
{
SetupFilter(Compression, InStream);
} // ctor
//-----------------------------------------------------------------------------
KUnTarCompressed::KUnTarCompressed(COMPRESSION Compression,
KStringView sArchiveFilename,
int AcceptedTypes,
bool bSkipAppleResourceForks)
//-----------------------------------------------------------------------------
: KUnTar(m_FilteredInStream, AcceptedTypes, bSkipAppleResourceForks)
{
m_File = std::make_unique<KInFile>(sArchiveFilename);
if (Compression == AUTODETECT)
{
KString sSuffix = kExtension(sArchiveFilename).ToLower();
if (sSuffix == "tar")
{
Compression = NONE;
}
else if (sSuffix == "tgz" || sSuffix == "gz" || sSuffix == "gzip")
{
Compression = GZIP;
}
else if (sSuffix == "tbz" || sSuffix == "tbz2" || sSuffix == "bz2" || sSuffix == "bzip2")
{
Compression = BZIP2;
}
else
{
Compression = NONE;
}
}
SetupFilter(Compression, *m_File);
} // ctor
//-----------------------------------------------------------------------------
void KUnTarCompressed::SetupFilter(COMPRESSION Compression, KInStream& InStream)
//-----------------------------------------------------------------------------
{
switch (Compression)
{
case AUTODETECT:
case NONE:
break;
case GZIP:
m_Filter.push(boost::iostreams::gzip_decompressor());
break;
case BZIP2:
m_Filter.push(boost::iostreams::bzip2_decompressor());
break;
}
m_Filter.push(InStream.InStream());
} // SetupFilter
} // end of namespace dekaf2
| 27.383981
| 112
| 0.503678
|
ridgeware
|
2d101d27bd25729bdbd00f556345f40ac5a982ba
| 1,800
|
hpp
|
C++
|
iehl/src/forward_rendering/vertex_array.hpp
|
the-last-willy/id3d
|
dc0d22e7247ac39fbc1fd8433acae378b7610109
|
[
"MIT"
] | null | null | null |
iehl/src/forward_rendering/vertex_array.hpp
|
the-last-willy/id3d
|
dc0d22e7247ac39fbc1fd8433acae378b7610109
|
[
"MIT"
] | null | null | null |
iehl/src/forward_rendering/vertex_array.hpp
|
the-last-willy/id3d
|
dc0d22e7247ac39fbc1fd8433acae378b7610109
|
[
"MIT"
] | null | null | null |
#pragma once
#include "scene/vertex_attribute/all.hpp"
#include "forward_renderer.hpp"
inline
gl::VertexArray vertex_array(
const ForwardRenderer&,
const VertexAttributeGroup& vag)
{
auto vao = gl::VertexArray();
if(gl::GetNamedBufferParameter(vag.normal_buffer, GL_BUFFER_SIZE) > 0) {
auto attribindex = GLuint(0);
auto bindingindex = GLuint(0);
auto size = GLint(3);
glVertexArrayAttribBinding(vao,
attribindex, bindingindex);
glVertexArrayAttribFormat(vao,
attribindex, size, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao,
bindingindex, vag.normal_buffer, 0, 4 * size);
glEnableVertexArrayAttrib(vao, attribindex);
}
if(gl::GetNamedBufferParameter(vag.position_buffer, GL_BUFFER_SIZE) > 0) {
auto attribindex = GLuint(1);
auto bindingindex = GLuint(1);
auto size = GLint(3);
glVertexArrayAttribBinding(vao,
attribindex, bindingindex);
glVertexArrayAttribFormat(vao,
attribindex, size, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao,
bindingindex, vag.position_buffer, 0, 4 * size);
glEnableVertexArrayAttrib(vao, attribindex);
}
if(gl::GetNamedBufferParameter(vag.texcoords_buffer, GL_BUFFER_SIZE) > 0) {
auto attribindex = GLuint(2);
auto bindingindex = GLuint(2);
auto size = GLint(2);
glVertexArrayAttribBinding(vao,
attribindex, bindingindex);
glVertexArrayAttribFormat(vao,
attribindex, size, GL_FLOAT, GL_FALSE, 0);
glVertexArrayVertexBuffer(vao,
bindingindex, vag.texcoords_buffer, 0, 4 * size);
glEnableVertexArrayAttrib(vao, attribindex);
}
return vao;
}
| 36
| 79
| 0.654444
|
the-last-willy
|
2d167a9cf4824caebe65c82b788698d5b5c7d84d
| 5,780
|
cpp
|
C++
|
osquery/sql/benchmarks/sql_benchmarks.cpp
|
trizt/osquery
|
9256819b8161ab1e02ea0d7eb55da132f197723d
|
[
"BSD-3-Clause"
] | 1
|
2018-10-30T03:58:24.000Z
|
2018-10-30T03:58:24.000Z
|
osquery/sql/benchmarks/sql_benchmarks.cpp
|
trizt/osquery
|
9256819b8161ab1e02ea0d7eb55da132f197723d
|
[
"BSD-3-Clause"
] | null | null | null |
osquery/sql/benchmarks/sql_benchmarks.cpp
|
trizt/osquery
|
9256819b8161ab1e02ea0d7eb55da132f197723d
|
[
"BSD-3-Clause"
] | 2
|
2020-09-23T04:49:23.000Z
|
2022-03-29T17:32:31.000Z
|
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <benchmark/benchmark.h>
#include <osquery/core.h>
#include <osquery/registry.h>
#include <osquery/sql.h>
#include <osquery/tables.h>
#include "osquery/sql/virtual_table.h"
namespace osquery {
class BenchmarkTablePlugin : public TablePlugin {
private:
TableColumns columns() const {
return {
std::make_tuple("test_int", INTEGER_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("test_text", TEXT_TYPE, ColumnOptions::DEFAULT),
};
}
QueryData generate(QueryContext& ctx) {
QueryData results;
results.push_back({{"test_int", "0"}});
results.push_back({{"test_int", "0"}, {"test_text", "hello"}});
return results;
}
};
static void SQL_virtual_table_registry(benchmark::State& state) {
// Add a sample virtual table plugin.
// Profile calling the plugin's column data.
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
while (state.KeepRunning()) {
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "generate"}}, res);
}
}
BENCHMARK(SQL_virtual_table_registry);
static void SQL_virtual_table_internal(benchmark::State& state) {
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "columns"}}, res);
// Attach a sample virtual table.
auto dbc = SQLiteDBManager::get();
attachTableInternal("benchmark", columnDefinition(res), dbc);
while (state.KeepRunning()) {
QueryData results;
queryInternal("select * from benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal);
static void SQL_virtual_table_internal_global(benchmark::State& state) {
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "columns"}}, res);
while (state.KeepRunning()) {
// Get a connection to the persistent database.
auto dbc = SQLiteDBManager::get();
attachTableInternal("benchmark", columnDefinition(res), dbc);
QueryData results;
queryInternal("select * from benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_global);
static void SQL_virtual_table_internal_unique(benchmark::State& state) {
Registry::add<BenchmarkTablePlugin>("table", "benchmark");
PluginResponse res;
Registry::call("table", "benchmark", {{"action", "columns"}}, res);
while (state.KeepRunning()) {
// Get a new database connection (to a unique database).
auto dbc = SQLiteDBManager::getUnique();
attachTableInternal("benchmark", columnDefinition(res), dbc);
QueryData results;
queryInternal("select * from benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_unique);
class BenchmarkLongTablePlugin : public TablePlugin {
private:
TableColumns columns() const {
return {
std::make_tuple("test_int", INTEGER_TYPE, ColumnOptions::DEFAULT),
std::make_tuple("test_text", TEXT_TYPE, ColumnOptions::DEFAULT),
};
}
QueryData generate(QueryContext& ctx) {
QueryData results;
for (int i = 0; i < 1000; i++) {
results.push_back({{"test_int", "0"}, {"test_text", "hello"}});
}
return results;
}
};
static void SQL_virtual_table_internal_long(benchmark::State& state) {
Registry::add<BenchmarkLongTablePlugin>("table", "long_benchmark");
PluginResponse res;
Registry::call("table", "long_benchmark", {{"action", "columns"}}, res);
// Attach a sample virtual table.
auto dbc = SQLiteDBManager::getUnique();
attachTableInternal("long_benchmark", columnDefinition(res), dbc);
while (state.KeepRunning()) {
QueryData results;
queryInternal("select * from long_benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_long);
class BenchmarkWideTablePlugin : public TablePlugin {
private:
TableColumns columns() const override {
TableColumns cols;
for (int i = 0; i < 20; i++) {
cols.push_back(std::make_tuple(
"test_" + std::to_string(i), INTEGER_TYPE, ColumnOptions::DEFAULT));
}
return cols;
}
QueryData generate(QueryContext& ctx) override {
QueryData results;
for (int k = 0; k < 50; k++) {
Row r;
for (int i = 0; i < 20; i++) {
r["test_" + std::to_string(i)] = "0";
}
results.push_back(r);
}
return results;
}
};
static void SQL_virtual_table_internal_wide(benchmark::State& state) {
Registry::add<BenchmarkWideTablePlugin>("table", "wide_benchmark");
PluginResponse res;
Registry::call("table", "wide_benchmark", {{"action", "columns"}}, res);
// Attach a sample virtual table.
auto dbc = SQLiteDBManager::getUnique();
attachTableInternal("wide_benchmark", columnDefinition(res), dbc);
while (state.KeepRunning()) {
QueryData results;
queryInternal("select * from wide_benchmark", results, dbc->db());
}
}
BENCHMARK(SQL_virtual_table_internal_wide);
static void SQL_select_metadata(benchmark::State& state) {
auto dbc = SQLiteDBManager::get();
while (state.KeepRunning()) {
QueryData results;
queryInternal(
"select count(*) from sqlite_temp_master;", results, dbc->db());
}
}
BENCHMARK(SQL_select_metadata);
static void SQL_select_basic(benchmark::State& state) {
// Profile executing a query against an internal, already attached table.
while (state.KeepRunning()) {
auto results = SQLInternal("select * from benchmark");
}
}
BENCHMARK(SQL_select_basic);
}
| 29.191919
| 79
| 0.692907
|
trizt
|
2d1776aac2e4aea98a712e4896a4aad4c598364a
| 2,658
|
cpp
|
C++
|
visual/kinect2/kinect2.cpp
|
TimothyYong/Tachikoma-Project
|
c7af70f2c58fe43f25331fd03589845480ae0f16
|
[
"MIT"
] | 1
|
2016-02-02T23:13:54.000Z
|
2016-02-02T23:13:54.000Z
|
visual/kinect2/kinect2.cpp
|
TimothyYong/Tachikoma-Project
|
c7af70f2c58fe43f25331fd03589845480ae0f16
|
[
"MIT"
] | null | null | null |
visual/kinect2/kinect2.cpp
|
TimothyYong/Tachikoma-Project
|
c7af70f2c58fe43f25331fd03589845480ae0f16
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <opencv2/imgproc/imgproc.hpp>
#include "kinect.h"
using namespace cv;
using namespace std;
/* This file accesses the Kinect Device and gets its video and depth frames. If a depth frame is deteced, a new distance frame is created as well */
KinectDevice::KinectDevice(freenect_context *_ctx, int _index) :
Freenect::FreenectDevice(_ctx, _index),
depth_buffer(FREENECT_DEPTH_11BIT),
video_buffer(FREENECT_VIDEO_RGB),
gamma_buffer(2048),
new_depth_frame(false),
new_video_frame(false),
depthMat(Size(640, 480), CV_16UC1),
videoMat(Size(640, 480), CV_8UC3),
new_distance_frame(false),
distanceMat(Size(640, 480), CV_64F),
rows(640),
cols(480) {
for (uint32_t i = 0; i < 2048; i++) {
float v = i / 2048.0;
v = pow(v, 3) * 6;
this->gamma_buffer[i] = v * 6 * 256;
}
}
KinectDevice::~KinectDevice() {
}
void KinectDevice::DepthCallback(void *data, uint32_t timestamp) {
this->depth_lock.lock();
this->depthMat.data = (uint8_t *)data;
this->new_depth_frame = true;
this->new_distance_frame = true;
this->depth_lock.unlock();
}
void KinectDevice::VideoCallback(void *data, uint32_t timestamp) {
this->video_lock.lock();
this->videoMat.data = (uint8_t *)data;
this->new_video_frame = true;
this->video_lock.unlock();
}
bool KinectDevice::getDepth(Mat& output) {
this->depth_lock.lock();
if (this->new_depth_frame) {
this->depthMat.copyTo(output);
this->new_depth_frame = false;
this->depth_lock.unlock();
return true;
} else {
this->depthMat.copyTo(output);
this->depth_lock.unlock();
return false;
}
}
bool KinectDevice::getVideo(Mat& output) {
this->video_lock.lock();
if (this->new_video_frame) {
cvtColor(this->videoMat, output, COLOR_RGB2BGR);
this->new_video_frame = false;
this->video_lock.unlock();
return true;
} else {
cvtColor(this->videoMat, output, COLOR_RGB2BGR);
this->video_lock.unlock();
return false;
}
}
bool KinectDevice::getDistance(Mat &output) {
this->depth_lock.lock();
if (this->new_distance_frame) {
for (int y = 0; y < this->depthMat.rows; y++) {
for (int x = 0; x < this->depthMat.cols; x++) {
this->distanceMat.at<double>(y, x) = raw2meters(this->depthMat.at<uint16_t>(y, x));
}
}
this->new_distance_frame = false;
this->depth_lock.unlock();
return true;
} else {
this->distanceMat.copyTo(output);
this->depth_lock.unlock();
return false;
}
}
double KinectDevice::raw2meters(uint16_t raw) {
// stephane maganate
return (0.1236 * tan((double)raw / 2842.5 + 1.1863));
}
| 26.848485
| 148
| 0.667043
|
TimothyYong
|
2d25bd97f5de8c170c7d94ce038e3042e8cce6f2
| 3,396
|
cc
|
C++
|
core/gen/server.grpc.pb.cc
|
dishanphilips/Jade
|
abefc34ec81b5c2f69e68f10ec1309fb1d786aba
|
[
"MIT"
] | null | null | null |
core/gen/server.grpc.pb.cc
|
dishanphilips/Jade
|
abefc34ec81b5c2f69e68f10ec1309fb1d786aba
|
[
"MIT"
] | null | null | null |
core/gen/server.grpc.pb.cc
|
dishanphilips/Jade
|
abefc34ec81b5c2f69e68f10ec1309fb1d786aba
|
[
"MIT"
] | null | null | null |
// Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: server.proto
#include "server.pb.h"
#include "server.grpc.pb.h"
#include <functional>
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/channel_interface.h>
#include <grpcpp/impl/codegen/client_unary_call.h>
#include <grpcpp/impl/codegen/client_callback.h>
#include <grpcpp/impl/codegen/message_allocator.h>
#include <grpcpp/impl/codegen/method_handler.h>
#include <grpcpp/impl/codegen/rpc_service_method.h>
#include <grpcpp/impl/codegen/server_callback.h>
#include <grpcpp/impl/codegen/server_callback_handlers.h>
#include <grpcpp/impl/codegen/server_context.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/sync_stream.h>
namespace JadeCore {
static const char* RpcBase_method_names[] = {
"/JadeCore.RpcBase/Handle",
};
std::unique_ptr< RpcBase::Stub> RpcBase::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) {
(void)options;
std::unique_ptr< RpcBase::Stub> stub(new RpcBase::Stub(channel));
return stub;
}
RpcBase::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
: channel_(channel), rpcmethod_Handle_(RpcBase_method_names[0], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel)
{}
::grpc::ClientReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* RpcBase::Stub::HandleRaw(::grpc::ClientContext* context) {
return ::grpc_impl::internal::ClientReaderWriterFactory< ::JadeCore::Command, ::JadeCore::Command>::Create(channel_.get(), rpcmethod_Handle_, context);
}
void RpcBase::Stub::experimental_async::Handle(::grpc::ClientContext* context, ::grpc::experimental::ClientBidiReactor< ::JadeCore::Command,::JadeCore::Command>* reactor) {
::grpc_impl::internal::ClientCallbackReaderWriterFactory< ::JadeCore::Command,::JadeCore::Command>::Create(stub_->channel_.get(), stub_->rpcmethod_Handle_, context, reactor);
}
::grpc::ClientAsyncReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* RpcBase::Stub::AsyncHandleRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) {
return ::grpc_impl::internal::ClientAsyncReaderWriterFactory< ::JadeCore::Command, ::JadeCore::Command>::Create(channel_.get(), cq, rpcmethod_Handle_, context, true, tag);
}
::grpc::ClientAsyncReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* RpcBase::Stub::PrepareAsyncHandleRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) {
return ::grpc_impl::internal::ClientAsyncReaderWriterFactory< ::JadeCore::Command, ::JadeCore::Command>::Create(channel_.get(), cq, rpcmethod_Handle_, context, false, nullptr);
}
RpcBase::Service::Service() {
AddMethod(new ::grpc::internal::RpcServiceMethod(
RpcBase_method_names[0],
::grpc::internal::RpcMethod::BIDI_STREAMING,
new ::grpc::internal::BidiStreamingHandler< RpcBase::Service, ::JadeCore::Command, ::JadeCore::Command>(
std::mem_fn(&RpcBase::Service::Handle), this)));
}
RpcBase::Service::~Service() {
}
::grpc::Status RpcBase::Service::Handle(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::JadeCore::Command, ::JadeCore::Command>* stream) {
(void) context;
(void) stream;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
} // namespace JadeCore
| 45.891892
| 179
| 0.746466
|
dishanphilips
|
2d26b1a96815542357f0887e0615d0e1fca59309
| 6,313
|
cpp
|
C++
|
lightstep/src/ngx_http_lightstep_module.cpp
|
SEJeff/nginx-opentracing
|
2cea68b20c744842171533b10385576f8380a8a4
|
[
"Apache-2.0"
] | 2
|
2019-06-17T22:54:04.000Z
|
2019-06-18T10:50:01.000Z
|
lightstep/src/ngx_http_lightstep_module.cpp
|
SEJeff/nginx-opentracing
|
2cea68b20c744842171533b10385576f8380a8a4
|
[
"Apache-2.0"
] | null | null | null |
lightstep/src/ngx_http_lightstep_module.cpp
|
SEJeff/nginx-opentracing
|
2cea68b20c744842171533b10385576f8380a8a4
|
[
"Apache-2.0"
] | null | null | null |
#include <lightstep/tracer.h>
#include <opentracing/tracer.h>
#include <cstdlib>
extern "C" {
#include <nginx.h>
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
extern ngx_module_t ngx_http_lightstep_module;
}
//------------------------------------------------------------------------------
// to_string
//------------------------------------------------------------------------------
static inline std::string to_string(const ngx_str_t &ngx_str) {
return {reinterpret_cast<char *>(ngx_str.data), ngx_str.len};
}
//------------------------------------------------------------------------------
// lightstep_main_conf_t
//------------------------------------------------------------------------------
struct lightstep_main_conf_t {
ngx_str_t access_token;
ngx_str_t component_name;
ngx_str_t collector_host;
ngx_flag_t collector_plaintext = NGX_CONF_UNSET;
ngx_str_t collector_port;
};
//------------------------------------------------------------------------------
// lightstep_module_init
//------------------------------------------------------------------------------
static ngx_int_t lightstep_module_init(ngx_conf_t *cf) {
auto main_conf = static_cast<lightstep_main_conf_t *>(
ngx_http_conf_get_module_main_conf(cf, ngx_http_lightstep_module));
// Validate the configuration
if (!main_conf->access_token.data) {
ngx_log_error(NGX_LOG_ERR, cf->log, 0,
"`lighstep_access_token` must be specified");
return NGX_ERROR;
}
return NGX_OK;
}
//------------------------------------------------------------------------------
// lightstep_init_worker
//------------------------------------------------------------------------------
static ngx_int_t lightstep_init_worker(ngx_cycle_t *cycle) {
auto main_conf = static_cast<lightstep_main_conf_t *>(
ngx_http_cycle_get_module_main_conf(cycle, ngx_http_lightstep_module));
lightstep::LightStepTracerOptions tracer_options;
if (!main_conf->access_token.data) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0,
"`lighstep_access_token` must be specified");
return NGX_ERROR;
}
tracer_options.access_token = to_string(main_conf->access_token);
if (main_conf->collector_host.data)
tracer_options.collector_host = to_string(main_conf->collector_host);
if (main_conf->collector_port.data)
// TODO: Check for errors here?
tracer_options.collector_port =
std::stoi(to_string(main_conf->collector_port));
if (main_conf->collector_plaintext != NGX_CONF_UNSET)
tracer_options.collector_plaintext = main_conf->collector_plaintext;
if (main_conf->component_name.data)
tracer_options.component_name = to_string(main_conf->component_name);
else
tracer_options.component_name = "nginx";
auto tracer = lightstep::MakeLightStepTracer(std::move(tracer_options));
if (!tracer) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0,
"Failed to create LightStep tracer");
return NGX_OK;
}
opentracing::Tracer::InitGlobal(std::move(tracer));
return NGX_OK;
}
//------------------------------------------------------------------------------
// create_lightstep_main_conf
//------------------------------------------------------------------------------
static void *create_lightstep_main_conf(ngx_conf_t *conf) {
auto main_conf = static_cast<lightstep_main_conf_t *>(
ngx_pcalloc(conf->pool, sizeof(lightstep_main_conf_t)));
// Default initialize members.
*main_conf = lightstep_main_conf_t();
if (!main_conf) return nullptr;
return main_conf;
}
//------------------------------------------------------------------------------
// lightstep_module_ctx
//------------------------------------------------------------------------------
static ngx_http_module_t lightstep_module_ctx = {
nullptr, /* preconfiguration */
lightstep_module_init, /* postconfiguration */
create_lightstep_main_conf, /* create main configuration */
nullptr, /* init main configuration */
nullptr, /* create server configuration */
nullptr, /* merge server configuration */
nullptr, /* create location configuration */
nullptr /* merge location configuration */
};
//------------------------------------------------------------------------------
// lightstep_commands
//------------------------------------------------------------------------------
static ngx_command_t lightstep_commands[] = {
{ngx_string("lightstep_access_token"), NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1,
ngx_conf_set_str_slot, NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(lightstep_main_conf_t, access_token), nullptr},
{ngx_string("lightstep_component_name"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_str_slot,
NGX_HTTP_MAIN_CONF_OFFSET, offsetof(lightstep_main_conf_t, component_name),
nullptr},
{ngx_string("lightstep_collector_host"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_str_slot,
NGX_HTTP_MAIN_CONF_OFFSET, offsetof(lightstep_main_conf_t, collector_host),
nullptr},
{ngx_string("lightstep_collector_plaintext"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_flag_slot,
NGX_HTTP_MAIN_CONF_OFFSET,
offsetof(lightstep_main_conf_t, collector_plaintext), nullptr},
{ngx_string("lightstep_collector_port"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_conf_set_str_slot,
NGX_HTTP_MAIN_CONF_OFFSET, offsetof(lightstep_main_conf_t, collector_port),
nullptr}};
//------------------------------------------------------------------------------
// ngx_http_lightstep_module
//------------------------------------------------------------------------------
ngx_module_t ngx_http_lightstep_module = {
NGX_MODULE_V1,
&lightstep_module_ctx, /* module context */
lightstep_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
nullptr, /* init master */
nullptr, /* init module */
lightstep_init_worker, /* init process */
nullptr, /* init thread */
nullptr, /* exit thread */
nullptr, /* exit process */
nullptr, /* exit master */
NGX_MODULE_V1_PADDING};
| 42.655405
| 80
| 0.569301
|
SEJeff
|
2d291cac9b621afceb0a49f76d6cbb67dd2bf702
| 4,508
|
cpp
|
C++
|
bltail.cpp
|
brendane/bltools
|
b25906c46d30339b5a009bddeeeb6b1de6700048
|
[
"MIT"
] | 1
|
2021-05-19T11:35:47.000Z
|
2021-05-19T11:35:47.000Z
|
bltail.cpp
|
brendane/bltools
|
b25906c46d30339b5a009bddeeeb6b1de6700048
|
[
"MIT"
] | null | null | null |
bltail.cpp
|
brendane/bltools
|
b25906c46d30339b5a009bddeeeb6b1de6700048
|
[
"MIT"
] | null | null | null |
/*
* Equivalent of tail for biological sequences.
*
*/
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <seqan/seq_io.h>
#include <tclap/CmdLine.h>
#include <SeqFileInWrapper.h>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::istream;
using std::queue;
using std::stoi;
using std::string;
using std::vector;
using namespace seqan;
using namespace bltools;
int main(int argc, char * argv[]) {
TCLAP::CmdLine cmd("Equivalent of `tail' for sequence files", ' ', "0.0");
TCLAP::ValueArg<string> format_arg("o", "output-format",
"Output format: fasta or fastq; fasta is default",
false, "fasta", "fast[aq]", cmd);
TCLAP::ValueArg<string> nlines_arg("n", "lines",
"print the last n lines of each file or all lines but the first +n",
false, "10", "[+]int", cmd);
TCLAP::UnlabeledMultiArg<string> files("FILE(s)", "filenames", false,
"file name(s)", cmd, false);
cmd.parse(argc, argv);
string format = format_arg.getValue();
vector<string> infiles = files.getValue();
if(infiles.size() == 0) infiles.push_back("-");
string nlines_string = nlines_arg.getValue();
int nskip = 0;
int nlines = 0;
if(nlines_string[0] == '+') {
nlines_string.erase(0, 1);
nskip = stoi(nlines_string);
nlines = 0;
} else {
nlines = stoi(nlines_string);
nskip = 0;
}
if(nlines < 0 || nskip < 0) {
cerr << "Can't have a negative number of lines" << endl;
return 1;
}
SeqFileOut out_handle(cout, Fasta());
if(format == "fasta") {
setFormat(out_handle, Fasta());
} else if(format == "fastq") {
setFormat(out_handle, Fastq());
} else {
cerr << "Unrecognized output format";
return 1;
}
CharString id;
queue<CharString> ids;
CharString seq; // CharString more flexible than Dna5String
queue<CharString> seqs;
CharString qual;
queue<CharString> quals;
SeqFileInWrapper seq_handle;
for(string& infile: infiles) {
try {
seq_handle.open(infile);
} catch(Exception const &e) {
cerr << "Could not open " << infile << endl;
seq_handle.close();
return 1;
}
int nrecs_read = 0;
// Fill up seqs, quals, ids until look_ahead is reached, then for
// every additional record, pop one off of seqs, quals, and ids, and
// push the new one on until the end of the file is reached.
while(!seq_handle.atEnd()) {
try {
readRecord(id, seq, qual, seq_handle.sqh);
nrecs_read++;
} catch (Exception const &e) {
cerr << "Error: " << e.what() << endl;
seq_handle.close();
close(out_handle);
return 1;
} // End try-catch for record reading.
// If nskip > 0, just continue until nrecs_read > nskip, then write
// output as file is read.
//
// Otherwise, keep pushing to the queue (after queue.size() == nlines,
// also pop a record each time). Then, after the while loop, write all
// the records in the queue.
if(nskip > 0) {
if(nrecs_read >= nskip) {
try {
writeRecord(out_handle, id, seq, qual);
} catch (Exception const &e) {
cerr << "Error writing output";
seq_handle.close();
return 1;
}
} else {
continue;
}
} // End if(nskip > 0)
else if(nlines > 0) {
seqs.push(seq); ids.push(id); quals.push(qual);
if(seqs.size() > (unsigned) nlines) {
ids.pop(); seqs.pop(); quals.pop();
}
} // End if(nlines > 0)
} // End single file reading loop
// Write output if nlines > 0
// Can we do for(StringChar id: ids; StringChar seq:seqs...)?
if(nlines > 0) {
for(int i=0; i < nlines; i++) {
try {
writeRecord(out_handle, ids.front(), seqs.front(),
quals.front());
ids.pop(); seqs.pop(); quals.pop();
} catch (Exception const &e) {
cerr << "Error writing output";
seq_handle.close();
return 1;
}
}
}
if(!seq_handle.close()) {
cerr << "Problem closing " << infile << endl;
close(out_handle);
return 1;
}
} // End loop over files
close(out_handle);
return 0;
}
| 27.156627
| 105
| 0.557453
|
brendane
|
2d2cca0e5fa20914f6211d594622f29f905f2164
| 201
|
cpp
|
C++
|
Challenges/Challenge29/src/main.cpp
|
GamesTrap/PracticeChallenges
|
46ad8b2c18515a9740910162381a3dea18be72ab
|
[
"MIT"
] | null | null | null |
Challenges/Challenge29/src/main.cpp
|
GamesTrap/PracticeChallenges
|
46ad8b2c18515a9740910162381a3dea18be72ab
|
[
"MIT"
] | null | null | null |
Challenges/Challenge29/src/main.cpp
|
GamesTrap/PracticeChallenges
|
46ad8b2c18515a9740910162381a3dea18be72ab
|
[
"MIT"
] | null | null | null |
#include <cstdint>
constexpr uint32_t Summation(const uint32_t num)
{
return num * (num + 1) / 2;
}
int main()
{
static_assert(Summation(1) == 1);
static_assert(Summation(8) == 36);
return 0;
}
| 14.357143
| 48
| 0.661692
|
GamesTrap
|
2d3232def81d485798f2ee7da6b978e9ec8917cf
| 13,860
|
cpp
|
C++
|
FEBioMech/FEReactiveViscoelastic.cpp
|
wzaylor/FEBio
|
5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6
|
[
"MIT"
] | null | null | null |
FEBioMech/FEReactiveViscoelastic.cpp
|
wzaylor/FEBio
|
5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6
|
[
"MIT"
] | null | null | null |
FEBioMech/FEReactiveViscoelastic.cpp
|
wzaylor/FEBio
|
5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6
|
[
"MIT"
] | null | null | null |
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEReactiveViscoelastic.h"
#include "FECore/FECoreKernel.h"
#include <FECore/FEModel.h>
#include <FECore/log.h>
#include <limits>
///////////////////////////////////////////////////////////////////////////////
//
// FEReactiveViscoelasticMaterial
//
///////////////////////////////////////////////////////////////////////////////
// Material parameters for the FEMultiphasic material
BEGIN_FECORE_CLASS(FEReactiveViscoelasticMaterial, FEElasticMaterial)
ADD_PARAMETER(m_wmin , FE_RANGE_CLOSED(0.0, 1.0), "wmin");
ADD_PARAMETER(m_btype, FE_RANGE_CLOSED(1,2), "kinetics");
ADD_PARAMETER(m_ttype, FE_RANGE_CLOSED(0,2), "trigger");
// set material properties
ADD_PROPERTY(m_pBase, "elastic");
ADD_PROPERTY(m_pBond, "bond");
ADD_PROPERTY(m_pRelx, "relaxation");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! constructor
FEReactiveViscoelasticMaterial::FEReactiveViscoelasticMaterial(FEModel* pfem) : FEElasticMaterial(pfem)
{
m_wmin = 0;
m_btype = 0;
m_ttype = 0;
m_pBase = 0;
m_pBond = 0;
m_pRelx = 0;
}
//-----------------------------------------------------------------------------
//! data initialization
bool FEReactiveViscoelasticMaterial::Init()
{
FEUncoupledMaterial* m_pMat = dynamic_cast<FEUncoupledMaterial*>((FEElasticMaterial*)m_pBase);
if (m_pMat != nullptr) {
feLogError("Elastic material should not be of type uncoupled");
return false;
}
m_pMat = dynamic_cast<FEUncoupledMaterial*>((FEElasticMaterial*)m_pBond);
if (m_pMat != nullptr) {
feLogError("Bond material should not be of type uncoupled");
return false;
}
return FEElasticMaterial::Init();
}
//-----------------------------------------------------------------------------
//! Create material point data for this material
FEMaterialPoint* FEReactiveViscoelasticMaterial::CreateMaterialPointData()
{
return new FEReactiveVEMaterialPoint(m_pBase->CreateMaterialPointData(), this);
}
//-----------------------------------------------------------------------------
//! detect new generation
bool FEReactiveViscoelasticMaterial::NewGeneration(FEMaterialPoint& mp)
{
double d;
double eps = std::numeric_limits<double>::epsilon();
// get the elastic material poit data
FEElasticMaterialPoint& pe = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
// check if the current deformation gradient is different from that of
// the last generation, in which case store the current state
// evaluate the relative deformation gradient
mat3d F = pe.m_F;
int lg = (int)pt.m_Fi.size() - 1;
mat3d Fi = (lg > -1) ? pt.m_Fi[lg] : mat3d(mat3dd(1));
mat3d Fu = F*Fi;
switch (m_ttype) {
case 0:
{
// trigger in response to any strain
// evaluate the Lagrangian strain
mat3ds E = ((Fu.transpose()*Fu).sym() - mat3dd(1))/2;
d = E.norm();
}
break;
case 1:
{
// trigger in response to distortional strain
// evaluate spatial Hencky (logarithmic) strain
mat3ds Bu = (Fu*Fu.transpose()).sym();
double l[3];
vec3d v[3];
Bu.eigen2(l,v);
mat3ds h = (dyad(v[0])*log(l[0]) + dyad(v[1])*log(l[1]) + dyad(v[2])*log(l[2]))/2;
// evaluate distortion magnitude (always positive)
d = (h.dev()).norm();
}
break;
case 2:
{
// trigger in response to dilatational strain
d = fabs(log(Fu.det()));
}
break;
default:
d = 0;
break;
}
if (d > eps) return true;
return false;
}
//-----------------------------------------------------------------------------
//! evaluate bond mass fraction
double FEReactiveViscoelasticMaterial::BreakingBondMassFraction(FEMaterialPoint& mp, const int ig, const mat3ds D)
{
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
// bond mass fraction
double w = 0;
// current time
double time = GetFEModel()->GetTime().currentTime;
switch (m_btype) {
case 1:
{
// time when this generation started breaking
double v = pt.m_v[ig];
if (time >= v)
w = pt.m_w[ig]*m_pRelx->Relaxation(mp, time - v, D);
}
break;
case 2:
{
double tu, tv;
if (ig == 0) {
tv = time - pt.m_v[ig];
w = m_pRelx->Relaxation(mp, tv, D);
}
else
{
tu = time - pt.m_v[ig-1];
tv = time - pt.m_v[ig];
w = m_pRelx->Relaxation(mp, tv, D) - m_pRelx->Relaxation(mp, tu, D);
}
}
break;
default:
break;
}
assert((w >= 0) && (w <= 1));
return w;
}
//-----------------------------------------------------------------------------
//! evaluate bond mass fraction of reforming generation
double FEReactiveViscoelasticMaterial::ReformingBondMassFraction(FEMaterialPoint& mp)
{
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
// get current number of generations
int ng = (int)pt.m_Fi.size();
double w = 1;
for (int ig=0; ig<ng-1; ++ig)
{
// evaluate relative deformation gradient for this generation Fu(v)
ep.m_F = pt.m_Fi[ig+1].inverse()*pt.m_Fi[ig];
ep.m_J = pt.m_Ji[ig]/pt.m_Ji[ig+1];
// evaluate the breaking bond mass fraction for this generation
w -= BreakingBondMassFraction(mp, ig, D);
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
assert((w >= 0) && (w <= 1));
// return the bond mass fraction of the reforming generation
return w;
}
//-----------------------------------------------------------------------------
//! Stress function
mat3ds FEReactiveViscoelasticMaterial::Stress(FEMaterialPoint& mp)
{
double dt = GetFEModel()->GetTime().timeIncrement;
if (dt == 0) return mat3ds(0, 0, 0, 0, 0, 0);
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
// calculate the base material Cauchy stress
mat3ds s = m_pBase->Stress(mp);
// current number of breaking generations
int ng = (int)pt.m_Fi.size();
// no bonds have broken
if (ng == 0) {
s += m_pBond->Stress(mp);
}
// bonds have broken
else {
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
double w;
mat3ds sb;
// calculate the bond stresses for breaking generations
for (int ig=0; ig<ng; ++ig) {
// evaluate relative deformation gradient for this generation
ep.m_F = F*pt.m_Fi[ig];
ep.m_J = J*pt.m_Ji[ig];
// evaluate bond mass fraction for this generation
w = BreakingBondMassFraction(mp, ig, D);
// evaluate bond stress
sb = m_pBond->Stress(mp);
// add bond stress to total stress
s += sb*(w*pt.m_Ji[ig]);
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
}
// return the total Cauchy stress
return s;
}
//-----------------------------------------------------------------------------
//! Material tangent
tens4ds FEReactiveViscoelasticMaterial::Tangent(FEMaterialPoint& mp)
{
CullGenerations(mp);
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
// calculate the base material tangent
tens4ds c = m_pBase->Tangent(mp);
// current number of breaking generations
int ng = (int)pt.m_Fi.size();
// no bonds have broken
if (ng == 0) {
c += m_pBond->Tangent(mp);
}
// bonds have broken
else {
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
double w;
tens4ds cb;
// calculate the bond tangents for breaking generations
for (int ig=0; ig<ng; ++ig) {
// evaluate relative deformation gradient for this generation
ep.m_F = F*pt.m_Fi[ig];
ep.m_J = J*pt.m_Ji[ig];
// evaluate bond mass fraction for this generation
w = BreakingBondMassFraction(mp, ig, D);
// evaluate bond tangent
cb = m_pBond->Tangent(mp);
// add bond tangent to total tangent
c += cb*(w*pt.m_Ji[ig]);
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
}
// return the total tangent
return c;
}
//-----------------------------------------------------------------------------
//! strain energy density function
double FEReactiveViscoelasticMaterial::StrainEnergyDensity(FEMaterialPoint& mp)
{
double dt = GetFEModel()->GetTime().timeIncrement;
if (dt == 0) return 0;
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
// get the viscous point data
mat3ds D = ep.RateOfDeformation();
// calculate the base material Cauchy stress
double sed = m_pBase->StrainEnergyDensity(mp);
// current number of breaking generations
int ng = (int)pt.m_Fi.size();
// no bonds have broken
if (ng == 0) {
sed += m_pBond->StrainEnergyDensity(mp);
}
// bonds have broken
else {
// keep safe copy of deformation gradient
mat3d F = ep.m_F;
double J = ep.m_J;
double w;
double sedb;
// calculate the strain energy density for breaking generations
for (int ig=0; ig<ng; ++ig) {
// evaluate relative deformation gradient for this generation
ep.m_F = F*pt.m_Fi[ig];
ep.m_J = J*pt.m_Ji[ig];
// evaluate bond mass fraction for this generation
w = BreakingBondMassFraction(mp, ig, D);
// evaluate bond stress
sedb = m_pBond->StrainEnergyDensity(mp);
// add bond stress to total stress
sed += sedb*w;
}
// restore safe copy of deformation gradient
ep.m_F = F;
ep.m_J = J;
}
// return the total Cauchy stress
return sed;
}
//-----------------------------------------------------------------------------
//! Cull generations that have relaxed below a threshold
void FEReactiveViscoelasticMaterial::CullGenerations(FEMaterialPoint& mp)
{
// get the elastic part
FEElasticMaterialPoint& ep = *mp.ExtractData<FEElasticMaterialPoint>();
// get the reactive viscoelastic point data
FEReactiveVEMaterialPoint& pt = *mp.ExtractData<FEReactiveVEMaterialPoint>();
mat3ds D = ep.RateOfDeformation();
if (pt.m_Fi.empty()) return;
// culling termination flag
bool done = false;
// always check oldest generation
while (!done) {
double w = BreakingBondMassFraction(mp, 0, D);
if ((w > m_wmin) || (pt.m_Fi.size() == 1))
done = true;
else {
pt.m_Fi.pop_front();
pt.m_Ji.pop_front();
pt.m_v.pop_front();
pt.m_w.pop_front();
}
}
return;
}
| 31.216216
| 114
| 0.571934
|
wzaylor
|
2d3234ac80649d190768ace625b253d8215ddcdd
| 641
|
cpp
|
C++
|
App/Lib/Bal/Test/test/testModule.cpp
|
belmayze/bal
|
710a96d011855fdab4e4b6962a2ba5b6b6b35aae
|
[
"MIT"
] | null | null | null |
App/Lib/Bal/Test/test/testModule.cpp
|
belmayze/bal
|
710a96d011855fdab4e4b6962a2ba5b6b6b35aae
|
[
"MIT"
] | null | null | null |
App/Lib/Bal/Test/test/testModule.cpp
|
belmayze/bal
|
710a96d011855fdab4e4b6962a2ba5b6b6b35aae
|
[
"MIT"
] | null | null | null |
/*!
* @file testModule.cpp
* @brief
* @author belmayze
*
* Copyright (c) 2020 belmayze. All rights reserved.
*/
// app
#include <test/testModule.h>
#include <test/container/testList.h>
#include <test/container/testTreeMap.h>
namespace app::test {
// ----------------------------------------------------------------------------
void Module::exec()
{
// container
{
// list
{
List v;
v.exec();
}
// treemap
{
TreeMap v;
v.exec();
}
}
}
// ----------------------------------------------------------------------------
}
| 16.868421
| 79
| 0.365055
|
belmayze
|
2d367d9d35a41e486d6bbcb8a6b74243ccc03b33
| 553
|
cpp
|
C++
|
Cplus/CountNumberofTexts.cpp
|
Jum1023/leetcode
|
d8248aa84452cb1ea768d9b05ecd72a6746c0016
|
[
"MIT"
] | 1
|
2018-01-22T12:06:28.000Z
|
2018-01-22T12:06:28.000Z
|
Cplus/CountNumberofTexts.cpp
|
Jum1023/leetcode
|
d8248aa84452cb1ea768d9b05ecd72a6746c0016
|
[
"MIT"
] | null | null | null |
Cplus/CountNumberofTexts.cpp
|
Jum1023/leetcode
|
d8248aa84452cb1ea768d9b05ecd72a6746c0016
|
[
"MIT"
] | null | null | null |
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
int countTexts(string pressedKeys)
{
int N = pressedKeys.length();
vector<int> keys = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4};
vector<int> dp(N + 1);
dp[N] = 1;
for (int i = N - 1; i >= 0; --i)
{
dp[i] = dp[i + 1];
int index = pressedKeys[i] - '0';
for (int j = 1; j + 1 <= keys[index] && i + j < N && pressedKeys[i + j] == pressedKeys[i]; ++j)
dp[i] = (dp[i] + dp[i + j + 1]) % MOD;
}
return dp[0];
}
private:
static const int MOD = 1e9 + 7;
};
| 21.269231
| 98
| 0.528029
|
Jum1023
|
2d387a5f8e3bb0a84f8ee21de2a5fc29af7539d8
| 1,928
|
cpp
|
C++
|
Aufgabe03/aufgabe2/main.cpp
|
Freshman83/mos.idk
|
2e8f4065228b98b612a0b284f9e552c46a5d1c04
|
[
"Apache-2.0"
] | 1
|
2020-06-14T22:47:58.000Z
|
2020-06-14T22:47:58.000Z
|
Aufgabe03/aufgabe2/main.cpp
|
Freshman83/mos.idk
|
2e8f4065228b98b612a0b284f9e552c46a5d1c04
|
[
"Apache-2.0"
] | null | null | null |
Aufgabe03/aufgabe2/main.cpp
|
Freshman83/mos.idk
|
2e8f4065228b98b612a0b284f9e552c46a5d1c04
|
[
"Apache-2.0"
] | null | null | null |
// --------------------------------------------------------------------------
// DashBoard - Aufgabe 3.2
//
// Bearbeitet von:
// Sascha Niklas, 257146
// David Rotärmel, 258201
//
// --------------------------------------------------------------------------
// Header
#include <stdio.h> // printf, fprintf
#include <stdlib.h> // exit
#include <unistd.h> // sleep
#include <math.h> // z.B. M_PI, cos(), sin()
#include <GL/glut.h>
#include "../lib/gles.h" // struct opengles, gles*-Funktionen
#include "../lib/tile.h" // struct tile, loadPngTile
GLfloat kmh2deg(GLfloat kmh)
{
if (0.0f < kmh && kmh <= 150.0f)
{
return 135.0f - kmh * 1.5f;
}
else if (kmh > 150.0f)
{
return 150.0f;
}
else
{
return 0.0;
}
}
int main(void)
{
// OpenGL ES initialisieren
struct opengles opengles;
glesInitialize(&opengles);
// Textur für Dashboard laden
struct tile dashboard = TILE_ZEROINIT;
tileLoadPng(&opengles, &dashboard, "../bilder/dashboard.png");
// Textur für Tachonadel laden
struct tile needle = TILE_ZEROINIT;
tileLoadPng(&opengles, &needle, "../bilder/needle.png");
GLfloat angle = kmh2deg(30);
do
{
// Framebuffer löschen.
glClear(GL_COLOR_BUFFER_BIT);
// Dashboard zeichnen
tileDraw(&dashboard);
// ---- Linke Tachonadel zeichnen ---------------------------
glPushMatrix();
// Tachonadel verschieben.
glTranslatef(-1.0,0.0,0.0);
// Tachonadel rotieren.
// 135.0° = 0 km/h; 0.0° = 90 km/h => 1,5° = 1 km/h
glRotatef(angle,0.0,0.0,1.0);
// Tachonadel verschieben.
glTranslatef(0.0,0.25,0.0);
// Tachonadel zeichnen.
tileDraw(&needle);
glPopMatrix();
// ---- Das gezeichnete Bild sichtbar machen ----------------
glesDraw(&opengles);
usleep(16 * 1000);
}
while(glesRun(&opengles));
// OpenGL ES Ressourcen freigeben.
glesDestroy(&opengles);
return 0;
}
/*
Push/Pop: Der letzte Befehl wird zuerst ausgeführt
*/
| 20.083333
| 77
| 0.576245
|
Freshman83
|
2d38e46592f54c07ca1e7bff0fe34a6d11224604
| 6,534
|
cpp
|
C++
|
SDKs/CryCode/3.6.15/CryEngine/CryAction/MaterialEffects/MFXDecalEffect.cpp
|
amrhead/FireNET
|
34d439aa0157b0c895b20b2b664fddf4f9b84af1
|
[
"BSD-2-Clause"
] | 4
|
2017-12-18T20:10:16.000Z
|
2021-02-07T21:21:24.000Z
|
SDKs/CryCode/3.6.15/CryEngine/CryAction/MaterialEffects/MFXDecalEffect.cpp
|
amrhead/FireNET
|
34d439aa0157b0c895b20b2b664fddf4f9b84af1
|
[
"BSD-2-Clause"
] | null | null | null |
SDKs/CryCode/3.6.15/CryEngine/CryAction/MaterialEffects/MFXDecalEffect.cpp
|
amrhead/FireNET
|
34d439aa0157b0c895b20b2b664fddf4f9b84af1
|
[
"BSD-2-Clause"
] | 3
|
2019-03-11T21:36:15.000Z
|
2021-02-07T21:21:26.000Z
|
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2006.
// -------------------------------------------------------------------------
// File name: MFXDecalEffect.cpp
// Version: v1.00
// Created: 28/11/2006 by JohnN/AlexL
// Compilers: Visual Studio.NET
// Description: Decal effect
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "MFXDecalEffect.h"
CMFXDecalEffect::CMFXDecalEffect() : m_material(0)
{
}
CMFXDecalEffect::~CMFXDecalEffect()
{
ReleaseMaterial();
}
void CMFXDecalEffect::ReadXMLNode(XmlNodeRef &node)
{
IMFXEffect::ReadXMLNode(node);
XmlNodeRef material = node->findChild("Material");
if (material)
{
m_decalParams.material = material->getContent();
// preloading is done during level loading itself
}
m_decalParams.minscale = 1.f;
m_decalParams.maxscale = 1.f;
m_decalParams.rotation = -1.f;
m_decalParams.growTime = 0.f;
m_decalParams.assemble = false;
m_decalParams.lifetime = 10.0f;
m_decalParams.forceedge = false;
XmlNodeRef scalenode = node->findChild("Scale");
if (scalenode)
{
m_decalParams.minscale = (float)atof(scalenode->getContent());
m_decalParams.maxscale = m_decalParams.minscale;
}
node->getAttr("minscale", m_decalParams.minscale);
node->getAttr("maxscale", m_decalParams.maxscale);
node->getAttr("rotation", m_decalParams.rotation);
m_decalParams.rotation = DEG2RAD(m_decalParams.rotation);
node->getAttr("growTime", m_decalParams.growTime);
node->getAttr("assembledecals", m_decalParams.assemble);
node->getAttr("forceedge", m_decalParams.forceedge);
node->getAttr("lifetime", m_decalParams.lifetime);
}
IMFXEffectPtr CMFXDecalEffect::Clone()
{
CMFXDecalEffect* clone = new CMFXDecalEffect();
clone->m_decalParams.material = m_decalParams.material;
clone->m_decalParams.minscale = m_decalParams.minscale;
clone->m_decalParams.maxscale = m_decalParams.maxscale;
clone->m_decalParams.rotation = m_decalParams.rotation;
clone->m_decalParams.growTime = m_decalParams.growTime;
clone->m_decalParams.assemble = m_decalParams.assemble;
clone->m_decalParams.forceedge = m_decalParams.forceedge;
clone->m_decalParams.lifetime = m_decalParams.lifetime;
clone->m_effectParams = m_effectParams;
return clone;
}
void CMFXDecalEffect::PreLoadAssets()
{
IMFXEffect::PreLoadAssets();
if (m_decalParams.material.c_str())
{
// store as smart pointer
m_material = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(
m_decalParams.material.c_str(),false);
}
}
void CMFXDecalEffect::ReleasePreLoadAssets()
{
IMFXEffect::ReleasePreLoadAssets();
ReleaseMaterial();
}
void CMFXDecalEffect::ReleaseMaterial()
{
// Release material (smart pointer)
m_material = 0;
}
void CMFXDecalEffect::Execute(SMFXRunTimeEffectParams ¶ms)
{
FUNCTION_PROFILER(gEnv->pSystem, PROFILE_ACTION);
if (!(params.playflags & MFX_PLAY_DECAL))
return;
// not on a static object or entity
const float angle = (params.angle != MFX_INVALID_ANGLE) ? params.angle : Random(0.f, gf_PI2);
if (!params.trgRenderNode && !params.trg)
{
CryEngineDecalInfo terrainDecal;
{ // 2d terrain
const float terrainHeight( gEnv->p3DEngine->GetTerrainElevation(params.pos.x, params.pos.y) );
const float terrainDelta( params.pos.z - terrainHeight );
if (terrainDelta > 2.0f || terrainDelta < -0.5f)
return;
terrainDecal.vPos = Vec3(params.decalPos.x, params.decalPos.y, terrainHeight);
}
terrainDecal.vNormal = params.normal;
terrainDecal.vHitDirection = params.dir[0].GetNormalized();
terrainDecal.fLifeTime = m_decalParams.lifetime;
terrainDecal.fGrowTime = m_decalParams.growTime;
if (!m_decalParams.material.empty())
strcpy(terrainDecal.szMaterialName, m_decalParams.material.c_str());
else
CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "CMFXDecalEffect::Execute: Decal material name is not specified");
terrainDecal.fSize = Random(m_decalParams.minscale, m_decalParams.maxscale);
if(m_decalParams.rotation>=0.f)
terrainDecal.fAngle = m_decalParams.rotation;
else
terrainDecal.fAngle = angle;
if(terrainDecal.fSize <= params.fDecalPlacementTestMaxSize)
gEnv->p3DEngine->CreateDecal(terrainDecal);
}
else
{
CryEngineDecalInfo decal;
IEntity *pEnt = gEnv->pEntitySystem->GetEntity(params.trg);
IRenderNode* pRenderNode = NULL;
if (pEnt)
{
IEntityRenderProxy *pRenderProxy = (IEntityRenderProxy*)pEnt->GetProxy(ENTITY_PROXY_RENDER);
if (pRenderProxy)
pRenderNode = pRenderProxy->GetRenderNode();
}
else
{
pRenderNode = params.trgRenderNode;
}
// filter out ropes
if (pRenderNode && pRenderNode->GetRenderNodeType() == eERType_Rope)
return;
decal.ownerInfo.pRenderNode = pRenderNode;
decal.vPos = params.pos;
decal.vNormal = params.normal;
decal.vHitDirection = params.dir[0].GetNormalized();
decal.fLifeTime = m_decalParams.lifetime;
decal.fGrowTime = m_decalParams.growTime;
decal.bAssemble = m_decalParams.assemble;
decal.bForceEdge = m_decalParams.forceedge;
if (!m_decalParams.material.empty())
strcpy(decal.szMaterialName, m_decalParams.material.c_str());
else
CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "CMFXDecalEffect::Execute: Decal material name is not specified");
decal.fSize = Random(m_decalParams.minscale, m_decalParams.maxscale);
if(m_decalParams.rotation>=0.f)
decal.fAngle = m_decalParams.rotation;
else
decal.fAngle = angle;
if(decal.fSize <= params.fDecalPlacementTestMaxSize)
gEnv->p3DEngine->CreateDecal(decal);
}
}
void CMFXDecalEffect::GetResources(SMFXResourceList &rlist)
{
SMFXDecalListNode *listNode = SMFXDecalListNode::Create();
listNode->m_decalParams.material = m_decalParams.material.c_str();
listNode->m_decalParams.minscale = m_decalParams.minscale;
listNode->m_decalParams.maxscale = m_decalParams.maxscale;
listNode->m_decalParams.rotation = m_decalParams.rotation;
listNode->m_decalParams.assemble = m_decalParams.assemble;
listNode->m_decalParams.forceedge = m_decalParams.forceedge;
listNode->m_decalParams.lifetime = m_decalParams.lifetime;
SMFXDecalListNode* next = rlist.m_decalList;
if (!next)
rlist.m_decalList = listNode;
else
{
while (next->pNext)
next = next->pNext;
next->pNext = listNode;
}
}
| 29.7
| 129
| 0.712274
|
amrhead
|
2d3bb4ef8e93d2b8d86ac5bb77b0e7864bcde0bc
| 5,309
|
hh
|
C++
|
DetectorModel/DetElem.hh
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
DetectorModel/DetElem.hh
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
DetectorModel/DetElem.hh
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
// ------------------------------------------------------------------------------
// File and Version Information:
// $Id: DetElem.hh,v 1.32 2004/12/14 07:10:17 bartoldu Exp $
//
// Description:
// Base Class to define a specific element of the tracking detector. The types
// must exist before elements can be created from them. Also the subclasses
// are responsable for providing the HepTransformation* to the base class
// (note: the DetElem HepTransformation pointer MUST point to a valid
// transform, which is owned (perhaps indirectly) by the element itself).
// This class is the main interface between abstract
// track representations (hits and fit parameters) and the 3-D material
// model.
//
// Copyright Information:
// Copyright (C) 1996 Lawrence Berkeley Laboratory
//
// Authors: Dave Brown, 7/17/96
// ------------------------------------------------------------------------------
#ifndef DETECTORELEMENT_HH
#define DETECTORELEMENT_HH
//----------------
// BaBar header --
//----------------
#if defined( HP1022 ) && !defined( BABAR_HH )
#include "BaBar/BaBar.hh"
#include "ErrLogger/ErrLog.hh"
#endif // HP1022 && !BABAR_HH
//
// global includes
//
#include <iostream>
#include <string>
#include "CLHEP/Geometry/HepPoint.h"
#include <vector>
//
// Local includes
//
#include "DetectorModel/DetType.hh"
#include "PDT/PdtPid.hh"
#include "TrkBase/TrkDirection.hh"
//
class TrkDifTraj;
class Trajectory;
class DetType;
class DetElem;
class DetAlignElem;
class HepTransformation;
class DetIntersection;
class GnuPlot;
//
// Define the class
//
class DetElem{
public:
//
// Constructors
//
DetElem();
DetElem(const DetType*,const char*,int);
// Assignment operator
DetElem& operator = (const DetElem&);
// equality operator (needed for old templates)
bool operator == (const DetElem& other) const;
// see if an align elem matches this element
bool match(const DetAlignElem& ae) const;
//
// Destructor
//
virtual ~DetElem();
//
// Geometric functions
//
// Intersect a trajectory with this detector element. The DetIntersection
// reference range limits initially define the search range and start value, but
// are returned as the entrance and exit point of the intersection. If the input
// lower limit is >= the upper limit, the range is ignored.
//
virtual int intersect(const Trajectory*,DetIntersection&) const = 0;
//
// Material information from an intersection. Default base class versions
// are provided which assume any given intersection goes through only
// one type of material. If this is not the case, the element subclass
// must overwrite these functions. The user interface is only the second
// function, which calls the first in the base class implementation. This
// allows subclasses which are not homogenous but still have only one
// material type for a given intersection to use the base implementation
// of materialInfo, only overwriting the base of material.
//
// Note, this function now returns the (dimensionless) fractional
// change in momentum associated with energy loss, not the energy
// loss itself (ditto for the energy loss RMS).
//
// DNB 3/13/00 Added the particle direction as an argument to materialInfo;
// trkIn means the particle is passing inwards (pfrac>0),
// trkOut for passing outwards (pfrac<0) through the material.
public:
virtual const DetMaterial& material(const DetIntersection&) const;
virtual void materialInfo(const DetIntersection&,
double momentum,
PdtPid::PidType pid,
double& deflectRMS,
double& pFractionRMS,
double& pFraction,
trkDirection dedxdir=trkOut) const;
//
// Alignment functions. The name and ID number of the local DetAlignElem
// must match that of the DetElem.
//
void applyGlobal(const DetAlignElem&);// apply global alignment
void applyLocal(const DetAlignElem&); // apply local alignment
void removeGlobal(const DetAlignElem&);// unapply global alignment
void removeLocal(const DetAlignElem&); // unapply local alignment
virtual void updateCache(); // update an elements cache (used for subclasses)
//
// Access functions
//
virtual void print(std::ostream& os) const;
virtual void printAll(std::ostream& os ) const;
const DetType* detectorType() const { return _dtype; }
int elementNumber() const {return _ielem; }
const std::string& elementName() const {return _ename; }
const HepTransformation& transform() const { return *_etrans; }
//
// Outline function
//
virtual void physicalOutline(std::vector<HepPoint>&) const;
virtual void gnuPlot( GnuPlot* ) const;
protected:
virtual HepPoint coordToPoint( const TypeCoord* aCoord ) const = 0;
// the ElemPointIterator class must be able to access coordToPoint function
friend class DetElemPointIterator;
// Following is so derived classes can set transform through method
HepTransformation*& myTransf() { return _etrans; }
HepTransformation& transf() { return *_etrans; } // nonconst transform
// private:
int _ielem; // integer identifier; this is controled by the sub-class
const std::string _ename; // name
const DetType* _dtype; // pointer to the type
HepTransformation* _etrans; // spatial transform
// this is used in the DetElemSet subclass of DetSet
friend class DetElemSet;
};
#endif
| 36.363014
| 81
| 0.70955
|
brownd1978
|
2d3f52c0e5774d7b23a26448ba4d68899d0c1413
| 5,489
|
cpp
|
C++
|
clessc/src/Selector.cpp
|
shoichikaji/CSS-clessc
|
194be6f00ad6f9277efedd7cadab76c6f69a540e
|
[
"Artistic-1.0"
] | 1
|
2015-03-17T06:27:25.000Z
|
2015-03-17T06:27:25.000Z
|
clessc/src/Selector.cpp
|
shoichikaji/CSS-clessc
|
194be6f00ad6f9277efedd7cadab76c6f69a540e
|
[
"Artistic-1.0"
] | null | null | null |
clessc/src/Selector.cpp
|
shoichikaji/CSS-clessc
|
194be6f00ad6f9277efedd7cadab76c6f69a540e
|
[
"Artistic-1.0"
] | null | null | null |
/*
* Copyright 2012 Bram van der Kroef
*
* This file is part of LESS CSS Compiler.
*
* LESS CSS Compiler is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LESS CSS Compiler is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LESS CSS Compiler. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Bram van der Kroef <bram@vanderkroef.net>
*/
#include "Selector.h"
#include <iostream>
#ifdef WITH_LIBGLOG
#include <glog/logging.h>
#endif
Selector::~Selector() {
clear();
}
void Selector::addPrefix(const Selector &prefix) {
list<Selector> prefixParts;
list<Selector> sepParts;
list<Selector>::iterator prefixIt;
list<Selector>::iterator sepIt;
Selector* tmp, *prefixPart;
TokenList::iterator i;
bool containsAmp;
Token space(" ", Token::WHITESPACE),
comma(",", Token::OTHER);
split(sepParts);
prefix.split(prefixParts);
clear();
for (sepIt = sepParts.begin();
sepIt != sepParts.end(); sepIt++) {
tmp = &(*sepIt);
tmp->ltrim();
containsAmp = tmp->contains(Token::OTHER, "&");
for (prefixIt = prefixParts.begin();
prefixIt != prefixParts.end(); prefixIt++) {
prefixPart = &(*prefixIt);
if (containsAmp) {
for (i = tmp->begin(); i != tmp->end(); i++) {
if (*i == "&")
insert(end(), prefixPart->begin(), prefixPart->end());
else
push_back(*i);
}
} else {
insert(end(), prefixPart->begin(), prefixPart->end());
push_back(space);
insert(end(), tmp->begin(), tmp->end());
}
push_back(comma);
}
}
pop_back();
}
void Selector::split(std::list<Selector> &l) const {
TokenList::const_iterator first, last;
Selector current;
for (first = begin(); first != end(); ) {
last = findComma(first);
current.assign(first, last);
#ifdef WITH_LIBGLOG
VLOG(3) << "Split: " << current.toString();
#endif
l.push_back(current);
first = last;
if (first != end())
first++;
}
}
TokenList::const_iterator Selector::findComma(const_iterator offset)
const {
return findComma(offset, end());
}
TokenList::const_iterator Selector::findComma(const_iterator offset,
const_iterator limit) const {
unsigned int parentheses = 0;
for (; offset != limit; offset++) {
if (parentheses == 0 &&
(*offset).type == Token::OTHER &&
*offset == ",") {
return offset;
} else {
if (*offset == "(")
parentheses++;
else if (*offset == ")")
parentheses--;
}
}
return offset;
}
bool Selector::match(const Selector &list) const {
TokenList::const_iterator first, last;
TokenList::const_iterator l_first, l_last;
for (first = begin(); first != end(); ) {
last = findComma(first);
for (l_first = list.begin(); l_first != list.end(); ) {
l_last = list.findComma(l_first);
if (walk(l_first, l_last, first) == last)
return true;
l_first = l_last;
if (l_first != list.end()) {
l_first++;
while (l_first != list.end() && (*l_first).type == Token::WHITESPACE)
l_first++;
}
}
first = last;
if (first != end()) {
first++;
while (first != end() && (*first).type == Token::WHITESPACE)
first++;
}
}
return false;
}
TokenList::const_iterator Selector::walk(const Selector &list,
const_iterator offset) const {
TokenList::const_iterator first, last, pos;
for (first = list.begin(); first != list.end(); ) {
last = list.findComma(first);
pos = walk(first, last, offset);
if (pos != begin())
return pos;
first = last;
if (first != list.end()) {
first++;
while (first != list.end() && (*first).type == Token::WHITESPACE)
first++;
}
}
return begin();
}
TokenList::const_iterator Selector::walk(const const_iterator &list_begin,
const const_iterator &list_end,
const_iterator offset) const {
TokenList::const_iterator li = list_begin;
while (offset != end() && li != list_end) {
if (*offset != *li)
return begin();
offset++;
li++;
if (offset != end() && *offset == ">") {
offset++;
if (offset != end() && (*offset).type == Token::WHITESPACE)
offset++;
}
if (li != list_end && *li == ">") {
li++;
if (li != list_end && (*li).type == Token::WHITESPACE)
li++;
}
}
if (li != list_end)
offset = begin();
return offset;
}
TokenList::const_iterator Selector::find(const TokenList &list,
TokenList::const_iterator offset,
TokenList::const_iterator limit) const {
for (; offset != limit; offset++) {
if (walk(list.begin(), list.end(), offset) != begin())
return offset;
}
return limit;
}
| 25.178899
| 81
| 0.567316
|
shoichikaji
|
2d40e9d2a5dd8d0b7d0a30d5b57c75c3acc3dead
| 1,240
|
cpp
|
C++
|
Game/GameEngine/Events/EventMove.cpp
|
arthurChennetier/R-Type
|
bac6f8cf6502f74798181181a819d609b1d82e3a
|
[
"MIT"
] | 1
|
2018-07-22T13:45:47.000Z
|
2018-07-22T13:45:47.000Z
|
Game/GameEngine/Events/EventMove.cpp
|
arthurChennetier/R-Type
|
bac6f8cf6502f74798181181a819d609b1d82e3a
|
[
"MIT"
] | null | null | null |
Game/GameEngine/Events/EventMove.cpp
|
arthurChennetier/R-Type
|
bac6f8cf6502f74798181181a819d609b1d82e3a
|
[
"MIT"
] | 1
|
2018-07-20T12:52:42.000Z
|
2018-07-20T12:52:42.000Z
|
//
// Created by chauvin on 28/01/18.
//
#include "EventMove.hpp"
#include "../Rigidbody/Rigidbody.hpp"
#include "../Input/Input.h"
TacosEngine::EventMove::EventMove(const std::shared_ptr<TacosEngine::GameObject> &obj, const Vector2 &dir)
{
this->_object = obj;
this->_dir = dir;
std::cout << "X :" << dir.get_x() << "Y :" << dir.get_y() << std::endl;
}
void TacosEngine::EventMove::onEvent()
{
std::cout << "MOVE" << std::endl;
auto rb = this->_object->getComponent<Rigidbody>();
CheckWindowCollide(_dir);
_object->getTransform().setDirection(_dir);
_object->getTransform().setSpeed(2.5);
rb->addForce(_dir * _object->getTransform().getSpeed());
}
TacosEngine::Vector2 &TacosEngine::EventMove::CheckWindowCollide(TacosEngine::Vector2 &dir)
{
if (dir.get_x() < 0 && _object->getTransform().getPosition().get_x() <= 0.5 ||
dir.get_x() > 0 && _object->getTransform().getPosition().get_x() >= (799.5 - _object->getScene()->getWindowSize().get_x()))
dir.set_x(0);
if (dir.get_y() > 0 && _object->getTransform().getPosition().get_y() >= (399.5 - _object->getScene()->getWindowSize().get_y()) ||
dir.get_y() < 0 && _object->getTransform().getPosition().get_y() <= 0.5)
dir.set_y(0);
return dir;
}
| 33.513514
| 131
| 0.651613
|
arthurChennetier
|
2d438f7c51dd615adffd85f9b5201eab1a437bbc
| 863
|
hpp
|
C++
|
src/cipher/DummyCipher.hpp
|
devktor/libbitcrypto
|
1b08fb75e6884a622f3a646bfb7bf22609f968ea
|
[
"MIT"
] | 1
|
2016-01-31T14:16:41.000Z
|
2016-01-31T14:16:41.000Z
|
src/cipher/DummyCipher.hpp
|
BitProfile/libethcrypto
|
1b08fb75e6884a622f3a646bfb7bf22609f968ea
|
[
"MIT"
] | null | null | null |
src/cipher/DummyCipher.hpp
|
BitProfile/libethcrypto
|
1b08fb75e6884a622f3a646bfb7bf22609f968ea
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <stdexcept>
#include "../detail/Data.hpp"
#include "../key/PrivateKey.hpp"
#include "EncryptedData.hpp"
#include "ScryptParams.hpp"
#include "ScryptParamsGenerator.hpp"
namespace Ethereum{
class DummyKey
{};
class DummyCipher
{
public:
typedef ScryptParams KdfParams;
public:
DummyCipher();
DummyCipher(const Data &, const ScryptParams &);
template<class Key>
PrivateKey decrypt(const EncryptedData &, const Key &) const;
template<class Key>
EncryptedData encrypt(const PrivateKey &, const Key &) const;
const Data & getIV() const;
const ScryptParams & getParams() const;
DummyCipher & operator = (const DummyCipher &);
private:
Data _iv;
ScryptParams _params;
};
}
#include "DummyCipher.ipp"
| 17.26
| 69
| 0.651217
|
devktor
|
2d4a525f107c2b72b03cc24ddd09e71ed1cc6962
| 618
|
cpp
|
C++
|
1098_Sequence IJ 4.cpp
|
Aunkon/URI
|
668181ba977d44823d228b6ac01dfed16027d524
|
[
"RSA-MD"
] | null | null | null |
1098_Sequence IJ 4.cpp
|
Aunkon/URI
|
668181ba977d44823d228b6ac01dfed16027d524
|
[
"RSA-MD"
] | null | null | null |
1098_Sequence IJ 4.cpp
|
Aunkon/URI
|
668181ba977d44823d228b6ac01dfed16027d524
|
[
"RSA-MD"
] | null | null | null |
/**** Md. Walid Bin khalid Aunkon ****/
/**** Daffodil International University ****/
/**** ID: 121-15-1669 ****/
/**** Email: mdwalidbinkhalidaunkon@gmail.com ****/
/**** Mobile No: +88-01916-492926 ****/
#include<bits/stdc++.h>
using namespace std;
int main()
{
double i,j=1;
for(i=0;i<=2;i+=.2)
{
cout << "I=" << i << " " << "J=" << j+i << "\n";
cout << "I=" << i << " " << "J=" << j+i+1 << "\n";
cout << "I=" << i << " " << "J=" << j+i+2 << "\n";
}
return 0;
}
| 32.526316
| 62
| 0.351133
|
Aunkon
|
2d4d91501f4073ae4acd194f5d365eee47cf6b21
| 380
|
cc
|
C++
|
nofx/nofx_ofTexture/nofx_ofEnableNormalizedTexCoords.cc
|
sepehr-laal/nofx
|
7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e
|
[
"MIT"
] | null | null | null |
nofx/nofx_ofTexture/nofx_ofEnableNormalizedTexCoords.cc
|
sepehr-laal/nofx
|
7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e
|
[
"MIT"
] | null | null | null |
nofx/nofx_ofTexture/nofx_ofEnableNormalizedTexCoords.cc
|
sepehr-laal/nofx
|
7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e
|
[
"MIT"
] | null | null | null |
#include "nofx_ofEnableNormalizedTexCoords.h"
#include "ofTexture.h"
namespace nofx
{
namespace ClassWrappers
{
NAN_METHOD(nofx_ofEnableNormalizedTexCoords)
{
ofEnableNormalizedTexCoords();
NanReturnUndefined();
} // !nofx_ofEnableNormalizedTexCoords
} // !namespace ClassWrappers
} // !namespace nofx
| 23.75
| 52
| 0.647368
|
sepehr-laal
|
2d5484871292df699cffd6926ea3afb2238d9dc3
| 18,529
|
cpp
|
C++
|
SOURCES/sim/digi/sfusion.cpp
|
IsraelyFlightSimulator/Negev-Storm
|
86de63e195577339f6e4a94198bedd31833a8be8
|
[
"Unlicense"
] | 1
|
2021-02-19T06:06:31.000Z
|
2021-02-19T06:06:31.000Z
|
src/sim/digi/sfusion.cpp
|
markbb1957/FFalconSource
|
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
|
[
"BSD-2-Clause"
] | null | null | null |
src/sim/digi/sfusion.cpp
|
markbb1957/FFalconSource
|
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
|
[
"BSD-2-Clause"
] | 2
|
2019-08-20T13:35:13.000Z
|
2021-04-24T07:32:04.000Z
|
#include "stdhdr.h"
#include "classtbl.h"
#include "digi.h"
#include "sensors.h"
#include "simveh.h"
#include "missile.h"
#include "object.h"
#include "sensclas.h"
#include "Entity.h"
#include "team.h"
#include "Aircrft.h"
/* 2001-03-15 S.G. */#include "campbase.h"
/* 2001-03-21 S.G. */#include "flight.h"
/* 2001-03-21 S.G. */#include "atm.h"
#include "RWR.h" // 2002-02-11 S.G.
#include "Radar.h" // 2002-02-11 S.G.
#include "simdrive.h" // 2002-02-17 S.G.
#define MAX_NCTR_RANGE (60.0F * NM_TO_FT) // 2002-02-12 S.G. See RadarDoppler.h
/* 2001-09-07 S.G. RP5 */ extern bool g_bRP5Comp;
extern int g_nLowestSkillForGCI; // 2002-03-12 S.G. Replaces the hardcoded '3' for skill test
extern bool g_bUseNewCanEnage; // 2002-03-11 S.G.
int GuestimateCombatClass(AircraftClass *self, FalconEntity *baseObj); // 2002-03-11 S.G.
FalconEntity* SpikeCheck (AircraftClass* self, FalconEntity *byHim = NULL, int *data = NULL);// 2002-02-10 S.G.
void DigitalBrain::SensorFusion(void)
{
SimObjectType* obj = targetList;
float turnTime=0.0F,timeToRmax=0.0F,rmax=0.0F,tof=0.0F,totV=0.0F;
SimObjectLocalData* localData=NULL;
int relation=0, pcId= ID_NONE, canSee=FALSE, i=0;
FalconEntity* baseObj=NULL;
// 2002-04-18 REINSTATED BY S.G. After putting back '||' instead of '&&' before "localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime" below, this is no longer required
// 2002-02-17 MODIFIED BY S.G. Sensor routines for AI runs less often than SensorFusion therefore the AI will time out his target after this delayTime as elapsed.
// By using the highest of both, I'm sure this will not happen...
int delayTime = SimLibElapsedTime - 6*SEC_TO_MSEC*(SkillLevel() + 1);
/* int delayTime;
unsigned int fromSkill = 6 * SEC_TO_MSEC * (SkillLevel() + 1);
if (fromSkill > self->targetUpdateRate)
delayTime = SimLibElapsedTime - fromSkill;
else
delayTime = SimLibElapsedTime - self->targetUpdateRate;
*/
/*--------------------*/
/* do for all objects */
/*--------------------*/
while (obj)
{
localData = obj->localData;
baseObj = obj->BaseData();
//if (F4IsBadCodePtr((FARPROC) baseObj)) // JB 010223 CTD
if (F4IsBadCodePtr((FARPROC) baseObj) || F4IsBadReadPtr(baseObj, sizeof(FalconEntity))) // JB 010305 CTD
break; // JB 010223 CTD
// Check all sensors for contact
canSee = FALSE;//PUt to true for testing only
//Cobra Begin rebuilding this function.
//GCI Code
CampBaseClass *campBaseObj = (CampBaseClass *)baseObj;
if (baseObj->IsSim())
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
// If the object is a weapon, don't do GCI on it
if (baseObj->IsWeapon())
campBaseObj = NULL;
// Only if we have a valid base object...
// This code is to make sure our GCI targets are prioritized, just like other targets
if (campBaseObj)
if (campBaseObj->GetSpotted(self->GetTeam()))
canSee = TRUE;
if (localData->sensorState[SensorClass::RWR] >= SensorClass::SensorTrack)
{
canSee = TRUE;
detRWR = 1;
}
else
detRWR = 0;
if (localData->sensorState[SensorClass::Radar] >= SensorClass::SensorTrack)
{
canSee = TRUE;
detRAD = 1;
}
else
detRAD = 0;
if (localData->sensorState[SensorClass::Visual] >= SensorClass::SensorTrack)
{
canSee = TRUE;
detVIS = 1;
}
else
detVIS = 0;
//End
/* if (!g_bRP5Comp) {
// Aces get to use GCI
// Idiots find out about you inside 1 mile anyway
if (localData->range > 3.0F * NM_TO_FT && // gci is crap inside 3nm
(SkillLevel() >= 2 &&
localData->range < 25.0F * NM_TO_FT||
SkillLevel() >=3 &&
localData->range < 35.0F * NM_TO_FT||
SkillLevel() >=4 &&
localData->range < 55.0F * NM_TO_FT)
)//me123 not if no sensor has seen it || localData->range < 1.0F * NM_TO_FT)
{
canSee = TRUE;
}
// You can always see your designated target
if (baseObj->Id() == mDesignatedObject && localData->range > 8.0F * NM_TO_FT)
{
canSee = TRUE;//me123
}
for (i = 0; i<self->numSensors && !canSee; i++)
{
if (localData->sensorState[self->sensorArray[i]->Type()] > SensorClass::NoTrack ||
localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime)
{
canSee = TRUE;
break;
}
}
}
else {*/
// 2001-03-21 REDONE BY S.G. SO SIM AIRPLANE WIL FLAG FLIGHT/AIRPLANE AS DETECTED AND WILL PROVIDE GCI
/*#if 0
// Aces get to use GCI
// Idiots find out about you inside 1 mile anyway
if (SkillLevel() >= 3 && localData->range < 15.0F * NM_TO_FT || localData->range < 1.0F * NM_TO_FT)
{
canSee = TRUE;
}
// You can always see your designated target
if (baseObj->Id() == mDesignatedObject && localData->range > 8.0F * NM_TO_FT)
{
canSee = TRUE;
}
for (i = 0; i<self->numSensors && !canSee; i++)
{
if (localData->sensorState[self->sensorArray[i]->Type()] > SensorClass::NoTrack ||
localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime)
{
canSee = TRUE;
break;
}
}
#else */
// First I'll get the campaign object if it's for a sim since I use it at many places...
/*CampBaseClass *campBaseObj = (CampBaseClass *)baseObj;
if (baseObj->IsSim())
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
// If the object is a weapon, don't do GCI on it
if (baseObj->IsWeapon())
campBaseObj = NULL;
// This is our GCI implementation... Ace and Veteran gets to use GCI.
// Only if we have a valid base object...
// This code is to make sure our GCI targets are prioritized, just like other targets
if (campBaseObj && SkillLevel() >= g_nLowestSkillForGCI && localData->range < 30.0F * NM_TO_FT)
if (campBaseObj->GetSpotted(self->GetTeam()))
canSee = TRUE;
// You can always see your designated target
if (baseObj->Id() == mDesignatedObject && localData->range > 8.0F * NM_TO_FT)
canSee = TRUE;*/
//if (SimDriver.RunningDogfight()) // 2002-02-17 ADDED BY S.G. If in dogfight, don't loose sight of your opponent.
//canSee = TRUE; //Cobra removed to test
// Go through all your sensors. If you 'see' the target and are bright enough, flag it as spotted and ask for an intercept if this FLIGHT is spotted for the first time...
//for (i = 0; i<self->numSensors; i++) {
//if (localData->sensorState[self->sensorArray[i]->Type()] > SensorClass::NoTrack || localData->sensorLoopCount[self->sensorArray[i]->Type()] > delayTime) { // 2002-04-18 MODIFIED BY S.G. Reverted to && instead of ||. *MY* logic was flawed. It gaves a 'delay' (grace period) after the sensor becomes 'NoLock'.
//if (campBaseObj && /*&& SkillLevel() >= g_nLowestSkillForGCI &&*/ !((UnitClass *)self->GetCampaignObject())->Broken()) {//Cobra removed GCI test here...not needed
//if (!campBaseObj->GetSpotted(self->GetTeam()) && campBaseObj->IsFlight())
//RequestIntercept((FlightClass *)campBaseObj, self->GetTeam());
// 2002-02-11 ADDED BY S.G. If the sensor can identify the target, mark it identified as well
/*int identified = FALSE;
if (self->sensorArray[i]->Type() == SensorClass::RWR) {
if (((RwrClass *)self->sensorArray[i])->GetTypeData()->flag & RWR_EXACT_TYPE)
identified = TRUE;
}
else if (self->sensorArray[i]->Type() == SensorClass::Radar) {
if (((RadarClass *)self->sensorArray[i])->GetRadarDatFile() && (((RadarClass *)self->sensorArray[i])->radarData->flag & RAD_NCTR) && localData->ataFrom < 45.0f * DTR && localData->range < ((RadarClass *)self->sensorArray[i])->GetRadarDatFile()->MaxNctrRange / (2.0f * (16.0f - (float)SkillLevel()) / 16.0f)) // 2002-03-05 MODIFIED BY S.G. target's aspect and skill used in the equation
identified = TRUE;
}
else
identified = TRUE;
campBaseObj->SetSpotted(self->GetTeam(),TheCampaign.CurrentTime, identified);
}
//canSee = TRUE; //Cobra we are removing these to test, this gave everything can see!
//break;
continue;
}
}
//#endif
}*/
/*--------------------------------------------------*/
/* Sensor id state */
/* RWR ids coming from RWR_INTERP can be incorrect. */
/* Visual identification is 100% correct. */
/*--------------------------------------------------*/
if (canSee)
{
//Cobra moved spotted stuff here
CampBaseClass *campBaseObj = (CampBaseClass *)baseObj;
if (baseObj->IsSim())
{
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
if (campBaseObj)
campBaseObj->SetSpotted(self->GetTeam(),TheCampaign.CurrentTime, 1);
}
if (baseObj->IsMissile())
{
pcId = ID_MISSILE;
}
else if (baseObj->IsBomb())
{
pcId = ID_NEUTRAL;
}
else
{
if (TeamInfo[self->GetTeam()]) // JB 010617 CTD
{
relation = TeamInfo[self->GetTeam()]->TStance(obj->BaseData()->GetTeam());
switch (relation)
{
case Hostile:
case War:
pcId = ID_HOSTILE;
break;
case Allied:
case Friendly:
pcId = ID_FRIENDLY;
break;
case Neutral:
pcId = ID_NEUTRAL;
break;
}
}
}
}
//Cobra Rewrite. Score threats
if (canSee)
{
int hisCombatClass = -1;
bool isHelo = FALSE;
float threatRng = 0.0f;
int totalThreat = 0;
if (baseObj)
{
hisCombatClass = baseObj->CombatClass();
if (baseObj->IsHelicopter())
isHelo = TRUE;
}
if (pcId == ID_HOSTILE)//Something we can shoot at
{
//Score combatclass
if (hisCombatClass <=4 && hisCombatClass >= 2)
totalThreat += 50;
else
totalThreat += 30;
if (localData->ataFrom > 90*DTR)
totalThreat = totalThreat/2;
if (localData->range < maxAAWpnRange)
totalThreat += 20;
if (missionType == AMIS_BARCAP || missionType == AMIS_BARCAP2 || missionComplete
|| (missionClass == AGMission && !IsSetATC(HasAGWeapon)))
{
if (isHelo || hisCombatClass >= 7)
totalThreat = 5;
}
else if (isHelo || hisCombatClass >= 7)
totalThreat = 0;
//is this our target?
CampBaseClass *campObj;
if (baseObj->IsSim())
campObj = ((SimBaseClass *)baseObj)->GetCampaignObject();
else
campObj = (CampBaseClass *)baseObj;
int isMissionTarget = campObj && (((FlightClass *)(self->GetCampaignObject()))-> GetUnitMissionTargetID() == campObj->Id() ||
((FlightClass *)(self->GetCampaignObject()))->GetAssignedTarget() == campObj->Id());
if (isMissionTarget)
totalThreat += 10;
localData->threatScore = totalThreat;
}
else if (pcId == ID_MISSILE)
{
if (obj->BaseData()->GetTeam() == self->GetTeam())
{
localData->threatScore = 0;
}
else
{
localData->threatScore = 90;
}
}
else
localData->threatScore = 0;
}//end cobra
/*----------------------------------------------------*/
/* Threat determination */
/* Assume threat has your own longest range missile. */
/* Hypothetical time before we're in the mort locker. */
/* If its a missile calculate time to impact. */
/*---------------------------------------------------*/
/*
localData->threatTime = 2.0F * MAX_THREAT_TIME;
if (canSee)
{
if (baseObj->IsMissile())
{
if (pcId == ID_MISSILE)
{
if (obj->BaseData()->GetTeam() == self->GetTeam())
{
localData->threatTime = 2.0F * MAX_THREAT_TIME;
}
else
{
if (localData->sensorState[SensorClass::RWR] >= SensorClass::SensorTrack)
localData->threatTime = localData->range / AVE_AIM120_VEL;
else
localData->threatTime = localData->range / AVE_AIM9L_VEL;
}
}
else localData->threatTime = MAX_THREAT_TIME;
}
else if ((baseObj->IsAirplane() || (baseObj->IsFlight() && !baseObj->IsHelicopter())) && pcId != ID_NONE && pcId < ID_NEUTRAL && GuestimateCombatClass(self, baseObj) < MnvrClassA10)
{
//TJL 11/07/03 VO log says there is an radian error in this code
// I think it is here. ataFrom is in radians
//turnTime = localData->ataFrom / FIVE_G_TURN_RATE;
turnTime = localData->ataFrom*RTD / FIVE_G_TURN_RATE;// 15.9f degrees per second
//TJL 11/07/03 Cos takes radians, thus no *DTR
//totV = obj->BaseData()->GetVt() + self->GetVt()*(float)cos(localData->ata*DTR);
totV = obj->BaseData()->GetVt() + self->GetVt()*(float)cos(localData->ata);
if (SpikeCheck(self) == obj->BaseData())//me123 addet
rmax = 2.5f*60762.11F;
else
rmax = 60762.11F;
if (localData->range > rmax)
{
if ( totV <= 0.0f )
{
timeToRmax = MAX_THREAT_TIME * 2.0f;
}
else
{
timeToRmax = (localData->range - rmax) / totV;
tof = rmax / AVE_AIM120_VEL;
}
}
else
{
timeToRmax = 0.0F;
tof = localData->range / AVE_AIM120_VEL;
}
localData->threatTime = turnTime + timeToRmax + tof;
}
else
{
localData->threatTime = 2.0F * MAX_THREAT_TIME;
}
}
*/
/*----------------------------------------------------*/
/* Targetability determination */
/* Use the longest range missile currently on board */
/* Hypothetical time before the tgt ac can be morted */
/* */
/* Aircraft on own team are returned SENSOR_UNK */
/*----------------------------------------------------*/
// 2002-03-05 MODIFIED BY S.G. CombatClass is defined for FlightClass and AircraftClass now and is virtual in FalconEntity which will return 999
// This code restrict the calculation of the missile range to either planes, chopper or flights. An aggregated chopper flight will have 'IsFlight' set so check if the 'AirUnitClass::IsHelicopter' function returned TRUE to screen them out from aircraft type test
// Have to be at war against us
// Chopper must be our assigned or mission target or we must be on sweep (not a AMIS_SWEEP but still has OnSweep set)
// Must be worth shooting at, unless it's our assigned or mission target (new addition so AI can go after an AWACS for example if it's their target...
// if (canSee && baseObj->IsAirplane() && pcId < ID_NEUTRAL &&
// (IsSetATC(OnSweep) || ((AircraftClass*)baseObj)->CombatClass() < MnvrClassA10))
// 2002-03-11 MODIFIED BY S.G. Don't call CombatClass directly but through GuestimateCombatClass which doesn't assume you have an ID on the target
// Since I'm going to check for this twice in the next if statement, do it once here but also do the 'canSee' test which is not CPU intensive and will prevent the test from being performed if can't see.
/*
CampBaseClass *campObj;
if (baseObj->IsSim())
campObj = ((SimBaseClass *)baseObj)->GetCampaignObject();
else
campObj = (CampBaseClass *)baseObj;
int isMissionTarget = canSee && campObj && (((FlightClass *)(self->GetCampaignObject()))->GetUnitMissionTargetID() == campObj->Id() || ((FlightClass *)(self->GetCampaignObject()))->GetAssignedTarget() == campObj->Id());
if (canSee &&
(baseObj->IsAirplane() || (baseObj->IsFlight() && !baseObj->IsHelicopter()) || (baseObj->IsHelicopter() && ((missionType != AMIS_SWEEP && IsSetATC(OnSweep)) || isMissionTarget))) &&
pcId < ID_NEUTRAL &&
(GuestimateCombatClass(self, baseObj) < MnvrClassA10 || IsSetATC(OnSweep) || isMissionTarget)) // 2002-03-11 Don't assume you know the combat class
// END OF MODIFIED SECTION 2002-03-05
{
// TJL 11/07/03 Cos takes Radians thus no *DTR
//totV = obj->BaseData()->GetVt()*(float)cos(localData->ataFrom*DTR) + self->GetVt();
totV = obj->BaseData()->GetVt()*(float)cos(localData->ataFrom) + self->GetVt();
//TJL 11/07/03 VO log says there is an radian error in this code
// I think it is here. ataFrom is in radians
//turnTime = localData->ataFrom / FIVE_G_TURN_RATE;
turnTime = localData->ataFrom*RTD / FIVE_G_TURN_RATE;// 15.9f degrees per second
rmax = maxAAWpnRange;//me123 60762.11F;
if (localData->range > rmax)
{
if ( totV <= 0.0f )
{
timeToRmax = MAX_TARGET_TIME * 2.0f;
}
else
{
timeToRmax = (localData->range - rmax) / totV;
tof = rmax / AVE_AIM120_VEL;
}
}
else
{
timeToRmax = 0.0F;
tof = localData->range / AVE_AIM120_VEL;
}
localData->targetTime = turnTime + timeToRmax + tof;
}
else
{
localData->targetTime = 2.0F * MAX_TARGET_TIME;
}
*/
obj = obj->next;
}
}
int GuestimateCombatClass(AircraftClass *self, FalconEntity *baseObj)
{
// Fail safe
if (!baseObj)
return 8;
// If asked to use the old code, then honor the request
if (!g_bUseNewCanEnage)
return baseObj->CombatClass();
// First I'll get the campaign object if it's for a sim since I use it at many places...
CampBaseClass *campBaseObj;
if (baseObj->IsSim())
campBaseObj = ((SimBaseClass*)baseObj)->GetCampaignObject();
else
campBaseObj = ((CampBaseClass *)baseObj);
// If the object is a weapon, no point
if (baseObj->IsWeapon())
return 8;
// If it doesn't have a campaign object or it's identified...
if (!campBaseObj || campBaseObj->GetIdentified(self->GetTeam())) {
// Yes, now you can get its combat class!
return baseObj->CombatClass();
}
else {
// No :-( Then guestimate it... (from RIK's BVR code)
if ((baseObj->GetVt() * FTPSEC_TO_KNOTS > 300.0f || baseObj->ZPos() < -10000.0f)) {
//this might be a combat jet.. asume the worst
return 4;
}
else if (baseObj->GetVt() * FTPSEC_TO_KNOTS > 250.0f) {
// this could be a a-a capable thingy, but if it's is it's low level so it's a-a long range shoot capabilitys are not great
return 1;
}
else {
// this must be something unthreatening...it's below 250 knots but it's still unidentified so...
return 0;
}
}
}
| 34.504655
| 391
| 0.602407
|
IsraelyFlightSimulator
|
2d5a9693443c446abe97ab6844e8633fc6be3fde
| 11,025
|
cpp
|
C++
|
1_Widgets-examples/1_4_Widgets_Surfing/src/ofApp.cpp
|
Daandelange/ofxSurfingImGui
|
122241ebcb900d30a5fa6b548de41b2910a27401
|
[
"MIT"
] | null | null | null |
1_Widgets-examples/1_4_Widgets_Surfing/src/ofApp.cpp
|
Daandelange/ofxSurfingImGui
|
122241ebcb900d30a5fa6b548de41b2910a27401
|
[
"MIT"
] | null | null | null |
1_Widgets-examples/1_4_Widgets_Surfing/src/ofApp.cpp
|
Daandelange/ofxSurfingImGui
|
122241ebcb900d30a5fa6b548de41b2910a27401
|
[
"MIT"
] | null | null | null |
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup_ImGui()
{
ImGuiConfigFlags flags = ImGuiConfigFlags_DockingEnable;
bool bRestore = true;
bool bMouse = false;
bool bAutoDraw = true;
// NOTE: it seems that must be false when multiple ImGui instances created!
gui.setup(nullptr, bAutoDraw, flags, bRestore, bMouse);
//-
// font
auto &io = ImGui::GetIO();
auto normalCharRanges = io.Fonts->GetGlyphRangesDefault();
std::string fontName;
float fontSize;
fontSize = 16;
fontName = "overpass-mono-bold.otf";
std::string _path = "assets/fonts/"; // assets folder
ofFile fileToRead(_path + fontName); // a file that exists
bool b = fileToRead.exists();
if (b) {
customFont = gui.addFont(_path + fontName, fontSize, nullptr, normalCharRanges);
}
if (customFont != nullptr) io.FontDefault = customFont;
//-
// theme
ofxImGuiSurfing::ImGui_ThemeMoebiusSurfing();
}
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
setup_ImGui();
// parameters
params.setName("paramsGroup1");// main container
params2.setName("paramsGroup2");// nested
params3.setName("paramsGroup3");// nested
params.add(indexPreset.set("Preset", 0, 0, 8));
params.add(bPrevious.set("<", false));
params.add(bNext.set(">", false));
params.add(bEnable1.set("Enable1", false));
params.add(bEnable2.set("Enable2", false));
params.add(bEnable3.set("Enable3", false));
params.add(lineWidth.set("lineWidth", 0.5, 0, 1));
params.add(separation.set("separation", 50, 1, 100));
params.add(speed.set("speed", 0.5, 0, 1));
params.add(shapeType.set("shapeType", 0, -50, 50));
params.add(size.set("size", 100, 0, 100));
params2.add(shapeType2.set("shapeType2", 0, -50, 50));
params2.add(size2.set("size2", 100, 0, 100));
params2.add(amount2.set("amount2", 10, 0, 25));
params3.add(lineWidth3.set("lineWidth3", 0.5, 0, 1));
params3.add(separation3.set("separation3", 50, 1, 100));
params3.add(speed3.set("speed3", 0.5, 0, 1));
params2.add(params3);
params.add(params2);
listener = indexPreset.newListener([this](int &i) {
ofLogNotice("loadGradient: ") << i;
loadGradient(indexPreset);
});
//--
// gradient
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor(0)));
gradient.addMark(1.0f, ImColor(ofColor(255)));
}
//--------------------------------------------------------------
void ofApp::draw() {
ofBackground(color);
//-
gui.begin();
{
ImGuiColorEditFlags _flagw;
string name;
{
// surfing widgets 1
_flagw = ImGuiWindowFlags_None;
name = "SurfingWidgets 1";
ImGui::Begin(name.c_str(), NULL, _flagw);
{
//static float f1 = -0.5f, f2 = 0.75f;
//ofxImGuiSurfing::RangeSliderFloat2("range slider float", &f1, &f2, -1.0f, 1.0f, "(%.3f, %.3f)");
// v sliders
ofxImGuiSurfing::AddVSlider2(valueKnob1, ImVec2(20, 100), false);
ImGui::SameLine();
ofxImGuiSurfing::AddVSlider2(valueKnob2, ImVec2(20, 100));
//ImGui::SameLine();
//ofxImGuiSurfing::AddVSlider2(valueKnob2, ImVec2(20, 100));
//ImGui::SameLine();
//ofxImGuiSurfing::AddVSlider2(valueKnob2, ImVec2(20, 100));
//ImGui::SameLine();
//ofxImGuiSurfing::AddVSlider2(valueKnob1, ImVec2(20, 100));
// knobs
ofxImGuiSurfing::AddKnob(valueKnob1);
//ImGui::SameLine();
//ofxImGuiSurfing::AddKnob(valueKnob2, true);
// more
draw_SurfingWidgets1();
}
ImGui::End();
//-
// surfing widgets 2
_flagw = ImGuiWindowFlags_None;
name = "SurfingWidgets 2";
ImGui::Begin(name.c_str(), NULL, _flagw);
{
draw_SurfingWidgets2();
}
ImGui::End();
}
}
gui.end();
}
//--------------------------------------------------------------
void ofApp::draw_SurfingWidgets1() {
// Common width sizes from 1 (_w1) to 4 (_w4) widgets per row
// Precalculate common widgets % sizes to fit current window "to be responsive"
// we will update the sizes on any gui drawing point, like inside a new foldered sub-window that could be indendeted and full size is being smaller.
// Internally takes care of ImGui spacing between widgets.
float _w1;
float _w2;
float _w3;
float _w4;
float _h;
_w1 = ofxImGuiSurfing::getWidgetsWidth(1); // 1 widget full width
_w2 = ofxImGuiSurfing::getWidgetsWidth(2); // 2 widgets half width
_w3 = ofxImGuiSurfing::getWidgetsWidth(3); // 3 widgets third width
_w4 = ofxImGuiSurfing::getWidgetsWidth(4); // 4 widgets quarter width
_h = WIDGETS_HEIGHT;
//--
// 1. An in index selector with a clickable preset matrix
{
bool bOpen = true;
ImGuiTreeNodeFlags _flagt = (bOpen ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
_flagt |= ImGuiTreeNodeFlags_Framed;
if (ImGui::TreeNodeEx("An Index Selector", _flagt))
{
// 1.1 Two buttons on same line
if (ImGui::Button("<", ImVec2(_w2, _h / 2)))
{
indexPreset--;
indexPreset = ofClamp(indexPreset, indexPreset.getMin(), indexPreset.getMax()); // clamp parameter
}
ImGui::SameLine();
if (ImGui::Button(">", ImVec2(_w2, _h / 2)))
{
indexPreset++;
indexPreset = ofClamp(indexPreset, indexPreset.getMin(), indexPreset.getMax()); // clamp parameter
}
// 1.2 Slider: the master int ofParam!
ofxImGuiSurfing::AddParameter(indexPreset);
ofxImGuiSurfing::HelpMarker("The master int ofParam!");
// 1.3 Matrix button clicker
AddMatrixClicker(indexPreset, true, 3); // responsive with 3 widgets per row
// 1.4 Spin arrows
int intSpin = indexPreset;
if (ofxImGuiSurfing::SpinInt("SpinInt", &intSpin))
{
intSpin = ofClamp(intSpin, indexPreset.getMin(), indexPreset.getMax()); // clamp to parameter
indexPreset = intSpin;
}
// 1.5 A tooltip over prev widget
if (ImGui::IsItemHovered()) {
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted("This is not an ofParam. Just an int!");
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
// 1.6 An external url link
ofxImGuiSurfing::ObjectInfo("ofxSurfingImGui @ github.com", "https://github.com/moebiussurfing/ofxSurfingImGui");
ImGui::TreePop();
}
}
ImGui::Dummy(ImVec2(0, 10)); // spacing
//--
// 2. an ofParameterGroup
ImGuiTreeNodeFlags flagst;
flagst = ImGuiTreeNodeFlags_None;
flagst |= ImGuiTreeNodeFlags_DefaultOpen;
flagst |= ImGuiTreeNodeFlags_Framed;
ofxImGuiSurfing::AddGroup(params3, flagst); // -> force to be expanded
//ofxImGuiSurfing::AddGroup(params3); // -> by default appears collapsed
}
//--------------------------------------------------------------
void ofApp::draw_SurfingWidgets2()
{
if (ImGui::TreeNode("ofParams Widgets"))
{
ofxImGuiSurfing::AddParameter(size2);
ofxImGuiSurfing::AddParameter(amount2);
ofxImGuiSurfing::AddParameter(separation3);
ImGui::TreePop();
}
ImGui::Dummy(ImVec2(0, 10)); // spacing
//--
// A gradient color tool
bool bOpen = true;
ImGuiTreeNodeFlags _flagt = (bOpen ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
_flagt |= ImGuiTreeNodeFlags_Framed;
if (ImGui::TreeNodeEx("A Gradient Widget", _flagt))
{
float _h = WIDGETS_HEIGHT;
float _w100 = ofxImGuiSurfing::getWidgetsWidth(1); // 1 widget full width
float _w50 = ofxImGuiSurfing::getWidgetsWidth(2); // 2 widgets half width
float _w33 = ofxImGuiSurfing::getWidgetsWidth(3); // 3 widgets per row
//-
static bool bEditGrad = false;
if (ImGui::GradientButton(&gradient))
{
//set show editor flag to true/false
bEditGrad = !bEditGrad;
}
//::EDITOR::
if (bEditGrad)
{
static ImGradientMark* draggingMark = nullptr;
static ImGradientMark* selectedMark = nullptr;
bool updated = ImGui::GradientEditor(&gradient, draggingMark, selectedMark);
}
//-
ImGui::Dummy(ImVec2(0, 5)); // spacing
// selector
ImGui::PushItemWidth(_w50); // make smaller bc too long label
if (ImGui::SliderFloat("SELECT COLOR PERCENT", &prcGrad, 0, 1))
{
//::GET A COLOR::
float _color[3];
gradient.getColorAt(prcGrad, _color); // position from 0 to 1
color.set(_color[0], _color[1], _color[2], 1.0f);
}
ImGui::PopItemWidth();
ImGui::Dummy(ImVec2(0, 5)); // spacing
//// presets
//if (ImGui::Button("Gradient1", ImVec2(_w3, _h / 2)))
//{
// indexPreset = 0;
//}
//ImGui::SameLine();
//if (ImGui::Button("Gradient2", ImVec2(_w3, _h / 2)))
//{
// indexPreset = 2;
//}
//ImGui::SameLine();
//if (ImGui::Button("Gradient3", ImVec2(_w3, _h / 2)))
//{
// indexPreset = 3;
//}
ImGui::TreePop();
}
}
//--------------------------------------------------------------
void ofApp::loadGradient(int index) {
int i = index;
if (i == 0) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::blue));
gradient.addMark(0.3f, ImColor(ofColor::blueViolet));
gradient.addMark(0.6f, ImColor(ofColor::yellow));
gradient.addMark(1.0f, ImColor(ofColor::orangeRed));
}
else if (i == 1) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(0xA0, 0x79, 0x3D));
//gradient.addMark(0.2f, ImColor(0xAA, 0x83, 0x47));
gradient.addMark(0.3f, ImColor(0xB4, 0x8D, 0x51));
//gradient.addMark(0.4f, ImColor(0xBE, 0x97, 0x5B));
//gradient.addMark(0.6f, ImColor(0xC8, 0xA1, 0x65));
gradient.addMark(0.7f, ImColor(0xD2, 0xAB, 0x6F));
gradient.addMark(0.8f, ImColor(0xDC, 0xB5, 0x79));
gradient.addMark(1.0f, ImColor(0xE6, 0xBF, 0x83));
}
else if (i == 2) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::red));
gradient.addMark(0.3f, ImColor(ofColor::yellowGreen));
gradient.addMark(1.0f, ImColor(ofColor::green));
}
else if (i == 3) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::blueSteel));
gradient.addMark(0.3f, ImColor(ofColor::blueViolet));
gradient.addMark(0.7f, ImColor(ofColor::cornflowerBlue));
gradient.addMark(1.0f, ImColor(ofColor::cadetBlue));
}
else if (i == 4) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::yellow));
gradient.addMark(0.5f, ImColor(ofColor::lightYellow));
gradient.addMark(1.0f, ImColor(ofColor::lightGoldenRodYellow));
}
else if (i == 5) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::red));
gradient.addMark(0.5f, ImColor(ofColor::orangeRed));
gradient.addMark(1.0f, ImColor(ofColor::blueViolet));
}
else if (i == 6) {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::lightYellow));
gradient.addMark(0.5f, ImColor(ofColor::floralWhite));
gradient.addMark(1.0f, ImColor(ofColor::whiteSmoke));
}
// repeat some if index is too big. just for testing..
else {
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(ofColor::paleVioletRed));
gradient.addMark(0.3f, ImColor(ofColor::red));
gradient.addMark(0.7f, ImColor(ofColor::darkRed));
gradient.addMark(1.0f, ImColor(ofColor::black));
}
//refresh
float _color[3];
gradient.getColorAt(prcGrad, _color); // position from 0 to 1
color.set(_color[0], _color[1], _color[2], 1.0f);
}
| 29.637097
| 149
| 0.655964
|
Daandelange
|
2d5beed9a2b8139f1e89c0b2a37b75774f14f85f
| 14,455
|
cpp
|
C++
|
Source/SupportGLUT/Viewer/ScreenBase.cpp
|
GoTamura/KVS
|
121ede0b9b81da56e9ea698a45ccfd71ff64ed41
|
[
"BSD-3-Clause"
] | null | null | null |
Source/SupportGLUT/Viewer/ScreenBase.cpp
|
GoTamura/KVS
|
121ede0b9b81da56e9ea698a45ccfd71ff64ed41
|
[
"BSD-3-Clause"
] | null | null | null |
Source/SupportGLUT/Viewer/ScreenBase.cpp
|
GoTamura/KVS
|
121ede0b9b81da56e9ea698a45ccfd71ff64ed41
|
[
"BSD-3-Clause"
] | null | null | null |
/*****************************************************************************/
/**
* @file ScreenBase.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "ScreenBase.h"
#include <kvs/Message>
#include <kvs/Assert>
#include <kvs/MouseEvent>
#include <kvs/KeyEvent>
#include <kvs/WheelEvent>
#include <kvs/TimerEventListener>
#include <kvs/glut/GLUT>
#include <kvs/glut/Application>
#include <kvs/glut/Timer>
#include <SupportGLUT/Viewer/KVSMouseButton.h>
#include <SupportGLUT/Viewer/KVSKey.h>
#include <cstdlib>
namespace
{
const size_t MaxNumberOfScreens = 256;
kvs::glut::ScreenBase* Context[ MaxNumberOfScreens ] = {};
#if defined( KVS_GL_HAS_LAYER_BACKED_VIEW )
int ResizeOnce[ MaxNumberOfScreens ] = {};
#endif
/*===========================================================================*/
/**
* @brief Function that is called when the application is terminated.
*/
/*===========================================================================*/
void ExitFunction()
{
for ( size_t i = 0; i < MaxNumberOfScreens; i++)
{
if ( Context[i] ) Context[i]->~ScreenBase();
}
}
}
namespace kvs
{
namespace glut
{
/*===========================================================================*/
/**
* @brief Display function for glutDisplayFunc.
*/
/*===========================================================================*/
void DisplayFunction()
{
const int id = glutGetWindow();
::Context[id]->paintEvent();
}
/*===========================================================================*/
/**
* @brief Resize function for glutReshapeFunc.
* @param width [in] window width
* @param height [in] window height
*/
/*===========================================================================*/
void ResizeFunction( int width, int height )
{
const int id = glutGetWindow();
#if defined( KVS_GL_HAS_LAYER_BACKED_VIEW )
if ( ::ResizeOnce[id] == 0 )
{
glutReshapeWindow( width + 1, height + 1 );
::ResizeOnce[id] = 1;
}
#endif
::Context[id]->resizeEvent( width, height );
}
/*===========================================================================*/
/**
* @brief Mouse function for glutMouseFunc.
* @param button [in] button ID
* @param state [in] state ID
* @param x [in] x coordinate of the mouse on the window coordinate
* @param y [in] y coordinate of the mouse on the window coordinate
*/
/*===========================================================================*/
void MouseFunction( int button, int state, int x, int y )
{
const int id = glutGetWindow();
const int modifier = kvs::glut::KVSKey::Modifier( glutGetModifiers() );
button = kvs::glut::KVSMouseButton::Button( button );
state = kvs::glut::KVSMouseButton::State( state );
::Context[id]->m_mouse_event->setButton( button );
::Context[id]->m_mouse_event->setState( state );
::Context[id]->m_mouse_event->setPosition( x, y );
::Context[id]->m_mouse_event->setModifiers( modifier );
switch ( state )
{
case kvs::MouseButton::Down:
::Context[id]->m_elapse_time_counter.stop();
if ( ::Context[id]->m_elapse_time_counter.sec() < 0.2f )
{
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::DoubleClicked );
::Context[id]->mouseDoubleClickEvent( ::Context[id]->m_mouse_event );
}
else
{
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::Pressed );
::Context[id]->mousePressEvent( ::Context[id]->m_mouse_event );
}
::Context[id]->m_elapse_time_counter.start();
break;
case kvs::MouseButton::Up:
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::Released );
::Context[id]->mouseReleaseEvent( ::Context[id]->m_mouse_event );
break;
default: break;
}
::Context[id]->m_wheel_event->setPosition( x, y );
switch( button )
{
case kvs::MouseButton::WheelUp:
::Context[id]->m_wheel_event->setDirection( 1 );
::Context[id]->wheelEvent( ::Context[id]->m_wheel_event );
break;
case kvs::MouseButton::WheelDown:
::Context[id]->m_wheel_event->setDirection( -1 );
::Context[id]->wheelEvent( ::Context[id]->m_wheel_event );
break;
default: break;
}
}
/*===========================================================================*/
/**
* @brief Mouse move function for glutMotionFunc.
* @param x [in] x coordinate value of the mouse cursor on the window coordinate
* @param y [in] y coordinate value of the mouse cursor on the window coordinate
*/
/*===========================================================================*/
void MouseMoveFunction( int x, int y )
{
const int id = glutGetWindow();
::Context[id]->m_mouse_event->setPosition( x, y );
::Context[id]->m_mouse_event->setAction( kvs::MouseButton::Moved );
::Context[id]->mouseMoveEvent( ::Context[id]->m_mouse_event );
}
/*===========================================================================*/
/**
* @brief Key press function for glutKeyboardFunc.
* @param key [in] key code
* @param x [in] x coordinate value of the mouse cursor on the window coordinate
* @param y [in] y coordinate value of the mouse cursor on the window coordinate
*/
/*===========================================================================*/
void KeyPressFunction( unsigned char key, int x, int y )
{
const int id = glutGetWindow();
const int code = kvs::glut::KVSKey::ASCIICode( key );
::Context[id]->m_key_event->setKey( code );
::Context[id]->m_key_event->setPosition( x, y );
::Context[id]->keyPressEvent( ::Context[id]->m_key_event );
}
/*===========================================================================*/
/**
* @brief Special key press function for glutSpecialFunc.
* @param key [in] key code
* @param x [in] x coordinate value of the mouse cursor on the window coordinate
* @param y [in] y coordinate value of the mouse cursor on the window coordinate
*/
/*===========================================================================*/
void SpecialKeyPressFunction( int key, int x, int y )
{
const int id = glutGetWindow();
const int code = kvs::glut::KVSKey::SpecialCode( key );
::Context[id]->m_key_event->setKey( code );
::Context[id]->m_key_event->setPosition( x, y );
::Context[id]->keyPressEvent( ::Context[id]->m_key_event );
}
/*===========================================================================*/
/**
* @brief Constructs a new ScreenBase class.
* @param application [in] pointer to the application
*/
/*===========================================================================*/
ScreenBase::ScreenBase( kvs::glut::Application* application ):
m_id( -1 ),
m_mouse_event( 0 ),
m_key_event( 0 ),
m_wheel_event( 0 ),
m_is_fullscreen( false )
{
if ( application ) application->attach( this );
m_mouse_event = new kvs::MouseEvent();
m_key_event = new kvs::KeyEvent();
m_wheel_event = new kvs::WheelEvent();
m_elapse_time_counter.start();
}
/*===========================================================================*/
/**
* @brief Destructs the ScreenBase class.
*/
/*===========================================================================*/
ScreenBase::~ScreenBase()
{
delete m_mouse_event;
delete m_key_event;
delete m_wheel_event;
::Context[ m_id ] = NULL;
glutDestroyWindow( m_id );
}
/*===========================================================================*/
/**
* @brief Creates the screen.
*/
/*===========================================================================*/
void ScreenBase::create()
{
KVS_ASSERT( m_id == -1 );
// Initialize display mode.
unsigned int mode = 0;
if ( displayFormat().doubleBuffer() ) mode |= GLUT_DOUBLE; else mode |= GLUT_SINGLE;
if ( displayFormat().colorBuffer() ) mode |= GLUT_RGBA; else mode |= GLUT_INDEX;
if ( displayFormat().depthBuffer() ) mode |= GLUT_DEPTH;
if ( displayFormat().accumulationBuffer() ) mode |= GLUT_ACCUM;
if ( displayFormat().stencilBuffer() ) mode |= GLUT_STENCIL;
if ( displayFormat().stereoBuffer() ) mode |= GLUT_STEREO;
if ( displayFormat().multisampleBuffer() ) mode |= GLUT_MULTISAMPLE;
if ( displayFormat().alphaChannel() ) mode |= GLUT_ALPHA;
glutInitDisplayMode( mode );
// Set screen geometry.
glutInitWindowPosition( BaseClass::x(), BaseClass::y() );
#if defined( KVS_GL_HAS_LAYER_BACKED_VIEW )
glutInitWindowSize( BaseClass::width() - 1, BaseClass::height() - 1 );
#else
glutInitWindowSize( BaseClass::width(), BaseClass::height() );
#endif
// Create window.
glutCreateWindow( BaseClass::title().c_str() );
// Set to the global context.
m_id = glutGetWindow();
::Context[ m_id ] = this;
// Initialize GLEW.
#if defined( KVS_ENABLE_GLEW )
GLenum result = glewInit();
if ( result != GLEW_OK )
{
const GLubyte* message = glewGetErrorString( result );
kvsMessageError( "GLEW initialization failed: %s.", message );
}
#endif
// Create paint device.
BaseClass::paintDevice()->create();
// Register the exit function.
static bool flag = true;
if ( flag ) { atexit( ::ExitFunction ); flag = false; }
// Register callback functions.
glutMouseFunc( MouseFunction );
glutMotionFunc( MouseMoveFunction );
glutKeyboardFunc( KeyPressFunction );
glutSpecialFunc( SpecialKeyPressFunction );
glutDisplayFunc( DisplayFunction );
glutReshapeFunc( ResizeFunction );
}
/*===========================================================================*/
/**
* @brief Shows the screen.
* @return window ID
*/
/*===========================================================================*/
void ScreenBase::show()
{
#if 1 // KVS_ENABLE_DEPRECATED
if ( m_id == -1 ) this->create();
else {
#endif
glutSetWindow( m_id );
glutShowWindow();
#if 1 // KVS_ENABLE_DEPRECATED
}
#endif
}
/*===========================================================================*/
/**
* @brief Shows the window as full-screen.
*/
/*===========================================================================*/
void ScreenBase::showFullScreen()
{
if ( m_is_fullscreen ) return;
m_is_fullscreen = true;
const int x = glutGet( (GLenum)GLUT_WINDOW_X );
const int y = glutGet( (GLenum)GLUT_WINDOW_Y );
BaseClass::setPosition( x, y );
glutFullScreen();
}
/*===========================================================================*/
/**
* @brief Shows the window as normal screen.
*/
/*===========================================================================*/
void ScreenBase::showNormal()
{
if ( !m_is_fullscreen ) return;
m_is_fullscreen = false;
glutReshapeWindow( BaseClass::width(), BaseClass::height() );
glutPositionWindow( BaseClass::x(), BaseClass::y() );
glutPopWindow();
}
/*===========================================================================*/
/**
* @brief Hides the window.
*/
/*===========================================================================*/
void ScreenBase::hide()
{
glutSetWindow( m_id );
glutHideWindow();
}
/*===========================================================================*/
/**
* @brief Pops up the window.
*/
/*===========================================================================*/
void ScreenBase::popUp()
{
glutPopWindow();
}
/*===========================================================================*/
/**
* @brief Pushes down the window.
*/
/*===========================================================================*/
void ScreenBase::pushDown()
{
glutPushWindow();
}
/*===========================================================================*/
/**
* @brief Redraws the window.
*/
/*===========================================================================*/
void ScreenBase::redraw()
{
const int id = glutGetWindow();
glutSetWindow( m_id );
glutPostRedisplay();
glutSetWindow( id );
}
/*===========================================================================*/
/**
* @brief Resizes the window.
* @param width [in] resized window width
* @param height [in] resized window height
*/
/*===========================================================================*/
void ScreenBase::resize( int width, int height )
{
BaseClass::setSize( width, height );
glutReshapeWindow( BaseClass::width(), BaseClass::height() );
}
/*===========================================================================*/
/**
* @brief Checks whether the window is full-screen or not.
* @return true, if the window is full-screen
*/
/*===========================================================================*/
bool ScreenBase::isFullScreen() const
{
return m_is_fullscreen;
}
void ScreenBase::enable(){}
void ScreenBase::disable(){}
void ScreenBase::reset(){}
void ScreenBase::initializeEvent(){}
void ScreenBase::paintEvent(){}
void ScreenBase::resizeEvent( int, int ){}
void ScreenBase::mousePressEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseMoveEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseReleaseEvent( kvs::MouseEvent* ){}
void ScreenBase::mouseDoubleClickEvent( kvs::MouseEvent* ){}
void ScreenBase::wheelEvent( kvs::WheelEvent* ){}
void ScreenBase::keyPressEvent( kvs::KeyEvent* ){}
std::list<kvs::glut::Timer*>& ScreenBase::timerEventHandler()
{
return m_timer_event_handler;
}
/*===========================================================================*/
/**
* @brief Adds a timer event listener.
* @param event [in] pointer to a timer event listener
* @param timer [in] pointer to timer
*/
/*===========================================================================*/
void ScreenBase::addTimerEvent( kvs::TimerEventListener* event, kvs::glut::Timer* timer )
{
event->setScreen( this );
timer->setEventListener( event );
m_timer_event_handler.push_back( timer );
}
} // end of namespace glut
} // end of namespace kvs
| 31.699561
| 89
| 0.499896
|
GoTamura
|
2d5bfd3aa2596cf710d4c1672e818b1c94d8d81f
| 1,967
|
hh
|
C++
|
src/mem/cache/c_dynamic_cache.hh
|
xiaoyaozi5566/DynamicCache
|
250e7a901f3244f69d0c8de4d3f525a92dbfaac5
|
[
"BSD-3-Clause"
] | null | null | null |
src/mem/cache/c_dynamic_cache.hh
|
xiaoyaozi5566/DynamicCache
|
250e7a901f3244f69d0c8de4d3f525a92dbfaac5
|
[
"BSD-3-Clause"
] | null | null | null |
src/mem/cache/c_dynamic_cache.hh
|
xiaoyaozi5566/DynamicCache
|
250e7a901f3244f69d0c8de4d3f525a92dbfaac5
|
[
"BSD-3-Clause"
] | 1
|
2021-07-05T18:02:56.000Z
|
2021-07-05T18:02:56.000Z
|
#include "mem/cache/base.hh"
#include "mem/cache/blk.hh"
#include "mem/cache/cache.hh"
#include "params/BaseCache.hh"
#include "stdio.h"
typedef BaseCacheParams Params;
template <class TagStore>
class C_DynamicCache : public SplitRPortCache<TagStore>
{
public:
C_DynamicCache( const Params *p, TagStore *tags );
/** Define the type of cache block to use. */
typedef typename TagStore::BlkType BlkType;
/** A typedef for a list of BlkType pointers. */
typedef typename TagStore::BlkList BlkList;
protected:
virtual void incMissCount(PacketPtr pkt)
{
if(pkt->threadID == 0) this->missCounter++;
}
void adjustPartition();
uint64_t array_avg(uint64_t* array, int count)
{
assert(count != 0);
uint64_t sum = 0;
for(int i = 0; i < count; i++){
sum += array[i];
}
return sum/count;
}
void update_history(uint64_t* array, int count, uint64_t curr_misses)
{
assert(count != 0);
for(int i = 0; i < count-1; i++){
array[i] = array[i+1];
}
array[count-1] = curr_misses;
}
void inc_size();
void dec_size();
EventWrapper<C_DynamicCache<TagStore>, &C_DynamicCache<TagStore>::adjustPartition> adjustEvent;
private:
// Time interval to change partition size (ticks)
uint64_t interval;
// Thresholds for changing partition size
float th_inc, th_dec;
// Window size
uint64_t window_size;
// Moving average
uint64_t *miss_history;
// Explore flag and stable flag
bool explore_phase, explore_inc, explore_dec, stable_phase;
// Stable length
uint64_t stable_length, stable_counter;
// Static miss curve
float *miss_curve;
unsigned assoc;
// protected:
// virtual bool access(PacketPtr pkt, BlkType *&blk,
// int &lat, PacketList &writebacks);
//
// virtual bool timingAccess(PacketPtr pkt);
//
// virtual void handleResponse(PacketPtr pkt);
//
// virtual BlkType *handleFill(PacketPtr pkt, BlkType *blk,
// PacketList &writebacks);
};
| 25.217949
| 96
| 0.685308
|
xiaoyaozi5566
|
2d5f5558224e023aec9b9a7ab47971122f40f8f8
| 2,023
|
hh
|
C++
|
src/random/distributions/ReciprocalDistribution.i.hh
|
amandalund/celeritas
|
c631594b00c040d5eb4418fa2129f88c01e29316
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/random/distributions/ReciprocalDistribution.i.hh
|
amandalund/celeritas
|
c631594b00c040d5eb4418fa2129f88c01e29316
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/random/distributions/ReciprocalDistribution.i.hh
|
amandalund/celeritas
|
c631594b00c040d5eb4418fa2129f88c01e29316
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
//----------------------------------*-C++-*----------------------------------//
// Copyright 2021 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file ReciprocalDistribution.i.hh
//---------------------------------------------------------------------------//
#include <cmath>
#include "base/Assert.hh"
#include "GenerateCanonical.hh"
namespace celeritas
{
//---------------------------------------------------------------------------//
/*!
* Construct on the interval [a, 1).
*
* The distribution is equivalent to switching a and b, and using
* \f$ \xi' = 1 - \xi \f$.
*/
template<class RealType>
CELER_FUNCTION
ReciprocalDistribution<RealType>::ReciprocalDistribution(real_type a)
: ReciprocalDistribution(1, a)
{
}
//---------------------------------------------------------------------------//
/*!
* Construct on the interval [a, b).
*
* As with UniformRealDistribution, it is allowable for the two bounds to be
* out of order.
*
* Note that writing as \code (1/a) * b \endcode allows the compiler to
* optimize better for the constexpr case a=1.
*/
template<class RealType>
CELER_FUNCTION
ReciprocalDistribution<RealType>::ReciprocalDistribution(real_type a,
real_type b)
: a_(a), logratio_(std::log((1 / a) * b))
{
CELER_EXPECT(a > 0);
CELER_EXPECT(b > 0);
}
//---------------------------------------------------------------------------//
/*!
* Sample a random number according to the distribution.
*/
template<class RealType>
template<class Generator>
CELER_FUNCTION auto
ReciprocalDistribution<RealType>::operator()(Generator& rng) const
-> result_type
{
return a_ * std::exp(logratio_ * generate_canonical<RealType>(rng));
}
//---------------------------------------------------------------------------//
} // namespace celeritas
| 31.609375
| 79
| 0.499259
|
amandalund
|
2d5fd58d1f97ac9c3c8d2e42c7a9249bafa07e07
| 1,174
|
hpp
|
C++
|
DnsUdpStateMachine.hpp
|
luotuo44/ADNS
|
ccc85b11c9a3fc7250493451429a44abc81bec39
|
[
"BSD-2-Clause"
] | 3
|
2016-04-10T04:58:37.000Z
|
2020-09-07T05:54:51.000Z
|
DnsUdpStateMachine.hpp
|
luotuo44/ADNS
|
ccc85b11c9a3fc7250493451429a44abc81bec39
|
[
"BSD-2-Clause"
] | null | null | null |
DnsUdpStateMachine.hpp
|
luotuo44/ADNS
|
ccc85b11c9a3fc7250493451429a44abc81bec39
|
[
"BSD-2-Clause"
] | null | null | null |
//Filename:
//Date: 2015-8-11
//Author: luotuo44 http://blog.csdn.net/luotuo44
//Copyright 2015, luotuo44. All rights reserved.
//Use of this source code is governed by a BSD-style license
#ifndef DNSUDPSTATEMACHINE
#define DNSUDPSTATEMACHINE
#include<map>
#include<memory>
#include"typedef.hpp"
#include"typedef-internal.hpp"
namespace ADNS
{
class DnsUdpStateMachine
{
public:
DnsUdpStateMachine(EventCreater &ev_creater);
~DnsUdpStateMachine();
DnsUdpStateMachine(const DnsUdpStateMachine& )=delete;
DnsUdpStateMachine& operator = (const DnsUdpStateMachine& )=delete;
void setResCB(DnsExplorerResCB &cb);
void addQuery(const DnsQuery_t &query);
void eventCB(int fd, int events, void *arg);
private:
struct QueryPacket;
using QueryPacketPtr = std::shared_ptr<QueryPacket>;
private:
void updateEvent(QueryPacketPtr &q, int events, int milliseconds =-1);
void replyResult(QueryPacketPtr &q, bool success);
bool getDNSQueryPacket(QueryPacketPtr &query);
protected:
EventCreater m_ev_creater;
DnsExplorerResCB m_res_cb;
std::map<int, QueryPacketPtr> m_querys;
};
}
#endif // DNSUDPSTATEMACHINE
| 20.241379
| 74
| 0.741908
|
luotuo44
|
2d60b4d8b1d0f74b28dd9ab79ee33c3a8aad5d31
| 8,456
|
cc
|
C++
|
examples/mp.cc
|
kaishengyao/cnn
|
a034b837e88f82bd8adf2c5b0a5defb26fd52096
|
[
"Apache-2.0"
] | 16
|
2015-09-10T07:50:50.000Z
|
2017-09-17T03:02:38.000Z
|
examples/mp.cc
|
kaishengyao/cnn
|
a034b837e88f82bd8adf2c5b0a5defb26fd52096
|
[
"Apache-2.0"
] | null | null | null |
examples/mp.cc
|
kaishengyao/cnn
|
a034b837e88f82bd8adf2c5b0a5defb26fd52096
|
[
"Apache-2.0"
] | 10
|
2015-09-08T12:43:13.000Z
|
2018-09-26T07:32:47.000Z
|
#include "cnn/cnn.h"
#include "cnn/training.h"
#include "cnn/expr.h"
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/algorithm/string.hpp>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <sstream>
#include <random>
using namespace std;
using namespace cnn;
using namespace cnn::expr;
struct SharedObject {
cnn::real m;
cnn::real b;
cnn::real loss;
cnn::real temp_m;
cnn::real temp_b;
};
typedef pair<cnn::real, cnn::real> Datum;
const unsigned num_children = 4;
SharedObject* shared_memory = nullptr;
cnn::real ReadReal(int pipe) {
cnn::real v;
read(pipe, &v, sizeof(cnn::real));
return v;
}
void WriteReal(int pipe, cnn::real v) {
write(pipe, &v, sizeof(cnn::real));
}
template <typename T>
void WriteIntVector(int pipe, const vector<T>& vec) {
unsigned length = vec.size();
write(pipe, &length, sizeof(unsigned));
for (T v : vec) {
write(pipe, &v, sizeof(T));
}
}
template<typename T>
vector<T> ReadIntVector(int pipe) {
unsigned length;
read(pipe, &length, sizeof(unsigned));
vector<T> vec(length);
for (unsigned i = 0; i < length; ++i) {
read(pipe, &vec[i], sizeof(T));
}
return vec;
}
cnn::real Mean(const vector<cnn::real>& values) {
return accumulate(values.begin(), values.end(), 0.0) / values.size();
}
struct Workload {
pid_t pid;
int c2p[2]; // Child to parent pipe
int p2c[2]; // Parent to child pipe
};
struct ModelParameters {
Parameters* m;
Parameters* b;
};
void BuildComputationGraph(ComputationGraph& cg, ModelParameters& model_parameters, cnn::real* x_value, cnn::real* y_value) {
Expression m = parameter(cg, model_parameters.m);
Expression b = parameter(cg, model_parameters.b);
Expression x = input(cg, x_value);
Expression y_star = input(cg, y_value);
Expression y = m * x + b;
Expression loss = squared_distance(y, y_star);
}
vector<Datum> ReadData(string filename) {
vector<Datum> data;
ifstream fs(filename);
if (!fs.is_open()) {
cerr << "ERROR: Unable to open " << filename << endl;
exit(1);
}
string line;
while (getline(fs, line)) {
if (line.size() > 0 && line[0] == '#') {
continue;
}
vector<string> parts;
boost::split(parts, line, boost::is_any_of("\t"));
data.push_back(make_pair(atof(parts[0].c_str()), atof(parts[1].c_str())));
}
return data;
}
unsigned SpawnChildren(vector<Workload>& workloads) {
assert (workloads.size() == num_children);
pid_t pid;
unsigned cid;
for (cid = 0; cid < num_children; ++cid) {
pid = fork();
if (pid == -1) {
cerr << "Fork failed. Exiting ...";
return 1;
}
else if (pid == 0) {
// children shouldn't continue looping
break;
}
workloads[cid].pid = pid;
}
return cid;
}
int RunChild(unsigned cid, ComputationGraph& cg, Trainer* trainer, vector<Workload>& workloads,
const vector<Datum>& data, cnn::real& x_value, cnn::real& y_value, ModelParameters& model_params) {
assert (cid >= 0 && cid < num_children);
while (true) {
// Check if the parent wants us to exit
bool cont = false;
read(workloads[cid].p2c[0], &cont, sizeof(bool));
if (!cont) {
break;
}
// Read in our workload and update our local model
vector<unsigned> indices = ReadIntVector<unsigned>(workloads[cid].p2c[0]);
TensorTools::SetElements(model_params.m->values, {shared_memory->m});
TensorTools::SetElements(model_params.b->values, {shared_memory->b});
cnn::real loss = 0;
for (unsigned i : indices) {
assert (i < data.size());
auto p = data[i];
x_value = get<0>(p);
y_value = get<1>(p);
loss += as_scalar(cg.forward());
cg.backward();
trainer->update(1.0);
}
loss /= indices.size();
// Get our final values of each parameter and send them back to the parent,
// along with the current loss value
cnn::real m = as_scalar(model_params.m->values);
cnn::real b = as_scalar(model_params.b->values);
shared_memory->temp_m += m;
shared_memory->temp_b += b;
shared_memory->loss += loss;
/*write(workloads[cid].c2p[1], (char*)&m, sizeof(cnn::real));
write(workloads[cid].c2p[1], (char*)&b, sizeof(cnn::real));
write(workloads[cid].c2p[1], (char*)&loss, sizeof(cnn::real));*/
WriteReal(workloads[cid].c2p[1], 0.0);
}
return 0;
}
void RunParent(vector<Datum>& data, vector<Workload>& workloads, ModelParameters& model_params, Trainer* trainer) {
shared_memory->m = TensorTools::AccessElement(model_params.m->values, {0, 0});
shared_memory->b = TensorTools::AccessElement(model_params.b->values, {0, 0});
for (unsigned iter = 0; iter < 10; ++iter) {
shared_memory->loss = 0.0;
shared_memory->temp_m = 0.0;
shared_memory->temp_b = 0.0;
/*vector<cnn::real> m_values;
vector<cnn::real> b_values;
vector<cnn::real> loss_values;*/
for(unsigned cid = 0; cid < num_children; ++cid) {
unsigned start = (unsigned)(1.0 * cid / num_children * data.size() + 0.5);
unsigned end = (unsigned)(1.0 * (cid + 1) / num_children * data.size() + 0.5);
vector<unsigned> indices;
indices.reserve(end - start);
for (unsigned i = start; i < end; ++i) {
indices.push_back(i);
}
bool cont = true;
write(workloads[cid].p2c[1], &cont, sizeof(bool));
WriteIntVector(workloads[cid].p2c[1], indices);
/*cnn::real m = ReadReal(workloads[cid].c2p[0]);
cnn::real b = ReadReal(workloads[cid].c2p[0]);
cnn::real loss = ReadReal(workloads[cid].c2p[0]);
m_values.push_back(m);
b_values.push_back(b);
loss_values.push_back(loss);*/
}
for(unsigned cid = 0; cid < num_children; ++cid) {
ReadReal(workloads[cid].c2p[0]);
}
/*cnn::real m = Mean(m_values);
cnn::real b = 0.0;
cnn::real loss = 0.0;
for (unsigned i = 0; i < m_values.size(); ++i) {
b += b_values[i];
loss += loss_values[i];
}
b /= b_values.size();*/
shared_memory->m = shared_memory->temp_m / num_children;
shared_memory->b = shared_memory->temp_b / num_children;
// Update parameters to use the new m and b values
//TensorTools::SetElements(model_params.m->values, {m});
//TensorTools::SetElements(model_params.b->values, {b});
trainer->update_epoch();
//cerr << shared_memory->m << "\t" << iter << "\t" << "loss = " << loss << "\tm = " << m << "\tb = " << b << endl;
cerr << iter << "\t" << "loss = " << shared_memory->loss << "\tm = " << shared_memory->m << "\tb = " << shared_memory->b << endl;
}
// Kill all children one by one and wait for them to exit
for (unsigned cid = 0; cid < num_children; ++cid) {
bool cont = false;
write(workloads[cid].p2c[1], &cont, sizeof(cont));
wait(NULL);
}
}
int main(int argc, char** argv) {
cnn::Initialize(argc, argv);
if (argc < 2) {
cerr << "Usage: " << argv[0] << " data.txt" << endl;
cerr << "Where data.txt contains tab-delimited pairs of cnn::reals." << endl;
return 1;
}
vector<Datum> data = ReadData(argv[1]);
vector<Workload> workloads(num_children);
Model model;
AdamTrainer sgd(&model, 0.0);
ComputationGraph cg;
cnn::real x_value, y_value;
Parameters* m_param = model.add_parameters({1, 1});
Parameters* b_param = model.add_parameters({1});
ModelParameters model_params = {m_param, b_param};
BuildComputationGraph(cg, model_params, &x_value, &y_value);
unsigned shm_size = 1024;
assert (sizeof(SharedObject) < shm_size);
key_t shm_key = ftok("/home/austinma/shared", 'R');
if (shm_key == -1) {
cerr << "Unable to get shared memory key" << endl;
return 1;
}
int shm_id = shmget(shm_key, shm_size, 0644 | IPC_CREAT);
if (shm_id == -1) {
cerr << "Unable to create shared memory" << endl;
return 1;
}
void* shm_p = shmat(shm_id, nullptr, 0);
if (shm_p == (void*)-1) {
cerr << "Unable to get shared memory pointer";
return 1;
}
shared_memory = (SharedObject*)shm_p;
for (unsigned cid = 0; cid < num_children; cid++) {
pipe(workloads[cid].p2c);
pipe(workloads[cid].c2p);
}
unsigned cid = SpawnChildren(workloads);
if (cid < num_children) {
return RunChild(cid, cg, &sgd, workloads, data, x_value, y_value, model_params);
}
else {
RunParent(data, workloads, model_params, &sgd);
}
}
| 29.158621
| 133
| 0.629849
|
kaishengyao
|
2d69f8d87d1ae27ea07aa88742e616f842578904
| 2,969
|
cpp
|
C++
|
hexl/eltwise/eltwise-cmp-add.cpp
|
tgonzalez89-intel/hexl
|
352e9ed14cb615defa33e4768d156eea3413361a
|
[
"Apache-2.0"
] | 136
|
2021-03-26T15:24:31.000Z
|
2022-03-30T07:50:15.000Z
|
hexl/eltwise/eltwise-cmp-add.cpp
|
tgonzalez89-intel/hexl
|
352e9ed14cb615defa33e4768d156eea3413361a
|
[
"Apache-2.0"
] | 24
|
2021-04-03T06:10:47.000Z
|
2022-03-24T03:34:50.000Z
|
hexl/eltwise/eltwise-cmp-add.cpp
|
tgonzalez89-intel/hexl
|
352e9ed14cb615defa33e4768d156eea3413361a
|
[
"Apache-2.0"
] | 27
|
2021-04-01T07:50:11.000Z
|
2022-03-22T00:54:23.000Z
|
// Copyright (C) 2020-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "hexl/eltwise/eltwise-cmp-add.hpp"
#include "eltwise/eltwise-cmp-add-avx512.hpp"
#include "eltwise/eltwise-cmp-add-internal.hpp"
#include "hexl/logging/logging.hpp"
#include "hexl/number-theory/number-theory.hpp"
#include "hexl/util/check.hpp"
#include "util/cpu-features.hpp"
namespace intel {
namespace hexl {
void EltwiseCmpAdd(uint64_t* result, const uint64_t* operand1, uint64_t n,
CMPINT cmp, uint64_t bound, uint64_t diff) {
HEXL_CHECK(result != nullptr, "Require result != nullptr");
HEXL_CHECK(operand1 != nullptr, "Require operand1 != nullptr");
HEXL_CHECK(n != 0, "Require n != 0");
HEXL_CHECK(diff != 0, "Require diff != 0");
#ifdef HEXL_HAS_AVX512DQ
if (has_avx512dq) {
EltwiseCmpAddAVX512(result, operand1, n, cmp, bound, diff);
return;
}
#endif
EltwiseCmpAddNative(result, operand1, n, cmp, bound, diff);
}
void EltwiseCmpAddNative(uint64_t* result, const uint64_t* operand1, uint64_t n,
CMPINT cmp, uint64_t bound, uint64_t diff) {
HEXL_CHECK(result != nullptr, "Require result != nullptr");
HEXL_CHECK(operand1 != nullptr, "Require operand1 != nullptr");
HEXL_CHECK(n != 0, "Require n != 0");
HEXL_CHECK(diff != 0, "Require diff != 0");
switch (cmp) {
case CMPINT::EQ: {
for (size_t i = 0; i < n; ++i) {
if (operand1[i] == bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
}
case CMPINT::LT:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] < bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::LE:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] <= bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::FALSE:
for (size_t i = 0; i < n; ++i) {
result[i] = operand1[i];
}
break;
case CMPINT::NE:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] != bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::NLT:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] >= bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::NLE:
for (size_t i = 0; i < n; ++i) {
if (operand1[i] > bound) {
result[i] = operand1[i] + diff;
} else {
result[i] = operand1[i];
}
}
break;
case CMPINT::TRUE:
for (size_t i = 0; i < n; ++i) {
result[i] = operand1[i] + diff;
}
break;
}
}
} // namespace hexl
} // namespace intel
| 26.990909
| 80
| 0.534187
|
tgonzalez89-intel
|
062231383872e4d1289bb030778b03619543b79d
| 5,365
|
cpp
|
C++
|
tc 160+/WarTransportation.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 3
|
2015-05-25T06:24:37.000Z
|
2016-09-10T07:58:00.000Z
|
tc 160+/WarTransportation.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | null | null | null |
tc 160+/WarTransportation.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>
#include <queue>
#include <numeric>
using namespace std;
vector<string> cutUp(const string &s, const string &delim=" ") {
int lastPos = 0, pos = 0;
vector<string> ret;
while (pos+delim.size() <= s.size()) {
if (s.substr(pos, delim.size()) == delim) {
ret.push_back(s.substr(lastPos, pos-lastPos));
pos += (int)delim.size()-1;
lastPos = pos+1;
}
++pos;
}
if (lastPos < (int)s.size())
ret.push_back(s.substr(lastPos));
return ret;
}
int worst[100];
const int inf = 1234567890;
int dist[100];
int min_dist(int u, const vector< vector< pair<int, int> > > &G, bool special=false) {
for (int i=0; i<100; ++i) {
dist[i] = inf;
}
dist[u] = 0;
priority_queue< pair<int, int> > Q;
Q.push(make_pair(0, u));
while (!Q.empty()) {
const pair<int, int> t = Q.top();
Q.pop();
u = t.second;
int d = -t.first;
if (d > dist[u]) {
continue;
}
for (int i=0; i<(int)G[u].size(); ++i) {
const int v = G[u][i].first;
const int c = G[u][i].second;
int nd = d + c;
if (special) {
nd = max(nd, worst[v]);
}
if (nd < dist[v]) {
dist[v] = nd;
Q.push(make_pair(-nd, v));
}
}
}
return special ? dist[0] : dist[1];
}
class WarTransportation {
public:
int messenger(int n, vector <string> highways) {
string s = accumulate(highways.begin(), highways.end(), string());
vector<string> t = cutUp(s, ",");
vector< vector< pair<int, int> > > G(n, vector< pair<int, int> >());
for (int i=0; i<(int)t.size(); ++i) {
int a, b, c;
sscanf(t[i].c_str(), "%d %d %d", &a, &b, &c);
G[a-1].push_back(make_pair(b-1, c));
}
worst[1] = 0;
for (int i=0; i<n; ++i) {
if (i == 1) {
continue;
}
if (G[i].size() == 0) {
worst[i] = inf;
} else {
worst[i] = 0;
for (int j=0; j<(int)G[i].size(); ++j) {
const int real = G[i][j].second;
G[i][j].second = inf;
worst[i] = max(worst[i], min_dist(i, G));
G[i][j].second = real;
}
}
}
vector< vector< pair<int, int> > > G2(n, vector< pair<int, int> >());
for (int i=0; i<n; ++i) {
for (int j=0; j<(int)G[i].size(); ++j) {
G2[G[i][j].first].push_back(make_pair(i, G[i][j].second));
}
}
int sol = min_dist(1, G2, true);
return sol<inf ? sol : -1;
}
// 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 int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 3; string Arr1[] = {"1 2 1,1 3 2,3 2 3"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 5; verify_case(0, Arg2, messenger(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 8; string Arr1[] = {"1 3 1,1 4 1,3 5 1,4 5 1,5 6 1,6 7 1,6 8 1,7 2 1,",
"8 2 1"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(1, Arg2, messenger(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 4; string Arr1[] = {"1 3 1,1 3 2,3 2 1,1 4 1,4 2 1"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(2, Arg2, messenger(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 4; string Arr1[] = {"1 3 1,3 2 1,1 4 1,4 2 1,3 4 1"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(3, Arg2, messenger(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 20; string Arr1[] = {"1 13 3,13 4 7,4 3 4,3 10 8,10 18 9,18 12 6,12 2 3,",
"1 17 6,17 13 6,13 9 4,9 10 8,10 7 2,7 5 5,5 19 9,1",
"9 14 6,14 16 9,16 18 7,18 15 5,15 20 3,20 12 9,12 ",
"8 4,8 11 3,11 4 1,4 3 7,3 2 3,20 10 2,1 18 2,16 19",
" 9,4 15 9,13 15 6"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 23; verify_case(4, Arg2, messenger(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
WarTransportation ___test;
___test.run_test(-1);
}
// END CUT HERE
| 36.746575
| 309
| 0.492265
|
ibudiselic
|
06286b2b18cfd53d64bd9681f7984f231baa8655
| 123,585
|
cpp
|
C++
|
tools/flang2/flang2exe/mwd.cpp
|
kammerdienerb/flang
|
8cc4a02b94713750f09fe6b756d33daced0b4a74
|
[
"Apache-2.0"
] | null | null | null |
tools/flang2/flang2exe/mwd.cpp
|
kammerdienerb/flang
|
8cc4a02b94713750f09fe6b756d33daced0b4a74
|
[
"Apache-2.0"
] | null | null | null |
tools/flang2/flang2exe/mwd.cpp
|
kammerdienerb/flang
|
8cc4a02b94713750f09fe6b756d33daced0b4a74
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2000-2019, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/** \file
* \brief mw's dump routines
*/
#include "mwd.h"
#include "error.h"
#include "machar.h"
#include "global.h"
#include "symtab.h"
#include "ilm.h"
#include "fih.h"
#include "ili.h"
#include "iliutil.h"
#include "dtypeutl.h"
#include "machreg.h"
#ifdef SOCPTRG
#include "soc.h"
#endif
#include "llutil.h"
#include "symfun.h"
static int putdtypex(DTYPE dtype, int len);
static void _printnme(int n);
static bool g_dout = true;
#if defined(HOST_WIN)
#define vsnprintf _vsnprintf
#endif
#if DEBUG
static FILE *dfile;
static int linelen = 0;
#define BUFSIZE 10000
static char BUF[BUFSIZE];
static int longlines = 1, tight = 0, nexttight = 0;
/* for debug purpuse: test if the current
* function is the one that func specifies */
int
testcurrfunc(const char* func)
{
if(strcmp(SYMNAME(GBL_CURRFUNC), func)==0)
return true;
else
return false;
}
/*
* 'full' is zero for a 'diff' dump, so things like symbol numbers,
* ili numbers, etc., are left off; this makes ili trees and symbol dumps
* that are for all intents and purposes the same look more identical.
* 'full' is 2 for an 'important things' only dump; nmptr, hashlk left off
* 'full' is 1 for full dump, everything
*/
static int full = 1;
void
dumplong(void)
{
longlines = 1;
} /* dumplong */
void
dumpshort(void)
{
longlines = 0;
} /* dumpshort */
void
dumpdiff(void)
{
full = 0;
} /* dumpdiff */
void
dumpddiff(int v)
{
full = v;
} /* dumpddiff */
static void
putit(void)
{
int l = strlen(BUF);
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (linelen + l >= 78 && !longlines) {
fprintf(dfile, "\n%s", BUF);
linelen = l;
} else if (linelen > 0 && nexttight) {
fprintf(dfile, "%s", BUF);
linelen += l + 1;
} else if (linelen > 0 && tight) {
fprintf(dfile, " %s", BUF);
linelen += l + 1;
} else if (linelen > 0) {
fprintf(dfile, " %s", BUF);
linelen += l + 2;
} else {
fprintf(dfile, "%s", BUF);
linelen = l;
}
nexttight = 0;
} /* putit */
static void
puttight(void)
{
int l = strlen(BUF);
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "%s", BUF);
linelen += l;
} /* puttight */
static void
putline(void)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (linelen)
fprintf(dfile, "\n");
linelen = 0;
} /* putline */
void
putmwline()
{
putline();
} /* putmwline */
#include <stdarg.h>
static void
puterr(const char *fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
putline();
strcpy(BUF, "*** ");
vsnprintf(BUF + 4, BUFSIZE - 4, fmt, argptr);
strcat(BUF, " ***");
putit();
putline();
} /* puterr */
static void
appendit(void)
{
int l = strlen(BUF);
if (g_dout)
fprintf(dfile, "%s", BUF);
linelen += l;
nexttight = 0;
} /* appendit */
static void
putint(const char *s, int d)
{
if (g_dout) {
snprintf(BUF, BUFSIZE, "%s:%d", s, d);
putit();
}
} /* putint */
static void
putdouble(const char *s, double d)
{
if (g_dout) {
snprintf(BUF, BUFSIZE, "%s:%lg", s, d);
putit();
}
} /* putdouble */
static void
putbigint(const char *s, ISZ_T d)
{
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
} /* putbigint */
static void
putINT(const char *s, INT d)
{
snprintf(BUF, BUFSIZE, "%s:%ld", s, (long)d);
putit();
} /* putINT */
static void
putisz(const char *s, ISZ_T d)
{
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
} /* putisz */
static void
putISZ1(ISZ_T d)
{
snprintf(BUF, BUFSIZE, "%" ISZ_PF "d", d);
putit();
} /* putISZ1 */
static void
putintarray(const char *s, int *x, int size)
{
int i;
if (x != NULL) {
for (i = 0; i < size; ++i) {
if (x[i] != 0) {
snprintf(BUF, BUFSIZE, "%s[%d]:%8d %8x", s, i, x[i], x[i]);
x[i] = 0;
putit();
putline();
}
}
}
} /* putintarray */
static void
put1char(const char *s, char c)
{
snprintf(BUF, BUFSIZE, "%s:%c", s, c);
putit();
} /* put1char */
static void
puthex(const char *s, int d)
{
snprintf(BUF, BUFSIZE, "%s:0x%x", s, d);
putit();
} /* puthex */
static void
putnzhex(const char *s, int d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:0x%x", s, d);
putit();
}
} /* putnzhex */
static void
putnvptr(const char *s, void *d)
{
if (d) {
snprintf(BUF, BUFSIZE, "%s:%p", s, d);
putit();
}
} /* putnvptr */
static void
putnzint(const char *s, int d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%d", s, d);
putit();
}
} /* putnzint */
static void
putnzbigint(const char *s, ISZ_T d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
}
} /* putnzbigint */
static void
putnzINT(const char *s, INT d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%ld", s, (long)d);
putit();
}
} /* putnzINT */
static void
putnzisz(const char *s, ISZ_T d)
{
if (d != 0) {
snprintf(BUF, BUFSIZE, "%s:%" ISZ_PF "d", s, d);
putit();
}
} /* putnzint */
static void
putnzopc(const char *s, int opc)
{
if (opc != 0) {
if (opc >= 0 && opc < N_ILI) {
snprintf(BUF, BUFSIZE, "%s:%s", s, ilis[opc].name);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, opc);
}
putit();
}
} /* putnzopc */
static void
putedge(int d1, int d2)
{
snprintf(BUF, BUFSIZE, "%d-->%d", d1, d2);
putit();
} /* putedge */
static void
put2int(const char *s, int d1, int d2)
{
snprintf(BUF, BUFSIZE, "%s(%d:%d)", s, d1, d2);
putit();
} /* put2int */
static void
put2int1(int d1, int d2)
{
snprintf(BUF, BUFSIZE, "%d:%d", d1, d2);
putit();
} /* put2int1 */
static void
putpint(const char *s, int d)
{
put2int(s, (int)(d & 0xff), (int)(d >> 8));
} /* putpint */
void
putint1(int d)
{
snprintf(BUF, BUFSIZE, "%d", d);
putit();
} /* putint1 */
static void
putint1t(int d)
{
snprintf(BUF, BUFSIZE, "%d", d);
puttight();
} /* putint1t */
static void
putint2(const char *s, int d, const char *s2, int d2)
{
snprintf(BUF, BUFSIZE, " %s:%d,%s:%d", s, d, s2, d2);
putit();
} /* putint2 */
static int
appendint1(int d)
{
int r;
if (!g_dout) {
r = snprintf(BUF, BUFSIZE, "%d", d);
sprintf(BUF, "%s%d", BUF, d);
r = 0;
} else
r = sprintf(BUF, "%d", d);
appendit();
return r;
} /* appendint1 */
static int
appendbigint(ISZ_T d)
{
int r;
if (!g_dout) {
r = snprintf(BUF, BUFSIZE, "%" ISZ_PF "d", d);
sprintf(BUF, ("%s%" ISZ_PF "d"), BUF, d);
r = 0;
} else
r = sprintf(BUF, ("%" ISZ_PF "d"), d);
appendit();
return r;
} /* appendbigint */
static void
appendhex1(int d)
{
snprintf(BUF, BUFSIZE, "0x%x", d);
appendit();
} /* appendhex1 */
static void
putint3star(int d, int star1, const char *star1string, int star2, const char *star2string,
int star3, const char *star3string, int star4, const char *star4string)
{
if (star1 && star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s,%s=%d)", d, star1string, star2string,
star3string, star4string, star4);
} else if (!star1 && star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s=%d)", d, star2string, star3string,
star4string, star4);
} else if (star1 && !star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s=%d)", d, star1string, star3string,
star4string, star4);
} else if (!star1 && !star2 && star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s=%d)", d, star3string, star4string, star4);
} else if (star1 && star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s=%d)", d, star1string, star2string,
star4string, star4);
} else if (!star1 && star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s=%d)", d, star2string, star4string, star4);
} else if (star1 && !star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s=%d)", d, star1string, star4string, star4);
} else if (!star1 && !star2 && !star3 && star4) {
snprintf(BUF, BUFSIZE, "%d(%s=%d)", d, star4string, star4);
} else if (star1 && star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s,%s)", d, star1string, star2string,
star3string);
} else if (!star1 && star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s)", d, star2string, star3string);
} else if (star1 && !star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s)", d, star1string, star3string);
} else if (!star1 && !star2 && star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s)", d, star3string);
} else if (star1 && star2 && !star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s,%s)", d, star1string, star2string);
} else if (!star1 && star2 && !star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s)", d, star2string);
} else if (star1 && !star2 && !star3 && !star4) {
snprintf(BUF, BUFSIZE, "%d(%s)", d, star1string);
} else {
snprintf(BUF, BUFSIZE, "%d", d);
}
putit();
} /* putint3star */
static void
putbit(const char *s, int b)
{
/* single space between flags */
if (b) {
int l = strlen(s);
if (linelen + l >= 79 && !longlines) {
fprintf(dfile, "\n%s", s);
linelen = l;
} else if (linelen > 0) {
fprintf(dfile, " %s", s);
linelen += l + 1;
} else {
fprintf(dfile, "%s", s);
linelen = l;
}
}
} /* putbit */
static void
putstring(const char *s, const char *t)
{
snprintf(BUF, BUFSIZE, "%s:%s", s, t);
putit();
} /* putstring */
static void
mputchar(const char *s, char t)
{
snprintf(BUF, BUFSIZE, "%s:%c", s, t);
putit();
} /* mputchar */
static void
putnzchar(const char *s, char t)
{
if (t) {
snprintf(BUF, BUFSIZE, "%s:%c", s, t);
putit();
}
} /* putnzchar */
static void
putnstring(const char *s, const char *t)
{
if (t != NULL) {
snprintf(BUF, BUFSIZE, "%s:%s", s, t);
putit();
}
} /* putstring */
static void
putstringarray(const char *s, char **arr)
{
int i;
if (arr != NULL) {
for (i = 0; arr[i] != NULL; ++i) {
snprintf(BUF, BUFSIZE, "%s[%d]:%s", s, i, arr[i]);
putit();
}
}
} /* putstringarray */
static void
putdefarray(const char *s, char **arr)
{
int i;
if (arr != NULL) {
for (i = 0; arr[i] != NULL; i += 2) {
if (arr[i + 1] == (const char *)1) {
snprintf(BUF, BUFSIZE, "%s[%d] pred:%s", s, i, arr[i]);
} else if (arr[i + 1] == (const char *)0) {
snprintf(BUF, BUFSIZE, "%s[%d] undef:%s", s, i, arr[i]);
} else {
snprintf(BUF, BUFSIZE, "%s[%d] def:%s", s, i, arr[i]);
}
putit();
putline();
}
}
} /* putdefarray */
static void
putstring1(const char *t)
{
snprintf(BUF, BUFSIZE, "%s", t);
putit();
} /* putstring1 */
static void
putstring1t(const char *t)
{
snprintf(BUF, BUFSIZE, "%s", t);
puttight();
nexttight = 0;
} /* putstring1t */
static void
putstring1tt(const char *t)
{
snprintf(BUF, BUFSIZE, "%s", t);
puttight();
nexttight = 1;
} /* putstring1tt */
static int
appendstring1(const char *t)
{
int r;
if (!g_dout) {
strcat(BUF, t);
r = 0;
} else {
r = snprintf(BUF, BUFSIZE, "%s", t);
}
appendit();
return r;
} /* appendstring1 */
static void
putsym(const char *s, SPTR sptr)
{
if (full) {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, sptr, "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d=%s%s", s, sptr, printname(sptr),
ADDRTKNG(sptr) ? " (&)" : "");
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sptr);
}
} else {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%s:%s", s, "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%s%s", s, printname(sptr),
ADDRTKNG(sptr) ? " (&)" : "");
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sptr);
}
}
putit();
} /* putsym */
static void
putnsym(const char *s, SPTR sptr)
{
if (sptr != 0)
putsym(s, sptr);
} /* putnsym */
static void
putsym1(int sptr)
{
if (full) {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%d=%s", sptr, "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%d=%s", sptr, printname(sptr));
} else {
snprintf(BUF, BUFSIZE, "%d", sptr);
}
} else {
if (sptr == NOSYM) {
snprintf(BUF, BUFSIZE, "%s", "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s", printname(sptr));
} else {
snprintf(BUF, BUFSIZE, "%d", sptr);
}
}
putit();
} /* putsym1 */
static int
appendsym1(int sptr)
{
int r;
if (sptr == NOSYM) {
r = snprintf(BUF, BUFSIZE, "%s", "NOSYM");
} else if (sptr > 0 && sptr < stb.stg_avail) {
r = snprintf(BUF, BUFSIZE, "%s", printname(sptr));
} else {
r = snprintf(BUF, BUFSIZE, "sym%d", sptr);
}
appendit();
return r;
} /* appendsym1 */
static void
putsc(const char *s, int sc)
{
if (full) {
if (sc >= 0 && sc <= SC_MAX) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, sc, stb.scnames[sc] + 3);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sc);
}
} else {
if (sc >= 0 && sc <= SC_MAX) {
snprintf(BUF, BUFSIZE, "%s:%s", s, stb.scnames[sc] + 3);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, sc);
}
}
putit();
} /* putsc */
static void
putnsc(const char *s, int sc)
{
if (sc != 0)
putsc(s, sc);
} /* putnsc */
static void
putstype(const char *s, int stype)
{
if (full) {
if (stype >= 0 && stype <= ST_MAX) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, stype, stb.stypes[stype]);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, stype);
}
} else {
if (stype >= 0 && stype <= ST_MAX) {
snprintf(BUF, BUFSIZE, "%s:%s", s, stb.stypes[stype]);
} else {
snprintf(BUF, BUFSIZE, "%s:%d", s, stype);
}
}
putit();
} /* putstype */
static void
putddtype(const char *s, DTYPE d)
{
if (d) {
snprintf(BUF, BUFSIZE, "%s:%d=", s, d);
putit();
putdtypex(d, 80);
}
} /* putddtype */
static void
putmd(const char *s, int md)
{
#ifdef MDG
if (md == 0)
return;
snprintf(BUF, BUFSIZE, "%s:0x%x", s, md);
putit();
if (md & MD_X) {
snprintf(BUF, BUFSIZE, "X");
md &= ~MD_X;
putit();
}
if (md & MD_Y) {
snprintf(BUF, BUFSIZE, "Y");
md &= ~MD_Y;
putit();
}
if (md & MD_DATA) {
snprintf(BUF, BUFSIZE, "data");
md &= ~MD_DATA;
putit();
}
if (md & MD_RO) {
snprintf(BUF, BUFSIZE, "ro");
md &= ~MD_RO;
putit();
}
if (md & MD_TINY) {
snprintf(BUF, BUFSIZE, "tiny");
md &= ~MD_TINY;
putit();
}
if (md & MD_SMALL) {
snprintf(BUF, BUFSIZE, "small");
md &= ~MD_SMALL;
putit();
}
if (md) {
snprintf(BUF, BUFSIZE, "***mdbits:0x%x", md);
putit();
}
#endif /* MDG */
} /* putmd */
static void
putcgmode(const char *s, int cgmode)
{
#ifdef CGMODEG
if (cgmode == 0)
return;
snprintf(BUF, BUFSIZE, "%s:%x", s, cgmode);
putit();
switch (cgmode) {
case 0:
break;
case 1:
snprintf(BUF, BUFSIZE, "gp16");
break;
case 2:
snprintf(BUF, BUFSIZE, "gp32");
break;
default:
snprintf(BUF, BUFSIZE, "other");
break;
}
putit();
#endif /* CGMODEG */
} /* putcgmode */
static void
putxyptr(const char *s, int xyptr)
{
#ifdef XYPTRG
if (xyptr == 0)
return;
snprintf(BUF, BUFSIZE, "%s:%x", s, xyptr);
putit();
switch (xyptr) {
case 0:
break;
case MD_X:
snprintf(BUF, BUFSIZE, "Xptr");
break;
case MD_Y:
snprintf(BUF, BUFSIZE, "Yptr");
break;
}
putit();
#endif /* XYPTRG */
} /* putxyptr */
static void
putnname(const char *s, int off)
{
if (off) {
putstring(s, stb.n_base + off);
}
} /* putnname */
static void
putsymlk(const char *name, int list)
{
int c = 0;
if (list <= NOSYM)
return;
putline();
putstring1(name);
for (; list > NOSYM && c < 200; list = SYMLKG(list), ++c)
putsym1(list);
putline();
} /* putsymlk */
static void
dsymlk(int list)
{
int c = 0;
if (list <= NOSYM)
return;
for (; list > NOSYM && c < 200; list = SYMLKG(list), ++c) {
ds(list);
}
} /* dsymlk */
#ifdef TPLNKG
static void
puttplnk(const char *name, int list)
{
if (list <= NOSYM)
return;
putline();
putstring1(name);
for (; list > NOSYM; list = TPLNKG(list)) {
putsym1(list);
}
} /* puttplnk */
#endif
void
putnme(const char *s, int nme)
{
if (full) {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, nme, "NONE");
putit();
} else {
snprintf(BUF, BUFSIZE, "%s:%d=", s, nme);
putit();
_printnme(nme);
}
} else {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d", s, nme);
putit();
} else {
snprintf(BUF, BUFSIZE, "%s:", s);
putit();
_printnme(nme);
}
}
} /* putnme */
static void
putnnme(const char *s, int nme)
{
if (full) {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d=%s", s, nme, "NONE");
putit();
} else if (nme > 0) {
snprintf(BUF, BUFSIZE, "%s:%d=", s, nme);
putit();
_printnme(nme);
}
} else {
if (nme < 0 || nme >= nmeb.stg_avail) {
snprintf(BUF, BUFSIZE, "%s:%d", s, nme);
putit();
} else if (nme > 0) {
snprintf(BUF, BUFSIZE, "%s:", s);
putit();
_printnme(nme);
}
}
} /* putnnme */
#ifdef DPDSCG
static void
putparam(int dpdsc, int paramct)
{
if (paramct == 0)
return;
putline();
putstring1("Parameters:");
for (; paramct; ++dpdsc, --paramct) {
int sptr = aux.dpdsc_base[dpdsc];
if (sptr == 0) {
putstring1("*");
} else {
putsym1(sptr);
}
}
} /* putparam */
#endif /* DPDSCG */
#define SIZEOF(array) (sizeof(array) / sizeof(char *))
static void
putval(const char *s, int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "%s:%d", s, val);
putit();
} else {
putstring(s, values[val]);
}
} /* putval */
static void
putnval(const char *s, int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "%s:%d", s, val);
putit();
} else if (val > 0) {
putstring(s, values[val]);
}
} /* putnval */
static void
putval1(int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "%d", val);
putit();
} else {
putstring1(values[val]);
}
} /* putval1 */
static void
appendval(int val, const char *values[], int sizeofvalues)
{
if (val < 0 || val >= sizeofvalues) {
snprintf(BUF, BUFSIZE, "/%d", val);
appendit();
} else {
appendstring1(values[val]);
}
} /* appendval */
#ifdef SOCPTRG
void
putsoc(int socptr)
{
int p, q;
if (socptr == 0)
return;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (soc.base == NULL) {
fprintf(dfile, "soc.base not allocated\n");
return;
}
q = 0;
putline();
putstring1("Storage Overlap Chain:");
for (p = socptr; p; p = SOC_NEXT(p)) {
putsym1(SOC_SPTR(p));
if (q == p) {
putstring1(" >>> soc loop");
break;
}
q = p;
}
} /* putsoc */
#endif /* SOCPTRG */
#ifdef CUDAG
static void
putcuda(const char *s, int cu)
{
if (cu) {
strcpy(BUF, s);
strcat(BUF, ":");
if (cu & CUDA_HOST) {
strcat(BUF, "host");
cu &= ~CUDA_HOST;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_DEVICE) {
strcat(BUF, "device");
cu &= ~CUDA_DEVICE;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_GLOBAL) {
strcat(BUF, "global");
cu &= ~CUDA_GLOBAL;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_BUILTIN) {
strcat(BUF, "builtin");
cu &= ~CUDA_BUILTIN;
if (cu)
strcat(BUF, "+");
}
if (cu & CUDA_CONSTRUCTOR) {
strcat(BUF, "constructor");
cu &= ~CUDA_CONSTRUCTOR;
if (cu)
strcat(BUF, "+");
}
#ifdef CUDA_STUB
if (cu & CUDA_STUB) {
strcat(BUF, "stub");
cu &= ~CUDA_STUB;
if (cu)
strcat(BUF, "+");
}
#endif
putit();
}
} /* putcuda */
#endif
static void
check(const char *s, int v)
{
if (v) {
fprintf(dfile, "*** %s: %d %x\n", s, v, v);
}
} /* check */
/* dump one symbol to gbl.dbgfil */
void
dsym(int sptr)
{
SYMTYPE stype;
DTYPE dtype;
const char *np;
#ifdef SOCPTRG
int socptr;
#endif
int i;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (sptr == 0 || sptr >= stb.stg_avail) {
fprintf(dfile, "\nsymbol %d out of %d\n", sptr, stb.stg_avail - 1);
return;
}
BCOPY(stb.stg_base, stb.stg_base + sptr, SYM, 1);
stype = STYPEG(0);
switch (stype) {
case ST_BLOCK:
case ST_CMBLK:
case ST_LABEL:
case ST_BASE:
case ST_UNKNOWN:
dtype = DT_NONE;
break;
default:
dtype = DTYPEG(0);
break;
}
np = printname(sptr);
if (strlen(np) >= 30) {
fprintf(dfile, "\n%s", np);
np = " ";
}
fprintf(dfile, "\n%-30.30s ", np);
if (dtype) {
putdtypex(dtype, 50);
}
fprintf(dfile, "\n");
linelen = 0;
if (full) {
putint("sptr", sptr);
putnzint("dtype", DTYPEG(0));
}
if (full & 1)
putnzint("nmptr", NMPTRG(0));
putnsc("sc", SCG(0));
putstype("stype", STYPEG(0));
putline();
STYPEP(0, ST_UNKNOWN);
DTYPEP(0, DT_NONE);
NMPTRP(0, 0);
SCP(0, SC_NONE);
if (full & 1)
putnsym("hashlk", HASHLKG(0));
putnsym("scope", SCOPEG(SPTR_NULL));
putnsym("symlk", SYMLKG(0));
putline();
HASHLKP(0, SPTR_NULL);
SCOPEP(0, 0);
SYMLKP(0, SPTR_NULL);
switch (stype) {
case ST_ARRAY:
case ST_IDENT:
case ST_STRUCT:
case ST_UNION:
case ST_UNKNOWN:
case ST_VAR:
/* three lines: integers, symbols, bits */
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef SDSCG
putnsym("sdsc", SDSCG(0));
SDSCP(0, 0);
#endif
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef OMPACCDEVSYMG
putbit("ompaccel", OMPACCDEVSYMG(0));
OMPACCDEVSYMP(0, 0);
#endif
#ifdef OMPACCSHMEMG
putbit("ompaccel-shared", OMPACCSHMEMG(0));
OMPACCSHMEMP(0, 0);
#endif
#ifdef OMPACCSTRUCTG
putbit("ompaccel-host", OMPACCSTRUCTG(0));
OMPACCSTRUCTP(0, 0);
#endif
#ifdef OMPACCDEVSYMG
putbit("ompaccel", OMPACCDEVSYMG(0));
OMPACCDEVSYMP(0, 0);
#endif
#ifdef OMPACCSHMEMG
putbit("ompaccel-shared", OMPACCSHMEMG(0));
OMPACCSHMEMP(0, 0);
#endif
#ifdef OMPACCSTRUCTG
putbit("ompaccel-host", OMPACCSTRUCTG(0));
OMPACCSTRUCTP(0, 0);
#endif
#ifdef OMPACCLITERALG
putbit("ompaccel-literal", OMPACCLITERALG(0));
OMPACCLITERALP(0, 0);
#endif
#ifdef SOCPTRG
socptr = SOCPTRG(0);
putnzint("socptr", SOCPTRG(0));
SOCPTRP(0, 0);
#endif
putline();
{
#ifdef MDG
putmd("mdg", MDG(0));
MDP(0, 0);
#endif
}
putnzint("b3", b3G(0));
b3P(0, 0);
#ifdef ALIASG
putnsym("alias", ALIASG(0));
ALIASP(0, 0);
#endif
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
#ifdef BASESYMG
if (BASEADDRG(0)) {
putnsym("basesym", BASESYMG(0));
BASESYMP(0, 0);
}
#endif
#ifdef CLENG
putnsym("clen", CLENG(0));
CLENP(0, 0);
#endif
putnsym("midnum", MIDNUMG(0));
MIDNUMP(0, 0);
#ifdef IPAINFOG
if (IPANAMEG(0)) {
putnzint("ipainfo", IPAINFOG(0));
if (stb.n_base && IPANAMEG(0) && IPAINFOG(0) > 0 &&
IPAINFOG(0) < stb.namavl) {
putstring("ipaname", stb.n_base + IPAINFOG(0));
}
IPAINFOP(0, 0);
}
#endif
#ifdef ORIGDIMG
putnzint("origdim", ORIGDIMG(0));
ORIGDIMP(0, 0);
#endif
#ifdef ORIGDUMMYG
putnsym("origdummy", ORIGDUMMYG(0));
ORIGDUMMYP(0, 0);
#endif
#ifdef PDALNG
putnzint("pdaln", PDALNG(0));
b4P(0, 0);
#endif
#ifdef PARAMVALG
{
putnzint("paramval", PARAMVALG(0));
PARAMVALP(0, 0);
}
#endif
#ifdef TPLNKG
if (stype == ST_ARRAY) {
putnsym("tplnk", TPLNKG(0));
TPLNKP(0, 0);
}
#endif
#ifdef XYPTRG
{
putxyptr("xyptr", XYPTRG(0));
XYPTRP(0, 0);
}
#endif
#ifdef XREFLKG
{
putnsym("xreflk", XREFLKG(0));
XREFLKP(0, 0);
}
#endif
#ifdef ELFSCNG
putnsym("elfscn", ELFSCNG(0));
ELFSCNP(0, 0);
if (stype != ST_FUNC) {
putnsym("elflkg", ELFLKG(0));
ELFLKP(0, 0);
}
#endif
putline();
putbit("addrtkn", ADDRTKNG(0));
ADDRTKNP(0, 0);
#ifdef ACCINITDATAG
putbit("accinitdata", ACCINITDATAG(0));
ACCINITDATAP(0, 0);
#endif
#ifdef ADJARRG
putbit("adjarr", ADJARRG(0));
ADJARRP(0, 0);
#endif
#ifdef ALLOCG
putbit("alloc", ALLOCG(0));
ALLOCP(0, 0);
#endif
#ifdef ARG1PTRG
putbit("arg1ptr", ARG1PTRG(0));
ARG1PTRP(0, 0);
#endif
putbit("assn", ASSNG(0));
ASSNP(0, 0);
#ifdef ASSUMSHPG
putbit("assumshp", ASSUMSHPG(0));
ASSUMSHPP(0, 0);
#endif
#ifdef ASUMSZG
putbit("asumsz", ASUMSZG(0));
ASUMSZP(0, 0);
#endif
#ifdef AUTOBJG
putbit("autobj", AUTOBJG(0));
AUTOBJP(0, 0);
#endif
#ifdef BASEADDRG
putbit("baseaddr", BASEADDRG(0));
BASEADDRP(0, 0);
#endif
#ifdef CALLEDG
putbit("called", CALLEDG(0));
CALLEDP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef CLASSG
putbit("class", CLASSG(0));
CLASSP(0, 0);
#endif
#ifdef CONSTANTG
putbit("constant", CONSTANTG(0));
CONSTANTP(0, 0);
#endif
#ifdef CONSTG
putbit("const", CONSTG(0));
CONSTP(0, 0);
#endif
#ifdef COPYPRMSG
putbit("copyprms", COPYPRMSG(0));
COPYPRMSP(0, 0);
#endif
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
putbit("defd", DEFDG(0));
DEFDP(0, 0);
#ifdef DESCARRAYG
putbit("descarray", DESCARRAYG(0));
DESCARRAYP(0, 0);
#endif
#ifdef DEVICEG
putbit("device", DEVICEG(0));
DEVICEP(0, 0);
#endif
#ifdef DEVICECOPYG
putbit("devicecopy", DEVICECOPYG(0));
DEVICECOPYP(0, 0);
#endif
putbit("dinit", DINITG(0));
DINITP(0, 0);
#ifdef DVLG
putbit("dvl", DVLG(0));
DVLP(0, 0);
#endif
#ifdef ESCTYALIASG
putbit("esctyalias", ESCTYALIASG(0));
ESCTYALIASP(0, 0);
#endif
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
putbit("gscope", GSCOPEG(0));
GSCOPEP(0, 0);
#ifdef HOMEDG
putbit("homed", HOMEDG(0));
HOMEDP(0, 0);
#endif
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef INLNARRG
putbit("inlnarr", INLNARRG(0));
INLNARRP(0, 0);
#endif
#ifdef LIBCG
putbit("libc", LIBCG(0));
LIBCP(0, 0);
#endif
#ifdef LIBMG
putbit("libm", LIBMG(0));
LIBMP(0, 0);
#endif
#ifdef LOCLIFETMG
putbit("loclifetm", LOCLIFETMG(0));
LOCLIFETMP(0, 0);
#endif
#ifdef LSCOPEG
putbit("lscope", LSCOPEG(0));
LSCOPEP(0, 0);
#endif
#ifdef LVALG
putbit("lval", LVALG(0));
LVALP(0, 0);
#endif
#ifdef MANAGEDG
putbit("managed", MANAGEDG(0));
MANAGEDP(0, 0);
#endif
putbit("memarg", MEMARGG(0));
MEMARGP(0, 0);
#ifdef MIRROREDG
putbit("mirrored", MIRROREDG(0));
MIRROREDP(0, 0);
#endif
#ifdef ACCCREATEG
putbit("acccreate", ACCCREATEG(0));
ACCCREATEP(0, 0);
#endif
#ifdef ACCCOPYING
putbit("acccopyin", ACCCOPYING(0));
ACCCOPYINP(0, 0);
#endif
#ifdef ACCRESIDENTG
putbit("accresident", ACCRESIDENTG(0));
ACCRESIDENTP(0, 0);
#endif
#ifdef ACCLINKG
putbit("acclink", ACCLINKG(0));
ACCLINKP(0, 0);
#endif
#ifdef MODESETG
if (stype == ST_FUNC) {
putbit("modeset", MODESETG(0));
MODESETP(0, 0);
}
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NOCONFLICTG
putbit("noconflict", NOCONFLICTG(0));
NOCONFLICTP(0, 0);
#endif
#ifdef NOTEXTERNG
putbit("notextern", NOTEXTERNG(0));
NOTEXTERNP(0, 0);
#endif
#ifdef OPTARGG
putbit("optarg", OPTARGG(0));
OPTARGP(0, 0);
#endif
#ifdef OSXINITG
if (stype == ST_FUNC) {
putbit("osxinit", OSXINITG(0));
OSXINITP(0, 0);
putbit("osxterm", OSXTERMG(0));
OSXTERMP(0, 0);
}
#endif
#ifdef PARAMG
putbit("param", PARAMG(0));
PARAMP(0, 0);
#endif
#ifdef PASSBYVALG
putbit("passbyval", PASSBYVALG(0));
PASSBYVALP(0, 0);
#endif
#ifdef PASSBYREFG
putbit("passbyref", PASSBYREFG(0));
PASSBYREFP(0, 0);
#endif
#ifdef PINNEDG
putbit("pinned", PINNEDG(0));
PINNEDP(0, 0);
#endif
#ifdef POINTERG
putbit("pointer", POINTERG(0));
POINTERP(0, 0);
#endif
#ifdef ALLOCATTRP
putbit("allocattr", ALLOCATTRG(0));
ALLOCATTRP(0, 0);
#endif
#ifdef PROTODCLG
putbit("protodcl", PROTODCLG(0));
PROTODCLP(0, 0);
#endif
#ifdef PTRSAFEG
putbit("ptrsafe", PTRSAFEG(0));
PTRSAFEP(0, 0);
#endif
putbit("qaln", QALNG(0));
QALNP(0, 0);
#ifdef REDUCG
putbit("reduc", REDUCG(0));
REDUCP(0, 0);
#endif
#ifdef REFG
putbit("ref", REFG(0));
REFP(0, 0);
#endif
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
#ifdef REFLECTEDG
putbit("reflected", REFLECTEDG(0));
REFLECTEDP(0, 0);
#endif
putbit("regarg", REGARGG(0));
REGARGP(0, 0);
#ifdef RESTRICTG
putbit("restrict", RESTRICTG(0));
RESTRICTP(0, 0);
#endif
#ifdef SAFEG
putbit("safe", SAFEG(0));
SAFEP(0, 0);
#endif
#ifdef SAVEG
putbit("save", SAVEG(0));
SAVEP(0, 0);
#endif
#ifdef SDSCCONTIGG
putbit("sdsccontig", SDSCCONTIGG(0));
SDSCCONTIGP(0, 0);
#endif
#ifdef SDSCS1G
putbit("sdscs1", SDSCS1G(0));
SDSCS1P(0, 0);
#endif
#ifdef SECTG
putbit("sect", SECTG(0));
SECTP(0, 0);
#endif
#ifdef SHAREDG
putbit("shared", SHAREDG(0));
SHAREDP(0, 0);
#endif
#ifdef TEXTUREG
putbit("texture", TEXTUREG(0));
TEXTUREP(0, 0);
#endif
#ifdef INTENTING
putbit("intentin", INTENTING(0));
INTENTINP(0, 0);
#endif
putbit("thread", THREADG(0));
THREADP(0, 0);
#ifdef UNSAFEG
putbit("unsafe", UNSAFEG(0));
UNSAFEP(0, 0);
#endif
#ifdef UPLEVELG
putbit("uplevel", UPLEVELG(0));
UPLEVELP(0, 0);
#endif
#ifdef INTERNREFG
putbit("internref", INTERNREFG(0));
INTERNREFP(0, 0);
#endif
#ifdef VARDSCG
putbit("vardsc", VARDSCG(0));
VARDSCP(0, 0);
#endif
#ifdef VLAG
putbit("vla", VLAG(0));
VLAP(0, 0);
#endif
#ifdef VLAIDXG
putbit("vlaidx", VLAIDXG(0));
VLAIDXP(0, 0);
#endif
putbit("vol", VOLG(0));
VOLP(0, 0);
#ifdef WEAKG
putbit("weak", WEAKG(0));
WEAKP(0, 0);
#endif
#ifdef PARREFG
putbit("parref", PARREFG(0));
PARREFP(0, 0);
#endif
#ifdef PARREFLOADG
putbit("parrefload", PARREFLOADG(0));
PARREFLOADP(0, 0);
#endif
#ifdef OMPTEAMPRIVATEG
putbit("team-private", OMPTEAMPRIVATEG(0));
OMPTEAMPRIVATEP(0, 0);
#endif
/*
putbit( "#", #G(0) ); #P(0,0);
*/
#ifdef SOCPTRG
if (socptr)
putsoc(socptr);
#endif
break;
case ST_BLOCK:
putint("startline", STARTLINEG(0));
STARTLINEP(0, 0);
putint("endline", ENDLINEG(0));
ENDLINEP(0, 0);
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
putnsym("startlab", STARTLABG(0));
STARTLABP(0, 0);
putnsym("endlab", ENDLABG(0));
ENDLABP(0, 0);
putnsym("beginscopelab", BEGINSCOPELABG(0));
BEGINSCOPELABP(0, 0);
putnsym("endscopelab", ENDSCOPELABG(0));
ENDSCOPELABP(0, 0);
#ifdef AUTOBJG
putnzint("autobj", AUTOBJG(0));
AUTOBJP(0, 0);
#endif
#ifdef AINITG
putbit("ainit", AINITG(0));
AINITP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
#ifdef PARUPLEVELG
putint("paruplevel", PARUPLEVELG(0));
PARUPLEVELP(0, 0);
#endif
#ifdef PARSYMSG
putbit("parsyms", PARSYMSG(0));
PARSYMSP(0, 0);
#endif
#ifdef PARSYMSCTG
putbit("parsymsct", PARSYMSCTG(0));
PARSYMSCTP(0, 0);
#endif
break;
case ST_BASE:
break;
case ST_CMBLK:
putint("size", SIZEG(0));
SIZEP(0, 0);
putline();
putsym("cmemf", CMEMFG(0));
CMEMFP(0, 0);
putsym("cmeml", CMEMLG(0));
CMEMLP(0, 0);
#ifdef INMODULEG
putnzint("inmodule", INMODULEG(0));
INMODULEP(0, 0);
#endif
putnsym("midnum", MIDNUMG(0));
MIDNUMP(0, 0);
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
#ifdef PDALNG
putnzint("pdaln", PDALNG(0));
PDALNP(0, 0);
#endif
putline();
#ifdef ACCCREATEG
putbit("acccreate", ACCCREATEG(0));
ACCCREATEP(0, 0);
#endif
#ifdef ACCCOPYING
putbit("acccopyin", ACCCOPYING(0));
ACCCOPYINP(0, 0);
#endif
#ifdef ACCRESIDENTG
putbit("accresident", ACCRESIDENTG(0));
ACCRESIDENTP(0, 0);
#endif
#ifdef ACCLINKG
putbit("acclink", ACCLINKG(0));
ACCLINKP(0, 0);
#endif
putbit("alloc", ALLOCG(0));
ALLOCP(0, 0);
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef CONSTANTG
putbit("constant", CONSTANTG(0));
CONSTANTP(0, 0);
#endif
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("defd", DEFDG(0));
DEFDP(0, 0);
#ifdef DEVICEG
putbit("device", DEVICEG(0));
DEVICEP(0, 0);
#endif
putbit("dinit", DINITG(0));
DINITP(0, 0);
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef FROMMODG
putbit("frommod", FROMMODG(0));
FROMMODP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef MODCMNG
putbit("modcmn", MODCMNG(0));
MODCMNP(0, 0);
#endif
putbit("qaln", QALNG(0));
QALNP(0, 0);
putbit("save", SAVEG(0));
SAVEP(0, 0);
#ifdef THREADG
putbit("thread", THREADG(0));
THREADP(0, 0);
#endif
putbit("vol", VOLG(0));
VOLP(0, 0);
putsymlk("Members:", CMEMFG(sptr));
break;
case ST_CONST:
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
if (DTY(dtype) == TY_PTR) {
putsym("pointee", STGetPointee(0));
CONVAL1P(0, 0);
putnzbigint("offset", ACONOFFG(0));
ACONOFFP(0, 0);
} else {
putint("conval1g", CONVAL1G(0));
CONVAL1P(0, 0);
putbigint("conval2g", CONVAL2G(0));
CONVAL2P(0, 0);
}
putline();
break;
case ST_ENTRY:
putnzint("bihnum", BIHNUMG(0));
BIHNUMP(0, 0);
#ifdef ARGSIZEG
putnzint("argsize", ARGSIZEG(0));
ARGSIZEP(0, 0);
#endif
putint("dpdsc", DPDSCG(0));
DPDSCP(0, 0);
putint("funcline", FUNCLINEG(0));
FUNCLINEP(0, 0);
#ifdef DECLLINEG
putnzint("declline", DECLLINEG(0));
DECLLINEP(0, 0);
#endif
putint("paramct", PARAMCTG(0));
PARAMCTP(0, 0);
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
putline();
#ifdef INMODULEG
putnsym("inmodule", INMODULEG(0));
INMODULEP(0, 0);
#endif
putnsym("gsame", GSAMEG(0));
GSAMEP(0, 0);
putnsym("fval", FVALG(0));
FVALP(0, 0);
#ifdef CUDAG
putcuda("cuda", CUDAG(0));
CUDAP(0, 0);
#endif
#ifdef ACCROUTG
putnzint("accrout", ACCROUTG(0));
ACCROUTP(0, 0);
#endif
#ifdef OMPACCFUNCDEVG
putbit("ompaccel-device", OMPACCFUNCDEVG(0));
OMPACCFUNCDEVP(0, 0);
#endif
#ifdef OMPACCFUNCKERNELG
putbit("ompaccel-kernel", OMPACCFUNCKERNELG(0));
OMPACCFUNCKERNELP(0, 0);
#endif
#ifdef OMPACCFUNCDEVG
putbit("ompaccel-device", OMPACCFUNCDEVG(0));
OMPACCFUNCDEVP(0, 0);
#endif
#ifdef OMPACCFUNCKERNELG
putbit("ompaccel-kernel", OMPACCFUNCKERNELG(0));
OMPACCFUNCKERNELP(0, 0);
#endif
#ifdef IPAINFOG
putnzint("ipainfo", IPAINFOG(0));
if (stb.n_base && IPANAMEG(0) && IPAINFOG(0) > 0 &&
IPAINFOG(0) < stb.namavl) {
putstring("ipaname", stb.n_base + IPAINFOG(0));
}
IPAINFOP(0, 0);
#endif
putline();
putbit("adjarr", ADJARRG(0));
ADJARRP(0, 0);
putbit("aftent", AFTENTG(0));
AFTENTP(0, 0);
#ifdef CALLEDG
putbit("called", CALLEDG(0));
CALLEDP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef CONTAINEDG
putbit("contained", CONTAINEDG(0));
CONTAINEDP(0, 0);
#endif
#ifdef COPYPRMSG
putbit("copyprms", COPYPRMSG(0));
COPYPRMSP(0, 0);
#endif
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#ifdef DECORATEG
putbit("decorate", DECORATEG(0));
DECORATEP(0, 0);
#endif
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NOTEXTERNG
putbit("notextern", NOTEXTERNG(0));
NOTEXTERNP(0, 0);
#endif
putbit("pure", PUREG(0));
PUREP(0, 0);
#ifdef ELEMENTALG
putbit("elemental", ELEMENTALG(0));
ELEMENTALP(0, 0);
#endif
#ifdef RECURG
putbit("recur", RECURG(0));
RECURP(0, 0);
#endif
#ifdef STDCALLG
putbit("stdcall", STDCALLG(0));
STDCALLP(0, 0);
#endif
putline();
putparam(DPDSCG(sptr), PARAMCTG(sptr));
break;
case ST_GENERIC:
putnsym("gcmplx", GCMPLXG(0));
GCMPLXP(0, 0);
putnsym("gdble", GDBLEG(0));
GDBLEP(0, 0);
putnsym("gdcmplx", GDCMPLXG(0));
GDCMPLXP(0, 0);
putnsym("gint", GINTG(0));
GINTP(0, 0);
putnsym("gint8", GINT8G(0));
GINT8P(0, 0);
#ifdef GQCMPLXG
putnsym("gqcmplx", GQCMPLXG(0));
GQCMPLXP(0, 0);
#endif
#ifdef GQUADG
putnsym("gquad", GQUADG(0));
GQUADP(0, 0);
#endif
putnsym("greal", GREALG(0));
GREALP(0, 0);
putnsym("gsame", GSAMEG(0));
GSAMEP(0, 0);
putnsym("gsint", GSINTG(0));
GSINTP(0, 0);
putnzint("gndsc", GNDSCG(0));
GNDSCP(0, 0);
putnzint("gncnt", GNCNTG(0));
GNCNTP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
break;
case ST_INTRIN:
putddtype("argtyp", ARGTYPG(0));
ARGTYPP(0, 0);
putnzint("arrayf", ARRAYFG(0));
ARRAYFP(0, 0);
putnzint("ilm", ILMG(0));
ILMP(0, 0);
putddtype("inttyp", INTTYPG(0));
INTTYPP(0, 0);
putnname("pnmptr", PNMPTRG(0));
PNMPTRP(0, 0);
putint("paramct", PARAMCTG(0));
PARAMCTP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("expst", EXPSTG(0));
EXPSTP(0, 0);
break;
case ST_LABEL:
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef FMTPTG
putnsym("fmtpt", FMTPTG(0));
FMTPTP(0, 0);
#endif
putnzint("iliblk", ILIBLKG(0));
ILIBLKP(0, 0);
#ifdef JSCOPEG
putnzint("jscope", JSCOPEG(0));
JSCOPEP(0, 0);
#endif
putint("rfcnt", RFCNTG(0));
RFCNTP(0, 0);
putline();
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
putbit("defd", DEFDG(0));
DEFDP(0, 0);
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef LSCOPEG
putbit("lscope", LSCOPEG(0));
LSCOPEP(0, 0);
#endif
putbit("qaln", QALNG(0));
QALNP(0, 0);
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
putbit("vol", VOLG(0));
VOLP(0, 0);
putbit("beginscope", BEGINSCOPEG(0));
BEGINSCOPEP(0, 0);
putbit("endscope", ENDSCOPEG(0));
ENDSCOPEP(0, 0);
break;
case ST_MEMBER:
putint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef BITOFFG
putnzint("bitoff", BITOFFG(0));
BITOFFP(0, 0);
#endif
#ifdef FLDSZG
putnzint("fldsz", FLDSZG(0));
FLDSZP(0, 0);
#endif
#ifdef LDSIZEG
putnzint("ldsize", LDSIZEG(0));
LDSIZEP(0, 0);
#endif
putsym("psmem", PSMEMG(0));
PSMEMP(0, 0);
#ifdef VARIANTG
putsym("variant", VARIANTG(0));
VARIANTP(0, 0);
#endif
#ifdef INDTYPEG
putnzint("indtype", INDTYPEG(0));
INDTYPEP(0, 0);
#endif
#ifdef SDSCG
putnsym("sdsc", SDSCG(0));
SDSCP(0, 0);
#endif
putline();
#ifdef ALLOCATTRG
putbit("allocattr", ALLOCATTRG(0));
ALLOCATTRP(0, 0);
#endif
#ifdef CLASSG
putbit("class", CLASSG(0));
CLASSP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
#ifdef DESCARRAYG
putbit("descarray", DESCARRAYG(0));
DESCARRAYP(0, 0);
#endif
#ifdef FIELDG
putbit("field", FIELDG(0));
FIELDP(0, 0);
#endif
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NOCONFLICTG
putbit("noconflict", NOCONFLICTG(0));
NOCONFLICTP(0, 0);
#endif
#ifdef PLAING
putbit("plain", PLAING(0));
PLAINP(0, 0);
#endif
#ifdef POINTERG
putbit("pointer", POINTERG(0));
POINTERP(0, 0);
#endif
#ifdef PTRSAFEG
putbit("ptrsafe", PTRSAFEG(0));
PTRSAFEP(0, 0);
#endif
#ifdef REFDG
putbit("refd", REFDG(0));
REFDP(0, 0);
#endif
#ifdef SDSCCONTIGG
putbit("sdsccontig", SDSCCONTIGG(0));
SDSCCONTIGP(0, 0);
#endif
#ifdef SDSCS1G
putbit("sdscs1", SDSCS1G(0));
SDSCS1P(0, 0);
#endif
break;
case ST_NML:
putsym("plist", (SPTR) ADDRESSG(0)); // ???
ADDRESSP(0, 0);
putsym("cmemf", CMEMFG(0));
CMEMFP(0, 0);
putsym("cmeml", CMEMLG(0));
CMEMLP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("ref", REFG(0));
REFP(0, 0);
putline();
for (i = CMEMFG(sptr); i; i = NML_NEXT(i)) {
putsym1(NML_SPTR(i));
}
break;
case ST_PARAM:
putint("conval1g", CONVAL1G(0));
CONVAL1P(0, 0);
putint("conval2g", CONVAL2G(0));
CONVAL2P(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("ref", REFG(0));
REFP(0, 0);
break;
case ST_PD:
putddtype("argtyp", ARGTYPG(0));
ARGTYPP(0, 0);
putint("paramct", PARAMCTG(0));
PARAMCTP(0, 0);
putnzint("ilm", ILMG(0));
ILMP(0, 0);
putint("pdnum", PDNUMG(0));
PDNUMP(0, 0);
break;
case ST_PLIST:
putint("address", ADDRESSG(0));
ADDRESSP(0, 0);
#ifdef BASESYMG
if (BASEADDRG(0)) {
putnsym("basesym", BASESYMG(0));
BASESYMP(0, 0);
}
#endif
putnzint("deflab", DEFLABG(0));
DEFLABP(0, 0);
putint("pllen", PLLENG(0));
PLLENP(0, 0);
putnzint("swel", SWELG(0));
SWELP(0, 0);
putline();
putbit("addrtkn", ADDRTKNG(0));
ADDRTKNP(0, 0);
#ifdef BASEADDRG
putbit("baseaddr", BASEADDRG(0));
BASEADDRP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("dinit", DINITG(0));
DINITP(0, 0);
#ifdef INLING
putbit("inlin", INLING(0));
INLINP(0, 0);
#endif
#ifdef ALWAYSINLING
putbit("alwaysinlin", ALWAYSINLING(0));
ALWAYSINLINP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
#ifdef LSCOPEG
putbit("lscope", LSCOPEG(0));
LSCOPEP(0, 0);
#endif
putbit("ref", REFG(0));
REFP(0, 0);
break;
case ST_PROC:
#ifdef INMODULEG
putnsym("inmodule", INMODULEG(0));
INMODULEP(0, 0);
#endif
#ifdef ARGSIZEG
putnzint("argsize", ARGSIZEG(0));
ARGSIZEP(0, 0);
#endif
putnzint("address", ADDRESSG(0));
ADDRESSP(0, 0);
putnsym("midnum", MIDNUMG(0));
MIDNUMP(0, 0);
#ifdef IPAINFOG
putnzint("ipainfo", IPAINFOG(0));
if (stb.n_base && IPANAMEG(0) && IPAINFOG(0) > 0 &&
IPAINFOG(0) < stb.namavl) {
putstring("ipaname", stb.n_base + IPAINFOG(0));
}
IPAINFOP(0, 0);
#endif
#ifdef ALTNAMEG
putnsym("altname", ALTNAMEG(0));
ALTNAMEP(0, 0);
#endif
#ifdef ACCROUTG
putnzint("accrout", ACCROUTG(0));
ACCROUTP(0, 0);
#endif
#ifdef ARG1PTRG
putbit("arg1ptr", ARG1PTRG(0));
ARG1PTRP(0, 0);
#endif
#ifdef CUDAG
putcuda("cuda", CUDAG(0));
CUDAP(0, 0);
#endif
putline();
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
putbit("ccsym", CCSYMG(0));
CCSYMP(0, 0);
#ifdef COPYPRMSG
putbit("copyprms", COPYPRMSG(0));
COPYPRMSP(0, 0);
#endif
#ifdef CONTAINEDG
putbit("contained", CONTAINEDG(0));
CONTAINEDP(0, 0);
#endif
#ifdef DECORATEG
putbit("decorate", DECORATEG(0));
DECORATEP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef NEEDMODG
putbit("needmod", NEEDMODG(0));
NEEDMODP(0, 0);
#endif
putbit("nopad", NOPADG(0));
NOPADP(0, 0);
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
putbit("func", FUNCG(0));
FUNCP(0, 0);
#ifdef FROMINLRG
putbit("frominlr", FROMINLRG(0));
FROMINLRP(0, 0);
#endif
#ifdef LIBMG
putbit("libm", LIBMG(0));
LIBMP(0, 0);
#endif
putbit("memarg", MEMARGG(0));
MEMARGP(0, 0);
#ifdef PASSBYVALG
putbit("passbyval", PASSBYVALG(0));
PASSBYVALP(0, 0);
#endif
#ifdef PASSBYREFG
putbit("passbyref", PASSBYREFG(0));
PASSBYREFP(0, 0);
#endif
putbit("pure", PUREG(0));
PUREP(0, 0);
putbit("ref", REFG(0));
REFP(0, 0);
#ifdef SDSCSAFEG
putbit("sdscsafe", SDSCSAFEG(0));
SDSCSAFEP(0, 0);
#endif
#ifdef STDCALLG
putbit("stdcall", STDCALLG(0));
STDCALLP(0, 0);
#endif
#ifdef UNIFIEDG
putbit("unified", UNIFIEDG(0));
UNIFIEDP(0, 0);
#endif
putline();
putparam(DPDSCG(sptr), PARAMCTG(sptr));
break;
case ST_STFUNC:
putint("excvlen", EXCVLENG(0));
EXCVLENP(0, 0);
putint("sfdsc", SFDSCG(0));
SFDSCP(0, 0);
putline();
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
break;
case ST_TYPEDEF:
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef PDALNG
putnzint("pdaln", PDALNG(0));
PDALNP(0, 0);
#endif
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
#ifdef FROMMODG
putbit("frommod", FROMMODG(0));
FROMMODP(0, 0);
#endif
#ifdef MSCALLG
putbit("mscall", MSCALLG(0));
MSCALLP(0, 0);
#endif
#ifdef CFUNCG
putbit("cfunc", CFUNCG(0));
CFUNCP(0, 0);
#endif
#ifdef CLASSG
putbit("class", CLASSG(0));
CLASSP(0, 0);
#endif
#ifdef PLAING
putbit("plain", PLAING(0));
PLAINP(0, 0);
#endif
break;
case ST_STAG:
#ifdef ENCLFUNCG
putnsym("enclfunc", ENCLFUNCG(0));
ENCLFUNCP(0, 0);
#endif
#ifdef DCLDG
putbit("dcld", DCLDG(0));
DCLDP(0, 0);
#endif
#ifdef INLNG
putbit("inln", INLNG(0));
INLNP(0, 0);
#endif
break;
} /* switch(stype) */
putline();
check("b3", stb.stg_base[0].b3);
check("b4", stb.stg_base[0].b4);
check("f1", stb.stg_base[0].f1);
check("f2", stb.stg_base[0].f2);
check("f3", stb.stg_base[0].f3);
check("f4", stb.stg_base[0].f4);
check("f5", stb.stg_base[0].f5);
check("f6", stb.stg_base[0].f6);
check("f7", stb.stg_base[0].f7);
check("f8", stb.stg_base[0].f8);
check("f9", stb.stg_base[0].f9);
check("f10", stb.stg_base[0].f10);
check("f11", stb.stg_base[0].f11);
check("f12", stb.stg_base[0].f12);
check("f13", stb.stg_base[0].f13);
check("f14", stb.stg_base[0].f14);
check("f15", stb.stg_base[0].f15);
check("f16", stb.stg_base[0].f16);
check("f17", stb.stg_base[0].f17);
check("f18", stb.stg_base[0].f18);
check("f19", stb.stg_base[0].f19);
check("f20", stb.stg_base[0].f20);
check("f21", stb.stg_base[0].f21);
check("f22", stb.stg_base[0].f22);
check("f23", stb.stg_base[0].f23);
check("f24", stb.stg_base[0].f24);
check("f25", stb.stg_base[0].f25);
check("f26", stb.stg_base[0].f26);
check("f27", stb.stg_base[0].f27);
check("f28", stb.stg_base[0].f28);
check("f29", stb.stg_base[0].f29);
check("f30", stb.stg_base[0].f30);
check("f31", stb.stg_base[0].f31);
check("f32", stb.stg_base[0].f32);
check("f33", stb.stg_base[0].f33);
check("f34", stb.stg_base[0].f34);
check("f35", stb.stg_base[0].f35);
check("f36", stb.stg_base[0].f36);
check("f37", stb.stg_base[0].f37);
check("f38", stb.stg_base[0].f38);
check("f39", stb.stg_base[0].f39);
check("f40", stb.stg_base[0].f40);
check("f41", stb.stg_base[0].f41);
check("f42", stb.stg_base[0].f42);
check("f43", stb.stg_base[0].f43);
check("f44", stb.stg_base[0].f44);
check("f45", stb.stg_base[0].f45);
check("f46", stb.stg_base[0].f46);
check("f47", stb.stg_base[0].f47);
check("f48", stb.stg_base[0].f48);
check("f50", stb.stg_base[0].f50);
check("f51", stb.stg_base[0].f51);
check("f52", stb.stg_base[0].f52);
check("f53", stb.stg_base[0].f53);
check("f54", stb.stg_base[0].f54);
check("f55", stb.stg_base[0].f55);
check("f56", stb.stg_base[0].f56);
check("f57", stb.stg_base[0].f57);
check("f58", stb.stg_base[0].f58);
check("f59", stb.stg_base[0].f59);
check("f60", stb.stg_base[0].f60);
check("f61", stb.stg_base[0].f61);
check("f62", stb.stg_base[0].f62);
check("f63", stb.stg_base[0].f63);
check("f64", stb.stg_base[0].f64);
check("f65", stb.stg_base[0].f65);
check("f66", stb.stg_base[0].f66);
check("f67", stb.stg_base[0].f67);
check("f68", stb.stg_base[0].f68);
check("f69", stb.stg_base[0].f69);
check("f70", stb.stg_base[0].f70);
check("f71", stb.stg_base[0].f71);
check("f72", stb.stg_base[0].f72);
check("f73", stb.stg_base[0].f73);
check("f74", stb.stg_base[0].f74);
check("f75", stb.stg_base[0].f75);
check("f76", stb.stg_base[0].f76);
check("f77", stb.stg_base[0].f77);
check("f78", stb.stg_base[0].f78);
check("f79", stb.stg_base[0].f79);
check("f80", stb.stg_base[0].f80);
check("f81", stb.stg_base[0].f81);
check("f82", stb.stg_base[0].f82);
check("f83", stb.stg_base[0].f83);
check("f84", stb.stg_base[0].f84);
check("f85", stb.stg_base[0].f85);
check("f86", stb.stg_base[0].f86);
check("f87", stb.stg_base[0].f87);
check("f88", stb.stg_base[0].f88);
check("f89", stb.stg_base[0].f89);
check("f90", stb.stg_base[0].f90);
check("f91", stb.stg_base[0].f91);
check("f92", stb.stg_base[0].f92);
check("f93", stb.stg_base[0].f93);
check("f94", stb.stg_base[0].f94);
check("f95", stb.stg_base[0].f95);
check("f96", stb.stg_base[0].f96);
check("f110", stb.stg_base[0].f110);
check("f111", stb.stg_base[0].f111);
check("w8", stb.stg_base[0].w8);
check("w9", stb.stg_base[0].w9);
check("w10", stb.stg_base[0].w10);
check("w11", stb.stg_base[0].w11);
check("w12", stb.stg_base[0].w12);
check("w13", stb.stg_base[0].w13);
check("w14", stb.stg_base[0].w14);
check("w15", stb.stg_base[0].w15);
check("w16", stb.stg_base[0].w16);
check("w17", stb.stg_base[0].w17);
check("w18", stb.stg_base[0].w18);
check("w20", stb.stg_base[0].w20);
} /* dsym */
void
dsyms(int l, int u)
{
int i;
if (l <= 0)
l = stb.firstusym;
if (u <= 0)
u = stb.stg_avail - 1;
if (u >= stb.stg_avail)
u = stb.stg_avail - 1;
for (i = l; i <= u; ++i) {
dsym(i);
}
fprintf(dfile, "\n");
} /* dsyms */
void
ds(int sptr)
{
dsym(sptr);
} /* ds */
void
dsa(void)
{
dsyms(0, 0);
} /* dsa */
void
dss(int l, int u)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** SYMBOL TABLE **********\n");
dsyms(l, u);
} /* dss */
void
dgbl(void)
{
GBL mbl;
int *ff;
int i, mblsize;
memcpy(&mbl, &gbl, sizeof(gbl));
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
putsym("gbl.currsub", mbl.currsub);
mbl.currsub = SPTR_NULL;
putnstring("gbl.datetime", mbl.datetime);
memset(mbl.datetime, 0, sizeof(mbl.datetime));
putline();
putnzint("gbl.maxsev", mbl.maxsev);
mbl.maxsev = 0;
putnzint("gbl.findex", mbl.findex);
mbl.findex = 0;
putsymlk("gbl.entries=", mbl.entries);
mbl.entries = SPTR_NULL;
putsymlk("gbl.cmblks=", mbl.cmblks);
mbl.cmblks = SPTR_NULL;
putsymlk("gbl.externs=", mbl.externs);
mbl.externs = SPTR_NULL;
putsymlk("gbl.consts=", mbl.consts);
mbl.consts = SPTR_NULL;
putsymlk("gbl.locals=", mbl.locals);
mbl.locals = SPTR_NULL;
putsymlk("gbl.statics=", mbl.statics);
mbl.statics = SPTR_NULL;
putsymlk("gbl.bssvars=", mbl.bssvars);
mbl.bssvars = SPTR_NULL;
putsymlk("gbl.locals=", mbl.locals);
mbl.locals = SPTR_NULL;
putsymlk("gbl.basevars=", mbl.basevars);
mbl.basevars = SPTR_NULL;
putsymlk("gbl.asgnlbls=", mbl.asgnlbls);
mbl.asgnlbls = SPTR_NULL;
putsymlk("gbl.autobj=", mbl.autobj);
mbl.autobj = 0;
putsymlk("gbl.typedescs=", mbl.typedescs);
mbl.typedescs = SPTR_NULL;
putline();
putnsym("gbl.outersub", mbl.outersub);
mbl.outersub = SPTR_NULL;
putline();
putnzint("gbl.vfrets", mbl.vfrets);
mbl.vfrets = 0;
putnzint("gbl.func_count", mbl.func_count);
mbl.func_count = 0;
putnzint("gbl.rutype=", mbl.rutype);
mbl.rutype = (RUTYPE)0; // no 0 value defined
putnzint("gbl.funcline=", mbl.funcline);
mbl.funcline = 0;
putnzint("gbl.threadprivate=", mbl.threadprivate);
mbl.threadprivate = SPTR_NULL;
putnzint("gbl.nofperror=", mbl.nofperror);
mbl.nofperror = 0;
putnzint("gbl.fperror_status=", mbl.fperror_status);
mbl.fperror_status = 0;
putnzint("gbl.entbih", mbl.entbih);
mbl.entbih = 0;
putnzint("gbl.lineno", mbl.lineno);
mbl.lineno = 0;
mbl.multiversion = 0;
mbl.multi_func_count = 0;
mbl.numversions = 0;
putnzint("gbl.pgfi_avail", mbl.pgfi_avail);
mbl.pgfi_avail = 0;
putnzint("gbl.ec_avail", mbl.ec_avail);
mbl.ec_avail = 0;
putnzint("gbl.cuda_constructor", mbl.cuda_constructor);
mbl.cuda_constructor = 0;
putnzint("gbl.cudaemu", mbl.cudaemu);
mbl.cudaemu = 0;
putnzint("gbl.ftn_true", mbl.ftn_true);
mbl.ftn_true = 0;
putnzint("gbl.in_include", mbl.in_include);
mbl.in_include = 0;
putnzint("gbl.denorm", mbl.denorm);
mbl.denorm = 0;
putnzint("gbl.nowarn", mbl.nowarn);
mbl.nowarn = 0;
putnzint("gbl.internal", mbl.internal);
mbl.internal = 0;
putnzisz("gbl.caddr", mbl.caddr);
mbl.caddr = 0;
putnzisz("gbl.locaddr", mbl.locaddr);
mbl.locaddr = 0;
putnzisz("gbl.saddr", mbl.saddr);
mbl.saddr = 0;
putnzisz("gbl.bss_addr", mbl.bss_addr);
mbl.bss_addr = 0;
putnzisz("gbl.paddr", mbl.paddr);
mbl.paddr = 0;
putline();
putnsym("gbl.prvt_sym_sz", (SPTR) mbl.prvt_sym_sz); // ???
mbl.prvt_sym_sz = 0;
putnsym("gbl.stk_sym_sz", (SPTR) mbl.stk_sym_sz); // ???
mbl.stk_sym_sz = 0;
putline();
putnstring("gbl.src_file", mbl.src_file);
mbl.src_file = NULL;
putnstring("gbl.file_name", mbl.file_name);
mbl.file_name = NULL;
putnstring("gbl.curr_file", mbl.curr_file);
mbl.curr_file = NULL;
putnstring("gbl.module", mbl.module);
mbl.module = NULL;
mbl.srcfil = NULL;
mbl.cppfil = NULL;
mbl.dbgfil = NULL;
mbl.ilmfil = NULL;
mbl.objfil = NULL;
mbl.asmfil = NULL;
putline();
ff = (int *)(&mbl);
mblsize = sizeof(mbl) / sizeof(int);
for (i = 0; i < mblsize; ++i) {
if (ff[i] != 0) {
fprintf(dfile, "*** gbl[%d] = %d 0x%x\n", i, ff[i], ff[i]);
}
}
} /* dgbl */
void
dflg(void)
{
FLG mlg;
int *ff;
int i, mlgsize;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
memcpy(&mlg, &flg, sizeof(flg));
putnzint("flg.asmcode", mlg.asmcode);
mlg.asmcode = 0;
putnzint("flg.list", mlg.list);
mlg.list = 0;
putnzint("flg.object", mlg.object);
mlg.object = 0;
putnzint("flg.xref", mlg.xref);
mlg.xref = 0;
putnzint("flg.code", mlg.code);
mlg.code = 0;
putnzint("flg.include", mlg.include);
mlg.include = 0;
putnzint("flg.debug", mlg.debug);
mlg.debug = 0;
putnzint("flg.opt", mlg.opt);
mlg.opt = 0;
putnzint("flg.depchk", mlg.depchk);
mlg.depchk = 0;
putnzint("flg.depwarn", mlg.depwarn);
mlg.depwarn = 0;
putnzint("flg.dclchk", mlg.dclchk);
mlg.dclchk = 0;
putnzint("flg.locchk", mlg.locchk);
mlg.locchk = 0;
putnzint("flg.onetrip", mlg.onetrip);
mlg.onetrip = 0;
putnzint("flg.save", mlg.save);
mlg.save = 0;
putnzint("flg.inform", mlg.inform);
mlg.inform = 0;
putnzINT("flg.xoff", mlg.xoff);
mlg.xoff = 0;
putnzINT("flg.xon", mlg.xon);
mlg.xon = 0;
putnzint("flg.ucase", mlg.ucase);
mlg.ucase = 0;
putnzint("flg.dlines", mlg.dlines);
mlg.dlines = 0;
putnzint("flg.extend_source", mlg.extend_source);
mlg.extend_source = 0;
putnzint("flg.i4", mlg.i4);
mlg.i4 = 0;
putnzint("flg.line", mlg.line);
mlg.line = 0;
putnzint("flg.symbol", mlg.symbol);
mlg.symbol = 0;
putnzint("flg.profile", mlg.profile);
mlg.profile = 0;
putnzint("flg.standard", mlg.standard);
mlg.profile = 0;
putnzint("flg.dalign", mlg.dalign);
mlg.dalign = 0;
putnzint("flg.astype", mlg.astype);
mlg.astype = 0;
putnzint("flg.recursive", mlg.recursive);
mlg.recursive = 0;
putnzint("flg.ieee", mlg.ieee);
mlg.ieee = 0;
putnzint("flg.inliner", mlg.inliner);
mlg.inliner = 0;
putnzint("flg.autoinline", mlg.autoinline);
mlg.autoinline = 0;
putnzint("flg.vect", mlg.vect);
mlg.vect = 0;
putnzint("flg.endian", mlg.endian);
mlg.endian = 0;
putnzint("flg.terse", mlg.terse);
mlg.terse = 0;
putnzint("flg.dollar", mlg.dollar);
mlg.dollar = 0;
putnzint("flg.quad", mlg.quad);
mlg.quad = 0;
putnzint("flg.anno", mlg.anno);
mlg.anno = 0;
putnzint("flg.qa", mlg.qa);
mlg.qa = 0;
putnzint("flg.es", mlg.es);
mlg.es = 0;
putnzint("flg.p", mlg.p);
mlg.p = 0;
putnzint("flg.smp", mlg.smp);
mlg.smp = 0;
putnzint("flg.errorlimit", mlg.errorlimit);
mlg.errorlimit = 0;
putnzint("flg.trans_inv", mlg.trans_inv);
mlg.trans_inv = 0;
putnzint("flg.tpcount", mlg.tpcount);
mlg.tpcount = 0;
if (mlg.stdinc == (char *)0) {
putint("flg.stdinc", 0);
mlg.stdinc = NULL;
} else if (mlg.stdinc == (char *)1) {
putint("flg.stdinc", 1);
mlg.stdinc = NULL;
} else {
putline();
putstring("flg.stdinc", mlg.stdinc);
mlg.stdinc = NULL;
}
putline();
putdefarray("flg.def", mlg.def);
mlg.def = NULL;
putstringarray("flg.idir", mlg.idir);
mlg.idir = NULL;
putline();
putintarray("flg.tpvalue", mlg.tpvalue, sizeof(mlg.tpvalue) / sizeof(int));
putintarray("flg.dbg", mlg.dbg, sizeof(mlg.dbg) / sizeof(int));
putintarray("flg.x", mlg.x, sizeof(mlg.x) / sizeof(int));
putline();
ff = (int *)(&mlg);
mlgsize = sizeof(mlg) / sizeof(int);
for (i = 0; i < mlgsize; ++i) {
if (ff[i] != 0) {
fprintf(dfile, "*** flg[%d] = %d %x\n", i, ff[i], ff[i]);
}
}
} /* dflg */
static bool
simpledtype(DTYPE dtype)
{
if (dtype < DT_NONE || ((int)dtype) >= stb.dt.stg_avail)
return false;
if (DTY(dtype) < TY_NONE || DTY(dtype) > TY_MAX)
return false;
if (dlen(DTY(dtype)) == 1)
return true;
if (DTY(dtype) == TY_PTR)
return true;
return false;
} /* simpledtype */
static int
putenumlist(int member, int len)
{
int r = 0;
if (len < 0)
return 0;
if (SYMLKG(member) > NOSYM) {
r += putenumlist(SYMLKG(member), len);
r += appendstring1(",");
}
if (r >= len)
return r;
r += appendsym1(member);
return r;
} /* putenumlist */
int
putdty(TY_KIND dty)
{
int r;
switch (dty) {
case TY_NONE:
r = appendstring1("none");
break;
case TY_WORD:
r = appendstring1("word");
break;
case TY_DWORD:
r = appendstring1("dword");
break;
case TY_HOLL:
r = appendstring1("hollerith");
break;
case TY_BINT:
r = appendstring1("int*1");
break;
case TY_UBINT:
r = appendstring1("uint*1");
break;
case TY_SINT:
r = appendstring1("short int");
break;
case TY_USINT:
r = appendstring1("unsigned short");
break;
case TY_INT:
r = appendstring1("int");
break;
case TY_UINT:
r = appendstring1("unsigned int");
break;
case TY_INT8:
r = appendstring1("int*8");
break;
case TY_UINT8:
r = appendstring1("unsigned int*8");
break;
case TY_INT128:
r = appendstring1("int128");
break;
case TY_UINT128:
r = appendstring1("uint128");
break;
case TY_128:
r = appendstring1("ty128");
break;
case TY_256:
r = appendstring1("ty256");
break;
case TY_512:
r = appendstring1("ty512");
break;
case TY_REAL:
r = appendstring1("real");
break;
case TY_FLOAT128:
r = appendstring1("float128");
break;
case TY_DBLE:
r = appendstring1("double");
break;
case TY_QUAD:
r = appendstring1("quad");
break;
case TY_CMPLX:
r = appendstring1("complex");
break;
case TY_DCMPLX:
r = appendstring1("double complex");
break;
case TY_CMPLX128:
r = appendstring1("cmplx128");
break;
case TY_BLOG:
r = appendstring1("byte logical");
break;
case TY_SLOG:
r = appendstring1("short logical");
break;
case TY_LOG:
r = appendstring1("logical");
break;
case TY_LOG8:
r = appendstring1("logical*8");
break;
case TY_CHAR:
r = appendstring1("character");
break;
case TY_NCHAR:
r = appendstring1("ncharacter");
break;
case TY_PTR:
r = appendstring1("pointer");
break;
case TY_ARRAY:
r = appendstring1("array");
break;
case TY_STRUCT:
r = appendstring1("struct");
break;
case TY_UNION:
r = appendstring1("union");
break;
case TY_NUMERIC:
r = appendstring1("numeric");
break;
case TY_ANY:
r = appendstring1("any");
break;
case TY_PROC:
r = appendstring1("proc");
break;
case TY_VECT:
r = appendstring1("vect");
break;
case TY_PFUNC:
r = appendstring1("prototype func");
break;
case TY_PARAM:
r = appendstring1("parameter");
break;
default:
// Don't use a case label for TY_FLOAT, because it might alias TY_REAL.
if (dty == TY_FLOAT) {
r = appendstring1("float");
break;
}
r = appendstring1("dty:");
r += appendint1(dty);
r = 0;
break;
}
return r;
} /* putdty */
void
_putdtype(DTYPE dtype, int structdepth)
{
TY_KIND dty;
ADSC *ad;
int numdim;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (dtype >= stb.dt.stg_avail) {
fprintf(dfile, "\ndtype %d out of %d\n", dtype, stb.dt.stg_avail - 1);
return;
}
dty = DTY(dtype);
switch (dty) {
default:
putdty(dty);
break;
case TY_CHAR:
appendstring1("char*");
appendint1(DTyCharLength(dtype));
break;
case TY_ARRAY:
_putdtype(DTySeqTyElement(dtype), structdepth);
ad = AD_DPTR(dtype);
numdim = AD_NUMDIM(ad);
appendstring1("(");
if (numdim >= 1 && numdim <= 7) {
int i;
for (i = 0; i < numdim; ++i) {
if (i)
appendstring1(",");
appendsym1(AD_LWBD(ad, i));
appendstring1(":");
appendsym1(AD_UPBD(ad, i));
}
}
appendstring1(")");
break;
case TY_PTR:
if (simpledtype(DTySeqTyElement(dtype))) {
appendstring1("*");
_putdtype(DTySeqTyElement(dtype), structdepth);
} else {
appendstring1("*(");
_putdtype(DTySeqTyElement(dtype), structdepth);
appendstring1(")");
}
break;
case TY_PARAM:
appendstring1("(");
_putdtype(DTyArgType(dtype), structdepth);
if (DTyArgSym(dtype)) {
appendstring1(" ");
appendsym1(DTyArgSym(dtype));
}
if (DTyArgNext(dtype)) {
appendstring1(", next=");
appendint1(DTyArgNext(dtype));
}
appendstring1(")");
break;
case TY_STRUCT:
case TY_UNION:
if (dty == TY_STRUCT)
appendstring1("struct");
if (dty == TY_UNION)
appendstring1("union");
DTySet(dtype, -dty);
if (DTyAlgTyTag(dtype)) {
appendstring1(" ");
appendsym1(DTyAlgTyTag(dtype));
}
if (DTyAlgTyTag(dtype) == SPTR_NULL || structdepth == 0) {
appendstring1("{");
if (DTyAlgTyMember(dtype)) {
int member;
for (member = DTyAlgTyMember(dtype); member > NOSYM && member < stb.stg_avail;) {
_putdtype(DTYPEG(member), structdepth + 1);
appendstring1(" ");
appendsym1(member);
member = SYMLKG(member);
appendstring1(";");
}
}
appendstring1("}");
}
DTySet(dtype, dty);
break;
case -TY_STRUCT:
case -TY_UNION:
if (dty == -TY_STRUCT)
appendstring1("struct");
if (dty == -TY_UNION)
appendstring1("union");
if (DTyAlgTyTagNeg(dtype)) {
appendstring1(" ");
appendsym1(DTyAlgTyTagNeg(dtype));
} else {
appendstring1(" ");
appendint1(dtype);
}
break;
}
} /* _putdtype */
void
putdtype(DTYPE dtype)
{
_putdtype(dtype, 0);
} /* putdtype */
static int
putdtypex(DTYPE dtype, int len)
{
TY_KIND dty;
int r = 0;
ADSC *ad;
int numdim;
if (len < 0)
return 0;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (dtype >= stb.dt.stg_avail) {
fprintf(dfile, "\ndtype %d out of %d\n", dtype, stb.dt.stg_avail - 1);
return 0;
}
dty = DTY(dtype);
switch (dty) {
default:
r += putdty(dty);
break;
case TY_CHAR:
r += appendstring1("char*");
r += appendint1(DTyCharLength(dtype));
break;
case TY_ARRAY:
r += putdtypex(DTySeqTyElement(dtype), len - r);
ad = AD_DPTR(dtype);
numdim = AD_NUMDIM(ad);
r += appendstring1("(");
if (numdim >= 1 && numdim <= 7) {
int i;
for (i = 0; i < numdim && r < len; ++i) {
if (i)
r += appendstring1(",");
r += appendsym1(AD_LWBD(ad, i));
r += appendstring1(":");
r += appendsym1(AD_UPBD(ad, i));
}
}
r += appendstring1(")");
break;
case TY_PTR:
if (simpledtype(DTySeqTyElement(dtype))) {
r += appendstring1("*");
r += putdtypex(DTySeqTyElement(dtype), len - 4);
} else {
r += appendstring1("*(");
r += putdtypex(DTySeqTyElement(dtype), len - 4);
r += appendstring1(")");
}
break;
case TY_PARAM:
r += appendstring1("(");
r += putdtypex(DTyArgType(dtype), len - 4);
if (DTyArgSym(dtype)) {
r += appendstring1(" ");
r += appendsym1(DTyArgSym(dtype));
}
if (DTyArgNext(dtype)) {
r += appendstring1(", next=");
r += appendint1(DTyArgNext(dtype));
}
r += appendstring1(")");
break;
case TY_STRUCT:
case TY_UNION:
if (dty == TY_STRUCT)
r += appendstring1("struct");
if (dty == TY_UNION)
r += appendstring1("union");
DTySet(dtype, -dty);
if (DTyAlgTyTag(dtype)) {
r += appendstring1(" ");
r += appendsym1(DTyAlgTyTag(dtype));
}
r += appendstring1("{");
if (DTyAlgTyMember(dtype)) {
int member;
for (member = DTyAlgTyMember(dtype);
member > NOSYM && member < stb.stg_avail && r < len;) {
r += putdtypex(DTYPEG(member), len - 4);
r += appendstring1(" ");
r += appendsym1(member);
member = SYMLKG(member);
r += appendstring1(";");
}
}
r += appendstring1("}");
DTySet(dtype, dty);
break;
case -TY_STRUCT:
case -TY_UNION:
if (dty == -TY_STRUCT)
r += appendstring1("struct");
if (dty == -TY_UNION)
r += appendstring1("union");
if (DTyAlgTyTagNeg(dtype)) {
r += appendstring1(" ");
r += appendsym1(DTyAlgTyTagNeg(dtype));
} else {
r += appendstring1(" ");
r += appendint1(dtype);
}
break;
}
return r;
} /* putdtypex */
void
dumpdtype(DTYPE dtype)
{
ADSC *ad;
int numdim;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n");
putint("dtype", dtype);
if (dtype <= 0 || dtype >= stb.dt.stg_avail) {
fprintf(dfile, "\ndtype %d out of %d\n", dtype, stb.dt.stg_avail - 1);
return;
}
appendstring1(" ");
putdty(DTY(dtype));
switch (DTY(dtype)) {
case TY_ARRAY:
putint("dtype", DTySeqTyElement(dtype));
ad = AD_DPTR(dtype);
numdim = AD_NUMDIM(ad);
putint("numdim", numdim);
putnzint("scheck", AD_SCHECK(ad));
putnsym("zbase", (SPTR) AD_ZBASE(ad)); // ???
putnsym("numelm", AD_NUMELM(ad));
putnsym("sdsc", AD_SDSC(ad));
if (numdim >= 1 && numdim <= 7) {
int i;
for (i = 0; i < numdim; ++i) {
putline();
putint("dim", i);
putint("mlpyr", AD_MLPYR(ad, i));
putint("lwbd", AD_LWBD(ad, i));
putint("upbd", AD_UPBD(ad, i));
}
}
break;
case TY_CHAR:
putint("len", DTyCharLength(dtype));
break;
case TY_PARAM:
putint("dtype", DTyArgType(dtype));
putnsym("sptr", DTyArgSym(dtype));
putint("next", DTyArgNext(dtype));
break;
case TY_PTR:
putint("dtype", DTySeqTyElement(dtype));
break;
case TY_STRUCT:
case TY_UNION:
putsym("member", DTyAlgTyMember(dtype));
putint("size", DTyAlgTySize(dtype));
putnsym("tag", DTyAlgTyTag(dtype));
putint("align", DTyAlgTyAlign(dtype));
break;
case TY_VECT:
fprintf(dfile, "<%lu x ", DTyVecLength(dtype));
putdtype(DTySeqTyElement(dtype));
fputc('>', dfile);
default:
/* simple datatypes, just the one line of info */
putline();
return;
}
putline();
putdtype(dtype);
putline();
} /* dumpdtype */
void
ddtype(DTYPE dtype)
{
dumpdtype(dtype);
} /* ddtype */
void
dumpdtypes(void)
{
DTYPE dtype;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** DATATYPE TABLE **********\n");
for (dtype = (DTYPE)1; ((int)dtype) < stb.dt.stg_avail; dtype += dlen(DTY(dtype))) {
dumpdtype(dtype);
}
fprintf(dfile, "\n");
} /* dumpdtypes */
void
dumpnewdtypes(int olddtavail)
{
DTYPE dtype;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** DATATYPE TABLE **********\n");
for (dtype = (DTYPE)olddtavail; ((int)dtype) < stb.dt.stg_avail; dtype += dlen(DTY(dtype))) {
dumpdtype(dtype);
}
fprintf(dfile, "\n");
} /* dumpnewdtypes */
void
ddtypes(void)
{
dumpdtypes();
} /* ddtypes */
static char prefix[1500];
static char *
smsz(int m)
{
const char *msz = NULL;
static char B[15];
switch (m) {
case MSZ_SBYTE:
msz = "sb";
break;
case MSZ_SHWORD:
msz = "sh";
break;
case MSZ_WORD:
msz = "wd";
break;
case MSZ_SLWORD:
msz = "sl";
break;
case MSZ_BYTE:
msz = "bt";
break;
case MSZ_UHWORD:
msz = "uh";
break;
case MSZ_PTR:
msz = "pt";
break;
case MSZ_ULWORD:
msz = "ul";
break;
case MSZ_F4:
msz = "fl";
break;
case MSZ_F8:
msz = "db";
break;
#ifdef MSZ_I8
case MSZ_I8:
msz = "i8";
break;
#endif
#ifdef MSZ_F10
case MSZ_F10:
msz = "ep";
break;
#endif
default:
break;
}
if (msz ) {
snprintf(B, 15, "%s", msz);
} else {
snprintf(B, 15, "%d", m);
}
return B;
} /* smsz */
char* scond(int);
static void
putstc(ILI_OP opc, int opnum, int opnd)
{
switch (ilstckind(opc, opnum)) {
case 1:
putstring("cond", scond(opnd));
break;
case 2:
putstring("msz", smsz(opnd));
break;
default:
putint("stc", opnd);
break;
}
} /* putstc */
#define OT_UNARY 1
#define OT_BINARY 2
#define OT_LEAF 3
static int
optype(int opc)
{
switch (opc) {
case IL_INEG:
case IL_UINEG:
case IL_KNEG:
case IL_UKNEG:
case IL_SCMPLXNEG:
case IL_DCMPLXNEG:
case IL_FNEG:
case IL_DNEG:
return OT_UNARY;
case IL_LD:
case IL_LDKR:
case IL_LDSP:
case IL_LDDP:
case IL_LDA:
case IL_ICON:
case IL_KCON:
case IL_DCON:
case IL_FCON:
case IL_ACON:
return OT_LEAF;
}
return OT_BINARY;
} /* optype */
static void _printili(int i);
static void
pnme(int n, int ili)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (n < 0 || n >= nmeb.stg_avail) {
fprintf(dfile, "nme:%d/%d", n, nmeb.stg_avail);
return;
}
switch (NME_TYPE(n)) {
case NT_VAR:
appendstring1(printname(NME_SYM(n)));
break;
case NT_MEM:
if (NME_NM(n)) {
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1("(");
pnme(NME_NM(n), ili);
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1(")");
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == 0) {
appendstring1(".real");
} else if (NME_SYM(n) == 1) {
appendstring1(".imag");
} else {
appendstring1(".");
appendstring1(printname(NME_SYM(n)));
}
break;
case NT_ARR:
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1("(");
pnme(NME_NM(n), ili);
if (NME_TYPE(NME_NM(n)) == NT_IND)
appendstring1(")");
if (NME_SYM(n) == NME_NULL) {
appendstring1("[]");
} else if (NME_SYM(n) == 0) {
appendstring1("[");
appendint1(NME_CNST(n));
appendstring1("]");
} else {
appendstring1("[?]");
}
break;
case NT_IND:
appendstring1("*(");
pnme(NME_NM(n), ili);
if (NME_SYM(n) == NME_NULL) {
} else if (NME_SYM(n) == 0) {
if (NME_CNST(n)) {
appendstring1("+");
appendint1(NME_CNST(n));
}
} else {
appendstring1("<");
_printili(ili);
appendstring1(">");
}
appendstring1(")");
break;
case NT_SAFE:
appendstring1("safe(");
pnme(NME_NM(n), ili);
appendstring1(")");
break;
case NT_UNK:
if (NME_SYM(n) == 0) {
appendstring1("unknown");
} else if (NME_SYM(n) == 1) {
appendstring1("volatile");
} else {
appendstring1("unknown:");
appendint1(NME_SYM(n));
}
break;
default:
appendstring1("nme(");
appendint1(n);
appendstring1(":");
appendint1(NME_TYPE(n));
appendstring1(")");
break;
}
} /* pnme */
static void
appendtarget(int sptr)
{
if (sptr > 0 && sptr < stb.stg_avail) {
appendstring1("[bih");
appendint1(ILIBLKG(sptr));
appendstring1("]");
}
} /* appendtarget */
static void
_put_device_type(int d)
{
static const char *names[] = {"*", "host", "nvidia", "?",
"?", "opencl", NULL};
int dd = 1, i, any = 0;
if (!d)
return;
appendstring1(" device_type(");
for (i = 0; names[i]; ++i) {
if (d & dd) {
if (any)
appendstring1(",");
appendstring1(names[i]);
++any;
}
dd <<= 1;
}
if (!any)
appendhex1(d);
appendstring1(")");
} /* _put_device_type */
static void
_printili(int i)
{
int n, k, j, noprs;
ILI_OP opc;
int o, typ;
const char *opval;
static const char *ccval[] = {"??", "==", "!=", "<", ">=", "<=", ">",
"!==", "!!=", "!<", "!>=", "!<=", "!>"};
static const char *ccvalzero[] = {"??", "==0", "!=0", "<0", ">=0",
"<=0", ">0", "!==0", "!!=0", "!<0",
"!>=0", "!<=0", "!>0"};
#define NONE 0
#define UNOP 1
#define postUNOP 2
#define BINOP 3
#define INTRINSIC 4
#define MVREG 5
#define DFREG 6
#define PSCOMM 7
#define ENC_N_OP 8
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (g_dout && (i <= 0 || i >= ilib.stg_size)) {
fprintf(dfile, "ili %d out of %d", i, ilib.stg_size - 1);
return;
}
opc = ILI_OPC(i);
if (opc <= 0 || opc >= N_ILI) {
appendstring1("illegalopc(");
appendint1(opc);
appendstring1(")");
return;
}
noprs = ilis[opc].oprs;
typ = NONE;
switch (opc) {
case IL_IADD:
case IL_KADD:
case IL_UKADD:
case IL_FADD:
case IL_DADD:
case IL_UIADD:
case IL_AADD:
opval = "+";
typ = BINOP;
break;
case IL_ISUB:
case IL_KSUB:
case IL_UKSUB:
case IL_FSUB:
case IL_DSUB:
case IL_UISUB:
case IL_ASUB:
opval = "-";
typ = BINOP;
break;
case IL_IMUL:
case IL_KMUL:
case IL_UKMUL:
case IL_FMUL:
case IL_DMUL:
case IL_UIMUL:
opval = "*";
typ = BINOP;
break;
case IL_DDIV:
case IL_KDIV:
case IL_UKDIV:
case IL_FDIV:
case IL_IDIV:
opval = "/";
typ = BINOP;
break;
case IL_KAND:
case IL_AND:
opval = "&";
typ = BINOP;
break;
case IL_KOR:
case IL_OR:
opval = "|";
typ = BINOP;
break;
case IL_KXOR:
case IL_XOR:
opval = "^";
typ = BINOP;
break;
case IL_KMOD:
case IL_KUMOD:
case IL_MOD:
case IL_UIMOD:
opval = "%";
typ = BINOP;
break;
case IL_LSHIFT:
case IL_ULSHIFT:
opval = "<<";
typ = BINOP;
break;
case IL_RSHIFT:
case IL_URSHIFT:
opval = ">>";
typ = BINOP;
break;
case IL_ARSHIFT:
case IL_KARSHIFT:
opval = "a>>";
typ = BINOP;
break;
case IL_KCMP:
case IL_UKCMP:
case IL_ICMP:
case IL_FCMP:
case IL_SCMPLXCMP:
case IL_DCMPLXCMP:
case IL_DCMP:
case IL_ACMP:
case IL_UICMP:
opval = ccval[ILI_OPND(i, 3)];
typ = BINOP;
break;
case IL_INEG:
case IL_KNEG:
case IL_UKNEG:
case IL_DNEG:
case IL_UINEG:
case IL_FNEG:
case IL_SCMPLXNEG:
case IL_DCMPLXNEG:
opval = "-";
typ = UNOP;
break;
case IL_NOT:
case IL_UNOT:
case IL_KNOT:
case IL_UKNOT:
opval = "!";
typ = UNOP;
break;
case IL_ICMPZ:
case IL_KCMPZ:
case IL_UKCMPZ:
case IL_FCMPZ:
case IL_DCMPZ:
case IL_ACMPZ:
case IL_UICMPZ:
opval = ccvalzero[ILI_OPND(i, 2)];
typ = postUNOP;
break;
case IL_FMAX:
case IL_DMAX:
case IL_KMAX:
case IL_UKMAX:
case IL_IMAX:
n = 2;
opval = "max";
typ = INTRINSIC;
break;
case IL_FMIN:
case IL_DMIN:
case IL_KMIN:
case IL_UKMIN:
case IL_IMIN:
n = 2;
opval = "min";
typ = INTRINSIC;
break;
case IL_DBLE:
n = 1;
opval = "dble";
typ = INTRINSIC;
break;
case IL_SNGL:
n = 1;
opval = "sngl";
typ = INTRINSIC;
break;
case IL_FIX:
case IL_FIXK:
case IL_FIXUK:
n = 1;
opval = "fix";
typ = INTRINSIC;
break;
case IL_DFIXK:
case IL_DFIXUK:
n = 1;
opval = "dfix";
typ = INTRINSIC;
break;
case IL_UFIX:
n = 1;
opval = "fix";
typ = INTRINSIC;
break;
case IL_DFIX:
case IL_DFIXU:
n = 1;
opval = "dfix";
typ = INTRINSIC;
break;
case IL_FLOAT:
case IL_FLOATU:
n = 1;
opval = "float";
typ = INTRINSIC;
break;
case IL_DFLOAT:
case IL_DFLOATU:
n = 1;
opval = "dfloat";
typ = INTRINSIC;
break;
case IL_DNEWT:
case IL_FNEWT:
n = 1;
opval = "recip";
typ = INTRINSIC;
break;
case IL_DABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_FABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_KABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_IABS:
n = 1;
opval = "abs";
typ = INTRINSIC;
break;
case IL_FSQRT:
n = 1;
opval = "sqrt";
typ = INTRINSIC;
break;
case IL_DSQRT:
n = 1;
opval = "dsqrt";
typ = INTRINSIC;
break;
case IL_KCJMP:
case IL_UKCJMP:
case IL_ICJMP:
case IL_FCJMP:
case IL_DCJMP:
case IL_ACJMP:
case IL_UICJMP:
_printili(ILI_OPND(i, 1));
appendstring1(" ");
appendstring1(ccval[ILI_OPND(i, 3)]);
appendstring1(" ");
_printili(ILI_OPND(i, 2));
appendstring1(" goto ");
if (full) {
appendint1(ILI_OPND(i, 4));
appendstring1("=");
}
appendsym1(ILI_OPND(i, 4));
appendtarget(ILI_OPND(i, 4));
break;
case IL_KCJMPZ:
case IL_UKCJMPZ:
case IL_ICJMPZ:
case IL_FCJMPZ:
case IL_DCJMPZ:
case IL_ACJMPZ:
case IL_UICJMPZ:
_printili(ILI_OPND(i, 1));
appendstring1(" ");
appendstring1(ccval[ILI_OPND(i, 2)]);
appendstring1(" 0 ");
appendstring1(" goto ");
if (full) {
appendint1(ILI_OPND(i, 3));
appendstring1("=");
}
appendsym1(ILI_OPND(i, 3));
appendtarget(ILI_OPND(i, 3));
break;
case IL_JMP:
appendstring1("goto ");
if (full) {
appendint1(ILI_OPND(i, 1));
appendstring1("=");
}
appendsym1(ILI_OPND(i, 1));
appendtarget(ILI_OPND(i, 1));
break;
case IL_DFRKR:
case IL_DFRIR:
case IL_DFRSP:
case IL_DFRDP:
case IL_DFRCS:
case IL_DFRCD:
case IL_DFRAR:
_printili(ILI_OPND(i, 1));
break;
case IL_QJSR:
case IL_JSR:
appendstring1(printname(ILI_OPND(i, 1)));
appendstring1("(");
j = ILI_OPND(i, 2);
k = 0;
while (ILI_OPC(j) != 0) {
if (k)
appendstring1(", ");
switch (ILI_OPC(j)) {
case IL_DAKR:
case IL_DAAR:
case IL_DADP:
#ifdef IL_DA128
case IL_DA128:
#endif
#ifdef IL_DA256
case IL_DA256:
#endif
case IL_DASP:
case IL_DAIR:
_printili(ILI_OPND(j, 1));
j = ILI_OPND(j, 3);
break;
case IL_ARGKR:
case IL_ARGIR:
case IL_ARGSP:
case IL_ARGDP:
case IL_ARGAR:
_printili(ILI_OPND(j, 1));
j = ILI_OPND(j, 2);
break;
#ifdef IL_ARGRSRV
case IL_ARGRSRV:
appendstring1("rsrv(");
appendint1(ILI_OPND(j, 1));
appendstring1(")");
j = ILI_OPND(j, 2);
break;
#endif
default:
goto done;
}
++k;
}
done:
appendstring1(")");
break;
case IL_MVKR:
opval = "MVKR";
appendstring1(opval);
appendstring1("(");
appendint1(KR_MSH(ILI_OPND(i, 2)));
appendstring1(",");
appendint1(KR_LSH(ILI_OPND(i, 2)));
appendstring1(")");
_printili(ILI_OPND(i, 1));
break;
case IL_MVIR:
opval = "MVIR";
typ = MVREG;
break;
case IL_MVSP:
opval = "MVSP";
typ = MVREG;
break;
case IL_MVDP:
opval = "MVDP";
typ = MVREG;
break;
case IL_MVAR:
opval = "MVAR";
typ = MVREG;
break;
case IL_KRDF:
opval = "KRDF";
appendstring1(opval);
appendstring1("(");
appendint1(KR_MSH(ILI_OPND(i, 1)));
appendstring1(",");
appendint1(KR_LSH(ILI_OPND(i, 1)));
appendstring1(")");
break;
case IL_IRDF:
opval = "IRDF";
typ = DFREG;
break;
case IL_SPDF:
opval = "SPDF";
typ = DFREG;
break;
case IL_DPDF:
opval = "DPDF";
typ = DFREG;
break;
case IL_ARDF:
opval = "ARDF";
typ = DFREG;
break;
case IL_IAMV:
case IL_AIMV:
case IL_KAMV:
case IL_AKMV:
_printili(ILI_OPND(i, 1));
break;
case IL_KIMV:
appendstring1("_K2I(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
break;
case IL_IKMV:
appendstring1("_I2K(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
break;
case IL_UIKMV:
appendstring1("_UI2K(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
break;
case IL_CSE:
case IL_CSEKR:
case IL_CSEIR:
case IL_CSESP:
case IL_CSEDP:
case IL_CSEAR:
case IL_CSECS:
case IL_CSECD:
#ifdef LONG_DOUBLE_FLOAT128
case IL_FLOAT128CSE:
#endif
appendstring1("#<");
_printili(ILI_OPND(i, 1));
appendstring1(">#");
break;
case IL_FREEKR:
opval = "FREEKR";
typ = PSCOMM;
break;
case IL_FREEDP:
opval = "FREEDP";
typ = PSCOMM;
break;
case IL_FREECS:
opval = "FREECS";
typ = PSCOMM;
break;
case IL_FREECD:
opval = "FREECD";
typ = PSCOMM;
break;
case IL_FREESP:
opval = "FREESP";
typ = PSCOMM;
break;
case IL_FREEAR:
opval = "FREEAR";
typ = PSCOMM;
break;
case IL_FREEIR:
opval = "FREEIR";
typ = PSCOMM;
break;
#ifdef LONG_DOUBLE_FLOAT128
case IL_FLOAT128FREE:
opval = "FLOAT128FREE";
typ = PSCOMM;
break;
#endif
case IL_KCON:
case IL_ICON:
case IL_FCON:
case IL_DCON:
appendstring1(printname(ILI_OPND(i, 1)));
break;
case IL_ACON:
j = ILI_OPND(i, 1);
appendstring1("&");
if (ACONOFFG(j)) {
appendstring1("(");
}
if (CONVAL1G(j)) {
appendstring1(printname(CONVAL1G(j)));
if (CONVAL1G(j) > NOSYM && CONVAL1G(j) < stb.stg_avail &&
SCG(CONVAL1G(j)) == SC_PRIVATE)
appendstring1("'");
} else {
appendint1(CONVAL1G(j));
}
if (ACONOFFG(j) > 0) {
appendstring1("+");
appendbigint(ACONOFFG(j));
appendstring1(")");
} else if (ACONOFFG(j) < 0) {
appendstring1("-");
appendbigint(-ACONOFFG(j));
appendstring1(")");
}
break;
case IL_LD:
case IL_LDSP:
case IL_LDDP:
case IL_LDKR:
case IL_LDA:
_printnme(ILI_OPND(i, 2));
if (DBGBIT(10, 4096)) {
appendstring1("<*");
_printili(ILI_OPND(i, 1));
appendstring1("*>");
}
break;
case IL_STKR:
case IL_ST:
case IL_STDP:
case IL_STSP:
case IL_SSTS_SCALAR:
case IL_DSTS_SCALAR:
case IL_STA:
_printnme(ILI_OPND(i, 3));
if (DBGBIT(10, 4096)) {
appendstring1("<*");
_printili(ILI_OPND(i, 2));
appendstring1("*>");
}
appendstring1(" = ");
_printili(ILI_OPND(i, 1));
appendstring1(";");
break;
case IL_LABEL: {
int label = ILI_OPND(i, 1);
appendstring1("label ");
appendsym1(label);
if (BEGINSCOPEG(label)) {
appendstring1(" beginscope(");
appendsym1(ENCLFUNCG(label));
appendstring1(")");
}
if (ENDSCOPEG(label)) {
appendstring1(" endscope(");
appendsym1(ENCLFUNCG(label));
appendstring1(")");
}
break;
}
case IL_NULL:
if (noprs == 1 && ILI_OPND(i, 1) == 0) {
/* expected case, print nothing else */
appendstring1("NULL");
break;
}
/* fall through */
default:
appendstring1(ilis[opc].name);
if (noprs) {
int j;
appendstring1("(");
for (j = 1; j <= noprs; ++j) {
if (j > 1)
appendstring1(",");
switch (IL_OPRFLAG(opc, j)) {
#ifdef ILIO_NULL
case ILIO_NULL:
appendstring1("null=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_SYM
case ILIO_SYM:
if (full) {
appendint1(ILI_OPND(i, j));
appendstring1("=");
}
appendsym1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_OFF
case ILIO_OFF:
appendstring1("off=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_NME
case ILIO_NME:
appendstring1("nme=");
if (full) {
appendint1(ILI_OPND(i, j));
appendstring1("=");
}
_printnme(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_IR
case ILIO_IR:
appendstring1("ir=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_SP
case ILIO_SP:
appendstring1("sp=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_DR
case ILIO_DR:
appendstring1("dr=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_AR
case ILIO_AR:
appendstring1("ar=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_KR
case ILIO_KR:
appendstring1("kr=");
appendint1(ILI_OPND(i, j));
break;
#endif
#ifdef ILIO_XMM
case ILIO_XMM:
/*
bits 0:23 of the operand represent the virtual register
number, and the value of the top byte is 1 for 'ymm'
register, otherwise for 'xmm' register.
*/
if (ILI_OPND(i, j) >> 24 == 1)
appendstring1("ymm=");
else
appendstring1("xmm=");
appendint1(ILI_OPND(i, j) & 0xFFFFFF);
break;
#endif
#ifdef ILIO_LNK
case ILIO_LNK:
#endif
#ifdef ILIO_IRLNK
case ILIO_IRLNK:
#endif
#ifdef ILIO_SPLNK
case ILIO_SPLNK:
#endif
#ifdef ILIO_DPLNK
case ILIO_DPLNK:
#endif
#ifdef ILIO_ARLNK
case ILIO_ARLNK:
#endif
#ifdef ILIO_KRLNK
case ILIO_KRLNK:
#endif
#ifdef ILIO_CSLNK
case ILIO_CSLNK:
#endif
#ifdef ILIO_CDLNK
case ILIO_CDLNK:
#endif
#ifdef ILIO_QPLNK
case ILIO_QPLNK:
#endif
#ifdef ILIO_CQLNK
case ILIO_CQLNK:
#endif
#ifdef ILIO_128LNK
case ILIO_128LNK:
#endif
#ifdef ILIO_256LNK
case ILIO_256LNK:
#endif
#ifdef ILIO_512LNK
case ILIO_512LNK:
#endif
#ifdef ILIO_X87LNK
case ILIO_X87LNK:
#endif
#ifdef ILIO_DOUBLEDOUBLELNK
case ILIO_DOUBLEDOUBLELNK:
#endif
_printili(ILI_OPND(i, j));
break;
default:
appendstring1("op=");
appendint1(ILI_OPND(i, j));
break;
}
}
appendstring1(")");
}
break;
}
switch (typ) {
case BINOP:
o = optype(ILI_OPC(ILI_OPND(i, 1)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 1));
}
appendstring1(opval);
o = optype(ILI_OPC(ILI_OPND(i, 2)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 2));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 2));
}
break;
case UNOP:
appendstring1(opval);
o = optype(ILI_OPC(ILI_OPND(i, 1)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 1));
}
break;
case postUNOP:
o = optype(ILI_OPC(ILI_OPND(i, 1)));
if (o != OT_UNARY && o != OT_LEAF) {
appendstring1("(");
_printili(ILI_OPND(i, 1));
appendstring1(")");
} else {
_printili(ILI_OPND(i, 1));
}
appendstring1(opval);
break;
case INTRINSIC:
appendstring1(opval);
appendstring1("(");
for (j = 1; j <= n; ++j) {
_printili(ILI_OPND(i, j));
if (j != n)
appendstring1(",");
}
appendstring1(")");
break;
case MVREG:
appendstring1(opval);
appendstring1(".");
appendint1(ILI_OPND(i, 2));
appendstring1("=");
_printili(ILI_OPND(i, 1));
break;
case DFREG:
appendstring1(opval);
appendstring1("(");
appendint1(ILI_OPND(i, 1));
appendstring1(")");
break;
case PSCOMM:
appendstring1(opval);
appendstring1(" = ");
_printili(ILI_OPND(i, 1));
appendstring1(";");
break;
case ENC_N_OP:
appendstring1(opval);
appendstring1("#0x");
appendhex1(ILI_OPND(i, n + 1));
appendstring1("(");
for (j = 1; j <= n; ++j) {
_printili(ILI_OPND(i, j));
if (j != n)
appendstring1(",");
}
appendstring1(")");
break;
default:
break;
}
} /* _printili */
/*
* call _printili with linelen = 0, so no prefix blanks are added
*/
void
printili(int i)
{
linelen = 0;
_printili(i);
linelen = 0;
} /* printili */
/**
* call _printilt with linelen = 0, so no prefix blanks are added
*/
void
printilt(int i)
{
linelen = 0;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
snprintf(BUF, BUFSIZE, "ilt:%-4d", i);
putit();
if (iltb.stg_base && i > 0 && i < iltb.stg_size && ILT_ILIP(i)) {
snprintf(BUF, BUFSIZE, "lineno:%-4d ili:%-4d ", ILT_LINENO(i),
ILT_ILIP(i));
putit();
_printili(ILT_ILIP(i));
}
putline();
linelen = 0;
} /* printilt */
void
putili(const char *name, int ilix)
{
if (ilix <= 0)
return;
if (full) {
snprintf(BUF, BUFSIZE, "%s:%d=", name, ilix);
} else {
snprintf(BUF, BUFSIZE, "%s=", name);
}
putit();
_printili(ilix);
} /* putili */
void
printblock(int block)
{
int ilt;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
db(block);
for (ilt = BIH_ILTFIRST(block); ilt; ilt = ILT_NEXT(ilt)) {
if (full) {
snprintf(BUF, BUFSIZE, "ilt:%d", ilt);
putit();
}
if (ilt >= 0 && ilt < iltb.stg_size) {
putint("lineno", ILT_LINENO(ilt));
putili("ili", ILT_ILIP(ilt));
putline();
}
}
} /* printblock */
void
printblockline(int block)
{
int ilt;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
db(block);
for (ilt = BIH_ILTFIRST(block); ilt; ilt = ILT_NEXT(ilt)) {
if (full) {
snprintf(BUF, BUFSIZE, "ilt:%d", ilt);
putit();
}
if (ilt >= 0 && ilt < iltb.stg_size) {
putint("lineno", ILT_LINENO(ilt));
putint("findex", ILT_FINDEX(ilt));
putili("ili", ILT_ILIP(ilt));
putline();
}
}
} /* printblockline */
void
printblocks(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
if (full) {
fprintf(dfile, "func_count=%d, curr_func=%d=%s\n", gbl.func_count,
GBL_CURRFUNC, GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "");
} else {
fprintf(dfile, "func_count=%d, curr_func=%s\n", gbl.func_count,
GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "");
}
#ifdef CUDAG
if (GBL_CURRFUNC > 0)
putcuda("cuda", CUDAG(GBL_CURRFUNC));
fprintf(dfile, "\n");
#endif
block = BIHNUMG(GBL_CURRFUNC);
for (; block; block = BIH_NEXT(block)) {
printblock(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* printblocks */
void
printblockt(int firstblock, int lastblock)
{
int block, limit = 1000, b;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
fprintf(dfile, "func_count=%d, curr_func=%d=%s, blocks=%d:%d\n",
gbl.func_count, GBL_CURRFUNC,
GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "", firstblock, lastblock);
block = BIHNUMG(GBL_CURRFUNC);
for (; block; block = BIH_NEXT(block)) {
if (block == firstblock)
break;
}
if (block != firstblock) {
fprintf(dfile, "block:%d not found\n", firstblock);
for (b = 0, block = firstblock; block && b < limit;
block = BIH_NEXT(block), ++b) {
printblock(block);
if (BIH_LAST(block) || block == lastblock)
break;
fprintf(dfile, "\n");
}
if (block != lastblock)
fprintf(dfile, "block:%d not found\n", lastblock);
} else {
for (b = 0; block && b < limit; block = BIH_NEXT(block), ++b) {
printblock(block);
if (BIH_LAST(block) || block == lastblock)
break;
fprintf(dfile, "\n");
}
if (block != lastblock)
fprintf(dfile, "block:%d not found\n", lastblock);
}
} /* printblockt */
void
printblocktt(int firstblock, int lastblock)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
fprintf(dfile, "func_count=%d, curr_func=%d=%s, blocks=%d:%d\n",
gbl.func_count, GBL_CURRFUNC,
GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "", firstblock, lastblock);
for (block = firstblock; block; block = BIH_NEXT(block)) {
printblock(block);
if (BIH_LAST(block) || block == lastblock)
break;
fprintf(dfile, "\n");
}
if (block != lastblock) {
fprintf(dfile, "block:%d not found\n", lastblock);
}
} /* printblocktt */
void
printblocksline(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
fprintf(dfile, "func_count=%d, curr_func=%d=%s\n", gbl.func_count,
GBL_CURRFUNC, GBL_CURRFUNC > 0 ? SYMNAME(GBL_CURRFUNC) : "");
block = BIHNUMG(GBL_CURRFUNC);
for (; block; block = BIH_NEXT(block)) {
printblockline(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* printblocksline */
void
dili(int ilix)
{
ILI_OP opc;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (full)
putint("ili", ilix);
if (ilix <= 0 || ilix >= ilib.stg_size) {
putstring1("out of bounds");
putline();
return;
}
opc = ILI_OPC(ilix);
if (opc <= 0 || opc >= N_ILI) {
putint("illegalopc", opc);
} else {
int noprs, j;
static const char *iltypes[] = {"(null)", "(arth)", "(branch)", "(cons)",
"(define)", "(load)", "(move)", "(other)",
"(proc)", "(store)"};
putstring("opc", IL_NAME(opc));
putval1(IL_TYPE(opc), iltypes, SIZEOF(iltypes));
noprs = IL_OPRS(opc);
for (j = 1; j <= noprs; ++j) {
int opnd;
opnd = ILI_OPND(ilix, j);
switch (IL_OPRFLAG(opc, j)) {
case ILIO_SYM:
putsym("sym", (SPTR)opnd);
if (opc == IL_ACON) {
putnsym("base", SymConval1((SPTR)opnd));
putnzbigint("offset", ACONOFFG(opnd));
}
break;
case ILIO_OFF:
putsym("sym", (SPTR)opnd);
break;
case ILIO_NME:
putnme("nme", opnd);
break;
case ILIO_STC:
putstc(opc, j, opnd);
break;
case ILIO_LNK:
if (full) {
putint("lnk", opnd);
} else {
putstring1("lnk");
}
break;
case ILIO_IRLNK:
if (full) {
putint("irlnk", opnd);
} else {
putstring1("irlnk");
}
break;
case ILIO_KRLNK:
if (full) {
putint("krlnk", opnd);
} else {
putstring1("krlnk");
}
break;
case ILIO_ARLNK:
if (full) {
putint("arlnk", opnd);
} else {
putstring1("arlnk");
}
break;
case ILIO_SPLNK:
if (full) {
putint("splnk", opnd);
} else {
putstring1("splnk");
}
break;
case ILIO_DPLNK:
if (full) {
putint("dplnk", opnd);
} else {
putstring1("dplnk");
}
break;
#ifdef ILIO_CSLNK
case ILIO_CSLNK:
if (full) {
putint("cslnk", opnd);
} else {
putstring1("cslnk");
}
break;
case ILIO_QPLNK:
if (full) {
putint("qplnk", opnd);
} else {
putstring1("qplnk");
}
break;
case ILIO_CDLNK:
if (full) {
putint("cdlnk", opnd);
} else {
putstring1("cdlnk");
}
break;
case ILIO_CQLNK:
if (full) {
putint("cqlnk", opnd);
} else {
putstring1("cqlnk");
}
break;
case ILIO_128LNK:
if (full) {
putint("128lnk", opnd);
} else {
putstring1("128lnk");
}
break;
case ILIO_256LNK:
if (full) {
putint("256lnk", opnd);
} else {
putstring1("256lnk");
}
break;
case ILIO_512LNK:
if (full) {
putint("512lnk", opnd);
} else {
putstring1("512lnk");
}
break;
#ifdef LONG_DOUBLE_FLOAT128
case ILIO_FLOAT128LNK:
if (full) {
putint("float128lnk", opnd);
} else {
putstring1("float128lnk");
}
break;
#endif
#endif /* ILIO_CSLNK */
#ifdef ILIO_PPLNK
case ILIO_PPLNK:
if (full) {
putint("pplnk", opnd);
} else {
putstring1("pplnk");
}
break;
#endif
case ILIO_IR:
putint("ir", opnd);
break;
#ifdef ILIO_KR
case ILIO_KR:
putpint("kr", opnd);
break;
#endif
case ILIO_AR:
putint("ar", opnd);
break;
case ILIO_SP:
putint("sp", opnd);
break;
case ILIO_DP:
putint("dp", opnd);
break;
default:
put2int("Unknown", IL_OPRFLAG(opc, j), opnd);
break;
}
}
}
if (full) {
putnzint("alt", ILI_ALT(ilix));
} else {
if (ILI_ALT(ilix)) {
putstring1("alt");
}
}
putnzint("count/rat/repl", ILI_COUNT(ilix));
if (full)
putnzint("hshlnk", ILI_HSHLNK(ilix));
putnzint("visit", ILI_VISIT(ilix));
if (full)
putnzint("vlist", ILI_VLIST(ilix));
putline();
} /* dili */
static void
dilitreex(int ilix, int l, int notlast)
{
ILI_OP opc;
int noprs, j, jj, nlinks;
int nshift = 0;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "%s", prefix);
dili(ilix);
if (ilix <= 0 || ilix >= ilib.stg_size)
return;
if (l) {
if (notlast) {
strcpy(prefix + l - 4, "| ");
} else {
strcpy(prefix + l - 4, " ");
}
}
opc = ILI_OPC(ilix);
if (opc >= 0 && opc < N_ILI) {
noprs = IL_OPRS(opc);
} else {
noprs = 0;
}
nlinks = 0;
for (j = 1; j <= noprs; ++j) {
if (IL_ISLINK(opc, j)) {
++nlinks;
}
}
if (ILI_ALT(ilix))
++nlinks;
switch (opc) {
case IL_CSEIR:
case IL_CSESP:
case IL_CSEDP:
case IL_CSECS:
case IL_CSECD:
case IL_CSEAR:
case IL_CSEKR:
case IL_CSE:
#ifdef LONG_DOUBLE_FLOAT128
case IL_FLOAT128CSE:
#endif
/* don't recurse unless we're at the top level */
if (l > 4)
nlinks = 0;
break;
case IL_ACCCOPY:
case IL_ACCCOPYIN:
case IL_ACCCOPYOUT:
case IL_ACCLOCAL:
case IL_ACCCREATE:
case IL_ACCDELETE:
case IL_ACCPRESENT:
case IL_ACCPCOPY:
case IL_ACCPCOPYIN:
case IL_ACCPCOPYOUT:
case IL_ACCPCREATE:
case IL_ACCPNOT:
case IL_ACCTRIPLE:
nshift = 1;
break;
default :
break;
}
if (nlinks) {
for (jj = 1; jj <= noprs; ++jj) {
j = jj;
if (nshift) {
j += nshift;
if (j > noprs)
j -= noprs;
}
if (IL_ISLINK(opc, j)) {
int opnd;
opnd = ILI_OPND(ilix, j);
if (ILI_OPC(opnd) != IL_NULL) {
strcpy(prefix + l, "+-- ");
dilitreex(opnd, l + 4, --nlinks);
}
prefix[l] = '\0';
}
}
if (ILI_ALT(ilix) && ILI_ALT(ilix) != ilix &&
ILI_OPC(ILI_ALT(ilix)) != IL_NULL) {
int opnd;
opnd = ILI_ALT(ilix);
strcpy(prefix + l, "+-- ");
dilitreex(opnd, l + 4, --nlinks);
prefix[l] = '\0';
}
}
} /* dilitreex */
void
dilitre(int ilix)
{
prefix[0] = ' ';
prefix[1] = ' ';
prefix[2] = ' ';
prefix[3] = ' ';
prefix[4] = '\0';
dilitreex(ilix, 4, 0);
prefix[0] = '\0';
} /* dilitre */
void
dilt(int ilt)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (iltb.stg_base == NULL) {
fprintf(dfile, "iltb.stg_base not allocated\n");
return;
}
if (full) {
putint("ilt", ilt);
} else {
putstring1("ilt:");
}
if (ilt <= 0 || ilt >= iltb.stg_size) {
fprintf(dfile, "\nilt %d out of %d\n", ilt, iltb.stg_size - 1);
return;
}
if (full) {
putnzint("ilip", ILT_ILIP(ilt));
putnzint("prev", ILT_PREV(ilt));
putnzint("next", ILT_NEXT(ilt));
#ifdef ILT_GUARD
putnzint("guard", ILT_GUARD(ilt));
#endif
}
putnzint("lineno", ILT_LINENO(ilt));
putnzint("findex", ILT_FINDEX(ilt));
#ifdef ILT_EXSDSCUNSAFE
putbit("sdscunsafe", ILT_EXSDSCUNSAFE(ilt));
#endif
putbit("st", ILT_ST(ilt));
putbit("br", ILT_BR(ilt));
putbit("can_throw", ILT_CAN_THROW(ilt));
putbit("dbgline", ILT_DBGLINE(ilt));
putbit("delete", ILT_DELETE(ilt));
putbit("ex", ILT_EX(ilt));
putbit("free", ILT_FREE(ilt));
putbit("ignore", ILT_IGNORE(ilt));
putbit("split", ILT_SPLIT(ilt));
putbit("cplx", ILT_CPLX(ilt));
putbit("keep", ILT_KEEP(ilt));
putbit("mcache", ILT_MCACHE(ilt));
putbit("nodel", ILT_NODEL(ilt));
#ifdef ILT_DELEBB
putbit("delebb", ILT_DELEBB(ilt));
#endif
#ifdef ILT_EQASRT
putbit("eqasrt", ILT_EQASRT(ilt));
#endif
#ifdef ILT_PREDC
putbit("predc", ILT_PREDC(ilt));
#endif
putline();
} /* dilt */
void
dumpilt(int ilt)
{
dilt(ilt);
if (ilt >= 0 && ilt < iltb.stg_size)
dilitre(ILT_ILIP(ilt));
} /* dumpilt */
void
dumpilts()
{
int bihx, iltx;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
bihx = BIHNUMG(gbl.currsub);
for (; bihx; bihx = BIH_NEXT(bihx)) {
db(bihx);
for (iltx = BIH_ILTFIRST(bihx); iltx; iltx = ILT_NEXT(iltx)) {
dilt(iltx);
}
if (BIH_LAST(bihx))
break;
fprintf(dfile, "\n");
}
} /* dumpilts */
void
db(int block)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
if (full) {
putint("block", block);
} else {
putstring1("block:");
}
if (block <= 0 || block >= bihb.stg_size) {
fprintf(dfile, "\nblock %d out of %d\n", block, bihb.stg_size - 1);
return;
}
putnzint("lineno", BIH_LINENO(block));
if (full)
putnzint("iltfirst", BIH_ILTFIRST(block));
if (full)
putnzint("iltlast", BIH_ILTLAST(block));
if (full)
putnzint("prev", BIH_PREV(block));
if (full)
putnzint("next", BIH_NEXT(block));
putnsym("label", BIH_LABEL(block));
if (BIH_LABEL(block)) {
putnzint("rfcnt", RFCNTG(BIH_LABEL(block)));
putbit("vol", VOLG(BIH_LABEL(block)));
}
putnzint("assn", BIH_ASSN(block));
putnzint("rgset", BIH_RGSET(block));
#ifdef BIH_ASM
putbit("asm", BIH_ASM(block));
#endif
putbit("rd", BIH_RD(block));
putbit("ft", BIH_FT(block));
putbit("en", BIH_EN(block));
putbit("ex", BIH_EX(block));
#ifdef BIH_EXSDSCUNSAFE
putbit("sdscunsafe", BIH_EXSDSCUNSAFE(block));
#endif
putbit("last", BIH_LAST(block));
putbit("xt", BIH_XT(block));
putbit("pl", BIH_PL(block));
putbit("ztrp", BIH_ZTRP(block));
putbit("guardee", BIH_GUARDEE(block));
putbit("guarder", BIH_GUARDER(block));
putbit("smove", BIH_SMOVE(block));
putbit("nobla", BIH_NOBLA(block));
putbit("nomerge", BIH_NOMERGE(block));
putbit("qjsr", BIH_QJSR(block));
putbit("head", BIH_HEAD(block));
putbit("tail", BIH_TAIL(block));
putbit("innermost", BIH_INNERMOST(block));
putbit("mexits", BIH_MEXITS(block));
putbit("ozcr", BIH_OZCR(block));
putbit("par", BIH_PAR(block));
putbit("cs", BIH_CS(block));
putbit("streg", BIH_STREG(block));
putbit("vpar", BIH_VPAR(block));
putbit("enlab", BIH_ENLAB(block));
putbit("mark", BIH_MARK(block));
putbit("mark2", BIH_MARK2(block));
putbit("mark3", BIH_MARK3(block));
putbit("parloop", BIH_PARLOOP(block));
putbit("parsect", BIH_PARSECT(block));
putbit("resid", BIH_RESID(block));
putbit("ujres", BIH_UJRES(block));
putbit("simd", BIH_SIMD(block));
putbit("ldvol", BIH_LDVOL(block));
putbit("stvol", BIH_STVOL(block));
putbit("task", BIH_TASK(block));
putbit("paraln", BIH_PARALN(block));
putbit("invif", BIH_INVIF(block));
putbit("noinvif", BIH_NOINVIF(block));
putbit("combst", BIH_COMBST(block));
putbit("deletable", BIH_DELETABLE(block));
putbit("vcand", BIH_VCAND(block));
putbit("accel", BIH_ACCEL(block));
putbit("endaccel", BIH_ENDACCEL(block));
putbit("accdata", BIH_ACCDATA(block));
putbit("endaccdata", BIH_ENDACCDATA(block));
putbit("kernel", BIH_KERNEL(block));
putbit("endkernel", BIH_ENDKERNEL(block));
putbit("midiom", BIH_MIDIOM(block));
putbit("nodepchk", BIH_NODEPCHK(block));
putbit("doconc", BIH_DOCONC(block));
putline();
#ifdef BIH_FINDEX
if (BIH_FINDEX(block) || BIH_FTAG(block)) {
putint("findex", BIH_FINDEX(block));
putint("ftag", BIH_FTAG(block));
/* The casting from double to int may cause an overflow in int.
* Just take a short-cut here for the ease of debugging. Will need
* to create a new function to accommodate the non-int types.
*/
if (BIH_BLKCNT(block) != -1.0)
putdouble("blkCnt", BIH_BLKCNT(block));
if (BIH_FINDEX(block) > 0 && BIH_FINDEX(block) < fihb.stg_avail) {
if (FIH_DIRNAME(BIH_FINDEX(block))) {
putstring1(FIH_DIRNAME(BIH_FINDEX(block)));
putstring1t("/");
putstring1t(FIH_FILENAME(BIH_FINDEX(block)));
} else {
putstring1(FIH_FILENAME(BIH_FINDEX(block)));
}
if (FIH_FUNCNAME(BIH_FINDEX(block)) != NULL) {
putstring1(FIH_FUNCNAME(BIH_FINDEX(block)));
}
} else if (BIH_FINDEX(block) < 0 || BIH_FINDEX(block) >= fihb.stg_avail) {
puterr("bad findex value");
}
putline();
}
#endif
} /* db */
void
dumpblock(int block)
{
int ilt;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
db(block);
for (ilt = BIH_ILTFIRST(block); ilt; ilt = ILT_NEXT(ilt)) {
dilt(ilt);
if (ilt >= 0 && ilt < iltb.stg_size)
dilitre(ILT_ILIP(ilt));
}
} /* dumpblock */
void
dumptblock(const char *title, int block)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** dump block %d %s **********\n", block, title);
dumpblock(block);
} /* dumptblock */
void
dbih(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
block = BIHNUMG(gbl.currsub);
for (; block; block = BIH_NEXT(block)) {
dumpblock(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* dbih */
void
dbihonly(void)
{
int block;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (bihb.stg_base == NULL) {
fprintf(dfile, "bihb.stg_base not allocated\n");
return;
}
block = BIHNUMG(gbl.currsub);
for (; block; block = BIH_NEXT(block)) {
db(block);
if (BIH_LAST(block))
break;
fprintf(dfile, "\n");
}
} /* dbihonly */
void
dumpblocksonly(void)
{
dbihonly();
} /* dumpblocksonly */
void
dumpblocks(const char *title)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "\n********** BLOCK INFORMATION HEADER TABLE **********\n");
fprintf(dfile, "%s called\n", title);
dbih();
fprintf(dfile, "%s done\n**********\n\n", title);
} /* dumpblocks */
#ifdef FIH_FULLNAME
void
dfih(int f)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (fihb.stg_base == NULL) {
fprintf(dfile, "fihb.stg_base not allocated\n");
return;
}
if (full) {
putint("fih", f);
} else {
putstring1("fih:");
}
if (f <= 0 || f >= fihb.stg_size) {
fprintf(dfile, "\nfile %d out of %d\n", f, fihb.stg_size - 1);
return;
}
putstring("fullname", FIH_FULLNAME(f));
if (FIH_FUNCNAME(f) != NULL && FIH_FUNCNAME(f)[0] != '\0') {
putstring("funcname", FIH_FUNCNAME(f));
}
putint("functag", FIH_FUNCTAG(f));
putint("srcline", FIH_SRCLINE(f));
putnzint("level", FIH_LEVEL(f));
putnzint("parent", FIH_PARENT(f));
putnzint("lineno", FIH_LINENO(f));
putnzint("next", FIH_NEXT(f));
putnzint("child", FIH_CHILD(f));
putbit("included", FIH_INC(f));
putbit("inlined", FIH_INL(f));
putbit("ipainlined", FIH_IPAINL(f));
putbit("ccff", FIH_FLAGS(f) & FIH_CCFF);
putbit("ccffinfo", (FIH_CCFFINFO(f) != NULL));
putline();
} /* dfih */
void
dumpfile(int f)
{
dfih(f);
} /* dumpfile */
void
dumpfiles(void)
{
int f;
for (f = 1; f < fihb.stg_avail; ++f) {
dfih(f);
}
} /* dumpfiles */
#endif
#ifdef NME_PTE
void
putptelist(int pte)
{
for (; pte > 0; pte = (PTE_NEXT(pte) == pte ? -1 : PTE_NEXT(pte))) {
switch (PTE_TYPE(pte)) {
case PT_UNK:
putstring1("unk");
break;
case PT_PSYM:
putsym("psym", PTE_SPTR(pte));
break;
case PT_ISYM:
putsym("isym", PTE_SPTR(pte));
break;
case PT_ANON:
putint("anon", PTE_VAL(pte));
break;
case PT_GDYN:
putint("gdyn", PTE_VAL(pte));
break;
case PT_LDYN:
putint("ldyn", PTE_VAL(pte));
break;
case PT_NLOC:
putstring1("nonlocal");
break;
default:
put2int("???", PTE_TYPE(pte), PTE_VAL(pte));
break;
}
}
} /* putptelist */
#endif
static void
_printnme(int n)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (n < 0 || n >= nmeb.stg_avail) {
putint("nme", n);
return;
}
switch (NME_TYPE(n)) {
case NT_VAR:
appendstring1(printname(NME_SYM(n)));
if (NME_SYM(n) > NOSYM && NME_SYM(n) < stb.stg_avail &&
SCG(NME_SYM(n)) == SC_PRIVATE)
appendstring1("'");
break;
case NT_MEM:
if (NME_NM(n)) {
_printnme(NME_NM(n));
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == 0) {
appendstring1(".real");
} else if (NME_SYM(n) == 1) {
appendstring1(".imag");
} else {
appendstring1(".");
appendstring1(printname(NME_SYM(n)));
}
break;
case NT_ARR:
if (NME_NM(n)) {
_printnme(NME_NM(n));
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == 0) {
appendstring1("[");
appendint1(NME_CNST(n));
appendstring1("]");
} else if (NME_SUB(n) != 0) {
appendstring1("[");
_printili(NME_SUB(n));
appendstring1("]");
} else {
appendstring1("[?]");
}
break;
case NT_IND:
appendstring1("*(");
if (NME_NM(n)) {
_printnme(NME_NM(n));
} else {
appendstring1("Unknown");
}
if (NME_SYM(n) == NME_NULL) {
} else if (NME_SYM(n) == 0) {
if (NME_CNST(n)) {
appendstring1("+");
appendint1(NME_CNST(n));
}
} else {
appendstring1("+?");
}
appendstring1(")");
if (NME_SUB(n) != 0) {
appendstring1("[");
_printili(NME_SUB(n));
appendstring1("]");
}
break;
case NT_UNK:
if (NME_SYM(n) == 0) {
appendstring1("unknown");
} else if (NME_SYM(n) == 1) {
appendstring1("volatile");
} else {
appendstring1("unknown:");
appendint1(NME_SYM(n));
}
break;
default:
appendstring1("nme(");
appendint1(n);
appendstring1(":");
appendint1(NME_TYPE(n));
appendstring1(")");
break;
}
} /* _printnme */
void
pprintnme(int n)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
putstring1("");
_printnme(n);
} /* pprintnme */
void
printnme(int n)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
linelen = 0;
_printnme(n);
} /* printnme */
static const char *nmetypes[] = {"unknown ", "indirect", "variable",
"member ", "element ", "safe "};
void
_dumpnme(int n, bool dumpdefsuses)
{
int store, pte;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (n <= 0 || n >= nmeb.stg_avail) {
fprintf(dfile, "\nNME %d out of %d\n", n, nmeb.stg_avail - 1);
return;
}
if (nmeb.stg_base == NULL) {
fprintf(dfile, "nmeb.stg_base not allocated\n");
return;
}
if (full) {
putint("nme", n);
} else {
putstring1("nme");
}
putval1(NME_TYPE(n), nmetypes, SIZEOF(nmetypes));
switch (NME_TYPE(n)) {
case NT_VAR:
putsym("var", NME_SYM(n));
break;
case NT_MEM:
pprintnme(n);
if (NME_SYM(n) == 0) {
putstring1(".real");
} else if (NME_SYM(n) == 1) {
putstring1(".imag");
break;
} else {
putsym("member", NME_SYM(n));
}
break;
case NT_ARR:
case NT_IND:
pprintnme(n);
if (NME_SYM(n) == NME_NULL) {
putint("sym", -1);
} else if (NME_SYM(n) == 0) {
} else {
if (NME_SYM(n) > 0 && NME_SYM(n) < stb.stg_avail) {
putsym("sym", NME_SYM(n));
} else {
putnzint("sym", NME_SYM(n));
}
}
break;
case NT_UNK:
pprintnme(n);
break;
default:
if (NME_SYM(n) > 0 && NME_SYM(n) < stb.stg_avail) {
putsym("sym", NME_SYM(n));
} else {
putnzint("sym", NME_SYM(n));
}
break;
}
putnzint("nm", NME_NM(n));
#ifdef NME_BASE
putnzint("base", NME_BASE(n));
#endif
putnzint("cnst", NME_CNST(n));
putnzint("cnt", NME_CNT(n));
if (full & 1)
putnzint("hashlink", NME_HSHLNK(n));
putnzint("inlarr", NME_INLARR(n));
putnzint("rat/rfptr", NME_RAT(n));
putnzint("stl", NME_STL(n));
putnzint("sub", NME_SUB(n));
putnzint("mask", NME_MASK(n));
#ifdef NME_PTE
pte = NME_PTE(n);
if (dumpdefsuses && pte) {
putline();
putstring1("pointer targets:");
putptelist(pte);
}
#endif
} /* _dumpnme */
void
dumpnnme(int n)
{
linelen = 0;
_dumpnme(n, false);
putline();
} /* dumpnme */
void
dumpnme(int n)
{
linelen = 0;
_dumpnme(n, true);
putline();
} /* dumpnme */
void
dumpnmes(void)
{
int n;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (nmeb.stg_base == NULL) {
fprintf(dfile, "nmeb.stg_base not allocated\n");
return;
}
fprintf(dfile, "\n********** NME TABLE **********\n");
for (n = 1; n < nmeb.stg_avail; ++n) {
fprintf(dfile, "\n");
dumpnme(n);
}
fprintf(dfile, "\n");
} /* dumpnmes */
#endif
char *
printname(int sptr)
{
extern void cprintf(char *s, const char *format, INT *val);
static char b[200];
double dd;
union {
float ff;
ISZ_T ww;
} xx;
if (sptr <= 0 || sptr >= stb.stg_avail) {
snprintf(b, 200, "symbol %d out of %d", sptr, stb.stg_avail - 1);
return b;
}
if (STYPEG(sptr) == ST_CONST) {
INT num[2], cons1, cons2;
int pointee;
char *bb, *ee;
switch (DTY(DTYPEG(sptr))) {
case TY_INT8:
case TY_UINT8:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
ui64toax(num, b, 22, 0, 10);
break;
case TY_INT:
snprintf(b, 200, "%10d", CONVAL2G(sptr));
break;
case TY_FLOAT:
xx.ww = CONVAL2G(sptr);
if ((xx.ww & 0x7f800000) == 0x7f800000) {
/* Infinity or NaN */
snprintf(b, 200, ("(float)(0x%8.8" ISZ_PF "x)"), xx.ww);
} else {
dd = xx.ff;
snprintf(b, 200, "%.8ef", dd);
}
break;
case TY_DBLE:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
if ((num[0] & 0x7ff00000) == 0x7ff00000) {
/* Infinity or NaN */
snprintf(b, 200, "(double)(0x%8.8x%8.8xLL)", num[0], num[1]);
} else {
cprintf(b, "%.17le", num);
}
break;
case TY_CMPLX:
xx.ww = CONVAL1G(sptr);
if ((xx.ww & 0x7f800000) == 0x7f800000) {
/* Infinity or NaN */
int len;
len = snprintf(b, 200, ("(0x%8.8" ISZ_PF "x, "), xx.ww);
bb = b + len;
} else {
b[0] = '(';
sprintf(&b[1], "%17.10e", xx.ff);
b[18] = ',';
b[19] = ' ';
bb = &b[20];
}
xx.ww = CONVAL2G(sptr);
if ((xx.ww & 0x7f800000) == 0x7f800000) {
snprintf(bb, 200, ("(0x%8.8" ISZ_PF "x, "), xx.ww);
} else {
sprintf(bb, "%17.10e", xx.ff);
bb += 17;
*bb++ = ')';
*bb = '\0';
}
break;
case TY_DCMPLX:
cons1 = CONVAL1G(sptr);
cons2 = CONVAL2G(sptr);
num[0] = CONVAL1G(cons1);
num[1] = CONVAL2G(cons1);
if ((num[0] & 0x7ff00000) == 0x7ff00000) {
/* Infinity or NaN */
int len;
len = snprintf(b, 200, "(0x%8.8x%8.8xLL, ", num[0], num[1]);
bb = b + len;
} else {
b[0] = '(';
cprintf(&b[1], "%24.17le", num);
b[25] = ',';
b[26] = ' ';
bb = &b[27];
}
num[0] = CONVAL1G(cons2);
num[1] = CONVAL2G(cons2);
if ((num[0] & 0x7ff00000) == 0x7ff00000) {
/* Infinity or NaN */
snprintf(bb, 200, "0x%8.8x%8.8xLL", num[0], num[1]);
} else {
cprintf(bb, "%24.17le", num);
bb += 24;
*bb++ = ')';
*bb = '\0';
}
break;
case TY_QUAD:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
cprintf(b, "%.17le", num);
break;
case TY_PTR:
pointee = CONVAL1G(sptr);
if (pointee > 0 && pointee < stb.stg_avail && STYPEG(pointee) != ST_CONST
) {
if (ACONOFFG(sptr) == 0) {
snprintf(b, 200, "*%s", SYMNAME(pointee));
} else {
snprintf(b, 200, "*%s+%" ISZ_PF "d", SYMNAME(pointee),
ACONOFFG(sptr));
}
} else {
if (ACONOFFG(sptr) == 0) {
snprintf(b, 200, "*(sym %d)", pointee);
} else {
snprintf(b, 200, "*(sym %d)+%" ISZ_PF "d", pointee, ACONOFFG(sptr));
}
}
break;
case TY_WORD:
snprintf(b, 200, "%10" ISZ_PF "d", ACONOFFG(sptr));
break;
case TY_CHAR:
return stb.n_base + CONVAL1G(sptr);
case TY_BLOG:
case TY_SLOG:
case TY_LOG:
snprintf(b, 200, "%10d", CONVAL2G(sptr));
break;
case TY_LOG8:
num[0] = CONVAL1G(sptr);
num[1] = CONVAL2G(sptr);
ui64toax(num, b, 22, 0, 10);
break;
default:
snprintf(b, 200, "unknown constant %d dty %d", sptr,
DTY(DTYPEG(sptr)));
break;
}
for (bb = b; *bb == ' '; ++bb)
;
for (ee = bb; *ee; ++ee)
; /* go to end of string */
for (; ee > bb && *(ee - 1) == ' '; --ee)
*ee = '\0';
return bb;
}
/* default case */
if (strncmp(SYMNAME(sptr), "..inline", 8) == 0) {
/* append symbol number to distinguish */
snprintf(b, 200, "%s_%d", SYMNAME(sptr), sptr);
return b;
}
return SYMNAME(sptr);
} /* printname */
#if DEBUG
/*
* dump the DVL structure
*/
void
dumpdvl(int d)
{
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (aux.dvl_base == NULL) {
fprintf(dfile, "aux.dvl_base not allocated\n");
return;
}
if (d < 0 || d >= aux.dvl_avl) {
fprintf(dfile, "\ndvl %d out of %d\n", d, aux.dvl_avl - 1);
return;
}
putint("dvl", d);
putsym("sym", (SPTR) DVL_SPTR(d)); // ???
putINT("conval", DVL_CONVAL(d));
putline();
} /* dumpdvl */
void
dumpdvls()
{
int d;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
if (aux.dvl_base == NULL) {
fprintf(dfile, "aux.dvl_base not allocated\n");
return;
}
for (d = 0; d < aux.dvl_avl; ++d) {
fprintf(dfile, "\n");
dumpdvl(d);
}
} /* dumpdvls */
/*
* dump variables which are kept on the stack
*/
void
stackvars()
{
int sptr;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
fprintf(dfile, "Local variables:\n");
for (sptr = gbl.locals; sptr > NOSYM; sptr = SYMLKG(sptr)) {
dsym(sptr);
}
} /* stackvars */
/*
* diagnose what stack locations are used
*/
void
stackcheck()
{
long maxstack, minstack, i, j, addr, size, totused, totfree;
int sptr, lastclash;
int *stack, *stackmem;
dfile = gbl.dbgfil ? gbl.dbgfil : stderr;
minstack = 0;
maxstack = -1;
for (sptr = gbl.locals; sptr > NOSYM; sptr = SYMLKG(sptr)) {
size = size_of(DTYPEG(sptr));
if (ADDRESSG(sptr) - size < minstack)
minstack = ADDRESSG(sptr) - size;
if (ADDRESSG(sptr) + size > maxstack)
maxstack = ADDRESSG(sptr) + size;
}
fprintf(dfile, "Stack for subprogram %d:%s\n%8ld:%-8ld\n", gbl.func_count,
SYMNAME(gbl.currsub), minstack, maxstack);
stackmem = (int *)malloc((maxstack - minstack + 1) * sizeof(int));
stack = stackmem - minstack; /* minstack is <= 0 */
for (i = minstack; i <= maxstack; ++i)
stack[i] = 0;
for (sptr = gbl.locals; sptr > NOSYM; sptr = SYMLKG(sptr)) {
addr = ADDRESSG(sptr);
size = size_of(DTYPEG(sptr));
lastclash = 0;
for (i = addr; i < addr + size; ++i) {
if (stack[i] != 0) {
if (stack[i] != lastclash)
fprintf(dfile, "sptr %d:%s and %d:%s clash at memory %ld\n", sptr,
SYMNAME(sptr), stack[i], SYMNAME(stack[i]), i);
lastclash = stack[i];
}
stack[i] = sptr;
}
}
sptr = -1;
totfree = 0;
totused = 0;
for (i = minstack; i <= maxstack; ++i) {
if (stack[i] == 0)
++totfree;
else
++totused;
if (stack[i] != sptr) {
sptr = stack[i];
for (j = i; j < maxstack && stack[j + 1] == sptr; ++j)
;
if (sptr == 0) {
fprintf(dfile, "%8ld:%-8ld ---free (%ld)\n", i, j, j - i + 1);
} else {
size = size_of(DTYPEG(sptr));
fprintf(dfile, "%8ld:%-8ld %8ld(%%rsp) %5d:%s (%ld) ", i, j,
i + 8 - minstack, sptr, SYMNAME(sptr), size);
putdtypex(DTYPEG(sptr), 1000);
fprintf(dfile, "\n");
}
}
}
fprintf(dfile, "%8ld used\n%8ld free\n", totused, totfree);
free(stackmem);
} /* stackcheck */
#endif /* DEBUG */
| 21.91612
| 95
| 0.568653
|
kammerdienerb
|
06311e251ef6551dd4c1494ace2781442008794a
| 9,775
|
cpp
|
C++
|
src/node_server_actions_1.cpp
|
srinivasyadav18/octotiger
|
4d93c50fe345a081b7985ecb4cb698d16c121565
|
[
"BSL-1.0"
] | 35
|
2016-11-17T22:35:11.000Z
|
2022-01-24T19:07:36.000Z
|
src/node_server_actions_1.cpp
|
srinivasyadav18/octotiger
|
4d93c50fe345a081b7985ecb4cb698d16c121565
|
[
"BSL-1.0"
] | 123
|
2016-11-17T21:29:25.000Z
|
2022-03-03T21:40:04.000Z
|
src/node_server_actions_1.cpp
|
srinivasyadav18/octotiger
|
4d93c50fe345a081b7985ecb4cb698d16c121565
|
[
"BSL-1.0"
] | 10
|
2018-11-28T18:17:42.000Z
|
2022-01-25T12:52:37.000Z
|
// Copyright (c) 2019 AUTHORS
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "octotiger/config.hpp"
#include "octotiger/container_device.hpp"
#include "octotiger/defs.hpp"
#include "octotiger/diagnostics.hpp"
#include "octotiger/future.hpp"
#include "octotiger/node_client.hpp"
#include "octotiger/node_registry.hpp"
#include "octotiger/node_server.hpp"
#include "octotiger/options.hpp"
#include "octotiger/profiler.hpp"
#include "octotiger/taylor.hpp"
#include <hpx/include/lcos.hpp>
#include <hpx/include/run_as.hpp>
#include <hpx/collectives/broadcast.hpp>
#include <boost/iostreams/stream.hpp>
#include <algorithm>
#include <array>
#include <chrono>
#include <fstream>
#include <vector>
using amr_error_action_type = node_server::amr_error_action;
HPX_REGISTER_ACTION(amr_error_action_type);
future<std::pair<real, real>> node_client::amr_error() const {
return hpx::async<typename node_server::amr_error_action>(get_unmanaged_gid());
}
std::pair<real, real> node_server::amr_error() {
std::vector<hpx::future<std::pair<real, real>>> kfuts;
auto sum = std::make_pair(0.0, 0.0);
if (is_refined) {
for (int i = 0; i < NCHILD; i++) {
kfuts.push_back(children[i].amr_error());
}
hpx::wait_all(kfuts);
for (int i = 0; i < NCHILD; i++) {
auto tmp = kfuts[i].get();
sum.first += tmp.first;
sum.second += tmp.second;
}
} else {
sum = grid_ptr->amr_error();
}
return sum;
}
using regrid_gather_action_type = node_server::regrid_gather_action;
HPX_REGISTER_ACTION(regrid_gather_action_type);
future<node_count_type> node_client::regrid_gather(bool rb) const {
return hpx::async<typename node_server::regrid_gather_action>(get_unmanaged_gid(), rb);
}
node_count_type node_server::regrid_gather(bool rebalance_only) {
node_registry::delete_(my_location);
node_count_type count;
count.total = 1;
count.leaf = is_refined ? 0 : 1;
std::vector<hpx::future<void>> kfuts;
if (is_refined) {
if (!rebalance_only) {
/* Turning refinement off */
if (refinement_flag == 0) {
for (int i = 0; i < NCHILD; i++) {
kfuts.push_back(children[i].kill());
}
std::fill_n(children.begin(), NCHILD, node_client());
is_refined = false;
}
}
if (is_refined) {
std::array<future<node_count_type>, NCHILD> futs;
integer index = 0;
for (auto &child : children) {
futs[index++] = child.regrid_gather(rebalance_only);
}
auto futi = futs.begin();
for (auto const &ci : geo::octant::full_set()) {
const auto child_cnt = futi->get();
++futi;
child_descendant_count[ci] = child_cnt.total;
count.leaf += child_cnt.leaf;
count.total += child_cnt.total;
}
} else {
count.leaf = 1;
for (auto const &ci : geo::octant::full_set()) {
child_descendant_count[ci] = 0;
}
}
} else if (!rebalance_only) {
if (refinement_flag != 0) {
refinement_flag = 0;
count.total += NCHILD;
count.leaf += NCHILD - 1;
/* Turning refinement on*/
is_refined = true;
for (auto &ci : geo::octant::full_set()) {
child_descendant_count[ci] = 1;
}
}
}
grid_ptr->set_leaf(!is_refined);
hpx::wait_all(kfuts);
return count;
}
future<hpx::id_type> node_server::create_child(hpx::id_type const &locality, integer ci) {
return hpx::async(hpx::util::annotated_function([ci, this](hpx::id_type const locality) {
return hpx::new_<node_server>(locality, my_location.get_child(ci), me, current_time, rotational_time, step_num, hcycle, rcycle, gcycle).then([this, ci](future<hpx::id_type> &&child_idf) {
hpx::id_type child_id = child_idf.get();
node_client child = child_id;
{
std::array<integer, NDIM> lb = {2 * H_BW, 2 * H_BW, 2 * H_BW};
std::array<integer, NDIM> ub;
lb[XDIM] += (1 & (ci >> 0)) * (INX);
lb[YDIM] += (1 & (ci >> 1)) * (INX);
lb[ZDIM] += (1 & (ci >> 2)) * (INX);
for (integer d = 0; d != NDIM; ++d) {
ub[d] = lb[d] + (INX);
}
std::vector<real> outflows(opts().n_fields, ZERO);
if (ci == 0) {
outflows = grid_ptr->get_outflows_raw();
}
if (current_time > ZERO || opts().restart_filename != "") {
std::vector<real> prolong;
{
std::unique_lock < hpx::lcos::local::spinlock > lk(prolong_mtx);
prolong = grid_ptr->get_prolong(lb, ub);
}
GET(child.set_grid(std::move(prolong), std::move(outflows)));
}
}
if (opts().radiation) {
std::array<integer, NDIM> lb = {2 * R_BW, 2 * R_BW, 2 * R_BW};
std::array<integer, NDIM> ub;
lb[XDIM] += (1 & (ci >> 0)) * (INX);
lb[YDIM] += (1 & (ci >> 1)) * (INX);
lb[ZDIM] += (1 & (ci >> 2)) * (INX);
for (integer d = 0; d != NDIM; ++d) {
ub[d] = lb[d] + (INX);
}
/* std::vector<real> outflows(NF, ZERO);
if (ci == 0) {
outflows = grid_ptr->get_outflows();
}*/
if (current_time > ZERO) {
std::vector<real> prolong;
{
std::unique_lock < hpx::lcos::local::spinlock > lk(prolong_mtx);
prolong = rad_grid_ptr->get_prolong(lb, ub);
}
child.set_rad_grid(std::move(prolong)/*, std::move(outflows)*/).get();
}
}
return child_id;
});}, "node_server::create_child::lambda"), locality);
}
using regrid_scatter_action_type = node_server::regrid_scatter_action;
HPX_REGISTER_ACTION(regrid_scatter_action_type);
future<void> node_client::regrid_scatter(integer a, integer b) const {
return hpx::async<typename node_server::regrid_scatter_action>(get_unmanaged_gid(), a, b);
}
void node_server::regrid_scatter(integer a_, integer total) {
position = a_;
refinement_flag = 0;
std::array<future<void>, geo::octant::count()> futs;
if (is_refined) {
integer a = a_;
++a;
integer index = 0;
for (auto &ci : geo::octant::full_set()) {
const integer loc_index = a * options::all_localities.size() / total;
const auto child_loc = options::all_localities[loc_index];
if (children[ci].empty()) {
futs[index++] = create_child(child_loc, ci).then([this, ci, a, total](future<hpx::id_type> &&child) {
children[ci] = GET(child);
GET(children[ci].regrid_scatter(a, total));
});
} else {
const hpx::id_type id = children[ci].get_gid();
integer current_child_id = hpx::naming::get_locality_id_from_gid(id.get_gid());
auto current_child_loc = options::all_localities[current_child_id];
if (child_loc != current_child_loc) {
futs[index++] = children[ci].copy_to_locality(child_loc).then([this, ci, a, total](future<hpx::id_type> &&child) {
children[ci] = GET(child);
GET(children[ci].regrid_scatter(a, total));
});
} else {
futs[index++] = children[ci].regrid_scatter(a, total);
}
}
a += child_descendant_count[ci];
}
}
if (is_refined) {
for (auto &f : futs) {
GET(f);
}
}
clear_family();
}
node_count_type node_server::regrid(const hpx::id_type &root_gid, real omega, real new_floor, bool rb, bool grav_energy_comp) {
timings::scope ts(timings_, timings::time_regrid);
hpx::util::high_resolution_timer timer;
assert(grid_ptr != nullptr);
print("-----------------------------------------------\n");
if (!rb) {
print("checking for refinement\n");
check_for_refinement(omega, new_floor);
} else {
node_registry::clear();
}
print("regridding\n");
real tstart = timer.elapsed();
auto a = regrid_gather(rb);
real tstop = timer.elapsed();
print("Regridded tree in %f seconds\n", real(tstop - tstart));
print("rebalancing %i nodes with %i leaves\n", int(a.total), int(a.leaf));
tstart = timer.elapsed();
regrid_scatter(0, a.total);
tstop = timer.elapsed();
print("Rebalanced tree in %f seconds\n", real(tstop - tstart));
assert(grid_ptr != nullptr);
tstart = timer.elapsed();
print("forming tree connections\n");
a.amr_bnd = form_tree(hpx::unmanaged(root_gid));
print("%i amr boundaries\n", a.amr_bnd);
tstop = timer.elapsed();
print("Formed tree in %f seconds\n", real(tstop - tstart));
print("solving gravity\n");
solve_gravity(grav_energy_comp, false);
double elapsed = timer.elapsed();
print("regrid done in %f seconds\n---------------------------------------\n", elapsed);
return a;
}
using set_aunt_action_type = node_server::set_aunt_action;
HPX_REGISTER_ACTION(set_aunt_action_type);
future<void> node_client::set_aunt(const hpx::id_type &aunt, const geo::face &f) const {
return hpx::async<typename node_server::set_aunt_action>(get_unmanaged_gid(), aunt, f);
}
void node_server::set_aunt(const hpx::id_type &aunt, const geo::face &face) {
if (aunts[face].get_gid() != hpx::invalid_id) {
print("AUNT ALREADY SET\n");
abort();
}
aunts[face] = aunt;
}
using set_grid_action_type = node_server::set_grid_action;
HPX_REGISTER_ACTION(set_grid_action_type);
future<void> node_client::set_grid(std::vector<real> &&g, std::vector<real> &&o) const {
return hpx::async<typename node_server::set_grid_action>(get_unmanaged_gid(), std::move(g), std::move(o));
}
void node_server::set_grid(const std::vector<real> &data, std::vector<real> &&outflows) {
grid_ptr->set_prolong(data, std::move(outflows));
}
using solve_gravity_action_type = node_server::solve_gravity_action;
HPX_REGISTER_ACTION(solve_gravity_action_type);
future<void> node_client::solve_gravity(bool ene, bool aonly) const {
return hpx::async<typename node_server::solve_gravity_action>(get_unmanaged_gid(), ene, aonly);
}
void node_server::solve_gravity(bool ene, bool aonly) {
if (!opts().gravity) {
return;
}
std::array<future<void>, NCHILD> child_futs;
if (is_refined) {
integer index = 0;
;
for (auto &child : children) {
child_futs[index++] = child.solve_gravity(ene, aonly);
}
}
compute_fmm(RHO, ene, aonly);
if (is_refined) {
// wait_all_and_propagate_exceptions(child_futs);
for (auto &f : child_futs) {
GET(f);
}
}
}
| 31.230032
| 189
| 0.668951
|
srinivasyadav18
|
0632117eadb9df1777de7677ec3db36e22dfec98
| 2,811
|
hpp
|
C++
|
graphics/source/geometry/curve.hpp
|
HrvojeFER/irg-lab
|
53f27430d39fa099dd605cfd632e38b55a392699
|
[
"MIT"
] | null | null | null |
graphics/source/geometry/curve.hpp
|
HrvojeFER/irg-lab
|
53f27430d39fa099dd605cfd632e38b55a392699
|
[
"MIT"
] | null | null | null |
graphics/source/geometry/curve.hpp
|
HrvojeFER/irg-lab
|
53f27430d39fa099dd605cfd632e38b55a392699
|
[
"MIT"
] | null | null | null |
#ifndef IRGLAB_CURVE_HPP
#define IRGLAB_CURVE_HPP
#include "external/external.hpp"
#include "primitive/primitive.hpp"
namespace il
{
// Type traits
[[nodiscard, maybe_unused]] constexpr bool is_curve_description_supported(
small_natural_number dimension_count)
{
return is_vector_size_supported(dimension_count);
}
// Base
template<small_natural_number DimensionCount>
class [[maybe_unused]] curve
{
// Traits and types
public:
[[maybe_unused]] static constexpr small_natural_number dimension_count = DimensionCount;
using control_point [[maybe_unused]] = cartesian_coordinates<dimension_count>;
// Constructors and related methods
// Only std::initializer_list constructor because I want to discourage the use of curves with
// a lot of control points because that would greatly affect performance.
template<
#pragma clang diagnostic push
#pragma ide diagnostic ignored "UnusedLocalVariable"
typename Dummy = void, std::enable_if_t<
std::is_same_v<Dummy, void> && is_curve_description_supported(dimension_count), int> = 0>
#pragma clang diagnostic pop
[[nodiscard, maybe_unused]] explicit curve(std::initializer_list<control_point> control_points) :
_control_points{control_points}
{ }
// Non-modifiers
[[nodiscard, maybe_unused]] cartesian_coordinates<dimension_count> operator()(
const rational_number parameter)
{
cartesian_coordinates<dimension_count> result{ };
for (natural_number i = 0 ; i < _control_points.size() ; ++i)
result += _control_points[i] * _get_bernstein_polynomial_result(
i, _control_points.size() - 1, parameter);
return result;
}
// Implementation details
private:
[[nodiscard]] static rational_number _get_bernstein_polynomial_result(
const natural_number index,
const natural_number control_point_count,
const rational_number parameter)
{
return static_cast<rational_number>(
number_of_combinations(control_point_count, index) *
glm::pow(parameter, index) *
glm::pow(1 - parameter, control_point_count - index));
}
// Data
std::vector<control_point> _control_points;
};
}
// Dimensional aliases
namespace il::d2
{
using curve [[maybe_unused]] = il::curve<dimension_count>;
}
namespace il::d3
{
using curve [[maybe_unused]] = il::curve<dimension_count>;
}
#endif
| 28.11
| 114
| 0.622554
|
HrvojeFER
|
06352ea040e35c97c36f7dbbbd6831e090340c34
| 3,068
|
cpp
|
C++
|
wpilibcExamples/src/main/cpp/templates/sample/cpp/Robot.cpp
|
balupillai/allwpilib
|
6992f5421f8222e1edf872a8788d88016ba46f2b
|
[
"BSD-3-Clause"
] | 1
|
2021-10-10T06:52:41.000Z
|
2021-10-10T06:52:41.000Z
|
wpilibcExamples/src/main/cpp/templates/sample/cpp/Robot.cpp
|
balupillai/allwpilib
|
6992f5421f8222e1edf872a8788d88016ba46f2b
|
[
"BSD-3-Clause"
] | null | null | null |
wpilibcExamples/src/main/cpp/templates/sample/cpp/Robot.cpp
|
balupillai/allwpilib
|
6992f5421f8222e1edf872a8788d88016ba46f2b
|
[
"BSD-3-Clause"
] | null | null | null |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "Robot.h"
#include <iostream>
#include <frc/Timer.h>
#include <frc/smartdashboard/SmartDashboard.h>
Robot::Robot() {
// Note SmartDashboard is not initialized here, wait until RobotInit() to make
// SmartDashboard calls
m_robotDrive.SetExpiration(0.1);
}
void Robot::RobotInit() {
m_chooser.SetDefaultOption(kAutoNameDefault, kAutoNameDefault);
m_chooser.AddOption(kAutoNameCustom, kAutoNameCustom);
frc::SmartDashboard::PutData("Auto Modes", &m_chooser);
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable chooser
* code works with the Java SmartDashboard. If you prefer the LabVIEW Dashboard,
* remove all of the chooser code and uncomment the GetString line to get the
* auto name from the text box below the Gyro.
*
* You can add additional auto modes by adding additional comparisons to the
* if-else structure below with additional strings. If using the SendableChooser
* make sure to add them to the chooser code above as well.
*/
void Robot::Autonomous() {
std::string autoSelected = m_chooser.GetSelected();
// std::string autoSelected = frc::SmartDashboard::GetString(
// "Auto Selector", kAutoNameDefault);
std::cout << "Auto selected: " << autoSelected << std::endl;
// MotorSafety improves safety when motors are updated in loops but is
// disabled here because motor updates are not looped in this autonomous mode.
m_robotDrive.SetSafetyEnabled(false);
if (autoSelected == kAutoNameCustom) {
// Custom Auto goes here
std::cout << "Running custom Autonomous" << std::endl;
// Spin at half speed for two seconds
m_robotDrive.ArcadeDrive(0.0, 0.5);
frc::Wait(2.0);
// Stop robot
m_robotDrive.ArcadeDrive(0.0, 0.0);
} else {
// Default Auto goes here
std::cout << "Running default Autonomous" << std::endl;
// Drive forwards at half speed for two seconds
m_robotDrive.ArcadeDrive(-0.5, 0.0);
frc::Wait(2.0);
// Stop robot
m_robotDrive.ArcadeDrive(0.0, 0.0);
}
}
/**
* Runs the motors with arcade steering.
*/
void Robot::OperatorControl() {
m_robotDrive.SetSafetyEnabled(true);
while (IsOperatorControl() && IsEnabled()) {
// Drive with arcade style (use right stick)
m_robotDrive.ArcadeDrive(-m_stick.GetY(), m_stick.GetX());
// The motors will be updated every 5ms
frc::Wait(0.005);
}
}
/**
* Runs during test mode
*/
void Robot::Test() {}
#ifndef RUNNING_FRC_TESTS
int main() { return frc::StartRobot<Robot>(); }
#endif
| 32.989247
| 80
| 0.650587
|
balupillai
|
0638e398efc5a165f675d66a600f7203bbdcafee
| 1,304
|
cpp
|
C++
|
cppcheck/data/c_files/82.cpp
|
awsm-research/LineVul
|
246baf18c1932094564a10c9b81efb21914b2978
|
[
"MIT"
] | 2
|
2022-03-23T12:16:20.000Z
|
2022-03-31T06:19:40.000Z
|
cppcheck/data/c_files/82.cpp
|
awsm-research/LineVul
|
246baf18c1932094564a10c9b81efb21914b2978
|
[
"MIT"
] | null | null | null |
cppcheck/data/c_files/82.cpp
|
awsm-research/LineVul
|
246baf18c1932094564a10c9b81efb21914b2978
|
[
"MIT"
] | null | null | null |
status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (!mTimeToSample.empty() || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
// Expected version = 0, flags = 0.
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
// Choose this bound because
// 1) 2 * sizeof(uint32_t) is the amount of memory needed for one
// time-to-sample entry in the time-to-sample table.
// 2) mTimeToSampleCount is the number of entries of the time-to-sample
// table.
// 3) We hope that the table size does not exceed UINT32_MAX.
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
// Note: At this point, we know that mTimeToSampleCount * 2 will not
// overflow because of the above condition.
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
return OK;
}
| 28.347826
| 71
| 0.721626
|
awsm-research
|
063c6beca76fd6308e9eabe47e48eaa887948f89
| 6,980
|
cpp
|
C++
|
apps/enumeration/numericalSemigroups/hivert.cpp
|
ruairidhm98/YewPar
|
dfcc204a308232ceca3223252f3a1b4a2f6f42f6
|
[
"MIT"
] | null | null | null |
apps/enumeration/numericalSemigroups/hivert.cpp
|
ruairidhm98/YewPar
|
dfcc204a308232ceca3223252f3a1b4a2f6f42f6
|
[
"MIT"
] | null | null | null |
apps/enumeration/numericalSemigroups/hivert.cpp
|
ruairidhm98/YewPar
|
dfcc204a308232ceca3223252f3a1b4a2f6f42f6
|
[
"MIT"
] | null | null | null |
/* Original Numerical Semigroups Code by Florent Hivert: https://www.lri.fr/~hivert/
Link: https://github.com/hivert/NumericMonoid/blob/master/src/Cilk++/monoid.hpp
*/
#include <hpx/hpx_init.hpp>
#include <hpx/include/iostreams.hpp>
#include <vector>
#include <chrono>
#include "YewPar.hpp"
#include "skeletons/Seq.hpp"
#include "skeletons/DepthBounded.hpp"
#include "skeletons/StackStealing.hpp"
#include "skeletons/Budget.hpp"
#include "monoid.hpp"
// Numerical Semigroups don't have a space
struct Empty {};
struct NodeGen : YewPar::NodeGenerator<Monoid, Empty> {
Monoid group;
generator_iter<CHILDREN> it;
NodeGen(const Empty &, const Monoid & s) : group(s), it(generator_iter<CHILDREN>(s)){
this->numChildren = it.count(group);
it.move_next(group); // Original code skips begin
}
Monoid next() override {
auto res = remove_generator(group, it.get_gen());
it.move_next(group);
return res;
}
};
int hpx_main(boost::program_options::variables_map & opts) {
auto spawnDepth = opts["spawn-depth"].as<unsigned>();
auto maxDepth = opts["genus"].as<unsigned>();
auto skeleton = opts["skeleton"].as<std::string>();
//auto stealAll = opts["stealall"].as<bool>();
Monoid root;
init_full_N(root);
auto start_time = std::chrono::steady_clock::now();
std::vector<std::uint64_t> counts;
if (skeleton == "depthbounded") {
YewPar::Skeletons::API::Params<> searchParameters;
searchParameters.maxDepth = maxDepth;
searchParameters.spawnDepth = spawnDepth;
counts = YewPar::Skeletons::DepthBounded<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (skeleton == "stacksteal"){
YewPar::Skeletons::API::Params<> searchParameters;
searchParameters.maxDepth = maxDepth;
searchParameters.stealAll = static_cast<bool>(opts.count("chunked"));
// EXTENSION
if (opts.count("nodes")) {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::NodeCounts,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("backtracks")) {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Backtracks,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("regularity")) {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Regularity,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else {
counts = YewPar::Skeletons::StackStealing<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
}
// END EXTENSION
} else if (skeleton == "budget"){
YewPar::Skeletons::API::Params<> searchParameters;
searchParameters.backtrackBudget = opts["backtrack-budget"].as<unsigned>();
searchParameters.maxDepth = maxDepth;
// EXTENSION
if (opts.count("nodes")) {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::NodeCounts,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("backtracks")) {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Backtracks,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else if (opts.count("regularity")) {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::Regularity,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
} else {
counts = YewPar::Skeletons::Budget<NodeGen,
YewPar::Skeletons::API::CountNodes,
YewPar::Skeletons::API::DepthLimited>
::search(Empty(), root, searchParameters);
}
// END EXTENSION
} else {
hpx::cout << "Invalid skeleton type: " << skeleton << hpx::endl;
return hpx::finalize();
}
auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - start_time);
hpx::cout << "Results Table: " << hpx::endl;
for (auto i = 0; i <= maxDepth; ++i) {
hpx::cout << i << ": " << counts[i] << hpx::endl;
}
hpx::cout << "=====" << hpx::endl;
hpx::cout << "cpu = " << overall_time.count() << hpx::endl;
return hpx::finalize();
}
int main(int argc, char* argv[]) {
boost::program_options::options_description
desc_commandline("Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()
( "skeleton",
boost::program_options::value<std::string>()->default_value("seq"),
"Which skeleton to use: seq, depthbound, stacksteal, or budget"
)
( "spawn-depth,d",
boost::program_options::value<unsigned>()->default_value(0),
"Depth in the tree to spawn until (for parallel skeletons only)"
)
( "genus,g",
boost::program_options::value<unsigned>()->default_value(0),
"Depth in the tree to count until"
)
( "backtrack-budget,b",
boost::program_options::value<unsigned>()->default_value(500),
"Number of backtracks before spawning work"
)
( "verbose,v",
boost::program_options::value<bool>()->default_value(false),
"Enable verbose output"
)
("chunked", "Use chunking with stack stealing")
// EXTENSION
("backtracks", "Collect the backtracks metric")
("nodes", "Collect the backtracks metric")
("regularity", "Collect the backtracks metric");
// END EXTENSION
YewPar::registerPerformanceCounters();
return hpx::init(desc_commandline, argc, argv);
}
| 40.581395
| 87
| 0.571777
|
ruairidhm98
|
063dc7485b02ff563021ac01662259de76748e96
| 3,180
|
cpp
|
C++
|
mcommon/ui/ui_manager.cpp
|
cmaughan/mgfx
|
488453333f23b38b22ba06b984615a8069dadcbf
|
[
"MIT"
] | 36
|
2017-03-27T16:57:47.000Z
|
2022-01-12T04:17:55.000Z
|
mcommon/ui/ui_manager.cpp
|
cmaughan/mgfx
|
488453333f23b38b22ba06b984615a8069dadcbf
|
[
"MIT"
] | 5
|
2017-03-04T12:13:54.000Z
|
2017-03-26T21:55:08.000Z
|
mcommon/ui/ui_manager.cpp
|
cmaughan/mgfx
|
488453333f23b38b22ba06b984615a8069dadcbf
|
[
"MIT"
] | 7
|
2017-03-04T11:01:44.000Z
|
2018-08-28T09:25:47.000Z
|
#include "mcommon.h"
#include "ui_manager.h"
// Statics
uint64_t UIMessage::CurrentID = 1;
namespace
{
uint64_t InvalidMessageID = 0;
}
void UIMessage::Log()
{
/* uint32_t level = easyloggingERROR;
if (m_type & MessageType::Warning)
{
level = WARNING;
}
*/
std::ostringstream str;
try
{
if (!m_file.empty())
{
str << m_file.string();
}
}
catch (fs::filesystem_error&)
{
// Ignore file errors
}
if (m_line != -1)
{
str << "(" << m_line;
if (m_columnRange.start != -1)
{
str << "," << m_columnRange.start;
if (m_columnRange.end != -1)
{
str << "-" << m_columnRange.end;
}
}
str << "): ";
}
else
{
// Just a file, no line
if (!m_file.empty())
{
str << ": ";
}
}
str << m_message;
LOG(INFO) << str.str();
}
UIManager::UIManager()
{
}
UIManager& UIManager::Instance()
{
static UIManager manager;
return manager;
}
uint64_t UIManager::AddMessage(uint32_t type, const std::string& message, const fs::path& file, int32_t line, const ColumnRange& column)
{
auto spMessage = std::make_shared<UIMessage>(type, message, file, line, column);
spMessage->Log();
if (type & MessageType::Task ||
!file.empty())
{
m_taskMessages[spMessage->m_id] = spMessage;
}
if (!file.empty())
{
m_fileMessages[spMessage->m_file].push_back(spMessage->m_id);
}
if (type & MessageType::System)
{
SDL_MessageBoxButtonData button;
button.flags = SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT;
button.buttonid = 0;
button.text = "OK";
SDL_MessageBoxData mbData;
mbData.buttons = &button;
mbData.colorScheme = nullptr;
if (type & MessageType::Error)
{
mbData.flags = SDL_MessageBoxFlags::SDL_MESSAGEBOX_ERROR;
mbData.title = "Error";
}
else if (type & MessageType::Warning)
{
mbData.flags = SDL_MessageBoxFlags::SDL_MESSAGEBOX_WARNING;
mbData.title = "Warning";
}
else if (type & MessageType::Info)
{
mbData.flags = SDL_MessageBoxFlags::SDL_MESSAGEBOX_INFORMATION;
mbData.title = "Information";
}
mbData.message = spMessage->m_message.c_str();
mbData.numbuttons = 1;
mbData.window = nullptr;
int buttonID = 0;
SDL_ShowMessageBox(&mbData, &buttonID);
}
return spMessage->m_id;
}
// Remove a message for a given ID
void UIManager::RemoveMessage(uint64_t id)
{
auto itrFound = m_taskMessages.find(id);
if (itrFound != m_taskMessages.end())
{
if (!itrFound->second->m_file.empty())
{
m_fileMessages.erase(itrFound->second->m_file);
}
}
}
// Remove all messages associated with a file
void UIManager::ClearFileMessages(fs::path path)
{
while(!m_fileMessages[path].empty())
{
RemoveMessage(m_fileMessages[path][0]);
}
}
| 22.553191
| 136
| 0.555031
|
cmaughan
|
064065e6ba627b73355756f7706d3276ca4312ff
| 2,602
|
hpp
|
C++
|
Simulator/includes/BitMaskEnums.hpp
|
lilggamegenius/M68KSimulator
|
af22bde681c11b0a8ee6fa4692be969566037926
|
[
"MIT"
] | null | null | null |
Simulator/includes/BitMaskEnums.hpp
|
lilggamegenius/M68KSimulator
|
af22bde681c11b0a8ee6fa4692be969566037926
|
[
"MIT"
] | null | null | null |
Simulator/includes/BitMaskEnums.hpp
|
lilggamegenius/M68KSimulator
|
af22bde681c11b0a8ee6fa4692be969566037926
|
[
"MIT"
] | null | null | null |
//
// Created by ggonz on 11/22/2021.
//
#pragma once
namespace M68K::Opcodes{
template<typename Enum>
struct EnableBitMaskOperators {
static const bool enable = false;
};
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator|(Enum lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
static_cast<underlying>(lhs) |
static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator&(Enum lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
static_cast<underlying>(lhs) &
static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator^(Enum lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
static_cast<underlying>(lhs) ^
static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
operator~(Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
return static_cast<Enum> (
~static_cast<underlying>(rhs)
);
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type &
operator|=(Enum &lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
lhs = static_cast<Enum> (
static_cast<underlying>(lhs) |
static_cast<underlying>(rhs)
);
return lhs;
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type &
operator&=(Enum &lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
lhs = static_cast<Enum> (
static_cast<underlying>(lhs) &
static_cast<underlying>(rhs)
);
return lhs;
}
template<typename Enum>
typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type &
operator^=(Enum &lhs, Enum rhs) {
using underlying = typename std::underlying_type<Enum>::type;
lhs = static_cast<Enum> (
static_cast<underlying>(lhs) ^
static_cast<underlying>(rhs)
);
return lhs;
}
constexpr int bit(int index) {
if (index == 0) return 0;
return 1 << (index - 1);
}
#define ENABLE_BITMASK_OPERATORS(x) \
template<> \
struct EnableBitMaskOperators<x> \
{ \
static const bool enable = true; \
};
}
| 26.02
| 76
| 0.691391
|
lilggamegenius
|
06471850e2f566be10650a5176216815fb6e0acc
| 128
|
cpp
|
C++
|
1d/kill_waw_scalar/main.cpp
|
realincubus/clang_plugin_tests
|
018e22f37baaa7c072de8d455ad16057c953fd96
|
[
"MIT"
] | null | null | null |
1d/kill_waw_scalar/main.cpp
|
realincubus/clang_plugin_tests
|
018e22f37baaa7c072de8d455ad16057c953fd96
|
[
"MIT"
] | null | null | null |
1d/kill_waw_scalar/main.cpp
|
realincubus/clang_plugin_tests
|
018e22f37baaa7c072de8d455ad16057c953fd96
|
[
"MIT"
] | null | null | null |
int main(int argc, char** argv){
for (int i = 0; i < 100; ++i){
double x;
x = 0;
}
return 0;
}
| 9.846154
| 34
| 0.398438
|
realincubus
|
06478b1e2d9c4788f6910906e30f5f34f4c2ce66
| 552
|
cpp
|
C++
|
Cpp/298_binary_tree_longest_consecutive_sequence/solution.cpp
|
zszyellow/leetcode
|
2ef6be04c3008068f8116bf28d70586e613a48c2
|
[
"MIT"
] | 1
|
2015-12-19T23:05:35.000Z
|
2015-12-19T23:05:35.000Z
|
Cpp/298_binary_tree_longest_consecutive_sequence/solution.cpp
|
zszyellow/leetcode
|
2ef6be04c3008068f8116bf28d70586e613a48c2
|
[
"MIT"
] | null | null | null |
Cpp/298_binary_tree_longest_consecutive_sequence/solution.cpp
|
zszyellow/leetcode
|
2ef6be04c3008068f8116bf28d70586e613a48c2
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestConsecutive(TreeNode* root) {
return search(root, NULL, 0);
}
int search(TreeNode *root, TreeNode *parent, int len) {
if (!root) return len;
len = (parent && root->val == parent->val + 1) ? len+1 : 1;
return max(len, max(search(root->left, root, len), search(root->right, root, len)));
}
};
| 25.090909
| 88
| 0.586957
|
zszyellow
|
0647d760d8c25460239aa4c791a20256d53410ee
| 3,694
|
hh
|
C++
|
net.ssa/xrLC/OpenMesh/Core/Utils/Noncopyable.hh
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
xrLC/OpenMesh/Core/Utils/Noncopyable.hh
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | null | null | null |
xrLC/OpenMesh/Core/Utils/Noncopyable.hh
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
//=============================================================================
//
// OpenMesh
// Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen
// www.openmesh.org
//
//-----------------------------------------------------------------------------
//
// License
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library General Public License as published
// by the Free Software Foundation, version 2.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//-----------------------------------------------------------------------------
//
// $Revision: 1.4 $
// $Date: 2003/11/14 14:03:25 $
//
//=============================================================================
//=============================================================================
//
// Implements the Non-Copyable metapher
//
//=============================================================================
#ifndef OPENMESH_NONCOPYABLE_HH
#define OPENMESH_NONCOPYABLE_HH
//-----------------------------------------------------------------------------
#include <OpenMesh/Core/System/config.h>
//-----------------------------------------------------------------------------
namespace OpenMesh {
namespace Utils {
//-----------------------------------------------------------------------------
/** This class demonstrates the non copyable idiom. In some cases it is
important an object can't be copied. Deriving from Noncopyable makes sure
all relevant constructor and operators are made inaccessable, for public
AND derived classes.
**/
class Noncopyable
{
public:
Noncopyable() { }
private:
/// Prevent access to copy constructor
Noncopyable( const Noncopyable& );
/// Prevent access to assignment operator
const Noncopyable& operator=( const Noncopyable& );
};
//=============================================================================
} // namespace Utils
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_NONCOPYABLE_HH
//=============================================================================
| 47.974026
| 80
| 0.319708
|
ixray-team
|
064e9fd8c85114ba9966dba4b6453fda5a1af84f
| 49,053
|
cpp
|
C++
|
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwpipelinebuilder.cpp
|
nsivov/wpf
|
d36941860f05dd7a09008e99d1bcd635b0a69fdb
|
[
"MIT"
] | 2
|
2020-05-18T17:00:43.000Z
|
2021-12-01T10:00:29.000Z
|
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwpipelinebuilder.cpp
|
nsivov/wpf
|
d36941860f05dd7a09008e99d1bcd635b0a69fdb
|
[
"MIT"
] | 5
|
2020-05-05T08:05:01.000Z
|
2021-12-11T21:35:37.000Z
|
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/hwpipelinebuilder.cpp
|
nsivov/wpf
|
d36941860f05dd7a09008e99d1bcd635b0a69fdb
|
[
"MIT"
] | 4
|
2020-05-04T06:43:25.000Z
|
2022-02-20T12:02:50.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_d3d
// $Keywords:
//
// $Description:
// Contains implementation for CHwPipelineBuilder class.
//
// $ENDTAG
//
//------------------------------------------------------------------------------
#include "precomp.hpp"
//+-----------------------------------------------------------------------------
//
// Table:
// sc_PipeOpProperties
//
// Synopsis:
// Table of HwBlendOp properties
//
//------------------------------------------------------------------------------
static const
struct BlendOperationProperties {
bool AllowsAlphaMultiplyInEarlierStage;
} sc_BlendOpProperties[] =
{ // HBO_SelectSource
{
/* AllowsAlphaMultiplyInEarlierStage */ false
},
// HBO_Multiply
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_SelectSourceColorIgnoreAlpha
{
/* AllowsAlphaMultiplyInEarlierStage */ false
},
// HBO_MultiplyColorIgnoreAlpha
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_BumpMap
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_MultiplyByAlpha
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
// HBO_MultiplyAlphaOnly
{
/* AllowsAlphaMultiplyInEarlierStage */ true
},
};
C_ASSERT(ARRAYSIZE(sc_BlendOpProperties)==HBO_Total);
//+-----------------------------------------------------------------------------
//
// Class:
// CHwPipelineBuilder
//
// Synopsis:
// Helper class for CHwPipeline that does the actual construction of the
// pipeline and to which other components interface
//
//------------------------------------------------------------------------------
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Builder
//
// Synopsis:
// ctor
//
//------------------------------------------------------------------------------
CHwPipelineBuilder::CHwPipelineBuilder(
__in_ecount(1) CHwPipeline * const pHP,
HwPipeline::Type oType
)
: m_pHP(pHP),
m_oPipelineType(oType)
{
Assert(pHP);
m_iCurrentSampler = INVALID_PIPELINE_SAMPLER;
m_iCurrentStage = INVALID_PIPELINE_STAGE;
m_mvfIn = MILVFAttrNone;
m_mvfGenerated = MILVFAttrNone;
m_fAntiAliasUsed = false;
m_eAlphaMultiplyOp = HBO_Nop;
m_iAlphaMultiplyOkayAtItem = INVALID_PIPELINE_STAGE;
m_iLastAlphaScalableItem = INVALID_PIPELINE_ITEM;
m_iAntiAliasingPiggybackedByItem = INVALID_PIPELINE_ITEM;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::InitializePipelineMembers
//
// Synopsis:
// Figure out the alpha multiply operation and obtain vertex info.
//
void
CHwPipelineBuilder::InitializePipelineMembers(
MilCompositingMode::Enum eCompositingMode,
__in_ecount(1) IGeometryGenerator const *pIGeometryGenerator
)
{
Assert(m_iCurrentSampler == INVALID_PIPELINE_SAMPLER);
Assert(m_iCurrentStage == INVALID_PIPELINE_STAGE);
Assert(m_iAlphaMultiplyOkayAtItem == INVALID_PIPELINE_STAGE);
Assert(m_iLastAlphaScalableItem == INVALID_PIPELINE_STAGE);
if (eCompositingMode == MilCompositingMode::SourceOverNonPremultiplied ||
eCompositingMode == MilCompositingMode::SourceInverseAlphaOverNonPremultiplied)
{
m_eAlphaMultiplyOp = HBO_MultiplyAlphaOnly;
}
else
{
m_eAlphaMultiplyOp = HBO_Multiply;
}
pIGeometryGenerator->GetPerVertexDataType(
OUT m_mvfIn
);
m_mvfAvailable = MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrSpecular | MILVFAttrUV4;
m_mvfAvailable &= ~m_mvfIn;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::SendPipelineOperations
//
// Synopsis:
// Construct a full rendering pipeline for the given context from scratch
//
HRESULT
CHwPipelineBuilder::SendPipelineOperations(
__inout_ecount(1) IHwPrimaryColorSource *pIPCS,
__in_ecount_opt(1) const IMILEffectList *pIEffects,
__in_ecount(1) const CHwBrushContext *pEffectContext,
__inout_ecount(1) IGeometryGenerator *pIGeometryGenerator
)
{
HRESULT hr = S_OK;
// Determine incoming per vertex data included with geometry.
// Request primary color source to send primary rendering operations
IFC(pIPCS->SendOperations(this));
// Setup effects operations if any
if (pIEffects)
{
IFC(ProcessEffectList(
pIEffects,
pEffectContext
));
}
IFC(pIGeometryGenerator->SendGeometryModifiers(this));
IFC(pIGeometryGenerator->SendLighting(this));
// Setup operations to handle clipping
IFC(ProcessClip());
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Set_BumpMap
//
// Synopsis:
// Take the given color source and set it as a bump map for the first
// texture color source
//
// This call must be followed by a Set_Texture call specifying the first
// real color source.
//
HRESULT
CHwPipelineBuilder::Set_BumpMap(
__in_ecount(1) CHwTexturedColorSource *pBumpMap
)
{
HRESULT hr = S_OK;
// Parameter Assertions
Assert(pBumpMap->GetSourceType() != CHwColorSource::Constant);
IFC(E_NOTIMPL);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Mul_AlphaMask
//
// Synopsis:
// Add a blend operation that uses the given color source's alpha
// components to scale previous rendering results
//
HRESULT
CHwPipelineBuilder::Mul_AlphaMask(
__in_ecount(1) CHwTexturedColorSource *pAlphaMaskColorSource
)
{
HRESULT hr = S_OK;
IFC(E_NOTIMPL);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessClip
//
// Synopsis:
// Set up clipping operations and/or resources
//
HRESULT
CHwPipelineBuilder::ProcessClip(
)
{
HRESULT hr = S_OK;
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessEffectList
//
// Synopsis:
// Read the effect list and add pipeline operations for each one
//
// This method and the ProcessXxxEffect helper methods make up the logical
// Hardware Effects Processor component.
//
// Responsibilities:
// - Decode effects list to create color sources and specify operation
// needed to pipeline
//
// Not responsible for:
// - Determining operation order or combining operations
//
// Inputs required:
// - Effects list
// - Pipeline builder object (this)
//
HRESULT
CHwPipelineBuilder::ProcessEffectList(
__in_ecount(1) const IMILEffectList *pIEffects,
__in_ecount(1) const CHwBrushContext *pEffectContext
)
{
HRESULT hr = S_OK;
UINT cEntries = 0;
// Get the count of the transform blocks in the effect object.
IFC(pIEffects->GetCount(&cEntries));
// Handle only alpha effects
for (UINT uIndex = 0; uIndex < cEntries; uIndex++)
{
CLSID clsid;
UINT cbSize;
UINT cResources;
IFC(pIEffects->GetCLSID(uIndex, &clsid));
IFC(pIEffects->GetParameterSize(uIndex, &cbSize));
IFC(pIEffects->GetResourceCount(uIndex, &cResources));
if (clsid == CLSID_MILEffectAlphaScale)
{
IFC(ProcessAlphaScaleEffect(pIEffects, uIndex, cbSize, cResources));
}
else if (clsid == CLSID_MILEffectAlphaMask)
{
IFC(ProcessAlphaMaskEffect(pEffectContext, pIEffects, uIndex, cbSize, cResources));
}
else
{
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessAlphaScaleEffect
//
// Synopsis:
// Decode an alpha scale effect and add to pipeline
//
HRESULT
CHwPipelineBuilder::ProcessAlphaScaleEffect(
__in_ecount(1) const IMILEffectList *pIEffects,
UINT uIndex,
UINT cbSize,
UINT cResources
)
{
HRESULT hr = S_OK;
CHwConstantAlphaScalableColorSource *pNewAlphaColorSource = NULL;
AlphaScaleParams alphaScale;
// check the parameter size
if (cbSize != sizeof(alphaScale))
{
AssertMsg(FALSE, "AlphaScale parameter has unexpected size.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
else if (cResources != 0)
{
AssertMsg(FALSE, "AlphaScale has unexpected number of resources.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
IFC(pIEffects->GetParameters(uIndex, cbSize, &alphaScale));
if (0.0f > alphaScale.scale || alphaScale.scale > 1.0f)
{
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
else
{
IFC(CHwConstantAlphaScalableColorSource::Create(
m_pHP->m_pDevice,
alphaScale.scale,
NULL,
&m_pHP->m_dbScratch,
&pNewAlphaColorSource
));
IFC(Mul_ConstAlpha(pNewAlphaColorSource));
}
Cleanup:
ReleaseInterfaceNoNULL(pNewAlphaColorSource);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ProcessAlphaMaskEffect
//
// Synopsis:
// Decode an alpha mask effect and add to pipeline
//
HRESULT
CHwPipelineBuilder::ProcessAlphaMaskEffect(
__in_ecount(1) const CHwBrushContext *pEffectContext,
__in_ecount(1) const IMILEffectList *pIEffects,
UINT uIndex,
UINT cbSize,
UINT cResources
)
{
HRESULT hr = S_OK;
AlphaMaskParams alphaMaskParams;
IUnknown *pIUnknown = NULL;
IWGXBitmapSource *pMaskBitmap = NULL;
CHwTexturedColorSource *pMaskColorSource = NULL;
CMultiOutSpaceMatrix<CoordinateSpace::RealizationSampling> matBitmapToIdealRealization;
CDelayComputedBounds<CoordinateSpace::RealizationSampling> rcRealizationBounds;
BitmapToXSpaceTransform matRealizationToGivenSampleSpace;
// check the parameter size
if (cbSize != sizeof(alphaMaskParams))
{
AssertMsg(FALSE, "AlphaMask parameter has unexpected size.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
else if (cResources != 1)
{
AssertMsg(FALSE, "AlphaMask has unexpected number of resources.");
IFC(WGXERR_UNSUPPORTED_OPERATION);
}
IFC(pIEffects->GetParameters(uIndex, cbSize, &alphaMaskParams));
IFC(pIEffects->GetResources(uIndex, cResources, &pIUnknown));
IFC(pIUnknown->QueryInterface(
IID_IWGXBitmapSource,
reinterpret_cast<void **>(&pMaskBitmap)));
pEffectContext->GetRealizationBoundsAndTransforms(
CMatrix<CoordinateSpace::RealizationSampling,CoordinateSpace::Effect>::ReinterpretBase(alphaMaskParams.matTransform),
OUT matBitmapToIdealRealization,
OUT matRealizationToGivenSampleSpace,
OUT rcRealizationBounds
);
{
CHwBitmapColorSource::CacheContextParameters oContextCacheParameters(
MilBitmapInterpolationMode::Linear,
pEffectContext->GetContextStatePtr()->RenderState->PrefilterEnable,
pEffectContext->GetFormat(),
MilBitmapWrapMode::Extend
);
IFC(CHwBitmapColorSource::DeriveFromBitmapAndContext(
m_pHP->m_pDevice,
pMaskBitmap,
NULL,
NULL,
rcRealizationBounds,
&matBitmapToIdealRealization,
&matRealizationToGivenSampleSpace,
pEffectContext->GetContextStatePtr()->RenderState->PrefilterThreshold,
pEffectContext->CanFallback(),
NULL,
oContextCacheParameters,
&pMaskColorSource
));
IFC(Mul_AlphaMask(pMaskColorSource));
}
Cleanup:
ReleaseInterfaceNoNULL(pIUnknown);
ReleaseInterfaceNoNULL(pMaskBitmap);
ReleaseInterfaceNoNULL(pMaskColorSource);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::ChooseVertexBuilder
//
// Synopsis:
// Create a vertex builder for the current pipeline
//
HRESULT
CHwPipelineBuilder::ChooseVertexBuilder(
__deref_out_ecount(1) CHwVertexBuffer::Builder **ppVertexBuilder
)
{
HRESULT hr = S_OK;
MilVertexFormatAttribute mvfaAALocation = MILVFAttrNone;
if (m_fAntiAliasUsed)
{
mvfaAALocation = HWPIPELINE_ANTIALIAS_LOCATION;
}
Assert((m_mvfIn & m_mvfGenerated) == 0);
IFC(CHwVertexBuffer::Builder::Create(
m_mvfIn,
m_mvfIn | m_mvfGenerated,
mvfaAALocation,
m_pHP,
m_pHP->m_pDevice,
&m_pHP->m_dbScratch,
ppVertexBuilder
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::TryToMultiplyConstantAlphaToExistingStage
//
// Synopsis:
// Tries to find an existing stage it can use to drop it's alpha multiply
// into. Should work on both shader and fixed function pipelines.
//
//------------------------------------------------------------------------------
bool
CHwPipelineBuilder::TryToMultiplyConstantAlphaToExistingStage(
__in_ecount(1) const CHwConstantAlphaColorSource *pAlphaColorSource
)
{
HRESULT hr = S_OK;
float flAlpha = pAlphaColorSource->GetAlpha();
CHwConstantAlphaScalableColorSource *pScalableAlphaSource = NULL;
bool fStageToMultiplyFound = false;
INT iItemCount = static_cast<INT>(m_pHP->m_rgItem.GetCount());
// Parameter Assertions
Assert(flAlpha >= 0.0f);
Assert(flAlpha <= 1.0f);
// Member Assertions
// There should be at least one stage
Assert(iItemCount > 0);
Assert(GetNumReservedStages() > 0);
// An alpha scale of 1.0 is a nop; do nothing
if (flAlpha == 1.0f)
{
fStageToMultiplyFound = true;
goto Cleanup;
}
int iLastAlphaScalableItem, iItemAvailableForAlphaMultiply;
iLastAlphaScalableItem = GetLastAlphaScalableItem();
iItemAvailableForAlphaMultiply = GetEarliestItemAvailableForAlphaMultiply();
// We can add logic to recognize that an alpha scale of 0 would give us a
// completely transparent result and then "compress" previous stages.
// Check for existing stage at which constant alpha scale may be applied
if (iItemAvailableForAlphaMultiply < iItemCount)
{
// Check for existing color source that will handle the alpha scale
if (iLastAlphaScalableItem >= iItemAvailableForAlphaMultiply)
{
Assert(m_pHP->m_rgItem[iLastAlphaScalableItem].pHwColorSource);
// Future Consideration: Shader pipe issue
// The if statement around the Assert is to prevent the Assert from
// firing on the shader path because the shader path does not set
// eBlendOp. We can remove this if in the future when the shader
// shader path uses the blend args.
HwBlendOp hwBlendOp = m_pHP->m_rgItem[iLastAlphaScalableItem].eBlendOp;
if (hwBlendOp == HBO_MultiplyAlphaOnly || hwBlendOp == HBO_Multiply)
{
Assert(hwBlendOp == m_eAlphaMultiplyOp);
}
// Multiply with new scale factor
m_pHP->m_rgItem[iLastAlphaScalableItem].pHwColorSource->AlphaScale(flAlpha);
fStageToMultiplyFound = true;
}
else
{
//
// Check for existing color source that can be reused to handle the
// alpha scale. Alpha scale can be applied to any constant color
// source using the ConstantAlphaScalable class.
//
// The scale should technically come at the end of the current
// operations; so, try to get as close to the end as possible.
//
for (INT iLastConstant = iItemCount-1;
iLastConstant >= iItemAvailableForAlphaMultiply;
iLastConstant--)
{
CHwColorSource *pHCS =
m_pHP->m_rgItem[iLastConstant].pHwColorSource;
if (pHCS && (pHCS->GetSourceType() & CHwColorSource::Constant))
{
// The ConstantAlphaScalable class only supports
// HBO_Multiply because it assumes premulitplied colors come
// in and go out.
Assert(m_eAlphaMultiplyOp == HBO_Multiply);
//
// Inject an alpha scalable color source in place
// of the current constant color source.
//
IFC(CHwConstantAlphaScalableColorSource::Create(
m_pHP->m_pDevice,
flAlpha,
DYNCAST(CHwConstantColorSource, pHCS),
&m_pHP->m_dbScratch,
&pScalableAlphaSource
));
// Transfer pScalableAlphaSource reference
m_pHP->m_rgItem[iLastConstant].pHwColorSource =
pScalableAlphaSource;
pHCS->Release();
//
// Color Sources being added to a pipeline are
// required to have their mappings reset. This
// normally happens when items are added to the
// pipeline, but since this is replacing an item
// we need to call it ourselves.
//
pScalableAlphaSource->ResetForPipelineReuse();
pScalableAlphaSource = NULL;
// Remember this location now holds an
// alpha scalable color source
SetLastAlphaScalableStage(iLastConstant);
fStageToMultiplyFound = true;
break;
}
}
}
}
Cleanup:
ReleaseInterfaceNoNULL(pScalableAlphaSource);
//
// We only want to consider success if our HRESULT is S_OK.
//
return (hr == S_OK && fStageToMultiplyFound);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::CheckForBlendAlreadyPresentAtAALocation
//
// Synopsis:
// We may have already added a blend operation using the location we're
// going to generate anti-aliasing in. If this is the case we don't need
// to add another blend operation.
//
//------------------------------------------------------------------------------
HRESULT
CHwPipelineBuilder::CheckForBlendAlreadyPresentAtAALocation(
bool *pfNeedToAddAnotherStageToBlendAntiAliasing
)
{
HRESULT hr = S_OK;
INT iAAPiggybackItem = GetAAPiggybackItem();
*pfNeedToAddAnotherStageToBlendAntiAliasing = false;
//
// Validate that any AA piggybacking is okay. If first location (item)
// available for alpha multiply is greater than location of piggyback item,
// then piggybacking is not allowed.
//
// AA piggyback item is -1 when not set so that case will also be detected.
//
if (iAAPiggybackItem < GetEarliestItemAvailableForAlphaMultiply())
{
//
// Check if there was a piggyback item
//
if (iAAPiggybackItem != INVALID_PIPELINE_ITEM)
{
// Future Consideration: Find new attribute for AA piggybacker
// and modify pipeline item with new properties.
RIP("Fixed function pipeline does not expect invalid piggybacking");
IFC(WGXERR_NOTIMPLEMENTED);
}
*pfNeedToAddAnotherStageToBlendAntiAliasing = true;
}
else
{
Assert(GetGeneratedComponents() & MILVFAttrDiffuse);
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::SetupVertexBuilder
//
// Synopsis:
// Choose the appropriate vertex builder class for the pipeline that has
// just been set up and initialize the vertex builder
//
HRESULT
CHwPipelineBuilder::SetupVertexBuilder(
__deref_out_ecount(1) CHwVertexBuffer::Builder **ppVertexBuilder
)
{
HRESULT hr = S_OK;
// Select a vertex builder
IFC(ChooseVertexBuilder(ppVertexBuilder));
// Send vertex mappings for each color source
HwPipelineItem *pItem;
pItem = m_pHP->m_rgItem.GetDataBuffer();
CHwVertexBuffer::Builder *pVertexBuilder;
pVertexBuilder = *ppVertexBuilder;
if (VerticesArePreGenerated())
{
// Pass NULL builder to color source to indicate that vertices are
// pre-generated and should not be modified.
pVertexBuilder = NULL;
}
if (m_oPipelineType == HwPipeline::FixedFunction)
{
for (UINT uItem = 0; uItem < m_pHP->m_rgItem.GetCount(); uItem++, pItem++)
{
if (pItem->pHwColorSource)
{
IFC(pItem->pHwColorSource->SendVertexMapping(
pVertexBuilder,
pItem->mvfaSourceLocation
));
}
}
}
else
{
for (UINT uItem = 0; uItem < m_pHP->m_rgItem.GetCount(); uItem++, pItem++)
{
if (pItem->pHwColorSource && pItem->mvfaTextureCoordinates != MILVFAttrNone)
{
IFC(pItem->pHwColorSource->SendVertexMapping(
pVertexBuilder,
pItem->mvfaTextureCoordinates
));
}
}
}
// Let vertex builder know that is the end of the vertex mappings
IFC((*ppVertexBuilder)->FinalizeMappings());
Cleanup:
if (FAILED(hr))
{
delete *ppVertexBuilder;
*ppVertexBuilder = NULL;
}
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Mul_BlendColorsInternal
//
// Synopsis:
// Multiplies the pipeline by a set of blend colors.
//
//------------------------------------------------------------------------------
HRESULT
CHwPipelineBuilder::Mul_BlendColors(
__in_ecount(1) CHwColorComponentSource *pBlendColorSource
)
{
HRESULT hr = S_OK;
Assert(GetAvailableForReference() & MILVFAttrDiffuse);
Assert(GetAAPiggybackItem() < GetEarliestItemAvailableForAlphaMultiply());
IFC(Mul_BlendColorsInternal(
pBlendColorSource
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipelineBuilder::Set_AAColorSource
//
// Synopsis:
// Adds an antialiasing colorsource.
//
//------------------------------------------------------------------------------
HRESULT
CHwPipelineBuilder::Set_AAColorSource(
__in_ecount(1) CHwColorComponentSource *pAAColorSource
)
{
HRESULT hr = S_OK;
//
// Use Geometry Generator specified AA location (none, falloff, UV) to
// 1) Append blend operation as needed
// 2) Otherwise set proper indicators to vertex builder
//
Assert(pAAColorSource->GetComponentLocation() == CHwColorComponentSource::Diffuse);
bool fNeedToAddAnotherStageToBlendAntiAliasing = true;
IFC(CheckForBlendAlreadyPresentAtAALocation(
&fNeedToAddAnotherStageToBlendAntiAliasing
));
if (fNeedToAddAnotherStageToBlendAntiAliasing)
{
IFC(Mul_BlendColorsInternal(
pAAColorSource
));
}
m_fAntiAliasUsed = true;
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Builder
//
// Synopsis:
// Create the fixed function pipeline builder.
//
CHwFFPipelineBuilder::CHwFFPipelineBuilder(
__inout_ecount(1) CHwFFPipeline *pHP
)
: CHwPipelineBuilder(
pHP,
HwPipeline::FixedFunction
)
{
m_pHP = pHP;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Setup
//
// Synopsis:
// Setup the fixed function pipeline for rendering
//
HRESULT
CHwFFPipelineBuilder::Setup(
MilCompositingMode::Enum eCompositingMode,
__inout_ecount(1) IGeometryGenerator *pIGeometryGenerator,
__inout_ecount(1) IHwPrimaryColorSource *pIPCS,
__in_ecount_opt(1) const IMILEffectList *pIEffects,
__in_ecount(1) const CHwBrushContext *pEffectContext
)
{
HRESULT hr = S_OK;
CHwPipelineBuilder::InitializePipelineMembers(
eCompositingMode,
pIGeometryGenerator
);
IFC(CHwPipelineBuilder::SendPipelineOperations(
pIPCS,
pIEffects,
pEffectContext,
pIGeometryGenerator
));
FinalizeBlendOperations(
eCompositingMode
);
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipeline::FinalizeBlendOperations
//
// Synopsis:
// Examine the pipeline after all the basic operations have been added and
// make any adjustments to yield a valid pipeline
//
void
CHwFFPipelineBuilder::FinalizeBlendOperations(
MilCompositingMode::Enum eCompositingMode
)
{
//
// Assertions for the currently very limited pipeline
//
// Currently implemented pipeline operations are:
// Primary operation - from primary color source (required)
// Set_Constant
// or
// Set_Texture
//
// Secondary operations - from secondary color source (optional)
// Mul_ConstAlpha
//
// Tertiary operations
// SetupPerPrimitiveAntialiasingBlend (optional)
//
// There is always a primary operation so there should always be something
// in the pipeline
Assert(m_pHP->m_rgItem.GetCount() > 0);
Assert(m_mvfIn == MILVFAttrXY
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrUV1)
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrUV1)
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrUV1 | MILVFAttrUV2)
|| m_mvfIn == (MILVFAttrXYZ | MILVFAttrUV1 | MILVFAttrUV2));
#if DBG
MilVertexFormat mvfDbgUsed = GetAvailableForReference() | GetGeneratedComponents();
Assert(
// Set_Constant (+ Antialias)
(mvfDbgUsed == (MILVFAttrXY | MILVFAttrDiffuse))
// or Set_Texture
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrUV1))
// or Set_Texture + (Mul_ConstAlpha | Antialias)
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrDiffuse | MILVFAttrUV1))
|| (mvfDbgUsed == (MILVFAttrXYZ | MILVFAttrDiffuse | MILVFAttrUV1))
// or Set_Texture + Mul_AlphaMask (with texture coords)
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrUV1 | MILVFAttrUV2))
// or Set_Texture + Mul_AlphaMask (with texture coords) + Antialias
|| (mvfDbgUsed == (MILVFAttrXY | MILVFAttrDiffuse | MILVFAttrUV1 | MILVFAttrUV2))
);
#endif
// At least one stage is guaranteed by the primary color source
Assert(GetNumReservedStages() > 0);
Assert(GetNumReservedSamplers() >= 0);
if (GetNumReservedStages() == 1)
{
//
// There is only one pipeline operation- (coming from Set_Constant or Set_Texture)
//
Assert(m_pHP->m_rgItem[0].dwStage == 0);
if (m_pHP->m_rgItem[0].oBlendParams.hbaSrc1 == HBA_Texture)
{
Assert(m_pHP->m_rgItem[0].dwSampler == 0);
}
else
{
Assert(m_pHP->m_rgItem[0].dwSampler == INVALID_PIPELINE_SAMPLER);
}
Assert(m_pHP->m_rgItem[0].oBlendParams.hbaSrc2 == HBA_None);
Assert(m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSource
|| m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSourceColorIgnoreAlpha );
}
else
{
//
// There are multiple pipeline items- see if we can combine several
// color sources into the same stage
//
// This combination is much easier if we can assume that
// the pipeline items are all re-orderable
Assert(GetEarliestItemAvailableForAlphaMultiply() == 0);
// The combination is further simplified knowing that we only
// have two items to deal with
Assert(GetNumReservedStages() <= 3);
int iFirstNonTextureStage = INVALID_PIPELINE_STAGE;
#if DBG
int iDbgNumTexturesEncountered = 0;
#endif
//
// Verifying the pipeline and looking for opportunities to consolidate it.
//
// All items after the first stage are going to involve some sort of multiply, which
// is going to take the current value and multiply it with another argument.
//
// The first stage however, is going to be selecting one parameter. This gives us
// an opportunity to collapse one of the later stages into the first stage, taking it
// from:
//
// Stage diagram
// Before
// Stage 0 Stage N
// Input 1 texture Diffuse
// Input 2 irrelevant Current
// Blend op SelectSource (1) Multiply
//
// After
// Stage 0
// Input 1 Diffuse
// Input 2 Texture
// Blend op Multiply
//
// It's easier for us to collapse a non-texture argument, because we don't have to
// worry about setting another texture stage. So while we validate the pipeline
// we search for a non-texture argument.
//
// Future Consideration: Could do further consolidation if stage 0 = diffuse && stage 1 = texture
for (int iStage = 0; iStage < GetNumReservedStages(); iStage++)
{
HwPipelineItem const &curItem = m_pHP->m_rgItem[iStage];
if (iStage == 0)
{
//
// Our First stage should be selecting the source.
//
Assert( curItem.eBlendOp == HBO_SelectSource
|| curItem.eBlendOp == HBO_SelectSourceColorIgnoreAlpha
);
}
else
{
//
// All non-first stages should involve a multiply
//
Assert( curItem.eBlendOp == HBO_Multiply
|| curItem.eBlendOp == HBO_MultiplyAlphaOnly
|| curItem.eBlendOp == HBO_MultiplyColorIgnoreAlpha
|| curItem.eBlendOp == HBO_MultiplyByAlpha
);
Assert(curItem.oBlendParams.hbaSrc2 == HBA_Current);
}
if (curItem.oBlendParams.hbaSrc1 != HBA_Texture)
{
if (iFirstNonTextureStage == INVALID_PIPELINE_STAGE)
{
iFirstNonTextureStage = iStage;
}
Assert(curItem.oBlendParams.hbaSrc1 == HBA_Diffuse);
}
else
{
#if DBG
Assert(curItem.dwSampler == static_cast<DWORD>(iDbgNumTexturesEncountered));
iDbgNumTexturesEncountered++;
#endif
}
}
//
// If we found a non-texture stage we can combine it with the 1st ("select")
// stage.
//
if (iFirstNonTextureStage != INVALID_PIPELINE_STAGE)
{
HwBlendOp eNewBlendOp;
HwBlendArg eNewBlendArg1;
HwBlendArg eNewBlendArg2;
HwPipelineItem &oFirstItem = m_pHP->m_rgItem[0];
HwPipelineItem &oCollapsableItem = m_pHP->m_rgItem[iFirstNonTextureStage];
//
// We're taking the first stage from a select source to a multiply, so
// determine which kind of multiply we need to do.
//
if (oFirstItem.eBlendOp == HBO_SelectSourceColorIgnoreAlpha)
{
Assert(oCollapsableItem.eBlendOp == HBO_Multiply);
eNewBlendOp = HBO_MultiplyColorIgnoreAlpha;
}
else
{
eNewBlendOp = oCollapsableItem.eBlendOp;
}
eNewBlendArg1 = oCollapsableItem.oBlendParams.hbaSrc1;
eNewBlendArg2 = oFirstItem.oBlendParams.hbaSrc1;
oFirstItem.eBlendOp = eNewBlendOp;
oFirstItem.oBlendParams.hbaSrc1 = eNewBlendArg1;
oFirstItem.oBlendParams.hbaSrc2 = eNewBlendArg2;
oCollapsableItem.eBlendOp = HBO_Nop;
//
// Decrease the stage number since we are using one less stage now
//
for (UINT i = iFirstNonTextureStage; static_cast<INT>(i) < GetNumReservedStages(); i++)
{
m_pHP->m_rgItem[i].dwStage--;
}
DecrementNumStages();
}
}
//
// Fix-up the need of SelectTextureIgnoreAlpha to have white as diffuse color
// The vertex builder is required (expected) to have white as the
// default value if nothing else has been specified. We could
// eliminate that requirement by adding a new solid white color
// source to the pipe line item list.
//
if ( m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSourceColorIgnoreAlpha
&& m_pHP->m_rgItem[0].oBlendParams.hbaSrc1 == HBA_Texture
)
{
if (GetAvailableForGeneration() & MILVFAttrDiffuse)
{
//
// Make sure diffuse value gets set. No color source should try
// to use this location so it should default to solid white.
//
// We should only be here if we're rendering 2D aliased.
//
GenerateVertexAttribute(MILVFAttrDiffuse);
}
}
//
// Set first blend stage that should be disabled
//
m_pHP->m_dwFirstUnusedStage = GetNumReservedStages();
//
// Compute the final vertex attributes we must fill-in to send data to
// DrawPrimitive.
//
// We always leave Z test enabled so we must always specify Z in vertices.
//
if (GetAvailableForGeneration() & MILVFAttrZ)
{
GenerateVertexAttribute(MILVFAttrZ);
}
//
// Setup composition mode
//
// Source over without transparency is equivalent to source copy, but
// source copy is faster, so we check for it and promote the mode to
// sourcecopy.
//
if ( eCompositingMode == MilCompositingMode::SourceOver
&& !m_fAntiAliasUsed
&& m_pHP->m_dwFirstUnusedStage == 1
&& ( ( m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSource
&& m_pHP->m_rgItem[0].pHwColorSource->IsOpaque())
|| m_pHP->m_rgItem[0].eBlendOp == HBO_SelectSourceColorIgnoreAlpha)
)
{
eCompositingMode = MilCompositingMode::SourceCopy;
}
m_pHP->SetupCompositionMode(
eCompositingMode
);
return;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::AddPipelineItem
//
// Synopsis:
// Adds a new pipeline item to the pipeline
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::AddFFPipelineItem(
HwBlendOp eBlendOp,
HwBlendArg hbaSrc1,
HwBlendArg hbaSrc2,
MilVertexFormatAttribute mvfaSourceLocation,
__in_ecount_opt(1) CHwColorSource *pHwColorSource
)
{
HRESULT hr = S_OK;
// No-op is designed for use in and after finalize blend operations only
Assert(eBlendOp != HBO_Nop);
// If we not performing a blend, there is no need for src 2
if ( eBlendOp == HBO_SelectSource
|| eBlendOp == HBO_SelectSourceColorIgnoreAlpha)
{
Assert(hbaSrc2 == HBA_None);
}
// It is not possible to put two textures in one pipeline item
// so let us enforce a convention that textures go in src 1
Assert(hbaSrc2 != HBA_Texture);
HwPipelineItem *pItem = NULL;
IFC(m_pHP->AddPipelineItem(&pItem));
Assert(pItem);
pItem->dwStage = ReserveCurrentStage();
if (hbaSrc1 == HBA_Texture)
{
// samplers are only needed for textures
pItem->dwSampler = ReserveCurrentTextureSampler();
}
else
{
pItem->dwSampler = UINT_MAX; // No sampler
}
pItem->eBlendOp = eBlendOp;
pItem->oBlendParams.hbaSrc1 = hbaSrc1;
pItem->oBlendParams.hbaSrc2 = hbaSrc2;
// If the operation does not allow alpha multiply in earlier stage advance
// tracking marker to this item (independent of whether the color sources
// support alpha scaling.)
if (!sc_BlendOpProperties[eBlendOp].AllowsAlphaMultiplyInEarlierStage)
{
SetLastItemAsEarliestAvailableForAlphaMultiply();
}
// Assert that the vertex attribute is not in use OR that we have special
// case of reuse when the attribute is for texture and is already provided.
// Having a constant source that does not truly require particular
// coordinates is not good enough because the pipeline builder just isn't
// prepared for the situation, which will likely result in three texture
// stages and require TexCoordinateIndex different than stage.
Assert( (GetAvailableForGeneration() & mvfaSourceLocation)
|| (GetAvailableForReference() & mvfaSourceLocation)
);
if ( (HWPIPELINE_ANTIALIAS_LOCATION == mvfaSourceLocation)
// NULL pHwColorSource indicates addition of AA scale factor; so
// skip piggyback marking for it.
&& pHwColorSource
)
{
SetLastItemAsAAPiggyback();
}
if (GetAvailableForGeneration() & mvfaSourceLocation)
{
Assert(!(GetAvailableForReference() & mvfaSourceLocation));
GenerateVertexAttribute(mvfaSourceLocation);
}
pItem->mvfaSourceLocation = mvfaSourceLocation;
pItem->pHwColorSource = pHwColorSource;
// This Addref will be handled by the base pipeline builder
if (pHwColorSource)
{
pHwColorSource->AddRef();
pHwColorSource->ResetForPipelineReuse();
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Set_Constant
//
// Synopsis:
// Takes the given color source and sets it as the first color source for
// the hardware blending pipeline
//
HRESULT
CHwFFPipelineBuilder::Set_Constant(
__in_ecount(1) CHwConstantColorSource *pConstant
)
{
HRESULT hr = S_OK;
// Parameter Assertions
Assert(pConstant->GetSourceType() & CHwColorSource::Constant);
// Member Assertions
// There shouldn't be any items or stages yet
Assert(m_pHP->m_rgItem.GetCount() == 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() == INVALID_PIPELINE_ITEM);
Assert(GetNumReservedStages() == 0);
Assert(GetNumReservedSamplers() == 0);
MilVertexFormatAttribute mvfa;
HwBlendArg hba;
//
// Find an acceptable vertex field
//
if (GetAvailableForGeneration() & MILVFAttrDiffuse)
{
mvfa = MILVFAttrDiffuse;
hba = HBA_Diffuse;
}
else
{
//
// Future Consideration: Use a alpha scale texture stage instead.
//
// Setting the a texture stage to be an alpha scale value should be
// supported on all our hardware and should be more efficient than
// using a texture.
//
// Required for logic to work
Assert(GetAvailableForReference() & MILVFAttrUV1);
mvfa = MILVFAttrUV1;
hba = HBA_Texture;
}
//
// Add the first color source
//
IFC(AddFFPipelineItem(
HBO_SelectSource,
hba,
HBA_None,
mvfa,
pConstant
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Set_Texture
//
// Synopsis:
// Takes the given color source and sets it as the first color source for
// the hardware blending pipeline
//
// If it is to be bump mapped the bump map operation has to specified by a
// call to Set_BumpMap just before this call.
//
HRESULT
CHwFFPipelineBuilder::Set_Texture(
__in_ecount(1) CHwTexturedColorSource *pTexture
)
{
HRESULT hr = S_OK;
// Parameter Assertions
Assert(pTexture->GetSourceType() != CHwColorSource::Constant);
// Member Assertions
// There shouldn't be any items or stages yet
Assert(m_pHP->m_rgItem.GetCount() == 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() == INVALID_PIPELINE_ITEM);
Assert(GetNumReservedStages() == 0);
Assert(GetNumReservedSamplers() == 0);
//
// Add the first color source
//
//
// Future Consideration: Seperate IgnoreAlpha BlendOp into multiple items
//
// This is dangerous. Select Source Color Ignore Alpha says it's the first stage,
// but its texture states specify that it's going to grab alpha from current.
// This works because specifying current on stage 0 will draw from diffuse, and
// we make sure to always fill diffuse.
//
// If the pipeline supports more rendering operations especially ones that don't
// allow re-ordering of the stages, we may have to break
// HBO_SelectSourceColorIgnoreAlpha into more than one stage.
//
IFC(AddFFPipelineItem(
HBO_SelectSource,
HBA_Texture,
HBA_None,
MILVFAttrUV1,
pTexture
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Set_RadialGradient
//
// Synopsis:
// Not implemented in the fixed function pipeline
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::Set_RadialGradient(
__in_ecount(1) CHwRadialGradientColorSource *pRadialGradient
)
{
RRETURN(E_NOTIMPL);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwPipeline::FFBuilder::Mul_ConstAlpha
//
// Synopsis:
// Add a blend operation that scales all previous rendering by the given
// alpha value
//
// This operation may be added as a modifier to an existing color source or
// as an independent operation. If added via modification to an existing
// color source then the results of the pipeline should be respected just
// as if it were added as a new operation.
//
HRESULT
CHwFFPipelineBuilder::Mul_ConstAlpha(
CHwConstantAlphaColorSource *pAlphaColorSource
)
{
HRESULT hr = S_OK;
float flAlpha = pAlphaColorSource->GetAlpha();
// There should be at least one item that has marked available alpha mul
Assert(m_pHP->m_rgItem.GetCount() > 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() >= 0);
CHwConstantAlphaScalableColorSource *pScalableAlphaSource = NULL;
if (TryToMultiplyConstantAlphaToExistingStage(pAlphaColorSource))
{
//
// We've succeeded in multiplying the alpha color source to an existing
// stage, so early out.
//
goto Cleanup;
}
//
// There is no color source available to apply this scale to directly.
// Add an additional blending stage.
//
MilVertexFormatAttribute mvfa;
mvfa = MILVFAttrNone;
HwBlendArg hba;
hba = HBA_None;
//
// Find an acceptable vertex field
//
if (GetAvailableForGeneration() & MILVFAttrDiffuse)
{
mvfa = MILVFAttrDiffuse;
hba = HBA_Diffuse;
}
else if (GetAvailableForReference() & MILVFAttrUV1)
{
// Piggyback on a texture coordinate set that is already requested.
mvfa = MILVFAttrUV1;
hba = HBA_Texture;
}
else if (GetAvailableForGeneration() & MILVFAttrSpecular)
{
mvfa = MILVFAttrSpecular;
hba = HBA_Specular;
}
if (mvfa != MILVFAttrNone)
{
//
// Append alpha scale blend operation
//
IFC(CHwConstantAlphaScalableColorSource::Create(
m_pHP->m_pDevice,
flAlpha,
NULL, // No orignal color source
&m_pHP->m_dbScratch,
&pScalableAlphaSource
));
IFC(AddFFPipelineItem(
m_eAlphaMultiplyOp,
hba,
HBA_Current,
mvfa,
pScalableAlphaSource
));
// Remember this location holds an alpha scalable color source
SetLastItemAsAlphaScalable();
}
else
{
// No suitable vertex location could be found
IFC(E_NOTIMPL);
}
Cleanup:
ReleaseInterfaceNoNULL(pScalableAlphaSource);
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Mul_AlphaMask
//
// Synopsis:
//
HRESULT
CHwFFPipelineBuilder::Mul_AlphaMask(
__in_ecount(1) CHwTexturedColorSource *pAlphaMask
)
{
HRESULT hr = S_OK;
// There should be at least one item that has marked available alpha mul
Assert(m_pHP->m_rgItem.GetCount() > 0);
Assert(GetEarliestItemAvailableForAlphaMultiply() >= 0);
Assert( m_eAlphaMultiplyOp == HBO_Multiply
|| m_eAlphaMultiplyOp == HBO_MultiplyAlphaOnly );
HwBlendOp blendop = m_eAlphaMultiplyOp;
if (blendop == HBO_Multiply)
{
blendop = HBO_MultiplyByAlpha;
}
MilVertexFormatAttribute mvfaSource = VerticesArePreGenerated() ?
MILVFAttrUV1 :
MILVFAttrUV2;
IFC(AddFFPipelineItem(
blendop,
HBA_Texture,
HBA_Current,
mvfaSource,
pAlphaMask
));
if (pAlphaMask->IsAlphaScalable())
{
// Remember this location holds an alpha scalable color source
SetLastItemAsAlphaScalable();
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Add_Lighting
//
// Synopsis:
// Adds an adds a lighting colorsource.
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::Add_Lighting(
__in_ecount(1) CHwLightingColorSource *pLightingSource
)
{
HRESULT hr = S_OK;
IFC(AddFFPipelineItem(
m_eAlphaMultiplyOp,
HBA_Diffuse,
HBA_Current,
MILVFAttrDiffuse,
pLightingSource
));
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CHwFFPipelineBuilder::Mul_BlendColors
//
// Synopsis:
// Multiplies the pipeline by a set of blend colors.
//
//------------------------------------------------------------------------------
HRESULT
CHwFFPipelineBuilder::Mul_BlendColorsInternal(
__in_ecount(1) CHwColorComponentSource *pBlendColorSource
)
{
HRESULT hr = S_OK;
HwBlendArg hbaParam1;
MilVertexFormatAttribute mvfaSource;
CHwColorComponentSource::VertexComponent eLocation = pBlendColorSource->GetComponentLocation();
switch(eLocation)
{
case CHwColorComponentSource::Diffuse:
{
hbaParam1 = HBA_Diffuse;
mvfaSource = MILVFAttrDiffuse;
}
break;
case CHwColorComponentSource::Specular:
{
hbaParam1 = HBA_Specular;
mvfaSource = MILVFAttrSpecular;
}
break;
default:
NO_DEFAULT("Unknown Color Component Source");
}
IFC(AddFFPipelineItem(
m_eAlphaMultiplyOp,
hbaParam1,
HBA_Current,
mvfaSource,
pBlendColorSource
));
Cleanup:
RRETURN(hr);
}
| 28.142857
| 125
| 0.586651
|
nsivov
|
0650d75d16eac84dbc9aa8c85c38361f5d0cdfc7
| 834
|
hpp
|
C++
|
include/lastfmpp/image.hpp
|
chrismanning/lastfmpp
|
59439e62d2654359a48f8244a4b69b95d398beb3
|
[
"MIT"
] | null | null | null |
include/lastfmpp/image.hpp
|
chrismanning/lastfmpp
|
59439e62d2654359a48f8244a4b69b95d398beb3
|
[
"MIT"
] | null | null | null |
include/lastfmpp/image.hpp
|
chrismanning/lastfmpp
|
59439e62d2654359a48f8244a4b69b95d398beb3
|
[
"MIT"
] | null | null | null |
/**************************************************************************
** Copyright (C) 2015 Christian Manning
**
** This software may be modified and distributed under the terms
** of the MIT license. See the LICENSE file for details.
**************************************************************************/
#ifndef LASTFM_IMAGE_HPP
#define LASTFM_IMAGE_HPP
#include <unordered_map>
#include <lastfmpp/lastfmpp.hpp>
#include <lastfmpp/uri.hpp>
namespace lastfmpp {
enum class image_size { small, medium, large, extralarge, mega };
struct LASTFM_EXPORT image {
image() = default;
const uri_t& uri() const;
void uri(uri_t);
image_size size() const;
void size(image_size);
private:
uri_t m_uri;
image_size m_size = image_size::small;
};
} // namespace lastfm
#endif // LASTFM_IMAGE_HPP
| 22.540541
| 75
| 0.585132
|
chrismanning
|
0653790c4e7d89850c8d214c0d2d3add74b8d1ac
| 598
|
cpp
|
C++
|
Primitive-Root.cpp
|
cirno99/Algorithms
|
6425b143f406693caf8f882bdfe5497c81df255a
|
[
"Unlicense"
] | 1,210
|
2016-08-07T13:32:12.000Z
|
2022-03-21T01:01:57.000Z
|
Primitive-Root.cpp
|
NeilQingqing/Algorithms-2
|
c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa
|
[
"Unlicense"
] | 7
|
2016-09-11T11:41:03.000Z
|
2017-10-29T02:12:57.000Z
|
Primitive-Root.cpp
|
NeilQingqing/Algorithms-2
|
c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa
|
[
"Unlicense"
] | 514
|
2016-10-17T03:52:16.000Z
|
2022-03-19T16:23:33.000Z
|
#include <cstdio>
typedef long long ll;
using namespace std;
ll p;
ll qpow(ll x, ll y)
{
if (y == 1) return x;
ll t = qpow(x, y >> 1);
t = t * t % p;
if ((y & 1) == 0) return t;
return t * x % p;
}
int main()
{
ll x;
while (true)
{
scanf("%lld", &p);
for (ll k = 2; ; k++)
{
x = p - 1;
for (ll i = 2; i * i <= x; i++)
{
if (x % i == 0)
{
if (qpow(k, (p - 1) / i) == 1) goto NEXT;
while (x % i == 0) x /= i;
}
}
if (x != 1)
{
if (qpow(k, (p - 1) / x) == 1) goto NEXT;
}
printf("%lld\n", k);
break;
NEXT:;
}
}
return 0;
}
| 13
| 46
| 0.404682
|
cirno99
|
065b60abd82dd78935f3cfdc9cbc8c764ada5733
| 16,479
|
hpp
|
C++
|
include/morphotree/tree/mtree.hpp
|
dennisjosesilva/morphotree
|
3be4ff7f36de65772ef273a61b0bc5916e2904d9
|
[
"MIT"
] | null | null | null |
include/morphotree/tree/mtree.hpp
|
dennisjosesilva/morphotree
|
3be4ff7f36de65772ef273a61b0bc5916e2904d9
|
[
"MIT"
] | 3
|
2022-03-23T19:16:08.000Z
|
2022-03-28T00:40:19.000Z
|
include/morphotree/tree/mtree.hpp
|
dennisjosesilva/morphotree
|
3be4ff7f36de65772ef273a61b0bc5916e2904d9
|
[
"MIT"
] | null | null | null |
#pragma once
#include "morphotree/core/alias.hpp"
#include "morphotree/core/box.hpp"
#include <memory>
#include <list>
#include <vector>
#include <limits>
#include "morphotree/tree/ct_builder.hpp"
#include "morphotree/adjacency/adjacency.hpp"
#include "morphotree/core/sort.hpp"
#include <queue>
#include <stack>
namespace morphotree
{
enum class MorphoTreeType
{
MaxTree,
MinTree,
TreeOfShapes
};
template<class WeightType>
class MTNode
{
public:
using ValueType = WeightType;
using NodePtr = std::shared_ptr<MTNode<WeightType>>;
MTNode(uint id=0);
inline uint id() const { return id_; }
inline uint& id() { return id_; }
inline void id(uint newid) { id_ = newid; }
inline uint32 representative() const { return representative_; }
inline uint32& representative() { return representative_; }
inline void representative(uint32 newrep) { representative_ = newrep; }
inline WeightType& level() { return level_; }
inline WeightType level() const { return level_; }
inline void level(WeightType v) { level_ = v; }
inline const std::vector<uint32>& cnps() const { return cnps_; }
inline void appendCNP(uint32 cnp) { cnps_.push_back(cnp); }
inline void includeCNPS(const std::vector<uint32> &cnps);
inline NodePtr parent() { return parent_; }
inline const NodePtr parent() const { return parent_; }
inline void parent(NodePtr parent) { parent_ = parent;}
inline void appendChild(std::shared_ptr<MTNode> child) { children_.push_back(child); }
inline void includeChildren(const std::vector<NodePtr> &children);
inline void removeChild(NodePtr c) { children_.remove(c); }
inline const std::list<NodePtr>& children() const { return children_; }
std::vector<uint32> reconstruct() const;
std::vector<bool> reconstruct(const Box &domain) const;
std::vector<WeightType> reconstructGrey(const Box &domain,
WeightType backgroundValue=0) const;
NodePtr copy() const;
private:
void reconstruct(std::vector<uint32> &pixels, const NodePtr node) const;
void reconstructGrey(NodePtr node, const Box &domain,
std::vector<WeightType> &f) const;
private:
uint32 id_;
uint32 representative_;
WeightType level_;
std::vector<uint32> cnps_;
NodePtr parent_;
std::list<NodePtr> children_;
};
template<class WeightType>
class MorphologicalTree
{
public:
using NodePtr = typename MTNode<WeightType>::NodePtr;
using NodeType = MTNode<WeightType>;
using TreeWeightType = WeightType;
MorphologicalTree(MorphoTreeType type, const std::vector<WeightType> &f, const CTBuilderResult &res);
MorphologicalTree(MorphoTreeType type, std::vector<uint32> &&cmap, std::vector<NodePtr> &&nodes);
MorphologicalTree(MorphoTreeType type);
const NodePtr node(uint id) const { return nodes_[id]; }
NodePtr node(uint id) { return nodes_[id]; }
const NodePtr root() const { return root_; }
NodePtr root() { return root_; }
inline std::vector<uint32> reconstructNode(uint32 nodeId) const { return nodes_[nodeId]->reconstruct(); }
std::vector<bool> reconstructNode(uint32 nodeId, const Box &domain) const { return nodes_[nodeId]->reconstruct(domain); };
std::vector<uint32> reconstructNodes(std::function<bool(NodePtr)> keep) const;
std::vector<bool> reconstructNodes(std::function<bool(NodePtr)> keep, const Box &domain) const;
uint32 numberOfNodes() const { return nodes_.size(); }
uint32 numberOfCNPs() const { return cmap_.size(); }
void tranverse(std::function<void(const NodePtr node)> visit) const;
std::vector<WeightType> reconstructImage() const;
std::vector<WeightType> reconstructImage(std::function<bool(const NodePtr)> keep) const;
void idirectFilter(std::function<bool(const NodePtr)> keep);
MorphologicalTree<WeightType> directFilter(std::function<bool(const NodePtr)> keep) const;
void traverseByLevel(std::function<void(const NodePtr)> visit) const;
void traverseByLevel(std::function<void(NodePtr)> visit);
inline NodePtr smallComponent(uint32 idx) { return nodes_[cmap_[idx]]; }
inline const NodePtr smallComponent(uint32 idx) const { return nodes_[cmap_[idx]]; }
NodePtr smallComponent(uint32 idx, const std::vector<bool> &mask);
const NodePtr smallComponent(uint32 idx, const std::vector<bool> &mask) const;
MorphologicalTree<WeightType> copy() const;
inline MorphoTreeType type() const { return type_; }
static const uint32 UndefinedIndex;
private:
void performDirectFilter(MorphologicalTree<WeightType> &tree, std::function<bool(const NodePtr)> keep) const;
private:
std::vector<NodePtr> nodes_;
std::vector<uint32> cmap_;
NodePtr root_;
MorphoTreeType type_;
};
template<class WeightType>
MorphologicalTree<WeightType> buildMaxTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj);
template<class WeightType>
MorphologicalTree<WeightType> buildMinTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj);
// ======================[ IMPLEMENTATION ] ===================================================================
template<typename WeightType>
const uint32 MorphologicalTree<WeightType>::UndefinedIndex = std::numeric_limits<uint32>::max();
template<class WeightType>
MTNode<WeightType>::MTNode(uint id)
:id_{id}, level_{0}, parent_{nullptr}
{}
template<class WeightType>
std::vector<uint32> MTNode<WeightType>::reconstruct() const
{
std::vector<uint32> pixels{cnps_};
for (NodePtr child : children_) {
reconstruct(pixels, child);
}
return pixels;
}
template<class WeightType>
void MTNode<WeightType>::reconstruct(std::vector<uint32> &pixels, const NodePtr node) const
{
pixels.insert(pixels.end(), node->cnps().begin(), node->cnps().end());
for (NodePtr child: node->children()) {
reconstruct(pixels, child);
}
}
template<class WeightType>
std::vector<bool> MTNode<WeightType>::reconstruct(const Box &domain) const
{
std::vector<uint32> indices = reconstruct();
std::vector<bool> img(domain.numberOfPoints(), false);
for (uint32 i : indices) {
img[i] = true;
}
return img;
}
template<class WeightType>
std::vector<WeightType> MTNode<WeightType>::reconstructGrey(const Box &domain,
WeightType backgroundValue) const
{
std::vector<WeightType> f(domain.numberOfPoints(), backgroundValue);
for (uint32 p : cnps()) {
f[p] = level();
}
for (NodePtr child :children()) {
reconstructGrey(child, domain, f);
}
return f;
}
template<class WeightType>
void MTNode<WeightType>::reconstructGrey(NodePtr node, const Box &domain,
std::vector<WeightType> &f) const
{
for (uint32 p : node->cnps()) {
f[p] = node->level();
}
for (NodePtr c : node->children()) {
reconstructGrey(c, domain, f);
}
}
template<class WeightType>
void MTNode<WeightType>::includeCNPS(const std::vector<uint32>& cnps)
{
cnps_.insert(cnps_.end(), cnps.begin(), cnps.end());
}
template<class WeightType>
void MTNode<WeightType>::includeChildren(const std::vector<NodePtr> &children)
{
children_.insert(children_.end(), children.begin(), children.end());
}
template<class WeightType>
typename MTNode<WeightType>::NodePtr MTNode<WeightType>::copy() const
{
NodePtr cnode = std::make_shared<MTNode<WeightType>>(id_);
cnode->level(level_);
cnode->cnps_ = cnps_;
cnode->representative_ = representative_;
return cnode;
}
// ========================== [TREEE] =========================================================================
template<class WeightType>
MorphologicalTree<WeightType>::MorphologicalTree(MorphoTreeType type)
:type_{type}
{ }
template<class WeightType>
MorphologicalTree<WeightType>::MorphologicalTree(MorphoTreeType type,
std::vector<uint32> &&cmap, std::vector<NodePtr> &&nodes)
:cmap_{cmap}, nodes_{nodes}, type_{type}
{
root_ = nodes_[0];
}
template<class WeightType>
MorphologicalTree<WeightType>::MorphologicalTree(MorphoTreeType type,
const std::vector<WeightType> &f, const CTBuilderResult &res)
:type_{type}
{
const uint32 UNDEF = std::numeric_limits<uint32>::max();
std::vector<uint32> sortedLevelRoots;
cmap_.resize(f.size(), UNDEF);
for (uint32 i = 0; i < res.R.size(); i++) {
uint32 p = res.R[i];
if (f[res.parent[p]] != f[p] || res.parent[p] == p)
sortedLevelRoots.push_back(p);
}
nodes_.resize(sortedLevelRoots.size(), nullptr);
uint32 p = sortedLevelRoots[sortedLevelRoots.size()-1];
NodePtr root = std::make_shared<NodeType>(0);
root->level(f[p]);
root->appendCNP(p);
root->representative(p);
root->parent(nullptr);
cmap_[p] = root->id();
nodes_[0] = root;
root_ = root;
for (uint32 i = 2; i <= sortedLevelRoots.size(); i++) {
uint32 p = sortedLevelRoots[sortedLevelRoots.size()-i];
cmap_[p] = i-1;
NodePtr node = std::make_shared<NodeType>(i-1);
NodePtr parentNode = nodes_[cmap_[res.parent[p]]];
node->id(i-1);
node->parent(parentNode);
node->level(f[p]);
node->appendCNP(p);
node->representative(p);
parentNode->appendChild(node);
nodes_[i-1] = node;
}
for (uint32 i = 0; i < f.size(); i++) {
if (cmap_[i] == UNDEF) {
cmap_[i] = cmap_[res.parent[i]];
nodes_[cmap_[i]]->appendCNP(i);
}
}
}
template<typename WeightType>
std::vector<uint32>
MorphologicalTree<WeightType>::reconstructNodes(std::function<bool(NodePtr)> keep) const
{
std::vector<uint32> rec;
std::stack<NodePtr> s;
s.push(root_);
while (!s.empty()) {
NodePtr n = s.top();
s.pop();
if ((n->id() != root_->id()) && keep(n)) {
std::vector<uint32> recn = n->reconstruct();
rec.insert(rec.end(), recn.begin(), recn.end());
}
else {
for (NodePtr c : n->children())
s.push(c);
}
}
return rec;
}
template<typename WeightType>
std::vector<bool> MorphologicalTree<WeightType>::reconstructNodes(std::function<
bool(NodePtr)> keep, const Box &domain) const
{
std::vector<bool> bin(domain.numberOfPoints(), false);
std::vector<uint32> pixels = reconstructNodes(keep);
for (const uint32 pidx : pixels) {
bin[pidx] = true;
}
return bin;
}
template<class WeightType>
void MorphologicalTree<WeightType>::tranverse(std::function<void(const NodePtr node)> visit) const
{
for(uint32 i = 1; i <= nodes_.size(); i++) {
visit(nodes_[nodes_.size() - i]);
}
}
template<class WeightType>
MorphologicalTree<WeightType> buildMaxTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj)
{
CTBuilder<WeightType> builder;
std::vector<uint32> R = sortIncreasing(f);
return MorphologicalTree<WeightType>(MorphoTreeType::MaxTree, f, builder.build(f, adj, R));
}
template<class WeightType>
MorphologicalTree<WeightType> buildMinTree(const std::vector<WeightType> &f,
std::shared_ptr<Adjacency> adj)
{
CTBuilder<WeightType> builder;
std::vector<uint32> R = sortDecreasing(f);
return MorphologicalTree<WeightType>(MorphoTreeType::MinTree, f, builder.build(f, adj, R));
}
template<typename WeightType>
std::vector<WeightType> MorphologicalTree<WeightType>::reconstructImage() const
{
std::vector<WeightType> f(cmap_.size());
for (NodePtr node : nodes_) {
for (uint idx : node->cnps()) {
f[idx] = node->level();
}
}
return f;
}
template<typename WeightType>
std::vector<WeightType> MorphologicalTree<WeightType>::reconstructImage(
std::function<bool(const NodePtr)> keep) const
{
using namespace std;
vector<vector<uint32>> up(numberOfNodes(), vector<uint32>());
vector<WeightType> f(cmap_.size(), 0);
tranverse([&up, &keep, &f](const NodePtr node){
if (keep(node)) {
for (uint32 pidx : node->cnps())
f[pidx] = node->level();
for (uint32 pidx : up[node->id()])
f[pidx] = node->level();
}
else {
const vector<uint32> &cnps = node->cnps();
const vector<uint32> &upCnps = up[node->id()];
vector<uint32> &upParent = up[node->parent()->id()];
upParent.insert(upParent.end(), cnps.begin(), cnps.end());
upParent.insert(upParent.end(), upCnps.begin(), upCnps.end());
}
});
return f;
}
template<class WeightType>
void MorphologicalTree<WeightType>::idirectFilter(std::function<bool(const NodePtr)> keep)
{
performDirectFilter(*this, keep);
}
template<class WeightType>
MorphologicalTree<WeightType> MorphologicalTree<WeightType>::directFilter(
std::function<bool(const NodePtr)> keep) const
{
MorphologicalTree<WeightType> ctree = copy();
performDirectFilter(ctree, keep);
return ctree;
}
template<typename WeightType>
void MorphologicalTree<WeightType>::performDirectFilter(MorphologicalTree<WeightType> &tree,
std::function<bool(const NodePtr)> keep) const
{
// remove node from data structure.
uint32 numRemovedNodes = 0;
std::queue<NodePtr> queue;
queue.push(tree.root());
while (!queue.empty())
{
NodePtr node = queue.front();
queue.pop();
for (NodePtr c : node->children()) {
queue.push(c);
}
if (!keep(node) && node->parent() != nullptr) {
numRemovedNodes++;
NodePtr parentNode = node->parent();
parentNode->includeCNPS(node->cnps());
parentNode->removeChild(node);
for (NodePtr c : node->children()) {
parentNode->appendChild(c);
c->parent(parentNode);
}
}
}
// fix cmap and nodes arrays
uint32 prevNumOfNodes = tree.numberOfNodes();
tree.nodes_.clear();
tree.nodes_.resize(prevNumOfNodes - numRemovedNodes);
uint32 newId = 0;
tree.traverseByLevel([&tree, &newId](NodePtr n) {
n->id(newId);
tree.nodes_[newId] = n;
for (uint32 idx : n->cnps()) {
tree.cmap_[idx] = newId;
}
newId++;
});
}
template<typename WeightType>
void MorphologicalTree<WeightType>::traverseByLevel(std::function<void(const NodePtr)> visit) const
{
std::queue<NodePtr> queue;
queue.push(root());
while (!queue.empty())
{
NodePtr node = queue.front();
queue.pop();
visit(node);
for (NodePtr c : node->children()) {
queue.push(c);
}
}
}
template<typename WeightType>
void MorphologicalTree<WeightType>::traverseByLevel(std::function<void(NodePtr)> visit)
{
std::queue<NodePtr> queue;
queue.push(root());
while (!queue.empty())
{
NodePtr node = queue.front();
queue.pop();
visit(node);
for (NodePtr c : node->children()) {
queue.push(c);
}
}
}
template<class WeightType>
typename MorphologicalTree<WeightType>::NodePtr
MorphologicalTree<WeightType>::smallComponent(uint32 idx, const std::vector<bool> &mask)
{
NodePtr node = nodes_[cmap_[idx]];
while (!mask[node->id()] && node->id() != 0)
node = node->parent();
return node;
}
template<class WeightType>
const typename MorphologicalTree<WeightType>::NodePtr
MorphologicalTree<WeightType>::smallComponent(uint32 idx, const std::vector<bool> &mask) const
{
NodePtr node = nodes_[cmap_[idx]];
while (!mask[node->id()] && node->id() != 0)
node = node->parent();
return node;
}
template<class WeightType>
MorphologicalTree<WeightType> MorphologicalTree<WeightType>::copy() const
{
MorphologicalTree ctree{type_};
ctree.nodes_.reserve(numberOfNodes());
ctree.cmap_ = cmap_;
for (NodePtr node : nodes_) {
ctree.nodes_.push_back(node->copy());
}
traverseByLevel([this, &ctree](NodePtr node) {
NodePtr cnode = ctree.nodes_[node->id()];
if (node->parent() != nullptr) {
NodePtr cparent = ctree.nodes_[node->parent()->id()];
cnode->parent(cparent);
cparent->appendChild(cnode);
}
});
ctree.root_ = ctree.nodes_[0];
return ctree;
}
}
| 29.532258
| 126
| 0.642879
|
dennisjosesilva
|
06623c4a5e54afdd80e862ffdc06b39ad69895b3
| 42,167
|
cpp
|
C++
|
Source/WebSocketEntities.cpp
|
braindigitalis/DiscordCoreAPI
|
1cc087ea8435051afb8a7ef9bb171665127df419
|
[
"Apache-2.0"
] | null | null | null |
Source/WebSocketEntities.cpp
|
braindigitalis/DiscordCoreAPI
|
1cc087ea8435051afb8a7ef9bb171665127df419
|
[
"Apache-2.0"
] | null | null | null |
Source/WebSocketEntities.cpp
|
braindigitalis/DiscordCoreAPI
|
1cc087ea8435051afb8a7ef9bb171665127df419
|
[
"Apache-2.0"
] | null | null | null |
// WebSocketEntities.cpp - Source file for the webSocket related classes and structs.
// May 13, 2021
// Chris M.
// https://github.com/RealTimeChris
#include "WebSocketEntities.hpp"
#include "JSONIfier.hpp"
#include "EventManager.hpp"
#include "CommandController.hpp"
#include "DiscordCoreClient.hpp"
namespace DiscordCoreInternal {
BaseSocketAgent::BaseSocketAgent(std::string botToken, std::string baseUrl, WebSocketOpCode opCode) {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
this->state = WebSocketState::Initializing;
this->botToken = botToken;
this->dataOpcode = opCode;
this->baseUrl = baseUrl;
this->doWeReconnect.set();
this->theTask = this->run();
}
BaseSocketAgent::BaseSocketAgent(nullptr_t nullPtr) {};
void BaseSocketAgent::sendMessage(std::string& dataToSend) {
try {
std::lock_guard<std::recursive_mutex> accessLock{ this->accessorMutex01 };
std::cout << "Sending WebSocket Message: " << std::endl << dataToSend;
this->webSocket->writeData(dataToSend);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
DiscordCoreAPI::TSUnboundedMessageBlock<WebSocketWorkload>& BaseSocketAgent::getWorkloadTarget() {
return this->webSocketWorkloadTarget;
}
void BaseSocketAgent::sendMessage(nlohmann::json& dataToSend) {
try {
std::lock_guard<std::recursive_mutex> accessLock{ this->accessorMutex01 };
DiscordCoreAPI::StopWatch<std::chrono::milliseconds> stopWatch{ std::chrono::milliseconds{3500} };
while (!this->areWeConnected.load(std::memory_order_consume) && !(dataToSend.contains("op") && (dataToSend.at("op") == 2 || dataToSend.at("op") == 6))) {
if (stopWatch.hasTimePassed()) {
return;
}
}
std::cout << "Sending WebSocket Message: " << dataToSend.dump() << std::endl << std::endl;
std::vector<uint8_t> theVector = this->erlPacker.parseJsonToEtf(dataToSend);
std::string out{};
out.resize(this->maxHeaderSize);
size_t size = this->createHeader(out.data(), theVector.size(), this->dataOpcode);
std::string header(out.data(), size);
std::vector<uint8_t> theVectorNew{};
theVectorNew.insert(theVectorNew.begin(), header.begin(), header.end());
theVectorNew.insert(theVectorNew.begin() + header.size(), theVector.begin(), theVector.end());
this->webSocket->writeData(theVectorNew);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
uint64_t BaseSocketAgent::createHeader(char* outBuffer, uint64_t sendlength, WebSocketOpCode opCode) {
try {
size_t position{ 0 };
int32_t indexCount{ 0 };
outBuffer[position++] = this->webSocketFinishBit | static_cast<unsigned char>(opCode);
if (sendlength <= this->webSocketMaxPayloadLengthSmall) {
outBuffer[position++] = static_cast<unsigned char>(sendlength);
}
else if (sendlength <= this->webSocketMaxPayloadLengthLarge) {
outBuffer[position++] = static_cast<unsigned char>(this->webSocketPayloadLengthMagicLarge);
indexCount = 2;
}
else {
outBuffer[position++] = this->webSocketPayloadLengthMagicHuge;
indexCount = 8;
}
for (int32_t x = indexCount - 1; x >= 0; x--) {
outBuffer[position++] = static_cast<unsigned char>(sendlength >> x * 8);
}
outBuffer[1] |= this->webSocketMaskBit;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
return position;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::createHeader()");
this->onClosedExternal();
return uint64_t{};
}
}
std::vector<std::string> BaseSocketAgent::tokenize(std::string& dataIn, std::string separator) {
try {
std::string::size_type value{ 0 };
std::vector<std::string> dataOut{};
while ((value = dataIn.find_first_not_of(separator, value)) != std::string::npos) {
auto output = dataIn.find(separator, value);
dataOut.push_back(dataIn.substr(value, output - value));
value = output;
}
return dataOut;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::tokenize()");
this->onClosedExternal();
return std::vector<std::string>{};
}
}
void BaseSocketAgent::getVoiceConnectionData(VoiceConnectInitData doWeCollect) {
try {
std::lock_guard<std::recursive_mutex> getVoiceConnectionDataLock{ this->accessorMutex01 };
this->voiceConnectInitData = doWeCollect;
DiscordCoreAPI::UpdateVoiceStateData dataPackage01;
dataPackage01.channelId = "";
dataPackage01.guildId = this->voiceConnectInitData.guildId;
dataPackage01.selfDeaf = false;
dataPackage01.selfMute = false;
nlohmann::json newString01 = JSONIFY(dataPackage01);
this->sendMessage(newString01);
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
DiscordCoreAPI::UpdateVoiceStateData dataPackage;
dataPackage.channelId = doWeCollect.channelId;
dataPackage.guildId = doWeCollect.guildId;
dataPackage.selfDeaf = false;
dataPackage.selfMute = false;
nlohmann::json newString = JSONIFY(dataPackage);
this->areWeCollectingData = true;
this->sendMessage(newString);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::getVoiceConnectionData()");
this->onClosedExternal();
}
}
DiscordCoreAPI::CoRoutine<void> BaseSocketAgent::run() {
try {
co_await DiscordCoreAPI::NewThreadAwaitable<void>();
this->connect();
while (!this->doWeQuit) {
if (this->doWeReconnect.wait(0) == 1) {
this->onClosedInternal();
}
if (this->webSocket != nullptr) {
if (!this->webSocket->processIO()) {
this->onClosedExternal();
}
this->handleBuffer();
}
}
co_return;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::run()");
this->onClosedExternal();
co_return;
}
}
bool BaseSocketAgent::onMessageReceived() {
try {
std::string messageNew = this->webSocket->getData();
nlohmann::json payload{};
try {
payload = this->erlPacker.parseEtfToJson(&messageNew);
}
catch (...) {
return false;
}
if (this->areWeCollectingData && payload.at("t") == "VOICE_SERVER_UPDATE" && !this->serverUpdateCollected) {
if (!this->serverUpdateCollected && !this->stateUpdateCollected) {
this->voiceConnectionData = VoiceConnectionData();
this->voiceConnectionData.endPoint = payload.at("d").at("endpoint").get<std::string>();
this->voiceConnectionData.token = payload.at("d").at("token").get<std::string>();
this->serverUpdateCollected = true;
}
else {
this->voiceConnectionData.endPoint = payload.at("d").at("endpoint").get<std::string>();
this->voiceConnectionData.token = payload.at("d").at("token").get<std::string>();
this->voiceConnectionDataBufferMap.at(payload.at("d").at("guild_id"))->send(this->voiceConnectionData);
this->serverUpdateCollected = false;
this->stateUpdateCollected = false;
this->areWeCollectingData = false;
}
}
if (this->areWeCollectingData && payload.at("t") == "VOICE_STATE_UPDATE" && !this->stateUpdateCollected && payload.at("d").at("member").at("user").at("id") == this->voiceConnectInitData.userId) {
if (!this->stateUpdateCollected && !this->serverUpdateCollected) {
this->voiceConnectionData = VoiceConnectionData();
this->voiceConnectionData.sessionId = payload.at("d").at("session_id").get<std::string>();
this->stateUpdateCollected = true;
}
else {
this->voiceConnectionData.sessionId = payload.at("d").at("session_id").get<std::string>();
this->voiceConnectionDataBufferMap.at(payload.at("d").at("guild_id"))->send(this->voiceConnectionData);
this->serverUpdateCollected = false;
this->stateUpdateCollected = false;
this->areWeCollectingData = false;
}
}
if (payload.at("s") >= 0) {
this->lastNumberReceived = payload.at("s");
}
if (payload.at("t") == "RESUMED") {
this->areWeConnected.store(true, std::memory_order_release);
this->currentReconnectTries = 0;
this->areWeReadyToConnectEvent.set();
}
if (payload.at("t") == "READY") {
this->areWeConnected.store(true, std::memory_order_release);
this->sessionId = payload.at("d").at("session_id");
this->currentReconnectTries = 0;
this->areWeReadyToConnectEvent.set();
this->areWeAuthenticated = true;
}
if (payload.at("op") == 1) {
this->sendHeartBeat();
}
if (payload.at("op") == 7) {
std::cout << "Reconnecting (Type 7)!" << std::endl << std::endl;
this->areWeResuming = true;
this->currentReconnectTries += 1;
this->areWeConnected.store(false, std::memory_order_release);
this->heartbeatTimer.cancel();
this->webSocket.reset(nullptr);
this->connect();
}
if (payload.at("op") == 9) {
std::cout << "Reconnecting (Type 9)!" << std::endl << std::endl;
srand(static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()));
this->areWeConnected.store(false, std::memory_order_release);
this->currentReconnectTries += 1;
int32_t numOfMsToWait = static_cast<int32_t>(1000.0f + ((static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) * static_cast<float>(4000.0f)));
std::this_thread::sleep_for(std::chrono::milliseconds(numOfMsToWait));
if (payload.at("d") == true) {
nlohmann::json identityJson = JSONIFY(this->botToken, this->intentsValue);
this->sendMessage(identityJson);
}
else {
this->heartbeatTimer.cancel();
this->webSocket.reset(nullptr);
this->areWeResuming = false;
this->areWeAuthenticated = false;
this->connect();
}
}
if (payload.at("op") == 10) {
this->heartbeatInterval = payload.at("d").at("heartbeat_interval");
DiscordCoreAPI::TimeElapsedHandler onHeartBeat = [this]() {
BaseSocketAgent::sendHeartBeat();
};
this->heartbeatTimer = DiscordCoreAPI::ThreadPoolTimer::createPeriodicTimer(onHeartBeat, this->heartbeatInterval);
if (!this->areWeAuthenticated) {
nlohmann::json identityJson = JSONIFY(this->botToken, this->intentsValue);
this->sendMessage(identityJson);
}
if (this->areWeResuming) {
std::this_thread::sleep_for(std::chrono::milliseconds{ 500 });
nlohmann::json resumePayload = JSONIFY(this->botToken, this->sessionId, this->lastNumberReceived);
this->sendMessage(resumePayload);
}
}
if (payload.at("op") == 11) {
this->haveWeReceivedHeartbeatAck = true;
}
if (payload.contains("d") && !payload.at("d").is_null() && payload.contains("t") && !payload.at("t").is_null()) {
WebSocketWorkload webSocketWorkload{};
webSocketWorkload.payLoad.update(std::move(payload.at("d")));
if (payload.at("t") == "APPLICATION_COMMAND_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Application_Command_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "APPLICATION_COMMAND_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Application_Command_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "APPLICATION_COMMAND_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Application_Command_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "CHANNEL_PINS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Channel_Pins_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_LIST_SYNC") {
webSocketWorkload.eventType = WebSocketEventType::Thread_List_Sync;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_MEMBER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Member_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "THREAD_MEMBERS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Thread_Members_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
return true;
}
else if (payload.at("t") == "GUILD_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_BAN_ADD") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Ban_Add;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_BAN_REMOVE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Ban_Remove;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_EMOJIS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Emojis_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_STICKERS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Stickers_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_INTEGRATIONS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Integrations_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBER_ADD") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Member_Add;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBER_REMOVE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Member_Remove;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Member_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_MEMBERS_CHUNK") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Members_Chunk;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_ROLE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Role_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_ROLE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Role_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "GUILD_ROLE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Guild_Role_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTEGRATION_ROLE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Integration_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTEGRATION_ROLE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Integration_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTEGRATION_ROLE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Integration_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INTERACTION_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Interaction_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INVITE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Invite_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "INVITE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Invite_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_DELETE_BULK") {
webSocketWorkload.eventType = WebSocketEventType::Message_Delete_Bulk;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_ADD") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Add;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_REMOVE") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Remove;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_REMOVE_ALL") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Remove_All;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "MESSAGE_REACTION_REMOVE_EMOJI") {
webSocketWorkload.eventType = WebSocketEventType::Message_Reaction_Remove_Emoji;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "PRESENCE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Presence_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
return true;
}
else if (payload.at("t") == "STAGE_INSTANCE_CREATE") {
webSocketWorkload.eventType = WebSocketEventType::Stage_Instance_Create;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "STAGE_INSTANCE_DELETE") {
webSocketWorkload.eventType = WebSocketEventType::Stage_Instance_Delete;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "STAGE_INSTANCE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Stage_Instance_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "TYPING_START") {
webSocketWorkload.eventType = WebSocketEventType::Typing_Start;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "USER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::User_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "VOICE_STATE_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Voice_State_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "VOICE_SERVER_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Voice_Server_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
else if (payload.at("t") == "WEBHOOKS_UPDATE") {
webSocketWorkload.eventType = WebSocketEventType::Webhooks_Update;
this->webSocketWorkloadTarget.send(std::move(webSocketWorkload));
}
std::cout << "Message received from WebSocket: " << payload.dump() << std::endl << std::endl;
return true;
}
std::cout << "Message received from WebSocket: " << payload.dump() << std::endl << std::endl;
return true;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::onMessageReceived()");
this->onClosedExternal();
return false;
}
}
void BaseSocketAgent::sendHeartBeat() {
try {
std::lock_guard<std::recursive_mutex> accesLock{ this->accessorMutex01 };
if (this->haveWeReceivedHeartbeatAck) {
nlohmann::json heartbeat = JSONIFY(this->lastNumberReceived);
this->sendMessage(heartbeat);
this->haveWeReceivedHeartbeatAck = false;
}
else {
this->onClosedExternal();
}
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::sendHeartBeat()");
this->onClosedExternal();
}
}
void BaseSocketAgent::handleBuffer() {
try {
std::string newVector{};
switch (this->state) {
case WebSocketState::Initializing:
newVector.insert(newVector.begin(), this->inputBuffer.begin(), this->inputBuffer.end());
if (newVector.find("\r\n\r\n") != std::string::npos) {
std::string headers = newVector.substr(0, newVector.find("\r\n\r\n"));
newVector.erase(0, newVector.find("\r\n\r\n") + 4);
std::vector<std::string> headerOut = tokenize(headers);
if (headerOut.size()) {
std::string statusLine = headerOut[0];
headerOut.erase(headerOut.begin());
std::vector<std::string> status = tokenize(statusLine, " ");
if (status.size() >= 3 && status[1] == "101") {
this->state = WebSocketState::Connected;
this->inputBuffer.clear();
this->inputBuffer.insert(this->inputBuffer.end(), newVector.begin(), newVector.end());
this->parseHeader();
}
else {
return;
}
}
}
break;
case WebSocketState::Connected:
while (this->parseHeader()) {};
return;
}
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::handleBuffer()");
this->onClosedExternal();
}
}
bool BaseSocketAgent::parseHeader() {
try {
std::vector<uint8_t> newVector = this->inputBuffer;
if (this->inputBuffer.size() < 4) {
return false;
}
else {
switch (static_cast<WebSocketOpCode>(this->inputBuffer[0] & ~this->webSocketMaskBit))
{
case WebSocketOpCode::Ws_Op_Continuation:
case WebSocketOpCode::Op_Text:
case WebSocketOpCode::Op_Binary:
case WebSocketOpCode::Op_Ping:
case WebSocketOpCode::Op_Pong:
{
uint8_t length01 = this->inputBuffer[1];
int32_t payloadStartOffset = 2;
if (length01 & this->webSocketMaskBit) {
return false;
}
uint64_t length02 = length01;
if (length01 == this->webSocketPayloadLengthMagicLarge) {
if (this->inputBuffer.size() < 8) {
return false;
}
uint8_t length03 = this->inputBuffer[2];
uint8_t length04 = this->inputBuffer[3];
length02 = static_cast<uint64_t>((length03 << 8) | length04);
payloadStartOffset += 2;
}
else if (length01 == this->webSocketPayloadLengthMagicHuge) {
if (this->inputBuffer.size() < 10) {
return false;
}
length02 = 0;
for (int32_t value = 2, shift = 56; value < 10; ++value, shift -= 8) {
uint8_t length05 = static_cast<uint8_t>(this->inputBuffer[value]);
length02 |= static_cast<uint64_t>(length05) << static_cast<uint64_t>(shift);
}
payloadStartOffset += 8;
}
if (this->inputBuffer.size() < payloadStartOffset + length02) {
return false;
}
else {
std::vector<uint8_t> newerVector{};
newerVector.reserve(length02);
for (uint32_t x = payloadStartOffset; x < payloadStartOffset + length02; x += 1) {
newerVector.push_back(this->inputBuffer[x]);
}
this->inputBuffer = std::move(newerVector);
this->onMessageReceived();
this->inputBuffer.insert(this->inputBuffer.begin(), newVector.begin() + payloadStartOffset + length02, newVector.end());
}
return true;
}
case WebSocketOpCode::Op_Close: {
uint16_t close = this->inputBuffer[2];
close <<= 8;
close |= (this->inputBuffer[3]);
this->closeCode = close;
std::cout << "WebSocket Closed; Code: " << this->closeCode << std::endl;
this->onClosedExternal();
return false;
}
default: {
this->closeCode = 0;
return false;
}
}
}
return false;
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::parseHeader()");
this->onClosedExternal();
return false;
}
}
void BaseSocketAgent::onClosedExternal() {
this->doWeReconnect.reset();
}
void BaseSocketAgent::onClosedInternal() {
this->areWeReadyToConnectEvent.reset();
if (this->maxReconnectTries > this->currentReconnectTries) {
this->areWeConnected.store(false, std::memory_order_release);
this->closeCode = 1000;
this->currentReconnectTries += 1;
this->webSocket.reset(nullptr);
this->areWeAuthenticated = false;
this->heartbeatTimer.cancel();
this->inputBuffer.clear();
this->haveWeReceivedHeartbeatAck = true;
this->connect();
}
else if (this->maxReconnectTries <= this->currentReconnectTries) {
this->doWeQuit = true;
}
}
void BaseSocketAgent::connect() {
try {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
this->webSocket = std::make_unique<WebSocketSSLClient>(this->baseUrl, this->port, &this->inputBuffer);
this->state = WebSocketState::Initializing;
if (this->heartbeatTimer.running()) {
this->heartbeatTimer.cancel();
}
this->doWeReconnect.set();
std::string sendVector = "GET " + this->relativePath + " HTTP/1.1\r\nHost: " + this->baseUrl +
"\r\nPragma: no-cache\r\nUser-Agent: DiscordCoreAPI/1.0\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " +
this->authKey + "\r\nSec-WebSocket-Version: 13\r\n\r\n";
this->sendMessage(sendVector);
}
catch (...) {
DiscordCoreAPI::reportException("BaseSocketAgent::connect()");
this->onClosedExternal();
}
}
BaseSocketAgent::~BaseSocketAgent() {
this->doWeQuit = true;
this->theTask.cancel();
this->theTask.get();
this->heartbeatTimer.cancel();
}
VoiceSocketAgent::VoiceSocketAgent(VoiceConnectInitData initDataNew, BaseSocketAgent* baseBaseSocketAgentNew) {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
this->baseSocketAgent = baseBaseSocketAgentNew;
this->voiceConnectInitData = initDataNew;
this->baseSocketAgent->getVoiceConnectionData(this->voiceConnectInitData);
this->doWeReconnect.set();
this->theTask = this->run();
}
void VoiceSocketAgent::sendVoiceData(std::vector<uint8_t>& responseData) {
try {
if (responseData.size() == 0) {
std::cout << "Please specify voice data to send" << std::endl << std::endl;
return;
}
else {
this->voiceSocket->writeData(responseData);
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendVoiceData()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::sendMessage(std::vector<uint8_t>& dataToSend) {
try {
std::string newString{};
newString.insert(newString.begin(), dataToSend.begin(), dataToSend.end());
std::cout << "Sending Voice WebSocket Message: " << newString << std::endl << std::endl;
std::vector<char> out{};
out.resize(this->maxHeaderSize);
size_t size = this->createHeader(out.data(), dataToSend.size(), this->dataOpcode);
std::string header(out.data(), size);
std::vector<uint8_t> theVectorNew{};
theVectorNew.insert(theVectorNew.begin(), header.begin(), header.end());
theVectorNew.insert(theVectorNew.begin() + header.size(), dataToSend.begin(), dataToSend.end());
this->webSocket->writeData(theVectorNew);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::sendMessage(std::string& dataToSend) {
try {
std::cout << "Sending Voice WebSocket Message: " << std::endl << dataToSend;
this->webSocket->writeData(dataToSend);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendMessage()");
this->onClosedExternal();
}
}
uint64_t VoiceSocketAgent::createHeader(char* outBuffer, uint64_t sendlength, WebSocketOpCode opCode) {
try {
size_t position = 0;
outBuffer[position++] = this->webSocketFinishBit | static_cast<unsigned char>(opCode);
if (sendlength <= this->webSocketMaxPayloadLengthSmall)
{
outBuffer[position++] = static_cast<unsigned char>(sendlength);
}
else if (sendlength <= this->webSocketMaxPayloadLengthLarge)
{
outBuffer[position++] = static_cast<unsigned char>(this->webSocketPayloadLengthMagicLarge);
outBuffer[position++] = static_cast<unsigned char>(sendlength >> 8);
outBuffer[position++] = static_cast<unsigned char>(sendlength);
}
else
{
outBuffer[position++] = this->webSocketPayloadLengthMagicHuge;
const uint64_t length02 = sendlength;
for (int32_t x = sizeof(uint64_t) - 1; x >= 0; x--) {
outBuffer[position++] = static_cast<unsigned char>(length02 >> x * 8);
}
}
outBuffer[1] |= this->webSocketMaskBit;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
outBuffer[position++] = 0;
return position;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::createHeader()");
this->onClosedExternal();
return size_t{};
}
}
std::vector<std::string> VoiceSocketAgent::tokenize(std::string& dataIn, std::string separator) {
try {
std::string::size_type value{ 0 };
std::vector<std::string> dataOut{};
while ((value = dataIn.find_first_not_of(separator, value)) != std::string::npos) {
auto output = dataIn.find(separator, value);
dataOut.push_back(dataIn.substr(value, output - value));
value = output;
}
return dataOut;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::tokenize()");
this->onClosedExternal();
return std::vector<std::string>{};
}
}
DiscordCoreAPI::CoRoutine<void> VoiceSocketAgent::run() {
try {
auto cancelHandle = co_await DiscordCoreAPI::NewThreadAwaitable<void>();
this->connect();
while (!this->doWeQuit && !cancelHandle.promise().isItStopped()) {
if (this->doWeReconnect.wait(0) == 1) {
this->onClosedInternal();
co_return;
}
if (this->webSocket != nullptr) {
if (!this->webSocket->processIO()) {
this->onClosedExternal();
}
}
if (this->voiceSocket != nullptr) {
this->voiceSocket->readData(true);
}
this->handleBuffer();
}
co_return;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::run()");
this->onClosedExternal();
co_return;
}
}
void VoiceSocketAgent::onMessageReceived() {
try {
std::string message = this->webSocket->getData();
nlohmann::json payload = payload.parse(message);
std::cout << "Message received from Voice WebSocket: " << message << std::endl << std::endl;
if (payload.contains("op")) {
if (payload.at("op") == 6) {
this->haveWeReceivedHeartbeatAck = true;
};
if (payload.at("op") == 2) {
this->voiceConnectionData.audioSSRC = payload.at("d").at("ssrc").get<uint32_t>();
this->voiceConnectionData.voiceIp = payload.at("d").at("ip").get<std::string>();
this->voiceConnectionData.voicePort = std::to_string(payload.at("d").at("port").get<int64_t>());
for (auto& value : payload.at("d").at("modes")) {
if (value == "xsalsa20_poly1305") {
this->voiceConnectionData.voiceEncryptionMode = value;
}
}
this->voiceConnect();
this->collectExternalIP();
int32_t counterValue{ 0 };
std::vector<uint8_t> protocolPayloadSelectString = JSONIFY(this->voiceConnectionData.voicePort, this->voiceConnectionData.externalIp, this->voiceConnectionData.voiceEncryptionMode, 0);
if (this->webSocket != nullptr) {
this->sendMessage(protocolPayloadSelectString);
}
}
if (payload.at("op") == 4) {
for (uint32_t x = 0; x < payload.at("d").at("secret_key").size(); x += 1) {
this->voiceConnectionData.secretKey.push_back(payload.at("d").at("secret_key").at(x).get<uint8_t>());
}
}
if (payload.at("op") == 9) {};
if (payload.at("op") == 8) {
if (payload.at("d").contains("heartbeat_interval")) {
this->heartbeatInterval = static_cast<int32_t>(payload.at("d").at("heartbeat_interval").get<float>());
}
DiscordCoreAPI::TimeElapsedHandler onHeartBeat{ [&, this]() ->void {
VoiceSocketAgent::sendHeartBeat();
} };
this->heartbeatTimer = DiscordCoreAPI::ThreadPoolTimer{ DiscordCoreAPI::ThreadPoolTimer::createPeriodicTimer(onHeartBeat, this->heartbeatInterval) };
this->haveWeReceivedHeartbeatAck = true;
std::vector<uint8_t> identifyPayload = JSONIFY(this->voiceConnectionData, this->voiceConnectInitData);
if (this->webSocket != nullptr) {
this->sendMessage(identifyPayload);
}
}
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::onMessageReceived()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::collectExternalIP() {
try {
std::vector<uint8_t> packet{};
packet.resize(74);
uint16_t val1601{ 0x01 };
uint16_t val1602{ 70 };
packet[0] = static_cast<uint8_t>(val1601 >> 8);
packet[1] = static_cast<uint8_t>(val1601 >> 0);
packet[2] = static_cast<uint8_t>(val1602 >> 8);
packet[3] = static_cast<uint8_t>(val1602 >> 0);
packet[4] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC >> 24);
packet[5] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC >> 16);
packet[6] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC >> 8);
packet[7] = static_cast<uint8_t>(this->voiceConnectionData.audioSSRC);
this->voiceSocket->writeData(packet);
while (this->inputBuffer01.size() < 74) {
this->voiceSocket->readData(false);
}
std::string message{};
message.insert(message.begin(), this->inputBuffer01.begin() + 8, this->inputBuffer01.begin() + 64);
if (message.find('\u0000') != std::string::npos) {
message = message.substr(0, message.find('\u0000', 5));
}
this->inputBuffer01.clear();
this->voiceConnectionData.externalIp = message;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::collectExternalIP()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::sendHeartBeat() {
try {
if (this->haveWeReceivedHeartbeatAck) {
std::vector<uint8_t> heartbeatPayload = JSONIFY(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
if (this->webSocket != nullptr) {
this->sendMessage(heartbeatPayload);
}
this->haveWeReceivedHeartbeatAck = false;
}
else {
this->onClosedExternal();
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::sendHeartBeat()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::voiceConnect() {
try {
this->voiceSocket = std::make_unique<DatagramSocketSSLClient>(this->voiceConnectionData.voiceIp, this->voiceConnectionData.voicePort, &this->inputBuffer01);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::voiceConnect()");
this->onClosedExternal();
}
}
void VoiceSocketAgent::handleBuffer() {
try {
std::string newVector{};
switch (this->state) {
case WebSocketState::Initializing:
newVector.insert(newVector.begin(), this->inputBuffer00.begin(), this->inputBuffer00.end());
if (newVector.find("\r\n\r\n") != std::string::npos) {
std::string headers = newVector.substr(0, newVector.find("\r\n\r\n"));
newVector.erase(0, newVector.find("\r\n\r\n") + 4);
std::vector<std::string> headerOut = tokenize(headers);
if (headerOut.size()) {
std::string statusLine = headerOut[0];
headerOut.erase(headerOut.begin());
std::vector<std::string> status = tokenize(statusLine, " ");
if (status.size() >= 3 && status[1] == "101") {
this->state = WebSocketState::Connected;
this->inputBuffer00.clear();
this->inputBuffer00.insert(this->inputBuffer00.end(), newVector.begin(), newVector.end());
this->parseHeader();
}
else {
return;
}
}
}
break;
case WebSocketState::Connected:
while (this->parseHeader()) {};
return;
}
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::handleBuffer()");
this->onClosedExternal();
}
}
bool VoiceSocketAgent::parseHeader() {
try {
std::vector<uint8_t> newVector = this->inputBuffer00;
if (this->inputBuffer00.size() < 4) {
return false;
}
else {
switch (static_cast<WebSocketOpCode>(this->inputBuffer00[0] & ~this->webSocketMaskBit))
{
case WebSocketOpCode::Ws_Op_Continuation:
case WebSocketOpCode::Op_Text:
case WebSocketOpCode::Op_Binary:
case WebSocketOpCode::Op_Ping:
case WebSocketOpCode::Op_Pong:
{
uint8_t length01 = this->inputBuffer00[1];
int32_t payloadStartOffset = 2;
if (length01 & this->webSocketMaskBit) {
return false;
}
uint64_t length02 = length01;
if (length01 == this->webSocketPayloadLengthMagicLarge) {
if (this->inputBuffer00.size() < 8) {
return false;
}
uint8_t length03 = this->inputBuffer00[2];
uint8_t length04 = this->inputBuffer00[3];
length02 = static_cast<uint64_t>((length03 << 8) | length04);
payloadStartOffset += 2;
}
else if (length01 == this->webSocketPayloadLengthMagicHuge) {
if (this->inputBuffer00.size() < 10) {
return false;
}
length02 = 0;
for (int32_t value = 2, shift = 56; value < 10; ++value, shift -= 8) {
uint8_t length05 = static_cast<uint8_t>(this->inputBuffer00[value]);
length02 |= static_cast<uint64_t>(length05) << static_cast<uint64_t>(shift);
}
payloadStartOffset += 8;
}
if (this->inputBuffer00.size() < payloadStartOffset + length02) {
return false;
}
else {
std::vector<uint8_t> newerVector{};
newerVector.reserve(length02);
for (uint32_t x = payloadStartOffset; x < payloadStartOffset + length02; x += 1) {
newerVector.push_back(this->inputBuffer00[x]);
}
this->inputBuffer00 = std::move(newerVector);
this->onMessageReceived();
this->inputBuffer00.insert(this->inputBuffer00.begin(), newVector.begin() + payloadStartOffset + length02, newVector.end());
}
return true;
}
case WebSocketOpCode::Op_Close: {
uint16_t close = this->inputBuffer00[2];
close <<= 8;
close |= this->inputBuffer00[3];
this->closeCode = close;
std::cout << "Voice WebSocket Closed; Code: " << this->closeCode << std::endl;
this->onClosedExternal();
return false;
}
default: {
this->closeCode = 0;
return false;
}
}
}
return false;
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::parseHeader()");
this->onClosedExternal();
return false;
}
}
void VoiceSocketAgent::onClosedExternal() {
this->doWeReconnect.reset();
}
void VoiceSocketAgent::onClosedInternal() {
this->closeCode = 1000;
this->voiceSocket.reset(nullptr);
this->webSocket.reset(nullptr);
this->heartbeatTimer.cancel();
this->inputBuffer00.clear();
this->inputBuffer01.clear();
}
void VoiceSocketAgent::connect() {
try {
this->authKey = DiscordCoreAPI::generateX64BaseEncodedKey();
DiscordCoreAPI::waitForTimeToPass(*this->baseSocketAgent->voiceConnectionDataBufferMap.at(this->voiceConnectInitData.guildId), this->voiceConnectionData, 20000);
this->baseUrl = this->voiceConnectionData.endPoint.substr(0, this->voiceConnectionData.endPoint.find(":"));
this->relativePath = "/?v=4";
this->heartbeatTimer.cancel();
this->webSocket = std::make_unique<WebSocketSSLClient>(this->baseUrl, "443", &this->inputBuffer00);
this->state = WebSocketState::Initializing;
std::string sendVector = "GET " + this->relativePath + " HTTP/1.1\r\nHost: " + this->baseUrl +
"\r\nPragma: no-cache\r\nUser-Agent: DiscordCoreAPI/1.0\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " +
this->authKey + "\r\nSec-WebSocket-Version: 13\r\n\r\n";
this->sendMessage(sendVector);
}
catch (...) {
DiscordCoreAPI::reportException("VoiceSocketAgent::connect()");
this->onClosedExternal();
}
}
VoiceSocketAgent::~VoiceSocketAgent() {
this->doWeQuit = true;
this->theTask.cancel();
this->theTask.get();
this->heartbeatTimer.cancel();
};
}
| 38.264065
| 198
| 0.682548
|
braindigitalis
|
066469719d36c5564bf1b88e3a934da65e4363d3
| 13,371
|
cpp
|
C++
|
eval.cpp
|
maxime-tournier/slip
|
a3765b27280cb29880e448310fbcb2c9a40a88cd
|
[
"MIT"
] | 1
|
2017-03-19T21:43:42.000Z
|
2017-03-19T21:43:42.000Z
|
eval.cpp
|
maxime-tournier/slip
|
a3765b27280cb29880e448310fbcb2c9a40a88cd
|
[
"MIT"
] | null | null | null |
eval.cpp
|
maxime-tournier/slip
|
a3765b27280cb29880e448310fbcb2c9a40a88cd
|
[
"MIT"
] | null | null | null |
#include "eval.hpp"
#include <vector>
#include "sexpr.hpp"
#include "package.hpp"
#include "gc.hpp"
#include "stack.hpp"
// #include "repr.hpp"
namespace eval {
////////////////////////////////////////////////////////////////////////////////
const symbol cons = "cons";
const symbol nil = "nil";
const symbol head = "head";
const symbol tail = "tail";
template<class T>
static value eval(state::ref env, const T& ) {
static_assert(sizeof(T) == 0, "eval implemented");
}
closure::closure(std::size_t argc, func_type func)
: func(func),
argc(argc) {
}
sum::sum(const value& data, symbol tag)
: value(data), tag(tag) { }
lambda::lambda(state::ref env, std::size_t argc, func_type func)
: closure(argc, func),
env(env) { }
state::state(ref parent): parent(parent) { }
state::ref scope(state::ref self) {
assert(self);
return gc::make_ref<state>(self);
}
state& state::def(symbol name, const value& self) {
auto err = locals.emplace(name, self); (void) err;
assert(err.second && "redefined variable");
return *this;
}
template<class NameIterator, class ValueIterator>
static state::ref augment(state::ref self,
NameIterator name_first, NameIterator name_last,
ValueIterator value_first, ValueIterator value_last) {
auto res = scope(self);
ValueIterator value = value_first;
for(NameIterator name = name_first; name != name_last; ++name) {
assert(value != value_last && "not enough values");
res->locals.emplace(*name, *value++);
}
assert(value == value_last && "too many values");
return res;
}
// apply a lambda to argument range
value apply(const value& self, const value* first, const value* last) {
const std::size_t argc = last - first;
const closure* ptr;
const std::size_t expected = self.match([&](const value& ) -> std::size_t {
throw std::runtime_error("type error in application");
},
[&](const closure& self) {
ptr = &self;
return self.argc;
});
if(argc < expected) {
// unsaturated call: build wrapper
const std::size_t remaining = expected - argc;
const std::vector<value> saved(first, last);
return closure(remaining, [self, saved, remaining](const value* args) {
std::vector<value> tmp = saved;
for(auto it = args, last = args + remaining; it != last; ++it) {
tmp.emplace_back(*it);
}
return apply(self, tmp.data(), tmp.data() + tmp.size());
});
}
if(argc > expected) {
// over-saturated call: call result with remaining args
const value* mid = first + expected;
assert(mid > first);
assert(mid < last);
const value func = apply(self, first, mid);
return apply(func, mid, last);
}
// saturated calls
return ptr->func(first);
}
template<class T>
static value eval(state::ref, const ast::lit<T>& self) {
return self.value;
}
static value eval(state::ref, const ast::lit<string>& self) {
return make_ref<string>(self.value);
}
static value eval(state::ref e, const ast::var& self) {
auto res = e->find(self.name); assert(res);
return *res;
}
using stack_type = stack<value>;
static stack_type stack{1000};
static value eval(state::ref e, const ast::app& self) {
// note: evaluate func first
const value func = eval(e, *self.func);
// TODO use allocator
using allocator_type = stack_allocator<value>;
std::vector<value, allocator_type> args{allocator_type{stack}};
args.reserve(self.argc);
for(const auto& arg : self.args) {
args.emplace_back(eval(e, arg));
};
return apply(func, args.data(), args.data() + args.size());
}
static value eval(state::ref e, const ast::abs& self) {
std::vector<symbol> names;
for(const auto& arg : self.args) {
names.emplace_back(arg.name());
}
const ast::expr body = *self.body;
return lambda(e, names.size(), [=](const value* args) {
auto sub = augment(e, names.begin(), names.end(),
args, args + names.size());
return eval(sub, body);
});
}
static value eval(state::ref e, const ast::bind& self) {
auto it = e->locals.emplace(self.id.name, eval(e, self.value)); (void) it;
assert(it.second && "redefined variable");
return unit();
}
static value eval(state::ref e, const ast::io& self) {
return self.match([&](const ast::expr& self) {
return eval(e, self);
},
[&](const ast::bind& self) {
return eval(e, self);
});
}
static value eval(state::ref e, const ast::seq& self) {
auto sub = scope(e);
const value init = unit();
foldl(init, self.items, [&](const value&, const ast::io& self) {
return eval(sub, self);
});
// return
return eval(sub, *self.last);
}
static value eval(state::ref e, const ast::run& self) {
return eval(e, *self.value);
}
static value eval(state::ref e, const ast::module& self) {
// just define the reified module type constructor
enum module::type type;
switch(self.type) {
case ast::module::product: type = module::product; break;
case ast::module::coproduct: type = module::coproduct; break;
}
return module{type};
}
static value eval(state::ref e, const ast::def& self) {
auto it = e->locals.emplace(self.id.name, eval(e, *self.value)); (void) it;
assert(it.second && "redefined variable");
return unit();
}
static value eval(state::ref e, const ast::let& self) {
auto sub = scope(e);
for(const ast::bind& def : self.defs) {
sub->locals.emplace(def.id.name, eval(sub, def.value));
}
return eval(sub, *self.body);
}
static value eval(state::ref e, const ast::cond& self) {
const value test = eval(e, *self.test);
assert(test.get<boolean>() && "type error");
if(test.cast<boolean>()) return eval(e, *self.conseq);
else return eval(e, *self.alt);
}
static value eval(state::ref e, const ast::record& self) {
auto res = make_ref<record>();
for(const auto& attr : self.attrs) {
res->emplace(attr.id.name, eval(e, attr.value));
}
return res;
}
static value eval(state::ref e, const ast::sel& self) {
const symbol name = self.id.name;
return closure(1, [name](const value* args) -> value {
return args[0].match([&](const value::list& self) -> value {
// note: the only possible way to call this is during a pattern
// match processing a non-empty list
assert(self && "type error");
if(name == head) return self->head;
if(name == tail) return self->tail;
assert(false && "type error");
},
[&](const ref<record>& self) {
const auto it = self->find(name); (void) it;
assert(it != self->end() && "attribute error");
return it->second;
},
[&](const value& self) -> value {
assert(false && "type error");
});
});
}
static value eval(state::ref e, const ast::inj& self) {
const symbol tag = self.id.name;
return closure(1, [tag](const value* args) -> value {
return make_ref<sum>(args[0], tag);
});
}
static value eval(state::ref e, const ast::make& self) {
switch(eval(e, *self.type).cast<module>().type) {
case module::product:
return eval(e, ast::record{self.attrs});
case module::coproduct: {
assert(size(self.attrs) == 1);
const auto& attr = self.attrs->head;
return make_ref<sum>(eval(e, attr.value), attr.id.name);
}
case module::list:
assert(size(self.attrs) == 1);
return eval(e, self.attrs->head.value);
};
}
static value eval(state::ref e, const ast::use& self) {
const value env = eval(e, *self.env);
assert(env.get<ref<record>>() && "type error");
// auto s = scope(e);
for(const auto& it : *env.cast<ref<record>>()) {
e->def(it.first, it.second);
}
// return eval(s, *self.body);
return unit();
}
static value eval(state::ref e, const ast::import& self) {
const auto pkg = package::import<state::ref>(self.package, [&] {
auto es = gc::make_ref<state>();
package::iter(self.package, [&](ast::expr self) {
eval(es, self);
});
return es;
});
e->def(self.package, make_ref<record>(pkg->locals));
return unit();
}
static value eval(state::ref e, const ast::match& self) {
std::map<symbol, std::pair<symbol, ast::expr>> dispatch;
for(const auto& handler : self.cases) {
auto err = dispatch.emplace(handler.id.name,
std::make_pair(handler.arg.name(),
handler.value));
(void) err; assert(err.second);
}
const ref<ast::expr> fallback = self.fallback;
return closure(1, [e, dispatch, fallback](const value* args) {
// matching on a list
return args[0].match([&](const value::list& self) {
auto it = dispatch.find(self ? cons : nil);
if(it != dispatch.end()) {
auto sub = scope(e);
sub->def(it->second.first, self);
return eval(sub, it->second.second);
} else {
assert(fallback);
return eval(e, *fallback);
}
},
[&](const ref<sum>& self) {
auto it = dispatch.find(self->tag);
if(it != dispatch.end()) {
auto sub = scope(e);
sub->def(it->second.first, *self);
return eval(sub, it->second.second);
} else {
assert(fallback);
return eval(e, *fallback);
}
},
[&](const value& self) -> value {
std::stringstream ss;
ss << "attempting to match on value " << self;
throw std::runtime_error(ss.str());
});
});
}
namespace {
struct eval_visitor {
template<class T>
value operator()(const T& self, state::ref e) const {
return eval(e, self);
}
};
}
static void debug(state::ref e) {
for(auto& it : e->locals) {
std::clog << it.first << ": " << it.second << std::endl;
}
}
value eval(state::ref e, const ast::expr& self) {
// std::clog << repr(self) << std::endl;
return self.visit(eval_visitor(), e);
}
namespace {
struct ostream_visitor {
void operator()(const ref<value>& self, std::ostream& out) const {
out << "#mut<" << *self << ">";
}
void operator()(const module& self, std::ostream& out) const {
out << "#<module>";
}
void operator()(const ref<string>& self, std::ostream& out) const {
out << '"' << *self << '"';
}
void operator()(const symbol& self, std::ostream& out) const {
out << self;
}
void operator()(const value::list& self, std::ostream& out) const {
out << self;
}
void operator()(const lambda& self, std::ostream& out) const {
out << "#<lambda>";
}
void operator()(const closure& self, std::ostream& out) const {
out << "#<closure>";
}
void operator()(const unit& self, std::ostream& out) const {
out << "()";
}
void operator()(const boolean& self, std::ostream& out) const {
out << (self ? "true" : "false");
}
void operator()(const integer& self, std::ostream& out) const {
out << self; // << "i";
}
void operator()(const real& self, std::ostream& out) const {
out << self; // << "d";
}
void operator()(const ref<record>& self, std::ostream& out) const {
out << "{";
bool first = true;
for(const auto& it : *self) {
if(first) first = false;
else out << "; ";
out << it.first << ": " << it.second;
}
out << "}";
}
void operator()(const ref<sum>& self, std::ostream& out) const {
out << "<" << self->tag << ": " << *self << ">";
}
};
}
std::ostream& operator<<(std::ostream& out, const value& self) {
self.visit(ostream_visitor(), out);
return out;
}
static void mark(const value& self, bool debug) {
self.match([&](const value& ) { },
[&](const ref<record>& self) {
for(const auto& it : *self) {
mark(it.second, debug);
}
},
[&](const ref<sum>& self) {
mark(*self, debug);
},
[&](const lambda& self) {
mark(self.env, debug);
});
}
void mark(state::ref e, bool debug) {
if(debug) std::clog << "marking:\t" << e.get() << std::endl;
if(e.marked()) return;
e.mark();
for(auto& it : e->locals) {
mark(it.second, debug);
}
if(e->parent) {
mark(e->parent, debug);
}
}
value* state::find(symbol name) {
auto it = locals.find(name);
if(it != locals.end()) return &it->second;
if(parent) return parent->find(name);
return nullptr;
}
}
| 25.468571
| 82
| 0.544238
|
maxime-tournier
|
06657b9629f5f8883f5c19899ccaa69c6e22bbe5
| 289
|
cpp
|
C++
|
src/liquid/string_std.cpp
|
kainjow/Jeqyll
|
3a234a345087c5d3366b1eda98d3ed92d3888101
|
[
"MIT"
] | 4
|
2018-02-01T04:46:37.000Z
|
2021-01-13T18:20:38.000Z
|
src/liquid/string_std.cpp
|
kainjow/Jeqyll
|
3a234a345087c5d3366b1eda98d3ed92d3888101
|
[
"MIT"
] | null | null | null |
src/liquid/string_std.cpp
|
kainjow/Jeqyll
|
3a234a345087c5d3366b1eda98d3ed92d3888101
|
[
"MIT"
] | 3
|
2017-03-27T19:12:56.000Z
|
2021-03-23T04:24:51.000Z
|
#include "string.hpp"
Liquid::StringRef Liquid::String::midRef(size_type pos, size_type num) const
{
if (pos > size()) {
return {};
}
const size_type len = num == static_cast<size_type>(-1) || size() < num ? size() - pos : num;
return StringRef(this, pos, len);
}
| 26.272727
| 97
| 0.608997
|
kainjow
|
06666820f2556feae941ec03439afd62c07f5374
| 4,464
|
cpp
|
C++
|
OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.cpp
|
sio-testtank-makerspace/OpenCTD
|
0595126c56dbd7e131d17491b5679a944ab44660
|
[
"MIT"
] | 2
|
2019-05-30T23:44:24.000Z
|
2019-09-04T00:50:38.000Z
|
OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.cpp
|
sio-testtank-makerspace/OpenCTD
|
0595126c56dbd7e131d17491b5679a944ab44660
|
[
"MIT"
] | null | null | null |
OpenCTD_Particle_Boron/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.cpp
|
sio-testtank-makerspace/OpenCTD
|
0595126c56dbd7e131d17491b5679a944ab44660
|
[
"MIT"
] | null | null | null |
#include "application.h"
#line 1 "/Users/pjb/Dropbox/Particle_Projects/OPO_OpenCTDTest/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.ino"
/*
* Simple data logger.
*/
#include <SPI.h>
#include "SdFat.h"
// SD chip select pin. Be sure to disable any other SPI devices such as Enet.
void writeHeader();
void logData();
void setup();
void loop();
#line 8 "/Users/pjb/Dropbox/Particle_Projects/OPO_OpenCTDTest/OpenCTD_SDCard/OpenCTD_SDCard/src/OpenCTD_SDCard.ino"
const uint8_t chipSelect = SS;
// Interval between data records in milliseconds.
// The interval must be greater than the maximum SD write latency plus the
// time to acquire and write data to the SD to avoid overrun errors.
// Run the bench example to check the quality of your SD card.
const uint32_t SAMPLE_INTERVAL_MS = 1000;
// Log file base name. Must be six characters or less.
#define FILE_BASE_NAME "Data"
//------------------------------------------------------------------------------
// File system object.
SdFat sd;
// Log file.
SdFile file;
// Time in micros for next data record.
uint32_t logTime;
//==============================================================================
// User functions. Edit writeHeader() and logData() for your requirements.
const uint8_t ANALOG_COUNT = 4;
//------------------------------------------------------------------------------
// Write data header.
void writeHeader() {
file.print(F("micros"));
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.print(F(",adc"));
file.print(i, DEC);
}
file.println();
}
//------------------------------------------------------------------------------
// Log a data record.
void logData() {
uint16_t data[ANALOG_COUNT];
// Read all channels to avoid SD write latency between readings.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
data[i] = analogRead(i);
}
// Write data to file. Start with log time in micros.
file.print(logTime);
// Write ADC data to CSV record.
for (uint8_t i = 0; i < ANALOG_COUNT; i++) {
file.write(',');
file.print(data[i]);
}
file.println();
}
//==============================================================================
// Error messages stored in flash.
#define error(msg) sd.errorHalt(F(msg))
//------------------------------------------------------------------------------
SYSTEM_MODE(MANUAL);
void setup() {
Cellular.off();
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[13] = FILE_BASE_NAME "00.csv";
Serial.begin(9600);
// Wait for USB Serial
while (!Serial) {
SysCall::yield();
}
delay(1000);
Serial.println(F("Type any character to start"));
while (!Serial.available()) {
SysCall::yield();
}
// Initialize at the highest speed supported by the board that is
// not over 50 MHz. Try a lower speed if SPI errors occur.
if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
sd.initErrorHalt();
}
// Find an unused file name.
if (BASE_NAME_SIZE > 6) {
error("FILE_BASE_NAME too long");
}
while (sd.exists(fileName)) {
if (fileName[BASE_NAME_SIZE + 1] != '9') {
fileName[BASE_NAME_SIZE + 1]++;
} else if (fileName[BASE_NAME_SIZE] != '9') {
fileName[BASE_NAME_SIZE + 1] = '0';
fileName[BASE_NAME_SIZE]++;
} else {
error("Can't create file name");
}
}
if (!file.open(fileName, O_WRONLY | O_CREAT | O_EXCL)) {
error("file.open");
}
// Read any Serial data.
do {
delay(10);
} while (Serial.available() && Serial.read() >= 0);
Serial.print(F("Logging to: "));
Serial.println(fileName);
Serial.println(F("Type any character to stop"));
// Write data header.
writeHeader();
// Start on a multiple of the sample interval.
logTime = micros()/(1000UL*SAMPLE_INTERVAL_MS) + 1;
logTime *= 1000UL*SAMPLE_INTERVAL_MS;
}
//------------------------------------------------------------------------------
void loop() {
// Time for next record.
logTime += 1000UL*SAMPLE_INTERVAL_MS;
// Wait for log time.
int32_t diff;
do {
diff = micros() - logTime;
} while (diff < 0);
// Check for data rate too high.
if (diff > 10) {
error("Missed data record");
}
logData();
// Force data to SD and update the directory entry to avoid data loss.
if (!file.sync() || file.getWriteError()) {
error("write error");
}
if (Serial.available()) {
// Close file and stop.
file.close();
Serial.println(F("Done"));
SysCall::halt();
}
}
| 27.9
| 115
| 0.575269
|
sio-testtank-makerspace
|
06691fe7604608f281cdf1b73c26e841e47ba944
| 4,319
|
cc
|
C++
|
physics/hadron/models/src/HadronicFinalStateModelStore.cc
|
Geant-RnD/geant
|
ffff95e23547531f3254ada2857c062a31f33e8f
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2016-10-16T14:37:42.000Z
|
2018-04-05T15:49:09.000Z
|
physics/hadron/models/src/HadronicFinalStateModelStore.cc
|
Geant-RnD/geant
|
ffff95e23547531f3254ada2857c062a31f33e8f
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
physics/hadron/models/src/HadronicFinalStateModelStore.cc
|
Geant-RnD/geant
|
ffff95e23547531f3254ada2857c062a31f33e8f
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
#include "Geant/HadronicFinalStateModelStore.h"
#include "Geant/HadronicFinalStateModel.h"
#include "Geant/Isotope.h"
using namespace geantphysics;
//------------------------------------------------
// HadronicFinalStateModelStore non-inline methods
//------------------------------------------------
HadronicFinalStateModelStore::HadronicFinalStateModelStore() : fName("")
{
}
HadronicFinalStateModelStore::HadronicFinalStateModelStore(const std::string name) : fName(name)
{
}
HadronicFinalStateModelStore::HadronicFinalStateModelStore(const HadronicFinalStateModelStore &other)
: fName(other.fName)
{
for (size_t i = 0; i < other.fHadFsVec.size(); i++) {
fHadFsVec.push_back(other.fHadFsVec[i]);
}
}
HadronicFinalStateModelStore &HadronicFinalStateModelStore::operator=(const HadronicFinalStateModelStore &other)
{
if (this != &other) {
fHadFsVec.clear();
for (size_t i = 0; i < other.fHadFsVec.size(); i++) {
fHadFsVec.push_back(other.fHadFsVec[i]);
}
fName = other.fName;
}
return *this;
}
HadronicFinalStateModelStore::~HadronicFinalStateModelStore()
{
// We are assuming here that this class is the owner of the hadronic final-state models, therefore it is in charge
// of deleting them at the end.
for (size_t i = 0; i < fHadFsVec.size(); i++) {
delete fHadFsVec[i];
}
fHadFsVec.clear();
}
void HadronicFinalStateModelStore::Initialize(/* Not yet defined */)
{
}
void HadronicFinalStateModelStore::RegisterHadronicFinalStateModel(HadronicFinalStateModel *ptrhadfs)
{
if (ptrhadfs) {
fHadFsVec.push_back(ptrhadfs);
}
}
int HadronicFinalStateModelStore::GetIndexChosenFinalStateModel(const int projectilecode,
const double projectilekineticenergy,
const Isotope *targetisotope) const
{
int index = -1;
std::vector<int> indexApplicableModelVec;
for (size_t i = 0; i < fHadFsVec.size(); i++) {
if (fHadFsVec[i] && fHadFsVec[i]->IsApplicable(projectilecode, projectilekineticenergy, targetisotope)) {
indexApplicableModelVec.push_back(i);
}
}
if (indexApplicableModelVec.size() == 1) {
index = indexApplicableModelVec[0];
} else if (indexApplicableModelVec.size() == 2) {
// The "first" index corresponds to the model with the lowest minimal energy
int first = indexApplicableModelVec[0];
int second = indexApplicableModelVec[1];
if (fHadFsVec[first]->GetLowEnergyUsageLimit() > fHadFsVec[second]->GetLowEnergyUsageLimit()) {
first = second;
second = indexApplicableModelVec[0];
}
if (fHadFsVec[first]->GetHighEnergyUsageLimit() >= fHadFsVec[second]->GetHighEnergyUsageLimit()) {
std::cerr << "HadronicFinalStateModelStore::GetIndexChosenFinalState : projectilecode=" << projectilecode
<< " ; projectilekineticenergy=" << projectilekineticenergy
<< " GeV; targetisotope: Z=" << targetisotope->GetZ() << " N=" << targetisotope->GetN() << std::endl
<< "\t NOT allowed full overlapping between two models: " << fHadFsVec[first]->GetName() << " , "
<< fHadFsVec[second]->GetName() << std::endl;
} else { // All if fine: first model applicable to lower energies than the second model
// Select one of the two models with probability depending linearly on the projectilekineticenergy
double probFirst = (fHadFsVec[first]->GetHighEnergyUsageLimit() - projectilekineticenergy) /
(fHadFsVec[first]->GetHighEnergyUsageLimit() - fHadFsVec[second]->GetLowEnergyUsageLimit());
double randomNumber = 0.5; //***LOOKHERE*** TO-BE-REPLACED with a call to a random number generator.
if (randomNumber < probFirst) {
index = first;
} else {
index = second;
}
}
} else {
std::cerr << "HadronicFinalStateModelStore::GetIndexChosenFinalState : projectilecode=" << projectilecode
<< " ; projectilekineticenergy=" << projectilekineticenergy
<< " GeV; targetisotope: Z=" << targetisotope->GetZ() << " N=" << targetisotope->GetN() << std::endl
<< "\t wrong number of applicable final-state models: " << indexApplicableModelVec.size() << std::endl;
}
return index;
}
| 39.990741
| 117
| 0.656865
|
Geant-RnD
|
06696f0f06efe1d4c70f313abf88e6b996dec1cb
| 954
|
cpp
|
C++
|
AYK/src/AYK/Renderer/OrthographicCamera.cpp
|
AreYouReal/AYK
|
c6859047cfed674291692cc31095d8bb61b27a35
|
[
"Apache-2.0"
] | null | null | null |
AYK/src/AYK/Renderer/OrthographicCamera.cpp
|
AreYouReal/AYK
|
c6859047cfed674291692cc31095d8bb61b27a35
|
[
"Apache-2.0"
] | null | null | null |
AYK/src/AYK/Renderer/OrthographicCamera.cpp
|
AreYouReal/AYK
|
c6859047cfed674291692cc31095d8bb61b27a35
|
[
"Apache-2.0"
] | null | null | null |
#include "aykpch.h"
#include "OrthographicCamera.h"
#include <glm/gtc/matrix_transform.hpp>
namespace AYK {
OrthographicCamera::OrthographicCamera(float Left, float Right, float Bottom, float Top) : ProjectionMatrix(glm::ortho(Left, Right, Bottom, Top, -1.0f, 1.0f)), ViewMatrix(1.0f){
AYK_PROFILE_FUNCTION();
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
}
void OrthographicCamera::SetProjection(float Left, float Right, float Bottom, float Top) {
AYK_PROFILE_FUNCTION();
ProjectionMatrix = glm::ortho(Left, Right, Bottom, Top, -1.0f, 1.0f);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
}
void OrthographicCamera::RecalculateViewMatrix(){
AYK_PROFILE_FUNCTION();
glm::mat4 Transform = glm::translate(glm::mat4(1.0f), Position) * glm::rotate(glm::mat4(1.0f), glm::radians(Rotation), glm::vec3(0, 0, 1));
ViewMatrix = glm::inverse(Transform);
ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
}
}
| 28.058824
| 178
| 0.736897
|
AreYouReal
|
066beba3c0647677cff0bddc2d0c969a82cda3f3
| 1,054
|
cpp
|
C++
|
FlyEngine/Source/FlyVariable.cpp
|
rogerta97/FlyEngine
|
33abd70c5b4307cd552e2b6269b401772b4327ba
|
[
"MIT"
] | null | null | null |
FlyEngine/Source/FlyVariable.cpp
|
rogerta97/FlyEngine
|
33abd70c5b4307cd552e2b6269b401772b4327ba
|
[
"MIT"
] | null | null | null |
FlyEngine/Source/FlyVariable.cpp
|
rogerta97/FlyEngine
|
33abd70c5b4307cd552e2b6269b401772b4327ba
|
[
"MIT"
] | null | null | null |
#include "FlyVariable.h"
#include "RandomNumberGenerator.h"
#include "mmgr.h"
FlyVariable::FlyVariable()
{
}
FlyVariable::~FlyVariable()
{
}
void FlyVariable::CleanUp()
{
}
void FlyVariable::SetDefault()
{
name = "";
varType = Var_Integer;
varIntegerValue = 0;
varToogleValue = true;
uniqueID = RandomNumberGenerator::getInstance()->GenerateUID();
}
void FlyVariable::Serialize(JSON_Object* jsonObject, std::string _baseObjectStr)
{
std::string saveString = _baseObjectStr + "VariableType";
json_object_dotset_number(jsonObject, saveString.c_str(), varType);
saveString = _baseObjectStr + "VariableName";
json_object_dotset_string(jsonObject, saveString.c_str(), name.c_str());
saveString = _baseObjectStr + "IntegerValue";
json_object_dotset_number(jsonObject, saveString.c_str(), varIntegerValue);
saveString = _baseObjectStr + "ToggleValue";
json_object_dotset_boolean(jsonObject, saveString.c_str(), varToogleValue);
saveString = _baseObjectStr + "UID";
json_object_dotset_number(jsonObject, saveString.c_str(), uniqueID);
}
| 23.954545
| 80
| 0.767552
|
rogerta97
|
066f9426ba98e9c4f33791fd877a1ed30b71d398
| 3,010
|
cpp
|
C++
|
src/MexUtils.cpp
|
markjolah/MexIface
|
42118754e7d4175d452fa7cdbd9335561ff69900
|
[
"Apache-2.0"
] | 4
|
2019-03-04T08:28:50.000Z
|
2021-09-30T16:50:51.000Z
|
src/MexUtils.cpp
|
markjolah/MexIFace
|
42118754e7d4175d452fa7cdbd9335561ff69900
|
[
"Apache-2.0"
] | null | null | null |
src/MexUtils.cpp
|
markjolah/MexIFace
|
42118754e7d4175d452fa7cdbd9335561ff69900
|
[
"Apache-2.0"
] | null | null | null |
/** @file MexUtils.cpp
* @author Mark J. Olah (mjo\@cs.unm DOT edu)
* @date 2013-2017
* @copyright Licensed under the Apache License, Version 2.0. See LICENSE file.
* @brief Helper functions for working with Matlab mxArrays and mxClassIDs
*/
#include <memory>
#include <cxxabi.h>
#include "MexIFace/MexUtils.h"
#include "MexIFace/explore.h"
namespace mexiface {
const char* get_mx_class_name(mxClassID id)
{
switch (id) {
case mxINT8_CLASS: return "int8";
case mxUINT8_CLASS: return "uint8";
case mxINT16_CLASS: return "int16";
case mxUINT16_CLASS:return "uint16";
case mxINT32_CLASS: return "int32";
case mxUINT32_CLASS: return "uint32";
case mxINT64_CLASS: return "int64";
case mxUINT64_CLASS:return "uint64";
case mxSINGLE_CLASS: return "single";
case mxDOUBLE_CLASS:return "double";
case mxLOGICAL_CLASS: return "logical";
case mxCHAR_CLASS: return "char";
case mxSTRUCT_CLASS: return "struct";
case mxCELL_CLASS: return "cell";
case mxUNKNOWN_CLASS: return "unknownclass";
default: return "mysteryclass???";
}
}
/** Templates for get_mx_class
* Can't use uint64_t as sometimes it may be long or long long.
* best to set mxClassID for long and long long individually
*/
template<> mxClassID get_mx_class<double>() {return mxDOUBLE_CLASS;}
template<> mxClassID get_mx_class<float>() {return mxSINGLE_CLASS;}
template<> mxClassID get_mx_class<int8_t>() {return mxINT8_CLASS;}
template<> mxClassID get_mx_class<int16_t>() {return mxINT16_CLASS;}
template<> mxClassID get_mx_class<int32_t>() {return mxINT32_CLASS;}
template<> mxClassID get_mx_class<long>() {return mxINT64_CLASS;}
template<> mxClassID get_mx_class<long long>() {return mxINT64_CLASS;}
template<> mxClassID get_mx_class<uint8_t>() {return mxUINT8_CLASS;}
template<> mxClassID get_mx_class<uint16_t>() {return mxUINT16_CLASS;}
template<> mxClassID get_mx_class<uint32_t>() {return mxUINT32_CLASS;}
template<> mxClassID get_mx_class<unsigned long long>() {return mxUINT64_CLASS;}
template<> mxClassID get_mx_class<unsigned long>() {return mxUINT64_CLASS;}
/* TODO Finish this method to replace matlab .c code dependencies */
// void get_characteristics(const mxArray *arr)
// {
// auto ndims = mxGetNumberOfDimensions(arr);
// auto size = mxGetDimensions(arr);
// auto name = mxGetClassName(arr);
// auto id = mxGetClassID(arr);
//
// }
void exploreMexArgs(int nargs, const mxArray *args[] )
{
mexPrintf("#Args: %d\n",nargs);
for (int i=0; i<nargs; i++) {
mexPrintf("\n\n");
mexPrintf("arg[%i]: ",i);
explore::get_characteristics(args[i]);
explore::analyze_class(args[i]);
}
}
std::string demangle(const char* name)
{
int status = -4;
std::unique_ptr<char, void(*)(void*)> res{abi::__cxa_demangle(name, NULL, NULL, &status),std::free};
return (status==0) ? res.get() : name;
}
} /* namespace mexiface */
| 35.411765
| 104
| 0.690033
|
markjolah
|
067009b97de9b3c912abfa77d7276ea3f9ff39be
| 34,300
|
cpp
|
C++
|
RC.cpp
|
eanmcgilvery/Embedded-Sys-Visualizer
|
412b23f0f90f5e9ee68d139f73f15df48c88d5a4
|
[
"MIT"
] | null | null | null |
RC.cpp
|
eanmcgilvery/Embedded-Sys-Visualizer
|
412b23f0f90f5e9ee68d139f73f15df48c88d5a4
|
[
"MIT"
] | null | null | null |
RC.cpp
|
eanmcgilvery/Embedded-Sys-Visualizer
|
412b23f0f90f5e9ee68d139f73f15df48c88d5a4
|
[
"MIT"
] | null | null | null |
/*MIT License
Copyright (c) 2021 Ean McGilvery, Janeen Yamak
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.
*/
/*************************************************************************************************
* File: RC.cpp
* Description:
* This file contains all the major compenents of the RC Graphicial Library and the RC Hardware Component
* Requires C++ 14 or later (Smart Pointers)
*
**************************************************************************************************/
#ifndef RC_CPP
#define RC_CPP
#include "RC.hpp"
#include "cpputils/graphics/image.h"
#include "cpputils/graphics/image_event.h"
#include "orientation.h"
#include <memory>
#include <fstream> //std::ofstream
#include <curl/curl.h>
#include <sys/stat.h>
#include <math.h>
/*====================================================================================================================*/
/* MUTATORS */
/*====================================================================================================================*/
/***************************************************************************
* Function: SetRC
* Description:
* This function shall decide whether the user would like to use the Graphical Interface or the Hardware Component
* Parameters:
* bool usingRCGraphics : 'true' enables the user to work with the Graphical Interface
* 'false' enables the user to work with the Hardware Component
* Return:
* None
***************************************************************************/
void RC::SetRC(bool usingRCGraphics){ UsingRCGraphics_ = usingRCGraphics; }
/***************************************************************************
* Function: SetSpeed
* Description:
* This Function sets the speed of the RC Car for the Graphical Interface
* Parameters:
* int speed : the speed of the car in ms
* Return:
* None
***************************************************************************/
void RC::SetSpeed(int speed){ Speed_ = speed; }
/*====================================================================================================================*/
/* END OF MUTATORS */
/*====================================================================================================================*/
/*====================================================================================================================*/
/* ACCESSORS */
/*====================================================================================================================*/
/***************************************************************************
* Function: RCWorldImage
* Description:
* Returns the underlying image object
* Parameters:
* None
* Return:
* Image: the underlying image object
***************************************************************************/
graphics::Image& RC::RCWorldImage(){ return RCWorldImage_; }
/***************************************************************************
* Function: XDim
* Description:
* Returns the X Dimention of the graphical interface
* Parameters:
* None
* Return:
* int: The X Dimention of the graphical interface
***************************************************************************/
int RC::XDim(){ return XDim_; }
/***************************************************************************
* Function: YDim
* Description:
* Returns the Y Dimention of the graphical interface
* Parameters:
* None
* Return:
* int: The Y Dimention of the graphical interface
***************************************************************************/
int RC::YDim(){ return YDim_; }
/***************************************************************************
* Function: UsingGraphics
* Description:
* Returns true/false depending on whether the use of the graphical interface has been enabled or not
* Parameters:
* None
* Return:
* bool: 'true': the graphical interface is enabled
* 'false': the RC Hardware compenent is enabled
***************************************************************************/
bool RC::UsingGraphics(){ return UsingRCGraphics_; }
/***************************************************************************
* Function: Speed
* Description:
* Returns the speed in ms
* Parameters:
* None
* Return:
* int: the speed in ms
***************************************************************************/
int RC::Speed(){ return Speed_; }
/***************************************************************************
* Function: positions
* Description:
* Returns the current x and y value of the car
* Parameters:
* None
* Return:
* DirectionAndOrientation: is an object that contains the x and y value of the RC car's position
***************************************************************************/
DirectionAndOrientation RC::positions(){ return position_; }
/***************************************************************************
* Function: pxPerCell
* Description:
* Returns the number of pixels per cell
* Parameters:
* None
* Return:
* int: the number of pixels per cell
***************************************************************************/
int RC::pxPerCell(){ return pxPerCell_; }
/*====================================================================================================================*/
/* END OF ACCESSORS */
/*====================================================================================================================*/
/*====================================================================================================================*/
/* HELPER FUNCTIONS (NOT TO BE EXPLICITLY CALLED) */
/*====================================================================================================================*/
/***************************************************************************
* Function: DrawRCCar
* Description:
* Passes the X and Y px position that represent the middle of a cell
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::DrawRCCar(){
if(UsingRCGraphics_){
DrawRCCar(position_.x_ * pxPerCell_ + pxPerCell_ / 2,
position_.y_* pxPerCell_ + pxPerCell_ / 2);
}
}
/***************************************************************************
* Function: ParseWorldFileError
* Description:
* This Function will display an error if the syntax of the file is not correct
* Parameters:
* error_text: is a description of what caused this function to be prompted
* line_number: specifies which line number caused the syntax error in the 'file' object
* Return:
* None
***************************************************************************/
void RC::ParseWorldFileError(std::string error_text, int line_number) {
if (line_number > 0) {
error_text += " (line " + std::to_string(line_number) + ")";
}
std::cout << error_text << std::endl << std::flush;
throw error_text;
}
/***************************************************************************
* Function: ParsePosition
* Description:
* Grabs the X and Y position of an object
* Parameters:
* fstream file: is a file object that is being read
* int line_number: specifies which line you are currently reading
* Return:
* DirectionAndOrientation: returns the coordinates of the object you read from the file
***************************************************************************/
DirectionAndOrientation RC::ParsePosition(std::fstream& file,int line_number) {
char open_paren, comma, closed_paren;
int x, y;
if (!(file >> open_paren >> x >> comma >> y >> closed_paren)) {
ParseWorldFileError("Error reading position", line_number);
}
CheckParsePosition(open_paren, comma, closed_paren, line_number);
DirectionAndOrientation result;
// Convert y in the file to y on-screen. In the file, (1, 1) is the
// bottom left corner.
// In car coordinates, that's (0, YDim_ - 1).
result.y_ = YDim_ - y;
result.x_ = x - 1;
return result;
}
/***************************************************************************
* Function: ParsePositionAndOrientation
* Description:
* Reads the Direction the RC Car
* Parameters:
* fstream file: is a file object that is being read
* int line_number: specifies which line you are currently reading
* Return:
* DirectionAndOrientation: returns the orientation of the RC Car
***************************************************************************/
DirectionAndOrientation RC::ParsePositionAndOrientation(std::fstream& file, int line_number) {
DirectionAndOrientation result = ParsePosition(file, line_number);
std::string direction;
if (!(file >> direction)) {
ParseWorldFileError("Error reading orientation", line_number);
}
// Ensure the first character is lower cased.
direction[0] = tolower(direction[0]);
if (direction == "north") {
result.orientation_ = Direction::North;
} else if (direction == "east") {
result.orientation_ = Direction::East;
} else if (direction == "south") {
result.orientation_ = Direction::South;
} else if (direction == "west") {
result.orientation_ = Direction::West;
} else {
ParseWorldFileError("Unknown orientation " + direction, line_number);
}
return result;
}
/***************************************************************************
* Function: CheckParsePosition
* Description:
* Checks to see if the following Syntax "(,)" is valid in the file
* Parameters:
* char open_paren: '('
* char comm: ','
* char closed_paren: ')'
* int line_number: is the line number the pareser is currently at
* Return:
* None
***************************************************************************/
void RC::CheckParsePosition(char open_paren, char comma, char closed_paren,int line_number) {
if (open_paren != '(') {
ParseWorldFileError("Invalid syntax: expected open parenthesis but found " +
std::string(1, open_paren),
line_number);
}
if (comma != ',') {
ParseWorldFileError(
"Invalid syntax: expected a comma but found " + std::string(1, comma),
line_number);
}
if (closed_paren != ')') {
ParseWorldFileError(
"Invalid syntax: expected closed parenthesis but found " +
std::string(1, closed_paren),
line_number);
}
}
/*====================================================================================================================*/
/* END OF HELPER FUNCTIONS */
/*====================================================================================================================*/
/*====================================================================================================================*/
/* OTHER FUNCTIONS USED TO MANIPULATE THE IMAGE */
/*====================================================================================================================*/
/***************************************************************************
* Function: PopulateBoard
* Description:
* Creates the graphical interface a user may be interacting with. It may contain rocks, roads if it was initialized.
* By Default the grpahical interface will contain a blank grid with the RC Car image starting at the Top Left of the grid.
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::PopulateBoard(){
if(UsingRCGraphics_){
//color constants
const graphics::Color kWallColor(50, 50, 50);
const graphics::Color backGroundColor(245,245,245);
const graphics::Color green1(143,202,92);
const graphics::Color green2(112,178,55);
const graphics::Color grey(128, 126, 120);
const graphics::Color yellow (247,181,0);
const int lineThickness = 4;
const int wallThickness_ = 3;
const int fontsize = 16;
const int margin = 32;
RCWorldImage_.DrawRectangle(0,0,XDim_*pxPerCell_-1,YDim_*pxPerCell_-1,backGroundColor);
//Horizontal Lines
for (int i = 0; i <= YDim_; i++) {
// Draw horizontal lines and indexes.
int x = pxPerCell_ * XDim_;
int y = i * pxPerCell_;
RCWorldImage_.DrawLine(0, y, x, y, kWallColor, wallThickness_);
//Adding Green Horizonal lines that look like grass
if(y < YDim_*pxPerCell_){
if(y%100==0)
RCWorldImage_.DrawRectangle(0,y,x,pxPerCell_,green1);
else
RCWorldImage_.DrawRectangle(0,y,x,pxPerCell_,green2);
}
//Add the index to the cell
if (i < YDim_) {
RCWorldImage_.DrawText(x + fontsize / 2, y + (pxPerCell_ - fontsize) / 2,
std::to_string(YDim_ - i), fontsize, kWallColor);
}
}
//Verticle Lines
for (int i = 0; i <= XDim_; i++) {
// Draw vertical lines and indexes.
int x = i * pxPerCell_;
int y = pxPerCell_ * YDim_;
RCWorldImage_.DrawLine(x, 0, x, y, kWallColor, wallThickness_);
//adding the text of the index of the specified cell
if (i < XDim_) {
RCWorldImage_.DrawText(x + (pxPerCell_ - fontsize) / 2, y + fontsize / 2,
std::to_string(i + 1), fontsize, kWallColor);
}
}
// Adding Roads and Rocks at to the Grids
for(int i = 0; i < XDim_; i++){
for(int j = 0; j < YDim_; j++){
int x_center = i * pxPerCell_ + pxPerCell_ / 2;
int y_center = j * pxPerCell_ + pxPerCell_ / 2;
Cell& cell = world_[i][j];
int rockCount = cell.GetNumOfRocks();
//Draw the Roads
if(cell.containsRoadNorth()){
//Set the positions for the upper left corner for the rectangle drawing
int x =i * pxPerCell_ + pxPerCell_/2;
int y = j * pxPerCell_;
//Set the height of the rectangle
int height = (YDim_-1) - j;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(i*pxPerCell_, 0, 1*pxPerCell_+1,(j+1)*pxPerCell_,grey);
RCWorldImage_.DrawLine(x,(j+1)*pxPerCell_,x,0, yellow,lineThickness);
}
if(cell.containsRoadEast()){
//Set the positions for the upper left corner for the rectangle drawing
int x = i * pxPerCell_;
int y = j * pxPerCell_+pxPerCell_/2;
//Set the width of the Rectangle
int width = XDim_ -i;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(i*pxPerCell_, j*pxPerCell_, width*pxPerCell_-1,1*pxPerCell_-1,grey);
RCWorldImage_.DrawLine(x,y,XDim_*pxPerCell_-1,y , yellow,4);
}
if(cell.containsRoadSouth()){
//Set the positions for the upper left corner for the rectangle drawing
int x =i * pxPerCell_ + pxPerCell_/2;
int y = j * pxPerCell_;
//Set the height of the rectangle
int height = YDim_ - j;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(i*pxPerCell_, j*pxPerCell_, 1*pxPerCell_+1,height*pxPerCell_,grey);
RCWorldImage_.DrawLine(x,y,x, YDim_*pxPerCell_-1 , yellow,4);
}
if(cell.containsRoadWest()){
//Set the positions for the upper left corner for the rectangle drawing
int x = i * pxPerCell_;
int y = j * pxPerCell_+pxPerCell_/2;
//Draw the road and a Yellow Line in the middle of the road
RCWorldImage_.DrawRectangle(0, j*pxPerCell_, (i+1)*pxPerCell_,1*pxPerCell_,grey);
RCWorldImage_.DrawLine((i+1)*pxPerCell_,y,0,y , yellow,4);
}
//Draw Rocks and Number of Rocks
if(rockCount > 0){
//Draw the rocks. Rocks are stacked so you cant tell if theres
//more than one in a stack
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 15;
const int heightOffset = 15;
graphics::Image rockImage;
rockImage.Load("./resources/rock.bmp");
graphics::Color black(0,0,0);
//Iterate throught the rock image and print it on the World
int temp = y_center;
for(int i = 0; i < rockImage.GetWidth(); i++ ){
for(int j = 0; j < rockImage.GetHeight(); j++){
graphics::Color color = rockImage.GetColor(i,j);
//Get rid of the black pixels that boarders the image
if(color != black){
RCWorldImage_.SetColor(x_center-widthOffset,y_center-heightOffset,color);
}
y_center++;
}
y_center = temp;
x_center++;
}
if (rockCount > 1) {
// Draw the rock count in the cell if it's biger than 1.
RCWorldImage_.DrawText(x_center-widthOffset- fontsize / 4, y_center - heightOffset - fontsize / 2,
std::to_string(rockCount), fontsize, kWallColor);
}
}
}
}
}
}
/***************************************************************************
* Function: Initialize
* Description:
* parces through a file and stores the "roads", "rocks", "RC",
* in the associated index of a 2D vector
* Parameters:
* string filename: is the filename that the user can pass so we can
* prepopulate the board with "rocks" and "roads"
* Return:
* None
***************************************************************************/
void RC::Initialize(std::string filename){
if(UsingRCGraphics_){
if (!filename.size()) {
// No file. Default 10x10 blank world with no roads or rocks.
for (int i = 0; i < XDim_; i++) {
world_.push_back(std::vector<Cell>());
for (int j = 0; j < YDim_; j++) {
world_[i].push_back(Cell());
}
}
position_.orientation_ = East;
}
else { //If file exists, read the file
std::fstream world_file;
try {
world_file.open(filename);
} catch (std::ifstream::failure e) {
ParseWorldFileError("Error opening file " + filename, -1);
}
if (!world_file.is_open()) {
ParseWorldFileError("Error opening file " + filename, -1);
}
std::string line;
int line_number = 1;
//File keywords
const std::string dimension_prefix = "Dimension:";
const std::string rock_prefix = "Rock:";
const std::string road_prefix = "Road:";
const std::string rccar_prefix = "RCCar:";
//Checks if "Dimensions" exists within the file
std::string line_prefix;
char open_paren, comma, closed_paren;
if (!(world_file >> line_prefix >> open_paren >> XDim_ >> comma >>
YDim_ >> closed_paren)) {
ParseWorldFileError(
"Could not parse world dimensions from the first line", line_number);
}
if (line_prefix != dimension_prefix) {
ParseWorldFileError("Could not find \"Dimension:\" in first line",
line_number);
}
CheckParsePosition(open_paren, comma, closed_paren, line_number);
//throws an error if the "Dimentions " is less then 1 cell wide or tall
if (XDim_ < 1 || YDim_ < 1) {
ParseWorldFileError(
"Cannot load a world less than 1 cell wide or less than 1 cell "
"tall",
line_number);
}
for (int i = 0; i < XDim_; i++) {
world_.push_back(std::vector<Cell>());
for (int j = 0; j < YDim_; j++) {
world_[i].push_back(Cell());
}
}
//Read the rest of the file to get rocks and road locations.
while (world_file >> line_prefix) {
line_number++;
if (line_prefix == road_prefix) {
DirectionAndOrientation wall = ParsePositionAndOrientation(world_file, line_number);
world_[wall.x_][wall.y_].AddRoad(wall.orientation_);
}
else if (line_prefix == rock_prefix) {
DirectionAndOrientation rock = ParsePosition(world_file, line_number);
int count;
if (!(world_file >> count)) {
ParseWorldFileError("Error reading Beeper count", line_number);
}
world_[rock.x_][rock.y_].SetNumOfRock(count);
world_[rock.x_][rock.y_].setContainsRock(true);
}
else if (line_prefix == rccar_prefix) {
position_ = ParsePositionAndOrientation(world_file, line_number);
}
else{
ParseWorldFileError("Unexpected token in file: " + line_prefix, line_number);
break;
}
}
world_file.close();
}
const int margin = 32;
int min_width = 5 * pxPerCell_ + margin;
RCWorldImage_.Initialize(std::max(XDim_*pxPerCell_+margin, min_width),YDim_*pxPerCell_+margin);
PopulateBoard();
Show();
DrawRCCar();
}
}
/***************************************************************************
* Function: DrawRCCar
* Description:
* Draws the RC Car given the position and the orientation of the car
* Parameters:
* int x_pixel: is the X position of the RC Car
* int y_pixel: is the Y position of the RC Car
* Return:
* None
***************************************************************************/
void RC::DrawRCCar(int x_pixel, int y_pixel){
//depending on the direction the car is facing print out a certain pixel image to the board
switch(position_.orientation_){
case Direction::North:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 30;
const int heightOffset = 32;
graphics::Image upCarImage;
upCarImage.Load("./resources/up.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < upCarImage.GetWidth(); i++ ){
for(int j = 0; j < upCarImage.GetHeight(); j++){
graphics::Color color = upCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
case Direction::East:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 32;
const int heightOffset = 30;
graphics::Image rightCarImage;
rightCarImage.Load("./resources/right.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < rightCarImage.GetWidth(); i++ ){
for(int j = 0; j < rightCarImage.GetHeight(); j++){
graphics::Color color = rightCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
case Direction::West:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 30;
const int heightOffset = 30;
graphics::Image leftCarImage;
leftCarImage.Load("./resources/left.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < leftCarImage.GetWidth(); i++ ){
for(int j = 0; j < leftCarImage.GetHeight(); j++){
graphics::Color color = leftCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
case Direction::South:{
//Offset consts to make sure the color is set in the center of the square
const int widthOffset = 32;
const int heightOffset = 30;
graphics::Image downCarImage;
downCarImage.Load("./resources/down.bmp");
graphics::Color black(0,0,0);
int temp = y_pixel;
for(int i = 0; i < downCarImage.GetWidth(); i++ ){
for(int j = 0; j < downCarImage.GetHeight(); j++){
graphics::Color color = downCarImage.GetColor(i,j);
if(color != black){
RCWorldImage_.SetColor(x_pixel-widthOffset,y_pixel-heightOffset,color);
}
y_pixel++;
}
y_pixel = temp;
x_pixel++;
}
break;
}
}
Show();
}
/***************************************************************************
* Function: MoveForward
* Description:
* The RC Car will move one cell forward in their current direction
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::MoveForward(){
if(UsingRCGraphics_){
switch(position_.orientation_){
case Direction::North:{
if(position_.y_==-1){
std::cout << "ERROR cannot move north\n"; //x will be out of bounds
}
else{
position_.y_-=1;//Decrease x axis by 1
}
break;
}
case Direction::East:{
if(position_.x_==YDim_-1){
std::cout << "ERROR cannot move east\n"; //y will be out of bounds
}
else{
position_.x_+=1; //increase y axis by 1
}
break;
}
case Direction::South:{
if(position_.y_==XDim_-1){
std::cout << "ERROR: cannot move south"; //x will be out of bounds
}
else{
position_.y_+=1; //increase x by 1
}
break;
}
case Direction::West:{
if(position_.x_==-1){
std::cout << "ERROR: cannot move west"; //y will be out of bounds
}
else{
position_.x_-=1; //Decrease y by 1
}
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('F');
}
}
/***************************************************************************
* Function: MoveBack
* Description:
* The RC Car will move one cell backward in the opposite direction
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::MoveBack(){
if(UsingRCGraphics_){
switch(position_.orientation_){
case Direction::North:{
if(position_.x_==0){
std::cout << "ERROR cannot move north\n"; //x will be out of bounds
}
else{
position_.y_+=1;//Increase y axis by 1
}
break;
}
case Direction::East:{
if(position_.y_==YDim_-1){
std::cout << "ERROR cannot move east\n"; //y will be out of bounds
}
else{
position_.x_-=1; //decrease x axis by 1
}
break;
}
case Direction::South:{
if(position_.x_==XDim_-1){
std::cout << "ERROR: cannot move south"; //x will be out of bounds
}
else{
position_.y_-=1; //Decrease y by 1
}
break;
}
case Direction::West:{
if(position_.y_==0){
std::cout << "ERROR: cannot move west"; //y will be out of bounds
}
else{
position_.x_+=1; //Increase x by 1
}
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('B');
}
}
/***************************************************************************
* Function: TurnLeft
* Description:
* The RC Car will rotate Left of their current orientation
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::TurnLeft(){
if(UsingRCGraphics_){
//given what the current direction of the car, the car will change the direction appropriatly
switch(position_.orientation_){
case Direction::North:{
position_.orientation_=Direction::West;
break;
}
case Direction::East:{
position_.orientation_=Direction::North;
break;
}
case Direction::South:{
position_.orientation_=Direction::East;
break;
}
case Direction::West:{
position_.orientation_=Direction::South;
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('L');
}
}
/***************************************************************************
* Function: MoveRight
* Description:
* The RC Car will rotate to the Right of their current orientation
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::TurnRight(){
if(UsingRCGraphics_){
switch(position_.orientation_){
case Direction::North:{
position_.orientation_=Direction::East;
break;
}
case Direction::East:{
position_.orientation_=Direction::South;
break;
}
case Direction::South:{
position_.orientation_=Direction::West;
break;
}
case Direction::West:{
position_.orientation_=Direction::North;
break;
}
}
PopulateBoard();
DrawRCCar();
}
else
{
commandVec_.push_back('R');
}
}
/***************************************************************************
* Function: MoveForward
* Description:
* Display the current instance of the car for N ms
* Parameters:
* None
* Return:
* None
***************************************************************************/
void RC::Show(){
if(UsingRCGraphics_){
RCWorldImage_.ShowForMs(Speed_,"RC World");
}
}
void RC::CreateCommandFile()
{
// Extra insurance this function is only called when using the RC
if(UsingRCGraphics_)
return;
// Attempt to create file and write to it
try
{
std::ofstream fout(fileName_);
// Loop through and vector and print it to the file.
for(int i = 0; i < commandVec_.size(); i++)
fout << commandVec_[i];
fout.close();
}
catch(std::ofstream::failure e)
{
std::cerr << e.what() << '\n';
}
for(int i = 0; i < commandVec_.size(); i++)
std::cout << "VEC: " << commandVec_[i] << '\n';
}
void RC::SendFileToServer()
{
// Check to ensure the file we wish to send exists
// std::ifstream fin("temp.txt");
//if(!fin.good())
// throw std::runtime_error("ERROR: Couldn't find file to send to server.");
CURL* curl_ptr;
CURLcode res;
struct stat fileInfo;
curl_off_t u_speed, total_speed;
// Open the file and ensure contents are okay
FILE* fd = fopen(fileName_.c_str(), "rb");
if(!fd || fstat(fileno(fd), &fileInfo) != 0) {throw std::runtime_error("FAILED TO OPEN FILE or FILE IS EMPTY");}
// Initlaize Windows socket stuff
curl_global_init(CURL_GLOBAL_ALL);
// Initalize curl handle
curl_ptr = curl_easy_init();
if(curl_ptr)
{
// Give Curl the server address
curl_easy_setopt(curl_ptr, CURLOPT_URL, "http://107.221.75.87/");
// Tell curl we're going to be "Uploading" to the URL
curl_easy_setopt(curl_ptr, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl_ptr, CURLOPT_READDATA, fd);
curl_easy_setopt(curl_ptr, CURLOPT_VERBOSE, 1L);
// Set the File Size to what we shall upload
curl_easy_setopt(curl_ptr, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileInfo.st_size);
// Perform the Request, and grab the return code
res = curl_easy_perform(curl_ptr);
if(res != CURLE_OK)
std::cout << "CURL FAILED: " << curl_easy_strerror(res) << '\n';
else
{
curl_easy_getinfo(curl_ptr, CURLINFO_SPEED_UPLOAD_T, &u_speed);
curl_easy_getinfo(curl_ptr, CURLINFO_TOTAL_TIME_T, &total_speed);
fprintf(stderr, "UPLOAD SPEED: %" CURL_FORMAT_CURL_OFF_T " bytes/sec during %"
CURL_FORMAT_CURL_OFF_T ".%01d ~seconds\n",u_speed, (total_speed /(pow(10,6))), (long)(total_speed % 1000000));
}
// Cleanup Resources
curl_easy_cleanup(curl_ptr);
}
curl_global_cleanup();
}
#endif
| 34.857724
| 128
| 0.504169
|
eanmcgilvery
|
0673d8a0bb1d3dbb436e0614d53d563f245fa063
| 8,212
|
cc
|
C++
|
deploy/pptracking/cpp/src/jde_predictor.cc
|
Amanda-Barbara/PaddleDetection
|
65ac13074eaaa2447c644a2df71969d8a3dd1fae
|
[
"Apache-2.0"
] | 3
|
2022-03-23T08:48:06.000Z
|
2022-03-28T01:59:34.000Z
|
deploy/pptracking/cpp/src/jde_predictor.cc
|
Amanda-Barbara/PaddleDetection
|
65ac13074eaaa2447c644a2df71969d8a3dd1fae
|
[
"Apache-2.0"
] | null | null | null |
deploy/pptracking/cpp/src/jde_predictor.cc
|
Amanda-Barbara/PaddleDetection
|
65ac13074eaaa2447c644a2df71969d8a3dd1fae
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sstream>
// for setprecision
#include <chrono>
#include <iomanip>
#include "include/jde_predictor.h"
using namespace paddle_infer; // NOLINT
namespace PaddleDetection {
// Load Model and create model predictor
void JDEPredictor::LoadModel(const std::string& model_dir,
const std::string& run_mode) {
paddle_infer::Config config;
std::string prog_file = model_dir + OS_PATH_SEP + "model.pdmodel";
std::string params_file = model_dir + OS_PATH_SEP + "model.pdiparams";
config.SetModel(prog_file, params_file);
if (this->device_ == "GPU") {
config.EnableUseGpu(200, this->gpu_id_);
config.SwitchIrOptim(true);
// use tensorrt
if (run_mode != "paddle") {
auto precision = paddle_infer::Config::Precision::kFloat32;
if (run_mode == "trt_fp32") {
precision = paddle_infer::Config::Precision::kFloat32;
} else if (run_mode == "trt_fp16") {
precision = paddle_infer::Config::Precision::kHalf;
} else if (run_mode == "trt_int8") {
precision = paddle_infer::Config::Precision::kInt8;
} else {
printf(
"run_mode should be 'paddle', 'trt_fp32', 'trt_fp16' or "
"'trt_int8'");
}
// set tensorrt
config.EnableTensorRtEngine(1 << 30,
1,
this->min_subgraph_size_,
precision,
false,
this->trt_calib_mode_);
}
} else if (this->device_ == "XPU") {
config.EnableXpu(10 * 1024 * 1024);
} else {
config.DisableGpu();
if (this->use_mkldnn_) {
config.EnableMKLDNN();
// cache 10 different shapes for mkldnn to avoid memory leak
config.SetMkldnnCacheCapacity(10);
}
config.SetCpuMathLibraryNumThreads(this->cpu_math_library_num_threads_);
}
config.SwitchUseFeedFetchOps(false);
config.SwitchIrOptim(true);
config.DisableGlogInfo();
// Memory optimization
config.EnableMemoryOptim();
predictor_ = std::move(CreatePredictor(config));
}
void FilterDets(const float conf_thresh,
const cv::Mat dets,
std::vector<int>* index) {
for (int i = 0; i < dets.rows; ++i) {
float score = *dets.ptr<float>(i, 4);
if (score > conf_thresh) {
index->push_back(i);
}
}
}
void JDEPredictor::Preprocess(const cv::Mat& ori_im) {
// Clone the image : keep the original mat for postprocess
cv::Mat im = ori_im.clone();
preprocessor_.Run(&im, &inputs_);
}
void JDEPredictor::Postprocess(const cv::Mat dets,
const cv::Mat emb,
MOTResult* result) {
result->clear();
std::vector<Track> tracks;
std::vector<int> valid;
FilterDets(conf_thresh_, dets, &valid);
cv::Mat new_dets, new_emb;
for (int i = 0; i < valid.size(); ++i) {
new_dets.push_back(dets.row(valid[i]));
new_emb.push_back(emb.row(valid[i]));
}
JDETracker::instance()->update(new_dets, new_emb, &tracks);
if (tracks.size() == 0) {
MOTTrack mot_track;
Rect ret = {*dets.ptr<float>(0, 0),
*dets.ptr<float>(0, 1),
*dets.ptr<float>(0, 2),
*dets.ptr<float>(0, 3)};
mot_track.ids = 1;
mot_track.score = *dets.ptr<float>(0, 4);
mot_track.rects = ret;
result->push_back(mot_track);
} else {
std::vector<Track>::iterator titer;
for (titer = tracks.begin(); titer != tracks.end(); ++titer) {
if (titer->score < threshold_) {
continue;
} else {
float w = titer->ltrb[2] - titer->ltrb[0];
float h = titer->ltrb[3] - titer->ltrb[1];
bool vertical = w / h > 1.6;
float area = w * h;
if (area > min_box_area_ && !vertical) {
MOTTrack mot_track;
Rect ret = {
titer->ltrb[0], titer->ltrb[1], titer->ltrb[2], titer->ltrb[3]};
mot_track.rects = ret;
mot_track.score = titer->score;
mot_track.ids = titer->id;
result->push_back(mot_track);
}
}
}
}
}
void JDEPredictor::Predict(const std::vector<cv::Mat> imgs,
const double threshold,
MOTResult* result,
std::vector<double>* times) {
auto preprocess_start = std::chrono::steady_clock::now();
int batch_size = imgs.size();
// in_data_batch
std::vector<float> in_data_all;
std::vector<float> im_shape_all(batch_size * 2);
std::vector<float> scale_factor_all(batch_size * 2);
// Preprocess image
for (int bs_idx = 0; bs_idx < batch_size; bs_idx++) {
cv::Mat im = imgs.at(bs_idx);
Preprocess(im);
im_shape_all[bs_idx * 2] = inputs_.im_shape_[0];
im_shape_all[bs_idx * 2 + 1] = inputs_.im_shape_[1];
scale_factor_all[bs_idx * 2] = inputs_.scale_factor_[0];
scale_factor_all[bs_idx * 2 + 1] = inputs_.scale_factor_[1];
in_data_all.insert(
in_data_all.end(), inputs_.im_data_.begin(), inputs_.im_data_.end());
}
// Prepare input tensor
auto input_names = predictor_->GetInputNames();
for (const auto& tensor_name : input_names) {
auto in_tensor = predictor_->GetInputHandle(tensor_name);
if (tensor_name == "image") {
int rh = inputs_.in_net_shape_[0];
int rw = inputs_.in_net_shape_[1];
in_tensor->Reshape({batch_size, 3, rh, rw});
in_tensor->CopyFromCpu(in_data_all.data());
} else if (tensor_name == "im_shape") {
in_tensor->Reshape({batch_size, 2});
in_tensor->CopyFromCpu(im_shape_all.data());
} else if (tensor_name == "scale_factor") {
in_tensor->Reshape({batch_size, 2});
in_tensor->CopyFromCpu(scale_factor_all.data());
}
}
auto preprocess_end = std::chrono::steady_clock::now();
std::vector<int> bbox_shape;
std::vector<int> emb_shape;
// Run predictor
auto inference_start = std::chrono::steady_clock::now();
predictor_->Run();
// Get output tensor
auto output_names = predictor_->GetOutputNames();
auto bbox_tensor = predictor_->GetOutputHandle(output_names[0]);
bbox_shape = bbox_tensor->shape();
auto emb_tensor = predictor_->GetOutputHandle(output_names[1]);
emb_shape = emb_tensor->shape();
// Calculate bbox length
int bbox_size = 1;
for (int j = 0; j < bbox_shape.size(); ++j) {
bbox_size *= bbox_shape[j];
}
// Calculate emb length
int emb_size = 1;
for (int j = 0; j < emb_shape.size(); ++j) {
emb_size *= emb_shape[j];
}
bbox_data_.resize(bbox_size);
bbox_tensor->CopyToCpu(bbox_data_.data());
emb_data_.resize(emb_size);
emb_tensor->CopyToCpu(emb_data_.data());
auto inference_end = std::chrono::steady_clock::now();
// Postprocessing result
auto postprocess_start = std::chrono::steady_clock::now();
result->clear();
cv::Mat dets(bbox_shape[0], 6, CV_32FC1, bbox_data_.data());
cv::Mat emb(bbox_shape[0], emb_shape[1], CV_32FC1, emb_data_.data());
Postprocess(dets, emb, result);
auto postprocess_end = std::chrono::steady_clock::now();
std::chrono::duration<float> preprocess_diff =
preprocess_end - preprocess_start;
(*times)[0] += static_cast<double>(preprocess_diff.count() * 1000);
std::chrono::duration<float> inference_diff = inference_end - inference_start;
(*times)[1] += static_cast<double>(inference_diff.count() * 1000);
std::chrono::duration<float> postprocess_diff =
postprocess_end - postprocess_start;
(*times)[2] += static_cast<double>(postprocess_diff.count() * 1000);
}
} // namespace PaddleDetection
| 34.79661
| 80
| 0.629445
|
Amanda-Barbara
|
067538bdca83fd2d62096ca981783b95168c04bf
| 1,271
|
cpp
|
C++
|
Engine/Source/honey.cpp
|
bugsbycarlin/Honey
|
56902979eb746c8dff5c8bcfc531fbf855c0bae5
|
[
"MIT"
] | null | null | null |
Engine/Source/honey.cpp
|
bugsbycarlin/Honey
|
56902979eb746c8dff5c8bcfc531fbf855c0bae5
|
[
"MIT"
] | null | null | null |
Engine/Source/honey.cpp
|
bugsbycarlin/Honey
|
56902979eb746c8dff5c8bcfc531fbf855c0bae5
|
[
"MIT"
] | null | null | null |
/*
Honey
Copyright 2018 - Matthew Carlin
*/
#include "honey.h"
using namespace std;
namespace Honey {
Window& window = Window::instance();
ScreenManager& screenmanager = ScreenManager::instance();
Timing& timing = Timing::instance();
MathUtilities& math_utils = MathUtilities::instance();
Config& config = Config::instance();
Config& conf = config;
Config& hot_config = config;
Input& input = Input::instance();
Collisions& collisions = Collisions::instance();
Effects& effects = Effects::instance();
Layouts& layouts = Layouts::instance();
Graphics& graphics = Graphics::instance();
Sound& sound = Sound::instance();
void StartHoney(string title, int screen_width, int screen_height, bool full_screen) {
window.initialize(title, screen_width, screen_height, full_screen);
graphics.initialize();
sound.initialize();
}
void StartHoney(string title) {
// Load configuration
if (config.checkAndUpdate() != config.SUCCESS) {
exit(1);
}
int screen_width = config.getInt("layout", "screen_width");
int screen_height = config.getInt("layout", "screen_height");
bool full_screen = config.getBool("layout", "full_screen");
StartHoney(title, screen_width, screen_height, full_screen);
}
}
| 28.244444
| 88
| 0.697876
|
bugsbycarlin
|
0679cdcc3547a36811b82bd645ed2b20d5e6bf7d
| 2,787
|
cpp
|
C++
|
src/Graphics/Model.cpp
|
llGuy/Ondine
|
325c2d3ea5bd5ef5456b0181c53ad227571fada3
|
[
"MIT"
] | 1
|
2022-01-24T18:15:56.000Z
|
2022-01-24T18:15:56.000Z
|
src/Graphics/Model.cpp
|
llGuy/Ondine
|
325c2d3ea5bd5ef5456b0181c53ad227571fada3
|
[
"MIT"
] | null | null | null |
src/Graphics/Model.cpp
|
llGuy/Ondine
|
325c2d3ea5bd5ef5456b0181c53ad227571fada3
|
[
"MIT"
] | null | null | null |
#include <assert.h>
#include "Model.hpp"
namespace Ondine::Graphics {
ModelConfig::ModelConfig(uint32_t vertexCount)
: mVertexCount(vertexCount),
mAttributeCount(0),
mAttributes{},
mIndexCount(0),
mIndexType(VkIndexType(0)),
mIndices{} {
}
void ModelConfig::pushAttribute(
const Attribute &attribute, const Buffer &data) {
assert(mAttributeCount < MAX_ATTRIBUTE_COUNT);
mAttributes[mAttributeCount++] = {
attribute.size,
attribute.format,
data
};
}
void ModelConfig::configureIndices(
uint32_t indexCount, VkIndexType type, const Buffer &data) {
mIndexCount = indexCount;
mIndexType = type;
mIndices = data;
}
void ModelConfig::configureVertexInput(VulkanPipelineConfig &config) {
config.configureVertexInput(mAttributeCount, mAttributeCount);
for (int i = 0; i < mAttributeCount; ++i) {
config.setBinding(i, mAttributes[i].attribSize, VK_VERTEX_INPUT_RATE_VERTEX);
config.setBindingAttribute(i, i, mAttributes[i].format, 0);
}
}
void Model::init(const ModelConfig &def, VulkanContext &context) {
mVertexCount = def.mVertexCount;
if (def.mIndexCount > 0) {
mIndexBuffer.init(
context.device(), def.mIndices.size,
(VulkanBufferFlagBits)VulkanBufferFlag::IndexBuffer);
mIndexBuffer.fillWithStaging(
context.device(), context.commandPool(),
def.mIndices);
}
mVertexBufferCount = 0;
// For now, store each attribute in a separate vertex buffer
for (int i = 0; i < def.mAttributeCount; ++i) {
auto &attribute = def.mAttributes[i];
auto &buf = mVertexBuffers[mVertexBufferCount++];
buf.init(
context.device(), attribute.data.size,
(VulkanBufferFlagBits)VulkanBufferFlag::VertexBuffer);
buf.fillWithStaging(
context.device(), context.commandPool(),
attribute.data);
mVertexBuffersRaw[i] = buf.mBuffer;
}
mVertexBufferCount = def.mAttributeCount;
mIndexType = def.mIndexType;
mIndexCount = def.mIndexCount;
}
void Model::bindVertexBuffers(const VulkanCommandBuffer &commandBuffer) const {
VkDeviceSize *offsets = STACK_ALLOC(VkDeviceSize, mVertexBufferCount);
memset(offsets, 0, sizeof(VkDeviceSize) * mVertexBufferCount);
commandBuffer.bindVertexBuffers(
0, mVertexBufferCount, mVertexBuffersRaw, offsets);
}
void Model::bindIndexBuffer(const VulkanCommandBuffer &commandBuffer) const {
commandBuffer.bindIndexBuffer(0, mIndexType, mIndexBuffer);
}
void Model::submitForRenderIndexed(
const VulkanCommandBuffer &commandBuffer,
uint32_t instanceCount) const {
commandBuffer.drawIndexed(mIndexCount, instanceCount, 0, 0, 0);
}
void Model::submitForRender(
const VulkanCommandBuffer &commandBuffer,
uint32_t instanceCount) const {
commandBuffer.draw(mVertexCount, instanceCount, 0, 0);
}
}
| 27.323529
| 81
| 0.735199
|
llGuy
|
067cf9785dac34b7f808b923e415dea463b94629
| 50,800
|
cpp
|
C++
|
tests/codegen.cpp
|
ajor/bpftrace
|
691e1264b526b9179a610c3ae706e439efd132d3
|
[
"Apache-2.0"
] | 278
|
2016-12-28T00:51:17.000Z
|
2022-02-09T10:32:31.000Z
|
tests/codegen.cpp
|
brendangregg/bpftrace
|
4cc2e864a9bbbcb97a508bfc5a3db1cd0b5d7f95
|
[
"Apache-2.0"
] | 48
|
2017-07-10T20:17:55.000Z
|
2020-01-20T23:41:51.000Z
|
tests/codegen.cpp
|
ajor/bpftrace
|
691e1264b526b9179a610c3ae706e439efd132d3
|
[
"Apache-2.0"
] | 19
|
2017-07-28T05:49:00.000Z
|
2022-02-22T22:05:37.000Z
|
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "bpforc.h"
#include "bpftrace.h"
#include "codegen_llvm.h"
#include "driver.h"
#include "fake_map.h"
#include "semantic_analyser.h"
namespace bpftrace {
namespace test {
namespace codegen {
using ::testing::_;
TEST(codegen, populate_sections)
{
BPFtrace bpftrace;
Driver driver;
ASSERT_EQ(driver.parse_str("kprobe:foo { 1 } kprobe:bar { 1 }"), 0);
ast::SemanticAnalyser semantics(driver.root_, bpftrace);
ASSERT_EQ(semantics.analyse(), 0);
std::stringstream out;
ast::CodegenLLVM codegen(driver.root_, bpftrace);
auto bpforc = codegen.compile(true, out);
// Check sections are populated
ASSERT_EQ(bpforc->sections_.size(), 2);
ASSERT_EQ(bpforc->sections_.count("s_kprobe:foo"), 1);
ASSERT_EQ(bpforc->sections_.count("s_kprobe:bar"), 1);
}
std::string header = R"HEAD(; ModuleID = 'bpftrace'
source_filename = "bpftrace"
target datalayout = "e-m:e-p:64:64-i64:64-n32:64-S128"
target triple = "bpf-pc-linux"
)HEAD";
void test(const std::string &input, const std::string expected_output)
{
BPFtrace bpftrace;
Driver driver;
FakeMap::next_mapfd_ = 1;
ASSERT_EQ(driver.parse_str(input), 0);
ast::SemanticAnalyser semantics(driver.root_, bpftrace);
ASSERT_EQ(semantics.analyse(), 0);
ASSERT_EQ(semantics.create_maps(true), 0);
std::stringstream out;
ast::CodegenLLVM codegen(driver.root_, bpftrace);
codegen.compile(true, out);
std::string full_expected_output = header + expected_output;
EXPECT_EQ(full_expected_output, out.str());
}
TEST(codegen, empty_function)
{
test("kprobe:f { 1; }",
R"EXPECTED(; Function Attrs: norecurse nounwind readnone
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr #0 section "s_kprobe:f" {
entry:
ret i64 0
}
attributes #0 = { norecurse nounwind readnone }
)EXPECTED");
}
TEST(codegen, map_assign_int)
{
test("kprobe:f { @x = 1; }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, map_assign_string)
{
test("kprobe:f { @x = \"blah\"; }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key" = alloca i64, align 8
%str = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i8 98, i8* %1, align 1
%str.repack1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 1
store i8 108, i8* %str.repack1, align 1
%str.repack2 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 2
store i8 97, i8* %str.repack2, align 1
%str.repack3 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 3
store i8 104, i8* %str.repack3, align 1
%str.repack4 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 4
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.memset.p0i8.i64(i8* %str.repack4, i8 0, i64 60, i32 1, i1 false)
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %str, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, map_key_int)
{
test("kprobe:f { @x[11,22,33] = 44 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca [24 x i8], align 8
%1 = getelementptr inbounds [24 x i8], [24 x i8]* %"@x_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 11, i8* %1, align 8
%2 = getelementptr inbounds [24 x i8], [24 x i8]* %"@x_key", i64 0, i64 8
store i64 22, i8* %2, align 8
%3 = getelementptr inbounds [24 x i8], [24 x i8]* %"@x_key", i64 0, i64 16
store i64 33, i8* %3, align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 44, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, [24 x i8]* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, map_key_string)
{
test("kprobe:f { @x[\"a\", \"b\"] = 44 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca [128 x i8], align 1
%1 = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i8 97, i8* %1, align 1
%str.sroa.3.0..sroa_idx = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 1
%str1.sroa.0.0..sroa_idx = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 64
call void @llvm.memset.p0i8.i64(i8* %str.sroa.3.0..sroa_idx, i8 0, i64 63, i32 1, i1 false)
store i8 98, i8* %str1.sroa.0.0..sroa_idx, align 1
%str1.sroa.3.0..sroa_idx = getelementptr inbounds [128 x i8], [128 x i8]* %"@x_key", i64 0, i64 65
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.memset.p0i8.i64(i8* %str1.sroa.3.0..sroa_idx, i8 0, i64 63, i32 1, i1 false)
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 44, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, [128 x i8]* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_nsecs)
{
test("kprobe:f { @x = nsecs }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_ns = tail call i64 inttoptr (i64 5 to i64 ()*)()
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_ns, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_stack)
{
test("kprobe:f { @x = stack }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%get_stackid = tail call i64 inttoptr (i64 27 to i64 (i8*, i8*, i64)*)(i8* %0, i64 %pseudo, i64 0)
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_stackid, i64* %"@x_val", align 8
%pseudo1 = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_ustack)
{
test("kprobe:f { @x = ustack }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%get_stackid = tail call i64 inttoptr (i64 27 to i64 (i8*, i8*, i64)*)(i8* %0, i64 %pseudo, i64 256)
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_stackid, i64* %"@x_val", align 8
%pseudo1 = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_pid_tid)
{
test("kprobe:f { @x = pid; @y = tid }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%1 = lshr i64 %get_pid_tgid, 32
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 %1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%get_pid_tgid1 = call i64 inttoptr (i64 14 to i64 ()*)()
%4 = and i64 %get_pid_tgid1, 4294967295
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%6 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
store i64 %4, i64* %"@y_val", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem3 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo2, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_uid_gid)
{
test("kprobe:f { @x = uid; @y = gid }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_uid_gid = tail call i64 inttoptr (i64 15 to i64 ()*)()
%1 = and i64 %get_uid_gid, 4294967295
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 %1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%get_uid_gid1 = call i64 inttoptr (i64 15 to i64 ()*)()
%4 = lshr i64 %get_uid_gid1, 32
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%6 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
store i64 %4, i64* %"@y_val", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem3 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo2, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_cpu)
{
test("kprobe:f { @x = cpu }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_cpu_id = tail call i64 inttoptr (i64 8 to i64 ()*)()
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 %get_cpu_id, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_comm)
{
test("kprobe:f { @x = comm }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key" = alloca i64, align 8
%comm = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %comm, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.memset.p0i8.i64(i8* nonnull %1, i8 0, i64 64, i32 1, i1 false)
%get_comm = call i64 inttoptr (i64 16 to i64 (i8*, i64)*)([64 x i8]* nonnull %comm, i64 64)
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %comm, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_arg)
{
test("kprobe:f { @x = arg0; @y = arg2 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%arg2 = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%arg0 = alloca i64, align 8
%1 = bitcast i64* %arg0 to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 112
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %arg0, i64 8, i8* %2)
%3 = load i64, i64* %arg0, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
%6 = bitcast i64* %arg2 to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
%7 = getelementptr i8, i8* %0, i64 96
%probe_read1 = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %arg2, i64 8, i8* %7)
%8 = load i64, i64* %arg2, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
%9 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %9)
store i64 0, i64* %"@y_key", align 8
%10 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %10)
store i64 %8, i64* %"@y_val", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem3 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo2, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %9)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %10)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_retval)
{
test("kprobe:f { @x = retval }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%retval = alloca i64, align 8
%1 = bitcast i64* %retval to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 80
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %retval, i64 8, i8* %2)
%3 = load i64, i64* %retval, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, builtin_func)
{
test("kprobe:f { @x = func }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%func = alloca i64, align 8
%1 = bitcast i64* %func to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 128
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %func, i64 8, i8* %2)
%3 = load i64, i64* %func, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_reg) // Identical to builtin_func apart from variable names
{
test("kprobe:f { @x = reg(\"ip\") }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%reg_ip = alloca i64, align 8
%1 = bitcast i64* %reg_ip to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%2 = getelementptr i8, i8* %0, i64 128
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %reg_ip, i64 8, i8* %2)
%3 = load i64, i64* %reg_ip, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%4 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 0, i64* %"@x_key", align 8
%5 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 %3, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_quantize)
{
test("kprobe:f { @x = quantize(pid) }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%1 = lshr i64 %get_pid_tgid, 32
%2 = icmp ugt i64 %get_pid_tgid, 281474976710655
%3 = zext i1 %2 to i64
%4 = shl nuw nsw i64 %3, 4
%5 = lshr i64 %1, %4
%6 = icmp sgt i64 %5, 255
%7 = zext i1 %6 to i64
%8 = shl nuw nsw i64 %7, 3
%9 = lshr i64 %5, %8
%10 = or i64 %8, %4
%11 = icmp sgt i64 %9, 15
%12 = zext i1 %11 to i64
%13 = shl nuw nsw i64 %12, 2
%14 = lshr i64 %9, %13
%15 = or i64 %10, %13
%16 = icmp sgt i64 %14, 3
%17 = zext i1 %16 to i64
%18 = shl nuw nsw i64 %17, 1
%19 = lshr i64 %14, %18
%20 = or i64 %15, %18
%21 = icmp sgt i64 %19, 1
%22 = zext i1 %21 to i64
%23 = or i64 %20, %22
%24 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %24)
store i64 %23, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo, i64* nonnull %"@x_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%25 = load i64, i8* %lookup_elem, align 8
%phitmp = add i64 %25, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%26 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %26)
store i64 %lookup_elem_val.0, i64* %"@x_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %24)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %26)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_count)
{
test("kprobe:f { @x = count() }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo, i64* nonnull %"@x_key")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%2 = load i64, i8* %lookup_elem, align 8
%phitmp = add i64 %2, 1
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %phitmp, %lookup_success ], [ 1, %entry ]
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 %lookup_elem_val.0, i64* %"@x_val", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_str)
{
test("kprobe:f { @x = str(arg0) }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key" = alloca i64, align 8
%arg0 = alloca i64, align 8
%str = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.memset.p0i8.i64(i8* nonnull %1, i8 0, i64 64, i32 1, i1 false)
%2 = bitcast i64* %arg0 to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
%3 = getelementptr i8, i8* %0, i64 112
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %arg0, i64 8, i8* %3)
%4 = load i64, i64* %arg0, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%probe_read_str = call i64 inttoptr (i64 45 to i64 (i8*, i64, i8*)*)([64 x i8]* nonnull %str, i64 64, i64 %4)
%5 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@x_key", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %str, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_delete)
{
test("kprobe:f { @x = 1; delete(@x) }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_key1" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%3 = bitcast i64* %"@x_key1" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key1", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%delete_elem = call i64 inttoptr (i64 3 to i64 (i8*, i8*)*)(i64 %pseudo2, i64* nonnull %"@x_key1")
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, call_printf)
{
test("kprobe:f { printf(\"hello\\n\") }",
R"EXPECTED(%printf_t = type { i64 }
; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8*) local_unnamed_addr section "s_kprobe:f" {
entry:
%printf_args = alloca %printf_t, align 8
%1 = bitcast %printf_t* %printf_args to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, %printf_t* %printf_args, align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%get_cpu_id = tail call i64 inttoptr (i64 8 to i64 ()*)()
%perf_event_output = call i64 inttoptr (i64 25 to i64 (i8*, i8*, i64, i8*, i64)*)(i8* %0, i64 %pseudo, i64 %get_cpu_id, %printf_t* nonnull %printf_args, i64 8)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, int_propagation)
{
test("kprobe:f { @x = 1234; @y = @x }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_val" = alloca i64, align 8
%"@y_key" = alloca i64, align 8
%"@x_key1" = alloca i64, align 8
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%1 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i64 0, i64* %"@x_key", align 8
%2 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 1234, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%3 = bitcast i64* %"@x_key1" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key1", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo2, i64* nonnull %"@x_key1")
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_merge, label %lookup_success
lookup_success: ; preds = %entry
%4 = load i64, i8* %lookup_elem, align 8
br label %lookup_merge
lookup_merge: ; preds = %entry, %lookup_success
%lookup_elem_val.0 = phi i64 [ %4, %lookup_success ], [ 0, %entry ]
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%6 = bitcast i64* %"@y_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %6)
store i64 %lookup_elem_val.0, i64* %"@y_val", align 8
%pseudo3 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem4 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo3, i64* nonnull %"@y_key", i64* nonnull %"@y_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %6)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, string_propagation)
{
test("kprobe:f { @x = \"asdf\"; @y = @x }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_key" = alloca i64, align 8
%lookup_elem_val = alloca [64 x i8], align 1
%"@x_key1" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%str = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
store i8 97, i8* %1, align 1
%str.repack5 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 1
store i8 115, i8* %str.repack5, align 1
%str.repack6 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 2
store i8 100, i8* %str.repack6, align 1
%str.repack7 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 3
store i8 102, i8* %str.repack7, align 1
%str.repack8 = getelementptr inbounds [64 x i8], [64 x i8]* %str, i64 0, i64 4
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.memset.p0i8.i64(i8* %str.repack8, i8 0, i64 60, i32 1, i1 false)
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %str, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%3 = bitcast i64* %"@x_key1" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key1", align 8
%pseudo2 = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%lookup_elem = call i8* inttoptr (i64 1 to i8* (i8*, i8*)*)(i64 %pseudo2, i64* nonnull %"@x_key1")
%4 = getelementptr inbounds [64 x i8], [64 x i8]* %lookup_elem_val, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
%map_lookup_cond = icmp eq i8* %lookup_elem, null
br i1 %map_lookup_cond, label %lookup_failure, label %lookup_success
lookup_success: ; preds = %entry
call void @llvm.memcpy.p0i8.p0i8.i64(i8* nonnull %4, i8* nonnull %lookup_elem, i64 64, i32 1, i1 false)
br label %lookup_merge
lookup_failure: ; preds = %entry
call void @llvm.memset.p0i8.i64(i8* nonnull %4, i8 0, i64 64, i32 1, i1 false)
br label %lookup_merge
lookup_merge: ; preds = %lookup_failure, %lookup_success
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
%5 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %5)
store i64 0, i64* %"@y_key", align 8
%pseudo3 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem4 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo3, i64* nonnull %"@y_key", [64 x i8]* nonnull %lookup_elem_val, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %5)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, pred_binop)
{
test("kprobe:f / pid == 1234 / { @x = 1 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask = and i64 %get_pid_tgid, -4294967296
%1 = icmp eq i64 %.mask, 5299989643264
br i1 %1, label %pred_true, label %pred_false
pred_false: ; preds = %entry
ret i64 0
pred_true: ; preds = %entry
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%3 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 1, i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, variable)
{
test("kprobe:f { $var = comm; @x = $var; @y = $var }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@y_key" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%comm = alloca [64 x i8], align 1
%1 = getelementptr inbounds [64 x i8], [64 x i8]* %comm, i64 0, i64 0
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
call void @llvm.memset.p0i8.i64(i8* nonnull %1, i8 0, i64 64, i32 1, i1 false)
%get_comm = call i64 inttoptr (i64 16 to i64 (i8*, i64)*)([64 x i8]* nonnull %comm, i64 64)
%2 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %2)
store i64 0, i64* %"@x_key", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", [64 x i8]* nonnull %comm, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %2)
%3 = bitcast i64* %"@y_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@y_key", align 8
%pseudo1 = call i64 @llvm.bpf.pseudo(i64 1, i64 2)
%update_elem2 = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo1, i64* nonnull %"@y_key", [64 x i8]* nonnull %comm, i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i32, i1) #1
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, dereference)
{
test("kprobe:f { @x = *1234 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%deref = alloca i64, align 8
%1 = bitcast i64* %deref to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %1)
%probe_read = call i64 inttoptr (i64 4 to i64 (i8*, i64, i8*)*)(i64* nonnull %deref, i64 8, i64 1234)
%2 = load i64, i64* %deref, align 8
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %1)
%3 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key", align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 %2, i64* %"@x_val", align 8
%pseudo = call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, logical_or)
{
test("kprobe:f { @x = pid == 1234 || pid == 1235 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask = and i64 %get_pid_tgid, -4294967296
%1 = icmp eq i64 %.mask, 5299989643264
br i1 %1, label %"||_true", label %"||_lhs_false"
"||_lhs_false": ; preds = %entry
%get_pid_tgid1 = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask2 = and i64 %get_pid_tgid1, -4294967296
%2 = icmp eq i64 %.mask2, 5304284610560
br i1 %2, label %"||_true", label %"||_merge"
"||_true": ; preds = %"||_lhs_false", %entry
br label %"||_merge"
"||_merge": ; preds = %"||_lhs_false", %"||_true"
%"||_result.0" = phi i64 [ 1, %"||_true" ], [ 0, %"||_lhs_false" ]
%3 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key", align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 %"||_result.0", i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
TEST(codegen, logical_and)
{
test("kprobe:f { @x = pid != 1234 && pid != 1235 }",
R"EXPECTED(; Function Attrs: nounwind
declare i64 @llvm.bpf.pseudo(i64, i64) #0
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.start.p0i8(i64, i8* nocapture) #1
define i64 @"kprobe:f"(i8* nocapture readnone) local_unnamed_addr section "s_kprobe:f" {
entry:
%"@x_val" = alloca i64, align 8
%"@x_key" = alloca i64, align 8
%get_pid_tgid = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask = and i64 %get_pid_tgid, -4294967296
%1 = icmp eq i64 %.mask, 5299989643264
br i1 %1, label %"&&_false", label %"&&_lhs_true"
"&&_lhs_true": ; preds = %entry
%get_pid_tgid1 = tail call i64 inttoptr (i64 14 to i64 ()*)()
%.mask2 = and i64 %get_pid_tgid1, -4294967296
%2 = icmp eq i64 %.mask2, 5304284610560
br i1 %2, label %"&&_false", label %"&&_merge"
"&&_false": ; preds = %"&&_lhs_true", %entry
br label %"&&_merge"
"&&_merge": ; preds = %"&&_lhs_true", %"&&_false"
%"&&_result.0" = phi i64 [ 0, %"&&_false" ], [ 1, %"&&_lhs_true" ]
%3 = bitcast i64* %"@x_key" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %3)
store i64 0, i64* %"@x_key", align 8
%4 = bitcast i64* %"@x_val" to i8*
call void @llvm.lifetime.start.p0i8(i64 -1, i8* nonnull %4)
store i64 %"&&_result.0", i64* %"@x_val", align 8
%pseudo = tail call i64 @llvm.bpf.pseudo(i64 1, i64 1)
%update_elem = call i64 inttoptr (i64 2 to i64 (i8*, i8*, i8*, i64)*)(i64 %pseudo, i64* nonnull %"@x_key", i64* nonnull %"@x_val", i64 0)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %3)
call void @llvm.lifetime.end.p0i8(i64 -1, i8* nonnull %4)
ret i64 0
}
; Function Attrs: argmemonly nounwind
declare void @llvm.lifetime.end.p0i8(i64, i8* nocapture) #1
attributes #0 = { nounwind }
attributes #1 = { argmemonly nounwind }
)EXPECTED");
}
} // namespace codegen
} // namespace test
} // namespace bpftrace
| 38.253012
| 161
| 0.657618
|
ajor
|
067d73d95df0b29938dd67d299227f270e8608d1
| 6,695
|
inl
|
C++
|
Library/Sources/Stroika/Foundation/Execution/WaitForIOReady.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 28
|
2015-09-22T21:43:32.000Z
|
2022-02-28T01:35:01.000Z
|
Library/Sources/Stroika/Foundation/Execution/WaitForIOReady.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 98
|
2015-01-22T03:21:27.000Z
|
2022-03-02T01:47:00.000Z
|
Library/Sources/Stroika/Foundation/Execution/WaitForIOReady.inl
|
SophistSolutions/Stroika
|
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
|
[
"MIT"
] | 4
|
2019-02-21T16:45:25.000Z
|
2022-02-18T13:40:04.000Z
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_WaitForIOReady_inl_
#define _Stroika_Foundation_Execution_WaitForIOReady_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "TimeOutException.h"
namespace Stroika::Foundation::Execution {
/*
********************************************************************************
************************** Execution::WaitForIOReady ***************************
********************************************************************************
*/
template <typename T, typename TRAITS>
inline WaitForIOReady<T, TRAITS>::WaitForIOReady (const Traversal::Iterable<pair<T, TypeOfMonitorSet>>& fds, optional<pair<SDKPollableType, TypeOfMonitorSet>> pollable2Wakeup)
// Containers::Collection{} to force CLONE/FREEZE of data, since elsewise it chould change without this class knowing (iterables not necessarily COW)
: fPollData_{Containers::Collection<pair<T, TypeOfMonitorSet>>{fds}}
, fPollable2Wakeup_{pollable2Wakeup}
{
//DbgTrace (L"WaitForIOReady::CTOR (%s, %s)", Characters::ToString (fds).c_str (), Characters::ToString (pollable2Wakeup).c_str ());
}
template <typename T, typename TRAITS>
WaitForIOReady<T, TRAITS>::WaitForIOReady (const Traversal::Iterable<T>& fds, const TypeOfMonitorSet& flags, optional<pair<SDKPollableType, TypeOfMonitorSet>> pollable2Wakeup)
: WaitForIOReady{fds.template Select<pair<T, TypeOfMonitorSet>> ([&] (const T& t) { return make_pair (t, flags); }), pollable2Wakeup}
{
}
template <typename T, typename TRAITS>
WaitForIOReady<T, TRAITS>::WaitForIOReady (T fd, const TypeOfMonitorSet& flags, optional<pair<SDKPollableType, TypeOfMonitorSet>> pollable2Wakeup)
: WaitForIOReady{Containers::Collection<pair<T, TypeOfMonitorSet>>{make_pair (fd, flags)}, pollable2Wakeup}
{
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::GetDescriptors () const -> Traversal::Iterable<pair<T, TypeOfMonitorSet>>
{
return fPollData_;
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::Wait (Time::DurationSecondsType waitFor) -> Containers::Set<T>
{
return WaitUntil (waitFor + Time::GetTickCount ());
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::Wait (const Time::Duration& waitFor) -> Containers::Set<T>
{
return WaitUntil (waitFor.As<Time::DurationSecondsType> () + Time::GetTickCount ());
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::WaitQuietly (Time::DurationSecondsType waitFor) -> Containers::Set<T>
{
return WaitQuietlyUntil (waitFor + Time::GetTickCount ());
}
template <typename T, typename TRAITS>
inline auto WaitForIOReady<T, TRAITS>::WaitQuietly (const Time::Duration& waitFor) -> Containers::Set<T>
{
return WaitQuietly (waitFor.As<Time::DurationSecondsType> ());
}
template <typename T, typename TRAITS>
auto WaitForIOReady<T, TRAITS>::WaitUntil (Time::DurationSecondsType timeoutAt) -> Containers::Set<T>
{
Containers::Set<T> result = WaitQuietlyUntil (timeoutAt);
if (result.empty ()) {
Execution::ThrowTimeoutExceptionAfter (timeoutAt); // maybe returning 0 entries without timeout, because of fPollable2Wakeup_
}
return result;
}
template <typename T, typename TRAITS>
auto WaitForIOReady<T, TRAITS>::WaitQuietlyUntil (Time::DurationSecondsType timeoutAt) -> Containers::Set<T>
{
Thread::CheckForInterruption ();
vector<pair<SDKPollableType, TypeOfMonitorSet>> pollBuffer;
vector<T> mappedObjectBuffer;
// @todo REDO THIS calling FillBuffer_ from CTOR (since always used at least once, but could be more than once.
FillBuffer_ (&pollBuffer, &mappedObjectBuffer);
Assert (pollBuffer.size () == mappedObjectBuffer.size () or pollBuffer.size () == mappedObjectBuffer.size () + 1);
Containers::Set<T> result;
for (size_t i : _WaitQuietlyUntil (Containers::Start (pollBuffer), Containers::End (pollBuffer), timeoutAt)) {
if (i == mappedObjectBuffer.size ()) {
Assert (fPollable2Wakeup_); // externally signalled to wakeup
}
else {
Assert (i < mappedObjectBuffer.size ());
result.Add (mappedObjectBuffer[i]);
}
}
return result;
}
template <typename T, typename TRAITS>
void WaitForIOReady<T, TRAITS>::FillBuffer_ (vector<pair<SDKPollableType, TypeOfMonitorSet>>* pollBuffer, vector<T>* mappedObjectBuffer)
{
RequireNotNull (pollBuffer);
RequireNotNull (mappedObjectBuffer);
Require (pollBuffer->size () == 0);
Require (mappedObjectBuffer->size () == 0);
pollBuffer->reserve (fPollData_.size ());
mappedObjectBuffer->reserve (fPollData_.size ());
for (const auto& i : fPollData_) {
pollBuffer->push_back (pair<SDKPollableType, TypeOfMonitorSet>{TRAITS::GetSDKPollable (i.first), i.second});
mappedObjectBuffer->push_back (i.first);
}
if (fPollable2Wakeup_) {
pollBuffer->push_back (pair<SDKPollableType, TypeOfMonitorSet>{fPollable2Wakeup_.value ().first, fPollable2Wakeup_.value ().second});
}
}
}
namespace Stroika::Foundation::Configuration {
#if !qCompilerAndStdLib_template_specialization_internalErrorWithSpecializationSignifier_Buggy
template <>
#endif
constexpr EnumNames<Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor> DefaultNames<Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor>::k{
EnumNames<Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor>::BasicArrayInitializer{{
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eRead, L"Read"},
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eWrite, L"Write"},
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eError, L"Error"},
{Execution::WaitForIOReady_Support::WaitForIOReady_Base::TypeOfMonitor::eHUP, L"HUP"},
}}};
}
#endif /*_Stroika_Foundation_Execution_WaitForIOReady_inl_*/
| 51.899225
| 182
| 0.645706
|
SophistSolutions
|
067f9303e31723e091d394718084d79cb76f3bd0
| 950
|
cpp
|
C++
|
sociality_model_cpp/main.cpp
|
pratikunterwegs/pathomove
|
be6b509442d975909bae2a46cc01d94e74e32a41
|
[
"MIT"
] | 1
|
2022-03-16T11:20:02.000Z
|
2022-03-16T11:20:02.000Z
|
sociality_model_cpp/main.cpp
|
pratikunterwegs/pathomove
|
be6b509442d975909bae2a46cc01d94e74e32a41
|
[
"MIT"
] | 1
|
2022-01-18T12:08:44.000Z
|
2022-01-18T12:08:44.000Z
|
sociality_model_cpp/main.cpp
|
pratikunterwegs/pathomove
|
be6b509442d975909bae2a46cc01d94e74e32a41
|
[
"MIT"
] | 1
|
2022-01-18T20:29:28.000Z
|
2022-01-18T20:29:28.000Z
|
#include <vector>
#include <random>
#include <cassert>
#include <iostream>
#include <fstream>
#include <algorithm>
#include "../src/simulations.hpp"
int main(int argc, char *argv[])
{
// process cliargs
std::vector<std::string> cliArgs(argv, argv+argc);
int nFood = 5;
float landsize = 5.0f;
int foodClusters = 2;
float clusterDispersal = 1.0f;
int popsize = 5;
int genmax = 1;
int tmax = 2;
int regen_time = 1;
// prepare landscape
Resources food (nFood, landsize, foodClusters, clusterDispersal, regen_time);
food.initResources();
food.countAvailable();
std::cout << "landscape with " << foodClusters << " clusters\n";
/// export landscape
// prepare population
Population pop (popsize, 0.1, 0.2, 1, 0.3);
// pop.initPop(popsize);
pop.setTrait();
std::cout << pop.nAgents << " agents over " << genmax << " gens of " << tmax << " timesteps\n";
return 0;
}
| 25
| 99
| 0.624211
|
pratikunterwegs
|
068378d6af38e997dad71e711f19708f7238cf00
| 3,053
|
cpp
|
C++
|
tokenizer.cpp
|
CreativeGP/c2js
|
8d06404d4d72918d83eacb49fe6e9353ab7aece4
|
[
"MIT"
] | null | null | null |
tokenizer.cpp
|
CreativeGP/c2js
|
8d06404d4d72918d83eacb49fe6e9353ab7aece4
|
[
"MIT"
] | null | null | null |
tokenizer.cpp
|
CreativeGP/c2js
|
8d06404d4d72918d83eacb49fe6e9353ab7aece4
|
[
"MIT"
] | null | null | null |
#include "tokenizer.h"
#include "util.h"
#include <fstream>
Tokenizer::Tokenizer() {}
Tokenizer::~Tokenizer() {}
int Tokenizer::add_token(string value, uint line, uint col) {
if (value == "")
return -1;
tokens.push_back(Token {value, line, col});
tokenvals.push_back(value);
return 0;
}
int Tokenizer::set(string key, string value) {
settings.insert(make_pair(key, value));
return 0;
}
int Tokenizer::preset(string name) {
if (name == "c" || name == "cpp") {
set("specials", "!#$%&()-^\\@[;:],./=~|`{+*}<>?");
set("escaper", "\"'");
set("ignores", "");
set("ignoresplit", " \t\n");
return 0;
}
return -1;
}
int Tokenizer::tokenize(string code) {
string specials = settings.at("specials");
string ignores = settings.at("ignores");
string escaper = settings.at("escaper");
string ignoresplit = settings.at("ignoresplit");
tokens.clear();
string little = "";
int mode = 0;
uint line = 1;
uint col = 1;
for (int i = 0; i < code.length(); ++i) {
col++;
if (code[i] == '\n') {
add_token(little, line, col);
little = "";
line++;
col = 0;
}
if (ignores.find(code[i]) != string::npos) continue;
if (ignoresplit.find(code[i]) != string::npos && mode == 0) {
add_token(little, line, col);
little = "";
continue;
}
if (mode != 0) {
char escape_chr = escaper[mode-escape_mode_padding];
if ((code[i-2] == '\\' || code[i-1] != '\\') && code[i] == escape_chr) {
add_token(little+escape_chr, line, col);
// add_token(little, line, col);
// tokens.push_back(Token {ctos(escape_chr), line, col});
// tokenvals.push_back(ctos(escape_chr));
mode = 0;
little = "";
} else little += code[i];
} else {
if (escaper.find(code[i]) != string::npos) {
mode = escape_mode_padding + escaper.find(code[i]);
// "foofoo" を " foofoo " とするか "foofoo" と解釈するか, 今は後者採用
little += code[i];
// add_token(ctos(code[i]), line, col);
continue;
}
if (specials.find(code[i]) != string::npos) {
add_token(little, line, col);
little = "";
tokens.push_back(Token {ctos(code[i]), line, col});
tokenvals.push_back(ctos(code[i]));
} else little += code[i];
}
}
add_token(little, line, col);
return 0;
}
int Tokenizer::tokenize_file(string filename) {
ifstream ifs(filename);
if (!ifs) return -1;
ifs.seekg(0, ifs.end);
int length = ifs.tellg();
ifs.seekg(0, ifs.beg);
char *buffer = new char[length+1];
ifs.read(buffer, length+1);
buffer[length] = '\0';
tokenize(buffer);
delete[] buffer;
return 0;
}
| 25.655462
| 84
| 0.496561
|
CreativeGP
|
068638527269bdc8b38aa4b45d95301f6697a5d2
| 15,390
|
hpp
|
C++
|
include/memoria/core/memory/smart_ptrs.hpp
|
victor-smirnov/memoria
|
c36a957c63532176b042b411b1646c536e71a658
|
[
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2
|
2021-07-30T16:54:24.000Z
|
2021-09-08T15:48:17.000Z
|
include/memoria/core/memory/smart_ptrs.hpp
|
victor-smirnov/memoria
|
c36a957c63532176b042b411b1646c536e71a658
|
[
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | null | null | null |
include/memoria/core/memory/smart_ptrs.hpp
|
victor-smirnov/memoria
|
c36a957c63532176b042b411b1646c536e71a658
|
[
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2
|
2020-03-14T15:15:25.000Z
|
2020-06-15T11:26:56.000Z
|
// Copyright 2018 Victor Smirnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memoria/core/types.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/smart_ptr/local_shared_ptr.hpp>
#include <boost/smart_ptr/make_local_shared.hpp>
#include <boost/smart_ptr/atomic_shared_ptr.hpp>
namespace memoria {
#ifdef MMA_NO_REACTOR
static inline int32_t current_cpu() {return 0;}
static inline int32_t number_of_cpus() {return 1;}
template <typename T>
using SharedPtr = boost::shared_ptr<T>;
template <typename T>
using LocalSharedPtr = boost::local_shared_ptr<T>;
template <typename T, typename... Args>
auto MakeShared(Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeSharedAt(int cpu, Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeLocalShared(Args&&... args) {
return boost::make_local_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateSharedAt(int32_t cpu, const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_local_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T>
using EnableSharedFromThis = boost::enable_shared_from_this<T>;
using EnableSharedFromRaw = boost::enable_shared_from_raw;
template <typename T>
using WeakPtr = boost::weak_ptr<T>;
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
#else
namespace reactor {
int32_t current_cpu();
int32_t number_of_cpus();
}
/*
template <typename T>
using SharedPtr = reactor::shared_ptr<T>;
template <typename T>
using LocalSharedPtr = reactor::local_shared_ptr<T>;
template <typename T, typename... Args>
auto MakeShared(Args&&... args) {
return reactor::make_shared_at<T>(reactor::current_cpu(), std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeSharedAt(int32_t cpu, Args&&... args) {
return reactor::make_shared_at<T>(cpu, std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeLocalShared(Args&&... args) {
return reactor::make_local_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateShared(const Allocator& alloc, Args&&... args) {
return reactor::allocate_shared_at<T>(reactor::current_cpu(), alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(int32_t cpu, const Allocator& alloc, Args&&... args) {
return reactor::allocate_shared_at<T>(cpu, alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(const Allocator& alloc, Args&&... args) {
return reactor::allocate_local_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T>
using EnableSharedFromThis = reactor::enable_shared_from_this<T>;
using EnableSharedFromRaw = reactor::enable_shared_from_raw;
template <typename T>
using WeakPtr = reactor::weak_ptr<T>;
template<typename T, typename U>
reactor::shared_ptr<T> StaticPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::static_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> StaticPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::shared_ptr<T> DynamicPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> DynamicPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::shared_ptr<T> ReinterpretPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> ReinterpretPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::shared_ptr<T> ConstPointerCast( const reactor::shared_ptr<U>& r ) noexcept {
return reactor::const_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::shared_ptr<T> ConstPointerCast( reactor::shared_ptr<U>&& r ) noexcept {
return reactor::const_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> StaticPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::static_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> StaticPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> DynamicPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> DynamicPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ReinterpretPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ReinterpretPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ConstPointerCast( const reactor::local_shared_ptr<U>& r ) noexcept {
return reactor::const_pointer_cast<T>(r);
}
template<typename T, typename U>
reactor::local_shared_ptr<T> ConstPointerCast( reactor::local_shared_ptr<U>&& r ) noexcept {
return reactor::const_pointer_cast<T>(std::move(r));
}
*/
template <typename T>
using SharedPtr = boost::shared_ptr<T>;
template <typename T>
using LocalSharedPtr = boost::local_shared_ptr<T>;
template <typename T, typename... Args>
auto MakeShared(Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeSharedAt(int cpu, Args&&... args) {
return boost::make_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename... Args>
auto MakeLocalShared(Args&&... args) {
return boost::make_local_shared<T>(std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateSharedAt(int32_t cpu, const Allocator& alloc, Args&&... args) {
return boost::allocate_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T, typename Allocator, typename... Args>
auto AllocateLocalShared(const Allocator& alloc, Args&&... args) {
return boost::allocate_local_shared<T>(alloc, std::forward<Args>(args)...);
}
template <typename T>
using EnableSharedFromThis = boost::enable_shared_from_this<T>;
using EnableSharedFromRaw = boost::enable_shared_from_raw;
template <typename T>
using WeakPtr = boost::weak_ptr<T>;
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> StaticPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> DynamicPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ReinterpretPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( const boost::shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::shared_ptr<T> ConstPointerCast( boost::shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::static_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> StaticPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::static_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::dynamic_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> DynamicPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::dynamic_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ReinterpretPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::reinterpret_pointer_cast<T>(std::move(r));
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( const boost::local_shared_ptr<U>& r ) noexcept {
return boost::const_pointer_cast<T>(r);
}
template<typename T, typename U>
boost::local_shared_ptr<T> ConstPointerCast( boost::local_shared_ptr<U>&& r ) noexcept {
return boost::const_pointer_cast<T>(std::move(r));
}
#endif
template <typename T, typename DtrT>
class ScopedDtr {
T* ptr_;
DtrT dtr_;
public:
ScopedDtr(T* ptr, DtrT dtr = [](T* ptr) { delete ptr; }) :
ptr_(ptr), dtr_(std::move(dtr))
{}
ScopedDtr(ScopedDtr&& other) :
ptr_(other.ptr_), dtr_(std::move(other.dtr_))
{
other.ptr_ = nullptr;
}
ScopedDtr(const ScopedDtr&) = delete;
~ScopedDtr() noexcept {
if (ptr_) dtr_(ptr_);
}
ScopedDtr& operator=(ScopedDtr&& other)
{
if (&other != this)
{
if (ptr_) {
dtr_(ptr_);
}
ptr_ = other.ptr_;
other.ptr_ = nullptr;
dtr_ = std::move(other.dtr_);
}
return this;
}
template <typename TT, typename FFn>
bool operator==(const ScopedDtr<TT, FFn>& other) const {
return ptr_ == other.get();
}
T* operator->() const {
return ptr_;
}
T* get() const {
return ptr_;
}
operator bool() const {
return ptr_ != nullptr;
}
};
template <typename T, typename Fn>
auto MakeScopedDtr(T* ptr, Fn&& dtr) {
return ScopedDtr<T, Fn>(ptr, std::forward<Fn>(dtr));
}
template <typename DtrT>
class OnScopeExit {
DtrT dtr_;
public:
OnScopeExit(DtrT&& dtr) :
dtr_(std::move(dtr))
{}
OnScopeExit(OnScopeExit&& other): dtr_(std::move(other.dtr_)) {}
OnScopeExit(const OnScopeExit&) = delete;
~OnScopeExit() noexcept {
dtr_();
}
};
template <typename Fn>
auto MakeOnScopeExit(Fn&& dtr) {
return OnScopeExit<Fn>(std::forward<Fn>(dtr));
}
}
| 27.190813
| 103
| 0.724756
|
victor-smirnov
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.