hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
42c83341197feafa97d7aabb293f15d88d120486 | 11,186 | cpp | C++ | src/debug.cpp | luizschonarth/JVM-8 | b828d1e12072b71cbadeb924b7b13661d300f798 | [
"MIT"
] | null | null | null | src/debug.cpp | luizschonarth/JVM-8 | b828d1e12072b71cbadeb924b7b13661d300f798 | [
"MIT"
] | 24 | 2022-03-12T18:38:22.000Z | 2022-03-28T00:29:03.000Z | src/debug.cpp | luizschonarth/JVM-8 | b828d1e12072b71cbadeb924b7b13661d300f798 | [
"MIT"
] | null | null | null | #include "../include/bytecode.hpp"
#include "../include/dump_class_file.hpp"
#include <iostream>
using namespace std;
extern ofstream outfile;
/**
* @brief Dumps the information about the bipush instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void bipush_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 byte = code[++code_index];
outfile << " " << (int)byte;
}
/**
* @brief Dumps the information about the iinc instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void iinc_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 index = code[++code_index];
u1 _const = code[++code_index];
outfile << " " << (int)index << " by " << (int)_const;
}
/**
* @brief Dumps the information about the iinc(wide) instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void iinc_wide_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 indexbyte1 = code[++code_index];
u1 indexbyte2 = code[++code_index];
u1 constbyte1 = code[++code_index];
u1 constbyte2 = code[++code_index];
u2 index = ((u2)indexbyte1 << 8) | indexbyte2;
u2 _const = ((u2)constbyte1 << 8) | constbyte2;
outfile << " #" << (int)index << " <" << (int)_const << "> ";
}
/**
* @brief Dumps the information about the index instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void index_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 index = code[++code_index];
outfile << " " << (int)index;
}
/**
* @brief Dumps the information about the index(wide) instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void index_wide_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 indexbyte1 = code[++code_index];
u1 indexbyte2 = code[++code_index];
u2 index = ((u2)indexbyte1 << 8) | indexbyte2;
outfile << " #" << (int)index;
}
/**
* @brief Dumps the information about the invoke instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void invoke_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
reference_debug(code_index, constant_pool, code);
u1 count = code[++code_index];
u1 zero = code[++code_index];
}
/**
* @brief Dumps the information about the jump instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void jump_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
s2 old_index = code_index;
u1 branchbyte1 = code[++code_index];
u1 branchbyte2 = code[++code_index];
s2 branchoffset = ((s2)branchbyte1 << 8) | branchbyte2;
outfile << " " << old_index + branchoffset << " (" << branchoffset << ")";
}
/**
* @brief Dumps the information about the jump(wide) instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void jump_wide_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
s4 old_index = code_index;
u1 branchbyte1 = code[++code_index];
u1 branchbyte2 = code[++code_index];
u1 branchbyte3 = code[++code_index];
u1 branchbyte4 = code[++code_index];
s4 branchoffset = ((s4)branchbyte1 << 24) | ((s4)branchbyte2 << 16) | ((s4)branchbyte3 << 8) | branchbyte4;
outfile << " " << old_index + branchoffset << " (" << branchoffset << ")";
}
/**
* @brief Dumps the information about the lookupswitch instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void lookupswitch_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u4 old_index = code_index;
u1 padding = (++code_index) % 4;
s4 defaultbyte1 = code[padding + code_index++] << 24;
s4 defaultbyte2 = code[padding + code_index++] << 16;
s4 defaultbyte3 = code[padding + code_index++] << 8;
s4 defaultbyte4 = code[padding + code_index++];
s4 defaultbytes = defaultbyte1 | defaultbyte2 | defaultbyte3 | defaultbyte4;
s4 npairs1 = (s4) code[padding + code_index++] << 24;
s4 npairs2 = (s4) code[padding + code_index++] << 16;
s4 npairs3 = (s4) code[padding + code_index++] << 8;
s4 npairs4 = (s4) code[padding + code_index++];
s4 npairs = npairs1 | npairs2 | npairs3 | npairs4;
outfile << " " << npairs << endl;
for (s4 n = 0; n < npairs; n++)
{
s4 matchbyte1 = code[code_index + padding++] << 24;
s4 matchbyte2 = code[code_index + padding++] << 16;
s4 matchbyte3 = code[code_index + padding++] << 8;
s4 matchbyte4 = code[code_index + padding++];
s4 matchbytes = matchbyte1 | matchbyte2 | matchbyte3 | matchbyte4;
s4 offset1 = code[code_index + padding++] << 24;
s4 offset2 = code[code_index + padding++] << 16;
s4 offset3 = code[code_index + padding++] << 8;
s4 offset4 = code[code_index + padding++];
s4 offset = offset1 | offset2 | offset3 | offset4;
outfile << " " << matchbytes << ": " << old_index + offset << " (" << offset << ")" << endl;
}
outfile << " default: " << old_index + defaultbytes << " (" << defaultbytes << ")";
code_index += padding - 1;
}
/**
* @brief Dumps the information about the multinewarray instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void multianewarray_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 indexbyte1 = code[++code_index];
u1 indexbyte2 = code[++code_index];
u1 dimensions = code[++code_index];
u2 index = (indexbyte1 << 8) | indexbyte2;
outfile << " #" << (int)index;
auto reference = to_cp_info(constant_pool[index - 1]);
outfile << " <" << reference->get_content(constant_pool) << "> ";
outfile << "dim " << (int) dimensions;
}
/**
* @brief Dumps the information about the newarray instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void newarray_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 atype = code[++code_index];
map<u1, string> types = {
{4, "T_BOOLEAN"},
{5, "T_CHAR"},
{6, "T_FLOAT"},
{7, "T_DOUBLE"},
{8, "T_BYTE"},
{9, "T_SHORT"},
{10, "T_INT"},
{11, "T_LONG"}
};
outfile << " " << types[atype];
}
/**
* @brief Dumps the information about the reference instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void reference_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 index = code[++code_index];
outfile << " #" << (int)index;
auto reference = to_cp_info(constant_pool[index - 1]);
outfile << " <" << reference->get_content(constant_pool) << "> ";
}
/**
* @brief Dumps the information about the reference(wide) instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void reference_wide_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 indexbyte1 = code[++code_index];
u1 indexbyte2 = code[++code_index];
u2 index = ((u2)indexbyte1 << 8) | indexbyte2;
outfile << " #" << index;
auto reference = to_cp_info(constant_pool[index - 1]);
outfile << " <" << reference->get_content(constant_pool) << "> ";
}
/**
* @brief Dumps the information about the sipush instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void sipush_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 byte1 = code[++code_index];
u1 byte2 = code[++code_index];
u2 short_val = ((u1)byte1 << 8) | byte2;
outfile << " " << (int)short_val;
}
// no examples to debug tableswitch! :D
/**
* @brief Dumps the information about the tableswitch instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void tableswitch_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u4 padding = (++code_index) % 4;
auto defaultbyte1 = code[padding + code_index++] << 24;
auto defaultbyte2 = code[padding + code_index++] << 16;
auto defaultbyte3 = code[padding + code_index++] << 8;
auto defaultbyte4 = code[padding + code_index++];
auto defaultbytes = defaultbyte1 | defaultbyte2 | defaultbyte3 | defaultbyte4;
auto lowbytes1 = code[padding + code_index++] << 24;
auto lowbytes2 = code[padding + code_index++] << 16;
auto lowbytes3 = code[padding + code_index++] << 8;
auto lowbytes4 = code[padding + code_index++];
auto lowbytes = lowbytes1 | lowbytes2 | lowbytes3 | lowbytes4;
auto offsets = defaultbytes - lowbytes + 1;
for (auto n = 0; n < offsets; n++)
{
auto highbytes1 = code[padding + code_index++] << 24;
auto highbytes2 = code[padding + code_index++] << 16;
auto highbytes3 = code[padding + code_index++] << 8;
auto highbytes4 = code[padding + code_index++];
auto highbytes = highbytes1 | highbytes2 | highbytes3 | highbytes4;
outfile << lowbytes << ": " << code_index + highbytes << " (" << highbytes << ")" << endl;
lowbytes++;
}
}
/**
* @brief Dumps the information about the wide instruction
* @param code_index the current index of the bytecode
* @param constant_pool the class constant pool
* @param code the instruction vector
*/
void wide_debug(int &code_index, cp_info_vector &constant_pool, bytestream &code)
{
u1 bytecode = code[++code_index];
u1 indexbyte1 = code[++code_index];
u1 indexbyte2 = code[++code_index];
if (!mnemonic.count(bytecode))
{
cout << "Instrução não encontrada" << endl;
return;
}
if (bytecode == 0x84) // iinc
iinc_wide_debug(code_index, constant_pool, code);
else if (bytecode == 0x19) // aload
reference_wide_debug(code_index, constant_pool, code);
else
index_wide_debug(code_index, constant_pool, code);
outfile << endl;
} | 35.398734 | 111 | 0.665922 | [
"vector"
] |
42d80f48205f2e5bbd5ab590f54f39d16fc8e9a1 | 3,061 | cpp | C++ | test/test_outpoint.cpp | ko-matsu/cfd-core | ad07f210cfefe7838a6eaf4ce0e13a27c0d6167e | [
"MIT"
] | 5 | 2019-10-12T11:05:26.000Z | 2020-05-10T19:09:19.000Z | test/test_outpoint.cpp | ko-matsu/cfd-core | ad07f210cfefe7838a6eaf4ce0e13a27c0d6167e | [
"MIT"
] | 128 | 2019-10-02T06:33:49.000Z | 2022-03-20T02:14:35.000Z | test/test_outpoint.cpp | p2pderivatives/cfd-core | 399750cb1fa320f3b203092290ebb9f3ed4fe742 | [
"MIT"
] | 4 | 2019-10-22T07:59:43.000Z | 2020-05-29T11:06:00.000Z | #include "gtest/gtest.h"
#include <vector>
#include "cfdcore/cfdcore_common.h"
#include "cfdcore/cfdcore_transaction.h"
#include "cfdcore/cfdcore_coin.h"
#include "cfdcore/cfdcore_exception.h"
using cfd::core::OutPoint;
using cfd::core::Txid;
using cfd::core::ByteData256;
using cfd::core::CfdException;
TEST(OutPoint, OutPointEmpty) {
OutPoint outpoint;
EXPECT_STREQ(outpoint.GetTxid().GetHex().c_str(), "");
EXPECT_EQ(outpoint.GetTxid().GetData().GetDataSize(), 0);
EXPECT_EQ(outpoint.GetVout(), 0);
EXPECT_FALSE(outpoint.IsValid());
}
TEST(OutPoint, Constructor) {
ByteData256 byte_data = ByteData256(
"3412907856341290785634129078563412907856341290785634129078563412");
Txid txid = Txid(byte_data);
OutPoint outpoint(txid, 1);
EXPECT_STREQ(
outpoint.GetTxid().GetHex().c_str(),
"1234567890123456789012345678901234567890123456789012345678901234");
EXPECT_EQ(outpoint.GetVout(), 1);
}
TEST(OutPoint, Equals) {
ByteData256 byte_data = ByteData256(
"3412907856341290785634129078563412907856341290785634129078563412");
Txid txid = Txid(byte_data);
ByteData256 byte_data2 = ByteData256(
"9812907856341290785634129078563412907856341290785634129078563412");
Txid txid2 = Txid(byte_data2);
OutPoint outpoint1(txid, 1);
OutPoint outpoint2(txid, 1);
OutPoint outpoint3(txid, 2);
OutPoint outpoint4(txid2, 1);
EXPECT_TRUE((outpoint1 == outpoint2));
EXPECT_FALSE((outpoint1 == outpoint3));
EXPECT_FALSE((outpoint1 == outpoint4));
}
TEST(OutPoint, NotEquals) {
ByteData256 byte_data = ByteData256(
"3412907856341290785634129078563412907856341290785634129078563412");
Txid txid = Txid(byte_data);
ByteData256 byte_data2 = ByteData256(
"9812907856341290785634129078563412907856341290785634129078563412");
Txid txid2 = Txid(byte_data2);
OutPoint outpoint1(txid, 1);
OutPoint outpoint2(txid, 1);
OutPoint outpoint3(txid, 2);
OutPoint outpoint4(txid2, 1);
EXPECT_FALSE((outpoint1 != outpoint2));
EXPECT_TRUE((outpoint1 != outpoint3));
EXPECT_TRUE((outpoint1 != outpoint4));
}
TEST(OutPoint, Operators) {
ByteData256 byte_data = ByteData256(
"3412907856341290785634129078563412907856341290785634129078563412");
Txid txid = Txid(byte_data);
ByteData256 byte_data2 = ByteData256(
"9812907856341290785634129078563412907856341290785634129078563412");
Txid txid2 = Txid(byte_data2);
OutPoint outpoint1(txid, 1);
OutPoint outpoint2(txid, 1);
OutPoint outpoint3(txid, 2);
OutPoint outpoint4(txid2, 1);
EXPECT_TRUE((outpoint1 >= outpoint2));
EXPECT_FALSE((outpoint1 >= outpoint3));
EXPECT_TRUE((outpoint1 >= outpoint4));
EXPECT_FALSE((outpoint1 > outpoint2));
EXPECT_FALSE((outpoint1 > outpoint3));
EXPECT_TRUE((outpoint1 > outpoint4));
EXPECT_TRUE((outpoint1 <= outpoint2));
EXPECT_TRUE((outpoint1 <= outpoint3));
EXPECT_FALSE((outpoint1 <= outpoint4));
EXPECT_FALSE((outpoint1 < outpoint2));
EXPECT_TRUE((outpoint1 < outpoint3));
EXPECT_FALSE((outpoint1 < outpoint4));
EXPECT_TRUE((outpoint4 < outpoint3));
}
| 31.556701 | 74 | 0.747795 | [
"vector"
] |
42d9af1fceecde0174eccef3c82d88d4ee4fdb28 | 2,745 | hpp | C++ | src/Enzo/enzo_EnzoMatrixLaplace.hpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 26 | 2019-02-12T19:39:13.000Z | 2022-03-31T01:52:29.000Z | src/Enzo/enzo_EnzoMatrixLaplace.hpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 128 | 2019-02-13T20:22:30.000Z | 2022-03-29T20:21:00.000Z | src/Enzo/enzo_EnzoMatrixLaplace.hpp | aoife-flood/enzo-e | ab8ebc4716fff22bed9f692daf0472ae6ffffe73 | [
"BSD-3-Clause"
] | 29 | 2019-02-12T19:37:51.000Z | 2022-03-14T14:02:45.000Z | // See LICENSE_CELLO file for license and copyright information
/// @file enzo_EnzoMatrixLaplace.hpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2015-04-02
/// @brief [\ref Compute] Declaration of the EnzoMatrixLaplace class
#ifndef COMPUTE_MATRIX_LAPLACE_HPP
#define COMPUTE_MATRIX_LAPLACE_HPP
class EnzoMatrixLaplace : public Matrix
{
/// @class EnzoMatrixLaplace
/// @ingroup Compute
/// @brief [\ref Compute] Interface to an application compute / analysis / visualization function.
public: // interface
/// Create a new EnzoMatrixLaplace
EnzoMatrixLaplace (int order = 4) throw()
: mx_(0),
my_(0),
mz_(0),
nx_(0),
ny_(0),
nz_(0),
hx_(0.0),
hy_(0.0),
hz_(0.0),
order_(order)
{}
/// Destructor
virtual ~EnzoMatrixLaplace() throw()
{}
/// Charm++ PUP::able declarations
PUPable_decl(EnzoMatrixLaplace);
/// CHARM++ migration constructor
EnzoMatrixLaplace(CkMigrateMessage *m)
: Matrix(m),
mx_(0),
my_(0),
mz_(0),
nx_(0),
ny_(0),
nz_(0),
hx_(0.0),
hy_(0.0),
hz_(0.0),
order_(0)
{ }
/// CHARM++ Pack / Unpack function
void pup (PUP::er &p)
{ TRACEPUP;
PUP::able::pup(p);
p | mx_;
p | my_;
p | mz_;
p | nx_;
p | ny_;
p | nz_;
p | hx_;
p | hy_;
p | hz_;
p | order_;
}
/// Set cell widths. Required for lower-level methods that don't have
/// access to the Block
void set_cell_width (double hx, double hy, double hz)
{
hx_ = hx;
hy_ = hy;
hz_ = hz;
}
public: // virtual functions
/// Apply the matrix to a vector Y <-- A*X
virtual void matvec (int id_y, int id_x, Block * block, int g0=1) throw();
/// Low-level matvec, useful for non-Block arrays (e.g. Block-local
/// multigrid). Must call set_cell_width and set_dimensions first
/// manually!
virtual void matvec (precision_type precision,
void * y, void * x, int g0=1) throw();
/// Extract the diagonal into the given field
virtual void diagonal (int id_x, Block * block, int g0=1) throw();
/// Whether the matrix is singular or not
virtual bool is_singular() const throw()
{ return true; }
/// How many ghost zones required for matvec
virtual int ghost_depth() const throw()
{ return (order_ == 2) ? 1 : ( (order_ == 4) ? 2 : 3); }
protected: // functions
void matvec_ (enzo_float * Y, enzo_float * X, int g0) const throw();
void diagonal_ (enzo_float * X, int g0) const throw();
protected: // attributes
int mx_, my_, mz_;
int nx_, ny_, nz_;
double hx_, hy_, hz_;
/// Order of the operator, 2 or 4
int order_;
};
#endif /* COMPUTE_MATRIX_LAPLACE_HPP */
| 23.067227 | 103 | 0.612022 | [
"vector"
] |
42dd9283f11398d68404fe051bdec83682b9b66c | 6,162 | cpp | C++ | src/SCCommon.cpp | BradyBrenot/screen_capture_lite | 775d058408dcc393f632d2bf3483104d5d781432 | [
"MIT"
] | 3 | 2018-07-08T15:32:27.000Z | 2019-11-08T16:50:55.000Z | src/SCCommon.cpp | BradyBrenot/screen_capture_lite | 775d058408dcc393f632d2bf3483104d5d781432 | [
"MIT"
] | null | null | null | src/SCCommon.cpp | BradyBrenot/screen_capture_lite | 775d058408dcc393f632d2bf3483104d5d781432 | [
"MIT"
] | 1 | 2018-12-02T09:02:04.000Z | 2018-12-02T09:02:04.000Z | #include "SCCommon.h"
#include <algorithm>
#include <assert.h>
#include <chrono>
#include <iostream>
#include <string.h>
namespace SL {
namespace Screen_Capture {
void SanitizeRects(std::vector<ImageRect> &rects, const Image &img)
{
for (auto &r : rects) {
if (r.right > Width(img)) {
r.right = Width(img);
}
if (r.bottom > Height(img)) {
r.bottom = Height(img);
}
}
}
#define maxdist 256
std::vector<ImageRect> GetDifs(const Image &oldimg, const Image &newimg)
{
std::vector<ImageRect> rects;
if (Width(oldimg) != Width(newimg) || Height(oldimg) != Height(newimg)) {
rects.push_back(Rect(newimg));
return rects;
}
rects.reserve((Height(newimg) / maxdist) + 1 * (Width(newimg) / maxdist) + 1);
auto oldimg_ptr = (const int *)StartSrc(oldimg);
auto newimg_ptr = (const int *)StartSrc(newimg);
auto imgwidth = Width(oldimg);
auto imgheight = Height(oldimg);
for (decltype(imgheight) row = 0; row < imgheight; row += maxdist) {
for (decltype(imgwidth) col = 0; col < imgwidth; col += maxdist) {
for (decltype(row) y = row; y < maxdist + row && y < imgheight; y++) {
for (decltype(col) x = col; x < maxdist + col && x < imgwidth; x++) {
auto old = oldimg_ptr[y * imgwidth + x];
auto ne = newimg_ptr[y * imgwidth + x];
if (ne != old) {
ImageRect re;
re.left = col;
re.top = row;
re.bottom = row + maxdist;
re.right = col + maxdist;
rects.push_back(re);
y += maxdist;
x += maxdist;
}
}
}
}
}
if (rects.size() <= 2) {
SanitizeRects(rects, newimg);
return rects; // make sure there is at least 2
}
std::vector<ImageRect> outrects;
outrects.reserve(rects.size());
outrects.push_back(rects[0]);
// horizontal scan
int expandcount = 0;
int containedcount = 0;
for (size_t i = 1; i < rects.size(); i++) {
if (outrects.back().right == rects[i].left && outrects.back().bottom == rects[i].bottom) {
outrects.back().right = rects[i].right;
expandcount++;
}
else {
outrects.push_back(rects[i]);
containedcount++;
}
}
if (expandcount != 0 || containedcount != 0) {
// std::cout << "On Horizontal Scan expandcount " << expandcount << "
// containedcount " << containedcount << std::endl;
}
expandcount = 0;
containedcount = 0;
if (outrects.size() <= 2) {
SanitizeRects(outrects, newimg);
return outrects; // make sure there is at least 2
}
rects.resize(0);
// vertical scan
for (auto &otrect : outrects) {
auto found = std::find_if(rects.rbegin(), rects.rend(), [=](const ImageRect &rec) {
return rec.bottom == otrect.top && rec.left == otrect.left && rec.right == otrect.right;
});
if (found == rects.rend()) {
rects.push_back(otrect);
containedcount++;
}
else {
found->bottom = otrect.bottom;
expandcount++;
}
}
if (expandcount != 0 || containedcount != 0) {
// std::cout << "On Horizontal Scan expandcount " << expandcount << "
// containedcount " << containedcount << std::endl;
}
/* for (auto& r : rects) {
std::cout << r << std::endl;
}
*/
// std::cout << "Found " << rects.size() << " rects in img dif. It took " <<
// elapsed.count() << " milliseconds to compare run GetDifs ";
SanitizeRects(rects, newimg);
return rects;
}
Monitor CreateMonitor(int index, int id, int h, int w, int ox, int oy, const std::string &n, float scaling)
{
Monitor ret = {};
ret.Index = index;
ret.Height = h;
ret.Id = id;
assert(n.size() + 1 < sizeof(ret.Name));
memcpy(ret.Name, n.c_str(), n.size() + 1);
ret.OffsetX = ox;
ret.OffsetY = oy;
ret.Width = w;
ret.Scaling = scaling;
return ret;
}
Image Create(const ImageRect &imgrect, int pixelstride, int rowpadding, const unsigned char *data)
{
Image ret;
ret.Bounds = imgrect;
ret.Data = data;
ret.Pixelstride = pixelstride;
ret.RowPadding = rowpadding;
return ret;
}
int Index(const Monitor &mointor) { return mointor.Index; }
int Id(const Monitor &mointor) { return mointor.Id; }
int OffsetX(const Monitor &mointor) { return mointor.OffsetX; }
int OffsetY(const Monitor &mointor) { return mointor.OffsetY; }
const char *Name(const Monitor &mointor) { return mointor.Name; }
int Height(const Monitor &mointor) { return mointor.Height; }
int Width(const Monitor &mointor) { return mointor.Width; }
int Height(const ImageRect &rect) { return rect.bottom - rect.top; }
int Width(const ImageRect &rect) { return rect.right - rect.left; }
int Height(const Image &img) { return Height(img.Bounds); }
int Width(const Image &img) { return Width(img.Bounds); }
const ImageRect &Rect(const Image &img) { return img.Bounds; }
// number of bytes per row, NOT including the Rowpadding
int RowStride(const Image &img) { return img.Pixelstride * Width(img); }
// number of bytes per row of padding
int RowPadding(const Image &img) { return img.RowPadding; }
const unsigned char *StartSrc(const Image &img) { return img.Data; }
} // namespace Screen_Capture
} // namespace SL
| 36.247059 | 111 | 0.519636 | [
"vector"
] |
42eed713ec705cdcd6f90ace96956d8163f98c59 | 28,017 | cxx | C++ | style/Style.cxx | myarchsource/openjade | e2bcc48e835c52b6665cedc680d6705b765be42d | [
"FTL"
] | 1 | 2021-12-05T15:07:16.000Z | 2021-12-05T15:07:16.000Z | style/Style.cxx | myarchsource/openjade | e2bcc48e835c52b6665cedc680d6705b765be42d | [
"FTL"
] | null | null | null | style/Style.cxx | myarchsource/openjade | e2bcc48e835c52b6665cedc680d6705b765be42d | [
"FTL"
] | null | null | null | // Copyright (c) 1996 James Clark
// See the file copying.txt for copying permission.
#include "stylelib.h"
#include "Style.h"
#include "VM.h"
#include "Interpreter.h"
#include "InterpreterMessages.h"
#include "SosofoObj.h"
#include "macros.h"
#ifdef DSSSL_NAMESPACE
namespace DSSSL_NAMESPACE {
#endif
StyleStack::StyleStack()
: level_(0)
{
}
void StyleStack::pushContinue(StyleObj *style,
const ProcessingMode::Rule *rule,
const NodePtr &nodePtr,
Messenger *mgr)
{
StyleObjIter iter;
style->appendIter(iter);
for (;;) {
const VarStyleObj *varStyle;
ConstPtr<InheritedC> spec(iter.next(varStyle));
if (spec.isNull())
break;
size_t ind = spec->index();
if (ind >= inheritedCInfo_.size())
inheritedCInfo_.resize(ind + 1);
Ptr<InheritedCInfo> &info = inheritedCInfo_[ind];
if (!info.isNull() && info->valLevel == level_) {
if (rule) {
ASSERT(info->rule != 0);
if (rule->compareSpecificity(*info->rule) == 0) {
mgr->setNextLocation(info->rule->location());
mgr->message(InterpreterMessages::ambiguousStyle,
StringMessageArg(info->spec->identifier()->name()),
rule->location());
}
}
}
else {
popList_->list.push_back(ind);
info = new InheritedCInfo(spec, varStyle, level_, level_, rule, info);
}
}
}
void StyleStack::pushEnd(VM &vm, FOTBuilder &fotb)
{
const PopList *oldPopList = popList_->prev.pointer();
if (oldPopList) {
for (size_t i = 0; i < oldPopList->dependingList.size(); i++) {
size_t d = oldPopList->dependingList[i];
// d is the index of a characteristic that depends on the actual
// value of another characteritistic
if (inheritedCInfo_[d]->valLevel != level_) {
const Vector<size_t> &dependencies = inheritedCInfo_[d]->dependencies;
bool changed = 0;
for (size_t j = 0; j < dependencies.size(); j++) {
const InheritedCInfo *p = inheritedCInfo_[dependencies[j]].pointer();
if (p && p->valLevel == level_) {
inheritedCInfo_[d] = new InheritedCInfo(inheritedCInfo_[d]->spec,
inheritedCInfo_[d]->style,
level_,
inheritedCInfo_[d]->specLevel,
inheritedCInfo_[d]->rule,
inheritedCInfo_[d]);
popList_->list.push_back(d);
changed = 1;
break;
}
}
// If it changed, then doing set() on the new value will add
// it to the dependingList for this level.
if (!changed)
popList_->dependingList.push_back(d);
}
}
}
vm.styleStack = this;
for (size_t i = 0; i < popList_->list.size(); i++) {
InheritedCInfo &info = *inheritedCInfo_[popList_->list[i]];
vm.specLevel = info.specLevel;
info.spec->set(vm, info.style, fotb, info.cachedValue, info.dependencies);
if (info.dependencies.size())
popList_->dependingList.push_back(popList_->list[i]);
}
vm.styleStack = 0;
}
void StyleStack::pop()
{
for (size_t i = 0; i < popList_->list.size(); i++) {
size_t ind = popList_->list[i];
ASSERT(inheritedCInfo_[ind]->valLevel == level_);
Ptr<InheritedCInfo> tem(inheritedCInfo_[ind]->prev);
inheritedCInfo_[ind] = tem;
}
level_--;
Ptr<PopList> tem(popList_->prev);
popList_ = tem;
}
ELObj *StyleStack::inherited(const ConstPtr<InheritedC> &ic, unsigned specLevel,
Interpreter &interp, Vector<size_t> &dependencies)
{
ASSERT(specLevel != unsigned(-1));
size_t ind = ic->index();
ConstPtr<InheritedC> spec;
const VarStyleObj *style = 0;
unsigned newSpecLevel = unsigned(-1);
if (ind >= inheritedCInfo_.size())
spec = ic;
else {
const InheritedCInfo *p = inheritedCInfo_[ind].pointer();
while (p != 0) {
if (p->specLevel < specLevel)
break;
p = p->prev.pointer();
}
if (!p)
spec = ic;
else {
if (p->cachedValue) {
// We can only use the cached value if none of the values
// we depended on changed since we computed it.
bool cacheOk = 1;
for (size_t i = 0; i < p->dependencies.size(); i++) {
size_t d = p->dependencies[i];
if (d < inheritedCInfo_.size()
&& inheritedCInfo_[d]->valLevel > p->valLevel) {
cacheOk = 0;
break;
}
}
if (cacheOk)
return p->cachedValue;
}
style = p->style;
spec = p->spec;
newSpecLevel = p->specLevel;
}
}
VM vm(interp);
vm.styleStack = this;
vm.specLevel = newSpecLevel;
return spec->value(vm, style, dependencies);
}
ELObj *StyleStack::actual(const ConstPtr<InheritedC> &ic, const Location &loc,
Interpreter &interp, Vector<size_t> &dependencies)
{
size_t ind = ic->index();
for (size_t i = 0; i < dependencies.size(); i++) {
if (dependencies[i] == ind) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::actualLoop,
StringMessageArg(ic->identifier()->name()));
return interp.makeError();
}
}
dependencies.push_back(ind);
ConstPtr<InheritedC> spec;
const VarStyleObj *style = 0;
if (ind >= inheritedCInfo_.size())
spec = ic;
else {
const InheritedCInfo *p = inheritedCInfo_[ind].pointer();
if (!p)
spec = ic;
else if (p->cachedValue) {
const Vector<size_t> &dep = p->dependencies;
for (size_t i = 0; i < dep.size(); i++)
dependencies.push_back(dep[i]);
return p->cachedValue;
}
else {
style = p->style;
spec = p->spec;
}
}
VM vm(interp);
vm.styleStack = this;
vm.specLevel = level_;
return spec->value(vm, style, dependencies);
}
void StyleStack::trace(Collector &c) const
{
for (size_t i = 0; i < inheritedCInfo_.size(); i++) {
for (const InheritedCInfo *p = inheritedCInfo_[i].pointer();
p;
p = p->prev.pointer()) {
c.trace(p->style);
c.trace(p->cachedValue);
}
}
}
InheritedCInfo::InheritedCInfo(const ConstPtr<InheritedC> &sp,
const VarStyleObj *so,
unsigned vl,
unsigned sl,
const ProcessingMode::Rule *r,
const Ptr<InheritedCInfo> &p)
: spec(sp), style(so), valLevel(vl), specLevel(sl), rule(r), prev(p), cachedValue(0)
{
}
StyleObj *StyleObj::asStyle()
{
return this;
}
VarStyleObj::VarStyleObj(const ConstPtr<StyleSpec> &styleSpec, StyleObj *use, ELObj **display,
const NodePtr &node)
: styleSpec_(styleSpec), use_(use), display_(display), node_(node)
{
hasSubObjects_ = 1;
}
VarStyleObj::~VarStyleObj()
{
delete [] display_;
}
void VarStyleObj::traceSubObjects(Collector &c) const
{
c.trace(use_);
if (display_)
for (ELObj **pp = display_; *pp; pp++)
c.trace(*pp);
}
void VarStyleObj::appendIterForce(StyleObjIter &iter) const
{
if (styleSpec_->forceSpecs.size())
iter.append(&styleSpec_->forceSpecs, this);
}
void VarStyleObj::appendIterNormal(StyleObjIter &iter) const
{
if (styleSpec_->specs.size())
iter.append(&styleSpec_->specs, this);
if (use_)
use_->appendIter(iter);
}
void VarStyleObj::appendIter(StyleObjIter &iter) const
{
VarStyleObj::appendIterForce(iter);
VarStyleObj::appendIterNormal(iter);
}
OverriddenStyleObj::OverriddenStyleObj(BasicStyleObj *basic, StyleObj *override)
: basic_(basic), override_(override)
{
hasSubObjects_ = 1;
}
void OverriddenStyleObj::traceSubObjects(Collector &c) const
{
c.trace(basic_);
c.trace(override_);
}
void OverriddenStyleObj::appendIter(StyleObjIter &iter) const
{
basic_->appendIterForce(iter);
override_->appendIter(iter);
basic_->appendIterNormal(iter);
}
MergeStyleObj::MergeStyleObj()
{
hasSubObjects_ = 1;
}
void MergeStyleObj::append(StyleObj *obj)
{
styles_.push_back(obj);
}
void MergeStyleObj::appendIter(StyleObjIter &iter) const
{
for (size_t i = 0; i < styles_.size(); i++)
styles_[i]->appendIter(iter);
}
void MergeStyleObj::traceSubObjects(Collector &c) const
{
for (size_t i = 0; i < styles_.size(); i++)
c.trace(styles_[i]);
}
ColorObj *ColorObj::asColor()
{
return this;
}
DeviceRGBColorObj::DeviceRGBColorObj(unsigned char red, unsigned char green,
unsigned char blue)
{
color_.red = red;
color_.green = green;
color_.blue = blue;
}
void DeviceRGBColorObj::set(FOTBuilder &fotb) const
{
fotb.setColor(color_);
}
void DeviceRGBColorObj::setBackground(FOTBuilder &fotb) const
{
fotb.setBackgroundColor(color_);
}
ColorSpaceObj *ColorSpaceObj::asColorSpace()
{
return this;
}
// invert a 3x3 matrix A. result is returned in B
// both must be arrays of length 9.
static void
invert(double *A, double *B)
{
B[0] = (A[4]*A[8] - A[5]*A[7]);
B[3] = - (A[3]*A[8] - A[5]*A[6]);
B[6] = (A[3]*A[7] - A[4]*A[6]);
B[1] = - (A[1]*A[8] - A[2]*A[7]);
B[4] = (A[0]*A[8] - A[2]*A[6]);
B[7] = - (A[0]*A[7] - A[1]*A[6]);
B[2] = (A[1]*A[5] - A[2]*A[4]);
B[5] = - (A[0]*A[5] - A[2]*A[3]);
B[8] = (A[0]*A[4] - A[1]*A[3]);
double det = A[0]*B[0] + A[1]*B[3] + A[2]*B[6];
if (det < 0.0001) {
//FIXME message
}
B[0] /= det; B[1] /= det; B[2] /= det;
B[3] /= det; B[4] /= det; B[5] /= det;
B[6] /= det; B[7] /= det; B[8] /= det;
}
/*
FIXME make color handling more flexible:
* pass different color types to backends
* move the conversion code to a separate
class ColorConverter, which could then
be used by backends to do the needed
conversions.
* make phosphors settable
* make highlight color for KX settable
* whitepoint correction, making the device
whitepoint/blackpoint settable
for the formulas used here, see:
* Computer Graphics, Principles and Practice, Second Edition,
Foley, van Damme, Hughes,
Addison-Wesley, 1987
* Principles of Color Technology, Second Edition,
Fred W. Billmeyer, Jr. and Max Saltzman,
John Wiley & Sons, Inc., 1981
* The color faq
*/
CIEXYZColorSpaceObj::CIEXYZColorSpaceObj(const double *wp, const double *bp)
{
xyzData_ = new XYZData;
for (int i = 0; i < 3; i++)
xyzData_->white_[i] = wp[i];
double tmp = wp[0] + 15*wp[1] + 3*wp[2];
xyzData_->white_u = 4*wp[0]/tmp;
xyzData_->white_v = 9*wp[1]/tmp;
// from the color faq
double xr = .64; double yr = .33;
double xg = .30; double yg = .60;
double xb = .15; double yb = .06;
double U[9];
U[0] = xr; U[1] = xg; U[2] = xb;
U[3] = yr; U[4] = yg; U[5] = yb;
U[6] = 1.0 - xr - yr; U[7] = 1.0 - xg - yg; U[8] = 1.0 - xb - yb;
double Uinv[9];
invert(U, Uinv);
double C[3];
for (int i = 0; i < 3; i++)
C[i] = Uinv[3*i]*wp[0] + Uinv[3*i+1]*wp[1] + Uinv[3*i+2]*wp[2];
double Minv[9];
Minv[0] = U[0]*C[0]; Minv[1] = U[1]*C[1]; Minv[2] = U[2]*C[2];
Minv[3] = U[3]*C[0]; Minv[4] = U[4]*C[1]; Minv[5] = U[5]*C[2];
Minv[6] = U[6]*C[0]; Minv[7] = U[7]*C[1]; Minv[8] = U[8]*C[2];
invert(Minv, xyzData_->M_);
}
CIEXYZColorSpaceObj::~CIEXYZColorSpaceObj()
{
delete xyzData_;
}
ELObj *CIEXYZColorSpaceObj::makeColor (const double *h, Interpreter &interp)
{
unsigned char c[3];
for (int i = 0; i < 3; i++)
c[i] = (unsigned char) ((xyzData_->M_[3*i]*h[0]
+ xyzData_->M_[3*i+1]*h[1]
+ xyzData_->M_[3*i+2]*h[2])*255.0 + .5);
return new (interp) DeviceRGBColorObj(c[0], c[1], c[2]);
}
CIELUVColorSpaceObj::CIELUVColorSpaceObj(const double *wp, const double *bp, const double *r)
: CIEXYZColorSpaceObj(wp, bp)
{
luvData_ = new LUVData;
for (int i = 0; i < 6; i++)
luvData_->range_[i] = r ? r[i] : ((i % 2) ? 1.0 : .0);
}
CIELUVColorSpaceObj::~CIELUVColorSpaceObj()
{
delete luvData_;
}
ELObj *CIELUVColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 3) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("CIE LUV")));
return interp.makeError();
}
double d[3];
for (int i = 0; i < 3; i++) {
if (!argv[i]->realValue(d[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("CIE LUV")));
return interp.makeError();
}
if (d[i] < luvData_->range_[2*i] || d[i] > luvData_->range_[2*i+1]) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("CIE LUV")));
return interp.makeError();
}
}
double h[3];
if (d[0] == 0.0) {
h[0] = h[1] = h[2] = 0.0;
} else {
if (d[0] <= 7.996968)
h[1] = d[0] / 903.0;
else {
h[1] = (d[0] + 16.0) / 116.0;
h[1] = h[1] * h[1] * h[1];
}
double uu = d[1] / (13.0 * d[0]) + xyzData_->white_u;
double vv = d[2] / (13.0 * d[0]) + xyzData_->white_v;
double tmp = 9.0 * h[1] / vv;
h[0] = uu * tmp / 4.0;
h[2] = (tmp - 15.0 * h[1] - h[0]) / 3.0;
}
return CIEXYZColorSpaceObj::makeColor(h, interp);
}
CIELABColorSpaceObj::CIELABColorSpaceObj(const double *wp, const double *bp, const double *r)
: CIEXYZColorSpaceObj(wp, bp)
{
labData_ = new LABData;
if (r)
for (int i = 0; i < 6; i++)
labData_->range_[i] = r[i];
else {
labData_->range_[0] = .0;
labData_->range_[1] = 100.0;
labData_->range_[2] = .0;
labData_->range_[3] = 1.0;
labData_->range_[4] = .0;
labData_->range_[5] = 1.0;
}
}
CIELABColorSpaceObj::~CIELABColorSpaceObj()
{
delete labData_;
}
ELObj *CIELABColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 3) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("CIE LAB")));
return interp.makeError();
}
double d[3];
for (int i = 0; i < 3; i++) {
if (!argv[i]->realValue(d[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("CIE LAB")));
return interp.makeError();
}
if (d[i] < labData_->range_[2*i] || d[i] > labData_->range_[2*i+1]) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("CIE LAB")));
return interp.makeError();
}
}
d[0] /= 100.0;
double h[3];
double tmp = (d[0] + 16.0) / 116.0;
h[1] = tmp * tmp * tmp;
if (h[1] < 0.008856) {
tmp = d[0] / 9.03292;
h[0] = xyzData_->white_[0] * ((d[1] / 3893.5) + tmp);
h[1] = tmp;
h[2] = xyzData_->white_[2] * (tmp - (d[2] / 1557.4));
} else {
double tmp2 = tmp + (d[1] / 5.0);
h[0] = xyzData_->white_[0] * tmp2 * tmp2 * tmp2;
tmp2 = tmp - (d[2] / 2.0);
h[2] = xyzData_->white_[2] * tmp2 * tmp2 * tmp2;
}
return CIEXYZColorSpaceObj::makeColor(h, interp);
}
CIEABCColorSpaceObj::CIEABCColorSpaceObj(const double *wp, const double *bp,
const double *rabc, FunctionObj **dabc, const double *mabc,
const double *rlmn, FunctionObj **dlmn, const double *mlmn)
: CIEXYZColorSpaceObj(wp, bp)
{
abcData_ = new ABCData;
int i;
for (i = 0; i < 6; i++)
abcData_->rangeAbc_[i] = rabc ? rabc[i] : ((i % 2) ? 1.0 : 0.0);
for (i = 0; i < 3; i++)
abcData_->decodeAbc_[i] = dabc ? dabc[i] : 0;
for (i = 0; i < 9; i++)
abcData_->matrixAbc_[i] = mabc ? mabc[i] : ((i % 4) ? 0.0 : 1.0);
for (i = 0; i < 6; i++)
abcData_->rangeLmn_[i] = rlmn ? rlmn[i] : ((i % 2) ? 1.0 : 0.0);
for (i = 0; i < 3; i++)
abcData_->decodeLmn_[i] = dlmn ? dlmn[i] : 0;
for (i = 0; i < 9; i++)
abcData_->matrixLmn_[i] = mlmn ? mlmn[i] : ((i % 4) ? 0.0 : 1.0);
}
CIEABCColorSpaceObj::~CIEABCColorSpaceObj()
{
delete abcData_;
}
void CIEABCColorSpaceObj::traceSubObjects(Collector &c) const
{
for (int i = 0; i < 3; i++)
if (abcData_->decodeAbc_[i])
c.trace(abcData_->decodeAbc_[i]);
for (int i = 0; i < 3; i++)
if (abcData_->decodeLmn_[i])
c.trace(abcData_->decodeLmn_[i]);
}
static
bool applyFunc(Interpreter &interp, FunctionObj *f, double &d)
{
InsnPtr insns[2];
insns[1] = f->makeCallInsn(1, interp, Location(), InsnPtr());
insns[0] = InsnPtr(new ConstantInsn(new (interp) RealObj(d),insns[1]));
VM vm(interp);
ELObj *res = vm.eval(insns[0].pointer());
if (!res || !res->realValue(d))
return 0;
return 1;
}
ELObj *CIEABCColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 3) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("CIE Based ABC")));
return interp.makeError();
}
double d[3];
for (int i = 0; i < 3; i++) {
if (!argv[i]->realValue(d[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("CIE Based ABC")));
return interp.makeError();
}
if (d[i] < abcData_->rangeAbc_[2*i] || d[i] > abcData_->rangeAbc_[2*i+1]) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("CIE Based ABC")));
return interp.makeError();
}
if (abcData_->decodeAbc_[i] && !applyFunc(interp, abcData_->decodeAbc_[i], d[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorProcResType,
StringMessageArg(interp.makeStringC("CIE Based ABC")));
return interp.makeError();
}
}
double l[3];
for (int i = 0; i < 3; i++) {
l[i] = abcData_->matrixAbc_[i]*d[0]
+ abcData_->matrixAbc_[3+i]*d[1]
+ abcData_->matrixAbc_[6+i]*d[2];
if (l[i] < abcData_->rangeLmn_[2*i] || l[i] > abcData_->rangeLmn_[2*i+1]) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("CIE Based ABC")));
return interp.makeError();
}
if (abcData_->decodeLmn_[i] && !applyFunc(interp, abcData_->decodeLmn_[i], l[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorProcResType,
StringMessageArg(interp.makeStringC("CIE Based ABC")));
return interp.makeError();
}
}
double h[3];
for (int i = 0; i < 3; i++)
h[i] = abcData_->matrixLmn_[i]*l[0]
+ abcData_->matrixLmn_[3+i]*l[1]
+ abcData_->matrixLmn_[6+i]*l[2];
return CIEXYZColorSpaceObj::makeColor(h, interp);
}
CIEAColorSpaceObj::CIEAColorSpaceObj(const double *wp, const double *bp,
const double *ra, FunctionObj *da, const double *ma,
const double *rlmn, FunctionObj **dlmn, const double *mlmn)
: CIEXYZColorSpaceObj(wp, bp)
{
aData_ = new AData;
int i;
for (i = 0; i < 2; i++)
aData_->rangeA_[i] = ra ? ra[i] : ((i % 2) ? 1.0 : 0.0);
aData_->decodeA_ = da ? da : 0;
for (i = 0; i < 3; i++)
aData_->matrixA_[i] = ma ? ma[i] : 1.0;
for (i = 0; i < 6; i++)
aData_->rangeLmn_[i] = rlmn ? rlmn[i] : ((i % 2) ? 1.0 : 0.0);
for (i = 0; i < 3; i++)
aData_->decodeLmn_[i] = dlmn ? dlmn[i] : 0;
for (i = 0; i < 9; i++)
aData_->matrixLmn_[i] = mlmn ? mlmn[i] : ((i % 4) ? 0.0 : 1.0);
}
CIEAColorSpaceObj::~CIEAColorSpaceObj()
{
delete aData_;
}
void CIEAColorSpaceObj::traceSubObjects(Collector &c) const
{
if (aData_->decodeA_)
c.trace(aData_->decodeA_);
for (int i = 0; i < 3; i++)
if (aData_->decodeLmn_[i])
c.trace(aData_->decodeLmn_[i]);
}
ELObj *CIEAColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 1) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("CIE Based A")));
return interp.makeError();
}
double d;
if (!argv[0]->realValue(d)) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("CIE Based A")));
return interp.makeError();
}
if (d < aData_->rangeA_[0] || d > aData_->rangeA_[1]) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("CIE Based A")));
return interp.makeError();
}
if (aData_->decodeA_ && !applyFunc(interp, aData_->decodeA_, d)) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorProcResType,
StringMessageArg(interp.makeStringC("CIE Based A")));
return interp.makeError();
}
double l[3];
for (int i = 0; i < 3; i++) {
l[i] = aData_->matrixA_[i]*d;
if (l[i] < aData_->rangeLmn_[2*i] || l[i] > aData_->rangeLmn_[2*i+1]) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("CIE Based A")));
return interp.makeError();
}
if (aData_->decodeLmn_[i] && !applyFunc(interp, aData_->decodeLmn_[i], l[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorProcResType,
StringMessageArg(interp.makeStringC("CIE Based A")));
return interp.makeError();
}
}
double h[3];
for (int i = 0; i < 3; i++) {
h[i] = aData_->matrixLmn_[i]*l[0]
+ aData_->matrixLmn_[3+i]*l[1]
+ aData_->matrixLmn_[6+i]*l[2];
}
return CIEXYZColorSpaceObj::makeColor(h, interp);
}
ELObj *DeviceRGBColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 3) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("Device RGB")));
return interp.makeError();
}
unsigned char c[3];
for (int i = 0; i < 3; i++) {
double d;
if (!argv[i]->realValue(d)) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("Device RGB")));
return interp.makeError();
}
if (d < 0.0 || d > 1.0) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("Device RGB")));
return interp.makeError();
}
c[i] = (unsigned char)(d*255.0 + .5);
}
return new (interp) DeviceRGBColorObj(c[0], c[1], c[2]);
}
ELObj *DeviceGrayColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 1) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("Device Gray")));
return interp.makeError();
}
unsigned char c;
double d;
if (!argv[0]->realValue(d)) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("Device Gray")));
return interp.makeError();
}
if (d < 0.0 || d > 1.0) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("Device Gray")));
return interp.makeError();
}
c = (unsigned char)(d*255.0 + .5);
return new (interp) DeviceRGBColorObj(c, c, c);
}
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
ELObj *DeviceCMYKColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 4) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("Device CMYK")));
return interp.makeError();
}
double d[4];
for (int i = 0; i < 4; i++) {
if (!argv[i]->realValue(d[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("Device CMYK")));
return interp.makeError();
}
if (d[i] < 0.0 || d[i] > 1.0) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("Device CMYK")));
return interp.makeError();
}
}
unsigned char c[3];
for (int i = 0; i < 3; i++)
c[i] = (unsigned char)((1 - MIN(1, d[i] + d[3]))*255.0 + .5);
return new (interp) DeviceRGBColorObj(c[0], c[1], c[2]);
}
ELObj *DeviceKXColorSpaceObj::makeColor(int argc, ELObj **argv,
Interpreter &interp, const Location &loc)
{
if (argc == 0)
return new (interp) DeviceRGBColorObj(0, 0, 0);
if (argc != 2) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgCount,
StringMessageArg(interp.makeStringC("Device KX")));
return interp.makeError();
}
double d[2];
for (int i = 0; i < 2; i++) {
if (!argv[i]->realValue(d[i])) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgType,
StringMessageArg(interp.makeStringC("Device KX")));
return interp.makeError();
}
if (d[i] < 0.0 || d[i] > 1.0) {
interp.setNextLocation(loc);
interp.message(InterpreterMessages::colorArgRange,
StringMessageArg(interp.makeStringC("Device KX")));
return interp.makeError();
}
}
unsigned char c;
c = (unsigned char)((1 - MIN(1, d[0] + d[1]))*255.0 + .5);
return new (interp) DeviceRGBColorObj(c, c, c);
}
VarInheritedC::VarInheritedC(const ConstPtr<InheritedC> &ic,
const InsnPtr &code, const Location &loc)
: InheritedC(ic->identifier(), ic->index()), inheritedC_(ic), code_(code), loc_(loc)
{
}
void VarInheritedC::set(VM &vm, const VarStyleObj *style, FOTBuilder &fotb,
ELObj *&cacheObj, Vector<size_t> &dependencies) const
{
if (!cacheObj) {
EvalContext::CurrentNodeSetter cns(style->node(), 0, vm);
vm.actualDependencies = &dependencies;
cacheObj = vm.eval(code_.pointer(), style->display());
ASSERT(cacheObj != 0);
vm.actualDependencies = 0;
}
if (!vm.interp->isError(cacheObj)) {
ConstPtr<InheritedC> c(inheritedC_->make(cacheObj, loc_, *vm.interp));
if (!c.isNull())
c->set(vm, 0, fotb, cacheObj, dependencies);
}
}
ConstPtr<InheritedC> VarInheritedC::make(ELObj *obj, const Location &loc, Interpreter &interp)
const
{
return inheritedC_->make(obj, loc, interp);
}
ELObj *VarInheritedC::value(VM &vm, const VarStyleObj *style,
Vector<size_t> &dependencies) const
{
EvalContext::CurrentNodeSetter cns(style->node(), 0, vm);
vm.actualDependencies = &dependencies;
return vm.eval(code_.pointer(), style->display());
}
StyleObjIter::StyleObjIter()
: i_(0), vi_(0)
{
}
void StyleObjIter::append(const Vector<ConstPtr<InheritedC> > *v, const VarStyleObj *obj)
{
styleVec_.push_back(obj);
vecs_.push_back(v);
}
ConstPtr<InheritedC> StyleObjIter::next(const VarStyleObj *&style)
{
for (; vi_ < vecs_.size(); vi_++, i_ = 0) {
if (i_ < vecs_[vi_]->size()) {
style = styleVec_[vi_];
return (*vecs_[vi_])[i_++];
}
}
return ConstPtr<InheritedC>();
}
StyleSpec::StyleSpec(Vector<ConstPtr<InheritedC> > &fs, Vector<ConstPtr<InheritedC> > &s)
{
fs.swap(forceSpecs);
s.swap(specs);
}
#ifdef DSSSL_NAMESPACE
}
#endif
| 29.773645 | 94 | 0.607881 | [
"vector"
] |
0cd8ca3b7bfb1673460cbbfd2dca88393541adf9 | 2,217 | cpp | C++ | src/OpcUaStackCore/ServiceSetApplication/RegisterForwardNodeRequest.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 108 | 2018-10-08T17:03:32.000Z | 2022-03-21T00:52:26.000Z | src/OpcUaStackCore/ServiceSetApplication/RegisterForwardNodeRequest.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 287 | 2018-09-18T14:59:12.000Z | 2022-01-13T12:28:23.000Z | src/OpcUaStackCore/ServiceSetApplication/RegisterForwardNodeRequest.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 32 | 2018-10-19T14:35:03.000Z | 2021-11-12T09:36:46.000Z | /*
Copyright 2015-2017 Kai Huebl (kai@huebl-sgh.de)
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl (kai@huebl-sgh.de)
*/
#include "OpcUaStackCore/ServiceSetApplication/RegisterForwardNodeRequest.h"
namespace OpcUaStackCore
{
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// OpcUa RegisterForwardNodeRequest
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
RegisterForwardNodeRequest::RegisterForwardNodeRequest(void)
: Object()
, nodesToRegisterArraySPtr_(constructSPtr<OpcUaNodeIdArray>())
, forwardNodeSync_(constructSPtr<ForwardNodeSync>())
{
}
RegisterForwardNodeRequest::~RegisterForwardNodeRequest(void)
{
}
void
RegisterForwardNodeRequest::nodesToRegister(const OpcUaNodeIdArray::SPtr nodesToRegister)
{
nodesToRegisterArraySPtr_ = nodesToRegister;
}
OpcUaNodeIdArray::SPtr
RegisterForwardNodeRequest::nodesToRegister(void) const
{
return nodesToRegisterArraySPtr_;
}
void
RegisterForwardNodeRequest::opcUaBinaryEncode(std::ostream& os) const
{
nodesToRegisterArraySPtr_->opcUaBinaryEncode(os);
}
void
RegisterForwardNodeRequest::opcUaBinaryDecode(std::istream& is)
{
nodesToRegisterArraySPtr_->opcUaBinaryDecode(is);
}
void
RegisterForwardNodeRequest::forwardNodeSync(ForwardNodeSync::SPtr forwardInfo)
{
forwardNodeSync_ = forwardInfo;
}
ForwardNodeSync::SPtr
RegisterForwardNodeRequest::forwardNodeSync(void)
{
return forwardNodeSync_;
}
}
| 28.063291 | 90 | 0.680198 | [
"object"
] |
0cdd7b7c36cb39caf922d19a4afbf55e79bdf169 | 581 | cpp | C++ | array/leetcode_array/485_max_consecutive_ones.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | 1 | 2020-10-12T19:18:19.000Z | 2020-10-12T19:18:19.000Z | array/leetcode_array/485_max_consecutive_ones.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | null | null | null | array/leetcode_array/485_max_consecutive_ones.cpp | Hadleyhzy/data_structure_and_algorithm | 0e610ba78dcb216323d9434a0f182756780ce5c0 | [
"MIT"
] | 1 | 2020-10-12T19:18:04.000Z | 2020-10-12T19:18:04.000Z | //
// 485_max_consecutive_ones.cpp
// leetcode_array
//
// Created by Hadley on 20.04.20.
// Copyright © 2020 Hadley. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int cur=0;
int max=0;
for(int i=0;i<nums.size();i++){
if(nums[i]){
cur++;
}else{
cur=0;
}
if(cur>max)max=cur;
}
return max;
}
};
| 18.741935 | 51 | 0.53012 | [
"vector"
] |
0ce6d3a384e61b10368d87a77626905ae71cad58 | 1,642 | cpp | C++ | Rectangle.cpp | crackaf/paint-tool | 7cc070a32d6c82f69577ec02898e572c5a598562 | [
"MIT"
] | null | null | null | Rectangle.cpp | crackaf/paint-tool | 7cc070a32d6c82f69577ec02898e572c5a598562 | [
"MIT"
] | null | null | null | Rectangle.cpp | crackaf/paint-tool | 7cc070a32d6c82f69577ec02898e572c5a598562 | [
"MIT"
] | null | null | null | #include "Rectangle.h"
My_Rectangle::My_Rectangle()
{
char name[] = "My_Rectangle";
type = new char[strlen(name) + 1];
strcpy_s(type, strlen(name) + 1, name);
}
My_Rectangle::My_Rectangle(double x1, double y1, double x2, double y2, int c)
: My_Polygon(x1, y1, c)
{
char name[] = "My_Rectangle";
type = new char[strlen(name) + 1];
strcpy_s(type, strlen(name) + 1, name);
addPoint(x2, y2);
}
My_Rectangle::~My_Rectangle()
{
}
void My_Rectangle::fill(int x, int y, int c, COLORREF bck)
{
fillColor = c;
Shape::fill(x, y, c, bck);
}
void My_Rectangle::draw()
{
GP142_lineXY(color, points[0].x, points[0].y, points[0].x, points[1].y, 2);
GP142_lineXY(color, points[0].x, points[0].y, points[1].x, points[0].y, 2);
GP142_lineXY(color, points[1].x, points[1].y, points[0].x, points[1].y, 2);
GP142_lineXY(color, points[1].x, points[1].y, points[1].x, points[0].y, 2);
//GP142_pixelXY(GREEN, points[0].x, points[0].y);
}
bool My_Rectangle::contains(Point p)
{
if (((points[0].x < p.x && p.x < points[1].x) || (points[1].x < p.x && p.x < points[0].x)) &&
((points[0].y < p.y && p.y < points[1].y) || (points[1].y < p.y && p.y < points[0].y)))
/*if (((points[0].x < p.y && p.y < points[1].y) || (points[1].y < p.y && p.y < points[0].y)) &&
((points[0].x < p.x && p.x < points[1].x) || (points[1].x < p.x && p.x < points[0].x)))*/
return true;
else
return false;
}
//void My_Rectangle::fill(int color)
//{
// // TODO: Add your implementation code here.
//}
void My_Rectangle::erase()
{
GP142_rectangleXY(BLACK, points[0].x, points[0].y, points[1].x, points[1].y, 0);
// TODO: Add your implementation code here.
}
| 27.366667 | 97 | 0.609622 | [
"shape"
] |
0cee47e2318e17ca5a99757439b0ea3fef251b44 | 591 | cpp | C++ | src/097.interleaving_string/code2.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2016-07-02T17:44:10.000Z | 2016-07-02T17:44:10.000Z | src/097.interleaving_string/code2.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | null | null | null | src/097.interleaving_string/code2.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2019-12-21T04:57:15.000Z | 2019-12-21T04:57:15.000Z | class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n = s1.length(), m = s2.length();
vector<vector<int> > dp(n + 1, vector<int>(m + 1, -1));
dp[0][0] = 0;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i > 0 && dp[i - 1][j] != -1 && s3[dp[i - 1][j]] == s1[i - 1]) dp[i][j] = dp[i - 1][j] + 1;
if (j > 0 && dp[i][j - 1] != -1 && s3[dp[i][j - 1]] == s2[j - 1]) dp[i][j] = dp[i][j - 1] + 1;
}
}
return dp[n][m] == s3.length();
}
};
| 36.9375 | 110 | 0.368866 | [
"vector"
] |
0cf06f978ccdcd44e369a6137468deab9996d8c3 | 8,975 | cpp | C++ | Algo_Ds_Notes-master/Algo_Ds_Notes-master/Reversal_Linked_List/Reversal_Linked_List.cpp | rajatenzyme/Coding-Journey- | 65a0570153b7e3393d78352e78fb2111223049f3 | [
"MIT"
] | null | null | null | Algo_Ds_Notes-master/Algo_Ds_Notes-master/Reversal_Linked_List/Reversal_Linked_List.cpp | rajatenzyme/Coding-Journey- | 65a0570153b7e3393d78352e78fb2111223049f3 | [
"MIT"
] | null | null | null | Algo_Ds_Notes-master/Algo_Ds_Notes-master/Reversal_Linked_List/Reversal_Linked_List.cpp | rajatenzyme/Coding-Journey- | 65a0570153b7e3393d78352e78fb2111223049f3 | [
"MIT"
] | null | null | null | // All C headers have a C++ version, which should used instead - cstdlib is C++'s stdlib.h.
#include <cstdlib> // contains EXIT_SUCCESS
#include <memory> // contains std::unique_ptr
#include <iostream> // contains std::cout, the console output stream, and its generalization std::ostream.
#include <iterator> // contains std::rbegin/rend for reverse iteration.
#include <initializer_list> // contains std::initializer_list
//Using a template allows us to only write the linked list once and then create different kinds of linked lists. That way we can distinguish between lists of integers and lists of strings and will never accidentally pass one when the other is required.
template<typename T> // T is our placeholder name for the type of element in the linked list.
class linked_list // "snake case" is what the standard library uses, so in the interest of consistency we will too.
{
// Friend function for printing a linked_list. (Note that this is a free function (i.e. not attached to any class), not a member function, despite being declared here, due to the friend keyword.)
// It is allowed to access the list's private parts. Friends should be used sparingly - they often indicate that your public interface is lacking some functionality, which is true in this case (we lack a way of retrieving the elements in the list), but in the interest of brevity/simplicity we're doing it this way.
// Note that we pass the list as a const reference - this means we cannot modify it (a print function shouldn't do that, after all) and it won't be passed as a copy (the default).
friend std::ostream& operator<<( std::ostream& os, const linked_list& list ) {
bool first = true;
os << '[';
for( auto curNode = list._first.get(); curNode; curNode = curNode->next.get() ) {
if( first ) {
first = false;
} else {
os << ", ";
}
os << curNode->element;
}
os << ']';
return os;
}
struct node;
// Helper type alias so we don't need to write so much. Since the node definition is not until later, we need the above forward declaration for this to work.
using node_ptr = std::unique_ptr<node>;
//The public part of the class is what users can access. One of the main ideas of object oriented programming is encapsulation: We can hide the implementation details from our users so they can't accidentally (or intentionally) mess with the internal consistency of the data structure.
public:
// An initializer_list allows us to define the contents of the list when creating one.
linked_list( std::initializer_list<T> elements ) {
// iterate through the elements in the list in reverse order and add them to the front
for( auto it = std::rbegin( elements ); it != std::rend( elements ); ++it ) {
push_front( *it );
}
}
// Since we defined a custom constructor (with an initializer_list), the default constructor with no arguments won't be automatically generated. We'd like to have it though. While we're at it we can declare that it will never throw, since it only calls std::unique_ptr's default constructor, which is also noexcept.
linked_list() noexcept = default;
// push_front adds a new element to the front of our linked list.
template<typename U>
// && is a universal reference. Basically this means if this function is called with a temporary object, we don't need to copy it into the list, we can move it there, which may be a lot cheaper. This is called perfect forwarding. Some types are move-only, i.e. can't be copied; perfect forwarding allows us to still use them here.
// Note that we don't declare this function noexcept because std::make_unique can throw exceptions for numerous reasons.
void push_front( U&& element ) {
// Note the order here, it is intentional: We first create the new node containing the element. We do not yet set its next pointer. If something goes awry during construction, an exception may be thrown.
node_ptr newNode = std::make_unique<node>( std::forward<U>( element ) );
// Only then do we move the former first node into the node's next field. _first is now a null-pointer. Had we passed std::move(_first) as an argument to node's constructor and then encountered an exception there, _first would be a null-pointer and our list thus empty.
// But this way, if something goes wrong, the (observable) state of our list is unchanged. This is called the strong exception guarantee and helps us stay consistent in the face of errors.
// You might wonder what would happen if the following assignment were to throw an exception - wouldn't we still lose our list's contents? We would, but std::unique_ptr::operator= (i.e. assigning to a unique_ptr) is "noexcept", i.e. gauranteed to never throw an exception.
newNode->next = std::move( _first );
_first = std::move( newNode );
}
// Since the only operation we execute is assigning to an std::unique_ptr, which is noexcept, this function is noexcept as well. This is useful information both to our users and the compiler, which can do more aggressive optimization knowing this.
void reverse_iteratively() noexcept {
node_ptr prev;
// Note how since std::unique_ptr is non-copyable we have to move the value around here. This may seem complicated, but it ensures we never leak memory or do a double free.
node_ptr current = std::move( _first );
while( current ) {
auto next = std::move( current->next );
current->next = std::move( prev );
prev = std::move( current );
current = std::move( next );
}
_first = std::move( prev );
}
void reverse_recursively() noexcept {
// nullptr is the modern, safe way of expressing a null pointer. It will be implicitly converted to an std::unique_ptr using the unique_ptr(nullptr_t) constructor. (nullptr_t is the type of nullptr.) This is shorter and arguably more readable than writing node_ptr() or node_ptr{} but functionally identical.
_first = std::move( reverse_recursively( nullptr, std::move( _first ) ) );
}
private:
// C++ allows us to have multiple functions with the same name as long as their parameters differ - this is called overloading.
static node_ptr reverse_recursively( node_ptr prev, node_ptr current ) noexcept {
if( !current ) {
return std::move( prev );
}
auto next = std::move( current->next );
current->next = std::move( prev );
return reverse_recursively( std::move( current ), std::move( next ) );
}
// How exactly a node in our linked list looks is of no concern to the user, so we put it in the private part. That way we can change it without breaking anybody's code.
// A node consists of an element and a pointer to the next node.
struct node {
// This noexcept declaration means the following: This function is noexcept if calling T's constructor with the forwarded value is noexcept.
template<typename U>
node( U&& elem ) noexcept( noexcept( T( std::forward<U>( elem ) ) ) )
// This is a so-called initialisation list. It allows us to define the initial state of the member variables in the class.
: element( std::forward<U>( elem ) ) // Again: Perfect forwarding potentially makes our code more efficient.
{
// If we assigned element here instead, it would first be default-constructed during initialisation. That would be unnecessary overhead and would also limit us to types that can be default-constructed in the first place (i.e. have a 0 argument constructor) - not all can.
}
T element;
// A unique pointer "owns" the memory it points to. That means once the pointer "dies", the memory is freed. This way we don't need to do any manual book keeping. This is possible without any garbage collection overhead thanks to the RAII principle, one of the most important concepts in C++.
node_ptr next;
};
// A side-effect of using the move-only unique_ptr type here is that our list cannot be copied by default. If we want it to be copyable, we have to define our own copy constructor (and copy assignment).
node_ptr _first;
};
/*
Entrypoint into our program - execution starts here.
*/
int main() {
// Initialize the list using an initializer_list
linked_list<int> l{ 1, 2, 3 };
std::cout << "original list: " << l << std::endl;
l.reverse_iteratively();
std::cout << "reversed list: " << l << std::endl;
// Since we have a generic linked_list implementation we can also create other types of lists - say a list of lists of integers. We use the default constructor here to create an empty list.
linked_list<linked_list<int>> l2;
std::cout << "Empty list: " << l2 << std::endl;
l2.push_front( std::move( l ) );
l2.push_front( linked_list<int>{ 4, 5, 6 } );
std::cout << "Nested list: " << l2 << std::endl;
l2.reverse_recursively();
std::cout << "Reversed nested list: " << l2 << std::endl;
// note that we have no way of accessing the elements of the list yet, so we can't reverse a list inside the list.
return EXIT_SUCCESS; // Using named constants is preferrable to "magic numbers". Not everybody knows that 0 means "success" in this context.
}
| 67.992424 | 331 | 0.734262 | [
"object"
] |
0cf0cd23b30078433af39412a04f7d9aa1725a9f | 1,728 | cpp | C++ | 2020/Day07/day7part1.cpp | bkf2020/AOC | 1df3ed1feed9ec1144e8097de00f9bf40938d4e4 | [
"Unlicense"
] | null | null | null | 2020/Day07/day7part1.cpp | bkf2020/AOC | 1df3ed1feed9ec1144e8097de00f9bf40938d4e4 | [
"Unlicense"
] | 2 | 2021-02-03T03:30:43.000Z | 2021-02-06T18:18:06.000Z | 2020/Day07/day7part1.cpp | bkf2020/AOC | 1df3ed1feed9ec1144e8097de00f9bf40938d4e4 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
using namespace std;
void part1() {
string line;
map<string, vector<string>> bag_contain; // maps a bag to the bags it will contain
map<string, bool> contain_shiny_gold;
vector<string> all_bags;
while(getline(cin, line)) {
vector<string> parts;
stringstream ss(line);
string part;
while(ss >> part) {
parts.push_back(part);
}
int ptr = 0;
string bag1 = "";
while(parts[ptr] != "bags") {
bag1 += parts[ptr];
bag1 += " ";
ptr++;
}
bag1.erase(bag1.end() - 1);
ptr += 3; // next bag name, "bags contain [number]..."
all_bags.push_back(bag1);
while(ptr < parts.size()) {
string bag2;
while(ptr < parts.size() && parts[ptr].substr(0, 3) != "bag") {
bag2 += parts[ptr];
bag2 += " ";
ptr++;
}
bag2.erase(bag2.end() - 1);
if(bag2 != "no other") bag_contain[bag1].push_back(bag2); // no other bags case
ptr += 2; // punctuation is counted...
}
}
int ans = 0;
for(int i = 0; i < (int) all_bags.size(); i++) {
for(int j = 0; j < bag_contain[all_bags[i]].size(); j++) {
if(bag_contain[all_bags[i]][j] == "shiny gold") {
contain_shiny_gold[all_bags[i]] = true;
ans++;
break;
}
}
}
bool bag_added = true;
while(bag_added) {
bool temp = false;
for(int i = 0; i < (int) all_bags.size(); i++) {
for(int j = 0; j < bag_contain[all_bags[i]].size(); j++) {
if(contain_shiny_gold[bag_contain[all_bags[i]][j]] && !contain_shiny_gold[all_bags[i]]) {
contain_shiny_gold[all_bags[i]] = true;
temp = true;
ans++;
break;
}
}
}
if(!temp) bag_added = false;
}
cout << ans << '\n';
}
int main() {
part1();
}
| 22.153846 | 93 | 0.581019 | [
"vector"
] |
4904f83962a4fbe1572700e1e08e74a4fa0b225e | 1,794 | cpp | C++ | Dungeon template/Dungeon/Player.cpp | jasonsie88/OOP-and-DS | fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28 | [
"MIT"
] | null | null | null | Dungeon template/Dungeon/Player.cpp | jasonsie88/OOP-and-DS | fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28 | [
"MIT"
] | null | null | null | Dungeon template/Dungeon/Player.cpp | jasonsie88/OOP-and-DS | fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28 | [
"MIT"
] | null | null | null | #include "Player.h"
Player:: Player(){};
Player:: Player(string name,int currentHealth,int MaxHealth,int attack ,int defense):GameCharacter(name,currentHealth,MaxHealth,attack,defense)
{
}
void Player:: addItem(Item item){inventory.push_back(item);}
void Player:: increaseStates(int health,int attack,int defense){
int newhealth,newattack,newdefense;
newhealth=getCurrentHealth()+health;
setCurrentHealth(newhealth);
newattack=getAttack()+attack;
setAttack(newattack);
newdefense=getDefense()+defense;
setDefense(newdefense);
}
void Player:: changeRoom(Room* room){
setPreviousRoom(getCurrentRoom());
setCurrentRoom(room);
}
/* Virtual function that you need to complete */
/* In Player, this function should show the */
/* status of player. */
void Player:: triggerEvent(Object* object){
Player* play=dynamic_cast<Player*>(object);
if(play){
cout<<"Name: "<<this->getName()<<endl;
cout<<"Health: "<<this->getCurrentHealth()<<"/"<<this->getMaxHealth()<<endl;
cout<<"Attack: "<<this->getAttack()<<endl;
cout<<"Defense: "<<this->getDefense()<<endl;
}
}
/* Set & Get function*/
void Player:: setCurrentRoom(Room* currentRoom){this->currentRoom=currentRoom;}
void Player:: setPreviousRoom(Room* previousRoom){this->previousRoom=previousRoom;}
void Player:: setInventory(vector<Item> inventory){this->inventory=inventory;}
Room* Player:: getCurrentRoom(){return currentRoom;}
Room* Player:: getPreviousRoom(){return previousRoom;}
vector<Item> Player:: getInventory(){return inventory;}
| 40.772727 | 148 | 0.624861 | [
"object",
"vector"
] |
4906654c001d4a96859497a293835b83046bc44a | 6,513 | cpp | C++ | WebKit/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if USE(ACCELERATED_COMPOSITING)
#include "cc/CCTiledLayerImpl.h"
#include "LayerRendererChromium.h"
#include "cc/CCSolidColorDrawQuad.h"
#include "cc/CCTileDrawQuad.h"
#include <wtf/text/WTFString.h>
using namespace std;
namespace WebCore {
class ManagedTexture;
class DrawableTile : public CCLayerTilingData::Tile {
WTF_MAKE_NONCOPYABLE(DrawableTile);
public:
DrawableTile() : m_textureId(0) { }
Platform3DObject textureId() const { return m_textureId; }
void setTextureId(Platform3DObject textureId) { m_textureId = textureId; }
private:
Platform3DObject m_textureId;
};
CCTiledLayerImpl::CCTiledLayerImpl(int id)
: CCLayerImpl(id)
, m_skipsDraw(true)
, m_contentsSwizzled(false)
{
}
CCTiledLayerImpl::~CCTiledLayerImpl()
{
}
void CCTiledLayerImpl::bindContentsTexture(LayerRendererChromium* layerRenderer)
{
// This function is only valid for single texture layers, e.g. masks.
ASSERT(m_tiler);
ASSERT(m_tiler->numTiles() == 1);
DrawableTile* tile = tileAt(0, 0);
Platform3DObject textureId = tile ? tile->textureId() : 0;
ASSERT(textureId);
layerRenderer->context()->bindTexture(GraphicsContext3D::TEXTURE_2D, textureId);
}
void CCTiledLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const
{
CCLayerImpl::dumpLayerProperties(ts, indent);
writeIndent(ts, indent);
ts << "skipsDraw: " << (!m_tiler || m_skipsDraw) << "\n";
}
bool CCTiledLayerImpl::hasTileAt(int i, int j) const
{
return m_tiler->tileAt(i, j);
}
DrawableTile* CCTiledLayerImpl::tileAt(int i, int j) const
{
return static_cast<DrawableTile*>(m_tiler->tileAt(i, j));
}
DrawableTile* CCTiledLayerImpl::createTile(int i, int j)
{
RefPtr<DrawableTile> tile = adoptRef(new DrawableTile());
m_tiler->addTile(tile, i, j);
return tile.get();
}
TransformationMatrix CCTiledLayerImpl::quadTransform() const
{
TransformationMatrix transform = drawTransform();
if (contentBounds().isEmpty())
return transform;
transform.scaleNonUniform(bounds().width() / static_cast<double>(contentBounds().width()),
bounds().height() / static_cast<double>(contentBounds().height()));
// Tiler draws with a different origin from other layers.
transform.translate(-contentBounds().width() / 2.0, -contentBounds().height() / 2.0);
return transform;
}
void CCTiledLayerImpl::appendQuads(CCQuadList& quadList, const CCSharedQuadState* sharedQuadState)
{
const IntRect& contentRect = visibleLayerRect();
if (m_skipsDraw || !m_tiler || m_tiler->isEmpty() || contentRect.isEmpty())
return;
int left, top, right, bottom;
m_tiler->contentRectToTileIndices(contentRect, left, top, right, bottom);
IntRect layerRect = m_tiler->contentRectToLayerRect(contentRect);
for (int j = top; j <= bottom; ++j) {
for (int i = left; i <= right; ++i) {
DrawableTile* tile = tileAt(i, j);
IntRect tileRect = m_tiler->tileBounds(i, j);
IntRect displayRect = tileRect;
tileRect.intersect(layerRect);
// Skip empty tiles.
if (tileRect.isEmpty())
continue;
if (!tile || !tile->textureId()) {
quadList.append(CCSolidColorDrawQuad::create(sharedQuadState, tileRect, backgroundColor()));
continue;
}
// Keep track of how the top left has moved, so the texture can be
// offset the same amount.
IntSize displayOffset = tileRect.minXMinYCorner() - displayRect.minXMinYCorner();
IntPoint textureOffset = m_tiler->textureOffset(i, j) + displayOffset;
float tileWidth = static_cast<float>(m_tiler->tileSize().width());
float tileHeight = static_cast<float>(m_tiler->tileSize().height());
IntSize textureSize(tileWidth, tileHeight);
bool useAA = m_tiler->hasBorderTexels() && !sharedQuadState->isLayerAxisAlignedIntRect();
bool leftEdgeAA = !i && useAA;
bool topEdgeAA = !j && useAA;
bool rightEdgeAA = i == m_tiler->numTilesX() - 1 && useAA;
bool bottomEdgeAA = j == m_tiler->numTilesY() - 1 && useAA;
const GC3Dint textureFilter = m_tiler->hasBorderTexels() ? GraphicsContext3D::LINEAR : GraphicsContext3D::NEAREST;
quadList.append(CCTileDrawQuad::create(sharedQuadState, tileRect, tile->textureId(), textureOffset, textureSize, textureFilter, contentsSwizzled(), leftEdgeAA, topEdgeAA, rightEdgeAA, bottomEdgeAA));
}
}
}
void CCTiledLayerImpl::setTilingData(const CCLayerTilingData& tiler)
{
if (m_tiler)
m_tiler->reset();
else
m_tiler = CCLayerTilingData::create(tiler.tileSize(), tiler.hasBorderTexels() ? CCLayerTilingData::HasBorderTexels : CCLayerTilingData::NoBorderTexels);
*m_tiler = tiler;
}
void CCTiledLayerImpl::syncTextureId(int i, int j, Platform3DObject textureId)
{
DrawableTile* tile = tileAt(i, j);
if (!tile)
tile = createTile(i, j);
tile->setTextureId(textureId);
}
}
#endif // USE(ACCELERATED_COMPOSITING)
| 35.396739 | 211 | 0.692768 | [
"transform"
] |
490a13882bd9bf72eca234183653f662c4da7c4e | 1,057 | cpp | C++ | easy/GRID.cpp | VasuGoel/codechef-problems | 53951be4d2a5a507798fb83e25bdaa675f65077b | [
"MIT"
] | null | null | null | easy/GRID.cpp | VasuGoel/codechef-problems | 53951be4d2a5a507798fb83e25bdaa675f65077b | [
"MIT"
] | null | null | null | easy/GRID.cpp | VasuGoel/codechef-problems | 53951be4d2a5a507798fb83e25bdaa675f65077b | [
"MIT"
] | null | null | null | //
// Created by Vasu Goel on 2/6/20.
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t, n, i, j;
cin >> t;
while(t--) {
cin >> n;
char block;
vector<vector<char>> grid;
vector<vector<int>> val(n, vector<int>(n, 0));
for(i = 0; i < n; i++) {
vector<char> row;
for(j = 0; j < n; j++) {
cin >> block;
row.push_back(block);
}
grid.push_back(row);
}
for(i = 0; i < n; i++) {
for(j = n-1; j >= 0; j--) {
if(grid[i][j] == '#') break;
val[i][j] = true;
}
}
for(j = 0; j < n; j++) {
for (i = n - 1; i >= 0; i--) if (grid[i][j] == '#') break;
for (; i >= 0; i--) val[i][j] = false;
}
int ways = 0;
for(i = 0; i < n; i++) for(j = 0; j < n; j++) ways += val[i][j];
cout << ways << '\n';
}
return 0;
} | 25.166667 | 74 | 0.367077 | [
"vector"
] |
49103fa202d36c3008bc935317b5cb0ae53484e0 | 10,718 | cpp | C++ | software/MFrame/graphicalFunctions/matrix.cpp | mihaip/mscape | fc83fc85dc40e4f171d759a916073b299e360d87 | [
"Apache-2.0"
] | null | null | null | software/MFrame/graphicalFunctions/matrix.cpp | mihaip/mscape | fc83fc85dc40e4f171d759a916073b299e360d87 | [
"Apache-2.0"
] | null | null | null | software/MFrame/graphicalFunctions/matrix.cpp | mihaip/mscape | fc83fc85dc40e4f171d759a916073b299e360d87 | [
"Apache-2.0"
] | null | null | null | #include "matrix.h"
void IdentityMatrix(RGBMatrix matrix)
{
matrix[0][0] = 1.0; /* row 1 */
matrix[0][1] = 0.0;
matrix[0][2] = 0.0;
matrix[0][3] = 0.0;
matrix[1][0] = 0.0; /* row 2 */
matrix[1][1] = 1.0;
matrix[1][2] = 0.0;
matrix[1][3] = 0.0;
matrix[2][0] = 0.0; /* row 3 */
matrix[2][1] = 0.0;
matrix[2][2] = 1.0;
matrix[2][3] = 0.0;
matrix[3][0] = 0.0; /* row 4 */
matrix[3][1] = 0.0;
matrix[3][2] = 0.0;
matrix[3][3] = 1.0;
}
void OffsetMatrix(RGBMatrix matrix, float rOffset, float gOffset, float bOffset)
{
RGBMatrix mmat;
mmat[0][0] = 1.0;
mmat[0][1] = 0.0;
mmat[0][2] = 0.0;
mmat[0][3] = 0.0;
mmat[1][0] = 0.0;
mmat[1][1] = 1.0;
mmat[1][2] = 0.0;
mmat[1][3] = 0.0;
mmat[2][0] = 0.0;
mmat[2][1] = 0.0;
mmat[2][2] = 1.0;
mmat[2][3] = 0.0;
mmat[3][0] = rOffset;
mmat[3][1] = gOffset;
mmat[3][2] = bOffset;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat,matrix,matrix);
}
void MultiplyMatrix(RGBMatrix a, RGBMatrix b, RGBMatrix c)
{
int x, y;
RGBMatrix temp;
for(y=0; y<4 ; y++)
for(x=0 ; x<4 ; x++) {
temp[y][x] = b[y][0] * a[0][x]
+ b[y][1] * a[1][x]
+ b[y][2] * a[2][x]
+ b[y][3] * a[3][x];
}
for(y=0; y<4; y++)
for(x=0; x<4; x++)
c[y][x] = temp[y][x];
}
void ScaleMatrix(RGBMatrix matrix, float rScale, float gScale, float bScale)
{
RGBMatrix mmat;
mmat[0][0] = rScale;
mmat[0][1] = 0.0;
mmat[0][2] = 0.0;
mmat[0][3] = 0.0;
mmat[1][0] = 0.0;
mmat[1][1] = gScale;
mmat[1][2] = 0.0;
mmat[1][3] = 0.0;
mmat[2][0] = 0.0;
mmat[2][1] = 0.0;
mmat[2][2] = bScale;
mmat[2][3] = 0.0;
mmat[3][0] = 0.0;
mmat[3][1] = 0.0;
mmat[3][2] = 0.0;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat, matrix, matrix);
}
void SaturateMatrix(RGBMatrix matrix, float saturation)
{
RGBMatrix mmat;
float a, b, c, d, e, f, g, h, i;
float rwgt, gwgt, bwgt;
rwgt = kRLuminance;
gwgt = kGLuminance;
bwgt = kBLuminance;
a = (1.0 - saturation)*rwgt + saturation;
b = (1.0 - saturation)*rwgt;
c = (1.0 - saturation)*rwgt;
d = (1.0 - saturation)*gwgt;
e = (1.0 - saturation)*gwgt + saturation;
f = (1.0 - saturation)*gwgt;
g = (1.0 - saturation)*bwgt;
h = (1.0 - saturation)*bwgt;
i = (1.0 - saturation)*bwgt + saturation;
mmat[0][0] = a;
mmat[0][1] = b;
mmat[0][2] = c;
mmat[0][3] = 0.0;
mmat[1][0] = d;
mmat[1][1] = e;
mmat[1][2] = f;
mmat[1][3] = 0.0;
mmat[2][0] = g;
mmat[2][1] = h;
mmat[2][2] = i;
mmat[2][3] = 0.0;
mmat[3][0] = 0.0;
mmat[3][1] = 0.0;
mmat[3][2] = 0.0;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat, matrix, matrix);
}
/*
* xrotate -
* rotate about the x (red) axis
*/
void XRotateMatrix(RGBMatrix matrix, float rs, float rc)
{
RGBMatrix mmat;
mmat[0][0] = 1.0;
mmat[0][1] = 0.0;
mmat[0][2] = 0.0;
mmat[0][3] = 0.0;
mmat[1][0] = 0.0;
mmat[1][1] = rc;
mmat[1][2] = rs;
mmat[1][3] = 0.0;
mmat[2][0] = 0.0;
mmat[2][1] = -rs;
mmat[2][2] = rc;
mmat[2][3] = 0.0;
mmat[3][0] = 0.0;
mmat[3][1] = 0.0;
mmat[3][2] = 0.0;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat, matrix, matrix);
}
/*
* yrotate -
* rotate about the y (green) axis
*/
void YRotateMatrix(RGBMatrix matrix, float rs, float rc)
{
float mmat[4][4];
mmat[0][0] = rc;
mmat[0][1] = 0.0;
mmat[0][2] = -rs;
mmat[0][3] = 0.0;
mmat[1][0] = 0.0;
mmat[1][1] = 1.0;
mmat[1][2] = 0.0;
mmat[1][3] = 0.0;
mmat[2][0] = rs;
mmat[2][1] = 0.0;
mmat[2][2] = rc;
mmat[2][3] = 0.0;
mmat[3][0] = 0.0;
mmat[3][1] = 0.0;
mmat[3][2] = 0.0;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat, matrix, matrix);
}
/*
* zrotate -
* rotate about the z (blue) axis
*/
void ZRotateMatrix(RGBMatrix matrix, float rs, float rc)
{
RGBMatrix mmat;
mmat[0][0] = rc;
mmat[0][1] = rs;
mmat[0][2] = 0.0;
mmat[0][3] = 0.0;
mmat[1][0] = -rs;
mmat[1][1] = rc;
mmat[1][2] = 0.0;
mmat[1][3] = 0.0;
mmat[2][0] = 0.0;
mmat[2][1] = 0.0;
mmat[2][2] = 1.0;
mmat[2][3] = 0.0;
mmat[3][0] = 0.0;
mmat[3][1] = 0.0;
mmat[3][2] = 0.0;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat,matrix,matrix);
}
/*
* zshear -
* shear z using x and y.
*/
void ZShearMatrix(RGBMatrix matrix, float dx, float dy)
{
RGBMatrix mmat;
mmat[0][0] = 1.0;
mmat[0][1] = 0.0;
mmat[0][2] = dx;
mmat[0][3] = 0.0;
mmat[1][0] = 0.0;
mmat[1][1] = 1.0;
mmat[1][2] = dy;
mmat[1][3] = 0.0;
mmat[2][0] = 0.0;
mmat[2][1] = 0.0;
mmat[2][2] = 1.0;
mmat[2][3] = 0.0;
mmat[3][0] = 0.0;
mmat[3][1] = 0.0;
mmat[3][2] = 0.0;
mmat[3][3] = 1.0;
MultiplyMatrix(mmat, matrix, matrix);
}
void HueRotateMatrix(RGBMatrix matrix, float angle)
{
RGBMatrix mmat;
float mag;
float lx, ly, lz;
float xrs, xrc;
float yrs, yrc;
float zrs, zrc;
float zsx, zsy;
IdentityMatrix(mmat);
/* rotate the grey vector into positive Z */
mag = sqrt(2.0);
xrs = 1.0/mag;
xrc = 1.0/mag;
XRotateMatrix(mmat,xrs,xrc);
mag = sqrt(3.0);
yrs = -1.0/mag;
yrc = sqrt(2.0)/mag;
YRotateMatrix(mmat,yrs,yrc);
/* shear the space to make the luminance plane horizontal */
XFormPoint(mmat,kRLuminance,kGLuminance,kBLuminance,&lx,&ly,&lz);
zsx = lx/lz;
zsy = ly/lz;
ZShearMatrix(mmat,zsx,zsy);
/* rotate the hue */
zrs = sin(angle*pi/180.0);
zrc = cos(angle*pi/180.0);
ZRotateMatrix(mmat,zrs,zrc);
/* unshear the space to put the luminance plane back */
ZShearMatrix(mmat,-zsx,-zsy);
/* rotate the grey vector back into place */
YRotateMatrix(mmat,-yrs,yrc);
XRotateMatrix(mmat,-xrs,xrc);
MultiplyMatrix(mmat,matrix,matrix);
}
/*
* xformpnt -
* transform a 3D point using a matrix
*/
void XFormPoint(RGBMatrix matrix, float x, float y, float z, float* tx, float* ty, float* tz)
{
*tx = x*matrix[0][0] + y*matrix[1][0] + z*matrix[2][0] + matrix[3][0];
*ty = x*matrix[0][1] + y*matrix[1][1] + z*matrix[2][1] + matrix[3][1];
*tz = x*matrix[0][2] + y*matrix[1][2] + z*matrix[2][2] + matrix[3][2];
}
void ApplyMatrix(RGBMatrix matrix, PixMapHandle pix)
{
#if 0
if MUtilities::GestaltTest(gestaltPowerPCProcessorFeatures, gestaltPowerPCHasVectorInstructions))
{
signed char* pixelData;
vector float vecMatrix[4];
vector signed char pChar;
vector signed short pShort[2];
vector signed int pLong[4];
vector float pFloat[4], result[4];
int numberOfBytes;
pixelData = (signed char*)(**pix).baseAddr;
numberOfBytes = ((**pix).bounds.bottom - (**pix).bounds.top) * ((**pix).rowBytes & 0x3FFF);
vecMatrix[0] = vec_ld(0, matrix[0]);
vecMatrix[1] = vec_ld(0, matrix[1]);
vecMatrix[2] = vec_ld(0, matrix[2]);
vecMatrix[3] = vec_ld(0, matrix[3]);
for (int i=0; i < numberOfBytes; i+=16)
{
pChar = vec_ld(0, pixelData);
pShort[0] = vec_unpackh(pChar);
pShort[1] = vec_unpackl(pChar);
pLong[0] = vec_unpackh(pShort[0]);
pLong[1] = vec_unpackl(pShort[0]);
pLong[2] = vec_unpackh(pShort[1]);
pLong[3] = vec_unpackl(pShort[1]);
pFloat[0] = vec_ctf(pLong[0], 0);
pFloat[1] = vec_ctf(pLong[1], 0);
pFloat[2] = vec_ctf(pLong[2], 0);
pFloat[3] = vec_ctf(pLong[3], 0);
vSgemul(1, 4, 4, &pFloat[0], 'n', vecMatrix, 'n', &result[0]);
vSgemul(1, 4, 4, &pFloat[1], 'n', vecMatrix, 'n', &result[1]);
vSgemul(1, 4, 4, &pFloat[2], 'n', vecMatrix, 'n', &result[2]);
vSgemul(1, 4, 4, &pFloat[3], 'n', vecMatrix, 'n', &result[3]);
pLong[0] = vec_cts(result[0], 0);
pLong[1] = vec_cts(result[1], 0);
pLong[2] = vec_cts(result[2], 0);
pLong[3] = vec_cts(result[3], 0);
pShort[0] = vec_pack(pLong[0], pLong[1]);
pShort[1] = vec_pack(pLong[2], pLong[3]);
pChar = vec_pack(pShort[0], pShort[1]);
vec_st(pChar, 0, pixelData);
pixelData += 16;
/*
signed char* pixelData;
vector float vecMatrix[4];
vector signed char pChar;
vector signed short pShort[2];
vector signed int pLong[4];
vector float pFloat[4], result[4];
int numberOfBytes;
pixelData = (signed char*)(**pix).baseAddr;
numberOfBytes = ((**pix).bounds.bottom - (**pix).bounds.top) * ((**pix).rowBytes & 0x3FFF);
vecMatrix[0] = vec_ld(0, matrix[0]);
vecMatrix[1] = vec_ld(1, matrix[1]);
vecMatrix[2] = vec_ld(2, matrix[2]);
vecMatrix[3] = vec_ld(3, matrix[3]);
for (int i=0; i < numberOfBytes; i+=16)
{
pChar = vec_ld(0, pixelData);
pShort[0] = vec_unpackh(pChar);
pShort[1] = vec_unpackl(pChar);
pLong[0] = vec_unpackh(pShort[0]);
pLong[1] = vec_unpackl(pShort[0]);
pLong[2] = vec_unpackh(pShort[1]);
pLong[3] = vec_unpackl(pShort[1]);
pFloat[0] = vec_ctf(pLong[0], 0);
pFloat[1] = vec_ctf(pLong[1], 0);
pFloat[2] = vec_ctf(pLong[2], 0);
pFloat[3] = vec_ctf(pLong[3], 0);
vSgemul(1, 4, 4, &pFloat[0], 'n', vecMatrix, 'n', &result[0]);
vSgemul(1, 4, 4, &pFloat[1], 'n', vecMatrix, 'n', &result[1]);
vSgemul(1, 4, 4, &pFloat[2], 'n', vecMatrix, 'n', &result[2]);
vSgemul(1, 4, 4, &pFloat[3], 'n', vecMatrix, 'n', &result[3]);
pLong[0] = vec_cts(result[0], 0);
pLong[1] = vec_cts(result[1], 0);
pLong[2] = vec_cts(result[2], 0);
pLong[3] = vec_cts(result[3], 0);
pShort[0] = vec_pack(pLong[0], pLong[1]);
pShort[1] = vec_pack(pLong[2], pLong[3]);
pChar = vec_pack(pShort[0], pShort[1]);
vec_st(pChar, 0, pixelData);
pixelData += 16;
*/
}
}
else
#endif
{
unsigned char* pixelData;
int numberOfBytes;
int ir, ig, ib, r, g, b;
pixelData = (unsigned char*)(**pix).baseAddr;
numberOfBytes = ((**pix).bounds.bottom - (**pix).bounds.top) * ((**pix).rowBytes & 0x3FFF);
for (int i=0; i < numberOfBytes; i+=4)
{
ir = pixelData[1];
ig = pixelData[2];
ib = pixelData[3];
r = int(ir*matrix[0][0] + ig*matrix[1][0] + ib*matrix[2][0] + matrix[3][0]);
g = int(ir*matrix[0][1] + ig*matrix[1][1] + ib*matrix[2][1] + matrix[3][1]);
b = int(ir*matrix[0][2] + ig*matrix[1][2] + ib*matrix[2][2] + matrix[3][2]);
if(r<0) r = 0; else if(r>255) r = 255;
if(g<0) g = 0; else if(g>255) g = 255;
if(b<0) b = 0; else if(b>255) b = 255;
pixelData[1] = r;
pixelData[2] = g;
pixelData[3] = b;
pixelData += 4;
}
}
}
| 23.049462 | 98 | 0.524072 | [
"vector",
"transform",
"3d"
] |
49106db3b924825819e17ff9c1dccb0bcd73bd05 | 4,791 | cpp | C++ | src/compile_unit.cpp | mbmaier/asm-lisp | a09a1d53d324c6a2b177a02a6233cb71124fb768 | [
"MIT"
] | null | null | null | src/compile_unit.cpp | mbmaier/asm-lisp | a09a1d53d324c6a2b177a02a6233cb71124fb768 | [
"MIT"
] | null | null | null | src/compile_unit.cpp | mbmaier/asm-lisp | a09a1d53d324c6a2b177a02a6233cb71124fb768 | [
"MIT"
] | 1 | 2015-06-24T12:54:34.000Z | 2015-06-24T12:54:34.000Z | #include "compile_unit.hpp"
#include "module.hpp"
#include "compilation_context.hpp"
#include "parse_state.hpp"
#include "parse.hpp"
#include "error/compile_exception.hpp"
#include "error/import_export_error.hpp"
#include <boost/optional.hpp>
#include <utility>
#include <fstream>
#include <iterator>
#include <algorithm>
using std::vector;
using std::pair;
using std::tuple;
using std::ifstream;
using std::ios;
using std::istreambuf_iterator;
using std::move;
using std::find;
using std::string;
using std::size_t;
using boost::filesystem::path;
using boost::filesystem::exists;
using boost::optional;
using boost::none;
using namespace import_export_error;
vector<size_t> toposort(const vector<vector<size_t>>& graph)
{
// crude implementation of topological sort
vector<optional<vector<size_t>>> remaining_graph{graph.begin(), graph.end()};
auto remove_node = [&](size_t node_to_remove)
{
remaining_graph[node_to_remove] = none;
for(optional<vector<size_t>>& neighbors : remaining_graph)
{
if(neighbors)
neighbors->erase(remove(neighbors->begin(), neighbors->end(), node_to_remove), neighbors->end());
}
};
vector<size_t> result;
result.reserve(graph.size());
while(result.size() != graph.size())
{
for(size_t node = 0; node != remaining_graph.size(); ++node)
{
optional<vector<size_t>>& neighbors = remaining_graph[node];
if(!neighbors)
continue;
if(neighbors->empty())
{
result.push_back(node);
remove_node(node);
goto node_removed;
}
}
throw circular_dependency{};
node_removed:;
}
return result;
}
parsed_file read_file(size_t file_id, const path& p)
{
if(p.extension() != ".al")
throw wrong_file_extension{};
if(!exists(p))
throw file_not_found{};
ifstream file{p.native(), ios::binary};
if(!file)
throw io_error{};
istreambuf_iterator<char> begin{file};
istreambuf_iterator<char> end{};
dynamic_graph graph_owner;
parse_state<istreambuf_iterator<char>> state{begin, end, file_id, graph_owner};
list_node& syntax_tree = parse_file(state);
module_header header = read_module_header(syntax_tree);
return {syntax_tree, move(graph_owner), move(header)};
}
vector<module> compile_unit(const vector<path>& paths, compilation_context& context)
{
auto parsed_files = save<vector<parsed_file>>(mapped(enumerate(paths), unpacking(
[&](size_t index, const path& p) -> parsed_file
{
return read_file(index, p);
})));
auto lookup_file_id = [&](const path& parent_path, const import_statement& import) -> size_t
{
path module_path{parent_path / (save<string>(rangeify(import.imported_module)) + ".al")};
auto it = find(paths.begin(), paths.end(), module_path);
if(it == paths.end())
fatal<id("module_not_found")>(import.imported_module.source());
return it - paths.begin();
};
auto dependency_graph = save<vector<vector<size_t>>>(mapped(zipped(paths, parsed_files), unpacking(
[&](const path& p, parsed_file& f)
{
path parent = p.parent_path();
auto& imports = f.header.imports;
auto non_core_imports = filtered(imports,
[&](const import_statement& import)
{
static const string core_str = "core";
return rangeify(import.imported_module) != rangeify(core_str);
});
return save<vector<size_t>>(mapped(non_core_imports,
[&](const import_statement& import)
{
return lookup_file_id(parent, import);
}));
})));
vector<size_t> compilation_order_indices = toposort(dependency_graph);
auto ordered_paths = permuted(paths, compilation_order_indices);
auto ordered_parsed_files = permuted(parsed_files, compilation_order_indices);
vector<module> modules;
modules.reserve(paths.size());
for_each(zipped(ordered_paths, ordered_parsed_files), unpacking(
[&](const path& p, parsed_file& file)
{
path parent = p.parent_path();
auto lookup_module = [&](const import_statement& import) -> module&
{
const static string core_str = "core";
if(rangeify(import.imported_module) == rangeify(core_str))
return context.core_module();
size_t file_id = lookup_file_id(parent, import);
assert(file_id < modules.size());
return modules[file_id];
};
modules.emplace_back(evaluate_module(file.syntax_tree, move(file.graph_owner), move(file.header), lookup_module));
}));
return modules;
}
| 30.322785 | 122 | 0.642455 | [
"vector"
] |
4914eadde6dd53a5bb5b4abb220bbb70ef1cd282 | 1,955 | cpp | C++ | tc 160+/LotteryPyaterochka.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/LotteryPyaterochka.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/LotteryPyaterochka.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
double C(int n, int k) {
int ret = 1;
for (int i=0; i<k; ++i) {
ret = ret*(n-i)/(i+1);
}
return double(ret);
}
class LotteryPyaterochka {
public:
double chanceToWin(int N) {
if (N <= 2) {
return 1.0;
}
return N*(C(5, 3)*C(5*(N-1), 2) + C(5, 4)*5*(N-1) + 1)/C(5*N, 5);
}
// 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(); }
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 double &Expected, const double &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 = 1; double Arg1 = 1.0; verify_case(0, Arg1, chanceToWin(Arg0)); }
void test_case_1() { int Arg0 = 2; double Arg1 = 1.0; verify_case(1, Arg1, chanceToWin(Arg0)); }
void test_case_2() { int Arg0 = 3; double Arg1 = 0.5004995004995004; verify_case(2, Arg1, chanceToWin(Arg0)); }
void test_case_3() { int Arg0 = 6; double Arg1 = 0.13161551092585574; verify_case(3, Arg1, chanceToWin(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
LotteryPyaterochka ___test;
___test.run_test(-1);
}
// END CUT HERE
| 33.706897 | 315 | 0.562148 | [
"vector"
] |
4919207f142e8bd4b3ee98a1dd89e489f63b64d6 | 7,339 | cxx | C++ | samples/boid.cxx | rita0222/FK | bc5786a5da0dd732e2f411c1a953b331323ee432 | [
"BSD-3-Clause"
] | 4 | 2020-05-15T03:43:53.000Z | 2021-06-05T16:21:31.000Z | samples/boid.cxx | rita0222/FK | bc5786a5da0dd732e2f411c1a953b331323ee432 | [
"BSD-3-Clause"
] | 1 | 2020-05-19T09:27:16.000Z | 2020-05-21T02:12:54.000Z | samples/boid.cxx | rita0222/FK | bc5786a5da0dd732e2f411c1a953b331323ee432 | [
"BSD-3-Clause"
] | null | null | null | #include <FK/FK.h>
#include <memory>
using namespace std;
using namespace FK;
// エージェント用クラス
class Agent {
private:
unique_ptr<fk_Model> model;
fk_Vector newVec;
public:
Agent(void);
fk_Vector getPos(void);
void setVec(fk_Vector);
fk_Vector getVec(void);
void setShape(fk_Shape *);
void entry(fk_AppWindow *);
void forward(void);
static constexpr double SPEED = 0.05;
static constexpr double AREASIZE = 15.0;
};
// 群衆用クラス
class Boid {
private:
vector< unique_ptr<Agent> > agent;
unique_ptr<fk_Cone> cone;
double paramA, paramB, paramC, paramLA, paramLB;
vector<fk_Vector> pArray, vArray;
public:
Boid(int);
void setParam(double, double, double, double, double);
void setWindow(fk_AppWindow *);
void forward(bool, bool, bool);
};
// コンストラクタ
Agent::Agent(void)
{
model = make_unique<fk_Model>();
model->setMaterial(Material::Red);
// モデルの方向と位置をランダムに設定
model->glVec(fk_Math::drand(-1.0, 1.0), fk_Math::drand(-1.0, 1.0), 0.0);
model->glMoveTo(fk_Math::drand(-AREASIZE, AREASIZE),
fk_Math::drand(-AREASIZE, AREASIZE), 0.0);
}
// 位置取得
fk_Vector Agent::getPos(void)
{
return model->getPosition();
}
// 方向設定
void Agent::setVec(fk_Vector argV)
{
newVec = argV;
}
// 方向取得
fk_Vector Agent::getVec(void)
{
return model->getVec();
}
// 形状設定
void Agent::setShape(fk_Shape *argS)
{
model->setShape(argS);
}
// ウィンドウ登録
void Agent::entry(fk_AppWindow *argWin)
{
argWin->entry(model.get());
}
// 前進
void Agent::forward()
{
model->glVec(newVec);
model->loTranslate(0.0, 0.0, -SPEED);
}
// 群集のコンストラクタ
Boid::Boid(int argNum)
{
// 形状インスタンス生成
cone = make_unique<fk_Cone>(16, 0.4, 1.0, true);
if(argNum < 0) return;
// エージェントインスタンスの作成
for(int i = 0; i < argNum; ++i) {
/*
unique_ptr<Agent> newAgent = make_unique<Agent>();
newAgent->setShape(cone.get());
agent.push_back(move(newAgent));
*/
agent.push_back(make_unique<Agent>());
agent.back()->setShape(cone.get());
}
pArray.resize(vector<fk_Vector>::size_type(argNum));
vArray.resize(vector<fk_Vector>::size_type(argNum));
// 各種パラメータ設定
paramA = 0.2;
paramB = 0.02;
paramC = 0.01;
paramLA = 3.0;
paramLB = 5.0;
}
// パラメータ設定メソッド
void Boid::setParam(double argA, double argB, double argC, double argLA, double argLB)
{
paramA = argA;
paramB = argB;
paramC = argC;
paramLA = argLA;
paramLB = argLB;
}
// ウィンドウへのエージェント登録メソッド
void Boid::setWindow(fk_AppWindow *argWin)
{
for(auto &A : agent) A->entry(argWin);
}
// 各エージェント動作メソッド
void Boid::forward(bool argSMode, bool argAMode, bool argCMode)
{
fk_Vector gVec, diff;
//vector<fk_Vector> pArray(agent.size()); // 位置ベクトル格納用配列
//vector<fk_Vector> vArray(agent.size()); // 方向ベクトル格納用配列
// 全体の重心計算
for(size_t i = 0; i < agent.size(); i++) {
pArray[i] = agent[i]->getPos();
vArray[i] = agent[i]->getVec();
gVec += pArray[i];
}
gVec /= (double)(agent.size());
// エージェントごとの動作算出演算
for(size_t i = 0; i < agent.size(); i++) {
fk_Vector p = pArray[i];
fk_Vector v = vArray[i];
for(size_t j = 0; j < agent.size(); j++) {
if(i == j) continue;
diff = p - pArray[j];
double dist = diff.dist();
// 分離 (Separation) 処理
if(dist < paramLA && argSMode == true) {
v += paramA * diff / (dist*dist);
}
// 整列 (Alignment) 処理
if(dist < paramLB && argAMode == true) {
v += paramB * vArray[j];
}
}
// 結合 (Cohesion) 処理 (スペースキーが押されていたら無効化)
if(argCMode == true) {
v += paramC * (gVec - p);
}
// 領域の外側に近づいたら方向修正
if(fabs(p.x) > Agent::AREASIZE && p.x * v.x > 0.0 && fabs(v.x) > 0.01) {
v.x -= v.x * (fabs(p.x) - Agent::AREASIZE)*0.2;
}
if(fabs(p.y) > Agent::AREASIZE && p.y * v.y > 0.0 && fabs(v.y) > 0.01) {
v.y -= v.y * (fabs(p.y) - Agent::AREASIZE)*0.2;
}
// 最終的な方向ベクトル演算結果を代入
v.z = 0.0;
agent[i]->setVec(v);
}
// 全エージェントを前進
for(auto &A : agent) A->forward();
}
int main(int, char **)
{
unique_ptr<fk_AppWindow> win(new fk_AppWindow());
unique_ptr<Boid> boid(new Boid(200));
boid->setWindow(win.get());
// ウィンドウ各種設定
win->setSize(800, 800);
win->setBGColor(0.6, 0.7, 0.8);
win->showGuide(fk_Guide::GRID_XY);
win->setCameraPos(0.0, 0.0, 80.0);
win->setCameraFocus(0.0, 0.0, 0.0);
win->setTrackBallMode(true);
win->open();
while(win->update() == true) {
// Sキーで「Separate(分離)」を OFF に
bool sMode = win->getKeyStatus('S', fk_Switch::RELEASE);
// Aキーで「Alignment(整列)」を OFF に
bool aMode = win->getKeyStatus('A', fk_Switch::RELEASE);
// Cキーで「Cohesion(結合)」を OFF に
bool cMode = win->getKeyStatus('C', fk_Switch::RELEASE);
// 群集の前進処理
boid->forward(sMode, aMode, cMode);
}
}
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* - Neither the name of the copyright holders nor the names
* of its contributors may be used to endorse or promote
* products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* 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.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* 本ソフトウェアおよびソースコードのライセンスは、基本的に
* 「修正 BSD ライセンス」に従います。以下にその詳細を記します。
*
* ソースコード形式かバイナリ形式か、変更するかしないかを問わず、
* 以下の条件を満たす場合に限り、再頒布および使用が許可されます。
*
* - ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、
* および下記免責条項を含めること。
*
* - バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の
* 資料に、上記の著作権表示、本条件一覧、および下記免責条項を
* 含めること。
*
* - 書面による特別の許可なしに、本ソフトウェアから派生した製品の
* 宣伝または販売促進に、本ソフトウェアの著作権者の名前または
* コントリビューターの名前を使用してはならない。
*
* 本ソフトウェアは、著作権者およびコントリビューターによって「現
* 状のまま」提供されており、明示黙示を問わず、商業的な使用可能性、
* および特定の目的に対する適合性に関す暗黙の保証も含め、またそれ
* に限定されない、いかなる保証もないものとします。著作権者もコン
* トリビューターも、事由のいかんを問わず、損害発生の原因いかんを
* 問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その
* 他の)不法行為であるかを問わず、仮にそのような損害が発生する可
* 能性を知らされていたとしても、本ソフトウェアの使用によって発生
* した(代替品または代用サービスの調達、使用の喪失、データの喪失、
* 利益の喪失、業務の中断も含め、またそれに限定されない)直接損害、
* 間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害に
* ついて、一切責任を負わないものとします。
*
****************************************************************************/
| 24.545151 | 86 | 0.654313 | [
"vector",
"model"
] |
4920eb1516481e17fc44c9890345a75715c4e0c4 | 4,718 | cpp | C++ | PLatformner/Motor2D/j2MainMenu.cpp | AdrianFR99/Raider-of-the-Lost-World | 6684f25ad98a9870a4b02767c1912e0984b6ccd5 | [
"MIT"
] | 1 | 2020-06-07T14:41:18.000Z | 2020-06-07T14:41:18.000Z | PLatformner/Motor2D/j2MainMenu.cpp | AdrianFR99/Raider-of-the-Lost-World | 6684f25ad98a9870a4b02767c1912e0984b6ccd5 | [
"MIT"
] | null | null | null | PLatformner/Motor2D/j2MainMenu.cpp | AdrianFR99/Raider-of-the-Lost-World | 6684f25ad98a9870a4b02767c1912e0984b6ccd5 | [
"MIT"
] | null | null | null | #include "j1App.h"
#include "j2MainMenu.h"
#include "p2Log.h"
#include "j1Audio.h"
#include "j1Textures.h"
#include "j1Render.h"
#include "j1FadeToBlack.h"
#include "j1Scene.h"
#include "j2EntityManager.h"
#include "ElementGUI.h"
#include "j1Input.h"
#include "PugiXml/src/pugixml.hpp"
j2MainMenu::j2MainMenu()
{
name.create("menu");
}
j2MainMenu::~j2MainMenu()
{
}
bool j2MainMenu::Awake(pugi::xml_node& config) {
folder.create(config.child("folder").child_value());
p2SString strAux = config.child("MainMenuTex").attribute("path").as_string();
p2SString strAux2("%s%s", folder.GetString(), strAux.GetString());
p2SString strAux3 = config.child("LogoTex").attribute("path").as_string();
p2SString strAux4("%s%s", folder.GetString(), strAux3.GetString());
MainMenuRect.x = config.child("MainMenuRect").attribute("x").as_int();
MainMenuRect.y= config.child("MainMenuRect").attribute("y").as_int();
MainMenuRect.w = config.child("MainMenuRect").attribute("w").as_int();
MainMenuRect.h = config.child("MainMenuRect").attribute("h").as_int();
LogoRect.x = config.child("LogoRect").attribute("x").as_int();
LogoRect.y = config.child("LogoRect").attribute("y").as_int();
LogoRect.w = config.child("LogoRect").attribute("w").as_int();
LogoRect.h = config.child("LogoRect").attribute("h").as_int();
texturePath = strAux2;
logoPath = strAux4;
return true;
}
// Called before the first frame
bool j2MainMenu::Start() {
App->scene->Disable();
App->entities->Disable();
MainMenuTex = App->tex->Load(texturePath.GetString());
LogoTex = App->tex->Load(logoPath.GetString());
//Play the menu song
p2SString menu_song("%s%s", App->audio->music_folder.GetString(), App->audio->songs_list.end->data->GetString());
App->audio->PlayMusic(menu_song.GetString(), 0.5f);
App->render->camera.x = 0;
App->render->camera.y = 0;
App->gui->Hide("Settings_Window");
App->gui->Hide("Credits_Window");
App->gui->Hide("InGameUI");
App->gui->Hide("InGame_Settings_Window");
App->gui->Display("Main_Menu");
/*App->gui->CreateMainMenuScreen();*/
//If the Continue button exists and is disabled and there is a save, enable
pugi::xml_document save_file;
pugi::xml_parse_result res;
res = save_file.load_file("save_game.xml");
ElementGUI* continue_ptr = nullptr;
for (p2List_item<ElementGUI*>* item = App->gui->ElementList.start; item != nullptr; item = item->next)
{
if (item->data->action == ElementAction::CONTINUE)
{
continue_ptr = item->data;
break;
}
}
if (res != NULL && continue_ptr !=nullptr)
{
continue_ptr->interactable = true;
}
return true;
}
// Called each loop iteration
bool j2MainMenu::PreUpdate() {
return true;
}
bool j2MainMenu::Update(float dt) {
bool ret = true;
if (exit_game == true)
{
ret = false;
}
if (App->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN)
{
App->gui->debug = !App->gui->debug;
}
return ret;
}
bool j2MainMenu::PostUpdate() {
App->render->Blit(MainMenuTex,0,0,&MainMenuRect);
App->render->Blit(LogoTex, 115, 20, &LogoRect,SDL_FLIP_NONE,1.0f,0.0,0,0,true,true);
return true;
}
// Called before quitting
bool j2MainMenu::CleanUp() {
if (MainMenuTex !=nullptr)
{
App->tex->UnLoad(MainMenuTex);
MainMenuTex = nullptr;
}
return true;
}
void j2MainMenu::callbackUiElement(ElementGUI *element)
{
if (element->type == ElementType::BUTTON)
{
switch (element->action)
{
case ElementAction::PLAY:
if (element->was_clicked && element->clicked == false)
{
App->fade->FadeToBlack(this, App->scene, 3.0f);
}
break;
case ElementAction::CONTINUE:
if (element->was_clicked && element->clicked == false)
{
App->fade->FadeToBlack(this, App->scene, 3.0f, true);
}
break;
case ElementAction::SETTINGS:
if (element->was_clicked && element->clicked == false)
{
App->gui->Display("Settings_Window");
}
break;
case ElementAction::SETTINGS_BACK:
if (element->was_clicked && element->clicked == false)
{
App->gui->Hide("Settings_Window");
}
break;
case ElementAction::CREDITS:
if (element->was_clicked && element->clicked == false)
{
App->gui->Display("Credits_Window");
}
break;
case ElementAction::CREDITS_BACK:
if (element->was_clicked && element->clicked == false)
{
App->gui->Hide("Credits_Window");
}
break;
case ElementAction::WEB:
if (element->was_clicked && element->clicked == false)
{
ShellExecuteA(NULL, "open", "https://adrianfr99.github.io/Raider-of-the-Lost-World/", NULL, NULL, SW_SHOWNORMAL);
}
break;
case ElementAction::EXIT:
if (element->was_clicked && element->clicked == false)
{
exit_game = true;
}
break;
}
}
}
| 20.513043 | 117 | 0.671683 | [
"render"
] |
49219f816f0a1528a4434ccdeb3fe878ad8c5948 | 12,778 | cpp | C++ | native/src/snappyclient/cpp/ResultSet.cpp | SnappyDataInc/snappy-store | 8f6a4b80fa14ffd0683752a03eeab311b545fbbd | [
"Apache-2.0"
] | 38 | 2016-01-04T01:31:40.000Z | 2020-04-07T06:35:36.000Z | native/src/snappyclient/cpp/ResultSet.cpp | SnappyDataInc/snappy-store | 8f6a4b80fa14ffd0683752a03eeab311b545fbbd | [
"Apache-2.0"
] | 261 | 2016-01-07T09:14:26.000Z | 2019-12-05T10:15:56.000Z | native/src/snappyclient/cpp/ResultSet.cpp | SnappyDataInc/snappy-store | 8f6a4b80fa14ffd0683752a03eeab311b545fbbd | [
"Apache-2.0"
] | 22 | 2016-03-09T05:47:09.000Z | 2020-04-02T17:55:30.000Z | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. 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. See accompanying
* LICENSE file.
*/
/*
* Changes for SnappyData data platform.
*
* Portions Copyright (c) 2017-2019 TIBCO Software Inc. 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. See accompanying
* LICENSE file.
*/
/**
* ResultSet.cpp
*/
#include "impl/pch.h"
#include "ResultSet.h"
#include "StatementAttributes.h"
#include "impl/ClientService.h"
using namespace io::snappydata;
using namespace io::snappydata::client;
const ResultSet::const_iterator ResultSet::ITR_END_CONST;
const ResultSet::iterator ResultSet::ITR_END;
ResultSet::ResultSet(thrift::RowSet* rows,
const std::shared_ptr<ClientService>& service,
const StatementAttributes& attrs, const int32_t batchSize, bool updatable,
bool scrollable, bool isOwner) :
m_rows(rows), m_service(service), m_attrs(attrs), m_batchSize(batchSize),
m_updatable(updatable), m_scrollable(scrollable), m_isOwner(isOwner),
m_descriptors(nullptr), m_columnPositionMap(nullptr) {
initRowData(false);
}
void ResultSet::initRowData(bool clearData) {
if (clearData) m_rowData.clear();
auto &rows = m_rows->rows;
auto numRows = rows.size();
if (numRows > 0) {
m_rowData.reserve(numRows);
for (thrift::Row& row : rows) {
m_rowData.push_back(std::move(row));
}
}
}
bool ResultSet::moveToNextRowSet(int32_t offset) {
checkOpen("moveToNextRowSet");
// copy descriptors prior to move since descriptors may not be
// set by server in subsequent calls
copyDescriptors();
m_service->scrollCursor(*m_rows, m_rows->cursorId, offset, false, false,
m_batchSize);
initRowData(true);
return !m_rowData.empty();
}
bool ResultSet::moveToRowSet(int32_t offset, int32_t batchSize,
bool offsetIsAbsolute) {
checkOpen("moveToRowSet");
checkScrollable("moveToRowSet");
// copy descriptors prior to move since descriptors may not be
// set by server in subsequent calls
copyDescriptors();
m_service->scrollCursor(*m_rows, m_rows->cursorId, offset, offsetIsAbsolute,
false, batchSize);
initRowData(true);
return !m_rowData.empty();
}
struct ClearUpdates final {
private:
UpdatableRow* m_row;
public:
ClearUpdates(UpdatableRow* row) : m_row(row) {
}
~ClearUpdates() {
m_row->clearChangedColumns();
}
};
void ResultSet::insertRow(UpdatableRow* row, int32_t rowIndex) {
checkOpen("insertRow");
if (row && row->getChangedColumns()) {
ClearUpdates clearRow(row);
std::vector<int32_t> changedColumns(
std::move(row->getChangedColumnsAsVector()));
if (!changedColumns.empty()) {
m_service->executeCursorUpdate(m_rows->cursorId,
thrift::CursorUpdateOperation::INSERT_OP, *row, changedColumns,
rowIndex);
return;
}
}
throw GET_SQLEXCEPTION2(
SQLStateMessage::CURSOR_NOT_POSITIONED_ON_INSERT_ROW_MSG);
}
void ResultSet::updateRow(UpdatableRow* row, int32_t rowIndex) {
checkOpen("updateRow");
if (row && row->getChangedColumns()) {
ClearUpdates clearRow(row);
std::vector<int32_t> changedColumns(
std::move(row->getChangedColumnsAsVector()));
if (!changedColumns.empty()) {
m_service->executeCursorUpdate(m_rows->cursorId,
thrift::CursorUpdateOperation::UPDATE_OP, *row, changedColumns,
rowIndex);
return;
}
}
throw GET_SQLEXCEPTION2(
SQLStateMessage::INVALID_CURSOR_UPDATE_AT_CURRENT_POSITION_MSG);
}
void ResultSet::deleteRow(UpdatableRow* row, int32_t rowIndex) {
checkOpen("deleteRow");
ClearUpdates clearRow(row);
m_service->executeBatchCursorUpdate(m_rows->cursorId,
Utils::singleVector(thrift::CursorUpdateOperation::DELETE_OP),
std::vector<thrift::Row>(), std::vector<std::vector<int32_t> >(),
Utils::singleVector(rowIndex));
}
ResultSet::const_iterator ResultSet::cbegin(int32_t offset) const {
checkOpen("cbegin");
if (offset != 0) {
checkScrollable("cbegin");
}
return const_iterator(const_cast<ResultSet*>(this), offset);
}
ResultSet::iterator ResultSet::begin(int32_t offset) {
checkOpen("begin");
if (offset != 0) {
checkScrollable("begin");
}
return iterator(this, offset);
}
uint32_t ResultSet::getColumnPosition(const std::string& name) const {
checkOpen("getColumnPosition");
if (!m_columnPositionMap) {
// populate the map on first call
const std::vector<thrift::ColumnDescriptor>* descriptors =
m_descriptors ? &m_rows->metadata : m_descriptors;
m_columnPositionMap = new std::unordered_map<std::string, uint32_t>();
std::locale currentLocale;
uint32_t index = 1;
for (const auto& cd : *descriptors) {
if (cd.__isset.name) {
m_columnPositionMap->emplace(cd.name, index);
// add lower-case if different
auto lower = boost::algorithm::to_lower_copy(cd.name, currentLocale);
if (cd.name != lower) {
m_columnPositionMap->emplace(lower, index);
}
// allow looking up using name, table.name and schema.table.name
if (cd.__isset.fullTableName) {
auto dotPos = cd.fullTableName.find('.');
if (dotPos != 0) {
auto fullName = cd.fullTableName + "." + cd.name;
m_columnPositionMap->emplace(fullName, index);
// add lower-case if different
lower = boost::algorithm::to_lower_copy(fullName, currentLocale);
if (fullName != lower) {
m_columnPositionMap->emplace(lower, index);
}
}
if (dotPos != std::string::npos) {
auto fullName = cd.fullTableName.substr(dotPos + 1) + "." + cd.name;
m_columnPositionMap->emplace(fullName, index);
// add lower-case if different
lower = boost::algorithm::to_lower_copy(fullName, currentLocale);
if (fullName != lower) {
m_columnPositionMap->emplace(lower, index);
}
}
}
}
index++;
}
}
auto findColumn = m_columnPositionMap->find(name);
if (findColumn != m_columnPositionMap->end()) {
return findColumn->second;
} else {
findColumn = m_columnPositionMap->find(
boost::algorithm::to_lower_copy(name));
if (findColumn != m_columnPositionMap->end()) {
return findColumn->second;
} else {
throw GET_SQLEXCEPTION2(SQLStateMessage::COLUMN_NOT_FOUND_MSG2,
name.c_str());
}
}
}
ColumnDescriptor ResultSet::getColumnDescriptor(
std::vector<thrift::ColumnDescriptor>& descriptors,
const uint32_t columnIndex, const char* operation) {
// Check that columnIndex is in range.
if (columnIndex >= 1 && columnIndex <= descriptors.size()) {
// check if fullTableName, typeAndClassName are missing
// which may be optimized out for consecutive same values
thrift::ColumnDescriptor& cd = descriptors[columnIndex - 1];
if (!cd.__isset.fullTableName) {
// search for the table
for (uint32_t i = columnIndex - 1; i > 0; i--) {
thrift::ColumnDescriptor& cd2 = descriptors[i - 1];
if (cd2.__isset.fullTableName) {
cd.__set_fullTableName(cd2.fullTableName);
break;
}
}
}
if (cd.type == thrift::SnappyType::JAVA_OBJECT) {
if (!cd.__isset.udtTypeAndClassName) {
// search for the UDT typeAndClassName
for (uint32_t i = columnIndex - 1; i > 0; i--) {
thrift::ColumnDescriptor& cd2 = descriptors[i - 1];
if (cd2.__isset.udtTypeAndClassName) {
cd.__set_udtTypeAndClassName(cd2.udtTypeAndClassName);
break;
}
}
}
}
return ColumnDescriptor(cd, columnIndex);
} else {
throw GET_SQLEXCEPTION2(SQLStateMessage::INVALID_DESCRIPTOR_INDEX_MSG,
static_cast<int>(columnIndex), descriptors.size(), operation);
}
}
ColumnDescriptor ResultSet::getColumnDescriptor(const uint32_t columnIndex) {
checkOpen("getColumnDescriptor");
return getColumnDescriptor(!m_descriptors ? m_rows->metadata : *m_descriptors,
columnIndex, "column number in result set");
}
int32_t ResultSet::getRow() const {
return m_rows ? m_rows->offset : 0;
}
std::string ResultSet::getCursorName() const {
checkOpen("getCursorName");
const thrift::RowSet* rs = m_rows;
return rs && rs->__isset.cursorName ? rs->cursorName : "";
}
std::unique_ptr<ResultSet> ResultSet::getNextResults(
const NextResultSetBehaviour behaviour) {
checkOpen("getNextResults");
if (m_rows->cursorId != thrift::snappydataConstants::INVALID_ID) {
std::unique_ptr<thrift::RowSet> rs(new thrift::RowSet());
m_service->getNextResultSet(*rs, m_rows->cursorId,
static_cast<int8_t>(behaviour));
std::unique_ptr<ResultSet> resultSet(
new ResultSet(rs.get(), m_service, m_attrs, m_batchSize, m_updatable,
m_scrollable));
rs.release();
// check for empty ResultSet
if (resultSet->getColumnCount() == 0) {
return std::unique_ptr<ResultSet>(nullptr);
} else {
return resultSet;
}
} else {
// single forward-only result set that has been consumed
return std::unique_ptr<ResultSet>(nullptr);
}
}
std::unique_ptr<SQLWarning> ResultSet::getWarnings() const {
checkOpen("getWarnings");
if (m_rows->__isset.warnings) {
return std::unique_ptr<SQLWarning>(new GET_SQLWARNING(m_rows->warnings));
} else {
return std::unique_ptr<SQLWarning>();
}
}
std::unique_ptr<ResultSet> ResultSet::clone() const {
checkOpen("clone");
if (m_rows) {
/* clone the contained object */
std::unique_ptr<thrift::RowSet> rs(new thrift::RowSet(*m_rows));
std::unique_ptr<ResultSet> resultSet(
new ResultSet(rs.get(), m_service, m_attrs, m_batchSize, m_updatable,
m_scrollable, true /* isOwner */));
rs.release();
if (m_descriptors) {
resultSet->m_descriptors = new std::vector<thrift::ColumnDescriptor>(
*m_descriptors);
}
return resultSet;
} else {
return std::unique_ptr<ResultSet>();
}
}
void ResultSet::cleanupRS() {
if (m_descriptors) {
delete m_descriptors;
m_descriptors = nullptr;
}
if (m_columnPositionMap) {
delete m_columnPositionMap;
m_columnPositionMap = nullptr;
}
}
void ResultSet::deleteData() noexcept {
Utils::handleExceptionsInDestructor("result set (delete data)", [&]() {
if (m_isOwner && m_rows) {
delete m_rows;
}
m_rows = nullptr;
cleanupRS();
});
}
bool ResultSet::cancelStatement() {
if (m_rows) {
const auto statementId = m_rows->statementId;
if (statementId != thrift::snappydataConstants::INVALID_ID) {
m_service->cancelStatement(statementId);
return true;
}
}
return false;
}
void ResultSet::close(bool closeStatement) {
if (m_rows && m_rows->cursorId != thrift::snappydataConstants::INVALID_ID) {
// need to make the server call only if this is not the last batch
// or a scrollable cursor with multiple batches, otherwise server
// would have already closed the ResultSet
if ((m_rows->flags &
thrift::snappydataConstants::ROWSET_LAST_BATCH) == 0 || m_scrollable) {
m_service->closeResultSet(m_rows->cursorId);
}
if (closeStatement) {
const auto statementId = m_rows->statementId;
if (statementId != thrift::snappydataConstants::INVALID_ID) {
m_service->closeStatement(statementId);
}
}
}
deleteData();
}
ResultSet::~ResultSet() {
// destructor should *never* throw an exception
// TODO: close from destructor should use bulkClose if valid handle
Utils::handleExceptionsInDestructor("result set", [&]() {
close(false);
});
deleteData();
}
| 31.945 | 80 | 0.67851 | [
"object",
"vector"
] |
492f1cfdc40547b295a7b68acb7fcb736522dde8 | 47,272 | cpp | C++ | tests/tests/block_tests.cpp | soundac/SounDAC-Source | 56bf367c1ac78fd71d16efd63affa5c293c674f7 | [
"BSD-2-Clause"
] | 2 | 2018-10-07T11:46:51.000Z | 2019-05-07T09:51:44.000Z | tests/tests/block_tests.cpp | soundac/SounDAC-Source | 56bf367c1ac78fd71d16efd63affa5c293c674f7 | [
"BSD-2-Clause"
] | 26 | 2018-08-20T13:03:25.000Z | 2019-10-02T19:42:00.000Z | tests/tests/block_tests.cpp | soundac/SounDAC-Source | 56bf367c1ac78fd71d16efd63affa5c293c674f7 | [
"BSD-2-Clause"
] | 7 | 2018-08-23T13:53:11.000Z | 2020-10-16T06:48:41.000Z | /*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <boost/test/unit_test.hpp>
#include <muse/chain/database.hpp>
#include <muse/chain/exceptions.hpp>
#include <muse/chain/base_objects.hpp>
#include <muse/chain/history_object.hpp>
#include <muse/account_history/account_history_plugin.hpp>
#include <graphene/utilities/tempdir.hpp>
#include <fc/crypto/digest.hpp>
#include "../common/database_fixture.hpp"
using namespace muse::chain;
using namespace muse::chain::test;
BOOST_AUTO_TEST_SUITE(block_tests)
BOOST_AUTO_TEST_CASE( block_database_test )
{
try {
fc::temp_directory data_dir( graphene::utilities::temp_directory_path() );
block_database bdb;
bdb.open( data_dir.path() );
FC_ASSERT( bdb.is_open() );
bdb.close();
FC_ASSERT( !bdb.is_open() );
bdb.open( data_dir.path() );
signed_block b;
for( uint32_t i = 0; i < 5; ++i )
{
if( i > 0 ) b.previous = b.id();
b.witness = witness_id_type(i+1);
bdb.store( b.id(), b );
auto fetch = bdb.fetch_by_number( b.block_num() );
FC_ASSERT( fetch.valid() );
FC_ASSERT( fetch->witness == b.witness );
fetch = bdb.fetch_by_number( i+1 );
FC_ASSERT( fetch.valid() );
FC_ASSERT( fetch->witness == b.witness );
fetch = bdb.fetch_optional( b.id() );
FC_ASSERT( fetch.valid() );
FC_ASSERT( fetch->witness == b.witness );
}
for( uint32_t i = 1; i < 5; ++i )
{
auto blk = bdb.fetch_by_number( i );
FC_ASSERT( blk.valid() );
// Another ASSERT may be needed here
}
auto last = bdb.last();
FC_ASSERT( last );
FC_ASSERT( last->id() == b.id() );
bdb.close();
bdb.open( data_dir.path() );
last = bdb.last();
FC_ASSERT( last );
FC_ASSERT( last->id() == b.id() );
for( uint32_t i = 0; i < 5; ++i )
{
auto blk = bdb.fetch_by_number( i+1 );
FC_ASSERT( blk.valid() );
// Another ASSERT may be needed here
}
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
static const fc::ecc::private_key& init_account_priv_key()
{
static const auto priv_key = fc::ecc::private_key::regenerate( fc::sha256::hash( string( "init_key" ) ) );
return priv_key;
}
static const fc::ecc::public_key& init_account_pub_key()
{
static const auto pub_key = init_account_priv_key().get_public_key();
return pub_key;
}
static void init_witness_keys( muse::chain::database& db )
{
const account_object& init_acct = db.get_account( MUSE_INIT_MINER_NAME );
db.modify( init_acct, []( account_object& acct ) {
acct.active.add_authority( init_account_pub_key(), acct.active.weight_threshold );
});
const witness_object& init_witness = db.get_witness( MUSE_INIT_MINER_NAME );
db.modify( init_witness, []( witness_object& witness ) {
witness.signing_key = init_account_pub_key();
});
}
BOOST_AUTO_TEST_CASE( generate_empty_blocks )
{
try {
fc::time_point_sec now( MUSE_TESTING_GENESIS_TIMESTAMP );
fc::temp_directory data_dir( graphene::utilities::temp_directory_path() );
signed_block b;
genesis_state_type genesis;
genesis.init_supply = INITIAL_TEST_SUPPLY;
// TODO: Don't generate this here
signed_block cutoff_block;
uint32_t last_block;
{
database db;
db.open(data_dir.path(), genesis, "TEST" );
init_witness_keys( db );
b = db.generate_block(db.get_slot_time(1), db.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
// TODO: Change this test when we correct #406
// n.b. we generate MUSE_MIN_UNDO_HISTORY+1 extra blocks which will be discarded on save
for( uint32_t i = 1; ; ++i )
{
BOOST_CHECK( db.head_block_id() == b.id() );
//witness_id_type prev_witness = b.witness;
string cur_witness = db.get_scheduled_witness(1);
//BOOST_CHECK( cur_witness != prev_witness );
b = db.generate_block(db.get_slot_time(1), cur_witness, init_account_priv_key(), database::skip_nothing);
BOOST_CHECK( b.witness == cur_witness );
uint32_t cutoff_height = db.get_dynamic_global_properties().last_irreversible_block_num;
if( cutoff_height >= 200 )
{
cutoff_block = *(db.fetch_block_by_number( cutoff_height ));
last_block = db.head_block_num();
break;
}
}
db.close();
}
{
database db;
db.open(data_dir.path(), genesis, "TEST" );
BOOST_CHECK_EQUAL( db.head_block_num(), last_block );
while( db.head_block_num() > cutoff_block.block_num() )
db.pop_block();
b = cutoff_block;
for( uint32_t i = 0; i < 200; ++i )
{
BOOST_CHECK( db.head_block_id() == b.id() );
//witness_id_type prev_witness = b.witness;
string cur_witness = db.get_scheduled_witness(1);
//BOOST_CHECK( cur_witness != prev_witness );
b = db.generate_block(db.get_slot_time(1), cur_witness, init_account_priv_key(), database::skip_nothing);
}
BOOST_CHECK_EQUAL( db.head_block_num(), cutoff_block.block_num()+200 );
}
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( undo_block )
{
try {
genesis_state_type genesis;
genesis.init_supply = INITIAL_TEST_SUPPLY;
fc::temp_directory data_dir( graphene::utilities::temp_directory_path() );
{
database db;
db.open(data_dir.path(), genesis, "TEST" );
init_witness_keys( db );
fc::time_point_sec now( MUSE_TESTING_GENESIS_TIMESTAMP );
std::vector< time_point_sec > time_stack;
for( uint32_t i = 0; i < 5; ++i )
{
now = db.get_slot_time(1);
time_stack.push_back( now );
auto b = db.generate_block( now, db.get_scheduled_witness( 1 ), init_account_priv_key(), database::skip_nothing );
}
BOOST_CHECK( db.head_block_num() == 5 );
BOOST_CHECK( db.head_block_time() == now );
db.pop_block();
time_stack.pop_back();
now = time_stack.back();
BOOST_CHECK( db.head_block_num() == 4 );
BOOST_CHECK( db.head_block_time() == now );
db.pop_block();
time_stack.pop_back();
now = time_stack.back();
BOOST_CHECK( db.head_block_num() == 3 );
BOOST_CHECK( db.head_block_time() == now );
db.pop_block();
time_stack.pop_back();
now = time_stack.back();
BOOST_CHECK( db.head_block_num() == 2 );
BOOST_CHECK( db.head_block_time() == now );
for( uint32_t i = 0; i < 5; ++i )
{
now = db.get_slot_time(1);
time_stack.push_back( now );
auto b = db.generate_block( now, db.get_scheduled_witness( 1 ), init_account_priv_key(), database::skip_nothing );
}
BOOST_CHECK( db.head_block_num() == 7 );
}
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( fork_blocks )
{
try {
fc::temp_directory data_dir1( graphene::utilities::temp_directory_path() );
fc::temp_directory data_dir2( graphene::utilities::temp_directory_path() );
genesis_state_type genesis;
genesis.init_supply = INITIAL_TEST_SUPPLY;
//TODO This test needs 6-7 ish witnesses prior to fork
database db1;
db1.open( data_dir1.path(), genesis, "TEST" );
init_witness_keys( db1 );
database db2;
db2.open( data_dir2.path(), genesis, "TEST" );
init_witness_keys( db2 );
BOOST_TEST_MESSAGE( "Adding blocks 1 through 10" );
for( uint32_t i = 1; i <= 10; ++i )
{
auto b = db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
try {
PUSH_BLOCK( db2, b );
} FC_CAPTURE_AND_RETHROW( ("db2") );
}
for( uint32_t j = 0; j <= 4; j += 4 )
{
// add blocks 11 through 13 to db1 only
BOOST_TEST_MESSAGE( "Adding 3 blocks to db1 only" );
for( uint32_t i = 11 + j; i <= 13 + j; ++i )
{
BOOST_TEST_MESSAGE( i );
auto b = db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
}
string db1_tip = db1.head_block_id().str();
// add different blocks 11 through 13 to db2 only
BOOST_TEST_MESSAGE( "Add 3 different blocks to db2 only" );
uint32_t next_slot = 3;
for( uint32_t i = 11 + j; i <= 13 + j; ++i )
{
BOOST_TEST_MESSAGE( i );
auto b = db2.generate_block(db2.get_slot_time(next_slot), db2.get_scheduled_witness(next_slot), init_account_priv_key(), database::skip_nothing);
next_slot = 1;
// notify both databases of the new block.
// only db2 should switch to the new fork, db1 should not
PUSH_BLOCK( db1, b );
BOOST_CHECK_EQUAL(db1.head_block_id().str(), db1_tip);
BOOST_CHECK_EQUAL(db2.head_block_id().str(), b.id().str());
}
//The two databases are on distinct forks now, but at the same height.
BOOST_CHECK_EQUAL(db1.head_block_num(), 13u + j);
BOOST_CHECK_EQUAL(db2.head_block_num(), 13u + j);
BOOST_CHECK( db1.head_block_id() != db2.head_block_id() );
//Make a block on db2, make it invalid, then
//pass it to db1 and assert that db1 doesn't switch to the new fork.
signed_block good_block;
{
auto b = db2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
good_block = b;
b.transactions.emplace_back(signed_transaction());
b.transactions.back().operations.emplace_back(transfer_operation());
b.sign( init_account_priv_key() );
BOOST_CHECK_EQUAL(b.block_num(), 14u + j);
MUSE_CHECK_THROW(PUSH_BLOCK( db1, b ), fc::exception);
// At this point, `fetch_block_by_number` will fetch block from fork_db,
// so unable to reproduce the issue which is fixed in PR #938
// https://github.com/bitshares/bitshares-core/pull/938
fc::optional<signed_block> previous_block = db1.fetch_block_by_number(1);
BOOST_CHECK ( previous_block.valid() );
uint32_t db1_blocks = db1.head_block_num();
for( uint32_t curr_block_num = 2; curr_block_num <= db1_blocks; ++curr_block_num )
{
fc::optional<signed_block> curr_block = db1.fetch_block_by_number( curr_block_num );
BOOST_CHECK( curr_block.valid() );
BOOST_CHECK_EQUAL( curr_block->previous.str(), previous_block->id().str() );
previous_block = curr_block;
}
}
BOOST_CHECK_EQUAL(db1.head_block_num(), 13u + j);
BOOST_CHECK_EQUAL(db1.head_block_id().str(), db1_tip);
if( j == 0 )
{
// assert that db1 switches to new fork with good block
BOOST_CHECK_EQUAL(db2.head_block_num(), 14u + j);
PUSH_BLOCK( db1, good_block );
BOOST_CHECK_EQUAL(db1.head_block_id().str(), db2.head_block_id().str());
}
}
// generate more blocks to push the forked blocks out of fork_db
BOOST_TEST_MESSAGE( "Adding more blocks to db1, push the forked blocks out of fork_db" );
for( uint32_t i = 1; i <= 50; ++i )
{
db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
}
{
// PR #938 make sure db is in a good state https://github.com/bitshares/bitshares-core/pull/938
BOOST_TEST_MESSAGE( "Checking whether all blocks on disk are good" );
fc::optional<signed_block> previous_block = db1.fetch_block_by_number(1);
BOOST_CHECK ( previous_block.valid() );
uint32_t db1_blocks = db1.head_block_num();
for( uint32_t curr_block_num = 2; curr_block_num <= db1_blocks; ++curr_block_num )
{
fc::optional<signed_block> curr_block = db1.fetch_block_by_number( curr_block_num );
BOOST_CHECK( curr_block.valid() );
BOOST_CHECK_EQUAL( curr_block->previous.str(), previous_block->id().str() );
previous_block = curr_block;
}
}
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( switch_forks_undo_create )
{
try {
fc::temp_directory dir1( graphene::utilities::temp_directory_path() ),
dir2( graphene::utilities::temp_directory_path() );
genesis_state_type genesis;
genesis.init_supply = INITIAL_TEST_SUPPLY;
database db1,
db2;
db1.open( dir1.path(), genesis, "TEST" );
init_witness_keys( db1 );
db2.open( dir2.path(), genesis, "TEST" );
init_witness_keys( db2 );
const graphene::db::index& account_idx = db1.get_index(implementation_ids, impl_account_object_type);
signed_transaction trx;
account_id_type alice_id = account_idx.get_next_id();
account_create_operation cop;
cop.fee = asset(50, MUSE_SYMBOL);
cop.new_account_name = "alice";
cop.creator = MUSE_INIT_MINER_NAME;
cop.owner = authority(1, init_account_pub_key(), 1);
cop.active = cop.owner;
trx.operations.push_back(cop);
trx.set_expiration( db1.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key(), db1.get_chain_id() );
PUSH_TX( db1, trx );
// generate blocks
// db1 : A
// db2 : B C D
auto b = db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
BOOST_CHECK( alice_id == db1.get_account( "alice" ).id );
BOOST_CHECK( alice_id(db1).name == "alice" );
b = db2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
db1.push_block(b);
b = db2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
db1.push_block(b);
MUSE_REQUIRE_THROW(alice_id(db2), fc::exception);
alice_id(db1); /// it should be included in the pending state
db1.clear_pending(); // clear it so that we can verify it was properly removed from pending state.
MUSE_REQUIRE_THROW(alice_id(db1), fc::exception);
PUSH_TX( db2, trx );
b = db2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
db1.push_block(b);
BOOST_CHECK(alice_id(db1).name == "alice");
BOOST_CHECK(alice_id(db2).name == "alice");
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( duplicate_transactions )
{
try {
fc::temp_directory dir1( graphene::utilities::temp_directory_path() ),
dir2( graphene::utilities::temp_directory_path() );
genesis_state_type genesis;
genesis.init_supply = INITIAL_TEST_SUPPLY;
database db1,
db2;
db1.open(dir1.path(), genesis, "TEST" );
init_witness_keys( db1 );
db2.open(dir2.path(), genesis, "TEST" );
init_witness_keys( db2 );
BOOST_CHECK( db1.get_chain_id() == db2.get_chain_id() );
auto skip_sigs = database::skip_transaction_signatures | database::skip_authority_check;
signed_transaction trx;
account_create_operation cop;
cop.new_account_name = "alice";
cop.creator = MUSE_INIT_MINER_NAME;
cop.owner = authority(1, init_account_pub_key(), 1);
cop.active = cop.owner;
trx.operations.push_back(cop);
trx.set_expiration( db1.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key(), db1.get_chain_id() );
PUSH_TX( db1, trx, skip_sigs );
trx = decltype(trx)();
transfer_operation t;
t.from = MUSE_INIT_MINER_NAME;
t.to = "alice";
t.amount = asset(500,MUSE_SYMBOL);
trx.operations.push_back(t);
trx.set_expiration( db1.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key(), db1.get_chain_id() );
PUSH_TX( db1, trx, skip_sigs );
MUSE_CHECK_THROW(PUSH_TX( db1, trx, skip_sigs ), fc::exception);
auto b = db1.generate_block( db1.get_slot_time(1), db1.get_scheduled_witness( 1 ), init_account_priv_key(), skip_sigs );
PUSH_BLOCK( db2, b, skip_sigs );
MUSE_CHECK_THROW(PUSH_TX( db1, trx, skip_sigs ), fc::exception);
MUSE_CHECK_THROW(PUSH_TX( db2, trx, skip_sigs ), fc::exception);
BOOST_CHECK_EQUAL(db1.get_balance( "alice", MUSE_SYMBOL ).amount.value, 500);
BOOST_CHECK_EQUAL(db2.get_balance( "alice", MUSE_SYMBOL ).amount.value, 500);
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( tapos )
{
try {
fc::temp_directory dir1( graphene::utilities::temp_directory_path() );
genesis_state_type genesis;
genesis.init_supply = INITIAL_TEST_SUPPLY;
database db1;
db1.open(dir1.path(), genesis, "TEST" );
init_witness_keys( db1 );
auto b = db1.generate_block( db1.get_slot_time(1), db1.get_scheduled_witness( 1 ), init_account_priv_key(), database::skip_nothing);
BOOST_TEST_MESSAGE( "Creating a transaction with reference block" );
idump((db1.head_block_id()));
signed_transaction trx;
//This transaction must be in the next block after its reference, or it is invalid.
trx.set_reference_block( db1.head_block_id() );
account_create_operation cop;
cop.fee = asset(50, MUSE_SYMBOL);
cop.new_account_name = "alice";
cop.creator = MUSE_INIT_MINER_NAME;
cop.owner = authority(1, init_account_pub_key(), 1);
cop.active = cop.owner;
trx.operations.push_back(cop);
trx.set_expiration( db1.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
trx.sign( init_account_priv_key(), db1.get_chain_id() );
BOOST_TEST_MESSAGE( "Pushing Pending Transaction" );
idump((trx));
db1.push_transaction(trx);
BOOST_TEST_MESSAGE( "Generating a block" );
b = db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
trx.clear();
transfer_operation t;
t.from = MUSE_INIT_MINER_NAME;
t.to = "alice";
t.amount = asset(50,MUSE_SYMBOL);
trx.operations.push_back(t);
trx.set_expiration( db1.head_block_time() + fc::seconds(2) );
trx.sign( init_account_priv_key(), db1.get_chain_id() );
idump((trx)(db1.head_block_time()));
b = db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
idump((b));
b = db1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key(), database::skip_nothing);
trx.signatures.clear();
trx.sign( init_account_priv_key(), db1.get_chain_id() );
BOOST_REQUIRE_THROW( db1.push_transaction(trx, 0/*database::skip_transaction_signatures | database::skip_authority_check*/), fc::exception );
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_FIXTURE_TEST_CASE( optional_tapos, clean_database_fixture )
{
try
{
idump((db.get_account("initminer")));
ACTORS( (alice)(bob) );
generate_block();
BOOST_TEST_MESSAGE( "Create transaction" );
transfer( MUSE_INIT_MINER_NAME, "alice", 1000000 );
transfer_operation op;
op.from = "alice";
op.to = "bob";
op.amount = asset(1000,MUSE_SYMBOL);
signed_transaction tx;
tx.operations.push_back( op );
BOOST_TEST_MESSAGE( "ref_block_num=0, ref_block_prefix=0" );
tx.ref_block_num = 0;
tx.ref_block_prefix = 0;
tx.signatures.clear();
tx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
tx.sign( alice_private_key, db.get_chain_id() );
PUSH_TX( db, tx );
BOOST_TEST_MESSAGE( "proper ref_block_num, ref_block_prefix" );
tx.signatures.clear();
tx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
tx.sign( alice_private_key, db.get_chain_id() );
PUSH_TX( db, tx, database::skip_transaction_dupe_check );
BOOST_TEST_MESSAGE( "ref_block_num=0, ref_block_prefix=12345678" );
tx.ref_block_num = 0;
tx.ref_block_prefix = 0x12345678;
tx.signatures.clear();
tx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
tx.sign( alice_private_key, db.get_chain_id() );
MUSE_REQUIRE_THROW( PUSH_TX( db, tx, database::skip_transaction_dupe_check ), fc::exception );
BOOST_TEST_MESSAGE( "ref_block_num=1, ref_block_prefix=12345678" );
tx.ref_block_num = 1;
tx.ref_block_prefix = 0x12345678;
tx.signatures.clear();
tx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
tx.sign( alice_private_key, db.get_chain_id() );
MUSE_REQUIRE_THROW( PUSH_TX( db, tx, database::skip_transaction_dupe_check ), fc::exception );
BOOST_TEST_MESSAGE( "ref_block_num=9999, ref_block_prefix=12345678" );
tx.ref_block_num = 9999;
tx.ref_block_prefix = 0x12345678;
tx.signatures.clear();
tx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
tx.sign( alice_private_key, db.get_chain_id() );
MUSE_REQUIRE_THROW( PUSH_TX( db, tx, database::skip_transaction_dupe_check ), fc::exception );
}
catch (fc::exception& e)
{
edump((e.to_detail_string()));
throw;
}
}
BOOST_FIXTURE_TEST_CASE( double_sign_check, clean_database_fixture )
{ try {
generate_block();
ACTOR(bob);
share_type amount = 1000;
transfer_operation t;
t.from = MUSE_INIT_MINER_NAME;
t.to = "bob";
t.amount = asset(amount,MUSE_SYMBOL);
trx.operations.push_back(t);
trx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
trx.validate();
db.push_transaction(trx, ~0);
trx.operations.clear();
account_witness_vote_operation v;
v.account = "bob";
v.witness = MUSE_INIT_MINER_NAME;
trx.operations.push_back(v);
trx.validate();
BOOST_TEST_MESSAGE( "Verify that not-signing causes an exception" );
MUSE_REQUIRE_THROW( db.push_transaction(trx, 0), fc::exception );
BOOST_TEST_MESSAGE( "Verify that double-signing causes an exception" );
trx.sign( bob_private_key, db.get_chain_id() );
trx.sign( bob_private_key, db.get_chain_id() );
MUSE_REQUIRE_THROW( db.push_transaction(trx, 0), tx_duplicate_sig );
BOOST_TEST_MESSAGE( "Verify that signing with an extra, unused key fails" );
trx.signatures.pop_back();
trx.sign( generate_private_key("bogus" ), db.get_chain_id() );
MUSE_REQUIRE_THROW( db.push_transaction(trx, 0), tx_irrelevant_sig );
BOOST_TEST_MESSAGE( "Verify that signing once with the proper key passes" );
trx.signatures.pop_back();
db.push_transaction(trx, 0);
} FC_LOG_AND_RETHROW() }
BOOST_FIXTURE_TEST_CASE( pop_block_twice, clean_database_fixture )
{
try
{
uint32_t skip_flags = (
database::skip_witness_signature
| database::skip_transaction_signatures
| database::skip_authority_check
);
// Sam is the creator of accounts
private_key_type sam_key = generate_private_key( "sam" );
account_object sam_account_object = account_create( "sam", sam_key.get_public_key() );
//Get a sane head block time
generate_block( skip_flags );
transaction tx;
signed_transaction ptx;
// transfer from committee account to Sam account
transfer( MUSE_INIT_MINER_NAME, "sam", 100000 );
generate_block(skip_flags);
account_create( "alice", generate_private_key( "alice" ).get_public_key() );
generate_block(skip_flags);
account_create( "bob", generate_private_key( "bob" ).get_public_key() );
generate_block(skip_flags);
db.pop_block();
db.pop_block();
} catch(const fc::exception& e) {
edump( (e.to_detail_string()) );
throw;
}
}
BOOST_FIXTURE_TEST_CASE( rsf_missed_blocks, clean_database_fixture )
{
try
{
generate_block();
auto rsf = [&]() -> string
{
fc::uint128 rsf = db.get_dynamic_global_properties().recent_slots_filled;
string result = "";
result.reserve(128);
for( int i=0; i<128; i++ )
{
result += ((rsf.lo & 1) == 0) ? '0' : '1';
rsf >>= 1;
}
return result;
};
auto pct = []( uint32_t x ) -> uint32_t
{
return uint64_t( MUSE_100_PERCENT ) * x / 128;
};
BOOST_TEST_MESSAGE("checking initial participation rate" );
BOOST_CHECK_EQUAL( rsf(),
"1111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), MUSE_100_PERCENT );
BOOST_TEST_MESSAGE("Generating a block skipping 1" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 1 );
BOOST_CHECK_EQUAL( rsf(),
"0111111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(127) );
BOOST_TEST_MESSAGE("Generating a block skipping 1" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 1 );
BOOST_CHECK_EQUAL( rsf(),
"0101111111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(126) );
BOOST_TEST_MESSAGE("Generating a block skipping 2" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 2 );
BOOST_CHECK_EQUAL( rsf(),
"0010101111111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(124) );
BOOST_TEST_MESSAGE("Generating a block for skipping 3" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 3 );
BOOST_CHECK_EQUAL( rsf(),
"0001001010111111111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(121) );
BOOST_TEST_MESSAGE("Generating a block skipping 5" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 5 );
BOOST_CHECK_EQUAL( rsf(),
"0000010001001010111111111111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(116) );
BOOST_TEST_MESSAGE("Generating a block skipping 8" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 8 );
BOOST_CHECK_EQUAL( rsf(),
"0000000010000010001001010111111111111111111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(108) );
BOOST_TEST_MESSAGE("Generating a block skipping 13" );
generate_block( ~database::skip_fork_db, init_account_priv_key, 13 );
BOOST_CHECK_EQUAL( rsf(),
"0000000000000100000000100000100010010101111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(95) );
BOOST_TEST_MESSAGE("Generating a block skipping none" );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1000000000000010000000010000010001001010111111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(95) );
BOOST_TEST_MESSAGE("Generating a block" );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1100000000000001000000001000001000100101011111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(95) );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1110000000000000100000000100000100010010101111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(95) );
generate_block();
BOOST_CHECK_EQUAL( rsf(),
"1111000000000000010000000010000010001001010111111111111111111111"
"1111111111111111111111111111111111111111111111111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(95) );
generate_block( ~database::skip_fork_db, init_account_priv_key, 64 );
BOOST_CHECK_EQUAL( rsf(),
"0000000000000000000000000000000000000000000000000000000000000000"
"1111100000000000001000000001000001000100101011111111111111111111"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(31) );
generate_block( ~database::skip_fork_db, init_account_priv_key, 32 );
BOOST_CHECK_EQUAL( rsf(),
"0000000000000000000000000000000010000000000000000000000000000000"
"0000000000000000000000000000000001111100000000000001000000001000"
);
BOOST_CHECK_EQUAL( db.witness_participation_rate(), pct(8) );
}
FC_LOG_AND_RETHROW()
}
BOOST_FIXTURE_TEST_CASE( skip_block, clean_database_fixture )
{
try
{
BOOST_TEST_MESSAGE( "Skipping blocks through db" );
BOOST_REQUIRE( db.head_block_num() == 1 );
int init_block_num = db.head_block_num();
int miss_blocks = fc::minutes( 1 ).to_seconds() / MUSE_BLOCK_INTERVAL;
auto witness = db.get_scheduled_witness( miss_blocks );
auto block_time = db.get_slot_time( miss_blocks );
db.generate_block( block_time , witness, init_account_priv_key, 0 );
BOOST_CHECK_EQUAL( db.head_block_num(), init_block_num + 1 );
BOOST_CHECK( db.head_block_time() == block_time );
BOOST_TEST_MESSAGE( "Generating a block through fixture" );
auto b = generate_block();
BOOST_CHECK_EQUAL( db.head_block_num(), init_block_num + 2 );
BOOST_CHECK( db.head_block_time() == block_time + MUSE_BLOCK_INTERVAL );
}
FC_LOG_AND_RETHROW();
}
BOOST_FIXTURE_TEST_CASE( hardfork_test, database_fixture )
{
try
{
initialize_clean( 0 );
generate_blocks( 2 * MUSE_MAX_MINERS );
BOOST_TEST_MESSAGE( "Check hardfork not applied at genesis" );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_TEST_MESSAGE( "Generate blocks up to the hardfork time and check hardfork still not applied" );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_1_TIME - MUSE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_TEST_MESSAGE( "Generate a block and check hardfork is applied" );
generate_block();
string op_msg = "Test: Hardfork applied";
auto itr = db.get_index_type< account_history_index >().indices().get< by_id >().end();
itr--;
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( get_last_operations( 1 )[0].get< custom_operation >().data == vector< char >( op_msg.begin(), op_msg.end() ) );
BOOST_REQUIRE( itr->op(db).timestamp == db.head_block_time() );
BOOST_TEST_MESSAGE( "Testing hardfork is only applied once" );
generate_block();
itr = db.get_index_type< account_history_index >().indices().get< by_id >().end();
itr--;
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( get_last_operations( 1 )[0].get< custom_operation >().data == vector< char >( op_msg.begin(), op_msg.end() ) );
BOOST_REQUIRE( itr->op(db).timestamp == db.head_block_time() - MUSE_BLOCK_INTERVAL );
generate_blocks( MUSE_MAX_MINERS );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_2_TIME - MUSE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
generate_block();
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
generate_blocks( 2*MUSE_MAX_MINERS );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_3_TIME - MUSE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
generate_block();
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
generate_blocks( 2*MUSE_MAX_MINERS );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_4_TIME - MUSE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_4 ) );
generate_block();
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_5 ) );
generate_blocks( 2*MUSE_MAX_MINERS );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_5_TIME - MUSE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_5 ) );
generate_block();
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_5 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_6 ) );
generate_blocks( 2*MUSE_MAX_MINERS );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_6_TIME - MUSE_BLOCK_INTERVAL ), true );
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_5 ) );
BOOST_REQUIRE( !db.has_hardfork( MUSE_HARDFORK_0_6 ) );
generate_block();
BOOST_REQUIRE( db.has_hardfork( 0 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_1 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_2 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_3 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_4 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_5 ) );
BOOST_REQUIRE( db.has_hardfork( MUSE_HARDFORK_0_6 ) );
}
FC_LOG_AND_RETHROW()
}
BOOST_FIXTURE_TEST_CASE( skip_witness_on_empty_key, database_fixture )
{ try {
initialize_clean(2);
const auto skip_sigs = database::skip_transaction_signatures | database::skip_authority_check;
generate_blocks( 2 * MUSE_MAX_MINERS );
const witness_schedule_object& wso = witness_schedule_id_type()(db);
std::set<string> witnesses( wso.current_shuffled_witnesses.begin(), wso.current_shuffled_witnesses.end() );
BOOST_CHECK_EQUAL( MUSE_MAX_MINERS, witnesses.size() );
{
witness_update_operation wup;
wup.block_signing_key = public_key_type();
wup.url = "http://peertracks.com";
wup.owner = MUSE_INIT_MINER_NAME;
wup.fee = asset( MUSE_MIN_ACCOUNT_CREATION_FEE, MUSE_SYMBOL );
trx.operations.push_back( wup );
trx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
PUSH_TX( db, trx, skip_sigs );
}
generate_blocks( 2 * MUSE_MAX_MINERS );
witnesses.clear();
witnesses.insert( wso.current_shuffled_witnesses.begin(), wso.current_shuffled_witnesses.end() );
BOOST_CHECK_EQUAL( MUSE_MAX_MINERS, witnesses.size() );
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_3_TIME ), true );
generate_blocks( 2 * MUSE_MAX_MINERS );
std::set<string> fewer_witnesses( wso.current_shuffled_witnesses.begin(), wso.current_shuffled_witnesses.end() );
BOOST_CHECK_EQUAL( MUSE_MAX_MINERS - 1, fewer_witnesses.size() );
for( const string& w : fewer_witnesses )
witnesses.erase( w );
BOOST_CHECK_EQUAL( 1, witnesses.size() );
BOOST_CHECK_EQUAL( 1, witnesses.count( MUSE_INIT_MINER_NAME ) );
} FC_LOG_AND_RETHROW() }
BOOST_FIXTURE_TEST_CASE( expire_proposals_on_hf3, database_fixture )
{ try {
initialize_clean(2);
ACTORS( (alice)(bob) );
const asset_object& core = asset_id_type()(db);
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_3_TIME - 5 * 60 ) );
transfer_operation transfer_op;
transfer_op.from = "alice";
transfer_op.to = "bob";
transfer_op.amount = core.amount(100);
proposal_create_operation op;
op.proposed_ops.emplace_back( transfer_op );
op.expiration_time = db.head_block_time() + fc::minutes(1);
trx.operations.push_back(op);
trx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
PUSH_TX( db, trx );
trx.clear();
op.proposed_ops.clear();
transfer_op.amount = core.amount(50);
op.proposed_ops.emplace_back( transfer_op );
op.expiration_time = db.head_block_time() + fc::minutes(2);
trx.operations.push_back(op);
PUSH_TX( db, trx );
trx.clear();
const auto& pidx = db.get_index_type<proposal_index>().indices().get<by_id>();
BOOST_CHECK_EQUAL( 2, pidx.size() );
const proposal_id_type pid1 = pidx.begin()->id;
const proposal_id_type pid2 = std::next( pidx.begin() )->id;
proposal_update_operation uop;
uop.proposal = pid1;
uop.active_approvals_to_add.insert("alice");
trx.operations.push_back(uop);
sign( trx, alice_private_key );
PUSH_TX( db, trx );
trx.clear();
// Proposals failed to execute
BOOST_CHECK_EQUAL( 2, pidx.size() );
fund( "alice" );
const auto original_balance = get_balance("alice").amount.value;
generate_block();
// Proposals failed to execute
BOOST_CHECK_EQUAL( 2, pidx.size() );
BOOST_CHECK_EQUAL( original_balance, get_balance("alice").amount.value );
const proposal_object& proposal1 = pid1(db);
BOOST_CHECK_EQUAL(proposal1.required_active_approvals.size(), 1);
BOOST_CHECK_EQUAL(proposal1.available_active_approvals.size(), 1);
BOOST_CHECK_EQUAL(proposal1.required_owner_approvals.size(), 0);
BOOST_CHECK_EQUAL(proposal1.available_owner_approvals.size(), 0);
BOOST_CHECK_EQUAL("alice", *proposal1.required_active_approvals.begin());
const proposal_object& proposal2 = pid2(db);
BOOST_CHECK_EQUAL(proposal2.required_active_approvals.size(), 1);
BOOST_CHECK_EQUAL(proposal2.available_active_approvals.size(), 0);
BOOST_CHECK_EQUAL(proposal2.required_owner_approvals.size(), 0);
BOOST_CHECK_EQUAL(proposal2.available_owner_approvals.size(), 0);
BOOST_CHECK_EQUAL("alice", *proposal2.required_active_approvals.begin());
generate_blocks( fc::time_point_sec( MUSE_HARDFORK_0_3_TIME ) );
generate_blocks( 2*MUSE_MAX_MINERS );
// Proposals were removed
BOOST_CHECK_EQUAL( 0, pidx.size() );
// ...and did not execute
BOOST_CHECK_EQUAL( original_balance, get_balance("alice").amount.value );
} FC_LOG_AND_RETHROW() }
static void generate_1_day_of_misses( database& db, const string& witness_to_skip )
{
for( int blocks = 0; blocks < MUSE_BLOCKS_PER_DAY + 2 * MUSE_MAX_MINERS; blocks++ )
{
int next = 0;
string next_witness;
do
{
next_witness = db.get_scheduled_witness( ++next );
} while( next_witness == witness_to_skip );
db.generate_block(db.get_slot_time( next ), next_witness, init_account_priv_key(), 0);
}
}
BOOST_FIXTURE_TEST_CASE( clear_witness_key, clean_database_fixture )
{ try {
generate_blocks( 2 * MUSE_MAX_MINERS );
auto witness = db.get_witness( MUSE_INIT_MINER_NAME );
BOOST_CHECK_NE( std::string(public_key_type()), std::string(witness.signing_key) );
generate_1_day_of_misses( db, MUSE_INIT_MINER_NAME );
witness = db.get_witness( MUSE_INIT_MINER_NAME );
BOOST_CHECK_GT( witness.total_missed, MUSE_BLOCKS_PER_DAY / MUSE_MAX_MINERS - 5 );
BOOST_CHECK_LT( witness.last_confirmed_block_num, db.head_block_num() - MUSE_BLOCKS_PER_DAY );
BOOST_CHECK_EQUAL( std::string(public_key_type()), std::string(witness.signing_key) );
} FC_LOG_AND_RETHROW() }
BOOST_FIXTURE_TEST_CASE( generate_block_size, clean_database_fixture )
{
try
{
generate_block();
db.modify( db.get_dynamic_global_properties(), []( dynamic_global_property_object& gpo )
{
gpo.maximum_block_size = MUSE_MIN_BLOCK_SIZE_LIMIT;
});
signed_transaction tx;
tx.set_expiration( db.head_block_time() + MUSE_MAX_TIME_UNTIL_EXPIRATION );
transfer_operation op;
op.from = MUSE_INIT_MINER_NAME;
op.to = MUSE_TEMP_ACCOUNT;
op.amount = asset( 1000, MUSE_SYMBOL );
// tx without ops is 78 bytes (77 + 1 for length of ops vector))
// op is 26 bytes (25 for op + 1 byte static variant tag)
// total is 65182
std::vector<char> raw_op = fc::raw::pack_to_vector( op, 255 );
BOOST_CHECK_EQUAL( 25, raw_op.size() );
BOOST_CHECK_EQUAL( raw_op.size(), fc::raw::pack_size( op ) );
for( size_t i = 0; i < 2507; i++ )
{
tx.operations.push_back( op );
}
tx.sign( init_account_priv_key, db.get_chain_id() );
db.push_transaction( tx, 0 );
std::vector<char> raw_tx = fc::raw::pack_to_vector( tx, 255 );
BOOST_CHECK_EQUAL( 65182+77+2, raw_tx.size() ); // 2 bytes for encoding # of ops
BOOST_CHECK_EQUAL( raw_tx.size(), fc::raw::pack_size( tx ) );
// Original generation logic only allowed 115 bytes for the header
BOOST_CHECK_EQUAL( 115, fc::raw::pack_size( signed_block_header() ) + 4 );
// We are targetting a size (minus header) of 65420 which creates a block of "size" 65535
// This block will actually be larger because the header estimates is too small
// Second transaction
// We need a 80 (65420 - (65182+77+2) - (77+1) - 1) byte op. We need a 55 character memo (1 byte for length); 54 = 80 - 25 (old op) - 1 (tag)
op.memo = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123";
raw_op = fc::raw::pack_to_vector( op, 255 );
BOOST_CHECK_EQUAL( 80, raw_op.size() );
BOOST_CHECK_EQUAL( raw_op.size(), fc::raw::pack_size( op ) );
tx.clear();
tx.operations.push_back( op );
sign( tx, init_account_priv_key );
db.push_transaction( tx, 0 );
raw_tx = fc::raw::pack_to_vector( tx, 255 );
BOOST_CHECK_EQUAL( 78+80+1, raw_tx.size() );
BOOST_CHECK_EQUAL( raw_tx.size(), fc::raw::pack_size( tx ) );
generate_block();
auto head_block = db.fetch_block_by_number( db.head_block_num() );
BOOST_CHECK_GE( 65535, fc::raw::pack_size( head_block ) );
// The last transfer should have been delayed due to size
BOOST_CHECK_EQUAL( 1, head_block->transactions.size() );
}
FC_LOG_AND_RETHROW()
}
BOOST_AUTO_TEST_SUITE_END()
| 38.843057 | 158 | 0.673253 | [
"vector"
] |
4931fad7cbdfbf9fd133995eeea320326a4ad036 | 464 | hpp | C++ | libraries/manifest/include/steemit/manifest/plugins.hpp | sergeyrizan/botchain-bot | 5e8081c79070ac43661c21fc8a86f34afade6b17 | [
"Unlicense"
] | null | null | null | libraries/manifest/include/steemit/manifest/plugins.hpp | sergeyrizan/botchain-bot | 5e8081c79070ac43661c21fc8a86f34afade6b17 | [
"Unlicense"
] | null | null | null | libraries/manifest/include/steemit/manifest/plugins.hpp | sergeyrizan/botchain-bot | 5e8081c79070ac43661c21fc8a86f34afade6b17 | [
"Unlicense"
] | null | null | null |
#pragma once
#include <memory>
#include <string>
#include <vector>
namespace steemit {
namespace app {
class abstract_plugin;
class application;
}
}
namespace steemit {
namespace plugin {
void initialize_plugin_factories();
std::shared_ptr<steemit::app::abstract_plugin> create_plugin(const std::string &name, steemit::app::application *app);
std::vector<std::string> get_available_plugins();
}
}
| 16 | 126 | 0.661638 | [
"vector"
] |
4936b072ecbb3aaa74adaf87089834126cf14082 | 5,910 | cpp | C++ | Doom/src/Doom/Components/Transform.cpp | Shturm0weak/OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 126 | 2020-10-20T21:39:53.000Z | 2022-01-25T14:43:44.000Z | Doom/src/Doom/Components/Transform.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 2 | 2021-01-07T17:29:19.000Z | 2021-08-14T14:04:28.000Z | Doom/src/Doom/Components/Transform.cpp | Shturm0weak/2D_OpenGL_Engine | 6e6570f8dd9000724274942fff5a100f0998b780 | [
"MIT"
] | 16 | 2021-01-09T09:08:40.000Z | 2022-01-25T14:43:46.000Z | #include "../pch.h"
#include "Transform.h"
#include "../Core/EventSystem.h"
#include "../Objects/GameObject.h"
#include "../Core/ViewPort.h"
#include "../Core/Timer.h"
#include "../Core/Utils.h"
#define GLM_ENABLE_EXPERIMENTAL
#include "glm/gtx/quaternion.hpp"
#include "Rays/Ray3D.h"
using namespace Doom;
Doom::Transform::Transform(const Transform& rhs)
{
Copy(rhs);
}
Transform::Transform(GameObject* owner)
{
m_OwnerOfCom = owner;
m_Type = Utils::GetComponentTypeName<Transform>();
}
//oid Transform::RealVertexPositions()
//
// glm::vec3 position = Utils::GetPosition(m_PosMat4);
// if (m_PrevPosition.x + m_PrevPosition.y + m_PrevPosition.z != position.x + position.y + position.z) {
// sr = m_Owner->m_ComponentManager.GetComponent<SpriteRenderer>();
// if (sr == NULL || sr == nullptr)
// return;
// m_PrevPosition = position;
// ((SpriteRenderer*)sr)->Update(position);
// }
//
void Doom::Transform::Copy(const Transform& rhs)
{
m_PosMat4 = rhs.m_PosMat4;
m_ViewMat4 = rhs.m_ViewMat4;
m_ScaleMat4 = rhs.m_ScaleMat4;
}
void Doom::Transform::operator=(const Transform& rhs)
{
Copy(rhs);
}
Component* Doom::Transform::Create()
{
return nullptr;
}
glm::vec3 Doom::Transform::GetRotation()
{
return m_Rotation;
}
glm::vec3 Doom::Transform::GetPosition()
{
return std::move(Utils::GetPosition(m_PosMat4));
}
glm::vec3 Doom::Transform::GetScale()
{
return std::move(Utils::GetScale(m_ScaleMat4));
}
glm::mat4 Doom::Transform::GetTransform()
{
return std::move(m_PosMat4 * m_ViewMat4 * m_ScaleMat4);
}
void Transform::Move(float x,float y,float z)
{
Move(glm::vec3(x, y, z));
}
void Transform::RotateOnce(float x, float y, float z,bool isRad)
{
RotateOnce(glm::vec3(x, y, z), isRad);
}
void Transform::Rotate(float x, float y, float z, bool isRad)
{
Rotate(glm::vec3(x, y, z), isRad);
}
void Transform::Scale(float x, float y,float z)
{
Scale(glm::vec3(x, y, z));
}
void Transform::Translate(float x, float y,float z)
{
Translate(glm::vec3(x, y, z));
}
void Doom::Transform::RotateOnce(glm::vec3 dir, glm::vec3 axis)
{
glm::vec3 position = Utils::GetPosition(m_PosMat4);
glm::vec3 b = glm::vec3(0, 1, 0);
float angleRad = acosf((dir.x * b.x + dir.y * b.y + dir.z * b.z) / ((sqrtf(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z) * (sqrtf(b.x * b.x + b.y * b.y + b.z * b.z)))));
if (ViewPort::GetInstance().GetMousePositionToWorldSpace().x > position.x)
angleRad = -angleRad;
axis *= angleRad;
m_ViewMat4 = glm::toMat4(glm::quat(axis));
//m_OwnerOfCom->GetComponent<RectangleCollider2D>()->CalculateRealVerPos();
EventSystem::GetInstance().SendEvent(EventType::ONROTATE, (Listener*)m_OwnerOfCom->m_Listener);
EventSystem::GetInstance().SendEvent(EventType::ONROTATE, (Listener*)m_OwnerOfCom->GetComponent<RectangleCollider2D>());
}
void Transform::Move(glm::vec3 vdir)
{
glm::vec3 position = Utils::GetPosition(m_PosMat4);
position.x += vdir.x * DeltaTime::GetDeltaTime();
position.y += vdir.y * DeltaTime::GetDeltaTime();
position.z += vdir.z * DeltaTime::GetDeltaTime();
m_PosMat4 = glm::translate(glm::mat4(1.0f), position);
//m_OwnerOfCom->GetComponent<RectangleCollider2D>()->CalculateRealVerPos();
if (m_OwnerOfCom->m_Enable)
{
unsigned int size = m_OwnerOfCom->GetChilds().size();
for (unsigned int i = 0; i < size; i++)
{
GameObject* go = static_cast<GameObject*>(m_OwnerOfCom->GetChilds()[i]);
if (go->m_Enable == true)
go->m_ComponentManager.GetComponent<Transform>()->Move(vdir);
}
}
EventSystem::GetInstance().SendEvent(EventType::ONMOVE, (Listener*)m_OwnerOfCom->m_Listener);
EventSystem::GetInstance().SendEvent(EventType::ONMOVE, (Listener*)m_OwnerOfCom->GetComponent<RectangleCollider2D>());
}
void Transform::RotateOnce(glm::vec3 vangles, bool isRad)
{
if (isRad) m_Rotation = vangles;
else m_Rotation = glm::radians(vangles);
m_ViewMat4 = glm::toMat4(glm::quat(m_Rotation));
//m_OwnerOfCom->GetComponent<RectangleCollider2D>()->CalculateRealVerPos();
EventSystem::GetInstance().SendEvent(EventType::ONROTATE, (Listener*)m_OwnerOfCom->m_Listener);
EventSystem::GetInstance().SendEvent(EventType::ONROTATE, (Listener*)m_OwnerOfCom->GetComponent<RectangleCollider2D>());
}
void Transform::Rotate(glm::vec3 vangles, bool isRad)
{
if (isRad) m_Rotation = vangles;
else m_Rotation = glm::radians(vangles);
m_ViewMat4 = glm::toMat4(glm::quat(m_Rotation));
//m_OwnerOfCom->GetComponent<RectangleCollider2D>()->CalculateRealVerPos();
EventSystem::GetInstance().SendEvent(EventType::ONROTATE, (Listener*)m_OwnerOfCom->m_Listener);
EventSystem::GetInstance().SendEvent(EventType::ONROTATE, (Listener*)m_OwnerOfCom->GetComponent<RectangleCollider2D>());
}
void Transform::Scale(glm::vec3 vscale)
{
m_ScaleMat4 = glm::scale(glm::mat4(1.f), vscale);
//m_OwnerOfCom->GetComponent<RectangleCollider2D>()->CalculateRealVerPos();
EventSystem::GetInstance().SendEvent(EventType::ONSCALE, (Listener*)m_OwnerOfCom->m_Listener);
EventSystem::GetInstance().SendEvent(EventType::ONSCALE, (Listener*)m_OwnerOfCom->GetComponent<RectangleCollider2D>());
}
void Transform::Translate(glm::vec3 vpos)
{
glm::vec3 position = Utils::GetPosition(m_PosMat4);
if (m_OwnerOfCom->m_Enable)
{
uint32_t size = m_OwnerOfCom->GetChilds().size();
for (uint32_t i = 0; i < size; i++)
{
GameObject* go = static_cast<GameObject*>(m_OwnerOfCom->GetChilds()[i]);
if (go->m_Enable == true) {
glm::vec3 _pos = go->GetPosition() - m_OwnerOfCom->GetPosition();
go->m_ComponentManager.GetComponent<Transform>()->Translate(_pos + vpos);
}
}
}
m_PosMat4 = translate(glm::mat4(1.f), vpos);
//m_OwnerOfCom->GetComponent<RectangleCollider2D>()->CalculateRealVerPos();
EventSystem::GetInstance().SendEvent(EventType::ONTRANSLATE, (Listener*)m_OwnerOfCom->m_Listener);
EventSystem::GetInstance().SendEvent(EventType::ONTRANSLATE, (Listener*)m_OwnerOfCom->GetComponent<RectangleCollider2D>());
} | 30.307692 | 171 | 0.715905 | [
"transform"
] |
494152fc03c688fa39a59e7a502b5abc0170c6ee | 14,472 | cpp | C++ | cudaaligner/src/aligner_global_myers_banded.cpp | ohadmo/GenomeWorks | b4b8bf76ea2ce44452d3a1107e66d47968414adb | [
"Apache-2.0"
] | 1 | 2020-08-07T18:18:58.000Z | 2020-08-07T18:18:58.000Z | cudaaligner/src/aligner_global_myers_banded.cpp | ohadmo/GenomeWorks | b4b8bf76ea2ce44452d3a1107e66d47968414adb | [
"Apache-2.0"
] | null | null | null | cudaaligner/src/aligner_global_myers_banded.cpp | ohadmo/GenomeWorks | b4b8bf76ea2ce44452d3a1107e66d47968414adb | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2020 NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "aligner_global_myers_banded.hpp"
#include "myers_gpu.cuh"
#include "batched_device_matrices.cuh"
#include "alignment_impl.hpp"
#include <claraparabricks/genomeworks/utils/signed_integer_utils.hpp>
#include <claraparabricks/genomeworks/utils/cudautils.hpp>
#include <claraparabricks/genomeworks/utils/genomeutils.hpp>
#include <claraparabricks/genomeworks/utils/mathutils.hpp>
#include <claraparabricks/genomeworks/utils/pinned_host_vector.hpp>
namespace claraparabricks
{
namespace genomeworks
{
namespace cudaaligner
{
namespace
{
constexpr int32_t n_alignments_initial_parameter = 1000; // for initial allocation - buffers will grow automatically if needed.
using myers::WordType;
constexpr int32_t word_size = sizeof(myers::WordType) * CHAR_BIT;
int64_t compute_matrix_size_for_alignment(const int32_t query_size, const int32_t target_size, const int32_t max_bandwidth)
{
assert(max_bandwidth >= 0);
assert(target_size >= 0);
const int32_t p = (max_bandwidth + 1) / 2;
const int32_t bandwidth = std::min(1 + 2 * p, query_size);
const int64_t n_words_band = ceiling_divide(bandwidth, word_size);
return n_words_band * (static_cast<int64_t>(target_size) + 1);
}
struct memory_distribution
{
int64_t sequence_memory;
int64_t results_memory;
int64_t query_patterns_memory;
int64_t pmvs_matrix_memory;
int64_t score_matrix_memory;
int64_t remainder;
};
memory_distribution split_available_memory(const int64_t max_device_memory, const int32_t max_bandwidth)
{
assert(max_device_memory >= 0);
assert(max_bandwidth >= 0);
// Memory requirements per alignment per base pair
const float mem_req_sequence = sizeof(char);
const float mem_req_results = 2 * sizeof(char);
const float mem_req_query_patterns = 4.f / word_size;
const float mem_req_pmvs_matrix = (sizeof(WordType) * static_cast<float>(max_bandwidth)) / word_size;
const float mem_req_score_matrix = (sizeof(int32_t) * static_cast<float>(max_bandwidth)) / word_size;
const float mem_req_total_per_bp = 2 * mem_req_sequence + mem_req_results + mem_req_query_patterns + 2 * mem_req_pmvs_matrix + mem_req_score_matrix;
const float fmax_device_memory = static_cast<float>(max_device_memory) * 0.95; // reserve 5% for misc
memory_distribution r;
r.sequence_memory = static_cast<int64_t>(fmax_device_memory / mem_req_total_per_bp * mem_req_sequence);
r.results_memory = static_cast<int64_t>(fmax_device_memory / mem_req_total_per_bp * mem_req_results);
r.query_patterns_memory = static_cast<int64_t>(fmax_device_memory / mem_req_total_per_bp * mem_req_query_patterns);
r.pmvs_matrix_memory = static_cast<int64_t>(fmax_device_memory / mem_req_total_per_bp * mem_req_pmvs_matrix);
r.score_matrix_memory = static_cast<int64_t>(fmax_device_memory / mem_req_total_per_bp * mem_req_score_matrix);
r.remainder = max_device_memory - (2 * r.sequence_memory + r.results_memory + r.query_patterns_memory + 2 * r.pmvs_matrix_memory + r.score_matrix_memory);
return r;
}
} // namespace
struct AlignerGlobalMyersBanded::InternalData
{
InternalData(const memory_distribution mem, const int32_t n_alignments_initial, const DefaultDeviceAllocator& allocator, cudaStream_t stream)
: seq_h(2 * mem.sequence_memory / sizeof(char))
, seq_starts_h()
, results_h(mem.results_memory / sizeof(char))
, result_lengths_h()
, result_starts_h()
, seq_d(2 * mem.sequence_memory / sizeof(char), allocator, stream)
, seq_starts_d(2 * n_alignments_initial + 1, allocator, stream)
, results_d(mem.results_memory / sizeof(char), allocator, stream)
, result_starts_d(n_alignments_initial + 1, allocator, stream)
, result_lengths_d(n_alignments_initial, allocator, stream)
, pvs(mem.pmvs_matrix_memory / sizeof(WordType), allocator, stream)
, mvs(mem.pmvs_matrix_memory / sizeof(WordType), allocator, stream)
, scores(mem.score_matrix_memory / sizeof(int32_t), allocator, stream)
, query_patterns(mem.query_patterns_memory / sizeof(WordType), allocator, stream)
{
seq_starts_h.reserve(2 * n_alignments_initial + 1);
result_starts_h.reserve(n_alignments_initial + 1);
result_lengths_h.reserve(n_alignments_initial);
}
pinned_host_vector<char> seq_h;
pinned_host_vector<int64_t> seq_starts_h;
pinned_host_vector<int8_t> results_h;
pinned_host_vector<int32_t> result_lengths_h;
pinned_host_vector<int64_t> result_starts_h;
device_buffer<char> seq_d;
device_buffer<int64_t> seq_starts_d;
device_buffer<int8_t> results_d;
device_buffer<int64_t> result_starts_d;
device_buffer<int32_t> result_lengths_d;
batched_device_matrices<WordType> pvs;
batched_device_matrices<WordType> mvs;
batched_device_matrices<int32_t> scores;
batched_device_matrices<WordType> query_patterns;
};
AlignerGlobalMyersBanded::AlignerGlobalMyersBanded(int64_t max_device_memory, int32_t max_bandwidth, DefaultDeviceAllocator allocator, cudaStream_t stream, int32_t device_id)
: data_()
, stream_(stream)
, device_id_(device_id)
, max_bandwidth_(max_bandwidth)
, alignments_()
{
if (max_bandwidth % (sizeof(WordType) * CHAR_BIT) == 1)
{
throw std::invalid_argument("Invalid max_bandwidth value. Please change it by +/-1.");
}
if (max_device_memory < 0)
{
max_device_memory = get_size_of_largest_free_memory_block(allocator);
}
scoped_device_switch dev(device_id);
const memory_distribution mem = split_available_memory(max_device_memory, max_bandwidth);
data_ = std::make_unique<AlignerGlobalMyersBanded::InternalData>(mem, n_alignments_initial_parameter, allocator, stream_);
data_->seq_starts_h.push_back(0);
data_->result_starts_h.push_back(0);
}
AlignerGlobalMyersBanded::~AlignerGlobalMyersBanded()
{
// Keep empty destructor to keep Workspace type incomplete in the .hpp file.
}
StatusType AlignerGlobalMyersBanded::add_alignment(const char* query, int32_t query_length, const char* target, int32_t target_length, bool reverse_complement_query, bool reverse_complement_target)
{
throw_on_negative(query_length, "query_length should not be negative");
throw_on_negative(target_length, "target_length should not be negative");
if (query == nullptr || target == nullptr)
return StatusType::generic_error;
scoped_device_switch dev(device_id_);
auto& seq_h = data_->seq_h;
auto& seq_starts_h = data_->seq_starts_h;
auto& result_starts_h = data_->result_starts_h;
batched_device_matrices<WordType>& pvs = data_->pvs;
batched_device_matrices<WordType>& mvs = data_->mvs;
batched_device_matrices<int32_t>& scores = data_->scores;
batched_device_matrices<WordType>& query_patterns = data_->query_patterns;
assert(!seq_starts_h.empty());
assert(!result_starts_h.empty());
assert(get_size(seq_h) == get_size(data_->seq_d));
assert(get_size(data_->results_h) == get_size(data_->results_d));
assert(pvs.remaining_free_matrix_elements() == scores.remaining_free_matrix_elements());
assert(mvs.remaining_free_matrix_elements() == scores.remaining_free_matrix_elements());
assert(pvs.number_of_matrices() == scores.number_of_matrices());
assert(mvs.number_of_matrices() == scores.number_of_matrices());
assert(query_patterns.number_of_matrices() == scores.number_of_matrices());
const int64_t matrix_size = compute_matrix_size_for_alignment(query_length, target_length, max_bandwidth_);
const int32_t n_words_query = ceiling_divide(query_length, word_size);
const int32_t query_pattern_size = n_words_query * 4;
if (matrix_size > scores.remaining_free_matrix_elements())
{
return StatusType::exceeded_max_alignments;
}
if (query_pattern_size > query_patterns.remaining_free_matrix_elements())
{
return StatusType::exceeded_max_alignments;
}
if (target_length + query_length > get_size<int64_t>(seq_h) - seq_starts_h.back() || target_length + query_length > get_size<int64_t>(data_->results_h) - result_starts_h.back())
{
return StatusType::exceeded_max_alignments;
}
// TODO handle reverse complements
assert(reverse_complement_query == false);
assert(reverse_complement_target == false);
assert(get_size(seq_starts_h) % 2 == 1);
const int64_t seq_start = seq_starts_h.back();
genomeutils::copy_sequence(query, query_length, seq_h.data() + seq_start, reverse_complement_query);
genomeutils::copy_sequence(target, target_length, seq_h.data() + seq_start + query_length, reverse_complement_target);
seq_starts_h.push_back(seq_start + query_length);
seq_starts_h.push_back(seq_start + query_length + target_length);
result_starts_h.push_back(result_starts_h.back() + query_length + target_length);
bool success = pvs.append_matrix(matrix_size);
success = success && mvs.append_matrix(matrix_size);
success = success && scores.append_matrix(matrix_size);
success = success && query_patterns.append_matrix(query_pattern_size);
try
{
std::shared_ptr<AlignmentImpl> alignment = std::make_shared<AlignmentImpl>(query, query_length, target, target_length);
alignment->set_alignment_type(AlignmentType::global_alignment);
alignments_.push_back(alignment);
}
catch (...)
{
success = false;
}
if (!success)
{
// This should never trigger due to the size check before the append.
this->reset();
return StatusType::generic_error;
}
return StatusType::success;
}
StatusType AlignerGlobalMyersBanded::align_all()
{
using cudautils::device_copy_n;
const auto n_alignments = get_size(alignments_);
if (n_alignments == 0)
return StatusType::success;
scoped_device_switch dev(device_id_);
data_->pvs.construct_device_matrices_async(stream_);
data_->mvs.construct_device_matrices_async(stream_);
data_->scores.construct_device_matrices_async(stream_);
data_->query_patterns.construct_device_matrices_async(stream_);
const auto& seq_h = data_->seq_h;
const auto& seq_starts_h = data_->seq_starts_h;
auto& results_h = data_->results_h;
auto& result_lengths_h = data_->result_lengths_h;
const auto& result_starts_h = data_->result_starts_h;
auto& seq_d = data_->seq_d;
auto& seq_starts_d = data_->seq_starts_d;
auto& results_d = data_->results_d;
auto& result_starts_d = data_->result_starts_d;
auto& result_lengths_d = data_->result_lengths_d;
assert(get_size(seq_starts_h) == 2 * n_alignments + 1);
assert(get_size(result_starts_h) == n_alignments + 1);
if (get_size(seq_starts_d) < 2 * n_alignments + 1)
{
seq_starts_d.clear_and_resize(2 * n_alignments + 1);
}
if (get_size(result_starts_d) < n_alignments + 1)
{
result_starts_d.clear_and_resize(n_alignments + 1);
}
if (get_size(result_lengths_d) < n_alignments)
{
result_lengths_d.clear_and_resize(n_alignments);
}
device_copy_n(seq_h.data(), seq_starts_h.back(), seq_d.data(), stream_);
device_copy_n(seq_starts_h.data(), 2 * n_alignments + 1, seq_starts_d.data(), stream_);
device_copy_n(result_starts_h.data(), n_alignments + 1, result_starts_d.data(), stream_);
myers_banded_gpu(results_d.data(), result_lengths_d.data(), result_starts_d.data(),
seq_d.data(), seq_starts_d.data(), n_alignments, max_bandwidth_,
data_->pvs, data_->mvs, data_->scores, data_->query_patterns,
stream_);
result_lengths_h.clear();
result_lengths_h.resize(n_alignments);
device_copy_n(results_d.data(), result_starts_h.back(), results_h.data(), stream_);
device_copy_n(result_lengths_d.data(), n_alignments, result_lengths_h.data(), stream_);
return StatusType::success;
}
StatusType AlignerGlobalMyersBanded::sync_alignments()
{
scoped_device_switch dev(device_id_);
GW_CU_CHECK_ERR(cudaStreamSynchronize(stream_));
const int32_t n_alignments = get_size<int32_t>(alignments_);
std::vector<AlignmentState> al_state;
for (int32_t i = 0; i < n_alignments; ++i)
{
al_state.clear();
const int8_t* r_begin = data_->results_h.data() + data_->result_starts_h[i];
const int8_t* r_end = r_begin + std::abs(data_->result_lengths_h[i]);
std::transform(r_begin, r_end, std::back_inserter(al_state), [](int8_t x) { return static_cast<AlignmentState>(x); });
std::reverse(begin(al_state), end(al_state));
if (!al_state.empty() || (alignments_[i]->get_query_sequence().empty() && alignments_[i]->get_target_sequence().empty()))
{
AlignmentImpl* alignment = dynamic_cast<AlignmentImpl*>(alignments_[i].get());
const bool is_optimal = (data_->result_lengths_h[i] >= 0);
alignment->set_alignment(al_state, is_optimal);
alignment->set_status(StatusType::success);
}
}
reset_data();
return StatusType::success;
}
void AlignerGlobalMyersBanded::reset()
{
reset_data();
alignments_.clear();
}
void AlignerGlobalMyersBanded::reset_data()
{
data_->seq_starts_h.clear();
data_->result_lengths_h.clear();
data_->result_starts_h.clear();
data_->seq_starts_h.push_back(0);
data_->result_starts_h.push_back(0);
data_->pvs.clear();
data_->mvs.clear();
data_->scores.clear();
data_->query_patterns.clear();
}
} // namespace cudaaligner
} // namespace genomeworks
} // namespace claraparabricks
| 41.230769 | 197 | 0.722844 | [
"vector",
"transform"
] |
4941d38f37b2ac376c8e6a13efb35f1b5e06c2b3 | 9,066 | cpp | C++ | cpplox/memory.cpp | HUNTINGHOUND/cpplox | ae3a53a1f70daf58322c1116d9e2565fc4880469 | [
"MIT"
] | 1 | 2021-07-03T08:42:46.000Z | 2021-07-03T08:42:46.000Z | cpplox/memory.cpp | HUNTINGHOUND/cpplox | ae3a53a1f70daf58322c1116d9e2565fc4880469 | [
"MIT"
] | null | null | null | cpplox/memory.cpp | HUNTINGHOUND/cpplox | ae3a53a1f70daf58322c1116d9e2565fc4880469 | [
"MIT"
] | null | null | null | #include "memory.hpp"
#include "chunk.hpp"
#include "debug.hpp"
#include "compiler.hpp"
#include "valuearray.hpp"
#include "flags.hpp"
#ifdef NAN_BOXING
#include "nanvalue.hpp"
#else
#include "value.hpp"
#endif
void freeObjects(VM* vm) {
Obj* object = vm->objects;
while (object != nullptr) {
Obj* next = object->next;
freeObject(object, vm);
object = next;
}
}
void freeObject(Obj* object, VM* vm) {
if(DEBUG_LOG_GC) {
std::cout << (void*)object << " free type ";
}
switch (object->type) {
case OBJ_STRING:
if(DEBUG_LOG_GC) std::cout << "OBJ_STRING" << std::endl;
mem_deallocate<ObjString>((ObjString*)object, sizeof(ObjString), vm);
break;
case OBJ_FUNCTION:
if(DEBUG_LOG_GC) std::cout << "OBJ_FUNCTION" << std::endl;
mem_deallocate<ObjFunction>((ObjFunction*)object, sizeof(ObjFunction), vm);
break;
case OBJ_NATIVE:
if(DEBUG_LOG_GC) std::cout << "OBJ_NATIVE" << std::endl;
mem_deallocate<ObjNative>((ObjNative*)object, sizeof(ObjNative), vm);
break;
case OBJ_UPVALUE:
if(DEBUG_LOG_GC) std::cout << "OBJ_UPVALUE" << std::endl;
mem_deallocate<ObjUpvalue>((ObjUpvalue*)object, sizeof(ObjUpvalue), vm);
break;
case OBJ_CLOSURE:
if(DEBUG_LOG_GC) std::cout << "OBJ_CLOSURE" << std::endl;
mem_deallocate<ObjClosure>((ObjClosure*)object, sizeof(ObjClosure), vm);
break;
case OBJ_CLASS:
if(DEBUG_LOG_GC) std::cout << "OBJ_CLASS" << std::endl;
mem_deallocate<ObjClass>((ObjClass*)object, sizeof(ObjClass), vm);
break;
case OBJ_INSTANCE:
if(DEBUG_LOG_GC) std::cout << "OBJ_INSTANCE" << std::endl;
mem_deallocate<ObjInstance>((ObjInstance*)object, sizeof(ObjInstance), vm);
break;
case OBJ_BOUND_METHOD:
if(DEBUG_LOG_GC) std::cout << "OBJ_BOUND_METHOD" << std::endl;
mem_deallocate<ObjBoundMethod>((ObjBoundMethod*)object, sizeof(ObjBoundMethod), vm);
break;
case OBJ_NATIVE_CLASS_METHOD:
if(DEBUG_LOG_GC) std::cout << "OBJ_NATIVE_CLASS_METHOD" << std::endl;
mem_deallocate<ObjNativeClassMethod>(static_cast<ObjNativeClassMethod*>(object), sizeof(ObjNativeClassMethod), vm);
break;
case OBJ_NATIVE_CLASS: {
ObjNativeClass* _class = static_cast<ObjNativeClass*>(object);
switch (_class->subType) {
case NATIVE_COLLECTION:
if(DEBUG_LOG_GC) std::cout << "NATIVE_COLLECTION";
mem_deallocate<ObjCollectionClass>(static_cast<ObjCollectionClass*>(object), sizeof(ObjCollectionClass), vm);
break;
default:
if(DEBUG_LOG_GC) std::cout << "OBJ_NATIVE_CLASS...shouldn't see this";
break;
}
break;
}
case OBJ_NATIVE_INSTANCE: {
ObjNativeInstance* instance = static_cast<ObjNativeInstance*>(object);
switch (instance->subType) {
case NATIVE_COLLECTION_INSTANCE:
if(DEBUG_LOG_GC) std::cout << "NATIVE_COLLECTION_INSTANCE";
mem_deallocate<ObjCollectionInstance>(static_cast<ObjCollectionInstance*>(instance), sizeof(ObjCollectionInstance), vm);
break;
default:
// should never be reached
if(DEBUG_LOG_GC) std::cout << "OBJ_NATIVE_INSTANCE...shouldn't see this";
break;
}
break;
}
}
}
void GarbageCollector::collectGarbage(VM* vm) {
if(DEBUG_LOG_GC) {
std::cout << "-- gc begin" << std::endl;
}
size_t before = vm->bytesAllocated;
markRoots(vm);
traceReferences(vm);
vm->strings.removeWhite(vm);
sweep(vm);
vm->nextGC = vm->bytesAllocated * GC_HEAP_GROW_FACTOR;
vm->marker = !vm->marker;
if(DEBUG_LOG_GC) {
std::cout << "-- gc end" << std::endl;
std::cout << " collected " << before - vm->bytesAllocated << " bytes (from " << before << " to " << vm->bytesAllocated << ") next at " << vm->nextGC << std::endl;
}
}
void GarbageCollector::markRoots(VM* vm) {
for (auto slot = vm->stack.begin(); slot < vm->stack.end(); slot++) {
markValue(vm, *slot);
}
for(int i = 0; i < vm->frames.size(); i++) {
markObject(vm, vm->frames[i].function);
}
for(ObjUpvalue* upvalue = vm->openUpvalues; upvalue != nullptr; upvalue = upvalue->nextUp) {
markObject(vm, (Obj*)upvalue);
}
markGlobal(&vm->globalNames, vm);
if(vm->current != nullptr) vm->current->markCompilerRoots();
markObject(vm, (Obj*)vm->initString);
}
void markGlobal(Table* table, VM* vm) {
for(int i = 0; i < table->entries.size(); i++) {
Entry* entry = &table->entries[i];
if(ValueOP::is_obj(entry->key)) {
markObject(vm, ValueOP::as_obj(entry->key));
markValue(vm, vm->globalValues.values[(int)ValueOP::as_number(entry->value)]);
}
}
}
void markValue(VM* vm, Value value) {
if(!ValueOP::is_obj(value)) return;
markObject(vm, ValueOP::as_obj(value));
}
void markObject(VM* vm, Obj* object) {
if(object == nullptr) return;
if(object->mark == vm->marker) return;
object->mark = vm->marker;
vm->grayStack.push_back(object);
if(DEBUG_LOG_GC) {
std::cout << (void*)object << " mark ";
ValueOP::printValue(ValueOP::obj_val(object));
std::cout << std::endl;
}
}
void traceReferences(VM* vm) {
while (vm->grayStack.size() > 0) {
Obj* object = vm->grayStack.back();
vm->grayStack.pop_back();
blackenObject(object, vm);
}
}
void blackenObject(Obj* object, VM* vm) {
if(DEBUG_LOG_GC) {
std::cout << (void*)object << " blacken ";
ValueOP::printValue(ValueOP::obj_val(object));
std::cout << std::endl;
}
switch (object->type) {
case OBJ_BOUND_METHOD: {
ObjBoundMethod* bound = (ObjBoundMethod*)object;
markValue(vm, bound->receiver);
markObject(vm, bound->method);
break;
}
case OBJ_NATIVE_INSTANCE: {
ObjNativeInstance* instance = static_cast<ObjNativeInstance*>(object);
switch(instance->subType) {
case NATIVE_COLLECTION_INSTANCE: {
ObjCollectionInstance* collection = static_cast<ObjCollectionInstance*>(instance);
for(int i = 0; i < collection->values.count; i++) {
markValue(vm, collection->values.values[i]);
}
break;
}
}
}
case OBJ_INSTANCE: {
ObjInstance* instance = (ObjInstance*)object;
markObject(vm, (Obj*)instance->_class);
markTable(vm, &instance->fields);
break;
}
case OBJ_NATIVE_CLASS:
case OBJ_CLASS: {
ObjClass* _class = (ObjClass*)object;
markObject(vm, (Obj*)_class->name);
markTable(vm, &_class->methods);
break;
}
case OBJ_CLOSURE: {
ObjClosure* closure = (ObjClosure*)object;
markObject(vm, (Obj*)closure->function);
for(int i = 0; i < closure->upvalueCount; i++) {
markObject(vm, (Obj*)closure->upvalues[i]);
}
break;
}
case OBJ_FUNCTION: {
ObjFunction* function = (ObjFunction*)object;
markObject(vm, (Obj*)function->name);
markArray(vm, &function->chunk.constants);
break;
}
case OBJ_UPVALUE:
markValue(vm, ((ObjUpvalue*)object)->closed);
break;
case OBJ_NATIVE:
case OBJ_NATIVE_CLASS_METHOD:
case OBJ_STRING:
break;
}
}
void markArray(VM* vm, ValueArray* array) {
for(int i = 0; i < array->count; i++) {
markValue(vm, array->values[i]);
}
}
void markTable(VM* vm, Table* table) {
for(int i = 0; i < table->entries.size(); i++) {
Entry* entry = &table->entries[i];
markValue(vm, entry->key);
markValue(vm, entry->value);
}
}
void sweep(VM* vm) {
Obj* previous = nullptr;
Obj* object = vm->objects;
while(object != nullptr) {
if(object->mark == vm->marker) {
previous = object;
object = object->next;
} else {
Obj* unreached = object;
object = object->next;
if (previous != nullptr) {
previous->next = object;
} else {
vm->objects = object;
}
freeObject(unreached, vm);
}
}
}
| 33.208791 | 172 | 0.547209 | [
"object"
] |
494a5091a0cf5a9e93afc61fd68d567120ea71ac | 4,102 | hpp | C++ | include/VROSC/UIColorPicker_UIColorPickerData.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/UIColorPicker_UIColorPickerData.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/UIColorPicker_UIColorPickerData.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.UIColorPicker
#include "VROSC/UIColorPicker.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::UIColorPicker::UIColorPickerData);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::UIColorPicker::UIColorPickerData*, "VROSC", "UIColorPicker/UIColorPickerData");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: VROSC.UIColorPicker/VROSC.UIColorPickerData
// [TokenAttribute] Offset: FFFFFFFF
class UIColorPicker::UIColorPickerData : public ::Il2CppObject {
public:
public:
// private System.String _displayName
// Size: 0x8
// Offset: 0x10
::StringW displayName;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
public:
// Creating conversion operator: operator ::StringW
constexpr operator ::StringW() const noexcept {
return displayName;
}
// Get instance field reference: private System.String _displayName
[[deprecated("Use field access instead!")]] ::StringW& dyn__displayName();
// public System.String get_DisplayName()
// Offset: 0xE800B0
::StringW get_DisplayName();
// public System.Void .ctor()
// Offset: 0xE800C0
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static UIColorPicker::UIColorPickerData* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::UIColorPicker::UIColorPickerData::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<UIColorPicker::UIColorPickerData*, creationType>()));
}
// public System.Void SetDisplayName(System.String displayName)
// Offset: 0xE800B8
void SetDisplayName(::StringW displayName);
}; // VROSC.UIColorPicker/VROSC.UIColorPickerData
#pragma pack(pop)
static check_size<sizeof(UIColorPicker::UIColorPickerData), 16 + sizeof(::StringW)> __VROSC_UIColorPicker_UIColorPickerDataSizeCheck;
static_assert(sizeof(UIColorPicker::UIColorPickerData) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::UIColorPicker::UIColorPickerData::get_DisplayName
// Il2CppName: get_DisplayName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (VROSC::UIColorPicker::UIColorPickerData::*)()>(&VROSC::UIColorPicker::UIColorPickerData::get_DisplayName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::UIColorPicker::UIColorPickerData*), "get_DisplayName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::UIColorPicker::UIColorPickerData::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::UIColorPicker::UIColorPickerData::SetDisplayName
// Il2CppName: SetDisplayName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::UIColorPicker::UIColorPickerData::*)(::StringW)>(&VROSC::UIColorPicker::UIColorPickerData::SetDisplayName)> {
static const MethodInfo* get() {
static auto* displayName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::UIColorPicker::UIColorPickerData*), "SetDisplayName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{displayName});
}
};
| 50.641975 | 191 | 0.742565 | [
"vector"
] |
4956cc110f247fd2642fb0e375347d538b81d071 | 14,731 | hpp | C++ | include/meck/font.hpp | edlund/libmeck | d4091db96d3ba5b4006d4166da4000a47a302a46 | [
"RSA-MD"
] | 1 | 2016-05-17T12:39:59.000Z | 2016-05-17T12:39:59.000Z | include/meck/font.hpp | edlund/libmeck | d4091db96d3ba5b4006d4166da4000a47a302a46 | [
"RSA-MD"
] | null | null | null | include/meck/font.hpp | edlund/libmeck | d4091db96d3ba5b4006d4166da4000a47a302a46 | [
"RSA-MD"
] | null | null | null |
/* meck - Mediocre (Entertainment Creation Kit)
* Copyright(c) 2016, Erik Edlund <erik.edlund@32767.se>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Erik Edlund, nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----
*
* Parts of meck are based on libSDL2pp - "C++11 bindings/wrapper for SDL2"
* by Dmitry Marakasov <amdmi3@amdmi3.ru>. libSDL2pp can be found at:
*
* https://github.com/libSDL2pp/libSDL2pp
*
* Code taken from libSDL2pp is most often altered and is not necessarily
* representative of the original software.
*
* libSDLpp is made available under the following conditions:
*
* Copyright (C) 2013-2015 Dmitry Marakasov <amdmi3@amdmi3.ru>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef MECK_FONT_HPP
#define MECK_FONT_HPP
#include <string>
#include <boost/filesystem/path.hpp>
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <meck/point.hpp>
#include <meck/renderer.hpp>
#include <meck/surface.hpp>
#include <meck/texture.hpp>
#include <SDL.h>
#include <SDL_ttf.h>
#define u16string_to_u16pointer_return(Parameter, Function, ...) \
std::vector<::Uint16> uint16_text(Parameter.length() + 1); \
std::copy(Parameter.begin(), Parameter.end(), uint16_text.begin()); \
return Function(uint16_text.data(), ##__VA_ARGS__); \
/**/
namespace meck {
class font
: private boost::noncopyable
{
public:
explicit
font(
::TTF_Font* f
) noexcept
: font_(f)
{}
font(
const boost::filesystem::path& file,
const int ptsize,
const long index = 0
)
: font_(::TTF_OpenFontIndex(
file.string().c_str(),
ptsize,
index
))
{
if (!font_)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
}
virtual
~font() noexcept {
::TTF_CloseFont(font_);
}
font(
font&& rhs
) noexcept:
font_(rhs.font_)
{
rhs.font_ = nullptr;
}
font&
operator=(
font&& rhs
) noexcept {
if (this != &rhs) {
if (font_)
::TTF_CloseFont(font_);
font_ = rhs.font_;
rhs.font_ = nullptr;
}
return *this;
}
::TTF_Font*
get() noexcept {
return font_;
}
const ::TTF_Font*
get() const noexcept {
return font_;
}
int
get_style() const {
RUNTIME_ASSERT(font_);
return ::TTF_GetFontStyle(font_);
}
font&
set_style(
const int style = TTF_STYLE_NORMAL
) {
RUNTIME_ASSERT(font_);
::TTF_SetFontStyle(font_, style);
return *this;
}
int
get_outline() const {
RUNTIME_ASSERT(font_);
return ::TTF_GetFontOutline(font_);
}
font&
set_outline(
const int outline = 0
) {
RUNTIME_ASSERT(font_);
::TTF_SetFontOutline(font_, outline);
return *this;
}
int
get_hinting() const {
RUNTIME_ASSERT(font_);
return ::TTF_GetFontHinting(font_);
}
font&
set_hinting(
const int hinting = TTF_HINTING_NORMAL
) {
RUNTIME_ASSERT(font_);
::TTF_SetFontHinting(font_, hinting);
return *this;
}
bool
get_kerning() const {
RUNTIME_ASSERT(font_);
return static_cast<bool>(::TTF_GetFontKerning(font_));
}
font&
set_kerning(
const bool allowed = true
) {
RUNTIME_ASSERT(font_);
::TTF_SetFontKerning(font_, allowed);
return *this;
}
int
get_height() const {
RUNTIME_ASSERT(font_);
return ::TTF_FontHeight(font_);
}
int
get_ascent() const {
RUNTIME_ASSERT(font_);
return ::TTF_FontAscent(font_);
}
int
get_descent() const {
RUNTIME_ASSERT(font_);
return ::TTF_FontDescent(font_);
}
int
get_line_skip() const {
RUNTIME_ASSERT(font_);
return ::TTF_FontLineSkip(font_);
}
long
get_num_faces() const {
RUNTIME_ASSERT(font_);
return ::TTF_FontFaces(font_);
}
bool is_fixed_width() const {
RUNTIME_ASSERT(font_);
return ::TTF_FontFaceIsFixedWidth(font_);
}
boost::optional<std::string>
get_family_name() const {
RUNTIME_ASSERT(font_);
const char* name = ::TTF_FontFaceFamilyName(font_);
return name?
OPT(std::string, std::string(name)):
OPT(std::string, boost::none);
}
boost::optional<std::string>
get_style_name() const {
RUNTIME_ASSERT(font_);
const char* name = ::TTF_FontFaceStyleName(font_);
return name?
OPT(std::string, std::string(name)):
OPT(std::string, boost::none);
}
int
is_glyph_provided(
const ::Uint16 ch
) const {
RUNTIME_ASSERT(font_);
return ::TTF_GlyphIsProvided(font_, ch);
}
void
get_glyph_metrics(
const ::Uint16 ch,
int& mx,
int& Mx,
int& my,
int& My,
int& advance
) const {
RUNTIME_ASSERT(font_);
if (::TTF_GlyphMetrics(font_, ch, &mx, &Mx, &my, &My, &advance))
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
}
rect
get_glyph_rect(
const ::Uint16 ch
) const {
RUNTIME_ASSERT(font_);
int mx;
int Mx;
int my;
int My;
int advance;
get_glyph_metrics(ch, mx, Mx, my, My, advance);
return rect(mx, my, Mx - mx, My - my);
}
int
get_glyph_advance(
const ::Uint16 ch
) const {
RUNTIME_ASSERT(font_);
int mx;
int Mx;
int my;
int My;
int advance;
get_glyph_metrics(ch, mx, Mx, my, My, advance);
return advance;
}
point
get_size_text(
const std::string& text
) const {
RUNTIME_ASSERT(font_);
int w;
int h;
if (::TTF_SizeText(font_, text.c_str(), &w, &h))
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return point(w, h);
}
point
get_size_UTF8(
const std::string& text
) const {
RUNTIME_ASSERT(font_);
int w;
int h;
if (::TTF_SizeUTF8(font_, text.c_str(), &w, &h))
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return point(w, h);
}
point
get_size_UNICODE(
const ::Uint16* text
) const {
RUNTIME_ASSERT(font_);
int w;
int h;
if (::TTF_SizeUNICODE(font_, text, &w, &h))
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return point(w, h);
}
point
get_size_UNICODE(
const std::u16string& text
) const {
u16string_to_u16pointer_return(text, get_size_UNICODE);
}
surface
render_text_solid(
const std::string& text,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = ::TTF_RenderText_Solid(font_, text.c_str(), fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UTF8_solid(
const std::string& text,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = ::TTF_RenderUTF8_Solid(font_, text.c_str(), fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UNICODE_solid(
const Uint16* text,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = ::TTF_RenderUNICODE_Solid(font_, text, fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UNICODE_solid(
const std::u16string& text,
const ::SDL_Color fg
) {
u16string_to_u16pointer_return(text, render_UNICODE_solid, fg);
}
surface
render_glyph_solid(
const ::Uint16 ch,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderGlyph_Solid(font_, ch, fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
texture
render_text_solid(
renderer& rndr,
const std::string& text,
const ::SDL_Color fg
) {
surface srfc(render_text_solid(text, fg));
return texture(rndr, srfc);
}
texture
render_UTF8_solid(
renderer& rndr,
const std::string& text,
const ::SDL_Color fg
) {
surface srfc(render_UTF8_solid(text, fg));
return texture(rndr, srfc);
}
texture
render_UNICODE_solid(
renderer& rndr,
const Uint16* text,
const ::SDL_Color fg
) {
surface srfc(render_UNICODE_solid(text, fg));
return texture(rndr, srfc);
}
texture
render_UNICODE_solid(
renderer& rndr,
const std::u16string& text,
const ::SDL_Color fg
) {
surface srfc(render_UNICODE_solid(text, fg));
return texture(rndr, srfc);
}
texture
render_glyph_solid(
renderer& rndr,
const ::Uint16 ch,
const ::SDL_Color fg
) {
surface srfc(render_glyph_solid(ch, fg));
return texture(rndr, srfc);
}
surface
render_text_shaded(
const std::string& text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderText_Shaded(font_, text.c_str(), fg, bg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UTF8_shaded(
const std::string& text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderUTF8_Shaded(font_, text.c_str(), fg, bg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UNICODE_shaded(
const Uint16* text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderUNICODE_Shaded(font_, text, fg, bg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UNICODE_shaded(
const std::u16string& text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
u16string_to_u16pointer_return(text, render_UNICODE_shaded, fg, bg);
}
surface
render_glyph_shaded(
const ::Uint16 ch,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
RUNTIME_ASSERT(font_);
SDL_Surface* s = TTF_RenderGlyph_Shaded(font_, ch, fg, bg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
texture
render_text_shaded(
renderer& rndr,
const std::string& text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
surface srfc(render_text_shaded(text, fg, bg));
return texture(rndr, srfc);
}
texture
render_UTF8_shaded(
renderer& rndr,
const std::string& text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
surface srfc(render_UTF8_shaded(text, fg, bg));
return texture(rndr, srfc);
}
texture
render_UNICODE_shaded(
renderer& rndr,
const Uint16* text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
surface srfc(render_UNICODE_shaded(text, fg, bg));
return texture(rndr, srfc);
}
texture
render_UNICODE_shaded(
renderer& rndr,
const std::u16string& text,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
surface srfc(render_UNICODE_shaded(text, fg, bg));
return texture(rndr, srfc);
}
texture
render_glyph_shaded(
renderer& rndr,
const ::Uint16 ch,
const ::SDL_Color fg,
const ::SDL_Color bg
) {
surface srfc(render_glyph_shaded(ch, fg, bg));
return texture(rndr, srfc);
}
surface
render_text_blended(
const std::string& text,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderText_Blended(font_, text.c_str(), fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UTF8_blended(
const std::string& text,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderUTF8_Blended(font_, text.c_str(), fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UNICODE_blended(
const Uint16* text,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
::SDL_Surface* s = TTF_RenderUNICODE_Blended(font_, text, fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
surface
render_UNICODE_blended(
const std::u16string& text,
const ::SDL_Color fg
) {
u16string_to_u16pointer_return(text, render_UNICODE_blended, fg);
}
surface
render_glyph_blended(
const ::Uint16 ch,
const ::SDL_Color fg
) {
RUNTIME_ASSERT(font_);
SDL_Surface* s = TTF_RenderGlyph_Blended(font_, ch, fg);
if (!s)
RUNTIME_ERROR("TTF: %s", ::TTF_GetError());
return surface(s);
}
texture
render_text_blended(
renderer& rndr,
const std::string& text,
const ::SDL_Color fg
) {
surface srfc(render_text_blended(text, fg));
return texture(rndr, srfc);
}
texture
render_UTF8_blended(
renderer& rndr,
const std::string& text,
const ::SDL_Color fg
) {
surface srfc(render_UTF8_blended(text, fg));
return texture(rndr, srfc);
}
texture
render_UNICODE_blended(
renderer& rndr,
const Uint16* text,
const ::SDL_Color fg
) {
surface srfc(render_UNICODE_blended(text, fg));
return texture(rndr, srfc);
}
texture
render_UNICODE_blended(
renderer& rndr,
const std::u16string& text,
const ::SDL_Color fg
) {
surface srfc(render_UNICODE_blended(text, fg));
return texture(rndr, srfc);
}
texture
render_glyph_blended(
renderer& rndr,
const ::Uint16 ch,
const ::SDL_Color fg
) {
surface srfc(render_glyph_blended(ch, fg));
return texture(rndr, srfc);
}
private:
::TTF_Font* font_;
};
} // namespace:meck
#undef u16string_to_u16pointer_return
#endif
| 21.134864 | 78 | 0.687055 | [
"vector"
] |
4957ca34cddcb98fd74edaa6ec1a8e847c408d11 | 2,822 | hpp | C++ | Axis.CommonLibrary/application/output/CollectorChain.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.CommonLibrary/application/output/CollectorChain.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.CommonLibrary/application/output/CollectorChain.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "AxisString.hpp"
#include "foundation/collections/Collectible.hpp"
namespace axis {
namespace services { namespace messaging {
class ResultMessage;
} } // namespace axis::services::messaging
namespace application { namespace output {
namespace recordsets {
class ResultRecordset;
} // namespace axis::application::output::recordsets::ResultRecordset
/**
* Groups entity collectors according to which
* entity set they work on.
*/
template<class CollectedItem, class Collector>
class CollectorChain : public axis::foundation::collections::Collectible
{
public:
CollectorChain(void);
~CollectorChain(void);
/**
* Destroys this object.
*/
void Destroy(void) const;
/**
* Queries if 'message' is of interest for this chain.
*
* @param message The message.
*
* @return true if it is of interest, false otherwise.
*/
bool IsOfInterest(const axis::services::messaging::ResultMessage& message) const;
/**
* Adds a new collector to the end of the chain.
*
* @param collector The collector to add.
* @remarks Although not checked, the new collector must accept the same set of messages
* than other collectors already in the chain, in order to avoid undefined
* behavior.
*/
void Add(const Collector& collector);
/**
* Removes the given collector from the chain.
*
* @param collector The collector to remove.
*/
void Remove(const Collector& collector);
/**
* Queries if this chain has no collector.
*
* @return true if it is empty, false otherwise.
*/
bool IsEmpty(void) const;
/**
* Returns the name of the entity set this chain is targeting to.
*
* @return The target set name.
*/
axis::String GetTargetSetName(void) const;
/**
* Returns how many collector are in this chain.
*
* @return The collector count.
*/
int GetCollectorCount(void) const;
/**
* Returns a collector in the chain.
*
* @param index Zero-based index of the collector.
*
* @return The collector.
*/
const Collector& operator[](int index) const;
/**
* Requests to process a message by every collector in this chain.
*
* @param message The message to process.
* @param [in,out] recordset The recordset to which data should be written to.
* @param item The item on which data will be based.
*/
void ChainCollect(const axis::services::messaging::ResultMessage& message,
axis::application::output::recordsets::ResultRecordset& recordset,
const CollectedItem& item);
private:
typedef std::vector<Collector *> collector_list;
collector_list collectors_;
}; // CollectorChain<CollectedItem, Collector>
} } } // namespace axis::application::output
| 26.622642 | 90 | 0.676825 | [
"object",
"vector"
] |
4958218e9793c3d1ed115f48dff5a152be45db6a | 12,535 | hpp | C++ | core/include/pipepp/pipeline.hpp | kang-sw/pipepp | 9ed511504a6ef7bdfb1795fc60d920040e4546e3 | [
"Apache-2.0"
] | null | null | null | core/include/pipepp/pipeline.hpp | kang-sw/pipepp | 9ed511504a6ef7bdfb1795fc60d920040e4546e3 | [
"Apache-2.0"
] | 1 | 2021-06-15T01:05:40.000Z | 2021-07-01T14:05:22.000Z | core/include/pipepp/pipeline.hpp | kang-sw/pipepp | 9ed511504a6ef7bdfb1795fc60d920040e4546e3 | [
"Apache-2.0"
] | 1 | 2021-06-07T01:55:29.000Z | 2021-06-07T01:55:29.000Z | #pragma once
#include <algorithm>
#include <functional>
#include <memory>
#include <typeinfo>
#include "kangsw/helpers/misc.hxx"
#include "kangsw/thread/thread_pool.hxx"
#include "nlohmann/json_fwd.hpp"
#include "pipepp/pipe.hpp"
namespace pipepp {
namespace detail {
class pipeline_base : public std::enable_shared_from_this<pipeline_base> {
public:
using factory_return_type = std::unique_ptr<detail::executor_base>;
protected:
pipeline_base();
virtual ~pipeline_base();
public:
decltype(auto) get_first();
decltype(auto) get_pipe(pipe_id_t);
auto get_pipe(std::string_view s);
auto& _thread_pool() { return workers_; }
void sync();
// launcher
void launch();
public:
auto& options() const { return *global_options_; }
auto& options() { return *global_options_; }
void export_options(nlohmann::json&);
void import_options(nlohmann::json const&);
protected:
// shared data object allocator
std::shared_ptr<base_shared_context> _fetch_shared();
virtual std::shared_ptr<base_shared_context> _new_shared_object() = 0;
protected:
std::vector<std::unique_ptr<pipe_base>> pipes_;
std::vector<std::shared_ptr<base_shared_context>> fence_objects_;
std::unordered_map<pipe_id_t, size_t> id_mapping_;
std::mutex fence_object_pool_lock_;
std::unique_ptr<option_base> global_options_;
kangsw::timer_thread_pool workers_;
std::vector<std::tuple<size_t, std::function<factory_return_type(void)>>> adapters_;
};
class pipe_proxy_base {
friend class pipeline_base;
friend class std::optional<pipe_proxy_base>;
protected:
pipe_proxy_base(
std::weak_ptr<pipeline_base> pipeline,
pipe_base& pipe_ref)
: pipeline_(pipeline)
, pipe_(&pipe_ref)
{
}
public:
virtual ~pipe_proxy_base() = default;
protected:
auto& pipe() { return *pipe_; }
auto& pipe() const { return *pipe_; }
public:
// size of output nodes
// output nodes[index]
size_t num_output_nodes() const { return pipe().output_links().size(); }
pipe_proxy_base get_output_node(size_t index) const { return {pipeline_, *pipe().output_links().at(index).pipe}; }
size_t num_input_nodes() const { return pipe().input_links().size(); }
pipe_proxy_base get_input_node(size_t index) const { return {pipeline_, *pipe().input_links().at(index).pipe}; }
// get previous execution context
std::shared_ptr<execution_context_data> consume_execution_result();
bool execution_result_available() const;
// get options
auto& options() const { return pipe().options(); }
// get id
auto id() const { return pipe().id(); }
// get name
auto& name() const { return pipe().name(); }
// check validity
bool is_valid() const { return pipeline_.expired() == false; }
bool is_optional() const { return pipe().is_optional_input(); }
// executor conditions
size_t num_executors() const { return pipe().num_executors(); }
void executor_conditions(std::vector<executor_condition_t>& out) const { pipe().executor_conditions(out); }
// return latest output interval
auto output_interval() const { return pipe().output_interval(); }
auto output_latency() const { return pipe().output_latency(); }
// pause functionality
bool is_paused() const { return pipe().is_paused(); }
void pause() { pipe().pause(); }
void unpause() { pipe().unpause(); }
bool recently_aborted() const { return pipe().recently_aborted(); }
// mark dirty
void mark_option_dirty() { pipe().mark_dirty(); }
auto configure_tweaks() { return pipe().get_prelaunch_tweaks(); }
auto tweaks() { return pipe().read_tweaks(); }
protected:
std::weak_ptr<pipeline_base> pipeline_;
pipe_base* pipe_;
};
inline decltype(auto) pipeline_base::get_first()
{
return pipe_proxy_base(weak_from_this(), *pipes_.front());
}
inline decltype(auto) pipepp::detail::pipeline_base::get_pipe(pipe_id_t id)
{
auto index = id_mapping_.at(id);
return pipe_proxy_base(weak_from_this(), *pipes_.at(index));
}
inline auto pipepp::detail::pipeline_base::get_pipe(std::string_view s)
{
std::optional<pipe_proxy_base> rval;
for (auto& pipe : pipes_) {
if (pipe->name() == s) {
rval = pipe_proxy_base(weak_from_this(), *pipe);
break;
}
}
return rval;
}
} // namespace detail
// template <typename SharedData_, typename InitialExec_>
// class pipeline;
template <typename SharedData_, typename Exec_>
class pipe_proxy final : public detail::pipe_proxy_base {
template <typename, typename>
friend class pipeline;
template <typename, typename>
friend class pipe_proxy;
public:
using shared_data_type = SharedData_;
using executor_type = Exec_;
using input_type = typename executor_type::input_type;
using output_type = typename executor_type::output_type;
using pipeline_type = pipeline<SharedData_, Exec_>;
private:
pipe_proxy(const std::weak_ptr<detail::pipeline_base>& pipeline, detail::pipe_base& pipe_ref)
: pipe_proxy_base(pipeline, pipe_ref)
{
}
public:
/**
* AVAILABLE LINKER SIGNATURES
*
* ( )\n
* (Next Input )\n
* (SharedData, Prev Output, Next Input )\n
* (SharedData, Next Input )\n
* (Prev Output, Next Input )\n
* (Exec Context, Prev Output, Next Input )\n
* (Shared Data, Exec Context, Prev Output, Next Input )\n
*/
template <typename LnkFn_, typename FactoryFn_, typename... FactoryArgs_>
pipe_proxy<SharedData_, typename std::invoke_result_t<FactoryFn_, FactoryArgs_...>::element_type::executor_type>
create_and_link_output(
std::string name, size_t num_executors, LnkFn_&& linker, FactoryFn_&& factory, FactoryArgs_&&... args);
/**
* AVAILABLE LINKER SIGNATURES
*
* ( )\n
* (Next Input )\n
* (SharedData, Prev Output, Next Input )\n
* (SharedData, Next Input )\n
* (Prev Output, Next Input )\n
* (Exec Context, Prev Output, Next Input )\n
* (Shared Data, Exec Context, Prev Output, Next Input )\n
*/
template <typename Dest_, typename LnkFn_>
pipe_proxy<shared_data_type, Dest_> link_output(pipe_proxy<shared_data_type, Dest_> dest, LnkFn_&& linker);
/**
* AVAILABLE OUTPUT HANDLER SIGNATURES
*
* ( )\n
* (Pipe Err, SharedData, Result )\n
* (SharedData )\n
* (SharedData, Exec Context )\n
* (Pipe Err, Result )\n
* (SharedData, Result )\n
* (SharedData, Exec Context, Result )\n
* (Pipe Err, SharedData, Exec Context, Result )\n
*/
template <typename Fn_>
pipe_proxy& add_output_handler(Fn_&& handler);
private:
std::shared_ptr<pipeline_type> _lock() const
{
auto ref = pipeline_.lock();
if (ref == nullptr) { throw pipe_exception("pipeline reference destroied"); }
return std::static_pointer_cast<pipeline_type>(ref);
}
private:
};
template <typename SharedData_, typename Exec_>
template <typename Dest_, typename LnkFn_>
pipe_proxy<typename pipe_proxy<SharedData_, Exec_>::shared_data_type, Dest_>
pipe_proxy<SharedData_, Exec_>::link_output(pipe_proxy<shared_data_type, Dest_> dest, LnkFn_&& linker)
{
using prev_output_type = output_type;
using next_input_type = typename Dest_::input_type;
pipe().connect_output_to<shared_data_type, prev_output_type, next_input_type>(
dest.pipe(), std::forward<LnkFn_>(linker));
return dest;
}
template <typename SharedData_, typename Exec_>
template <typename Fn_>
pipe_proxy<SharedData_, Exec_>&
pipe_proxy<SharedData_, Exec_>::add_output_handler(Fn_&& handler)
{
auto wrapper = [fn_ = std::move(handler)](pipe_error e, base_shared_context& s, execution_context& ec, std::any const& o) {
auto& sd = static_cast<SharedData_&>(s);
auto& out = std::any_cast<output_type const&>(o);
using PE = pipe_error;
using SD = SharedData_&;
using EC = execution_context&;
using OUT = output_type const&;
bool const okay = e <= pipe_error::warning;
// clang-format off
if constexpr (std::is_invocable_v<Fn_>) { if(okay) fn_(); }
if constexpr (std::is_invocable_v<Fn_, PE, SD, OUT>) { fn_(e, sd, out); }
else if constexpr (std::is_invocable_v<Fn_, SD>) { if (okay) { fn_(sd); } }
else if constexpr (std::is_invocable_v<Fn_, SD, EC>) { if (okay) { fn_(sd, ec); } }
else if constexpr (std::is_invocable_v<Fn_, PE, OUT>) { fn_(e, o); }
else if constexpr (std::is_invocable_v<Fn_, SD, OUT>) { if (okay) { fn_(sd, out); } }
else if constexpr (std::is_invocable_v<Fn_, SD, EC, OUT>) { if (okay) { fn_(sd, ec, out); } }
else if constexpr (std::is_invocable_v<Fn_, PE, SD, EC, OUT>) { fn_(e, sd, ec, out); }
else { static_assert(false, "No invocable method"); }
// clang-format on
};
pipe().add_output_handler(std::move(wrapper));
return *this;
} // namespace pipepp
template <typename SharedData_, typename InitialExec_>
class pipeline final : public detail::pipeline_base {
template <typename, typename>
friend class pipe_proxy;
public:
using shared_data_type = SharedData_;
using initial_executor_type = InitialExec_;
using input_type = typename initial_executor_type::input_type;
using initial_proxy_type = pipe_proxy<shared_data_type, initial_executor_type>;
~pipeline() { sync(); }
private:
template <typename Exec_, typename Fn_, typename... Args_> auto& _create_pipe(std::string initial_pipe_name, bool is_optional, size_t num_execs, Fn_&& exec_factory, Args_&&... args);
template <typename Fn_, typename... Args_> pipeline(std::string initial_pipe_name, size_t num_exec, Fn_&& initial_executor_factory, Args_&&... args);
public:
template <typename FactoryFn_, typename... FactoryArgs_>
pipe_proxy<SharedData_, typename std::invoke_result_t<FactoryFn_, FactoryArgs_...>::element_type::executor_type>
create(std::string name, size_t num_executors, FactoryFn_&& factory, FactoryArgs_&&... args);
template <typename Fn_, typename... Args_>
static std::shared_ptr<pipeline> make(std::string initial_pipe_name, size_t num_initial_exec, Fn_&& factory, Args_&&... factory_args)
{
return std::shared_ptr<pipeline>{
new pipeline(
std::move(initial_pipe_name),
num_initial_exec,
std::forward<Fn_>(factory),
std::forward<Args_>(factory_args)...)};
}
public:
initial_proxy_type front()
{
return initial_proxy_type{
std::static_pointer_cast<detail::pipeline_base>(shared_from_this()),
*pipes_.front()};
}
public:
// check if suppliable
bool can_suply() const { return !pipes_.front()->is_paused() && pipes_.front()->can_submit_input_direct(); }
// supply input (trigger)
template <typename Fn_>
bool suply(
input_type input, Fn_&& shared_data_init_func = [](auto&&) {})
{
auto shared = _fetch_shared();
shared_data_init_func(static_cast<shared_data_type&>(*shared));
shared->reload();
return pipes_.front()->try_submit(std::move(input), std::move(shared));
}
bool wait_supliable(std::chrono::milliseconds timeout = std::chrono::milliseconds{10}) const
{
return !pipes_.front()->is_paused() && pipes_.front()->wait_active_slot_idle(timeout);
}
protected:
std::shared_ptr<base_shared_context> _new_shared_object() override
{
return std::make_shared<shared_data_type>();
}
private:
};
static constexpr auto link_as_is = [](auto&& prev_out, auto&& next_in) { next_in = std::forward<decltype(prev_out)>(prev_out); return true; };
} // namespace pipepp | 35.610795 | 186 | 0.63566 | [
"object",
"vector"
] |
4959d7b5e01d3f59f1c1a5617efccd9a11f3c9d3 | 3,241 | cpp | C++ | src/model/game/matrix.cpp | vanderpluijmg/tetris_cpp | e7f8f5dfe1eba6bf97caeb0c10e371e9431e5068 | [
"MIT"
] | null | null | null | src/model/game/matrix.cpp | vanderpluijmg/tetris_cpp | e7f8f5dfe1eba6bf97caeb0c10e371e9431e5068 | [
"MIT"
] | null | null | null | src/model/game/matrix.cpp | vanderpluijmg/tetris_cpp | e7f8f5dfe1eba6bf97caeb0c10e371e9431e5068 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2022 Andrew SASSOYE, Constantin GUNDUZ, Gregory VAN DER PLUIJM,
// Thomas LEUTSCHER
//
// 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 "model/game/matrix.hpp"
#include <iostream>
#include "model/game/states/exceptions/lockedoutexception.hpp"
namespace tetris::model::game {
void Matrix::add(const std::shared_ptr<tetrimino::Tetrimino>& tetrimino) {
auto minoTemplate = tetrimino->minos();
for (size_t i = 0; i < minoTemplate.size(); i++) {
for (size_t j = 0;
j < minoTemplate.at(tetrimino->orientation()).at(i).size(); j++) {
if (minoTemplate.at(tetrimino->orientation()).at(i).at(j) == std::nullopt)
continue;
size_t line = tetrimino->Y() + i;
size_t col = tetrimino->X() + j;
if (!(line < 0 || col < 0) && line < minos_.size() &&
col < minos_.at(line).size()) {
minos_.at(line).at(col) =
minoTemplate.at(tetrimino->orientation()).at(i).at(j);
}
}
}
}
void Matrix::removeLine(unsigned long i) {
for (size_t j = 0; j < width(); j++) {
minos_.at(i).at(j).reset();
}
}
void Matrix::setLine(std::vector<OptionalMino> minos, unsigned long line) {
for (size_t col = 0; col < width(); col++)
if (minos.at(col).has_value()) {
minos_.at(line).at(col).emplace(minos.at(col).value());
} else {
minos_.at(line).at(col).reset();
}
}
std::vector<unsigned int> Matrix::getCompletedLines() {
std::vector<unsigned int> completedLines;
for (size_t i = 0; i < minos_.size(); i++) {
bool isComplete = true;
for (auto& j : minos_.at(i))
if (j == std::nullopt) isComplete = false;
if (isComplete) completedLines.push_back(i);
}
return completedLines;
}
void Matrix::set(tetris::model::tetrimino::Mino m, int line, int col) {
minos_.at(line).at(col) = m;
}
std::vector<std::vector<bool>> Matrix::generateMask() const {
std::vector<std::vector<bool>> mask{};
mask.reserve(minos_.size());
for (auto& line : minos_) {
std::vector<bool> t{};
t.reserve(line.size());
for (auto& mino : line) {
t.push_back(!mino.has_value());
}
mask.push_back(t);
}
return mask;
}
} // namespace tetris::model::game
| 33.760417 | 80 | 0.664301 | [
"vector",
"model"
] |
495b727b1e3ff379105acd7502a59555b11a7a06 | 5,518 | cpp | C++ | Source/Cell.cpp | yuhongyi/HazelEngine | fad6eb1f42ad7ac06b8a0e9e2d3154147b3a7c9c | [
"MIT"
] | null | null | null | Source/Cell.cpp | yuhongyi/HazelEngine | fad6eb1f42ad7ac06b8a0e9e2d3154147b3a7c9c | [
"MIT"
] | null | null | null | Source/Cell.cpp | yuhongyi/HazelEngine | fad6eb1f42ad7ac06b8a0e9e2d3154147b3a7c9c | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Cell.h"
#include "Grid.h"
#include "ImageResource.h"
#include "ResourceManager.h"
Cell::Cell(Grid* parentGrid):
mPrevCellState(CellState::Idle),
mCellState(CellState::Idle),
mFallingSpeed(0.f),
mCellBelow(nullptr),
mParentGrid(parentGrid),
mVBResource(nullptr)
{
mVBResource = new VertexBufferResource();
mSize.X = (float)gCellSize;
mSize.Y = (float)gCellSize;
}
bool Cell::Initialize(LPDIRECT3DDEVICE9 d3dDevice)
{
D3DCOLOR cellDiffuse = 0xffffffff;
CUSTOMVERTEX Vertices[] =
{
{ 0.f, 0.f, 0.f, cellDiffuse, 0.f, 0.f }, // x, y, z, tex2
{ mSize.X, 0.f, 0.f, cellDiffuse, 1.f, 0.f },
{ 0.f, mSize.Y, 0.f, cellDiffuse, 0.f, 1.f },
{ mSize.X, mSize.Y, 0.f, cellDiffuse, 1.f, 1.f },
};
mVBResource->SetVertexBufferData(sizeof(CUSTOMVERTEX), 4, D3DFVF_CUSTOMVERTEX, Vertices);
mVBResource->InitResource(d3dDevice);
return true;
}
void Cell::Deinitialize()
{
}
void Cell::Render(LPDIRECT3DDEVICE9 d3dDevice, ID3DXEffect* effect)
{
// Set Texture
ArchivedGameResource* d3dResource = ResourceManager::GetInstance()->GetArchivedGameResource(mResourceName);
ImageResource* image = dynamic_cast<ImageResource*>(d3dResource);
if(image)
{
D3DXHANDLE cellTextureHandle = effect->GetParameterByName(0, "gCellTexture");
effect->SetTexture(cellTextureHandle, image->GetTexture());
}
// Set VB
d3dDevice->SetStreamSource(0, mVBResource->GetVertexBuffer(), 0, mVBResource->GetVertexStride());
d3dDevice->SetFVF(mVBResource->GetVertexFormat());
// Update matrix
D3DXHANDLE wvpMatrixHandle = effect->GetParameterByName(0, "gWorldViewProjectionMatrix");
effect->SetMatrix(wvpMatrixHandle, &mWVPMatrix);
// Draw
effect->CommitChanges();
d3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
}
void Cell::SetPosition(Vector2D newPosition)
{
if(mPosition != newPosition)
{
GameObject::SetPosition(newPosition);
OnPositionUpdated();
}
}
void Cell::SetTargetPosition(Vector2D targetPosition)
{
mTargetPosition = targetPosition;
}
void Cell::OnPositionUpdated()
{
D3DXMATRIX matCellTrans;
D3DXMATRIX matCellWorldTrans;
D3DXMatrixTranslation(&matCellTrans, mPosition.X, -mPosition.Y, 0.0f);
D3DXMatrixMultiply(&matCellWorldTrans, &mParentGrid->GetWorldMatrix(), &matCellTrans);
D3DXMatrixMultiply(&mWVPMatrix, &matCellWorldTrans, &mParentGrid->GetProjectionMatrix());
}
void Cell::SetResourceName(const wstring& resourceName)
{
mResourceName = resourceName;
}
const wstring& Cell::GetResourceName() const
{
return mResourceName;
}
void Cell::SetRow(int row)
{
mRow = row;
}
int Cell::GetRow() const
{
return mRow;
}
void Cell::SetColumn(int column)
{
mColumn = column;
}
int Cell::GetColumn() const
{
return mColumn;
}
void Cell::SetCellState(CellState newCellState)
{
mCellState = newCellState;
}
CellState Cell::GetCellState() const
{
return mCellState;
}
Cell* Cell::GetSwappedCell() const
{
return mSwappedCell;
}
void Cell::SetSwappedCell(Cell* other)
{
mSwappedCell = other;
}
void Cell::SetCellBelow(Cell* cellBelow)
{
mCellBelow = cellBelow;
}
bool Cell::IsAdjacentTo(Cell* other)
{
if(!other)
{
return false;
}
if((abs(this->GetRow() - other->GetRow()) + abs(this->GetColumn() - other->GetColumn())) == 1)
{
return true;
}
return false;
}
void Cell::Tick(float deltaTime)
{
switch(mCellState)
{
case CellState::Falling:
TickFalling(deltaTime);
break;
case CellState::Switching:
TickSwitching(deltaTime);
break;
}
mPrevCellState = mCellState;
}
void Cell::TickFalling(float deltaTime)
{
if(mPrevCellState == CellState::Idle)
{
mFallingSpeed = 0.f;
}
mFallingSpeed += gFallingAcceleration * deltaTime;
mPosition.Y += mFallingSpeed * deltaTime;
// Should not overlap with cell below
if(mCellBelow)
{
float maxPositionY = mCellBelow->GetPosition().Y - mSize.Y;
mPosition.Y = min<float>(mPosition.Y, maxPositionY);
}
// Check if landed
if(mPosition.Y >= mTargetPosition.Y)
{
mPosition.Y = mTargetPosition.Y;
mFallingSpeed = 0.f;
SetCellState(CellState::Idle);
}
OnPositionUpdated();
}
void Cell::TickSwitching(float deltaTime)
{
// Reach target
if(mTargetPosition.X > mPosition.X)
{
mPosition.X += gSwitchingSpeed * deltaTime;
if(mPosition.X > mTargetPosition.X)
{
mPosition.X = mTargetPosition.X;
}
}
else
{
mPosition.X -= gSwitchingSpeed * deltaTime;
if(mPosition.X < mTargetPosition.X)
{
mPosition.X = mTargetPosition.X;
}
}
if(mTargetPosition.Y > mPosition.Y)
{
mPosition.Y += gSwitchingSpeed * deltaTime;
if(mPosition.Y > mTargetPosition.Y)
{
mPosition.Y = mTargetPosition.Y;
}
}
else
{
mPosition.Y -= gSwitchingSpeed * deltaTime;
if(mPosition.Y < mTargetPosition.Y)
{
mPosition.Y = mTargetPosition.Y;
}
}
if(mPosition == mTargetPosition)
{
if(GetSwappedCell() != nullptr)
{
SetCellState(CellState::PendingCheck);
}
else
{
SetCellState(CellState::Idle);
}
}
OnPositionUpdated();
}
void Cell::SwapWith(Cell* other, bool isSwapBack)
{
const wstring tempResourceId = this->GetResourceName();
this->SetResourceName(other->GetResourceName());
other->SetResourceName(tempResourceId);
const Vector2D tempPosition = this->GetPosition();
this->SetPosition(other->GetPosition());
other->SetPosition(tempPosition);
if(!isSwapBack)
{
this->SetSwappedCell(other);
other->SetSwappedCell(this);
}
else
{
this->SetSwappedCell(nullptr);
other->SetSwappedCell(nullptr);
}
this->SetCellState(CellState::Switching);
other->SetCellState(CellState::Switching);
} | 19.920578 | 108 | 0.720188 | [
"render"
] |
495ee2efbffcff76e8f3d6f5a1f957f6e4f5bec3 | 13,463 | cpp | C++ | tests/utilities/20.auto.ptr.cpp | isabella232/stdcxx | b0b0cab391b7b1f2d17ef4342aeee6b792bde63c | [
"Apache-2.0"
] | 53 | 2015-01-13T05:46:43.000Z | 2022-02-24T23:46:04.000Z | tests/utilities/20.auto.ptr.cpp | mann-patel/stdcxx | a22c5192f4b2a8b0b27d3588ea8f6d1faf8b037a | [
"Apache-2.0"
] | 1 | 2021-11-04T12:35:39.000Z | 2021-11-04T12:35:39.000Z | tests/utilities/20.auto.ptr.cpp | isabella232/stdcxx | b0b0cab391b7b1f2d17ef4342aeee6b792bde63c | [
"Apache-2.0"
] | 33 | 2015-07-09T13:31:00.000Z | 2021-11-04T12:12:20.000Z | /***************************************************************************
*
* 20.autoptr.cpp - test exercising [lib.auto.ptr]
*
* $Id$
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 2000-2007 Rogue Wave Software, Inc.
*
**************************************************************************/
#include <rw/_defs.h>
#if defined (__IBMCPP__) && !defined (_RWSTD_NO_IMPLICIT_INCLUSION)
// disable implicit inclusion to work around
// a limitation in IBM VisualAge 5.0.2.0 (see PR #26959)
# define _RWSTD_NO_IMPLICIT_INCLUSION
#endif
#include <memory>
/**************************************************************************/
#ifndef _RWSTD_EXPLICIT_INSTANTIATION
// explicitly instantiate
# if !defined (_RWSTD_NO_NAMESPACE) && !defined (_RWSTD_NO_HONOR_STD)
// verify that names are declared [only[ in namespace std
# define TEST_CLASS_DEF(name, Tparam) \
template class std::name Tparam \
/* void name (void *name) */
# else // if defined (_RWSTD_NO_NAMESPACE) || defined (_RWSTD_NO_HONOR_STD)
// verify that names do not collide with function argument names
# define TEST_CLASS_DEF(name, Tparam) \
template class std::name Tparam; \
void foo (void *name)
# endif // !_RWSTD_NO_NAMESPACE && !_RWSTD_NO_HONOR_STD
#else // if defined (_RWSTD_EXPLICIT_INSTANTIATION)
// classes will implicitly instantiated below
# if !defined (_RWSTD_NO_NAMESPACE) && !defined (_RWSTD_NO_HONOR_STD)
// verify that names are declared [only] in namespace std
# define TEST_CLASS_DEF(name, ignore) void name (void *name)
# else // if defined (_RWSTD_NO_NAMESPACE) || defined (_RWSTD_NO_HONOR_STD)
# define TEST_CLASS_DEF(name, ignore) void foo (void *name)
# endif // !_RWSTD_NO_NAMESPACE && !_RWSTD_NO_HONOR_STD
#endif // _RWSTD_EXPLICIT_INSTANTIATION
// auto_ptr_ref instantiated first to prevent bogus MSVC 6.0 warning C4660:
// template-class specialization 'auto_ptr_ref<int>' is already instantiated
// follows lwg issue 127
TEST_CLASS_DEF (auto_ptr_ref, <int>);
TEST_CLASS_DEF (auto_ptr, <int>);
/**************************************************************************/
#include <rw_cmdopt.h> // for rw_enabled()
#include <rw_driver.h> // for rw_assert(), rw_test(), ...
/**************************************************************************/
struct Base
{
int i_; // unique object id
static int cnt_; // object counter
static int gen_; // unique id generator
Base (): i_ (gen_++) { ++cnt_; }
~Base () {
--cnt_;
}
static void sink (std::auto_ptr<Base>) { }
};
int Base::cnt_; // Base object counter
int Base::gen_; // Base unique id generator
struct Derived: Base
{
static std::auto_ptr<Derived> source () {
return std::auto_ptr<Derived> ();
}
static void sink (std::auto_ptr<Derived>) { }
};
// helpers to verify that each class' ctor is explicit
// not defined since they must not be referenced if test is successful
void is_explicit (const std::auto_ptr<Base>&);
struct has_implicit_ctor
{
// NOT explicit
#ifndef _RWSTD_NO_NATIVE_BOOL
has_implicit_ctor (bool*) { }
#endif // _RWSTD_NO_NATIVE_BOOL
has_implicit_ctor (char*) { }
has_implicit_ctor (int*) { }
has_implicit_ctor (double*) { }
has_implicit_ctor (void**) { }
has_implicit_ctor (Base*) { }
};
void is_explicit (const has_implicit_ctor&) { }
template <class T>
void test_auto_ptr (T*, const char *tname)
{
rw_info (0, 0, 0, "std::auto_ptr<%s>", tname);
if (!rw_enabled (tname)) {
rw_note (0, 0, __LINE__, "auto_ptr<%s> test disabled", tname);
return;
}
// exercise 20.4.5, p2 - auto_ptr<> interface
typedef typename std::auto_ptr<T>::element_type element_type;
// verify that element_type is the same as T
element_type *elem = (T*)0;
// verify that default ctor is explicit
is_explicit (elem);
// verify that a member function is accessible and has the appropriate
// signature, including return type and exception specification
#define FUN(result, T, name, arg_list) do { \
result (std::auto_ptr<T>::*pf) arg_list = &std::auto_ptr<T>::name; \
_RWSTD_UNUSED (pf); \
} while (0)
#if !defined (__HP_aCC) || _RWSTD_HP_aCC_MAJOR > 5
// working around a bug in aCC (see PR #24430)
FUN (std::auto_ptr<T>&, T, operator=, (std::auto_ptr<T>&) _PTR_THROWS(()));
#endif // HP aCC > 5
FUN (T&, T, operator*, () const _PTR_THROWS (()));
#ifndef _RWSTD_NO_NONCLASS_ARROW_RETURN
FUN (T*, T, operator->, () const _PTR_THROWS (()));
#endif // _RWSTD_NO_NONCLASS_ARROW_RETURN
FUN (T*, T, get, () const _PTR_THROWS (()));
FUN (T*, T, release, () _PTR_THROWS (()));
FUN (void, T, reset, (T*) _PTR_THROWS (()));
#if !defined(__GNUG__) || __GNUG__ > 3 || __GNUG__ == 3 && __GNUC_MINOR__ > 2
// g++ 2.95.2 and HP aCC can't take the address of a template member
# if !defined (__HP_aCC) || _RWSTD_HP_aCC_MAJOR > 5
// SunPro incorrectly warns here (see PR #27276)
FUN (std::auto_ptr<Base>&, Base,
operator=, (std::auto_ptr<Derived>&) _PTR_THROWS (()));
// SunPro 5.4 can't decide between a ctor template
// and a conversion operator (see PR #24476)
# if !defined (__SUNPRO_CC) || __SUNPRO_CC > 0x540
# if !defined (_RWSTD_MSVC) || _RWSTD_MSVC > 1310
FUN (std::auto_ptr_ref<Base>, Derived,
operator std::auto_ptr_ref<Base>, () _PTR_THROWS (()));
FUN (std::auto_ptr<Base>, Derived,
operator std::auto_ptr<Base>, () _PTR_THROWS (()));
# endif // MSVC > 7.1
# endif // SunPro > 5.4
# endif // HP aCC > 5
#endif // gcc > 3.2
rw_info (0, 0, 0, "[lib.auto.ptr.cons]");
T *pt = new T ();
// 20.4.5.1, p1
std::auto_ptr<T> ap1 (pt);
rw_assert (pt == ap1.get (), 0, __LINE__,
"auto_ptr<%s>::auto_ptr (%1$s*)", tname);
// 20.4.5.1, p2
std::auto_ptr<T> ap2 (ap1);
rw_assert (0 == ap1.get (), 0, __LINE__,
"auto_ptr<%s>::auto_ptr (auto_ptr&", tname);
rw_assert (pt == ap2.get (), 0, __LINE__,
"auto_ptr<%s>::auto_ptr (auto_ptr&)", tname);
// 20.4.5.1, p7, 8, 9
ap1 = ap2;
rw_assert (0 == ap2.get (), 0, __LINE__,
"auto_ptr<%s>::operator= (auto_ptr&)", tname);
rw_assert (pt == ap1.get (), 0, __LINE__,
"auto_ptr<%s>::operator= (auto_ptr&)", tname);
rw_info (0, 0, 0, "[lib.auto.ptr.members]");
// 20.4.5.2, p2
rw_assert (*ap1.get () == ap1.operator*(), 0, __LINE__,
"auto_ptr<%s>::operator*()", tname);
// 20.4.5.2, p3
rw_assert (ap1.get () == ap1.operator->(), 0, __LINE__,
"auto_ptr<%s>::operator->()", tname);
// 20.4.5.2, p4
rw_assert (pt == ap1.get (), 0, __LINE__,
"auto_ptr<%s>::get ()", tname);
// 20.4.5.2, p5, 6
rw_assert (pt == ap1.release () && 0 == ap1.get (), 0, __LINE__,
"auto_ptr<%s>::release ()", tname);
// 20.4.5.2, p7
ap1.reset (pt);
rw_assert (pt == ap1.get (), 0, __LINE__,
"auto_ptr<%s>::reset ()", tname);
}
/**************************************************************************/
static void
test_auto_ptr_void ()
{
// note that specializing auto_ptr on void is undefined
// due to 17.4.3.6, p2; this is an extension of this
// implementation
rw_info (0, 0, 0, "std::auto_ptr<void> [extension]");
std::auto_ptr<void> ap1;
std::auto_ptr<void> ap2 ((void*)0);
std::auto_ptr<void> ap3 (ap2);
ap1 = ap1;
ap1.operator= (ap1);
#if !defined (__HP_aCC) || 6 <= _RWSTD_HP_aCC_MAJOR
// working around an HP aCC 3 and 5 bug (STDCXX-655)
ap1.operator=<void>(ap1);
#endif // !HP aCC or HP aCC 6 and better
std::auto_ptr<int> ap4;
ap1 = ap4;
ap1.operator= (ap4);
ap1.operator=<int>(ap4);
// operator*() cannot be instantiated
void* pv;
pv = ap1.operator->();
pv = ap1.get ();
pv = ap1.release ();
ap1.reset ();
ap1.reset (pv);
#if !defined (__HP_aCC) || 6 <= _RWSTD_HP_aCC_MAJOR
// working around an HP aCC 3 and 5 bug (STDCXX-656)
const std::auto_ptr_ref<void> ar = ap1.operator std::auto_ptr_ref<void>();
const std::auto_ptr<void> ap5 = ap1.operator std::auto_ptr<void>();
_RWSTD_UNUSED (ar);
_RWSTD_UNUSED (ap5);
#endif // !HP aCC or HP aCC 6 and better
}
/**************************************************************************/
// exercise 20.4.5.4
static std::auto_ptr<Derived>
test_auto_ptr_conversions ()
{
rw_info (0, 0, 0, "[lib.auto.ptr.conv]");
// 20.4.5.1, p4, 5, 6
Derived *pd = new Derived;
std::auto_ptr<Derived> ap1 (pd);
rw_assert (pd == ap1.get (), 0, __LINE__,
"auto_ptr::auto_ptr ()");
std::auto_ptr<Base> ap2 (ap1);
rw_assert (0 == ap1.get (), 0, __LINE__,
"auto_ptr<Base>::auto_ptr(auto_ptr<Derived>&)");
rw_assert (_RWSTD_STATIC_CAST (Base*, pd) == ap2.get (), 0, __LINE__,
"auto_ptr<Base>::auto_ptr(auto_ptr<Derived>&)");
ap2.reset (pd);
// 20.4.5.2, p7 - must not delete owning pointer
ap2.reset (pd);
rw_assert (pd == ap2.get (), 0, __LINE__, "auto_ptr::reset ()");
pd = new Derived;
ap2.reset (pd); // must delete owning pointer
rw_assert (pd == ap2.get (), 0, __LINE__, "auto_ptr::reset ()");
// 20.4.5.3, p1, 2, 3 - creates an auto_ptr_ref
pd = new Derived;
std::auto_ptr<Base> ap3 =
std::auto_ptr<Base>(std::auto_ptr<Derived>(pd));
rw_assert ((Base*)pd == ap3.get (), 0, __LINE__,
"auto_ptr<>::auto_ptr(std::auto_ptr_ref)");
#if !defined (__HP_aCC) || _RWSTD_HP_aCC_MAJOR > 5
pd = new Derived;
std::auto_ptr<Derived> ap4 (pd);
ap3 = std::auto_ptr<Base> (ap4);
rw_assert (0 == ap4.get () && (Base*)pd == ap3.get (), 0, __LINE__,
"auto_ptr<>::operator auto_ptr<>()");
#endif // HP aCC > 5
{
// see CWG issue 84 for some background on the sequence below
// http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/cwg_defects.html#84
std::auto_ptr<Derived> pd1 (Derived::source ());
std::auto_ptr<Derived> pd2 (pd1);
#if !defined (__HP_aCC) || _RWSTD_HP_aCC_MAJOR > 5
Derived::sink (Derived::source ());
#endif // HP aCC > 5
pd1 = pd2;
pd1 = Derived::source();
std::auto_ptr<Base> pb1 (Derived::source ());
std::auto_ptr<Base> pb2 (pd1);
// conversion sequence:
// 1. auto_ptr<Derived>::operator auto_ptr<Base>() [UDC]
// 2. auto_ptr<Base>::operator auto_ptr_ref<Base>() [UDC]
// 3. auto_ptr<Base>(auto_ptr_ref<Base>) [UDC]
// since the conversion sequence involves more than one UDC
// (User-Defined Conversion), it is illegal
// Base::sink (Derived::source ());
pb1 = pd2;
pb1 = Derived::source ();
return pd1;
}
}
/**************************************************************************/
static int rw_opt_no_conversions; // for --no-conversions
static int
run_test (int, char**)
{
#ifndef _RWSTD_NO_NATIVE_BOOL
test_auto_ptr ((bool*)0, "bool");
#endif // _RWSTD_NO_NATIVE_BOOL
test_auto_ptr ((char*)0, "char");
test_auto_ptr ((int*)0, "int");
test_auto_ptr ((double*)0, "double");
test_auto_ptr ((void**)0, "void*");
int count = Base::cnt_;
// exercise 20.4.5.4
if (rw_opt_no_conversions)
rw_note (0, 0, 0, "conversions test disabled");
else
test_auto_ptr_conversions ();
// verify that no objects leaked
rw_assert (count == Base::cnt_, 0, __LINE__,
"autoptr leaked %d objects", Base::cnt_ - count);
if (!rw_enabled ("void"))
rw_note (0, 0, 0, "auto_ptr<void> test disabled");
else
test_auto_ptr_void ();
return 0;
}
/**************************************************************************/
int main (int argc, char *argv[])
{
return rw_test (argc, argv, __FILE__,
"lib.auto.ptr",
0 /* no comment */,
run_test,
"|-no-conversions#",
&rw_opt_no_conversions,
(void*)0 /* sentinel */);
}
| 28.952688 | 79 | 0.561019 | [
"object"
] |
4962460a7e497468f743998047f56812b6b785b4 | 2,340 | cc | C++ | adapters/omnetpp/seed/parser/distribution.cc | kit-tm/seed | c6d4eaffbe25615b396aeabeae7305b724260d92 | [
"BSD-2-Clause"
] | null | null | null | adapters/omnetpp/seed/parser/distribution.cc | kit-tm/seed | c6d4eaffbe25615b396aeabeae7305b724260d92 | [
"BSD-2-Clause"
] | null | null | null | adapters/omnetpp/seed/parser/distribution.cc | kit-tm/seed | c6d4eaffbe25615b396aeabeae7305b724260d92 | [
"BSD-2-Clause"
] | null | null | null | #include "omnetpp.h"
#include "distribution.h"
#include "internal.h"
bool parseArray(
std::vector<std::string>& args,
std::vector<std::pair<double, std::string>>& res
)
{
for (arg : args) {
double number;
std::string unit;
if (!parseUnitNumber(arg, number, unit)) return false;
res.push_back(std::make_pair(number, unit));
}
return true;
}
bool parseDistribtion(
std::string expr,
std::string unit,
std::function<double(double)>& res
)
{
Term term;
std::string nv;
std::vector<std::string> _args;
if (!parseTerm(expr, term, nv, _args))
return false;
std::vector<std::pair<double, std::string>> args;
if (term == FUNCTION)
{
if (!parseArray(_args, args)) return false;
}
else if (term == VARIABLE)
{
double number;
std::string unit;
if (!parseUnitNumber(nv, number, unit)) return false;
args.push_back(std::make_pair(number, unit));
nv = "interval";
} else return false;
if (nv == "interval")
{
if (args.size() != 1) return false;
if (args[0].second != unit) return false;
double interval = args[0].first;
res = [interval](double rand) {
return interval;
};
}
else if (nv == "uniform")
{
if (args.size() != 2) return false;
if (args[0].second != unit) return false;
if (args[1].second != unit) return false;
double lower = args[0].first;
double upper = args[1].first;
res = [lower, upper](double rand) {
return lower + (upper - lower) * rand;
};
}
else if (nv == "exp")
{
if (args.size() != 1) return false;
if (args[0].second != unit) return false;
double invlambda = args[0].first;
res = [invlambda](double rand) {
return -log(rand) * invlambda;
};
}
else if (nv == "pareto")
{
if (args.size() != 2) return false;
if (args[0].second != unit) return false;
if (args[1].second != "") return false;
double scale = args[0].first;
double shape = args[1].first;
res = [scale, shape](double rand) {
return scale / pow(rand, 1/shape);
};
}
else
return false;
return true;
}
| 26 | 62 | 0.535043 | [
"shape",
"vector"
] |
49670a9afa1c81b56db9a51bb5f164ca1d5a343a | 8,946 | cxx | C++ | ds/security/tools/ksetup/strings.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/tools/ksetup/strings.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/tools/ksetup/strings.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
STRINGS.CXX
Copyright (C) 1999 Microsoft Corporation, all rights reserved.
DESCRIPTION: MultiString class
Created, Dec 29, 1999 by DavidCHR.
CONTENTS: CMULTISTRING
WriteToRegistry
ReadFromRegistry
RemoveString
AddString
~CMULTISTRING
--*/
#include "everything.hxx"
/*++**************************************************************
NAME: CMULTISTRING
constructor for the class.
**************************************************************--*/
CMULTISTRING::
CMULTISTRING( VOID ) {
this->cEntries = 0;
this->pEntries = NULL;
this->TotalStringCount = 0;
}
/*++**************************************************************
NAME: ~CMULTISTRING
destructor for the class. Frees any strings still around.
**************************************************************--*/
CMULTISTRING::
~CMULTISTRING( VOID ) {
ULONG i;
if ( this->cEntries &&
this->pEntries ) {
for ( i = 0 ;
i < this->cEntries ;
i ++ ) {
if ( this->pEntries[ i ] ) {
free( this->pEntries[ i ] );
}
}
free( this->pEntries );
}
}
/*++**************************************************************
NAME: AddString
adds a string to the end of string table
MODIFIES: this->pEntries, this->cEntries
TAKES: String -- string to add (duplicated)
RETURNS: TRUE when the function succeeds.
FALSE otherwise.
LOGGING: printf on failure
CREATED: Dec 29, 1999
LOCKING: none
CALLED BY: anyone
FREE WITH: ~CMULTISTRING
**************************************************************--*/
BOOL CMULTISTRING::
AddString( IN LPWSTR String ) {
LPWSTR *tempString;
tempString = (LPWSTR *) realloc( this->pEntries,
( this->cEntries + 1 ) *
sizeof( LPWSTR ) );
if ( tempString ) {
this->pEntries = tempString;
tempString[ this->cEntries ] = _wcsdup( String );
if ( tempString[ this->cEntries ] ) {
this->cEntries ++;
this->TotalStringCount += wcslen( String );
return TRUE;
} else {
printf( "Cannot add string %ld (%ws). Not enough memory.\n",
this->cEntries,
String );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
}
// don't free the string.
}
return FALSE;
}
/*++**************************************************************
NAME: RemoveString
removes a string from the list
MODIFIES: this->pEntries, this->cEntries
TAKES: String -- string to remove (case-insensitive)
RETURNS: TRUE when the function succeeds.
FALSE otherwise.
LOGGING: printf if the string doesn't exist
CREATED: Dec 29, 1999
LOCKING: none
CALLED BY: anyone
FREE WITH: n/a -- no resources are allocated
**************************************************************--*/
BOOL CMULTISTRING::
RemoveString( IN LPWSTR String ) {
ULONG i, DeleteCount = 0;
BOOL ret = TRUE;
// first, go through and free the matches
for ( i = 0 ;
i < this->cEntries ;
i ++ ) {
if ( _wcsicmp( String,
this->pEntries[ i ] ) == 0 ) {
// match. Free it.
free( this->pEntries[ i ] );
this->pEntries[ i ] = NULL;
DeleteCount++;
} else if ( DeleteCount > 0 ) {
/* If we've deleted stuff already, and we're not deleting
this one, then move this entry earlier in the array. */
this->pEntries[ i - DeleteCount ] = this->pEntries[ i ];
#if DBG
/* For the sake of debugging, set this to a known
bad value. */
#ifdef _WIN64 // to avoid ia64 compile-time error, give it a qword for a pointer
this->pEntries[ i ] = (LPWSTR) 0xdeadbeefdeadbeef;
#else
this->pEntries[ i ] = (LPWSTR) ULongToPtr( 0xdeadbeef );
#endif // _WIN64
#endif // DBG
}
}
if ( DeleteCount ) {
this->cEntries -= DeleteCount;
this->TotalStringCount -= DeleteCount * wcslen( String );
/* We could realloc the array down to the correct cEntries now,
but there's no pressing need. */
} else {
printf( "No match for %ws.\n",
String );
ret = FALSE;
}
return ret;
}
/*++**************************************************************
NAME: ReadFromRegistry
reads a string vector from a REG_MULTI_SZ in the registry
MODIFIES: this, indirectly
TAKES: hKey -- handle to open parent key
ValueName -- value to read
RETURNS: TRUE when the function succeeds.
FALSE otherwise.
LOGGING: printf on failure
CREATED: Dec 29, 1999
LOCKING: none
CALLED BY: anyone
FREE WITH: n/a -- no resources are allocated
**************************************************************--*/
BOOL CMULTISTRING::
ReadFromRegistry( IN HKEY hKey,
IN LPWSTR ValueName ) {
ULONG RegistrySize = 0;
ULONG cEntries = 0;
LPWSTR RegistryStrings;
LPWSTR *StringTable = NULL;
LPWSTR *pTempTable, Cursor;
DWORD WinError;
DWORD Type;
BOOL ret = FALSE;
WinError = RegQueryValueEx( hKey,
ValueName,
NULL,
&Type,
NULL,
&RegistrySize );
if (WinError == ERROR_SUCCESS) {
RegistryStrings = (LPWSTR) malloc( RegistrySize );
if ( RegistryStrings ) {
WinError = RegQueryValueEx( hKey,
ValueName,
NULL,
&Type,
(PUCHAR) RegistryStrings,
&RegistrySize );
if (WinError == ERROR_SUCCESS) {
ret = TRUE;
if ( RegistrySize > 2 * sizeof( WCHAR ) ) { /* 2 == two nulls
which would indicate
that the value is
empty. */
/* Now, allocate a string vector, counting the strings
as we go. */
for ( Cursor = RegistryStrings ;
*Cursor != L'\0' ;
Cursor = wcschr( Cursor, '\0' ) +1 ) {
if ( !this->AddString( Cursor ) ) {
ret = FALSE;
break;
}
}
} // else the value was empty -- nothing to do.
} else {
printf("Failed to query value %ws: 0x%x\n",
ValueName,
WinError );
}
free( RegistryStrings );
} else {
printf( "Failed to allocate buffer of size (0x%x)\n",
RegistrySize );
}
} else if ( WinError == ERROR_FILE_NOT_FOUND ) {
/* The key doesn't exist-- no mappings. */
// WinError = ERROR_SUCCESS;
ret = TRUE;
} else {
/* an actual error. */
printf( "Failed to query %ws: 0x%x\n",
ValueName,
WinError );
}
return ret;
}
/*++**************************************************************
NAME: WriteToRegistry
dumps the string vector to a REG_MULTI_SZ in the registry
MODIFIES: the registry only
TAKES: hKey -- handle to open parent key
ValueName -- value to write
RETURNS: TRUE when the function succeeds.
FALSE otherwise.
LOGGING: printf on failure
CREATED: Dec 29, 1999
LOCKING: none
CALLED BY: anyone
FREE WITH: n/a -- no resources are allocated
**************************************************************--*/
BOOL CMULTISTRING::
WriteToRegistry( IN HKEY hKey,
IN LPWSTR ValueName ) {
LPWSTR StringVector;
ULONG StringIndex, EntryIndex, Length, VectorLength;
DWORD dwErr;
BOOL ret = FALSE;
VectorLength = ( this->TotalStringCount + // string characters
this->cEntries + // null characters
2 // trailing nulls
) * sizeof( WCHAR );
StringVector = (LPWSTR) malloc( VectorLength );
if ( !StringVector ) {
printf( "Failed to allocate string blob to write %ws.\n",
ValueName );
} else {
for ( StringIndex = EntryIndex = 0 ;
EntryIndex < this->cEntries ;
EntryIndex++ ) {
Length = wcslen( this->pEntries[ EntryIndex ] ) +1; /* include the
null */
memcpy( StringVector + StringIndex, // to
this->pEntries[ EntryIndex ], // from
Length * sizeof( WCHAR ) ); // byte count
StringIndex += Length;
}
StringVector[ StringIndex ] = L'\0';
StringVector[ StringIndex+1 ] = L'\0';
dwErr = RegSetValueExW( hKey,
ValueName,
0, // mbz
REG_MULTI_SZ,
(PBYTE) StringVector,
VectorLength );
free( StringVector );
if ( dwErr != ERROR_SUCCESS ) {
printf( "Failed to write %ws value to registry: 0x%x.\n",
ValueName,
dwErr );
} else {
ret = TRUE;
}
}
return ret;
}
| 21.249406 | 81 | 0.501453 | [
"vector"
] |
4968db08442f92324f58698392ae6982b692db9a | 29,475 | cpp | C++ | src/pcc/pcc_utility_manager.cpp | Alexyali/PCC-Uspace | 30c2cfe1e276646aae03751b9df91889afea42dd | [
"BSD-3-Clause"
] | 98 | 2018-04-10T22:14:45.000Z | 2022-03-11T07:02:18.000Z | src/pcc/pcc_utility_manager.cpp | Alexyali/PCC-Uspace | 30c2cfe1e276646aae03751b9df91889afea42dd | [
"BSD-3-Clause"
] | 22 | 2018-04-10T13:53:33.000Z | 2021-10-11T05:40:18.000Z | src/pcc/pcc_utility_manager.cpp | Alexyali/PCC-Uspace | 30c2cfe1e276646aae03751b9df91889afea42dd | [
"BSD-3-Clause"
] | 57 | 2018-05-18T14:30:23.000Z | 2022-03-20T14:05:07.000Z | #include "pcc_utility_manager.h"
#include "math.h"
#include <assert.h>
#include <iostream>
//#include "third_party/pcc_quic/pcc_utility_manager.h"
//#include "third_party/quic/core/congestion_control/rtt_stats.h"
// namespace quic {
namespace {
const QuicByteCount kMaxPacketSize = 1500;
// Number of bits per byte.
const size_t kBitsPerByte = 8;
const size_t kRttHistoryLen = 6;
// Tolerance of loss rate by Allegro utility function.
const float kLossTolerance = 0.05f;
// Coefficeint of the loss rate term in Allegro utility function.
const float kLossCoefficient = -1000.0f;
// Coefficient of RTT term in Allegro utility function.
const float kRTTCoefficient = -200.0f;
// Exponent of sending rate contribution term in Vivace utility function.
const float kSendingRateExponent = 0.9f;
// Coefficient of loss penalty term in Vivace utility function.
const float kVivaceLossCoefficient = 11.35f;
// Coefficient of latency penalty term in Vivace utility function.
const float kLatencyCoefficient = 900.0f;
// Coefficient of rtt deviation term in Scavenger utility function.
const float kRttDeviationCoefficient = 0.0015f;
// The factor for sending rate transform in hybrid utility function.
const float kHybridUtilityRateTransformFactor = 0.1f;
// The update rate for moving average variable.
const float kAlpha = 0.1f;
// The order of magnitude that distinguishes abnormal sample.
const float kBeta = 100.0f;
// The threshold for ratio of monitor interval count, above which moving average
// of trending RTT metrics (gradient and deviation) would be reset.
const float kTrendingResetIntervalRatio = 0.95f;
// Number of deviation above/below average trending gradient used for RTT
//inflation tolerance for primary and scavenger senders.
const float kInflationToleranceGainHigh = 2.0f;
const float kInflationToleranceGainLow = 2.0f;
const size_t kLostPacketTolerance = 10;
} // namespace
PccUtilityManager::PccUtilityManager()
: utility_tag_("Allegro"),
effective_utility_tag_("Allegro"),
lost_bytes_tolerance_quota_(kMaxPacketSize * kLostPacketTolerance),
avg_mi_rtt_dev_(-1.0),
dev_mi_rtt_dev_(-1.0),
min_rtt_(-1.0),
avg_trending_gradient_(-1.0),
min_trending_gradient_(-1.0),
dev_trending_gradient_(-1.0),
last_trending_gradient_(-1.0),
avg_trending_dev_(-1.0),
min_trending_dev_(-1.0),
dev_trending_dev_(-1.0),
last_trending_dev_(-1.0),
ratio_inflated_mi_(0),
ratio_fluctuated_mi_(0),
is_rtt_inflation_tolerable_(true),
is_rtt_dev_tolerable_(true) {}
const std::string PccUtilityManager::GetUtilityTag() const {
return utility_tag_;
}
const std::string PccUtilityManager::GetEffectiveUtilityTag() const {
return effective_utility_tag_;
}
void PccUtilityManager::SetUtilityTag(std::string utility_tag) {
utility_tag_ = utility_tag;
effective_utility_tag_ = utility_tag;
std::cerr << "Using Utility Function: " << utility_tag_ << std::endl;
}
void PccUtilityManager::SetEffectiveUtilityTag(std::string utility_tag) {
effective_utility_tag_ = utility_tag;
}
void* PccUtilityManager::GetUtilityParameter(int parameter_index) const {
return utility_parameters_.size() > parameter_index
? utility_parameters_[parameter_index]
: (new float(0.0f));
}
void PccUtilityManager::SetUtilityParameter(void* param) {
if (utility_tag_ == "HybridAllegro" || utility_tag_ == "HybridVivace" ||
utility_tag_ == "Proportional" || utility_tag_ == "Scavenger" ||
utility_tag_ == "RateLimiter" || utility_tag_ == "TEST" ||
utility_tag_ == "Hybrid") {
utility_parameters_.push_back(new float(*(float *)param));
std::cerr << "Update Utility Parameter: " << (*(float *)param) << std::endl;
}
}
void PccUtilityManager::PrepareStatistics(const MonitorInterval* interval) {
PreProcessing(interval);
ComputeSimpleMetrics(interval);
ComputeApproxRttGradient(interval);
ComputeRttGradient(interval);
ComputeRttDeviation(interval);
ComputeRttGradientError(interval);
DetermineToleranceGeneral();
ProcessRttTrend(interval);
}
float PccUtilityManager::CalculateUtility(const MonitorInterval* interval,
QuicTime::Delta event_time) {
// The caller should guarantee utility of this interval is available.
assert(interval->first_packet_sent_time !=
interval->last_packet_sent_time);
PrepareStatistics(interval);
float utility = 0.0;
if (utility_tag_ == "Allegro") {
utility = CalculateUtilityAllegro(interval);
} else if (utility_tag_ == "Vivace") {
utility = CalculateUtilityVivace(interval);
} else if (utility_tag_ == "Proportional") {
float latency_coefficient = *(float *)(utility_parameters_[0]);
float loss_coefficient = *(float *)(utility_parameters_[1]);
utility = CalculateUtilityProportional(interval, latency_coefficient,
loss_coefficient);
} else if (utility_tag_ == "Scavenger") {
float rtt_deviation_coefficient = *(float *)(utility_parameters_[0]);
utility = CalculateUtilityScavenger(interval, rtt_deviation_coefficient);
} else if (utility_tag_ == "HybridAllegro") {
float bound = *(float *)(utility_parameters_[0]);
utility = CalculateUtilityHybridAllegro(interval, bound);
} else if (utility_tag_ == "HybridVivace") {
float bound = *(float *)utility_parameters_[0];
utility = CalculateUtilityHybridVivace(interval, bound);
} else if (utility_tag_ == "RateLimiter") {
float bound = *(float *)utility_parameters_[0];
float rate_limiter_parameter = 0.9 / pow(bound, 0.1);
utility = CalculateUtilityRateLimiter(interval, rate_limiter_parameter);
} else if (utility_tag_ == "Hybrid") {
float rate_bound = *(float *)utility_parameters_[0];
utility = CalculateUtilityHybrid(interval, rate_bound);
} else if (utility_tag_ == "TEST") {
float latency_coefficient = *(float *)(utility_parameters_[0]);
float loss_coefficient = *(float *)(utility_parameters_[1]);
utility = CalculateUtilityTEST(interval, latency_coefficient,
loss_coefficient);
} else {
std::cerr << "Unrecognized utility tag, use Allegro instead" << std::endl;
utility = CalculateUtilityAllegro(interval);
}
#ifdef PER_MI_DEBUG_
std::cerr << event_time.ToMicroseconds() / 1000000.0 << " "
<< interval->sending_rate.ToKBitsPerSecond() << " "
<< interval_stats_.actual_sending_rate_mbps << " "
<< interval_stats_.avg_rtt << " "
<< interval_stats_.min_rtt << " "
<< interval_stats_.max_rtt << " "
<< interval_stats_.max_rtt - interval_stats_.min_rtt << " "
<< interval->rtt_on_monitor_end.ToMicroseconds() << " "
<< interval_stats_.rtt_dev << " "
<< avg_mi_rtt_dev_ << " "
<< interval_stats_.rtt_dev / interval_stats_.avg_rtt << " "
<< interval_stats_.approx_rtt_gradient << " "
<< interval_stats_.loss_rate << " "
<< utility << " "
<< std::abs(interval_stats_.rtt_gradient) << " "
<< interval_stats_.rtt_gradient_error << " "
<< std::abs(interval_stats_.rtt_gradient) -
interval_stats_.rtt_gradient_error << " "
<< interval_stats_.trending_gradient << " "
<< avg_trending_gradient_ << " "
<< dev_trending_gradient_ << " "
<< avg_trending_gradient_ - 2 * dev_trending_gradient_ << " "
<< avg_trending_gradient_ + 2 * dev_trending_gradient_;
if (utility_tag_ == "Scavenger") {
std::cerr << " " << CalculateUtilityVivace(interval);
}
std::cerr << std::endl;
#endif
return utility;
}
float PccUtilityManager::CalculateUtilityAllegro(
const MonitorInterval* interval) {
if (interval_stats_.rtt_ratio >
1.0 - interval->rtt_fluctuation_tolerance_ratio &&
interval_stats_.rtt_ratio <
1.0 + interval->rtt_fluctuation_tolerance_ratio) {
interval_stats_.rtt_ratio = 1.0;
}
float latency_penalty = 1.0 -
1.0 / (1.0 + exp(kRTTCoefficient * (1.0 - interval_stats_.rtt_ratio)));
float loss_penalty =
1.0 - 1.0 / (1.0 + exp(kLossCoefficient *
(interval_stats_.loss_rate - kLossTolerance)));
float bytes_acked = static_cast<float>(interval->bytes_acked);
float bytes_lost = static_cast<float>(interval->bytes_lost);
return (bytes_acked / interval_stats_.interval_duration * loss_penalty *
latency_penalty -
bytes_lost / interval_stats_.interval_duration) * 1000.0;
}
float PccUtilityManager::CalculateUtilityVivace(
const MonitorInterval* interval) {
return CalculateUtilityProportional(interval, kLatencyCoefficient,
kVivaceLossCoefficient);
}
float PccUtilityManager::CalculateUtilityProportional(
const MonitorInterval* interval,
float latency_coefficient,
float loss_coefficient) {
float sending_rate_contribution =
pow(interval_stats_.actual_sending_rate_mbps, kSendingRateExponent);
float rtt_gradient =
is_rtt_inflation_tolerable_ ? 0.0 : interval_stats_.rtt_gradient;
if (interval->rtt_fluctuation_tolerance_ratio > 50.0 &&
std::abs(rtt_gradient) < 1000.0 / interval_stats_.interval_duration) {
rtt_gradient = 0.0;
}
if (rtt_gradient < 0) {
rtt_gradient = 0.0;
}
/*rtt_gradient =
static_cast<float>(static_cast<int>(rtt_gradient * 100.0)) / 100.0;*/
/*if ((rtt_gradient > -1.0 * interval->rtt_fluctuation_tolerance_ratio &&
rtt_gradient < interval->rtt_fluctuation_tolerance_ratio) ||
interval_stats_.actual_sending_rate_mbps < 2) {
rtt_gradient =
// static_cast<float>(static_cast<int>(rtt_gradient * 100.0)) / 100.0;
}*/
float latency_penalty = latency_coefficient * rtt_gradient *
interval_stats_.actual_sending_rate_mbps;
float loss_penalty = loss_coefficient * interval_stats_.loss_rate *
interval_stats_.actual_sending_rate_mbps;
return sending_rate_contribution - latency_penalty - loss_penalty;
}
float PccUtilityManager::CalculateUtilityScavenger(
const MonitorInterval* interval,
float rtt_variance_coefficient) {
float sending_rate_contribution =
pow(interval_stats_.actual_sending_rate_mbps, kSendingRateExponent);
float loss_penalty = kVivaceLossCoefficient * interval_stats_.loss_rate *
interval_stats_.actual_sending_rate_mbps;
float rtt_gradient =
is_rtt_inflation_tolerable_ ? 0.0 : interval_stats_.rtt_gradient;
if (interval->rtt_fluctuation_tolerance_ratio > 50.0 &&
std::abs(rtt_gradient) < 1000.0 / interval_stats_.interval_duration) {
rtt_gradient = 0.0;
}
if (rtt_gradient < 0) {
rtt_gradient = 0.0;
}
float latency_penalty = kLatencyCoefficient * rtt_gradient *
interval_stats_.actual_sending_rate_mbps;
float rtt_dev = is_rtt_dev_tolerable_ ? 0.0 : interval_stats_.rtt_dev;
if (interval->rtt_fluctuation_tolerance_ratio > 50.0) {
rtt_dev = 0.0;
}
float rtt_dev_penalty = rtt_variance_coefficient * rtt_dev *
interval_stats_.actual_sending_rate_mbps;
return sending_rate_contribution - loss_penalty -
latency_penalty - rtt_dev_penalty;
}
float PccUtilityManager::CalculateUtilityHybridAllegro(
const MonitorInterval* interval,
float bound) {
float allegro_utility = CalculateUtilityAllegro(interval);
if (interval_stats_.actual_sending_rate_mbps < bound) {
return allegro_utility;
} else {
float perfect_utility = CalculatePerfectUtilityAllegro(
interval_stats_.actual_sending_rate_mbps);
float bounded_sending_rate_mbps = bound +
(interval_stats_.actual_sending_rate_mbps - bound) *
kHybridUtilityRateTransformFactor;
float bounded_perfect_utility =
CalculatePerfectUtilityAllegro(bounded_sending_rate_mbps);
return bounded_perfect_utility * (allegro_utility / perfect_utility);
}
}
float PccUtilityManager::CalculateUtilityHybridVivace(
const MonitorInterval* interval,
float bound) {
float vivace_utility = CalculateUtilityVivace(interval);
if (interval_stats_.actual_sending_rate_mbps < bound) {
return vivace_utility;
} else {
float perfect_utility = CalculatePerfectUtilityVivace(
interval_stats_.actual_sending_rate_mbps);
float bounded_sending_rate_mbps = bound +
(interval_stats_.actual_sending_rate_mbps - bound) *
kHybridUtilityRateTransformFactor;
float bounded_perfect_utility =
CalculatePerfectUtilityVivace(bounded_sending_rate_mbps);
return bounded_perfect_utility + vivace_utility - perfect_utility;
}
}
float PccUtilityManager::CalculateUtilityHybridVivace2(
const MonitorInterval* interval,
float bound) {
float vivace_utility = CalculateUtilityVivace(interval);
if (interval_stats_.actual_sending_rate_mbps < bound) {
return vivace_utility;
} else {
float perfect_utility = CalculatePerfectUtilityVivace(
interval_stats_.actual_sending_rate_mbps);
float bounded_sending_rate_mbps = bound +
(interval_stats_.actual_sending_rate_mbps - bound) *
kHybridUtilityRateTransformFactor;
float bounded_perfect_utility =
CalculatePerfectUtilityVivace(bounded_sending_rate_mbps);
return bounded_perfect_utility * (vivace_utility / perfect_utility);
}
}
float PccUtilityManager::CalculateUtilityRateLimiter(
const MonitorInterval* interval,
float rate_limiter_parameter) {
float vivace_utility = CalculateUtilityVivace(interval);
float rate_penalty =
rate_limiter_parameter * interval_stats_.actual_sending_rate_mbps;
return vivace_utility - rate_penalty;
}
float PccUtilityManager::CalculateUtilityHybrid(
const MonitorInterval* interval,
float rate_bound) {
if (interval_stats_.actual_sending_rate_mbps < rate_bound) {
return CalculateUtilityVivace(interval);
} else {
return CalculateUtilityScavenger(interval, kRttDeviationCoefficient);
}
}
float PccUtilityManager::CalculateUtilityTEST(
const MonitorInterval* interval,
float latency_coefficient,
float loss_coefficient) {
return CalculateUtilityVivace(interval);
}
float PccUtilityManager::CalculatePerfectUtilityAllegro(
float sending_rate_mbps) {
float rtt_ratio = 1.0;
float latency_penalty =
1.0 - 1.0 / (1.0 + exp(kRTTCoefficient * (1.0 - rtt_ratio)));
float loss_rate = 0.0f;
float loss_penalty =
1.0 - 1.0 / (1.0 + exp(kLossCoefficient * (loss_rate - kLossTolerance)));
float sending_rate_bype_per_usec =
sending_rate_mbps / static_cast<float>(kBitsPerByte);
return (sending_rate_bype_per_usec * loss_penalty * latency_penalty) * 1000.0;
}
float PccUtilityManager::CalculatePerfectUtilityVivace(
float sending_rate_mbps) {
return pow(sending_rate_mbps, kSendingRateExponent);
}
void PccUtilityManager::PreProcessing(const MonitorInterval* interval) {
interval_stats_.marked_lost_bytes = 0;
/*size_t num_lost_samples = interval->lost_packet_samples.size();
for (size_t i = 0; i < num_lost_samples; ++i) {
if ((i == 0 || interval->lost_packet_samples[i - 1].packet_number <
interval->lost_packet_samples[i].packet_number - 1) &&
(i == num_lost_samples - 1 ||
interval->lost_packet_samples[i + 1].packet_number >
interval->lost_packet_samples[i].packet_number + 1)) {
interval_stats_.marked_lost_bytes +=
interval->lost_packet_samples[i].bytes;
}
}
if (lost_bytes_tolerance_quota_ > 0) {
int64_t tolerated_lost_bytes =
std::min(lost_bytes_tolerance_quota_,
interval->bytes_lost - interval_stats_.marked_lost_bytes);
lost_bytes_tolerance_quota_ -= tolerated_lost_bytes;
interval_stats_.marked_lost_bytes += tolerated_lost_bytes;
}*/
}
void PccUtilityManager::ComputeSimpleMetrics(const MonitorInterval* interval) {
// Add the transfer time of the last packet in the monitor interval when
// calculating monitor interval duration.
interval_stats_.interval_duration = static_cast<float>(
(interval->last_packet_sent_time - interval->first_packet_sent_time +
interval->sending_rate.TransferTime(kMaxPacketSize)).ToMicroseconds());
interval_stats_.rtt_ratio =
static_cast<float>(interval->rtt_on_monitor_start.ToMicroseconds()) /
static_cast<float>(interval->rtt_on_monitor_end.ToMicroseconds());
interval_stats_.loss_rate =
static_cast<float>(interval->bytes_lost -
interval_stats_.marked_lost_bytes) /
static_cast<float>(interval->bytes_sent);
interval_stats_.actual_sending_rate_mbps =
static_cast<float>(interval->bytes_sent) *
static_cast<float>(kBitsPerByte) / interval_stats_.interval_duration;
size_t num_rtt_samples = interval->packet_rtt_samples.size();
if (num_rtt_samples > 1) {
float ack_duration = static_cast<float>(
(interval->packet_rtt_samples[num_rtt_samples - 1].ack_timestamp -
interval->packet_rtt_samples[0].ack_timestamp).ToMicroseconds());
interval_stats_.ack_rate_mbps =
static_cast<float>(interval->bytes_acked - kMaxPacketSize) *
static_cast<float>(kBitsPerByte) / ack_duration;
} else if (num_rtt_samples == 1) {
interval_stats_.ack_rate_mbps =
static_cast<float>(interval->bytes_acked) /
interval_stats_.interval_duration;
} else {
interval_stats_.ack_rate_mbps = 0;
}
}
void PccUtilityManager::ComputeApproxRttGradient(
const MonitorInterval* interval) {
// Separate all RTT samples in the interval into two halves, and calculate an
// approximate RTT gradient.
QuicTime::Delta rtt_first_half = QuicTime::Delta::Zero();
QuicTime::Delta rtt_second_half = QuicTime::Delta::Zero();
size_t num_half_samples = interval->packet_rtt_samples.size() / 2;
size_t num_first_half_samples = 0;
size_t num_second_half_samples = 0;
for (size_t i = 0; i < num_half_samples; ++i) {
if (interval->packet_rtt_samples[i].is_reliable_for_gradient_calculation) {
rtt_first_half = rtt_first_half +
interval->packet_rtt_samples[i].sample_rtt;
num_first_half_samples++;
}
if (interval->packet_rtt_samples[i + num_half_samples]
.is_reliable_for_gradient_calculation) {
rtt_second_half = rtt_second_half +
interval->packet_rtt_samples[i + num_half_samples].sample_rtt;
num_second_half_samples++;
}
}
if (num_first_half_samples == 0 || num_second_half_samples == 0) {
interval_stats_.approx_rtt_gradient = 0.0;
return;
}
rtt_first_half =
rtt_first_half * (1.0 / static_cast<float>(num_first_half_samples));
rtt_second_half =
rtt_second_half * (1.0 / static_cast<float>(num_second_half_samples));
interval_stats_.approx_rtt_gradient = 2.0 *
static_cast<float>((rtt_second_half - rtt_first_half).ToMicroseconds()) /
static_cast<float>((rtt_second_half + rtt_first_half).ToMicroseconds());
}
void PccUtilityManager::ComputeRttGradient(const MonitorInterval* interval) {
if (interval->num_reliable_rtt_for_gradient_calculation < 2) {
interval_stats_.rtt_gradient = 0;
interval_stats_.rtt_gradient_cut = 0;
return;
}
// Calculate RTT gradient using linear regression.
float gradient_x_avg = 0.0;
float gradient_y_avg = 0.0;
float gradient_x = 0.0;
float gradient_y = 0.0;
for (const PacketRttSample& rtt_sample : interval->packet_rtt_samples) {
if (!rtt_sample.is_reliable_for_gradient_calculation) {
continue;
}
gradient_x_avg += static_cast<float>(rtt_sample.packet_number);
gradient_y_avg +=
static_cast<float>(rtt_sample.sample_rtt.ToMicroseconds());
}
gradient_x_avg /=
static_cast<float>(interval->num_reliable_rtt_for_gradient_calculation);
gradient_y_avg /=
static_cast<float>(interval->num_reliable_rtt_for_gradient_calculation);
for (const PacketRttSample& rtt_sample : interval->packet_rtt_samples) {
if (!rtt_sample.is_reliable_for_gradient_calculation) {
continue;
}
float delta_packet_number =
static_cast<float>(rtt_sample.packet_number) - gradient_x_avg;
float delta_rtt_sample =
static_cast<float>(rtt_sample.sample_rtt.ToMicroseconds()) -
gradient_y_avg;
gradient_x += delta_packet_number * delta_packet_number;
gradient_y += delta_packet_number * delta_rtt_sample;
}
interval_stats_.rtt_gradient = gradient_y / gradient_x;
interval_stats_.rtt_gradient /=
static_cast<float>(interval->sending_rate.TransferTime(kMaxPacketSize)
.ToMicroseconds());
interval_stats_.avg_rtt = gradient_y_avg;
interval_stats_.rtt_gradient_cut =
gradient_y_avg - interval_stats_.rtt_gradient * gradient_x_avg;
}
void PccUtilityManager::ComputeRttGradientError(
const MonitorInterval* interval) {
interval_stats_.rtt_gradient_error = 0.0;
if (interval->num_reliable_rtt_for_gradient_calculation < 2) {
return;
}
for (const PacketRttSample& rtt_sample : interval->packet_rtt_samples) {
if (!rtt_sample.is_reliable_for_gradient_calculation) {
continue;
}
float regression_rtt = static_cast<float>(rtt_sample.packet_number *
interval_stats_.rtt_gradient) +
interval_stats_.rtt_gradient_cut;
interval_stats_.rtt_gradient_error +=
pow(rtt_sample.sample_rtt.ToMicroseconds() - regression_rtt, 2.0);
}
interval_stats_.rtt_gradient_error /=
static_cast<float>(interval->num_reliable_rtt_for_gradient_calculation);
interval_stats_.rtt_gradient_error = sqrt(interval_stats_.rtt_gradient_error);
interval_stats_.rtt_gradient_error /=
static_cast<float>(interval_stats_.avg_rtt);
}
void PccUtilityManager::ComputeRttDeviation(const MonitorInterval* interval) {
if (interval->num_reliable_rtt < 2) {
interval_stats_.rtt_dev = 0;
return;
}
// Calculate RTT deviation.
interval_stats_.rtt_dev = 0.0;
interval_stats_.max_rtt = -1;
interval_stats_.min_rtt = -1;
for (const PacketRttSample& rtt_sample : interval->packet_rtt_samples) {
if (!rtt_sample.is_reliable) {
continue;
}
float delta_rtt_sample =
static_cast<float>(rtt_sample.sample_rtt.ToMicroseconds()) -
interval_stats_.avg_rtt;
interval_stats_.rtt_dev += delta_rtt_sample * delta_rtt_sample;
if (min_rtt_ < 0 || rtt_sample.sample_rtt.ToMicroseconds() < min_rtt_) {
min_rtt_ = rtt_sample.sample_rtt.ToMicroseconds();
}
if (interval_stats_.min_rtt < 0 ||
rtt_sample.sample_rtt.ToMicroseconds() < interval_stats_.min_rtt) {
interval_stats_.min_rtt =
static_cast<float>(rtt_sample.sample_rtt.ToMicroseconds());
}
if (interval_stats_.max_rtt < 0 ||
rtt_sample.sample_rtt.ToMicroseconds() > interval_stats_.max_rtt) {
interval_stats_.max_rtt =
static_cast<float>(rtt_sample.sample_rtt.ToMicroseconds());
}
}
interval_stats_.rtt_dev =
sqrt(interval_stats_.rtt_dev /
static_cast<float>(interval->num_reliable_rtt));
}
void PccUtilityManager::ProcessRttTrend(
const MonitorInterval* interval) {
if (interval->num_reliable_rtt < 2) {
return;
}
mi_avg_rtt_history_.emplace_back(interval_stats_.avg_rtt);
mi_rtt_dev_history_.emplace_back(interval_stats_.rtt_dev);
if (mi_avg_rtt_history_.size() > kRttHistoryLen) {
mi_avg_rtt_history_.pop_front();
}
if (mi_rtt_dev_history_.size() > kRttHistoryLen) {
mi_rtt_dev_history_.pop_front();
}
if (mi_avg_rtt_history_.size() >= kRttHistoryLen) {
ComputeTrendingGradient();
ComputeTrendingGradientError();
DetermineToleranceInflation();
}
if (mi_rtt_dev_history_.size() >= kRttHistoryLen) {
ComputeTrendingDeviation();
DetermineToleranceDeviation();
}
}
void PccUtilityManager::ComputeTrendingGradient() {
// Calculate RTT gradient using linear regression.
float gradient_x_avg = 0.0;
float gradient_y_avg = 0.0;
float gradient_x = 0.0;
float gradient_y = 0.0;
size_t num_sample = mi_avg_rtt_history_.size();
for (size_t i = 0; i < num_sample; ++i) {
gradient_x_avg += static_cast<float>(i);
gradient_y_avg += mi_avg_rtt_history_[i];
}
gradient_x_avg /= static_cast<float>(num_sample);
gradient_y_avg /= static_cast<float>(num_sample);
for (size_t i = 0; i < num_sample; ++i) {
float delta_x = static_cast<float>(i) - gradient_x_avg;
float delta_y = mi_avg_rtt_history_[i] - gradient_y_avg;
gradient_x += delta_x * delta_x;
gradient_y += delta_x * delta_y;
}
interval_stats_.trending_gradient = gradient_y / gradient_x;
interval_stats_.trending_gradient_cut =
gradient_y_avg - interval_stats_.trending_gradient * gradient_x_avg;
}
void PccUtilityManager::ComputeTrendingGradientError() {
size_t num_sample = mi_avg_rtt_history_.size();
interval_stats_.trending_gradient_error = 0.0;
for (size_t i = 0; i < num_sample; ++i) {
float regression_rtt =
static_cast<float>(i) * interval_stats_.trending_gradient +
interval_stats_.trending_gradient_cut;
interval_stats_.trending_gradient_error +=
pow(mi_avg_rtt_history_[i] - regression_rtt, 2.0);
}
interval_stats_.trending_gradient_error /= static_cast<float>(num_sample);
interval_stats_.trending_gradient_error =
sqrt(interval_stats_.trending_gradient_error);
}
void PccUtilityManager::ComputeTrendingDeviation() {
size_t num_sample = mi_rtt_dev_history_.size();
float avg_rtt_dev = 0.0;
for (size_t i = 0; i < num_sample; ++i) {
avg_rtt_dev += mi_rtt_dev_history_[i];
}
avg_rtt_dev /= static_cast<float>(num_sample);
interval_stats_.trending_deviation = 0.0;
for (size_t i = 0; i < num_sample; ++i) {
float delta_dev = avg_rtt_dev - mi_rtt_dev_history_[i];
interval_stats_.trending_deviation += (delta_dev * delta_dev);
}
interval_stats_.trending_deviation /= static_cast<float>(num_sample);
interval_stats_.trending_deviation = sqrt(interval_stats_.trending_deviation);
}
void PccUtilityManager::DetermineToleranceGeneral() {
if (interval_stats_.rtt_gradient_error <
std::abs(interval_stats_.rtt_gradient)) {
is_rtt_inflation_tolerable_ = false;
is_rtt_dev_tolerable_ = false;
} else {
is_rtt_inflation_tolerable_ = true;
is_rtt_dev_tolerable_ = true;
}
}
void PccUtilityManager::DetermineToleranceInflation() {
ratio_inflated_mi_ *= (1 - kAlpha);
if (utility_tag_ != "Scavenger" &&
mi_avg_rtt_history_.size() < kRttHistoryLen) {
return;
}
if (min_trending_gradient_ < 0.000001 ||
std::abs(interval_stats_.trending_gradient) <
min_trending_gradient_ / kBeta) {
avg_trending_gradient_ = 0.0f;
min_trending_gradient_ = std::abs(interval_stats_.trending_gradient);
dev_trending_gradient_ = std::abs(interval_stats_.trending_gradient);
last_trending_gradient_ = interval_stats_.trending_gradient;
} else {
float dev_gain = interval_stats_.rtt_dev < 1000
? kInflationToleranceGainLow : kInflationToleranceGainHigh;
float tolerate_threshold_h =
avg_trending_gradient_ + dev_gain * dev_trending_gradient_;
float tolerate_threshold_l =
avg_trending_gradient_ - dev_gain * dev_trending_gradient_;
if (interval_stats_.trending_gradient < tolerate_threshold_l ||
interval_stats_.trending_gradient > tolerate_threshold_h) {
if (interval_stats_.trending_gradient > 0) {
is_rtt_inflation_tolerable_ = false;
}
is_rtt_dev_tolerable_ = false;
ratio_inflated_mi_ += kAlpha;
} else {
dev_trending_gradient_ =
dev_trending_gradient_ * (1 - kAlpha) +
std::abs(interval_stats_.trending_gradient -
last_trending_gradient_) * kAlpha;
avg_trending_gradient_ =
avg_trending_gradient_ * (1 - kAlpha) +
interval_stats_.trending_gradient * kAlpha;
last_trending_gradient_ = interval_stats_.trending_gradient;
}
min_trending_gradient_ =
std::min(min_trending_gradient_,
std::abs(interval_stats_.trending_gradient));
}
/*if (ratio_inflated_mi_ > kTrendingResetIntervalRatio) {
// TODO: reset based on minimum RTT observation.
avg_trending_gradient_ = 0.0;
dev_trending_gradient_ = min_trending_gradient_;
ratio_inflated_mi_ = 0;
}*/
}
void PccUtilityManager::DetermineToleranceDeviation() {
ratio_fluctuated_mi_ *= (1 - kAlpha);
if (avg_mi_rtt_dev_ < 0.000001) {
avg_mi_rtt_dev_ = interval_stats_.rtt_dev;
dev_mi_rtt_dev_ = 0.5 * interval_stats_.rtt_dev;
} else {
if (interval_stats_.rtt_dev > avg_mi_rtt_dev_ + dev_mi_rtt_dev_ * 4.0 &&
interval_stats_.rtt_dev > 1000) {
is_rtt_dev_tolerable_ = false;
ratio_fluctuated_mi_ += kAlpha;
} else {
dev_mi_rtt_dev_ =
dev_mi_rtt_dev_ * (1 - kAlpha) +
std::abs(interval_stats_.rtt_dev - avg_mi_rtt_dev_) * kAlpha;
avg_mi_rtt_dev_ =
avg_mi_rtt_dev_ * (1 - kAlpha) + interval_stats_.rtt_dev * kAlpha;
}
}
if (ratio_fluctuated_mi_ > kTrendingResetIntervalRatio) {
avg_mi_rtt_dev_ = -1;
dev_mi_rtt_dev_ = -1;
ratio_fluctuated_mi_ = 0;
}
}
// } // namespace quic
| 37.885604 | 80 | 0.718507 | [
"transform"
] |
496ed434b1662e04dd441ea75db8e91456c25825 | 1,688 | cpp | C++ | src/_leetcode/leet_102.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_102.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | src/_leetcode/leet_102.cpp | turesnake/leetPractice | a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b | [
"MIT"
] | null | null | null | /*
* ====================== leet_102.cpp ==========================
* -- tpr --
* CREATE -- 2020.05.04
* MODIFY --
* ----------------------------------------------------------
* 102. 二叉树的层序遍历
*/
#include "innLeet.h"
#include <stack>
#include "TreeNode1.h"
namespace leet_102 {//~
void lvlWork( TreeNode* root,
int deep,
std::vector<std::vector<int>> &outs ){
if( !root ){ return; }
while( static_cast<int>(outs.size()) < deep ){
outs.push_back( std::vector<int>{} );
}
if( root->left ){ lvlWork( root->left, deep+1, outs ); }
outs.at(deep-1).push_back( root->val );
if( root->right ){ lvlWork( root->right, deep+1, outs ); }
}
std::vector<std::vector<int>> levelOrder( TreeNode* root ){
std::vector<std::vector<int>> outs {};
lvlWork( root, 1, outs );
return outs;
}
//=========================================================//
void main_(){
int Nil {INT_MIN};
//std::vector<int> inputs { 3,9,20,Nil,Nil,15,7 };
std::vector<int> inputs { 1,2,2,3,3,Nil,Nil,4,4 };
//std::vector<int> inputs { 3,9,20,Nil,Nil,15,7 };
//std::vector<int> inputs { 1,2,3,4,5 };
TreeNode *treeRoot = create_a_tree( inputs );
//TreeNode *treeRoot {nullptr};
print_a_tree( treeRoot );
cout << endl;
auto outs = levelOrder( treeRoot );
for( const auto &v : outs ){
cout << "[ ";
for( const auto &i : v ){
cout << i << ", ";
}
cout << " ]" << endl;
}
debug::log( "\n~~~~ leet: 102 :end ~~~~\n" );
}
}//~
| 23.444444 | 65 | 0.437204 | [
"vector"
] |
49711a26e34396abb72779e35d38de169f91aae0 | 49,083 | cc | C++ | ompi/contrib/vt/vt/tools/vtunify/vt_unify_defs.cc | ystk/debian-openmpi | cea6f8a27c406a30cfa81d49ab479d3f67a58878 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | ompi/contrib/vt/vt/tools/vtunify/vt_unify_defs.cc | ystk/debian-openmpi | cea6f8a27c406a30cfa81d49ab479d3f67a58878 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | ompi/contrib/vt/vt/tools/vtunify/vt_unify_defs.cc | ystk/debian-openmpi | cea6f8a27c406a30cfa81d49ab479d3f67a58878 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /**
* VampirTrace
* http://www.tu-dresden.de/zih/vampirtrace
*
* Copyright (c) 2005-2008, ZIH, TU Dresden, Federal Republic of Germany
*
* Copyright (c) 1998-2005, Forschungszentrum Juelich, Juelich Supercomputing
* Centre, Federal Republic of Germany
*
* See the file COPYING in the package base directory for details
**/
#include "vt_unify_defs.h"
#include "vt_unify.h"
#include "vt_unify_defs_hdlr.h"
#include "vt_unify_stats.h"
#include "vt_unify_tkfac.h"
#include "vt_inttypes.h"
#include "otf.h"
#include <iostream>
#include <list>
#include <map>
#include <string>
#include <vector>
#include <assert.h>
#include <stdio.h>
#include <string.h>
Definitions * theDefinitions; // instance of class Definitions
bool
LocDefsCmp( Definitions::DefRec_Base_struct * a,
Definitions::DefRec_Base_struct * b )
{
// both record types are DEF_REC_TYPE__DefinitionComment ? ...
//
if( a->etype == Definitions::DEF_REC_TYPE__DefinitionComment &&
b->etype == Definitions::DEF_REC_TYPE__DefinitionComment )
{
Definitions::DefRec_DefinitionComment_struct * c1 =
static_cast<Definitions::DefRec_DefinitionComment_struct*>(a);
Definitions::DefRec_DefinitionComment_struct * c2 =
static_cast<Definitions::DefRec_DefinitionComment_struct*>(b);
// ... sort by trace order
return c1->orderidx < c2->orderidx;
}
// both records have the same type ? ...
//
if( a->etype == b->etype &&
( a->etype != Definitions::DEF_REC_TYPE__DefCreator &&
a->etype != Definitions::DEF_REC_TYPE__DefTimerResolution ) )
{
if( a->deftoken == b->deftoken )
{
// ... sort by local process id if local tokens are equal
return a->loccpuid < b->loccpuid;
}
else
{
// ... sort by local token
return a->deftoken < b->deftoken;
}
}
// otherwise ...
else
{
// ... sort by type
return a->etype < b->etype;
}
}
bool
GlobDefsCmp( Definitions::DefRec_Base_struct * a,
Definitions::DefRec_Base_struct * b )
{
// both record types are Definitions::DEF_REC_TYPE__DefProcess ? ...
//
if( a->etype == Definitions::DEF_REC_TYPE__DefProcess &&
b->etype == Definitions::DEF_REC_TYPE__DefProcess )
{
// ... sort as follow:
// Master 0
// Child 1/0
// Child 2/0
// Master 1
// Child 1/1
// Child 2/1
// ...
Definitions::DefRec_DefProcess_struct * p1 =
static_cast<Definitions::DefRec_DefProcess_struct*>(a);
Definitions::DefRec_DefProcess_struct * p2 =
static_cast<Definitions::DefRec_DefProcess_struct*>(b);
// both are master
if( p1->parent == 0 && p2->parent == 0 )
return p1->deftoken < p2->deftoken;
// p2 child of p1
else if( p1->deftoken == p2->parent )
return true;
// p1 child of p2
else if( p1->parent == p2->deftoken )
return false;
// both are childs and have same master
else if( p1->parent != 0 && ( p1->parent == p2->parent ) )
return p1->deftoken < p2->deftoken;
// both are childs, but not from same master
else if( p1->parent != 0 && p2->parent != 0 &&
( p1->parent != p2->parent ) )
return p1->parent < p2->parent;
// p1 is master and p2 is child, but both have no reference
else if( p1->parent == 0 && p2->parent != 0 )
return p1->deftoken < p2->parent;
// p1 is child and p2 is master, but both have no reference
else
return p1->parent < p2->deftoken;
}
// both record types are Definitions::DEF_REC_TYPE__DefProcessGroup ? ...
//
else if( a->etype == Definitions::DEF_REC_TYPE__DefProcessGroup &&
b->etype == Definitions::DEF_REC_TYPE__DefProcessGroup )
{
Definitions::DefRec_DefProcessGroup_struct * p1 =
static_cast<Definitions::DefRec_DefProcessGroup_struct*>(a);
Definitions::DefRec_DefProcessGroup_struct * p2 =
static_cast<Definitions::DefRec_DefProcessGroup_struct*>(b);
// ... sort to this order:
// Nodes
// MPI_COMM_WORLD
// MPI_COMM_SELFs
// remaining MPI communicators
// OpenMP Thread Teams
// Rest
// p1 == TYPE_NODE && p2 != TYPE_NODE
if( p1->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_NODE
&& p2->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_NODE )
{
return true;
}
// p1 != TYPE_NODE && p2 == TYPE_NODE
else if(
p1->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_NODE
&& p2->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_NODE )
{
return false;
}
// p1 == TYPE_MPI_COMM_WORLD && p2 != TYPE_MPI_COMM_WORLD
else if(
p1->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_WORLD
&& p2->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_WORLD )
{
return true;
}
// p1 != TYPE_MPI_COMM_WORLD && p2 == TYPE_MPI_COMM_WORLD
else if(
p1->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_WORLD
&& p2->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_WORLD )
{
return false;
}
// p1 == TYPE_MPI_COMM_SELF && p2 != TYPE_MPI_COMM_SELF
else if(
p1->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_SELF
&& p2->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_SELF )
{
return true;
}
// p1 != TYPE_MPI_COMM_SELF && p2 == TYPE_MPI_COMM_SELF
else if(
p1->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_SELF
&& p2->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_SELF )
{
return false;
}
// p1 == TYPE_MPI_COMM_USER && p2 != TYPE_MPI_COMM_USER
else if(
p1->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_USER
&& p2->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_USER )
{
return true;
}
// p1 != TYPE_MPI_COMM_USER && p2 == TYPE_MPI_COMM_USER
else if(
p1->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_USER
&& p2->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_USER )
{
return false;
}
// p1 == TYPE_OMP_TEAM && p2 != TYPE_OMP_TEAM
else if(
p1->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_OMP_TEAM
&& p2->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_OMP_TEAM )
{
return true;
}
// p1 != TYPE_OMP_TEAM && p2 == TYPE_OMP_TEAM
else if(
p1->type != Definitions::DefRec_DefProcessGroup_struct::TYPE_OMP_TEAM
&& p2->type == Definitions::DefRec_DefProcessGroup_struct::TYPE_OMP_TEAM )
{
return false;
}
else
{
// sort by token, if process group types are equal
return p1->deftoken < p2->deftoken;
}
}
// both record types are Definitions::DEF_REC_TYPE__DefinitionComment ? ...
//
if( a->etype == Definitions::DEF_REC_TYPE__DefinitionComment &&
b->etype == Definitions::DEF_REC_TYPE__DefinitionComment )
{
Definitions::DefRec_DefinitionComment_struct * c1 =
static_cast<Definitions::DefRec_DefinitionComment_struct*>(a);
Definitions::DefRec_DefinitionComment_struct * c2 =
static_cast<Definitions::DefRec_DefinitionComment_struct*>(b);
// ... sort by trace order
return c1->orderidx < c2->orderidx;
}
// both records have the same type ? ...
//
else if( a->etype == b->etype &&
( a->etype != Definitions::DEF_REC_TYPE__DefCreator &&
a->etype != Definitions::DEF_REC_TYPE__DefTimerResolution ) )
{
// ... sort by defined token
return a->deftoken < b->deftoken;
}
// otherwise ...
else
{
// ... sort by type
return a->etype < b->etype;
}
}
//////////////////// class Definitions ////////////////////
// public methods
//
Definitions::Definitions()
{
// Empty
}
Definitions::~Definitions()
{
// Empty
}
bool
Definitions::run()
{
bool error = false;
// allocate vector for local definitions
std::vector<DefRec_Base_struct*> * p_vec_loc_defs =
new std::vector<DefRec_Base_struct*>();
assert( p_vec_loc_defs );
// allocate vector for global definitions
std::vector<DefRec_Base_struct*> * p_vec_glob_defs =
new std::vector<DefRec_Base_struct*>();
assert( p_vec_glob_defs );
// read local definitions
if( !readLocal( p_vec_loc_defs ) )
error = true;
// create global definitions
if( !error && !createGlobal( p_vec_loc_defs, p_vec_glob_defs ) )
error = true;
// write global definitions
if( !error && !writeGlobal( p_vec_glob_defs ) )
error = true;
// free local/global definition record vector
//
for( uint32_t i = 0; i < p_vec_loc_defs->size(); i++ )
delete (*p_vec_loc_defs)[i];
delete p_vec_loc_defs;
for( uint32_t i = 0; i < p_vec_glob_defs->size(); i++ )
delete (*p_vec_glob_defs)[i];
delete p_vec_glob_defs;
return !error;
}
// private methods
//
bool
Definitions::readLocal( std::vector<DefRec_Base_struct*> * p_vecLocDefs )
{
if( Params.beverbose )
std::cout << "Reading local definitions ..." << std::endl;
bool error = false;
// create record handler and set the local definition
// record vector as first handler argument for ...
//
OTF_HandlerArray * p_handler_array =
OTF_HandlerArray_open();
assert( p_handler_array );
// ... OTF_DEFINITIONCOMMENT_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefinitionComment,
OTF_DEFINITIONCOMMENT_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFINITIONCOMMENT_RECORD );
// ... OTF_DEFCREATOR_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefCreator,
OTF_DEFCREATOR_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFCREATOR_RECORD );
// ... OTF_DEFTIMERRESOLUTION_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefTimerResolution,
OTF_DEFTIMERRESOLUTION_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFTIMERRESOLUTION_RECORD );
// ... OTF_DEFPROCESSGROUP_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefProcessGroup,
OTF_DEFPROCESSGROUP_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFPROCESSGROUP_RECORD );
// ... OTF_DEFPROCESS_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefProcess,
OTF_DEFPROCESS_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFPROCESS_RECORD );
// ... OTF_DEFSCLFILE_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefSclFile,
OTF_DEFSCLFILE_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFSCLFILE_RECORD );
// ... OTF_DEFSCL_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefScl,
OTF_DEFSCL_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFSCL_RECORD );
// ... OTF_DEFFILEGROUP_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefFileGroup,
OTF_DEFFILEGROUP_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFFILEGROUP_RECORD );
// ... OTF_DEFFILE_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefFile,
OTF_DEFFILE_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFFILE_RECORD );
// ... OTF_DEFFUNCTIONGROUP_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefFunctionGroup,
OTF_DEFFUNCTIONGROUP_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFFUNCTIONGROUP_RECORD );
// ... OTF_DEFFUNCTION_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefFunction,
OTF_DEFFUNCTION_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFFUNCTION_RECORD );
// ... OTF_DEFCOLLOP_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefCollectiveOperation,
OTF_DEFCOLLOP_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFCOLLOP_RECORD );
// ... OTF_DEFCOUNTERGROUP_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefCounterGroup,
OTF_DEFCOUNTERGROUP_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFCOUNTERGROUP_RECORD );
// ... OTF_DEFCOUNTER_RECORD
OTF_HandlerArray_setHandler( p_handler_array,
(OTF_FunctionPointer*)Handle_DefCounter,
OTF_DEFCOUNTER_RECORD );
OTF_HandlerArray_setFirstHandlerArg( p_handler_array,
p_vecLocDefs,
OTF_DEFCOUNTER_RECORD );
// read local definitions
//
for( uint32_t i = 0; i < g_vecUnifyCtls.size(); i++ )
{
// open file manager for reader stream
OTF_FileManager * p_loc_def_manager
= OTF_FileManager_open( 1 );
assert( p_loc_def_manager );
// open stream for reading
OTF_RStream * p_loc_def_rstream =
OTF_RStream_open( Params.in_file_prefix.c_str(),
g_vecUnifyCtls[i]->streamid,
p_loc_def_manager );
assert( p_loc_def_rstream );
if( Params.beverbose )
std::cout << " Opened OTF reader stream [namestub "
<< Params.in_file_prefix << " id "
<< std::hex << g_vecUnifyCtls[i]->streamid << "]"
<< std::dec << std::endl;
if( !OTF_RStream_getDefBuffer( p_loc_def_rstream ) )
{
if( Params.beverbose )
{
std::cout << " No definitions found in this OTF reader stream "
<< "- Ignored" << std::endl;
}
}
else
{
// close definitions buffer
OTF_RStream_closeDefBuffer( p_loc_def_rstream );
// read definitions
if( OTF_RStream_readDefinitions( p_loc_def_rstream, p_handler_array )
== OTF_READ_ERROR )
{
std::cerr << ExeName << ": Error: "
<< "Could not read definitions of OTF stream [namestub "
<< Params.in_file_prefix << " id "
<< std::hex << g_vecUnifyCtls[i]->streamid << "]"
<< std::dec << std::endl;
error = true;
}
}
// close reader stream
OTF_RStream_close( p_loc_def_rstream );
// close file manager for reader stream
OTF_FileManager_close( p_loc_def_manager );
if( Params.beverbose )
std::cout << " Closed OTF reader stream [namestub "
<< Params.in_file_prefix << " id "
<< std::hex << g_vecUnifyCtls[i]->streamid << "]"
<< std::dec << std::endl;
if( error ) break;
}
// close record handler
OTF_HandlerArray_close( p_handler_array );
if( error )
{
std::cerr << ExeName << ": "
<< "An error occurred during unifying definitions - Terminating ..."
<< std::endl;
}
else
{
// sort local definitions
std::sort( p_vecLocDefs->begin(), p_vecLocDefs->end(),
LocDefsCmp );
}
return !error;
}
bool
Definitions::createGlobal( const std::vector<DefRec_Base_struct*> *
p_vecLocDefs,
std::vector<DefRec_Base_struct*> * p_vecGlobDefs )
{
assert( p_vecLocDefs->size() > 0 );
bool error = false;
uint32_t omp_comm_idx = 0;
uint32_t mpi_comm_self_idx = 0;
for( uint32_t i = 0; i < p_vecLocDefs->size(); i++ )
{
switch( (*p_vecLocDefs)[i]->etype )
{
// DefinitionComment
//
case DEF_REC_TYPE__DefinitionComment:
{
// get local definition entry
DefRec_DefinitionComment_struct * p_loc_def_entry =
(DefRec_DefinitionComment_struct*)((*p_vecLocDefs)[i]);
// add definition without any changes to vector of
// global definitions
p_vecGlobDefs->push_back( new DefRec_DefinitionComment_struct(
p_loc_def_entry->orderidx,
p_loc_def_entry->comment ) );
break;
}
// DefCreator
//
case DEF_REC_TYPE__DefCreator:
{
// get local definition entry
DefRec_DefCreator_struct * p_loc_def_entry =
(DefRec_DefCreator_struct*)((*p_vecLocDefs)[i]);
// add definition without any changes to vector of
// global definitions
p_vecGlobDefs->push_back( new DefRec_DefCreator_struct(
p_loc_def_entry->creator ) );
break;
}
// DefTimerResolution
//
case DEF_REC_TYPE__DefTimerResolution:
{
// get local definition entry
DefRec_DefTimerResolution_struct * p_loc_def_entry =
(DefRec_DefTimerResolution_struct*)((*p_vecLocDefs)[i]);
// add definition without any changes to vector of
// global definitions
p_vecGlobDefs->push_back( new DefRec_DefTimerResolution_struct(
p_loc_def_entry->ticksPerSecond ) );
break;
}
// DefProcess
//
case DEF_REC_TYPE__DefProcess:
{
// get local definition entry
DefRec_DefProcess_struct *p_loc_def_entry =
(DefRec_DefProcess_struct*)((*p_vecLocDefs)[i]);
// add definition without any changes to vector of
// global definitions
p_vecGlobDefs->push_back( new DefRec_DefProcess_struct(
p_loc_def_entry->deftoken,
p_loc_def_entry->name,
p_loc_def_entry->parent ) );
break;
}
// DefProcessGroup
//
case DEF_REC_TYPE__DefProcessGroup:
{
// get local definition entry
DefRec_DefProcessGroup_struct * p_loc_def_entry =
(DefRec_DefProcessGroup_struct*)((*p_vecLocDefs)[i]);
// node definition?
if( p_loc_def_entry->type ==
DefRec_DefProcessGroup_struct::TYPE_NODE )
{
addProc2NodeGroup( p_loc_def_entry->name.substr(9),
p_loc_def_entry->members[0] );
}
// MPI communicator (except MPI_COMM_WORLD and MPI_COMM_SELF)
else if( p_loc_def_entry->type ==
DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_USER )
{
addMPIComm( p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->members );
}
else
{
// get global token factory for this definition type
TokenFactory_DefProcessGroup * p_tkfac_defprocessgroup =
static_cast<TokenFactory_DefProcessGroup*>(theTokenFactory[TKFAC__DEF_PROCESS_GROUP]);
// get global token
uint32_t global_token =
p_tkfac_defprocessgroup->getGlobalToken(
p_loc_def_entry->name,
p_loc_def_entry->members );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_defprocessgroup->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name,
p_loc_def_entry->members );
char new_name[256];
if( p_loc_def_entry->type ==
DefRec_DefProcessGroup_struct::TYPE_OMP_TEAM )
{
snprintf( new_name, sizeof( new_name ) - 1,
"OMP Thread Team %d", omp_comm_idx++ );
}
else if( p_loc_def_entry->type ==
DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_WORLD )
{
strncpy( new_name, "MPI_COMM_WORLD",
sizeof( new_name ) - 1 );
}
else if( p_loc_def_entry->type ==
DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_SELF )
{
snprintf( new_name, sizeof( new_name ) - 1,
"MPI_COMM_SELF %d", mpi_comm_self_idx++ );
}
else
{
strncpy( new_name, p_loc_def_entry->name.c_str(),
sizeof( new_name ) - 1 );
}
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefProcessGroup_struct(
0,
global_token,
p_loc_def_entry->type,
new_name,
p_loc_def_entry->members ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_defprocessgroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_defprocessgroup->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
}
break;
}
// DefSclFile
//
case DEF_REC_TYPE__DefSclFile:
{
// get local definition entry
DefRec_DefSclFile_struct * p_loc_def_entry =
(DefRec_DefSclFile_struct*)((*p_vecLocDefs)[i]);
// get global token factory for this definition type
TokenFactory_DefSclFile * p_tkfac_defsclfile =
static_cast<TokenFactory_DefSclFile*>(theTokenFactory[TKFAC__DEF_SCL_FILE]);
// get global token
uint32_t global_token =
p_tkfac_defsclfile->getGlobalToken(
p_loc_def_entry->filename );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_defsclfile->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->filename );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefSclFile_struct(
0,
global_token,
p_loc_def_entry->filename ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_defsclfile->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_defsclfile->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefScl
//
case DEF_REC_TYPE__DefScl:
{
// get local definition entry
DefRec_DefScl_struct * p_loc_def_entry =
(DefRec_DefScl_struct*)((*p_vecLocDefs)[i]);
// get global token factory for DefSclFile
TokenFactory_DefSclFile * p_tkfac_defsclfile =
static_cast<TokenFactory_DefSclFile*>(theTokenFactory[TKFAC__DEF_SCL_FILE]);
// get global token factory for this definition type
TokenFactory_DefScl * p_tkfac_defscl =
static_cast<TokenFactory_DefScl*>(theTokenFactory[TKFAC__DEF_SCL]);
// get global token for DefSclFile (exit if not exists)
uint32_t global_sclfile =
p_tkfac_defsclfile->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->sclfile );
assert( global_sclfile != 0 );
// get global token
uint32_t global_token =
p_tkfac_defscl->getGlobalToken( global_sclfile,
p_loc_def_entry->sclline );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_defscl->createGlobalToken( p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_sclfile,
p_loc_def_entry->sclline );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefScl_struct(
0,
global_token,
global_sclfile,
p_loc_def_entry->sclline ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_defscl->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_defscl->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefFileGroup
//
case DEF_REC_TYPE__DefFileGroup:
{
// get local definition entry
DefRec_DefFileGroup_struct * p_loc_def_entry =
(DefRec_DefFileGroup_struct*)((*p_vecLocDefs)[i]);
// get global token factory for this definition type
TokenFactory_DefFileGroup * p_tkfac_deffilegroup =
static_cast<TokenFactory_DefFileGroup*>(theTokenFactory[TKFAC__DEF_FILE_GROUP]);
// get global token
uint32_t global_token =
p_tkfac_deffilegroup->getGlobalToken(
p_loc_def_entry->name );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_deffilegroup->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefFileGroup_struct(
0,
global_token,
p_loc_def_entry->name ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_deffilegroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_deffilegroup->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefFile
//
case DEF_REC_TYPE__DefFile:
{
// get local definition entry
DefRec_DefFile_struct * p_loc_def_entry =
(DefRec_DefFile_struct*)((*p_vecLocDefs)[i]);
// get global token factory for DefFileGroup
TokenFactory_DefFileGroup * p_tkfac_deffilegroup =
static_cast<TokenFactory_DefFileGroup*>(theTokenFactory[TKFAC__DEF_FILE_GROUP]);
// get global token factory for this definition type
TokenFactory_DefFile * p_tkfac_deffile =
static_cast<TokenFactory_DefFile*>(theTokenFactory[TKFAC__DEF_FILE]);
// get global token for DefFileGroup (exit if not exists)
uint32_t global_group =
p_tkfac_deffilegroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->group );
assert( global_group != 0 );
// get global token
uint32_t global_token =
p_tkfac_deffile->getGlobalToken(
p_loc_def_entry->name,
global_group );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_deffile->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name,
global_group );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefFile_struct(
0,
global_token,
p_loc_def_entry->name,
global_group ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_deffile->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_deffile->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefFunctionGroup
//
case DEF_REC_TYPE__DefFunctionGroup:
{
// get local definition entry
DefRec_DefFunctionGroup_struct * p_loc_def_entry =
(DefRec_DefFunctionGroup_struct*)((*p_vecLocDefs)[i]);
// get global token factory for this definition type
TokenFactory_DefFunctionGroup * p_tkfac_deffunctiongroup =
static_cast<TokenFactory_DefFunctionGroup*>(theTokenFactory[TKFAC__DEF_FUNCTION_GROUP]);
// get global token
uint32_t global_token =
p_tkfac_deffunctiongroup->getGlobalToken(
p_loc_def_entry->name );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_deffunctiongroup->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefFunctionGroup_struct(
0,
global_token,
p_loc_def_entry->name ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_deffunctiongroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_deffunctiongroup->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefFunction
//
case DEF_REC_TYPE__DefFunction:
{
// get local definition entry
DefRec_DefFunction_struct * p_loc_def_entry =
(DefRec_DefFunction_struct*)((*p_vecLocDefs)[i]);
// get global token factory for DefFunctionGroup
TokenFactory_DefFunctionGroup * p_tkfac_deffunctiongroup =
static_cast<TokenFactory_DefFunctionGroup*>(theTokenFactory[TKFAC__DEF_FUNCTION_GROUP]);
// get global token factory for DefScl
TokenFactory_DefScl * p_tkfac_defscl =
static_cast<TokenFactory_DefScl*>(theTokenFactory[TKFAC__DEF_SCL]);
// get global token factory for this definition type
TokenFactory_DefFunction * p_tkfac_deffunction =
static_cast<TokenFactory_DefFunction*>(theTokenFactory[TKFAC__DEF_FUNCTION]);
// get global token for DefFunctionGroup (exit if not exists)
uint32_t global_group =
p_tkfac_deffunctiongroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->group );
assert( global_group != 0 );
// get global token for DefScl (exit if not exists)
uint32_t global_scltoken = p_loc_def_entry->scltoken;
if( p_loc_def_entry->scltoken != 0 )
{
global_scltoken =
p_tkfac_defscl->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->scltoken );
assert( global_scltoken != 0 );
}
// get global token
uint32_t global_token =
p_tkfac_deffunction->getGlobalToken(
p_loc_def_entry->name,
global_group,
global_scltoken );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_deffunction->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name,
global_group,
global_scltoken );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefFunction_struct(
0,
global_token,
p_loc_def_entry->name,
global_group,
global_scltoken ) );
// add new function definition to statistics
theStatistics->addFunc( global_token,
std::string( p_loc_def_entry->name ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_deffunction->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_deffunction->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefCollectiveOperation
//
case DEF_REC_TYPE__DefCollectiveOperation:
{
// get local definition entry
DefRec_DefCollectiveOperation_struct * p_loc_def_entry =
(DefRec_DefCollectiveOperation_struct*)((*p_vecLocDefs)[i]);
// get global token factory for this definition type
TokenFactory_DefCollectiveOperation * p_tkfac_defcollop =
static_cast<TokenFactory_DefCollectiveOperation*>(theTokenFactory[TKFAC__DEF_COLL_OP]);
// get global token
uint32_t global_token =
p_tkfac_defcollop->getGlobalToken(
p_loc_def_entry->name,
p_loc_def_entry->type );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_defcollop->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name,
p_loc_def_entry->type );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefCollectiveOperation_struct(
0,
global_token,
p_loc_def_entry->name,
p_loc_def_entry->type ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_defcollop->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_defcollop->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefCounterGroup
//
case DEF_REC_TYPE__DefCounterGroup:
{
// get local definition entry
DefRec_DefCounterGroup_struct * p_loc_def_entry =
(DefRec_DefCounterGroup_struct*)((*p_vecLocDefs)[i]);
// get global token factory for this definition type
TokenFactory_DefCounterGroup * p_tkfac_defcountergroup =
static_cast<TokenFactory_DefCounterGroup*>(theTokenFactory[TKFAC__DEF_COUNTER_GROUP]);
// get global token
uint32_t global_token =
p_tkfac_defcountergroup->getGlobalToken(
p_loc_def_entry->name );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_defcountergroup->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefCounterGroup_struct(
0,
global_token,
p_loc_def_entry->name ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_defcountergroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_defcountergroup->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
// DefCounter
//
case DEF_REC_TYPE__DefCounter:
{
// get local definition entry
DefRec_DefCounter_struct * p_loc_def_entry =
(DefRec_DefCounter_struct*)((*p_vecLocDefs)[i]);
// get global token factory for DefCounterGroup
TokenFactory_DefCounterGroup * p_tkfac_defcountergroup =
static_cast<TokenFactory_DefCounterGroup*>(theTokenFactory[TKFAC__DEF_COUNTER_GROUP]);
// get global token factory for this definition type
TokenFactory_DefCounter * p_tkfac_defcounter =
static_cast<TokenFactory_DefCounter*>(theTokenFactory[TKFAC__DEF_COUNTER]);
// get global token for DefCounterGroup (exit if not exists)
uint32_t global_countergroup =
p_tkfac_defcountergroup->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->countergroup );
assert( global_countergroup != 0 );
// get global token
uint32_t global_token =
p_tkfac_defcounter->getGlobalToken(
p_loc_def_entry->name,
p_loc_def_entry->properties,
global_countergroup,
p_loc_def_entry->unit );
// global token found ?
if( global_token == 0 )
{
// no -> create it
global_token =
p_tkfac_defcounter->createGlobalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
p_loc_def_entry->name,
p_loc_def_entry->properties,
global_countergroup,
p_loc_def_entry->unit );
// add new definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefCounter_struct(
0,
global_token,
p_loc_def_entry->name,
p_loc_def_entry->properties,
global_countergroup,
p_loc_def_entry->unit ) );
}
else
{
// yes -> (global definition already exists in vector)
// set translation for this local process id, if necessary
//
if( p_tkfac_defcounter->translateLocalToken(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken ) == 0 )
{
p_tkfac_defcounter->setTranslation(
p_loc_def_entry->loccpuid,
p_loc_def_entry->deftoken,
global_token );
}
}
break;
}
default: // DEF_REC_TYPE__Unknown
{
assert( 0 );
}
}
}
// add process group records for nodes to global definition records
addNodeGroups2Global( p_vecGlobDefs );
// add process group records for MPI communicators to global def. records
addMPIComms2Global( p_vecGlobDefs );
// sort global definition records
std::sort( p_vecGlobDefs->begin(), p_vecGlobDefs->end(),
GlobDefsCmp );
return !error;
}
bool
Definitions::writeGlobal( const std::vector<DefRec_Base_struct*> *
p_vecGlobDefs )
{
if( Params.beverbose )
std::cout << "Writing global definitions ..." << std::endl;
assert( p_vecGlobDefs->size() > 0 );
bool error = false;
std::string tmp_out_file_prefix =
Params.out_file_prefix + TmpFileSuffix;
// open file manager for writer stream
OTF_FileManager * p_glob_def_manager
= OTF_FileManager_open( 1 );
assert( p_glob_def_manager );
// open stream for writing (stream id = 0)
OTF_WStream * p_glob_def_wstream =
OTF_WStream_open( tmp_out_file_prefix.c_str(), 0, p_glob_def_manager );
assert( p_glob_def_wstream );
// set file compression
if( Params.docompress )
{
OTF_WStream_setCompression( p_glob_def_wstream,
OTF_FILECOMPRESSION_COMPRESSED );
}
// try to get def. buffer
if( !OTF_WStream_getDefBuffer( p_glob_def_wstream ) )
{
std::cerr << ExeName << ": Error: "
<< "Could not open OTF writer stream [namestub "
<< tmp_out_file_prefix.c_str() << " id 0]" << std::endl;
OTF_WStream_close( p_glob_def_wstream );
OTF_FileManager_close( p_glob_def_manager );
return false;
}
if( Params.beverbose )
{
std::cout << " Opened OTF writer stream [namestub "
<< tmp_out_file_prefix.c_str() << " id 0]" << std::endl;
}
// write OTF version record
OTF_WStream_writeOtfVersion( p_glob_def_wstream );
// write global definition records
//
for( uint32_t i = 0; i < p_vecGlobDefs->size(); i++ )
{
switch( (*p_vecGlobDefs)[i]->etype )
{
case DEF_REC_TYPE__DefinitionComment:
{
DefRec_DefinitionComment_struct * p_entry =
(DefRec_DefinitionComment_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefinitionComment( p_glob_def_wstream,
p_entry->comment.c_str() );
break;
}
case DEF_REC_TYPE__DefCreator:
{
DefRec_DefCreator_struct * p_entry =
(DefRec_DefCreator_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefCreator( p_glob_def_wstream,
p_entry->creator.c_str() );
break;
}
case DEF_REC_TYPE__DefTimerResolution:
{
DefRec_DefTimerResolution_struct * p_entry =
(DefRec_DefTimerResolution_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefTimerResolution( p_glob_def_wstream,
p_entry->ticksPerSecond );
break;
}
case DEF_REC_TYPE__DefProcess:
{
DefRec_DefProcess_struct *p_entry =
(DefRec_DefProcess_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefProcess( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str(),
p_entry->parent );
break;
}
case DEF_REC_TYPE__DefProcessGroup:
{
DefRec_DefProcessGroup_struct * p_entry =
(DefRec_DefProcessGroup_struct*)((*p_vecGlobDefs)[i]);
uint32_t n = p_entry->members.size();
uint32_t * array = new uint32_t[n];
for( uint32_t j = 0; j < n; j++ )
array[j] = p_entry->members[j];
OTF_WStream_writeDefProcessGroup( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str(),
n,
array );
delete[] array;
break;
}
case DEF_REC_TYPE__DefSclFile:
{
DefRec_DefSclFile_struct * p_entry =
(DefRec_DefSclFile_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefSclFile( p_glob_def_wstream,
p_entry->deftoken,
p_entry->filename.c_str() );
break;
}
case DEF_REC_TYPE__DefScl:
{
DefRec_DefScl_struct * p_entry =
(DefRec_DefScl_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefScl( p_glob_def_wstream,
p_entry->deftoken,
p_entry->sclfile,
p_entry->sclline );
break;
}
case DEF_REC_TYPE__DefFileGroup:
{
DefRec_DefFileGroup_struct * p_entry =
(DefRec_DefFileGroup_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefFileGroup( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str() );
break;
}
case DEF_REC_TYPE__DefFile:
{
DefRec_DefFile_struct * p_entry =
(DefRec_DefFile_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefFile( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str(),
p_entry->group );
break;
}
case DEF_REC_TYPE__DefFunctionGroup:
{
DefRec_DefFunctionGroup_struct * p_entry =
(DefRec_DefFunctionGroup_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefFunctionGroup( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str() );
break;
}
case DEF_REC_TYPE__DefFunction:
{
DefRec_DefFunction_struct * p_entry =
(DefRec_DefFunction_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefFunction( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str(),
p_entry->group,
p_entry->scltoken );
break;
}
case DEF_REC_TYPE__DefCollectiveOperation:
{
DefRec_DefCollectiveOperation_struct * p_entry =
(DefRec_DefCollectiveOperation_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefCollectiveOperation( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str(),
p_entry->type );
break;
}
case DEF_REC_TYPE__DefCounterGroup:
{
DefRec_DefCounterGroup_struct * p_entry =
(DefRec_DefCounterGroup_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefCounterGroup( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str() );
break;
}
case DEF_REC_TYPE__DefCounter:
{
DefRec_DefCounter_struct * p_entry =
(DefRec_DefCounter_struct*)((*p_vecGlobDefs)[i]);
OTF_WStream_writeDefCounter( p_glob_def_wstream,
p_entry->deftoken,
p_entry->name.c_str(),
p_entry->properties,
p_entry->countergroup,
p_entry->unit.c_str() );
break;
}
default: // DEF_REC_TYPE__Unknown
{
assert( 0 );
}
}
}
// close writer stream
OTF_WStream_close( p_glob_def_wstream );
// close file manager for writer stream
OTF_FileManager_close( p_glob_def_manager );
if( Params.beverbose )
std::cout << " Closed OTF writer stream [namestub "
<< tmp_out_file_prefix << " id 0]" << std::endl;
return !error;
}
bool
Definitions::addProc2NodeGroup( const std::string & nodeName,
const uint32_t & nodeProc )
{
// process id already exists for this node?
std::vector<NodeProc_struct>::iterator it =
std::find( m_mapNodeProcs[nodeName].begin(),
m_mapNodeProcs[nodeName].end(),
NodeProc_struct( nodeProc ) );
// no -> add process id
if( it == m_mapNodeProcs[nodeName].end() )
{
m_mapNodeProcs[nodeName].push_back( NodeProc_struct( nodeProc ) );
std::sort( m_mapNodeProcs[nodeName].begin(),
m_mapNodeProcs[nodeName].end(),
std::less<NodeProc_struct>() );
return true;
}
return false;
}
bool
Definitions::addNodeGroups2Global( std::vector<DefRec_Base_struct*> *
p_vecGlobDefs )
{
uint32_t seq_node_group_token = 1500000000;
for( std::map<std::string, std::vector<NodeProc_struct> >::iterator it =
m_mapNodeProcs.begin(); it != m_mapNodeProcs.end(); it++ )
{
std::vector<uint32_t> vec_procids;
for( uint32_t i = 0; i < it->second.size(); i++ )
vec_procids.push_back( it->second[i].procid );
p_vecGlobDefs->push_back( new DefRec_DefProcessGroup_struct(
0,
seq_node_group_token++,
DefRec_DefProcessGroup_struct::TYPE_NODE,
it->first,
vec_procids ) );
}
return true;
}
bool
Definitions::addMPIComm( const uint32_t proc, const uint32_t defToken,
const std::vector<uint32_t> & vecMembers )
{
uint32_t comm_id = getMPICommIdByMembers( vecMembers );
uint32_t index;
// search MPI comm. entry with same members for proc
//
std::list<MPIComm_struct>::iterator it =
std::find( m_mapProcMPIComms[proc].begin(),
m_mapProcMPIComms[proc].end(),
MPIComm_struct( comm_id ) );
// if found -> increment index; otherwise init index
if( it != m_mapProcMPIComms[proc].end() )
index = (it->index) + 1;
else
index = 0;
// create new MPI comm. entry for proc
//
MPIComm_struct new_comm( comm_id, proc, defToken, index );
m_mapProcMPIComms[proc].push_front( new_comm );
return true;
}
bool
Definitions::addMPIComms2Global( std::vector<DefRec_Base_struct*> *
p_vecGlobDefs )
{
std::list<MPIComm_struct> list_mpi_comms;
// convert local MPI comm. map to list
//
for( std::map<uint32_t, std::list<MPIComm_struct> >::iterator map_it =
m_mapProcMPIComms.begin(); map_it != m_mapProcMPIComms.end();
map_it++ )
{
for( std::list<MPIComm_struct>::iterator list_it =
map_it->second.begin(); list_it != map_it->second.end();
list_it++ )
{
list_mpi_comms.push_back( *list_it );
}
}
// get global token factory for this definition type
TokenFactory_DefProcessGroup * p_tkfac_defprocessgroup =
static_cast<TokenFactory_DefProcessGroup*>(theTokenFactory[TKFAC__DEF_PROCESS_GROUP]);
char comm_name[256];
uint32_t comm_name_idx = 0;
// unify local MPI comms.
//
while( list_mpi_comms.size() > 0 )
{
std::list<MPIComm_struct>::iterator it = list_mpi_comms.begin();
uint32_t commid = it->commid;
uint32_t index = it->index;
std::vector<uint32_t> vec_members = m_mapMPICommId2Members[commid];
// add index to comm's name
snprintf( comm_name, sizeof( comm_name ) - 1,
"MPI Communicator %d", comm_name_idx++ );
// create token for global comm.
uint32_t global_token =
p_tkfac_defprocessgroup->createGlobalToken(
it->loccpuid,
it->deftoken,
comm_name,
vec_members );
// add process group definition to vector of global definitions
p_vecGlobDefs->push_back( new DefRec_DefProcessGroup_struct(
0,
global_token,
DefRec_DefProcessGroup_struct::TYPE_MPI_COMM_USER,
comm_name,
vec_members ) );
// set translation for all remaining comms. which have this commid
// and index
//
do
{
if( p_tkfac_defprocessgroup->translateLocalToken(
it->loccpuid,
it->deftoken ) == 0 )
{
p_tkfac_defprocessgroup->setTranslation(
it->loccpuid,
it->deftoken,
global_token );
}
// delete processed comm. from list
list_mpi_comms.erase( it );
// search next comm. which have this commid and index
it = std::find( list_mpi_comms.begin(),
list_mpi_comms.end(),
MPIComm_struct(commid, index) );
}
while( it != list_mpi_comms.end() );
}
return true;
}
uint32_t
Definitions::getMPICommIdByMembers( const std::vector<uint32_t> & vecMembers )
{
uint32_t comm_id = (uint32_t)-1;
// linear search of comm. id in map
//
for( std::map<uint32_t, std::vector<uint32_t> >::iterator it =
m_mapMPICommId2Members.begin(); it != m_mapMPICommId2Members.end();
it++ )
{
if( it->second == vecMembers )
{
comm_id = it->first;
break;
}
}
// create new map entry, if not exists
//
if( comm_id == (uint32_t)-1 )
{
comm_id = m_mapMPICommId2Members.size();
m_mapMPICommId2Members.insert( std::make_pair( (uint32_t)comm_id,
(std::vector<uint32_t>) vecMembers ) );
}
return comm_id;
}
| 28.889347 | 96 | 0.65593 | [
"vector"
] |
4973de506720937c4cd2de59c09eab681a5d2f8c | 17,727 | cc | C++ | src/encode.cc | lemire/zuckerli | 0da1f46d58d848eedf4bf875cbf93b35f3f84712 | [
"Apache-2.0"
] | 26 | 2020-09-05T13:05:17.000Z | 2021-05-14T08:37:19.000Z | src/encode.cc | lemire/zuckerli | 0da1f46d58d848eedf4bf875cbf93b35f3f84712 | [
"Apache-2.0"
] | 1 | 2021-01-20T04:41:20.000Z | 2021-01-20T14:51:45.000Z | src/encode.cc | google/zuckerli | 44f54f2e8739ad68f6d78aff97470800c0c7aedb | [
"Apache-2.0"
] | 6 | 2020-10-13T17:12:02.000Z | 2021-10-15T11:22:26.000Z | #include "encode.h"
#include <math.h>
#include <algorithm>
#include <chrono>
#include <numeric>
#include "ans.h"
#include "checksum.h"
#include "common.h"
#include "context_model.h"
#include "huffman.h"
#include "integer_coder.h"
#include "absl/flags/flag.h"
#include "uncompressed_graph.h"
ABSL_FLAG(bool, print_bits_breakdown, false,
"Print a breakdown of where bits are spent");
namespace zuckerli {
namespace {
// TODO: consider discarding short "copy" runs.
void ComputeBlocksAndResiduals(const UncompressedGraph &g, size_t i, size_t ref,
std::vector<uint32_t> *blocks,
std::vector<uint32_t> *residuals) {
blocks->clear();
residuals->clear();
constexpr size_t kMinBlockLen = 0;
size_t ipos = 0;
size_t rpos = 0;
bool is_same = true;
blocks->push_back(0);
while (ipos < g.Degree(i) && rpos < g.Degree(i - ref)) {
size_t a = g.Neighbours(i)[ipos];
size_t b = g.Neighbours(i - ref)[rpos];
if (a == b) {
ipos++;
rpos++;
if (!is_same) {
blocks->emplace_back(0);
}
blocks->back()++;
is_same = true;
} else if (a < b) {
ipos++;
residuals->push_back(a);
} else { // a > b
if (is_same) {
blocks->emplace_back(0);
}
blocks->back()++;
is_same = false;
rpos++;
}
}
if (ipos != g.Degree(i)) {
for (size_t j = ipos; j < g.Degree(i); j++) {
residuals->push_back(g.Neighbours(i)[j]);
}
}
size_t pos = 0;
size_t cur = 1;
bool include = false;
for (size_t k = 1; k < blocks->size(); k++) {
if (include && (*blocks)[k] < kMinBlockLen && k + 1 < blocks->size()) {
size_t add = (*blocks)[k];
size_t skip = (*blocks)[k + 1];
(*blocks)[cur - 1] += add + skip;
for (size_t j = 0; j < add; j++) {
residuals->push_back(g.Neighbours(i)[pos + j]);
}
pos += add + skip;
k++;
} else {
(*blocks)[cur++] = (*blocks)[k];
pos += (*blocks)[k];
include = !include;
}
}
std::sort(residuals->begin(), residuals->end());
if (rpos == g.Degree(i - ref) || !is_same) {
blocks->pop_back();
}
}
template <typename CB1, typename CB2>
void ProcessBlocks(const std::vector<uint32_t> &blocks,
const UncompressedGraph &g, size_t i, size_t reference,
CB1 copy_cb, CB2 cb) {
// TODO: more ctx modeling.
cb(kBlockCountContext, blocks.size());
bool copy = true;
size_t pos = 0;
for (size_t j = 0; j < blocks.size(); j++) {
size_t b = blocks[j];
if (j) {
b--;
}
size_t ctx = j == 0 ? kBlockContext
: (j % 2 == 0 ? kBlockContextEven : kBlockContextOdd);
cb(ctx, b);
if (copy) {
for (size_t k = 0; k < blocks[j]; k++) {
copy_cb(g.Neighbours(i - reference)[pos++]);
}
} else {
pos += blocks[j];
}
copy = !copy;
}
if (copy) {
for (size_t k = pos; k < g.Neighbours(i - reference).size(); k++) {
copy_cb(g.Neighbours(i - reference)[pos++]);
}
}
}
template <typename CB1, typename CB2>
void ProcessResiduals(const std::vector<uint32_t> &residuals, size_t i,
const std::vector<uint32_t> &adj_block,
bool allow_random_access, CB1 undo_cb, CB2 cb) {
size_t ref = i;
size_t last_delta = 0;
size_t adj_pos = 0;
size_t adj_lim = adj_block.size();
size_t zero_run = 0;
for (size_t j = 0; j < residuals.size(); j++) {
size_t ctx = 0;
if (j == 0) {
ctx = FirstResidualContext(residuals.size());
last_delta = PackSigned(int64_t(residuals[j]) - ref);
} else {
ctx = ResidualContext(last_delta);
last_delta = residuals[j] - ref;
while (adj_pos < adj_lim && adj_block[adj_pos] < ref) {
adj_pos++;
}
while (adj_pos < adj_lim && adj_block[adj_pos] < residuals[j]) {
ZKR_DASSERT(last_delta > 0);
last_delta--;
adj_pos++;
}
}
if (last_delta != 0) {
if (zero_run >= kRleMin && allow_random_access) {
for (size_t cnt = kRleMin; cnt < zero_run; cnt++) {
undo_cb();
}
cb(kRleContext, zero_run - kRleMin);
}
zero_run = 0;
}
if (last_delta == 0) {
zero_run++;
}
cb(ctx, last_delta);
ref = residuals[j] + 1;
}
if (zero_run >= kRleMin && allow_random_access) {
for (size_t cnt = kRleMin; cnt < zero_run; cnt++) {
undo_cb();
}
cb(kRleContext, zero_run - kRleMin);
}
}
void UpdateReferencesForMaxLength(const std::vector<float> &saved_costs,
std::vector<size_t> &references,
size_t max_length) {
ZKR_ASSERT(saved_costs.size() == references.size());
size_t N = references.size();
for (size_t i = 0; i < N; i++) {
ZKR_ASSERT(references[i] <= i);
ZKR_ASSERT(saved_costs[i] >= 0);
if (references[i] == 0) ZKR_ASSERT(saved_costs[i] == 0);
}
size_t has_ref = 0;
for (size_t i = 0; i < N; i++) {
if (references[i]) {
has_ref++;
}
}
fprintf(stderr, "has ref pre: %lu\n", has_ref);
std::vector<std::vector<uint32_t>> out_edges(N);
for (size_t i = 0; i < N; i++) {
if (references[i] != 0) {
out_edges[i - references[i]].push_back(i);
}
}
std::vector<float> dyn(N * (max_length + 1));
std::vector<bool> choice(N * (max_length + 1)); // true -> use reference.
// TODO: check this.
for (size_t ip1 = N; ip1 > 0; ip1--) {
size_t i = ip1 - 1;
float child_sum_full_chain = 0;
for (uint64_t child : out_edges[i]) {
child_sum_full_chain += dyn[child * (max_length + 1) + max_length];
}
choice[i * (max_length + 1)] = false;
dyn[i * (max_length + 1)] = child_sum_full_chain;
// counting parent link, if any.
for (size_t links_to_use = 1; links_to_use <= max_length; links_to_use++) {
float child_sum = saved_costs[i];
// Take it.
for (uint64_t child : out_edges[i]) {
child_sum += dyn[child * (max_length + 1) + links_to_use - 1];
}
if (child_sum > child_sum_full_chain) {
choice[i * (max_length + 1) + links_to_use] = true;
dyn[i * (max_length + 1) + links_to_use] = child_sum;
} else {
choice[i * (max_length + 1) + links_to_use] = false;
dyn[i * (max_length + 1) + links_to_use] = child_sum_full_chain;
}
}
}
std::vector<size_t> available_length(N, max_length);
has_ref = 0;
for (size_t i = 0; i < N; i++) {
if (choice[i * (max_length + 1) + available_length[i]]) {
// Taken: push available_length.
for (uint64_t child : out_edges[i]) {
available_length[child] = available_length[i] - 1;
}
} else {
// Not taken: remove reference.
references[i] = 0;
}
if (references[i]) {
has_ref++;
}
}
fprintf(stderr, "has ref post: %lu\n", has_ref);
}
} // namespace
std::vector<uint8_t> EncodeGraph(const UncompressedGraph &g,
bool allow_random_access, size_t *checksum) {
auto start = std::chrono::high_resolution_clock::now();
size_t N = g.size();
size_t chksum = 0;
size_t edges = 0;
BitWriter writer;
writer.Reserve(64);
writer.Write(48, N);
writer.Write(1, allow_random_access);
size_t with_blocks = 0;
IntegerData tokens;
size_t ref = 0;
size_t last_degree_delta = 0;
std::vector<size_t> references(N);
std::vector<float> saved_costs(N);
std::vector<float> symbol_cost(kNumContexts * kNumSymbols, 1.0f);
std::vector<uint32_t> residuals;
std::vector<uint32_t> blocks;
std::vector<uint32_t> adj_block;
std::vector<std::vector<size_t>> symbol_count(kNumContexts);
for (size_t i = 0; i < kNumContexts; i++) {
symbol_count[i].resize(kNumSymbols, 0);
}
// More rounds improve compression a bit, but are also much slower.
// TODO: sometimes, it actually makes things worse (???). Might be max
// chain length.
for (size_t round = 0; round < absl::GetFlag(FLAGS_num_rounds); round++) {
fprintf(stderr, "Selecting references, round %lu%20s\n", round + 1, "");
std::fill(references.begin(), references.end(), 0);
float c = 0;
auto token_cost = [&](size_t ctx, size_t v) {
int token = IntegerCoder::Token(v);
c += IntegerCoder::Cost(ctx, v, symbol_cost.data());
symbol_count[ctx][token]++;
};
// Very rough estimate.
auto rle_undo = [&]() {
c -= symbol_cost[kResidualBaseContext * kNumSymbols];
};
static constexpr size_t kMaxChainLength = 3;
bool greedy =
allow_random_access && absl::GetFlag(FLAGS_greedy_random_access);
std::vector<uint32_t> chain_length(N, 0);
for (size_t i = 0; i < N; i++) {
if (i % 32 == 0) fprintf(stderr, "%lu/%lu\r", i, N);
c = 0;
// No block copying.
residuals.assign(g.Neighbours(i).begin(), g.Neighbours(i).end());
ProcessResiduals(residuals, i, adj_block, allow_random_access, rle_undo,
token_cost);
float cost = c;
float base_cost = c;
saved_costs[i] = 0;
for (size_t ref = 1; ref < std::min(SearchNum(), i) + 1; ref++) {
if (greedy && chain_length[i - ref] >= kMaxChainLength) continue;
adj_block.clear();
c = 0;
ComputeBlocksAndResiduals(g, i, ref, &blocks, &residuals);
ProcessBlocks(
blocks, g, i, ref, [&](size_t x) { adj_block.push_back(x); },
token_cost);
ProcessResiduals(residuals, i, adj_block, allow_random_access, rle_undo,
token_cost);
if (c + 1e-6f < cost) {
references[i] = ref;
cost = c;
saved_costs[i] = base_cost - c;
}
}
if (references[i] != 0) {
chain_length[i] = chain_length[i - references[i]] + 1;
}
}
// Ensure max reference chain length.
if (allow_random_access && !greedy) {
UpdateReferencesForMaxLength(saved_costs, references, kMaxChainLength);
std::vector<size_t> chain_length(N);
for (size_t i = 0; i < N; i++) {
if (references[i] != 0) {
chain_length[i] = chain_length[i - references[i]] + 1;
}
}
std::vector<size_t> fwd_chain_length(N);
for (size_t ip1 = N; ip1 > 0; ip1--) {
size_t i = ip1 - 1;
if (references[i] != 0) {
fwd_chain_length[i - references[i]] = std::max(
fwd_chain_length[i] + 1, fwd_chain_length[i - references[i]]);
}
}
fprintf(stderr, "Adding removed references, round %lu%20s\n", round + 1,
"");
for (size_t i = 0; i < N; i++) {
if (i % 32 == 0) fprintf(stderr, "%lu/%lu\r", i, N);
if (references[i] != 0) {
chain_length[i] = chain_length[i - references[i]] + 1;
continue;
}
c = 0;
// No block copying
residuals.assign(g.Neighbours(i).begin(), g.Neighbours(i).end());
ProcessResiduals(residuals, i, adj_block, allow_random_access, rle_undo,
token_cost);
float cost = c;
for (size_t ref = 1; ref < std::min(SearchNum(), i) + 1; ref++) {
if (chain_length[i - ref] + fwd_chain_length[i] + 1 >
kMaxChainLength) {
continue;
}
adj_block.clear();
c = 0;
ComputeBlocksAndResiduals(g, i, ref, &blocks, &residuals);
ProcessBlocks(
blocks, g, i, ref, [&](size_t x) { adj_block.push_back(x); },
token_cost);
ProcessResiduals(residuals, i, adj_block, allow_random_access,
rle_undo, token_cost);
if (c + 1e-6f < cost) {
references[i] = ref;
cost = c;
}
}
if (references[i] != 0) {
chain_length[i] = chain_length[i - references[i]] + 1;
}
}
size_t has_ref = 0;
for (size_t i = 0; i < N; i++) {
if (references[i]) {
has_ref++;
}
}
fprintf(stderr, "has ref restore: %lu\n", has_ref);
}
// TODO: update references to take into account max chain length.
for (size_t i = 0; i < kNumContexts; i++) {
symbol_count[i].clear();
symbol_count[i].resize(256, 0);
}
if (round + 1 != absl::GetFlag(FLAGS_num_rounds)) {
fprintf(stderr, "Computing freqs, round %lu%20s\n", round + 1, "");
for (size_t i = 0; i < N; i++) {
if (i % 32 == 0) fprintf(stderr, "%lu/%lu\r", i, N);
adj_block.clear();
if (references[i] == 0) {
residuals.assign(g.Neighbours(i).begin(), g.Neighbours(i).end());
} else {
ComputeBlocksAndResiduals(g, i, references[i], &blocks, &residuals);
ProcessBlocks(
blocks, g, i, references[i],
[&](size_t x) { adj_block.push_back(x); }, token_cost);
}
ProcessResiduals(residuals, i, adj_block, allow_random_access, rle_undo,
token_cost);
}
for (size_t i = 0; i < kNumContexts; i++) {
float total_symbols = std::accumulate(symbol_count[i].begin(),
symbol_count[i].end(), 0ul);
if (total_symbols < 0.5f) {
continue;
}
for (size_t s = 0; s < 256; s++) {
float cnt = std::max(1.0f * symbol_count[i][s], 0.1f);
symbol_cost[i * kNumSymbols + s] = std::log(total_symbols / cnt);
symbol_count[i][s] = 0;
}
}
}
}
// Holds the index of every node degree delta in `tokens` .
std::vector<size_t> node_degree_indices;
size_t last_reference = 0;
fprintf(stderr, "Compressing%20s\n", "");
for (size_t i = 0; i < N; i++) {
if (i % 32 == 0) fprintf(stderr, "%lu/%lu\r", i, N);
fflush(stderr);
if ((allow_random_access && i % kDegreeReferenceChunkSize == 0) || i == 0) {
last_reference = 0;
last_degree_delta = g.Degree(i);
node_degree_indices.push_back(tokens.Size());
tokens.Add(kFirstDegreeContext, last_degree_delta);
} else {
size_t ctx = DegreeContext(last_degree_delta);
last_degree_delta = PackSigned(g.Degree(i) - ref);
node_degree_indices.push_back(tokens.Size());
tokens.Add(ctx, last_degree_delta);
}
ref = g.Degree(i);
if (g.Degree(i) == 0) {
continue;
}
size_t reference = references[i];
std::vector<uint32_t> residuals;
std::vector<uint32_t> blocks;
if (reference == 0) {
residuals.assign(g.Neighbours(i).begin(), g.Neighbours(i).end());
} else {
ComputeBlocksAndResiduals(g, i, reference, &blocks, &residuals);
}
std::vector<uint32_t> adj_block;
if (i != 0) {
tokens.Add(ReferenceContext(last_reference), reference);
last_reference = reference;
if (reference != 0) {
with_blocks++;
ProcessBlocks(
blocks, g, i, reference, [&](size_t x) { adj_block.push_back(x); },
[&](size_t ctx, size_t v) { tokens.Add(ctx, v); });
}
}
// Residuals.
ProcessResiduals(
residuals, i, adj_block, allow_random_access,
[&]() { tokens.RemoveLast(); },
[&](size_t ctx, size_t v) { tokens.Add(ctx, v); });
}
for (size_t i = 0; i < N; i++) {
edges += g.Degree(i);
for (size_t j = 0; j < g.Degree(i); j++) {
chksum = Checksum(chksum, i, g.Neighbours(i)[j]);
}
}
std::vector<double> bits_per_ctx;
if (allow_random_access) {
HuffmanEncode(tokens, kNumContexts, &writer, node_degree_indices,
&bits_per_ctx);
} else {
ANSEncode(tokens, kNumContexts, &writer, &bits_per_ctx);
}
auto data = std::move(writer).GetData();
auto stop = std::chrono::high_resolution_clock::now();
if (absl::GetFlag(FLAGS_print_bits_breakdown)) {
double degree_bits = 0;
for (size_t i = kFirstDegreeContext; i < kReferenceContextBase; i++) {
degree_bits += bits_per_ctx[i];
}
double reference_bits = 0;
for (size_t i = kReferenceContextBase; i < kBlockCountContext; i++) {
reference_bits += bits_per_ctx[i];
}
double block_bits = 0;
for (size_t i = kBlockCountContext; i < kFirstResidualBaseContext; i++) {
block_bits += bits_per_ctx[i];
}
double first_residual_bits = 0;
for (size_t i = kFirstResidualBaseContext; i < kResidualBaseContext; i++) {
first_residual_bits += bits_per_ctx[i];
}
double residual_bits = 0;
for (size_t i = kResidualBaseContext; i < kNumContexts; i++) {
residual_bits += bits_per_ctx[i];
}
double total_bits = data.size() * 8.0f;
fprintf(stderr, "Degree bits: %10.2f [%5.2f bits/edge]\n",
degree_bits, degree_bits / edges);
fprintf(stderr, "Reference bits: %10.2f [%5.2f bits/edge]\n",
reference_bits, reference_bits / edges);
fprintf(stderr, "Block bits: %10.2f [%5.2f bits/edge]\n",
block_bits, block_bits / edges);
fprintf(stderr, "First residual bits: %10.2f [%5.2f bits/edge]\n",
first_residual_bits, first_residual_bits / edges);
fprintf(stderr, "Residual bits: %10.2f [%5.2f bits/edge]\n",
residual_bits, residual_bits / edges);
fprintf(stderr, "Total bits: %10.2f [%5.2f bits/edge]\n",
total_bits, total_bits / edges);
}
float elapsed =
std::chrono::duration_cast<std::chrono::microseconds>(stop - start)
.count();
fprintf(stderr, "Compressed %.2f ME/s (%zu) to %.2f BPE. Checksum: %lx\n",
edges / elapsed, edges, 8.0 * data.size() / edges, chksum);
if (checksum) *checksum = chksum;
return data;
}
} // namespace zuckerli
| 33.134579 | 80 | 0.565239 | [
"vector"
] |
4975dcbf537bfbb4f9dd6717d9ee8cb4e1596291 | 3,951 | cc | C++ | src/Helpers.cc | philberty/overflow | 7370cd4d145f290c32a8c020ae849241ac9b1082 | [
"MIT"
] | 4 | 2020-03-27T21:17:06.000Z | 2022-02-11T15:20:17.000Z | src/Helpers.cc | philberty/overflow | 7370cd4d145f290c32a8c020ae849241ac9b1082 | [
"MIT"
] | null | null | null | src/Helpers.cc | philberty/overflow | 7370cd4d145f290c32a8c020ae849241ac9b1082 | [
"MIT"
] | null | null | null | // -*-c++-*-
// Copyright (c) 2017 Philip Herron.
//
// 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 "Helpers.h"
#include <cstring>
#include <sstream>
std::string
Overflow::Helper::intToString(int number)
{
std::ostringstream ss;
ss << number;
return ss.str();
}
std::string
Overflow::Helper::findKeyAndValuePair(const std::vector<std::string>* values,
const std::string& key)
{
for (auto it = values->begin(); it != values->end(); ++it) {
const std::string& value = *it;
if (value.find(key) != std::string::npos) {
return value;
}
}
return std::string();
}
std::vector<std::string>
Overflow::Helper::stringSplit(const std::string& data,
std::string token)
{
std::vector<std::string> output;
std::string input(data);
size_t pos = std::string::npos;
do {
pos = input.find(token);
output.push_back(input.substr(0, pos));
if (std::string::npos != pos) {
input = input.substr(pos + token.size());
}
} while (std::string::npos != pos);
return output;
}
std::vector<std::pair<int, int>>
Overflow::Helper::splitBuffer(const unsigned char * buffer,
const size_t length,
const std::string& delim)
{
std::vector<std::pair<int, int>> lines;
size_t delim_length = delim.size();
size_t line_begin_offset = 0;
for (size_t i = 0; i < length; ++i)
{
unsigned char idx = buffer[i];
unsigned char first_char = delim[0];
if (first_char == idx)
{
bool is_long_enough = (length - i) >= delim_length;
if (is_long_enough)
{
const void* cmp_buf = buffer + i;
bool is_match = memcmp(cmp_buf, delim.c_str(), delim_length) == 0;
if (is_match)
{
int line_length = (i + delim_length) - line_begin_offset;
lines.push_back(std::pair<int, int>(line_begin_offset, line_length));
i += delim_length - 1;
line_begin_offset = i + 1;
}
}
}
}
// handle trailing and empty cases
if (lines.size() == 0)
{
lines.push_back(std::pair<int,int>(0, length));
}
else
{
std::pair<int,int>& last_pair = lines.back();
size_t total = last_pair.first + last_pair.second;
bool did_read_end = total == length;
if (did_read_end == false)
{
// offset is always the total from previous lines as each
// split is inclusive of delim
lines.push_back(std::pair<int,int>(total, length - total));
}
}
return lines;
}
| 31.357143 | 89 | 0.579094 | [
"vector"
] |
4977625357bacb66a9e95413665453ffb0b278d9 | 36,604 | cpp | C++ | src/terminal/Screen.cpp | 3n16m4/contour | f9b98e1bc186c59b7f23526b8568bc733cebe47a | [
"Apache-2.0"
] | null | null | null | src/terminal/Screen.cpp | 3n16m4/contour | f9b98e1bc186c59b7f23526b8568bc733cebe47a | [
"Apache-2.0"
] | null | null | null | src/terminal/Screen.cpp | 3n16m4/contour | f9b98e1bc186c59b7f23526b8568bc733cebe47a | [
"Apache-2.0"
] | null | null | null | /**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 <terminal/Screen.h>
#include <terminal/Commands.h>
#include <terminal/VTType.h>
#include <terminal/Logger.h>
#include <crispy/algorithm.h>
#include <crispy/escape.h>
#include <crispy/times.h>
#include <unicode/emoji_segmenter.h>
#include <unicode/word_segmenter.h>
#include <unicode/grapheme_segmenter.h>
#include <unicode/utf8.h>
#include <algorithm>
#include <iterator>
#include <sstream>
#if defined(LIBTERMINAL_EXECUTION_PAR)
#include <execution>
#define LIBTERMINAL_EXECUTION_COMMA(par) (std::execution:: par),
#else
#define LIBTERMINAL_EXECUTION_COMMA(par) /*!*/
#endif
using namespace std;
using namespace crispy;
namespace terminal {
Screen::Screen(WindowSize const& _size,
optional<size_t> _maxHistoryLineCount,
ModeSwitchCallback _useApplicationCursorKeys,
function<void()> _onWindowTitleChanged,
ResizeWindowCallback _resizeWindow,
SetApplicationKeypadMode _setApplicationkeypadMode,
SetBracketedPaste _setBracketedPaste,
SetMouseProtocol _setMouseProtocol,
SetMouseTransport _setMouseTransport,
SetMouseWheelMode _setMouseWheelMode,
OnSetCursorStyle _setCursorStyle,
Reply reply,
Logger const& _logger,
bool _logRaw,
bool _logTrace,
Hook onCommands,
OnBufferChanged _onBufferChanged,
std::function<void()> _bell,
std::function<RGBColor(DynamicColorName)> _requestDynamicColor,
std::function<void(DynamicColorName)> _resetDynamicColor,
std::function<void(DynamicColorName, RGBColor const&)> _setDynamicColor,
std::function<void(bool)> _setGenerateFocusEvents,
NotifyCallback _notify
) :
onCommands_{ move(onCommands) },
logger_{ _logger },
logRaw_{ _logRaw },
logTrace_{ _logTrace },
useApplicationCursorKeys_{ move(_useApplicationCursorKeys) },
onWindowTitleChanged_{ move(_onWindowTitleChanged) },
resizeWindow_{ move(_resizeWindow) },
setApplicationkeypadMode_{ move(_setApplicationkeypadMode) },
setBracketedPaste_{ move(_setBracketedPaste) },
setMouseProtocol_{ move(_setMouseProtocol) },
setMouseTransport_{ move(_setMouseTransport) },
setMouseWheelMode_{ move(_setMouseWheelMode) },
setCursorStyle_{ move(_setCursorStyle) },
reply_{ move(reply) },
commandBuilder_{ _logger },
parser_{
ref(commandBuilder_),
[this](string const& _msg) { logger_(ParserErrorEvent{_msg}); }
},
primaryBuffer_{ ScreenBuffer::Type::Main, _size, _maxHistoryLineCount },
alternateBuffer_{ ScreenBuffer::Type::Alternate, _size, nullopt },
buffer_{ &primaryBuffer_ },
size_{ _size },
maxHistoryLineCount_{ _maxHistoryLineCount },
onBufferChanged_{ move(_onBufferChanged) },
bell_{ move(_bell) },
requestDynamicColor_{ move(_requestDynamicColor) },
resetDynamicColor_{ move(_resetDynamicColor) },
setDynamicColor_{ move(_setDynamicColor) },
setGenerateFocusEvents_{ move(_setGenerateFocusEvents) },
notify_{ move(_notify) }
{
(*this)(SetMode{Mode::AutoWrap, true});
}
void Screen::setMaxHistoryLineCount(std::optional<size_t> _maxHistoryLineCount)
{
maxHistoryLineCount_ = _maxHistoryLineCount;
primaryBuffer_.maxHistoryLineCount_ = _maxHistoryLineCount;
primaryBuffer_.clampSavedLines();
// Alternate buffer does not have a history usually (and for now we keep it that way).
}
void Screen::resize(WindowSize const& _newSize)
{
// TODO: only resize current screen buffer, and then make sure we resize the other upon actual switch
primaryBuffer_.resize(_newSize);
alternateBuffer_.resize(_newSize);
size_ = _newSize;
}
void Screen::write(Command const& _command)
{
buffer_->verifyState();
visit(*this, _command);
buffer_->verifyState();
instructionCounter_++;
if (onCommands_)
onCommands_({_command});
}
void Screen::write(char const * _data, size_t _size)
{
#if defined(LIBTERMINAL_LOG_RAW)
if (logRaw_ && logger_)
logger_(RawOutputEvent{ escape(_data, _data + _size) });
#endif
commandBuilder_.commands().clear();
parser_.parseFragment(_data, _size);
buffer_->verifyState();
#if defined(LIBTERMINAL_LOG_TRACE)
if (logTrace_ && logger_)
{
auto const traces = to_mnemonic(commandBuilder_.commands(), true, true);
for (auto const& trace : traces)
logger_(TraceOutputEvent{trace});
}
#endif
for_each(
commandBuilder_.commands(),
[&](Command const& _command) {
visit(*this, _command);
instructionCounter_++;
buffer_->verifyState();
}
);
if (onCommands_)
onCommands_(commandBuilder_.commands());
}
void Screen::write(std::u32string_view const& _text)
{
for (char32_t codepoint : _text)
{
uint8_t bytes[4];
auto const len = unicode::to_utf8(codepoint, bytes);
write((char const*) bytes, len);
}
}
void Screen::render(Renderer const& _render, size_t _scrollOffset) const
{
if (!_scrollOffset)
{
for_each(
times(1, size_.rows) * times(1, size_.columns),
[&](auto pos) {
auto const [row, col] = pos;
_render(row, col, at(row, col));
}
);
}
else
{
_scrollOffset = min(_scrollOffset, buffer_->savedLines.size());
auto const historyLineCount = min(size_.rows, static_cast<unsigned int>(_scrollOffset));
auto const mainLineCount = size_.rows - historyLineCount;
cursor_pos_t rowNumber = 1;
for (auto line = prev(end(buffer_->savedLines), _scrollOffset); rowNumber <= historyLineCount; ++line, ++rowNumber)
{
if (line->size() < size_.columns)
line->resize(size_.columns);
auto column = begin(*line);
for (cursor_pos_t colNumber = 1; colNumber <= size_.columns; ++colNumber, ++column)
_render(rowNumber, colNumber, *column);
}
for (auto line = begin(buffer_->lines); line != next(begin(buffer_->lines), mainLineCount); ++line, ++rowNumber)
{
auto column = begin(*line);
for (cursor_pos_t colNumber = 1; colNumber <= size_.columns; ++colNumber, ++column)
_render(rowNumber, colNumber, *column);
}
}
}
string Screen::renderHistoryTextLine(cursor_pos_t _lineNumberIntoHistory) const
{
assert(1 <= _lineNumberIntoHistory && _lineNumberIntoHistory <= buffer_->savedLines.size());
string line;
line.reserve(size_.columns);
auto const lineIter = next(buffer_->savedLines.rbegin(), _lineNumberIntoHistory - 1);
for (Cell const& cell : *lineIter)
if (cell.codepointCount())
line += cell.toUtf8();
else
line += " "; // fill character
return line;
}
void Screen::renderSelection(terminal::Screen::Renderer const& _render) const
{
if (selector_)
selector_->render(_render);
}
vector<Selector::Range> Screen::selection() const
{
if (selector_)
return selector_->selection();
else
return {};
}
// {{{ viewport management
bool Screen::isAbsoluteLineVisible(cursor_pos_t _row) const noexcept
{
return _row >= historyLineCount() - scrollOffset_
&& _row <= historyLineCount() - scrollOffset_ + size().rows;
}
bool Screen::scrollUp(size_t _numLines)
{
if (isAlternateScreen()) // TODO: make configurable
return false;
if (auto const newOffset = min(scrollOffset_ + _numLines, historyLineCount()); newOffset != scrollOffset_)
{
scrollOffset_ = newOffset;
return true;
}
else
return false;
}
bool Screen::scrollDown(size_t _numLines)
{
if (isAlternateScreen()) // TODO: make configurable
return false;
if (auto const newOffset = scrollOffset_ >= _numLines ? scrollOffset_ - _numLines : 0; newOffset != scrollOffset_)
{
scrollOffset_ = newOffset;
return true;
}
else
return false;
}
bool Screen::scrollMarkUp()
{
if (auto const newScrollOffset = findPrevMarker(scrollOffset_); newScrollOffset.has_value())
{
scrollOffset_ = 1 + newScrollOffset.value();
return true;
}
return false;
}
bool Screen::scrollMarkDown()
{
if (auto const newScrollOffset = findNextMarker(scrollOffset_); newScrollOffset.has_value())
{
scrollOffset_ = newScrollOffset.value();
return true;
}
return false;
}
bool Screen::scrollToTop()
{
if (auto top = historyLineCount(); top != scrollOffset_)
{
scrollOffset_ = top;
return true;
}
else
return false;
}
bool Screen::scrollToBottom()
{
if (scrollOffset_ != 0)
{
scrollOffset_ = 0;
return true;
}
else
return false;
}
// }}}
// {{{ ops
void Screen::operator()(Bell const&)
{
if (bell_)
bell_();
}
void Screen::operator()(FullReset const&)
{
resetHard();
}
void Screen::operator()(Linefeed const&)
{
if (isModeEnabled(Mode::AutomaticNewLine))
buffer_->linefeed(buffer_->margin_.horizontal.from);
else
buffer_->linefeed(realCursorPosition().column);
}
void Screen::operator()(Backspace const&)
{
moveCursorTo({cursorPosition().row, cursorPosition().column > 1 ? cursorPosition().column - 1 : 1});
}
void Screen::operator()(DeviceStatusReport const&)
{
reply("\033[0n");
}
void Screen::operator()(ReportCursorPosition const&)
{
reply("\033[{};{}R", cursorPosition().row, cursorPosition().column);
}
void Screen::operator()(ReportExtendedCursorPosition const&)
{
auto const pageNum = 1;
reply("\033[{};{};{}R", cursorPosition().row, cursorPosition().column, pageNum);
}
void Screen::operator()(SendDeviceAttributes const&)
{
// See https://vt100.net/docs/vt510-rm/DA1.html
auto const id = [&]() -> string_view {
switch (terminalId_)
{
case VTType::VT100:
return "1";
case VTType::VT220:
case VTType::VT240:
return "62";
case VTType::VT320:
case VTType::VT330:
case VTType::VT340:
return "63";
case VTType::VT420:
return "64";
case VTType::VT510:
case VTType::VT520:
case VTType::VT525:
return "65";
}
return "1"; // Should never be reached.
}();
auto const attrs = to_params(
DeviceAttributes::AnsiColor |
DeviceAttributes::AnsiTextLocator |
DeviceAttributes::Columns132 |
//TODO: DeviceAttributes::NationalReplacementCharacterSets |
//TODO: DeviceAttributes::RectangularEditing |
//TODO: DeviceAttributes::SelectiveErase |
//TODO: DeviceAttributes::SixelGraphics |
//TODO: DeviceAttributes::TechnicalCharacters |
DeviceAttributes::UserDefinedKeys
);
reply("\033[?{};{}c", id, attrs);
}
void Screen::operator()(SendTerminalId const&)
{
// Note, this is "Secondary DA".
// It requests for the terminalID
// terminal protocol type
auto const Pp = static_cast<unsigned>(terminalId_);
// version number
// TODO: (PACKAGE_VERSION_MAJOR * 100 + PACKAGE_VERSION_MINOR) * 100 + PACKAGE_VERSION_MICRO
auto constexpr Pv = (LIBTERMINAL_VERSION_MAJOR * 100 + LIBTERMINAL_VERSION_MINOR) * 100 + LIBTERMINAL_VERSION_PATCH;
// ROM cardridge registration number (always 0)
auto constexpr Pc = 0;
reply("\033[>{};{};{}c", Pp, Pv, Pc);
}
void Screen::operator()(ClearToEndOfScreen const&)
{
if (isAlternateScreen() && buffer_->cursor.row == 1 && buffer_->cursor.column == 1)
buffer_->hyperlinks.clear();
(*this)(ClearToEndOfLine{});
for_each(
LIBTERMINAL_EXECUTION_COMMA(par)
next(buffer_->currentLine),
end(buffer_->lines),
[&](ScreenBuffer::Line& line) {
fill(begin(line), end(line), Cell{{}, buffer_->graphicsRendition});
}
);
}
void Screen::operator()(ClearToBeginOfScreen const&)
{
(*this)(ClearToBeginOfLine{});
for_each(
LIBTERMINAL_EXECUTION_COMMA(par)
begin(buffer_->lines),
buffer_->currentLine,
[&](ScreenBuffer::Line& line) {
fill(begin(line), end(line), Cell{{}, buffer_->graphicsRendition});
}
);
}
void Screen::operator()(ClearScreen const&)
{
// Instead of *just* clearing the screen, and thus, losing potential important content,
// we scroll up by RowCount number of lines, so move it all into history, so the user can scroll
// up in case the content is still needed.
buffer_->scrollUp(size().rows);
}
void Screen::operator()(ClearScrollbackBuffer const&)
{
if (selector_)
selector_.reset();
buffer_->savedLines.clear();
}
void Screen::operator()(EraseCharacters const& v)
{
// Spec: https://vt100.net/docs/vt510-rm/ECH.html
// It's not clear from the spec how to perform erase when inside margin and number of chars to be erased would go outside margins.
// TODO: See what xterm does ;-)
size_t const n = min(buffer_->size_.columns - realCursorPosition().column + 1, v.n == 0 ? 1 : v.n);
fill_n(buffer_->currentColumn, n, Cell{{}, buffer_->graphicsRendition});
}
void Screen::operator()(ScrollUp const& v)
{
buffer_->scrollUp(v.n);
}
void Screen::operator()(ScrollDown const& v)
{
buffer_->scrollDown(v.n);
}
void Screen::operator()(ClearToEndOfLine const&)
{
fill(
buffer_->currentColumn,
end(*buffer_->currentLine),
Cell{{}, buffer_->graphicsRendition}
);
}
void Screen::operator()(ClearToBeginOfLine const&)
{
fill(
begin(*buffer_->currentLine),
next(buffer_->currentColumn),
Cell{{}, buffer_->graphicsRendition}
);
}
void Screen::operator()(ClearLine const&)
{
fill(
begin(*buffer_->currentLine),
end(*buffer_->currentLine),
Cell{{}, buffer_->graphicsRendition}
);
}
void Screen::operator()(CursorNextLine const& v)
{
buffer_->moveCursorTo({cursorPosition().row + v.n, 1});
}
void Screen::operator()(CursorPreviousLine const& v)
{
auto const n = min(v.n, cursorPosition().row - 1);
buffer_->moveCursorTo({cursorPosition().row - n, 1});
}
void Screen::operator()(InsertCharacters const& v)
{
if (isCursorInsideMargins())
buffer_->insertChars(realCursorPosition().row, v.n);
}
void Screen::operator()(InsertLines const& v)
{
if (isCursorInsideMargins())
{
buffer_->scrollDown(
v.n,
Margin{
{ buffer_->cursor.row, buffer_->margin_.vertical.to },
buffer_->margin_.horizontal
}
);
}
}
void Screen::operator()(InsertColumns const& v)
{
if (isCursorInsideMargins())
buffer_->insertColumns(v.n);
}
void Screen::operator()(DeleteLines const& v)
{
if (isCursorInsideMargins())
{
buffer_->scrollUp(
v.n,
Margin{
{ buffer_->cursor.row, buffer_->margin_.vertical.to },
buffer_->margin_.horizontal
}
);
}
}
void Screen::operator()(DeleteCharacters const& v)
{
if (isCursorInsideMargins() && v.n != 0)
buffer_->deleteChars(realCursorPosition().row, v.n);
}
void Screen::operator()(DeleteColumns const& v)
{
if (isCursorInsideMargins())
for (cursor_pos_t lineNo = buffer_->margin_.vertical.from; lineNo <= buffer_->margin_.vertical.to; ++lineNo)
buffer_->deleteChars(lineNo, v.n);
}
void Screen::operator()(HorizontalPositionAbsolute const& v)
{
// HPA: We only care about column-mode (not pixel/inches) for now.
(*this)(MoveCursorToColumn{v.n});
}
void Screen::operator()(HorizontalPositionRelative const& v)
{
// HPR: We only care about column-mode (not pixel/inches) for now.
(*this)(MoveCursorForward{v.n});
}
void Screen::operator()(HorizontalTabClear const& v)
{
switch (v.which)
{
case HorizontalTabClear::AllTabs:
buffer_->clearAllTabs();
break;
case HorizontalTabClear::UnderCursor:
buffer_->clearTabUnderCursor();
break;
}
}
void Screen::operator()(HorizontalTabSet const&)
{
buffer_->setTabUnderCursor();
}
void Screen::operator()(Hyperlink const& v)
{
if (v.uri.empty())
buffer_->currentHyperlink = nullptr;
else if (v.id.empty())
buffer_->currentHyperlink = make_shared<HyperlinkInfo>(HyperlinkInfo{v.id, v.uri});
else if (auto i = buffer_->hyperlinks.find(v.id); i != buffer_->hyperlinks.end())
buffer_->currentHyperlink = i->second;
else
{
buffer_->currentHyperlink = make_shared<HyperlinkInfo>(HyperlinkInfo{v.id, v.uri});
buffer_->hyperlinks[v.id] = buffer_->currentHyperlink;
}
// TODO:
// Care about eviction.
// Move hyperlink store into ScreenBuffer, so it gets reset upon every switch into
// alternate screen (not for main screen!)
}
void Screen::operator()(MoveCursorUp const& v)
{
auto const n = min(v.n, cursorPosition().row - buffer_->margin_.vertical.from);
buffer_->cursor.row -= n;
buffer_->currentLine = prev(buffer_->currentLine, n);
buffer_->setCurrentColumn(cursorPosition().column);
buffer_->verifyState();
}
void Screen::operator()(MoveCursorDown const& v)
{
auto const n = min(v.n, size_.rows - cursorPosition().row);
buffer_->cursor.row += n;
buffer_->currentLine = next(buffer_->currentLine, n);
buffer_->setCurrentColumn(cursorPosition().column);
}
void Screen::operator()(MoveCursorForward const& v)
{
buffer_->incrementCursorColumn(v.n);
}
void Screen::operator()(MoveCursorBackward const& v)
{
// even if you move to 80th of 80 columns, it'll first write a char and THEN flag wrap pending
buffer_->wrapPending = false;
// TODO: skip cells that in counting when iterating backwards over a wide cell (such as emoji)
auto const n = min(v.n, buffer_->cursor.column - 1);
buffer_->setCurrentColumn(buffer_->cursor.column - n);
}
void Screen::operator()(MoveCursorToColumn const& v)
{
buffer_->wrapPending = false;
buffer_->setCurrentColumn(v.column);
}
void Screen::operator()(MoveCursorToBeginOfLine const&)
{
buffer_->wrapPending = false;
buffer_->setCurrentColumn(1);
}
void Screen::operator()(MoveCursorTo const& v)
{
moveCursorTo(Coordinate{v.row, v.column});
}
void Screen::operator()(MoveCursorToLine const& v)
{
moveCursorTo({v.row, buffer_->cursor.column});
}
void Screen::operator()(MoveCursorToNextTab const&)
{
// TODO: I guess something must remember when a \t was added, for proper move-back?
// TODO: respect HTS/TBC
if (!buffer_->tabs.empty())
{
// advance to the next tab
size_t i = 0;
while (i < buffer_->tabs.size() && buffer_->realCursorPosition().column >= buffer_->tabs[i])
++i;
auto const currentCursorColumn = cursorPosition().column;
if (i < buffer_->tabs.size())
(*this)(MoveCursorForward{buffer_->tabs[i] - currentCursorColumn});
else if (buffer_->realCursorPosition().column < buffer_->margin_.horizontal.to)
(*this)(MoveCursorForward{buffer_->margin_.horizontal.to - currentCursorColumn});
else
(*this)(CursorNextLine{1});
}
else if (buffer_->tabWidth)
{
// default tab settings
if (buffer_->realCursorPosition().column < buffer_->margin_.horizontal.to)
{
auto const n = min(
buffer_->tabWidth - (buffer_->cursor.column - 1) % buffer_->tabWidth,
size_.columns - cursorPosition().column
);
(*this)(MoveCursorForward{n});
}
else
(*this)(CursorNextLine{1});
}
else
{
// no tab stops configured
if (buffer_->realCursorPosition().column < buffer_->margin_.horizontal.to)
// then TAB moves to the end of the screen
(*this)(MoveCursorToColumn{buffer_->margin_.horizontal.to});
else
// then TAB moves to next line left margin
(*this)(CursorNextLine{1});
}
}
void Screen::operator()(Notify const& _notify)
{
cout << "Screen.NOTIFY: title: '" << _notify.title << "', content: '" << _notify.content << "'\n";
if (notify_)
notify_(_notify.title, _notify.content);
}
void Screen::operator()(CursorBackwardTab const& v)
{
if (v.count == 0)
return;
if (!buffer_->tabs.empty())
{
for (unsigned k = 0; k < v.count; ++k)
{
auto const i = std::find_if(rbegin(buffer_->tabs), rend(buffer_->tabs),
[&](auto tabPos) -> bool {
return tabPos <= cursorPosition().column - 1;
});
if (i != rend(buffer_->tabs))
{
// prev tab found -> move to prev tab
(*this)(MoveCursorToColumn{*i});
}
else
{
(*this)(MoveCursorToColumn{buffer_->margin_.horizontal.from});
break;
}
}
}
else if (buffer_->tabWidth)
{
// default tab settings
if (buffer_->cursor.column <= buffer_->tabWidth)
(*this)(MoveCursorToBeginOfLine{});
else
{
auto const m = buffer_->cursor.column % buffer_->tabWidth;
auto const n = m
? (v.count - 1) * buffer_->tabWidth + m
: v.count * buffer_->tabWidth + m;
(*this)(MoveCursorBackward{n - 1});
}
}
else
{
// no tab stops configured
(*this)(MoveCursorToBeginOfLine{});
}
}
void Screen::operator()(SaveCursor const&)
{
buffer_->saveState();
}
void Screen::operator()(RestoreCursor const&)
{
buffer_->restoreState();
}
void Screen::operator()(Index const&)
{
if (realCursorPosition().row == buffer_->margin_.vertical.to)
buffer_->scrollUp(1);
else
moveCursorTo({cursorPosition().row + 1, cursorPosition().column});
}
void Screen::operator()(ReverseIndex const&)
{
if (realCursorPosition().row == buffer_->margin_.vertical.from)
buffer_->scrollDown(1);
else
moveCursorTo({cursorPosition().row - 1, cursorPosition().column});
}
void Screen::operator()(BackIndex const&)
{
if (realCursorPosition().column == buffer_->margin_.horizontal.from)
;// TODO: scrollRight(1);
else
moveCursorTo({cursorPosition().row, cursorPosition().column - 1});
}
void Screen::operator()(ForwardIndex const&)
{
if (realCursorPosition().column == buffer_->margin_.horizontal.to)
;// TODO: scrollLeft(1);
else
moveCursorTo({cursorPosition().row, cursorPosition().column + 1});
}
void Screen::operator()(SetForegroundColor const& v)
{
buffer_->graphicsRendition.foregroundColor = v.color;
}
void Screen::operator()(SetBackgroundColor const& v)
{
buffer_->graphicsRendition.backgroundColor = v.color;
}
void Screen::operator()(SetUnderlineColor const& v)
{
buffer_->graphicsRendition.underlineColor = v.color;
}
void Screen::operator()(SetCursorStyle const& v)
{
if (setCursorStyle_)
setCursorStyle_(v.display, v.shape);
}
void Screen::operator()(SetGraphicsRendition const& v)
{
// TODO: optimize this as there are only 3 cases
// 1.) reset
// 2.) set some bits |=
// 3.) clear some bits &= ~
switch (v.rendition)
{
case GraphicsRendition::Reset:
buffer_->graphicsRendition = {};
break;
case GraphicsRendition::Bold:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Bold;
break;
case GraphicsRendition::Faint:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Faint;
break;
case GraphicsRendition::Italic:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Italic;
break;
case GraphicsRendition::Underline:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Underline;
break;
case GraphicsRendition::Blinking:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Blinking;
break;
case GraphicsRendition::Inverse:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Inverse;
break;
case GraphicsRendition::Hidden:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Hidden;
break;
case GraphicsRendition::CrossedOut:
buffer_->graphicsRendition.styles |= CharacterStyleMask::CrossedOut;
break;
case GraphicsRendition::DoublyUnderlined:
buffer_->graphicsRendition.styles |= CharacterStyleMask::DoublyUnderlined;
break;
case GraphicsRendition::CurlyUnderlined:
buffer_->graphicsRendition.styles |= CharacterStyleMask::CurlyUnderlined;
break;
case GraphicsRendition::DottedUnderline:
buffer_->graphicsRendition.styles |= CharacterStyleMask::DottedUnderline;
break;
case GraphicsRendition::DashedUnderline:
buffer_->graphicsRendition.styles |= CharacterStyleMask::DashedUnderline;
break;
case GraphicsRendition::Overline:
buffer_->graphicsRendition.styles |= CharacterStyleMask::Overline;
break;
case GraphicsRendition::Normal:
buffer_->graphicsRendition.styles &= ~(CharacterStyleMask::Bold | CharacterStyleMask::Faint);
break;
case GraphicsRendition::NoItalic:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::Italic;
break;
case GraphicsRendition::NoUnderline:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::Underline;
break;
case GraphicsRendition::NoBlinking:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::Blinking;
break;
case GraphicsRendition::NoInverse:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::Inverse;
break;
case GraphicsRendition::NoHidden:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::Hidden;
break;
case GraphicsRendition::NoCrossedOut:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::CrossedOut;
break;
case GraphicsRendition::NoOverline:
buffer_->graphicsRendition.styles &= ~CharacterStyleMask::Overline;
break;
}
}
void Screen::operator()(SetMark const&)
{
buffer_->currentLine->marked = true;
}
void Screen::operator()(SetMode const& v)
{
buffer_->setMode(v.mode, v.enable);
switch (v.mode)
{
case Mode::UseAlternateScreen:
if (v.enable)
setBuffer(ScreenBuffer::Type::Alternate);
else
setBuffer(ScreenBuffer::Type::Main);
break;
case Mode::UseApplicationCursorKeys:
if (useApplicationCursorKeys_)
useApplicationCursorKeys_(v.enable);
if (isAlternateScreen() && setMouseWheelMode_)
{
if (v.enable)
setMouseWheelMode_(InputGenerator::MouseWheelMode::ApplicationCursorKeys);
else
setMouseWheelMode_(InputGenerator::MouseWheelMode::NormalCursorKeys);
}
break;
case Mode::BracketedPaste:
if (setBracketedPaste_)
setBracketedPaste_(v.enable);
break;
case Mode::MouseSGR:
if (setMouseTransport_)
setMouseTransport_(MouseTransport::SGR);
break;
case Mode::MouseExtended:
if (setMouseTransport_)
setMouseTransport_(MouseTransport::Extended);
break;
case Mode::MouseURXVT:
if (setMouseTransport_)
setMouseTransport_(MouseTransport::URXVT);
break;
case Mode::MouseAlternateScroll:
if (setMouseWheelMode_)
{
if (v.enable)
setMouseWheelMode_(InputGenerator::MouseWheelMode::ApplicationCursorKeys);
else
setMouseWheelMode_(InputGenerator::MouseWheelMode::NormalCursorKeys);
}
break;
case Mode::FocusTracking:
if (setGenerateFocusEvents_)
setGenerateFocusEvents_(v.enable);
break;
default:
break;
}
}
void Screen::operator()(RequestMode const& v)
{
enum class ModeResponse { // TODO: respect response 0, 3, 4.
NotRecognized = 0,
Set = 1,
Reset = 2,
PermanentlySet = 3,
PermanentlyReset = 4
};
ModeResponse const modeResponse = isModeEnabled(v.mode)
? ModeResponse::Set
: ModeResponse::Reset;
if (isAnsiMode(v.mode))
reply("\033[{};{}$y", to_code(v.mode), static_cast<unsigned>(modeResponse));
else
reply("\033[?{};{}$y", to_code(v.mode), static_cast<unsigned>(modeResponse));
}
void Screen::operator()(SetTopBottomMargin const& _margin)
{
auto const bottom = _margin.bottom.has_value()
? min(_margin.bottom.value(), size_.rows)
: size_.rows;
auto const top = _margin.top.value_or(1);
if (top < bottom)
{
buffer_->margin_.vertical.from = top;
buffer_->margin_.vertical.to = bottom;
buffer_->moveCursorTo({1, 1});
}
}
void Screen::operator()(SetLeftRightMargin const& margin)
{
if (isModeEnabled(Mode::LeftRightMargin))
{
auto const right = margin.right.has_value()
? min(margin.right.value(), size_.columns)
: size_.columns;
auto const left = margin.left.value_or(1);
if (left + 1 < right)
{
buffer_->margin_.horizontal.from = left;
buffer_->margin_.horizontal.to = right;
buffer_->moveCursorTo({1, 1});
}
}
}
void Screen::operator()(ScreenAlignmentPattern const&)
{
// sets the margins to the extremes of the page
buffer_->margin_.vertical.from = 1;
buffer_->margin_.vertical.to = size_.rows;
buffer_->margin_.horizontal.from = 1;
buffer_->margin_.horizontal.to = size_.columns;
// and moves the cursor to the home position
moveCursorTo({1, 1});
// fills the complete screen area with a test pattern
for_each(
LIBTERMINAL_EXECUTION_COMMA(par)
begin(buffer_->lines),
end(buffer_->lines),
[&](ScreenBuffer::Line& line) {
fill(
LIBTERMINAL_EXECUTION_COMMA(par)
begin(line),
end(line),
ScreenBuffer::Cell{'X', buffer_->graphicsRendition}
);
}
);
}
void Screen::operator()(SendMouseEvents const& v)
{
if (setMouseProtocol_)
setMouseProtocol_(v.protocol, v.enable);
}
void Screen::operator()(ApplicationKeypadMode const& v)
{
if (setApplicationkeypadMode_)
setApplicationkeypadMode_(v.enable);
}
void Screen::operator()(DesignateCharset const&)
{
// TODO
}
void Screen::operator()(SingleShiftSelect const&)
{
// TODO
}
void Screen::operator()(SoftTerminalReset const&)
{
resetSoft();
}
void Screen::operator()(ChangeIconTitle const&)
{
// Not supported (for now), ignored.
}
void Screen::operator()(ChangeWindowTitle const& v)
{
windowTitle_ = v.title;
if (onWindowTitleChanged_)
onWindowTitleChanged_();
}
void Screen::operator()(SaveWindowTitle const&)
{
savedWindowTitles_.push(windowTitle_);
}
void Screen::operator()(RestoreWindowTitle const&)
{
if (!savedWindowTitles_.empty())
{
windowTitle_ = savedWindowTitles_.top();
savedWindowTitles_.pop();
if (onWindowTitleChanged_)
onWindowTitleChanged_();
}
}
void Screen::operator()(ResizeWindow const& v)
{
if (resizeWindow_)
resizeWindow_(v.width, v.height, v.unit == ResizeWindow::Unit::Pixels);
}
void Screen::operator()(AppendChar const& v)
{
buffer_->appendChar(v.ch, instructionCounter_ == 1);
instructionCounter_ = 0;
}
void Screen::operator()(RequestDynamicColor const& v)
{
if (requestDynamicColor_)
{
reply("\033]{};{}\x07",
setDynamicColorCommand(v.name),
setDynamicColorValue(requestDynamicColor_(v.name))
);
}
}
void Screen::operator()(RequestTabStops const&)
{
// Response: `DCS 2 $ u Pt ST`
ostringstream dcs;
dcs << "\033P2$u"; // DCS
if (!buffer_->tabs.empty())
{
for (size_t const i : times(buffer_->tabs.size()))
{
if (i)
dcs << '/';
dcs << buffer_->tabs[i];
}
}
else if (buffer_->tabWidth != 0)
{
dcs << buffer_->tabWidth + 1;
for (unsigned column = 2 * buffer_->tabWidth + 1; column <= size().columns; column += buffer_->tabWidth)
dcs << '/' << column;
}
dcs << '\x5c'; // ST
reply(dcs.str());
}
void Screen::operator()(ResetDynamicColor const& v)
{
if (resetDynamicColor_)
resetDynamicColor_(v.name);
}
void Screen::operator()(SetDynamicColor const& v)
{
if (setDynamicColor_)
setDynamicColor_(v.name, v.color);
}
void Screen::operator()(DumpState const&)
{
buffer_->dumpState("Dumping screen state");
}
// }}}
// {{{ others
void Screen::resetSoft()
{
(*this)(SetGraphicsRendition{GraphicsRendition::Reset}); // SGR
(*this)(MoveCursorTo{1, 1}); // DECSC (Save cursor state)
(*this)(SetMode{Mode::VisibleCursor, true}); // DECTCEM (Text cursor enable)
(*this)(SetMode{Mode::Origin, false}); // DECOM
(*this)(SetMode{Mode::KeyboardAction, false}); // KAM
(*this)(SetMode{Mode::AutoWrap, false}); // DECAWM
(*this)(SetMode{Mode::Insert, false}); // IRM
(*this)(SetMode{Mode::UseApplicationCursorKeys, false}); // DECCKM (Cursor keys)
(*this)(SetTopBottomMargin{1, size().rows}); // DECSTBM
(*this)(SetLeftRightMargin{1, size().columns}); // DECRLM
// TODO: DECNKM (Numeric keypad)
// TODO: DECSCA (Select character attribute)
// TODO: DECNRCM (National replacement character set)
// TODO: GL, GR (G0, G1, G2, G3)
// TODO: DECAUPSS (Assign user preference supplemental set)
// TODO: DECSASD (Select active status display)
// TODO: DECKPM (Keyboard position mode)
// TODO: DECPCTERM (PCTerm mode)
}
void Screen::resetHard()
{
primaryBuffer_.reset();
alternateBuffer_.reset();
setBuffer(ScreenBuffer::Type::Main);
}
void Screen::moveCursorTo(Coordinate to)
{
buffer_->wrapPending = false;
buffer_->moveCursorTo(to);
}
void Screen::setBuffer(ScreenBuffer::Type _type)
{
if (bufferType() != _type)
{
switch (_type)
{
case ScreenBuffer::Type::Main:
if (setMouseWheelMode_)
setMouseWheelMode_(InputGenerator::MouseWheelMode::Default);
buffer_ = &primaryBuffer_;
break;
case ScreenBuffer::Type::Alternate:
if (buffer_->isModeEnabled(Mode::MouseAlternateScroll))
setMouseWheelMode_(InputGenerator::MouseWheelMode::ApplicationCursorKeys);
else
setMouseWheelMode_(InputGenerator::MouseWheelMode::NormalCursorKeys);
buffer_ = &alternateBuffer_;
break;
}
if (selector_)
selector_.reset();
if (onBufferChanged_)
onBufferChanged_(_type);
}
}
// }}}
} // namespace terminal
| 29.073868 | 134 | 0.624577 | [
"render",
"shape",
"vector"
] |
21b2589a00e34f399dd12719c3902f971af203d3 | 591 | cc | C++ | src/counter_group.unknown.cc | rayglover-ibm/cpu-perf-counters.js | 3f578312bffdbcf30498c60a377d5d4fea97f7a3 | [
"Apache-2.0"
] | null | null | null | src/counter_group.unknown.cc | rayglover-ibm/cpu-perf-counters.js | 3f578312bffdbcf30498c60a377d5d4fea97f7a3 | [
"Apache-2.0"
] | null | null | null | src/counter_group.unknown.cc | rayglover-ibm/cpu-perf-counters.js | 3f578312bffdbcf30498c60a377d5d4fea97f7a3 | [
"Apache-2.0"
] | null | null | null | #include "counter_group.h"
#include <stdexcept>
namespace node_perf_counters
{
struct counter_group::impl { };
/** ------------------------------------------------------------------------------------------- */
counter_group::counter_group(const std::vector<counter>&)
: _pimpl{ new impl() }
{
throw std::runtime_error("Unsupported platform");
}
int32_t counter_group::id() { return -1; }
void counter_group::read(std::function<void(counter, std::int64_t)>&&) { }
void counter_group::reset() { }
counter_group::~counter_group() { }
} | 25.695652 | 102 | 0.536379 | [
"vector"
] |
21b59a9b0299344a8d21351fb774f0ff1ad1d6b6 | 436 | cpp | C++ | Notes/chap3/code/Q3/main.cpp | Alexbeast-CN/Notes2SLAM | 43651d8548431b26538739cc3130d315de4d4f7f | [
"MIT"
] | null | null | null | Notes/chap3/code/Q3/main.cpp | Alexbeast-CN/Notes2SLAM | 43651d8548431b26538739cc3130d315de4d4f7f | [
"MIT"
] | null | null | null | Notes/chap3/code/Q3/main.cpp | Alexbeast-CN/Notes2SLAM | 43651d8548431b26538739cc3130d315de4d4f7f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <Eigen/Core>
#include <Eigen/Geometry>
using namespace std;
using namespace Eigen;
int main(int argc, char const *argv[])
{
// 证明1:
cout << "证明1: " << endl;
// 首先创建创建一个随机的四元数,并将其转变为旋转矩阵
Vector3d q = Vector3d::Random();
Isometry3d R = Isometry3d::Identity(); // 矩阵初始化
R.rotate(q);
//证明 R*R^T = I
auto I = R * R.inverse();
return 0;
}
| 18.166667 | 66 | 0.587156 | [
"geometry"
] |
21b663eda0388f0144aaec08cf55e3dc841fa634 | 8,671 | cxx | C++ | Applications/DistanceTransform/niftkDistanceTransform.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | Applications/DistanceTransform/niftkDistanceTransform.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | Applications/DistanceTransform/niftkDistanceTransform.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include <niftkLogHelper.h>
#include <niftkConversionUtils.h>
#include <itkCommandLineHelper.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkNifTKImageIOFactory.h>
#include <itkDanielssonDistanceMapImageFilter.h>
#include <itkInvertIntensityBetweenMaxAndMinImageFilter.h>
#include <itkAddImageFilter.h>
#include <itkBinaryCrossStructuringElement.h>
#include <itkBinaryErodeImageFilter.h>
#include <itkNegateImageFilter.h>
#include <itkAbsImageFilter.h>
/*!
* \file niftkDistanceTransform.cxx
* \page niftkDistanceTransform
* \section niftkDistanceTransformSummary Runs the ITK DanielssonDistanceMapImageFilter, specifically for binary images, outputting the distance transform.
*/
void Usage(char *exec)
{
niftk::LogHelper::PrintCommandLineHeader(std::cout);
std::cout << " " << std::endl;
std::cout << " Runs the ITK DanielssonDistanceMapImageFilter, specifically for binary images, outputting the distance transform." << std::endl;
std::cout << " Assumes your input image, has 1 object, with background = 0, and foreground = 1." << std::endl;
std::cout << " " << std::endl;
std::cout << " " << exec << " -i inputFileName -o outputFileName [options]" << std::endl;
std::cout << " " << std::endl;
std::cout << "*** [mandatory] ***" << std::endl << std::endl;
std::cout << " -i <filename> Input image " << std::endl;
std::cout << " -o <filename> Output image" << std::endl << std::endl;
std::cout << "*** [options] ***" << std::endl << std::endl;
std::cout << " -invert If specified, will invert the input image prior to calculating distances. " << std::endl;
std::cout << " -internal If specified, will calculate distances internal to the object. " << std::endl;
std::cout << " Usefull if you have 1 object, and want to simulate a level set." << std::endl;
std::cout << " -abs If specified, will calculate absolute distances, " << std::endl;
std::cout << " otherwise internal distances are negative." << std::endl;
}
struct arguments
{
std::string inputImage;
std::string outputImage;
bool internal;
bool invert;
bool absolute;
};
template <int Dimension, class PixelType>
int DoMain(arguments args)
{
typedef typename itk::Image< PixelType, Dimension > InputImageType;
typedef typename itk::ImageFileReader< InputImageType > InputImageReaderType;
typedef typename itk::ImageFileWriter< InputImageType > OutputImageWriterType;
typedef typename itk::InvertIntensityBetweenMaxAndMinImageFilter<InputImageType> InvertFilterType;
typedef typename itk::DanielssonDistanceMapImageFilter<InputImageType, InputImageType> DistanceFilterType;
try
{
typename InputImageReaderType::Pointer imageReader = InputImageReaderType::New();
typename DistanceFilterType::Pointer distanceFilter = DistanceFilterType::New();
typename OutputImageWriterType::Pointer imageWriter = OutputImageWriterType::New();
imageReader->SetFileName(args.inputImage);
imageReader->Update();
typename InputImageType::Pointer image = imageReader->GetOutput();
image->DisconnectPipeline();
imageWriter->SetFileName(args.outputImage);
if ( args.invert )
{
typename InvertFilterType::Pointer invertInputImageFilter = InvertFilterType::New();
invertInputImageFilter->SetInput( image );
invertInputImageFilter->Update();
image = invertInputImageFilter->GetOutput();
image->DisconnectPipeline();
}
distanceFilter->SetInput( image );
distanceFilter->SetSquaredDistance(false);
distanceFilter->SetInputIsBinary(true);
distanceFilter->SetUseImageSpacing(true);
distanceFilter->Update();
if (args.internal)
{
typedef typename itk::BinaryCrossStructuringElement<PixelType, Dimension> StructuringElementType;
StructuringElementType element;
element.SetRadius(1);
element.CreateStructuringElement();
typedef typename itk::BinaryErodeImageFilter<InputImageType, InputImageType, StructuringElementType> ErodeImageFilterType;
typename ErodeImageFilterType::Pointer erodeFilter = ErodeImageFilterType::New();
erodeFilter->SetInput( image );
erodeFilter->SetKernel(element);
erodeFilter->SetErodeValue(1);
erodeFilter->SetBackgroundValue(0);
erodeFilter->SetBoundaryToForeground(false);
erodeFilter->Update();
typename InvertFilterType::Pointer invertInputImageFilter = InvertFilterType::New();
invertInputImageFilter->SetInput(erodeFilter->GetOutput());
typename DistanceFilterType::Pointer insideDistanceFilter = DistanceFilterType::New();
insideDistanceFilter->SetInput(invertInputImageFilter->GetOutput());
insideDistanceFilter->SetSquaredDistance(false);
insideDistanceFilter->SetInputIsBinary(true);
insideDistanceFilter->SetUseImageSpacing(true);
typedef typename itk::NegateImageFilter<InputImageType, InputImageType> NegateFilterType;
typename NegateFilterType::Pointer negateFilter = NegateFilterType::New();
negateFilter->SetInput(insideDistanceFilter->GetOutput());
typedef typename itk::AddImageFilter<InputImageType, InputImageType> AddFilterType;
typename AddFilterType::Pointer addFilter = AddFilterType::New();
addFilter->SetInput(0, distanceFilter->GetOutput());
addFilter->SetInput(1, negateFilter->GetOutput());
addFilter->Update();
image = addFilter->GetOutput();
}
else
{
image = distanceFilter->GetOutput();
}
image->DisconnectPipeline();
if ( args.absolute )
{
typedef itk::AbsImageFilter< InputImageType, InputImageType > AbsImageFilterType;
typename AbsImageFilterType::Pointer absFilter = AbsImageFilterType::New();
absFilter->SetInput( image );
absFilter->Update();
image = absFilter->GetOutput();
image->DisconnectPipeline();
}
imageWriter->SetInput(image);
imageWriter->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "Failed: " << err << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/**
* \brief Takes image1 and image2 and adds them together
*/
int main(int argc, char** argv)
{
itk::NifTKImageIOFactory::Initialize();
// To pass around command line args
struct arguments args;
args.invert = false;
args.internal = false;
args.absolute = false;
// Parse command line args
for(int i=1; i < argc; i++){
if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0){
Usage(argv[0]);
return -1;
}
else if(strcmp(argv[i], "-i") == 0){
args.inputImage=argv[++i];
std::cout << "Set -i=" << args.inputImage << std::endl;
}
else if(strcmp(argv[i], "-o") == 0){
args.outputImage=argv[++i];
std::cout << "Set -o=" << args.outputImage << std::endl;
}
else if(strcmp(argv[i], "-invert") == 0){
args.invert=true;
std::cout << "Set -invert=" << niftk::ConvertToString(args.invert) << std::endl;
}
else if(strcmp(argv[i], "-internal") == 0){
args.internal=true;
std::cout << "Set -internal=" << niftk::ConvertToString(args.internal) << std::endl;
}
else if(strcmp(argv[i], "-abs") == 0){
args.absolute=true;
std::cout << "Set -abs=" << niftk::ConvertToString(args.absolute) << std::endl;
}
else {
std::cerr << argv[0] << ":\tParameter " << argv[i] << " unknown." << std::endl;
return -1;
}
}
// Validate command line args
if (args.inputImage.length() == 0 || args.outputImage.length() == 0)
{
Usage(argv[0]);
return EXIT_FAILURE;
}
int dims = itk::PeekAtImageDimension(args.inputImage);
if (dims != 2 && dims != 3)
{
std::cout << "Unsupported image dimension" << std::endl;
return EXIT_FAILURE;
}
int result;
if (dims == 2)
{
result = DoMain<2, float>(args);
}
else
{
result = DoMain<3, float>(args);
}
return result;
}
| 34.272727 | 155 | 0.662207 | [
"object",
"transform"
] |
21b9f713f302ae53eff6f5599b74651b0fdfc089 | 1,079 | cpp | C++ | LeetCode/Tag/Breadth-first Search/cpp/1091.shortest-path-in-binary-matrix.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 17 | 2017-08-12T14:42:46.000Z | 2022-02-26T16:35:44.000Z | LeetCode/Tag/Breadth-first Search/cpp/1091.shortest-path-in-binary-matrix.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 21 | 2019-09-20T07:06:27.000Z | 2021-11-02T10:30:50.000Z | LeetCode/Tag/Breadth-first Search/cpp/1091.shortest-path-in-binary-matrix.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 21 | 2017-05-28T10:15:07.000Z | 2021-07-20T07:19:58.000Z | class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
if (grid[0][0] == 1) return -1;
int n = grid.size();
if (n == 1) return 1;
queue<tuple<int, int>> q;
q.push({0, 0});
grid[0][0] = -1;
int pathLen = 1, r, c;
int dirn[8][2] = {{-1,-1}, {-1,0}, {-1,1}, {0,1},
{1,1}, {1,0}, {1,-1}, {0,-1}};
while (!q.empty()) {
++pathLen;
int qsize = q.size();
while (qsize--) {
tie(r, c) = q.front(); q.pop();
for (int i = 0; i < 8; ++i) {
int rr = r + dirn[i][0];
int cc = c + dirn[i][1];
if (rr < 0 || rr == n || cc < 0 || cc == n || grid[rr][cc] != 0)
continue;
if (rr == n-1 && cc == n-1)
return pathLen;
q.push({rr, cc});
grid[rr][cc] = -1;
}
}
}
return -1;
}
}; | 30.828571 | 84 | 0.317887 | [
"vector"
] |
21c6e0dfef47a2a06a367ce32563696679aedb17 | 5,215 | cpp | C++ | build/linux-build/Sources/src/differ/data/RayCollisionHelper.cpp | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/differ/data/RayCollisionHelper.cpp | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/src/differ/data/RayCollisionHelper.cpp | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | // Generated by Haxe 4.0.5
#include <hxcpp.h>
#ifndef INCLUDED_differ_data_RayCollision
#include <hxinc/differ/data/RayCollision.h>
#endif
#ifndef INCLUDED_differ_data_RayCollisionHelper
#include <hxinc/differ/data/RayCollisionHelper.h>
#endif
#ifndef INCLUDED_differ_math_Vector
#include <hxinc/differ/math/Vector.h>
#endif
#ifndef INCLUDED_differ_shapes_Ray
#include <hxinc/differ/shapes/Ray.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_b624bc43be442e83_66_hitStartX,"differ.data.RayCollisionHelper","hitStartX",0xea174bd9,"differ.data.RayCollisionHelper.hitStartX","differ/data/RayCollision.hx",66,0xad474e0e)
HX_LOCAL_STACK_FRAME(_hx_pos_b624bc43be442e83_71_hitStartY,"differ.data.RayCollisionHelper","hitStartY",0xea174bda,"differ.data.RayCollisionHelper.hitStartY","differ/data/RayCollision.hx",71,0xad474e0e)
HX_LOCAL_STACK_FRAME(_hx_pos_b624bc43be442e83_80_hitEndX,"differ.data.RayCollisionHelper","hitEndX",0x1e4f6780,"differ.data.RayCollisionHelper.hitEndX","differ/data/RayCollision.hx",80,0xad474e0e)
HX_LOCAL_STACK_FRAME(_hx_pos_b624bc43be442e83_89_hitEndY,"differ.data.RayCollisionHelper","hitEndY",0x1e4f6781,"differ.data.RayCollisionHelper.hitEndY","differ/data/RayCollision.hx",89,0xad474e0e)
namespace differ{
namespace data{
void RayCollisionHelper_obj::__construct() { }
Dynamic RayCollisionHelper_obj::__CreateEmpty() { return new RayCollisionHelper_obj; }
void *RayCollisionHelper_obj::_hx_vtable = 0;
Dynamic RayCollisionHelper_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< RayCollisionHelper_obj > _hx_result = new RayCollisionHelper_obj();
_hx_result->__construct();
return _hx_result;
}
bool RayCollisionHelper_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x5c3d6c16;
}
Float RayCollisionHelper_obj::hitStartX( ::differ::data::RayCollision data){
HX_STACKFRAME(&_hx_pos_b624bc43be442e83_66_hitStartX)
HXDLIN( 66) Float data1 = data->ray->start->x;
HXDLIN( 66) return (data1 + (data->ray->get_dir()->x * data->start));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(RayCollisionHelper_obj,hitStartX,return )
Float RayCollisionHelper_obj::hitStartY( ::differ::data::RayCollision data){
HX_STACKFRAME(&_hx_pos_b624bc43be442e83_71_hitStartY)
HXDLIN( 71) Float data1 = data->ray->start->y;
HXDLIN( 71) return (data1 + (data->ray->get_dir()->y * data->start));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(RayCollisionHelper_obj,hitStartY,return )
Float RayCollisionHelper_obj::hitEndX( ::differ::data::RayCollision data){
HX_STACKFRAME(&_hx_pos_b624bc43be442e83_80_hitEndX)
HXDLIN( 80) Float data1 = data->ray->start->x;
HXDLIN( 80) return (data1 + (data->ray->get_dir()->x * data->end));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(RayCollisionHelper_obj,hitEndX,return )
Float RayCollisionHelper_obj::hitEndY( ::differ::data::RayCollision data){
HX_STACKFRAME(&_hx_pos_b624bc43be442e83_89_hitEndY)
HXDLIN( 89) Float data1 = data->ray->start->y;
HXDLIN( 89) return (data1 + (data->ray->get_dir()->y * data->end));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(RayCollisionHelper_obj,hitEndY,return )
RayCollisionHelper_obj::RayCollisionHelper_obj()
{
}
bool RayCollisionHelper_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 7:
if (HX_FIELD_EQ(inName,"hitEndX") ) { outValue = hitEndX_dyn(); return true; }
if (HX_FIELD_EQ(inName,"hitEndY") ) { outValue = hitEndY_dyn(); return true; }
break;
case 9:
if (HX_FIELD_EQ(inName,"hitStartX") ) { outValue = hitStartX_dyn(); return true; }
if (HX_FIELD_EQ(inName,"hitStartY") ) { outValue = hitStartY_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo *RayCollisionHelper_obj_sMemberStorageInfo = 0;
static hx::StaticInfo *RayCollisionHelper_obj_sStaticStorageInfo = 0;
#endif
hx::Class RayCollisionHelper_obj::__mClass;
static ::String RayCollisionHelper_obj_sStaticFields[] = {
HX_("hitStartX",69,1c,0c,3a),
HX_("hitStartY",6a,1c,0c,3a),
HX_("hitEndX",10,f4,9b,d8),
HX_("hitEndY",11,f4,9b,d8),
::String(null())
};
void RayCollisionHelper_obj::__register()
{
RayCollisionHelper_obj _hx_dummy;
RayCollisionHelper_obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("differ.data.RayCollisionHelper",de,e3,2e,23);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &RayCollisionHelper_obj::__GetStatic;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mStatics = hx::Class_obj::dupFunctions(RayCollisionHelper_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = hx::TCanCast< RayCollisionHelper_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = RayCollisionHelper_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = RayCollisionHelper_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace differ
} // end namespace data
| 38.345588 | 202 | 0.772196 | [
"vector"
] |
21d25062e5227bfe5c4f01aaf0569fbce2a06bcc | 471 | cpp | C++ | 7-10-21/max_cons_ones.cpp | ahanavish/GDSC-DSA-Interview-Preparation | d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf | [
"MIT"
] | null | null | null | 7-10-21/max_cons_ones.cpp | ahanavish/GDSC-DSA-Interview-Preparation | d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf | [
"MIT"
] | null | null | null | 7-10-21/max_cons_ones.cpp | ahanavish/GDSC-DSA-Interview-Preparation | d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf | [
"MIT"
] | 1 | 2021-11-29T06:10:48.000Z | 2021-11-29T06:10:48.000Z | // https://leetcode.com/problems/max-consecutive-ones/
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& n) {
int count=0, ans=0;
for(int i=0; i<n.size(); i++)
{
if(n[i] == 1)
count++;
else
{
cout<<count;
ans = max(ans, count); //2
count = 0;
}
}
ans = max(ans, count);
return ans;
}
}; | 22.428571 | 54 | 0.40552 | [
"vector"
] |
21d357ceb3d67506a1020c11255847bc7beec6fa | 6,991 | cpp | C++ | libs/e_float/test/real/cases/test_case_00221_various_gamma_func.cpp | ckormanyos/e_float-2021 | fac3eef3aa15cc5b74fb19135d6474396cbc6fa8 | [
"BSL-1.0"
] | null | null | null | libs/e_float/test/real/cases/test_case_00221_various_gamma_func.cpp | ckormanyos/e_float-2021 | fac3eef3aa15cc5b74fb19135d6474396cbc6fa8 | [
"BSL-1.0"
] | 10 | 2021-02-08T14:43:47.000Z | 2021-03-17T15:12:27.000Z | libs/e_float/test/real/cases/test_case_00221_various_gamma_func.cpp | ckormanyos/e_float-2021 | fac3eef3aa15cc5b74fb19135d6474396cbc6fa8 | [
"BSL-1.0"
] | null | null | null |
// Copyright Christopher Kormanyos 1999 - 2021.
// 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)
// This work is based on an earlier work:
// "Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations",
// in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469
// Automatically generated file
#include <array>
#include <e_float/e_float_complex.h>
#include <e_float/e_float_functions.h>
#include <e_float/e_float_functions_complex.h>
#include <../test/real/test_case_real.h>
namespace test
{
namespace real
{
class TestCase_case_00221_various_gamma_func : public TestCaseReal
{
public:
TestCase_case_00221_various_gamma_func() { }
virtual ~TestCase_case_00221_various_gamma_func() { }
private:
virtual const std::string& name() const
{
static const std::string str("TestCase_case_00221_various_gamma_func");
return str;
}
virtual void e_float_test(std::vector<e_float>& data) const
{
data.clear();
data.push_back(ef::binomial( 20U, 10U));
data.push_back(ef::binomial( 200U, 100U));
data.push_back(ef::binomial(2000U, 1000U));
data.push_back(ef::binomial( 20U, ef::pi()));
data.push_back(ef::binomial( 200U, ef::euler_gamma()));
data.push_back(ef::binomial(ef::pi(), 20U));
data.push_back(ef::binomial(ef::euler_gamma(), 200U));
data.push_back(ef::binomial(ef::pi(), ef::euler_gamma()));
data.push_back(ef::real(ef::pochhammer(ef::complex<e_float>(ef::third(), ef::catalan()), ef::complex<e_float>(ef::pi(), ef::euler_gamma()))));
data.push_back(ef::imag(ef::pochhammer(ef::complex<e_float>(ef::third(), ef::catalan()), ef::complex<e_float>(ef::pi(), ef::euler_gamma()))));
data.push_back(ef::real(ef::pochhammer(ef::complex<e_float>(ef::third(), ef::catalan()), 17U)));
data.push_back(ef::imag(ef::pochhammer(ef::complex<e_float>(ef::third(), ef::catalan()), 17U)));
}
virtual const std::vector<e_float>& control_data() const
{
static const std::array<e_float, 12U> a =
{{
e_float("184756."),
e_float("9.054851465610328116540417707748416387450458967541333684132e58"),
e_float("2.0481516269894897143351625029808250443964248879813970338203826376717481862020837558289329941826102062014647663199980236924154817980045247920180475497692615785630128966343206471485115239525165122776858861153954625614790737866846415444453361761377007385567381458963007130651045595951447988874620636871851455182855117316627625366377308468293225538904974385948143175503078379644437081008516372482746279142e600"),
e_float("1426.2875030516824045190474871275847729610929647117178800653022745251962712249707445157273933966843872568527224787237025554131878339600530478719032313554763427360721488756093392253813229658100564292171732133350532208227507093154629266943286522621238015096412669116807540438027251666868309539712883280049119239645930336330076174743206247596649403559443674627228992616061900507179654878296462325149959779"),
e_float("23.905807241512394798031322623498819327532394382354962100257335309915288947122100144010787022343352490102943174682028714280647066212565849981503239376815427267462681968008266840836806076583172116229479815702276779531595620821074308701024028942321603306154794376868053004626539188760291493888402142780216534904313067460585404963770412097706832916711745592577404899046617653259420661910864245282648095687"),
e_float("5.6963816832640242844919552652159138827866213713172597878482401725674355827471357835225369384013178060362647450507731446625889429203180720953909308392113979081629970117792139947181063526228392980246705188456776319936934238547470466701633490045271558938144816898886029024857117477476768344525517620614855179138850987077688445942369527715042007920808536944663306693900047804831548532207767701883374488226e-6"),
e_float("-0.000064813661381704035413125766070598403349380018125924589067776393730670039970238017825688419996782474898665714347544897878075841533091153265283467434502901775742227453591410203041876567155233659662991883938956472692298625514100086450383537348892987257000215046403944202337418613133429680795301438175913399121145475000015938979999544284889667921479247850203646268054003574883503064715472183419132372473871"),
e_float("2.2591590103167630190452733430384211373521343658823833761813141983667173059953914970939256890295005366854944600940834213197002027822306748818548861205594799774484976985539727592377899452702878200835064299641918223375658027834460435738482686901141547787547253595277235131884714790921874824761713332395413378999045488707756309020327335384455949550882941358601905770319924198306108918970861855442062137397"),
e_float("-3.6215162717920215625633717539208633118712867642757483374687955271130098748057889599659215315432663567235808345053657354414534961323156841124935122897289092755071176642527846013059555786399905794977356653285448791884290399613283798008262455259167867694210264313203835509563061698853660854598708760557829561095207959771714436896137642117702494838972128190061371150274941459507543811480857300071275836566"),
e_float("0.83099788602765992595492178898464247715558000072537423822967749809394629317938691902002837282366615461021279628533093592288740494116137715229135123184288777457135266694834120576993810702408416134641940525396688798005808868948609128732886975573235337577633420194806096431753278615961754669345692462061813104888472234149917217092389317885470686324503044448468709127256522772934226361651395368905947057546"),
e_float("-6.7195625256450753067370125862972561246633315487427733443556289130561824093050570570502135154581091356227792305458885622653519570699121792170020555378302467880293629322684263401102408762148658601687039807387722039255615124660734869847882817537790378472317878152346927507280453423670226329304049733802574304332827772002207926333958933086568346833578245386822028638114547214217036296604212098373211628956e13"),
e_float("-5.3151927138507502109590981067680725465842152964099134846973687497026217487364530057872799562136824970616293018797829836534101401830288383550955342524270155305699456811988584739699887666310159610776467204263451070037657070761698698983071008397320844517196873980882515586153126567805935301582564276154321299249086930037049432662250081277169327052253061426296436412837509883624088691560327457829392045447e13"),
}};
static const std::vector<e_float> v(a.cbegin(), a.cend());
return v;
}
};
bool test_case_00221_various_gamma_func(const bool b_write_output)
{
return TestCase_case_00221_various_gamma_func().execute(b_write_output);
}
}
}
| 88.493671 | 431 | 0.839222 | [
"vector"
] |
21dc5391b8779f13fe5cc1435916a13e123b0626 | 872 | cc | C++ | Problem_27/main.cc | kmcdermo/Euler | f156020a1a3282db864b8125ad82e475b5af625f | [
"MIT"
] | null | null | null | Problem_27/main.cc | kmcdermo/Euler | f156020a1a3282db864b8125ad82e475b5af625f | [
"MIT"
] | null | null | null | Problem_27/main.cc | kmcdermo/Euler | f156020a1a3282db864b8125ad82e475b5af625f | [
"MIT"
] | null | null | null | #include "common.hh"
static const long N = 100000;
static const long a = 1000;
static const long b = 1000;
void makeSieve(std::vector<bool> & primes)
{
primes[0] = primes[1] = false;
const long sqrtN = std::sqrt(N);
for (long p = 2; p <= sqrtN; p++)
{
if (primes[p])
{
for (long i = p*p; i <= N; i += p)
{
primes[i] = false;
}
}
}
}
int main()
{
std::vector<bool> primes(N, true);
makeSieve(primes);
long product = 0;
long counter = 0;
for (long i = -a+1; i < a; i++)
{
for (long j = -b; j <= b; j++)
{
long n = 0;
bool isPrime = true;
while (isPrime)
{
const long calc = std::abs(n*n+n*i+j);
isPrime = primes[calc];
if (isPrime) n++;
}
n--;
if (n > counter) {counter = n; product = i*j;}
}
}
std::cout << counter << " : " << product << std::endl;
}
| 18.166667 | 56 | 0.5 | [
"vector"
] |
21de432784ac98963e949e742de68b9c4ed0114d | 2,442 | cc | C++ | src/addon.cc | fivdi/node-addon-api-experiments | 15b2f844882c702f20bb83be2d8948cec28c46ad | [
"MIT"
] | null | null | null | src/addon.cc | fivdi/node-addon-api-experiments | 15b2f844882c702f20bb83be2d8948cec28c46ad | [
"MIT"
] | null | null | null | src/addon.cc | fivdi/node-addon-api-experiments | 15b2f844882c702f20bb83be2d8948cec28c46ad | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <pthread.h>
#include <uv.h>
#include <napi.h>
static uv_async_t async_g;
static Napi::FunctionReference callback_ref_g;
void DispatchEvent(uv_async_t* handle) {
Napi::Env env = callback_ref_g.Env();
Napi::HandleScope scope(env);
// TODO - If the callback throws how can it be handled?
callback_ref_g.Call({ Napi::String::New(env, "hello world") });
// The following code doesn't work
/* if (env.IsExceptionPending()) {
printf("c++: after callback - exception pending\n");
Napi::Error e = env.GetAndClearPendingException();
e.ThrowAsJavaScriptException(); // <- This doesn't work
} else {
printf("c++: after callback\n");
}*/
}
void *InfiniteLoop(void *arg) {
while (true) {
sleep(1);
uv_async_send(&async_g);
}
return 0;
}
int StartInfiniteLoop() {
pthread_t theread_id;
int err = uv_async_init(uv_default_loop(), &async_g, DispatchEvent);
if (err < 0) {
return -err;
}
// Prevent async_g from keeping event loop alive initially.
uv_unref((uv_handle_t *) &async_g);
err = pthread_create(&theread_id, 0, InfiniteLoop, 0);
if (err != 0) {
uv_close((uv_handle_t *) &async_g, 0);
return err;
}
return 0;
}
void Start(const Napi::CallbackInfo& info) {
static bool running_g = false;
if (running_g == false) {
Napi::Function callback = info[0].As<Napi::Function>();
callback_ref_g = Napi::Reference<Napi::Function>::New(callback, 1);
callback_ref_g.SuppressDestruct();
// TODO evaruate return code from StartInfiniteLoop
StartInfiniteLoop();
running_g = true;
}
}
void KeepEventLoopAlive(const Napi::CallbackInfo& info) {
uv_ref((uv_handle_t *) &async_g);
}
void DontKeepEventLoopAlive(const Napi::CallbackInfo& info) {
uv_unref((uv_handle_t *) &async_g);
}
Napi::Value RunCallback(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Function cb = info[0].As<Napi::Function>();
cb.Call({ Napi::String::New(env, "hello world") });
return env.Undefined();
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports["start"] = Napi::Function::New(env, Start);
exports["keepEventLoopAlive"] =
Napi::Function::New(env, KeepEventLoopAlive);
exports["dontKeepEventLoopAlive"] =
Napi::Function::New(env, DontKeepEventLoopAlive);
exports["runCallback"] =
Napi::Function::New(env, RunCallback);
return exports;
}
NODE_API_MODULE(hello, Init)
| 24.178218 | 71 | 0.68018 | [
"object"
] |
21e789ae68a881449ac9bd350e80e6085b7c147f | 1,317 | cpp | C++ | aoc/src/2018/day-5.cpp | DrPizza/advent-of-code-2017 | bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9 | [
"Zlib"
] | 2 | 2017-12-09T06:13:08.000Z | 2017-12-18T12:15:08.000Z | aoc/src/2018/day-5.cpp | DrPizza/advent-of-code-2017 | bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9 | [
"Zlib"
] | 1 | 2018-01-03T17:46:56.000Z | 2018-01-03T17:46:56.000Z | aoc/src/2018/day-5.cpp | DrPizza/advent-of-code | bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9 | [
"Zlib"
] | null | null | null | #include "stdafx.h"
#include "problem.hpp"
#include <fstream>
#include <vector>
#include <cctype>
#include <range/v3/all.hpp>
struct advent_2018_5 : problem
{
advent_2018_5() noexcept : problem(2018, 5) {
}
protected:
std::string polymer;
void prepare_input(std::ifstream& fin) override {
std::getline(fin, polymer);
}
std::string react(const std::string& input) {
std::string reacted;
for(const char ch : input) {
if(reacted.empty()) {
reacted.push_back(ch);
continue;
}
if(std::tolower(reacted.back()) == std::tolower(ch)
&& reacted.back() != ch ) {
reacted.pop_back();
} else {
reacted.push_back(ch);
}
}
return reacted;
}
std::string part_1() override {
const std::string reacted = react(polymer);
return std::to_string(reacted.size());
}
std::string part_2() override {
const auto smallest = ranges::min(ranges::view::closed_iota('a', 'z')
| ranges::view::transform([&] (char C) {
return react(polymer
| ranges::view::filter([&] (char c) noexcept { return std::tolower(c) != C; })).size();
}
));
return std::to_string(smallest);
}
};
REGISTER_SOLVER(2018, 5);
| 22.706897 | 133 | 0.558846 | [
"vector",
"transform"
] |
21eeffac50aae16214ee799c6704968a14e34e4c | 2,894 | hh | C++ | src/elle/factory.hh | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | src/elle/factory.hh | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | src/elle/factory.hh | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | #pragma once
#include <elle/Error.hh>
#include <elle/memory.hh>
#include <unordered_map>
namespace elle
{
namespace _details
{
template <typename F>
class Factory
{
public:
using Type = decltype(std::declval<F>()());
Factory(F f)
: _f(f)
{}
template <typename C>
operator C() const
{
return this->_f();
}
ELLE_ATTRIBUTE(F, f);
};
}
template <typename F>
_details::Factory<F>
factory(F f)
{
return _details::Factory<F>(std::move(f));
}
/// A generic Factory.
///
/// \code{.cc}
///
/// struct Foo;
/// {
/// Foo() = default;
/// virtual
/// ~Foo() = default;
/// };
///
/// struct FooA
/// : public Foo
/// {
/// FooA() = default;
/// std::string v = {"I'm a A"};
/// };
///
/// struct FooB
/// : public Foo
/// {
/// FooB() = default;
/// std::string u = {"I'm a B"};
/// };
///
/// elle::Factory<Foo>::register_(
/// "A", [] (elle::Factory<Foo>::Arguments const&)
/// {
/// return std::make_unique<FooA>();
/// });
/// elle::Factory<Foo>::register_(
/// "B", [] (elle::Factory<Foo>::Arguments const&)
/// {
/// return std::make_unique<FooB>();
/// });
/// auto a = elle::cast<FooA>::runtime(
/// std::move(elle::Factory<Foo>::instantiate("A", {})));
/// std::cout << a->v << ", ";
/// auto _b = elle::Factory<Foo>::instantiate("B", {});
/// auto b = elle::cast<FooB>::compiletime(_b);
/// std::cout << b->u;
///
/// // Result: I'm a A, I'm a B.
///
/// \endcode
///
template <typename T>
class Factory
{
public:
class KeyError
: public Error
{
public:
KeyError(std::string const& key)
: Error("No such key: " + key)
{}
};
using Arguments = std::vector<std::string>;
using Builder = std::function<std::unique_ptr<T>(Arguments const&)>;
/// Register a Builder for a given name.
///
/// @param name The name of the Builder.
/// @param builder The builder.
/// @returns 0
static
int
register_(std::string const& name, Builder builder);
/// Instantiate a std::unique_ptr<\T> using the requested Builder.
///
/// @param name The name of the Builder to use.
/// @param args The Arguments.
/// @returns An std::unique_ptr.
///
/// @throw KeyError If no Builder was registered under the given name.
static
std::unique_ptr<T>
instantiate(std::string const& name, Arguments const& args);
private:
using Items = std::unordered_map<std::string, Builder>;
static
Items&
_items();
};
}
#define FACTORY_REGISTER(type, name, builder) \
static int __attribute__((unused)) \
unused = elle::Factory<type>::register_(name, builder)
#include <elle/factory.hxx>
| 22.434109 | 74 | 0.526952 | [
"vector"
] |
21ef646738c39aaeac1e6c5f49d0f9ea16d6a038 | 654 | cpp | C++ | Problemas/254 - Esquiando en Alaska/30 - Esquiando en Alaska/Source.cpp | Jackesgamero/-Solved-ACR-problems- | 12fe74469f6d41c4947505f52898840093069b38 | [
"MIT"
] | 1 | 2021-02-24T17:41:37.000Z | 2021-02-24T17:41:37.000Z | Problemas/254 - Esquiando en Alaska/30 - Esquiando en Alaska/Source.cpp | Jackesgamero/-Solved-ACR-problems- | 12fe74469f6d41c4947505f52898840093069b38 | [
"MIT"
] | null | null | null | Problemas/254 - Esquiando en Alaska/30 - Esquiando en Alaska/Source.cpp | Jackesgamero/-Solved-ACR-problems- | 12fe74469f6d41c4947505f52898840093069b38 | [
"MIT"
] | null | null | null | // Autor : Jaime Martinez Gamero
#include <iostream>
#include <vector>
#include <algorithm>
bool resuelveCaso() {
int N;
std::cin >> N;
if (N == 0) return false;
std::vector<int> alturas, esquis;
int aux;
for (size_t i = 0; i < N; ++i){
std::cin >> aux;
alturas.push_back(aux);
}
for (size_t i = 0; i < N; ++i){
std::cin >> aux;
esquis.push_back(aux);
}
std::sort(alturas.begin(), alturas.end());
std::sort(esquis.begin(), esquis.end());
int suma = 0;
for (size_t i = 0; i < N; ++i){
suma += abs(alturas[i] - esquis[i]);
}
std::cout << suma << '\n';
return true;
}
int main() {
while (resuelveCaso());
return 0;
}
| 14.863636 | 43 | 0.576453 | [
"vector"
] |
21ffeba82b64c2bec00441b22c4d9ca0f940a83f | 2,050 | cpp | C++ | Sources/Elastos/External/alljoyn/src/org/alljoyn/bus/PropertiesChangedListener.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/External/alljoyn/src/org/alljoyn/bus/PropertiesChangedListener.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/External/alljoyn/src/org/alljoyn/bus/PropertiesChangedListener.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "org/alljoyn/bus/PropertiesChangedListener.h"
#include "org/alljoyn/bus/NativePropertiesChangedListener.h"
namespace Org {
namespace Alljoyn {
namespace Bus {
CAR_INTERFACE_IMPL(PropertiesChangedListener, Object, IPropertiesChangedListener)
PropertiesChangedListener::PropertiesChangedListener()
: mHandle(0)
{}
PropertiesChangedListener::~PropertiesChangedListener()
{
Destroy();
}
ECode PropertiesChangedListener::constructor()
{
Create();
return NOERROR;
}
void PropertiesChangedListener::Create()
{
// changed Property values that changed as an array of dictionary entries, signature "a{sv}".
// invalidated Properties whose values have been invalidated, signature "as".
AutoPtr<IWeakReference> wr;
GetWeakReference((IWeakReference**)&wr);
NativePropertiesChangedListener* npcl = new NativePropertiesChangedListener(wr, String("a{sv}"), String("as"));
mHandle = reinterpret_cast<Int64>(npcl);
}
/** Release native resources. */
void PropertiesChangedListener::Destroy()
{
if (mHandle != 0) {
NativePropertiesChangedListener* npcl = reinterpret_cast<NativePropertiesChangedListener*>(mHandle);
delete npcl;
mHandle = 0;
}
}
} // namespace Bus
} // namespace Alljoyn
} // namespace Org | 32.539683 | 115 | 0.684878 | [
"object"
] |
1d0584a209dba2da147da7de5ba8037fbd01b4e0 | 10,753 | cpp | C++ | courses/coursera-sandiego-algorithms/algorithmic-toolbox/assignment004/placing_parentheses/placing_parentheses.cpp | xunilrj/sandbox | f92c12f83433cac01a885585e41c02bb5826a01f | [
"Apache-2.0"
] | 7 | 2017-04-01T17:18:35.000Z | 2022-01-12T05:23:23.000Z | courses/coursera-sandiego-algorithms/algorithmic-toolbox/assignment004/placing_parentheses/placing_parentheses.cpp | xunilrj/sandbox | f92c12f83433cac01a885585e41c02bb5826a01f | [
"Apache-2.0"
] | 6 | 2020-05-24T13:36:50.000Z | 2022-02-15T06:44:20.000Z | courses/coursera-sandiego-algorithms/algorithmic-toolbox/assignment004/placing_parentheses/placing_parentheses.cpp | xunilrj/sandbox | f92c12f83433cac01a885585e41c02bb5826a01f | [
"Apache-2.0"
] | 2 | 2018-09-20T01:07:39.000Z | 2019-02-22T14:55:38.000Z | #include <iostream>
#include <cassert>
#include <string>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <functional>
#include <tuple>
using std::vector;
using std::string;
using std::max;
using std::min;
template<typename T>
void permutations(vector<T>& set, std::function<void(std::vector<T>)> f) {
do {
f(set);
} while(std::next_permutation(set.begin(), set.end()));
}
long long eval(long long a, long long b, char op) {
if (op == '*') {
return a * b;
} else if (op == '+') {
return a + b;
} else if (op == '-') {
return a - b;
} else {
assert(0);
}
}
struct node{
bool digit;
union{
long long number;
char op;
};
};
node digit(long long d)
{
auto n = node();
n.digit = true;
n.number = d;
return n;
}
node digit(char d)
{
auto n = node();
n.digit = true;
n.number = (long long)(d-48);
return n;
}
node op(char op)
{
auto n = node();
n.digit = false;
n.op = op;
return n;
}
node make_node(char c)
{
if((c == '+')||(c == '-')||(c == '*'))
{
return op(c);
}
else
{
return digit(c);
}
}
#include <memory>
template <template <typename, typename> class Container,
typename Allocator=std::allocator<node> >
std::ostream & operator << (std::ostream & o, Container<node,Allocator> nodes)
{
o << "[";
for(auto current : nodes)
{
if(current.digit){
o << "(" << current.number << "),";
}else{
o << "(" << current.op << ")";
}
}
return o << "]";
}
template <template <typename, typename> class Container,
typename Value,
typename Allocator=std::allocator<Value> >
std::ostream & operator << (std::ostream & o, Container<Value,Allocator> v)
{
o << "[";
for(auto current : v)
{
o << current << ",";
}
return o << "]";
}
long long evaluate(std::vector<char> problem, std::vector<int> order)
{
auto stack = std::deque<node>();
bool first = true;
std::for_each(order.begin(), order.end(), [&](const int& i)
{
auto operator_i = (i * 2) + 1;
auto r = operator_i + 1;
if(first){
auto l = operator_i - 1;
stack.push_back(make_node(problem[l]));
first = false;
}
stack.push_back(make_node(problem[r]));
stack.push_back(make_node(problem[operator_i]));
});
// std::cout << stack << std::endl;
auto ops = std::vector<node>();
while(!stack.empty())
{
auto current = stack.front();
stack.pop_front();
if(!current.digit)
{
// std::cout << ops[0].number << current.op << ops[1].number << std::endl;
auto result = eval(ops[0].number, ops[1].number, current.op);
stack.push_front(digit(result));
ops.clear();
// std::cout << stack << std::endl;
}
else
{
ops.push_back(current);
}
}
return ops[0].number;
}
std::ostream & tab(int depth)
{
return std::cout << std::string(depth, ' ');
}
std::tuple<int,int> get_maximum_value_naive_internal(std::vector<char> exp, int i, int j, int depth = 0)
{
if(i > j)
{
tab(depth) << "ERROR!";
return std::make_tuple(0,0);
}
else if (i+1 == j)
{
auto v = (long long)(exp[i*2]-48);
// tab(depth) << "digit " << i << " " << v << std::endl;
return std::make_tuple(v,v);
}
auto min = std::numeric_limits<long long>::max(),
max = std::numeric_limits<long long>::min();
for(int newi = i+1;newi < j;++newi)
{
auto op = exp[(2*newi)-1];
tab(depth) << "[" << i << "," << newi << "] " << op << " [" << newi << "," << j << "]" << std::endl;
int minl = 0, maxl = 0;
std::tie(minl,maxl) = get_maximum_value_naive_internal(exp, i, newi, depth + 1);
int minr = 0, maxr = 0;
std::tie(minr,maxr) = get_maximum_value_naive_internal(exp, newi, j, depth + 1);
auto a = eval(minl, minr, op);
auto b = eval(minl, maxr, op);
auto c = eval(maxl, minr, op);
auto d = eval(maxl, maxr, op);
auto cmin = 0, cmax = 0;
std::tie(cmin,cmax) = std::minmax({a,b,c,d});
tab(depth) << "options {" << std::vector<long long>{a,b,c,d} << "}" << std::endl;
if(cmin < min) min = cmin;
if(cmax > max) max = cmax;
}
return std::make_tuple(min,max);
}
long long get_maximum_value_naive(string exp) {
std::stringstream ss(exp);
auto operators = std::vector<char>();
for(char c; ss >> c;)
{
operators.push_back(c);
}
// std::cout << operators << std::endl;
auto digit_count = (operators.size() / 2) + 1;
int min = 0, max = 0;
std::tie(min,max) = get_maximum_value_naive_internal(operators, 0, digit_count, 0);
return max;
}
void print(long long *array, int w, int h, int cx, int cy){
auto at = [&](int x,int y){return x+(y*(w));};
for (int j = 0; j < h; j++){
for (int i = 0; i < w; i++){
if(i == cx & j == cy ){
std::cout << "[" << array[at(i,j)] << "] ";
}
else{
std::cout << array[at(i,j)] << " ";
}
}
std::cout << std::endl;
}
}
void inspectMatrix(int w, int j, int i)
{
std::cout << j << " " << i << std::endl;
auto istart = i-1;
auto jstart = i;
for(int index = 0; index < i;++index)
{
std::cout << j << " " << istart-index << " + " << jstart-index << "," << i << std::endl;
}
}
std::tuple<long long,long long> minmax(std::vector<char> &operators, std::vector<long long> &mins, std::vector<long long> &maxs, int w, int i, int j)
{
// std::cout << "minmax " << j << " " << i << std::endl;
auto at = [&](int i, int j){return i+(j*w); };
long long min = std::numeric_limits<long long>::max(),
max = std::numeric_limits<long long>::min();
auto istart = i-1;
auto jstart = i;
for(int index = 0; index < (i-j);++index)
{
auto left_j = j;
auto left_i = istart-index;
auto left_min = mins[at(left_i,left_j)];
auto left_max = maxs[at(left_i,left_j)];
auto below_j = jstart-index;
auto below_i = i;
auto below_min = mins[at(below_i,below_j)];
auto below_max = maxs[at(below_i,below_j)];
auto op = operators[((left_i)*2)+1];
auto r1 = eval(left_min,below_min, op);
auto r2 = eval(left_max,below_max, op);
auto possible_min = std::min(r1,r2);
auto possible_max = std::max(r1,r2);
// std::cout <<left_min << " " << op << " " << below_min << " = " << r1 << " or " << left_max << " " << op << " " << below_max << " = " << r2 << " [" << left_j << "," << left_i << "]" << " [" << below_j << "," << below_i << "] " << std::endl;
if(possible_min < min) min = possible_min;
if(possible_max > max) max = possible_max;
}
mins[at(i,j)] = min;
maxs[at(i,j)] = max;
}
long long get_maximum_value_dynamic(string exp){
std::stringstream ss(exp);
auto operators = std::vector<char>();
for(char c; ss >> c;)
{
operators.push_back(c);
}
// std::cout << operators << std::endl;
auto digit_count = (operators.size() / 2) + 1;
auto stride = digit_count;
auto mins = std::vector<long long>(stride*stride);
auto maxs = std::vector<long long>(stride*stride);
auto at = [&](int i, int j){return i+(j*stride); };
for(int x = 0; x < digit_count; ++x)
{
auto c = (long long)(operators[x*2]-48);
mins[at(x,x)] = c;
maxs[at(x,x)] = c;
}
// print(&mins[0], stride, stride, -1, -1);
// std::cout << std::endl;
// print(&maxs[0], stride, stride, -1, -1);
// std::cout << "-----------------------------" << std::endl;
auto n = digit_count;
for(int s = 0; s < n;++s)
{
for(int j = 0; j < n-s;++j)
{
int i = j + s;
if(i==j) continue;
// std::cout << "MINS -----------------------------------" << std::endl;
// print(&mins[0], stride, stride, i, j);
// std::cout << "MAXS -----------------------------------" << std::endl;
// print(&maxs[0], stride, stride, i, j);
// std::cout << std::endl;
minmax(operators, mins, maxs, stride, i, j);
}
}
// std::cout << "MINS -----------------------------" << std::endl;
// print(&mins[0], stride, stride, n-1, 0);
// std::cout << "MAXS -----------------------------" << std::endl;
// print(&maxs[0], stride, stride, n-1, 0);
return std::max(mins[at(n-1,0)],maxs[at(n-1,0)]);
}
#ifdef UNITTESTS
#define CATCH_CONFIG_MAIN
#include "../../catch.hpp"
TEST_CASE("get_maximum_value_naive must work","get_maximum_value_naive")
{
// REQUIRE(get_maximum_value_naive("1 + 5") == 6);
// REQUIRE(get_maximum_value_naive("1 + 5 + 2") == 8);
// REQUIRE(get_maximum_value_naive("1 + 5 * 2") == 12);
// REQUIRE(get_maximum_value_naive("1 - 5 * 2") == -8);
// REQUIRE(get_maximum_value_naive("5 - 8 + 7 * 4 - 8 + 9") == 200);
REQUIRE(get_maximum_value_naive("2+8*3-9-5-3")== 25);
}
TEST_CASE("get_maximum_value_dynamic must work","get_maximum_value_dynamic")
{
// REQUIRE(get_maximum_value_dynamic("1 + 5") == 6);
// REQUIRE(get_maximum_value_dynamic("1 + 5 + 2") == 8);
// REQUIRE(get_maximum_value_dynamic("1 + 5 * 2") == 12);
// REQUIRE(get_maximum_value_dynamic("1 - 5 * 2") == -8);
// REQUIRE(get_maximum_value_dynamic("5 - 8 + 7 * 4 - 8 + 9") == 200);
// REQUIRE(get_maximum_value_dynamic("2+8*3-9-5-3")== 25);
}
void printProg(int x, int total){
int progress = ((double)x / total) * 100;
std::cout << "[";
for (int i=1;i<=100;i++){
if (i<progress || progress==100)
std::cout << "=";
else if (i==progress)
std::cout << ">";
else
std::cout << " ";
}
std::cout << "] " << x << "/" << total << "\r" << std::flush;
}
std::string random_expression( size_t length )
{
auto randdigit = []() -> char {
static const char digits[] = "0123456789";
const size_t max_index = (sizeof(digits) - 1);
return digits[ rand() % max_index ];
};
auto randop = []() -> char{
static const char ops[] = "+-*";
const size_t max_index = (sizeof(ops) - 1);
return ops[ rand() % max_index ];
};
std::string str(length,0);
for(int i = 0; i < str.size();++i){
if((i % 2) == 0){
str[i] = randdigit();
}else{
str[i] = randop();
}
}
return str;
}
void compare()
{
auto size = (std::rand() % 5) + 2;
size = size + (size-1);
auto expression = random_expression(size);
auto r1 = get_maximum_value_naive(expression);
auto r2 = get_maximum_value_dynamic(expression);
auto isEqual = r1 == r2;
if(!isEqual) std::cout << expression << " result: "<< r1 << r2 << std::endl;
REQUIRE(r1==r2);
}
TEST_CASE("get_maximum_value must be equal","get_maximum_value")
{
// for(int i = 0; i <= 1000000;++i)
// {
// printProg(i,1000000);
// compare();
// }
}
#else
int main() {
string s;
std::cin >> s;
std::cout << get_maximum_value_dynamic(s) << '\n';
}
#endif | 25.006977 | 246 | 0.540686 | [
"vector"
] |
1d075ea7a0d82080149d3089a0e03d14d9c43c70 | 5,068 | cpp | C++ | gui/qubjson_test.cpp | Gurten/apitrace | e4ab1fee3eeb1f9f95a3b6f68339a0e5a87f5528 | [
"MIT"
] | 1,723 | 2015-01-08T19:10:21.000Z | 2022-03-31T16:41:40.000Z | gui/qubjson_test.cpp | Gurten/apitrace | e4ab1fee3eeb1f9f95a3b6f68339a0e5a87f5528 | [
"MIT"
] | 471 | 2015-01-02T15:02:34.000Z | 2022-03-26T17:54:10.000Z | gui/qubjson_test.cpp | Gurten/apitrace | e4ab1fee3eeb1f9f95a3b6f68339a0e5a87f5528 | [
"MIT"
] | 380 | 2015-01-22T19:06:32.000Z | 2022-03-25T02:20:39.000Z | /**************************************************************************
*
* Copyright 2015 VMware, Inc
* All Rights Reserved.
*
* 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 "qubjson.h"
#include <QDebug>
#include <QBuffer>
#include "gtest/gtest.h"
static inline std::ostream &
operator << (std::ostream &os, const QVariant &var)
{
QString buf;
QDebug debug(&buf);
debug << var;
os << buf.trimmed().toLocal8Bit().constData();
return os;
}
static ::testing::AssertionResult
check(const char *buf_expr, const char *exp_expr, QByteArray & bytearray, const QVariant & expected)
{
QBuffer buffer(&bytearray);
buffer.open(QIODevice::ReadOnly);
QVariant actual = decodeUBJSONObject(&buffer);
if (!buffer.atEnd()) {
return ::testing::AssertionFailure() << "Trailing bytes";
}
if (actual != expected) {
return ::testing::AssertionFailure() << "Expected " << expected << " but got " << actual;
}
return ::testing::AssertionSuccess();
}
#define BYTEARRAY(...) { __VA_ARGS__ }
#define CHECK( x , y ) \
{ \
static const unsigned char X[] = x; \
QByteArray bytearray((const char *)X, sizeof X); \
EXPECT_PRED_FORMAT2(check, bytearray, y); \
}
TEST(qubjson, null) {
CHECK(BYTEARRAY('Z'), QVariant());
}
TEST(qubjson, boolean) {
CHECK(BYTEARRAY('T'), true);
CHECK(BYTEARRAY('F'), false);
}
TEST(qubjson, integral) {
CHECK(BYTEARRAY('i', 0x00), +0x00);
CHECK(BYTEARRAY('i', 0x7f), +0x7f);
CHECK(BYTEARRAY('i', 0x80), -0x80);
CHECK(BYTEARRAY('U', 0x00), +0x00);
CHECK(BYTEARRAY('U', 0x80), +0x80);
CHECK(BYTEARRAY('U', 0xff), +0xff);
CHECK(BYTEARRAY('I', 0x01, 0x23), +0x0123);
CHECK(BYTEARRAY('I', 0x80, 0x00), -0x8000);
CHECK(BYTEARRAY('l', 0x01, 0x23, 0x45, 0x67), +0x01234567);
CHECK(BYTEARRAY('l', 0x80, 0x00, 0x00, 0x00), -0x7fffffff - 1); // -0x80000000 causes signed warnings
CHECK(BYTEARRAY('L', 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF), qlonglong(+0x0123456789ABCDEFLL));
CHECK(BYTEARRAY('L', 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), qlonglong(-0x8000000000000000LL));
}
TEST(qubjson, float) {
CHECK(BYTEARRAY('d', 0x3f, 0x80, 0x00, 0x00), 1.0f);
CHECK(BYTEARRAY('d', 0x00, 0x00, 0x00, 0x01), 1.40129846e-45f);
CHECK(BYTEARRAY('d', 0xff, 0x7f, 0xff, 0xff), -3.4028234e38f);
CHECK(BYTEARRAY('D', 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), 1.0);
CHECK(BYTEARRAY('D', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01), 4.9406564584124654e-324);
CHECK(BYTEARRAY('D', 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff), -1.7976931348623157e308);
}
TEST(qubjson, string) {
CHECK(BYTEARRAY('C', 'A'), "A");
CHECK(BYTEARRAY('S', 'U', 0), "");
CHECK(BYTEARRAY('S', 'U', 5, 'A', 'B', 'C', 'D', 'E'), "ABCDE");
}
TEST(qubjson, array) {
QVariantList list;
CHECK(BYTEARRAY('[', ']'), list);
list.append(1);
CHECK(BYTEARRAY('[', 'i', 1, ']'), list);
CHECK(BYTEARRAY('[', '#', 'i', 1, 'i', 1), list);
list.append(2);
CHECK(BYTEARRAY('[', 'U', 1, 'i', 2, ']'), list);
CHECK(BYTEARRAY('[', '#', 'U', 2, 'i', 1, 'i', 2), list);
}
TEST(qubjson, object) {
QVariantMap map;
CHECK(BYTEARRAY('{', '}'), map);
map["A"] = 1;
CHECK(BYTEARRAY('{', 'U', 1, 'A', 'i', 1, '}'), map);
map["B"] = 2;
CHECK(BYTEARRAY('{', 'U', 1, 'A', 'i', 1, 'U', 1, 'B', 'i', 2, '}'), map);
}
TEST(qubjson, binary_data) {
CHECK(BYTEARRAY('[', '$', 'U', '#', 'U', 0), QByteArray());
CHECK(BYTEARRAY('[', '$', 'U', '#', 'U', 1, 'A'), QByteArray("A"));
CHECK(BYTEARRAY('[', '$', 'U', '#', 'U', 2, 'A', 'B'), QByteArray("AB"));
CHECK(BYTEARRAY('[', '$', 'U', '#', 'U', 3, 'A', 'B', 'C'), QByteArray("ABC"));
}
int
main(int argc, char **argv)
{
#if defined(_MSC_VER) && !defined(NDEBUG)
return 0;
#else
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
#endif
}
| 31.283951 | 108 | 0.599842 | [
"object"
] |
1d0788af61d22e26742e490d1bd8b34b48339a5c | 1,430 | hpp | C++ | iRODS/lib/api/include/structFileSync.hpp | PlantandFoodResearch/irods | 9dfe7ffe5aa0760b7493bd9392ea1270df9335d4 | [
"BSD-3-Clause"
] | null | null | null | iRODS/lib/api/include/structFileSync.hpp | PlantandFoodResearch/irods | 9dfe7ffe5aa0760b7493bd9392ea1270df9335d4 | [
"BSD-3-Clause"
] | null | null | null | iRODS/lib/api/include/structFileSync.hpp | PlantandFoodResearch/irods | 9dfe7ffe5aa0760b7493bd9392ea1270df9335d4 | [
"BSD-3-Clause"
] | null | null | null | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to subStructFiles in the COPYRIGHT directory ***/
/* structFileSync.h
*/
#ifndef STRUCT_FILE_SYNC_HPP
#define STRUCT_FILE_SYNC_HPP
/* This is Object File I/O type API call */
#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#include "initServer.hpp"
/* definition for flags */
typedef struct StructFileOprInp {
rodsHostAddr_t addr;
int oprType; /* see syncMountedColl.h */ // JMC - backport 4643
int flags;
specColl_t *specColl;
keyValPair_t condInput; /* include chksum flag and value */
} structFileOprInp_t;
#define StructFileOprInp_PI "struct RHostAddr_PI; int oprType; int flags; struct *SpecColl_PI; struct KeyValPair_PI;"
#if defined(RODS_SERVER)
#define RS_STRUCT_FILE_SYNC rsStructFileSync
/* prototype for the server handler */
int
rsStructFileSync( rsComm_t *rsComm, structFileOprInp_t *structFileOprInp );
int
_rsStructFileSync( rsComm_t *rsComm, structFileOprInp_t *structFileOprInp );
int
remoteStructFileSync( rsComm_t *rsComm, structFileOprInp_t *structFileOprInp,
rodsServerHost_t *rodsServerHost );
#else
#define RS_STRUCT_FILE_SYNC NULL
#endif
/* prototype for the client call */
int
rcStructFileSync( rcComm_t *conn, structFileOprInp_t *structFileOprInp );
#endif /* STRUCT_FILE_SYNC_H */
| 29.791667 | 117 | 0.752448 | [
"object"
] |
1d0bba07ae9857a383eacfb911b5ebd15343ed27 | 3,534 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcDirection.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcDirection.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcDirection.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcDirection.h"
#include "include/IfcPresentationLayerAssignment.h"
#include "include/IfcReal.h"
#include "include/IfcStyledItem.h"
// ENTITY IfcDirection
IfcDirection::IfcDirection() { m_entity_enum = IFCDIRECTION; }
IfcDirection::IfcDirection( int id ) { m_id = id; m_entity_enum = IFCDIRECTION; }
IfcDirection::~IfcDirection() {}
shared_ptr<IfcPPObject> IfcDirection::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcDirection> copy_self( new IfcDirection() );
for( size_t ii=0; ii<m_DirectionRatios.size(); ++ii )
{
auto item_ii = m_DirectionRatios[ii];
if( item_ii )
{
copy_self->m_DirectionRatios.push_back( dynamic_pointer_cast<IfcReal>(item_ii->getDeepCopy(options) ) );
}
}
return copy_self;
}
void IfcDirection::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCDIRECTION" << "(";
writeNumericTypeList( stream, m_DirectionRatios );
stream << ");";
}
void IfcDirection::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcDirection::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 1 ){ std::stringstream err; err << "Wrong parameter count for entity IfcDirection, expecting 1, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
readTypeOfRealList( args[0], m_DirectionRatios );
}
void IfcDirection::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcGeometricRepresentationItem::getAttributes( vec_attributes );
if( m_DirectionRatios.size() > 0 )
{
shared_ptr<IfcPPAttributeObjectVector> DirectionRatios_vec_object( new IfcPPAttributeObjectVector() );
std::copy( m_DirectionRatios.begin(), m_DirectionRatios.end(), std::back_inserter( DirectionRatios_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "DirectionRatios", DirectionRatios_vec_object ) );
}
}
void IfcDirection::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcGeometricRepresentationItem::getAttributesInverse( vec_attributes_inverse );
}
void IfcDirection::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcGeometricRepresentationItem::setInverseCounterparts( ptr_self_entity );
}
void IfcDirection::unlinkFromInverseCounterparts()
{
IfcGeometricRepresentationItem::unlinkFromInverseCounterparts();
}
| 44.734177 | 220 | 0.744765 | [
"vector",
"model"
] |
1d0e6c48f94248361d9d65a1ca7423d1961404b1 | 487 | cpp | C++ | luogu/p1508.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | luogu/p1508.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | luogu/p1508.cpp | freedomDR/coding | 310a68077de93ef445ccd2929e90ba9c22a9b8eb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m; cin >> n >> m;
vector<vector<int>> dp(2, vector<int>(m+5));
int p = 0;
for(int i = 0; i < n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> dp[p%2][j];
dp[p%2][j] += max(dp[(p+1)%2][j], max(dp[(p+1)%2][j-1], dp[(p+1)%2][j+1]));
}
p++;
}
cout << max(dp[(p+1)%2][m/2], max(dp[(p+1)%2][m/2+1], dp[(p+1)%2][m/2+2])) << endl;
return 0;
}
| 23.190476 | 87 | 0.390144 | [
"vector"
] |
1d1159d11178c05c83adf8a1b8438838a770f4af | 7,049 | cpp | C++ | src/deng/camera/3d/fpp_cam_ev.cpp | inugami-dev64/Deng | ce7b05db57a9ee576293f3de28f9cc3a3255f5ca | [
"Apache-2.0"
] | 5 | 2020-12-15T19:27:34.000Z | 2021-12-15T17:00:36.000Z | src/deng/camera/3d/fpp_cam_ev.cpp | inugami-dev64/Deng | ce7b05db57a9ee576293f3de28f9cc3a3255f5ca | [
"Apache-2.0"
] | null | null | null | src/deng/camera/3d/fpp_cam_ev.cpp | inugami-dev64/Deng | ce7b05db57a9ee576293f3de28f9cc3a3255f5ca | [
"Apache-2.0"
] | null | null | null | /// NEKO: dynamic engine - small but powerful 2D and 3D game engine
/// licence: Apache, see LICENCE file
/// file: fpp_cam_ev.h - first person camera event class header
/// author: Karl-Mihkel Ott
#define __FPP_CAM_EV_CPP
#include <deng/camera/3d/fpp_cam_ev.h>
namespace deng {
__FPPCameraEv::__FPPCameraEv (
Window *p_win,
const dengMath::vec2<deng_f64_t> &mouse_sens,
const dengMath::vec3<deng_vec_t> &camera_mov_sens
) : __Event3DBase (
{
NEKO_VCP_OVERFLOW_ACTION_TO_OPPOSITE_POSITION,
NEKO_VCP_OVERFLOW_ACTION_BLOCK_POSITION
},
{
{ static_cast<deng_px_t>(-BASE_MAX_VC_X / mouse_sens.first), static_cast<deng_px_t>(BASE_MAX_VC_X / mouse_sens.first) },
{ static_cast<deng_px_t>(-BASE_MAX_VC_Y / mouse_sens.second), static_cast<deng_px_t>(BASE_MAX_VC_Y / mouse_sens.second) }
},
{ PI / 2, PI * 2 },
p_win
) {
m_p_win = p_win;
m_move_speed.first = static_cast<deng_vec_t>(DENG_CAMERA_BASE_SPEED_X * camera_mov_sens.first);
m_move_speed.second = static_cast<deng_vec_t>(DENG_CAMERA_BASE_SPEED_Y * camera_mov_sens.second);
m_move_speed.third = static_cast<deng_vec_t>(DENG_CAMERA_BASE_SPEED_Z * camera_mov_sens.third);
m_move_speed.fourth = 0.0f;
}
/// Find the current movement type and direction
void __FPPCameraEv::__findMovements() {
deng_bool_t mov_nw = __checkInputAction(DENG_CAMERA_ACTION_MOV_NW);
deng_bool_t mov_w = __checkInputAction(DENG_CAMERA_ACTION_MOV_W);
deng_bool_t mov_nv = __checkInputAction(DENG_CAMERA_ACTION_MOV_NV);
deng_bool_t mov_v = __checkInputAction(DENG_CAMERA_ACTION_MOV_V);
deng_bool_t mov_nu = __checkInputAction(DENG_CAMERA_ACTION_MOV_NU);
deng_bool_t mov_u = __checkInputAction(DENG_CAMERA_ACTION_MOV_U);
// We are assuming right handed coordinate system
if(mov_nw && !mov_w) m_movements.third = DENG_MOVEMENT_FORWARD;
else if(!mov_nw && mov_w) m_movements.third = DENG_MOVEMENT_BACKWARD;
else m_movements.third = DENG_MOVEMENT_NONE;
if(mov_nu && !mov_u) m_movements.first = DENG_MOVEMENT_LEFTWARD;
else if(!mov_nu && mov_u) m_movements.first = DENG_MOVEMENT_RIGHTWARD;
else m_movements.first = DENG_MOVEMENT_NONE;
if(!mov_nv && mov_v) m_movements.second = DENG_MOVEMENT_UPWARD;
else if(mov_nv && !mov_v) m_movements.second = DENG_MOVEMENT_DOWNWARD;
else m_movements.second = DENG_MOVEMENT_NONE;
}
/// Check if input FPP camera mouse input mode has changed
void __FPPCameraEv::__checkForInputModeChange(dengMath::CameraMatrix *p_vm) {
__Event3DBase::__updateCameraMousePos();
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::duration<deng_ui64_t, std::milli> im_duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_last_input_mode_ch_beg);
// Check if input mode should be changed ([ESC] key)
if(im_duration.count() > DENG_KEY_PRESS_INTERVAL && __checkInputAction(DENG_CAMERA_ACTION_CHANGE_MM)) {
m_p_win->toggleVCMode();
if(m_p_win->isVCP())
m_p_win->changeCursor(DENG_CURSOR_MODE_HIDDEN);
else m_p_win->changeCursor(DENG_CURSOR_MODE_STANDARD);
m_last_input_mode_ch_beg = std::chrono::system_clock::now();
}
// Check if virtual mouse cursor mode is enabled and
// if true then update camera rotation and key events
if(m_p_win->isVCP()) {
__findMovements();
dengMath::vec2<deng_f64_t> rot = __Event3DBase::__getMouseRotation();
p_vm->setCameraRotation(static_cast<deng_vec_t>(rot.first), static_cast<deng_vec_t>(rot.second));
p_vm->camTransform(false);
}
else {
m_movements.first = DENG_MOVEMENT_NONE;
m_movements.second = DENG_MOVEMENT_NONE;
m_movements.third = DENG_MOVEMENT_NONE;
}
}
/// Check for input mode changes and move camera if needed
void __FPPCameraEv::updateEv(__FPPCamera *p_cam) {
__checkForInputModeChange(p_cam->getCamMatPtr());
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::duration<deng_ui64_t, std::milli> lmov_duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_last_mov_beg);
if(lmov_duration.count() > DENG_MOVEMENT_INTERVAL) {
switch (m_movements.first) {
case DENG_MOVEMENT_LEFTWARD:
p_cam->moveU(-m_move_speed.first, true);
break;
case DENG_MOVEMENT_RIGHTWARD:
p_cam->moveU(m_move_speed.first, true);
break;
case DENG_MOVEMENT_NONE: break;
default:
break;
}
switch (m_movements.second) {
case DENG_MOVEMENT_UPWARD:
if(m_p_win->getHints() & DENG_WINDOW_HINT_API_OPENGL)
p_cam->moveV(m_move_speed.second, true);
else p_cam->moveV(-m_move_speed.second, true);
break;
case DENG_MOVEMENT_DOWNWARD:
if(m_p_win->getHints() & DENG_WINDOW_HINT_API_OPENGL)
p_cam->moveV(-m_move_speed.second, true);
else p_cam->moveV(m_move_speed.second, true);
break;
case DENG_MOVEMENT_NONE:
break;
default:
break;
}
switch (m_movements.third) {
case DENG_MOVEMENT_FORWARD:
p_cam->moveW(-m_move_speed.first, true);
break;
case DENG_MOVEMENT_BACKWARD:
p_cam->moveW(m_move_speed.first, true);
break;
default:
break;
}
m_last_mov_beg = std::chrono::system_clock::now();
}
}
/// Get the pointer to the window instance
Window *__FPPCameraEv::getWinPtr() {
return m_p_win;
}
/// Set the window pointer
void __FPPCameraEv::setWinPtr(Window *p_win) {
m_p_win = p_win;
}
/// Find the correct movement speed
/// Parameters for this method are boolean flags about the axis being opposite or not
dengMath::vec4<deng_vec_t> __FPPCameraEv::getMoveSpeed (
deng_bool_t op_x,
deng_bool_t op_y,
deng_bool_t op_z
) {
dengMath::vec4<deng_vec_t> move_speed;
if(op_x)
move_speed.first = -m_move_speed.first;
else move_speed.first = m_move_speed.first;
if(op_y)
move_speed.second = m_move_speed.second;
else move_speed.second = -m_move_speed.second;
if(op_z)
move_speed.third = -m_move_speed.third;
else move_speed.third = m_move_speed.third;
return move_speed;
}
}
| 37.494681 | 155 | 0.633139 | [
"3d"
] |
1d14df99ea43998b10478c1755fdfa62c82adc9f | 2,559 | cc | C++ | mediasoup-client/deps/webrtc/src/build/fuchsia/layout_test_proxy/layout_test_proxy.cc | skgwazap/mediasoup-client-android | 474cffd75eeb3d25d515e7aca626a7e09180e99f | [
"MIT"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | mediasoup-client/deps/webrtc/src/build/fuchsia/layout_test_proxy/layout_test_proxy.cc | qq88797833/mediasoup-client-android | 474cffd75eeb3d25d515e7aca626a7e09180e99f | [
"MIT"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | mediasoup-client/deps/webrtc/src/build/fuchsia/layout_test_proxy/layout_test_proxy.cc | qq88797833/mediasoup-client-android | 474cffd75eeb3d25d515e7aca626a7e09180e99f | [
"MIT"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "net/base/ip_endpoint.h"
#include "net/test/tcp_socket_proxy.h"
const char kPortsSwitch[] = "ports";
const char kRemoteAddressSwitch[] = "remote-address";
int main(int argc, char** argv) {
base::CommandLine::Init(argc, argv);
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(kPortsSwitch)) {
LOG(ERROR) << "--" << kPortsSwitch << " was not specified.";
return 1;
}
std::vector<std::string> ports_strings =
base::SplitString(command_line->GetSwitchValueASCII(kPortsSwitch), ",",
base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
if (ports_strings.empty()) {
LOG(ERROR) << "At least one port must be specified with --" << kPortsSwitch;
return 1;
}
std::vector<int> ports;
for (auto& port_string : ports_strings) {
int port;
if (!base::StringToInt(port_string, &port) || port <= 0 || port > 65535) {
LOG(ERROR) << "Invalid value specified for --" << kPortsSwitch << ": "
<< port_string;
return 1;
}
ports.push_back(port);
}
if (!command_line->HasSwitch(kRemoteAddressSwitch)) {
LOG(ERROR) << "--" << kRemoteAddressSwitch << " was not specified.";
return 1;
}
std::string remote_address_str =
command_line->GetSwitchValueASCII(kRemoteAddressSwitch);
net::IPAddress remote_address;
if (!remote_address.AssignFromIPLiteral(remote_address_str)) {
LOG(ERROR) << "Invalid value specified for --" << kRemoteAddressSwitch
<< ": " << remote_address_str;
return 1;
}
base::MessageLoopForIO message_loop;
std::vector<std::unique_ptr<net::TcpSocketProxy>> proxies;
for (int port : ports) {
auto test_server_proxy =
std::make_unique<net::TcpSocketProxy>(message_loop.task_runner());
if (!test_server_proxy->Initialize(port)) {
LOG(ERROR) << "Can't bind proxy to port " << port;
return 1;
}
LOG(INFO) << "Listening on port " << test_server_proxy->local_port();
test_server_proxy->Start(net::IPEndPoint(remote_address, port));
proxies.push_back(std::move(test_server_proxy));
}
// Run the message loop indefinitely.
base::RunLoop().Run();
return 0;
} | 32.807692 | 80 | 0.672138 | [
"vector"
] |
1d19359f07b47eba4bb7bd06f61e249d8bde5f62 | 7,747 | hpp | C++ | renderboi/window/enums.hpp | deqyra/GLSandbox | 40d641ebbf6af694e8640a584d283876d128748c | [
"MIT"
] | null | null | null | renderboi/window/enums.hpp | deqyra/GLSandbox | 40d641ebbf6af694e8640a584d283876d128748c | [
"MIT"
] | null | null | null | renderboi/window/enums.hpp | deqyra/GLSandbox | 40d641ebbf6af694e8640a584d283876d128748c | [
"MIT"
] | null | null | null | #ifndef RENDERBOI__WINDOW__ENUMS_HPP
#define RENDERBOI__WINDOW__ENUMS_HPP
#include <string>
#include <unordered_map>
#include <vector>
#include <renderboi/utilities/to_string.hpp>
namespace Renderboi
{
namespace Window
{
namespace Input
{
namespace Mode
{
/// @brief Collection of literals describing the aspects of a window
/// whose input mode can be modified.
enum class Target
{
Cursor,
StickyKeys,
StickyMouseButtons,
LockKeyMods,
RawMouseMotion
};
/// @brief Collection of literals describing the input modes which
/// certain aspects of a window may have.
enum class Value
{
True,
False,
NormalCursor,
HiddenCursor,
DisabledCursor
};
}
/// @brief Collection of literals describing an action which was performed
/// on a key or button. The repeat action is ignored altogether.
enum class Action
{
Press,
// Repeat, // FIX ME IF REPEAT KEYS MUST BE HANDLED
Release
};
/// @brief Collection of literals describing the keys on a keyboard.
enum class Key : unsigned int
{
Unknown,
Space,
Apostrophe, /* ' */
Comma, /* , */
Minus, /* - */
Period, /* . */
Slash, /* / */
Key0,
Key1,
Key2,
Key3,
Key4,
Key5,
Key6,
Key7,
Key8,
Key9,
Semicolon, /* ; */
Equal, /* = */
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket, /* [ */
Backslash, /* \ */
RightBracket, /* ] */
GraveAccent, /* ` */
World1, /* non-US #1 */
World2, /* non-US #2 */
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Keypad0,
Keypad1,
Keypad2,
Keypad3,
Keypad4,
Keypad5,
Keypad6,
Keypad7,
Keypad8,
Keypad9,
KeypadDecimal,
KeypadDivide,
KeypadMultiply,
KeypadSubtract,
KeypadAdd,
KeypadEnter,
KeypadEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu
};
/// @brief Collection of literals describing modifier key statuses.
/// Every literal is assigned a power of 2 in order to ease bitwise
/// operations on a recorded status flag.
enum class Modifier : unsigned int
{
None = 0x0000,
Shift = 0x0001,
Control = 0x0002,
Alt = 0x0004,
Super = 0x0008,
CapsLock = 0x0010,
NumLock = 0x0020
};
/// @brief Collection of literals describing the buttons on a mouse.
enum class MouseButton : unsigned int
{
B1,
B2,
B3,
B4,
B5,
B6,
B7,
B8,
Last = B8,
Left = B1,
Right = B2,
Middle = B3
};
/// @brief Collection of literals describing hardware joysticks that can
/// be reached and polled.
enum class Joystick : unsigned int
{
J1 = 0x0,
J2 = 0x1,
J3 = 0x2,
J4 = 0x3,
J5 = 0x4,
J6 = 0x5,
J7 = 0x6,
J8 = 0x7,
J9 = 0x8,
J10 = 0x9,
J11 = 0xA,
J12 = 0xB,
J13 = 0xC,
J14 = 0xD,
J15 = 0xE,
J16 = 0xF
};
extern const std::vector<Joystick> Joysticks;
namespace Gamepad
{
/// @brief Collection of literals describing the buttons on a modern
/// gamepad (XBox, DualShock, etc).
enum class Button : unsigned int
{
A = 0x0,
B = 0x1,
X = 0x2,
Y = 0x3,
LeftBumper = 0x4,
RightBumper = 0x5,
Select = 0x6,
Start = 0x7,
Home = 0x8,
LeftThumb = 0x9,
RightThumb = 0xA,
DPadUp = 0xB,
DPadRight = 0xC,
DPadDown = 0xD,
DPadLeft = 0xE,
Cross = A,
Circle = B,
Square = X,
Triangle = Y
};
/// @brief Collection of literals describing the continous input
/// controllers on a modern gamepad.
enum class Axis : unsigned int
{
LeftX = 0x0,
LeftY = 0x1,
RightX = 0x2,
RightY = 0x3,
LeftTrigger = 0x4,
RightTrigger = 0x5
};
}
}
/// @brief Collection of literals describing the different OpenGL profiles.
enum class OpenGLProfile
{
Core,
Compatibility,
Any
};
}//namespace Window
unsigned int operator&(unsigned int left, Window::Input::Modifier right);
unsigned int operator|(unsigned int left, Window::Input::Modifier right);
bool any(Window::Input::Modifier value);
std::string to_string(const Window::Input::Mode::Target& mode);
std::string to_string(const Window::Input::Mode::Value& value);
std::string to_string(const Window::Input::Action& action);
std::string to_string(const Window::Input::Key& key);
std::string to_string(const Window::Input::Modifier& mod);
std::string to_string(const Window::Input::MouseButton& mouseButton);
std::string to_string(const Window::Input::Joystick& joystick);
std::string to_string(const Window::Input::Gamepad::Button& gamepadButton);
std::string to_string(const Window::Input::Gamepad::Axis& gamepadAxis);
}//namespace Renderboi
#endif//RENDERBOI__WINDOW__ENUMS_HPP | 25.996644 | 82 | 0.409707 | [
"vector"
] |
1d1cca109cdaed79d3ebbf34e921a88cea453c86 | 2,559 | cpp | C++ | Sources/LibRT/source/RTAnimationBones.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/LibRT/source/RTAnimationBones.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/LibRT/source/RTAnimationBones.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | /// https://github.com/Rominitch/MouCaLab
/// \author Rominitch
/// \license No license
#include "Dependencies.h"
#include "LibRT/include/RTAnimationBones.h"
namespace RT
{
void AnimationImporter::initialize(AnimationBonesSPtr animation)
{
MOUCA_PRE_CONDITION(!isNull() && !_animation);
_animation = animation;
MOUCA_PRE_CONDITION(!isNull());
}
void AnimationImporter::release()
{
MOUCA_PRE_CONDITION(!isNull());
_filename.clear();
_animation.reset();
MOUCA_PRE_CONDITION(isNull());
}
void AnimationBones::updateAnimation(AnimatedGeometry& geometry, const uint32_t idAnimation, const double time) const
{
auto& buffer = geometry.getEditBonesBuffer();
const Animation& animation = _animations[idAnimation];
// Get animation key frame
auto itNext = std::find_if(animation.cbegin(), animation.cend(), [&](const BonesFrame& frame) {return frame._time > time; });
auto itFrame = itNext;
--itFrame;
MOUCA_ASSERT(itNext != animation.cbegin());
if( itNext == animation.cend() )
{
if( !geometry.hasLoop() )
return;
else
itNext = animation.cbegin();
}
// Find interpolation factor
const double interpolate = (time - itFrame->_time) / ( itNext->_time - itFrame->_time );
MOUCA_ASSERT(0.0 <= interpolate && interpolate <= 1.0);
// Parsing all nodes
computeNodeAnimation(buffer, geometry.getBones(), Transform(), *itFrame, *itNext, interpolate);
#ifdef USE_MATRIX
// Latest element
buffer[buffer.size()-1]._transform = geometry.getOrientation().getLocalToWorld().convert();
#else
// Latest element
buffer[buffer.size() - 1]._transform = geometry.getOrientation().getLocalToWorld();
#endif
}
void AnimationBones::computeNodeAnimation(RT::BonesBuffer& buffer, const BonesHierarchy& bones, const Transform& local, const BonesFrame& start, const BonesFrame& end, const double interpolation) const
{
uint32_t id = bones._id;
// Compute local position
const Transform current = Transform::slerp(start._bonesState[id], end._bonesState[id], static_cast<float>(interpolation));
// Now global and save
const Transform nodeTransform = local * current;
const Transform final = nodeTransform * bones._offset;
#ifdef USE_MATRIX
buffer[id]._transform = final.convert();
#else
buffer[id]._transform = final;
#endif
// Parse other children
for(const auto& child : bones._children)
{
computeNodeAnimation(buffer, child, nodeTransform, start, end, interpolation);
}
}
} | 29.755814 | 201 | 0.695193 | [
"geometry",
"transform"
] |
1d1e664677618b7413672243a4fa75d769a0c217 | 6,817 | cpp | C++ | src/main.cpp | nazo6/BSQuest-QuestDarthMaul | ce0aa1d266f1fed6341541000cfb82e77c465f3f | [
"MIT"
] | null | null | null | src/main.cpp | nazo6/BSQuest-QuestDarthMaul | ce0aa1d266f1fed6341541000cfb82e77c465f3f | [
"MIT"
] | null | null | null | src/main.cpp | nazo6/BSQuest-QuestDarthMaul | ce0aa1d266f1fed6341541000cfb82e77c465f3f | [
"MIT"
] | null | null | null | #include "../include/main.hpp"
#include <dlfcn.h>
#include "../customui/customui.hpp"
int stop = 0;
CustomUI::TextObject Maul;
float grayScaleColor = 1.0f;
Vector2 posOffset = {-41.3f, -16.9f};
float fontSize = 3.6f;
bool leftHand;
bool noArrows;
void llog(const std::string &text)
{
Logger::get().info("[QuestDarthMaul dev0002]" + text);
}
MAKE_HOOK_OFFSETLESS(Refresh, void, Il2CppObject *self)
{
if (stop == 1)
{
Il2CppObject *nameText = il2cpp_utils::GetFieldValue(self, "_nameText").value();
Il2CppObject *nameTextTransform;
Il2CppObject *nameTextParent;
nameTextTransform =
il2cpp_utils::RunMethodUnsafe(nameText, "get_transform").value();
nameTextParent =
il2cpp_utils::RunMethodUnsafe(nameTextTransform, "GetParent").value();
Maul.text = "/Darth Maul Mode";
Maul.fontSize = fontSize;
Maul.parentTransform = nameTextParent;
Maul.sizeDelta = posOffset;
Maul.color = {grayScaleColor, grayScaleColor, grayScaleColor,
grayScaleColor};
Maul.create();
}
stop++;
Refresh(self);
}
MAKE_HOOK_OFFSETLESS(SongStart,
void,
Il2CppObject *self,
Il2CppString *gameMode,
Il2CppObject *difficultyBeatmap,
Il2CppObject *overrideEnvironmentSettings,
Il2CppObject *overrideColorScheme,
Il2CppObject *gameplayModifiers,
Il2CppObject *playerSpecificSettings,
Il2CppObject *practiceSettings,
Il2CppString *backButtonText,
bool useTestNoteCutSoundEffects)
{
noArrows = il2cpp_utils::RunMethodUnsafe(gameplayModifiers, "get_noArrows").value();
leftHand = il2cpp_utils::RunMethodUnsafe(playerSpecificSettings, "get_leftHanded").value();
SongStart(self, gameMode, difficultyBeatmap, overrideEnvironmentSettings,
overrideColorScheme, gameplayModifiers, playerSpecificSettings,
practiceSettings, backButtonText, useTestNoteCutSoundEffects);
llog("SongStart Hook");
}
MAKE_HOOK_OFFSETLESS(PlayerController_Update, void, Il2CppObject *self)
{
llog("Activate");
PlayerController_Update(self);
if (noArrows)
{
Il2CppObject *leftSaber =
il2cpp_utils::GetFieldValue(self, "_leftSaber").value();
Il2CppObject *rightSaber =
il2cpp_utils::GetFieldValue(self, "_rightSaber").value();
if (leftSaber != nullptr && rightSaber != nullptr)
{
Il2CppObject *leftSaberTransform = nullptr;
Il2CppObject *rightSaberTransform = nullptr;
Il2CppClass *componentsClass = il2cpp_utils::GetClassFromName("", "Saber");
leftSaberTransform = il2cpp_utils::RunMethod(leftSaber,
il2cpp_functions::class_get_method_from_name(
componentsClass, "get_transform", 0))
.value();
rightSaberTransform =
il2cpp_utils::RunMethod(rightSaber,
il2cpp_functions::class_get_method_from_name(
componentsClass, "get_transform", 0))
.value();
if (leftSaberTransform != nullptr && rightSaberTransform != nullptr)
{
Il2CppClass *transformClass =
il2cpp_utils::GetClassFromName("UnityEngine", "Transform");
const MethodInfo *getMethod =
il2cpp_functions::class_get_method_from_name(
transformClass, "get_localPosition", 0);
const MethodInfo *setMethod =
il2cpp_functions::class_get_method_from_name(
transformClass, "set_localPosition", 1);
const MethodInfo *setRotate =
il2cpp_functions::class_get_method_from_name(transformClass,
"Rotate", 1);
const MethodInfo *setTranslate =
il2cpp_functions::class_get_method_from_name(transformClass,
"Translate", 1);
const MethodInfo *getLocalRotation =
il2cpp_functions::class_get_method_from_name(
transformClass, "get_localRotation", 0);
const MethodInfo *setLocalRotation =
il2cpp_functions::class_get_method_from_name(
transformClass, "set_localRotation", 1);
Vector3 rightSaberLocalPosition;
Vector3 leftSaberLocalPosition;
rightSaberLocalPosition = il2cpp_utils::RunMethod<Vector3>(rightSaberTransform, getMethod).value();
leftSaberLocalPosition = il2cpp_utils::RunMethod<Vector3>(leftSaberTransform, getMethod).value();
Quaternion rightSaberLocalRotation;
Quaternion leftSaberLocalRotation;
rightSaberLocalRotation = il2cpp_utils::RunMethod<Quaternion>(rightSaberTransform, getLocalRotation).value();
leftSaberLocalRotation = il2cpp_utils::RunMethod<Quaternion>(leftSaberTransform, getLocalRotation).value();
if (!leftHand)
{
il2cpp_utils::RunMethod(leftSaberTransform, setMethod, rightSaberLocalPosition);
il2cpp_utils::RunMethod(leftSaberTransform, setLocalRotation, rightSaberLocalRotation);
il2cpp_utils::RunMethod(leftSaberTransform, setRotate, Vector3{0, 180, 0});
il2cpp_utils::RunMethod(leftSaberTransform, setTranslate, Vector3{0, 0, 0.335});
}
else
{
il2cpp_utils::RunMethod(rightSaberTransform, setMethod, leftSaberLocalPosition);
il2cpp_utils::RunMethod(rightSaberTransform, setLocalRotation, leftSaberLocalRotation);
il2cpp_utils::RunMethod(rightSaberTransform, setRotate, Vector3{0, 180, 0});
il2cpp_utils::RunMethod(rightSaberTransform, setTranslate, Vector3{0, 0, 0.335});
}
llog("position set");
}
}
}
}
MAKE_HOOK_OFFSETLESS(HapticFeedbackController_HitNote,
void,
Il2CppObject *self,
int node)
{
if (noArrows)
{
if (!leftHand)
{
node = 5;
}
else
{
node = 4;
}
}
HapticFeedbackController_HitNote(self, node);
}
extern "C" void load()
{
INSTALL_HOOK_OFFSETLESS(Refresh, il2cpp_utils::FindMethodUnsafe("", "GameplayModifierToggle", "Start", 0));
INSTALL_HOOK_OFFSETLESS(
SongStart,
il2cpp_utils::FindMethodUnsafe("", "StandardLevelScenesTransitionSetupDataSO", "Init", 9));
INSTALL_HOOK_OFFSETLESS(
PlayerController_Update,
il2cpp_utils::FindMethodUnsafe("", "SaberManager", "Update", 0));
INSTALL_HOOK_OFFSETLESS(
HapticFeedbackController_HitNote,
il2cpp_utils::FindMethodUnsafe("", "NoteCutHapticEffect", "HitNote", 1));
llog("Hooks installed.");
} | 36.260638 | 117 | 0.646032 | [
"transform"
] |
918f50da8934e1e1a043e687f87c5df5858c47bb | 6,104 | cpp | C++ | src/main.cpp | mushrom/softrend | eef6e8ef8cc32c04ea4371b4f59da4b68c4a754f | [
"MIT"
] | null | null | null | src/main.cpp | mushrom/softrend | eef6e8ef8cc32c04ea4371b4f59da4b68c4a754f | [
"MIT"
] | null | null | null | src/main.cpp | mushrom/softrend | eef6e8ef8cc32c04ea4371b4f59da4b68c4a754f | [
"MIT"
] | null | null | null | #include <softrend/backend/sdl.hpp>
#include <softrend/render.hpp>
#include <softrend/jobQueue.hpp>
#include <softrend/cubeMesh.hpp>
#include <softrend/attributes.hpp>
#include <softrend/shader.hpp>
#include <softrend/renderContext.hpp>
#include <softrend/renderImpl.hpp>
#include <chrono>
#include <vector>
#include <array>
#include <algorithm> // sort
#include <list>
using namespace softrend;
struct asdfUniforms {
mat4 p;
mat4 v;
mat4 m;
mat4 rotx;
mat4 roty;
vec3 cameraPos;
float zoom;
float xoff;
uint32_t color;
};
static inline
uint32_t getTexel(vec2 uv) {
int width = _179_small_ppm_img.width;
int height = _179_small_ppm_img.height;
int x = int(uv[0] * width) % width;
int y = int(uv[1] * height) % height;
x = (x < 0)? width + x : x;
y = (y < 0)? height + y : y;
uint8_t *idx = _179_small_ppm_img.pixels
+ 3*(y*width)
+ 3*x;
//return (ubvec4) {0xff, idx[2], idx[1], idx[0]};
return idx[2] | (idx[1] << 8) | (idx[0] << 16);
}
template <typename T, typename U, typename F>
struct textureShader : baseShader<T, U, F> {
static inline
bool fragmentShader(const U& uniforms,
const T& in,
F& buffers,
int fragX,
int fragY)
{
auto c = getTexel(in.uv);
buffers.color->setPixel(fragX, fragY, c);
return true;
}
};
template <typename T, typename U, typename F>
struct constantColorShader : baseShader<T, U, F> {
static inline
bool fragmentShader(const U& uniforms,
const T& in,
F& buffers,
int fragX,
int fragY)
{
buffers.color->setPixel(fragX, fragY, uniforms.color);
return true;
}
};
int main(void) {
__builtin_cpu_init();
#if 0
// TODO: platform checks, hotpaths for different feature support...?
if (!__builtin_cpu_supports("avx")) {
puts("wut");
return 1;
}
#endif
SDL_Init(SDL_INIT_VIDEO);
sdl2_backend back(1280, 720);
jobQueue jobs(std::thread::hardware_concurrency());
auto fb = back.getFramebuffer();
framebuffer<float> depthfb(fb->width, fb->height, fb->pitch);
renderContext<vertexOut, asdfUniforms, constantColorShader> ctx(jobs, fb, &depthfb);
renderContext<vertexOut, asdfUniforms, textureShader> texctx(jobs, fb, &depthfb);
vertex_buffer vertbuf;
for (auto& em : cube_vertices) { vertbuf.vertices.push_back(em); }
for (auto& em : cube_normals) { vertbuf.normals.push_back(em); }
for (auto& em : cube_elements) { vertbuf.elements.push_back(em); }
for (auto& em : cube_texcoords) { vertbuf.uvs.push_back(em); }
printf("\n");
float times[8];
unsigned timeidx;
asdfUniforms uniforms;
uniforms.p = perspective(M_PI/2.f, 16.f/9.f, 0.1f, 100.f);
uniforms.rotx = identity_mat4();
uniforms.roty = identity_mat4();
uniforms.zoom = 64;
uniforms.xoff = 0.f;
uniforms.cameraPos = (vec3) {0, 0, 0};
uniforms.color = 0x8080b0;
mat4 cameraRot = identity_mat4();
int flags
= DepthTest
| DepthMask
| CullBackFaces
| SortGeometry;
for (size_t i = 0;; i++) {
auto start = std::chrono::high_resolution_clock::now();
SDL_Event ev;
while (SDL_PollEvent(&ev)) {
if (ev.type == SDL_QUIT)
return 0;
if (ev.type == SDL_KEYDOWN) {
switch (ev.key.keysym.sym) {
case SDLK_w: uniforms.cameraPos[2] += 1.0; break;
case SDLK_a: uniforms.cameraPos[0] += 1.0; break;
case SDLK_s: uniforms.cameraPos[2] -= 1.0; break;
case SDLK_d: uniforms.cameraPos[0] -= 1.0; break;
case SDLK_q: uniforms.cameraPos[1] += 1.0; break;
case SDLK_e: uniforms.cameraPos[1] -= 1.0; break;
default: break;
}
}
}
int mx, my;
uint32_t mouse = SDL_GetMouseState(&mx, &my);
if (mouse & SDL_BUTTON(SDL_BUTTON_LEFT)) {
//rotx = rotateY(M_PI * float(mx) / fb->width);
uniforms.rotx = rotateY(2*M_PI * float(mx) / fb->width);
uniforms.roty = rotateX(2*M_PI * float(my) / fb->height);
}
if (mouse & SDL_BUTTON(SDL_BUTTON_RIGHT)) {
uniforms.zoom = 32 + 64*(float(my)/fb->height - 0.5);
uniforms.xoff = 32*(float(mx)/fb->width - 0.5);
}
if (mouse & SDL_BUTTON(SDL_BUTTON_MIDDLE)) {
//uniforms.v = mult()
mat4 rx = rotateY(-2*M_PI * float(mx) / fb->width);
mat4 ry = rotateX(-2*M_PI * float(my) / fb->height);
//cameraRot = rx;
cameraRot = mult(rx, ry);
}
fb->clear();
depthfb.clear(HUGE_VALF);
uniforms.v = mult(translate(-uniforms.cameraPos), cameraRot);
//uniforms.v = translate(-uniforms.cameraPos);
uniforms.color = 0x8080b0;
uniforms.m = translate((vec3) {uniforms.xoff, 0, uniforms.zoom});
drawBufferTriangles(ctx, vertbuf, uniforms, flags);
#if 1
time_t foo = time(NULL);
uint64_t j = 0;
for (int kz = 8; kz < 72; kz += 16) {
for (int kx = -8; kx < 8; kx += 4) {
for (int ky = -8; ky < 8; ky += 4) {
uniforms.color
= (((kz-8)/16) << 20)
| (((kx+8)/4) << 12)
| (((ky+8)/4) << 4)
;
uniforms.color += 0x020202;
uniforms.m = translate((vec3) {
uniforms.xoff + kx,
float(ky),
uniforms.zoom + kz
});
if (kx < 0) {
drawBufferTriangles(texctx, vertbuf, uniforms, flags);
} else {
drawBufferTriangles(ctx, vertbuf, uniforms, flags);
}
#if 0
//if (foo&(1ULL << j)) { // uncomment for binary clock lol
uniforms.m = translate((vec3) {
uniforms.xoff + kx,
float(ky),
uniforms.zoom + kz
});
drawBufferTriangles(nctx, vertbuf, uniforms, flags);
//}
j++;
#endif
}
}
}
#endif
ctx.sync();
texctx.sync();
auto end = std::chrono::high_resolution_clock::now();
back.swapFramebuffer();
std::chrono::duration<float> secs = end - start;
times[timeidx++ % 8] = secs.count();
float frametimes = 0;
for (unsigned i = 0; i < 8; i++) {
frametimes += times[(timeidx + i) % 8];
}
frametimes /= 8.f;
static unsigned counter = 1;
if (counter++ % 11 == 0) {
printf("\rFPS: %g ", 1.f/frametimes);
fflush(stdout);
}
int time = 1000 * (1/60.f - secs.count());
if (time > 0) {
SDL_Delay(time);
}
//SDL_Delay(16);
//SDL_Delay(32);
}
return 0;
}
| 24.318725 | 85 | 0.614515 | [
"render",
"vector"
] |
91a28451bc2a23958d86cdf7151a3cb08b60fd30 | 3,711 | cc | C++ | src/converter/SvgExporter.cc | jmvdwerf/FaBriCAD | 522ab9b1a930539681dd255679a2a30471e014a4 | [
"MIT"
] | null | null | null | src/converter/SvgExporter.cc | jmvdwerf/FaBriCAD | 522ab9b1a930539681dd255679a2a30471e014a4 | [
"MIT"
] | null | null | null | src/converter/SvgExporter.cc | jmvdwerf/FaBriCAD | 522ab9b1a930539681dd255679a2a30471e014a4 | [
"MIT"
] | null | null | null |
#include <vector>
#include "SvgExporter.h"
namespace fabricad::converter
{
SvgExporter::SvgExporter()
{
createInitialFile = false;
}
box SvgExporter::determineEnvelope(fabricad::config::Blueprint* print)
{
box mBound(point(0,0),point(0,0));
for(auto& item: print->getLayers())
{
std::vector<shapelayer> layers = item.second;
for(int layer = 0 ; layer < 4 ; layer++)
{
for(int i = 0 ; i < layers[layer].polygons.size() ; i++)
{
box b;
bg::envelope(layers[layer].polygons[i], b);
bg::expand(mBound, b);
}
for(int i = 0 ; i < layers[layer].lines.size() ; i++)
{
box b;
bg::envelope(layers[layer].lines[i], b);
bg::expand(mBound, b);
}
}
}
return mBound;
}
void SvgExporter::handleBlockStart(fabricad::blocks::BasicBuildingBlock* block, std::string const& filename, std::ostream &out)
{
out << "\t<g id=\"" << block->getId() << "\" ";
out << "inkscape:label=\"" << block->getName() << "\" ";
out << "inkscape:groupmode=\"layer\" >" << std::endl;
}
void SvgExporter::handleBlockFinish(fabricad::blocks::BasicBuildingBlock* block, std::string const& filename, std::ostream &out)
{
out << "\t</g>" << std::endl;
}
void SvgExporter::handleBlueprintStart(fabricad::config::Blueprint* print, std::string const& filename, std::ofstream &out)
{
// Create a new out stream based on filename and Blueprint ID
out.close();
std::string file = filename + "_" + print->getId() + ".svg";
// TODO: Check that file path exists, and if not, create it.
out.open(file, std::ofstream::out);
box maxBound = determineEnvelope(print);
float topX = maxBound.max_corner().get<0>() + 20;
float topY = maxBound.max_corner().get<1>() + 20;
top = topY;
out << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" << std::endl;
out << "<svg height=\""<< topY << "mm\" width=\"" << topX << "mm\" ";
out << "viewBox=\"0 0 "<< topX << " " << topY << "\" ";
out << "xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\">" << std::endl;
}
void SvgExporter::handleBlueprintFinish(fabricad::config::Blueprint* print, std::string const& filename, std::ofstream &out)
{
out << "</svg>" << std::endl;
out.close();
}
void SvgExporter::handleLayerStart(std::ostream &out, shapelayer const& layer)
{
out << "\t\t<g id=\"" << getCurrentBlock()->getId() << "_" << layer.id << "\" ";
out << "inkscape:label=\"" << layer.name << "\" ";
out << "inkscape:groupmode=\"layer\" >" << std::endl;
}
void SvgExporter::handleLayerFinish(std::ostream &out, shapelayer const& layer)
{
out << "\t\t</g>" << std::endl;
}
void SvgExporter::handlePolygon(std::ostream &out, polygon const& p)
{
std::vector<point> const& points = p.outer();
out << "\t\t\t<polygon points=\"";
for(size_t i = 0 ; i < points.size() ; ++i )
{
handlePoint(out, points[i]);
out << " ";
}
out << "\" style=\"fill:"<< getColor() << ";stroke:black;stroke-width:1\" fill-opacity=\"0.5\" />";
out << std::endl;
}
void SvgExporter::handleLinestring(std::ostream &out, linestring const& l)
{
out << "\t\t\t<polyline style=\"stroke:"<< getLineColor() << ";stroke-width:" << getLineWidth() << "\" points=\"";
for(int i = 0 ; i < l.size() ; i++)
{
handlePoint(out, l[i]);
out << " ";
}
out << + "\" />" << std::endl;
}
void SvgExporter::handlePoint(std::ostream &out, point const& p)
{
float x = p.get<0>() + 10;
float y = top - p.get<1>() - 10;
out << x << ", " << y;
}
}
| 29.927419 | 130 | 0.560496 | [
"vector"
] |
91a8641d6545ed5ee203bdfa5862859410c5b9de | 579 | cpp | C++ | uva/12531.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | uva/12531.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | uva/12531.cpp | partho222/programming | 98a87b6a04f39c343125cf5f0dd85e0f1c37d56c | [
"BSD-2-Clause"
] | null | null | null | #include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main()
{
int deg;
while(scanf("%d",°)!=EOF)
{
if((deg%6)==0)
{
cout << "Y\n";
}
else
{
cout << "N\n";
}
}
return 0;
}
| 15.648649 | 33 | 0.509499 | [
"vector"
] |
91abcb51e3a67ec6c583ac5e173556928711dc00 | 3,316 | cpp | C++ | TAO/orbsvcs/tests/ImplRepo/nestea_client_i.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/orbsvcs/tests/ImplRepo/nestea_client_i.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/orbsvcs/tests/ImplRepo/nestea_client_i.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: nestea_client_i.cpp 91672 2010-09-08 18:44:58Z johnnyw $
#include "nestea_client_i.h"
#include "tao/debug.h"
#include "ace/Get_Opt.h"
#include "ace/Read_Buffer.h"
#include "ace/ACE.h"
// Constructor.
Nestea_Client_i::Nestea_Client_i (void)
: server_key_ (ACE::strnew (ACE_TEXT("key0")))
, server_ (Nestea_Bookshelf::_nil ())
, shutdown_server_(false)
{
}
// Parses the command line arguments and returns an error status.
int
Nestea_Client_i::parse_args (void)
{
ACE_Get_Opt get_opts (argc_, argv_, ACE_TEXT("dsn:k:"));
int c;
while ((c = get_opts ()) != -1)
switch (c)
{
case 'd': // debug flag
TAO_debug_level++;
break;
case 'k': // ior provide on command line
delete [] this->server_key_;
this->server_key_ = ACE::strnew (get_opts.opt_arg ());
break;
case 's': // shutdown server before exiting
this->shutdown_server_ = true;
break;
case '?':
default:
ACE_ERROR_RETURN ((LM_ERROR,
"usage: %s"
" [-d]"
" [-n loopcount]"
" [-s]"
" [-k server-object-key]"
"\n",
this->argv_ [0]),
-1);
}
// Indicates successful parsing of command line.
return 0;
}
// Execute client example code.
int
Nestea_Client_i::run ()
{
this->server_->drink (40);
this->server_->drink (100);
CORBA::String_var praise = this->server_->get_praise ();
ACE_DEBUG ((LM_DEBUG, "Cans: %d\n"
"Praise: %s\n",
this->server_->bookshelf_size (),
praise.in ()));
this->server_->drink (500);
this->server_->crush (200);
praise = this->server_->get_praise ();
ACE_DEBUG ((LM_DEBUG, "Cans: %d\n"
"Praise: %s\n",
this->server_->bookshelf_size (),
praise.in ()));
if (shutdown_server_)
server_->shutdown();
return 0;
}
Nestea_Client_i::~Nestea_Client_i (void)
{
// Free resources
CORBA::release (this->server_);
delete [] this->server_key_;
}
int
Nestea_Client_i::init (int argc, ACE_TCHAR **argv)
{
this->argc_ = argc;
this->argv_ = argv;
try
{
// Retrieve the ORB.
this->orb_ = CORBA::ORB_init (this->argc_,
this->argv_,
"internet");
// Parse command line and verify parameters.
if (this->parse_args () == -1)
return -1;
if (this->server_key_ == 0)
ACE_ERROR_RETURN ((LM_ERROR,
"%s: no server key specified\n",
this->argv_[0]),
-1);
CORBA::Object_var server_object =
this->orb_->string_to_object (this->server_key_);
this->server_ = Nestea_Bookshelf::_narrow (server_object.in());
if (CORBA::is_nil (server_object.in ()))
ACE_ERROR_RETURN ((LM_ERROR,
"Error: invalid server key <%s>\n", this->server_key_), -1);
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("Nestea_Client_i::init");
return -1;
}
return 0;
}
| 24.382353 | 70 | 0.522618 | [
"object"
] |
91ac44a64d419bad09e71d3a8e2605c870ae3db6 | 1,577 | cpp | C++ | StockfishFragmented/src/main/cpp/utils/jniutils.cpp | loloof64/StockfishParcelizedCompose | 3975636005d64ea1395f201dfe75f722053a762a | [
"MIT"
] | null | null | null | StockfishFragmented/src/main/cpp/utils/jniutils.cpp | loloof64/StockfishParcelizedCompose | 3975636005d64ea1395f201dfe75f722053a762a | [
"MIT"
] | null | null | null | StockfishFragmented/src/main/cpp/utils/jniutils.cpp | loloof64/StockfishParcelizedCompose | 3975636005d64ea1395f201dfe75f722053a762a | [
"MIT"
] | null | null | null | /**
* Laurent Bernabe - 2022
*/
#include <jni.h>
#include <vector>
#include <string>
namespace loloof64 {
/*
* Adapted from https://stackoverflow.com/a/19592062/662618
*/
std::vector<std::string> nativeStringsArrayToStlVector(
JNIEnv* env,
jobject /* this */,
jobjectArray stringsArray) {
std::vector<std::string> result;
int size = env->GetArrayLength(stringsArray);
for (int i=0; i < size; ++i)
{
jstring currentNativeString = (jstring) env->GetObjectArrayElement(stringsArray, i);
const char* currentCString = env->GetStringUTFChars(currentNativeString, 0);
std::string currentSTLString(currentCString);
result.push_back(currentSTLString);
env->ReleaseStringUTFChars(currentNativeString, currentCString);
env->DeleteLocalRef(currentNativeString);
}
return result;
}
jobjectArray stlStringsVectorToNativeStringsArray(
JNIEnv* env,
jobject /* this */,
std::vector<std::string> inputVector
) {
jobjectArray result;
int arraySize = inputVector.size();
result = (jobjectArray) env->NewObjectArray(arraySize,
env->FindClass("java/lang/String"),
NULL);
for (int i = 0; i < arraySize; i++) {
env->SetObjectArrayElement(result, i, env->NewStringUTF(inputVector[i].c_str()));
}
return result;
}
} | 30.921569 | 96 | 0.571972 | [
"vector"
] |
91b0fbde3fc64acb8d545d883c835bdab91044b7 | 47,880 | cpp | C++ | src/liquidappconfigwindow.cpp | Y2Z/liquid | f55fd3c6f8e9cf2f6f024df4499470945b06400f | [
"CC0-1.0"
] | 5 | 2017-02-10T08:37:14.000Z | 2022-03-27T23:52:56.000Z | src/liquidappconfigwindow.cpp | Y2Z/Liquid | f55fd3c6f8e9cf2f6f024df4499470945b06400f | [
"CC0-1.0"
] | 87 | 2016-01-22T01:39:59.000Z | 2022-01-04T01:17:30.000Z | src/liquidappconfigwindow.cpp | Y2Z/liquid | f55fd3c6f8e9cf2f6f024df4499470945b06400f | [
"CC0-1.0"
] | 1 | 2017-04-20T20:14:00.000Z | 2017-04-20T20:14:00.000Z | #include <QDir>
#include <QNetworkCookie>
#include <QWebEngineProfile>
#include "liquid.hpp"
#include "liquidappconfigwindow.hpp"
#include "lqd.h"
#include "mainwindow.hpp"
LiquidAppConfigDialog::LiquidAppConfigDialog(QWidget* parent, QString liquidAppName) : QDialog(parent)
{
setWindowFlags(Qt::Window);
liquidAppName = liquidAppName.replace(QDir::separator(), "_");
Liquid::applyQtStyleSheets(this);
// Attempt to load liquid app's config file
QSettings* existingLiquidAppConfig = new QSettings(QSettings::IniFormat,
QSettings::UserScope,
QString(PROG_NAME "%1" LQD_APPS_DIR_NAME).arg(QDir::separator()),
liquidAppName,
Q_NULLPTR);
// Check to see if Liquid app by this name already has config file
if (liquidAppName.size() > 0) {
isEditingExistingBool = existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_URL);
} else {
delete existingLiquidAppConfig;
}
if (isEditingExistingBool) {
setWindowTitle(tr("Editing existing Liquid App “%1”").arg(liquidAppName));
} else {
setWindowTitle(tr("Adding new Liquid App"));
}
backgroundColor = new QColor(LQD_DEFAULT_BG_COLOR);
QVBoxLayout* mainLayout = new QVBoxLayout();
mainLayout->setSpacing(4);
mainLayout->setContentsMargins(4, 4, 4, 4);
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
QGridLayout* basicLayout = new QGridLayout();
QWidget* advancedWidget = new QWidget(this);
QVBoxLayout* advancedLayout = new QVBoxLayout();
advancedWidget->setContentsMargins(0, 0, 0, 0);
advancedWidget->setLayout(advancedLayout);
QTabWidget* tabWidget = new QTabWidget;
mainLayout->addLayout(basicLayout);
// Name input
{
QLabel* nameInputLabel = new QLabel(tr("Name:"), this);
nameInput = new QLineEdit;
nameInput->setMinimumSize(480, 0);
nameInput->setPlaceholderText("my-liquid-app-name");
nameInput->setText(liquidAppName);
if (isEditingExistingBool) {
// TODO: make it possible to edit names for existing Liquid apps
nameInput->setReadOnly(true);
}
basicLayout->addWidget(nameInputLabel, 0, 0);
basicLayout->addWidget(nameInput, 0, 1);
}
// "URL" input
{
QLabel* addressInputLabel = new QLabel(tr("URL:"), this);
addressInput = new QLineEdit;
addressInput->setPlaceholderText("https://example.com");
if (isEditingExistingBool) {
addressInput->setText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_URL).toString());
}
basicLayout->addWidget(addressInputLabel, 1, 0);
basicLayout->addWidget(addressInput, 1, 1);
}
// Extra checkboxes visible only in "Create" mode
if (!isEditingExistingBool) {
QHBoxLayout* extraCheckboxesLayout = new QHBoxLayout();
// "Create desktop icon" checkbox
{
createIconCheckBox = new QCheckBox(tr("Create desktop icon"), this);
createIconCheckBox->setCursor(Qt::PointingHandCursor);
extraCheckboxesLayout->addWidget(createIconCheckBox);
}
// "Run after creation" checkbox
{
planningToRunCheckBox = new QCheckBox(tr("Run after creation"), this);
planningToRunCheckBox->setChecked(isPlanningToRunBool);
planningToRunCheckBox->setCursor(Qt::PointingHandCursor);
extraCheckboxesLayout->addWidget(planningToRunCheckBox, 0, Qt::AlignRight);
}
basicLayout->addLayout(extraCheckboxesLayout, 2, 1);
}
QPushButton* advancedButton;
QPushButton* cancelButton;
QPushButton* saveButton;
// Horizontal buttons ("Advanced", "Cancel", "Create"/"Save")
{
QHBoxLayout* buttonsLayout = new QHBoxLayout();
buttonsLayout->setSpacing(4);
buttonsLayout->setContentsMargins(0, 0, 0, 0);
{
advancedButton = new QPushButton(tr("Advanced"), this);
advancedButton->setCursor(Qt::PointingHandCursor);
advancedButton->setCheckable(true);
buttonsLayout->addWidget(advancedButton);
connect(advancedButton, SIGNAL(toggled(bool)), advancedWidget, SLOT(setVisible(bool)));
}
{
cancelButton = new QPushButton(tr("Cancel"), this);
cancelButton->setCursor(Qt::PointingHandCursor);
buttonsLayout->addWidget(cancelButton);
connect(cancelButton, &QPushButton::clicked, [&]() {
close();
});
}
{
saveButton = new QPushButton(tr((isEditingExistingBool) ? "Save" : "Add"), this);
saveButton->setCursor(Qt::PointingHandCursor);
saveButton->setDefault(true);
buttonsLayout->addWidget(saveButton);
connect(saveButton, &QPushButton::clicked, [&]() {
save();
});
}
mainLayout->addLayout(buttonsLayout);
}
advancedLayout->addWidget(tabWidget);
/////////////////
// General tab //
/////////////////
{
QWidget* generalTabWidget = new QWidget(this);
QVBoxLayout* generalTabWidgetLayout = new QVBoxLayout();
generalTabWidget->setLayout(generalTabWidgetLayout);
tabWidget->addTab(generalTabWidget, tr("General"));
// Title text input
{
QHBoxLayout* titleLayout = new QHBoxLayout();
// Title label
{
QLabel* textLabel = new QLabel(tr("Title:"), this);
titleLayout->addWidget(textLabel);
}
// Title text input
{
titleInput = new QLineEdit(this);
titleInput->setPlaceholderText(tr("Application Title"));
if (isEditingExistingBool) {
titleInput->setText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_TITLE).toString());
}
titleLayout->addWidget(titleInput);
}
generalTabWidgetLayout->addLayout(titleLayout);
}
// Additional domains list view
{
generalTabWidgetLayout->addWidget(separator());
// Additional domains label
{
QLabel* additionalDomainsListLabel = new QLabel(tr("Additional domains:"), this);
generalTabWidgetLayout->addWidget(additionalDomainsListLabel);
}
// Editable list of additional domains
{
additionalDomainsListView = new QListView(this);
additionalDomainsModel = new QStandardItemModel(this);
// Assign model
additionalDomainsListView->setModel(additionalDomainsModel);
// Fill model items
if (isEditingExistingBool) {
if (existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_ADDITIONAL_DOMAINS)) {
const QStringList additionalDomainsList = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_ADDITIONAL_DOMAINS).toString().split(" ");
for (int i = 0; i < additionalDomainsList.size(); i++) {
QStandardItem* item = new QStandardItem(additionalDomainsList[i]);
additionalDomainsModel->appendRow(item);
}
}
}
// Append empty row
additionalDomainsModel->appendRow(new QStandardItem());
connect(additionalDomainsModel, &QStandardItemModel::itemChanged, [&](QStandardItem* item){
const int itemIndex = item->row();
const bool isLastItem = itemIndex == additionalDomainsModel->rowCount() - 1;
static const QRegularExpression allowedCharacters = QRegularExpression("[^a-z0-9\\.:\\-]");
// Format domain name
item->setText(item->text().toLower().remove(allowedCharacters));
if (item->text().size() == 0) {
// Automatically remove empty rows from the list
if (!isLastItem) {
additionalDomainsModel->removeRows(itemIndex, 1);
}
} else {
if (isLastItem) {
// Append empty row
additionalDomainsModel->appendRow(new QStandardItem());
}
}
});
}
generalTabWidgetLayout->addWidget(additionalDomainsListView);
}
// Custom user-agent text input
{
generalTabWidgetLayout->addWidget(separator());
QHBoxLayout* customUserAgentLayout = new QHBoxLayout();
// Custom user-agent label
{
QLabel* customUserAgentLabel = new QLabel(tr("Custom user-agent string:"), this);
customUserAgentLayout->addWidget(customUserAgentLabel);
}
// Custom user-agent text input
{
userAgentInput = new QLineEdit(this);
// Set placeholder to what QWebEngineProfile has by default
userAgentInput->setPlaceholderText(Liquid::getDefaultUserAgentString());
if (isEditingExistingBool) {
userAgentInput->setText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_USER_AGENT).toString());
}
customUserAgentLayout->addWidget(userAgentInput);
}
generalTabWidgetLayout->addLayout(customUserAgentLayout);
}
// Notes text area
{
generalTabWidgetLayout->addWidget(separator());
QLabel* notesLabel = new QLabel(tr("Notes:"), this);
notesTextArea = new QPlainTextEdit(this);
notesTextArea->setPlaceholderText(tr("Intentionally left blank"));
if (isEditingExistingBool) {
notesTextArea->setPlainText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_NOTES).toString());
}
generalTabWidgetLayout->addWidget(notesLabel);
generalTabWidgetLayout->addWidget(notesTextArea);
}
}
////////////////////
// Appearance tab //
////////////////////
{
QWidget* appearanceTabWidget = new QWidget(this);
QVBoxLayout* appearanceTabWidgetLayout = new QVBoxLayout();
appearanceTabWidget->setLayout(appearanceTabWidgetLayout);
tabWidget->addTab(appearanceTabWidget, tr("Appearance"));
// Hide scrollbars checkbox
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
{
hideScrollBarsCheckBox = new QCheckBox(tr("Hide scrollbars"), this);
hideScrollBarsCheckBox->setCursor(Qt::PointingHandCursor);
if (isEditingExistingBool) {
if (existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_HIDE_SCROLLBARS)) {
hideScrollBarsCheckBox->setChecked(
existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_HIDE_SCROLLBARS).toBool()
);
}
}
appearanceTabWidgetLayout->addWidget(hideScrollBarsCheckBox);
}
#endif
// Remove window frame
{
appearanceTabWidgetLayout->addWidget(separator());
removeWindowFrameCheckBox = new QCheckBox(tr("Remove window frame"), this);
removeWindowFrameCheckBox->setCursor(Qt::PointingHandCursor);
if (isEditingExistingBool) {
if (existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_REMOVE_WINDOW_FRAME)) {
removeWindowFrameCheckBox->setChecked(
existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_REMOVE_WINDOW_FRAME).toBool()
);
}
}
appearanceTabWidgetLayout->addWidget(removeWindowFrameCheckBox);
}
// Custom background color
{
appearanceTabWidgetLayout->addWidget(separator());
QHBoxLayout* customBackgroundColorButtonLayout = new QHBoxLayout();
// Use custom background checkbox
{
useCustomBackgroundCheckBox = new QCheckBox(tr("Use custom background color:"), this);
useCustomBackgroundCheckBox->setCursor(Qt::PointingHandCursor);
customBackgroundColorButtonLayout->addWidget(useCustomBackgroundCheckBox);
}
// Custom background color button
{
customBackgroundColorButton = new QPushButton("█");
customBackgroundColorButton->setCursor(Qt::PointingHandCursor);
customBackgroundColorButton->setFlat(true);
customBackgroundColorButton->setFixedSize(customBackgroundColorButton->width(), 24);
static const QString buttonStyle = QString("background-image: url(:/images/checkers.svg); border-radius: 4px; padding: 0; color: %1; font-size: %2px;");
// TODO: animate background pattern
static const int fontSize = customBackgroundColorButton->width() * 0.9;
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_CUSTOM_BG_COLOR)) {
backgroundColor = new QColor(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_CUSTOM_BG_COLOR).toString());
customBackgroundColorButton->setStyleSheet(buttonStyle.arg(backgroundColor->name(QColor::HexArgb)).arg(fontSize));
} else {
static const QColor defaultColor = QColor(LQD_DEFAULT_BG_COLOR);
customBackgroundColorButton->setStyleSheet(buttonStyle.arg(defaultColor.name(QColor::HexArgb)).arg(fontSize));
}
customBackgroundColorButtonLayout->addWidget(customBackgroundColorButton);
connect(customBackgroundColorButton, &QPushButton::clicked, [&]() {
const QColorDialog::ColorDialogOptions options = QFlag(QColorDialog::ShowAlphaChannel);
QColor color = QColorDialog::getColor(*backgroundColor, this, tr("Pick custom background color"), options);
if (color.isValid()) {
if (!useCustomBackgroundCheckBox->isChecked()) {
useCustomBackgroundCheckBox->setChecked(true);
}
*backgroundColor = color;
customBackgroundColorButton->setStyleSheet(buttonStyle.arg(backgroundColor->name(QColor::HexArgb)).arg(fontSize));
}
});
}
appearanceTabWidgetLayout->addLayout(customBackgroundColorButtonLayout);
if (isEditingExistingBool) {
bool enabledInConfig = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_USE_CUSTOM_BG, false).toBool();
useCustomBackgroundCheckBox->setChecked(enabledInConfig);
}
}
// Additional CSS text area
{
appearanceTabWidgetLayout->addWidget(separator());
{
QLabel* additionalCssLabel = new QLabel(tr("Additional CSS:"), this);
appearanceTabWidgetLayout->addWidget(additionalCssLabel);
}
additionalCssTextArea = new QPlainTextEdit(this);
additionalCssTextArea->setObjectName("liquidAppConfigAdditionalCSSTextArea");
additionalCssTextArea->setPlaceholderText(tr("/* put your custom CSS here */"));
if (isEditingExistingBool) {
additionalCssTextArea->setPlainText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_ADDITIONAL_CSS).toString());
}
appearanceTabWidgetLayout->addWidget(additionalCssTextArea);
}
}
////////////////////
// JavaScript tab //
////////////////////
{
QWidget* jsTabWidget = new QWidget(this);
QVBoxLayout* jsTabWidgetLayout = new QVBoxLayout();
jsTabWidget->setLayout(jsTabWidgetLayout);
tabWidget->addTab(jsTabWidget, tr("JavaScript"));
// Enable JavaScript checkbox
{
enableJavaScriptCheckBox = new QCheckBox(tr("Enable JavaScript"), this);
enableJavaScriptCheckBox->setCursor(Qt::PointingHandCursor);
if (isEditingExistingBool) {
bool isChecked = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_ENABLE_JS).toBool();
enableJavaScriptCheckBox->setChecked(isChecked);
} else {
// Checked by default (when creating new Liquid app)
enableJavaScriptCheckBox->setChecked(true);
}
jsTabWidgetLayout->addWidget(enableJavaScriptCheckBox);
}
// Additonal JavaScript code text area
{
jsTabWidgetLayout->addWidget(separator());
additionalJsLabel = new QLabel(tr("Additonal JavaScript code:"), this);
additionalJsTextArea = new QPlainTextEdit(this);
additionalJsTextArea->setObjectName("liquidAppConfigAdditionalJSTextArea");
additionalJsTextArea->setPlaceholderText(tr("// This code will run even when JS is disabled"));
if (isEditingExistingBool) {
additionalJsTextArea->setPlainText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_ADDITIONAL_JS).toString());
}
jsTabWidgetLayout->addWidget(additionalJsLabel);
jsTabWidgetLayout->addWidget(additionalJsTextArea);
}
}
/////////////////
// Cookies tab //
/////////////////
{
QWidget* cookiesTabWidget = new QWidget(this);
QVBoxLayout* cookiesTabWidgetLayout = new QVBoxLayout();
cookiesTabWidget->setLayout(cookiesTabWidgetLayout);
tabWidget->addTab(cookiesTabWidget, tr("Cookies"));
// Allow cookies & allow third-party cookies checkboxes
{
// Allow cookies checkbox
{
allowCookiesCheckBox = new QCheckBox(tr("Allow cookies"), this);
allowCookiesCheckBox->setCursor(Qt::PointingHandCursor);
if (isEditingExistingBool) {
bool isChecked = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_ALLOW_COOKIES).toBool();
allowCookiesCheckBox->setChecked(isChecked);
} else {
// Checked by default (when creating new Liquid App)
allowCookiesCheckBox->setChecked(true);
}
cookiesTabWidgetLayout->addWidget(allowCookiesCheckBox);
}
// Allow third-party cookies checkbox
{
QHBoxLayout* allowThirdPartyCookiesLayout = new QHBoxLayout();
allowThirdPartyCookiesLayout->setContentsMargins(LQD_UI_MARGIN, 0, 0, 0);
allowThirdPartyCookiesCheckBox = new QCheckBox(tr("Allow third-party cookies"), this);
allowThirdPartyCookiesCheckBox->setCursor(Qt::PointingHandCursor);
if (isEditingExistingBool) {
bool isChecked = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_ALLOW_3RD_PARTY_COOKIES).toBool();
allowThirdPartyCookiesCheckBox->setChecked(isChecked);
}
allowThirdPartyCookiesLayout->addWidget(allowThirdPartyCookiesCheckBox);
connect(allowCookiesCheckBox, &QCheckBox::toggled, [&](const bool isOn){
if (!isOn) {
allowThirdPartyCookiesCheckBox->setChecked(false);
}
});
connect(allowThirdPartyCookiesCheckBox, &QCheckBox::toggled, [&](const bool isOn){
if (isOn) {
allowCookiesCheckBox->setChecked(isOn);
}
});
cookiesTabWidgetLayout->addLayout(allowThirdPartyCookiesLayout);
}
}
// Cookies list view
{
cookiesTabWidgetLayout->addWidget(separator());
// Cookies list label
{
QLabel* cookiesListLabel = new QLabel(tr("Cookie jar:"), this);
cookiesTabWidgetLayout->addWidget(cookiesListLabel);
}
// Cookies list
{
cookiesTableView = new QTableView(this);
cookiesModel = new QStandardItemModel(this);
cookiesModel->setHorizontalHeaderItem(0, new QStandardItem(tr("Name")));
cookiesModel->setHorizontalHeaderItem(1, new QStandardItem(tr("Value")));
cookiesModel->setHorizontalHeaderItem(2, new QStandardItem(tr("Domain")));
cookiesModel->setHorizontalHeaderItem(3, new QStandardItem(tr("Path")));
cookiesModel->setHorizontalHeaderItem(4, new QStandardItem(tr("Expires")));
cookiesModel->setHorizontalHeaderItem(5, new QStandardItem(tr("HttpOnly")));
cookiesModel->setHorizontalHeaderItem(6, new QStandardItem(tr("Secure")));
// Assign model
cookiesTableView->setModel(cookiesModel);
// Fill model items
if (isEditingExistingBool) {
existingLiquidAppConfig->beginGroup(LQD_CFG_GROUP_NAME_COOKIES);
int i = 0;
foreach(QString cookieId, existingLiquidAppConfig->allKeys()) {
const QByteArray rawCookie = existingLiquidAppConfig->value(cookieId).toByteArray();
QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(rawCookie);
if (cookies.size() > 0) {
QNetworkCookie cookie = cookies[0];
cookiesModel->appendRow(new QStandardItem());
cookiesModel->setItem(i, 0, new QStandardItem(QString(cookie.name())));
cookiesModel->setItem(i, 1, new QStandardItem(QString(cookie.value())));
cookiesModel->setItem(i, 2, new QStandardItem(cookie.domain()));
cookiesModel->setItem(i, 3, new QStandardItem(cookie.path()));
cookiesModel->setItem(i, 4, new QStandardItem(cookie.expirationDate().toString()));
cookiesModel->setItem(i, 5, new QStandardItem(cookie.isHttpOnly() ? "true" : "false"));
cookiesModel->setItem(i, 6, new QStandardItem(cookie.isSecure() ? "true" : "false"));
i++;
}
}
existingLiquidAppConfig->endGroup();
}
}
cookiesTabWidgetLayout->addWidget(cookiesTableView);
}
}
/////////////////
// Network tab //
/////////////////
{
QWidget* networkTabWidget = new QWidget(this);
QVBoxLayout* networkTabWidgetLayout = new QVBoxLayout();
networkTabWidget->setLayout(networkTabWidgetLayout);
tabWidget->addTab(networkTabWidget, tr("Network"));
// Proxy
{
// Option 1: Use global system proxy settings (default)
{
proxyModeSystemRadioButton = new QRadioButton(tr("Use global system settings"), this);
proxyModeSystemRadioButton->setCursor(Qt::PointingHandCursor);
networkTabWidgetLayout->addWidget(proxyModeSystemRadioButton);
}
// Option 2: Use direct internet connection
{
proxyModeDirectRadioButton = new QRadioButton(tr("Direct internet connection"), this);
proxyModeDirectRadioButton->setCursor(Qt::PointingHandCursor);
networkTabWidgetLayout->addWidget(proxyModeDirectRadioButton);
}
// Option 3: Use custom proxy configuration
{
QHBoxLayout* customProxyModeLayout = new QHBoxLayout();
// Radio box
proxyModeCustomRadioButton = new QRadioButton(tr("Custom proxy configuration:"), this);
proxyModeCustomRadioButton->setCursor(Qt::PointingHandCursor);
customProxyModeLayout->addWidget(proxyModeCustomRadioButton, 0, Qt::AlignTop);
// Custom proxy configuration
{
QVBoxLayout* proxyConfigLayout = new QVBoxLayout();
// Row 1 (type, host, port)
{
QHBoxLayout* proxyTypeHostPortLayout = new QHBoxLayout();
// Proxy type
{
useSocksSelectBox = new QComboBox(this);
useSocksSelectBox->addItem(tr("HTTP"), false);
useSocksSelectBox->addItem(tr("SOCKS"), true);
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USE_SOCKS)) {
const bool useSocks = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_USE_SOCKS, false).toBool();
if (useSocks) {
useSocksSelectBox->setCurrentIndex(1);
}
}
proxyTypeHostPortLayout->addWidget(useSocksSelectBox);
}
// Proxy host
{
proxyHostInput = new QLineEdit(this);
proxyHostInput->setPlaceholderText(LQD_DEFAULT_PROXY_HOST);
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_HOST)) {
proxyHostInput->setText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_HOST).toString());
}
proxyTypeHostPortLayout->addWidget(proxyHostInput);
}
// Proxy port
{
proxyPortInput = new QSpinBox(this);
proxyPortInput->setRange(0, 65535);
proxyPortInput->setValue(LQD_DEFAULT_PROXY_PORT);
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_PORT)) {
proxyPortInput->setValue(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_PORT).toInt());
}
proxyTypeHostPortLayout->addWidget(proxyPortInput);
}
proxyConfigLayout->addLayout(proxyTypeHostPortLayout);
}
// Row 2 (use authentication checkbox, username, password)
{
QHBoxLayout* proxyCredentialsLayout = new QHBoxLayout();
// Use credentials
{
proxyUseAuthCheckBox = new QCheckBox(tr("Authenticate with credentials:"), this);
proxyCredentialsLayout->addWidget(proxyUseAuthCheckBox);
}
// Username
{
proxyUsernameInput = new QLineEdit(this);
proxyUsernameInput->setPlaceholderText(tr("Username"));
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USER_NAME)) {
proxyUsernameInput->setText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_USER_NAME).toString());
}
proxyCredentialsLayout->addWidget(proxyUsernameInput);
}
// Password
{
proxyPasswordInput = new QLineEdit(this);
proxyPasswordInput->setPlaceholderText(tr("Password"));
proxyPasswordInput->setEchoMode(QLineEdit::Password);
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USER_NAME)) {
proxyPasswordInput->setText(existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_USER_NAME).toString());
}
proxyCredentialsLayout->addWidget(proxyPasswordInput);
}
proxyConfigLayout->addLayout(proxyCredentialsLayout);
}
if (isEditingExistingBool && existingLiquidAppConfig->contains(LQD_CFG_KEY_NAME_USE_PROXY)) {
const bool proxyEnabled = existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_USE_PROXY, false).toBool();
if (proxyEnabled) {
proxyModeCustomRadioButton->setChecked(true);
} else {
proxyModeDirectRadioButton->setChecked(true);
}
} else {
proxyModeSystemRadioButton->setChecked(true);
}
if (isEditingExistingBool && existingLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_USE_AUTH, false).toBool()) {
proxyUseAuthCheckBox->setChecked(true);
}
customProxyModeLayout->addLayout(proxyConfigLayout);
}
connect(useSocksSelectBox, &QComboBox::currentTextChanged, [&](){
proxyModeCustomRadioButton->setChecked(true);
});
connect(proxyHostInput, &QLineEdit::textChanged, [&](const QString value){
if (value.size() > 0) {
proxyModeCustomRadioButton->setChecked(true);
} else {
proxyModeSystemRadioButton->setChecked(true);
}
});
connect(proxyPortInput, QOverload<int>::of(&QSpinBox::valueChanged), [&](){
proxyModeCustomRadioButton->setChecked(true);
});
connect(proxyUseAuthCheckBox, &QCheckBox::stateChanged, [&](){
proxyModeCustomRadioButton->setChecked(true);
});
connect(proxyUsernameInput, &QLineEdit::textChanged, [&](const QString value){
proxyModeCustomRadioButton->setChecked(true);
proxyUseAuthCheckBox->setChecked(value.size() > 0);
});
connect(proxyPasswordInput, &QLineEdit::textChanged, [&](const QString value){
proxyModeCustomRadioButton->setChecked(true);
proxyUseAuthCheckBox->setChecked(value.size() > 0);
});
networkTabWidgetLayout->addLayout(customProxyModeLayout);
}
}
// Spacer
{
QWidget* spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
networkTabWidgetLayout->addWidget(spacer);
}
}
mainLayout->addWidget(advancedWidget);
setLayout(mainLayout);
if (isEditingExistingBool) {
// Force advanced section to be visible in edit mode
advancedButton->toggle();
} else {
advancedWidget->hide();
}
// Reveal and bring to front
{
show();
raise();
activateWindow();
}
// Connect keyboard shortcuts
bindShortcuts();
}
LiquidAppConfigDialog::~LiquidAppConfigDialog(void)
{
}
void LiquidAppConfigDialog::save()
{
bool isFormValid = nameInput->text().size() > 0 && addressInput->text().size() > 0;
if (!isFormValid) {
return;
}
QString appName = nameInput->text();
// Replace directory separators (slashes) with underscores
// to ensure no sub-directories would get created
appName = appName.replace(QDir::separator(), "_");
// Check if given Liquid App name is already in use
if (!isEditingExistingBool && Liquid::getLiquidAppsList().contains(appName)) {
return;
}
QSettings* tempLiquidAppConfig = new QSettings(QSettings::IniFormat,
QSettings::UserScope,
QString(PROG_NAME) + QDir::separator() + LQD_APPS_DIR_NAME,
appName,
Q_NULLPTR);
// URL
{
QUrl url(QUrl::fromUserInput(addressInput->text()));
// TODO: if was given only hostname and prepending http:// didn't help, prepend https://
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_URL, url.toString());
}
// Enable JS
{
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ENABLE_JS, enableJavaScriptCheckBox->isChecked());
}
// Allow cookies
{
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ALLOW_COOKIES, allowCookiesCheckBox->isChecked());
}
// Allow third-party cookies
{
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ALLOW_3RD_PARTY_COOKIES, allowThirdPartyCookiesCheckBox->isChecked());
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
// Hide scrollbars
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_HIDE_SCROLLBARS) && !hideScrollBarsCheckBox->isChecked()) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_HIDE_SCROLLBARS);
} else {
if (hideScrollBarsCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_HIDE_SCROLLBARS, true);
}
}
} else {
if (hideScrollBarsCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_HIDE_SCROLLBARS, true);
}
}
}
#endif
// Remove window frame
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_REMOVE_WINDOW_FRAME) && !removeWindowFrameCheckBox->isChecked()) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_REMOVE_WINDOW_FRAME);
} else {
if (removeWindowFrameCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_REMOVE_WINDOW_FRAME, true);
}
}
} else {
if (removeWindowFrameCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_REMOVE_WINDOW_FRAME, true);
}
}
}
// Custom window title
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_TITLE) && titleInput->text().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_TITLE);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_TITLE).toString().size() > 0
|| titleInput->text().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_TITLE, titleInput->text());
}
}
} else {
if (titleInput->text().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_TITLE, titleInput->text());
}
}
}
// Custom CSS
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_ADDITIONAL_CSS) && additionalCssTextArea->toPlainText().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_ADDITIONAL_CSS);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_ADDITIONAL_CSS).toString().size() > 0
|| additionalCssTextArea->toPlainText().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ADDITIONAL_CSS, additionalCssTextArea->toPlainText());
}
}
} else {
if (additionalCssTextArea->toPlainText().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ADDITIONAL_CSS, additionalCssTextArea->toPlainText());
}
}
}
// Custom JS
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_ADDITIONAL_JS) && additionalJsTextArea->toPlainText().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_ADDITIONAL_JS);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_ADDITIONAL_JS).toString().size() > 0
|| additionalJsTextArea->toPlainText().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ADDITIONAL_JS, additionalJsTextArea->toPlainText());
}
}
} else {
if (additionalJsTextArea->toPlainText().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ADDITIONAL_JS, additionalJsTextArea->toPlainText());
}
}
}
// Custom user-agent
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_USER_AGENT) && userAgentInput->text().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_USER_AGENT);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_USER_AGENT).toString().size() > 0
|| userAgentInput->text().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_USER_AGENT, userAgentInput->text());
}
}
} else {
if (userAgentInput->text().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_USER_AGENT, userAgentInput->text());
}
}
}
// Notes
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_NOTES) && notesTextArea->toPlainText().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_NOTES);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_NOTES).toString().size() > 0
|| notesTextArea->toPlainText().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_NOTES, notesTextArea->toPlainText());
}
}
} else {
if (notesTextArea->toPlainText().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_NOTES, notesTextArea->toPlainText());
}
}
}
// Create desktop icon
{
// TODO: make it possible to remove and (re-)create desktop icons for existing Liquid Apps
if (!isEditingExistingBool) {
if (createIconCheckBox->isChecked()) {
QUrl url(QUrl::fromUserInput(addressInput->text()));
Liquid::createDesktopFile(appName, url.toString());
}
}
}
// Custom background color
{
// Use custom background checkbox
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_USE_CUSTOM_BG) && !useCustomBackgroundCheckBox->isChecked()) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_USE_CUSTOM_BG);
} else {
if (useCustomBackgroundCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_USE_CUSTOM_BG, true);
}
}
} else {
if (useCustomBackgroundCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_USE_CUSTOM_BG, true);
}
}
}
// Custom background color
{
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_CUSTOM_BG_COLOR, backgroundColor->name(QColor::HexArgb));
}
}
// Additional domains
{
if (isEditingExistingBool && tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_ADDITIONAL_DOMAINS) && additionalDomainsModel->rowCount() == 1) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_ADDITIONAL_DOMAINS);
} else {
QString additionalDomains;
for (int i = 0, ilen = additionalDomainsModel->rowCount() - 1; i < ilen; i++) {
if (i > 0) {
additionalDomains += " ";
}
additionalDomains += additionalDomainsModel->data(additionalDomainsModel->index(i, 0)).toString();
}
if (additionalDomains.size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_ADDITIONAL_DOMAINS, additionalDomains);
}
}
}
// Proxy
{
// Proxy mode
{
if (proxyModeSystemRadioButton->isChecked()) {
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_USE_PROXY)) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_USE_PROXY);
}
}
} else if (proxyModeDirectRadioButton->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_USE_PROXY, false);
} else if (proxyModeCustomRadioButton->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_USE_PROXY, true);
}
}
// Proxy type
{
if (useSocksSelectBox->currentIndex() == 0) {
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USE_SOCKS)) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_PROXY_USE_SOCKS);
}
}
} else {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USE_SOCKS, true);
}
}
// Proxy host
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_HOST) && proxyHostInput->text().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_PROXY_HOST);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_HOST).toString().size() > 0
|| proxyHostInput->text().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_HOST, proxyHostInput->text());
}
}
} else {
if (proxyHostInput->text().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_HOST, proxyHostInput->text());
}
}
}
// Proxy port number
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_PORT) && proxyPortInput->value() == LQD_DEFAULT_PROXY_PORT) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_PROXY_PORT);
} else {
if (proxyPortInput->value() != LQD_DEFAULT_PROXY_PORT) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_PORT, proxyPortInput->value());
}
}
} else {
if (proxyPortInput->value() != LQD_DEFAULT_PROXY_PORT) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_PORT, proxyPortInput->value());
}
}
}
// Proxy authentication
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USE_AUTH) && !proxyUseAuthCheckBox->isChecked()) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_PROXY_USE_AUTH);
} else {
if (proxyUseAuthCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USE_AUTH, true);
}
}
} else {
if (proxyUseAuthCheckBox->isChecked()) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USE_AUTH, true);
}
}
}
// Proxy username
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USER_NAME) && proxyUsernameInput->text().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_PROXY_USER_NAME);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_USER_NAME).toString().size() > 0
|| proxyUsernameInput->text().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USER_NAME, proxyUsernameInput->text());
}
}
} else {
if (proxyUsernameInput->text().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USER_NAME, proxyUsernameInput->text());
}
}
}
// Proxy password
{
if (isEditingExistingBool) {
if (tempLiquidAppConfig->contains(LQD_CFG_KEY_NAME_PROXY_USER_PASSWORD) && proxyPasswordInput->text().size() == 0) {
tempLiquidAppConfig->remove(LQD_CFG_KEY_NAME_PROXY_USER_PASSWORD);
} else {
if (tempLiquidAppConfig->value(LQD_CFG_KEY_NAME_PROXY_USER_PASSWORD).toString().size() > 0
|| proxyPasswordInput->text().size() > 0
) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USER_PASSWORD, proxyPasswordInput->text());
}
}
} else {
if (proxyPasswordInput->text().size() > 0) {
tempLiquidAppConfig->setValue(LQD_CFG_KEY_NAME_PROXY_USER_PASSWORD, proxyPasswordInput->text());
}
}
}
}
tempLiquidAppConfig->sync();
accept();
}
void LiquidAppConfigDialog::bindShortcuts(void)
{
// Connect keyboard shortcut that closes the dialog
quitAction = new QAction();
quitAction->setShortcut(QKeySequence(tr(LQD_KBD_SEQ_QUIT)));
addAction(quitAction);
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
}
bool LiquidAppConfigDialog::isPlanningToRun(void)
{
return !isEditingExistingBool && planningToRunCheckBox->isChecked();
}
QString LiquidAppConfigDialog::getName(void)
{
return nameInput->text();
}
QFrame* LiquidAppConfigDialog::separator(void)
{
QFrame* separatorFrame = new QFrame;
separatorFrame->setFrameShape(QFrame::HLine);
separatorFrame->setFrameShadow(QFrame::Sunken);
return separatorFrame;
}
void LiquidAppConfigDialog::setPlanningToRun(const bool state)
{
if (!isEditingExistingBool) {
isPlanningToRunBool = state;
if (planningToRunCheckBox != Q_NULLPTR) {
planningToRunCheckBox->setChecked(state);
}
}
}
| 40.30303 | 168 | 0.568484 | [
"model"
] |
91bbab9b703ffc316016572e45e62f97c409ac9a | 3,709 | cpp | C++ | gui/helpers/QQuickExtraAnchors.cpp | Romain-Donze/QQmlTricks | a5179d9e7d67e3195f186a0d8630586cb88b49ec | [
"Unlicense"
] | 3 | 2022-01-10T15:19:50.000Z | 2022-01-28T07:55:16.000Z | gui/helpers/QQuickExtraAnchors.cpp | Romain-Donze/QQmlTricks | a5179d9e7d67e3195f186a0d8630586cb88b49ec | [
"Unlicense"
] | null | null | null | gui/helpers/QQuickExtraAnchors.cpp | Romain-Donze/QQmlTricks | a5179d9e7d67e3195f186a0d8630586cb88b49ec | [
"Unlicense"
] | null | null | null |
#include "QQuickExtraAnchors.h"
#include <QQmlProperty>
QQuickExtraAnchors::QQuickExtraAnchors (QObject * parent)
: QObject (parent)
, m_topDock { Q_NULLPTR }
, m_leftDock { Q_NULLPTR }
, m_rightDock { Q_NULLPTR }
, m_bottomDock { Q_NULLPTR }
, m_verticalFill { Q_NULLPTR }
, m_horizontalFill { Q_NULLPTR }
, m_topLeftCorner { Q_NULLPTR }
, m_topRightCorner { Q_NULLPTR }
, m_bottomLeftCorner { Q_NULLPTR }
, m_bottomRightCorner { Q_NULLPTR }
, m_anchors { (parent ? QQmlProperty (parent, "anchors").read ().value<QObject *> () : Q_NULLPTR) }
{
connect (this, &QQuickExtraAnchors::verticalFillChanged, [&] (void) {
defineAnchorLine (m_verticalFill, TOP);
defineAnchorLine (m_verticalFill, BOTTOM);
});
connect (this, &QQuickExtraAnchors::horizontalFillChanged, [&] (void) {
defineAnchorLine (m_horizontalFill, LEFT);
defineAnchorLine (m_horizontalFill, RIGHT);
});
connect (this, &QQuickExtraAnchors::topLeftCornerChanged, [&] (void) {
defineAnchorLine (m_topLeftCorner, TOP);
defineAnchorLine (m_topLeftCorner, LEFT);
});
connect (this, &QQuickExtraAnchors::topRightCornerChanged, [&] (void) {
defineAnchorLine (m_topRightCorner, TOP);
defineAnchorLine (m_topRightCorner, RIGHT);
});
connect (this, &QQuickExtraAnchors::bottomLeftCornerChanged, [&] (void) {
defineAnchorLine (m_bottomLeftCorner, LEFT);
defineAnchorLine (m_bottomLeftCorner, BOTTOM);
});
connect (this, &QQuickExtraAnchors::bottomRightCornerChanged, [&] (void) {
defineAnchorLine (m_bottomRightCorner, RIGHT);
defineAnchorLine (m_bottomRightCorner, BOTTOM);
});
connect (this, &QQuickExtraAnchors::topDockChanged, [&] (void) {
defineAnchorLine (m_topDock, TOP);
defineAnchorLine (m_topDock, LEFT);
defineAnchorLine (m_topDock, RIGHT);
});
connect (this, &QQuickExtraAnchors::leftDockChanged, [&] (void) {
defineAnchorLine (m_leftDock, TOP);
defineAnchorLine (m_leftDock, LEFT);
defineAnchorLine (m_leftDock, BOTTOM);
});
connect (this, &QQuickExtraAnchors::rightDockChanged, [&] (void) {
defineAnchorLine (m_rightDock, TOP);
defineAnchorLine (m_rightDock, RIGHT);
defineAnchorLine (m_rightDock, BOTTOM);
});
connect (this, &QQuickExtraAnchors::bottomDockChanged, [&] (void) {
defineAnchorLine (m_bottomDock, LEFT);
defineAnchorLine (m_bottomDock, RIGHT);
defineAnchorLine (m_bottomDock, BOTTOM);
});
}
QQuickExtraAnchors * QQuickExtraAnchors::qmlAttachedProperties (QObject * object) {
return new QQuickExtraAnchors { object };
}
void QQuickExtraAnchors::defineAnchorLine (QQuickItem * otherItem, const Sides side) {
static const QVariant UNDEFINED { };
if (m_anchors) {
const QString lineName {
[&] (void) -> QString {
switch (side) {
case TOP: return QStringLiteral ("top");
case LEFT: return QStringLiteral ("left");
case RIGHT: return QStringLiteral ("right");
case BOTTOM: return QStringLiteral ("bottom");
}
return "";
} ()
};
if (!lineName.isEmpty ()) {
QQmlProperty prop { m_anchors, lineName };
if (otherItem != Q_NULLPTR) {
QQmlProperty tmp { otherItem, lineName };
prop.write (tmp.read ());
}
else {
prop.write (UNDEFINED);
}
}
}
}
| 38.635417 | 113 | 0.611486 | [
"object"
] |
91c324dfaa90802bb717a1ec6b77d3c989483ef6 | 12,059 | cc | C++ | test-cderiv.cc | gilteunchoi/clstm | e87843c9f32345d899768d801a92871c210a8054 | [
"Apache-2.0"
] | 848 | 2015-01-16T13:16:28.000Z | 2022-03-31T14:07:21.000Z | test-cderiv.cc | gilteunchoi/clstm | e87843c9f32345d899768d801a92871c210a8054 | [
"Apache-2.0"
] | 135 | 2015-01-21T10:17:13.000Z | 2020-01-04T18:07:24.000Z | test-cderiv.cc | gilteunchoi/clstm | e87843c9f32345d899768d801a92871c210a8054 | [
"Apache-2.0"
] | 250 | 2015-01-15T02:57:02.000Z | 2022-01-01T13:25:21.000Z | #include <assert.h>
#include <math.h>
#include <cmath>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "clstm.h"
#include "clstm_compute.h"
#include "extras.h"
#include "utils.h"
using std_string = std::string;
#define string std_string
using std::vector;
using std::shared_ptr;
using std::unique_ptr;
using std::to_string;
using std::make_pair;
using std::cout;
using std::stoi;
using namespace Eigen;
using namespace ocropus;
typedef vector<Params> ParamVec;
double sqr(double x) { return x * x; }
double randu() {
static int count = 1;
for (;;) {
double x = cos(count * 3.7);
count++;
if (fabs(x) > 0.1) return x;
}
}
void randseq(Sequence &a, int N, int n, int m) {
bool finit = getienv("finit", 0);
a.resize(N, n, m);
for (int t = 0; t < N; t++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (finit) {
a[t].v(i, j) = 10000 * t + 100 * i + j;
a[t].d(i, j) = 10000 * t + 100 * i + j + 0.5;
} else {
a[t].v(i, j) = randu();
a[t].d(i, j) = randu();
}
}
}
}
a.check();
}
void randparams(ParamVec &a, const vector<vector<int>> &specs) {
int N = specs.size();
a.resize(N);
for (int k = 0; k < N; k++) {
int n = specs[k][0];
int m = specs[k][1];
a[k].setZero(n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[k].v(i, j) = randu();
a[k].d(i, j) = randu();
}
}
}
}
double maxerr(Sequence &out, Sequence &target) {
assert(out.size() == target.size());
assert(out.rows() == target.rows());
assert(out.cols() == target.cols());
int N = out.size(), n = out.rows(), m = out.cols();
double maxerr = 0.0;
for (int t = 0; t < N; t++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
double delta = target[t].v(i, j) - out[t].v(i, j);
if (fabs(delta) > maxerr) maxerr = fabs(delta);
}
}
}
return maxerr;
}
double avgerr(Sequence &out, Sequence &target) {
assert(out.size() == target.size());
assert(out.rows() == target.rows());
assert(out.cols() == target.cols());
int N = out.size(), n = out.rows(), m = out.cols();
double total = 0.0;
int count = 0;
for (int t = 0; t < N; t++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
double delta = target[t].v(i, j) - out[t].v(i, j);
total += fabs(delta);
count++;
}
}
}
return total / count;
}
double mse(Sequence &out, Sequence &target) {
assert(out.size() == target.size());
assert(out.rows() == target.rows());
assert(out.cols() == target.cols());
int N = out.size(), n = out.rows(), m = out.cols();
double total = 0.0;
for (int t = 0; t < N; t++) {
out[t].zeroGrad();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
double delta = target[t].v(i, j) - out[t].v(i, j);
out[t].d(i, j) = delta;
total += sqr(delta);
}
}
}
return total;
}
struct Minimizer {
double value = INFINITY;
double param = 0;
void add(double value, double param = NAN) {
if (value >= this->value) return;
this->value = value;
this->param = param;
}
};
struct Maximizer {
double value = -INFINITY;
double param = 0;
void add(double value, double param = NAN) {
if (value <= this->value) return;
this->value = value;
this->param = param;
}
};
struct Testcase;
vector<Testcase *> testcases;
struct Testcase {
virtual ~Testcase() {}
Sequence inputs;
ParamVec ps;
Sequence outputs;
Sequence targets;
virtual string name() { return typeid(*this).name(); }
// Store random initial test values appropriate for
// the test case into inputs, ps, and targets
virtual void init() {
// reasonable defaults
randseq(inputs, 1, 7, 4);
randseq(targets, 1, 3, 4);
randparams(ps, {{3, 7}});
}
// Perform forward and backward steps using inputs,
// outputs, and ps.
virtual void forward() = 0;
virtual void backward() = 0;
};
void test_net(Testcase &tc) {
int verbose = getienv("verbose", 0);
print("testing", tc.name());
tc.init();
// make backups for computing derivatives
Sequence inputs = tc.inputs;
Sequence targets = tc.targets;
ParamVec ps = tc.ps;
Maximizer maxinerr;
int N = inputs.size();
int ninput = inputs.rows();
int bs = inputs.cols();
for (int t = 0; t < N; t++) {
for (int i = 0; i < ninput; i++) {
for (int b = 0; b < bs; b++) {
Minimizer minerr;
for (float h = 1e-6; h < 1.0; h *= 10) {
tc.inputs = inputs;
tc.outputs.like(targets);
tc.forward();
double out = mse(tc.outputs, targets);
tc.inputs.zeroGrad();
for (Params &p : tc.ps) p.zeroGrad();
tc.backward();
double a_deriv = tc.inputs[t].d(i, b);
tc.inputs[t].v(i, b) += h;
tc.forward();
double out1 = mse(tc.outputs, targets);
double num_deriv = (out1 - out) / h;
double error = fabs(1.0 - num_deriv / a_deriv / -2.0);
if (verbose > 1)
print(t, i, b, ":", error, h, "num:", num_deriv, "analytic:",
a_deriv, "out:", out1, out);
minerr.add(error, h);
}
if (verbose) print("deltas", t, i, b, minerr.value, minerr.param);
assert(minerr.value < 0.1);
maxinerr.add(minerr.value);
}
}
}
Maximizer maxparamerr;
for (int k = 0; k < ps.size(); k++) {
int n = ps[k].rows();
int m = ps[k].cols();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
Minimizer minerr;
for (float h = 1e-6; h < 1.0; h *= 10) {
tc.ps = ps;
tc.inputs = inputs;
tc.outputs.like(targets);
tc.forward();
double out = mse(tc.outputs, targets);
tc.inputs.zeroGrad();
for (Params &p : tc.ps) p.zeroGrad();
tc.backward();
double a_deriv = tc.ps[k].d(i, j);
tc.ps[k].v(i, j) += h;
tc.forward();
double out1 = mse(tc.outputs, targets);
double num_deriv = (out1 - out) / h;
double error = fabs(1.0 - num_deriv / a_deriv / -2.0);
if (verbose > 1)
print(k, i, j, ":", error, h, "/", num_deriv, a_deriv, out1, out);
minerr.add(error, h);
}
maxparamerr.add(minerr.value);
}
}
}
tc.inputs = inputs;
tc.ps = ps;
tc.targets = targets;
print("OK", maxinerr.value, maxparamerr.value);
}
struct TestFull1Sigmoid : Testcase {
virtual void init() {
randseq(inputs, 1, 7, 4);
randseq(targets, 1, 3, 4);
randparams(ps, {{3, 8}});
}
void forward() { forward_full1(outputs[0], ps[0], inputs[0], SIG); }
void backward() { backward_full1(outputs[0], ps[0], inputs[0], SIG); }
};
struct TestFull1Tanh : Testcase {
virtual void init() {
randseq(inputs, 1, 7, 4);
randseq(targets, 1, 3, 4);
randparams(ps, {{3, 8}});
}
void forward() { forward_full1(outputs[0], ps[0], inputs[0], TANH); }
void backward() { backward_full1(outputs[0], ps[0], inputs[0], TANH); }
};
struct TestFull1Logmag : Testcase {
virtual void init() {
randseq(inputs, 1, 7, 4);
randseq(targets, 1, 3, 4);
randparams(ps, {{3, 8}});
}
void forward() { forward_full1(outputs[0], ps[0], inputs[0], LOGMAG); }
void backward() { backward_full1(outputs[0], ps[0], inputs[0], LOGMAG); }
};
struct TestStack : Testcase {
virtual void init() {
randseq(inputs, 2, 7, 4);
randseq(targets, 1, 14, 4);
randparams(ps, {});
}
void forward() { forward_stack(outputs[0], inputs[0], inputs[1]); }
void backward() { backward_stack(outputs[0], inputs[0], inputs[1]); }
};
struct TestStackDelay : Testcase {
virtual void init() {
randseq(inputs, 2, 7, 4);
randseq(targets, 1, 14, 4);
randparams(ps, {});
}
void forward() { forward_stack_delay(outputs[0], inputs[0], inputs, 1); }
void backward() { backward_stack_delay(outputs[0], inputs[0], inputs, 1); }
};
#ifdef DEPRECATED
struct TestFullSigmoid : Testcase {
void forward() { forward_full<SigmoidNonlin>(outputs[0], ps[0], inputs[0]); }
void backward() {
backward_full<SigmoidNonlin>(outputs[0], ps[0], inputs[0]);
}
};
struct TestFullTanh : Testcase {
void forward() { forward_full<SigmoidNonlin>(outputs[0], ps[0], inputs[0]); }
void backward() {
backward_full<SigmoidNonlin>(outputs[0], ps[0], inputs[0]);
}
};
struct TestStack1Delay : Testcase {
virtual void init() {
randseq(inputs, 2, 7, 4);
randseq(targets, 1, 15, 4);
randparams(ps, {});
}
void forward() { forward_stack1(outputs[0], inputs[0], inputs, 1); }
void backward() { backward_stack1(outputs[0], inputs[0], inputs, 1); }
};
#endif
struct TestReverse : Testcase {
virtual void init() {
randseq(inputs, 5, 7, 4);
randseq(targets, 5, 7, 4);
randparams(ps, {});
}
void forward() { forward_reverse(outputs, inputs); }
void backward() { backward_reverse(outputs, inputs); }
};
struct TestBtswitch : Testcase {
virtual void init() {
randseq(inputs, 5, 7, 4);
randseq(targets, 4, 7, 5);
randparams(ps, {});
}
void forward() { forward_btswitch(outputs, inputs); }
void backward() { backward_btswitch(outputs, inputs); }
};
struct TestBatchstack : Testcase {
virtual void init() {
randseq(inputs, 5, 4, 11);
randseq(targets, 5, 12, 11);
randparams(ps, {});
}
void forward() { forward_batchstack(outputs, inputs, 1, 1); }
void backward() { backward_batchstack(outputs, inputs, 1, 1); }
};
struct TestStatemem : Testcase {
virtual void init() {
randseq(inputs, 4, 7, 4);
randseq(targets, 1, 7, 4);
randparams(ps, {});
}
void forward() {
forward_statemem(outputs[0], inputs[0], inputs[1], inputs, 2, inputs[3]);
}
void backward() {
backward_statemem(outputs[0], inputs[0], inputs[1], inputs, 2, inputs[3]);
}
};
struct TestNonlingate : Testcase {
virtual void init() {
randseq(inputs, 2, 7, 4);
randseq(targets, 1, 7, 4);
randparams(ps, {});
}
void forward() { forward_nonlingate(outputs[0], inputs[0], inputs[1], TANH); }
void backward() {
backward_nonlingate(outputs[0], inputs[0], inputs[1], TANH);
}
};
inline Eigen::array<ptrdiff_t, 1> indexes(int i) {
return Eigen::array<ptrdiff_t, 1>({i});
}
inline Eigen::array<ptrdiff_t, 2> indexes(int i, int j) {
return Eigen::array<ptrdiff_t, 2>({i, j});
}
#ifdef DEPRECATED
void test_full() {
print("comparing full and full1");
Sequence inputs;
ParamVec ps;
Sequence outputs;
randseq(inputs, 1, 7, 4);
randparams(ps, {{3, 8}});
randseq(outputs, 2, 3, 4);
Batch inputs1;
inputs1.resize(8, 4);
inputs1.v().slice(indexes(0, 0), indexes(1, 4)).setConstant(Float(1));
inputs1.v().slice(indexes(1, 0), indexes(7, 4)) = inputs[0].v();
forward_full1<SigmoidNonlin>(outputs[0], ps[0], inputs[0]);
forward_full<SigmoidNonlin>(outputs[1], ps[0], inputs1);
EigenTensor1 err = (outputs[0].v() - outputs[1].v()).abs().maximum();
assert(err(0) < 0.001);
print("OK", err(0));
backward_full1<SigmoidNonlin>(outputs[0], ps[0], inputs[0]);
backward_full<SigmoidNonlin>(outputs[1], ps[0], inputs1);
EigenTensor1 derr =
(inputs[0].d() - inputs1.d().slice(indexes(1, 0), indexes(7, 4)))
.abs()
.maximum();
// assert(derr(0) < 0.001);
print("OK", derr(0));
}
#endif
int main(int argc, char **argv) {
TRY {
test_net(*new TestBatchstack);
test_net(*new TestFull1Sigmoid);
test_net(*new TestFull1Tanh);
test_net(*new TestFull1Logmag);
test_net(*new TestStack);
test_net(*new TestStackDelay);
test_net(*new TestReverse);
test_net(*new TestBtswitch);
test_net(*new TestStatemem);
test_net(*new TestNonlingate);
#ifdef DEPRECATED
test_net(*new TestFullSigmoid);
test_net(*new TestFullTanh);
test_net(*new TestStack1Delay);
test_full();
#endif
}
CATCH(const char *message) { print("ERROR", message); }
}
| 27.914352 | 80 | 0.573679 | [
"vector"
] |
91cb206f2546eeec2df6653a96efbf2fdd61ebcd | 24,514 | cpp | C++ | Source/automap.cpp | sergi4ua/Give-Me-Sanctuary | e21888aff4d249762b6c90b77e440cca9a2fec47 | [
"Unlicense"
] | 1 | 2019-06-12T13:53:12.000Z | 2019-06-12T13:53:12.000Z | Source/automap.cpp | sergi4ua/Give-Me-Sanctuary | e21888aff4d249762b6c90b77e440cca9a2fec47 | [
"Unlicense"
] | 1 | 2019-06-12T18:23:36.000Z | 2019-06-12T18:23:36.000Z | Source/automap.cpp | sergi4ua/Give-Me-Sanctuary | e21888aff4d249762b6c90b77e440cca9a2fec47 | [
"Unlicense"
] | null | null | null | //HEADER_GOES_HERE
#include "../types.h"
#include <iostream>
#include <map>
#include <vector>
DEVILUTION_BEGIN_NAMESPACE
// BUGFIX: only the first 256 elements are ever read
WORD automaptype[512];
static int MapX;
static int MapY;
BOOL automapflag; // idb
char AmShiftTab[32]; // [31]?
unsigned char automapview[DMAXX][DMAXY];
int AutoMapScale; // idb
int AutoMapXOfs; // weak
int AutoMapYOfs; // weak
int AutoMapPosBits; // weak
int AutoMapXPos; // weak
int AutoMapYPos; // weak
int AMPlayerX; // weak
int AMPlayerY; // weak
// color used to draw the player's arrow
#define COLOR_PLAYER (PAL8_ORANGE + 1)
// color for bright map lines (doors, stairs etc.)
#define COLOR_BRIGHT PAL8_YELLOW
// color for dim map lines/dots
#define COLOR_DIM (PAL16_YELLOW + 8)
#define MAPFLAG_TYPE 0x000F
// these are in the second byte
#define MAPFLAG_VERTDOOR 0x01
#define MAPFLAG_HORZDOOR 0x02
#define MAPFLAG_VERTARCH 0x04
#define MAPFLAG_HORZARCH 0x08
#define MAPFLAG_VERTGRATE 0x10
#define MAPFLAG_HORZGRATE 0x20
#define MAPFLAG_SQUARE 0x40
#define MAPFLAG_STAIRS 0x80
using namespace std;
std::map<std::string, bool> BoolConfig;
std::map<std::string, int> IntConfig; //config variables
void __cdecl InitAutomapOnce()
{
automapflag = FALSE;
AutoMapScale = 50;
AutoMapPosBits = 32;
AutoMapXPos = 16;
AutoMapYPos = 8;
AMPlayerX = 4;
AMPlayerY = 2;
AMPlayerY = AutoMapPosBits >> 4;
}
// old ver
/*
void HighlightItemsNameOnMap()
{
class drawingQueue
{
public:
int ItemID;
int Row;
int Col;
int x;
int y;
int new_x = -1;
int new_y = -1;
int width;
int height;
int magicLevel;
std::string text;
drawingQueue(int x2, int y2, int width2, int height2, int Row2, int Col2, int ItemID2, int q2, std::string text2) { x = x2; y = y2; Row = Row2; Col = Col2; ItemID = ItemID2; width = width2; height = height2; magicLevel = q2; text = text2; }
};
char textOnGround[256];
int ScreenHeight = 480;
int Screen_TopEnd = 160;
int Screen_LeftBorder = 64;
int ScreenWidth = 640;
std::vector<drawingQueue> q;
//SDL_ShowMessageBox("null",0);
/*
if (numitems < 127)
{
ii = itemavail[0];
GetSuperItemSpace(x, y, itemavail[0]);
itemactive[numitems] = ii;
itemavail[0] = itemavail[-numitems + 126];
*//*
for (int i = 0; i < numitems; i++) {
//ItemStruct& item = ItemsOnGround[MapItemsFreeIndexes[i + 1]];
ItemStruct& item_local = item[itemactive[i]];
int row = item_local._ix - plr[myplr].WorldX;
int col = item_local._iy - plr[myplr].WorldY;
// items on ground name highlighting (Qndel)
if (item_local._itype == ITYPE_GOLD) {
sprintf(textOnGround, "%i gold", item_local._ivalue);
}
else {
sprintf(textOnGround, "%s", item_local._iIdentified ? item_local._iIName : item_local._iName);
}
int x2 = 32 * (row - col);// +(200 * ScrollInfo._sxoff / 100 >> 1) + AutoMapXOfs;
int y2 = 16 * (row + col);// +(200 * ScrollInfo._syoff / 100 >> 1) + AutoMapYOfs - 16;
int centerXOffset = GetTextWidth(textOnGround) / 2; // offset to attempt to center the name above the item
int x = x2;// -96 - centerXOffset;
int y = y2;
int x3 = x;// +95;
int y3 = y - 1;
//if( x > -Screen_LeftBorder * 2 && x + centerXOffset < ScreenWidth + Screen_LeftBorder && y > -8 && y < ScreenHeight ){
//if (x > -Screen_LeftBorder * 2 && x3 + centerXOffset < ScreenWidth + Screen_LeftBorder && y3 > 13 && y3 + 13 < ScreenHeight + Screen_TopEnd) {
if(true){
// add to drawing queue
//DrawLevelInfoText( x, y, textOnGround, By( item.MagicLevel, C_0_White, C_1_Blue, C_3_Gold, C_4_Orange) );
std::string t2(textOnGround);
q.push_back(drawingQueue(x, y, centerXOffset * 2, 13, item_local._ix, item_local._iy, itemactive[i], item_local._iMagical, t2));
}
}
const int borderX = 5;
bool highlightItem = false;
for (unsigned int i = 0; i < q.size(); ++i) {
if (q[i].new_x == -1 && q[i].new_y == -1) {
q[i].new_x = q[i].x; q[i].new_y = q[i].y;
}
std::map<int, bool> backtrace;
while (1) {
bool canShow = true;
for (unsigned int j = 0; j < i; ++j) {
if (abs(q[j].new_y - q[i].new_y) < q[i].height + 2) {
if (q[j].new_x >= q[i].new_x && q[j].new_x - q[i].new_x < q[i].width + borderX) {
canShow = false;
int newpos = q[j].new_x - q[i].width - borderX;
if (backtrace.find(newpos) == backtrace.end()) {
q[i].new_x = newpos;
backtrace[newpos] = true;
}
else {
newpos = q[j].new_x + q[j].width + borderX;
q[i].new_x = newpos;
backtrace[newpos] = true;
}
}
else if (q[j].new_x < q[i].new_x && q[i].new_x - q[j].new_x < q[j].width + borderX) {
canShow = false;
int newpos = q[j].new_x + q[j].width + borderX;;
if (backtrace.find(newpos) == backtrace.end()) {
q[i].new_x = newpos;
backtrace[newpos] = true;
}
else {
newpos = q[j].new_x - q[i].width - borderX;
q[i].new_x = newpos;
backtrace[newpos] = true;
}
}
}
}
if (canShow) { break; }
}
}
for (unsigned int i = 0; i < q.size(); ++i) {
drawingQueue t = q[i];
if (t.new_x == -1 && t.new_y == -1) {
t.new_x = t.x; t.new_y = t.y;
}
int x3 = t.new_x + 95;
int y3 = t.new_y - 1;
int bgcolor = 0;
if(true){
//if (t.new_x > -Screen_LeftBorder * 2 && x3 + t.width / 2 < ScreenWidth + Screen_LeftBorder && y3 > 13 && y3 + 13 < ScreenHeight + Screen_TopEnd) {
/*
int bgcolor = 0;
int highlightY = t.new_y - 175;
int highlightX = t.new_x + 30;
if (CursorX >= highlightX && CursorX <= highlightX + t.width + 1 && CursorY >= highlightY && CursorY <= highlightY + t.height) {
bgcolor = 134;
HighlightedItem.ItemID = t.ItemID;
HighlightedItem.Row = t.Row;
HighlightedItem.Col = t.Col;
highlightItem = true;
}
*/
/*
//DrawTransparentBackground(x3, y3, t.width + 1, t.height, 0, 0, bgcolor, bgcolor);
char color = COL_WHITE;
//DrawCustomText(t.new_x, t.new_y, 0, &t.text[0u], color);
int sx = t.new_x + 320 - t.width / 2;
int sy = t.new_y + 180;
int sx2 = t.new_x + 383 - t.width / 2;
int sy2 = t.new_y + 342;
if (sx < 0 || sx > 640 || sy < 0 || sy > 480) {
continue;
}
if (sx2 < 0 || sx2 > 640 || sy2 < 0 || sy2 > 480) {
continue;
}
DrawTransparentBackground(sx2,sy2, t.width + 1, t.height, 0, 0, bgcolor, bgcolor);
PrintGameStr(sx,sy,&t.text[0u], color);
//ADD_PlrStringXY(t.new_x, t.new_y, GetTextWidth(&t.text[0]), &t.text[0u], color);
}
}
/*
if (highlightItem == false) {
HighlightedItem.ItemID = -1;
}
*/
/*
#ifdef PREVHIGHLIGHT
char textOnGround[256];
for (int i = 0; i < CountItemsOnMap; i++) {
Item& item = ItemsOnGround[MapItemsFreeIndexes[i + 1]];
int row = item.MapRow - PlayerRowPos;
int col = item.MapCol - PlayerColPos;
// items on ground name highlighting (Qndel)
if (item.ItemCode == IC_11_GOLD) {
sprintf(textOnGround, "%i gold", item.QualityLevel);
}
else {
sprintf(textOnGround, "%s", item.Identified ? item.FullMagicalItemName : item.Name);
}
int x2 = 32 * (row - col) + (200 * (PlayerMovedX + PlayerShiftY) / 100 >> 1) + Xofs;
int y2 = 16 * (row + col) + (200 * (PlayerMovedY + PlayerShiftX) / 100 >> 1) + Yofs - 16;
int centerXOffset = GetTextWidth(textOnGround) / 2; // offset to attempt to center the name above the item
// don't think that red square is needs (there is item outline and blue square already)
//AutomapDrawOneItem( x2, y2 + item.CelWidth / 8, 155 ); // drawing a red square on the item
int x = x2 - 64 - centerXOffset;
int y = y2 - 156;
if (x > -Screen_LeftBorder * 2 && x + centerXOffset < ScreenWidth + Screen_LeftBorder && y > -8 && y < ScreenHeight) {
DrawLevelInfoText(x, y, textOnGround, By(item.MagicLevel, C_0_White, C_1_Blue, C_3_Gold, C_4_Orange));
}
}
#endif
}
*/
void __cdecl InitAutomap()
{
unsigned char b1, b2;
unsigned int dwTiles;
int x, y;
unsigned char *pAFile, *pTmp;
int i, j;
int d;
j = 50;
for (i = 0; i < 31; i++) {
d = (j << 6) / 100;
AmShiftTab[i] = 2 * (320 / d) + 1;
if (320 % d)
AmShiftTab[i]++;
if (320 % d >= (j << 5) / 100)
AmShiftTab[i]++;
j += 5;
}
memset(automaptype, 0, sizeof(automaptype));
switch (leveltype) {
case DTYPE_CATHEDRAL:
pAFile = LoadFileInMem("Levels\\L1Data\\L1.AMP", (int *)&dwTiles);
dwTiles >>= 1;
break;
case DTYPE_CATACOMBS:
pAFile = LoadFileInMem("Levels\\L2Data\\L2.AMP", (int *)&dwTiles);
dwTiles >>= 1;
break;
case DTYPE_CAVES:
pAFile = LoadFileInMem("Levels\\L3Data\\L3.AMP", (int *)&dwTiles);
dwTiles >>= 1;
break;
case DTYPE_HELL:
pAFile = LoadFileInMem("Levels\\L4Data\\L4.AMP", (int *)&dwTiles);
dwTiles >>= 1;
break;
default:
return;
}
pTmp = pAFile;
for (i = 1; i <= dwTiles; i++) {
b1 = *pTmp++;
b2 = *pTmp++;
automaptype[i] = b1 + (b2 << 8);
}
mem_free_dbg(pAFile);
memset(automapview, 0, sizeof(automapview));
for (y = 0; y < MAXDUNY; y++) {
for (x = 0; x < MAXDUNX; x++)
dFlags[x][y] &= ~DFLAG_EXPLORED;
}
}
void __cdecl StartAutomap()
{
AutoMapXOfs = 0;
AutoMapYOfs = 0;
automapflag = TRUE;
}
void __cdecl AutomapUp()
{
--AutoMapXOfs;
--AutoMapYOfs;
}
void __cdecl AutomapDown()
{
++AutoMapXOfs;
++AutoMapYOfs;
}
void __cdecl AutomapLeft()
{
--AutoMapXOfs;
++AutoMapYOfs;
}
void __cdecl AutomapRight()
{
++AutoMapXOfs;
--AutoMapYOfs;
}
void __cdecl AutomapZoomIn()
{
if (AutoMapScale < 200) {
AutoMapScale += 5;
AutoMapPosBits = (AutoMapScale << 6) / 100;
AutoMapXPos = AutoMapPosBits >> 1;
AutoMapYPos = AutoMapXPos >> 1;
AMPlayerX = AutoMapYPos >> 1;
AMPlayerY = AMPlayerX >> 1;
}
}
void __cdecl AutomapZoomOut()
{
if (AutoMapScale > 50) {
AutoMapScale -= 5;
AutoMapPosBits = (AutoMapScale << 6) / 100;
AutoMapXPos = AutoMapPosBits >> 1;
AutoMapYPos = AutoMapXPos >> 1;
AMPlayerX = AutoMapYPos >> 1;
AMPlayerY = AMPlayerX >> 1;
}
}
void __cdecl DrawAutomap()
{
int cells;
int sx, sy;
int i, j;
int mapx, mapy;
if (leveltype == DTYPE_TOWN) {
DrawAutomapGame();
return;
}
gpBufEnd = (unsigned char *)&gpBuffer[(352 + 160) * 768];
MapX = (ViewX - 16) >> 1;
while (MapX + AutoMapXOfs < 0)
AutoMapXOfs++;
while (MapX + AutoMapXOfs >= DMAXX)
AutoMapXOfs--;
MapX += AutoMapXOfs;
MapY = (ViewY - 16) >> 1;
while (MapY + AutoMapYOfs < 0)
AutoMapYOfs++;
while (MapY + AutoMapYOfs >= DMAXY)
AutoMapYOfs--;
MapY += AutoMapYOfs;
cells = AmShiftTab[(AutoMapScale - 50) / 5];
if (ScrollInfo._sxoff + ScrollInfo._syoff)
cells++;
mapx = MapX - cells;
mapy = MapY - 1;
if (cells & 1) {
sx = 384 - AutoMapPosBits * ((cells - 1) >> 1);
sy = 336 - AutoMapXPos * ((cells + 1) >> 1);
} else {
sx = 384 - AutoMapPosBits * (cells >> 1) + AutoMapXPos;
sy = 336 - AutoMapXPos * (cells >> 1) - AutoMapYPos;
}
if (ViewX & 1) {
sx -= AutoMapYPos;
sy -= AMPlayerX;
}
if (ViewY & 1) {
sx += AutoMapYPos;
sy -= AMPlayerX;
}
sx += AutoMapScale * ScrollInfo._sxoff / 100 >> 1;
sy += AutoMapScale * ScrollInfo._syoff / 100 >> 1;
if (invflag || sbookflag) {
sx -= 160;
}
if (chrflag || questlog) {
sx += 160;
}
for (i = 0; i <= cells + 1; i++) {
int x = sx;
int y;
for (j = 0; j < cells; j++) {
WORD maptype = GetAutomapType(mapx + j, mapy - j, TRUE);
if (maptype)
DrawAutomapType(x, sy, maptype);
x += AutoMapPosBits;
}
mapy++;
x = sx - AutoMapXPos;
y = sy + AutoMapYPos;
for (j = 0; j <= cells; j++) {
WORD maptype = GetAutomapType(mapx + j, mapy - j, TRUE);
if (maptype)
DrawAutomapType(x, y, maptype);
x += AutoMapPosBits;
}
mapx++;
sy += AutoMapXPos;
}
DrawAutomapPlr();
DrawAutomapGame();
}
// 4B8968: using guessed type int sbookflag;
// 69BD04: using guessed type int questlog;
// 69CF0C: using guessed type int gpBufEnd;
void __fastcall DrawAutomapType(int sx, int sy, WORD automap_type)
{
BOOL do_vert;
BOOL do_horz;
BOOL do_cave_horz;
BOOL do_cave_vert;
int x1, y1, x2, y2;
BYTE flags = automap_type >> 8;
if (flags & MAPFLAG_SQUARE) {
ENG_set_pixel(sx, sy, COLOR_DIM);
ENG_set_pixel(sx - AMPlayerX, sy - AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx - AMPlayerX, sy + AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx + AMPlayerX, sy - AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx + AMPlayerX, sy + AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx - AutoMapYPos, sy, COLOR_DIM);
ENG_set_pixel(sx + AutoMapYPos, sy, COLOR_DIM);
ENG_set_pixel(sx, sy - AMPlayerX, COLOR_DIM);
ENG_set_pixel(sx, sy + AMPlayerX, COLOR_DIM);
ENG_set_pixel(sx + AMPlayerX - AutoMapXPos, sy + AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx - AMPlayerX + AutoMapXPos, sy + AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx - AutoMapYPos, sy + AMPlayerX, COLOR_DIM);
ENG_set_pixel(sx + AutoMapYPos, sy + AMPlayerX, COLOR_DIM);
ENG_set_pixel(sx - AMPlayerX, sy + AutoMapYPos - AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx + AMPlayerX, sy + AutoMapYPos - AMPlayerY, COLOR_DIM);
ENG_set_pixel(sx, sy + AutoMapYPos, COLOR_DIM);
}
if (flags & MAPFLAG_STAIRS) {
DrawLine(sx - AMPlayerX, sy - AMPlayerX - AMPlayerY, sx + AMPlayerX + AutoMapYPos, sy + AMPlayerY, COLOR_BRIGHT);
DrawLine(sx - AutoMapYPos, sy - AMPlayerX, sx + AutoMapYPos, sy + AMPlayerX, COLOR_BRIGHT);
DrawLine(sx - AutoMapYPos - AMPlayerX, sy - AMPlayerY, sx + AMPlayerX, sy + AMPlayerX + AMPlayerY, COLOR_BRIGHT);
DrawLine(sx - AutoMapXPos, sy, sx, sy + AutoMapYPos, COLOR_BRIGHT);
}
do_vert = FALSE;
do_horz = FALSE;
do_cave_horz = FALSE;
do_cave_vert = FALSE;
switch (automap_type & MAPFLAG_TYPE) {
case 1: // stand-alone column or other unpassable object
x1 = sx - AutoMapYPos;
y1 = sy - AutoMapYPos;
x2 = x1 + AutoMapXPos;
y2 = sy - AMPlayerX;
DrawLine(sx, y1, x1, y2, COLOR_DIM);
DrawLine(sx, y1, x2, y2, COLOR_DIM);
DrawLine(sx, sy, x1, y2, COLOR_DIM);
DrawLine(sx, sy, x2, y2, COLOR_DIM);
return;
case 2:
case 5:
do_vert = TRUE;
break;
case 4:
do_vert = TRUE;
do_horz = TRUE;
break;
case 3:
case 6:
do_horz = TRUE;
break;
case 8:
do_vert = TRUE;
do_cave_horz = TRUE;
break;
case 9:
do_horz = TRUE;
do_cave_vert = TRUE;
break;
case 10:
do_cave_horz = TRUE;
break;
case 11:
do_cave_vert = TRUE;
break;
case 12:
do_cave_horz = TRUE;
do_cave_vert = TRUE;
break;
}
if (do_vert) { // right-facing obstacle
if (flags & MAPFLAG_VERTDOOR) { // two wall segments with a door in the middle
x1 = sx - AutoMapXPos;
x2 = sx - AutoMapYPos;
y1 = sy - AutoMapYPos;
y2 = sy - AMPlayerX;
DrawLine(sx, y1, sx - AMPlayerX, y1 + AMPlayerY, COLOR_DIM);
DrawLine(x1, sy, x1 + AMPlayerX, sy - AMPlayerY, COLOR_DIM);
DrawLine(x2, y1, x1, y2, COLOR_BRIGHT);
DrawLine(x2, y1, sx, y2, COLOR_BRIGHT);
DrawLine(x2, sy, x1, y2, COLOR_BRIGHT);
DrawLine(x2, sy, sx, y2, COLOR_BRIGHT);
}
if (flags & MAPFLAG_VERTGRATE) { // right-facing half-wall
DrawLine(sx - AutoMapYPos, sy - AMPlayerX, sx - AutoMapXPos, sy, COLOR_DIM);
flags |= MAPFLAG_VERTARCH;
}
if (flags & MAPFLAG_VERTARCH) { // window or passable column
x1 = sx - AutoMapYPos;
y1 = sy - AutoMapYPos;
x2 = x1 + AutoMapXPos;
y2 = sy - AMPlayerX;
DrawLine(sx, y1, x1, y2, COLOR_DIM);
DrawLine(sx, y1, x2, y2, COLOR_DIM);
DrawLine(sx, sy, x1, y2, COLOR_DIM);
DrawLine(sx, sy, x2, y2, COLOR_DIM);
}
if (!(flags & (MAPFLAG_VERTDOOR | MAPFLAG_VERTGRATE | MAPFLAG_VERTARCH)))
DrawLine(sx, sy - AutoMapYPos, sx - AutoMapXPos, sy, COLOR_DIM);
}
if (do_horz) { // left-facing obstacle
if (flags & MAPFLAG_HORZDOOR) {
x1 = sx + AutoMapYPos;
x2 = sx + AutoMapXPos;
y1 = sy - AutoMapYPos;
y2 = sy - AMPlayerX;
DrawLine(sx, y1, sx + AMPlayerX, y1 + AMPlayerY, COLOR_DIM);
DrawLine(x2, sy, x2 - AMPlayerX, sy - AMPlayerY, COLOR_DIM);
DrawLine(x1, y1, sx, y2, COLOR_BRIGHT);
DrawLine(x1, y1, x2, y2, COLOR_BRIGHT);
DrawLine(x1, sy, sx, y2, COLOR_BRIGHT);
DrawLine(x1, sy, x2, y2, COLOR_BRIGHT);
}
if (flags & MAPFLAG_HORZGRATE) {
DrawLine(sx + AutoMapYPos, sy - AMPlayerX, sx + AutoMapXPos, sy, COLOR_DIM);
flags |= MAPFLAG_HORZARCH;
}
if (flags & MAPFLAG_HORZARCH) {
x1 = sx - AutoMapYPos;
y1 = sy - AutoMapYPos;
x2 = x1 + AutoMapXPos;
y2 = sy - AMPlayerX;
DrawLine(sx, y1, x1, y2, COLOR_DIM);
DrawLine(sx, y1, x2, y2, COLOR_DIM);
DrawLine(sx, sy, x1, y2, COLOR_DIM);
DrawLine(sx, sy, x2, y2, COLOR_DIM);
}
if (!(flags & (MAPFLAG_HORZDOOR | MAPFLAG_HORZGRATE | MAPFLAG_HORZARCH)))
DrawLine(sx, sy - AutoMapYPos, sx + AutoMapXPos, sy, COLOR_DIM);
}
// for caves the horz/vert flags are switched
if (do_cave_horz) {
if (flags & MAPFLAG_VERTDOOR) {
x1 = sx - AutoMapXPos;
x2 = sx - AutoMapYPos;
y1 = sy + AutoMapYPos;
y2 = sy + AMPlayerX;
DrawLine(sx, y1, sx - AMPlayerX, y1 - AMPlayerY, COLOR_DIM);
DrawLine(x1, sy, x1 + AMPlayerX, sy + AMPlayerY, COLOR_DIM);
DrawLine(x2, y1, x1, y2, COLOR_BRIGHT);
DrawLine(x2, y1, sx, y2, COLOR_BRIGHT);
DrawLine(x2, sy, x1, y2, COLOR_BRIGHT);
DrawLine(x2, sy, sx, y2, COLOR_BRIGHT);
} else
DrawLine(sx, sy + AutoMapYPos, sx - AutoMapXPos, sy, COLOR_DIM);
}
if (do_cave_vert) {
if (flags & MAPFLAG_HORZDOOR) {
x1 = sx + AutoMapYPos;
x2 = sx + AutoMapXPos;
y1 = sy + AutoMapYPos;
y2 = sy + AMPlayerX;
DrawLine(sx, y1, sx + AMPlayerX, y1 - AMPlayerY, COLOR_DIM);
DrawLine(x2, sy, x2 - AMPlayerX, sy + AMPlayerY, COLOR_DIM);
DrawLine(x1, y1, sx, y2, COLOR_BRIGHT);
DrawLine(x1, y1, x2, y2, COLOR_BRIGHT);
DrawLine(x1, sy, sx, y2, COLOR_BRIGHT);
DrawLine(x1, sy, x2, y2, COLOR_BRIGHT);
} else
DrawLine(sx, sy + AutoMapYPos, sx + AutoMapXPos, sy, COLOR_DIM);
}
}
void __cdecl DrawAutomapPlr()
{
int px, py;
int x, y;
if (plr[myplr]._pmode == PM_WALK3) {
x = plr[myplr]._px;
y = plr[myplr]._py;
if (plr[myplr]._pdir == DIR_W)
x++;
else
y++;
} else {
x = plr[myplr].WorldX;
y = plr[myplr].WorldY;
}
px = x - 2 * AutoMapXOfs - ViewX;
py = y - 2 * AutoMapYOfs - ViewY;
x = (plr[myplr]._pxoff * AutoMapScale / 100 >> 1) + (ScrollInfo._sxoff * AutoMapScale / 100 >> 1) + (px - py) * AutoMapYPos + 384;
y = (plr[myplr]._pyoff * AutoMapScale / 100 >> 1) + (ScrollInfo._syoff * AutoMapScale / 100 >> 1) + (px + py) * AMPlayerX + 336;
if (invflag || sbookflag)
x -= 160;
if (chrflag || questlog)
x += 160;
y -= AMPlayerX;
switch (plr[myplr]._pdir) {
case DIR_N:
DrawLine(x, y, x, y - AutoMapYPos, COLOR_PLAYER);
DrawLine(x, y - AutoMapYPos, x - AMPlayerY, y - AMPlayerX, COLOR_PLAYER);
DrawLine(x, y - AutoMapYPos, x + AMPlayerY, y - AMPlayerX, COLOR_PLAYER);
break;
case DIR_NE:
DrawLine(x, y, x + AutoMapYPos, y - AMPlayerX, COLOR_PLAYER);
DrawLine(x + AutoMapYPos, y - AMPlayerX, x + AMPlayerX, y - AMPlayerX, COLOR_PLAYER);
DrawLine(x + AutoMapYPos, y - AMPlayerX, x + AMPlayerX + AMPlayerY, y, COLOR_PLAYER);
break;
case DIR_E:
DrawLine(x, y, x + AutoMapYPos, y, COLOR_PLAYER);
DrawLine(x + AutoMapYPos, y, x + AMPlayerX, y - AMPlayerY, COLOR_PLAYER);
DrawLine(x + AutoMapYPos, y, x + AMPlayerX, y + AMPlayerY, COLOR_PLAYER);
break;
case DIR_SE:
DrawLine(x, y, x + AutoMapYPos, y + AMPlayerX, COLOR_PLAYER);
DrawLine(x + AutoMapYPos, y + AMPlayerX, x + AMPlayerX + AMPlayerY, y, COLOR_PLAYER);
DrawLine(x + AutoMapYPos, y + AMPlayerX, x + AMPlayerX, y + AMPlayerX, COLOR_PLAYER);
break;
case DIR_S:
DrawLine(x, y, x, y + AutoMapYPos, COLOR_PLAYER);
DrawLine(x, y + AutoMapYPos, x + AMPlayerY, y + AMPlayerX, COLOR_PLAYER);
DrawLine(x, y + AutoMapYPos, x - AMPlayerY, y + AMPlayerX, COLOR_PLAYER);
break;
case DIR_SW:
DrawLine(x, y, x - AutoMapYPos, y + AMPlayerX, COLOR_PLAYER);
DrawLine(x - AutoMapYPos, y + AMPlayerX, x - AMPlayerY - AMPlayerX, y, COLOR_PLAYER);
DrawLine(x - AutoMapYPos, y + AMPlayerX, x - AMPlayerX, y + AMPlayerX, COLOR_PLAYER);
break;
case DIR_W:
DrawLine(x, y, x - AutoMapYPos, y, COLOR_PLAYER);
DrawLine(x - AutoMapYPos, y, x - AMPlayerX, y - AMPlayerY, COLOR_PLAYER);
DrawLine(x - AutoMapYPos, y, x - AMPlayerX, y + AMPlayerY, COLOR_PLAYER);
break;
case DIR_NW:
DrawLine(x, y, x - AutoMapYPos, y - AMPlayerX, COLOR_PLAYER);
DrawLine(x - AutoMapYPos, y - AMPlayerX, x - AMPlayerX, y - AMPlayerX, COLOR_PLAYER);
DrawLine(x - AutoMapYPos, y - AMPlayerX, x - AMPlayerY - AMPlayerX, y, COLOR_PLAYER);
}
}
WORD __fastcall GetAutomapType(int x, int y, BOOL view)
{
if (view) {
if (x == -1 && y >= 0 && y < DMAXY && automapview[0][y])
return ~GetAutomapType(0, y, FALSE) & (MAPFLAG_SQUARE << 8);
if (y == -1) {
if (x < 0)
return 0;
if (x < DMAXX && automapview[x][0])
return ~GetAutomapType(x, 0, FALSE) & (MAPFLAG_SQUARE << 8);
}
}
if (x >= 0 && x < DMAXX && y >= 0 && y < DMAXY) {
if (automapview[x][y] || !view) {
WORD type = automaptype[(BYTE)dungeon[x][y]];
if (type == 7 && GetAutomapType(x - 1, y, FALSE) & (MAPFLAG_HORZARCH << 8)
&& GetAutomapType(x, y - 1, FALSE) & (MAPFLAG_VERTARCH << 8)) {
type = 1;
}
return type;
}
}
return 0;
}
void __cdecl DrawAutomapGame()
{
char desc[256];
int nextline = 20;
if (gbMaxPlayers > 1) {
strcat(strcpy(desc, "game: "), szPlayerName);
PrintGameStr(8, 20, desc, COL_GOLD);
nextline = 35;
if (szPlayerDescript[0]) {
strcat(strcpy(desc, "password: "), szPlayerDescript);
PrintGameStr(8, 35, desc, COL_GOLD);
nextline = 50;
}
}
if (setlevel)
PrintGameStr(8, nextline, quest_level_names[(BYTE)setlvlnum], COL_GOLD);
else if (currlevel) {
sprintf(desc, "Level: %i", currlevel);
PrintGameStr(8, nextline, desc, COL_GOLD);
}
}
void __fastcall SetAutomapView(int x, int y)
{
WORD maptype, solid;
int xx, yy;
xx = (x - 16) >> 1;
yy = (y - 16) >> 1;
if (xx < 0 || xx >= DMAXX || yy < 0 || yy >= DMAXY) {
return;
}
automapview[xx][yy] = 1;
maptype = GetAutomapType(xx, yy, FALSE);
solid = maptype & 0x4000;
switch (maptype & 0xF) {
case 2:
if (solid) {
if (GetAutomapType(xx, yy + 1, FALSE) == 0x4007)
automapview[xx][yy + 1] = 1;
} else if (GetAutomapType(xx - 1, yy, FALSE) & 0x4000) {
automapview[xx - 1][yy] = 1;
}
return;
case 3:
if (solid) {
if (GetAutomapType(xx + 1, yy, FALSE) == 0x4007)
automapview[xx + 1][yy] = 1;
} else if (GetAutomapType(xx, yy - 1, FALSE) & 0x4000) {
automapview[xx][yy - 1] = 1;
}
return;
case 4:
if (solid) {
if (GetAutomapType(xx, yy + 1, FALSE) == 0x4007)
automapview[xx][yy + 1] = 1;
if (GetAutomapType(xx + 1, yy, FALSE) == 0x4007)
automapview[xx + 1][yy] = 1;
} else {
if (GetAutomapType(xx - 1, yy, FALSE) & 0x4000)
automapview[xx - 1][yy] = 1;
if (GetAutomapType(xx, yy - 1, FALSE) & 0x4000)
automapview[xx][yy - 1] = 1;
if (GetAutomapType(xx - 1, yy - 1, FALSE) & 0x4000)
automapview[xx - 1][yy - 1] = 1;
}
return;
case 5:
if (solid) {
if (GetAutomapType(xx, yy - 1, FALSE) & 0x4000)
automapview[xx][yy - 1] = 1;
if (GetAutomapType(xx, yy + 1, FALSE) == 0x4007)
automapview[xx][yy + 1] = 1;
} else if (GetAutomapType(xx - 1, yy, FALSE) & 0x4000) {
automapview[xx - 1][yy] = 1;
}
return;
case 6:
if (solid) {
if (GetAutomapType(xx - 1, yy, FALSE) & 0x4000)
automapview[xx - 1][yy] = 1;
if (GetAutomapType(xx + 1, yy, FALSE) == 0x4007)
automapview[xx + 1][yy] = 1;
} else if (GetAutomapType(xx, yy - 1, FALSE) & 0x4000) {
automapview[xx][yy - 1] = 1;
}
return;
}
}
void __cdecl AutomapZoomReset()
{
AutoMapXOfs = 0;
AutoMapYOfs = 0;
AutoMapPosBits = (AutoMapScale << 6) / 100;
AutoMapXPos = AutoMapPosBits >> 1;
AutoMapYPos = AutoMapXPos >> 1;
AMPlayerX = AutoMapYPos >> 1;
AMPlayerY = AMPlayerX >> 1;
}
DEVILUTION_END_NAMESPACE
| 28.73857 | 243 | 0.609244 | [
"object",
"vector",
"solid"
] |
91cba416c49852d1c1770eef7a5a527f51fa484a | 3,482 | hpp | C++ | Sources/Gizmos/GizmoType.hpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 977 | 2019-05-23T01:53:42.000Z | 2022-03-30T04:22:41.000Z | Sources/Gizmos/GizmoType.hpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 44 | 2019-06-02T17:30:32.000Z | 2022-03-27T14:22:40.000Z | Sources/Gizmos/GizmoType.hpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 121 | 2019-05-23T05:18:01.000Z | 2022-03-27T21:59:23.000Z | #pragma once
#include "Maths/Colour.hpp"
#include "Maths/Matrix4.hpp"
#include "Models/Model.hpp"
#include "Graphics/Buffers/InstanceBuffer.hpp"
#include "Graphics/Descriptors/DescriptorsHandler.hpp"
#include "Graphics/Pipelines/PipelineGraphics.hpp"
#include "Resources/Resource.hpp"
#include "Files/Node.hpp"
namespace acid {
class Gizmo;
/**
* @brief Resource that represents a gizmo type.
*/
class ACID_EXPORT GizmoType : public Resource {
public:
class Instance {
public:
static Shader::VertexInput GetVertexInput(uint32_t baseBinding = 0) {
std::vector<VkVertexInputBindingDescription> bindingDescriptions = {
{baseBinding, sizeof(Instance), VK_VERTEX_INPUT_RATE_INSTANCE}
};
std::vector<VkVertexInputAttributeDescription> attributeDescriptions = {
{0, baseBinding, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Instance, modelMatrix) + offsetof(Matrix4, rows[0])},
{1, baseBinding, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Instance, modelMatrix) + offsetof(Matrix4, rows[1])},
{2, baseBinding, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Instance, modelMatrix) + offsetof(Matrix4, rows[2])},
{3, baseBinding, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Instance, modelMatrix) + offsetof(Matrix4, rows[3])},
{4, baseBinding, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Instance, colour)}
};
return {bindingDescriptions, attributeDescriptions};
}
Matrix4 modelMatrix;
Colour colour;
};
/**
* Creates a new gizmo type, or finds one with the same values.
* @param node The node to decode values from.
* @return The gizmo type with the requested values.
*/
static std::shared_ptr<GizmoType> Create(const Node &node);
/**
* Creates a new gizmo type, or finds one with the same values.
* @param model The model that the gizmo will render.
* @param lineThickness The thickness that the model will be rendered at.
* @param colour The default colour for gizmos.
* @return The gizmo type with the requested values.
*/
static std::shared_ptr<GizmoType> Create(const std::shared_ptr<Model> &model = nullptr, float lineThickness = 1.0f, const Colour &colour = Colour::White);
/**
* Creates a new gizmo type.
* @param model The model that the gizmo will render.
* @param lineThickness The thickness that the model will be rendered at.
* @param colour The default colour for gizmos.
*/
explicit GizmoType(std::shared_ptr<Model> model, float lineThickness = 1.0f, const Colour &colour = Colour::White);
void Update(const std::vector<std::unique_ptr<Gizmo>> &gizmos);
bool CmdRender(const CommandBuffer &commandBuffer, const PipelineGraphics &pipeline, UniformHandler &uniformScene);
std::type_index GetTypeIndex() const override { return typeid(GizmoType); }
const std::shared_ptr<Model> &GetModel() const { return model; }
void SetModel(const std::shared_ptr<Model> &model) { this->model = model; }
float GetLineThickness() const { return lineThickness; }
void SetLineThickness(float lineThickness) { this->lineThickness = lineThickness; }
const Colour &GetColour() const { return colour; }
void SetColour(const Colour &colour) { this->colour = colour; }
friend const Node &operator>>(const Node &node, GizmoType &gizmoType);
friend Node &operator<<(Node &node, const GizmoType &gizmoType);
private:
std::shared_ptr<Model> model;
float lineThickness;
Colour colour;
uint32_t maxInstances = 0;
uint32_t instances = 0;
DescriptorsHandler descriptorSet;
InstanceBuffer instanceBuffer;
};
}
| 37.042553 | 155 | 0.749856 | [
"render",
"vector",
"model"
] |
91d4239b867815fe537fd4c979bb9ccf23787247 | 4,644 | cpp | C++ | src/ai/npc/npcplayer.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 8 | 2018-04-03T23:06:33.000Z | 2021-12-28T18:04:19.000Z | src/ai/npc/npcplayer.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | null | null | null | src/ai/npc/npcplayer.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 1 | 2020-07-31T00:23:27.000Z | 2020-07-31T00:23:27.000Z | #include "npcplayer.h"
#include "../stdai.h"
#include "../ai.h"
#include "../sym/smoke.h"
#include "../../tsc.h"
#include "../../sound/sound.h"
#include "../../common/misc.h"
#include "../../game.h"
#include "../../player.h"
#include "../../map.h"
#include "../../graphics/tileset.h"
#include "../../autogen/sprites.h"
/*
This is an object which looks exactly like the player,
but is controlled as if he is an NPC. Used during cutscenes.
*/
INITFUNC(AIRoutines)
{
ONTICK(OBJ_NPC_PLAYER, ai_npc_player);
ONTICK(OBJ_PTELIN, ai_ptelin);
ONTICK(OBJ_PTELOUT, ai_ptelout);
}
/*
void c------------------------------() {}
*/
void ai_npc_player(Object *o)
{
static const int pwalkanimframes[] = { 0, 1, 0, 2 };
#define NUM_PWALK_FRAMES 4
o->sprite = (player->equipmask & EQUIP_MIMIGA_MASK) ? \
SPR_MYCHAR_MIMIGA : SPR_MYCHAR;
switch(o->state)
{
case 0:
{
o->frame = 0;
o->xinertia = 0;
// used during Hermit Gunsmith scene when he is awake
if (o->dirparam >= 10)
{
o->x = player->x;
o->y = player->y;
o->dir = CVTDir(o->dirparam - 10);
o->dirparam = 0;
}
}
break;
case 2: // looking up
{
o->frame = 3;
}
break;
case 10: // he gets flattened
{
sound(SND_LITTLE_CRASH);
SmokeClouds(o, 6, 8, 8);
o->state++;
}
case 11:
{
o->frame = 9;
}
break;
case 20: // he teleports away
{
if (DoTeleportOut(o, 2))
o->Delete();
}
break;
case 50: // walking
{
// z-order tweaking for oside bad-ending
Object *dragon = Objects::FindByType(OBJ_SKY_DRAGON);
if (dragon) o->PushBehind(dragon);
o->state = 51;
o->animframe = 0;
o->animtimer = 0;
}
case 51:
{
o->animate_seq(4, pwalkanimframes, NUM_PWALK_FRAMES);
XMOVE(0x200);
}
break;
// falling, upside-down (from good ending; Fall stage)
case 60:
{
o->state = 61;
o->frame = 10;
o->xmark = o->x;
o->ymark = o->y;
}
case 61:
{
o->ymark += 0x100;
o->x = o->xmark + (random(-1, 1) * CSFI);
o->y = o->ymark + (random(-1, 1) * CSFI);
}
break;
case 80: // face away
o->frame = 11;
break;
// walking in place during credits
case 99:
case 100:
{
o->state = 101;
o->frame = 1;
o->animtimer = 0;
if ((player->equipmask & EQUIP_MIMIGA_MASK) || game.flags[1020])
o->sprite = SPR_MYCHAR_MIMIGA;
}
case 101: // falling a short dist
case 102: // walk in place
{
if (!o->blockd)
{
o->yinertia += 0x40;
LIMITY(0x5ff);
}
else
{
o->yinertia = 0;
o->animate_seq(8, pwalkanimframes, NUM_PWALK_FRAMES);
}
}
break;
}
}
/*
void c------------------------------() {}
*/
// player (teleporting in)
void ai_ptelin(Object *o)
{
o->sprite = (player->equipmask & EQUIP_MIMIGA_MASK) ? \
SPR_MYCHAR_MIMIGA : SPR_MYCHAR;
switch(o->state)
{
case 0:
{
o->flags &= ~FLAG_IGNORE_SOLID;
o->frame = 0;
o->timer = 0;
o->x += (TILE_W * CSFI);
o->y += (TILE_H / 2) * CSFI;
o->state++;
// note, it looks sort of like we might be supposed to face left when
// appearing at the Labyrinth teleporter as well, but the original engine
// does not do this, so I'm following what it does.
if (game.curmap == STAGE_SAND)
o->dir = LEFT; // for Sand Zone, hackety
}
case 1:
{
if (DoTeleportIn(o, 2))
{
o->timer = 0;
o->state = 2;
}
}
break;
case 2:
{
if (++o->timer > 20)
{
o->yinertia += 0x40;
o->frame = 1;
o->state = 3;
}
}
break;
case 3:
{
o->yinertia += 0x40;
if (o->blockd)
{
o->frame = 0;
o->state = 4;
}
}
}
}
// player (teleporting out)
void ai_ptelout(Object *o)
{
o->sprite = (player->equipmask & EQUIP_MIMIGA_MASK) ? \
SPR_MYCHAR_MIMIGA : SPR_MYCHAR;
switch(o->state)
{
case 0:
{
o->y -= (TILE_H * CSFI);
o->ymark = o->y - (8 * CSFI);
o->frame = 0;
o->timer = 0;
o->state = 1;
}
break;
case 1:
{
if (++o->timer > 20)
{
o->state = 2;
o->frame = 1;
o->timer = 0;
o->yinertia = -0x2FF;
}
}
break;
case 2:
{
if (o->yinertia >= 0 && o->y >= o->ymark)
{
o->y = o->ymark;
o->yinertia = 0;
o->state = 3;
o->frame = 0;
o->timer = 0;
}
}
break;
case 3:
{
if (++o->timer > 40)
{
o->state = 4;
o->timer = 0;
}
}
break;
case 4:
{
if (DoTeleportOut(o, 2))
o->Delete();
}
break;
}
if (o->state < 3)
o->yinertia += 50;
LIMITY(0x5ff);
}
| 15.689189 | 76 | 0.515935 | [
"object"
] |
91d5df7b344698e70986f6d12a774b204e90d80d | 1,957 | cpp | C++ | modules/lwjgl/driftfx/src/main/c/src/FrameNativeAPI.cpp | amatiushkin/lwjgl3 | f3e08f9797ee3c2218f3f337c37dede62a16b800 | [
"BSD-3-Clause"
] | 9 | 2020-01-20T01:10:40.000Z | 2021-07-27T08:42:34.000Z | modules/lwjgl/driftfx/src/main/c/src/FrameNativeAPI.cpp | octeep/lwjgl3 | 2894a2fde95ac5d624eba8cbe20e971f87788a50 | [
"BSD-3-Clause"
] | 1 | 2021-07-24T18:04:57.000Z | 2021-07-24T18:04:57.000Z | modules/lwjgl/driftfx/src/main/c/src/FrameNativeAPI.cpp | octeep/lwjgl3 | 2894a2fde95ac5d624eba8cbe20e971f87788a50 | [
"BSD-3-Clause"
] | 4 | 2020-03-28T06:42:52.000Z | 2021-02-10T17:45:44.000Z |
#include <jni.h>
#include <iostream>
#include <iomanip>
#include "utils/Logger.h"
#include "NativeSurfaceRegistry.h"
#include "NativeSurface.h"
#include "FrameManager.h"
#include "jni/JNITiming.h"
using namespace std;
using namespace driftfx::internal;
std::string Convert(JNIEnv* env, jstring in) {
const char* chars = env->GetStringUTFChars(in, 0);
string s(chars);
env->ReleaseStringUTFChars(in, chars);
return s;
}
jobject Convert(JNIEnv* env, Timing & t) {
return jni::Timing::New(env, env->NewStringUTF(t.tag.c_str()), (jlong) t.begin, (jlong) t.end);
}
jobjectArray Convert(JNIEnv* env, vector<Timing> report) {
jobjectArray result = env->NewObjectArray(report.size(), jni::Timing::Class(), 0);
vector<Timing>::iterator it;
int index;
for (index = 0; index < report.size(); index++) {
Timing & t = report[index];
env->SetObjectArrayElement(result, index, Convert(env, t));
}
return result;
}
extern "C" JNIEXPORT void JNICALL Java_org_eclipse_fx_drift_internal_Frame_nBegin(JNIEnv* env, jclass cls, jlong surfaceId, jlong frameId, jstring tag) {
NativeSurface* surface = NativeSurfaceRegistry::Get()->Get((long) surfaceId);
Frame* frame = surface->GetFrameManager()->GetFrame(frameId);
frame->Begin(Convert(env, tag));
}
extern "C" JNIEXPORT void JNICALL Java_org_eclipse_fx_drift_internal_Frame_nEnd(JNIEnv* env, jclass cls, jlong surfaceId, jlong frameId, jstring tag) {
NativeSurface* surface = NativeSurfaceRegistry::Get()->Get((long) surfaceId);
Frame* frame = surface->GetFrameManager()->GetFrame(frameId);
frame->End(Convert(env, tag));
}
extern "C" JNIEXPORT jarray JNICALL Java_org_eclipse_fx_drift_internal_Frame_nGetReport(JNIEnv* env, jclass cls, jlong surfaceId, jlong frameId) {
NativeSurface* surface = NativeSurfaceRegistry::Get()->Get((long) surfaceId);
Frame* frame = surface->GetFrameManager()->GetFrame(frameId);
vector<Timing> report = frame->GetReport();
return Convert(env, report);
}
| 31.063492 | 153 | 0.740419 | [
"vector"
] |
91dc57cf8e288988f5e447839ef7b70d391a7859 | 89,457 | cxx | C++ | vtr/toro/TVPR_Interface/TVPR_FabricModel.cxx | haojunliu/OpenFPGA | b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1 | [
"BSD-2-Clause"
] | 31 | 2016-02-15T02:57:28.000Z | 2021-06-02T10:40:25.000Z | vtr/toro/TVPR_Interface/TVPR_FabricModel.cxx | haojunliu/OpenFPGA | b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1 | [
"BSD-2-Clause"
] | null | null | null | vtr/toro/TVPR_Interface/TVPR_FabricModel.cxx | haojunliu/OpenFPGA | b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1 | [
"BSD-2-Clause"
] | 6 | 2017-02-08T21:51:51.000Z | 2021-06-02T10:40:40.000Z | //===========================================================================//
// Purpose : Method definitions for the TVPR_FabricModel_c class.
//
// Public methods include:
// - TVPR_FabricModel_c, ~TVPR_FabricModel_c
// - Export
// - Import
//
// Private methods include:
// - PopulateFabricView_
// - PopulateBlockPlane_
// - PopulateChannelPlane_
// - PopulateSegmentPlane_
// - PopulateConnectionPlane_
// - GenerateFabricView_
// - ExtractFabricView_
// - ExtractBlockPlane_
// - ExtractChannelPlane_
// - ExtractSegmentPlane_
// - ExtractPinList_
// - PeekInputOutputs_
// - PeekPhysicalBlocks_
// - PeekChannels_
// - PeekSegments_
// - PeekSwitchBoxes_
// - PeekConnectionBoxes_
// - AddBlockPinList_
// - AddBlockMapTable_
// - UpdatePinList_
// - BuildChannelDefaults_
// - UpdateChannelCounts_
// - ResizeChannelWidths_
// - ResizeChannelLengths_
// - BuildSwitchBoxes_
// - UpdateSwitchMapTables_
// - BuildConnectionBoxes_
// - BuildConnectionRegion_
// - UpdateConnectionPoints_
// - CalcMaxPinCount_
// - CalcPinCountArray_
// - CalcPinOffsetArray_
// - FindPinName_
// - FindPinSide_
// - FindPinOffset_
// - FindChannelCount_
// - FindChannelRegion_
// - FindSegmentRegion_
// - FindBlockRegion_
// - FindNodeRegion_
// - FindSwitchSide_
// - MapDataTypeToLayer_
// - MapDataTypeToBlockType_
// - MapBlockTypeToDataType_
// - AddFabricViewRegion_
// - ReplaceFabricViewRegion_
//
//===========================================================================//
//---------------------------------------------------------------------------//
// Copyright (C) 2012 Jeff Rudolph, Texas Instruments (jrudolph@ti.com) //
// //
// 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 3 of the License, or any later version. //
// //
// This program is distributed in the hope that it will be useful, but //
// WITHOUT ANY WARRANTY; without even an implied warranty of MERCHANTABILITY //
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License //
// for more details. //
// //
// You should have received a copy of the GNU General Public License along //
// with this program; if not, see <http://www.gnu.org/licenses>. //
//---------------------------------------------------------------------------//
#include <string>
using namespace std;
#include "TVPR_FabricModel.h"
//===========================================================================//
// Method : TVPR_FabricModel_c
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 07/10/12 jeffr : Original
//===========================================================================//
TVPR_FabricModel_c::TVPR_FabricModel_c(
void )
{
}
//===========================================================================//
// Method : ~TVPR_FabricModel_c
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 07/10/12 jeffr : Original
//===========================================================================//
TVPR_FabricModel_c::~TVPR_FabricModel_c(
void )
{
}
//===========================================================================//
// Method : Export
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::Export(
const TFM_FabricModel_c& fabricModel ) const
{
bool ok = true;
TFM_FabricModel_c* pfabricModel = const_cast< TFM_FabricModel_c* >( &fabricModel );
TFV_FabricView_c* pfabricView = pfabricModel->GetFabricView( );
ok = this->PopulateFabricView_( fabricModel, pfabricView );
// WIP ??? Still need to poke fabric view data directly into VPR structures...
return( ok );
}
//===========================================================================//
// Method : Import
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::Import(
t_grid_tile** vpr_gridArray,
int vpr_nx,
int vpr_ny,
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFM_FabricModel_c* pfabricModel ) const
{
bool ok = true;
// Define local grid dimensions (overall) based on VPR nx/ny values
TGS_IntDims_t vpr_gridDims( vpr_nx + 2, vpr_ny + 2 );
// Start by generating fabric view based on VPR's internal data structures
TFV_FabricView_c* pfabricView = pfabricModel->GetFabricView( );
ok = this->GenerateFabricView_( vpr_gridArray, vpr_gridDims,
vpr_rrNodeArray, vpr_rrNodeCount,
pfabricView );
// Then, extract fabric view contents to populate fabric model
if( ok )
{
this->ExtractFabricView_( *pfabricView,
pfabricModel );
}
return( ok );
}
//===========================================================================//
// Method : PopulateFabricView_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::PopulateFabricView_(
const TFM_FabricModel_c& fabricModel,
TFV_FabricView_c* pfabricView ) const
{
bool ok = true;
pfabricView->Clear( );
if( fabricModel.IsValid( ))
{
const string& srName = fabricModel.srName;
const TFM_Config_c& config = fabricModel.config;
const TFM_PhysicalBlockList_t& physicalBlockList = fabricModel.physicalBlockList;
const TFM_InputOutputList_t& inputOutputList = fabricModel.inputOutputList;
const TFM_SwitchBoxList_t& switchBoxList = fabricModel.switchBoxList;
const TFM_ChannelList_t& channelList = fabricModel.channelList;
const TFM_SegmentList_t& segmentList = fabricModel.segmentList;
pfabricView->Init( TIO_SR_STR( srName ), config.fabricRegion );
this->PopulateBlockPlane_( physicalBlockList, pfabricView );
this->PopulateBlockPlane_( inputOutputList, pfabricView );
this->PopulateBlockPlane_( switchBoxList, pfabricView );
this->PopulateChannelPlane_( channelList, pfabricView );
this->PopulateSegmentPlane_( segmentList, pfabricView );
if( ok )
{
ok = PopulateConnectionPlane_( physicalBlockList, pfabricView );
}
if( ok )
{
ok = PopulateConnectionPlane_( inputOutputList, pfabricView );
}
}
return( ok );
}
//===========================================================================//
// Method : PopulateBlockPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PopulateBlockPlane_(
const TFM_BlockList_t& blockList,
TFV_FabricView_c* pfabricView ) const
{
for( size_t i = 0; i < blockList.GetLength( ); ++i )
{
const TFM_Block_c& block = *blockList[i];
const TGS_Region_c& blockRegion = block.region;
TFV_DataType_t dataType = this->MapBlockTypeToDataType_( block.blockType );
const char* pszName = TIO_SR_STR( block.srName );
const char* pszMasterName = TIO_SR_STR( block.srMasterName );
unsigned int sliceCount = block.slice.count;
unsigned int sliceCapacity = block.slice.capacity;
TFV_FabricData_c* pfabricData = 0;
this->AddFabricViewRegion_( blockRegion, dataType,
pszName, pszMasterName,
sliceCount, sliceCapacity,
pfabricView, &pfabricData );
if( pfabricData )
{
// Add given block's pins, if any, to fabric block's pin list
if( block.pinList.IsValid( ))
{
this->AddBlockPinList_( block.pinList, pfabricData );
}
// Add given block's map table, if any, to fabric block's map table
if( block.mapTable.IsValid( ))
{
this->AddBlockMapTable_( block.mapTable, pfabricData );
}
}
}
}
//===========================================================================//
// Method : PopulateChannelPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PopulateChannelPlane_(
const TFM_ChannelList_t& channelList,
TFV_FabricView_c* pfabricView ) const
{
for( size_t i = 0; i < channelList.GetLength( ); ++i )
{
const TFM_Channel_c& channel = *channelList[i];
const TGS_Region_c& channelRegion = channel.region;
TFV_DataType_t dataType = ( channel.orient == TGS_ORIENT_HORIZONTAL ?
TFV_DATA_CHANNEL_HORZ : TFV_DATA_CHANNEL_VERT );
const char* pszName = TIO_SR_STR( channel.srName );
unsigned int trackHorzCount = ( channel.orient == TGS_ORIENT_HORIZONTAL ?
channel.count : 0 );
unsigned int trackVertCount = ( channel.orient == TGS_ORIENT_HORIZONTAL ?
0 : channel.count );
this->AddFabricViewRegion_( channelRegion, dataType,
pszName, trackHorzCount, trackVertCount,
pfabricView );
}
}
//===========================================================================//
// Method : PopulateSegmentPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PopulateSegmentPlane_(
const TFM_SegmentList_t& segmentList,
TFV_FabricView_c* pfabricView ) const
{
for( size_t i = 0; i < segmentList.GetLength( ); ++i )
{
const TFM_Segment_c& segment = *segmentList[i];
TGS_Region_c segmentRegion;
segment.path.FindRegion( &segmentRegion );
TGS_OrientMode_t segmentOrient = segment.path.FindOrient( );
TFV_DataType_t dataType = ( segmentOrient == TGS_ORIENT_HORIZONTAL ?
TFV_DATA_SEGMENT_HORZ : TFV_DATA_SEGMENT_VERT );
const char* pszName = TIO_SR_STR( segment.srName );
unsigned int trackIndex = segment.index;
this->AddFabricViewRegion_( segmentRegion, dataType,
pszName, trackIndex, pfabricView );
}
}
//===========================================================================//
// Method : PopulateConnectionPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::PopulateConnectionPlane_(
const TFM_BlockList_t& blockList,
TFV_FabricView_c* pfabricView ) const
{
bool ok = true;
for( size_t i = 0; i < blockList.GetLength( ); ++i )
{
const TFM_Block_c& block = *blockList[i];
const TGS_Region_c& blockRegion = block.region;
TFV_FabricFigure_t* pfabricFigure = 0;
if( !pfabricView->IsSolidAll( TFV_LAYER_INPUT_OUTPUT, blockRegion, &pfabricFigure ) &&
!pfabricView->IsSolidAll( TFV_LAYER_PHYSICAL_BLOCK, blockRegion, &pfabricFigure ))
{
continue;
}
// Iterate for every pin associated with this PB|IO figure
TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
const TFV_FabricPinList_t& fabricPinList = pfabricData->GetPinList( );
for( size_t j = 0; j < fabricPinList.GetLength( ); ++j )
{
const TFV_FabricPin_c& fabricPin = *fabricPinList[j];
// Define a connection box region spanning from pin to channel region
TGS_Region_c connectionRegion;
ok = this->BuildConnectionRegion_( *pfabricView, fabricPin,
blockRegion, &connectionRegion );
if( !ok )
break;
TFV_DataType_t dataType = TFV_DATA_CONNECTION_BOX;
this->AddFabricViewRegion_( connectionRegion, dataType,
pfabricView, &pfabricData );
if( pfabricData )
{
// Update connection box figure per asso. side and track index
pfabricData->AddConnection( fabricPin.GetConnectionList( ));
}
}
if( !ok )
break;
}
return( ok );
}
//===========================================================================//
// Method : GenerateFabricView_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::GenerateFabricView_(
t_grid_tile** vpr_gridArray,
const TGS_IntDims_t& vpr_gridDims,
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFV_FabricView_c* pfabricView ) const
{
bool ok = true;
string srFabricName;
TGS_Region_c fabricRegion;
if( pfabricView->IsValid( ))
{
srFabricName = pfabricView->GetName( );
fabricRegion = pfabricView->GetRegion( );
}
TGS_Region_c gridRegion( 0.0, 0.0, vpr_gridDims.dx - 1, vpr_gridDims.dy - 1 );
gridRegion.ApplyScale( 1.0 );
fabricRegion.ApplyUnion( gridRegion );
ok = pfabricView->Init( srFabricName, fabricRegion );
if( ok &&
vpr_gridArray && vpr_rrNodeArray )
{
this->PeekInputOutputs_( vpr_gridArray, vpr_gridDims,
pfabricView );
this->PeekPhysicalBlocks_( vpr_gridArray, vpr_gridDims,
pfabricView );
this->PeekChannels_( vpr_gridDims,
vpr_rrNodeArray, vpr_rrNodeCount,
pfabricView );
this->PeekSwitchBoxes_( vpr_gridDims,
vpr_rrNodeArray, vpr_rrNodeCount,
pfabricView );
this->PeekSegments_( vpr_rrNodeArray, vpr_rrNodeCount,
pfabricView );
ok = this->PeekConnectionBoxes_( vpr_gridDims,
vpr_rrNodeArray, vpr_rrNodeCount,
pfabricView );
}
return( ok );
}
//===========================================================================//
// Method : ExtractFabricView_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ExtractFabricView_(
const TFV_FabricView_c& fabricView,
TFM_FabricModel_c* pfabricModel ) const
{
pfabricModel->Clear( );
if( fabricView.IsValid( ))
{
pfabricModel->srName = TIO_PSZ_STR( fabricView.GetName( ));
pfabricModel->config.fabricRegion = fabricView.GetRegion( );
const TFV_FabricPlane_c& ioPlane = *fabricView.FindFabricPlane( TFV_LAYER_INPUT_OUTPUT );
this->ExtractBlockPlane_( ioPlane, &pfabricModel->inputOutputList );
const TFV_FabricPlane_c& pbPlane = *fabricView.FindFabricPlane( TFV_LAYER_PHYSICAL_BLOCK );
this->ExtractBlockPlane_( pbPlane, &pfabricModel->physicalBlockList );
const TFV_FabricPlane_c& sbPlane = *fabricView.FindFabricPlane( TFV_LAYER_SWITCH_BOX );
this->ExtractBlockPlane_( sbPlane, &pfabricModel->switchBoxList );
const TFV_FabricPlane_c& chPlane = *fabricView.FindFabricPlane( TFV_LAYER_CHANNEL_HORZ );
this->ExtractChannelPlane_( chPlane, &pfabricModel->channelList );
const TFV_FabricPlane_c& cvPlane = *fabricView.FindFabricPlane( TFV_LAYER_CHANNEL_VERT );
this->ExtractChannelPlane_( cvPlane, &pfabricModel->channelList );
const TFV_FabricPlane_c& shPlane = *fabricView.FindFabricPlane( TFV_LAYER_SEGMENT_HORZ );
this->ExtractSegmentPlane_( shPlane, &pfabricModel->segmentList );
const TFV_FabricPlane_c& svPlane = *fabricView.FindFabricPlane( TFV_LAYER_SEGMENT_VERT );
this->ExtractSegmentPlane_( svPlane, &pfabricModel->segmentList );
}
}
//===========================================================================//
// Method : ExtractBlockPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ExtractBlockPlane_(
const TFV_FabricPlane_t& fabricPlane,
TFM_BlockList_t* pblockList ) const
{
TFV_FabricPlaneIter_t fabricPlaneIter( fabricPlane );
TFV_FabricFigure_t* pfabricFigure = 0;
while( fabricPlaneIter.Next( &pfabricFigure, TFV_FIGURE_SOLID ))
{
const TGS_Region_c& region = pfabricFigure->GetRegion( );
const TFV_FabricData_c& fabricData = *pfabricFigure->GetData( );
if(( fabricData.GetDataType( ) != TFV_DATA_INPUT_OUTPUT ) &&
( fabricData.GetDataType( ) != TFV_DATA_PHYSICAL_BLOCK ) &&
( fabricData.GetDataType( ) != TFV_DATA_SWITCH_BOX ))
continue;
const char* pszName = fabricData.GetName( );
const char* pszMasterName = fabricData.GetMasterName( );
TFV_DataType_t dataType = fabricData.GetDataType( );
TFM_BlockType_t blockType = this->MapDataTypeToBlockType_( dataType );
TFM_Block_c block( blockType, pszName, pszMasterName, region );
block.slice.count = fabricData.GetSliceCount( );
block.slice.capacity = fabricData.GetSliceCapacity( );
block.mapTable = fabricData.GetMapTable( );
const TFV_FabricPinList_t& fabricPinList = fabricData.GetPinList( );
this->ExtractPinList_( fabricPinList, &block.pinList );
pblockList->Add( block );
}
}
//===========================================================================//
// Method : ExtractChannelPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ExtractChannelPlane_(
const TFV_FabricPlane_t& fabricPlane,
TFM_ChannelList_t* pchannelList ) const
{
TFV_FabricPlaneIter_t fabricPlaneIter( fabricPlane );
TFV_FabricFigure_t* pfabricFigure = 0;
while( fabricPlaneIter.Next( &pfabricFigure, TFV_FIGURE_SOLID ))
{
const TGS_Region_c& region = pfabricFigure->GetRegion( );
const TFV_FabricData_c& fabricData = *pfabricFigure->GetData( );
TFV_DataType_t dataType = fabricData.GetDataType( );
if(( dataType != TFV_DATA_CHANNEL_HORZ ) &&
( dataType != TFV_DATA_CHANNEL_VERT ))
continue;
const char* pszName = fabricData.GetName( );
TGS_OrientMode_t orient = ( dataType == TFV_DATA_CHANNEL_HORZ ?
TGS_ORIENT_HORIZONTAL : TGS_ORIENT_VERTICAL );
unsigned int horzCount = fabricData.GetTrackHorzCount( );
unsigned int vertCount = fabricData.GetTrackVertCount( );
unsigned int count = ( dataType == TFV_DATA_CHANNEL_HORZ ?
horzCount : vertCount );
TFM_Channel_c channel( pszName, region, orient, count );
pchannelList->Add( channel );
}
}
//===========================================================================//
// Method : ExtractSegmentPlane_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ExtractSegmentPlane_(
const TFV_FabricPlane_t& fabricPlane,
TFM_SegmentList_t* psegmentList ) const
{
TFV_FabricPlaneIter_t fabricPlaneIter( fabricPlane );
TFV_FabricFigure_t* pfabricFigure = 0;
while( fabricPlaneIter.Next( &pfabricFigure, TFV_FIGURE_SOLID ))
{
const TGS_Region_c& region = pfabricFigure->GetRegion( );
const TFV_FabricData_c& fabricData = *pfabricFigure->GetData( );
TFV_DataType_t dataType = fabricData.GetDataType( );
if(( dataType != TFV_DATA_SEGMENT_HORZ ) &&
( dataType != TFV_DATA_SEGMENT_VERT ))
continue;
const char* pszName = fabricData.GetName( );
unsigned int index = fabricData.GetTrackIndex( );
TGS_Path_c path( region );
TFM_Segment_c segment( pszName, path, index );
psegmentList->Add( segment );
}
}
//===========================================================================//
// Method : ExtractPinList_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ExtractPinList_(
const TFV_FabricPinList_t& fabricPinList,
TFM_PinList_t* ppinList ) const
{
TC_Bit_c trueBit( TC_BIT_TRUE );
TC_Bit_c falseBit( TC_BIT_FALSE );
for( size_t i = 0; i < fabricPinList.GetLength( ); ++i )
{
const TFV_FabricPin_c& fabricPin = *fabricPinList[i];
TFM_Pin_c pin( fabricPin.GetName( ),
fabricPin.GetSide( ),
fabricPin.GetOffset( ),
fabricPin.GetWidth( ),
fabricPin.GetSlice( ));
unsigned int channelCount = fabricPin.GetChannelCount( );
if( channelCount )
{
for( size_t j = 0; j < channelCount; ++j )
{
pin.connectionPattern.Add( falseBit );
}
const TFV_ConnectionList_t& connectionList = fabricPin.GetConnectionList( );
for( size_t j = 0; j < connectionList.GetLength( ); ++j )
{
const TFV_Connection_t& connection = *connectionList[j];
unsigned int index = static_cast< unsigned int >( connection.GetIndex( ));
pin.connectionPattern.Replace( index, trueBit );
}
}
ppinList->Add( pin );
}
}
//===========================================================================//
// Method : PeekInputOutputs_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PeekInputOutputs_(
t_grid_tile** vpr_gridArray,
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
// Iterate for every IO found within VPR's grid
// (includes condition where IO may not be located the grid perimeter)
for( int x = 0; x < vpr_gridDims.dx; ++x )
{
for( int y = 0; y < vpr_gridDims.dy; ++y )
{
if( vpr_gridArray[x][y].type != IO_TYPE )
continue;
t_type_descriptor vpr_type = *grid[x][y].type;
char szName[TIO_FORMAT_STRING_LEN_DATA];
sprintf( szName, "io[%d][%d]", x, y );
const char* pszMasterName = "";
if( vpr_type.pb_type )
{
pszMasterName = vpr_type.pb_type->name;
}
TGS_Region_c ioRegion( x, y, x, y );
double dx = TFV_MODEL_INPUT_OUTPUT_DEF_WIDTH;
double dy = TFV_MODEL_INPUT_OUTPUT_DEF_WIDTH;
ioRegion.ApplyScale( dx, dy, TGS_SNAP_MIN_GRID );
unsigned int sliceCount = vpr_type.capacity;
unsigned int sliceCapacity = vpr_type.num_pins / ( vpr_type.capacity ? vpr_type.capacity : 1 );
this->AddFabricViewRegion_( ioRegion, TFV_DATA_INPUT_OUTPUT,
szName, pszMasterName,
sliceCount, sliceCapacity,
pfabricView );
TC_SideMode_t onlySide = TC_SIDE_UNDEFINED;
onlySide = ( x == 0 ? TC_SIDE_RIGHT : onlySide );
onlySide = ( x == vpr_gridDims.dx - 1 ? TC_SIDE_LEFT : onlySide );
onlySide = ( y == 0 ? TC_SIDE_UPPER : onlySide );
onlySide = ( y == vpr_gridDims.dy - 1 ? TC_SIDE_LOWER : onlySide );
this->UpdatePinList_( ioRegion, onlySide, TFV_DATA_INPUT_OUTPUT,
vpr_type, pfabricView );
}
}
}
//===========================================================================//
// Method : PeekPhysicalBlocks_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PeekPhysicalBlocks_(
t_grid_tile** vpr_gridArray,
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
unsigned int maxPinCount = this->CalcMaxPinCount_( vpr_gridArray,
vpr_gridDims );
// Iterate for every physical block found within VPR's grid
for( int x = 0; x < vpr_gridDims.dx; ++x )
{
for( int y = 0; y < vpr_gridDims.dy; ++y )
{
if( vpr_gridArray[x][y].type != FILL_TYPE )
continue;
t_type_descriptor vpr_type = *grid[x][y].type;
char szName[TIO_FORMAT_STRING_LEN_DATA];
sprintf( szName, "pb[%d][%d]", x, y );
const char* pszMasterName = "";
if( vpr_type.pb_type )
{
pszMasterName = vpr_type.pb_type->name;
}
TGS_Region_c pbRegion( x, y, x, y );
double dx = TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double dy = TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
if( vpr_type.height > 1 )
{
// Using VPR's architecture height for multi-grid tall blocks
pbRegion.y2 += vpr_type.height;
}
// TBD ??? else if( vpr_type.size.IsValid( ))
// TBD ??? {
// TBD ??? // Using Toro's architecture size for non-uniform blocks
// TBD ??? dx = vpr_type.size.width;
// TBD ??? dy = vpr_type.size.height;
// TBD ??? }
else if( maxPinCount > 1 )
{
// Using max pin count to estimate min size for all blocks
double pinWidth = TFV_MODEL_PIN_DEF_WIDTH;
double pinSpacing = TFV_MODEL_PIN_DEF_SPACING;
dx = TCT_Max( dx, ( pinWidth + pinSpacing ) * maxPinCount );
dy = TCT_Max( dy, ( pinWidth + pinSpacing ) * maxPinCount );
}
pbRegion.ApplyScale( dx, dy, TGS_SNAP_MIN_GRID );
unsigned int sliceCount = 0;
unsigned int sliceCapacity = 0;
this->AddFabricViewRegion_( pbRegion, TFV_DATA_PHYSICAL_BLOCK,
szName, pszMasterName,
sliceCount, sliceCapacity,
pfabricView );
TC_SideMode_t onlySide = TC_SIDE_UNDEFINED;
this->UpdatePinList_( pbRegion, onlySide, TFV_DATA_PHYSICAL_BLOCK,
vpr_type, pfabricView );
}
}
}
//===========================================================================//
// Method : PeekChannels_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PeekChannels_(
const TGS_IntDims_t& vpr_gridDims,
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFV_FabricView_c* pfabricView ) const
{
// Generate initial 0-width channels based on given VPR grid dimensions
this->BuildChannelDefaults_( vpr_gridDims, pfabricView );
// Update 0-width channels to reflect max track count (per VPR's rr_nodes)
this->UpdateChannelCounts_( vpr_rrNodeArray, vpr_rrNodeCount, *pfabricView );
// Resize channel widths based on max track count (per each channel)
this->ResizeChannelWidths_( vpr_gridDims, pfabricView );
// Resize channel lengths based on orthogonal channels (per each channel)
this->ResizeChannelLengths_( vpr_gridDims, pfabricView );
}
//===========================================================================//
// Method : PeekSegments_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PeekSegments_(
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFV_FabricView_c* pfabricView ) const
{
// Iterate for all VPR internal rr_node CHANX|CHANY nodes,
// in order to add segments based on channel and track coordinates
for( int i = 0; i < vpr_rrNodeCount; ++i )
{
const t_rr_node& vpr_rrNode = vpr_rrNodeArray[i];
if(( vpr_rrNode.type != CHANX ) && ( vpr_rrNode.type != CHANY ))
continue;
TGS_Region_c segmentRegion;
this->FindSegmentRegion_( vpr_rrNode, *pfabricView, &segmentRegion );
double segmentWidth = TFV_MODEL_SEGMENT_DEF_WIDTH;
TFV_DataType_t dataType = TFV_DATA_UNDEFINED;
char szName[TIO_FORMAT_STRING_LEN_DATA];
if( vpr_rrNode.type == CHANX )
{
segmentRegion.ApplyScale( 0.0, segmentWidth / 2.0, TGS_SNAP_MIN_GRID );
dataType = TFV_DATA_SEGMENT_HORZ;
sprintf( szName, "sh[%d].%d", vpr_rrNode.ylow, vpr_rrNode.ptc_num );
}
if( vpr_rrNode.type == CHANY )
{
segmentRegion.ApplyScale( segmentWidth / 2.0, 0.0, TGS_SNAP_MIN_GRID );
dataType = TFV_DATA_SEGMENT_VERT;
sprintf( szName, "sv[%d].%d", vpr_rrNode.xlow, vpr_rrNode.ptc_num );
}
unsigned int trackIndex = static_cast< int >( vpr_rrNode.ptc_num );
this->AddFabricViewRegion_( segmentRegion, dataType,
szName, trackIndex, pfabricView );
}
}
//===========================================================================//
// Method : PeekSwitchBoxes_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::PeekSwitchBoxes_(
const TGS_IntDims_t& vpr_gridDims,
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFV_FabricView_c* pfabricView ) const
{
// Generate initial switch boxes based on channels (but sans mappings)
this->BuildSwitchBoxes_( vpr_gridDims, pfabricView );
// Update switch boxes to reflect mappings (per VPR's rr_nodes)
this->UpdateSwitchMapTables_( vpr_rrNodeArray, vpr_rrNodeCount, *pfabricView );
}
//===========================================================================//
// Method : PeekConnectionBoxes_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::PeekConnectionBoxes_(
const TGS_IntDims_t& vpr_gridDims,
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFV_FabricView_c* pfabricView ) const
{
bool ok = true;
// Generate initial connection boxes based on pins (but sans connections)
ok = this->BuildConnectionBoxes_( vpr_gridDims, pfabricView );
// Update connection boxes to reflect pin connections (per VPR's rr_nodes)
if( ok )
{
this->UpdateConnectionPoints_( vpr_rrNodeArray, vpr_rrNodeCount, pfabricView );
}
return( ok );
}
//===========================================================================//
// Method : AddBlockPinList_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::AddBlockPinList_(
const TFM_PinList_t& pinList,
TFV_FabricData_c* pfabricData ) const
{
// Add given pins, if any, to fabric block's pin list
for( size_t i = 0; i < pinList.GetLength( ); ++i )
{
const TFM_Pin_c& pin = *pinList[i];
TFV_FabricPin_c fabricPin( pin.GetName( ), pin.slice,
pin.side, pin.offset, pin.width );
if( pin.connectionPattern.IsValid( ))
{
unsigned int channelCount = static_cast< unsigned int >( pin.connectionPattern.GetLength( ));
fabricPin.SetChannelCount( channelCount );
for( size_t j = 0; j < pin.connectionPattern.GetLength( ); ++j )
{
const TC_Bit_c& bit = *pin.connectionPattern[j];
if( !bit.IsTrue( ))
continue;
unsigned int index = static_cast< unsigned int >( j );
TFV_Connection_t connection( pin.side, index );
fabricPin.AddConnection( connection );
}
}
pfabricData->AddPin( fabricPin );
}
}
//===========================================================================//
// Method : AddBlockMapList_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::AddBlockMapTable_(
const TC_MapTable_c& mapTable,
TFV_FabricData_c* pfabricData ) const
{
// Copy given pin's map table, if any, to fabric pin's map table
pfabricData->AddMap( mapTable );
}
//===========================================================================//
// Method : UpdatePinList_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::UpdatePinList_(
const TGS_Region_c& region,
TC_SideMode_t onlySide,
TFV_DataType_t dataType,
const t_type_descriptor vpr_type,
TFV_FabricView_c* pfabricView ) const
{
TGS_Layer_t layer = this->MapDataTypeToLayer_( dataType );
TFV_FabricData_c* pfabricData = 0;
if( pfabricView->Find( layer, region, &pfabricData ))
{
this->UpdatePinList_( region, onlySide, vpr_type, pfabricData );
}
}
//===========================================================================//
void TVPR_FabricModel_c::UpdatePinList_(
const TGS_Region_c& region,
TC_SideMode_t onlySide,
const t_type_descriptor vpr_type,
TFV_FabricData_c* pfabricData ) const
{
// Decide initial slice size and index (for IO blocks with capacity)
unsigned int sliceCapacity = pfabricData->GetSliceCapacity( );
unsigned int sliceIndex = 0;
// Generate PB|IO's max pin count per side
unsigned int countArray[4];
this->CalcPinCountArray_( vpr_type,
&countArray[0] );
// Generate PB|IO's initial pin offset per side
double offsetArray[4];
this->CalcPinOffsetArray_( vpr_type, region, sliceIndex, countArray,
&offsetArray[0] );
// Iterate for all pins, assigning side and offset, then adding to region
for( int pinIndex = 0; pinIndex < vpr_type.num_pins; ++pinIndex )
{
if( vpr_type.is_global_pin[pinIndex] )
continue;
if(( sliceCapacity ) &&
( pinIndex / sliceCapacity != sliceIndex ))
{
// Recompute pin offset per side (for IO blocks with capacity)
sliceIndex = pinIndex / sliceCapacity;
this->CalcPinOffsetArray_( vpr_type, region, sliceIndex, countArray,
&offsetArray[0] );
}
for( int sideIndex = 0; sideIndex < 4; ++sideIndex )
{
if( onlySide != TC_SIDE_UNDEFINED )
{
TC_SideMode_t pinSide = FindPinSide_( sideIndex );
if( onlySide != pinSide )
continue;
}
for( int offsetIndex = 0; offsetIndex < vpr_type.height; ++offsetIndex )
{
if( !vpr_type.pinloc[offsetIndex][sideIndex][pinIndex] )
continue;
string srPinName;
this->FindPinName_( vpr_type, pinIndex, &srPinName );
TC_SideMode_t pinSide = this->FindPinSide_( sideIndex );
unsigned int pinSlice = ( sliceCapacity ? pinIndex / sliceCapacity : 0 );
double pinOffset = this->FindPinOffset_( sideIndex, &offsetArray[0] );
double pinWidth = TFV_MODEL_PIN_DEF_WIDTH;
TFV_FabricPin_c fabricPin( srPinName, pinSlice,
pinSide, pinOffset, pinWidth );
pfabricData->AddPin( fabricPin );
}
}
}
}
//===========================================================================//
// Method : BuildChannelDefaults_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::BuildChannelDefaults_(
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
double x1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double x2 = vpr_gridDims.dx - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y2 = vpr_gridDims.dy - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
// Generate initial 0-width channels based on given VPR grid dimensions
for( int y = 0; y < vpr_gridDims.dy - 1; ++y )
{
TGS_Region_c channelRegion( x1, y, x2, y );
channelRegion.ApplyShift( 0.5, TGS_ORIENT_HORIZONTAL );
char szName[TIO_FORMAT_STRING_LEN_DATA];
sprintf( szName, "ch[%d]", y );
this->AddFabricViewRegion_( channelRegion, TFV_DATA_CHANNEL_HORZ,
szName, pfabricView );
}
for( int x = 0; x < vpr_gridDims.dx - 1; ++x )
{
TGS_Region_c channelRegion( x, y1, x, y2 );
channelRegion.ApplyShift( 0.5, TGS_ORIENT_VERTICAL );
char szName[TIO_FORMAT_STRING_LEN_DATA];
sprintf( szName, "cv[%d]", x );
this->AddFabricViewRegion_( channelRegion, TFV_DATA_CHANNEL_VERT,
szName, pfabricView );
}
}
//===========================================================================//
// Method : UpdateChannelCounts_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::UpdateChannelCounts_(
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
const TFV_FabricView_c& fabricView ) const
{
// Iterate for all VPR internal rr_node CHANX|CHANY nodes,
// in order to update max track count for asso. fabric channels
for( int i = 0; i < vpr_rrNodeCount; ++i )
{
const t_rr_node& vpr_rrNode = vpr_rrNodeArray[i];
if(( vpr_rrNode.type != CHANX ) && ( vpr_rrNode.type != CHANY ))
continue;
TGS_Region_c channelRegion;
this->FindChannelRegion_( vpr_rrNode, fabricView, &channelRegion );
TFV_LayerType_t channelLayer = ( vpr_rrNode.type == CHANX ?
TFV_LAYER_CHANNEL_HORZ : TFV_LAYER_CHANNEL_VERT );
TFV_FabricFigure_t* pfabricFigure = 0;
if( !fabricView.IsSolidAll( channelLayer, channelRegion, &pfabricFigure ))
continue;
TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
if( vpr_rrNode.type == CHANX )
{
unsigned int count = pfabricData->GetTrackHorzCount( );
unsigned int index = static_cast< int >( vpr_rrNode.ptc_num );
pfabricData->SetTrackHorzCount( TCT_Max( count, index + 1 ));
}
if( vpr_rrNode.type == CHANY )
{
unsigned int count = pfabricData->GetTrackVertCount( );
unsigned int index = static_cast< int >( vpr_rrNode.ptc_num );
pfabricData->SetTrackVertCount( TCT_Max( count, index + 1 ));
}
}
}
//===========================================================================//
// Method : ResizeChannelWidths_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ResizeChannelWidths_(
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
double x1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double x2 = vpr_gridDims.dx - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y2 = vpr_gridDims.dy - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
// Resize channel widths based on max track count (per each channel)
double segmentWidth = TFV_MODEL_SEGMENT_DEF_WIDTH;
double segmentSpacing = TFV_MODEL_SEGMENT_DEF_SPACING;
for( int y = 0; y < vpr_gridDims.dy - 1; ++y )
{
TGS_Region_c channelRegion( x1, y, x2, y );
channelRegion.ApplyShift( 0.5, TGS_ORIENT_HORIZONTAL );
TFV_FabricFigure_t* pfabricFigure = 0;
TGS_Layer_t channelLayer = TFV_LAYER_CHANNEL_HORZ;
if( !pfabricView->IsSolidAll( channelLayer, channelRegion, &pfabricFigure ))
continue;
TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
int count = pfabricData->GetTrackHorzCount( );
double dx = 0.0;
double dy = ( count * ( segmentWidth + segmentSpacing )) / 2.0;
TGS_Region_c replaceRegion( channelRegion, dx, dy, TGS_SNAP_MIN_GRID );
this->ReplaceFabricViewRegion_( channelRegion, replaceRegion,
*pfabricData, pfabricView );
}
for( int x = 0; x < vpr_gridDims.dx - 1; ++x )
{
TGS_Region_c channelRegion( x, y1, x, y2 );
channelRegion.ApplyShift( 0.5, TGS_ORIENT_VERTICAL );
TFV_FabricFigure_t* pfabricFigure = 0;
TGS_Layer_t channelLayer = TFV_LAYER_CHANNEL_VERT;
if( !pfabricView->IsSolidAll( channelLayer, channelRegion, &pfabricFigure ))
continue;
TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
int count = pfabricData->GetTrackVertCount( );
double dx = ( count * ( segmentWidth + segmentSpacing )) / 2.0;
double dy = 0.0;
TGS_Region_c replaceRegion( channelRegion, dx, dy, TGS_SNAP_MIN_GRID );
this->ReplaceFabricViewRegion_( channelRegion, replaceRegion,
*pfabricData, pfabricView );
}
}
//===========================================================================//
// Method : ResizeChannelLengths_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::ResizeChannelLengths_(
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
double x1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double x2 = vpr_gridDims.dx - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y2 = vpr_gridDims.dy - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
// Resize channel lengths based on orthogonal channels (per each channel)
for( int y = 0; y < vpr_gridDims.dy - 1; ++y )
{
TGS_Region_c channelRegion( x1, y, x2, y );
channelRegion.ApplyShift( 0.5, TGS_ORIENT_HORIZONTAL );
TFV_FabricFigure_t* pfabricFigure = 0;
TGS_Layer_t horzLayer = TFV_LAYER_CHANNEL_HORZ;
if( !pfabricView->IsSolidAll( horzLayer, channelRegion, &pfabricFigure ))
continue;
TGS_Region_c replaceRegion = pfabricFigure->GetRegion( );
const TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
TGS_Point_c lowerLeft = channelRegion.FindLowerLeft( );
TGS_Point_c upperRight = channelRegion.FindUpperRight( );
TGS_Region_c nearestRegion;
TGS_Layer_t vertLayer = TFV_LAYER_CHANNEL_VERT;
if( pfabricView->FindNearest( vertLayer, lowerLeft, &nearestRegion ))
{
replaceRegion.x1 = TCT_Min( replaceRegion.x1, nearestRegion.x2 );
}
if( pfabricView->FindNearest( vertLayer, upperRight, &nearestRegion ))
{
replaceRegion.x2 = TCT_Max( replaceRegion.x2, nearestRegion.x1 );
}
this->ReplaceFabricViewRegion_( channelRegion, replaceRegion,
*pfabricData, pfabricView );
}
for( int x = 0; x < vpr_gridDims.dx - 1; ++x )
{
TGS_Region_c channelRegion( x, y1, x, y2 );
channelRegion.ApplyShift( 0.5, TGS_ORIENT_VERTICAL );
TFV_FabricFigure_t* pfabricFigure = 0;
TGS_Layer_t vertLayer = TFV_LAYER_CHANNEL_VERT;
if( !pfabricView->IsSolidAll( vertLayer, channelRegion, &pfabricFigure ))
continue;
TGS_Region_c replaceRegion = pfabricFigure->GetRegion( );
const TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
TGS_Point_c lowerLeft = channelRegion.FindLowerLeft( );
TGS_Point_c upperRight = channelRegion.FindUpperRight( );
TGS_Region_c nearestRegion;
TGS_Layer_t horzLayer = TFV_LAYER_CHANNEL_HORZ;
if( pfabricView->FindNearest( horzLayer, lowerLeft, &nearestRegion ))
{
replaceRegion.y1 = TCT_Min( replaceRegion.y1, nearestRegion.y2 );
}
if( pfabricView->FindNearest( horzLayer, upperRight, &nearestRegion ))
{
replaceRegion.y2 = TCT_Max( replaceRegion.y2, nearestRegion.y1 );
}
this->ReplaceFabricViewRegion_( channelRegion, replaceRegion,
*pfabricData, pfabricView );
}
}
//===========================================================================//
// Method : BuildSwitchBoxes_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::BuildSwitchBoxes_(
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
const TGS_Region_c& fabricRegion = pfabricView->GetRegion( );
double x1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double x2 = vpr_gridDims.dx - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y1 = 1.0 - TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
double y2 = vpr_gridDims.dy - 2.0 + TFV_MODEL_PHYSICAL_BLOCK_DEF_WIDTH;
// Iterate based on VPR's grid to define switch box locations
for( int x = 0; x < vpr_gridDims.dx - 1; ++x )
{
// Find vertical channel asso. with next set of switch boxes
TGS_Region_c vertRegion( x, y1, x, y2 );
vertRegion.ApplyShift( 0.5, TGS_ORIENT_VERTICAL );
TFV_FabricFigure_t* pfabricFigure = 0;
TGS_Layer_t vertLayer = TFV_LAYER_CHANNEL_VERT;
if( !pfabricView->IsSolidAll( vertLayer, vertRegion, &pfabricFigure ))
continue;
vertRegion.Set( pfabricFigure->GetRegion( ).x1, fabricRegion.y1,
pfabricFigure->GetRegion( ).x2, fabricRegion.y2 );
unsigned int vertCount = pfabricFigure->GetData( )->GetTrackVertCount( );
for( int y = 0; y < vpr_gridDims.dy - 1; ++y )
{
// Find horizontal channel asso. with next set of switch boxes
TGS_Region_c horzRegion( x1, y, x2, y );
horzRegion.ApplyShift( 0.5, TGS_ORIENT_HORIZONTAL );
TGS_Layer_t horzLayer = TFV_LAYER_CHANNEL_HORZ;
if( !pfabricView->IsSolidAll( horzLayer, horzRegion, &pfabricFigure ))
continue;
horzRegion.Set( fabricRegion.x1, pfabricFigure->GetRegion( ).y1,
fabricRegion.x2, pfabricFigure->GetRegion( ).y2 );
unsigned int horzCount = pfabricFigure->GetData( )->GetTrackHorzCount( );
// Add switch box based on intersecting channel region
TGS_Region_c switchRegion;
switchRegion.ApplyIntersect( vertRegion, horzRegion );
char szName[TIO_FORMAT_STRING_LEN_DATA];
sprintf( szName, "sb[%d][%d]", x, y );
this->AddFabricViewRegion_( switchRegion, TFV_DATA_SWITCH_BOX,
szName, horzCount, vertCount, pfabricView );
}
}
}
//===========================================================================//
// Method : UpdateSwitchMapTables_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::UpdateSwitchMapTables_(
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
const TFV_FabricView_c& fabricView ) const
{
// Iterate for all VPR internal rr_node CHANX|CHANY nodes,
// in order to discover switch box mappings between CHANX|CHANY nodes
for( int i = 0; i < vpr_rrNodeCount; ++i )
{
const t_rr_node& vpr_rrNode1 = vpr_rrNodeArray[i];
if(( vpr_rrNode1.type != CHANX ) && ( vpr_rrNode1.type != CHANY ))
continue;
for( int j = 0; j < vpr_rrNode1.num_edges; ++j )
{
const t_rr_node& vpr_rrNode2 = vpr_rrNodeArray[vpr_rrNode1.edges[j]];
if(( vpr_rrNode2.type != CHANX ) && ( vpr_rrNode2.type != CHANY ))
continue;
TGS_Region_c segmentRegion1, segmentRegion2;
this->FindSegmentRegion_( vpr_rrNode1, fabricView, &segmentRegion1 );
this->FindSegmentRegion_( vpr_rrNode2, fabricView, &segmentRegion2 );
// Find nearest points between CHANX|CHANY regions
TGS_Point_c nearestPoint1, nearestPoint2;
segmentRegion1.FindNearest( segmentRegion2, &nearestPoint2, &nearestPoint1 );
// Find switch box asso. with CHANX|CHANY nearest points
TGS_Region_c nearestRegion( nearestPoint1, nearestPoint2 );
TFV_FabricFigure_t* pfabricFigure = 0;
TGS_Layer_t switchLayer = TFV_LAYER_SWITCH_BOX;
if( !fabricView.IsSolidAny( switchLayer, nearestRegion, &pfabricFigure ))
continue;
const TGS_Region_c& switchRegion = pfabricFigure->GetRegion( );
TC_SideMode_t side1 = this->FindSwitchSide_( vpr_rrNode1, TGS_DIR_PREV,
nearestPoint1, switchRegion );
unsigned int index1 = vpr_rrNode1.ptc_num;
TC_SideMode_t side2 = this->FindSwitchSide_( vpr_rrNode2, TGS_DIR_NEXT,
nearestPoint2, switchRegion );
unsigned int index2 = vpr_rrNode2.ptc_num;
TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
pfabricData->AddMap( side1, index1, side2, index2 );
}
}
}
//===========================================================================//
// Method : BuildConnectionBoxes_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::BuildConnectionBoxes_(
const TGS_IntDims_t& vpr_gridDims,
TFV_FabricView_c* pfabricView ) const
{
bool ok = true;
// Iterate for every PB|IO found within VPR's grid
for( int x = 0; x < vpr_gridDims.dx; ++x )
{
for( int y = 0; y < vpr_gridDims.dy; ++y )
{
// Get fabric's PB|IO figure (ie. region and asso. data)
TGS_Point_c point( x, y );
TFV_FabricFigure_t* pfabricFigure = 0;
if( !pfabricView->IsSolid( TFV_LAYER_INPUT_OUTPUT, point, &pfabricFigure ) &&
!pfabricView->IsSolid( TFV_LAYER_PHYSICAL_BLOCK, point, &pfabricFigure ))
{
continue;
}
// Iterate for every pin associated with this PB|IO figure
const TGS_Region_c& blockRegion = pfabricFigure->GetRegion( );
TFV_FabricData_c* pfabricData = pfabricFigure->GetData( );
const TFV_FabricPinList_t& fabricPinList = pfabricData->GetPinList( );
for( size_t i = 0; i < fabricPinList.GetLength( ); ++i )
{
const TFV_FabricPin_c& fabricPin = *fabricPinList[i];
// Define a connection box region spanning from pin to channel region
TGS_Region_c connectionRegion;
ok = this->BuildConnectionRegion_( *pfabricView, fabricPin,
blockRegion, &connectionRegion );
if( !ok )
break;
// Add connection box region to fabric view
this->AddFabricViewRegion_( connectionRegion, TFV_DATA_CONNECTION_BOX,
pfabricView );
}
if( !ok )
break;
}
if( !ok )
break;
}
return( ok );
}
//===========================================================================//
// Method : BuildConnectionRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::BuildConnectionRegion_(
const TFV_FabricView_c& fabricView,
const TFV_FabricPin_c& fabricPin,
const TGS_Region_c& blockRegion,
TGS_Region_c* pconnectionRegion ) const
{
pconnectionRegion->Reset( );
// Define a connection box spanning from pin to far side of neighboring channel
TFV_FabricData_c fabricData;
TGS_Point_c pinPoint = fabricData.CalcPoint( blockRegion, fabricPin );
TGS_Region_c channelRegion;
switch( fabricPin.GetSide( ))
{
case TC_SIDE_LEFT:
case TC_SIDE_RIGHT:
fabricView.FindNearest( TFV_LAYER_CHANNEL_VERT, pinPoint, &channelRegion );
pconnectionRegion->Set( TCT_Min( pinPoint.x, channelRegion.x1 ),
pinPoint.y,
TCT_Max( pinPoint.x, channelRegion.x2 ),
pinPoint.y );
break;
case TC_SIDE_LOWER:
case TC_SIDE_UPPER:
fabricView.FindNearest( TFV_LAYER_CHANNEL_HORZ, pinPoint, &channelRegion );
pconnectionRegion->Set( pinPoint.x,
TCT_Min( pinPoint.y, channelRegion.y1 ),
pinPoint.x,
TCT_Max( pinPoint.y, channelRegion.y2 ));
break;
default:
break;
}
if( pconnectionRegion->IsValid( ))
{
double scale = TFV_MODEL_CONNECTION_BOX_DEF_WIDTH / 2.0;
pconnectionRegion->ApplyScale( scale, TGS_SNAP_MIN_GRID );
}
return( pconnectionRegion->IsValid( ) ? true : false );
}
//===========================================================================//
// Method : UpdateConnectionPoints_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::UpdateConnectionPoints_(
const t_rr_node* vpr_rrNodeArray,
int vpr_rrNodeCount,
TFV_FabricView_c* pfabricView ) const
{
// Iterate for all VPR internal rr_nodes that indicate a connection box
// (ie. rr_nodes that span OPIN-->CHANX|CHANY or span CHANX|CHANY-->IPIN)
for( int i = 0; i < vpr_rrNodeCount; ++i )
{
const t_rr_node& vpr_rrNode1 = vpr_rrNodeArray[i];
if(( vpr_rrNode1.type != CHANX ) && ( vpr_rrNode1.type != CHANY ) &&
( vpr_rrNode1.type != IPIN ) && ( vpr_rrNode1.type != OPIN ))
continue;
for( int j = 0; j < vpr_rrNode1.num_edges; ++j )
{
const t_rr_node& vpr_rrNode2 = vpr_rrNodeArray[vpr_rrNode1.edges[j]];
if(( vpr_rrNode2.type != CHANX ) && ( vpr_rrNode2.type != CHANY ) &&
( vpr_rrNode2.type != IPIN ) && ( vpr_rrNode2.type != OPIN ))
continue;
// Handle connection boxes from output pins
if(( vpr_rrNode1.type == OPIN ) && ( vpr_rrNode2.type == CHANX ))
{
this->UpdateConnectionPoints_( vpr_rrNode1, vpr_rrNode2,
pfabricView );
}
if(( vpr_rrNode1.type == OPIN ) && ( vpr_rrNode2.type == CHANY ))
{
this->UpdateConnectionPoints_( vpr_rrNode1, vpr_rrNode2,
pfabricView );
}
// Handle connection boxes to input pins
if(( vpr_rrNode1.type == CHANX ) && ( vpr_rrNode2.type == IPIN ))
{
this->UpdateConnectionPoints_( vpr_rrNode2, vpr_rrNode1,
pfabricView );
}
if(( vpr_rrNode1.type == CHANY ) && ( vpr_rrNode2.type == IPIN ))
{
this->UpdateConnectionPoints_( vpr_rrNode2, vpr_rrNode1,
pfabricView );
}
}
}
}
//===========================================================================//
void TVPR_FabricModel_c::UpdateConnectionPoints_(
const t_rr_node& vpr_rrNodePin,
const t_rr_node& vpr_rrNodeChan,
TFV_FabricView_c* pfabricView ) const
{
// Determine pin name based on IPIN|OPIN node
string srPinName;
this->FindPinName_( vpr_rrNodePin.pb_graph_pin, &srPinName );
if( srPinName.length( ))
{
// Determine pin side based on IPIN|OPIN node wrt CHANX|CHANY node
TC_SideMode_t pinSide = this->FindPinSide_( vpr_rrNodePin, vpr_rrNodeChan );
// Find pin from PB|IO based on the extracted pin name and pin side
TGS_Region_c blockRegion;
TFV_FabricData_c* pfabricData = 0;
if( this->FindBlockRegion_( vpr_rrNodePin, *pfabricView,
&blockRegion, &pfabricData ))
{
const TFV_FabricPinList_t& pinList = pfabricData->GetPinList( );
int sliceCount = static_cast< int >( TCT_Max( pfabricData->GetSliceCount( ), 1u ));
for( int sliceIndex = 0; sliceIndex < sliceCount; ++sliceIndex )
{
TFV_FabricPin_c pin( srPinName, sliceIndex, pinSide );
if( pinList.IsMember( pin ))
{
TFV_FabricPin_c* ppin = pinList[pin];
// Find asso. track index based on CHANX|CHANY node
unsigned int trackIndex = static_cast< int >( vpr_rrNodeChan.ptc_num );
// Update pin's connection box list per asso. side and track index
TFV_Connection_t connection( pinSide, trackIndex );
ppin->AddConnection( connection );
// And, update pin's channel count based on nearest channel width
TGS_Point_c pinPoint = pfabricData->CalcPoint( blockRegion, *ppin );
unsigned int channelCount = 0;
channelCount = this->FindChannelCount_( *pfabricView, pinPoint, pinSide );
ppin->SetChannelCount( channelCount );
// Update fabric view's connection box layer per asso. track index
TGS_Layer_t connectionLayer = TFV_LAYER_CONNECTION_BOX;
TFV_FabricFigure_t* pfabricFigure = 0;
if( pfabricView->IsSolid( connectionLayer, pinPoint, &pfabricFigure ))
{
// Update connection box figure per asso. side and track index
pfabricData = pfabricFigure->GetData( );
pfabricData->AddConnection( connection );
}
}
}
}
}
}
//===========================================================================//
// Method : CalcMaxPinCount_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
unsigned int TVPR_FabricModel_c::CalcMaxPinCount_(
t_grid_tile** vpr_gridArray,
const TGS_IntDims_t& vpr_gridDims ) const
{
unsigned int maxPins = 0;
for( int x = 0; x < vpr_gridDims.dx; ++x )
{
for( int y = 0; y < vpr_gridDims.dy; ++y )
{
if( vpr_gridArray[x][y].type != FILL_TYPE )
continue;
t_type_descriptor vpr_type = *grid[x][y].type;
unsigned int typePins = this->CalcMaxPinCount_( vpr_type );
maxPins = TCT_Max( maxPins, typePins );
}
}
return( maxPins );
}
//===========================================================================//
unsigned int TVPR_FabricModel_c::CalcMaxPinCount_(
const t_type_descriptor vpr_type ) const
{
unsigned int countArray[4];
this->CalcPinCountArray_( vpr_type, countArray );
return( TCT_Max( TCT_Max( countArray[0], countArray[1] ),
TCT_Max( countArray[2], countArray[3] )));
}
//===========================================================================//
// Method : CalcPinCountArray_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::CalcPinCountArray_(
const t_type_descriptor vpr_type,
unsigned int* pcountArray ) const
{
for( int sideIndex = 0; sideIndex < 4; ++sideIndex )
{
*( pcountArray + sideIndex ) = 0;
}
for( int pinIndex = 0; pinIndex < vpr_type.num_pins; ++pinIndex )
{
if( vpr_type.is_global_pin[pinIndex] )
continue;
for( int sideIndex = 0; sideIndex < 4; ++sideIndex )
{
for( int offsetIndex = 0; offsetIndex < vpr_type.height; ++offsetIndex )
{
if( !vpr_type.pinloc[offsetIndex][sideIndex][pinIndex] )
continue;
++*( pcountArray + sideIndex );
}
}
}
if( vpr_type.capacity > 1 )
{
for( int sideIndex = 0; sideIndex < 4; ++sideIndex )
{
*( pcountArray + sideIndex ) /= vpr_type.capacity;
}
}
}
//===========================================================================//
// Method : CalcPinOffsetArray_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::CalcPinOffsetArray_(
const t_type_descriptor vpr_type,
const TGS_Region_c& region,
unsigned int index,
const unsigned int* pcountArray,
double* poffsetArray ) const
{
TGS_Point_c regionCenter = region.FindCenter( TGS_SNAP_MIN_GRID );
if( vpr_type.capacity > 1 )
{
double dx = region.GetDx( ) / ( vpr_type.capacity ? vpr_type.capacity : 1 );
double dy = region.GetDy( ) / ( vpr_type.capacity ? vpr_type.capacity : 1 );
TGS_Region_c region_( region.x1, region.y1, region.x1 + dx, region.y1 + dy );
regionCenter = region_.FindCenter( TGS_SNAP_MIN_GRID );
}
double pinWidth = TFV_MODEL_PIN_DEF_WIDTH;
double pinSpacing = TFV_MODEL_PIN_DEF_SPACING;
for( int sideIndex = 0; sideIndex < 4; ++sideIndex )
{
unsigned int count = *( pcountArray + sideIndex );
double offset = 0.0;
switch( sideIndex ) // Based on VPR's e_side enumeration values...
{
case LEFT:
case RIGHT:
offset = regionCenter.y - count / 2 * ( pinWidth + pinSpacing ) - region.y1;
offset += index * ( region.GetDx( ) / ( vpr_type.capacity ? vpr_type.capacity : 1 ));
break;
case BOTTOM:
case TOP:
offset = regionCenter.x - count / 2 * ( pinWidth + pinSpacing ) - region.x1;
offset += index * ( region.GetDy( ) / ( vpr_type.capacity ? vpr_type.capacity : 1 ));
break;
default:
break;
}
*( poffsetArray + sideIndex ) = offset;
}
}
//===========================================================================//
// Method : FindPinName_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
void TVPR_FabricModel_c::FindPinName_(
const t_type_descriptor vpr_type,
int pinIndex,
string* psrString ) const
{
const t_pb_type& vpr_pb_type = *vpr_type.pb_type;
const t_pb_graph_node& vpr_pb_graph_node = *vpr_type.pb_graph_head;
pinIndex %= ( vpr_pb_type.num_input_pins +
vpr_pb_type.num_output_pins +
vpr_pb_type.num_clock_pins );
if( pinIndex < vpr_pb_type.num_input_pins )
{
for( int i = 0; i < vpr_pb_graph_node.num_input_ports; ++i )
{
if( pinIndex < vpr_pb_graph_node.num_input_pins[i] )
{
const t_pb_graph_pin* pvpr_pb_graph_pin = &vpr_pb_graph_node.input_pins[i][pinIndex];
if( pvpr_pb_graph_pin )
{
this->FindPinName_( pvpr_pb_graph_pin, psrString );
}
break;
}
pinIndex -= vpr_pb_graph_node.num_input_pins[i];
}
}
else if ( pinIndex < vpr_pb_type.num_input_pins + vpr_pb_type.num_output_pins )
{
pinIndex -= vpr_pb_type.num_input_pins;
for( int i = 0; i < vpr_pb_graph_node.num_output_ports; ++i )
{
if( pinIndex < vpr_pb_graph_node.num_output_pins[i] )
{
const t_pb_graph_pin* pvpr_pb_graph_pin = &vpr_pb_graph_node.output_pins[i][pinIndex];
if( pvpr_pb_graph_pin )
{
this->FindPinName_( pvpr_pb_graph_pin, psrString );
}
break;
}
pinIndex -= vpr_pb_graph_node.num_output_pins[i];
}
}
else
{
pinIndex -= vpr_pb_type.num_input_pins + vpr_pb_type.num_output_pins;
for( int i = 0; i < vpr_pb_graph_node.num_clock_ports; ++i )
{
if( pinIndex < vpr_pb_graph_node.num_clock_pins[i] )
{
const t_pb_graph_pin* pvpr_pb_graph_pin = &vpr_pb_graph_node.clock_pins[i][pinIndex];
if( pvpr_pb_graph_pin )
{
this->FindPinName_( pvpr_pb_graph_pin, psrString );
}
break;
}
pinIndex -= vpr_pb_graph_node.num_clock_pins[i];
}
}
}
//===========================================================================//
void TVPR_FabricModel_c::FindPinName_(
const t_pb_graph_pin* pvpr_pb_graph_pin,
string* psrPinName ) const
{
if( psrPinName )
{
if( pvpr_pb_graph_pin &&
pvpr_pb_graph_pin->port &&
pvpr_pb_graph_pin->port->name )
{
const char* pszName = pvpr_pb_graph_pin->port->name;
char szIndex[TIO_FORMAT_STRING_LEN_VALUE];
sprintf( szIndex, "%d", pvpr_pb_graph_pin->pin_number );
*psrPinName = pszName;
*psrPinName += "[";
*psrPinName += szIndex;
*psrPinName += "]";
}
}
}
//===========================================================================//
// Method : FindPinSide_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
TC_SideMode_t TVPR_FabricModel_c::FindPinSide_(
int side ) const
{
TC_SideMode_t pinSide = TC_SIDE_UNDEFINED;
switch( side )
{
case LEFT: pinSide = TC_SIDE_LEFT; break;
case RIGHT: pinSide = TC_SIDE_RIGHT; break;
case BOTTOM: pinSide = TC_SIDE_LOWER; break;
case TOP: pinSide = TC_SIDE_UPPER; break;
default: break;
}
return( pinSide );
}
//===========================================================================//
TC_SideMode_t TVPR_FabricModel_c::FindPinSide_(
const t_rr_node& vpr_rrNodePin,
const t_rr_node& vpr_rrNodeChan ) const
{
TC_SideMode_t pinSide = TC_SIDE_UNDEFINED;
if(( vpr_rrNodePin.type == IPIN ) || ( vpr_rrNodePin.type == OPIN ))
{
if( vpr_rrNodeChan.type == CHANX )
{
if( vpr_rrNodeChan.ylow < vpr_rrNodePin.ylow )
{
pinSide = TC_SIDE_LOWER;
}
else // if( vpr_rrNodeChan.ylow == vpr_rrNodePin.ylow )
{
pinSide = TC_SIDE_UPPER;
}
}
if( vpr_rrNodeChan.type == CHANY )
{
if( vpr_rrNodeChan.xlow < vpr_rrNodePin.xlow )
{
pinSide = TC_SIDE_LEFT;
}
else // if( vpr_rrNodeChan.xlow == vpr_rrNodePin.xlow )
{
pinSide = TC_SIDE_RIGHT;
}
}
}
return( pinSide );
}
//===========================================================================//
// Method : FindPinOffset_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
double TVPR_FabricModel_c::FindPinOffset_(
int side,
double* poffsetArray ) const
{
double pinWidth = TFV_MODEL_PIN_DEF_WIDTH;
double pinSpacing = TFV_MODEL_PIN_DEF_SPACING;
double pinOffset = *( poffsetArray + side );
*( poffsetArray + side ) += pinWidth + pinSpacing;
return( pinOffset );
}
//===========================================================================//
// Method : FindChannelCount_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
unsigned int TVPR_FabricModel_c::FindChannelCount_(
const TFV_FabricView_c& fabricView,
const TGS_Point_c& point,
TC_SideMode_t side ) const
{
unsigned int channelCount = 0;
TGS_Layer_t channelLayer = TFV_LAYER_UNDEFINED;
switch( side )
{
case TC_SIDE_LEFT:
case TC_SIDE_RIGHT: channelLayer = TFV_LAYER_CHANNEL_VERT; break;
case TC_SIDE_LOWER:
case TC_SIDE_UPPER: channelLayer = TFV_LAYER_CHANNEL_HORZ; break;
default: break;
}
TGS_Region_c channelRegion;
if( fabricView.FindNearest( channelLayer, point, &channelRegion ))
{
TFV_FabricData_c* pfabricData = 0;
fabricView.Find( channelLayer, channelRegion, &pfabricData );
switch( side )
{
case TC_SIDE_LEFT:
case TC_SIDE_RIGHT: channelCount = pfabricData->GetTrackVertCount( ); break;
case TC_SIDE_LOWER:
case TC_SIDE_UPPER: channelCount = pfabricData->GetTrackHorzCount( ); break;
default: break;
}
}
return( channelCount );
}
//===========================================================================//
// Method : FindChannelRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::FindChannelRegion_(
const t_rr_node& vpr_rrNode,
const TFV_FabricView_c& fabricView,
TGS_Region_c* pregion,
TFV_FabricData_c** ppfabricData ) const
{
TFV_LayerType_t layer = ( vpr_rrNode.type == CHANX ?
TFV_LAYER_CHANNEL_HORZ : TFV_LAYER_CHANNEL_VERT );
bool applyShift = true;
bool applyTrack = false;
return( this->FindNodeRegion_( vpr_rrNode, fabricView,
layer, pregion, ppfabricData,
applyShift, applyTrack ));
}
//===========================================================================//
// Method : FindSegmentRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::FindSegmentRegion_(
const t_rr_node& vpr_rrNode,
const TFV_FabricView_c& fabricView,
TGS_Region_c* pregion,
TFV_FabricData_c** ppfabricData ) const
{
TFV_LayerType_t layer = ( vpr_rrNode.type == CHANX ?
TFV_LAYER_CHANNEL_HORZ : TFV_LAYER_CHANNEL_VERT );
bool applyShift = true;
bool applyTrack = true;
return( this->FindNodeRegion_( vpr_rrNode, fabricView,
layer, pregion, ppfabricData,
applyShift, applyTrack ));
}
//===========================================================================//
// Method : FindBlockRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::FindBlockRegion_(
const t_rr_node& vpr_rrNode,
const TFV_FabricView_c& fabricView,
TGS_Region_c* pregion,
TFV_FabricData_c** ppfabricData ) const
{
pregion->Reset( );
TGS_Layer_t ioLayer = TFV_LAYER_INPUT_OUTPUT;
TGS_Layer_t pbLayer = TFV_LAYER_PHYSICAL_BLOCK;
bool applyShift = false;
bool applyTrack = false;
if( !this->FindNodeRegion_( vpr_rrNode, fabricView,
ioLayer, pregion, ppfabricData,
applyShift, applyTrack ))
{
this->FindNodeRegion_( vpr_rrNode, fabricView,
pbLayer, pregion, ppfabricData,
applyShift, applyTrack );
}
return( pregion->IsValid( ) ? true : false );
}
//===========================================================================//
// Method : FindNodeRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::FindNodeRegion_(
const t_rr_node& vpr_rrNode,
const TFV_FabricView_c& fabricView,
TGS_Layer_t layer,
TGS_Region_c* pregion,
TFV_FabricData_c** ppfabricData,
bool applyShift,
bool applyTrack ) const
{
TGS_Region_c region;
TFV_FabricData_c* pfabricData = 0;
TGS_OrientMode_t orient = ( vpr_rrNode.type == CHANX ?
TGS_ORIENT_HORIZONTAL : TGS_ORIENT_VERTICAL );
TGS_Region_c rrRegion( vpr_rrNode.xlow, vpr_rrNode.ylow,
vpr_rrNode.xhigh, vpr_rrNode.yhigh );
if( applyShift )
{
rrRegion.ApplyShift( 0.5, orient );
}
TFV_FabricFigure_t* pfabricFigure = 0;
if( fabricView.IsSolidAll( layer, rrRegion, &pfabricFigure ))
{
region = pfabricFigure->GetRegion( );
pfabricData = pfabricFigure->GetData( );
if( applyTrack )
{
unsigned int index = static_cast< int >( vpr_rrNode.ptc_num );
double track = pfabricData->CalcTrack( rrRegion, orient, index );
layer = TFV_LAYER_SWITCH_BOX;
TGS_Region_c prevRegion, nextRegion;
if( orient == TGS_ORIENT_HORIZONTAL )
{
fabricView.FindNearest( layer, rrRegion, TC_SIDE_LEFT, &prevRegion );
fabricView.FindNearest( layer, rrRegion, TC_SIDE_RIGHT, &nextRegion );
region.Set( prevRegion.x2, track, nextRegion.x1, track );
}
if( orient == TGS_ORIENT_VERTICAL )
{
fabricView.FindNearest( layer, rrRegion, TC_SIDE_LOWER, &prevRegion );
fabricView.FindNearest( layer, rrRegion, TC_SIDE_UPPER, &nextRegion );
region.Set( track, prevRegion.y2, track, nextRegion.y1 );
}
}
}
if( pregion )
{
*pregion = region;
}
if( ppfabricData )
{
*ppfabricData = pfabricData;
}
return( region.IsValid( ) ? true : false );
}
//===========================================================================//
// Method : FindSwitchSide_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
TC_SideMode_t TVPR_FabricModel_c::FindSwitchSide_(
const t_rr_node& vpr_rrNode,
TGS_DirMode_t refDir,
const TGS_Point_c& refPoint,
const TGS_Region_c& switchRegion ) const
{
TGS_Point_c nearestPoint( refPoint );
TC_MinGrid_c& MinGrid = TC_MinGrid_c::GetInstance( );
if( switchRegion.IsWithin( nearestPoint, MinGrid.GetGrid( )))
{
if( vpr_rrNode.type == CHANX )
{
if( vpr_rrNode.direction == INC_DIRECTION )
{
nearestPoint.x = ( refDir == TGS_DIR_PREV ?
switchRegion.x1 : switchRegion.x2 );
}
else // if( vpr_rrNode.direction == DEC_DIRECTION )
{
nearestPoint.x = ( refDir == TGS_DIR_PREV ?
switchRegion.x2 : switchRegion.x1 );
}
}
else // if( vpr_rrNode.type == CHANY )
{
if( vpr_rrNode.direction == INC_DIRECTION )
{
nearestPoint.y = ( refDir == TGS_DIR_PREV ?
switchRegion.y1 : switchRegion.y2 );
}
else // if( vpr_rrNode.direction == DEC_DIRECTION )
{
nearestPoint.y = ( refDir == TGS_DIR_PREV ?
switchRegion.y2 : switchRegion.y1 );
}
}
}
return( switchRegion.FindSide( nearestPoint ));
}
//===========================================================================//
// Method : MapDataTypeToLayer_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
TGS_Layer_t TVPR_FabricModel_c::MapDataTypeToLayer_(
TFV_DataType_t dataType ) const
{
TGS_Layer_t layer = TGS_LAYER_UNDEFINED;
switch( dataType )
{
case TFV_DATA_INPUT_OUTPUT: layer = TFV_LAYER_INPUT_OUTPUT; break;
case TFV_DATA_PHYSICAL_BLOCK: layer = TFV_LAYER_PHYSICAL_BLOCK; break;
case TFV_DATA_SWITCH_BOX: layer = TFV_LAYER_SWITCH_BOX; break;
case TFV_DATA_CONNECTION_BOX: layer = TFV_LAYER_CONNECTION_BOX; break;
case TFV_DATA_CHANNEL_HORZ: layer = TFV_LAYER_CHANNEL_HORZ; break;
case TFV_DATA_CHANNEL_VERT: layer = TFV_LAYER_CHANNEL_VERT; break;
case TFV_DATA_SEGMENT_HORZ: layer = TFV_LAYER_SEGMENT_HORZ; break;
case TFV_DATA_SEGMENT_VERT: layer = TFV_LAYER_SEGMENT_VERT; break;
default: break;
}
return( layer );
}
//===========================================================================//
// Method : MapDataTypeToBlockType_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
TFM_BlockType_t TVPR_FabricModel_c::MapDataTypeToBlockType_(
TFV_DataType_t dataType ) const
{
TFM_BlockType_t blockType = TFM_BLOCK_UNDEFINED;
switch( dataType )
{
case TFV_DATA_INPUT_OUTPUT: blockType = TFM_BLOCK_INPUT_OUTPUT; break;
case TFV_DATA_PHYSICAL_BLOCK: blockType = TFM_BLOCK_PHYSICAL_BLOCK; break;
case TFV_DATA_SWITCH_BOX: blockType = TFM_BLOCK_SWITCH_BOX; break;
default: break;
}
return( blockType );
}
//===========================================================================//
// Method : MapBlockTypeToDataType_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
TFV_DataType_t TVPR_FabricModel_c::MapBlockTypeToDataType_(
TFM_BlockType_t blockType ) const
{
TFV_DataType_t dataType = TFV_DATA_UNDEFINED;
switch( blockType )
{
case TFM_BLOCK_PHYSICAL_BLOCK: dataType = TFV_DATA_PHYSICAL_BLOCK; break;
case TFM_BLOCK_INPUT_OUTPUT: dataType = TFV_DATA_INPUT_OUTPUT; break;
case TFM_BLOCK_SWITCH_BOX: dataType = TFV_DATA_SWITCH_BOX; break;
default: break;
};
return( dataType );
};
//===========================================================================//
// Method : AddFabricViewRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::AddFabricViewRegion_(
const TGS_Region_c& region,
TFV_DataType_t dataType,
TFV_FabricView_c* pfabricView,
TFV_FabricData_c** ppfabricData ) const
{
TFV_FabricData_c fabricData( dataType );
return( this->AddFabricViewRegion_( region, fabricData,
pfabricView, ppfabricData ));
}
//===========================================================================//
bool TVPR_FabricModel_c::AddFabricViewRegion_(
const TGS_Region_c& region,
TFV_DataType_t dataType,
const char* pszName,
TFV_FabricView_c* pfabricView,
TFV_FabricData_c** ppfabricData ) const
{
TFV_FabricData_c fabricData( dataType );
fabricData.SetName( pszName );
return( this->AddFabricViewRegion_( region, fabricData,
pfabricView, ppfabricData ));
}
//===========================================================================//
bool TVPR_FabricModel_c::AddFabricViewRegion_(
const TGS_Region_c& region,
TFV_DataType_t dataType,
const char* pszName,
const char* pszMasterName,
unsigned int sliceCount,
unsigned int sliceCapacity,
TFV_FabricView_c* pfabricView,
TFV_FabricData_c** ppfabricData ) const
{
TFV_FabricData_c fabricData( dataType );
fabricData.SetName( pszName );
fabricData.SetMasterName( pszMasterName );
fabricData.SetSliceCount( sliceCount );
fabricData.SetSliceCapacity( sliceCapacity );
return( this->AddFabricViewRegion_( region, fabricData,
pfabricView, ppfabricData ));
}
//===========================================================================//
bool TVPR_FabricModel_c::AddFabricViewRegion_(
const TGS_Region_c& region,
TFV_DataType_t dataType,
const char* pszName,
unsigned int trackHorzCount,
unsigned int trackVertCount,
TFV_FabricView_c* pfabricView,
TFV_FabricData_c** ppfabricData ) const
{
TFV_FabricData_c fabricData( dataType );
fabricData.SetName( pszName );
fabricData.SetTrackHorzCount( trackHorzCount );
fabricData.SetTrackVertCount( trackVertCount );
fabricData.InitMapTable( trackHorzCount, trackVertCount );
return( this->AddFabricViewRegion_( region, fabricData,
pfabricView, ppfabricData ));
}
//===========================================================================//
bool TVPR_FabricModel_c::AddFabricViewRegion_(
const TGS_Region_c& region,
TFV_DataType_t dataType,
const char* pszName,
unsigned int trackIndex,
TFV_FabricView_c* pfabricView,
TFV_FabricData_c** ppfabricData ) const
{
TFV_FabricData_c fabricData( dataType );
fabricData.SetName( pszName );
fabricData.SetTrackIndex( trackIndex );
return( this->AddFabricViewRegion_( region, fabricData,
pfabricView, ppfabricData ));
}
//===========================================================================//
bool TVPR_FabricModel_c::AddFabricViewRegion_(
const TGS_Region_c& region,
const TFV_FabricData_c& fabricData,
TFV_FabricView_c* pfabricView,
TFV_FabricData_c** ppfabricData ) const
{
TGS_Layer_t layer = this->MapDataTypeToLayer_( fabricData.GetDataType( ));
bool ok = pfabricView->Add( layer, region, fabricData );
if( ok )
{
if( ppfabricData )
{
pfabricView->Find( layer, region, ppfabricData );
}
}
return( ok );
}
//===========================================================================//
// Method : ReplaceFabricViewRegion_
// Author : Jeff Rudolph
//---------------------------------------------------------------------------//
// Version history
// 08/25/12 jeffr : Original
//===========================================================================//
bool TVPR_FabricModel_c::ReplaceFabricViewRegion_(
const TGS_Region_c& region,
const TGS_Region_c& region_,
const TFV_FabricData_c& fabricData,
TFV_FabricView_c* pfabricView ) const
{
TFV_FabricData_c fabricData_( fabricData );
TGS_Layer_t layer = this->MapDataTypeToLayer_( fabricData.GetDataType( ));
pfabricView->Delete( layer, region );
return( pfabricView->Add( layer, region_, fabricData_ ));
}
| 38.476129 | 102 | 0.527695 | [
"model"
] |
91dd74c9e286c9d5fb155b4ff889f693cc87b09c | 3,417 | cpp | C++ | TotalSTL/src/iterator/auxiliary_functions/auxiliary_iterator_func_test.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | 15 | 2015-11-04T12:53:23.000Z | 2021-08-10T09:53:12.000Z | TotalSTL/src/iterator/auxiliary_functions/auxiliary_iterator_func_test.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | null | null | null | TotalSTL/src/iterator/auxiliary_functions/auxiliary_iterator_func_test.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | 6 | 2015-11-13T10:17:01.000Z | 2020-05-14T07:25:48.000Z | #include "gtest/gtest.h"
#include "inc.h"
#include "stl_headers.h"
#include <functional>
#include <algorithm>
#include <array>
#include <iterator>
NS_BEGIN(elloop);
using namespace std;
using namespace std::placeholders;
//----------------------- Advance ----------------------
BEGIN_TEST(AuxiliaryIterFuncTest, Advance, @);
array<int, 5> a = {{1, 2, 3, 4, 5}};
printContainer(a, "a: ");
auto iter = a.begin();
EXPECT_EQ(1, *iter);
advance(iter, 1); // iter is changed.
EXPECT_EQ(2, *iter);
advance(iter, 2);
EXPECT_EQ(4, *iter);
advance(iter, -1); // go backward 1.
EXPECT_EQ(3, *iter);
advance(iter, -2); // go backward 2.
EXPECT_EQ(1, *iter);
iter = a.begin();
pln("advance pass the end()");
//advance(iter, 100); // undefined behaviour.
//advance(iter, -100); // undefined behaviour.
END_TEST;
//----------------------- next ----------------------
// next(pos, n) calls advance(pos, n) for an internal temporary object.
BEGIN_TEST(AuxiliaryIterFuncTest, Next, @);
array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
printContainer(a, "a: ");
auto iter = a.begin();
EXPECT_EQ(1, *iter);
auto pos2 = next(iter, 1); // iter is not changed.
EXPECT_EQ(1, *iter);
EXPECT_EQ(2, *pos2);
auto pos3 = next(pos2); // default n = 1
EXPECT_EQ(2, *pos2);
EXPECT_EQ(3, *pos3);
auto pos5 = next(iter, 4); // iter + 4
EXPECT_EQ(5, *pos5);
auto pos4 = next(pos5, -1);
EXPECT_EQ(4, *pos4);
auto pos1 = next(pos5, -4);
EXPECT_EQ(1, *pos1);
//auto posPassEnd = next(iter, 100); // error, undefined behaviour.
//auto posBeforeBegin = next(iter, -100); // error, undefined behaviour.
END_TEST;
//----------------------- prev ----------------------
// prev(pos, n) calls advance(pos, -n) for an internal temporary object.
BEGIN_TEST(AuxiliaryIterFuncTest, Prev, @);
array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
printContainer(a, "a: ");
auto last = prev(a.end()); // call prev with end() is ok.
EXPECT_EQ(5, *last);
auto last2 = prev(a.end(), 2); // call prev with end() is ok.
EXPECT_EQ(4, *last2);
auto iter = a.begin();
auto pos2 = prev(iter, -1); // move forward use prev.
EXPECT_EQ(2, *pos2);
//auto posBeforeBegin = prev(a.begin(), 1); // error: undefined behaviour.
END_TEST;
//----------------------- distance ----------------------
BEGIN_TEST(AuxiliaryIterFuncTest, Distance, @);
array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
printContainer(a, "a: ");
auto pos2 = find(a.begin(), a.end(), 2);
auto pos5 = find(a.begin(), a.end(), 5);
//array<int, 5>::difference_type dis = distance(pos2, pos5);
auto dis = distance(pos2, pos5);
psln(dis); // dis = 3
EXPECT_EQ(5 - 2, dis);
auto negativeDis = distance(pos5, pos2);
psln(negativeDis); // negativeDis = -3
EXPECT_EQ(2 - 5, negativeDis);
END_TEST;
//----------------------- iter_swap ----------------------
BEGIN_TEST(AuxiliaryIterFuncTest, Iter_swap, @);
array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
printContainer(a, "a: "); // 1 2 3
iter_swap(a.begin(), next(a.begin()));
printContainer(a, "a: "); // 2 1 3
list<int> l = { 10, 11, 12};
printContainer(l, "l: ");
iter_swap(a.begin(), l.begin());
printContainer(a, "after swap, a: "); // 10 1 3
printContainer(l, "after swap, l: "); // 2 11 12
END_TEST;
NS_END(elloop);
| 22.629139 | 77 | 0.552824 | [
"object"
] |
91ded47e10e60e46f08be60bf83996b982c58c24 | 4,725 | cc | C++ | mysql-server/unittest/gunit/innodb/lob/ut0frags.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/unittest/gunit/innodb/lob/ut0frags.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/unittest/gunit/innodb/lob/ut0frags.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*****************************************************************************
Copyright (c) 2016, 2017, Oracle and/or its affiliates. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License, version 2.0, as published by the
Free Software Foundation.
This program is also distributed with certain software (including but not
limited to OpenSSL) that is licensed under separate terms, as designated in a
particular file or component or in included license documentation. The authors
of MySQL hereby grant you an additional permission to link the program and
your derivative works with the separately licensed software that they have
included with MySQL.
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, version 2.0,
for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
#include <list>
#include <vector>
#include "zlob0int.h"
using namespace zlob;
void line() { std::cout << " - - - - - - - - - - - " << std::endl; }
void basic_0() {
zlob::z_frag_page_t frag_page;
frag_page.print(std::cout);
frag_page.alloc();
frag_page.print(std::cout);
}
void basic_1() {
zlob::z_frag_page_t frag_page;
line();
frag_page.print(std::cout);
frag_page.alloc();
line();
frag_page.print(std::cout);
frag_page.alloc_fragment(100);
line();
frag_page.print(std::cout);
}
void basic_2() {
zlob::z_frag_page_t frag_page;
line();
frag_page.print(std::cout);
frag_page.alloc();
line();
frag_page.print(std::cout);
ulint frag = frag_page.alloc_fragment(100);
line();
frag_page.print(std::cout);
frag_page.dealloc_fragment(frag);
line();
frag_page.print(std::cout);
}
void basic_3() {
zlob::z_frag_page_t frag_page;
frag_page.alloc();
line();
frag_page.print(std::cout);
std::list<ulint> fragments;
for (int i = 0; i < 5; ++i) {
ulint frag = frag_page.alloc_fragment(100);
fragments.push_back(frag);
}
line();
frag_page.print(std::cout);
while (!fragments.empty()) {
frag_page.dealloc_fragment(fragments.front());
fragments.pop_front();
}
line();
frag_page.print(std::cout);
}
void basic_4() {
zlob::z_frag_page_t frag_page;
frag_page.alloc();
line();
frag_page.print(std::cout);
std::list<ulint> fragments;
ulint frag = frag_page.alloc_fragment(100);
while (frag != FRAG_ID_NULL) {
fragments.push_back(frag);
frag = frag_page.alloc_fragment(100);
}
line();
frag_page.print(std::cout);
while (!fragments.empty()) {
frag_page.dealloc_fragment(fragments.front());
fragments.pop_front();
}
line();
frag_page.print(std::cout);
}
void basic_5() {
zlob::z_frag_page_t frag_page;
frag_page.alloc();
line();
frag_page.print(std::cout);
std::list<ulint> fragments;
ulint frag = frag_page.alloc_fragment(100);
while (frag != FRAG_ID_NULL) {
fragments.push_back(frag);
frag = frag_page.alloc_fragment(100);
}
frag = frag_page.alloc_fragment(32);
if (frag != FRAG_ID_NULL) {
fragments.push_back(frag);
}
line();
frag_page.print(std::cout);
while (!fragments.empty()) {
frag_page.dealloc_fragment(fragments.front());
fragments.pop_front();
}
line();
frag_page.print(std::cout);
}
void basic_6() {
zlob::z_frag_page_t frag_page;
frag_page.alloc();
line();
frag_page.print(std::cout);
std::vector<frag_id_t> fragments;
ulint frag = frag_page.alloc_fragment(100);
while (frag != FRAG_ID_NULL) {
fragments.push_back(frag);
frag = frag_page.alloc_fragment(100);
}
line();
frag_page.print(std::cout);
for (ulint i = 0; i < fragments.size(); i += 2) {
frag_page.dealloc_fragment(fragments[i]);
}
line();
frag_page.print(std::cout);
}
void test7() {
zlob::z_frag_page_t frag_page;
frag_page.alloc();
frag_id_t f1 = frag_page.alloc_fragment(5692);
ut_ad(f1 != FRAG_ID_NULL);
std::cout << "ONE" << std::endl;
frag_page.print(std::cout);
frag_id_t f2 = frag_page.alloc_fragment(433);
ut_ad(f2 != FRAG_ID_NULL);
std::cout << "TWO" << std::endl;
frag_page.print(std::cout);
frag_id_t f3 = frag_page.alloc_fragment(419);
ut_ad(f3 != FRAG_ID_NULL);
frag_node_t node3 = frag_page.get_frag_node(f3);
std::cout << node3 << std::endl;
}
int main() { test7(); }
| 21.09375 | 78 | 0.665608 | [
"vector"
] |
91e3f2905c48b309769b0b9eb6ef08618c48b083 | 6,854 | cpp | C++ | arch/Player.cpp | pettro98/BotsGame | d6bc91e277a1599ae7e0fe22df6cc73fce17d9d1 | [
"MIT"
] | null | null | null | arch/Player.cpp | pettro98/BotsGame | d6bc91e277a1599ae7e0fe22df6cc73fce17d9d1 | [
"MIT"
] | null | null | null | arch/Player.cpp | pettro98/BotsGame | d6bc91e277a1599ae7e0fe22df6cc73fce17d9d1 | [
"MIT"
] | 1 | 2018-02-26T09:24:15.000Z | 2018-02-26T09:24:15.000Z | #include "Player.h"
namespace game_module
{
Player::Player(hex_color color, const std::string & player_name)
: Color(color)
, Name(player_name)
{ }
hex_color Player::color() const
{
return Color;
}
std::string Player::name() const
{
return Name;
}
size_type Player::get_capitals_number() const
{
return Capitals.size();
}
std::list<Pair> Player::get_capitals() const
{
return Capitals;
}
bool Player::operator == (const Player & player) const
{
return Color == player.color();
}
hex_color Player::color(const Pair & hex) const
{
return GameController->color(hex);
}
Pair Player::capital(const Pair & hex) const
{
return GameController->capital(hex);
}
size_type Player::distance(const Pair & hex1, const Pair & hex2) const
{
return GameController->distance(hex1, hex2);
}
unit_type Player::get_type(const Pair & hex) const
{
return GameController->get_type(hex);
}
size_type Player::get_unit_strength(const Pair & hex) const
{
return GameController->get_unit_strength(hex);
}
size_type Player::get_hex_strength(const Pair & hex) const
{
return GameController->get_hex_strength(hex);
}
bool Player::get_moved(const Pair & hex) const
{
return GameController->get_moved(hex);
}
size_type Player::get_district_money(const Pair & hex) const
{
return GameController->get_district_money(hex);
}
size_type Player::get_district_income(const Pair & hex) const
{
return GameController->get_district_income(hex);
}
size_type Player::get_farms_number(const Pair & hex) const
{
return GameController->get_farms_number(hex);
}
std::string Player::get_map_type() const
{
return GameController->get_map_type();
}
size_type Player::get_map_dimension_x() const
{
return GameController->get_map_dimension_x();
}
size_type Player::get_map_dimension_y() const
{
return GameController->get_map_dimension_y();
}
size_type Player::get_players_number() const
{
return GameController->get_players_number();
}
std::vector<hex_color> Player::get_players_colors() const
{
return GameController->get_players_colors();
}
std::list<Pair> Player::get_player_capitals(hex_color color) const
{
return GameController->get_player_capitals(color);
}
size_type Player::get_current_turn() const
{
return GameController->get_current_turn();
}
size_type Player::get_max_turns() const
{
return GameController->get_max_turns();
}
bool Player::can_move(const Pair & hex1, const Pair & hex2) const
{
return GameController->can_move(hex1, hex2, Army::move_points());
}
bool Player::can_place_tower(const Pair & hex) const
{
return GameController->can_place_tower(hex);
}
bool Player::can_place_farm(const Pair & hex) const
{
return GameController->can_place_farm(hex);
}
bool Player::can_place_army(const Pair & hex, size_type strength) const
{
return GameController->can_place_army(hex, strength);
}
std::vector<Pair> Player::hexs_to_place_farm(const Pair & hex) const
{
return GameController->hexs_to_place_farm(hex);
}
std::vector<Pair> Player::hexs_to_move_army(const Pair & hex) const
{
return GameController->hexs_to_move_army(hex);
}
std::vector<Pair> Player::get_district_units(const Pair & hex, unit_type type) const
{
return GameController->get_district_units(hex, type);
}
std::vector<Pair> Player::get_district_static(const Pair & hex) const
{
return GameController->get_district_static(hex);
}
std::vector<Pair> Player::get_army_list(const Pair & hex) const
{
return GameController->get_army_list(hex);
}
bool Player::get_neighbours_exist(const Pair & hex,
std::function <bool(hex_color)> compare1,
std::function <bool(unit_type)> compare2) const
{
return GameController->get_neighbours_exist(hex, compare1, compare2);
}
std::vector<Pair> Player::get_neighbours(const Pair & hex,
std::function <bool(hex_color)> compare1,
std::function <bool(unit_type)> compare2) const
{
return GameController->get_neighbours(hex, compare1, compare2);
}
std::vector<Pair> Player::get_hex_row(const Pair & hex, size_type radius,
std::function <bool(hex_color)> compare1,
std::function <bool(unit_type)> compare2) const
{
return GameController->get_hex_row(hex, radius, compare1, compare2);
}
bool Player::get_hex_row_exist(const Pair & hex, size_type radius,
std::function <bool(hex_color)> compare1,
std::function <bool(unit_type)> compare2) const
{
return GameController->get_hex_row_exist(hex, radius, compare1, compare2);
}
std::vector<Pair> Player::get_internal_border(const Pair & hex,
std::function <bool(unit_type)> compare) const
{
return GameController->get_internal_border(hex, compare);
}
std::vector<Pair> Player::get_external_border(const Pair & hex,
std::function <bool(hex_color)> compare1,
std::function <bool(unit_type)> compare2) const
{
return GameController->get_external_border(hex, compare1, compare2);
}
std::vector<Pair> Player::easy_solve_maze(const Pair & hex,
std::function <bool(unit_type)> compare) const
{
return GameController->easy_solve_maze(hex, compare);
}
size_type Player::easy_solve_maze_count(const Pair & hex,
std::function <bool(unit_type)> compare) const
{
return GameController->easy_solve_maze_count(hex, compare);
}
size_type Player::get_farm_cost(const Pair & hex) const
{
return GameController->get_farm_cost(hex);
}
size_type Player::get_army_cost(size_type strength) const
{
return GameController->get_army_cost(strength);
}
size_type Player::get_tower_cost(size_type strength) const
{
return GameController->get_tower_cost(strength);
}
bool Player::make_move(const Pair & start, const Pair & end)
{
return GameController->make_move(start, end);
}
bool Player::buy_tower(const Pair & hex, size_type strength)
{
return GameController->buy_tower(hex, strength);
}
bool Player::buy_farm(const Pair & hex)
{
return GameController->buy_farm(hex);
}
bool Player::buy_army(const Pair & hex, size_type strength)
{
return GameController->buy_army(hex, strength);
}
void Player::add_capital(const Pair & capital)
{
Capitals.push_back(capital);
}
bool Player::remove_capital(const Pair & capital)
{
for (auto i = Capitals.begin(); i != Capitals.end(); ++i)
{
if (*i == capital) {
Capitals.erase(i);
return true;
}
}
return false;
}
void Player::set_controller(Controller * controller)
{
GameController = controller;
}
bool operator != (const Player & player1, const Player & player2)
{
return !(player1 == player2);
}
}
| 23.881533 | 86 | 0.698716 | [
"vector"
] |
91e6c694aeba3920b99bc15cef08219831500b7a | 391 | cpp | C++ | Cplus/CountSortedVowelStrings.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | 1 | 2018-01-22T12:06:28.000Z | 2018-01-22T12:06:28.000Z | Cplus/CountSortedVowelStrings.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | Cplus/CountSortedVowelStrings.cpp | JumHorn/leetcode | 1447237ae8fc3920b19f60b30c71a84b088cc200 | [
"MIT"
] | null | null | null | #include <vector>
using namespace std;
class Solution
{
public:
int countVowelStrings(int n)
{
vector<vector<int>> dp(n + 1, vector<int>(5));
dp[0][0] = 1;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < 5; ++j)
{
for (int k = 0; k <= j; ++k)
dp[i + 1][j] += dp[i][k];
}
}
int res = 0;
for (int i = 0; i < 5; ++i)
res += dp[n][i];
return res;
}
}; | 15.64 | 48 | 0.468031 | [
"vector"
] |
91e89a64b6fc791c2332cae65364667e73b00d82 | 2,600 | hpp | C++ | Blaze/core/StorageBuffer.hpp | KidRigger/Blaze | 7e76de71e2e22f3b5e8c4c2c50c58e6d205646c6 | [
"MIT"
] | 14 | 2019-12-10T03:57:03.000Z | 2021-09-16T14:58:39.000Z | Blaze/core/StorageBuffer.hpp | kidrigger/Blaze | 7e76de71e2e22f3b5e8c4c2c50c58e6d205646c6 | [
"MIT"
] | null | null | null | Blaze/core/StorageBuffer.hpp | kidrigger/Blaze | 7e76de71e2e22f3b5e8c4c2c50c58e6d205646c6 | [
"MIT"
] | null | null | null |
#pragma once
#include <core/Context.hpp>
#include <cstring>
#include <thirdparty/vma/vk_mem_alloc.h>
namespace blaze
{
/**
* @brief The base class for all UBOs
*
* The type independent size dependent generic class to implement a buffer for
* uniforms.
* Mostly not to be used directly, but extended by a type safe derived class.
*/
class SSBO
{
protected:
vkw::Buffer buffer;
size_t size{0};
public:
/**
* @brief Default Constructor.
*/
SSBO() noexcept
{
}
/**
* @brief Main Constructor.
*
* @param context Pointer to the Context in use.
* @param size The size of the actual buffer to allocate.
*/
SSBO(const Context* context, size_t size) noexcept;
/**
* @name Move Constructors.
*
* @brief Move only, copy deleted.
*
* @{
*/
SSBO(SSBO&& other) noexcept;
SSBO& operator=(SSBO&& other) noexcept;
SSBO(const SSBO& other) = delete;
SSBO& operator=(const SSBO& other) = delete;
/**
* @}
*/
/**
* @brief Creates a new VkDescriptorBufferInfo for the UBO
*/
inline VkDescriptorBufferInfo get_descriptorInfo() const
{
return VkDescriptorBufferInfo{
buffer.handle,
0,
size,
};
}
/**
* @}
*/
/**
* @brief Writes data to the buffer.
*
* @param data The pointer to the data to write into buffer.
* @param size The size of the data to write into the buffer.
*/
void writeData(const void* data, size_t size);
/**
* @brief Writes data to the buffer.
*
* @param data The pointer to the data to write into buffer.
* @param size The size of the data to write into the buffer.
*/
void writeData(const void* data, size_t offset, size_t size);
};
class SSBODataVector
{
private:
using ssbo_t = SSBO;
std::vector<ssbo_t> ssbos;
uint32_t count;
public:
SSBODataVector() noexcept
{
}
SSBODataVector(const Context* context, size_t size, uint32_t numUBOS) noexcept : count(numUBOS)
{
ssbos.reserve(count);
for (uint32_t i = 0; i < count; ++i)
{
ssbos.emplace_back(context, size);
}
}
SSBODataVector(const SSBODataVector& other) = delete;
SSBODataVector& operator=(const SSBODataVector& other) = delete;
SSBODataVector(SSBODataVector&& other) = default;
SSBODataVector& operator=(SSBODataVector&& other) = default;
const std::vector<ssbo_t>& get() const
{
return ssbos;
}
uint32_t size() const
{
return count;
}
ssbo_t& operator[](uint32_t idx)
{
return ssbos[idx];
}
const ssbo_t& operator[](uint32_t idx) const
{
return ssbos[idx];
}
~SSBODataVector()
{
ssbos.clear();
count = 0;
}
};
} // namespace blaze
| 18.181818 | 96 | 0.658462 | [
"vector"
] |
91ebac84c67f0cdf645190ef4dc15f2c391a98db | 5,123 | cpp | C++ | tests/basic_properties.cpp | j-renggli/properties | d005afd3c862248a163e61c7b1fbc4bff4cc0c0d | [
"MIT"
] | null | null | null | tests/basic_properties.cpp | j-renggli/properties | d005afd3c862248a163e61c7b1fbc4bff4cc0c0d | [
"MIT"
] | null | null | null | tests/basic_properties.cpp | j-renggli/properties | d005afd3c862248a163e61c7b1fbc4bff4cc0c0d | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <basic_property.h>
namespace property
{
template <class T>
void checkBasicProperty(const T& prop, const typename T::value_type& value)
{
CHECK(prop.value() == value);
CHECK(prop.name() == "name");
CHECK(prop.displayName() == "display");
CHECK(prop.id() == T::identifier);
}
template <class T>
void testBasicPropertyConstructor(const typename T::value_type& value)
{
INFO("BasicProperty constructor");
T prop("name", value, "display");
checkBasicProperty(prop, value);
}
template <class T>
void testBasicPropertyCopyConstructor(const typename T::value_type& value)
{
INFO("BasicProperty copy-constructor");
T original("name", value, "display");
T prop(original);
checkBasicProperty(prop, value);
}
template <class T>
void testBasicPropertyCopyOperator(const typename T::value_type& value, const typename T::value_type& other)
{
INFO("BasicProperty copy-operator");
T original("name2", value, "display2");
T prop("name", other, "display");
prop = original;
checkBasicProperty(prop, value);
}
template <class T>
void testBasicPropertyConvert(const typename T::value_type& value)
{
INFO("BasicProperty convert");
T original("name", value, "display");
auto prop = T::convert(original);
checkBasicProperty(prop, value);
}
template <class T>
void testBasicPropertyAssignment(const typename T::value_type& value, const typename T::value_type& other)
{
INFO("BasicProperty constructor");
T prop("name", value, "display");
prop = other;
checkBasicProperty(prop, other);
}
template <class T>
void testBasicPropertyCopyConstructedAssignment(const typename T::value_type& value,
const typename T::value_type& other)
{
INFO("BasicProperty copy-constructor is independent from its base");
T original("name", value, "display");
T prop(original);
prop = other;
checkBasicProperty(original, value);
checkBasicProperty(prop, other);
}
template <class T>
void testBasicPropertyCopyOperatedAssignment(const typename T::value_type& value, const typename T::value_type& other)
{
INFO("BasicProperty copy-operator is independent from its base");
T original("name", value, "display");
T prop("name", other, "display");
prop = original;
checkBasicProperty(prop, value);
prop = other;
checkBasicProperty(original, value);
checkBasicProperty(prop, other);
}
template <class T>
void testBasicPropertyConvertedAssignment(const typename T::value_type& value, const typename T::value_type& other)
{
INFO("BasicProperty convert is independent from its base");
T original("name", value, "display");
auto prop = T::convert(original);
prop = other;
checkBasicProperty(original, value);
checkBasicProperty(prop, other);
}
template <class T>
void testBasicPropertyEquality(const typename T::value_type& value)
{
INFO("BasicProperty equals another of same name and value");
T left("name", value, "display");
T right("name", value, "display2");
CHECK(left == left);
CHECK(left == right);
}
template <class T>
void testBasicPropertyUnequality(const typename T::value_type& value, const typename T::value_type& other)
{
INFO("BasicProperty is not equal to another of different name or value");
T base("name", value, "display");
T name("name2", value, "display");
T val("name", other, "display");
CHECK(base != name);
CHECK(base != val);
}
template <class T>
void testBasicProperty(const typename T::value_type& base, const typename T::value_type& other)
{
{
INFO("Constructors and related");
testBasicPropertyConstructor<T>(base);
testBasicPropertyCopyConstructor<T>(base);
testBasicPropertyCopyOperator<T>(base, other);
testBasicPropertyConvert<T>(base);
}
{
INFO("Set value modifies only target object");
testBasicPropertyAssignment<T>(base, other);
testBasicPropertyCopyConstructedAssignment<T>(base, other);
testBasicPropertyCopyOperatedAssignment<T>(base, other);
testBasicPropertyConvertedAssignment<T>(base, other);
}
{
INFO("Equality of basic properties");
testBasicPropertyEquality<T>(base);
testBasicPropertyUnequality<T>(base, other);
}
{
INFO("To string");
T prop("a_name", base, "Display");
std::stringstream ss;
ss << "Display=" << T::identifier << "[";
stream::convert(ss, base) << "]";
std::wstringstream wss;
wss << L"Display=";
stream::convert(wss, T::identifier) << L"[";
stream::convert(wss, base) << L"]";
CHECK(static_cast<std::string>(prop) == ss.str());
CHECK(static_cast<std::wstring>(prop) == wss.str());
}
}
TEST_CASE("Test BooleanProperty")
{
testBasicProperty<BooleanProperty>(true, false);
}
TEST_CASE("Test StringProperty")
{
testBasicProperty<StringProperty>("Asdf", "Qwer");
}
TEST_CASE("Test WStringProperty")
{
testBasicProperty<WStringProperty>(L"Asdf", L"Qwer");
}
}
| 29.442529 | 118 | 0.674995 | [
"object"
] |
91f492125831ef46269d8e38f184285fe39da408 | 4,389 | cpp | C++ | Engine/Source/Runtime/MovieScene/Private/Evaluation/MovieSceneLegacyTrackInstanceTemplate.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/MovieScene/Private/Evaluation/MovieSceneLegacyTrackInstanceTemplate.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/MovieScene/Private/Evaluation/MovieSceneLegacyTrackInstanceTemplate.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Evaluation/MovieSceneLegacyTrackInstanceTemplate.h"
#include "Evaluation/MovieSceneEvaluationTemplateInstance.h"
#include "IMovieScenePlayer.h"
/** Legacy tracks just get a new ID each time (so they always save/restore state, regardless of whether a similar track has already animated the object. That was the old behaviour) */
struct FMovieSceneLegacyAnimTypeID : FMovieSceneAnimTypeID
{
FMovieSceneLegacyAnimTypeID(uint32 InSeed)
{
ID = GenerateHash(&UnusedStatic, InSeed);
}
static uint64 UnusedStatic;
};
uint64 FMovieSceneLegacyAnimTypeID::UnusedStatic = 0;
static uint32 LegacyTrackIdSeed = 0;
IMovieSceneTrackInstance::IMovieSceneTrackInstance()
: AnimTypeID(FMovieSceneLegacyAnimTypeID(LegacyTrackIdSeed++))
{
}
struct FLegacyTrackData : IPersistentEvaluationData
{
TSharedPtr<IMovieSceneTrackInstance> TrackInstance;
};
struct FRestoreStateToken : IMovieScenePreAnimatedGlobalToken
{
TArray<TWeakObjectPtr<>> RuntimeObjects;
TSharedPtr<FMovieSceneSequenceInstance> LegacySequence;
TSharedPtr<IMovieSceneTrackInstance> LegacyTrackInstance;
virtual void RestoreState(IMovieScenePlayer& InPlayer) override
{
LegacyTrackInstance->RestoreState(RuntimeObjects, InPlayer, *LegacySequence);
}
};
struct FLegacyPreAnimatedStateProducer : IMovieScenePreAnimatedGlobalTokenProducer
{
FLegacyPreAnimatedStateProducer(TFunctionRef<IMovieScenePreAnimatedGlobalTokenPtr()> In) : Producer(MoveTemp(In)) {}
TFunctionRef<IMovieScenePreAnimatedGlobalTokenPtr()> Producer;
virtual IMovieScenePreAnimatedGlobalTokenPtr CacheExistingState() const override
{
return Producer();
}
};
struct FLegacyExecutionToken : IMovieSceneExecutionToken
{
virtual void Execute(const FMovieSceneContext& Context, const FMovieSceneEvaluationOperand& Operand, FPersistentEvaluationData& PersistentData, IMovieScenePlayer& Player) override
{
const FMovieSceneEvaluationTemplateInstance* TemplateInstance = Player.GetEvaluationTemplate().GetInstance(Operand.SequenceID);
TSharedPtr<FMovieSceneSequenceInstance> LegacySequence = TemplateInstance ? TemplateInstance->LegacySequenceInstance : nullptr;
TSharedPtr<IMovieSceneTrackInstance> LegacyTrackInstance = PersistentData.GetSectionData<FLegacyTrackData>().TrackInstance;
if (!ensure(LegacyTrackInstance.IsValid() && LegacySequence.IsValid()))
{
return;
}
EMovieSceneUpdateData UpdateData(Context.GetTime(), Context.GetPreviousTime());
UpdateData.bJumpCut = Context.HasJumped();
TArray<TWeakObjectPtr<>> RuntimeObjects;
for (TWeakObjectPtr<> Obj : Player.FindBoundObjects(Operand))
{
RuntimeObjects.Add(Obj);
}
FLegacyPreAnimatedStateProducer Producer([&]() -> IMovieScenePreAnimatedGlobalTokenPtr{
LegacyTrackInstance->SaveState(RuntimeObjects, Player, *LegacySequence);
FRestoreStateToken Token;
Token.RuntimeObjects = RuntimeObjects;
Token.LegacySequence = LegacySequence;
Token.LegacyTrackInstance = LegacyTrackInstance;
return MoveTemp(Token);
});
Player.SavePreAnimatedState(LegacyTrackInstance->AnimTypeID, Producer);
UpdateData.UpdatePass = MSUP_PreUpdate;
if (LegacyTrackInstance->HasUpdatePasses() & UpdateData.UpdatePass)
{
LegacyTrackInstance->Update(UpdateData, RuntimeObjects, Player, *LegacySequence);
}
UpdateData.UpdatePass = MSUP_Update;
if (LegacyTrackInstance->HasUpdatePasses() & UpdateData.UpdatePass)
{
LegacyTrackInstance->Update(UpdateData, RuntimeObjects, Player, *LegacySequence);
}
UpdateData.UpdatePass = MSUP_PostUpdate;
if (LegacyTrackInstance->HasUpdatePasses() & UpdateData.UpdatePass)
{
LegacyTrackInstance->Update(UpdateData, RuntimeObjects, Player, *LegacySequence);
}
}
};
FMovieSceneLegacyTrackInstanceTemplate::FMovieSceneLegacyTrackInstanceTemplate(const UMovieSceneTrack* InTrack)
: Track(InTrack)
{
}
void FMovieSceneLegacyTrackInstanceTemplate::Evaluate(const FMovieSceneEvaluationOperand& Operand, const FMovieSceneContext& Context, const FPersistentEvaluationData& PersistentData, FMovieSceneExecutionTokens& ExecutionTokens) const
{
ExecutionTokens.Add(FLegacyExecutionToken());
}
void FMovieSceneLegacyTrackInstanceTemplate::Setup(FPersistentEvaluationData& PersistentData, IMovieScenePlayer& Player) const
{
PersistentData.AddSectionData<FLegacyTrackData>().TrackInstance = Track->CreateLegacyInstance();
}
| 35.395161 | 233 | 0.815448 | [
"object"
] |
91f5c177ff2fec4584b24223d397ae408cd0aeba | 5,759 | cpp | C++ | src/gipAzure.cpp | GlistPlugins/gipAzure | ffd12db44eb9a3aaf2a4c2ee61bdebbe0f3238f7 | [
"Apache-2.0"
] | null | null | null | src/gipAzure.cpp | GlistPlugins/gipAzure | ffd12db44eb9a3aaf2a4c2ee61bdebbe0f3238f7 | [
"Apache-2.0"
] | null | null | null | src/gipAzure.cpp | GlistPlugins/gipAzure | ffd12db44eb9a3aaf2a4c2ee61bdebbe0f3238f7 | [
"Apache-2.0"
] | 3 | 2021-08-11T10:59:39.000Z | 2021-08-28T16:06:27.000Z | /*
* gipAzure.cpp
*
* Created on: Aug 4, 2021
* Author: Onur Demir
*/
#include "gipAzure.h"
gipAzure::gipAzure() {
account_name = "";
account_key = "";
blob_endpoint = "";
connection_count = 2;
currentcontainer = "";
httpsProtocol = false;
}
gipAzure::~gipAzure() {
}
void gipAzure::initSettings(std::string _account_name, std::string _account_key, bool _httpsProtocol) {
account_name = _account_name;
account_key = _account_key;
httpsProtocol = _httpsProtocol;
}
void gipAzure::initSettings(std::string _account_name, std::string _account_key, int _connectioncount, bool _httpsProtocol) {
initSettings(_account_name, _account_key, _httpsProtocol);
connection_count = _connectioncount;
}
void gipAzure::initSettings(std::string _account_name, std::string _account_key, std::string _blob_endpoint, bool _httpsProtocol) {
initSettings(_account_name, _account_key, _httpsProtocol);
blob_endpoint = _blob_endpoint;
}
void gipAzure::initSettings(std::string _account_name, std::string _account_key, std::string _blob_endpoint, int _connectioncount, bool _httpsProtocol) {
initSettings(_account_name, _account_key, _blob_endpoint, _httpsProtocol);
connection_count = _connectioncount;
}
void gipAzure::createClient() {
credential = std::make_shared<azure::storage_lite::shared_key_credential>(account_name, account_key);
storage_account = std::make_shared<azure::storage_lite::storage_account>(account_name, credential, httpsProtocol, blob_endpoint);
client = std::make_shared<azure::storage_lite::blob_client>(storage_account, connection_count);
clientwrapper = std::make_shared<azure::storage_lite::blob_client_wrapper>(client);
}
std::string gipAzure::getUrl() {
return storage_account.get()->get_url(azure::storage_lite::storage_account::service::blob).get_domain();
}
void gipAzure::deleteAllContainers() {
std::vector<std::string> containernames = listContainerNames();
if (!containernames.empty()) {
for (std::string containername : containernames) {
deleteContainer(containername);
}
}
}
bool gipAzure::containerExists(std::string containername) {
return client.get()->get_container_properties(containername).get().response().valid();
}
void gipAzure::deleteContainer(std::string containername){
if (containerExists(containername)) {
client.get()->delete_container(containername);
gLogi("Azure")<< containername << " deleted..." ;
}
else gLogi("Azure") << "Does not exist..." ;
}
void gipAzure::createContainer(std::string containername) {
if (client) {
auto outcome = client.get()->create_container(containername).get();
if (!outcome.success())
{
gLogi("Azure") << "Failed to create container, Error: " << outcome.error().code << ", " << outcome.error().code_name ;
}
}
}
std::vector<std::string> gipAzure::listContainerNames() {
std::vector<std::string> container_names;
auto containers = client.get()->list_containers_segmented("", "", false).get();
if (!containers.success()){
gLogi("Azure") << "Failed to list container names, Error: " << containers.error().code << ", " << containers.error().code_name;
}
else{
for (auto name : containers.response().containers) {
container_names.push_back(name.name);
}
}
return container_names;
}
bool gipAzure::blobExists(std::string containername, std::string blobname) {
if (containerExists(containername)) {
return client.get()->get_blob_properties(containername, blobname).get().response().valid();
}
else return false;
}
std::vector<std::string> gipAzure::listBlobNamesFromContainer(std::string containername) {
std::vector<std::string> blob_names;
if (containerExists(containername)) {
auto blobs = client.get()->list_blobs_segmented(containername, "/", "", "").get();
if (!blobs.success()) {
gLogi("Azure") << "Failed to list container names, Error: " << blobs.error().code << ", " << blobs.error().code_name;
blob_names.push_back("Failed to list container names, Error: " + blobs.error().code + ", " + blobs.error().code_name);
}
else {
for (auto name : blobs.response().blobs) {
blob_names.push_back(name.name);
}
}
}
else blob_names.push_back("Container does not exists");
return blob_names;
}
void gipAzure::deleteBlob(std::string containername, std::string blobname) {
if (blobExists(containername, blobname)) client.get()->delete_blob(containername, blobname);
else gLogi("Azure") << "Blob or container does not exists.";
}
void gipAzure::downloadBlob(std::string containername, std::string blobname, std::string fullpath) {
if (!dirExists(fullpath)) fs::create_directories(fullpath);
time_t last_modified;
clientwrapper.get()->download_blob_to_file(containername, blobname, fullpath + "/" + blobname, last_modified);
gLogi("Azure") << "Download Blob done: " << errno;
}
void gipAzure::uploadBlob(std::string container, std::string fullpath) {
if (containerExists(container)) {
gLogi("Azure") << fullpath;
std::ifstream fin(fullpath, std::ios_base::in | std::ios_base::binary);
std::vector<std::pair<std::string, std::string>> metadata;
metadata.emplace_back(std::make_pair("meta_key1", "meta-value1"));
metadata.emplace_back(std::make_pair("meta_key2", "meta-value2"));
auto value = client.get()->upload_block_blob_from_stream(container, fs::path(fullpath).filename().u8string(), fin, metadata).get();
if (!value.success()) gLogi("Azure") << "Failed to upload blob, Error:" << value.error().code << ", " << value.error().code_name;
}
else gLogi("Container doesn't exists...");
}
void gipAzure::setup() {
}
void gipAzure::update() {
}
int gipAzure::dirExists (std::string fullpath) {
struct stat info;
if(stat( fullpath.c_str(), &info ) != 0)
return 0;
else if(info.st_mode & S_IFDIR)
return 1;
else
return 0;
}
| 33.876471 | 154 | 0.722521 | [
"vector"
] |
91f8b6ec35716b3a1c7940f3dc5e1ba4d7d9bba1 | 51,192 | cpp | C++ | src/ProgramFunction.cpp | tommyhuangthu/EvoEF | 0bbdab442146d1497570642f7f90300146dac166 | [
"MIT"
] | 3 | 2020-01-12T01:41:31.000Z | 2021-08-11T09:22:20.000Z | src/ProgramFunction.cpp | tommyhuangthu/EvoEF | 0bbdab442146d1497570642f7f90300146dac166 | [
"MIT"
] | 1 | 2021-01-06T16:00:53.000Z | 2021-01-06T16:20:56.000Z | src/ProgramFunction.cpp | tommyhuangthu/EvoEF | 0bbdab442146d1497570642f7f90300146dac166 | [
"MIT"
] | 5 | 2020-09-08T15:21:54.000Z | 2022-03-30T17:49:12.000Z | /*******************************************************************************************************************************
This file is a part of the EvoDesign physical Energy Function (EvoEF)
Copyright (c) 2019 Xiaoqiang Huang (tommyhuangthu@foxmail.com, xiaoqiah@umich.edu)
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 "ProgramFunction.h"
#include <string.h>
#include <ctype.h>
int EvoEF_help(){
printf(
"Usage: EvoEF [OPTIONS] --pdb=pdbfile\n\n"
"EvoEF basic OPTIONS:\n\n"
"short options:\n"
" -v print version info of EvoEF\n"
" -h print help message of EvoEF\n"
"\nlong options:\n"
" --version print version info of EvoEF\n"
" --help print help message of EvoEF\n"
" --command=arg choose your computation type:\n"
" ComputeStability\n"
" ComputeBinding\n"
" ::user should specify how to split complex for multichain\n"
" proteins, i.e., --split=AB,C or --split=A,BC\n"
" RepairStructure\n"
" ComputeResiEnergy\n"
" ::compute interaction between a residue\n"
" with protein backbone and surrounding residues\n"
" AddHydrogen\n"
" OptimizeHydrogen\n"
" ShowResiComposition\n"
" BuildMutant\n"
" ::user should input the mutant file (see below)\n"
" --split=arg arg specify how to split chains using one-letter chain identifier\n"
" divided by comma, i.e., AB,C or A,BC\n"
" --mutant_file=arg arg can have any arbitrary name such as 'mutants.txt'\n"
" and 'individual_list.txt'. The default mutantfile name is individual_list.txt\n"
" Please see the README file to know more about the file format\n"
" --pdb=pdbfile pdbfile should be a valid pdbfile suffixed with '.pdb'\n"
);
return Success;
}
int EvoEF_version(){
printf("EvoDesign Energy Function (EvoEF) version 1.1\n");
return Success;
}
int EvoEF_interface(){
printf("******************************************************\n");
printf("* EvoDesign Energy Function *\n");
printf("* *\n");
printf("* Copyright (c) 2019 Xiaoqiang Huang *\n");
printf("* The Yang Zhang Lab *\n");
printf("* Dept. of Computational Medicine & Bioinformatics *\n");
printf("* Medical School *\n");
printf("* University of Michigan *\n");
printf("******************************************************\n");
return Success;
}
BOOL CheckCommandName(char* queryname){
int MAX_CMD_NUM = 100;
char *supportedcmd[] = {
"RepairStructure",
"ComputeStability",
"ComputeBinding",
"BuildMutant",
"ComputeResiEnergy",
"AddHydrogen",
"OptimizeHydrogen",
"ShowResiComposition",
NULL
};
BOOL exist = FALSE;
for(int i = 0; i < MAX_CMD_NUM; i++){
if(supportedcmd[i] == NULL) break;
else{
if(strcmp(queryname, supportedcmd[i]) == 0){
exist = TRUE;
break;
}
}
}
return exist;
}
int EvoEF_ComputeStability(Structure *pStructure, double *energyTerms){
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++) energyTerms[i] = 0.0;
// if the structure is composed of several chains, the residue position could be different in the whole structure from that in the separate chain
//StructureComputeResiduePosition(pStructure);
for(int i = 0; i < StructureGetChainCount(pStructure); i++){
Chain *pChainI = StructureGetChain(pStructure,i);
for(int ir = 0; ir < ChainGetResidueCount(pChainI); ir++){
Residue *pResIR = ChainGetResidue(pChainI,ir);
double ratio1 = CalcResidueBuriedRatio(pResIR);
double refer=0.0;
ResidueReferenceEnergy(pResIR, energyTerms);
EVOEF_EnergyResidueSelfEnergy(pResIR,ratio1,energyTerms);
for(int is = ir+1; is < ChainGetResidueCount(pChainI); is++){
Residue *pResIS = ChainGetResidue(pChainI,is);
double ratio2 = CalcResidueBuriedRatio(pResIS);
double ratio12 = CalcAverageBuriedRatio(ratio1, ratio2);
if(is==ir+1) EVOEF_EnergyResidueAndNextResidue(pResIR,pResIS,ratio12,energyTerms);
else EVOEF_EnergyResidueAndOtherResidueSameChain(pResIR,pResIS,ratio12,energyTerms);
}
for(int k = i+1; k < StructureGetChainCount(pStructure); k++){
Chain *pChainK = StructureGetChain(pStructure,k);
for(int ks = 0; ks < ChainGetResidueCount(pChainK); ks++){
Residue *pResKS = ChainGetResidue(pChainK,ks);
double ratio2 = CalcResidueBuriedRatio(pResKS);
double ratio12 = CalcAverageBuriedRatio(ratio1, ratio2);
EVOEF_EnergyResidueAndOtherResidueDifferentChain(pResIR,pResKS,ratio12,energyTerms);
}
}
}
}
//total energy: weighted
EnergyTermWeighting(energyTerms);
for(int i = 1; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTerms[0] += energyTerms[i];
}
//energy term details: not weighted
printf("\nStructure energy details:\n");
printf("reference_ALA = %8.2f\n", energyTerms[21]);
printf("reference_CYS = %8.2f\n", energyTerms[22]);
printf("reference_ASP = %8.2f\n", energyTerms[23]);
printf("reference_GLU = %8.2f\n", energyTerms[24]);
printf("reference_PHE = %8.2f\n", energyTerms[25]);
printf("reference_GLY = %8.2f\n", energyTerms[26]);
printf("reference_HIS = %8.2f\n", energyTerms[27]);
printf("reference_ILE = %8.2f\n", energyTerms[28]);
printf("reference_LYS = %8.2f\n", energyTerms[29]);
printf("reference_LEU = %8.2f\n", energyTerms[30]);
printf("reference_MET = %8.2f\n", energyTerms[31]);
printf("reference_ASN = %8.2f\n", energyTerms[32]);
printf("reference_PRO = %8.2f\n", energyTerms[33]);
printf("reference_GLN = %8.2f\n", energyTerms[34]);
printf("reference_ARG = %8.2f\n", energyTerms[35]);
printf("reference_SER = %8.2f\n", energyTerms[36]);
printf("reference_THR = %8.2f\n", energyTerms[37]);
printf("reference_VAL = %8.2f\n", energyTerms[38]);
printf("reference_TRP = %8.2f\n", energyTerms[39]);
printf("reference_TYR = %8.2f\n", energyTerms[40]);
printf("intraR_vdwatt = %8.2f\n", energyTerms[6]);
printf("intraR_vdwrep = %8.2f\n", energyTerms[7]);
printf("intraR_electr = %8.2f\n", energyTerms[8]);
printf("intraR_deslvP = %8.2f\n", energyTerms[9]);
printf("intraR_deslvH = %8.2f\n", energyTerms[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTerms[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTerms[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTerms[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTerms[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTerms[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTerms[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTerms[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTerms[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTerms[49]);
printf("interS_vdwatt = %8.2f\n", energyTerms[1]);
printf("interS_vdwrep = %8.2f\n", energyTerms[2]);
printf("interS_electr = %8.2f\n", energyTerms[3]);
printf("interS_deslvP = %8.2f\n", energyTerms[4]);
printf("interS_deslvH = %8.2f\n", energyTerms[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTerms[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTerms[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTerms[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTerms[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTerms[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTerms[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTerms[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTerms[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTerms[19]);
printf("interD_vdwatt = %8.2f\n", energyTerms[51]);
printf("interD_vdwrep = %8.2f\n", energyTerms[52]);
printf("interD_electr = %8.2f\n", energyTerms[53]);
printf("interD_deslvP = %8.2f\n", energyTerms[54]);
printf("interD_deslvH = %8.2f\n", energyTerms[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTerms[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTerms[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTerms[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTerms[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTerms[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTerms[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTerms[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTerms[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTerms[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n\n", energyTerms[0]);
return Success;
}
int EvoEF_ComputeStabilityForSelectedChains(Structure *pStructure, double *energyTerms,char selechains[]){
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++) energyTerms[i] = 0.0;
// if the structure is composed of several chains, the residue position could be different in the whole structure from that in the separate chain
//StructureComputeResiduePosition(pStructure);
for(int i = 0; i < StructureGetChainCount(pStructure); i++){
Chain *pChainI = StructureGetChain(pStructure,i);
if(strstr(selechains,ChainGetName(pChainI))==NULL){continue;}
for(int ir = 0; ir < ChainGetResidueCount(pChainI); ir++){
Residue *pResIR = ChainGetResidue(pChainI,ir);
double ratio1 = CalcResidueBuriedRatio(pResIR);
double refer=0.0;
ResidueReferenceEnergy(pResIR, energyTerms);
EVOEF_EnergyResidueSelfEnergy(pResIR,ratio1,energyTerms);
for(int is = ir+1; is < ChainGetResidueCount(pChainI); is++){
Residue *pResIS = ChainGetResidue(pChainI,is);
double ratio2 = CalcResidueBuriedRatio(pResIS);
double ratio12 = CalcAverageBuriedRatio(ratio1, ratio2);
if(is==ir+1) EVOEF_EnergyResidueAndNextResidue(pResIR,pResIS,ratio12,energyTerms);
else EVOEF_EnergyResidueAndOtherResidueSameChain(pResIR,pResIS,ratio12,energyTerms);
}
for(int k = i+1; k < StructureGetChainCount(pStructure); k++){
Chain *pChainK = StructureGetChain(pStructure,k);
if(strstr(selechains,ChainGetName(pChainK))==NULL){continue;}
for(int ks = 0; ks < ChainGetResidueCount(pChainK); ks++){
Residue *pResKS = ChainGetResidue(pChainK,ks);
double ratio2 = CalcResidueBuriedRatio(pResKS);
double ratio12 = CalcAverageBuriedRatio(ratio1, ratio2);
EVOEF_EnergyResidueAndOtherResidueDifferentChain(pResIR,pResKS,ratio12,energyTerms);
}
}
}
}
//total energy: weighted
EnergyTermWeighting(energyTerms);
for(int i = 1; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTerms[0] += energyTerms[i];
}
//energy term details: not weighted
printf("\nStructure energy details for chains %s:\n",selechains);
printf("reference_ALA = %8.2f\n", energyTerms[21]);
printf("reference_CYS = %8.2f\n", energyTerms[22]);
printf("reference_ASP = %8.2f\n", energyTerms[23]);
printf("reference_GLU = %8.2f\n", energyTerms[24]);
printf("reference_PHE = %8.2f\n", energyTerms[25]);
printf("reference_GLY = %8.2f\n", energyTerms[26]);
printf("reference_HIS = %8.2f\n", energyTerms[27]);
printf("reference_ILE = %8.2f\n", energyTerms[28]);
printf("reference_LYS = %8.2f\n", energyTerms[29]);
printf("reference_LEU = %8.2f\n", energyTerms[30]);
printf("reference_MET = %8.2f\n", energyTerms[31]);
printf("reference_ASN = %8.2f\n", energyTerms[32]);
printf("reference_PRO = %8.2f\n", energyTerms[33]);
printf("reference_GLN = %8.2f\n", energyTerms[34]);
printf("reference_ARG = %8.2f\n", energyTerms[35]);
printf("reference_SER = %8.2f\n", energyTerms[36]);
printf("reference_THR = %8.2f\n", energyTerms[37]);
printf("reference_VAL = %8.2f\n", energyTerms[38]);
printf("reference_TRP = %8.2f\n", energyTerms[39]);
printf("reference_TYR = %8.2f\n", energyTerms[40]);
printf("intraR_vdwatt = %8.2f\n", energyTerms[6]);
printf("intraR_vdwrep = %8.2f\n", energyTerms[7]);
printf("intraR_electr = %8.2f\n", energyTerms[8]);
printf("intraR_deslvP = %8.2f\n", energyTerms[9]);
printf("intraR_deslvH = %8.2f\n", energyTerms[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTerms[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTerms[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTerms[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTerms[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTerms[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTerms[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTerms[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTerms[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTerms[49]);
printf("interS_vdwatt = %8.2f\n", energyTerms[1]);
printf("interS_vdwrep = %8.2f\n", energyTerms[2]);
printf("interS_electr = %8.2f\n", energyTerms[3]);
printf("interS_deslvP = %8.2f\n", energyTerms[4]);
printf("interS_deslvH = %8.2f\n", energyTerms[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTerms[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTerms[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTerms[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTerms[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTerms[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTerms[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTerms[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTerms[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTerms[19]);
printf("interD_vdwatt = %8.2f\n", energyTerms[51]);
printf("interD_vdwrep = %8.2f\n", energyTerms[52]);
printf("interD_electr = %8.2f\n", energyTerms[53]);
printf("interD_deslvP = %8.2f\n", energyTerms[54]);
printf("interD_deslvH = %8.2f\n", energyTerms[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTerms[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTerms[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTerms[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTerms[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTerms[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTerms[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTerms[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTerms[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTerms[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n\n", energyTerms[0]);
return Success;
}
int EvoEF_ComputeBinding(Structure *pStructure, double *energyTerms){
if(StructureGetChainCount(pStructure)>2){
printf("Your structure has more than two protein chains, and you should specify how to split chains "
"before computing the binding energy\n");
printf("Otherwise, EvoEF just output the interactions between any chain pair (DEFAULT)\n");
}
else if(StructureGetChainCount(pStructure)<=1){
printf("Your structure has less than or equal to one chain, binding energy cannot be calculated\n");
return Warning;
}
for(int i=0; i<StructureGetChainCount(pStructure);i++){
Chain* pChainI=StructureGetChain(pStructure,i);
for(int k=i+1; k<StructureGetChainCount(pStructure);k++){
Chain* pChainK=StructureGetChain(pStructure,k);
double energyTermsStructure[MAX_EVOEF_ENERGY_TERM_NUM];
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTermsStructure[i] = 0.0;
}
for(int j=0;j<ChainGetResidueCount(pChainI);j++){
Residue* pResiIJ=ChainGetResidue(pChainI,j);
for(int s=0;s<ChainGetResidueCount(pChainK);s++){
Residue* pResiKS=ChainGetResidue(pChainK,s);
EVOEF_EnergyResidueAndOtherResidueDifferentChain(pResiIJ,pResiKS,1.0,energyTermsStructure);
}
}
EnergyTermWeighting(energyTermsStructure);
for(int j = 0; j < MAX_EVOEF_ENERGY_TERM_NUM; j++){
energyTermsStructure[0] += energyTermsStructure[j];
}
// energy terms are weighted during the calculation, don't weight them for the difference
printf("Binding energy details between chain(s) %s and chain(s) %s:\n",
ChainGetName(pChainI),ChainGetName(pChainK),ChainGetName(pChainI),ChainGetName(pChainK));
printf("reference_ALA = %8.2f\n", energyTermsStructure[21]);
printf("reference_CYS = %8.2f\n", energyTermsStructure[22]);
printf("reference_ASP = %8.2f\n", energyTermsStructure[23]);
printf("reference_GLU = %8.2f\n", energyTermsStructure[24]);
printf("reference_PHE = %8.2f\n", energyTermsStructure[25]);
printf("reference_GLY = %8.2f\n", energyTermsStructure[26]);
printf("reference_HIS = %8.2f\n", energyTermsStructure[27]);
printf("reference_ILE = %8.2f\n", energyTermsStructure[28]);
printf("reference_LYS = %8.2f\n", energyTermsStructure[29]);
printf("reference_LEU = %8.2f\n", energyTermsStructure[30]);
printf("reference_MET = %8.2f\n", energyTermsStructure[31]);
printf("reference_ASN = %8.2f\n", energyTermsStructure[32]);
printf("reference_PRO = %8.2f\n", energyTermsStructure[33]);
printf("reference_GLN = %8.2f\n", energyTermsStructure[34]);
printf("reference_ARG = %8.2f\n", energyTermsStructure[35]);
printf("reference_SER = %8.2f\n", energyTermsStructure[36]);
printf("reference_THR = %8.2f\n", energyTermsStructure[37]);
printf("reference_VAL = %8.2f\n", energyTermsStructure[38]);
printf("reference_TRP = %8.2f\n", energyTermsStructure[39]);
printf("reference_TYR = %8.2f\n", energyTermsStructure[40]);
printf("intraR_vdwatt = %8.2f\n", energyTermsStructure[6]);
printf("intraR_vdwrep = %8.2f\n", energyTermsStructure[7]);
printf("intraR_electr = %8.2f\n", energyTermsStructure[8]);
printf("intraR_deslvP = %8.2f\n", energyTermsStructure[9]);
printf("intraR_deslvH = %8.2f\n", energyTermsStructure[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTermsStructure[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTermsStructure[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTermsStructure[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTermsStructure[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTermsStructure[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTermsStructure[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTermsStructure[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTermsStructure[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTermsStructure[49]);
printf("interS_vdwatt = %8.2f\n", energyTermsStructure[1]);
printf("interS_vdwrep = %8.2f\n", energyTermsStructure[2]);
printf("interS_electr = %8.2f\n", energyTermsStructure[3]);
printf("interS_deslvP = %8.2f\n", energyTermsStructure[4]);
printf("interS_deslvH = %8.2f\n", energyTermsStructure[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTermsStructure[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTermsStructure[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTermsStructure[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTermsStructure[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTermsStructure[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTermsStructure[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTermsStructure[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTermsStructure[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTermsStructure[19]);
printf("interD_vdwatt = %8.2f\n", energyTermsStructure[51]);
printf("interD_vdwrep = %8.2f\n", energyTermsStructure[52]);
printf("interD_electr = %8.2f\n", energyTermsStructure[53]);
printf("interD_deslvP = %8.2f\n", energyTermsStructure[54]);
printf("interD_deslvH = %8.2f\n", energyTermsStructure[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTermsStructure[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTermsStructure[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTermsStructure[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTermsStructure[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTermsStructure[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTermsStructure[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTermsStructure[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTermsStructure[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTermsStructure[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n", energyTermsStructure[0]);
}
}
return Success;
}
int EvoEF_ComputeBindingWithSplitting(Structure *pStructure, double *energyTerms,char split1[], char split2[]){
double energyTermsStructure[MAX_EVOEF_ENERGY_TERM_NUM];
double energyTermsPart[MAX_EVOEF_ENERGY_TERM_NUM];
double energyTermsPartSum[MAX_EVOEF_ENERGY_TERM_NUM];
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTermsStructure[i] = 0.0;
energyTermsPart[i] = 0.0;
energyTermsPartSum[i] = 0.0;
}
EvoEF_ComputeStability(pStructure, energyTermsStructure);
EvoEF_ComputeStabilityForSelectedChains(pStructure,energyTermsPart,split1);
for(int j = 0; j < MAX_EVOEF_ENERGY_TERM_NUM; j++){
energyTermsPartSum[j] += energyTermsPart[j];
}
EvoEF_ComputeStabilityForSelectedChains(pStructure,energyTermsPart,split2);
for(int j = 0; j < MAX_EVOEF_ENERGY_TERM_NUM; j++){
energyTermsPartSum[j] += energyTermsPart[j];
}
// energy terms are weighted during the calculation, don't weight them for the difference
printf("Binding energy details between chain(s) %s and chain(s) %s (DG_bind = DG(stability,complex) - DG(stability,%s) - DG(stability,%s):\n",split1,split2,split1,split2);
printf("reference_ALA = %8.2f\n", energyTermsStructure[21] - energyTermsPartSum[21]);
printf("reference_CYS = %8.2f\n", energyTermsStructure[22] - energyTermsPartSum[22]);
printf("reference_ASP = %8.2f\n", energyTermsStructure[23] - energyTermsPartSum[23]);
printf("reference_GLU = %8.2f\n", energyTermsStructure[24] - energyTermsPartSum[24]);
printf("reference_PHE = %8.2f\n", energyTermsStructure[25] - energyTermsPartSum[25]);
printf("reference_GLY = %8.2f\n", energyTermsStructure[26] - energyTermsPartSum[26]);
printf("reference_HIS = %8.2f\n", energyTermsStructure[27] - energyTermsPartSum[27]);
printf("reference_ILE = %8.2f\n", energyTermsStructure[28] - energyTermsPartSum[28]);
printf("reference_LYS = %8.2f\n", energyTermsStructure[29] - energyTermsPartSum[29]);
printf("reference_LEU = %8.2f\n", energyTermsStructure[30] - energyTermsPartSum[30]);
printf("reference_MET = %8.2f\n", energyTermsStructure[31] - energyTermsPartSum[31]);
printf("reference_ASN = %8.2f\n", energyTermsStructure[32] - energyTermsPartSum[32]);
printf("reference_PRO = %8.2f\n", energyTermsStructure[33] - energyTermsPartSum[33]);
printf("reference_GLN = %8.2f\n", energyTermsStructure[34] - energyTermsPartSum[34]);
printf("reference_ARG = %8.2f\n", energyTermsStructure[35] - energyTermsPartSum[35]);
printf("reference_SER = %8.2f\n", energyTermsStructure[36] - energyTermsPartSum[36]);
printf("reference_THR = %8.2f\n", energyTermsStructure[37] - energyTermsPartSum[37]);
printf("reference_VAL = %8.2f\n", energyTermsStructure[38] - energyTermsPartSum[38]);
printf("reference_TRP = %8.2f\n", energyTermsStructure[39] - energyTermsPartSum[39]);
printf("reference_TYR = %8.2f\n", energyTermsStructure[40] - energyTermsPartSum[40]);
printf("intraR_vdwatt = %8.2f\n", energyTermsStructure[6] - energyTermsPartSum[6]);
printf("intraR_vdwrep = %8.2f\n", energyTermsStructure[7] - energyTermsPartSum[7]);
printf("intraR_electr = %8.2f\n", energyTermsStructure[8] - energyTermsPartSum[8]);
printf("intraR_deslvP = %8.2f\n", energyTermsStructure[9] - energyTermsPartSum[9]);
printf("intraR_deslvH = %8.2f\n", energyTermsStructure[10] - energyTermsPartSum[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTermsStructure[41] - energyTermsPartSum[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTermsStructure[42] - energyTermsPartSum[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTermsStructure[43] - energyTermsPartSum[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTermsStructure[44] - energyTermsPartSum[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTermsStructure[45] - energyTermsPartSum[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTermsStructure[46] - energyTermsPartSum[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTermsStructure[47] - energyTermsPartSum[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTermsStructure[48] - energyTermsPartSum[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTermsStructure[49] - energyTermsPartSum[49]);
printf("interS_vdwatt = %8.2f\n", energyTermsStructure[1] - energyTermsPartSum[1]);
printf("interS_vdwrep = %8.2f\n", energyTermsStructure[2] - energyTermsPartSum[2]);
printf("interS_electr = %8.2f\n", energyTermsStructure[3] - energyTermsPartSum[3]);
printf("interS_deslvP = %8.2f\n", energyTermsStructure[4] - energyTermsPartSum[4]);
printf("interS_deslvH = %8.2f\n", energyTermsStructure[5] - energyTermsPartSum[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTermsStructure[11] - energyTermsPartSum[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTermsStructure[12] - energyTermsPartSum[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTermsStructure[13] - energyTermsPartSum[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTermsStructure[14] - energyTermsPartSum[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTermsStructure[15] - energyTermsPartSum[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTermsStructure[16] - energyTermsPartSum[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTermsStructure[17] - energyTermsPartSum[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTermsStructure[18] - energyTermsPartSum[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTermsStructure[19] - energyTermsPartSum[19]);
printf("interD_vdwatt = %8.2f\n", energyTermsStructure[51] - energyTermsPartSum[51]);
printf("interD_vdwrep = %8.2f\n", energyTermsStructure[52] - energyTermsPartSum[52]);
printf("interD_electr = %8.2f\n", energyTermsStructure[53] - energyTermsPartSum[53]);
printf("interD_deslvP = %8.2f\n", energyTermsStructure[54] - energyTermsPartSum[54]);
printf("interD_deslvH = %8.2f\n", energyTermsStructure[55] - energyTermsPartSum[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTermsStructure[61] - energyTermsPartSum[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTermsStructure[62] - energyTermsPartSum[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTermsStructure[63] - energyTermsPartSum[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTermsStructure[64] - energyTermsPartSum[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTermsStructure[65] - energyTermsPartSum[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTermsStructure[66] - energyTermsPartSum[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTermsStructure[67] - energyTermsPartSum[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTermsStructure[68] - energyTermsPartSum[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTermsStructure[69] - energyTermsPartSum[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n", energyTermsStructure[0] - energyTermsPartSum[0]);
return Success;
}
int EvoEF_ComputeBindingWithSplittingNew(Structure *pStructure, double *energyTerms,char split1[], char split2[]){
double energyTermsStructure[MAX_EVOEF_ENERGY_TERM_NUM];
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTermsStructure[i] = 0.0;
}
for(int i=0;i<StructureGetChainCount(pStructure);i++){
Chain* pChainI=StructureGetChain(pStructure,i);
for(int k=i+1;k<StructureGetChainCount(pStructure);k++){
Chain* pChainK=StructureGetChain(pStructure,k);
if((strstr(split1,ChainGetName(pChainI))!=NULL && strstr(split2,ChainGetName(pChainK))!=NULL)||
((strstr(split2,ChainGetName(pChainI))!=NULL && strstr(split1,ChainGetName(pChainK))!=NULL))){
for(int j=0;j<ChainGetResidueCount(pChainI);j++){
Residue* pResiIJ=ChainGetResidue(pChainI,j);
for(int s=0;s<ChainGetResidueCount(pChainK);s++){
Residue* pResiKS=ChainGetResidue(pChainK,s);
EVOEF_EnergyResidueAndOtherResidueDifferentChain(pResiIJ,pResiKS,1.0,energyTermsStructure);
}
}
}
}
}
EnergyTermWeighting(energyTermsStructure);
for(int j = 0; j < MAX_EVOEF_ENERGY_TERM_NUM; j++){
energyTermsStructure[0] += energyTermsStructure[j];
}
// energy terms are weighted during the calculation, don't weight them for the difference
printf("Binding energy details between chain(s) %s and chain(s) %s (DG_bind = DG(stability,complex) - DG(stability,%s) - DG(stability,%s):\n",split1,split2,split1,split2);
printf("reference_ALA = %8.2f\n", energyTermsStructure[21]);
printf("reference_CYS = %8.2f\n", energyTermsStructure[22]);
printf("reference_ASP = %8.2f\n", energyTermsStructure[23]);
printf("reference_GLU = %8.2f\n", energyTermsStructure[24]);
printf("reference_PHE = %8.2f\n", energyTermsStructure[25]);
printf("reference_GLY = %8.2f\n", energyTermsStructure[26]);
printf("reference_HIS = %8.2f\n", energyTermsStructure[27]);
printf("reference_ILE = %8.2f\n", energyTermsStructure[28]);
printf("reference_LYS = %8.2f\n", energyTermsStructure[29]);
printf("reference_LEU = %8.2f\n", energyTermsStructure[30]);
printf("reference_MET = %8.2f\n", energyTermsStructure[31]);
printf("reference_ASN = %8.2f\n", energyTermsStructure[32]);
printf("reference_PRO = %8.2f\n", energyTermsStructure[33]);
printf("reference_GLN = %8.2f\n", energyTermsStructure[34]);
printf("reference_ARG = %8.2f\n", energyTermsStructure[35]);
printf("reference_SER = %8.2f\n", energyTermsStructure[36]);
printf("reference_THR = %8.2f\n", energyTermsStructure[37]);
printf("reference_VAL = %8.2f\n", energyTermsStructure[38]);
printf("reference_TRP = %8.2f\n", energyTermsStructure[39]);
printf("reference_TYR = %8.2f\n", energyTermsStructure[40]);
printf("intraR_vdwatt = %8.2f\n", energyTermsStructure[6]);
printf("intraR_vdwrep = %8.2f\n", energyTermsStructure[7]);
printf("intraR_electr = %8.2f\n", energyTermsStructure[8]);
printf("intraR_deslvP = %8.2f\n", energyTermsStructure[9]);
printf("intraR_deslvH = %8.2f\n", energyTermsStructure[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTermsStructure[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTermsStructure[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTermsStructure[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTermsStructure[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTermsStructure[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTermsStructure[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTermsStructure[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTermsStructure[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTermsStructure[49]);
printf("interS_vdwatt = %8.2f\n", energyTermsStructure[1]);
printf("interS_vdwrep = %8.2f\n", energyTermsStructure[2]);
printf("interS_electr = %8.2f\n", energyTermsStructure[3]);
printf("interS_deslvP = %8.2f\n", energyTermsStructure[4]);
printf("interS_deslvH = %8.2f\n", energyTermsStructure[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTermsStructure[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTermsStructure[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTermsStructure[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTermsStructure[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTermsStructure[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTermsStructure[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTermsStructure[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTermsStructure[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTermsStructure[19]);
printf("interD_vdwatt = %8.2f\n", energyTermsStructure[51]);
printf("interD_vdwrep = %8.2f\n", energyTermsStructure[52]);
printf("interD_electr = %8.2f\n", energyTermsStructure[53]);
printf("interD_deslvP = %8.2f\n", energyTermsStructure[54]);
printf("interD_deslvH = %8.2f\n", energyTermsStructure[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTermsStructure[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTermsStructure[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTermsStructure[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTermsStructure[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTermsStructure[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTermsStructure[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTermsStructure[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTermsStructure[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTermsStructure[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n", energyTermsStructure[0]);
return Success;
}
//this function is used to build the structure model of mutations
int EvoEF_BuildMutant(Structure* pStructure, char* mutantfile, RotamerLib* rotlib, AtomParamsSet* atomParams,ResiTopoSet* resiTopos, char* pdbid){
FileReader fr;
if(FAILED(FileReaderCreate(&fr, mutantfile))){
printf("in file %s line %d, mutant file not found\n",__FILE__,__LINE__);
exit(IOError);
}
int mutantcount = FileReaderGetLineCount(&fr);
if(mutantcount<=0){
printf("in file %s line %d, no mutation found in the mutant file\n",__FILE__,__LINE__);
exit(DataNotExistError);
}
StringArray* mutants = (StringArray*)malloc(sizeof(StringArray)*mutantcount);
char line[MAX_LENGTH_ONE_LINE_IN_FILE+1];
int mutantIndex=0;
while(!FAILED(FileReaderGetNextLine(&fr, line))){
StringArrayCreate(&mutants[mutantIndex]);
StringArraySplitString(&mutants[mutantIndex], line, ',');
char lastMutant[MAX_LENGTH_ONE_LINE_IN_FILE+1];
int lastmutindex = StringArrayGetCount(&mutants[mutantIndex])-1;
strcpy(lastMutant, StringArrayGet(&mutants[mutantIndex], lastmutindex));
//deal with the last char of the last single mutant
if((!isdigit(lastMutant[strlen(lastMutant)-1])) && !isalpha(lastMutant[strlen(lastMutant)-1])){
lastMutant[strlen(lastMutant)-1] = '\0';
}
StringArraySet(&mutants[mutantIndex], lastmutindex, lastMutant);
mutantIndex++;
}
FileReaderDestroy(&fr);
for(int mutantIndex = 0; mutantIndex < mutantcount; mutantIndex++){
Structure tempStruct;
StructureCreate(&tempStruct);
StructureCopy(&tempStruct,pStructure);
//for each mutant, build the rotamer-tree
IntArray mutatedArray,rotamersArray;
IntArrayCreate(&mutatedArray,0);
IntArrayCreate(&rotamersArray,0);
for(int posIndex=0; posIndex<StringArrayGetCount(&mutants[mutantIndex]); posIndex++){
char mutstr[10];
char aa1, chn, aa2;
int posInChain;
strcpy(mutstr, StringArrayGet(&mutants[mutantIndex], posIndex));
sscanf(mutstr, "%c%c%d%c", &aa1, &chn, &posInChain, &aa2);
int chainIndex = -1, residueIndex = -1;
char chainname[MAX_LENGTH_CHAIN_NAME]; chainname[0] = chn; chainname[1] = '\0';
StructureFindChain(&tempStruct, chainname, &chainIndex);
if(chainIndex==-1){
printf("in file %s function %s() line %d, cannot find mutation %s\n", __FILE__, __FUNCTION__, __LINE__, mutstr);
exit(ValueError);
}
ChainFindResidueByPosInChain(StructureGetChain(&tempStruct, chainIndex), posInChain, &residueIndex);
if(residueIndex==-1){
printf("in file %s function %s() line %d, cannot find mutation %s\n", __FILE__, __FUNCTION__, __LINE__, mutstr);
exit(ValueError);
}
char mutaatype[MAX_LENGTH_RESIDUE_NAME];
OneLetterAAToThreeLetterAA(aa2, mutaatype);
StringArray designType, patchType;
StringArrayCreate(&designType);
StringArrayCreate(&patchType);
// for histidine, the default mutaatype is HSD, we need to add HSE
StringArrayAppend(&designType, mutaatype); StringArrayAppend(&patchType, "");
if(aa2=='H'){StringArrayAppend(&designType, "HSE"); StringArrayAppend(&patchType, "");}
ProteinSiteBuildMutatedRotamers(&tempStruct, chainIndex, residueIndex, rotlib, atomParams, resiTopos, &designType, &patchType);
IntArrayAppend(&mutatedArray, chainIndex);
IntArrayAppend(&mutatedArray, residueIndex);
IntArrayAppend(&rotamersArray,chainIndex);
IntArrayAppend(&rotamersArray,residueIndex);
StringArrayDestroy(&designType);
StringArrayDestroy(&patchType);
}
//build rotamers for surrounding residues
for(int ii=0; ii<IntArrayGetLength(&mutatedArray); ii+=2){
int chainIndex = IntArrayGet(&mutatedArray,ii);
int resiIndex = IntArrayGet(&mutatedArray,ii+1);
Residue *pResi1 = ChainGetResidue(StructureGetChain(&tempStruct, chainIndex), resiIndex);
for(int j = 0; j < StructureGetChainCount(&tempStruct); ++j){
Chain* pChain = StructureGetChain(&tempStruct,j);
for(int k=0; k<ChainGetResidueCount(pChain); k++){
Residue* pResi2 = ChainGetResidue(pChain,k);
if(AtomArrayCalcMinDistance(&pResi1->atoms,&pResi2->atoms)<VDW_DISTANCE_CUTOFF){
if(pResi2->designSiteType==Type_ResidueDesignType_Fixed){
ProteinSiteBuildWildtypeRotamers(&tempStruct,j,k,rotlib,atomParams,resiTopos);
ProteinSiteAddCrystalRotamer(&tempStruct,j,k,resiTopos);
IntArrayAppend(&rotamersArray,j);
IntArrayAppend(&rotamersArray,k);
}
}
}
}
}
// optimization rotamers sequentially
printf("EvoEF Building Mutation Model %d, the following sites will be optimized:\n",mutantIndex+1);
//IntArrayShow(&rotamersArray);
//printf("\n");
printf("chnIndex resIndex (both of them starts from zero on the chain)\n");
for(int ii=0;ii<IntArrayGetLength(&rotamersArray);ii+=2){
printf("%8d %8d\n",IntArrayGet(&rotamersArray,ii),IntArrayGet(&rotamersArray,ii+1));
}
for(int cycle=0; cycle<10; cycle++){
printf("optimization cycle %d ...\n",cycle+1);
for(int ii=0; ii<IntArrayGetLength(&rotamersArray); ii+=2){
int chainIndex = IntArrayGet(&rotamersArray, ii);
int resiIndex = IntArrayGet(&rotamersArray, ii+1);
//ProteinSiteOptimizeRotamer(pStructure, chainIndex, resiIndex);
ProteinSiteOptimizeRotamerLocally(&tempStruct,chainIndex,resiIndex,1.0);
}
}
IntArrayDestroy(&mutatedArray);
IntArrayDestroy(&rotamersArray);
//remember to delete rotamers for previous mutant
StructureRemoveAllDesignSites(&tempStruct);
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL)
sprintf(modelfile,"%s_Model_%04d.pdb",pdbid,mutantIndex+1);
else
sprintf(modelfile,"EvoEF_Model_%04d.pdb",mutantIndex+1);
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <BuildMutant>\n");
StructureShowInPDBFormat(&tempStruct,TRUE,pf);
fclose(pf);
StructureDestroy(&tempStruct);
}
return Success;
}
int EvoEF_RepairStructure(Structure* pStructure, RotamerLib* rotlib, AtomParamsSet* atomParams,ResiTopoSet* resiTopos, char* pdbid){
for(int cycle=0; cycle<3; cycle++){
printf("EvoEF Repairing PDB: optimization cycle %d ...\n",cycle+1);
for(int i=0; i<StructureGetChainCount(pStructure); ++i){
Chain* pChain = StructureGetChain(pStructure, i);
for(int j=0; j<ChainGetResidueCount(pChain); j++){
Residue* pResi = ChainGetResidue(pChain, j);
//skip CYS which may form disulfide bonds
if(strcmp(ResidueGetName(pResi),"CYS")==0) continue;
if(strcmp(ResidueGetName(pResi),"ASN")==0||strcmp(ResidueGetName(pResi),"GLN")==0||strcmp(ResidueGetName(pResi),"HSD")==0||strcmp(ResidueGetName(pResi),"HSE")==0){
printf("Flip residue %s%d%c to optimize hbond\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteBuildFlippedCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteOptimizeRotamerHBondEnergy(pStructure,i,j);
}
else if(strcmp(ResidueGetName(pResi),"SER")==0 || strcmp(ResidueGetName(pResi),"THR")==0 || strcmp(ResidueGetName(pResi),"TYR")==0){
printf("Rotate hydroxyl group of residue %s%d%c to optimize hbond\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteExpandHydroxylRotamers(pStructure,i,j,resiTopos);
ProteinSiteOptimizeRotamerHBondEnergy(pStructure,i,j);
}
if(TRUE){
printf("Optimize side chain of residue %s%d%c\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteBuildWildtypeRotamers(pStructure,i,j,rotlib,atomParams,resiTopos);
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteExpandHydroxylRotamers(pStructure,i,j,resiTopos);
//ProteinSiteOptimizeRotamer(pStructure,i,j);
ProteinSiteOptimizeRotamerLocally(pStructure,i,j, 1.0);
}
ProteinSiteRemoveDesignSite(pStructure,i,j);
}
}
}
//output the repaired structure
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL){sprintf(modelfile,"%s_Repair.pdb",pdbid);}
else{strcpy(modelfile,"EvoEF_Repair.pdb");}
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <RepairStructure>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
return Success;
}
int EvoEF_WriteStructureToFile(Structure* pStructure, char* pdbfile){
FILE* pf=fopen(pdbfile,"w");
if(pf!=NULL){
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
}
else{
printf("failed to open file for writing structure coordinates\n");
return IOError;
}
return Success;
}
int EvoEF_AddHydrogen(Structure* pStructure, char* pdbid){
//polar hydrogens are automatically added, so we just output the repaired structure
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL){sprintf(modelfile,"%s_PolH.pdb",pdbid);}
else{strcpy(modelfile,"EvoEF_PolH.pdb");}
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <AddHydrogen>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
return Success;
}
int EvoEF_OptimizeHydrogen(Structure* pStructure, AtomParamsSet* atomParams,ResiTopoSet* resiTopos, char* pdbid){
for(int cycle=0; cycle<3; cycle++){
printf("EvoEF Repairing PDB: optimization cycle %d ...\n",cycle+1);
for(int i=0; i<StructureGetChainCount(pStructure); ++i){
Chain* pChain = StructureGetChain(pStructure, i);
for(int j=0; j<ChainGetResidueCount(pChain); j++){
Residue* pResi = ChainGetResidue(pChain, j);
if(strcmp(ResidueGetName(pResi),"SER")==0 || strcmp(ResidueGetName(pResi),"THR")==0 || strcmp(ResidueGetName(pResi),"TYR")==0){
printf("We will rotate hydroxyl group of residue %s%d%c to optimize hbond\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteExpandHydroxylRotamers(pStructure,i,j,resiTopos);
ProteinSiteOptimizeRotamerHBondEnergy(pStructure,i,j);
ProteinSiteRemoveDesignSite(pStructure,i,j);
}
}
}
}
//output the repaired structure
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL){sprintf(modelfile,"%s_OptH.pdb",pdbid);}
else{strcpy(modelfile,"EvoEF_OptH.pdb");}
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <OptimizeHydrogen>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
return Success;
}
| 60.367925 | 194 | 0.611932 | [
"model"
] |
6200103247017526893112d9fd5a362adf4c7d25 | 744 | hpp | C++ | functional_mapping_helper/include/functional_mapping_helper/GeometricalConstructs/RotationMatrix.hpp | talkingrobots/GeoCompROS | f934e0f98377aef21c791a0d0efffad84be1e37b | [
"BSD-3-Clause"
] | null | null | null | functional_mapping_helper/include/functional_mapping_helper/GeometricalConstructs/RotationMatrix.hpp | talkingrobots/GeoCompROS | f934e0f98377aef21c791a0d0efffad84be1e37b | [
"BSD-3-Clause"
] | null | null | null | functional_mapping_helper/include/functional_mapping_helper/GeometricalConstructs/RotationMatrix.hpp | talkingrobots/GeoCompROS | f934e0f98377aef21c791a0d0efffad84be1e37b | [
"BSD-3-Clause"
] | 1 | 2019-05-09T11:40:00.000Z | 2019-05-09T11:40:00.000Z | #ifndef FUNCTIONALMAPPING_ROTATION_MATRIX_HPP
#define FUNCTIONALMAPPING_ROTATION_MATRIX_HPP
#include <ros/ros.h>
#include <functional_mapping_helper/GeometricalConstructs/Vector.hpp>
#include <LinearMath/btQuaternion.h>
class RotationMatrix
{
// | e11 e12 e13 |
// | e21 e22 e23 |
// | e31 e32 e33 |
float e11, e12, e13, e21, e22, e23, e31, e32, e33;
friend bool operator==(const RotationMatrix &r1, const RotationMatrix &r2);
public:
void initRotationMatrix(float el11, float el12, float el13, float el21, float el22, float el23, float el31, float el32, float el33);
RotationMatrix(geometry_msgs::Vector3 fromVector, geometry_msgs::Vector3 toVector);
geometry_msgs::Vector3 operator*(geometry_msgs::Vector3 multVec);
};
#endif
| 31 | 133 | 0.767473 | [
"vector"
] |
620aa3493e9bb5aed6ebafbcc6540a6423d5176e | 403 | hpp | C++ | rpg-engine/include/rpg-engine/Element.hpp | Krozark/rpg-engine | c705f777d0382b26b695ea1e3672328887bca39f | [
"BSD-2-Clause"
] | 1 | 2018-07-09T21:49:01.000Z | 2018-07-09T21:49:01.000Z | rpg-engine/include/rpg-engine/Element.hpp | Krozark/rpg-engine | c705f777d0382b26b695ea1e3672328887bca39f | [
"BSD-2-Clause"
] | 1 | 2015-03-12T10:29:26.000Z | 2015-03-12T10:29:26.000Z | rpg-engine/include/rpg-engine/Element.hpp | Krozark/rpg-engine | c705f777d0382b26b695ea1e3672328887bca39f | [
"BSD-2-Clause"
] | null | null | null | #ifndef RPG_ELEMENT_HPP
#define RPG_ELEMENT_HPP
#include <string>
#include <vector>
namespace rpg
{
enum Elements{Eau=0,
Feu,
Terre,
Aire,
Neutre,
Lumiere,
Ombre,
Size};
namespace element
{
static float Oppose[Elements::Size][Elements::Size];
void init();
float get(Elements _1,Elements _2);
}
}
#endif
| 14.925926 | 60 | 0.565757 | [
"vector"
] |
6216f3572ff9fe76bd74496acbfb5876de83773b | 1,638 | cpp | C++ | third_party/libosmium/test/t/basic/test_entity_bits.cpp | motis-project/osrm-backend | 9aa492376a664304d8209513230bb43258367108 | [
"BSD-2-Clause"
] | null | null | null | third_party/libosmium/test/t/basic/test_entity_bits.cpp | motis-project/osrm-backend | 9aa492376a664304d8209513230bb43258367108 | [
"BSD-2-Clause"
] | null | null | null | third_party/libosmium/test/t/basic/test_entity_bits.cpp | motis-project/osrm-backend | 9aa492376a664304d8209513230bb43258367108 | [
"BSD-2-Clause"
] | null | null | null | #include "catch.hpp"
#include <osmium/osm/entity_bits.hpp>
TEST_CASE("entity_bits") {
SECTION("can_be_set_and_checked") {
osrm_osmium::osm_entity_bits::type entities = osrm_osmium::osm_entity_bits::node | osrm_osmium::osm_entity_bits::way;
REQUIRE(entities == (osrm_osmium::osm_entity_bits::node | osrm_osmium::osm_entity_bits::way));
entities |= osrm_osmium::osm_entity_bits::relation;
REQUIRE((entities & osrm_osmium::osm_entity_bits::object));
entities |= osrm_osmium::osm_entity_bits::area;
REQUIRE(entities == osrm_osmium::osm_entity_bits::object);
REQUIRE(! (entities & osrm_osmium::osm_entity_bits::changeset));
entities &= osrm_osmium::osm_entity_bits::node;
REQUIRE((entities & osrm_osmium::osm_entity_bits::node));
REQUIRE(! (entities & osrm_osmium::osm_entity_bits::way));
REQUIRE(entities == osrm_osmium::osm_entity_bits::node);
REQUIRE(osrm_osmium::osm_entity_bits::node == osrm_osmium::osm_entity_bits::from_item_type(osrm_osmium::item_type::node));
REQUIRE(osrm_osmium::osm_entity_bits::way == osrm_osmium::osm_entity_bits::from_item_type(osrm_osmium::item_type::way));
REQUIRE(osrm_osmium::osm_entity_bits::relation == osrm_osmium::osm_entity_bits::from_item_type(osrm_osmium::item_type::relation));
REQUIRE(osrm_osmium::osm_entity_bits::changeset == osrm_osmium::osm_entity_bits::from_item_type(osrm_osmium::item_type::changeset));
REQUIRE(osrm_osmium::osm_entity_bits::area == osrm_osmium::osm_entity_bits::from_item_type(osrm_osmium::item_type::area));
}
}
| 51.1875 | 140 | 0.721612 | [
"object"
] |
6217089cd5e34b291ddc29a7cbe7506e222a6b33 | 87,238 | cc | C++ | third_party/blink/renderer/core/input/event_handler.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/input/event_handler.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/input/event_handler.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights
* reserved.
* Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2012 Digia Plc. and/or its subsidiary(-ies)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/input/event_handler.h"
#include <memory>
#include <utility>
#include "build/build_config.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "third_party/blink/renderer/bindings/core/v8/exception_state.h"
#include "third_party/blink/renderer/core/clipboard/data_transfer.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/events/event_path.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/selection_controller.h"
#include "third_party/blink/renderer/core/events/gesture_event.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/events/pointer_event.h"
#include "third_party/blink/renderer/core/events/text_event.h"
#include "third_party/blink/renderer/core/events/touch_event.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/event_handler_registry.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_frame_set_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input/event_handling_util.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/input/touch_action_util.h"
#include "third_party/blink/renderer/core/input/touch_list.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/core/layout/hit_test_request.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/drag_state.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/frame_tree.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scrolling/scroll_state.h"
#include "third_party/blink/renderer/core/page/touch_adjustment.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/cursor_data.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar.h"
#include "third_party/blink/renderer/platform/windows_keyboard_codes.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
namespace {
// Refetch the event target node if it is removed or currently is the shadow
// node inside an <input> element. If a mouse event handler changes the input
// element type to one that has a EmbeddedContentView associated, we'd like to
// EventHandler::handleMousePressEvent to pass the event to the
// EmbeddedContentView and thus the event target node can't still be the shadow
// node.
bool ShouldRefetchEventTarget(const MouseEventWithHitTestResults& mev) {
Node* target_node = mev.InnerNode();
if (!target_node || !target_node->parentNode())
return true;
return target_node->IsShadowRoot() &&
IsHTMLInputElement(ToShadowRoot(target_node)->host());
}
} // namespace
using namespace HTMLNames;
// The amount of time to wait for a cursor update on style and layout changes
// Set to 50Hz, no need to be faster than common screen refresh rate
static const double kCursorUpdateInterval = 0.02;
static const int kMaximumCursorSize = 128;
// It's pretty unlikely that a scale of less than one would ever be used. But
// all we really need to ensure here is that the scale isn't so small that
// integer overflow can occur when dividing cursor sizes (limited above) by the
// scale.
static const double kMinimumCursorScale = 0.001;
// The minimum amount of time an element stays active after a ShowPress
// This is roughly 9 frames, which should be long enough to be noticeable.
constexpr TimeDelta kMinimumActiveInterval = TimeDelta::FromSecondsD(0.15);
EventHandler::EventHandler(LocalFrame& frame)
: frame_(frame),
selection_controller_(SelectionController::Create(frame)),
hover_timer_(frame.GetTaskRunner(TaskType::kUserInteraction),
this,
&EventHandler::HoverTimerFired),
cursor_update_timer_(
frame.GetTaskRunner(TaskType::kInternalUserInteraction),
this,
&EventHandler::CursorUpdateTimerFired),
event_handler_will_reset_capturing_mouse_events_node_(0),
should_only_fire_drag_over_event_(false),
event_handler_registry_(
frame_->IsLocalRoot()
? new EventHandlerRegistry(*frame_)
: &frame_->LocalFrameRoot().GetEventHandlerRegistry()),
scroll_manager_(new ScrollManager(frame)),
mouse_event_manager_(new MouseEventManager(frame, *scroll_manager_)),
mouse_wheel_event_manager_(new MouseWheelEventManager(frame)),
keyboard_event_manager_(
new KeyboardEventManager(frame, *scroll_manager_)),
pointer_event_manager_(
new PointerEventManager(frame, *mouse_event_manager_)),
gesture_manager_(new GestureManager(frame,
*scroll_manager_,
*mouse_event_manager_,
*pointer_event_manager_,
*selection_controller_)),
active_interval_timer_(frame.GetTaskRunner(TaskType::kUserInteraction),
this,
&EventHandler::ActiveIntervalTimerFired) {}
void EventHandler::Trace(blink::Visitor* visitor) {
visitor->Trace(frame_);
visitor->Trace(selection_controller_);
visitor->Trace(capturing_mouse_events_node_);
visitor->Trace(last_mouse_move_event_subframe_);
visitor->Trace(last_scrollbar_under_mouse_);
visitor->Trace(drag_target_);
visitor->Trace(frame_set_being_resized_);
visitor->Trace(event_handler_registry_);
visitor->Trace(scroll_manager_);
visitor->Trace(mouse_event_manager_);
visitor->Trace(mouse_wheel_event_manager_);
visitor->Trace(keyboard_event_manager_);
visitor->Trace(pointer_event_manager_);
visitor->Trace(gesture_manager_);
visitor->Trace(last_deferred_tap_element_);
}
void EventHandler::Clear() {
hover_timer_.Stop();
cursor_update_timer_.Stop();
active_interval_timer_.Stop();
last_mouse_move_event_subframe_ = nullptr;
last_scrollbar_under_mouse_ = nullptr;
frame_set_being_resized_ = nullptr;
drag_target_ = nullptr;
should_only_fire_drag_over_event_ = false;
last_mouse_down_user_gesture_token_ = nullptr;
capturing_mouse_events_node_ = nullptr;
pointer_event_manager_->Clear();
scroll_manager_->Clear();
gesture_manager_->Clear();
mouse_event_manager_->Clear();
mouse_wheel_event_manager_->Clear();
last_show_press_timestamp_.reset();
last_deferred_tap_element_ = nullptr;
event_handler_will_reset_capturing_mouse_events_node_ = false;
should_use_touch_event_adjusted_point_ = false;
touch_adjustment_result_.unique_event_id = 0;
}
void EventHandler::UpdateSelectionForMouseDrag() {
mouse_event_manager_->UpdateSelectionForMouseDrag();
}
void EventHandler::StartMiddleClickAutoscroll(LayoutObject* layout_object) {
DCHECK(RuntimeEnabledFeatures::MiddleClickAutoscrollEnabled());
if (!layout_object->IsBox())
return;
AutoscrollController* controller = scroll_manager_->GetAutoscrollController();
if (!controller)
return;
controller->StartMiddleClickAutoscroll(
layout_object->GetFrame(),
frame_->GetPage()->GetVisualViewport().ViewportToRootFrame(
mouse_event_manager_->LastKnownMousePosition()),
mouse_event_manager_->LastKnownMousePositionGlobal());
mouse_event_manager_->InvalidateClick();
}
HitTestResult EventHandler::HitTestResultAtPoint(
const LayoutPoint& point,
HitTestRequest::HitTestRequestType hit_type,
const LayoutRectOutsets& padding,
const LayoutObject* stop_node) {
TRACE_EVENT0("blink", "EventHandler::hitTestResultAtPoint");
DCHECK((hit_type & HitTestRequest::kListBased) || padding.IsZero());
// We always send hitTestResultAtPoint to the main frame if we have one,
// otherwise we might hit areas that are obscured by higher frames.
if (frame_->GetPage()) {
LocalFrame& main_frame = frame_->LocalFrameRoot();
if (frame_ != &main_frame) {
LocalFrameView* frame_view = frame_->View();
LocalFrameView* main_view = main_frame.View();
if (frame_view && main_view) {
LayoutPoint main_content_point = main_view->RootFrameToContents(
frame_view->ContentsToRootFrame(point));
return main_frame.GetEventHandler().HitTestResultAtPoint(
main_content_point, hit_type, padding);
}
}
}
// hitTestResultAtPoint is specifically used to hitTest into all frames, thus
// it always allows child frame content.
HitTestRequest request(hit_type | HitTestRequest::kAllowChildFrameContent,
stop_node);
HitTestResult result(request, point, padding);
// LayoutView::hitTest causes a layout, and we don't want to hit that until
// the first layout because until then, there is nothing shown on the screen -
// the user can't have intentionally clicked on something belonging to this
// page. Furthermore, mousemove events before the first layout should not
// lead to a premature layout() happening, which could show a flash of white.
// See also the similar code in Document::performMouseEventHitTest.
// The check to LifecycleUpdatesActive() prevents hit testing to frames
// that have already had layout but are throttled to prevent painting
// because the current Document isn't ready to render yet. In that case
// the lifecycle update prompted by HitTest() would fail.
if (!frame_->ContentLayoutObject() || !frame_->View() ||
!frame_->View()->DidFirstLayout() ||
!frame_->View()->LifecycleUpdatesActive())
return result;
frame_->ContentLayoutObject()->HitTest(result);
if (!request.ReadOnly())
frame_->GetDocument()->UpdateHoverActiveState(request,
result.InnerElement());
return result;
}
void EventHandler::StopAutoscroll() {
scroll_manager_->StopMiddleClickAutoscroll();
scroll_manager_->StopAutoscroll();
}
// TODO(bokan): This should be merged with logicalScroll assuming
// defaultSpaceEventHandler's chaining scroll can be done crossing frames.
bool EventHandler::BubblingScroll(ScrollDirection direction,
ScrollGranularity granularity,
Node* starting_node) {
return scroll_manager_->BubblingScroll(
direction, granularity, starting_node,
mouse_event_manager_->MousePressNode());
}
IntPoint EventHandler::LastKnownMousePositionInRootFrame() const {
return frame_->GetPage()->GetVisualViewport().ViewportToRootFrame(
mouse_event_manager_->LastKnownMousePosition());
}
IntPoint EventHandler::DragDataTransferLocationForTesting() {
if (mouse_event_manager_->GetDragState().drag_data_transfer_)
return mouse_event_manager_->GetDragState()
.drag_data_transfer_->DragLocation();
return IntPoint();
}
static bool IsSubmitImage(Node* node) {
return IsHTMLInputElement(node) &&
ToHTMLInputElement(node)->type() == InputTypeNames::image;
}
bool EventHandler::UseHandCursor(Node* node, bool is_over_link) {
if (!node)
return false;
return ((is_over_link || IsSubmitImage(node)) && !HasEditableStyle(*node));
}
void EventHandler::CursorUpdateTimerFired(TimerBase*) {
DCHECK(frame_);
DCHECK(frame_->GetDocument());
UpdateCursor();
}
void EventHandler::UpdateCursor() {
TRACE_EVENT0("input", "EventHandler::updateCursor");
// We must do a cross-frame hit test because the frame that triggered the
// cursor update could be occluded by a different frame.
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
LocalFrameView* view = frame_->View();
if (!view || !view->ShouldSetCursor())
return;
auto* layout_view = view->GetLayoutView();
if (!layout_view)
return;
frame_->GetDocument()->UpdateStyleAndLayout();
HitTestRequest request(HitTestRequest::kReadOnly |
HitTestRequest::kAllowChildFrameContent);
HitTestResult result(
request,
view->ViewportToContents(mouse_event_manager_->LastKnownMousePosition()));
layout_view->HitTest(result);
if (LocalFrame* frame = result.InnerNodeFrame()) {
EventHandler::OptionalCursor optional_cursor =
frame->GetEventHandler().SelectCursor(result);
if (optional_cursor.IsCursorChange()) {
view->SetCursor(optional_cursor.GetCursor());
}
}
}
bool EventHandler::ShouldShowResizeForNode(const Node* node,
const HitTestResult& result) {
if (LayoutObject* layout_object = node->GetLayoutObject()) {
PaintLayer* layer = layout_object->EnclosingLayer();
if (layer->GetScrollableArea() &&
layer->GetScrollableArea()->IsPointInResizeControl(
result.RoundedPointInMainFrame(), kResizerForPointer)) {
return true;
}
}
return false;
}
bool EventHandler::IsSelectingLink(const HitTestResult& result) {
// If a drag may be starting or we're capturing mouse events for a particular
// node, don't treat this as a selection. Note calling
// ComputeVisibleSelectionInDOMTreeDeprecated may update layout.
const bool mouse_selection =
!capturing_mouse_events_node_ &&
mouse_event_manager_->MousePressed() &&
GetSelectionController().MouseDownMayStartSelect() &&
!mouse_event_manager_->MouseDownMayStartDrag() &&
!frame_->Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.IsNone();
return mouse_selection && result.IsOverLink();
}
bool EventHandler::ShouldShowIBeamForNode(const Node* node,
const HitTestResult& result) {
if (!node)
return false;
if (node->IsTextNode() && (node->CanStartSelection() || result.IsOverLink()))
return true;
return HasEditableStyle(*node);
}
EventHandler::OptionalCursor EventHandler::SelectCursor(
const HitTestResult& result) {
if (scroll_manager_->InResizeMode())
return kNoCursorChange;
Page* page = frame_->GetPage();
if (!page)
return kNoCursorChange;
if (scroll_manager_->MiddleClickAutoscrollInProgress())
return kNoCursorChange;
if (result.GetScrollbar())
return PointerCursor();
Node* node = result.InnerPossiblyPseudoNode();
if (!node)
return SelectAutoCursor(result, node, IBeamCursor());
if (ShouldShowResizeForNode(node, result))
return PointerCursor();
LayoutObject* layout_object = node->GetLayoutObject();
const ComputedStyle* style = layout_object ? layout_object->Style() : nullptr;
if (layout_object) {
Cursor override_cursor;
switch (layout_object->GetCursor(RoundedIntPoint(result.LocalPoint()),
override_cursor)) {
case kSetCursorBasedOnStyle:
break;
case kSetCursor:
return override_cursor;
case kDoNotSetCursor:
return kNoCursorChange;
}
}
if (style && style->Cursors()) {
const CursorList* cursors = style->Cursors();
for (unsigned i = 0; i < cursors->size(); ++i) {
StyleImage* style_image = (*cursors)[i].GetImage();
if (!style_image)
continue;
ImageResourceContent* cached_image = style_image->CachedImage();
if (!cached_image)
continue;
float scale = style_image->ImageScaleFactor();
bool hot_spot_specified = (*cursors)[i].HotSpotSpecified();
// Get hotspot and convert from logical pixels to physical pixels.
IntPoint hot_spot = (*cursors)[i].HotSpot();
hot_spot.Scale(scale, scale);
IntSize size = cached_image->GetImage()->Size();
if (cached_image->ErrorOccurred())
continue;
// Limit the size of cursors (in UI pixels) so that they cannot be
// used to cover UI elements in chrome.
size.Scale(1 / scale);
if (size.Width() > kMaximumCursorSize ||
size.Height() > kMaximumCursorSize)
continue;
Image* image = cached_image->GetImage();
// Ensure no overflow possible in calculations above.
if (scale < kMinimumCursorScale)
continue;
return Cursor(image, hot_spot_specified, hot_spot, scale);
}
}
bool horizontal_text = !style || style->IsHorizontalWritingMode();
const Cursor& i_beam = horizontal_text ? IBeamCursor() : VerticalTextCursor();
switch (style ? style->Cursor() : ECursor::kAuto) {
case ECursor::kAuto: {
return SelectAutoCursor(result, node, i_beam);
}
case ECursor::kCrosshair:
return CrossCursor();
case ECursor::kPointer:
return IsSelectingLink(result) ? i_beam : HandCursor();
case ECursor::kMove:
return MoveCursor();
case ECursor::kAllScroll:
return MoveCursor();
case ECursor::kEResize:
return EastResizeCursor();
case ECursor::kWResize:
return WestResizeCursor();
case ECursor::kNResize:
return NorthResizeCursor();
case ECursor::kSResize:
return SouthResizeCursor();
case ECursor::kNeResize:
return NorthEastResizeCursor();
case ECursor::kSwResize:
return SouthWestResizeCursor();
case ECursor::kNwResize:
return NorthWestResizeCursor();
case ECursor::kSeResize:
return SouthEastResizeCursor();
case ECursor::kNsResize:
return NorthSouthResizeCursor();
case ECursor::kEwResize:
return EastWestResizeCursor();
case ECursor::kNeswResize:
return NorthEastSouthWestResizeCursor();
case ECursor::kNwseResize:
return NorthWestSouthEastResizeCursor();
case ECursor::kColResize:
return ColumnResizeCursor();
case ECursor::kRowResize:
return RowResizeCursor();
case ECursor::kText:
return i_beam;
case ECursor::kWait:
return WaitCursor();
case ECursor::kHelp:
return HelpCursor();
case ECursor::kVerticalText:
return VerticalTextCursor();
case ECursor::kCell:
return CellCursor();
case ECursor::kContextMenu:
return ContextMenuCursor();
case ECursor::kProgress:
return ProgressCursor();
case ECursor::kNoDrop:
return NoDropCursor();
case ECursor::kAlias:
return AliasCursor();
case ECursor::kCopy:
return CopyCursor();
case ECursor::kNone:
return NoneCursor();
case ECursor::kNotAllowed:
return NotAllowedCursor();
case ECursor::kDefault:
return PointerCursor();
case ECursor::kZoomIn:
return ZoomInCursor();
case ECursor::kZoomOut:
return ZoomOutCursor();
case ECursor::kGrab:
return GrabCursor();
case ECursor::kGrabbing:
return GrabbingCursor();
}
return PointerCursor();
}
EventHandler::OptionalCursor EventHandler::SelectAutoCursor(
const HitTestResult& result,
Node* node,
const Cursor& i_beam) {
if (ShouldShowIBeamForNode(node, result))
return i_beam;
return PointerCursor();
}
WebInputEventResult EventHandler::DispatchBufferedTouchEvents() {
return pointer_event_manager_->FlushEvents();
}
WebInputEventResult EventHandler::HandlePointerEvent(
const WebPointerEvent& web_pointer_event,
const Vector<WebPointerEvent>& coalesced_events) {
return pointer_event_manager_->HandlePointerEvent(web_pointer_event,
coalesced_events);
}
WebInputEventResult EventHandler::HandleMousePressEvent(
const WebMouseEvent& mouse_event) {
TRACE_EVENT0("blink", "EventHandler::handleMousePressEvent");
// For 4th/5th button in the mouse since Chrome does not yet send
// button value to Blink but in some cases it does send the event.
// This check is needed to suppress such an event (crbug.com/574959)
if (mouse_event.button == WebPointerProperties::Button::kNoButton)
return WebInputEventResult::kHandledSuppressed;
if (event_handler_will_reset_capturing_mouse_events_node_)
capturing_mouse_events_node_ = nullptr;
mouse_event_manager_->HandleMousePressEventUpdateStates(mouse_event);
if (!frame_->View())
return WebInputEventResult::kNotHandled;
HitTestRequest request(HitTestRequest::kActive);
// Save the document point we generate in case the window coordinate is
// invalidated by what happens when we dispatch the event.
LayoutPoint document_point = frame_->View()->RootFrameToContents(
FlooredIntPoint(mouse_event.PositionInRootFrame()));
MouseEventWithHitTestResults mev =
frame_->GetDocument()->PerformMouseEventHitTest(request, document_point,
mouse_event);
if (!mev.InnerNode()) {
mouse_event_manager_->InvalidateClick();
return WebInputEventResult::kNotHandled;
}
mouse_event_manager_->SetMousePressNode(mev.InnerNode());
frame_->GetDocument()->SetSequentialFocusNavigationStartingPoint(
mev.InnerNode());
LocalFrame* subframe = EventHandlingUtil::SubframeForHitTestResult(mev);
if (subframe) {
WebInputEventResult result = PassMousePressEventToSubframe(mev, subframe);
// Start capturing future events for this frame. We only do this if we
// didn't clear the m_mousePressed flag, which may happen if an AppKit
// EmbeddedContentView entered a modal event loop. The capturing should be
// done only when the result indicates it has been handled. See
// crbug.com/269917
mouse_event_manager_->SetCapturesDragging(
subframe->GetEventHandler().mouse_event_manager_->CapturesDragging());
if (mouse_event_manager_->MousePressed() &&
mouse_event_manager_->CapturesDragging()) {
capturing_mouse_events_node_ = mev.InnerNode();
event_handler_will_reset_capturing_mouse_events_node_ = true;
}
mouse_event_manager_->InvalidateClick();
return result;
}
std::unique_ptr<UserGestureIndicator> gesture_indicator =
Frame::NotifyUserActivation(frame_);
frame_->LocalFrameRoot()
.GetEventHandler()
.last_mouse_down_user_gesture_token_ =
UserGestureIndicator::CurrentToken();
if (RuntimeEnabledFeatures::MiddleClickAutoscrollEnabled()) {
// We store whether middle click autoscroll is in progress before calling
// stopAutoscroll() because it will set m_autoscrollType to NoAutoscroll on
// return.
bool is_middle_click_autoscroll_in_progress =
scroll_manager_->MiddleClickAutoscrollInProgress();
scroll_manager_->StopMiddleClickAutoscroll();
if (is_middle_click_autoscroll_in_progress) {
// We invalidate the click when exiting middle click auto scroll so that
// we don't inadvertently navigate away from the current page (e.g. the
// click was on a hyperlink). See <rdar://problem/6095023>.
mouse_event_manager_->InvalidateClick();
return WebInputEventResult::kHandledSuppressed;
}
}
mouse_event_manager_->SetClickCount(mouse_event.click_count);
mouse_event_manager_->SetClickElement(mev.InnerElement());
if (!mouse_event.FromTouch())
frame_->Selection().SetCaretBlinkingSuspended(true);
WebInputEventResult event_result = DispatchMousePointerEvent(
WebInputEvent::kPointerDown, mev.InnerNode(), mev.CanvasRegionId(),
mev.Event(), Vector<WebMouseEvent>());
// Disabled form controls still need to resize the scrollable area.
if ((event_result == WebInputEventResult::kNotHandled ||
event_result == WebInputEventResult::kHandledSuppressed) &&
frame_->View()) {
LocalFrameView* view = frame_->View();
PaintLayer* layer =
mev.InnerNode()->GetLayoutObject()
? mev.InnerNode()->GetLayoutObject()->EnclosingLayer()
: nullptr;
IntPoint p = view->RootFrameToContents(
FlooredIntPoint(mouse_event.PositionInRootFrame()));
if (layer && layer->GetScrollableArea() &&
layer->GetScrollableArea()->IsPointInResizeControl(
p, kResizerForPointer)) {
scroll_manager_->SetResizeScrollableArea(layer, p);
return WebInputEventResult::kHandledSystem;
}
}
// m_selectionInitiationState is initialized after dispatching mousedown
// event in order not to keep the selection by DOM APIs because we can't
// give the user the chance to handle the selection by user action like
// dragging if we keep the selection in case of mousedown. FireFox also has
// the same behavior and it's more compatible with other browsers.
GetSelectionController().InitializeSelectionState();
HitTestResult hit_test_result = EventHandlingUtil::HitTestResultInFrame(
frame_, document_point, HitTestRequest::kReadOnly);
InputDeviceCapabilities* source_capabilities =
frame_->GetDocument()
->domWindow()
->GetInputDeviceCapabilities()
->FiresTouchEvents(mouse_event.FromTouch());
if (event_result == WebInputEventResult::kNotHandled) {
event_result = mouse_event_manager_->HandleMouseFocus(hit_test_result,
source_capabilities);
}
mouse_event_manager_->SetCapturesDragging(
event_result == WebInputEventResult::kNotHandled || mev.GetScrollbar());
// If the hit testing originally determined the event was in a scrollbar,
// refetch the MouseEventWithHitTestResults in case the scrollbar
// EmbeddedContentView was destroyed when the mouse event was handled.
if (mev.GetScrollbar()) {
const bool was_last_scroll_bar =
mev.GetScrollbar() == last_scrollbar_under_mouse_.Get();
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
mev = frame_->GetDocument()->PerformMouseEventHitTest(
request, document_point, mouse_event);
if (was_last_scroll_bar &&
mev.GetScrollbar() != last_scrollbar_under_mouse_.Get())
last_scrollbar_under_mouse_ = nullptr;
}
if (event_result != WebInputEventResult::kNotHandled) {
// Scrollbars should get events anyway, even disabled controls might be
// scrollable.
PassMousePressEventToScrollbar(mev);
} else {
if (ShouldRefetchEventTarget(mev)) {
HitTestRequest request(HitTestRequest::kReadOnly |
HitTestRequest::kActive);
mev = frame_->GetDocument()->PerformMouseEventHitTest(
request, document_point, mouse_event);
}
if (PassMousePressEventToScrollbar(mev))
event_result = WebInputEventResult::kHandledSystem;
else
event_result = mouse_event_manager_->HandleMousePressEvent(mev);
}
if (mev.GetHitTestResult().InnerNode() &&
mouse_event.button == WebPointerProperties::Button::kLeft) {
DCHECK_EQ(WebInputEvent::kMouseDown, mouse_event.GetType());
HitTestResult result = mev.GetHitTestResult();
result.SetToShadowHostIfInRestrictedShadowRoot();
frame_->GetChromeClient().OnMouseDown(*result.InnerNode());
}
return event_result;
}
WebInputEventResult EventHandler::HandleMouseMoveEvent(
const WebMouseEvent& event,
const Vector<WebMouseEvent>& coalesced_events) {
TRACE_EVENT0("blink", "EventHandler::handleMouseMoveEvent");
HitTestResult hovered_node = HitTestResult();
WebInputEventResult result =
HandleMouseMoveOrLeaveEvent(event, coalesced_events, &hovered_node);
Page* page = frame_->GetPage();
if (!page)
return result;
if (PaintLayer* layer =
EventHandlingUtil::LayerForNode(hovered_node.InnerNode())) {
if (ScrollableArea* layer_scrollable_area =
EventHandlingUtil::AssociatedScrollableArea(layer))
layer_scrollable_area->MouseMovedInContentArea();
}
if (LocalFrameView* frame_view = frame_->View())
frame_view->MouseMovedInContentArea();
hovered_node.SetToShadowHostIfInRestrictedShadowRoot();
page->GetChromeClient().MouseDidMoveOverElement(*frame_, hovered_node);
return result;
}
void EventHandler::HandleMouseLeaveEvent(const WebMouseEvent& event) {
TRACE_EVENT0("blink", "EventHandler::handleMouseLeaveEvent");
Page* page = frame_->GetPage();
if (page)
page->GetChromeClient().ClearToolTip(*frame_);
HandleMouseMoveOrLeaveEvent(event, Vector<WebMouseEvent>(), nullptr, false,
true);
}
WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
const WebMouseEvent& mouse_event,
const Vector<WebMouseEvent>& coalesced_events,
HitTestResult* hovered_node,
bool only_update_scrollbars,
bool force_leave) {
DCHECK(frame_);
DCHECK(frame_->View());
mouse_event_manager_->SetLastKnownMousePosition(mouse_event);
hover_timer_.Stop();
cursor_update_timer_.Stop();
mouse_event_manager_->CancelFakeMouseMoveEvent();
mouse_event_manager_->HandleSvgPanIfNeeded(false);
// Mouse states need to be reset when mouse move with no button down.
// This is for popup/context_menu opened at mouse_down event and
// mouse_release is not handled in page.
// crbug.com/527582
if (mouse_event.button == WebPointerProperties::Button::kNoButton &&
!(mouse_event.GetModifiers() &
WebInputEvent::Modifiers::kRelativeMotionEvent)) {
mouse_event_manager_->ClearDragHeuristicState();
if (event_handler_will_reset_capturing_mouse_events_node_)
capturing_mouse_events_node_ = nullptr;
}
if (RuntimeEnabledFeatures::MiddleClickAutoscrollEnabled()) {
if (Page* page = frame_->GetPage()) {
if (mouse_event.GetType() == WebInputEvent::kMouseLeave &&
mouse_event.button != WebPointerProperties::Button::kMiddle) {
page->GetAutoscrollController().StopMiddleClickAutoscroll(frame_);
} else {
page->GetAutoscrollController().HandleMouseMoveForMiddleClickAutoscroll(
frame_, mouse_event_manager_->LastKnownMousePositionGlobal(),
mouse_event.button == WebPointerProperties::Button::kMiddle);
}
}
}
if (frame_set_being_resized_) {
return DispatchMousePointerEvent(WebInputEvent::kPointerMove,
frame_set_being_resized_.Get(), String(),
mouse_event, coalesced_events);
}
// Send events right to a scrollbar if the mouse is pressed.
if (last_scrollbar_under_mouse_ && mouse_event_manager_->MousePressed()) {
last_scrollbar_under_mouse_->MouseMoved(mouse_event);
return WebInputEventResult::kHandledSystem;
}
HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kMove;
if (mouse_event_manager_->MousePressed()) {
hit_type |= HitTestRequest::kActive;
} else if (only_update_scrollbars) {
// Mouse events should be treated as "read-only" if we're updating only
// scrollbars. This means that :hover and :active freeze in the state they
// were in, rather than updating for nodes the mouse moves while the
// window is not key (which will be the case if onlyUpdateScrollbars is
// true).
hit_type |= HitTestRequest::kReadOnly;
}
// Treat any mouse move events as readonly if the user is currently touching
// the screen.
if (pointer_event_manager_->IsAnyTouchActive() && !force_leave)
hit_type |= HitTestRequest::kActive | HitTestRequest::kReadOnly;
HitTestRequest request(hit_type);
MouseEventWithHitTestResults mev = MouseEventWithHitTestResults(
mouse_event, HitTestResult(request, LayoutPoint()));
// We don't want to do a hit-test in forceLeave scenarios because there
// might actually be some other frame above this one at the specified
// co-ordinate. So we must force the hit-test to fail, while still clearing
// hover/active state.
if (force_leave) {
frame_->GetDocument()->UpdateHoverActiveState(request, nullptr);
} else {
mev = EventHandlingUtil::PerformMouseEventHitTest(frame_, request,
mouse_event);
}
if (hovered_node)
*hovered_node = mev.GetHitTestResult();
Scrollbar* scrollbar = nullptr;
if (scroll_manager_->InResizeMode()) {
scroll_manager_->Resize(mev.Event());
} else {
if (!scrollbar)
scrollbar = mev.GetScrollbar();
UpdateLastScrollbarUnderMouse(scrollbar,
!mouse_event_manager_->MousePressed());
if (only_update_scrollbars)
return WebInputEventResult::kHandledSuppressed;
}
WebInputEventResult event_result = WebInputEventResult::kNotHandled;
LocalFrame* new_subframe =
capturing_mouse_events_node_.Get()
? EventHandlingUtil::SubframeForTargetNode(
capturing_mouse_events_node_.Get())
: EventHandlingUtil::SubframeForHitTestResult(mev);
// We want mouseouts to happen first, from the inside out. First send a
// move event to the last subframe so that it will fire mouseouts.
if (last_mouse_move_event_subframe_ &&
last_mouse_move_event_subframe_->Tree().IsDescendantOf(frame_) &&
last_mouse_move_event_subframe_ != new_subframe) {
last_mouse_move_event_subframe_->GetEventHandler().HandleMouseLeaveEvent(
mev.Event());
last_mouse_move_event_subframe_->GetEventHandler()
.mouse_event_manager_->SetLastMousePositionAsUnknown();
}
if (new_subframe) {
// Update over/out state before passing the event to the subframe.
pointer_event_manager_->SendMouseAndPointerBoundaryEvents(
EffectiveMouseEventTargetNode(mev.InnerNode()), mev.CanvasRegionId(),
mev.Event());
// Event dispatch in sendMouseAndPointerBoundaryEvents may have caused the
// subframe of the target node to be detached from its LocalFrameView, in
// which case the event should not be passed.
if (new_subframe->View()) {
event_result = PassMouseMoveEventToSubframe(mev, coalesced_events,
new_subframe, hovered_node);
}
} else {
if (scrollbar && !mouse_event_manager_->MousePressed()) {
// Handle hover effects on platforms that support visual feedback on
// scrollbar hovering.
scrollbar->MouseMoved(mev.Event());
}
if (LocalFrameView* view = frame_->View()) {
EventHandler::OptionalCursor optional_cursor =
SelectCursor(mev.GetHitTestResult());
if (optional_cursor.IsCursorChange()) {
view->SetCursor(optional_cursor.GetCursor());
}
}
}
last_mouse_move_event_subframe_ = new_subframe;
if (event_result != WebInputEventResult::kNotHandled)
return event_result;
event_result = DispatchMousePointerEvent(
WebInputEvent::kPointerMove, mev.InnerNode(), mev.CanvasRegionId(),
mev.Event(), coalesced_events);
if (event_result != WebInputEventResult::kNotHandled)
return event_result;
return mouse_event_manager_->HandleMouseDraggedEvent(mev);
}
WebInputEventResult EventHandler::HandleMouseReleaseEvent(
const WebMouseEvent& mouse_event) {
TRACE_EVENT0("blink", "EventHandler::handleMouseReleaseEvent");
// For 4th/5th button in the mouse since Chrome does not yet send
// button value to Blink but in some cases it does send the event.
// This check is needed to suppress such an event (crbug.com/574959)
if (mouse_event.button == WebPointerProperties::Button::kNoButton)
return WebInputEventResult::kHandledSuppressed;
if (!mouse_event.FromTouch())
frame_->Selection().SetCaretBlinkingSuspended(false);
if (RuntimeEnabledFeatures::MiddleClickAutoscrollEnabled()) {
if (Page* page = frame_->GetPage()) {
page->GetAutoscrollController()
.HandleMouseReleaseForMiddleClickAutoscroll(
frame_,
mouse_event.button == WebPointerProperties::Button::kMiddle);
}
}
mouse_event_manager_->ReleaseMousePress();
mouse_event_manager_->SetLastKnownMousePosition(mouse_event);
mouse_event_manager_->HandleSvgPanIfNeeded(true);
if (frame_set_being_resized_) {
return mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
EffectiveMouseEventTargetNode(frame_set_being_resized_.Get()), String(),
EventTypeNames::mouseup, mouse_event);
}
// Only relase scrollbar when left button up.
if (mouse_event.button == WebPointerProperties::Button::kLeft &&
last_scrollbar_under_mouse_) {
mouse_event_manager_->InvalidateClick();
last_scrollbar_under_mouse_->MouseUp(mouse_event);
return DispatchMousePointerEvent(
WebInputEvent::kPointerUp, mouse_event_manager_->GetNodeUnderMouse(),
String(), mouse_event, Vector<WebMouseEvent>());
}
// Mouse events simulated from touch should not hit-test again.
DCHECK(!mouse_event.FromTouch());
HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kRelease;
HitTestRequest request(hit_type);
MouseEventWithHitTestResults mev =
EventHandlingUtil::PerformMouseEventHitTest(frame_, request, mouse_event);
Element* mouse_release_target = mev.InnerElement();
LocalFrame* subframe = capturing_mouse_events_node_.Get()
? EventHandlingUtil::SubframeForTargetNode(
capturing_mouse_events_node_.Get())
: EventHandlingUtil::SubframeForHitTestResult(mev);
if (event_handler_will_reset_capturing_mouse_events_node_)
capturing_mouse_events_node_ = nullptr;
if (subframe)
return PassMouseReleaseEventToSubframe(mev, subframe);
// Mouse events will be associated with the Document where mousedown
// occurred. If, e.g., there is a mousedown, then a drag to a different
// Document and mouseup there, the mouseup's gesture will be associated with
// the mousedown's Document. It's not absolutely certain that this is the
// correct behavior.
std::unique_ptr<UserGestureIndicator> gesture_indicator;
if (frame_->LocalFrameRoot()
.GetEventHandler()
.last_mouse_down_user_gesture_token_) {
gesture_indicator = std::make_unique<UserGestureIndicator>(
std::move(frame_->LocalFrameRoot()
.GetEventHandler()
.last_mouse_down_user_gesture_token_));
} else {
gesture_indicator = Frame::NotifyUserActivation(frame_);
}
WebInputEventResult event_result = DispatchMousePointerEvent(
WebInputEvent::kPointerUp, mev.InnerNode(), mev.CanvasRegionId(),
mev.Event(), Vector<WebMouseEvent>());
WebInputEventResult click_event_result =
mouse_release_target ? mouse_event_manager_->DispatchMouseClickIfNeeded(
mev, *mouse_release_target)
: WebInputEventResult::kNotHandled;
scroll_manager_->ClearResizeScrollableArea(false);
if (event_result == WebInputEventResult::kNotHandled)
event_result = mouse_event_manager_->HandleMouseReleaseEvent(mev);
mouse_event_manager_->HandleMouseReleaseEventUpdateStates();
return EventHandlingUtil::MergeEventResult(click_event_result, event_result);
}
static bool TargetIsFrame(Node* target, LocalFrame*& frame) {
if (!IsHTMLFrameElementBase(target))
return false;
// Cross-process drag and drop is not yet supported.
if (ToHTMLFrameElementBase(target)->ContentFrame() &&
!ToHTMLFrameElementBase(target)->ContentFrame()->IsLocalFrame())
return false;
frame = ToLocalFrame(ToHTMLFrameElementBase(target)->ContentFrame());
return true;
}
WebInputEventResult EventHandler::UpdateDragAndDrop(
const WebMouseEvent& event,
DataTransfer* data_transfer) {
WebInputEventResult event_result = WebInputEventResult::kNotHandled;
if (!frame_->View())
return event_result;
HitTestRequest request(HitTestRequest::kReadOnly);
MouseEventWithHitTestResults mev =
EventHandlingUtil::PerformMouseEventHitTest(frame_, request, event);
// Drag events should never go to text nodes (following IE, and proper
// mouseover/out dispatch)
Node* new_target = mev.InnerNode();
if (new_target && new_target->IsTextNode())
new_target = FlatTreeTraversal::Parent(*new_target);
if (AutoscrollController* controller =
scroll_manager_->GetAutoscrollController()) {
controller->UpdateDragAndDrop(new_target,
FlooredIntPoint(event.PositionInRootFrame()),
event.TimeStamp());
}
if (drag_target_ != new_target) {
// FIXME: this ordering was explicitly chosen to match WinIE. However,
// it is sometimes incorrect when dragging within subframes, as seen with
// LayoutTests/fast/events/drag-in-frames.html.
//
// Moreover, this ordering conforms to section 7.9.4 of the HTML 5 spec.
// <http://dev.w3.org/html5/spec/Overview.html#drag-and-drop-processing-model>.
LocalFrame* target_frame;
if (TargetIsFrame(new_target, target_frame)) {
if (target_frame)
event_result = target_frame->GetEventHandler().UpdateDragAndDrop(
event, data_transfer);
} else if (new_target) {
// As per section 7.9.4 of the HTML 5 spec., we must always fire a drag
// event before firing a dragenter, dragleave, or dragover event.
if (mouse_event_manager_->GetDragState().drag_src_) {
// For now we don't care if event handler cancels default behavior,
// since there is none.
mouse_event_manager_->DispatchDragSrcEvent(EventTypeNames::drag, event);
}
event_result = mouse_event_manager_->DispatchDragEvent(
EventTypeNames::dragenter, new_target, drag_target_, event,
data_transfer);
}
if (TargetIsFrame(drag_target_.Get(), target_frame)) {
if (target_frame)
event_result = target_frame->GetEventHandler().UpdateDragAndDrop(
event, data_transfer);
} else if (drag_target_) {
mouse_event_manager_->DispatchDragEvent(EventTypeNames::dragleave,
drag_target_.Get(), new_target,
event, data_transfer);
}
if (new_target) {
// We do not explicitly call m_mouseEventManager->dispatchDragEvent here
// because it could ultimately result in the appearance that two dragover
// events fired. So, we mark that we should only fire a dragover event on
// the next call to this function.
should_only_fire_drag_over_event_ = true;
}
} else {
LocalFrame* target_frame;
if (TargetIsFrame(new_target, target_frame)) {
if (target_frame)
event_result = target_frame->GetEventHandler().UpdateDragAndDrop(
event, data_transfer);
} else if (new_target) {
// Note, when dealing with sub-frames, we may need to fire only a dragover
// event as a drag event may have been fired earlier.
if (!should_only_fire_drag_over_event_ &&
mouse_event_manager_->GetDragState().drag_src_) {
// For now we don't care if event handler cancels default behavior,
// since there is none.
mouse_event_manager_->DispatchDragSrcEvent(EventTypeNames::drag, event);
}
event_result = mouse_event_manager_->DispatchDragEvent(
EventTypeNames::dragover, new_target, nullptr, event, data_transfer);
should_only_fire_drag_over_event_ = false;
}
}
drag_target_ = new_target;
return event_result;
}
void EventHandler::CancelDragAndDrop(const WebMouseEvent& event,
DataTransfer* data_transfer) {
LocalFrame* target_frame;
if (TargetIsFrame(drag_target_.Get(), target_frame)) {
if (target_frame)
target_frame->GetEventHandler().CancelDragAndDrop(event, data_transfer);
} else if (drag_target_.Get()) {
if (mouse_event_manager_->GetDragState().drag_src_)
mouse_event_manager_->DispatchDragSrcEvent(EventTypeNames::drag, event);
mouse_event_manager_->DispatchDragEvent(EventTypeNames::dragleave,
drag_target_.Get(), nullptr, event,
data_transfer);
}
ClearDragState();
}
WebInputEventResult EventHandler::PerformDragAndDrop(
const WebMouseEvent& event,
DataTransfer* data_transfer) {
LocalFrame* target_frame;
WebInputEventResult result = WebInputEventResult::kNotHandled;
if (TargetIsFrame(drag_target_.Get(), target_frame)) {
if (target_frame)
result = target_frame->GetEventHandler().PerformDragAndDrop(
event, data_transfer);
} else if (drag_target_.Get()) {
result = mouse_event_manager_->DispatchDragEvent(
EventTypeNames::drop, drag_target_.Get(), nullptr, event,
data_transfer);
}
ClearDragState();
return result;
}
void EventHandler::ClearDragState() {
scroll_manager_->StopAutoscroll();
drag_target_ = nullptr;
capturing_mouse_events_node_ = nullptr;
should_only_fire_drag_over_event_ = false;
}
void EventHandler::SetCapturingMouseEventsNode(Node* n) {
capturing_mouse_events_node_ = n;
event_handler_will_reset_capturing_mouse_events_node_ = false;
}
Node* EventHandler::EffectiveMouseEventTargetNode(Node* target_node) {
Node* new_node_under_mouse = target_node;
if (capturing_mouse_events_node_) {
new_node_under_mouse = capturing_mouse_events_node_.Get();
} else {
// If the target node is a text node, dispatch on the parent node -
// rdar://4196646
if (new_node_under_mouse && new_node_under_mouse->IsTextNode())
new_node_under_mouse = FlatTreeTraversal::Parent(*new_node_under_mouse);
}
return new_node_under_mouse;
}
bool EventHandler::IsTouchPointerIdActiveOnFrame(int pointer_id,
LocalFrame* frame) const {
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
return pointer_event_manager_->IsTouchPointerIdActiveOnFrame(pointer_id,
frame);
}
bool EventHandler::RootFrameTouchPointerActiveInCurrentFrame(
int pointer_id) const {
return frame_ != &frame_->LocalFrameRoot() &&
frame_->LocalFrameRoot()
.GetEventHandler()
.IsTouchPointerIdActiveOnFrame(pointer_id, frame_);
}
bool EventHandler::IsPointerEventActive(int pointer_id) {
return pointer_event_manager_->IsActive(pointer_id) ||
RootFrameTouchPointerActiveInCurrentFrame(pointer_id);
}
void EventHandler::SetPointerCapture(int pointer_id, EventTarget* target) {
// TODO(crbug.com/591387): This functionality should be per page not per
// frame.
if (RootFrameTouchPointerActiveInCurrentFrame(pointer_id)) {
frame_->LocalFrameRoot().GetEventHandler().SetPointerCapture(pointer_id,
target);
} else {
pointer_event_manager_->SetPointerCapture(pointer_id, target);
}
}
void EventHandler::ReleasePointerCapture(int pointer_id, EventTarget* target) {
if (RootFrameTouchPointerActiveInCurrentFrame(pointer_id)) {
frame_->LocalFrameRoot().GetEventHandler().ReleasePointerCapture(pointer_id,
target);
} else {
pointer_event_manager_->ReleasePointerCapture(pointer_id, target);
}
}
void EventHandler::ReleaseMousePointerCapture() {
pointer_event_manager_->ReleaseMousePointerCapture();
}
bool EventHandler::HasPointerCapture(int pointer_id,
const EventTarget* target) const {
if (RootFrameTouchPointerActiveInCurrentFrame(pointer_id)) {
return frame_->LocalFrameRoot().GetEventHandler().HasPointerCapture(
pointer_id, target);
} else {
return pointer_event_manager_->HasPointerCapture(pointer_id, target);
}
}
bool EventHandler::HasProcessedPointerCapture(int pointer_id,
const EventTarget* target) const {
return pointer_event_manager_->HasProcessedPointerCapture(pointer_id, target);
}
void EventHandler::ProcessPendingPointerCaptureForPointerLock(
const WebMouseEvent& mouse_event) {
pointer_event_manager_->ProcessPendingPointerCaptureForPointerLock(
mouse_event);
}
void EventHandler::ElementRemoved(EventTarget* target) {
pointer_event_manager_->ElementRemoved(target);
if (target)
mouse_wheel_event_manager_->ElementRemoved(target->ToNode());
}
WebInputEventResult EventHandler::DispatchMousePointerEvent(
const WebInputEvent::Type event_type,
Node* target_node,
const String& canvas_region_id,
const WebMouseEvent& mouse_event,
const Vector<WebMouseEvent>& coalesced_events) {
const auto& event_result = pointer_event_manager_->SendMousePointerEvent(
EffectiveMouseEventTargetNode(target_node), canvas_region_id, event_type,
mouse_event, coalesced_events);
return event_result;
}
WebInputEventResult EventHandler::HandleWheelEvent(
const WebMouseWheelEvent& event) {
return mouse_wheel_event_manager_->HandleWheelEvent(event);
}
WebInputEventResult EventHandler::HandleGestureEvent(
const WebGestureEvent& gesture_event) {
// Propagation to inner frames is handled below this function.
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
DCHECK_NE(0, gesture_event.FrameScale());
// Scrolling-related gesture events invoke EventHandler recursively for each
// frame down the chain, doing a single-frame hit-test per frame. This matches
// handleWheelEvent.
// FIXME: Add a test that traverses this path, e.g. for devtools overlay.
if (gesture_event.IsScrollEvent())
return HandleGestureScrollEvent(gesture_event);
// Hit test across all frames and do touch adjustment as necessary for the
// event type.
GestureEventWithHitTestResults targeted_event =
TargetGestureEvent(gesture_event);
return HandleGestureEvent(targeted_event);
}
WebInputEventResult EventHandler::HandleGestureEvent(
const GestureEventWithHitTestResults& targeted_event) {
TRACE_EVENT0("input", "EventHandler::handleGestureEvent");
if (!frame_->GetPage())
return WebInputEventResult::kNotHandled;
// Propagation to inner frames is handled below this function.
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
// Non-scrolling related gesture events do a single cross-frame hit-test and
// jump directly to the inner most frame. This matches handleMousePressEvent
// etc.
DCHECK(!targeted_event.Event().IsScrollEvent());
if (targeted_event.Event().GetType() == WebInputEvent::kGestureShowPress)
last_show_press_timestamp_ = CurrentTimeTicks();
// Update mouseout/leave/over/enter events before jumping directly to the
// inner most frame.
if (targeted_event.Event().GetType() == WebInputEvent::kGestureTap)
UpdateGestureTargetNodeForMouseEvent(targeted_event);
// Route to the correct frame.
if (LocalFrame* inner_frame =
targeted_event.GetHitTestResult().InnerNodeFrame())
return inner_frame->GetEventHandler().HandleGestureEventInFrame(
targeted_event);
// No hit test result, handle in root instance. Perhaps we should just return
// false instead?
return gesture_manager_->HandleGestureEventInFrame(targeted_event);
}
WebInputEventResult EventHandler::HandleGestureEventInFrame(
const GestureEventWithHitTestResults& targeted_event) {
return gesture_manager_->HandleGestureEventInFrame(targeted_event);
}
WebInputEventResult EventHandler::HandleGestureScrollEvent(
const WebGestureEvent& gesture_event) {
TRACE_EVENT0("input", "EventHandler::handleGestureScrollEvent");
if (!frame_->GetPage())
return WebInputEventResult::kNotHandled;
return scroll_manager_->HandleGestureScrollEvent(gesture_event);
}
WebInputEventResult EventHandler::HandleGestureScrollEnd(
const WebGestureEvent& gesture_event) {
if (!frame_->GetPage())
return WebInputEventResult::kNotHandled;
return scroll_manager_->HandleGestureScrollEnd(gesture_event);
}
void EventHandler::SetMouseDownMayStartAutoscroll() {
mouse_event_manager_->SetMouseDownMayStartAutoscroll();
}
bool EventHandler::IsScrollbarHandlingGestures() const {
return scroll_manager_->IsScrollbarHandlingGestures();
}
bool EventHandler::ShouldApplyTouchAdjustment(
const WebGestureEvent& event) const {
if (frame_->GetSettings() &&
!frame_->GetSettings()->GetTouchAdjustmentEnabled())
return false;
if (event.primary_pointer_type == WebPointerProperties::PointerType::kPen)
return false;
return !event.TapAreaInRootFrame().IsEmpty();
}
void EventHandler::CacheTouchAdjustmentResult(uint32_t id,
FloatPoint adjusted_point) {
touch_adjustment_result_.unique_event_id = id;
touch_adjustment_result_.adjusted_point = adjusted_point;
}
bool EventHandler::GestureCorrespondsToAdjustedTouch(
const WebGestureEvent& event) {
if (!RuntimeEnabledFeatures::UnifiedTouchAdjustmentEnabled())
return false;
// Gesture events start with a GestureTapDown. If GestureTapDown's unique id
// matches stored adjusted touchstart event id, then we can use the stored
// result for following gesture event.
if (event.GetType() == WebInputEvent::kGestureTapDown) {
should_use_touch_event_adjusted_point_ =
(event.unique_touch_event_id != 0 &&
event.unique_touch_event_id ==
touch_adjustment_result_.unique_event_id);
}
// Check if the adjusted point is in the gesture event tap rect.
// If not, should not use this touch point in following events.
if (should_use_touch_event_adjusted_point_) {
FloatRect tap_rect(FloatPoint(event.PositionInRootFrame()) -
FloatSize(event.TapAreaInRootFrame()) * 0.5,
FloatSize(event.TapAreaInRootFrame()));
should_use_touch_event_adjusted_point_ =
tap_rect.Contains(touch_adjustment_result_.adjusted_point);
}
return should_use_touch_event_adjusted_point_;
}
bool EventHandler::BestClickableNodeForHitTestResult(
const HitTestResult& result,
IntPoint& target_point,
Node*& target_node) {
// FIXME: Unify this with the other best* functions which are very similar.
TRACE_EVENT0("input", "EventHandler::bestClickableNodeForHitTestResult");
DCHECK(result.IsRectBasedTest());
// If the touch is over a scrollbar, don't adjust the touch point since touch
// adjustment only takes into account DOM nodes so a touch over a scrollbar
// will be adjusted towards nearby nodes. This leads to things like textarea
// scrollbars being untouchable.
if (result.GetScrollbar()) {
target_node = nullptr;
return false;
}
IntPoint touch_center =
frame_->View()->ContentsToRootFrame(result.RoundedPointInMainFrame());
IntRect touch_rect = frame_->View()->ContentsToRootFrame(
result.GetHitTestLocation().EnclosingIntRect());
HeapVector<Member<Node>, 11> nodes;
CopyToVector(result.ListBasedTestResult(), nodes);
// FIXME: the explicit Vector conversion copies into a temporary and is
// wasteful.
return FindBestClickableCandidate(target_node, target_point, touch_center,
touch_rect,
HeapVector<Member<Node>>(nodes));
}
bool EventHandler::BestContextMenuNodeForHitTestResult(
const HitTestResult& result,
IntPoint& target_point,
Node*& target_node) {
DCHECK(result.IsRectBasedTest());
IntPoint touch_center =
frame_->View()->ContentsToRootFrame(result.RoundedPointInMainFrame());
IntRect touch_rect = frame_->View()->ContentsToRootFrame(
result.GetHitTestLocation().EnclosingIntRect());
HeapVector<Member<Node>, 11> nodes;
CopyToVector(result.ListBasedTestResult(), nodes);
// FIXME: the explicit Vector conversion copies into a temporary and is
// wasteful.
return FindBestContextMenuCandidate(target_node, target_point, touch_center,
touch_rect,
HeapVector<Member<Node>>(nodes));
}
// Update the hover and active state across all frames for this gesture.
// This logic is different than the mouse case because mice send MouseLeave
// events to frames as they're exited. With gestures, a single event
// conceptually both 'leaves' whatever frame currently had hover and enters a
// new frame
void EventHandler::UpdateGestureHoverActiveState(const HitTestRequest& request,
Element* inner_element) {
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
HeapVector<Member<LocalFrame>> new_hover_frame_chain;
LocalFrame* new_hover_frame_in_document =
inner_element ? inner_element->GetDocument().GetFrame() : nullptr;
// Insert the ancestors of the frame having the new hovered element to the
// frame chain. The frame chain doesn't include the main frame to avoid the
// redundant work that cleans the hover state because the hover state for the
// main frame is updated by calling Document::updateHoverActiveState.
while (new_hover_frame_in_document && new_hover_frame_in_document != frame_) {
new_hover_frame_chain.push_back(new_hover_frame_in_document);
Frame* parent_frame = new_hover_frame_in_document->Tree().Parent();
new_hover_frame_in_document = parent_frame && parent_frame->IsLocalFrame()
? ToLocalFrame(parent_frame)
: nullptr;
}
Element* old_hover_element_in_cur_doc = frame_->GetDocument()->HoverElement();
Element* new_innermost_hover_element = inner_element;
if (new_innermost_hover_element != old_hover_element_in_cur_doc) {
size_t index_frame_chain = new_hover_frame_chain.size();
// Clear the hover state on any frames which are no longer in the frame
// chain of the hovered element.
while (old_hover_element_in_cur_doc &&
old_hover_element_in_cur_doc->IsFrameOwnerElement()) {
LocalFrame* new_hover_frame = nullptr;
// If we can't get the frame from the new hover frame chain,
// the newHoverFrame will be null and the old hover state will be cleared.
if (index_frame_chain > 0)
new_hover_frame = new_hover_frame_chain[--index_frame_chain];
HTMLFrameOwnerElement* owner =
ToHTMLFrameOwnerElement(old_hover_element_in_cur_doc);
if (!owner->ContentFrame() || !owner->ContentFrame()->IsLocalFrame())
break;
LocalFrame* old_hover_frame = ToLocalFrame(owner->ContentFrame());
Document* doc = old_hover_frame->GetDocument();
if (!doc)
break;
old_hover_element_in_cur_doc = doc->HoverElement();
// If the old hovered frame is different from the new hovered frame.
// we should clear the old hovered element from the old hovered frame.
if (new_hover_frame != old_hover_frame)
doc->UpdateHoverActiveState(request, nullptr);
}
}
// Recursively set the new active/hover states on every frame in the chain of
// innerElement.
frame_->GetDocument()->UpdateHoverActiveState(request, inner_element);
}
// Update the mouseover/mouseenter/mouseout/mouseleave events across all frames
// for this gesture, before passing the targeted gesture event directly to a hit
// frame.
void EventHandler::UpdateGestureTargetNodeForMouseEvent(
const GestureEventWithHitTestResults& targeted_event) {
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
// Behaviour of this function is as follows:
// - Create the chain of all entered frames.
// - Compare the last frame chain under the gesture to newly entered frame
// chain from the main frame one by one.
// - If the last frame doesn't match with the entered frame, then create the
// chain of exited frames from the last frame chain.
// - Dispatch mouseout/mouseleave events of the exited frames from the inside
// out.
// - Dispatch mouseover/mouseenter events of the entered frames into the
// inside.
// Insert the ancestors of the frame having the new target node to the entered
// frame chain.
HeapVector<Member<LocalFrame>, 2> entered_frame_chain;
LocalFrame* entered_frame_in_document =
targeted_event.GetHitTestResult().InnerNodeFrame();
while (entered_frame_in_document) {
entered_frame_chain.push_back(entered_frame_in_document);
Frame* parent_frame = entered_frame_in_document->Tree().Parent();
entered_frame_in_document = parent_frame && parent_frame->IsLocalFrame()
? ToLocalFrame(parent_frame)
: nullptr;
}
size_t index_entered_frame_chain = entered_frame_chain.size();
LocalFrame* exited_frame_in_document = frame_;
HeapVector<Member<LocalFrame>, 2> exited_frame_chain;
// Insert the frame from the disagreement between last frames and entered
// frames.
while (exited_frame_in_document) {
Node* last_node_under_tap = exited_frame_in_document->GetEventHandler()
.mouse_event_manager_->GetNodeUnderMouse();
if (!last_node_under_tap)
break;
LocalFrame* next_exited_frame_in_document = nullptr;
if (last_node_under_tap->IsFrameOwnerElement()) {
HTMLFrameOwnerElement* owner =
ToHTMLFrameOwnerElement(last_node_under_tap);
if (owner->ContentFrame() && owner->ContentFrame()->IsLocalFrame())
next_exited_frame_in_document = ToLocalFrame(owner->ContentFrame());
}
if (exited_frame_chain.size() > 0) {
exited_frame_chain.push_back(exited_frame_in_document);
} else {
LocalFrame* last_entered_frame_in_document =
index_entered_frame_chain
? entered_frame_chain[index_entered_frame_chain - 1]
: nullptr;
if (exited_frame_in_document != last_entered_frame_in_document)
exited_frame_chain.push_back(exited_frame_in_document);
else if (next_exited_frame_in_document && index_entered_frame_chain)
--index_entered_frame_chain;
}
exited_frame_in_document = next_exited_frame_in_document;
}
const WebGestureEvent& gesture_event = targeted_event.Event();
unsigned modifiers = gesture_event.GetModifiers();
WebMouseEvent fake_mouse_move(
WebInputEvent::kMouseMove, gesture_event,
WebPointerProperties::Button::kNoButton,
/* clickCount */ 0,
modifiers | WebInputEvent::Modifiers::kIsCompatibilityEventForTouch,
gesture_event.TimeStamp());
// Update the mouseout/mouseleave event
size_t index_exited_frame_chain = exited_frame_chain.size();
while (index_exited_frame_chain) {
LocalFrame* leave_frame = exited_frame_chain[--index_exited_frame_chain];
leave_frame->GetEventHandler().mouse_event_manager_->SetNodeUnderMouse(
EffectiveMouseEventTargetNode(nullptr), String(), fake_mouse_move);
}
// update the mouseover/mouseenter event
while (index_entered_frame_chain) {
Frame* parent_frame =
entered_frame_chain[--index_entered_frame_chain]->Tree().Parent();
if (parent_frame && parent_frame->IsLocalFrame()) {
ToLocalFrame(parent_frame)
->GetEventHandler()
.mouse_event_manager_->SetNodeUnderMouse(
EffectiveMouseEventTargetNode(ToHTMLFrameOwnerElement(
entered_frame_chain[index_entered_frame_chain]->Owner())),
String(), fake_mouse_move);
}
}
}
GestureEventWithHitTestResults EventHandler::TargetGestureEvent(
const WebGestureEvent& gesture_event,
bool read_only) {
TRACE_EVENT0("input", "EventHandler::targetGestureEvent");
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
// Scrolling events get hit tested per frame (like wheel events do).
DCHECK(!gesture_event.IsScrollEvent());
HitTestRequest::HitTestRequestType hit_type =
gesture_manager_->GetHitTypeForGestureType(gesture_event.GetType());
TimeDelta active_interval;
bool should_keep_active_for_min_interval = false;
if (read_only) {
hit_type |= HitTestRequest::kReadOnly;
} else if (gesture_event.GetType() == WebInputEvent::kGestureTap &&
last_show_press_timestamp_) {
// If the Tap is received very shortly after ShowPress, we want to
// delay clearing of the active state so that it's visible to the user
// for at least a couple of frames.
active_interval = CurrentTimeTicks() - last_show_press_timestamp_.value();
should_keep_active_for_min_interval =
active_interval < kMinimumActiveInterval;
if (should_keep_active_for_min_interval)
hit_type |= HitTestRequest::kReadOnly;
}
GestureEventWithHitTestResults event_with_hit_test_results =
HitTestResultForGestureEvent(gesture_event, hit_type);
// Now apply hover/active state to the final target.
HitTestRequest request(hit_type | HitTestRequest::kAllowChildFrameContent);
if (!request.ReadOnly()) {
UpdateGestureHoverActiveState(
request, event_with_hit_test_results.GetHitTestResult().InnerElement());
}
if (should_keep_active_for_min_interval) {
last_deferred_tap_element_ =
event_with_hit_test_results.GetHitTestResult().InnerElement();
// TODO(https://crbug.com/668758): Use a normal BeginFrame update for this.
active_interval_timer_.StartOneShot(
(kMinimumActiveInterval - active_interval).InSecondsF(), FROM_HERE);
}
return event_with_hit_test_results;
}
GestureEventWithHitTestResults EventHandler::HitTestResultForGestureEvent(
const WebGestureEvent& gesture_event,
HitTestRequest::HitTestRequestType hit_type) {
// Perform the rect-based hit-test (or point-based if adjustment is
// disabled). Note that we don't yet apply hover/active state here because
// we need to resolve touch adjustment first so that we apply hover/active
// it to the final adjusted node.
WebGestureEvent adjusted_event = gesture_event;
LayoutSize padding;
if (ShouldApplyTouchAdjustment(gesture_event)) {
// If gesture_event unique id matches the stored touch event result, do
// point-base hit test. Otherwise add padding and do rect-based hit test.
if (GestureCorrespondsToAdjustedTouch(gesture_event)) {
adjusted_event.ApplyTouchAdjustment(
touch_adjustment_result_.adjusted_point);
} else {
padding = GetHitTestRectForAdjustment(
LayoutSize(adjusted_event.TapAreaInRootFrame()) * 0.5f);
if (!padding.IsEmpty())
hit_type |= HitTestRequest::kListBased;
}
}
LayoutPoint hit_test_point(frame_->View()->RootFrameToContents(
adjusted_event.PositionInRootFrame()));
HitTestResult hit_test_result = HitTestResultAtPoint(
hit_test_point, hit_type | HitTestRequest::kReadOnly,
LayoutRectOutsets(padding.Height(), padding.Width(), padding.Height(),
padding.Width()));
if (hit_test_result.IsRectBasedTest()) {
// Adjust the location of the gesture to the most likely nearby node, as
// appropriate for the type of event.
ApplyTouchAdjustment(&adjusted_event, &hit_test_result);
// Do a new hit-test at the (adjusted) gesture co-ordinates. This is
// necessary because rect-based hit testing and touch adjustment sometimes
// return a different node than what a point-based hit test would return for
// the same point.
// FIXME: Fix touch adjustment to avoid the need for a redundant hit test.
// http://crbug.com/398914
LocalFrame* hit_frame = hit_test_result.InnerNodeFrame();
if (!hit_frame)
hit_frame = frame_;
hit_test_result = EventHandlingUtil::HitTestResultInFrame(
hit_frame,
hit_frame->View()->RootFrameToContents(
LayoutPoint(adjusted_event.PositionInRootFrame())),
(hit_type | HitTestRequest::kReadOnly) & ~HitTestRequest::kListBased);
}
// If we did a rect-based hit test it must be resolved to the best single node
// by now to ensure consumers don't accidentally use one of the other
// candidates.
DCHECK(!hit_test_result.IsRectBasedTest());
if (ShouldApplyTouchAdjustment(gesture_event) &&
(gesture_event.GetType() == WebInputEvent::kGestureTap ||
gesture_event.GetType() == WebInputEvent::kGestureLongPress)) {
float adjusted_distance = FloatSize(adjusted_event.PositionInRootFrame() -
gesture_event.PositionInRootFrame())
.DiagonalLength();
UMA_HISTOGRAM_COUNTS_100("Event.Touch.TouchAdjustment.AdjustDistance",
static_cast<int>(adjusted_distance));
}
return GestureEventWithHitTestResults(adjusted_event, hit_test_result);
}
void EventHandler::ApplyTouchAdjustment(WebGestureEvent* gesture_event,
HitTestResult* hit_test_result) {
Node* adjusted_node = nullptr;
IntPoint adjusted_point =
FlooredIntPoint(gesture_event->PositionInRootFrame());
bool adjusted = false;
switch (gesture_event->GetType()) {
case WebInputEvent::kGestureTap:
case WebInputEvent::kGestureTapUnconfirmed:
case WebInputEvent::kGestureTapDown:
case WebInputEvent::kGestureShowPress:
adjusted = BestClickableNodeForHitTestResult(
*hit_test_result, adjusted_point, adjusted_node);
break;
case WebInputEvent::kGestureLongPress:
case WebInputEvent::kGestureLongTap:
case WebInputEvent::kGestureTwoFingerTap:
adjusted = BestContextMenuNodeForHitTestResult(
*hit_test_result, adjusted_point, adjusted_node);
break;
default:
NOTREACHED();
}
// Update the hit-test result to be a point-based result instead of a
// rect-based result.
// FIXME: We should do this even when no candidate matches the node filter.
// crbug.com/398914
if (adjusted) {
hit_test_result->ResolveRectBasedTest(
adjusted_node, frame_->View()->RootFrameToContents(adjusted_point));
gesture_event->ApplyTouchAdjustment(
WebFloatPoint(adjusted_point.X(), adjusted_point.Y()));
}
}
WebInputEventResult EventHandler::SendContextMenuEvent(
const WebMouseEvent& event,
Node* override_target_node) {
LocalFrameView* v = frame_->View();
if (!v)
return WebInputEventResult::kNotHandled;
// Clear mouse press state to avoid initiating a drag while context menu is
// up.
mouse_event_manager_->ReleaseMousePress();
LayoutPoint position_in_contents =
v->RootFrameToContents(FlooredIntPoint(event.PositionInRootFrame()));
HitTestRequest request(HitTestRequest::kActive);
MouseEventWithHitTestResults mev =
frame_->GetDocument()->PerformMouseEventHitTest(
request, position_in_contents, event);
// Since |Document::performMouseEventHitTest()| modifies layout tree for
// setting hover element, we need to update layout tree for requirement of
// |SelectionController::sendContextMenuEvent()|.
frame_->GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
GetSelectionController().SendContextMenuEvent(mev, position_in_contents);
Node* target_node =
override_target_node ? override_target_node : mev.InnerNode();
return mouse_event_manager_->DispatchMouseEvent(
EffectiveMouseEventTargetNode(target_node), EventTypeNames::contextmenu,
event, mev.GetHitTestResult().CanvasRegionId(), nullptr);
}
static bool ShouldShowContextMenuAtSelection(const FrameSelection& selection) {
// TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets
// needs to be audited. See http://crbug.com/590369 for more details.
selection.GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const VisibleSelection& visible_selection =
selection.ComputeVisibleSelectionInDOMTree();
if (!visible_selection.IsRange() && !visible_selection.RootEditableElement())
return false;
return selection.SelectionHasFocus();
}
WebInputEventResult EventHandler::ShowNonLocatedContextMenu(
Element* override_target_element,
WebMenuSourceType source_type) {
LocalFrameView* view = frame_->View();
if (!view)
return WebInputEventResult::kNotHandled;
Document* doc = frame_->GetDocument();
if (!doc)
return WebInputEventResult::kNotHandled;
static const int kContextMenuMargin = 1;
#if defined(OS_WIN)
int right_aligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
#else
int right_aligned = 0;
#endif
IntPoint location_in_root_frame;
Element* focused_element =
override_target_element ? override_target_element : doc->FocusedElement();
FrameSelection& selection = frame_->Selection();
VisualViewport& visual_viewport = frame_->GetPage()->GetVisualViewport();
if (!override_target_element && ShouldShowContextMenuAtSelection(selection)) {
DCHECK(!doc->NeedsLayoutTreeUpdate());
IntRect first_rect =
FirstRectForRange(selection.ComputeVisibleSelectionInDOMTree()
.ToNormalizedEphemeralRange());
int x = right_aligned ? first_rect.MaxX() : first_rect.X();
// In a multiline edit, firstRect.maxY() would end up on the next line, so
// take the midpoint.
int y = (first_rect.MaxY() + first_rect.Y()) / 2;
location_in_root_frame = view->ContentsToRootFrame(IntPoint(x, y));
} else if (focused_element) {
IntRect clipped_rect = focused_element->BoundsInViewport();
location_in_root_frame =
visual_viewport.ViewportToRootFrame(clipped_rect.Center());
} else {
location_in_root_frame = IntPoint(
right_aligned
? visual_viewport.VisibleRect().MaxX() - kContextMenuMargin
: visual_viewport.GetScrollOffset().Width() + kContextMenuMargin,
visual_viewport.GetScrollOffset().Height() + kContextMenuMargin);
}
frame_->View()->SetCursor(PointerCursor());
IntPoint location_in_viewport =
visual_viewport.RootFrameToViewport(location_in_root_frame);
IntPoint global_position =
view->GetChromeClient()
->ViewportToScreen(IntRect(location_in_viewport, IntSize()),
frame_->View())
.Location();
Node* target_node =
override_target_element ? override_target_element : doc->FocusedElement();
if (!target_node)
target_node = doc;
// Use the focused node as the target for hover and active.
HitTestRequest request(HitTestRequest::kActive);
HitTestResult result(request, location_in_root_frame);
result.SetInnerNode(target_node);
doc->UpdateHoverActiveState(request, result.InnerElement());
// The contextmenu event is a mouse event even when invoked using the
// keyboard. This is required for web compatibility.
WebInputEvent::Type event_type = WebInputEvent::kMouseDown;
if (frame_->GetSettings() &&
frame_->GetSettings()->GetShowContextMenuOnMouseUp())
event_type = WebInputEvent::kMouseUp;
WebMouseEvent mouse_event(
event_type,
WebFloatPoint(location_in_root_frame.X(), location_in_root_frame.Y()),
WebFloatPoint(global_position.X(), global_position.Y()),
WebPointerProperties::Button::kNoButton, /* clickCount */ 0,
WebInputEvent::kNoModifiers, CurrentTimeTicks(), source_type);
// TODO(dtapuska): Transition the mouseEvent to be created really in viewport
// coordinates instead of root frame coordinates.
mouse_event.SetFrameScale(1);
return SendContextMenuEvent(mouse_event, override_target_element);
}
void EventHandler::ScheduleHoverStateUpdate() {
// TODO(https://crbug.com/668758): Use a normal BeginFrame update for this.
if (!hover_timer_.IsActive() &&
!mouse_event_manager_->IsMousePositionUnknown())
hover_timer_.StartOneShot(TimeDelta(), FROM_HERE);
}
void EventHandler::ScheduleCursorUpdate() {
// We only want one timer for the page, rather than each frame having it's own
// timer competing which eachother (since there's only one mouse cursor).
DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
// TODO(https://crbug.com/668758): Use a normal BeginFrame update for this.
if (!cursor_update_timer_.IsActive())
cursor_update_timer_.StartOneShot(kCursorUpdateInterval, FROM_HERE);
}
bool EventHandler::CursorUpdatePending() {
return cursor_update_timer_.IsActive();
}
bool EventHandler::FakeMouseMovePending() const {
return mouse_event_manager_->FakeMouseMovePending();
}
void EventHandler::DispatchFakeMouseMoveEventSoon(
MouseEventManager::FakeMouseMoveReason fake_mouse_move_reason) {
mouse_event_manager_->DispatchFakeMouseMoveEventSoon(fake_mouse_move_reason);
}
void EventHandler::DispatchFakeMouseMoveEventSoonInQuad(const FloatQuad& quad) {
mouse_event_manager_->DispatchFakeMouseMoveEventSoonInQuad(quad);
}
void EventHandler::SetResizingFrameSet(HTMLFrameSetElement* frame_set) {
frame_set_being_resized_ = frame_set;
}
void EventHandler::ResizeScrollableAreaDestroyed() {
scroll_manager_->ClearResizeScrollableArea(true);
}
void EventHandler::HoverTimerFired(TimerBase*) {
TRACE_EVENT0("input", "EventHandler::hoverTimerFired");
DCHECK(frame_);
DCHECK(frame_->GetDocument());
if (auto* layout_object = frame_->ContentLayoutObject()) {
if (LocalFrameView* view = frame_->View()) {
HitTestRequest request(HitTestRequest::kMove);
HitTestResult result(request,
view->ViewportToContents(
mouse_event_manager_->LastKnownMousePosition()));
layout_object->HitTest(result);
frame_->GetDocument()->UpdateHoverActiveState(request,
result.InnerElement());
}
}
}
void EventHandler::ActiveIntervalTimerFired(TimerBase*) {
TRACE_EVENT0("input", "EventHandler::activeIntervalTimerFired");
if (frame_ && frame_->GetDocument() && last_deferred_tap_element_) {
// FIXME: Enable condition when http://crbug.com/226842 lands
// m_lastDeferredTapElement.get() == m_frame->document()->activeElement()
HitTestRequest request(HitTestRequest::kTouchEvent |
HitTestRequest::kRelease);
frame_->GetDocument()->UpdateHoverActiveState(
request, last_deferred_tap_element_.Get());
}
last_deferred_tap_element_ = nullptr;
}
void EventHandler::NotifyElementActivated() {
// Since another element has been set to active, stop current timer and clear
// reference.
active_interval_timer_.Stop();
last_deferred_tap_element_ = nullptr;
}
bool EventHandler::HandleAccessKey(const WebKeyboardEvent& evt) {
return keyboard_event_manager_->HandleAccessKey(evt);
}
WebInputEventResult EventHandler::KeyEvent(
const WebKeyboardEvent& initial_key_event) {
return keyboard_event_manager_->KeyEvent(initial_key_event);
}
void EventHandler::DefaultKeyboardEventHandler(KeyboardEvent* event) {
keyboard_event_manager_->DefaultKeyboardEventHandler(
event, mouse_event_manager_->MousePressNode());
}
void EventHandler::DragSourceEndedAt(const WebMouseEvent& event,
DragOperation operation) {
// Asides from routing the event to the correct frame, the hit test is also an
// opportunity for Layer to update the :hover and :active pseudoclasses.
HitTestRequest request(HitTestRequest::kRelease);
MouseEventWithHitTestResults mev =
EventHandlingUtil::PerformMouseEventHitTest(frame_, request, event);
LocalFrame* target_frame;
if (TargetIsFrame(mev.InnerNode(), target_frame)) {
if (target_frame) {
target_frame->GetEventHandler().DragSourceEndedAt(event, operation);
return;
}
}
mouse_event_manager_->DragSourceEndedAt(event, operation);
}
void EventHandler::UpdateDragStateAfterEditDragIfNeeded(
Element* root_editable_element) {
// If inserting the dragged contents removed the drag source, we still want to
// fire dragend at the root editble element.
if (mouse_event_manager_->GetDragState().drag_src_ &&
!mouse_event_manager_->GetDragState().drag_src_->isConnected())
mouse_event_manager_->GetDragState().drag_src_ = root_editable_element;
}
bool EventHandler::HandleTextInputEvent(const String& text,
Event* underlying_event,
TextEventInputType input_type) {
// Platforms should differentiate real commands like selectAll from text input
// in disguise (like insertNewline), and avoid dispatching text input events
// from keydown default handlers.
DCHECK(!underlying_event || !underlying_event->IsKeyboardEvent() ||
ToKeyboardEvent(underlying_event)->type() == EventTypeNames::keypress);
if (!frame_)
return false;
EventTarget* target;
if (underlying_event)
target = underlying_event->target();
else
target = EventTargetNodeForDocument(frame_->GetDocument());
if (!target)
return false;
TextEvent* event = TextEvent::Create(frame_->DomWindow(), text, input_type);
event->SetUnderlyingEvent(underlying_event);
target->DispatchEvent(event);
return event->DefaultHandled() || event->defaultPrevented();
}
void EventHandler::DefaultTextInputEventHandler(TextEvent* event) {
if (frame_->GetEditor().HandleTextEvent(event))
event->SetDefaultHandled();
}
void EventHandler::CapsLockStateMayHaveChanged() {
keyboard_event_manager_->CapsLockStateMayHaveChanged();
}
bool EventHandler::PassMousePressEventToScrollbar(
MouseEventWithHitTestResults& mev) {
// Only handle mouse left button as press.
if (mev.Event().button != WebPointerProperties::Button::kLeft)
return false;
Scrollbar* scrollbar = mev.GetScrollbar();
UpdateLastScrollbarUnderMouse(scrollbar, true);
if (!scrollbar || !scrollbar->Enabled())
return false;
scrollbar->MouseDown(mev.Event());
return true;
}
// If scrollbar (under mouse) is different from last, send a mouse exited. Set
// last to scrollbar if setLast is true; else set last to 0.
void EventHandler::UpdateLastScrollbarUnderMouse(Scrollbar* scrollbar,
bool set_last) {
if (last_scrollbar_under_mouse_ != scrollbar) {
// Send mouse exited to the old scrollbar.
if (last_scrollbar_under_mouse_)
last_scrollbar_under_mouse_->MouseExited();
// Send mouse entered if we're setting a new scrollbar.
if (scrollbar && set_last)
scrollbar->MouseEntered();
last_scrollbar_under_mouse_ = set_last ? scrollbar : nullptr;
}
}
WebInputEventResult EventHandler::PassMousePressEventToSubframe(
MouseEventWithHitTestResults& mev,
LocalFrame* subframe) {
GetSelectionController().PassMousePressEventToSubframe(mev);
WebInputEventResult result =
subframe->GetEventHandler().HandleMousePressEvent(mev.Event());
if (result != WebInputEventResult::kNotHandled)
return result;
return WebInputEventResult::kHandledSystem;
}
WebInputEventResult EventHandler::PassMouseMoveEventToSubframe(
MouseEventWithHitTestResults& mev,
const Vector<WebMouseEvent>& coalesced_events,
LocalFrame* subframe,
HitTestResult* hovered_node) {
if (mouse_event_manager_->MouseDownMayStartDrag())
return WebInputEventResult::kNotHandled;
WebInputEventResult result =
subframe->GetEventHandler().HandleMouseMoveOrLeaveEvent(
mev.Event(), coalesced_events, hovered_node);
if (result != WebInputEventResult::kNotHandled)
return result;
return WebInputEventResult::kHandledSystem;
}
WebInputEventResult EventHandler::PassMouseReleaseEventToSubframe(
MouseEventWithHitTestResults& mev,
LocalFrame* subframe) {
WebInputEventResult result =
subframe->GetEventHandler().HandleMouseReleaseEvent(mev.Event());
if (result != WebInputEventResult::kNotHandled)
return result;
return WebInputEventResult::kHandledSystem;
}
} // namespace blink
| 40.63251 | 84 | 0.727447 | [
"geometry",
"render",
"vector",
"model"
] |
62243d15d4b938ccc23922965542beee29af91ff | 833 | cpp | C++ | adventofcode/2020/day4/solution.cpp | SnoopJeDi/playground | 73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf | [
"MIT"
] | null | null | null | adventofcode/2020/day4/solution.cpp | SnoopJeDi/playground | 73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf | [
"MIT"
] | null | null | null | adventofcode/2020/day4/solution.cpp | SnoopJeDi/playground | 73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "common.h"
#include "PassportInfo.h"
int
main(int argc, char* argv[])
{
std::vector<std::string> input;
try {
input = Acme::load_input(argc, argv);
} catch(...) {
return 1;
}
auto passports = Acme::parseInfo(input);
std::cout << passports.size() << " passports parsed" << std::endl;
auto nump1 = std::count_if(passports.begin(), passports.end(), [](Acme::PassportInfo& p) { return p.allParams(); });
std::cout << "Part one: " << nump1 << " passports with all required fields defined" << std::endl;
auto nump2 = std::count_if(passports.begin(), passports.end(), [](Acme::PassportInfo& p) { return p.valid(); });
std::cout << "Part two: " << nump2 << " passports with all fields validated" << std::endl;
return 0;
}
| 27.766667 | 120 | 0.638655 | [
"vector"
] |
622c93c3deef9b6856ee5d77acdb5b4d7ebda611 | 843 | cpp | C++ | physically-based-cloud-rendering/clouds/transform.cpp | markomijolovic/physically-based-cloud-rendering | a8f9b3e11d6c2f744a45a598b872afb45ff8756c | [
"BSD-3-Clause"
] | 3 | 2021-05-25T13:58:22.000Z | 2022-02-21T11:53:26.000Z | physically-based-cloud-rendering/clouds/transform.cpp | markomijolovic/physically-based-cloud-rendering | a8f9b3e11d6c2f744a45a598b872afb45ff8756c | [
"BSD-3-Clause"
] | null | null | null | physically-based-cloud-rendering/clouds/transform.cpp | markomijolovic/physically-based-cloud-rendering | a8f9b3e11d6c2f744a45a598b872afb45ff8756c | [
"BSD-3-Clause"
] | null | null | null | #include "transform.hpp"
#include "transforms.hpp"
auto get_transform_matrix(const transform_t &transform) -> glm::mat4x4
{
auto transform_matrix = translate(transform.position);
transform_matrix *= rotate(radians(transform.rotation.z), {0.0F, 0.0F, 1.0F});
transform_matrix *= rotate(radians(transform.rotation.y), {0.0F, 1.0F, 0.0F});
transform_matrix *= rotate(radians(transform.rotation.x), {1.0F, 0.0F, 0.0F});
transform_matrix *= scale(transform.scale);
return transform_matrix;
}
auto get_view_matrix(const transform_t &transform) -> glm::mat4x4
{
auto transform_matrix = rotate(radians(-transform.rotation.x), {1.0F, 0.0F, 0.0F});
transform_matrix = transform_matrix * rotate(radians(-transform.rotation.y), {0.0F, 1.0F, 0.0F});
return transform_matrix * translate(-transform.position);
}
| 36.652174 | 106 | 0.71293 | [
"transform"
] |
62387e92630f81c38c0c5078df9ed632b9217f04 | 43,819 | hpp | C++ | src/environment_const_string.hpp | gto76/comp-m2 | 7eb67e9c016782b73694d933b9a8ee2ef5867687 | [
"MIT"
] | 188 | 2015-07-02T08:46:54.000Z | 2022-02-20T13:06:28.000Z | src/environment_const_string.hpp | gto76/comp-m2 | 7eb67e9c016782b73694d933b9a8ee2ef5867687 | [
"MIT"
] | 5 | 2015-10-04T13:49:54.000Z | 2015-10-18T00:08:21.000Z | src/environment_const_string.hpp | gto76/comp-m2 | 7eb67e9c016782b73694d933b9a8ee2ef5867687 | [
"MIT"
] | 18 | 2015-10-04T12:12:17.000Z | 2021-01-04T13:27:48.000Z | #ifndef ENVIRONMENT_CONST_STRING_H
#define ENVIRONMENT_CONST_STRING_H
#include <string>
#include <vector>
using namespace std;
// Automaticaly generated file from environment.c
// Do not edit this line.
const vector<string> environmentConstString = {u8"\u0023", u8"\u0069", u8"\u006E", u8"\u0063", u8"\u006C", u8"\u0075",
u8"\u0064", u8"\u0065", u8"\u0020", u8"\u003C", u8"\u0073", u8"\u0069",
u8"\u0067", u8"\u006E", u8"\u0061", u8"\u006C", u8"\u002E", u8"\u0068",
u8"\u003E", u8"\u000D", u8"\u000A", u8"\u0023", u8"\u0069", u8"\u006E",
u8"\u0063", u8"\u006C", u8"\u0075", u8"\u0064", u8"\u0065", u8"\u0020",
u8"\u003C", u8"\u0073", u8"\u0074", u8"\u0064", u8"\u0069", u8"\u006F",
u8"\u002E", u8"\u0068", u8"\u003E", u8"\u000D", u8"\u000A", u8"\u0023",
u8"\u0069", u8"\u006E", u8"\u0063", u8"\u006C", u8"\u0075", u8"\u0064",
u8"\u0065", u8"\u0020", u8"\u003C", u8"\u0073", u8"\u0074", u8"\u0064",
u8"\u006C", u8"\u0069", u8"\u0062", u8"\u002E", u8"\u0068", u8"\u003E",
u8"\u000D", u8"\u000A", u8"\u0023", u8"\u0069", u8"\u006E", u8"\u0063",
u8"\u006C", u8"\u0075", u8"\u0064", u8"\u0065", u8"\u0020", u8"\u003C",
u8"\u0073", u8"\u0074", u8"\u0072", u8"\u0069", u8"\u006E", u8"\u0067",
u8"\u002E", u8"\u0068", u8"\u003E", u8"\u000D", u8"\u000A", u8"\u0023",
u8"\u0069", u8"\u006E", u8"\u0063", u8"\u006C", u8"\u0075", u8"\u0064",
u8"\u0065", u8"\u0020", u8"\u003C", u8"\u0073", u8"\u0079", u8"\u0073",
u8"\u002F", u8"\u0069", u8"\u006F", u8"\u0063", u8"\u0074", u8"\u006C",
u8"\u002E", u8"\u0068", u8"\u003E", u8"\u000D", u8"\u000A", u8"\u0023",
u8"\u0069", u8"\u006E", u8"\u0063", u8"\u006C", u8"\u0075", u8"\u0064",
u8"\u0065", u8"\u0020", u8"\u003C", u8"\u0074", u8"\u0065", u8"\u0072",
u8"\u006D", u8"\u0069", u8"\u006F", u8"\u0073", u8"\u002E", u8"\u0068",
u8"\u003E", u8"\u000D", u8"\u000A", u8"\u0023", u8"\u0069", u8"\u006E",
u8"\u0063", u8"\u006C", u8"\u0075", u8"\u0064", u8"\u0065", u8"\u0020",
u8"\u003C", u8"\u0075", u8"\u006E", u8"\u0069", u8"\u0073", u8"\u0074",
u8"\u0064", u8"\u002E", u8"\u0068", u8"\u003E", u8"\u000D", u8"\u000A",
u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0020", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0045", u8"\u006E",
u8"\u0076", u8"\u0069", u8"\u0072", u8"\u006F", u8"\u006E", u8"\u006D",
u8"\u0065", u8"\u006E", u8"\u0074", u8"\u0028", u8"\u0076", u8"\u006F",
u8"\u0069", u8"\u0064", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A",
u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0063",
u8"\u0068", u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0054", u8"\u0065",
u8"\u0072", u8"\u006D", u8"\u0069", u8"\u006E", u8"\u0061", u8"\u006C",
u8"\u0028", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0020", u8"\u0073", u8"\u0061", u8"\u0076", u8"\u0065",
u8"\u0041", u8"\u0074", u8"\u0074", u8"\u0072", u8"\u0069", u8"\u0062",
u8"\u0075", u8"\u0074", u8"\u0065", u8"\u0073", u8"\u0028", u8"\u0076",
u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u004D", u8"\u0065", u8"\u006E",
u8"\u0075", u8"\u004D", u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0028",
u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0020", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0052", u8"\u0061",
u8"\u0063", u8"\u0065", u8"\u004D", u8"\u006F", u8"\u0064", u8"\u0065",
u8"\u0028", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0020", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u004E",
u8"\u006F", u8"\u006E", u8"\u0063", u8"\u0061", u8"\u006E", u8"\u006F",
u8"\u006E", u8"\u0069", u8"\u0063", u8"\u0061", u8"\u006C", u8"\u004D",
u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0028", u8"\u0069", u8"\u006E",
u8"\u0074", u8"\u0020", u8"\u0076", u8"\u006D", u8"\u0069", u8"\u006E",
u8"\u002C", u8"\u0020", u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0020",
u8"\u0076", u8"\u0074", u8"\u0069", u8"\u006D", u8"\u0065", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0067", u8"\u0069",
u8"\u0073", u8"\u0074", u8"\u0065", u8"\u0072", u8"\u0053", u8"\u0069",
u8"\u0067", u8"\u0049", u8"\u006E", u8"\u0074", u8"\u0043", u8"\u0061",
u8"\u0074", u8"\u0063", u8"\u0068", u8"\u0065", u8"\u0072", u8"\u0028",
u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0020", u8"\u0073", u8"\u0069", u8"\u0067", u8"\u0049", u8"\u006E",
u8"\u0074", u8"\u0043", u8"\u0061", u8"\u0074", u8"\u0063", u8"\u0068",
u8"\u0065", u8"\u0072", u8"\u0028", u8"\u0069", u8"\u006E", u8"\u0074",
u8"\u0020", u8"\u0073", u8"\u0069", u8"\u0067", u8"\u006E", u8"\u0075",
u8"\u006D", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076",
u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0064", u8"\u0069",
u8"\u0073", u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0065", u8"\u0052",
u8"\u0065", u8"\u0070", u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0041",
u8"\u006E", u8"\u0064", u8"\u0043", u8"\u0075", u8"\u0072", u8"\u0073",
u8"\u006F", u8"\u0072", u8"\u0028", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076",
u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0072", u8"\u0065",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0045", u8"\u006E", u8"\u0076",
u8"\u0069", u8"\u0072", u8"\u006F", u8"\u006E", u8"\u006D", u8"\u0065",
u8"\u006E", u8"\u0074", u8"\u0028", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076",
u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0072", u8"\u0065",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0049", u8"\u006E", u8"\u0070",
u8"\u0075", u8"\u0074", u8"\u004D", u8"\u006F", u8"\u0064", u8"\u0065",
u8"\u0028", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0020", u8"\u0065", u8"\u006E", u8"\u0061", u8"\u0062",
u8"\u006C", u8"\u0065", u8"\u0052", u8"\u0065", u8"\u0070", u8"\u0065",
u8"\u0061", u8"\u0074", u8"\u0041", u8"\u006E", u8"\u0064", u8"\u0043",
u8"\u0075", u8"\u0072", u8"\u0073", u8"\u006F", u8"\u0072", u8"\u0028",
u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0043", u8"\u006F", u8"\u006E", u8"\u0073", u8"\u006F", u8"\u006C",
u8"\u0065", u8"\u0028", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A", u8"\u0069", u8"\u006E",
u8"\u0074", u8"\u0020", u8"\u0063", u8"\u006F", u8"\u006E", u8"\u0073",
u8"\u0074", u8"\u0020", u8"\u0044", u8"\u0049", u8"\u0053", u8"\u0041",
u8"\u0042", u8"\u004C", u8"\u0045", u8"\u005F", u8"\u0052", u8"\u0045",
u8"\u0050", u8"\u0045", u8"\u0041", u8"\u0054", u8"\u0020", u8"\u003D",
u8"\u0020", u8"\u0030", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u000D",
u8"\u000A", u8"\u0073", u8"\u0074", u8"\u0072", u8"\u0075", u8"\u0063",
u8"\u0074", u8"\u0020", u8"\u0074", u8"\u0065", u8"\u0072", u8"\u006D",
u8"\u0069", u8"\u006F", u8"\u0073", u8"\u0020", u8"\u0073", u8"\u0061",
u8"\u0076", u8"\u0065", u8"\u0064", u8"\u005F", u8"\u0061", u8"\u0074",
u8"\u0074", u8"\u0072", u8"\u0069", u8"\u0062", u8"\u0075", u8"\u0074",
u8"\u0065", u8"\u0073", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0076",
u8"\u006F", u8"\u006C", u8"\u0061", u8"\u0074", u8"\u0069", u8"\u006C",
u8"\u0065", u8"\u0020", u8"\u0073", u8"\u0069", u8"\u0067", u8"\u005F",
u8"\u0061", u8"\u0074", u8"\u006F", u8"\u006D", u8"\u0069", u8"\u0063",
u8"\u005F", u8"\u0074", u8"\u0020", u8"\u0070", u8"\u006C", u8"\u0065",
u8"\u0061", u8"\u0073", u8"\u0065", u8"\u0045", u8"\u0078", u8"\u0069",
u8"\u0074", u8"\u0020", u8"\u003D", u8"\u0020", u8"\u0030", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u0020", u8"\u0041", u8"\u0054", u8"\u0020",
u8"\u0053", u8"\u0054", u8"\u0041", u8"\u0052", u8"\u0054", u8"\u0020",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u000D", u8"\u000A",
u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0020", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0045", u8"\u006E",
u8"\u0076", u8"\u0069", u8"\u0072", u8"\u006F", u8"\u006E", u8"\u006D",
u8"\u0065", u8"\u006E", u8"\u0074", u8"\u0028", u8"\u0029", u8"\u0020",
u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0063",
u8"\u0068", u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0054", u8"\u0065",
u8"\u0072", u8"\u006D", u8"\u0069", u8"\u006E", u8"\u0061", u8"\u006C",
u8"\u0028", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0073", u8"\u0061", u8"\u0076", u8"\u0065", u8"\u0041",
u8"\u0074", u8"\u0074", u8"\u0072", u8"\u0069", u8"\u0062", u8"\u0075",
u8"\u0074", u8"\u0065", u8"\u0073", u8"\u0028", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0073", u8"\u0065",
u8"\u0074", u8"\u004D", u8"\u0065", u8"\u006E", u8"\u0075", u8"\u004D",
u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0028", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0072", u8"\u0065",
u8"\u0067", u8"\u0069", u8"\u0073", u8"\u0074", u8"\u0065", u8"\u0072",
u8"\u0053", u8"\u0069", u8"\u0067", u8"\u0049", u8"\u006E", u8"\u0074",
u8"\u0043", u8"\u0061", u8"\u0074", u8"\u0063", u8"\u0068", u8"\u0065",
u8"\u0072", u8"\u0028", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u0020", u8"\u0064", u8"\u0069", u8"\u0073", u8"\u0061",
u8"\u0062", u8"\u006C", u8"\u0065", u8"\u0052", u8"\u0065", u8"\u0070",
u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0041", u8"\u006E", u8"\u0064",
u8"\u0043", u8"\u0075", u8"\u0072", u8"\u0073", u8"\u006F", u8"\u0072",
u8"\u0028", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D",
u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F",
u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0063", u8"\u0068", u8"\u0065",
u8"\u0063", u8"\u006B", u8"\u0054", u8"\u0065", u8"\u0072", u8"\u006D",
u8"\u0069", u8"\u006E", u8"\u0061", u8"\u006C", u8"\u0028", u8"\u0029",
u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020",
u8"\u0069", u8"\u0066", u8"\u0020", u8"\u0028", u8"\u0021", u8"\u007E",
u8"\u0069", u8"\u0073", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0079",
u8"\u0028", u8"\u0053", u8"\u0054", u8"\u0044", u8"\u0049", u8"\u004E",
u8"\u005F", u8"\u0046", u8"\u0049", u8"\u004C", u8"\u0045", u8"\u004E",
u8"\u004F", u8"\u0029", u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0070",
u8"\u0072", u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0066", u8"\u0028",
u8"\u0022", u8"\u004E", u8"\u006F", u8"\u0074", u8"\u0020", u8"\u0061",
u8"\u0020", u8"\u0074", u8"\u0065", u8"\u0072", u8"\u006D", u8"\u0069",
u8"\u006E", u8"\u0061", u8"\u006C", u8"\u003A", u8"\u0020", u8"\u0025",
u8"\u0064", u8"\u002E", u8"\u005C", u8"\u006E", u8"\u0022", u8"\u002C",
u8"\u0020", u8"\u0053", u8"\u0054", u8"\u0044", u8"\u0049", u8"\u004E",
u8"\u005F", u8"\u0046", u8"\u0049", u8"\u004C", u8"\u0045", u8"\u004E",
u8"\u004F", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0065", u8"\u0078", u8"\u0069",
u8"\u0074", u8"\u0028", u8"\u0045", u8"\u0058", u8"\u0049", u8"\u0054",
u8"\u005F", u8"\u0046", u8"\u0041", u8"\u0049", u8"\u004C", u8"\u0055",
u8"\u0052", u8"\u0045", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u0020", u8"\u007D", u8"\u000D", u8"\u000A", u8"\u007D",
u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F",
u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0073", u8"\u0061", u8"\u0076",
u8"\u0065", u8"\u0041", u8"\u0074", u8"\u0074", u8"\u0072", u8"\u0069",
u8"\u0062", u8"\u0075", u8"\u0074", u8"\u0065", u8"\u0073", u8"\u0028",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0074", u8"\u0063", u8"\u0067", u8"\u0065", u8"\u0074",
u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072", u8"\u0028", u8"\u0053",
u8"\u0054", u8"\u0044", u8"\u0049", u8"\u004E", u8"\u005F", u8"\u0046",
u8"\u0049", u8"\u004C", u8"\u0045", u8"\u004E", u8"\u004F", u8"\u002C",
u8"\u0020", u8"\u0026", u8"\u0073", u8"\u0061", u8"\u0076", u8"\u0065",
u8"\u0064", u8"\u005F", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072",
u8"\u0069", u8"\u0062", u8"\u0075", u8"\u0074", u8"\u0065", u8"\u0073",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D",
u8"\u000A", u8"\u000D", u8"\u000A", u8"\u002F", u8"\u002A", u8"\u0020",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u002A", u8"\u0020", u8"\u0053",
u8"\u0065", u8"\u0074", u8"\u0073", u8"\u0020", u8"\u0062", u8"\u006C",
u8"\u006F", u8"\u0063", u8"\u006B", u8"\u0069", u8"\u006E", u8"\u0067",
u8"\u0020", u8"\u006D", u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0020",
u8"\u0028", u8"\u0067", u8"\u0065", u8"\u0074", u8"\u0063", u8"\u0020",
u8"\u0077", u8"\u0061", u8"\u0069", u8"\u0074", u8"\u0073", u8"\u0020",
u8"\u0066", u8"\u006F", u8"\u0072", u8"\u0020", u8"\u0069", u8"\u006E",
u8"\u0070", u8"\u0075", u8"\u0074", u8"\u0029", u8"\u002E", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u002A", u8"\u002F", u8"\u000D", u8"\u000A",
u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0073",
u8"\u0065", u8"\u0074", u8"\u004D", u8"\u0065", u8"\u006E", u8"\u0075",
u8"\u004D", u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0028", u8"\u0029",
u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u004E", u8"\u006F", u8"\u006E",
u8"\u0063", u8"\u0061", u8"\u006E", u8"\u006F", u8"\u006E", u8"\u0069",
u8"\u0063", u8"\u0061", u8"\u006C", u8"\u004D", u8"\u006F", u8"\u0064",
u8"\u0065", u8"\u0028", u8"\u0031", u8"\u002C", u8"\u0020", u8"\u0030",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D",
u8"\u000A", u8"\u000D", u8"\u000A", u8"\u002F", u8"\u002A", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u002A", u8"\u0020", u8"\u0053", u8"\u0065",
u8"\u0074", u8"\u0073", u8"\u0020", u8"\u006E", u8"\u006F", u8"\u006E",
u8"\u0062", u8"\u006C", u8"\u006F", u8"\u0063", u8"\u006B", u8"\u0069",
u8"\u006E", u8"\u0067", u8"\u0020", u8"\u006D", u8"\u006F", u8"\u0064",
u8"\u0065", u8"\u0020", u8"\u0028", u8"\u0067", u8"\u0065", u8"\u0074",
u8"\u0063", u8"\u0020", u8"\u0064", u8"\u006F", u8"\u0065", u8"\u0073",
u8"\u0020", u8"\u006E", u8"\u006F", u8"\u0074", u8"\u0020", u8"\u0077",
u8"\u0061", u8"\u0069", u8"\u0074", u8"\u0020", u8"\u0066", u8"\u006F",
u8"\u0072", u8"\u0020", u8"\u0069", u8"\u006E", u8"\u0070", u8"\u0075",
u8"\u0074", u8"\u002C", u8"\u0020", u8"\u0069", u8"\u0074", u8"\u0020",
u8"\u0072", u8"\u0065", u8"\u0074", u8"\u0075", u8"\u0072", u8"\u006E",
u8"\u0073", u8"\u0020", u8"\u0065", u8"\u0076", u8"\u0065", u8"\u0072",
u8"\u0079", u8"\u0020", u8"\u0030", u8"\u002E", u8"\u0031", u8"\u0020",
u8"\u0073", u8"\u0029", u8"\u002E", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u002A", u8"\u002F", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F",
u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0052", u8"\u0061", u8"\u0063", u8"\u0065", u8"\u004D", u8"\u006F",
u8"\u0064", u8"\u0065", u8"\u0028", u8"\u0029", u8"\u0020", u8"\u007B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0073", u8"\u0065",
u8"\u0074", u8"\u004E", u8"\u006F", u8"\u006E", u8"\u0063", u8"\u0061",
u8"\u006E", u8"\u006F", u8"\u006E", u8"\u0069", u8"\u0063", u8"\u0061",
u8"\u006C", u8"\u004D", u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0028",
u8"\u0030", u8"\u002C", u8"\u0020", u8"\u0031", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D", u8"\u000A", u8"\u000D",
u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u004E", u8"\u006F", u8"\u006E",
u8"\u0063", u8"\u0061", u8"\u006E", u8"\u006F", u8"\u006E", u8"\u0069",
u8"\u0063", u8"\u0061", u8"\u006C", u8"\u004D", u8"\u006F", u8"\u0064",
u8"\u0065", u8"\u0028", u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0020",
u8"\u0076", u8"\u006D", u8"\u0069", u8"\u006E", u8"\u002C", u8"\u0020",
u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0020", u8"\u0076", u8"\u0074",
u8"\u0069", u8"\u006D", u8"\u0065", u8"\u0029", u8"\u0020", u8"\u007B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0073", u8"\u0074",
u8"\u0072", u8"\u0075", u8"\u0063", u8"\u0074", u8"\u0020", u8"\u0074",
u8"\u0065", u8"\u0072", u8"\u006D", u8"\u0069", u8"\u006F", u8"\u0073",
u8"\u0020", u8"\u0074", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u002F",
u8"\u002F", u8"\u0020", u8"\u0053", u8"\u0065", u8"\u0074", u8"\u0073",
u8"\u0020", u8"\u006E", u8"\u006F", u8"\u006E", u8"\u0063", u8"\u0061",
u8"\u006E", u8"\u006F", u8"\u006E", u8"\u0069", u8"\u0063", u8"\u0061",
u8"\u006C", u8"\u0020", u8"\u006D", u8"\u006F", u8"\u0064", u8"\u0065",
u8"\u0020", u8"\u0061", u8"\u006E", u8"\u0064", u8"\u0020", u8"\u0064",
u8"\u0069", u8"\u0073", u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0065",
u8"\u0020", u8"\u0065", u8"\u0063", u8"\u0068", u8"\u006F", u8"\u002E",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0061", u8"\u0074",
u8"\u0065", u8"\u0078", u8"\u0069", u8"\u0074", u8"\u0028", u8"\u0072",
u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0045", u8"\u006E",
u8"\u0076", u8"\u0069", u8"\u0072", u8"\u006F", u8"\u006E", u8"\u006D",
u8"\u0065", u8"\u006E", u8"\u0074", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0074", u8"\u0063", u8"\u0067",
u8"\u0065", u8"\u0074", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072",
u8"\u0028", u8"\u0053", u8"\u0054", u8"\u0044", u8"\u0049", u8"\u004E",
u8"\u005F", u8"\u0046", u8"\u0049", u8"\u004C", u8"\u0045", u8"\u004E",
u8"\u004F", u8"\u002C", u8"\u0020", u8"\u0026", u8"\u0074", u8"\u0061",
u8"\u0074", u8"\u0074", u8"\u0072", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0074", u8"\u0061", u8"\u0074",
u8"\u0074", u8"\u0072", u8"\u002E", u8"\u0063", u8"\u005F", u8"\u006C",
u8"\u0066", u8"\u006C", u8"\u0061", u8"\u0067", u8"\u0020", u8"\u0026",
u8"\u003D", u8"\u0020", u8"\u007E", u8"\u0028", u8"\u0049", u8"\u0043",
u8"\u0041", u8"\u004E", u8"\u004F", u8"\u004E", u8"\u007C", u8"\u0045",
u8"\u0043", u8"\u0048", u8"\u004F", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0074", u8"\u0061", u8"\u0074",
u8"\u0074", u8"\u0072", u8"\u002E", u8"\u0063", u8"\u005F", u8"\u0063",
u8"\u0063", u8"\u005B", u8"\u0056", u8"\u004D", u8"\u0049", u8"\u004E",
u8"\u005D", u8"\u0020", u8"\u003D", u8"\u0020", u8"\u0076", u8"\u006D",
u8"\u0069", u8"\u006E", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0074", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072",
u8"\u002E", u8"\u0063", u8"\u005F", u8"\u0063", u8"\u0063", u8"\u005B",
u8"\u0056", u8"\u0054", u8"\u0049", u8"\u004D", u8"\u0045", u8"\u005D",
u8"\u0020", u8"\u003D", u8"\u0020", u8"\u0076", u8"\u0074", u8"\u0069",
u8"\u006D", u8"\u0065", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0074", u8"\u0063", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072", u8"\u0028", u8"\u0053",
u8"\u0054", u8"\u0044", u8"\u0049", u8"\u004E", u8"\u005F", u8"\u0046",
u8"\u0049", u8"\u004C", u8"\u0045", u8"\u004E", u8"\u004F", u8"\u002C",
u8"\u0020", u8"\u0054", u8"\u0043", u8"\u0053", u8"\u0041", u8"\u0046",
u8"\u004C", u8"\u0055", u8"\u0053", u8"\u0048", u8"\u002C", u8"\u0020",
u8"\u0026", u8"\u0074", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D",
u8"\u000A", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0067", u8"\u0069",
u8"\u0073", u8"\u0074", u8"\u0065", u8"\u0072", u8"\u0053", u8"\u0069",
u8"\u0067", u8"\u0049", u8"\u006E", u8"\u0074", u8"\u0043", u8"\u0061",
u8"\u0074", u8"\u0063", u8"\u0068", u8"\u0065", u8"\u0072", u8"\u0028",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0073", u8"\u0074", u8"\u0072", u8"\u0075", u8"\u0063",
u8"\u0074", u8"\u0020", u8"\u0073", u8"\u0069", u8"\u0067", u8"\u0061",
u8"\u0063", u8"\u0074", u8"\u0069", u8"\u006F", u8"\u006E", u8"\u0020",
u8"\u0061", u8"\u0063", u8"\u0074", u8"\u0069", u8"\u006F", u8"\u006E",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u002F",
u8"\u002F", u8"\u0020", u8"\u0052", u8"\u0065", u8"\u0073", u8"\u0065",
u8"\u0074", u8"\u0020", u8"\u0061", u8"\u006C", u8"\u006C", u8"\u0020",
u8"\u006D", u8"\u0065", u8"\u006D", u8"\u0062", u8"\u0065", u8"\u0072",
u8"\u0073", u8"\u002E", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020",
u8"\u006D", u8"\u0065", u8"\u006D", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0028", u8"\u0026", u8"\u0061", u8"\u0063", u8"\u0074", u8"\u0069",
u8"\u006F", u8"\u006E", u8"\u002C", u8"\u0020", u8"\u0030", u8"\u002C",
u8"\u0020", u8"\u0073", u8"\u0069", u8"\u007A", u8"\u0065", u8"\u006F",
u8"\u0066", u8"\u0028", u8"\u0061", u8"\u0063", u8"\u0074", u8"\u0069",
u8"\u006F", u8"\u006E", u8"\u0029", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0061", u8"\u0063", u8"\u0074",
u8"\u0069", u8"\u006F", u8"\u006E", u8"\u002E", u8"\u0073", u8"\u0061",
u8"\u005F", u8"\u0068", u8"\u0061", u8"\u006E", u8"\u0064", u8"\u006C",
u8"\u0065", u8"\u0072", u8"\u0020", u8"\u003D", u8"\u0020", u8"\u0073",
u8"\u0069", u8"\u0067", u8"\u0049", u8"\u006E", u8"\u0074", u8"\u0043",
u8"\u0061", u8"\u0074", u8"\u0063", u8"\u0068", u8"\u0065", u8"\u0072",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0073",
u8"\u0069", u8"\u0067", u8"\u0061", u8"\u0063", u8"\u0074", u8"\u0069",
u8"\u006F", u8"\u006E", u8"\u0028", u8"\u0053", u8"\u0049", u8"\u0047",
u8"\u0049", u8"\u004E", u8"\u0054", u8"\u002C", u8"\u0020", u8"\u0026",
u8"\u0061", u8"\u0063", u8"\u0074", u8"\u0069", u8"\u006F", u8"\u006E",
u8"\u002C", u8"\u0020", u8"\u004E", u8"\u0055", u8"\u004C", u8"\u004C",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D",
u8"\u000A", u8"\u000D", u8"\u000A", u8"\u002F", u8"\u002A", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u002A", u8"\u0020", u8"\u0047", u8"\u0065",
u8"\u0074", u8"\u0073", u8"\u0020", u8"\u0065", u8"\u0078", u8"\u0065",
u8"\u0063", u8"\u0075", u8"\u0074", u8"\u0065", u8"\u0064", u8"\u0020",
u8"\u0077", u8"\u0068", u8"\u0065", u8"\u006E", u8"\u0020", u8"\u0063",
u8"\u0074", u8"\u0072", u8"\u006C", u8"\u002D", u8"\u0063", u8"\u0020",
u8"\u0069", u8"\u0073", u8"\u0020", u8"\u0070", u8"\u0072", u8"\u0065",
u8"\u0073", u8"\u0073", u8"\u0065", u8"\u0064", u8"\u002E", u8"\u0020",
u8"\u0049", u8"\u0074", u8"\u0020", u8"\u006E", u8"\u0065", u8"\u0063",
u8"\u0065", u8"\u0073", u8"\u0061", u8"\u0072", u8"\u0079", u8"\u0020",
u8"\u0073", u8"\u006F", u8"\u0020", u8"\u0074", u8"\u0068", u8"\u0061",
u8"\u0074", u8"\u0020", u8"\u0061", u8"\u0074", u8"\u0065", u8"\u0078",
u8"\u0069", u8"\u0074", u8"\u0020", u8"\u006D", u8"\u0065", u8"\u0074",
u8"\u0068", u8"\u006F", u8"\u0064", u8"\u0020", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u002A", u8"\u0020", u8"\u0067", u8"\u0065", u8"\u0074",
u8"\u0073", u8"\u0020", u8"\u0065", u8"\u0078", u8"\u0065", u8"\u0063",
u8"\u0075", u8"\u0074", u8"\u0065", u8"\u0064", u8"\u002E", u8"\u0020",
u8"\u0061", u8"\u0074", u8"\u0065", u8"\u0078", u8"\u0069", u8"\u0074",
u8"\u0020", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0073", u8"\u0020",
u8"\u0074", u8"\u0065", u8"\u0072", u8"\u006D", u8"\u0069", u8"\u006E",
u8"\u0061", u8"\u006C", u8"\u0020", u8"\u0062", u8"\u0061", u8"\u0063",
u8"\u006B", u8"\u0020", u8"\u0074", u8"\u006F", u8"\u0020", u8"\u0074",
u8"\u0068", u8"\u0065", u8"\u0020", u8"\u006F", u8"\u0072", u8"\u0069",
u8"\u0067", u8"\u0069", u8"\u006E", u8"\u0061", u8"\u006C", u8"\u0020",
u8"\u0073", u8"\u0074", u8"\u0061", u8"\u0074", u8"\u0065", u8"\u002E",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u002A", u8"\u002F", u8"\u000D",
u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020",
u8"\u0073", u8"\u0069", u8"\u0067", u8"\u0049", u8"\u006E", u8"\u0074",
u8"\u0043", u8"\u0061", u8"\u0074", u8"\u0063", u8"\u0068", u8"\u0065",
u8"\u0072", u8"\u0028", u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0020",
u8"\u0073", u8"\u0069", u8"\u0067", u8"\u006E", u8"\u0075", u8"\u006D",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0070", u8"\u006C", u8"\u0065", u8"\u0061", u8"\u0073",
u8"\u0065", u8"\u0045", u8"\u0078", u8"\u0069", u8"\u0074", u8"\u0020",
u8"\u003D", u8"\u0020", u8"\u0031", u8"\u003B", u8"\u000D", u8"\u000A",
u8"\u007D", u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A", u8"\u0076",
u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0063", u8"\u0068",
u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052", u8"\u0065", u8"\u0074",
u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028", u8"\u0069", u8"\u006E",
u8"\u0074", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0074", u8"\u0056",
u8"\u0061", u8"\u006C", u8"\u002C", u8"\u0020", u8"\u0063", u8"\u0068",
u8"\u0061", u8"\u0072", u8"\u0020", u8"\u0063", u8"\u006F", u8"\u006E",
u8"\u0073", u8"\u0074", u8"\u0020", u8"\u0065", u8"\u0072", u8"\u0072",
u8"\u004D", u8"\u0073", u8"\u0067", u8"\u005B", u8"\u005D", u8"\u0029",
u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020",
u8"\u0069", u8"\u0066", u8"\u0020", u8"\u0028", u8"\u0072", u8"\u0065",
u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0020", u8"\u003D",
u8"\u003D", u8"\u0020", u8"\u002D", u8"\u0031", u8"\u0029", u8"\u0020",
u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020",
u8"\u0020", u8"\u0066", u8"\u0070", u8"\u0072", u8"\u0069", u8"\u006E",
u8"\u0074", u8"\u0066", u8"\u0028", u8"\u0073", u8"\u0074", u8"\u0064",
u8"\u0065", u8"\u0072", u8"\u0072", u8"\u002C", u8"\u0020", u8"\u0022",
u8"\u0025", u8"\u0073", u8"\u0022", u8"\u002C", u8"\u0020", u8"\u0065",
u8"\u0072", u8"\u0072", u8"\u004D", u8"\u0073", u8"\u0067", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u007D",
u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D", u8"\u000A", u8"\u000D",
u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020",
u8"\u0064", u8"\u0069", u8"\u0073", u8"\u0061", u8"\u0062", u8"\u006C",
u8"\u0065", u8"\u0052", u8"\u0065", u8"\u0070", u8"\u0065", u8"\u0061",
u8"\u0074", u8"\u0041", u8"\u006E", u8"\u0064", u8"\u0043", u8"\u0075",
u8"\u0072", u8"\u0073", u8"\u006F", u8"\u0072", u8"\u0028", u8"\u0029",
u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020",
u8"\u0069", u8"\u0066", u8"\u0020", u8"\u0028", u8"\u0044", u8"\u0049",
u8"\u0053", u8"\u0041", u8"\u0042", u8"\u004C", u8"\u0045", u8"\u005F",
u8"\u0052", u8"\u0045", u8"\u0050", u8"\u0045", u8"\u0041", u8"\u0054",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0020", u8"\u0020", u8"\u002F", u8"\u002F", u8"\u0020",
u8"\u0044", u8"\u0069", u8"\u0073", u8"\u0061", u8"\u0062", u8"\u006C",
u8"\u0065", u8"\u0073", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0070",
u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0020", u8"\u0069", u8"\u006E",
u8"\u0020", u8"\u0078", u8"\u0077", u8"\u0069", u8"\u006E", u8"\u0064",
u8"\u006F", u8"\u0077", u8"\u0020", u8"\u0063", u8"\u006F", u8"\u006E",
u8"\u0073", u8"\u006F", u8"\u006C", u8"\u0065", u8"\u002E", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0069",
u8"\u006E", u8"\u0074", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0074",
u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0020", u8"\u003D", u8"\u0020",
u8"\u0073", u8"\u0079", u8"\u0073", u8"\u0074", u8"\u0065", u8"\u006D",
u8"\u0028", u8"\u0022", u8"\u0078", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0020", u8"\u002D", u8"\u0072", u8"\u0022", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020",
u8"\u0063", u8"\u0068", u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052",
u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028",
u8"\u0072", u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C",
u8"\u002C", u8"\u0020", u8"\u0022", u8"\u0043", u8"\u006F", u8"\u0075",
u8"\u006C", u8"\u0064", u8"\u0020", u8"\u0064", u8"\u0069", u8"\u0073",
u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0065", u8"\u0020", u8"\u006B",
u8"\u0065", u8"\u0079", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0070",
u8"\u0065", u8"\u0061", u8"\u0074", u8"\u002E", u8"\u0022", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020",
u8"\u0020", u8"\u002F", u8"\u002F", u8"\u0020", u8"\u0044", u8"\u0069",
u8"\u0073", u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0065", u8"\u0073",
u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0070", u8"\u0065", u8"\u0061",
u8"\u0074", u8"\u0020", u8"\u0069", u8"\u006E", u8"\u0020", u8"\u004C",
u8"\u0069", u8"\u006E", u8"\u0075", u8"\u0078", u8"\u0020", u8"\u0063",
u8"\u006F", u8"\u006E", u8"\u0073", u8"\u006F", u8"\u006C", u8"\u0065",
u8"\u002E", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020",
u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061",
u8"\u006C", u8"\u0020", u8"\u003D", u8"\u0020", u8"\u0073", u8"\u0079",
u8"\u0073", u8"\u0074", u8"\u0065", u8"\u006D", u8"\u0028", u8"\u0022",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0074", u8"\u0065", u8"\u0072",
u8"\u006D", u8"\u0020", u8"\u002D", u8"\u002D", u8"\u0072", u8"\u0065",
u8"\u0070", u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0020", u8"\u006F",
u8"\u0066", u8"\u0066", u8"\u0022", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0063",
u8"\u0068", u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052", u8"\u0065",
u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028", u8"\u0072",
u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u002C",
u8"\u0020", u8"\u0022", u8"\u0043", u8"\u006F", u8"\u0075", u8"\u006C",
u8"\u0064", u8"\u0020", u8"\u0064", u8"\u0069", u8"\u0073", u8"\u0061",
u8"\u0062", u8"\u006C", u8"\u0065", u8"\u0020", u8"\u006B", u8"\u0065",
u8"\u0079", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0070", u8"\u0065",
u8"\u0061", u8"\u0074", u8"\u002E", u8"\u0022", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u007D", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u002F", u8"\u002F", u8"\u0020",
u8"\u0053", u8"\u0065", u8"\u0074", u8"\u0073", u8"\u0020", u8"\u0063",
u8"\u0075", u8"\u0072", u8"\u0073", u8"\u006F", u8"\u0072", u8"\u0020",
u8"\u006F", u8"\u0066", u8"\u0066", u8"\u002E", u8"\u0020", u8"\u0043",
u8"\u006F", u8"\u0075", u8"\u006C", u8"\u0064", u8"\u0020", u8"\u0061",
u8"\u006C", u8"\u0073", u8"\u006F", u8"\u0020", u8"\u0070", u8"\u0072",
u8"\u006F", u8"\u0062", u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0079",
u8"\u0020", u8"\u0075", u8"\u0073", u8"\u0065", u8"\u0020", u8"\u0073",
u8"\u0079", u8"\u0073", u8"\u0074", u8"\u0065", u8"\u006D", u8"\u0028",
u8"\u0022", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0074", u8"\u0065",
u8"\u0072", u8"\u006D", u8"\u0020", u8"\u002D", u8"\u0063", u8"\u0075",
u8"\u0072", u8"\u0073", u8"\u006F", u8"\u0072", u8"\u0020", u8"\u006F",
u8"\u0066", u8"\u0066", u8"\u0029", u8"\u002E", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u0020", u8"\u0070", u8"\u0072", u8"\u0069", u8"\u006E",
u8"\u0074", u8"\u0066", u8"\u0028", u8"\u0022", u8"\u005C", u8"\u0065",
u8"\u005B", u8"\u003F", u8"\u0032", u8"\u0035", u8"\u006C", u8"\u0022",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020",
u8"\u0066", u8"\u0066", u8"\u006C", u8"\u0075", u8"\u0073", u8"\u0068",
u8"\u0028", u8"\u0073", u8"\u0074", u8"\u0064", u8"\u006F", u8"\u0075",
u8"\u0074", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D",
u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u0020", u8"\u0041", u8"\u0054",
u8"\u0020", u8"\u0045", u8"\u004E", u8"\u0044", u8"\u0020", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F",
u8"\u002F", u8"\u002F", u8"\u002F", u8"\u002F", u8"\u000D", u8"\u000A",
u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064",
u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0045", u8"\u006E", u8"\u0076", u8"\u0069", u8"\u0072", u8"\u006F",
u8"\u006E", u8"\u006D", u8"\u0065", u8"\u006E", u8"\u0074", u8"\u0028",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0049", u8"\u006E", u8"\u0070", u8"\u0075", u8"\u0074", u8"\u004D",
u8"\u006F", u8"\u0064", u8"\u0065", u8"\u0028", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0065", u8"\u006E",
u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0065", u8"\u0052", u8"\u0065",
u8"\u0070", u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0041", u8"\u006E",
u8"\u0064", u8"\u0043", u8"\u0075", u8"\u0072", u8"\u0073", u8"\u006F",
u8"\u0072", u8"\u0028", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0073", u8"\u0065",
u8"\u0074", u8"\u0043", u8"\u006F", u8"\u006E", u8"\u0073", u8"\u006F",
u8"\u006C", u8"\u0065", u8"\u0028", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u007D", u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A",
u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020", u8"\u0072",
u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0043", u8"\u006F",
u8"\u006E", u8"\u0073", u8"\u006F", u8"\u006C", u8"\u0065", u8"\u0028",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0020", u8"\u0072",
u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0020",
u8"\u003D", u8"\u0020", u8"\u0073", u8"\u0079", u8"\u0073", u8"\u0074",
u8"\u0065", u8"\u006D", u8"\u0028", u8"\u0022", u8"\u0072", u8"\u0065",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0022", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0063", u8"\u0068",
u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052", u8"\u0065", u8"\u0074",
u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028", u8"\u0072", u8"\u0065",
u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u002C", u8"\u0020",
u8"\u0022", u8"\u0043", u8"\u006F", u8"\u0075", u8"\u006C", u8"\u0064",
u8"\u0020", u8"\u006E", u8"\u006F", u8"\u0074", u8"\u0020", u8"\u0072",
u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0020", u8"\u0074",
u8"\u0068", u8"\u0065", u8"\u0020", u8"\u0073", u8"\u0063", u8"\u0072",
u8"\u0065", u8"\u0065", u8"\u006E", u8"\u002E", u8"\u0022", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D", u8"\u000A",
u8"\u000D", u8"\u000A", u8"\u002F", u8"\u002A", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u002A", u8"\u0020", u8"\u0042", u8"\u0072", u8"\u0069",
u8"\u006E", u8"\u0067", u8"\u0073", u8"\u0020", u8"\u0062", u8"\u0061",
u8"\u0063", u8"\u006B", u8"\u0020", u8"\u0063", u8"\u0061", u8"\u006E",
u8"\u006F", u8"\u006E", u8"\u0069", u8"\u0063", u8"\u0061", u8"\u006C",
u8"\u0020", u8"\u006D", u8"\u006F", u8"\u0064", u8"\u0065", u8"\u002E",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u002A", u8"\u002F", u8"\u000D",
u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069", u8"\u0064", u8"\u0020",
u8"\u0072", u8"\u0065", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0049",
u8"\u006E", u8"\u0070", u8"\u0075", u8"\u0074", u8"\u004D", u8"\u006F",
u8"\u0064", u8"\u0065", u8"\u0028", u8"\u0029", u8"\u0020", u8"\u007B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0074", u8"\u0063",
u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0061", u8"\u0074", u8"\u0074",
u8"\u0072", u8"\u0028", u8"\u0053", u8"\u0054", u8"\u0044", u8"\u0049",
u8"\u004E", u8"\u005F", u8"\u0046", u8"\u0049", u8"\u004C", u8"\u0045",
u8"\u004E", u8"\u004F", u8"\u002C", u8"\u0020", u8"\u0054", u8"\u0043",
u8"\u0053", u8"\u0041", u8"\u004E", u8"\u004F", u8"\u0057", u8"\u002C",
u8"\u0020", u8"\u0026", u8"\u0073", u8"\u0061", u8"\u0076", u8"\u0065",
u8"\u0064", u8"\u005F", u8"\u0061", u8"\u0074", u8"\u0074", u8"\u0072",
u8"\u0069", u8"\u0062", u8"\u0075", u8"\u0074", u8"\u0065", u8"\u0073",
u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D", u8"\u000D",
u8"\u000A", u8"\u000D", u8"\u000A", u8"\u0076", u8"\u006F", u8"\u0069",
u8"\u0064", u8"\u0020", u8"\u0065", u8"\u006E", u8"\u0061", u8"\u0062",
u8"\u006C", u8"\u0065", u8"\u0052", u8"\u0065", u8"\u0070", u8"\u0065",
u8"\u0061", u8"\u0074", u8"\u0041", u8"\u006E", u8"\u0064", u8"\u0043",
u8"\u0075", u8"\u0072", u8"\u0073", u8"\u006F", u8"\u0072", u8"\u0028",
u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0069", u8"\u0066", u8"\u0020", u8"\u0028", u8"\u0044",
u8"\u0049", u8"\u0053", u8"\u0041", u8"\u0042", u8"\u004C", u8"\u0045",
u8"\u005F", u8"\u0052", u8"\u0045", u8"\u0050", u8"\u0045", u8"\u0041",
u8"\u0054", u8"\u0029", u8"\u0020", u8"\u007B", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u002F", u8"\u002F",
u8"\u0020", u8"\u0045", u8"\u006E", u8"\u0061", u8"\u0062", u8"\u006C",
u8"\u0065", u8"\u0073", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0070",
u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0020", u8"\u0069", u8"\u006E",
u8"\u0020", u8"\u0058", u8"\u0077", u8"\u0069", u8"\u006E", u8"\u0064",
u8"\u006F", u8"\u0077", u8"\u0020", u8"\u0063", u8"\u006F", u8"\u006E",
u8"\u0073", u8"\u006F", u8"\u006C", u8"\u0065", u8"\u002E", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0069",
u8"\u006E", u8"\u0074", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0074",
u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0020", u8"\u003D", u8"\u0020",
u8"\u0073", u8"\u0079", u8"\u0073", u8"\u0074", u8"\u0065", u8"\u006D",
u8"\u0028", u8"\u0022", u8"\u0078", u8"\u0073", u8"\u0065", u8"\u0074",
u8"\u0020", u8"\u0072", u8"\u0022", u8"\u0029", u8"\u003B", u8"\u000D",
u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0063",
u8"\u0068", u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052", u8"\u0065",
u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028", u8"\u0072",
u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u002C",
u8"\u0020", u8"\u0022", u8"\u0043", u8"\u006F", u8"\u0075", u8"\u006C",
u8"\u0064", u8"\u0020", u8"\u006E", u8"\u006F", u8"\u0074", u8"\u0020",
u8"\u0065", u8"\u006E", u8"\u0061", u8"\u0062", u8"\u006C", u8"\u0065",
u8"\u0020", u8"\u006B", u8"\u0065", u8"\u0079", u8"\u0020", u8"\u0072",
u8"\u0065", u8"\u0070", u8"\u0065", u8"\u0061", u8"\u0074", u8"\u002E",
u8"\u0022", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0020", u8"\u0020", u8"\u002F", u8"\u002F", u8"\u0020",
u8"\u0044", u8"\u0069", u8"\u0073", u8"\u0061", u8"\u0062", u8"\u006C",
u8"\u0065", u8"\u0073", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0070",
u8"\u0065", u8"\u0061", u8"\u0074", u8"\u0020", u8"\u0069", u8"\u006E",
u8"\u0020", u8"\u004C", u8"\u0069", u8"\u006E", u8"\u0075", u8"\u0078",
u8"\u0020", u8"\u0063", u8"\u006F", u8"\u006E", u8"\u0073", u8"\u006F",
u8"\u006C", u8"\u0065", u8"\u002E", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0072", u8"\u0065", u8"\u0074",
u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0020", u8"\u003D", u8"\u0020",
u8"\u0073", u8"\u0079", u8"\u0073", u8"\u0074", u8"\u0065", u8"\u006D",
u8"\u0028", u8"\u0022", u8"\u0073", u8"\u0065", u8"\u0074", u8"\u0074",
u8"\u0065", u8"\u0072", u8"\u006D", u8"\u0020", u8"\u002D", u8"\u002D",
u8"\u0072", u8"\u0065", u8"\u0070", u8"\u0065", u8"\u0061", u8"\u0074",
u8"\u0020", u8"\u006F", u8"\u006E", u8"\u0022", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0020", u8"\u0020",
u8"\u0063", u8"\u0068", u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052",
u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028",
u8"\u0072", u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C",
u8"\u002C", u8"\u0020", u8"\u0022", u8"\u0043", u8"\u006F", u8"\u0075",
u8"\u006C", u8"\u0064", u8"\u0020", u8"\u006E", u8"\u006F", u8"\u0074",
u8"\u0020", u8"\u0065", u8"\u006E", u8"\u0061", u8"\u0062", u8"\u006C",
u8"\u0065", u8"\u0020", u8"\u006B", u8"\u0065", u8"\u0079", u8"\u0020",
u8"\u0072", u8"\u0065", u8"\u0070", u8"\u0065", u8"\u0061", u8"\u0074",
u8"\u002E", u8"\u0022", u8"\u0029", u8"\u003B", u8"\u000D", u8"\u000A",
u8"\u0020", u8"\u0020", u8"\u007D", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0069", u8"\u006E", u8"\u0074", u8"\u0020", u8"\u0072",
u8"\u0065", u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0020",
u8"\u003D", u8"\u0020", u8"\u0073", u8"\u0079", u8"\u0073", u8"\u0074",
u8"\u0065", u8"\u006D", u8"\u0028", u8"\u0022", u8"\u0063", u8"\u006C",
u8"\u0065", u8"\u0061", u8"\u0072", u8"\u0022", u8"\u0029", u8"\u003B",
u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0063", u8"\u0068",
u8"\u0065", u8"\u0063", u8"\u006B", u8"\u0052", u8"\u0065", u8"\u0074",
u8"\u0056", u8"\u0061", u8"\u006C", u8"\u0028", u8"\u0072", u8"\u0065",
u8"\u0074", u8"\u0056", u8"\u0061", u8"\u006C", u8"\u002C", u8"\u0020",
u8"\u0022", u8"\u0043", u8"\u006F", u8"\u0075", u8"\u006C", u8"\u0064",
u8"\u0020", u8"\u006E", u8"\u006F", u8"\u0074", u8"\u0020", u8"\u0063",
u8"\u006C", u8"\u0065", u8"\u0061", u8"\u0072", u8"\u0020", u8"\u0074",
u8"\u0068", u8"\u0065", u8"\u0020", u8"\u0073", u8"\u0063", u8"\u0072",
u8"\u0065", u8"\u0065", u8"\u006E", u8"\u002E", u8"\u0022", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u002F",
u8"\u002F", u8"\u0020", u8"\u0042", u8"\u0072", u8"\u0069", u8"\u006E",
u8"\u0067", u8"\u0073", u8"\u0020", u8"\u0062", u8"\u0061", u8"\u0063",
u8"\u006B", u8"\u0020", u8"\u0063", u8"\u0075", u8"\u0072", u8"\u0073",
u8"\u006F", u8"\u0072", u8"\u002E", u8"\u000D", u8"\u000A", u8"\u0020",
u8"\u0020", u8"\u0070", u8"\u0072", u8"\u0069", u8"\u006E", u8"\u0074",
u8"\u0066", u8"\u0028", u8"\u0022", u8"\u005C", u8"\u0065", u8"\u005B",
u8"\u003F", u8"\u0032", u8"\u0035", u8"\u0068", u8"\u0022", u8"\u0029",
u8"\u003B", u8"\u000D", u8"\u000A", u8"\u0020", u8"\u0020", u8"\u0066",
u8"\u0066", u8"\u006C", u8"\u0075", u8"\u0073", u8"\u0068", u8"\u0028",
u8"\u0073", u8"\u0074", u8"\u0064", u8"\u006F", u8"\u0075", u8"\u0074",
u8"\u0029", u8"\u0020", u8"\u003B", u8"\u000D", u8"\u000A", u8"\u007D",
u8"\u000D", u8"\u000A", u8"\u000D", u8"\u000A"
};
#endif | 71.716858 | 119 | 0.576668 | [
"vector"
] |
9a8e2530e7c74319bd4a47208d59d5ca737ff469 | 9,658 | cc | C++ | paddle/fluid/framework/ir/memory_optimize_pass/memory_reuse_pass.cc | qingfengwuhen/Paddle | cff5e2c173afc4431085b9382c716be7a9b91759 | [
"Apache-2.0"
] | 1 | 2019-09-05T07:32:44.000Z | 2019-09-05T07:32:44.000Z | paddle/fluid/framework/ir/memory_optimize_pass/memory_reuse_pass.cc | qingfengwuhen/Paddle | cff5e2c173afc4431085b9382c716be7a9b91759 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/framework/ir/memory_optimize_pass/memory_reuse_pass.cc | qingfengwuhen/Paddle | cff5e2c173afc4431085b9382c716be7a9b91759 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/ir/memory_optimize_pass/memory_reuse_pass.h"
#include <map>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace paddle {
namespace framework {
namespace ir {
// Each ShareTensorBufferOpHandle should only have one pending
// ComputationOpHandle
static details::ComputationOpHandle *GetUniquePendingComputationOpHandle(
details::ShareTensorBufferOpHandle *share_tensor_op) {
details::ComputationOpHandle *result_op = nullptr;
for (Node *out_var : share_tensor_op->Node()->outputs) {
for (Node *pending_op : out_var->outputs) {
auto &op = pending_op->Wrapper<details::OpHandleBase>();
auto *compute_op = dynamic_cast<details::ComputationOpHandle *>(&op);
PADDLE_ENFORCE_NOT_NULL(compute_op);
if (result_op == nullptr) {
result_op = compute_op;
} else {
PADDLE_ENFORCE_EQ(result_op, compute_op);
}
}
}
PADDLE_ENFORCE_NOT_NULL(result_op);
return result_op;
}
void MemoryReusePass::ApplyImpl(Graph *graph) const {
graph_ = graph;
all_vars_ = &(graph_->Get<details::GraphVars>(details::kGraphVars));
var_infos_ = &(Get<MemOptVarInfoMapList>(kMemOptVarInfoMapList));
last_live_ops_of_vars_ =
&(Get<std::vector<LastLiveOpsOfVars>>(kLastLiveOpsOfVars));
reused_var_names_.resize(all_vars_->size());
var_descs_.resize(all_vars_->size());
// Collect the existing ShareTensorBufferOpHandles.
// This is because (1) we want to reuse the existing
// ShareTensorBufferOpHandles to avoid inserting too many ops;
// (2) what is more important, a variable cannot be reused
// by two different variables, which may cause wrong calculation
// results. We have to know which variables have been reused.
CollectShareTensorBufferOpHandles();
CollectReusedVars();
Run(graph);
std::map<size_t, size_t> op_num;
for (auto &pair : ops_) {
++op_num[pair.first->GetScopeIdx()];
}
for (auto &pair : op_num) {
VLOG(2) << "Create " << pair.second
<< " ShareTensorBufferOpHandles in Scope " << pair.first;
}
}
bool MemoryReusePass::TryReuseVar(details::VarHandle *in_var,
details::VarHandle *out_var) const {
auto *op =
dynamic_cast<details::ComputationOpHandle *>(out_var->GeneratedOp());
PADDLE_ENFORCE_NOT_NULL(op);
if (IsVarsReusable(in_var, out_var)) {
AddReuseVar(op, in_var, out_var);
return true;
} else {
return false;
}
}
std::unordered_set<Node *> MemoryReusePass::FindNodesByName(
const std::string &name, const std::vector<Node *> &nodes) const {
std::unordered_set<ir::Node *> ret;
for (auto *node : nodes) {
if (node->Name() == name) {
ret.insert(node);
}
}
return ret;
}
VarDesc *MemoryReusePass::GetVarDesc(details::VarHandle *var) const {
auto iter = var_descs_[var->scope_idx()].find(var->Name());
if (iter == var_descs_[var->scope_idx()].end()) {
PADDLE_ENFORCE((*all_vars_)[var->scope_idx()].count(var->Name()),
"Variable %s not found", var->Name());
auto *desc =
TryGetLatestVarDesc((*all_vars_)[var->scope_idx()].at(var->Name()));
PADDLE_ENFORCE_NOT_NULL(desc);
var_descs_[var->scope_idx()].emplace(var->Name(), desc);
return desc;
} else {
return iter->second;
}
}
void MemoryReusePass::CollectShareTensorBufferOpHandles() const {
auto all_ops = FilterByNodeWrapper<details::OpHandleBase>(*graph_);
for (auto *op : all_ops) {
auto *share_buffer_op =
dynamic_cast<details::ShareTensorBufferOpHandle *>(op);
if (share_buffer_op != nullptr) {
auto *compute_op = GetUniquePendingComputationOpHandle(share_buffer_op);
PADDLE_ENFORCE(ops_.count(compute_op) == 0);
ops_.emplace(compute_op, share_buffer_op);
}
}
}
void MemoryReusePass::CollectReusedVars() const {
for (auto &pair : ops_) {
auto reused_vars = pair.second->ReusedVarSet();
reused_var_names_[pair.first->GetScopeIdx()].insert(reused_vars.begin(),
reused_vars.end());
}
}
bool MemoryReusePass::IsVarAlreadyReused(details::VarHandle *var) const {
return reused_var_names_[var->scope_idx()].count(var->Name()) > 0;
}
details::ShareTensorBufferOpHandle *
MemoryReusePass::InsertShareTensorBufferOpHandleToGraph(
details::ComputationOpHandle *op) const {
auto *buffer_share_node =
graph_->CreateEmptyNode("buffer_share", ir::Node::Type::kOperation);
auto *buffer_share_op = new details::ShareTensorBufferOpHandle(
buffer_share_node, op->GetScope(), op->GetScopeIdx(), op->GetOp()->Type(),
{}, {});
buffer_share_op->SetDeviceContext(
op->GetPlace(),
platform::DeviceContextPool::Instance().Get(op->GetPlace()));
// Inputs of `buffer_share_op` should be all inputs of `op`
for (auto *in_var : op->Inputs()) {
buffer_share_op->AddInput(in_var);
}
// Add a dep_var to resolve write-after-write data hazard between
// `buffer_share_op` and `op`.
auto *dep_var = new details::DummyVarHandle(graph_->CreateControlDepVar());
graph_->Get<details::GraphDepVars>(details::kGraphDepVars).emplace(dep_var);
op->AddInput(dep_var);
buffer_share_op->AddOutput(dep_var);
ops_.emplace(op, buffer_share_op);
return buffer_share_op;
}
bool MemoryReusePass::IsVarsReusable(details::VarHandle *in_var,
details::VarHandle *out_var) const {
const auto in_name = in_var->Name();
const auto out_name = out_var->Name();
if (in_name == out_name) {
return false;
}
if (in_name == kEmptyVarName || out_name == kEmptyVarName) {
return false;
}
if (IsVarAlreadyReused(in_var)) {
return false;
}
// out_var must be the first version!!!
auto out_var_iter = (*all_vars_)[out_var->scope_idx()].find(out_name);
PADDLE_ENFORCE(out_var_iter != (*all_vars_)[out_var->scope_idx()].end() &&
!out_var_iter->second.empty(),
"Cannot find variable %s", out_name);
if (out_var_iter->second[0] != out_var) {
return false;
}
const VarDesc *in_var_desc = GetVarDesc(in_var);
const VarDesc *out_var_desc = GetVarDesc(out_var);
if (in_var_desc->Persistable() || out_var_desc->Persistable()) {
return false;
}
if (in_var_desc->GetType() != proto::VarType::LOD_TENSOR ||
out_var_desc->GetType() != proto::VarType::LOD_TENSOR) {
return false;
}
if (!FindNodesByName(in_name, out_var->GeneratedOp()->Node()->outputs)
.empty()) {
return false;
}
if (!FindNodesByName(out_name, out_var->GeneratedOp()->Node()->inputs)
.empty()) {
return false;
}
auto all_input_args =
out_var->GeneratedOp()->Node()->Op()->InputArgumentNames();
if (std::count(all_input_args.begin(), all_input_args.end(), in_name) > 1) {
return false;
}
return true;
}
void MemoryReusePass::AddReuseVar(details::ComputationOpHandle *op,
details::VarHandle *in_var,
details::VarHandle *out_var) const {
PADDLE_ENFORCE((*var_infos_)[op->GetScopeIdx()].count(in_var->Name()) > 0,
"%s does not in mem-opt var infos", in_var->Name());
if (ops_.count(op) == 0) {
InsertShareTensorBufferOpHandleToGraph(op);
}
auto *share_buffer_op = ops_[op];
auto &all_input_vars = share_buffer_op->Inputs();
bool has_input = std::find(all_input_vars.begin(), all_input_vars.end(),
in_var) != all_input_vars.end();
if (!has_input) {
share_buffer_op->AddInput(in_var);
}
share_buffer_op->Add(
(*var_infos_)[op->GetScopeIdx()].at(in_var->Name()).get(),
out_var->Name());
reused_var_names_[op->GetScopeIdx()].insert(in_var->Name());
UpdateLastLiveOpOfVar(op, in_var, out_var);
}
// 1. Set last living op of in_var to be any last living op of out_var
// 2. Set reference count of in_var to be 1
void MemoryReusePass::UpdateLastLiveOpOfVar(details::ComputationOpHandle *op,
details::VarHandle *in_var,
details::VarHandle *out_var) const {
size_t scope_idx = op->GetScopeIdx();
auto out_var_op_iter =
(*last_live_ops_of_vars_)[scope_idx].find(out_var->Name());
PADDLE_ENFORCE(out_var_op_iter != (*last_live_ops_of_vars_)[scope_idx].end(),
"Cannot find variable %s", out_var->Name());
PADDLE_ENFORCE(!out_var_op_iter->second.empty());
auto &last_live_ops_of_in_var =
(*last_live_ops_of_vars_)[scope_idx][in_var->Name()];
last_live_ops_of_in_var.clear();
last_live_ops_of_in_var.insert(*(out_var_op_iter->second.begin()));
auto in_var_info_iter = (*var_infos_)[scope_idx].find(in_var->Name());
PADDLE_ENFORCE(in_var_info_iter != (*var_infos_)[scope_idx].end(),
"Cannot find variable %s", in_var->Name());
in_var_info_iter->second->SetRefCnt(1);
}
} // namespace ir
} // namespace framework
} // namespace paddle
| 33.651568 | 80 | 0.672914 | [
"vector"
] |
9aa0d12bd43ba4e537c465799b39403987eb1d84 | 4,455 | cpp | C++ | example/src/main.cpp | demurzasty/rabb | f980fd18332f7846cd22b502f1075d224938379c | [
"MIT"
] | 8 | 2020-11-21T17:59:09.000Z | 2022-02-13T05:14:40.000Z | example/src/main.cpp | demurzasty/rabb | f980fd18332f7846cd22b502f1075d224938379c | [
"MIT"
] | null | null | null | example/src/main.cpp | demurzasty/rabb | f980fd18332f7846cd22b502f1075d224938379c | [
"MIT"
] | 1 | 2020-11-23T23:01:14.000Z | 2020-11-23T23:01:14.000Z | #include <rabbit/rabbit.hpp>
#include <filesystem>
using namespace rb;
struct camera_controller : public rb::system {
void update(registry& registry, float elapsed_time) override {
if (input::is_mouse_button_pressed(mouse_button::right)) {
_last_mouse_position = input::mouse_position();
}
for (const auto& [entity, transform, camera] : registry.view<transform, camera>().each()) {
if (input::is_mouse_button_down(mouse_button::right)) {
const auto speed = input::is_key_down(keycode::space) ? 10.0f : 2.5f;
const auto mouse_position = input::mouse_position();
const auto diff = _last_mouse_position - mouse_position;
_last_mouse_position = mouse_position;
registry.patch<rb::transform>(entity, [this, diff, elapsed_time, speed](rb::transform& transform) {
_target_camera_rotation.y += diff.x * 0.005f;
_target_camera_rotation.x += diff.y * 0.005f;
if (input::is_key_down(keycode::e)) {
_target_camera_position.y += elapsed_time * speed;
} else if (input::is_key_down(keycode::q)) {
_target_camera_position.y -= elapsed_time * speed;
}
if (input::is_key_down(keycode::w)) {
_target_camera_position.x -= std::sin(_target_camera_rotation.y) * elapsed_time * speed;
_target_camera_position.z -= std::cos(_target_camera_rotation.y) * elapsed_time * speed;
} else if (input::is_key_down(keycode::s)) {
_target_camera_position.x += std::sin(_target_camera_rotation.y) * elapsed_time * speed;
_target_camera_position.z += std::cos(_target_camera_rotation.y) * elapsed_time * speed;
}
if (input::is_key_down(keycode::d)) {
_target_camera_position.x -= std::sin(_target_camera_rotation.y - pi<float>() * 0.5f) * elapsed_time * speed;
_target_camera_position.z -= std::cos(_target_camera_rotation.y - pi<float>() * 0.5f) * elapsed_time * speed;
} else if (input::is_key_down(keycode::a)) {
_target_camera_position.x -= std::sin(_target_camera_rotation.y + pi<float>() * 0.5f) * elapsed_time * speed;
_target_camera_position.z -= std::cos(_target_camera_rotation.y + pi<float>() * 0.5f) * elapsed_time * speed;
}
});
}
registry.patch<rb::transform>(entity, [this, elapsed_time](rb::transform& transform) {
transform.position = _smooth(transform.position, _target_camera_position, elapsed_time);
transform.rotation = _smooth(transform.rotation, _target_camera_rotation, elapsed_time);
});
}
}
private:
vec3f _smooth(const vec3f& origin, const vec3f& target, float elapsed_time) {
const auto diff = target - origin;
if (diff != vec3f::zero()) {
const auto len = length(diff);
if (len > 0.0f) {
const auto dir = diff / len;
const auto ftr = std::max(len * 40.0f, 0.01f);
const auto off = std::min(elapsed_time * ftr, len);
return origin + dir * off;
}
}
return target;
}
private:
vec2i _last_mouse_position;
vec3f _target_camera_position{ -6.0f, 5.0f, 6.0f };
vec3f _target_camera_rotation{ -0.471238941f, -0.785398185f, 0.0f };
};
class fps_meter : public rb::system {
public:
void update(registry& registry, float elapsed_time) override {
_time += elapsed_time;
if (_time > 1.0f) {
window::set_title(format("RabBit FPS: {}", _fps));
_fps = 0;
_time -= 1.0f;
}
}
void draw(registry& registry) override {
++_fps;
}
private:
int _fps{ 0 };
float _time{ 0.0f };
};
int main(int argc, char* argv[]) {
#if !RB_PROD_BUILD
std::filesystem::current_path(CURRENT_DIRECTORY);
#endif
app::setup();
app::system<camera_controller>();
app::system<fps_meter>();
app::run("data/prefabs/scene.scn");
}
| 40.87156 | 134 | 0.558025 | [
"transform"
] |
9aa79e9db6aa48a4b94aec85de992731badc894c | 1,529 | cpp | C++ | src/caffe/layers/relu_layer.cpp | oscmansan/nvcaffe | 22738c97e9c6991e49a12a924c3c773d95795b5c | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/relu_layer.cpp | oscmansan/nvcaffe | 22738c97e9c6991e49a12a924c3c773d95795b5c | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/relu_layer.cpp | oscmansan/nvcaffe | 22738c97e9c6991e49a12a924c3c773d95795b5c | [
"BSD-2-Clause"
] | null | null | null | #include <algorithm>
#include <vector>
#include "caffe/layer.hpp"
#include "caffe/vision_layers.hpp"
namespace caffe {
template <typename Dtype, typename Mtype>
void ReLULayer<Dtype,Mtype>::Forward_cpu(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
const int count = bottom[0]->count();
Mtype negative_slope(this->layer_param_.relu_param().negative_slope());
for (int i = 0; i < count; ++i) {
top_data[i] = Get<Dtype>( std::max(Get<Mtype>(bottom_data[i]), Mtype(0))
+ negative_slope * std::min(Get<Mtype>(bottom_data[i]), Mtype(0)) );
}
}
template <typename Dtype, typename Mtype>
void ReLULayer<Dtype,Mtype>::Backward_cpu(const vector<Blob<Dtype,Mtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype,Mtype>*>& bottom) {
if (propagate_down[0]) {
const Dtype* bottom_data = bottom[0]->cpu_data();
const Dtype* top_diff = top[0]->cpu_diff();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const int count = bottom[0]->count();
Mtype negative_slope(this->layer_param_.relu_param().negative_slope());
for (int i = 0; i < count; ++i) {
bottom_diff[i] = Get<Dtype>( Get<Mtype>(top_diff[i]) * ((Get<Mtype>(bottom_data[i]) > 0)
+ negative_slope * (Get<Mtype>(bottom_data[i]) <= 0)) );
}
}
}
#ifdef CPU_ONLY
STUB_GPU(ReLULayer);
#endif
INSTANTIATE_CLASS(ReLULayer);
} // namespace caffe
| 32.531915 | 94 | 0.671681 | [
"vector"
] |
9aabd69b5314844153e3bc8dcdbf8acd7d454bc9 | 16,768 | cpp | C++ | games/pacman/Pacman.cpp | rectoria/cpp_arcade | 72bff5ec97f90dcc05ff4079f7ba30d5af9fb147 | [
"MIT"
] | null | null | null | games/pacman/Pacman.cpp | rectoria/cpp_arcade | 72bff5ec97f90dcc05ff4079f7ba30d5af9fb147 | [
"MIT"
] | null | null | null | games/pacman/Pacman.cpp | rectoria/cpp_arcade | 72bff5ec97f90dcc05ff4079f7ba30d5af9fb147 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** cpp_arcade
** File description:
** Created by rectoria
*/
#include <string>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include "Pacman.hpp"
Arcade::IGameLib *lib = nullptr;
__attribute__((constructor)) void init()
{
lib = new Arcade::Pacman;
}
__attribute__((destructor)) void destruct()
{
delete lib;
}
extern "C" Arcade::IGameLib *entryPoint(void)
{
return lib;
}
Arcade::Pacman::Pacman()
{
_startTime = static_cast<size_t>(time(nullptr));
}
bool Arcade::Pacman::init()
{
// Initialisation des variables, des Fantom et de la map
loadMap();
initPosition();
countFood();
return true;
}
void Arcade::Pacman::clearValue()
{
// Remet à 0 les valeurs
_score = 0;
_time = 0;
_startTime = static_cast<size_t>(time(nullptr));
_posp.pop_back();
_posp.pop_back();
_posf.pop_back();
_posf.pop_back();
_posf.pop_back();
_posf.pop_back();
}
void Arcade::Pacman::initPosition()
{
// Initialisation de toutes les positions
_posp.push_back(27 - 1); // x
_posp.push_back(30 - 1); // y
std::vector<size_t> one = {13 - 1, 14 - 1, 0, 32};
_posf.push_back(one);
std::vector<size_t> two = {13 - 1, 15 - 1, 0, 32};
_posf.push_back(two);
std::vector<size_t> three = {15 - 1, 15 - 1, 0, 32};
_posf.push_back(three);
std::vector<size_t> four = {15 - 1, 14 - 1, 0, 32};
_posf.push_back(four);
}
bool Arcade::Pacman::stop()
{
// Lorsque BACKSPACE est cliqué
clearValue();
init();
return true;
}
bool Arcade::Pacman::applyEvent(Arcade::Keys key)
{
std::unordered_map<Arcade::Keys, size_t> action = {{Arcade::Keys::Z, 0},
{Arcade::Keys::S, 1}, {Arcade::Keys::Q, 2},
{Arcade::Keys::D, 3}};
bool (Arcade::Pacman::*moveArr[4])() = {&Arcade::Pacman::moveUpP,
&Arcade::Pacman::moveDownP, &Arcade::Pacman::moveLeftP,
&Arcade::Pacman::moveRightP};
if (action.count(key))
return (this->*moveArr[action.at(key)])();
return true;
}
bool Arcade::Pacman::update()
{
goToHouse();
return end_condition();
}
void Arcade::Pacman::printGhost(Arcade::IGraphicLib &gl,
Arcade::Vect<size_t> res
) const
{
Arcade::PixelBox pB;
auto pWidth = static_cast<size_t>(res.getX() * 0.6 / _width);
auto pHeight = static_cast<size_t>(res.getY() * 0.6 / _height);
auto offsetX = static_cast<size_t>(res.getX() * 0.3);
auto offsetY = static_cast<size_t>(res.getY() * 0.3);
//Print des fantomes
//F1
pB = Arcade::PixelBox(Arcade::Vect<size_t>(pWidth, pHeight),
Arcade::Vect<size_t>(), Arcade::Color(234, 130, 229, 255));
pB.setX(offsetX + _posf[0][0] * pWidth);
pB.setY(offsetY + _posf[0][1] * pHeight);
gl.drawPixelBox(pB);
//F2
pB = Arcade::PixelBox(Arcade::Vect<size_t>(pWidth, pHeight),
Arcade::Vect<size_t>(), Arcade::Color(70, 191, 238, 255));
pB.setX(offsetX + _posf[1][0] * pWidth);
pB.setY(offsetY + _posf[1][1] * pHeight);
gl.drawPixelBox(pB);
//F3
pB = Arcade::PixelBox(Arcade::Vect<size_t>(pWidth, pHeight),
Arcade::Vect<size_t>(), Arcade::Color(208, 62, 25, 255));
pB.setX(offsetX + _posf[2][0] * pWidth);
pB.setY(offsetY + _posf[2][1] * pHeight);
gl.drawPixelBox(pB);
//F4
pB = Arcade::PixelBox(Arcade::Vect<size_t>(pWidth, pHeight),
Arcade::Vect<size_t>(), Arcade::Color(219, 133, 28, 255));
pB.setX(offsetX + _posf[3][0] * pWidth);
pB.setY(offsetY + _posf[3][1] * pHeight);
gl.drawPixelBox(pB);
}
void Arcade::Pacman::printPac(Arcade::IGraphicLib &gl, Arcade::Vect<size_t> res
) const
{
Arcade::PixelBox pB;
auto pWidth = static_cast<size_t>(res.getX() * 0.6 / _width);
auto pHeight = static_cast<size_t>(res.getY() * 0.6 / _height);
auto offsetX = static_cast<size_t>(res.getX() * 0.3);
auto offsetY = static_cast<size_t>(res.getY() * 0.3);
//Print du Pacman
pB = Arcade::PixelBox(Arcade::Vect<size_t>(pWidth, pHeight),
Arcade::Vect<size_t>(), Arcade::Color(253, 255, 0, 255));
pB.setX(offsetX + _posp[0] * pWidth);
pB.setY(offsetY + _posp[1] * pHeight);
gl.drawPixelBox(pB);
}
void Arcade::Pacman::printMaze(Arcade::IGraphicLib &gl,
Arcade::Vect<size_t> res
) const
{
Arcade::PixelBox pB;
auto pWidth = static_cast<size_t>(res.getX() * 0.6 / _width);
auto pHeight = static_cast<size_t>(res.getY() * 0.6 / _height);
auto offsetX = static_cast<size_t>(res.getX() * 0.3);
auto offsetY = static_cast<size_t>(res.getY() * 0.3);
Arcade::Color cols[3] = {Arcade::Color(64, 25, 76, 255),
Arcade::Color(183, 110, 0, 255),
Arcade::Color(236, 117, 115, 255)};
char caracs[5] = {'=', '.', 'o', '|', 'X'};
//Print du labyrinthe
for (unsigned i = 0, idx = 0; i < _map.size(); ++i, idx = 0) {
for (int iter = 0; !iter; ++idx)
iter = _map[i] == caracs[idx];
pB = Arcade::PixelBox(Arcade::Vect<size_t>(pWidth, pHeight),
Arcade::Vect<size_t>(), cols[idx % 3]);
if (_map[i] == '=' || _map[i] == '.' || _map[i] == 'o') {
pB.setX(offsetX + i % (_width) * pWidth);
pB.setY(offsetY + i / (_width) * pHeight);
gl.drawPixelBox(pB);
}
}
}
void Arcade::Pacman::refresh(IGraphicLib &gl)
{
auto res = gl.getScreenSize();
// Gestion du temsp de jeu
_time = time(nullptr) - _startTime;
// Movement du Pacman et des Fantoms
movePacman();
moveFantom();
// Condition de win (avoir tout mangé sur la map)
if (_food <= 0) {
clearValue();
init();
}
Arcade::TextBox score = Arcade::TextBox(
"Score : " + std::to_string(static_cast<unsigned >(_score)),
Arcade::Vect<size_t>());
Arcade::TextBox timer = Arcade::TextBox(
"Time : " + std::to_string(static_cast<unsigned >(_time)),
Arcade::Vect<size_t>(res.getX() / 2, 0));
gl.clearWindow();
printMaze(gl, res);
printPac(gl, res);
printGhost(gl, res);
//Print du score et du timer
gl.drawText(score);
gl.drawText(timer);
gl.refreshWindow();
}
bool Arcade::Pacman::end_condition()
{
// Gestion du temps de GodMod
if (_time - _timeGod >= 10)
_god = false;
// Condition de fin (si un fantom attrape Pacman)
for (int i = 0; i != 4; i++) {
if (_posf[i][0] == _posp[0] && _posf[i][1] == _posp[1] &&
!_god) {
// Réinitialisation des variables
clearValue();
_score = 0;
init();
return false;
}
}
return true;
}
void Arcade::Pacman::goToHouse()
{
// Réinitialise la position d'un fantom si il est mangé
for (int i = 0; i != 4; i++) {
if (_posp[0] == _posf[i][0] && _posp[1] == _posf[i][1] &&
_god) {
switch (i) {
case 0:
setValue(12, 13, 0, 32, i);
break;
case 1:
setValue(12, 14, 0, 32, i);
break;
case 2:
setValue(14, 14, 0, 32, i);
break;
case 3:
setValue(14, 13, 0, 32, i);
break;
}
}
}
}
void Arcade::Pacman::setValue(size_t x, size_t y, size_t pos, size_t old_char,
int nb
)
{
// Set la position d'un fantom
_posf[nb][0] = x;
_posf[nb][1] = y;
_posf[nb][2] = pos;
_posf[nb][3] = old_char;
}
void Arcade::Pacman::loadMap()
{
// Chargement de la map dans le fichier map.txt
std::ifstream input("map.txt");
char tmp;
if (!input) {
std::cout << "Error : file 'map.txt' not found. The default "
"map is loaded" << std::endl;
_map = _defaultMap;
} else {
while (input.read(&tmp, 1)) {
if (tmp != '\n')
_map.push_back(tmp);
}
}
}
/*
** Movement
*/
// PACMAN
bool Arcade::Pacman::moveUpP() // dir = 1
{
// Deplacement en haur de Pacman
_dir = 1;
if (_map[(((_posp[1] - 1) * _width) + _posp[0])] == '=') {
return false;
}
if (_map[((_posp[1] - 1) * _width) + (_posp[0])] == '.' ||
_map[((_posp[1] - 1) * _width) + (_posp[0])] == 'o') {
_food--;
_score += 100;
}
if (_map[((_posp[1] - 1) * _width) + (_posp[0])] == 'o') {
_timeGod = _time;
_god = true;
}
_map[(((_posp[1] - 1) * _width) + _posp[0])] = 'X';
_map[((_posp[1]) * _width) + _posp[0]] = ' ';
_posp[1]--;
return true;
}
bool Arcade::Pacman::moveDownP() // dir = 2
{
// Deplacement en bas de Pacman
_dir = 2;
if (_map[((_posp[1] + 1) * _width) + _posp[0]] == '=') {
return false;
}
if (_map[((_posp[1] + 1) * _width) + (_posp[0])] == '.' ||
_map[((_posp[1] + 1) * _width) + (_posp[0])] == 'o') {
_food--;
_score += 100;
}
if (_map[((_posp[1] + 1) * _width) + (_posp[0])] == 'o') {
_timeGod = _time;
_god = true;
}
_map[((_posp[1] + 1) * _width) + _posp[0]] = 'X';
_map[((_posp[1]) * _width) + _posp[0]] = ' ';
_posp[1]++;
return true;
}
bool Arcade::Pacman::moveLeftP() // dir = 3
{
// Deplacement à gauche de Pacman
_dir = 3;
if (_map[((_posp[1]) * _width) + (_posp[0] - 1)] == '=') {
return false;
}
if (_map[((_posp[1]) * _width) + (_posp[0] - 1)] == '.' ||
_map[((_posp[1]) * _width) + (_posp[0] - 1)] == 'o') {
_food--;
_score += 100;
}
if (_map[((_posp[1]) * _width) + (_posp[0] - 1)] == 'o') {
_timeGod = _time;
_god = true;
}
_map[((_posp[1]) * _width) + (_posp[0] - 1)] = 'X';
_map[((_posp[1]) * _width) + _posp[0]] = ' ';
_posp[0]--;
return true;
}
bool Arcade::Pacman::moveRightP() // dir = 4
{
// Deplacement à droite de Pacman
_dir = 4;
if (_map[((_posp[1]) * _width) + (_posp[0] + 1)] == '=') {
return false;
}
if (_map[((_posp[1]) * _width) + (_posp[0] + 1)] == '.' ||
_map[((_posp[1]) * _width) + (_posp[0] + 1)] == 'o') {
_food--;
_score += 100;
}
if (_map[((_posp[1]) * _width) + (_posp[0] + 1)] == 'o') {
_timeGod = _time;
_god = true;
}
_map[((_posp[1]) * _width) + (_posp[0] + 1)] = 'X';
_map[((_posp[1]) * _width) + _posp[0]] = ' ';
_posp[0]++;
return true;
}
bool Arcade::Pacman::movePacman()
{
bool ret; // Valeur de retour
// Deplacement du Pacman
switch (_dir) {
case 0:
return false;
case 1:
ret = moveUpP();
break;
case 2:
ret = moveDownP();
break;
case 3:
ret = moveLeftP();
break;
case 4:
ret = moveRightP();
break;
}
return ret;
}
// FANTOM
// _posf[i][2] = dir = 1
bool Arcade::Pacman::moveUpF(std::vector<size_t> &pos, char sym)
{
// Déplacement en bas d'un fantom
pos[2] = 1;
if (_map[(((pos[1] - 1) * _width) + pos[0])] == '=' ||
isNum(_map[(((pos[1] - 1) * _width) + pos[0])])) {
pos[2] = 0;
return false;
}
_map[((pos[1]) * _width) + pos[0]] = pos[3];
pos[3] = _map[(((pos[1] - 1) * _width) + pos[0])];
_map[(((pos[1] - 1) * _width) + pos[0])] = sym;
pos[1]--;
return true;
}
// _posf[i][2] = dir = 2
bool Arcade::Pacman::moveDownF(std::vector<size_t> &pos, char sym)
{
// Déplacement en bas d'un fantom
pos[2] = 2;
if (_map[(((pos[1] + 1) * _width) + pos[0])] == '=' ||
isNum(_map[(((pos[1] + 1) * _width) + pos[0])])) {
pos[2] = 0;
return false;
}
_map[((pos[1]) * _width) + pos[0]] = pos[3];
pos[3] = _map[(((pos[1] + 1) * _width) + pos[0])];
_map[(((pos[1] + 1) * _width) + pos[0])] = sym;
pos[1]++;
return true;
}
// _posf[i][2] = dir = 3
bool Arcade::Pacman::moveLeftF(std::vector<size_t> &pos, char sym)
{
// Déplacement à gauche d'un fantom
pos[2] = 3;
if (_map[(((pos[1]) * _width) + pos[0] - 1)] == '=' ||
isNum(_map[(((pos[1]) * _width) + pos[0] - 1)])) {
pos[2] = 0;
return false;
}
_map[((pos[1]) * _width) + pos[0]] = pos[3];
pos[3] = _map[(((pos[1]) * _width) + pos[0] - 1)];
_map[(((pos[1]) * _width) + pos[0] - 1)] = sym;
pos[0]--;
return true;
}
// _posf[i][2] = dir = 4
bool Arcade::Pacman::moveRightF(std::vector<size_t> &pos, char sym)
{
// Déplacement à droite d'un fantom
pos[2] = 4;
if (_map[(((pos[1]) * _width) + pos[0] + 1)] == '=' ||
isNum(_map[(((pos[1]) * _width) + pos[0] + 1)])) {
pos[2] = 0;
return false;
}
_map[((pos[1]) * _width) + pos[0]] = pos[3];
pos[3] = _map[(((pos[1]) * _width) + pos[0] + 1)];
_map[(((pos[1]) * _width) + pos[0] + 1)] = sym;
pos[0]++;
return true;
}
bool Arcade::Pacman::moveFantom()
{
bool ret; // Valeur de retour
for (int i = 0; i != 4; i++) {
if (_posf[i][0] >= 12 && _posf[i][0] <= 14 &&
_posf[i][1] >= 12 && _posf[i][1] <= 14 &&
_time >= 10) { // Si les fantomes sont dans la room
ret = exitRoom(i);
} else { // Si les fantom ne sont pas dans leur room
if (_posf[i][2] != 0) { // Si ils n'ont pas de direction
if (findIntersection(i))
findDirection(i);
ret = dirFantom(i);
} else { // Si ils sont sortis !
findDirection(i);
ret = dirFantom(i);
}
}
}
return ret;
}
// count the number of intersection for the fantom
// if > 3 Fantom choose a new direction
bool Arcade::Pacman::findIntersection(int nb)
{
int count = 0;
if (_map[_posf[nb][0] + ((_posf[nb][1] - 1) * _width)] != '=')
count++;
if (_map[_posf[nb][0] + ((_posf[nb][1] + 1) * _width)] != '=')
count++;
if (_map[_posf[nb][0] + 1 + ((_posf[nb][1]) * _width)] != '=')
count++;
if (_map[_posf[nb][0] - 1 + ((_posf[nb][1]) * _width)] != '=')
count++;
if (count >= 3) {
_posf[nb][2] = 0;
return true;
}
return false;
}
void Arcade::Pacman::findDirection(int nb)
{
int dir; // Direction aléatoire
int count = 0; // Si trop grand saute le tour du Fantom afin de ne
// pas bloquer le jeu
// if : check si la case au dessus est libre ! dir = 1
// else if : check si la case au dessous est libre ! dir = 2
// else if : check si la case a gauche est libre ! dir = 3
// else if : check si la case a droite est libre ! dir = 4
// else : dir = 0
while (_posf[nb][2] == 0 && count < 1000) {
dir = rand() % 5;
if (dir == 1 &&
(_map[_posf[nb][0] + ((_posf[nb][1] - 1) * _width)] ==
'.' || _map[_posf[nb][0] +
((_posf[nb][1] - 1) * _width)] == ' ' ||
_map[_posf[nb][0] +
((_posf[nb][1] - 1) * _width)] == 'X' ||
_map[_posf[nb][0] +
((_posf[nb][1] - 1) * _width)] == 'o'))
_posf[nb][2] = 1;
else if (dir == 2 &&
(_map[_posf[nb][0] + ((_posf[nb][1] + 1) * _width)] ==
'.' || _map[_posf[nb][0] +
((_posf[nb][1] + 1) * _width)] == ' ' ||
_map[_posf[nb][0] +
((_posf[nb][1] + 1) * _width)] == 'X' ||
_map[_posf[nb][0] +
((_posf[nb][1] + 1) * _width)] == 'o'))
_posf[nb][2] = 2;
else if (dir == 3 &&
(_map[_posf[nb][0] - 1 + ((_posf[nb][1]) * _width)] ==
'.' || _map[_posf[nb][0] - 1 +
((_posf[nb][1]) * _width)] == ' ' ||
_map[_posf[nb][0] - 1 +
((_posf[nb][1]) * _width)] == 'X' ||
_map[_posf[nb][0] - 1 +
((_posf[nb][1]) * _width)] == 'o'))
_posf[nb][2] = 3;
else if ((dir == 4 &&
((_map[_posf[nb][0] + 1 + ((_posf[nb][1]) * _width)] ==
'.') || (_map[_posf[nb][0] + 1 +
((_posf[nb][1]) * _width)] == ' ') ||
(_map[_posf[nb][0] + 1 +
((_posf[nb][1]) * _width)] == 'X') ||
(_map[_posf[nb][0] + 1 +
((_posf[nb][1]) * _width)] == 'o'))))
_posf[nb][2] = 4;
else
_posf[nb][2] = 0;
count++;
}
}
bool Arcade::Pacman::dirFantom(int nb) // deplace le fantom dans sa direction
{
bool ret; // Valeur de retour
// Deplacement d'un Fantom
switch (_posf[nb][2]) {
case 1:
ret = moveUpF(_posf[nb], nb + 1 + 48);
break;
case 2:
ret = moveDownF(_posf[nb], nb + 1 + 48);
break;
case 3:
ret = moveLeftF(_posf[nb], nb + 1 + 48);
break;
case 4:
ret = moveRightF(_posf[nb], nb + 1 + 48);
break;
}
return ret;
}
bool Arcade::Pacman::exitRoom(int i)
{
// Déplace les fantom dans leur room afin qu'il sortent !
if (_posf[i][0] > 13 && _map[_width * _posf[i][1] + 13] == ' ') {
_map[_width * _posf[i][1] + 14] = _posf[i][3];
_posf[i][3] = _map[_width * _posf[i][1] + 13];
_map[_width * _posf[i][1] + 13] = i + 1 + 48;
_posf[i][0]--;
_posf[i][2] = 0;
return true;
} else if (_posf[i][0] < 13 && _map[_width * _posf[i][1] + 13] == ' ') {
_map[_width * _posf[i][1] + 12] = _posf[i][3];
_posf[i][3] = _map[_width * _posf[i][1] + 13];
_map[_width * _posf[i][1] + 13] = i + 1 + 48;
_posf[i][0]++;
_posf[i][2] = 0;
return true;
}
if (_posf[i][0] == 13 && _posf[i][1] <= 14 && _posf[i][1] >= 12 &&
(_map[_width * (_posf[i][1] - 1) + _posf[i][0]] == ' ' ||
_map[_width * (_posf[i][1] - 1) + _posf[i][0]] == '.' ||
_map[_width * (_posf[i][1] - 1) + _posf[i][0]] ==
'_')) {
_map[_width * (_posf[i][1]) + _posf[i][0]] = _posf[i][3];
_posf[i][3] = _map[_width * (_posf[i][1] - 1) + _posf[i][0]];
_map[_width * (_posf[i][1] - 1) + _posf[i][0]] = i + 1 + 48;
_posf[i][1]--;
_posf[i][2] = 0;
return true;
}
return false;
}
/*
** Other
*/
bool Arcade::Pacman::isNum(char num)
{
return num >= '1' && num <= '9';
}
void Arcade::Pacman::countFood()
{
// Compte le nombre de "pacgums" sur la map
for (size_t i = 0; i != _map.size(); i++) {
if (_map[i] == '.' || _map[i] == 'o')
_food++;
}
}
/*
** Getter
*/
size_t Arcade::Pacman::getScore()
{
// Retourne le score du joueur actuel
return _score;
}
int Arcade::Pacman::getDir()
{
// Retourne la direction de pacman
return _dir;
}
std::vector<size_t> &Arcade::Pacman::getPacmanPos()
{
// Retourne le vecteur de position de pacman
return _posp;
}
std::vector<std::vector<size_t>> Arcade::Pacman::getFantomPos()
{
// Retourne le vector contenant les vector des positions des fantomes
return _posf;
}
const std::string Arcade::Pacman::getName() const
{
return _name;
}
| 24.33672 | 79 | 0.565601 | [
"vector"
] |
9aaf8ab494e07d949dbc3801458ac1d0dbfe62d1 | 1,291 | cc | C++ | track/detail/test/GridFinder.test.cc | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | track/detail/test/GridFinder.test.cc | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | track/detail/test/GridFinder.test.cc | celeritas-project/orange-port | 9aa2d36984a24a02ed6d14688a889d4266f7b1af | [
"Apache-2.0",
"MIT"
] | null | null | null | //---------------------------------*-C++-*-----------------------------------//
/*!
* \file track/detail/test/tstGridFinder.cc
* \brief Tests for class GridFinder
* \note Copyright (c) 2021 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#include "../GridFinder.hh"
#include <vector>
#include "Nemesis/containers/Span.hh"
#include "celeritas_test.hh"
using make_span;
using celeritas::detail::GridFinder;
GridFinder<int>::result_type make_result(unsigned int cell, int edge)
{
CELER_EXPECT(edge >= -1 && edge <= 1);
return {cell, edge};
}
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
TEST(GridFinderTest, all)
{
std::vector<int> values = {1, 2, 4, 8, 16};
GridFinder<int> find{make_span(values)};
EXPECT_EQ(make_result(0, -1), find(-123));
EXPECT_EQ(make_result(0, -1), find(1));
EXPECT_EQ(make_result(1, -1), find(2));
EXPECT_EQ(make_result(1, 0), find(3));
EXPECT_EQ(make_result(2, -1), find(4));
EXPECT_EQ(make_result(3, 0), find(15));
EXPECT_EQ(make_result(3, 1), find(16));
EXPECT_EQ(make_result(3, 1), find(17));
}
| 30.738095 | 79 | 0.499613 | [
"vector"
] |
9ab9adaf1ad3b47a4809a31aab2c5d69fbb748ca | 12,586 | cpp | C++ | src/quantum.cpp | jiosue/Quantum-Computer-Simulator-with-Algorithms | 6724615ad1d5a64e0024ead856159e15f6f1caf6 | [
"MIT"
] | 15 | 2018-01-29T18:49:08.000Z | 2020-04-10T01:33:49.000Z | src/quantum.cpp | jtiosue/Quantum-Computer-Simulator-with-Algorithms | 6724615ad1d5a64e0024ead856159e15f6f1caf6 | [
"MIT"
] | null | null | null | src/quantum.cpp | jtiosue/Quantum-Computer-Simulator-with-Algorithms | 6724615ad1d5a64e0024ead856159e15f6f1caf6 | [
"MIT"
] | 2 | 2020-04-10T01:33:53.000Z | 2020-04-15T01:16:12.000Z | #include <cstdlib>
#include "quantum.h"
#include "rand.h"
#include "qalgorithms.h"
#include "methods.h"
#include <iostream>
// Register class
Register::Register(unsigned int num_qubits) {
/*
By default, initializes vaccum (|000...>) to amplitude
one and the rest zero. This can be adjust with logic
gates, of course, or explicitly with the function
set_nonzero_states.
*/
this->num_qubits = num_qubits;
states[string(num_qubits, '0')] = amp(1, 0); // total prob 1;
}
vec_states Register::all_states(unsigned int n) {
/*
returns vector of all the possible n qubit states
IN ORDER, where we choose the basis to be in increasing
order in terms of their binary representation.
i.e. 0..00 < 0..01 < 0..10 < 0..11 < 1..00 < 1..01 < 1..11
*/
vec_states v;
if (n == 1) {v.push_back("0"); v.push_back("1");}
else if(n > 1) {
for (string s : all_states(n - 1)) {
v.push_back(s + "0");
v.push_back(s + "1");
}
}
return v;
}
bool Register::check_state(string state) {
// See if state is in state map.
return states.count(state);
}
void Register::set_nonzero_states(state_map &s) {
amp total = 0.0;
for (state_map::iterator i = s.begin(); i != s.end(); ++i) {
states[i->first] = i->second; total += pow(abs(i->second), 2);
}
if (total == 0.0)
printf("Bad input: must have at least one state with nonzero amplitude\n");
else if (total == 1.0)
states = s;
else { // normalize input
states = s;
for (state_map::iterator i = states.begin(); i != states.end(); ++i)
states[i->first] = i->second / sqrt(total);
};
}
amp Register::amplitude(string state) {
// Note: not actually physically measureable.
if(check_state(state)) return states[state];
else return 0;
}
double Register::probability(string state) {
return pow(abs(amplitude(state)), 2);
}
string Register::measure() {
/*
Measure the system, and collapse it into a state.
Update the states map to have 1 probability of being
in this state, and return the state.
*/
// Will always return something because there is no way for the total
// probability to not equal 1.
double r = get_rand();
double total(0.0); string s;
for (state_map::iterator i = states.begin(); i != states.end(); ++i) {
s = i->first;
total += probability(s);
if (r <= total) { // collapse
// get rid of all other states which just take up memory with amp zero.
states = state_map();
states[s] = 1.0;
return s;
}
}
// WE SHOULD NEVER MAKE IT OUT HERE. If you use my functions, I make sure
// that the total probability is always 1, so we will never make it out here.
// But, if you adjusted the states manually with the operator[] funcionality
// that I included and you did something wrong, then we may make it out here.
// This is why I recommend you never use the reg[] functionality, but if you do,
// make sure you get the physics correct so that the total probability is always
// one and we never make it out here. In the event that we do, just pretend like
// we measured |000...>.
s = string(num_qubits, '0');
states = state_map();
states[s] = 1.0;
return s;
}
char Register::measure(unsigned int qubit) {
/*
Measure a qubit, and collapse it.
Update the states map to have 1 probability of having a particular
value for the qubit, and returns the value.
*/
// Will always return something because there is no way for the total
// probability to not equal 1.
double zero_prob = 0; string s;
for (state_map::iterator i = states.begin(); i != states.end(); ++i) {
s = i->first;
if(s[qubit] == '0') zero_prob += probability(s);
}
state_map m; char v; amp p;
if (get_rand() < zero_prob) {v = '0'; p = sqrt(zero_prob);}
else { v = '1'; p = sqrt(1 - zero_prob); }
// Resete state map to only states with the measured qubit.
for (state_map::iterator i = states.begin(); i != states.end(); ++i) {
s = i->first;
if (s[qubit] == v) m[s] = states[s] / p;
}
states = m;
return v;
}
void Register::print_states() {
// Show all nonzero states.
cout << *this;
}
std::ostream &operator<<(std::ostream &os, Register ®) {
// Show all nonzero states
for (state_map::iterator i = reg.states.begin(); i != reg.states.end(); ++i)
os << "|" << i->first << ">: amp-> "
<< (i->second).real() << " + " << (i->second).imag() << "i"
<< ", prob-> " << reg.probability(i->first) << "\n";
return os;
}
state_map Register::copy_map(state_map &s) {
state_map m;
for (state_map::iterator i = s.begin(); i != s.end(); ++i) { m[i->first] = i->second; }
return m;
}
vec_states Register::nonzero_states() {
/*
Returns all the keys in the states map; so only
states with nonzero amplitude.
This function is primarily here to be used with the function
below (operator[]). I HEAVILY RECOMMEND NOT USING THIS OR
THAT FUNCTION. See below for why.
*/
vec_states v;
for (state_map::iterator i = states.begin(); i != states.end(); ++i)
v.push_back(i->first);
return v;
}
amp & Register::operator[](string state) {
/*
Gives public access to the private states map. We return a reference,
so that one can change the states dictionary from outside the class.
THERE ARE NO CHECKS ON THIS FUNCTION. Anything you change, YOU must
make sure that it acts as a unitary transformation, otherwise probabilites
will fail, and then you can have issues with the measure function.
I HEAVILY RECOMMEND NOT USING THIS FUNCTIONALITY. I make the states
map private because you should really only be using quantum gates
(unitary transformations) to affect the register, and should not be
directly accessing the states. With that being said, I include this
function as a last option.
Use:
Register reg(4);
cout << reg["0000"] << endl;
reg["0000"] = 1 / sqrt(2);
reg["1000"] = 1 / sqrt(2);
cout << reg << endl;
*/
return states[state];
}
// Gates
void Register::apply_gate(Unitary u, vec_int qubits) {
/*
Applys the unitary matrix u to the given qubits in the system.
To get rid of unneccessary memory, if we come across a state with
amplitude zero, remove it from the states map.
Example:
if vec_int qubits = [0, 2], then expect u.dimension to be 4.
We apply the matrix u to the zeroth and second qubits in the
system. The matrix is represented in the basis
{|00>, |01>, |10>, |11>}
where the first number applies to the zeroth qubit and the
second number applies to the second qubit.
Example:
if vec_int qubits = [2, 4, 0], then we expect u.dimension to be 8.
We apply the matrix u to the second, fourth, and zeroth qubits in the
system. The matrix is represented in the basis
{|000>, |001>, |010>, |011>, |100>, |101>, |110>, |111>}
where the first number applies to the second qubit, the second
number applies the fourth qubit, and the third number applies
to the zeroth qubit.
All integers in vec_qubits should be different! I do not perform a check,
but instead assume that the user uses the gates correctly.
*/
if (u.dimension != (unsigned int)(1 << qubits.size())) { // 1 << qubits.size is pow(2, qubits.size())
printf("Unitary matrix dimension is not correct to be applied to the inputs qubits\n");
return;
}
string state, s; unsigned int r, j; state_map old = copy_map(states); amp c;
vec_states temp_states = all_states(qubits.size());
for (state_map::iterator i = old.begin(); i != old.end(); ++i) {
state = i->first; s = "";
for (unsigned int q : qubits) s += state[q];
r = binary_to_base10(s); // Find which number basis element s corresponds to.
states[state] -= (1.0 - u[r][r]) * old[state];
// if (states[state] == 0.0) states.erase(state); // Get rid of it.
if (probability(state) < 1e-16) states.erase(state); // zero beyond machine precision.
j = 0;
for(string k : temp_states) {
if (j != r) {
s = state;
for (unsigned int l = 0; l < k.size(); l++) s[qubits[l]] = k[l];
c = u[j][r] * old[state];
if (check_state(s)) {
states[s] += c;
// if (states[s] == 0.0) states.erase(s);
if (probability(s) < 1e-16) states.erase(s); // zero beyond machine precision.
} else if(c != 0.0) states[s] = c;
}
j++;
}
}
}
// Common gates listed below. Any gate you want to use that is not
// listed below can be implemented by just creating the unitary operator
// corresponding to the gate and calling the apply_gate function.
void Register::Hadamard(unsigned int qubit) {
/*
zero -> n-1 qubit indexing.
Hadamard operator on single qubit is
H = ((|0> + |1>) <0| + (|0> - |1>) <1|) / sqrt(2)
*/
vec_int v; v.push_back(qubit);
apply_gate(Unitary::Hadamard(), v);
}
void Register::PhaseShift(unsigned int qubit, double theta) {
/*
zero -> n-1 qubit indexing.
Phase shift by theta is
P = |1><0| + exp(i theta) |0><1|
*/
vec_int v; v.push_back(qubit);
apply_gate(Unitary::PhaseShift(theta), v);
}
void Register::PiOverEight(unsigned int qubit) {
// zero->n - 1 qubit indexing.
// PhaseShift(qubit, pi / 4.0);
vec_int v; v.push_back(qubit);
apply_gate(Unitary::PiOverEight(), v);
}
void Register::PauliX(unsigned int qubit) {
/*
zero->n - 1 qubit indexing.
Pauli-X gates, also the NOT gate, for a single qubit is
PX = |1><0| + |0><1|
*/
vec_int v; v.push_back(qubit);
apply_gate(Unitary::PauliX(), v);
}
void Register::PauliY(unsigned int qubit) {
/*
zero->n - 1 qubit indexing.
Pauli-Y gate for a single qubit is
PY = i(|1><0| - |0><1|)
*/
vec_int v; v.push_back(qubit);
apply_gate(Unitary::PauliY(), v);
}
void Register::PauliZ(unsigned int qubit) {
/*
zero->n - 1 qubit indexing.
Pauli-Z gate for a single qubit is
PZ = |1><0| - |0><1|
*/
// PhaseShift(qubit, pi);
vec_int v; v.push_back(qubit);
apply_gate(Unitary::PauliZ(), v);
}
void Register::ControlledNot(unsigned int control_qubit, unsigned int target_qubit) {
/*
zero -> num_qubits-1 qubit indexing.
ControlledNot gate is just the NOT gate (PauliX) on the target
qubit if the controlled qubit is 1. Otherwise, do nothing.
*/
vec_int v; v.push_back(control_qubit); v.push_back(target_qubit);
apply_gate(Unitary::ControlledNot(), v);
}
void Register::Toffoli(unsigned int control_qubit1, unsigned int control_qubit2, unsigned int target_qubit) {
/*
zero -> num_qubits-1 qubit indexing.
Toffoli gate, also known as the Controlled-Controlled-Not gate
is just the NOT gate (PauliX) on the target qubit if both the
controlled qubits are 1. Otherwise, do nothing.
*/
vec_int v; v.push_back(control_qubit1); v.push_back(control_qubit2); v.push_back(target_qubit);
apply_gate(Unitary::Toffoli(), v);
}
void Register::ControlledPhaseShift(unsigned int control_qubit, unsigned int target_qubit, double theta) {
/*
zero -> num_qubits-1 qubit indexing.
Just the phase shift gate on the target qubit if the first qubit is 1.
*/
vec_int v; v.push_back(control_qubit); v.push_back(target_qubit);
apply_gate(Unitary::ControlledPhaseShift(theta), v);
}
void Register::Swap(unsigned int qubit1, unsigned int qubit2) {
/*
zero -> num_qubits-1 qubit indexing.
Swap qubit1 and qubit2.
*/
// vec_int v; v.push_back(qubit1); v.push_back(qubit2);
// apply_gate(Unitary::Swap(), v);
ControlledNot(qubit1, qubit2);
ControlledNot(qubit2, qubit1);
ControlledNot(qubit1, qubit2);
}
void Register::Ising(unsigned int qubit1, unsigned int qubit2, double theta) {
vec_int v; v.push_back(qubit1); v.push_back(qubit2);
apply_gate(Unitary::Ising(theta), v);
}
// Sort of a gate
void Register::apply_function(function<string(string)> f) {
/*
Unitary transformation that sends
|x> to |f(x)>
This one is not technically a gate in the code, but in real life would be
a unitary transformation that could be implemented with a quantum circuit.
Note that in order for this to be unitary, f(x) must map each x to a unique
f(x). ie. f(x) cannot equal f(y) unless x = y. This is checked in this function.
*/
state_map old = copy_map(states); string state; states = state_map();
for (state_map::iterator i = old.begin(); i != old.end(); ++i) {
state = f(i->first);
if (check_state(state)) {
printf("The provided function does not constitute a unitary transformation.\n");
states = old; return; // reset.
}
states[state] = i->second;
}
}
| 32.025445 | 110 | 0.651994 | [
"vector"
] |
9ab9f8edcf331bc88ebe36f9083d5834d1cabc39 | 22,867 | cpp | C++ | MetroGame/MetroGame/Vision.cpp | Kevintjeb/OpenCV-MetroGame | e3a88108576853c2f9f5a5901074b2d4a547cd39 | [
"MIT"
] | null | null | null | MetroGame/MetroGame/Vision.cpp | Kevintjeb/OpenCV-MetroGame | e3a88108576853c2f9f5a5901074b2d4a547cd39 | [
"MIT"
] | null | null | null | MetroGame/MetroGame/Vision.cpp | Kevintjeb/OpenCV-MetroGame | e3a88108576853c2f9f5a5901074b2d4a547cd39 | [
"MIT"
] | null | null | null | #include "Vision.h"
#include "RenderableOutput.h"
using namespace mg_gameLogic;
bool debug = true;
int low_v = 30, low_s = 30, low_h = 30;
int high_v = 100, high_s = 100, high_h = 100;
int low_r = 30, low_g = 30, low_b = 30;
int high_r = 100, high_g = 100, high_b = 100;
void on_low_v_thresh_trackbar(int, void *);
void on_high_v_thresh_trackbar(int, void *);
void on_low_s_thresh_trackbar(int, void *);
void on_high_s_thresh_trackbar(int, void *);
void on_low_h_thresh_trackbar(int, void *);
void on_high_h_thresh_trackbar(int, void *);
void on_low_r_thresh_trackbar(int, void *);
void on_high_r_thresh_trackbar(int, void *);
void on_low_g_thresh_trackbar(int, void *);
void on_high_g_thresh_trackbar(int, void *);
void on_low_b_thresh_trackbar(int, void *);
void on_high_b_thresh_trackbar(int, void *);
Vision::Vision()
{
}
Vision::~Vision()
{
}
void Vision::start()
{
cap.open(1);
cap.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 720);
scanner;
scanner.set_config(zbar::ZBAR_NONE, zbar::ZBAR_CFG_ENABLE, 1);
}
void Vision::calibrate()
{
string value;
ifstream readFile("thresholds.txt");
if (readFile.is_open())
{
getline(readFile, value); redSettings.high_r = atoi(value.c_str()); getline(readFile, value); redSettings.high_g = atoi(value.c_str()); getline(readFile, value); redSettings.high_b = atoi(value.c_str()); getline(readFile, value); redSettings.high_h = atoi(value.c_str()); getline(readFile, value); redSettings.high_s = atoi(value.c_str()); getline(readFile, value); redSettings.high_v = atoi(value.c_str());
getline(readFile, value); redSettings.low_r = atoi(value.c_str()); getline(readFile, value); redSettings.low_g = atoi(value.c_str()); getline(readFile, value); redSettings.low_b = atoi(value.c_str()); getline(readFile, value); redSettings.low_h = atoi(value.c_str()); getline(readFile, value); redSettings.low_s = atoi(value.c_str()); getline(readFile, value); redSettings.low_v = atoi(value.c_str());
getline(readFile, value); greenSettings.high_r = atoi(value.c_str()); getline(readFile, value); greenSettings.high_g = atoi(value.c_str()); getline(readFile, value); greenSettings.high_b = atoi(value.c_str()); getline(readFile, value); greenSettings.high_h = atoi(value.c_str()); getline(readFile, value); greenSettings.high_s = atoi(value.c_str()); getline(readFile, value); greenSettings.high_v = atoi(value.c_str());
getline(readFile, value); greenSettings.low_r = atoi(value.c_str()); getline(readFile, value); greenSettings.low_g = atoi(value.c_str()); getline(readFile, value); greenSettings.low_b = atoi(value.c_str()); getline(readFile, value); greenSettings.low_h = atoi(value.c_str()); getline(readFile, value); greenSettings.low_s = atoi(value.c_str()); getline(readFile, value); greenSettings.low_v = atoi(value.c_str());
getline(readFile, value); blueSettings.high_r = atoi(value.c_str()); getline(readFile, value); blueSettings.high_g = atoi(value.c_str()); getline(readFile, value); blueSettings.high_b = atoi(value.c_str()); getline(readFile, value); blueSettings.high_h = atoi(value.c_str()); getline(readFile, value); blueSettings.high_s = atoi(value.c_str()); getline(readFile, value); blueSettings.high_v = atoi(value.c_str());
getline(readFile, value); blueSettings.low_r = atoi(value.c_str()); getline(readFile, value); blueSettings.low_g = atoi(value.c_str()); getline(readFile, value); blueSettings.low_b = atoi(value.c_str()); getline(readFile, value); blueSettings.low_h = atoi(value.c_str()); getline(readFile, value); blueSettings.low_s = atoi(value.c_str()); getline(readFile, value); blueSettings.low_v = atoi(value.c_str());
readFile.close();
}
namedWindow("Video Capture", WINDOW_NORMAL);
namedWindow("TrackBars", WINDOW_NORMAL);
namedWindow("RGB", WINDOW_NORMAL);
namedWindow("HSV", WINDOW_NORMAL);
namedWindow("Cut out", WINDOW_NORMAL);
namedWindow("Combined", WINDOW_NORMAL);
//-- Trackbars to set thresholds for RGB values
createTrackbar("Low Hue", "TrackBars", &low_h, 255, on_low_h_thresh_trackbar);
createTrackbar("High Hue", "TrackBars", &high_h, 255, on_high_h_thresh_trackbar);
createTrackbar("Low Saturation", "TrackBars", &low_s, 255, on_low_s_thresh_trackbar);
createTrackbar("High Saturation", "TrackBars", &high_s, 255, on_high_s_thresh_trackbar);
createTrackbar("Low Value", "TrackBars", &low_v, 255, on_low_v_thresh_trackbar);
createTrackbar("High Value", "TrackBars", &high_v, 255, on_high_v_thresh_trackbar);
createTrackbar("Low Red", "TrackBars", &low_r, 255, on_low_r_thresh_trackbar);
createTrackbar("High Red", "TrackBars", &high_r, 255, on_high_r_thresh_trackbar);
createTrackbar("Low Green", "TrackBars", &low_g, 255, on_low_g_thresh_trackbar);
createTrackbar("High Green", "TrackBars", &high_g, 255, on_high_g_thresh_trackbar);
createTrackbar("Low Blue", "TrackBars", &low_b, 255, on_low_b_thresh_trackbar);
createTrackbar("High Blue", "TrackBars", &high_b, 255, on_high_b_thresh_trackbar);
setTrackbarPos("Low Hue", "TrackBars", redSettings.low_h);
setTrackbarPos("High Hue", "TrackBars", redSettings.high_h);
setTrackbarPos("Low Saturation", "TrackBars", redSettings.low_s);
setTrackbarPos("High Saturation", "TrackBars", redSettings.high_s);
setTrackbarPos("Low Value", "TrackBars", redSettings.low_v);
setTrackbarPos("High Value", "TrackBars", redSettings.high_v);
setTrackbarPos("Low Red", "TrackBars", redSettings.low_r);
setTrackbarPos("High Red", "TrackBars", redSettings.high_r);
setTrackbarPos("Low Green", "TrackBars", redSettings.low_g);
setTrackbarPos("High Green", "TrackBars", redSettings.high_g);
setTrackbarPos("Low Blue", "TrackBars", redSettings.low_b);
setTrackbarPos("High Blue", "TrackBars", redSettings.high_b);
if (debug) //DEBUG ONLY
{
setTrackbarPos("Low Hue", "TrackBars", 150);
setTrackbarPos("High Hue", "TrackBars", 255);
setTrackbarPos("Low Saturation", "TrackBars", 72);
setTrackbarPos("High Saturation", "TrackBars", 255);
setTrackbarPos("Low Value", "TrackBars", 255);
setTrackbarPos("High Value", "TrackBars", 255);
setTrackbarPos("Low Red", "TrackBars", 232);
setTrackbarPos("High Red", "TrackBars", 255);
setTrackbarPos("Low Green", "TrackBars", 0);
setTrackbarPos("High Green", "TrackBars", 101);
setTrackbarPos("Low Blue", "TrackBars", 0);
setTrackbarPos("High Blue", "TrackBars", 142);
}
redSettings = colourCalibrate();
setTrackbarPos("Low Hue", "TrackBars", greenSettings.low_h);
setTrackbarPos("High Hue", "TrackBars", greenSettings.high_h);
setTrackbarPos("Low Saturation", "TrackBars", greenSettings.low_s);
setTrackbarPos("High Saturation", "TrackBars", greenSettings.high_s);
setTrackbarPos("Low Value", "TrackBars", greenSettings.low_v);
setTrackbarPos("High Value", "TrackBars", greenSettings.high_v);
setTrackbarPos("Low Red", "TrackBars", greenSettings.low_r);
setTrackbarPos("High Red", "TrackBars", greenSettings.high_r);
setTrackbarPos("Low Green", "TrackBars", greenSettings.low_g);
setTrackbarPos("High Green", "TrackBars", greenSettings.high_g);
setTrackbarPos("Low Blue", "TrackBars", greenSettings.low_b);
setTrackbarPos("High Blue", "TrackBars", greenSettings.high_b);
if (debug) //DEBUG ONLY
{
setTrackbarPos("Low Hue", "TrackBars", 0);
setTrackbarPos("High Hue", "TrackBars", 75);
setTrackbarPos("Low Saturation", "TrackBars", 200);
setTrackbarPos("High Saturation", "TrackBars", 255);
setTrackbarPos("Low Value", "TrackBars", 200);
setTrackbarPos("High Value", "TrackBars", 255);
setTrackbarPos("Low Red", "TrackBars", 70);
setTrackbarPos("High Red", "TrackBars", 155);
setTrackbarPos("Low Green", "TrackBars", 170);
setTrackbarPos("High Green", "TrackBars", 255);
setTrackbarPos("Low Blue", "TrackBars", 0);
setTrackbarPos("High Blue", "TrackBars", 255);
}
greenSettings = colourCalibrate();
setTrackbarPos("Low Hue", "TrackBars", blueSettings.low_h);
setTrackbarPos("High Hue", "TrackBars", blueSettings.high_h);
setTrackbarPos("Low Saturation", "TrackBars", blueSettings.low_s);
setTrackbarPos("High Saturation", "TrackBars", blueSettings.high_s);
setTrackbarPos("Low Value", "TrackBars", blueSettings.low_v);
setTrackbarPos("High Value", "TrackBars", blueSettings.high_v);
setTrackbarPos("Low Red", "TrackBars", blueSettings.low_r);
setTrackbarPos("High Red", "TrackBars", blueSettings.high_r);
setTrackbarPos("Low Green", "TrackBars", blueSettings.low_g);
setTrackbarPos("High Green", "TrackBars", blueSettings.high_g);
setTrackbarPos("Low Blue", "TrackBars", blueSettings.low_b);
setTrackbarPos("High Blue", "TrackBars", blueSettings.high_b);
if (debug) //DEBUG ONLY
{
setTrackbarPos("Low Hue", "TrackBars", 90);
setTrackbarPos("High Hue", "TrackBars", 150);
setTrackbarPos("Low Saturation", "TrackBars", 180);
setTrackbarPos("High Saturation", "TrackBars", 255);
setTrackbarPos("Low Value", "TrackBars", 255);
setTrackbarPos("High Value", "TrackBars", 255);
setTrackbarPos("Low Red", "TrackBars", 0);
setTrackbarPos("High Red", "TrackBars", 160);
setTrackbarPos("Low Green", "TrackBars", 0);
setTrackbarPos("High Green", "TrackBars", 120);
setTrackbarPos("Low Blue", "TrackBars", 180);
setTrackbarPos("High Blue", "TrackBars", 255);
}
blueSettings = colourCalibrate();
blueSettings = colourCalibrate();
cvDestroyWindow("Video Capture");
cvDestroyWindow("TrackBars");
cvDestroyWindow("RGB");
cvDestroyWindow("HSV");
cvDestroyWindow("Cut out");
cvDestroyWindow("Combined");
ofstream writeFile("thresholds.txt");
if (writeFile.is_open())
{
writeFile << redSettings.high_r << "\n"; writeFile << redSettings.high_g << "\n"; writeFile << redSettings.high_b << "\n"; writeFile << redSettings.high_h << "\n"; writeFile << redSettings.high_s << "\n"; writeFile << redSettings.high_v << "\n";
writeFile << redSettings.low_r << "\n"; writeFile << redSettings.low_g << "\n"; writeFile << redSettings.low_b << "\n"; writeFile << redSettings.low_h << "\n"; writeFile << redSettings.low_s << "\n"; writeFile << redSettings.low_v << "\n";
writeFile << greenSettings.high_r << "\n"; writeFile << greenSettings.high_g << "\n"; writeFile << greenSettings.high_b << "\n"; writeFile << greenSettings.high_h << "\n"; writeFile << greenSettings.high_s << "\n"; writeFile << greenSettings.high_v << "\n";
writeFile << greenSettings.low_r << "\n"; writeFile << greenSettings.low_g << "\n"; writeFile << greenSettings.low_b << "\n"; writeFile << greenSettings.low_h << "\n"; writeFile << greenSettings.low_s << "\n"; writeFile << greenSettings.low_v << "\n";
writeFile << blueSettings.high_r << "\n"; writeFile << blueSettings.high_g << "\n"; writeFile << blueSettings.high_b << "\n"; writeFile << blueSettings.high_h << "\n"; writeFile << blueSettings.high_s << "\n"; writeFile << blueSettings.high_v << "\n";
writeFile << blueSettings.low_r << "\n"; writeFile << blueSettings.low_g << "\n"; writeFile << blueSettings.low_b << "\n"; writeFile << blueSettings.low_h << "\n"; writeFile << blueSettings.low_s << "\n"; writeFile << blueSettings.low_v << "\n";
writeFile.close();
}
else cout << "Unable to open file";
}
Vision::ColourSettings Vision::colourCalibrate()
{
Mat frame, frame_threshold, frame_rgb;
while ((char)waitKey(1) != 'q') {
if (debug)
{
frame = imread("metro_test.png");
}
else
{
cap >> frame;
if (frame.empty())
break;
}
Mat mask;
Mat cutout;
mask = imread("mask.png");
frame.copyTo(cutout, mask);
imshow("Cut out", cutout);
cutout.copyTo(frame);
//-- Detect the object based on RGB Range Values
Mat hsv_image;
cvtColor(frame, hsv_image, CV_BGR2HSV);
inRange(hsv_image, Scalar(low_h, low_s, low_v), Scalar(high_h, high_s, high_v), frame_threshold);
inRange(frame, Scalar(low_b, low_g, low_r), Scalar(high_b, high_g, high_r), frame_rgb);
int dilation_size = 9;//7
int erosion_size = 7;//5
Mat element = getStructuringElement(MORPH_ELLIPSE,
Size(2 * dilation_size + 1, 2 * dilation_size + 1),
Point(dilation_size, dilation_size));
Mat element2 = getStructuringElement(MORPH_ELLIPSE,
Size(2 * erosion_size + 1, 2 * erosion_size + 1),
Point(erosion_size, erosion_size));
imshow("Video Capture", hsv_image);
dilate(frame_threshold, frame_threshold, element);
erode(frame_threshold, frame_threshold, element2);
dilate(frame_rgb, frame_rgb, element);
erode(frame_rgb, frame_rgb, element2);
//-- Show the frames
imshow("RGB", frame_rgb);
imshow("HSV", frame_threshold);
Mat combined;
combined = frame_rgb.mul(frame_threshold);
//addWeighted(frame_rgb, 1.0, frame_threshold, 1.0, 0.0, combined);
imshow("Combined", combined);
}
Vision::ColourSettings coloursettings;
coloursettings.high_r = high_r;
coloursettings.high_g = high_g;
coloursettings.high_b = high_b;
coloursettings.low_r = low_r;
coloursettings.low_g = low_g;
coloursettings.low_b = low_b;
coloursettings.high_h = high_h;
coloursettings.high_s = high_s;
coloursettings.high_v = high_v;
coloursettings.low_h = low_h;
coloursettings.low_s = low_s;
coloursettings.low_v = low_v;
return coloursettings;
}
std::list<GameLogic::Vec2f> Vision::getLines(int linecolour)
{
Mat image;
//image = imread("line.png");
//cap.open(1);
cap >> image;
if (image.empty())
cout << "GEEN IMAGE" << endl;
if (debug)
{
image = imread("metro_test.png");
}
Mat mask;
Mat cutout;
mask = imread("mask2.png");
image.copyTo(cutout, mask);
//imshow("Cut out", cutout);
cutout.copyTo(image);
// De afbeelding converteren naar een grijswaarde afbeelding
Mat hsv_image;
cvtColor(image, hsv_image, CV_BGR2HSV);
//imshow("LINE_HSV Image", hsv_image);
//namedWindow("HSV image", WINDOW_AUTOSIZE);
//imshow("HSV image", hsv_image);
// Seperate Colors with inRange
/*cv::Mat lower_red_hue_range;
cv::Mat upper_red_hue_range;*/
//cv::inRange(hsv_image, cv::Scalar(0, 10, 100), cv::Scalar(10, 255, 255), lower_red_hue_range); // 0 10
//cv::inRange(hsv_image, cv::Scalar(160, 10, 100), cv::Scalar(179, 255, 255), upper_red_hue_range); // 160 179
// Combine the above two images
//HSV
cv::Mat red_hue_image;
//cv::addWeighted(lower_red_hue_range, 1.0, upper_red_hue_range, 1.0, 0.0, red_hue_image);
cv::inRange(hsv_image, cv::Scalar(redSettings.low_h, redSettings.low_s, redSettings.low_v), cv::Scalar(redSettings.high_h, redSettings.high_s, redSettings.high_v), red_hue_image);
cv::Mat blue_hue_image;
cv::inRange(hsv_image, cv::Scalar(blueSettings.low_h, blueSettings.low_s, blueSettings.low_v), cv::Scalar(blueSettings.high_h, blueSettings.high_s, blueSettings.high_v), blue_hue_image);
cv::Mat green_hue_image;
cv::inRange(hsv_image, cv::Scalar(greenSettings.low_h, greenSettings.low_s, greenSettings.low_v), cv::Scalar(greenSettings.high_h, greenSettings.high_s, greenSettings.high_v), green_hue_image);
//RGB
cv::Mat red_rgb_image;
cv::inRange(image, cv::Scalar(redSettings.low_b, redSettings.low_g, redSettings.low_r), cv::Scalar(redSettings.high_b, redSettings.high_g, redSettings.high_r), red_rgb_image);
cv::Mat blue_rgb_image;
cv::inRange(image, cv::Scalar(blueSettings.low_b, blueSettings.low_g, blueSettings.low_r), cv::Scalar(blueSettings.high_b, blueSettings.high_g, blueSettings.high_r), blue_rgb_image);
cv::Mat green_rgb_image;
cv::inRange(image, cv::Scalar(greenSettings.low_b, greenSettings.low_g, greenSettings.low_r), cv::Scalar(greenSettings.high_b, greenSettings.high_g, greenSettings.high_r), green_rgb_image);
int dilation_size = 9;//7
int erosion_size = 7;//5
Mat element = getStructuringElement(MORPH_ELLIPSE,
Size(2 * dilation_size + 1, 2 * dilation_size + 1),
Point(dilation_size, dilation_size));
Mat element2 = getStructuringElement(MORPH_ELLIPSE,
Size(2 * erosion_size + 1, 2 * erosion_size + 1),
Point(erosion_size, erosion_size));
dilate(red_hue_image, red_hue_image, element);
erode(red_hue_image, red_hue_image, element2);
dilate(red_rgb_image, red_rgb_image, element);
erode(red_rgb_image, red_rgb_image, element2);
dilate(blue_hue_image, blue_hue_image, element);
erode(blue_hue_image, blue_hue_image, element2);
dilate(blue_rgb_image, blue_rgb_image, element);
erode(blue_rgb_image, blue_rgb_image, element2);
dilate(green_hue_image, green_hue_image, element);
erode(green_hue_image, green_hue_image, element2);
dilate(green_rgb_image, green_rgb_image, element);
erode(green_rgb_image, green_rgb_image, element2);
Mat combined_red, combined_green, combined_blue;
combined_red = red_rgb_image.mul(red_hue_image);
combined_green = green_rgb_image.mul(green_hue_image);
combined_blue = blue_rgb_image.mul(blue_hue_image);
namedWindow("Combined Blue", WINDOW_AUTOSIZE);
imshow("LINE_Combined Blue", combined_red);
//imshow("LINE_HSV Blue", blue_hue_image);
//imshow("LINE_RGB Blue", blue_rgb_image);
//Threshold to get Binary image
Mat binaryImage_red;
threshold(combined_red, binaryImage_red, 254, 1, CV_THRESH_BINARY);
Mat binaryImage_green;
threshold(combined_green, binaryImage_green, 254, 1, CV_THRESH_BINARY);
Mat binaryImage_blue;
threshold(combined_blue, binaryImage_blue, 254, 1, CV_THRESH_BINARY);
// Convert to 16 binary
Mat binary16S_red;
binaryImage_red.convertTo(binary16S_red, CV_16S);
Mat binary16S_green;
binaryImage_green.convertTo(binary16S_green, CV_16S);
Mat binary16S_blue;
binaryImage_blue.convertTo(binary16S_blue, CV_16S);
//Label all the blobs
Mat labeledImageRed, labeledImageGreen, labeledImageBlue;
vector<vector<Point2d *>> coords;
int blobs;
switch (linecolour)
{
case LINE_RED:
blobs = labelBLOBs(binary16S_red, labeledImageRed, coords);
cout << "N:" << blobs << " Red" << endl;
break;
case LINE_GREEN:
blobs = labelBLOBs(binary16S_green, labeledImageGreen, coords);
cout << "N:" << blobs << " Green" << endl;
break;
case LINE_BLUE:
blobs = labelBLOBs(binary16S_blue, labeledImageBlue, coords);
cout << "N:" << blobs << " Blue" << endl;
break;
default:
break;
}
//imshow("Blue blob", labeledImageBlue * 254);
std::list<GameLogic::Vec2f> lines;
std::vector<GameLogic::Vec2f> test;
if (coords.size() > 0)
{
for (int j = 0; j < coords.size() - 1; j++)
{
for (int i = 0; i < coords[j].size(); i++)
{
GameLogic::Vec2f vector = GameLogic::Vec2f((((coords[j][i]->x - 260) / ((image.cols - 500) / 2.0f)) - 1.0f), ((coords[j][i]->y - 60) / ((image.rows - 180) / 2.0f)) - 1.0f);
lines.push_back(vector);
}
}
}
//test.push_back(GameLogic::Vec2f(-1.0f, -1.0f));
//test.push_back(GameLogic::Vec2f(1.0f, 1.0f));
RenderableLine pLine;
switch (linecolour)
{
case LINE_RED:
pLine = RenderableLine(test, LineType::Red);
break;
case LINE_GREEN:
pLine = RenderableLine(test, LineType::Green);
break;
case LINE_BLUE:
pLine = RenderableLine(test, LineType::Blue);
break;
default:
break;
}
allocate_line(pLine);
Mat redLines, greenLines, blueLines;
//switch (linecolour)
//{
//case LINE_RED:
// redLines = image.clone();
// for (int i = 0; i < coords.size(); i++)
// {
// for (int y = 1; y < coords[i].size(); y++)
// {
// line(redLines, *coords[i][y - 1], *coords[i][y], Scalar(150, 20, 20), 3, CV_AA);
// }
// }
// namedWindow("RedLines", WINDOW_AUTOSIZE);
// imshow("RedLines", redLines);
// break;
//case LINE_GREEN:
// greenLines = image.clone();
// for (int i = 0; i < coords.size(); i++)
// {
// for (int y = 1; y < coords[i].size(); y++)
// {
// line(greenLines, *coords[i][y - 1], *coords[i][y], Scalar(150, 20, 20), 3, CV_AA);
// }
// }
// namedWindow("GreenLines", WINDOW_AUTOSIZE);
// imshow("GreenLines", greenLines);
// break;
//case LINE_BLUE:
// blueLines = image.clone();
// for (int i = 0; i < coords.size(); i++)
// {
// for (int y = 1; y < coords[i].size(); y++)
// {
// line(blueLines, *coords[i][y - 1], *coords[i][y], Scalar(150, 20, 20), 3, CV_AA);
// }
// }
// namedWindow("BlueLines", WINDOW_AUTOSIZE);
// imshow("BlueLines", blueLines);
// break;
//default:
// break;
//}
return lines;
}
std::list<Vision::CV_Station> Vision::getStations()
{
Mat frame;
cap >> frame;
if (debug)
{
frame = imread("metro_test.png");
}
Mat grey;
cvtColor(frame, grey, CV_BGR2GRAY);
int width = frame.cols;
int height = frame.rows;
uchar *raw = (uchar *)grey.data;
std::list<Vision::CV_Station> qr_stations;
zbar::Image image(width, height, "Y800", raw, width * height);
int n = scanner.scan(image);
for (zbar::Image::SymbolIterator symbol = image.symbol_begin(); symbol != image.symbol_end(); ++symbol)
{
vector<Point> vp;
Vision::CV_Station station;
station.location = Vec2f(symbol->get_location_x(0), symbol->get_location_y(0));
station.id = std::stoi(symbol->get_data());
qr_stations.push_back(station);
cout << "decoded " << symbol->get_type_name() << " symbol \"" << symbol->get_data() << '"' << " " << "x:" << symbol->get_location_x(0) << " y:" << symbol->get_location_y(0) << endl;
int n = symbol->get_location_size();
for (int i = 0; i<n; i++) {
vp.push_back(Point(symbol->get_location_x(i), symbol->get_location_y(i)));
}
RotatedRect r = minAreaRect(vp);
Point2f pts[4];
r.points(pts);
for (int i = 0; i<4; i++) {
line(frame, pts[i], pts[(i + 1) % 4], Scalar(255, 0, 0), 3);
}
//cout<<"Angle: "<<r.angle<<endl;
}
imshow("MyVideo", frame);
return qr_stations;
}
void on_low_v_thresh_trackbar(int, void *)
{
low_v = min(high_v - 1, low_v);
setTrackbarPos("Low Value", "Object Detection", low_v);
}
void on_high_v_thresh_trackbar(int, void *)
{
high_v = max(high_v, low_v + 1);
setTrackbarPos("High Value", "Object Detection", high_v);
}
void on_low_s_thresh_trackbar(int, void *)
{
low_s = min(high_s - 1, low_s);
setTrackbarPos("Low Saturation", "Object Detection", low_s);
}
void on_high_s_thresh_trackbar(int, void *)
{
high_s = max(high_s, low_s + 1);
setTrackbarPos("High Saturation", "Object Detection", high_s);
}
void on_low_h_thresh_trackbar(int, void *)
{
low_h = min(high_h - 1, low_h);
setTrackbarPos("Low Hue", "Object Detection", low_h);
}
void on_high_h_thresh_trackbar(int, void *)
{
high_h = max(high_h, low_h + 1);
setTrackbarPos("High Hue", "Object Detection", high_h);
}
void on_low_r_thresh_trackbar(int, void *)
{
low_r = min(high_r - 1, low_r);
setTrackbarPos("Low R", "RGB", low_r);
}
void on_high_r_thresh_trackbar(int, void *)
{
high_r = max(high_r, low_r + 1);
setTrackbarPos("High R", "RGB", high_r);
}
void on_low_g_thresh_trackbar(int, void *)
{
low_g = min(high_g - 1, low_g);
setTrackbarPos("Low G", "RGB", low_g);
}
void on_high_g_thresh_trackbar(int, void *)
{
high_g = max(high_g, low_g + 1);
setTrackbarPos("High G", "RGB", high_g);
}
void on_low_b_thresh_trackbar(int, void *)
{
low_b = min(high_b - 1, low_b);
setTrackbarPos("Low B", "RGB", low_b);
}
void on_high_b_thresh_trackbar(int, void *)
{
high_b = max(high_b, low_b + 1);
setTrackbarPos("High B", "RGB", high_b);
}
| 38.889456 | 421 | 0.710893 | [
"object",
"vector"
] |
9abadb93cfe1397558bb127b0b1ced5aab2d4e35 | 55,707 | cpp | C++ | wznmcmbd/VecWznm/VecWznmVCall.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | wznmcmbd/VecWznm/VecWznmVCall.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | wznmcmbd/VecWznm/VecWznmVCall.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file VecWznmVCall.cpp
* vector VecWznmVCall (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
#include "VecWznmVCall.h"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
namespace VecWznmVCall
******************************************************************************/
uint VecWznmVCall::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "callwznmapp.vereq") return CALLWZNMAPP_VEREQ;
if (s == "callwznmappmod") return CALLWZNMAPPMOD;
if (s == "callwznmappmod.vereq") return CALLWZNMAPPMOD_VEREQ;
if (s == "callwznmappupd.refeq") return CALLWZNMAPPUPD_REFEQ;
if (s == "callwznmbitjmod.blkaitmeq") return CALLWZNMBITJMOD_BLKAITMEQ;
if (s == "callwznmblk.reteq") return CALLWZNMBLK_RETEQ;
if (s == "callwznmblk.reueq") return CALLWZNMBLK_REUEQ;
if (s == "callwznmblk.vereq") return CALLWZNMBLK_VEREQ;
if (s == "callwznmblkaitmmod.blkeq") return CALLWZNMBLKAITMMOD_BLKEQ;
if (s == "callwznmblkaitmmod.clueq") return CALLWZNMBLKAITMMOD_CLUEQ;
if (s == "callwznmblkmod") return CALLWZNMBLKMOD;
if (s == "callwznmblkmod.retreueq") return CALLWZNMBLKMOD_RETREUEQ;
if (s == "callwznmblkmod.vereq") return CALLWZNMBLKMOD_VEREQ;
if (s == "callwznmblkupd.refeq") return CALLWZNMBLKUPD_REFEQ;
if (s == "callwznmboolvalpreset") return CALLWZNMBOOLVALPRESET;
if (s == "callwznmcal.reteq") return CALLWZNMCAL_RETEQ;
if (s == "callwznmcal.reueq") return CALLWZNMCAL_REUEQ;
if (s == "callwznmcal.typeq") return CALLWZNMCAL_TYPEQ;
if (s == "callwznmcal.vereq") return CALLWZNMCAL_VEREQ;
if (s == "callwznmcalmod") return CALLWZNMCALMOD;
if (s == "callwznmcalmod.retreueq") return CALLWZNMCALMOD_RETREUEQ;
if (s == "callwznmcalmod.vereq") return CALLWZNMCALMOD_VEREQ;
if (s == "callwznmcalrstbmod.caleq") return CALLWZNMCALRSTBMOD_CALEQ;
if (s == "callwznmcalrstbmod.stbeq") return CALLWZNMCALRSTBMOD_STBEQ;
if (s == "callwznmcalupd.refeq") return CALLWZNMCALUPD_REFEQ;
if (s == "callwznmcar.jobeq") return CALLWZNMCAR_JOBEQ;
if (s == "callwznmcar.mdleq") return CALLWZNMCAR_MDLEQ;
if (s == "callwznmcar.reteq") return CALLWZNMCAR_RETEQ;
if (s == "callwznmcar.reueq") return CALLWZNMCAR_REUEQ;
if (s == "callwznmcarjtitmod.careq") return CALLWZNMCARJTITMOD_CAREQ;
if (s == "callwznmcarmod") return CALLWZNMCARMOD;
if (s == "callwznmcarmod.mdleq") return CALLWZNMCARMOD_MDLEQ;
if (s == "callwznmcarmod.retreueq") return CALLWZNMCARMOD_RETREUEQ;
if (s == "callwznmcarupd.refeq") return CALLWZNMCARUPD_REFEQ;
if (s == "callwznmchk.caleq") return CALLWZNMCHK_CALEQ;
if (s == "callwznmchk.tcoeq") return CALLWZNMCHK_TCOEQ;
if (s == "callwznmchkmod") return CALLWZNMCHKMOD;
if (s == "callwznmchkmod.tbleq") return CALLWZNMCHKMOD_TBLEQ;
if (s == "callwznmchkupd.refeq") return CALLWZNMCHKUPD_REFEQ;
if (s == "callwznmclaimchg") return CALLWZNMCLAIMCHG;
if (s == "callwznmcmp.insbs") return CALLWZNMCMP_INSBS;
if (s == "callwznmcmp.typeq") return CALLWZNMCMP_TYPEQ;
if (s == "callwznmcmp.vereq") return CALLWZNMCMP_VEREQ;
if (s == "callwznmcmpmod") return CALLWZNMCMPMOD;
if (s == "callwznmcmpmod.vereq") return CALLWZNMCMPMOD_VEREQ;
if (s == "callwznmcmprlibmod.cmpeq") return CALLWZNMCMPRLIBMOD_CMPEQ;
if (s == "callwznmcmprlibmod.libeq") return CALLWZNMCMPRLIBMOD_LIBEQ;
if (s == "callwznmcmpropkmod.cmpeq") return CALLWZNMCMPROPKMOD_CMPEQ;
if (s == "callwznmcmpropkmod.opkeq") return CALLWZNMCMPROPKMOD_OPKEQ;
if (s == "callwznmcmpupd.refeq") return CALLWZNMCMPUPD_REFEQ;
if (s == "callwznmcon.clueq") return CALLWZNMCON_CLUEQ;
if (s == "callwznmcon.fedeq") return CALLWZNMCON_FEDEQ;
if (s == "callwznmcon.hkteq") return CALLWZNMCON_HKTEQ;
if (s == "callwznmcon.hkueq") return CALLWZNMCON_HKUEQ;
if (s == "callwznmcon.insbs") return CALLWZNMCON_INSBS;
if (s == "callwznmcon.reteq") return CALLWZNMCON_RETEQ;
if (s == "callwznmcon.reueq") return CALLWZNMCON_REUEQ;
if (s == "callwznmcon.shseq") return CALLWZNMCON_SHSEQ;
if (s == "callwznmcon.stseq") return CALLWZNMCON_STSEQ;
if (s == "callwznmcon.supeq") return CALLWZNMCON_SUPEQ;
if (s == "callwznmcon.typeq") return CALLWZNMCON_TYPEQ;
if (s == "callwznmconaparmod.coneq") return CALLWZNMCONAPARMOD_CONEQ;
if (s == "callwznmconaparmod.loceq") return CALLWZNMCONAPARMOD_LOCEQ;
if (s == "callwznmconjmod.coneq") return CALLWZNMCONJMOD_CONEQ;
if (s == "callwznmconjtitmod.coneq") return CALLWZNMCONJTITMOD_CONEQ;
if (s == "callwznmconmod") return CALLWZNMCONMOD;
if (s == "callwznmconmod.clueq") return CALLWZNMCONMOD_CLUEQ;
if (s == "callwznmconmod.hkthkueq") return CALLWZNMCONMOD_HKTHKUEQ;
if (s == "callwznmconmod.retreueq") return CALLWZNMCONMOD_RETREUEQ;
if (s == "callwznmconmod.supeq") return CALLWZNMCONMOD_SUPEQ;
if (s == "callwznmconupd.refeq") return CALLWZNMCONUPD_REFEQ;
if (s == "callwznmcpb.insbs") return CALLWZNMCPB_INSBS;
if (s == "callwznmcpb.tpleq") return CALLWZNMCPB_TPLEQ;
if (s == "callwznmcpb.vereq") return CALLWZNMCPB_VEREQ;
if (s == "callwznmcpbaparmod.cpbeq") return CALLWZNMCPBAPARMOD_CPBEQ;
if (s == "callwznmcpbmod") return CALLWZNMCPBMOD;
if (s == "callwznmcpbmod.tpleq") return CALLWZNMCPBMOD_TPLEQ;
if (s == "callwznmcpbmod.vereq") return CALLWZNMCPBMOD_VEREQ;
if (s == "callwznmcpbupd.refeq") return CALLWZNMCPBUPD_REFEQ;
if (s == "callwznmcrdactive") return CALLWZNMCRDACTIVE;
if (s == "callwznmcrdclose") return CALLWZNMCRDCLOSE;
if (s == "callwznmcrdopen") return CALLWZNMCRDOPEN;
if (s == "callwznmctlaparmod.usreq") return CALLWZNMCTLAPARMOD_USREQ;
if (s == "callwznmdatchg") return CALLWZNMDATCHG;
if (s == "callwznmdblvalpreset") return CALLWZNMDBLVALPRESET;
if (s == "callwznmdlg.careq") return CALLWZNMDLG_CAREQ;
if (s == "callwznmdlg.jobeq") return CALLWZNMDLG_JOBEQ;
if (s == "callwznmdlg.reteq") return CALLWZNMDLG_RETEQ;
if (s == "callwznmdlg.reueq") return CALLWZNMDLG_REUEQ;
if (s == "callwznmdlgclose") return CALLWZNMDLGCLOSE;
if (s == "callwznmdlgmod") return CALLWZNMDLGMOD;
if (s == "callwznmdlgmod.careq") return CALLWZNMDLGMOD_CAREQ;
if (s == "callwznmdlgmod.retreueq") return CALLWZNMDLGMOD_RETREUEQ;
if (s == "callwznmdlgrqrymod.dlgeq") return CALLWZNMDLGRQRYMOD_DLGEQ;
if (s == "callwznmdlgrqrymod.qryeq") return CALLWZNMDLGRQRYMOD_QRYEQ;
if (s == "callwznmdlgupd.refeq") return CALLWZNMDLGUPD_REFEQ;
if (s == "callwznmerr.vereq") return CALLWZNMERR_VEREQ;
if (s == "callwznmerrjtitmod.erreq") return CALLWZNMERRJTITMOD_ERREQ;
if (s == "callwznmerrmod") return CALLWZNMERRMOD;
if (s == "callwznmerrmod.vereq") return CALLWZNMERRMOD_VEREQ;
if (s == "callwznmerrupd.refeq") return CALLWZNMERRUPD_REFEQ;
if (s == "callwznmevt.appeq") return CALLWZNMEVT_APPEQ;
if (s == "callwznmevtmod") return CALLWZNMEVTMOD;
if (s == "callwznmevtmod.appeq") return CALLWZNMEVTMOD_APPEQ;
if (s == "callwznmevtupd.refeq") return CALLWZNMEVTUPD_REFEQ;
if (s == "callwznmfed.srteq") return CALLWZNMFED_SRTEQ;
if (s == "callwznmfed.srueq") return CALLWZNMFED_SRUEQ;
if (s == "callwznmfedmod") return CALLWZNMFEDMOD;
if (s == "callwznmfedmod.srtsrueq") return CALLWZNMFEDMOD_SRTSRUEQ;
if (s == "callwznmfedupd.refeq") return CALLWZNMFEDUPD_REFEQ;
if (s == "callwznmfil.clueq") return CALLWZNMFIL_CLUEQ;
if (s == "callwznmfil.reteq") return CALLWZNMFIL_RETEQ;
if (s == "callwznmfil.reueq") return CALLWZNMFIL_REUEQ;
if (s == "callwznmfilmod") return CALLWZNMFILMOD;
if (s == "callwznmfilmod.clueq") return CALLWZNMFILMOD_CLUEQ;
if (s == "callwznmfilmod.retreueq") return CALLWZNMFILMOD_RETREUEQ;
if (s == "callwznmfilupd.refeq") return CALLWZNMFILUPD_REFEQ;
if (s == "callwznmhusrrunvmod.crdusreq") return CALLWZNMHUSRRUNVMOD_CRDUSREQ;
if (s == "callwznmiel.im2eq") return CALLWZNMIEL_IM2EQ;
if (s == "callwznmiel.imeeq") return CALLWZNMIEL_IMEEQ;
if (s == "callwznmiel.psteq") return CALLWZNMIEL_PSTEQ;
if (s == "callwznmiel.stbeq") return CALLWZNMIEL_STBEQ;
if (s == "callwznmiel.viteq") return CALLWZNMIEL_VITEQ;
if (s == "callwznmieljstbmod.ieleq") return CALLWZNMIELJSTBMOD_IELEQ;
if (s == "callwznmielmod") return CALLWZNMIELMOD;
if (s == "callwznmielmod.imeeq") return CALLWZNMIELMOD_IMEEQ;
if (s == "callwznmielmod.tcoeq") return CALLWZNMIELMOD_TCOEQ;
if (s == "callwznmielupd.refeq") return CALLWZNMIELUPD_REFEQ;
if (s == "callwznmiex.jobeq") return CALLWZNMIEX_JOBEQ;
if (s == "callwznmiex.vereq") return CALLWZNMIEX_VEREQ;
if (s == "callwznmiexjtitmod.iexeq") return CALLWZNMIEXJTITMOD_IEXEQ;
if (s == "callwznmiexmod") return CALLWZNMIEXMOD;
if (s == "callwznmiexmod.vereq") return CALLWZNMIEXMOD_VEREQ;
if (s == "callwznmiexupd.refeq") return CALLWZNMIEXUPD_REFEQ;
if (s == "callwznmime.iexeq") return CALLWZNMIME_IEXEQ;
if (s == "callwznmime.supeq") return CALLWZNMIME_SUPEQ;
if (s == "callwznmimemod") return CALLWZNMIMEMOD;
if (s == "callwznmimemod.iexeq") return CALLWZNMIMEMOD_IEXEQ;
if (s == "callwznmimemod.supeq") return CALLWZNMIMEMOD_SUPEQ;
if (s == "callwznmimemod.tbleq") return CALLWZNMIMEMOD_TBLEQ;
if (s == "callwznmimeupd.refeq") return CALLWZNMIMEUPD_REFEQ;
if (s == "callwznmintvalpreset") return CALLWZNMINTVALPRESET;
if (s == "callwznmixpreset") return CALLWZNMIXPRESET;
if (s == "callwznmjob.reteq") return CALLWZNMJOB_RETEQ;
if (s == "callwznmjob.reueq") return CALLWZNMJOB_REUEQ;
if (s == "callwznmjob.typeq") return CALLWZNMJOB_TYPEQ;
if (s == "callwznmjob.vereq") return CALLWZNMJOB_VEREQ;
if (s == "callwznmjobacmdmod.jobeq") return CALLWZNMJOBACMDMOD_JOBEQ;
if (s == "callwznmjobavarmod.clueq") return CALLWZNMJOBAVARMOD_CLUEQ;
if (s == "callwznmjobavarmod.jobeq") return CALLWZNMJOBAVARMOD_JOBEQ;
if (s == "callwznmjobmod") return CALLWZNMJOBMOD;
if (s == "callwznmjobmod.retreueq") return CALLWZNMJOBMOD_RETREUEQ;
if (s == "callwznmjobmod.vereq") return CALLWZNMJOBMOD_VEREQ;
if (s == "callwznmjobrjobmod.subeq") return CALLWZNMJOBRJOBMOD_SUBEQ;
if (s == "callwznmjobrjobmod.supeq") return CALLWZNMJOBRJOBMOD_SUPEQ;
if (s == "callwznmjobropkmod.jobeq") return CALLWZNMJOBROPKMOD_JOBEQ;
if (s == "callwznmjobropkmod.opkeq") return CALLWZNMJOBROPKMOD_OPKEQ;
if (s == "callwznmjobropxmod.jobeq") return CALLWZNMJOBROPXMOD_JOBEQ;
if (s == "callwznmjobropxmod.opxeq") return CALLWZNMJOBROPXMOD_OPXEQ;
if (s == "callwznmjobupd.refeq") return CALLWZNMJOBUPD_REFEQ;
if (s == "callwznmklkjkeymod.klsakeyeq") return CALLWZNMKLKJKEYMOD_KLSAKEYEQ;
if (s == "callwznmklsakeymod.klseq") return CALLWZNMKLSAKEYMOD_KLSEQ;
if (s == "callwznmklsakeymod.klsmtburfeq") return CALLWZNMKLSAKEYMOD_KLSMTBURFEQ;
if (s == "callwznmlibamkfmod.libeq") return CALLWZNMLIBAMKFMOD_LIBEQ;
if (s == "callwznmlibamkfmod.mcheq") return CALLWZNMLIBAMKFMOD_MCHEQ;
if (s == "callwznmlibapklmod.libeq") return CALLWZNMLIBAPKLMOD_LIBEQ;
if (s == "callwznmlibapklmod.mcheq") return CALLWZNMLIBAPKLMOD_MCHEQ;
if (s == "callwznmlibmod") return CALLWZNMLIBMOD;
if (s == "callwznmlibropkmod.libeq") return CALLWZNMLIBROPKMOD_LIBEQ;
if (s == "callwznmlibropkmod.opkeq") return CALLWZNMLIBROPKMOD_OPKEQ;
if (s == "callwznmlibupd.refeq") return CALLWZNMLIBUPD_REFEQ;
if (s == "callwznmlocjtitmod.loceq") return CALLWZNMLOCJTITMOD_LOCEQ;
if (s == "callwznmlocmod") return CALLWZNMLOCMOD;
if (s == "callwznmlocrvermod.loceq") return CALLWZNMLOCRVERMOD_LOCEQ;
if (s == "callwznmlocrvermod.vereq") return CALLWZNMLOCRVERMOD_VEREQ;
if (s == "callwznmlocupd.refeq") return CALLWZNMLOCUPD_REFEQ;
if (s == "callwznmlog") return CALLWZNMLOG;
if (s == "callwznmlogout") return CALLWZNMLOGOUT;
if (s == "callwznmmch.ccheq") return CALLWZNMMCH_CCHEQ;
if (s == "callwznmmch.supeq") return CALLWZNMMCH_SUPEQ;
if (s == "callwznmmchamkfmod.mcheq") return CALLWZNMMCHAMKFMOD_MCHEQ;
if (s == "callwznmmchaparmod.mcheq") return CALLWZNMMCHAPARMOD_MCHEQ;
if (s == "callwznmmchmod") return CALLWZNMMCHMOD;
if (s == "callwznmmchmod.supeq") return CALLWZNMMCHMOD_SUPEQ;
if (s == "callwznmmchupd.refeq") return CALLWZNMMCHUPD_REFEQ;
if (s == "callwznmmdl.vereq") return CALLWZNMMDL_VEREQ;
if (s == "callwznmmdljmod.mdleq") return CALLWZNMMDLJMOD_MDLEQ;
if (s == "callwznmmdlmod") return CALLWZNMMDLMOD;
if (s == "callwznmmdlmod.vereq") return CALLWZNMMDLMOD_VEREQ;
if (s == "callwznmmdlupd.refeq") return CALLWZNMMDLUPD_REFEQ;
if (s == "callwznmmonstatchg") return CALLWZNMMONSTATCHG;
if (s == "callwznmmtd.jobeq") return CALLWZNMMTD_JOBEQ;
if (s == "callwznmmtdaipamod.mtdeq") return CALLWZNMMTDAIPAMOD_MTDEQ;
if (s == "callwznmmtdarpamod.mtdeq") return CALLWZNMMTDARPAMOD_MTDEQ;
if (s == "callwznmmtdmod") return CALLWZNMMTDMOD;
if (s == "callwznmmtdmod.jobeq") return CALLWZNMMTDMOD_JOBEQ;
if (s == "callwznmmtdupd.refeq") return CALLWZNMMTDUPD_REFEQ;
if (s == "callwznmnodechg") return CALLWZNMNODECHG;
if (s == "callwznmopk.sqkeq") return CALLWZNMOPK_SQKEQ;
if (s == "callwznmopk.vereq") return CALLWZNMOPK_VEREQ;
if (s == "callwznmopkainvmod.clueq") return CALLWZNMOPKAINVMOD_CLUEQ;
if (s == "callwznmopkainvmod.opkeq") return CALLWZNMOPKAINVMOD_OPKEQ;
if (s == "callwznmopkaretmod.clueq") return CALLWZNMOPKARETMOD_CLUEQ;
if (s == "callwznmopkaretmod.opkeq") return CALLWZNMOPKARETMOD_OPKEQ;
if (s == "callwznmopkmod") return CALLWZNMOPKMOD;
if (s == "callwznmopkmod.vereq") return CALLWZNMOPKMOD_VEREQ;
if (s == "callwznmopkupd.refeq") return CALLWZNMOPKUPD_REFEQ;
if (s == "callwznmopx.opkeq") return CALLWZNMOPX_OPKEQ;
if (s == "callwznmopx.sqkeq") return CALLWZNMOPX_SQKEQ;
if (s == "callwznmopxainvmod.clueq") return CALLWZNMOPXAINVMOD_CLUEQ;
if (s == "callwznmopxainvmod.opxeq") return CALLWZNMOPXAINVMOD_OPXEQ;
if (s == "callwznmopxaretmod.clueq") return CALLWZNMOPXARETMOD_CLUEQ;
if (s == "callwznmopxaretmod.opxeq") return CALLWZNMOPXARETMOD_OPXEQ;
if (s == "callwznmopxmod") return CALLWZNMOPXMOD;
if (s == "callwznmopxmod.opkeq") return CALLWZNMOPXMOD_OPKEQ;
if (s == "callwznmopxupd.refeq") return CALLWZNMOPXUPD_REFEQ;
if (s == "callwznmpnl.careq") return CALLWZNMPNL_CAREQ;
if (s == "callwznmpnl.jobeq") return CALLWZNMPNL_JOBEQ;
if (s == "callwznmpnl.reteq") return CALLWZNMPNL_RETEQ;
if (s == "callwznmpnl.reueq") return CALLWZNMPNL_REUEQ;
if (s == "callwznmpnlmod") return CALLWZNMPNLMOD;
if (s == "callwznmpnlmod.careq") return CALLWZNMPNLMOD_CAREQ;
if (s == "callwznmpnlmod.retreueq") return CALLWZNMPNLMOD_RETREUEQ;
if (s == "callwznmpnlrqrymod.pnleq") return CALLWZNMPNLRQRYMOD_PNLEQ;
if (s == "callwznmpnlrqrymod.qryeq") return CALLWZNMPNLRQRYMOD_QRYEQ;
if (s == "callwznmpnlupd.refeq") return CALLWZNMPNLUPD_REFEQ;
if (s == "callwznmprj.vereq") return CALLWZNMPRJ_VEREQ;
if (s == "callwznmprjmod") return CALLWZNMPRJMOD;
if (s == "callwznmprjupd.refeq") return CALLWZNMPRJUPD_REFEQ;
if (s == "callwznmprsadetmod.prseq") return CALLWZNMPRSADETMOD_PRSEQ;
if (s == "callwznmprsjlnmmod.prseq") return CALLWZNMPRSJLNMMOD_PRSEQ;
if (s == "callwznmprsmod") return CALLWZNMPRSMOD;
if (s == "callwznmprsrprjmod.prjeq") return CALLWZNMPRSRPRJMOD_PRJEQ;
if (s == "callwznmprsrprjmod.prseq") return CALLWZNMPRSRPRJMOD_PRSEQ;
if (s == "callwznmprsupd.refeq") return CALLWZNMPRSUPD_REFEQ;
if (s == "callwznmpst.reteq") return CALLWZNMPST_RETEQ;
if (s == "callwznmpst.reueq") return CALLWZNMPST_REUEQ;
if (s == "callwznmpst.vereq") return CALLWZNMPST_VEREQ;
if (s == "callwznmpstjtitmod.psteq") return CALLWZNMPSTJTITMOD_PSTEQ;
if (s == "callwznmpstmod") return CALLWZNMPSTMOD;
if (s == "callwznmpstmod.retreueq") return CALLWZNMPSTMOD_RETREUEQ;
if (s == "callwznmpstmod.vereq") return CALLWZNMPSTMOD_VEREQ;
if (s == "callwznmpstupd.refeq") return CALLWZNMPSTUPD_REFEQ;
if (s == "callwznmqco.qryeq") return CALLWZNMQCO_QRYEQ;
if (s == "callwznmqco.stbeq") return CALLWZNMQCO_STBEQ;
if (s == "callwznmqcojstbmod.qcoeq") return CALLWZNMQCOJSTBMOD_QCOEQ;
if (s == "callwznmqcomod") return CALLWZNMQCOMOD;
if (s == "callwznmqcomod.qryeq") return CALLWZNMQCOMOD_QRYEQ;
if (s == "callwznmqcomod.tcoeq") return CALLWZNMQCOMOD_TCOEQ;
if (s == "callwznmqcoupd.refeq") return CALLWZNMQCOUPD_REFEQ;
if (s == "callwznmqmd.psteq") return CALLWZNMQMD_PSTEQ;
if (s == "callwznmqmd.qryeq") return CALLWZNMQMD_QRYEQ;
if (s == "callwznmqmd.reteq") return CALLWZNMQMD_RETEQ;
if (s == "callwznmqmd.reueq") return CALLWZNMQMD_REUEQ;
if (s == "callwznmqmdmod") return CALLWZNMQMDMOD;
if (s == "callwznmqmdmod.psteq") return CALLWZNMQMDMOD_PSTEQ;
if (s == "callwznmqmdmod.qryeq") return CALLWZNMQMDMOD_QRYEQ;
if (s == "callwznmqmdmod.retreueq") return CALLWZNMQMDMOD_RETREUEQ;
if (s == "callwznmqmdupd.refeq") return CALLWZNMQMDUPD_REFEQ;
if (s == "callwznmqry.jobeq") return CALLWZNMQRY_JOBEQ;
if (s == "callwznmqry.supeq") return CALLWZNMQRY_SUPEQ;
if (s == "callwznmqry.vereq") return CALLWZNMQRY_VEREQ;
if (s == "callwznmqryacsemod.qmdeq") return CALLWZNMQRYACSEMOD_QMDEQ;
if (s == "callwznmqryacsemod.qryeq") return CALLWZNMQRYACSEMOD_QRYEQ;
if (s == "callwznmqryaordmod.qryeq") return CALLWZNMQRYAORDMOD_QRYEQ;
if (s == "callwznmqrymod") return CALLWZNMQRYMOD;
if (s == "callwznmqrymod.supeq") return CALLWZNMQRYMOD_SUPEQ;
if (s == "callwznmqrymod.vereq") return CALLWZNMQRYMOD_VEREQ;
if (s == "callwznmqryrtblmod.qryeq") return CALLWZNMQRYRTBLMOD_QRYEQ;
if (s == "callwznmqryrtblmod.tbleq") return CALLWZNMQRYRTBLMOD_TBLEQ;
if (s == "callwznmqryupd.refeq") return CALLWZNMQRYUPD_REFEQ;
if (s == "callwznmrecaccess") return CALLWZNMRECACCESS;
if (s == "callwznmrefpreset") return CALLWZNMREFPRESET;
if (s == "callwznmrefspreset") return CALLWZNMREFSPRESET;
if (s == "callwznmrel.clueq") return CALLWZNMREL_CLUEQ;
if (s == "callwznmrel.frseq") return CALLWZNMREL_FRSEQ;
if (s == "callwznmrel.supeq") return CALLWZNMREL_SUPEQ;
if (s == "callwznmrel.toseq") return CALLWZNMREL_TOSEQ;
if (s == "callwznmrel.vereq") return CALLWZNMREL_VEREQ;
if (s == "callwznmrelatitmod.loceq") return CALLWZNMRELATITMOD_LOCEQ;
if (s == "callwznmrelatitmod.releq") return CALLWZNMRELATITMOD_RELEQ;
if (s == "callwznmrelmod") return CALLWZNMRELMOD;
if (s == "callwznmrelmod.clueq") return CALLWZNMRELMOD_CLUEQ;
if (s == "callwznmrelmod.frteq") return CALLWZNMRELMOD_FRTEQ;
if (s == "callwznmrelmod.supeq") return CALLWZNMRELMOD_SUPEQ;
if (s == "callwznmrelmod.toteq") return CALLWZNMRELMOD_TOTEQ;
if (s == "callwznmrelmod.vereq") return CALLWZNMRELMOD_VEREQ;
if (s == "callwznmrelupd.refeq") return CALLWZNMRELUPD_REFEQ;
if (s == "callwznmreptrstart") return CALLWZNMREPTRSTART;
if (s == "callwznmreptrstop") return CALLWZNMREPTRSTOP;
if (s == "callwznmrls.cmpeq") return CALLWZNMRLS_CMPEQ;
if (s == "callwznmrls.mcheq") return CALLWZNMRLS_MCHEQ;
if (s == "callwznmrlsmod") return CALLWZNMRLSMOD;
if (s == "callwznmrlsmod.cmpeq") return CALLWZNMRLSMOD_CMPEQ;
if (s == "callwznmrlsmod.mcheq") return CALLWZNMRLSMOD_MCHEQ;
if (s == "callwznmrlsupd.refeq") return CALLWZNMRLSUPD_REFEQ;
if (s == "callwznmrtbmod") return CALLWZNMRTBMOD;
if (s == "callwznmrtbmod.retreueq") return CALLWZNMRTBMOD_RETREUEQ;
if (s == "callwznmrtbmod.rtjeq") return CALLWZNMRTBMOD_RTJEQ;
if (s == "callwznmrtbupd.refeq") return CALLWZNMRTBUPD_REFEQ;
if (s == "callwznmrtdmod") return CALLWZNMRTDMOD;
if (s == "callwznmrtdmod.blkeq") return CALLWZNMRTDMOD_BLKEQ;
if (s == "callwznmrtdmod.rtjeq") return CALLWZNMRTDMOD_RTJEQ;
if (s == "callwznmrtdupd.refeq") return CALLWZNMRTDUPD_REFEQ;
if (s == "callwznmrtj.appeq") return CALLWZNMRTJ_APPEQ;
if (s == "callwznmrtj.jobeq") return CALLWZNMRTJ_JOBEQ;
if (s == "callwznmrtj.supeq") return CALLWZNMRTJ_SUPEQ;
if (s == "callwznmrtjmod") return CALLWZNMRTJMOD;
if (s == "callwznmrtjmod.appeq") return CALLWZNMRTJMOD_APPEQ;
if (s == "callwznmrtjmod.jobeq") return CALLWZNMRTJMOD_JOBEQ;
if (s == "callwznmrtjmod.supeq") return CALLWZNMRTJMOD_SUPEQ;
if (s == "callwznmrtjupd.refeq") return CALLWZNMRTJUPD_REFEQ;
if (s == "callwznmsbs.careq") return CALLWZNMSBS_CAREQ;
if (s == "callwznmsbs.psteq") return CALLWZNMSBS_PSTEQ;
if (s == "callwznmsbsatitmod.loceq") return CALLWZNMSBSATITMOD_LOCEQ;
if (s == "callwznmsbsatitmod.sbseq") return CALLWZNMSBSATITMOD_SBSEQ;
if (s == "callwznmsbsmod") return CALLWZNMSBSMOD;
if (s == "callwznmsbsmod.tbleq") return CALLWZNMSBSMOD_TBLEQ;
if (s == "callwznmsbsrsbsmod.asbeq") return CALLWZNMSBSRSBSMOD_ASBEQ;
if (s == "callwznmsbsrsbsmod.bsbeq") return CALLWZNMSBSRSBSMOD_BSBEQ;
if (s == "callwznmsbsupd.refeq") return CALLWZNMSBSUPD_REFEQ;
if (s == "callwznmseq.appeq") return CALLWZNMSEQ_APPEQ;
if (s == "callwznmseqmod") return CALLWZNMSEQMOD;
if (s == "callwznmseqmod.appeq") return CALLWZNMSEQMOD_APPEQ;
if (s == "callwznmsequpd.refeq") return CALLWZNMSEQUPD_REFEQ;
if (s == "callwznmsesmod") return CALLWZNMSESMOD;
if (s == "callwznmsesmod.usreq") return CALLWZNMSESMOD_USREQ;
if (s == "callwznmsesupd.refeq") return CALLWZNMSESUPD_REFEQ;
if (s == "callwznmsge.fnxeq") return CALLWZNMSGE_FNXEQ;
if (s == "callwznmsge.jobeq") return CALLWZNMSGE_JOBEQ;
if (s == "callwznmsge.snxeq") return CALLWZNMSGE_SNXEQ;
if (s == "callwznmsge.sqkeq") return CALLWZNMSGE_SQKEQ;
if (s == "callwznmsgechg") return CALLWZNMSGECHG;
if (s == "callwznmsgemod") return CALLWZNMSGEMOD;
if (s == "callwznmsgemod.jobeq") return CALLWZNMSGEMOD_JOBEQ;
if (s == "callwznmsgeupd.refeq") return CALLWZNMSGEUPD_REFEQ;
if (s == "callwznmshrdatchg") return CALLWZNMSHRDATCHG;
if (s == "callwznmsnsmod") return CALLWZNMSNSMOD;
if (s == "callwznmsnsmod.caleq") return CALLWZNMSNSMOD_CALEQ;
if (s == "callwznmsnsmod.jobeq") return CALLWZNMSNSMOD_JOBEQ;
if (s == "callwznmsnsupd.refeq") return CALLWZNMSNSUPD_REFEQ;
if (s == "callwznmsqkjtitmod.sqkeq") return CALLWZNMSQKJTITMOD_SQKEQ;
if (s == "callwznmsqkmod") return CALLWZNMSQKMOD;
if (s == "callwznmsqkmod.retreueq") return CALLWZNMSQKMOD_RETREUEQ;
if (s == "callwznmsqkrstbmod.sqkeq") return CALLWZNMSQKRSTBMOD_SQKEQ;
if (s == "callwznmsqkrstbmod.stbeq") return CALLWZNMSQKRSTBMOD_STBEQ;
if (s == "callwznmsqkupd.refeq") return CALLWZNMSQKUPD_REFEQ;
if (s == "callwznmsrefpreset") return CALLWZNMSREFPRESET;
if (s == "callwznmstatchg") return CALLWZNMSTATCHG;
if (s == "callwznmstb.sbseq") return CALLWZNMSTB_SBSEQ;
if (s == "callwznmstb.tcoeq") return CALLWZNMSTB_TCOEQ;
if (s == "callwznmstbmod") return CALLWZNMSTBMOD;
if (s == "callwznmstbmod.tbleq") return CALLWZNMSTBMOD_TBLEQ;
if (s == "callwznmstbrstbmod.subeq") return CALLWZNMSTBRSTBMOD_SUBEQ;
if (s == "callwznmstbrstbmod.supeq") return CALLWZNMSTBRSTBMOD_SUPEQ;
if (s == "callwznmstbupd.refeq") return CALLWZNMSTBUPD_REFEQ;
if (s == "callwznmste.seqeq") return CALLWZNMSTE_SEQEQ;
if (s == "callwznmsteaactmod.steeq") return CALLWZNMSTEAACTMOD_STEEQ;
if (s == "callwznmsteatrgmod.steeq") return CALLWZNMSTEATRGMOD_STEEQ;
if (s == "callwznmstemod") return CALLWZNMSTEMOD;
if (s == "callwznmstemod.seqeq") return CALLWZNMSTEMOD_SEQEQ;
if (s == "callwznmsteupd.refeq") return CALLWZNMSTEUPD_REFEQ;
if (s == "callwznmstgchg") return CALLWZNMSTGCHG;
if (s == "callwznmstrjcndmod.steatrgeq") return CALLWZNMSTRJCNDMOD_STEATRGEQ;
if (s == "callwznmstubchg") return CALLWZNMSTUBCHG;
if (s == "callwznmsuspsess") return CALLWZNMSUSPSESS;
if (s == "callwznmtag.cpbeq") return CALLWZNMTAG_CPBEQ;
if (s == "callwznmtagjtitmod.tageq") return CALLWZNMTAGJTITMOD_TAGEQ;
if (s == "callwznmtagmod") return CALLWZNMTAGMOD;
if (s == "callwznmtagmod.cpbeq") return CALLWZNMTAGMOD_CPBEQ;
if (s == "callwznmtagupd.refeq") return CALLWZNMTAGUPD_REFEQ;
if (s == "callwznmtbl.careq") return CALLWZNMTBL_CAREQ;
if (s == "callwznmtbl.insbs") return CALLWZNMTBL_INSBS;
if (s == "callwznmtbl.psteq") return CALLWZNMTBL_PSTEQ;
if (s == "callwznmtbl.reteq") return CALLWZNMTBL_RETEQ;
if (s == "callwznmtbl.reueq") return CALLWZNMTBL_REUEQ;
if (s == "callwznmtbl.typeq") return CALLWZNMTBL_TYPEQ;
if (s == "callwznmtbl.vereq") return CALLWZNMTBL_VEREQ;
if (s == "callwznmtblalfcmod.tbleq") return CALLWZNMTBLALFCMOD_TBLEQ;
if (s == "callwznmtblatitmod.loceq") return CALLWZNMTBLATITMOD_LOCEQ;
if (s == "callwznmtblatitmod.tbleq") return CALLWZNMTBLATITMOD_TBLEQ;
if (s == "callwznmtblmod") return CALLWZNMTBLMOD;
if (s == "callwznmtblmod.retreueq") return CALLWZNMTBLMOD_RETREUEQ;
if (s == "callwznmtblmod.vereq") return CALLWZNMTBLMOD_VEREQ;
if (s == "callwznmtblrvecmod.tbleq") return CALLWZNMTBLRVECMOD_TBLEQ;
if (s == "callwznmtblrvecmod.veceq") return CALLWZNMTBLRVECMOD_VECEQ;
if (s == "callwznmtblupd.refeq") return CALLWZNMTBLUPD_REFEQ;
if (s == "callwznmtco.fcteq") return CALLWZNMTCO_FCTEQ;
if (s == "callwznmtco.fcueq") return CALLWZNMTCO_FCUEQ;
if (s == "callwznmtco.insbs") return CALLWZNMTCO_INSBS;
if (s == "callwznmtco.releq") return CALLWZNMTCO_RELEQ;
if (s == "callwznmtco.sbseq") return CALLWZNMTCO_SBSEQ;
if (s == "callwznmtco.tbl.insbs") return CALLWZNMTCO_TBL_INSBS;
if (s == "callwznmtco.tbleq") return CALLWZNMTCO_TBLEQ;
if (s == "callwznmtcoatitmod.loceq") return CALLWZNMTCOATITMOD_LOCEQ;
if (s == "callwznmtcoatitmod.tcoeq") return CALLWZNMTCOATITMOD_TCOEQ;
if (s == "callwznmtcomod") return CALLWZNMTCOMOD;
if (s == "callwznmtcomod.fctfcueq") return CALLWZNMTCOMOD_FCTFCUEQ;
if (s == "callwznmtcomod.releq") return CALLWZNMTCOMOD_RELEQ;
if (s == "callwznmtcomod.tbleq") return CALLWZNMTCOMOD_TBLEQ;
if (s == "callwznmtcoupd.refeq") return CALLWZNMTCOUPD_REFEQ;
if (s == "callwznmtxtvalpreset") return CALLWZNMTXTVALPRESET;
if (s == "callwznmusgaaccmod.usgeq") return CALLWZNMUSGAACCMOD_USGEQ;
if (s == "callwznmusgmod") return CALLWZNMUSGMOD;
if (s == "callwznmusgupd.refeq") return CALLWZNMUSGUPD_REFEQ;
if (s == "callwznmusr.prseq") return CALLWZNMUSR_PRSEQ;
if (s == "callwznmusr.usgeq") return CALLWZNMUSR_USGEQ;
if (s == "callwznmusraaccmod.usreq") return CALLWZNMUSRAACCMOD_USREQ;
if (s == "callwznmusrjstemod.usreq") return CALLWZNMUSRJSTEMOD_USREQ;
if (s == "callwznmusrmod") return CALLWZNMUSRMOD;
if (s == "callwznmusrrusgmod.usgeq") return CALLWZNMUSRRUSGMOD_USGEQ;
if (s == "callwznmusrrusgmod.usreq") return CALLWZNMUSRRUSGMOD_USREQ;
if (s == "callwznmusrupd.refeq") return CALLWZNMUSRUPD_REFEQ;
if (s == "callwznmvec.hkteq") return CALLWZNMVEC_HKTEQ;
if (s == "callwznmvec.hkueq") return CALLWZNMVEC_HKUEQ;
if (s == "callwznmvec.insbs") return CALLWZNMVEC_INSBS;
if (s == "callwznmvec.psteq") return CALLWZNMVEC_PSTEQ;
if (s == "callwznmvec.typeq") return CALLWZNMVEC_TYPEQ;
if (s == "callwznmvec.vereq") return CALLWZNMVEC_VEREQ;
if (s == "callwznmvecatitmod.loceq") return CALLWZNMVECATITMOD_LOCEQ;
if (s == "callwznmvecatitmod.veceq") return CALLWZNMVECATITMOD_VECEQ;
if (s == "callwznmvecmod") return CALLWZNMVECMOD;
if (s == "callwznmvecmod.hkthkueq") return CALLWZNMVECMOD_HKTHKUEQ;
if (s == "callwznmvecmod.vereq") return CALLWZNMVECMOD_VEREQ;
if (s == "callwznmvecupd.refeq") return CALLWZNMVECUPD_REFEQ;
if (s == "callwznmver.bvreq") return CALLWZNMVER_BVREQ;
if (s == "callwznmver.loceq") return CALLWZNMVER_LOCEQ;
if (s == "callwznmver.prjeq") return CALLWZNMVER_PRJEQ;
if (s == "callwznmver.steeq") return CALLWZNMVER_STEEQ;
if (s == "callwznmverjmod.vereq") return CALLWZNMVERJMOD_VEREQ;
if (s == "callwznmverjstemod.vereq") return CALLWZNMVERJSTEMOD_VEREQ;
if (s == "callwznmvermod") return CALLWZNMVERMOD;
if (s == "callwznmvermod.bvreq") return CALLWZNMVERMOD_BVREQ;
if (s == "callwznmvermod.prjeq") return CALLWZNMVERMOD_PRJEQ;
if (s == "callwznmverupd.refeq") return CALLWZNMVERUPD_REFEQ;
if (s == "callwznmvit.veceq") return CALLWZNMVIT_VECEQ;
if (s == "callwznmvitjmod.viteq") return CALLWZNMVITJMOD_VITEQ;
if (s == "callwznmvitmod") return CALLWZNMVITMOD;
if (s == "callwznmvitmod.veceq") return CALLWZNMVITMOD_VECEQ;
if (s == "callwznmvitupd.refeq") return CALLWZNMVITUPD_REFEQ;
return(0);
};
string VecWznmVCall::getSref(
const uint ix
) {
if (ix == CALLWZNMAPP_VEREQ) return("CallWznmApp.verEq");
if (ix == CALLWZNMAPPMOD) return("CallWznmAppMod");
if (ix == CALLWZNMAPPMOD_VEREQ) return("CallWznmAppMod.verEq");
if (ix == CALLWZNMAPPUPD_REFEQ) return("CallWznmAppUpd.refEq");
if (ix == CALLWZNMBITJMOD_BLKAITMEQ) return("CallWznmBitJMod.blkAitmEq");
if (ix == CALLWZNMBLK_RETEQ) return("CallWznmBlk.retEq");
if (ix == CALLWZNMBLK_REUEQ) return("CallWznmBlk.reuEq");
if (ix == CALLWZNMBLK_VEREQ) return("CallWznmBlk.verEq");
if (ix == CALLWZNMBLKAITMMOD_BLKEQ) return("CallWznmBlkAitmMod.blkEq");
if (ix == CALLWZNMBLKAITMMOD_CLUEQ) return("CallWznmBlkAitmMod.cluEq");
if (ix == CALLWZNMBLKMOD) return("CallWznmBlkMod");
if (ix == CALLWZNMBLKMOD_RETREUEQ) return("CallWznmBlkMod.retReuEq");
if (ix == CALLWZNMBLKMOD_VEREQ) return("CallWznmBlkMod.verEq");
if (ix == CALLWZNMBLKUPD_REFEQ) return("CallWznmBlkUpd.refEq");
if (ix == CALLWZNMBOOLVALPRESET) return("CallWznmBoolvalPreSet");
if (ix == CALLWZNMCAL_RETEQ) return("CallWznmCal.retEq");
if (ix == CALLWZNMCAL_REUEQ) return("CallWznmCal.reuEq");
if (ix == CALLWZNMCAL_TYPEQ) return("CallWznmCal.typEq");
if (ix == CALLWZNMCAL_VEREQ) return("CallWznmCal.verEq");
if (ix == CALLWZNMCALMOD) return("CallWznmCalMod");
if (ix == CALLWZNMCALMOD_RETREUEQ) return("CallWznmCalMod.retReuEq");
if (ix == CALLWZNMCALMOD_VEREQ) return("CallWznmCalMod.verEq");
if (ix == CALLWZNMCALRSTBMOD_CALEQ) return("CallWznmCalRstbMod.calEq");
if (ix == CALLWZNMCALRSTBMOD_STBEQ) return("CallWznmCalRstbMod.stbEq");
if (ix == CALLWZNMCALUPD_REFEQ) return("CallWznmCalUpd.refEq");
if (ix == CALLWZNMCAR_JOBEQ) return("CallWznmCar.jobEq");
if (ix == CALLWZNMCAR_MDLEQ) return("CallWznmCar.mdlEq");
if (ix == CALLWZNMCAR_RETEQ) return("CallWznmCar.retEq");
if (ix == CALLWZNMCAR_REUEQ) return("CallWznmCar.reuEq");
if (ix == CALLWZNMCARJTITMOD_CAREQ) return("CallWznmCarJtitMod.carEq");
if (ix == CALLWZNMCARMOD) return("CallWznmCarMod");
if (ix == CALLWZNMCARMOD_MDLEQ) return("CallWznmCarMod.mdlEq");
if (ix == CALLWZNMCARMOD_RETREUEQ) return("CallWznmCarMod.retReuEq");
if (ix == CALLWZNMCARUPD_REFEQ) return("CallWznmCarUpd.refEq");
if (ix == CALLWZNMCHK_CALEQ) return("CallWznmChk.calEq");
if (ix == CALLWZNMCHK_TCOEQ) return("CallWznmChk.tcoEq");
if (ix == CALLWZNMCHKMOD) return("CallWznmChkMod");
if (ix == CALLWZNMCHKMOD_TBLEQ) return("CallWznmChkMod.tblEq");
if (ix == CALLWZNMCHKUPD_REFEQ) return("CallWznmChkUpd.refEq");
if (ix == CALLWZNMCLAIMCHG) return("CallWznmClaimChg");
if (ix == CALLWZNMCMP_INSBS) return("CallWznmCmp.inSbs");
if (ix == CALLWZNMCMP_TYPEQ) return("CallWznmCmp.typEq");
if (ix == CALLWZNMCMP_VEREQ) return("CallWznmCmp.verEq");
if (ix == CALLWZNMCMPMOD) return("CallWznmCmpMod");
if (ix == CALLWZNMCMPMOD_VEREQ) return("CallWznmCmpMod.verEq");
if (ix == CALLWZNMCMPRLIBMOD_CMPEQ) return("CallWznmCmpRlibMod.cmpEq");
if (ix == CALLWZNMCMPRLIBMOD_LIBEQ) return("CallWznmCmpRlibMod.libEq");
if (ix == CALLWZNMCMPROPKMOD_CMPEQ) return("CallWznmCmpRopkMod.cmpEq");
if (ix == CALLWZNMCMPROPKMOD_OPKEQ) return("CallWznmCmpRopkMod.opkEq");
if (ix == CALLWZNMCMPUPD_REFEQ) return("CallWznmCmpUpd.refEq");
if (ix == CALLWZNMCON_CLUEQ) return("CallWznmCon.cluEq");
if (ix == CALLWZNMCON_FEDEQ) return("CallWznmCon.fedEq");
if (ix == CALLWZNMCON_HKTEQ) return("CallWznmCon.hktEq");
if (ix == CALLWZNMCON_HKUEQ) return("CallWznmCon.hkuEq");
if (ix == CALLWZNMCON_INSBS) return("CallWznmCon.inSbs");
if (ix == CALLWZNMCON_RETEQ) return("CallWznmCon.retEq");
if (ix == CALLWZNMCON_REUEQ) return("CallWznmCon.reuEq");
if (ix == CALLWZNMCON_SHSEQ) return("CallWznmCon.shsEq");
if (ix == CALLWZNMCON_STSEQ) return("CallWznmCon.stsEq");
if (ix == CALLWZNMCON_SUPEQ) return("CallWznmCon.supEq");
if (ix == CALLWZNMCON_TYPEQ) return("CallWznmCon.typEq");
if (ix == CALLWZNMCONAPARMOD_CONEQ) return("CallWznmConAparMod.conEq");
if (ix == CALLWZNMCONAPARMOD_LOCEQ) return("CallWznmConAparMod.locEq");
if (ix == CALLWZNMCONJMOD_CONEQ) return("CallWznmConJMod.conEq");
if (ix == CALLWZNMCONJTITMOD_CONEQ) return("CallWznmConJtitMod.conEq");
if (ix == CALLWZNMCONMOD) return("CallWznmConMod");
if (ix == CALLWZNMCONMOD_CLUEQ) return("CallWznmConMod.cluEq");
if (ix == CALLWZNMCONMOD_HKTHKUEQ) return("CallWznmConMod.hktHkuEq");
if (ix == CALLWZNMCONMOD_RETREUEQ) return("CallWznmConMod.retReuEq");
if (ix == CALLWZNMCONMOD_SUPEQ) return("CallWznmConMod.supEq");
if (ix == CALLWZNMCONUPD_REFEQ) return("CallWznmConUpd.refEq");
if (ix == CALLWZNMCPB_INSBS) return("CallWznmCpb.inSbs");
if (ix == CALLWZNMCPB_TPLEQ) return("CallWznmCpb.tplEq");
if (ix == CALLWZNMCPB_VEREQ) return("CallWznmCpb.verEq");
if (ix == CALLWZNMCPBAPARMOD_CPBEQ) return("CallWznmCpbAparMod.cpbEq");
if (ix == CALLWZNMCPBMOD) return("CallWznmCpbMod");
if (ix == CALLWZNMCPBMOD_TPLEQ) return("CallWznmCpbMod.tplEq");
if (ix == CALLWZNMCPBMOD_VEREQ) return("CallWznmCpbMod.verEq");
if (ix == CALLWZNMCPBUPD_REFEQ) return("CallWznmCpbUpd.refEq");
if (ix == CALLWZNMCRDACTIVE) return("CallWznmCrdActive");
if (ix == CALLWZNMCRDCLOSE) return("CallWznmCrdClose");
if (ix == CALLWZNMCRDOPEN) return("CallWznmCrdOpen");
if (ix == CALLWZNMCTLAPARMOD_USREQ) return("CallWznmCtlAparMod.usrEq");
if (ix == CALLWZNMDATCHG) return("CallWznmDatChg");
if (ix == CALLWZNMDBLVALPRESET) return("CallWznmDblvalPreSet");
if (ix == CALLWZNMDLG_CAREQ) return("CallWznmDlg.carEq");
if (ix == CALLWZNMDLG_JOBEQ) return("CallWznmDlg.jobEq");
if (ix == CALLWZNMDLG_RETEQ) return("CallWznmDlg.retEq");
if (ix == CALLWZNMDLG_REUEQ) return("CallWznmDlg.reuEq");
if (ix == CALLWZNMDLGCLOSE) return("CallWznmDlgClose");
if (ix == CALLWZNMDLGMOD) return("CallWznmDlgMod");
if (ix == CALLWZNMDLGMOD_CAREQ) return("CallWznmDlgMod.carEq");
if (ix == CALLWZNMDLGMOD_RETREUEQ) return("CallWznmDlgMod.retReuEq");
if (ix == CALLWZNMDLGRQRYMOD_DLGEQ) return("CallWznmDlgRqryMod.dlgEq");
if (ix == CALLWZNMDLGRQRYMOD_QRYEQ) return("CallWznmDlgRqryMod.qryEq");
if (ix == CALLWZNMDLGUPD_REFEQ) return("CallWznmDlgUpd.refEq");
if (ix == CALLWZNMERR_VEREQ) return("CallWznmErr.verEq");
if (ix == CALLWZNMERRJTITMOD_ERREQ) return("CallWznmErrJtitMod.errEq");
if (ix == CALLWZNMERRMOD) return("CallWznmErrMod");
if (ix == CALLWZNMERRMOD_VEREQ) return("CallWznmErrMod.verEq");
if (ix == CALLWZNMERRUPD_REFEQ) return("CallWznmErrUpd.refEq");
if (ix == CALLWZNMEVT_APPEQ) return("CallWznmEvt.appEq");
if (ix == CALLWZNMEVTMOD) return("CallWznmEvtMod");
if (ix == CALLWZNMEVTMOD_APPEQ) return("CallWznmEvtMod.appEq");
if (ix == CALLWZNMEVTUPD_REFEQ) return("CallWznmEvtUpd.refEq");
if (ix == CALLWZNMFED_SRTEQ) return("CallWznmFed.srtEq");
if (ix == CALLWZNMFED_SRUEQ) return("CallWznmFed.sruEq");
if (ix == CALLWZNMFEDMOD) return("CallWznmFedMod");
if (ix == CALLWZNMFEDMOD_SRTSRUEQ) return("CallWznmFedMod.srtSruEq");
if (ix == CALLWZNMFEDUPD_REFEQ) return("CallWznmFedUpd.refEq");
if (ix == CALLWZNMFIL_CLUEQ) return("CallWznmFil.cluEq");
if (ix == CALLWZNMFIL_RETEQ) return("CallWznmFil.retEq");
if (ix == CALLWZNMFIL_REUEQ) return("CallWznmFil.reuEq");
if (ix == CALLWZNMFILMOD) return("CallWznmFilMod");
if (ix == CALLWZNMFILMOD_CLUEQ) return("CallWznmFilMod.cluEq");
if (ix == CALLWZNMFILMOD_RETREUEQ) return("CallWznmFilMod.retReuEq");
if (ix == CALLWZNMFILUPD_REFEQ) return("CallWznmFilUpd.refEq");
if (ix == CALLWZNMHUSRRUNVMOD_CRDUSREQ) return("CallWznmHusrRunvMod.crdUsrEq");
if (ix == CALLWZNMIEL_IM2EQ) return("CallWznmIel.im2Eq");
if (ix == CALLWZNMIEL_IMEEQ) return("CallWznmIel.imeEq");
if (ix == CALLWZNMIEL_PSTEQ) return("CallWznmIel.pstEq");
if (ix == CALLWZNMIEL_STBEQ) return("CallWznmIel.stbEq");
if (ix == CALLWZNMIEL_VITEQ) return("CallWznmIel.vitEq");
if (ix == CALLWZNMIELJSTBMOD_IELEQ) return("CallWznmIelJstbMod.ielEq");
if (ix == CALLWZNMIELMOD) return("CallWznmIelMod");
if (ix == CALLWZNMIELMOD_IMEEQ) return("CallWznmIelMod.imeEq");
if (ix == CALLWZNMIELMOD_TCOEQ) return("CallWznmIelMod.tcoEq");
if (ix == CALLWZNMIELUPD_REFEQ) return("CallWznmIelUpd.refEq");
if (ix == CALLWZNMIEX_JOBEQ) return("CallWznmIex.jobEq");
if (ix == CALLWZNMIEX_VEREQ) return("CallWznmIex.verEq");
if (ix == CALLWZNMIEXJTITMOD_IEXEQ) return("CallWznmIexJtitMod.iexEq");
if (ix == CALLWZNMIEXMOD) return("CallWznmIexMod");
if (ix == CALLWZNMIEXMOD_VEREQ) return("CallWznmIexMod.verEq");
if (ix == CALLWZNMIEXUPD_REFEQ) return("CallWznmIexUpd.refEq");
if (ix == CALLWZNMIME_IEXEQ) return("CallWznmIme.iexEq");
if (ix == CALLWZNMIME_SUPEQ) return("CallWznmIme.supEq");
if (ix == CALLWZNMIMEMOD) return("CallWznmImeMod");
if (ix == CALLWZNMIMEMOD_IEXEQ) return("CallWznmImeMod.iexEq");
if (ix == CALLWZNMIMEMOD_SUPEQ) return("CallWznmImeMod.supEq");
if (ix == CALLWZNMIMEMOD_TBLEQ) return("CallWznmImeMod.tblEq");
if (ix == CALLWZNMIMEUPD_REFEQ) return("CallWznmImeUpd.refEq");
if (ix == CALLWZNMINTVALPRESET) return("CallWznmIntvalPreSet");
if (ix == CALLWZNMIXPRESET) return("CallWznmIxPreSet");
if (ix == CALLWZNMJOB_RETEQ) return("CallWznmJob.retEq");
if (ix == CALLWZNMJOB_REUEQ) return("CallWznmJob.reuEq");
if (ix == CALLWZNMJOB_TYPEQ) return("CallWznmJob.typEq");
if (ix == CALLWZNMJOB_VEREQ) return("CallWznmJob.verEq");
if (ix == CALLWZNMJOBACMDMOD_JOBEQ) return("CallWznmJobAcmdMod.jobEq");
if (ix == CALLWZNMJOBAVARMOD_CLUEQ) return("CallWznmJobAvarMod.cluEq");
if (ix == CALLWZNMJOBAVARMOD_JOBEQ) return("CallWznmJobAvarMod.jobEq");
if (ix == CALLWZNMJOBMOD) return("CallWznmJobMod");
if (ix == CALLWZNMJOBMOD_RETREUEQ) return("CallWznmJobMod.retReuEq");
if (ix == CALLWZNMJOBMOD_VEREQ) return("CallWznmJobMod.verEq");
if (ix == CALLWZNMJOBRJOBMOD_SUBEQ) return("CallWznmJobRjobMod.subEq");
if (ix == CALLWZNMJOBRJOBMOD_SUPEQ) return("CallWznmJobRjobMod.supEq");
if (ix == CALLWZNMJOBROPKMOD_JOBEQ) return("CallWznmJobRopkMod.jobEq");
if (ix == CALLWZNMJOBROPKMOD_OPKEQ) return("CallWznmJobRopkMod.opkEq");
if (ix == CALLWZNMJOBROPXMOD_JOBEQ) return("CallWznmJobRopxMod.jobEq");
if (ix == CALLWZNMJOBROPXMOD_OPXEQ) return("CallWznmJobRopxMod.opxEq");
if (ix == CALLWZNMJOBUPD_REFEQ) return("CallWznmJobUpd.refEq");
if (ix == CALLWZNMKLKJKEYMOD_KLSAKEYEQ) return("CallWznmKlkJkeyMod.klsAkeyEq");
if (ix == CALLWZNMKLSAKEYMOD_KLSEQ) return("CallWznmKlsAkeyMod.klsEq");
if (ix == CALLWZNMKLSAKEYMOD_KLSMTBURFEQ) return("CallWznmKlsAkeyMod.klsMtbUrfEq");
if (ix == CALLWZNMLIBAMKFMOD_LIBEQ) return("CallWznmLibAmkfMod.libEq");
if (ix == CALLWZNMLIBAMKFMOD_MCHEQ) return("CallWznmLibAmkfMod.mchEq");
if (ix == CALLWZNMLIBAPKLMOD_LIBEQ) return("CallWznmLibApklMod.libEq");
if (ix == CALLWZNMLIBAPKLMOD_MCHEQ) return("CallWznmLibApklMod.mchEq");
if (ix == CALLWZNMLIBMOD) return("CallWznmLibMod");
if (ix == CALLWZNMLIBROPKMOD_LIBEQ) return("CallWznmLibRopkMod.libEq");
if (ix == CALLWZNMLIBROPKMOD_OPKEQ) return("CallWznmLibRopkMod.opkEq");
if (ix == CALLWZNMLIBUPD_REFEQ) return("CallWznmLibUpd.refEq");
if (ix == CALLWZNMLOCJTITMOD_LOCEQ) return("CallWznmLocJtitMod.locEq");
if (ix == CALLWZNMLOCMOD) return("CallWznmLocMod");
if (ix == CALLWZNMLOCRVERMOD_LOCEQ) return("CallWznmLocRverMod.locEq");
if (ix == CALLWZNMLOCRVERMOD_VEREQ) return("CallWznmLocRverMod.verEq");
if (ix == CALLWZNMLOCUPD_REFEQ) return("CallWznmLocUpd.refEq");
if (ix == CALLWZNMLOG) return("CallWznmLog");
if (ix == CALLWZNMLOGOUT) return("CallWznmLogout");
if (ix == CALLWZNMMCH_CCHEQ) return("CallWznmMch.cchEq");
if (ix == CALLWZNMMCH_SUPEQ) return("CallWznmMch.supEq");
if (ix == CALLWZNMMCHAMKFMOD_MCHEQ) return("CallWznmMchAmkfMod.mchEq");
if (ix == CALLWZNMMCHAPARMOD_MCHEQ) return("CallWznmMchAparMod.mchEq");
if (ix == CALLWZNMMCHMOD) return("CallWznmMchMod");
if (ix == CALLWZNMMCHMOD_SUPEQ) return("CallWznmMchMod.supEq");
if (ix == CALLWZNMMCHUPD_REFEQ) return("CallWznmMchUpd.refEq");
if (ix == CALLWZNMMDL_VEREQ) return("CallWznmMdl.verEq");
if (ix == CALLWZNMMDLJMOD_MDLEQ) return("CallWznmMdlJMod.mdlEq");
if (ix == CALLWZNMMDLMOD) return("CallWznmMdlMod");
if (ix == CALLWZNMMDLMOD_VEREQ) return("CallWznmMdlMod.verEq");
if (ix == CALLWZNMMDLUPD_REFEQ) return("CallWznmMdlUpd.refEq");
if (ix == CALLWZNMMONSTATCHG) return("CallWznmMonstatChg");
if (ix == CALLWZNMMTD_JOBEQ) return("CallWznmMtd.jobEq");
if (ix == CALLWZNMMTDAIPAMOD_MTDEQ) return("CallWznmMtdAipaMod.mtdEq");
if (ix == CALLWZNMMTDARPAMOD_MTDEQ) return("CallWznmMtdArpaMod.mtdEq");
if (ix == CALLWZNMMTDMOD) return("CallWznmMtdMod");
if (ix == CALLWZNMMTDMOD_JOBEQ) return("CallWznmMtdMod.jobEq");
if (ix == CALLWZNMMTDUPD_REFEQ) return("CallWznmMtdUpd.refEq");
if (ix == CALLWZNMNODECHG) return("CallWznmNodeChg");
if (ix == CALLWZNMOPK_SQKEQ) return("CallWznmOpk.sqkEq");
if (ix == CALLWZNMOPK_VEREQ) return("CallWznmOpk.verEq");
if (ix == CALLWZNMOPKAINVMOD_CLUEQ) return("CallWznmOpkAinvMod.cluEq");
if (ix == CALLWZNMOPKAINVMOD_OPKEQ) return("CallWznmOpkAinvMod.opkEq");
if (ix == CALLWZNMOPKARETMOD_CLUEQ) return("CallWznmOpkAretMod.cluEq");
if (ix == CALLWZNMOPKARETMOD_OPKEQ) return("CallWznmOpkAretMod.opkEq");
if (ix == CALLWZNMOPKMOD) return("CallWznmOpkMod");
if (ix == CALLWZNMOPKMOD_VEREQ) return("CallWznmOpkMod.verEq");
if (ix == CALLWZNMOPKUPD_REFEQ) return("CallWznmOpkUpd.refEq");
if (ix == CALLWZNMOPX_OPKEQ) return("CallWznmOpx.opkEq");
if (ix == CALLWZNMOPX_SQKEQ) return("CallWznmOpx.sqkEq");
if (ix == CALLWZNMOPXAINVMOD_CLUEQ) return("CallWznmOpxAinvMod.cluEq");
if (ix == CALLWZNMOPXAINVMOD_OPXEQ) return("CallWznmOpxAinvMod.opxEq");
if (ix == CALLWZNMOPXARETMOD_CLUEQ) return("CallWznmOpxAretMod.cluEq");
if (ix == CALLWZNMOPXARETMOD_OPXEQ) return("CallWznmOpxAretMod.opxEq");
if (ix == CALLWZNMOPXMOD) return("CallWznmOpxMod");
if (ix == CALLWZNMOPXMOD_OPKEQ) return("CallWznmOpxMod.opkEq");
if (ix == CALLWZNMOPXUPD_REFEQ) return("CallWznmOpxUpd.refEq");
if (ix == CALLWZNMPNL_CAREQ) return("CallWznmPnl.carEq");
if (ix == CALLWZNMPNL_JOBEQ) return("CallWznmPnl.jobEq");
if (ix == CALLWZNMPNL_RETEQ) return("CallWznmPnl.retEq");
if (ix == CALLWZNMPNL_REUEQ) return("CallWznmPnl.reuEq");
if (ix == CALLWZNMPNLMOD) return("CallWznmPnlMod");
if (ix == CALLWZNMPNLMOD_CAREQ) return("CallWznmPnlMod.carEq");
if (ix == CALLWZNMPNLMOD_RETREUEQ) return("CallWznmPnlMod.retReuEq");
if (ix == CALLWZNMPNLRQRYMOD_PNLEQ) return("CallWznmPnlRqryMod.pnlEq");
if (ix == CALLWZNMPNLRQRYMOD_QRYEQ) return("CallWznmPnlRqryMod.qryEq");
if (ix == CALLWZNMPNLUPD_REFEQ) return("CallWznmPnlUpd.refEq");
if (ix == CALLWZNMPRJ_VEREQ) return("CallWznmPrj.verEq");
if (ix == CALLWZNMPRJMOD) return("CallWznmPrjMod");
if (ix == CALLWZNMPRJUPD_REFEQ) return("CallWznmPrjUpd.refEq");
if (ix == CALLWZNMPRSADETMOD_PRSEQ) return("CallWznmPrsAdetMod.prsEq");
if (ix == CALLWZNMPRSJLNMMOD_PRSEQ) return("CallWznmPrsJlnmMod.prsEq");
if (ix == CALLWZNMPRSMOD) return("CallWznmPrsMod");
if (ix == CALLWZNMPRSRPRJMOD_PRJEQ) return("CallWznmPrsRprjMod.prjEq");
if (ix == CALLWZNMPRSRPRJMOD_PRSEQ) return("CallWznmPrsRprjMod.prsEq");
if (ix == CALLWZNMPRSUPD_REFEQ) return("CallWznmPrsUpd.refEq");
if (ix == CALLWZNMPST_RETEQ) return("CallWznmPst.retEq");
if (ix == CALLWZNMPST_REUEQ) return("CallWznmPst.reuEq");
if (ix == CALLWZNMPST_VEREQ) return("CallWznmPst.verEq");
if (ix == CALLWZNMPSTJTITMOD_PSTEQ) return("CallWznmPstJtitMod.pstEq");
if (ix == CALLWZNMPSTMOD) return("CallWznmPstMod");
if (ix == CALLWZNMPSTMOD_RETREUEQ) return("CallWznmPstMod.retReuEq");
if (ix == CALLWZNMPSTMOD_VEREQ) return("CallWznmPstMod.verEq");
if (ix == CALLWZNMPSTUPD_REFEQ) return("CallWznmPstUpd.refEq");
if (ix == CALLWZNMQCO_QRYEQ) return("CallWznmQco.qryEq");
if (ix == CALLWZNMQCO_STBEQ) return("CallWznmQco.stbEq");
if (ix == CALLWZNMQCOJSTBMOD_QCOEQ) return("CallWznmQcoJstbMod.qcoEq");
if (ix == CALLWZNMQCOMOD) return("CallWznmQcoMod");
if (ix == CALLWZNMQCOMOD_QRYEQ) return("CallWznmQcoMod.qryEq");
if (ix == CALLWZNMQCOMOD_TCOEQ) return("CallWznmQcoMod.tcoEq");
if (ix == CALLWZNMQCOUPD_REFEQ) return("CallWznmQcoUpd.refEq");
if (ix == CALLWZNMQMD_PSTEQ) return("CallWznmQmd.pstEq");
if (ix == CALLWZNMQMD_QRYEQ) return("CallWznmQmd.qryEq");
if (ix == CALLWZNMQMD_RETEQ) return("CallWznmQmd.retEq");
if (ix == CALLWZNMQMD_REUEQ) return("CallWznmQmd.reuEq");
if (ix == CALLWZNMQMDMOD) return("CallWznmQmdMod");
if (ix == CALLWZNMQMDMOD_PSTEQ) return("CallWznmQmdMod.pstEq");
if (ix == CALLWZNMQMDMOD_QRYEQ) return("CallWznmQmdMod.qryEq");
if (ix == CALLWZNMQMDMOD_RETREUEQ) return("CallWznmQmdMod.retReuEq");
if (ix == CALLWZNMQMDUPD_REFEQ) return("CallWznmQmdUpd.refEq");
if (ix == CALLWZNMQRY_JOBEQ) return("CallWznmQry.jobEq");
if (ix == CALLWZNMQRY_SUPEQ) return("CallWznmQry.supEq");
if (ix == CALLWZNMQRY_VEREQ) return("CallWznmQry.verEq");
if (ix == CALLWZNMQRYACSEMOD_QMDEQ) return("CallWznmQryAcseMod.qmdEq");
if (ix == CALLWZNMQRYACSEMOD_QRYEQ) return("CallWznmQryAcseMod.qryEq");
if (ix == CALLWZNMQRYAORDMOD_QRYEQ) return("CallWznmQryAordMod.qryEq");
if (ix == CALLWZNMQRYMOD) return("CallWznmQryMod");
if (ix == CALLWZNMQRYMOD_SUPEQ) return("CallWznmQryMod.supEq");
if (ix == CALLWZNMQRYMOD_VEREQ) return("CallWznmQryMod.verEq");
if (ix == CALLWZNMQRYRTBLMOD_QRYEQ) return("CallWznmQryRtblMod.qryEq");
if (ix == CALLWZNMQRYRTBLMOD_TBLEQ) return("CallWznmQryRtblMod.tblEq");
if (ix == CALLWZNMQRYUPD_REFEQ) return("CallWznmQryUpd.refEq");
if (ix == CALLWZNMRECACCESS) return("CallWznmRecaccess");
if (ix == CALLWZNMREFPRESET) return("CallWznmRefPreSet");
if (ix == CALLWZNMREFSPRESET) return("CallWznmRefsPreSet");
if (ix == CALLWZNMREL_CLUEQ) return("CallWznmRel.cluEq");
if (ix == CALLWZNMREL_FRSEQ) return("CallWznmRel.frsEq");
if (ix == CALLWZNMREL_SUPEQ) return("CallWznmRel.supEq");
if (ix == CALLWZNMREL_TOSEQ) return("CallWznmRel.tosEq");
if (ix == CALLWZNMREL_VEREQ) return("CallWznmRel.verEq");
if (ix == CALLWZNMRELATITMOD_LOCEQ) return("CallWznmRelAtitMod.locEq");
if (ix == CALLWZNMRELATITMOD_RELEQ) return("CallWznmRelAtitMod.relEq");
if (ix == CALLWZNMRELMOD) return("CallWznmRelMod");
if (ix == CALLWZNMRELMOD_CLUEQ) return("CallWznmRelMod.cluEq");
if (ix == CALLWZNMRELMOD_FRTEQ) return("CallWznmRelMod.frtEq");
if (ix == CALLWZNMRELMOD_SUPEQ) return("CallWznmRelMod.supEq");
if (ix == CALLWZNMRELMOD_TOTEQ) return("CallWznmRelMod.totEq");
if (ix == CALLWZNMRELMOD_VEREQ) return("CallWznmRelMod.verEq");
if (ix == CALLWZNMRELUPD_REFEQ) return("CallWznmRelUpd.refEq");
if (ix == CALLWZNMREPTRSTART) return("CallWznmReptrStart");
if (ix == CALLWZNMREPTRSTOP) return("CallWznmReptrStop");
if (ix == CALLWZNMRLS_CMPEQ) return("CallWznmRls.cmpEq");
if (ix == CALLWZNMRLS_MCHEQ) return("CallWznmRls.mchEq");
if (ix == CALLWZNMRLSMOD) return("CallWznmRlsMod");
if (ix == CALLWZNMRLSMOD_CMPEQ) return("CallWznmRlsMod.cmpEq");
if (ix == CALLWZNMRLSMOD_MCHEQ) return("CallWznmRlsMod.mchEq");
if (ix == CALLWZNMRLSUPD_REFEQ) return("CallWznmRlsUpd.refEq");
if (ix == CALLWZNMRTBMOD) return("CallWznmRtbMod");
if (ix == CALLWZNMRTBMOD_RETREUEQ) return("CallWznmRtbMod.retReuEq");
if (ix == CALLWZNMRTBMOD_RTJEQ) return("CallWznmRtbMod.rtjEq");
if (ix == CALLWZNMRTBUPD_REFEQ) return("CallWznmRtbUpd.refEq");
if (ix == CALLWZNMRTDMOD) return("CallWznmRtdMod");
if (ix == CALLWZNMRTDMOD_BLKEQ) return("CallWznmRtdMod.blkEq");
if (ix == CALLWZNMRTDMOD_RTJEQ) return("CallWznmRtdMod.rtjEq");
if (ix == CALLWZNMRTDUPD_REFEQ) return("CallWznmRtdUpd.refEq");
if (ix == CALLWZNMRTJ_APPEQ) return("CallWznmRtj.appEq");
if (ix == CALLWZNMRTJ_JOBEQ) return("CallWznmRtj.jobEq");
if (ix == CALLWZNMRTJ_SUPEQ) return("CallWznmRtj.supEq");
if (ix == CALLWZNMRTJMOD) return("CallWznmRtjMod");
if (ix == CALLWZNMRTJMOD_APPEQ) return("CallWznmRtjMod.appEq");
if (ix == CALLWZNMRTJMOD_JOBEQ) return("CallWznmRtjMod.jobEq");
if (ix == CALLWZNMRTJMOD_SUPEQ) return("CallWznmRtjMod.supEq");
if (ix == CALLWZNMRTJUPD_REFEQ) return("CallWznmRtjUpd.refEq");
if (ix == CALLWZNMSBS_CAREQ) return("CallWznmSbs.carEq");
if (ix == CALLWZNMSBS_PSTEQ) return("CallWznmSbs.pstEq");
if (ix == CALLWZNMSBSATITMOD_LOCEQ) return("CallWznmSbsAtitMod.locEq");
if (ix == CALLWZNMSBSATITMOD_SBSEQ) return("CallWznmSbsAtitMod.sbsEq");
if (ix == CALLWZNMSBSMOD) return("CallWznmSbsMod");
if (ix == CALLWZNMSBSMOD_TBLEQ) return("CallWznmSbsMod.tblEq");
if (ix == CALLWZNMSBSRSBSMOD_ASBEQ) return("CallWznmSbsRsbsMod.asbEq");
if (ix == CALLWZNMSBSRSBSMOD_BSBEQ) return("CallWznmSbsRsbsMod.bsbEq");
if (ix == CALLWZNMSBSUPD_REFEQ) return("CallWznmSbsUpd.refEq");
if (ix == CALLWZNMSEQ_APPEQ) return("CallWznmSeq.appEq");
if (ix == CALLWZNMSEQMOD) return("CallWznmSeqMod");
if (ix == CALLWZNMSEQMOD_APPEQ) return("CallWznmSeqMod.appEq");
if (ix == CALLWZNMSEQUPD_REFEQ) return("CallWznmSeqUpd.refEq");
if (ix == CALLWZNMSESMOD) return("CallWznmSesMod");
if (ix == CALLWZNMSESMOD_USREQ) return("CallWznmSesMod.usrEq");
if (ix == CALLWZNMSESUPD_REFEQ) return("CallWznmSesUpd.refEq");
if (ix == CALLWZNMSGE_FNXEQ) return("CallWznmSge.fnxEq");
if (ix == CALLWZNMSGE_JOBEQ) return("CallWznmSge.jobEq");
if (ix == CALLWZNMSGE_SNXEQ) return("CallWznmSge.snxEq");
if (ix == CALLWZNMSGE_SQKEQ) return("CallWznmSge.sqkEq");
if (ix == CALLWZNMSGECHG) return("CallWznmSgeChg");
if (ix == CALLWZNMSGEMOD) return("CallWznmSgeMod");
if (ix == CALLWZNMSGEMOD_JOBEQ) return("CallWznmSgeMod.jobEq");
if (ix == CALLWZNMSGEUPD_REFEQ) return("CallWznmSgeUpd.refEq");
if (ix == CALLWZNMSHRDATCHG) return("CallWznmShrdatChg");
if (ix == CALLWZNMSNSMOD) return("CallWznmSnsMod");
if (ix == CALLWZNMSNSMOD_CALEQ) return("CallWznmSnsMod.calEq");
if (ix == CALLWZNMSNSMOD_JOBEQ) return("CallWznmSnsMod.jobEq");
if (ix == CALLWZNMSNSUPD_REFEQ) return("CallWznmSnsUpd.refEq");
if (ix == CALLWZNMSQKJTITMOD_SQKEQ) return("CallWznmSqkJtitMod.sqkEq");
if (ix == CALLWZNMSQKMOD) return("CallWznmSqkMod");
if (ix == CALLWZNMSQKMOD_RETREUEQ) return("CallWznmSqkMod.retReuEq");
if (ix == CALLWZNMSQKRSTBMOD_SQKEQ) return("CallWznmSqkRstbMod.sqkEq");
if (ix == CALLWZNMSQKRSTBMOD_STBEQ) return("CallWznmSqkRstbMod.stbEq");
if (ix == CALLWZNMSQKUPD_REFEQ) return("CallWznmSqkUpd.refEq");
if (ix == CALLWZNMSREFPRESET) return("CallWznmSrefPreSet");
if (ix == CALLWZNMSTATCHG) return("CallWznmStatChg");
if (ix == CALLWZNMSTB_SBSEQ) return("CallWznmStb.sbsEq");
if (ix == CALLWZNMSTB_TCOEQ) return("CallWznmStb.tcoEq");
if (ix == CALLWZNMSTBMOD) return("CallWznmStbMod");
if (ix == CALLWZNMSTBMOD_TBLEQ) return("CallWznmStbMod.tblEq");
if (ix == CALLWZNMSTBRSTBMOD_SUBEQ) return("CallWznmStbRstbMod.subEq");
if (ix == CALLWZNMSTBRSTBMOD_SUPEQ) return("CallWznmStbRstbMod.supEq");
if (ix == CALLWZNMSTBUPD_REFEQ) return("CallWznmStbUpd.refEq");
if (ix == CALLWZNMSTE_SEQEQ) return("CallWznmSte.seqEq");
if (ix == CALLWZNMSTEAACTMOD_STEEQ) return("CallWznmSteAactMod.steEq");
if (ix == CALLWZNMSTEATRGMOD_STEEQ) return("CallWznmSteAtrgMod.steEq");
if (ix == CALLWZNMSTEMOD) return("CallWznmSteMod");
if (ix == CALLWZNMSTEMOD_SEQEQ) return("CallWznmSteMod.seqEq");
if (ix == CALLWZNMSTEUPD_REFEQ) return("CallWznmSteUpd.refEq");
if (ix == CALLWZNMSTGCHG) return("CallWznmStgChg");
if (ix == CALLWZNMSTRJCNDMOD_STEATRGEQ) return("CallWznmStrJcndMod.steAtrgEq");
if (ix == CALLWZNMSTUBCHG) return("CallWznmStubChg");
if (ix == CALLWZNMSUSPSESS) return("CallWznmSuspsess");
if (ix == CALLWZNMTAG_CPBEQ) return("CallWznmTag.cpbEq");
if (ix == CALLWZNMTAGJTITMOD_TAGEQ) return("CallWznmTagJtitMod.tagEq");
if (ix == CALLWZNMTAGMOD) return("CallWznmTagMod");
if (ix == CALLWZNMTAGMOD_CPBEQ) return("CallWznmTagMod.cpbEq");
if (ix == CALLWZNMTAGUPD_REFEQ) return("CallWznmTagUpd.refEq");
if (ix == CALLWZNMTBL_CAREQ) return("CallWznmTbl.carEq");
if (ix == CALLWZNMTBL_INSBS) return("CallWznmTbl.inSbs");
if (ix == CALLWZNMTBL_PSTEQ) return("CallWznmTbl.pstEq");
if (ix == CALLWZNMTBL_RETEQ) return("CallWznmTbl.retEq");
if (ix == CALLWZNMTBL_REUEQ) return("CallWznmTbl.reuEq");
if (ix == CALLWZNMTBL_TYPEQ) return("CallWznmTbl.typEq");
if (ix == CALLWZNMTBL_VEREQ) return("CallWznmTbl.verEq");
if (ix == CALLWZNMTBLALFCMOD_TBLEQ) return("CallWznmTblAlfcMod.tblEq");
if (ix == CALLWZNMTBLATITMOD_LOCEQ) return("CallWznmTblAtitMod.locEq");
if (ix == CALLWZNMTBLATITMOD_TBLEQ) return("CallWznmTblAtitMod.tblEq");
if (ix == CALLWZNMTBLMOD) return("CallWznmTblMod");
if (ix == CALLWZNMTBLMOD_RETREUEQ) return("CallWznmTblMod.retReuEq");
if (ix == CALLWZNMTBLMOD_VEREQ) return("CallWznmTblMod.verEq");
if (ix == CALLWZNMTBLRVECMOD_TBLEQ) return("CallWznmTblRvecMod.tblEq");
if (ix == CALLWZNMTBLRVECMOD_VECEQ) return("CallWznmTblRvecMod.vecEq");
if (ix == CALLWZNMTBLUPD_REFEQ) return("CallWznmTblUpd.refEq");
if (ix == CALLWZNMTCO_FCTEQ) return("CallWznmTco.fctEq");
if (ix == CALLWZNMTCO_FCUEQ) return("CallWznmTco.fcuEq");
if (ix == CALLWZNMTCO_INSBS) return("CallWznmTco.inSbs");
if (ix == CALLWZNMTCO_RELEQ) return("CallWznmTco.relEq");
if (ix == CALLWZNMTCO_SBSEQ) return("CallWznmTco.sbsEq");
if (ix == CALLWZNMTCO_TBL_INSBS) return("CallWznmTco.tbl.inSbs");
if (ix == CALLWZNMTCO_TBLEQ) return("CallWznmTco.tblEq");
if (ix == CALLWZNMTCOATITMOD_LOCEQ) return("CallWznmTcoAtitMod.locEq");
if (ix == CALLWZNMTCOATITMOD_TCOEQ) return("CallWznmTcoAtitMod.tcoEq");
if (ix == CALLWZNMTCOMOD) return("CallWznmTcoMod");
if (ix == CALLWZNMTCOMOD_FCTFCUEQ) return("CallWznmTcoMod.fctFcuEq");
if (ix == CALLWZNMTCOMOD_RELEQ) return("CallWznmTcoMod.relEq");
if (ix == CALLWZNMTCOMOD_TBLEQ) return("CallWznmTcoMod.tblEq");
if (ix == CALLWZNMTCOUPD_REFEQ) return("CallWznmTcoUpd.refEq");
if (ix == CALLWZNMTXTVALPRESET) return("CallWznmTxtvalPreSet");
if (ix == CALLWZNMUSGAACCMOD_USGEQ) return("CallWznmUsgAaccMod.usgEq");
if (ix == CALLWZNMUSGMOD) return("CallWznmUsgMod");
if (ix == CALLWZNMUSGUPD_REFEQ) return("CallWznmUsgUpd.refEq");
if (ix == CALLWZNMUSR_PRSEQ) return("CallWznmUsr.prsEq");
if (ix == CALLWZNMUSR_USGEQ) return("CallWznmUsr.usgEq");
if (ix == CALLWZNMUSRAACCMOD_USREQ) return("CallWznmUsrAaccMod.usrEq");
if (ix == CALLWZNMUSRJSTEMOD_USREQ) return("CallWznmUsrJsteMod.usrEq");
if (ix == CALLWZNMUSRMOD) return("CallWznmUsrMod");
if (ix == CALLWZNMUSRRUSGMOD_USGEQ) return("CallWznmUsrRusgMod.usgEq");
if (ix == CALLWZNMUSRRUSGMOD_USREQ) return("CallWznmUsrRusgMod.usrEq");
if (ix == CALLWZNMUSRUPD_REFEQ) return("CallWznmUsrUpd.refEq");
if (ix == CALLWZNMVEC_HKTEQ) return("CallWznmVec.hktEq");
if (ix == CALLWZNMVEC_HKUEQ) return("CallWznmVec.hkuEq");
if (ix == CALLWZNMVEC_INSBS) return("CallWznmVec.inSbs");
if (ix == CALLWZNMVEC_PSTEQ) return("CallWznmVec.pstEq");
if (ix == CALLWZNMVEC_TYPEQ) return("CallWznmVec.typEq");
if (ix == CALLWZNMVEC_VEREQ) return("CallWznmVec.verEq");
if (ix == CALLWZNMVECATITMOD_LOCEQ) return("CallWznmVecAtitMod.locEq");
if (ix == CALLWZNMVECATITMOD_VECEQ) return("CallWznmVecAtitMod.vecEq");
if (ix == CALLWZNMVECMOD) return("CallWznmVecMod");
if (ix == CALLWZNMVECMOD_HKTHKUEQ) return("CallWznmVecMod.hktHkuEq");
if (ix == CALLWZNMVECMOD_VEREQ) return("CallWznmVecMod.verEq");
if (ix == CALLWZNMVECUPD_REFEQ) return("CallWznmVecUpd.refEq");
if (ix == CALLWZNMVER_BVREQ) return("CallWznmVer.bvrEq");
if (ix == CALLWZNMVER_LOCEQ) return("CallWznmVer.locEq");
if (ix == CALLWZNMVER_PRJEQ) return("CallWznmVer.prjEq");
if (ix == CALLWZNMVER_STEEQ) return("CallWznmVer.steEq");
if (ix == CALLWZNMVERJMOD_VEREQ) return("CallWznmVerJMod.verEq");
if (ix == CALLWZNMVERJSTEMOD_VEREQ) return("CallWznmVerJsteMod.verEq");
if (ix == CALLWZNMVERMOD) return("CallWznmVerMod");
if (ix == CALLWZNMVERMOD_BVREQ) return("CallWznmVerMod.bvrEq");
if (ix == CALLWZNMVERMOD_PRJEQ) return("CallWznmVerMod.prjEq");
if (ix == CALLWZNMVERUPD_REFEQ) return("CallWznmVerUpd.refEq");
if (ix == CALLWZNMVIT_VECEQ) return("CallWznmVit.vecEq");
if (ix == CALLWZNMVITJMOD_VITEQ) return("CallWznmVitJMod.vitEq");
if (ix == CALLWZNMVITMOD) return("CallWznmVitMod");
if (ix == CALLWZNMVITMOD_VECEQ) return("CallWznmVitMod.vecEq");
if (ix == CALLWZNMVITUPD_REFEQ) return("CallWznmVitUpd.refEq");
return("");
};
| 60.881967 | 84 | 0.752168 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.