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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
330614f3c27b5b56c46f7d9136c9f5dd5e08c039 | 729 | cpp | C++ | source/Ch18/drill/Drill18_2.cpp | Atroox/UDProg-Introduction | ac0ddca66825480c0e3c8fe2d93ba2a57da4068f | [
"CC0-1.0"
] | null | null | null | source/Ch18/drill/Drill18_2.cpp | Atroox/UDProg-Introduction | ac0ddca66825480c0e3c8fe2d93ba2a57da4068f | [
"CC0-1.0"
] | null | null | null | source/Ch18/drill/Drill18_2.cpp | Atroox/UDProg-Introduction | ac0ddca66825480c0e3c8fe2d93ba2a57da4068f | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;
vector<int> gv {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
void f(vector<int> v)
{
vector<int> lv(10);
lv = v;
for (auto& a : lv)
cout << a << '\t';
cout << '\n';
vector<int> lv2 = v;
for (auto& a : lv2)
cout << a << '\t';
cout << '\n';
}
int fac(int n) { return n > 1 ? n * fac(n - 1) : 1; }
int main()
try {
// code
f(gv);
vector<int> vv(10);
for (int i = 0; i < vv.size(); ++i)
vv[i] = fac(i + 1);
f(vv);
}
catch(std::exception& e) {
std::cerr << "Exception: " << e.what() << '\n';
return 1;
}
catch(...) {
std::cerr << "Unknown exception\n";
return 2;
} | 17.357143 | 55 | 0.470508 | [
"vector"
] |
330cce7fae9c8f55ed4b7561fdba58d8d2fe566e | 3,590 | hxx | C++ | include/Algorithms.hxx | nilsalex/tensor-trees | 48b5b4f6932705bac7160bb3379f6066222f9b70 | [
"MIT"
] | null | null | null | include/Algorithms.hxx | nilsalex/tensor-trees | 48b5b4f6932705bac7160bb3379f6066222f9b70 | [
"MIT"
] | null | null | null | include/Algorithms.hxx | nilsalex/tensor-trees | 48b5b4f6932705bac7160bb3379f6066222f9b70 | [
"MIT"
] | null | null | null | #pragma once
#include <functional>
#include <map>
#include <set>
#include <gmpxx.h>
#include "Tree.hxx"
#include "Node.hxx"
std::string printTree (std::unique_ptr<Tree<Node>> const & tree);
std::string printTreeMaple (std::unique_ptr<Tree<Node>> const & tree);
std::string printBranchMaple (std::vector<Node *> const & branch);
std::string printForest (Forest<Node> const & f, size_t depth = 0);
std::unique_ptr<Tree<Node>> copyTree (std::unique_ptr<Tree<Node>> const & tree);
void multiplyTree (std::unique_ptr<Tree<Node>> & tree, mpq_class const & factor);
void exchangeTensorIndices (std::unique_ptr<Tree<Node>> & tree, std::map<char, char> const & exchange_map);
void applyTensorSymmetries (std::unique_ptr<Tree<Node>> & tree, int parity = 1);
void exchangeSymmetrizeTree (std::unique_ptr<Tree<Node>> & tree, std::map<char, char> const & exchange_map, int parity = 1);
void multiExchangeSymmetrizeTree (std::unique_ptr<Tree<Node>> & tree, std::vector<std::pair<std::map<char, char>, int>> const & exchange_map_set);
void redefineScalarsSym (std::unique_ptr<Tree<Node>> & tree);
void sortBranch (std::vector<Node *> & branch);
void sortTreeAndMerge (std::unique_ptr<Tree<Node>> & dst, std::unique_ptr<Tree<Node>> const & src);
void mergeTrees (std::unique_ptr<Tree<Node>> & dst, std::unique_ptr<Tree<Node>> const & src);
void canonicalizeTree (std::unique_ptr<Tree<Node>> & tree);
void insertBranch (std::unique_ptr<Tree<Node>> & dst, std::vector<Node *> & branch, size_t const node_number = 0);
void removeEmptyBranches (std::unique_ptr<Tree<Node>> & tree);
void removeZeroScalars (std::unique_ptr<Tree<Node>> & tree);
void sortForest (Forest<Node> & forest);
void sortTree (std::unique_ptr<Tree<Node>> & tree);
bool isTreeSorted (std::unique_ptr<Tree<Node>> const & tree);
std::set<size_t> getVariableSet (std::unique_ptr<Tree<Node>> const & tree);
std::map<size_t, size_t> getVariableMap (std::unique_ptr<Tree<Node>> const & tree);
void substituteVariables (std::unique_ptr<Tree<Node>> & tree, std::map<size_t, size_t> const & subs_map);
std::map<size_t, mpq_class> evaluateTree (std::unique_ptr<Tree<Node>> const & tree, std::map<char, char> const & eval_map, mpq_class prefactor = 1);
void shrinkForest (Forest<Node> & forest);
void setVariablesToZero (std::unique_ptr<Tree<Node>> & tree, std::set<size_t> const & variables);
void solveNumerical (std::vector<std::pair<std::unique_ptr<Tree<Node>> &, std::function< void (std::unique_ptr<Tree<Node>> const &, std::set<std::map<size_t, mpq_class>> &)>>> const & equations);
void reduceNumerical (std::unique_ptr<Tree<Node>> & tree, std::function< void (std::unique_ptr<Tree<Node>> const &, std::set<std::map<size_t, mpq_class>> &)> fun);
bool compareTrees (std::unique_ptr<Tree<Node>> const & tree1, std::unique_ptr<Tree<Node>> const & tree2);
void contractTreeWithEta (std::unique_ptr<Tree<Node>> & tree, char i1, char i2);
std::unique_ptr<Tree<Node>> eliminateSecondEta (std::unique_ptr<Tree<Node>> & tree, char i1, char i2);
Forest<Node> contractTreeWithEtaInner (std::unique_ptr<Tree<Node>> & tree, char i1, char i2);
void contractTreeWithEpsilon3 (std::unique_ptr<Tree<Node>> & tree, char m, char i1, char i2, char i3);
void multiplyTreeWithEta (std::unique_ptr<Tree<Node>> & tree, char i1, char i2);
void saveTree (std::unique_ptr<Tree<Node>> const & tree, std::string const & filename);
std::unique_ptr<Tree<Node>> loadTree (std::string const & filename);
bool checkSaveAndLoad (std::unique_ptr<Tree<Node>> const & tree);
void shiftVariables (std::unique_ptr<Tree<Node>> & tree, int i);
| 41.264368 | 195 | 0.723955 | [
"vector"
] |
33131307964a7b6a5b8fc27234a728566045e2cc | 5,038 | cc | C++ | tests/unit/base/SGObjectAll_unittest.cc | Arpit2601/shogun | e509f8c57f47dc74b3f791d450a70b770d11582a | [
"BSD-3-Clause"
] | 1 | 2019-10-02T11:10:08.000Z | 2019-10-02T11:10:08.000Z | tests/unit/base/SGObjectAll_unittest.cc | Arpit2601/shogun | e509f8c57f47dc74b3f791d450a70b770d11582a | [
"BSD-3-Clause"
] | null | null | null | tests/unit/base/SGObjectAll_unittest.cc | Arpit2601/shogun | e509f8c57f47dc74b3f791d450a70b770d11582a | [
"BSD-3-Clause"
] | 1 | 2020-06-02T09:15:40.000Z | 2020-06-02T09:15:40.000Z | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Heiko Strathmann
*/
#include "utils/Utils.h"
#include "utils/SGObjectIterator.h"
#include <gtest/gtest.h>
#include <iterator>
#include <shogun/base/ShogunEnv.h>
#include <shogun/base/Parameter.h>
#include <shogun/base/SGObject.h>
#include <shogun/base/class_list.h>
#include <shogun/base/range.h>
#include <shogun/base/some.h>
#include <shogun/io/fs/FileSystem.h>
#include <shogun/io/serialization/JsonSerializer.h>
#include <shogun/io/serialization/JsonDeserializer.h>
#include <shogun/io/stream/FileInputStream.h>
#include <shogun/io/stream/FileOutputStream.h>
using namespace shogun;
// list of classes that (currently) cannot be instantiated
std::set<std::string> sg_object_all_ignores = {"ParseBuffer", "Set",
"TreeMachine"};
// template arguments for SGObject
// TODO: SGString doesn't support complex128_t, so omitted here
typedef ::testing::Types<bool, char, int8_t, int16_t, int32_t, int64_t,
float32_t, float64_t, floatmax_t, untemplated_sgobject>
SGPrimitiveTypes;
template <typename T>
class SGObjectAll : public ::testing::Test
{
};
TYPED_TEST_CASE(SGObjectAll, SGPrimitiveTypes);
TYPED_TEST(SGObjectAll, sg_object_iterator)
{
for (auto obj : sg_object_iterator<TypeParam>())
{
ASSERT_NE(obj, nullptr);
SCOPED_TRACE(obj->get_name());
ASSERT_EQ(obj->ref_count(), 1);
}
}
TYPED_TEST(SGObjectAll, clone_basic)
{
for (auto obj : sg_object_iterator<TypeParam>().ignore(sg_object_all_ignores))
{
SCOPED_TRACE(obj->get_name());
CSGObject* clone = nullptr;
try
{
clone = obj->clone();
}
catch (...)
{
}
ASSERT_NE(clone, nullptr);
EXPECT_NE(clone, obj);
EXPECT_EQ(clone->ref_count(), 1);
EXPECT_EQ(std::string(clone->get_name()), std::string(obj->get_name()));
SG_UNREF(clone);
}
}
TYPED_TEST(SGObjectAll, clone_equals_empty)
{
for (auto obj : sg_object_iterator<TypeParam>().ignore(sg_object_all_ignores))
{
SCOPED_TRACE(obj->get_name());
CSGObject* clone = obj->clone();
EXPECT_TRUE(clone->equals(obj));
SG_UNREF(clone);
}
}
TYPED_TEST(SGObjectAll, serialization_empty_json)
{
for (auto obj : sg_object_iterator<TypeParam>().ignore(sg_object_all_ignores))
{
SCOPED_TRACE(obj->get_name());
std::string filename = "shogun-unittest-serialization-json-" +
std::string(obj->get_name()) + "_" +
sg_primitive_type_string<TypeParam>() +
".XXXXXX";
generate_temp_filename(const_cast<char*>(filename.c_str()));
SG_REF(obj);
auto fs = env();
ASSERT_FALSE(fs->file_exists(filename));
std::unique_ptr<io::WritableFile> file;
ASSERT_FALSE(fs->new_writable_file(filename, &file));
auto fos = some<io::CFileOutputStream>(file.get());
auto serializer = some<io::CJsonSerializer>();
serializer->attach(fos);
serializer->write(wrap<CSGObject>(obj));
std::unique_ptr<io::RandomAccessFile> raf;
ASSERT_FALSE(fs->new_random_access_file(filename, &raf));
auto fis = some<io::CFileInputStream>(raf.get());
auto deserializer = some<io::CJsonDeserializer>();
deserializer->attach(fis);
auto loaded = deserializer->read_object();
// set accuracy to tolerate lossy formats
env()->set_global_fequals_epsilon(1e-14);
ASSERT_TRUE(obj->equals(loaded));
env()->set_global_fequals_epsilon(0);
ASSERT_FALSE(fs->delete_file(filename));
}
}
// temporary test until old parameter framework is gone
// enable test to hunt for parameters not registered in tags
// see https://github.com/shogun-toolbox/shogun/issues/4117
// not typed as all template instantiations will have the same tags
TEST(SGObjectAll, DISABLED_tag_coverage)
{
auto class_names = available_objects();
for (auto class_name : class_names)
{
auto obj = create(class_name.c_str(), PT_NOT_GENERIC);
// templated classes cannot be created in the above way
if (!obj)
{
// only test single generic type here: all types have the same
// parameter names
obj = create(class_name.c_str(), PT_FLOAT64);
}
// obj must exist now, whether templated or not
ASSERT_NE(obj, nullptr);
// old parameter framework names
std::vector<std::string> old_names;
for (auto i : range(obj->m_parameters->get_num_parameters()))
old_names.push_back(obj->m_parameters->get_parameter(i)->m_name);
std::vector<std::string> tag_names;
std::transform(obj->get_params().cbegin(), obj->get_params().cend(), std::back_inserter(tag_names),
[](const std::pair<std::string, std::shared_ptr<const AnyParameter>>& each) -> std::string {
return each.first;
});
// hack to increase readability of error messages
old_names.push_back("_Shogun class: " + class_name);
tag_names.push_back("_Shogun class: " + class_name);
// comparing std::vector depends on order
std::sort(old_names.begin(), old_names.end());
std::sort(tag_names.begin(), tag_names.end());
EXPECT_EQ(tag_names, old_names);
SG_UNREF(obj);
}
}
| 29.121387 | 101 | 0.70524 | [
"vector",
"transform"
] |
331752e828c8412a1b536c323ed8cc5f84a91af2 | 25,114 | cpp | C++ | lib/stages/visAccumulate.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | null | null | null | lib/stages/visAccumulate.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | null | null | null | lib/stages/visAccumulate.cpp | eschnett/kotekan | 81918288147435cef8ad52db05da0988c999a7dd | [
"MIT"
] | null | null | null | #include "visAccumulate.hpp"
#include "Config.hpp" // for Config
#include "Hash.hpp" // for operator!=
#include "StageFactory.hpp" // for REGISTER_KOTEKAN_STAGE, StageMakerTemplate
#include "Telescope.hpp" // for Telescope
#include "buffer.h" // for register_producer, Buffer, allocate_new_metadata_object
#include "bufferContainer.hpp" // for bufferContainer
#include "chimeMetadata.hpp" // for chimeMetadata, get_dataset_id, get_fpga_seq_num, get_lo...
#include "configUpdater.hpp" // for configUpdater
#include "datasetManager.hpp" // for state_id_t, dset_id_t, datasetManager
#include "datasetState.hpp" // for eigenvalueState, freqState, gatingState, inputState
#include "factory.hpp" // for FACTORY
#include "kotekanLogging.hpp" // for FATAL_ERROR, INFO, logLevel, DEBUG
#include "metadata.h" // for metadataContainer
#include "prometheusMetrics.hpp" // for Counter, MetricFamily, Metrics
#include "version.h" // for get_git_commit_hash
#include "visBuffer.hpp" // for VisFrameView
#include "visUtil.hpp" // for prod_ctype, frameID, modulo, input_ctype, operator+
#include "fmt.hpp" // for format, fmt
#include "gsl-lite.hpp" // for span<>::iterator, span
#include "json.hpp" // for json, basic_json, iteration_proxy_value, basic_json<>::...
#include <algorithm> // for copy, max, fill, copy_backward, equal, transform
#include <assert.h> // for assert
#include <atomic> // for atomic_bool
#include <cmath> // for pow
#include <complex> // for operator*, complex
#include <cstring> // for memcpy
#include <exception> // for exception
#include <iterator> // for back_insert_iterator, begin, end, back_inserter
#include <mutex> // for lock_guard, mutex
#include <numeric> // for iota
#include <regex> // for match_results<>::_Base_type
#include <stdexcept> // for runtime_error, invalid_argument
#include <time.h> // for size_t, timespec
#include <tuple> // for get
#include <vector> // for vector, vector<>::iterator, __alloc_traits<>::value_type
using namespace std::placeholders;
using kotekan::bufferContainer;
using kotekan::Config;
using kotekan::configUpdater;
using kotekan::Stage;
using kotekan::prometheus::Metrics;
REGISTER_KOTEKAN_STAGE(visAccumulate);
visAccumulate::visAccumulate(Config& config, const std::string& unique_name,
bufferContainer& buffer_container) :
Stage(config, unique_name, buffer_container, std::bind(&visAccumulate::main_thread, this)),
skipped_frame_counter(Metrics::instance().add_counter(
"kotekan_visaccumulate_skipped_frame_total", unique_name, {"freq_id", "reason"})) {
auto& tel = Telescope::instance();
// Fetch any simple configuration
num_elements = config.get<size_t>(unique_name, "num_elements");
num_freq_in_frame = config.get_default<size_t>(unique_name, "num_freq_in_frame", 1);
block_size = config.get<size_t>(unique_name, "block_size");
samples_per_data_set = config.get<size_t>(unique_name, "samples_per_data_set");
max_age = config.get_default<float>(unique_name, "max_age", 60.0);
// Get the indices for reordering
auto input_reorder = parse_reorder_default(config, unique_name);
input_remap = std::get<0>(input_reorder);
float int_time = config.get_default<float>(unique_name, "integration_time", -1.0);
// If the integration time was set then calculate the number of GPU frames
// we need to integrate for.
if (int_time >= 0.0) {
float frame_length = samples_per_data_set * tel.seq_length_nsec() * 1e-9;
// Calculate nearest *even* number of frames
num_gpu_frames = 2 * ((int)(int_time / frame_length) / 2);
INFO("Integrating for {:d} gpu frames (={:.2f} s ~{:.2f} s)", num_gpu_frames,
frame_length * num_gpu_frames, int_time);
} else {
num_gpu_frames = config.get<size_t>(unique_name, "num_gpu_frames");
INFO("Integrating for {:d} gpu frames.", num_gpu_frames);
}
// Get the minimum number of samples for an output frame
float low_sample_fraction = config.get_default<float>(unique_name, "low_sample_fraction", 0.01);
minimum_samples = (size_t)(low_sample_fraction * num_gpu_frames * samples_per_data_set);
size_t nb = num_elements / block_size;
num_prod_gpu = num_freq_in_frame * nb * (nb + 1) * block_size * block_size / 2;
// Get everything we need for registering dataset states
// --> get metadata
std::string instrument_name =
config.get_default<std::string>(unique_name, "instrument_name", "chime");
std::vector<uint32_t> freq_ids;
// Get the frequency IDs that are on this stream, check the config or just
// assume all CHIME channels
if (config.exists(unique_name, "freq_ids")) {
freq_ids = config.get<std::vector<uint32_t>>(unique_name, "freq_ids");
} else {
freq_ids.resize(tel.num_freq());
std::iota(std::begin(freq_ids), std::end(freq_ids), 0);
}
// Create the frequency specification
std::vector<std::pair<uint32_t, freq_ctype>> freqs;
std::transform(std::begin(freq_ids), std::end(freq_ids), std::back_inserter(freqs),
[&tel](uint32_t id) -> std::pair<uint32_t, freq_ctype> {
return {id, {tel.to_freq(id), tel.freq_width(id)}};
});
// The input specification from the config
std::vector<input_ctype> inputs = std::get<1>(input_reorder);
size_t num_elements = inputs.size();
// Create the product specification
std::vector<prod_ctype> prods;
prods.reserve(num_elements * (num_elements + 1) / 2);
for (uint16_t i = 0; i < num_elements; i++) {
for (uint16_t j = i; j < num_elements; j++) {
prods.push_back({i, j});
}
}
// register base dataset states to prepare for getting dataset IDs for out frames
register_base_dataset_states(instrument_name, freqs, inputs, prods);
in_buf = get_buffer("in_buf");
register_consumer(in_buf, unique_name.c_str());
out_buf = get_buffer("out_buf");
register_producer(out_buf, unique_name.c_str());
// Create the state for the main visibility accumulation
gated_datasets.emplace_back(
out_buf, gateSpec::create("uniform", "vis", kotekan::logLevel(_member_log_level)),
num_prod_gpu);
// Get and validate any gating config
nlohmann::json gating_conf = config.get_default<nlohmann::json>(unique_name, "gating", {});
if (!gating_conf.empty() && !gating_conf.is_object()) {
FATAL_ERROR("Gating config must be a dictionary: {:s}", gating_conf.dump());
}
if (!gating_conf.empty() && num_freq_in_frame > 1) {
FATAL_ERROR("Cannot use gating with multifrequency GPU buffers[num_freq_in_frame={:d}; "
"gating config={:s}].",
num_freq_in_frame, gating_conf.dump());
}
// Register gating update callbacks
std::map<std::string, std::function<bool(nlohmann::json&)>> callbacks;
for (auto& it : gating_conf.items()) {
// Get the name of the gated dataset
std::string name = it.key();
// Validate and fetch the gating mode
try {
if (!it.value().at("mode").is_string()) {
throw std::invalid_argument(fmt::format(fmt("Config for gated dataset {:s} did "
"not have a valid mode argument: {:s}"),
name, it.value().dump()));
}
} catch (std::exception& e) {
FATAL_ERROR("Failure reading 'mode' from config: {:s}", e.what());
}
std::string mode = it.value().at("mode");
if (!FACTORY(gateSpec)::exists(mode)) {
FATAL_ERROR("Requested gating mode {:s} for dataset {:s} is not a known.", name, mode);
}
INFO("Creating gated dataset {:s} of type {:s}", name, mode);
// Validate and fetch the output buffer name
try {
if (!it.value().at("buf").is_string()) {
throw std::invalid_argument(fmt::format(fmt("Config for gated dataset {:s} did "
"not have a valid buf argument: {:s}"),
name, it.value().dump()));
}
} catch (std::exception& e) {
FATAL_ERROR("Failure reading 'buf' from config: {:s}", e.what());
}
std::string buffer_name = it.value().at("buf");
// Fetch and register the buffer
auto buf = buffer_container.get_buffer(buffer_name);
register_producer(buf, unique_name.c_str());
// Create the gated datasets and register the update callback
gated_datasets.emplace_back(
buf, gateSpec::create(mode, name, kotekan::logLevel(_member_log_level)), num_prod_gpu);
auto& state = gated_datasets.back();
callbacks[name] = [&state](nlohmann::json& json) -> bool {
bool success = state.spec->update_spec(json);
if (success) {
std::lock_guard<std::mutex> lock(state.state_mtx);
state.changed = true;
}
return success;
};
}
configUpdater::instance().subscribe(this, callbacks);
}
void visAccumulate::register_base_dataset_states(
std::string& instrument_name, std::vector<std::pair<uint32_t, freq_ctype>>& freqs,
std::vector<input_ctype>& inputs, std::vector<prod_ctype>& prods) {
// weight calculation is hardcoded, so is the weight type name
const std::string weight_type = "inverse_var";
const std::string git_tag = get_git_commit_hash();
// create all the states
base_dataset_states.push_back(dm.create_state<freqState>(freqs).first);
base_dataset_states.push_back(dm.create_state<inputState>(inputs).first);
base_dataset_states.push_back(dm.create_state<prodState>(prods).first);
base_dataset_states.push_back(dm.create_state<eigenvalueState>(0).first);
base_dataset_states.push_back(
dm.create_state<metadataState>(weight_type, instrument_name, git_tag).first);
}
dset_id_t visAccumulate::register_gate_dataset(const gateSpec& spec) {
// register with the datasetManager
state_id_t gstate_id = dm.create_state<gatingState>(spec).first;
// register gated dataset
return dm.add_dataset(gstate_id, base_dataset_id);
}
void visAccumulate::main_thread() {
frameID in_frame_id(in_buf);
dset_id_t ds_id_in = dset_id_t::null;
// Hold the gated datasets that are enabled;
std::vector<std::reference_wrapper<internalState>> enabled_gated_datasets;
uint32_t last_frame_count = 0;
uint32_t frames_in_this_cycle = 0;
// Temporary arrays for storing intermediates
std::vector<int32_t> vis_even(2 * num_prod_gpu);
int32_t samples_even = 0;
auto& tel = Telescope::instance();
// Have we initialised a frame for writing yet
bool init = false;
while (!stop_thread) {
// Fetch a new frame and get its sequence id
uint8_t* in_frame = wait_for_full_frame(in_buf, unique_name.c_str(), in_frame_id);
if (in_frame == nullptr)
break;
// Check if dataset ID changed
dset_id_t ds_id_in_new = get_dataset_id(in_buf, in_frame_id);
if (ds_id_in_new != ds_id_in) {
ds_id_in = ds_id_in_new;
// Register base dataset. If no dataset ID was was set in the incoming frame,
// ds_id_in will be dset_id_t::null and thus cause a root dataset to
// be registered.
base_dataset_id = dm.add_dataset(base_dataset_states, ds_id_in);
DEBUG("Registered base dataset: {}", base_dataset_id)
// Set the output dataset ID for the main visibility accumulation
gated_datasets.at(0).output_dataset_id = base_dataset_id;
}
int32_t* input = (int32_t*)in_frame;
uint64_t frame_count = (get_fpga_seq_num(in_buf, in_frame_id) / samples_per_data_set);
// Start and end times of this frame
timespec t_s = ((chimeMetadata*)in_buf->metadata[in_frame_id]->metadata)->gps_time;
timespec t_e = add_nsec(t_s, samples_per_data_set * tel.seq_length_nsec());
// If we have wrapped around we need to write out any frames that have
// been filled in previous iterations. In here we need to reorder the
// accumulates and do any final manipulations.
bool wrapped = (last_frame_count / num_gpu_frames) < (frame_count / num_gpu_frames);
if (init && wrapped) {
internalState& d0 = enabled_gated_datasets.at(0);
// Debias the weights estimate, by subtracting out the bias estimation
float w = d0.weight_diff_sum / pow(d0.sample_weight_total, 2);
for (size_t i = 0; i < num_prod_gpu; i++) {
float di = d0.vis1[2 * i];
float dr = d0.vis1[2 * i + 1];
d0.vis2[i] -= w * (dr * dr + di * di);
}
// Iterate over *only* the gated datasets (remember that element
// zero is the vis), and remove the bias and copy in the variance
for (size_t i = 1; i < enabled_gated_datasets.size(); i++) {
combine_gated(enabled_gated_datasets.at(i), d0);
}
// Finalise the output and release the frames
for (internalState& dset : enabled_gated_datasets) {
finalise_output(dset, t_s);
}
init = false;
frames_in_this_cycle = 0;
}
// We've started accumulating a new frame. Initialise the output and
// copy over any metadata.
if (frame_count % num_gpu_frames == 0) {
// Reset gated streams and find which ones are enabled for this period
enabled_gated_datasets.clear();
for (auto& state : gated_datasets) {
if (reset_state(state, t_s)) {
enabled_gated_datasets.push_back(state);
}
}
// For each dataset and frequency, claim an empty frame and initialise it...
for (internalState& dset : enabled_gated_datasets) {
// Initialise the output, if true is returned we need to exit
// the process as kotekan is shutting down
if (initialise_output(dset, in_frame_id)) {
return;
}
}
init = true;
}
// If we've got to here and we've not initialised we need to skip this frame.
if (init) {
// Get the amount of data in the frame
// TODO: for the multifrequency support this probably needs to become frequency
// dependent
int32_t lost_in_frame = get_lost_timesamples(in_buf, in_frame_id);
int32_t rfi_in_frame = get_rfi_flagged_samples(in_buf, in_frame_id);
// Assert that we haven't got an issue calculating the lost data
// This did happen when the RFI system was messing up.
assert(lost_in_frame >= 0);
assert(rfi_in_frame >= 0);
assert(samples_per_data_set >= (size_t)lost_in_frame);
assert(samples_per_data_set >= (size_t)rfi_in_frame);
int32_t samples_in_frame = samples_per_data_set - lost_in_frame;
// Accumulate the weighted data into each dataset. At the moment this
// doesn't really work if there are multiple frequencies in the same buffer..
for (internalState& dset : enabled_gated_datasets) {
float freq_in_MHz = tel.to_freq(dset.frames[0].freq_id);
float w = dset.calculate_weight(t_s, t_e, freq_in_MHz);
// Don't bother to accumulate if weight is zero
if (w == 0)
break;
// TODO: implement generalised non uniform weighting, I'm primarily
// not doing this because I don't want to burn cycles doing the
// multiplications
// Perform primary accumulation (assume that the weight is one)
for (size_t i = 0; i < 2 * num_prod_gpu; i++) {
dset.vis1[i] += input[i];
}
dset.sample_weight_total += samples_in_frame;
for (auto& frame : dset.frames) {
// Accumulate the samples/RFI
frame.fpga_seq_total += (uint32_t)samples_in_frame;
frame.rfi_total += (uint32_t)rfi_in_frame;
DEBUG("Lost samples {:d}, RFI flagged samples {:d}, total_samples: {:d}",
lost_in_frame, rfi_in_frame, frame.fpga_seq_total);
}
}
// We are calculating the weights by differencing even and odd samples.
// Every even sample we save the set of visibilities...
if (frame_count % 2 == 0) {
std::memcpy(vis_even.data(), input, 8 * num_prod_gpu);
samples_even = samples_in_frame;
}
// ... every odd sample we accumulate the squared differences into the weight dataset
// NOTE: this incrementally calculates the variance, but eventually
// output_frame.weight will hold the *inverse* variance
// TODO: we might need to account for packet loss in here too, but it
// would require some awkward rescalings
else {
internalState& d0 = enabled_gated_datasets.at(0); // Save into the main vis dataset
for (size_t i = 0; i < num_prod_gpu; i++) {
// NOTE: avoid using the slow std::complex routines in here
float di = input[2 * i] - vis_even[2 * i];
float dr = input[2 * i + 1] - vis_even[2 * i + 1];
d0.vis2[i] += (dr * dr + di * di);
}
// Accumulate the squared samples difference which we need for
// debiasing the variance estimate
float samples_diff = samples_in_frame - samples_even;
d0.weight_diff_sum += samples_diff * samples_diff;
}
}
// Move the input buffer on one step
mark_frame_empty(in_buf, unique_name.c_str(), in_frame_id++);
last_frame_count = frame_count;
frames_in_this_cycle++;
}
}
bool visAccumulate::initialise_output(visAccumulate::internalState& state, int in_frame_id) {
auto metadata = (const chimeMetadata*)in_buf->metadata[in_frame_id]->metadata;
for (size_t freq_ind = 0; freq_ind < num_freq_in_frame; freq_ind++) {
if (wait_for_empty_frame(state.buf, unique_name.c_str(), state.frame_id + freq_ind)
== nullptr) {
return true;
}
allocate_new_metadata_object(state.buf, state.frame_id + freq_ind);
VisFrameView::set_metadata(state.buf, state.frame_id + freq_ind, num_elements,
num_elements * (num_elements + 1) / 2, 0);
state.frames.emplace_back(state.buf, state.frame_id + freq_ind);
auto& frame = state.frames[freq_ind];
// Copy over the metadata
frame.fill_chime_metadata(metadata, freq_ind);
// Set dataset ID produced by the dM
frame.dataset_id = state.output_dataset_id;
// Set the length of time this frame will cover
frame.fpga_seq_length = samples_per_data_set * num_gpu_frames;
// Reset the total accumulated and RFI flagged samples
frame.fpga_seq_total = 0;
frame.rfi_total = 0;
// Fill other datasets with reasonable values
std::fill(frame.flags.begin(), frame.flags.end(), 1.0);
std::fill(frame.evec.begin(), frame.evec.end(), 0.0);
std::fill(frame.eval.begin(), frame.eval.end(), 0.0);
frame.erms = 0;
std::fill(frame.gain.begin(), frame.gain.end(), 1.0);
}
return false;
}
void visAccumulate::combine_gated(visAccumulate::internalState& gate,
visAccumulate::internalState& vis) {
// NOTE: getting all of these scaling right is a pain. At the moment they
// assume that within an `on` period the weights applied are one.
// Subtract out the bias from the gated data
float scl = gate.sample_weight_total / vis.sample_weight_total;
for (size_t i = 0; i < 2 * num_prod_gpu; i++) {
gate.vis1[i] -= (int32_t)(scl * vis.vis1[i]);
}
// TODO: very strong assumption that the weights are one (when on) baked in
// here.
gate.sample_weight_total = vis.sample_weight_total - gate.sample_weight_total;
// Copy in the proto weight data
for (size_t i = 0; i < num_prod_gpu; i++) {
gate.vis2[i] = scl * (1.0 - scl) * vis.vis2[i];
}
}
void visAccumulate::finalise_output(visAccumulate::internalState& state,
timespec newest_frame_time) {
// Determine the weighting factors (if weight is zero we should just
// multiply the visibilities by zero so as not to generate Infs)
float w = state.sample_weight_total;
float iw = (w != 0.0) ? (1.0 / w) : 0.0;
bool blocked = false;
// Loop over the frequencies in the frame and unpack the accumulates
// into the output frame...
for (size_t freq_ind = 0; freq_ind < num_freq_in_frame; freq_ind++) {
auto output_frame = state.frames[freq_ind];
// Check if we need to skip the frame.
//
// TODO: if we have multifrequencies, if any need to be skipped all of
// the following ones must be too. I think this requires the buffer
// mechanism being rewritten to fix this one.
if (ts_to_double(std::get<1>(output_frame.time) - newest_frame_time) > max_age) {
skipped_frame_counter.labels({std::to_string(output_frame.freq_id), "age"}).inc();
blocked = true;
continue;
}
if (output_frame.fpga_seq_total < minimum_samples) {
skipped_frame_counter.labels({std::to_string(output_frame.freq_id), "flagged"}).inc();
blocked = true;
continue;
} else if (blocked) {
// If we are here, an earlier frame was skipped and thus we have to
// throw this one away too. Mark it as skipped because it was
// blocked.
skipped_frame_counter.labels({std::to_string(output_frame.freq_id), "blocked"}).inc();
continue;
}
// Copy the visibilities into place
map_vis_triangle(input_remap, block_size, num_elements, freq_ind,
[&](int32_t pi, int32_t bi, bool conj) {
cfloat t = {(float)state.vis1[2 * bi + 1], (float)state.vis1[2 * bi]};
t = !conj ? t : std::conj(t);
output_frame.vis[pi] = iw * t;
});
// Unpack and invert the weights
map_vis_triangle(input_remap, block_size, num_elements, freq_ind,
[&](int32_t pi, int32_t bi, bool conj) {
(void)conj;
float t = state.vis2[bi];
output_frame.weight[pi] = w * w / t;
});
mark_frame_full(state.buf, unique_name.c_str(), state.frame_id++);
}
}
bool visAccumulate::reset_state(visAccumulate::internalState& state, timespec t) {
// Reset the internal counters
state.sample_weight_total = 0;
state.weight_diff_sum = 0;
// Acquire the lock so we don't get confused by any changes made via the
// REST callback
{
std::lock_guard<std::mutex> lock(state.state_mtx);
// Update the weight function in case an update arrives mid integration
// This is done every cycle to allow the calculation to change with time
// (without any external update), e.g. in SegmentedPolyco's.
if (!state.spec->enabled()) {
state.calculate_weight = nullptr;
return false;
}
state.calculate_weight = state.spec->weight_function(t);
// Update dataset ID if an external change occurred
if (state.changed) {
state.output_dataset_id = register_gate_dataset(*state.spec.get());
state.changed = false;
}
}
// Zero out accumulation arrays
std::fill(state.vis1.begin(), state.vis1.end(), 0.0);
std::fill(state.vis2.begin(), state.vis2.end(), 0.0);
// Remove all the old frame views
state.frames.clear();
return true;
}
visAccumulate::internalState::internalState(Buffer* out_buf, std::unique_ptr<gateSpec> gate_spec,
size_t nprod) :
buf(out_buf),
frame_id(buf),
spec(std::move(gate_spec)),
changed(true),
vis1(2 * nprod),
vis2(nprod) {}
| 41.305921 | 100 | 0.615075 | [
"vector",
"transform"
] |
332028c5a854d265a32093fcf5565d82bd6bba84 | 414 | hpp | C++ | include/sge/nodes/body.hpp | smaudet/sdl-game-engine | e49a001541c6e30c0cc0ee6aa04ee6ba2b5f4af7 | [
"MIT"
] | 75 | 2017-07-19T14:00:55.000Z | 2022-01-10T21:50:44.000Z | include/sge/nodes/body.hpp | smaudet/sdl-game-engine | e49a001541c6e30c0cc0ee6aa04ee6ba2b5f4af7 | [
"MIT"
] | 3 | 2017-04-05T00:57:33.000Z | 2018-11-14T07:48:40.000Z | include/sge/nodes/body.hpp | smaudet/sdl-game-engine | e49a001541c6e30c0cc0ee6aa04ee6ba2b5f4af7 | [
"MIT"
] | 12 | 2017-09-19T09:51:48.000Z | 2021-12-05T18:11:53.000Z | #ifndef __SGE_BODY_NODE_HPP
#define __SGE_BODY_NODE_HPP
#include <sge/nodes/position.hpp>
#include <sge/physics/manifold.hpp>
namespace sge
{
class BodyNode : public PositionNode
{
using PositionNode::PositionNode;
public:
virtual std::vector<std::string> mro() const;
virtual void colliding(const Manifold &manifold);
};
}
#endif /* __SGE_BODY_NODE_HPP */
| 19.714286 | 61 | 0.676329 | [
"vector"
] |
3322d3bdea98e9ca68f2018181a113e204de0cce | 244 | cpp | C++ | ProfessionalC++/VectorIterators/ConstIterator.cpp | zzragida/CppExamples | d627b097efc04209aa4012f7b7f9d82858da3f2d | [
"Apache-2.0"
] | null | null | null | ProfessionalC++/VectorIterators/ConstIterator.cpp | zzragida/CppExamples | d627b097efc04209aa4012f7b7f9d82858da3f2d | [
"Apache-2.0"
] | null | null | null | ProfessionalC++/VectorIterators/ConstIterator.cpp | zzragida/CppExamples | d627b097efc04209aa4012f7b7f9d82858da3f2d | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
vector<string> stringVector(10, "hello");
for (auto it = stringVector.cbegin();
it != stringVector.cend(); ++it)
{
cout << *it << endl;
}
}
| 14.352941 | 42 | 0.627049 | [
"vector"
] |
3328db4523cdcae44c3ac80da69c2eb08a08298b | 6,167 | cpp | C++ | 600-700/671.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 600-700/671.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | 600-700/671.cpp | Thomaw/Project-Euler | bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const int MAXN = 105;
const int P = 1000004321;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); }
template <typename T> void read(T &x) {
x = 0; int f = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
x *= f;
}
template <typename T> void write(T x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
write(x);
puts("");
}
int power(int x, int y) {
if (y == 0) return 1;
int tmp = power(x, y / 2);
if (y % 2 == 0) return 1ll * tmp * tmp % P;
else return 1ll * tmp * tmp % P * x % P;
}
void update(int &x, int y) {
x += y;
if (x >= P) x -= P;
}
namespace LinearSequence {
const int MAXN = 5005;
const int MAXLOG = 62;
const int P = 1000004321;
vector <int> a[MAXN];
int cnt, delta[MAXN], fail[MAXN];
int k, h[MAXN], now[MAXLOG][MAXN];
int power(int x, int y) {
if (y == 0) return 1;
int tmp = power(x, y / 2);
if (y % 2 == 0) return 1ll * tmp * tmp % P;
else return 1ll * tmp * tmp % P * x % P;
}
void times(int *res, int *x, int *y) {
static int tmp[MAXN];
memset(tmp, 0, sizeof(tmp));
for (int i = 0; i <= k - 1; i++)
for (int j = 0; j <= k - 1; j++)
tmp[i + j] = (tmp[i + j] + 1ll * x[i] * y[j]) % P;
for (int i = 2 * k - 2; i >= k; i--) {
int val = tmp[i]; tmp[i] = 0;
for (unsigned j = 0; j < a[cnt].size(); j++)
tmp[i - j - 1] = (tmp[i - j - 1] + 1ll * val * a[cnt][j]) % P;
}
memcpy(res, tmp, sizeof(tmp));
}
void init(int n, int *val) {
for (int i = 0; i <= cnt; i++)
a[i].clear();
cnt = 0;
for (int i = 1; i <= n; i++) {
delta[i] = val[i];
for (unsigned j = 0; j < a[cnt].size(); j++)
delta[i] = (delta[i] - 1ll * a[cnt][j] * val[i - j - 1] % P + P) % P;
if (delta[i] == 0) continue;
fail[cnt] = i;
if (cnt == 0) {
a[++cnt].resize(i);
continue;
}
int mul = 1ll * delta[i] * power(delta[fail[cnt - 1]], P - 2) % P;
a[cnt + 1].resize(i - fail[cnt - 1] - 1);
a[cnt + 1].push_back(mul);
for (unsigned j = 0; j < a[cnt - 1].size(); j++)
a[cnt + 1].push_back(1ll * a[cnt - 1][j] * (P - mul) % P);
if (a[cnt + 1].size() < a[cnt].size()) a[cnt + 1].resize(a[cnt].size());
for (unsigned j = 0; j < a[cnt].size(); j++)
a[cnt + 1][j] = (a[cnt + 1][j] + a[cnt][j]) % P;
cnt++;
}
if (n < 2 * a[cnt].size() + 5) {
cerr << "Failed!" << endl;
return;
}
memset(now, 0, sizeof(now));
k = a[cnt].size();
if (k == 1) now[0][0] = a[cnt][0];
else now[0][1] = 1;
for (int i = 1; i <= 2 * k; i++)
h[i] = val[i];
for (int p = 1; p < MAXLOG; p++)
times(now[p], now[p - 1], now[p - 1]);
}
int query(long long n) {
if (n <= k) return h[n]; n -= k;
static int res[MAXN];
memset(res, 0, sizeof(res));
res[0] = 1;
for (int p = 0; p < MAXLOG; p++) {
long long tmp = 1ll << p;
if (n & tmp) times(res, res, now[p]);
}
int ans = 0;
for (int i = 0; i <= k - 1; i++)
ans = (ans + 1ll * res[i] * h[i + k]) % P;
return ans;
}
}
struct State {int cola, colb, dista, distb; };
bool operator < (State a, State b) {
if (a.cola == b.cola) {
if (a.colb == b.colb) {
if (a.dista == b.dista) return a.distb < b.distb;
else return a.dista < b.dista;
} return a.colb < b.colb;
} return a.cola < b.cola;
}
int n, m, ans[MAXN];
map <State, int> mp[MAXN];
set <State> start;
void initstates() {
State now = (State) {0, 0, 0, 0};
for (int j = 1; j <= m; j++)
if (j != now.cola && j != now.colb) {
State res = now;
res.dista = res.distb = 0;
res.cola = res.colb = j;
start.insert(res);
}
for (int j = 1; j <= m; j++)
for (int dj = 1; dj <= 3; dj++)
for (int k = 1; k <= m; k++)
for (int dk = 1; dk <= 3; dk++)
if (j != k) {
State res = now;
res.dista = dj, res.distb = dk;
res.cola = j, res.colb = k;
res.dista--, res.distb--;
start.insert(res);
}
}
int main() {
n = 70, m = 10;
initstates();
int progress = 0;
for (auto s : start) {
for (int i = 0; i <= n; i++)
mp[i].clear();
mp[0][s] = 1;
for (int i = 1; i <= n; i++)
for (auto x : mp[i - 1]) {
State now = x.first;
if (now.dista == 0 && now.distb == 0) {
for (int j = 1; j <= m; j++)
if (j != now.cola && j != now.colb) {
State res = now;
res.dista = res.distb = 0;
res.cola = res.colb = j;
update(mp[i][res], x.second);
}
if (now.cola == now.colb) {
for (int j = 1; j <= m; j++)
for (int dj = 1; dj <= 3; dj++)
for (int k = 1; k <= m; k++)
for (int dk = 1; dk <= 3; dk++)
if (j != now.cola && k != now.colb && j != k) {
State res = now;
res.dista = dj, res.distb = dk;
res.cola = j, res.colb = k;
res.dista--, res.distb--;
update(mp[i][res], x.second);
}
}
} else if (now.dista == 0) {
for (int j = 1; j <= m; j++)
for (int dj = 1; dj <= 3; dj++)
if (j != now.cola && j != now.colb) {
State res = now;
res.dista = dj, res.cola = j;
res.dista--, res.distb--;
update(mp[i][res], x.second);
}
} else if (now.distb == 0) {
for (int j = 1; j <= m; j++)
for (int dj = 1; dj <= 3; dj++)
if (j != now.cola && j != now.colb) {
State res = now;
res.distb = dj, res.colb = j;
res.dista--, res.distb--;
update(mp[i][res], x.second);
}
} else {
now.dista--, now.distb--;
update(mp[i][now], x.second);
}
}
for (int i = 1; i <= n; i++)
update(ans[i], mp[i][s]);
cerr << "CalculationFinished " << ++progress << '/' << start.size() << endl;
}
LinearSequence :: init(n, ans);
ll N = 10004003002001ll;
int finalans = LinearSequence :: query(N);
writeln(1ll * finalans * power(N % P, P - 2) % P);
return 0;
} | 29.227488 | 79 | 0.471704 | [
"vector"
] |
06ac7011303c68570640936ddb0ecba22d02c335 | 1,558 | cpp | C++ | src/Core/Geometry/Lines.cpp | kokizzu/OmniPhotos | b8aa4c90b87b87b087bca8de3cf0e2b6d13f84da | [
"Apache-2.0"
] | 129 | 2020-12-13T02:22:05.000Z | 2022-03-22T02:45:39.000Z | src/Core/Geometry/Lines.cpp | kokizzu/OmniPhotos | b8aa4c90b87b87b087bca8de3cf0e2b6d13f84da | [
"Apache-2.0"
] | 4 | 2020-12-20T20:18:05.000Z | 2021-06-03T10:51:55.000Z | src/Core/Geometry/Lines.cpp | kokizzu/OmniPhotos | b8aa4c90b87b87b087bca8de3cf0e2b6d13f84da | [
"Apache-2.0"
] | 23 | 2020-12-15T15:11:18.000Z | 2022-03-18T00:15:30.000Z | #include "Lines.hpp"
#include "Core/GL/GLRenderModel.hpp"
#include "Core/Geometry/Primitive.hpp"
using namespace std;
// Uniform lines
Lines::Lines(const std::vector<float>& _vertices) :
GLRenderable(_vertices)
{
}
// Coloured lines
Lines::Lines(const std::vector<float>& _vertices, const std::vector<float>& _colours) :
GLRenderable(_vertices, _colours)
{
use_colour_buffer = true;
}
void Lines::createRenderModel(const std::string& _name)
{
int n_vertices = numberOfVertices(); // 3 float per vertex
int n_lines = n_vertices / 2; // come as pairs
GLRenderModel* model = getRenderModel();
if (!model)
model = new GLRenderModel(_name, make_shared<Primitive>(2 * n_lines, PrimitiveType::Line));
else
model->updateVertCnt(2 * n_lines);
//vertices
GLMemoryLayout memLayout = GLMemoryLayout(n_lines * 2, 3, "", "GL_FLOAT", "", 0, NULL);
GLBufferLayout bufLayout = GLBufferLayout(memLayout, 0);
model->glGenVBO(bufLayout);
model->glGenVAO();
glBindVertexArray(model->getVAO());
glBindBuffer(GL_ARRAY_BUFFER, model->getVertBufID());
glEnableVertexAttribArray(0);
model->setVertexAttrib(0);
model->setVertexBufferData(0, vertices.data());
//colour
bufLayout = GLBufferLayout(memLayout, 1);
glEnableVertexAttribArray(1);
model->glGenCBO(bufLayout);
glBindBuffer(GL_ARRAY_BUFFER, model->getPrimitive()->colourBuffer->gl_ID);
model->setColourAttrib(1);
model->setColourBufferData(0, colours.data());
glBindVertexArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
setRenderModel(model);
}
| 25.966667 | 93 | 0.740051 | [
"geometry",
"vector",
"model"
] |
06b4b53c10ec965059d7e07d5d91b157d9cd04cf | 5,677 | cpp | C++ | AtCoder/EduDP/W.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | AtCoder/EduDP/W.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | AtCoder/EduDP/W.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | // clang-format off
#include<bits/stdc++.h>
// g++ -std=c++17 -Wl,-stack_size -Wl,0x10000000 main.cpp
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1e18
#define MOD 1000000007
#define EPS 1e-6
#define ll long long int
#define ld long double
#define fi first
#define se second
#define all(v) v.begin(),v.end()
#define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;}
#define t1(x) cerr<<#x<<" : "<<x<<endl
#define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl
#define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)
#define _ cerr<<"here"<<endl;
#define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template <ll> ostream& operator<<(ostream& os, const vector<ll>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { if(v[i]!=INF) os << v[i]; else os << "INF";if (i != v.size() - 1) os << ", "; } os << "]"; return os; }
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; ;if (i != v.size() - 1) os << ", "; } os << "]"; return os; }
template <typename T> ostream& operator<<(ostream& os, const set<T>& s) {os << "{"; for(auto it : s) {if(it != *s.rbegin()) os << it << ", "; else os << it;} os << "}"; return os;}
template<class A, class B> ostream& operator<<(ostream& out, const pair<A, B> &a){ return out<<"("<<a.first<<", "<<a.second<<")";}
// clang-format on
ll max(ll x, ll y) { return x > y ? x : y; }
typedef struct node {
// Any variable
int beg = 0, end = 0;
// Default for null nodes
ll ans = -INF;
void assign(ll value) { ans = value; }
void update(ll value) { ans += value; }
void combine(node &n1, node &n2) { ans = max(n1.ans, n2.ans); }
ll query() { return ans; }
} node;
typedef struct SegTree {
int n;
vector<ll> a;
vector<ll> lazy;
vector<node> tree;
void init(int n) {
this->n = n;
a.resize(n);
lazy.resize(4 * n);
tree.resize(4 * n);
build(0, 0, n - 1);
}
void build(int pos, int l, int r) {
// if(l>=n || r<0) return;
tree[pos].beg = l, tree[pos].end = r;
if (l == r) {
tree[pos].assign(a[l]);
return;
}
int left = (pos << 1) + 1, right = left + 1, mid = (l + r) >> 1;
build(left, l, mid);
build(right, mid + 1, r);
tree[pos].combine(tree[left], tree[right]);
}
// Range update
void upd(int pos, int l, int r, ll x) {
lazy[pos] += x; // Associative lazy function
tree[pos].update(x); // How much this contributes to the node
}
void shift(int pos, int l, int r) {
if (lazy[pos] && l < r) {
int mid = (l + r) >> 1, left = (pos << 1) + 1, right = left + 1;
upd(left, l, mid, lazy[pos]);
upd(right, mid + 1, r, lazy[pos]);
lazy[pos] = 0; // Identity of the function
}
}
void update(int x, int y, ll val, int pos, int l, int r) {
// t(l,r,x,y);
if (l > y || r < x)
return;
if (l >= x && r <= y) {
upd(pos, l, r, val);
return;
}
shift(pos, l, r);
int left = (pos << 1) + 1, right = left + 1, mid = (l + r) >> 1;
update(x, y, val, left, l, mid);
update(x, y, val, right, mid + 1, r);
tree[pos].combine(tree[left], tree[right]);
}
void update(int x, int y, ll val) { update(x, y, val, 0, 0, n - 1); }
node query(int x, int y, int pos, int l, int r) {
node ans, n1, n2;
// if(l>y || r<x) return ans;
if (r < x || l > y)
return ans;
if (l >= x && r <= y)
return tree[pos];
shift(pos, l, r); // Only needed for lazy propagation
int left = (pos << 1) + 1, right = left + 1, mid = (l + r) >> 1;
n1 = query(x, y, left, l, mid);
n2 = query(x, y, right, mid + 1, r);
ans.combine(n1, n2);
return ans;
}
node query(int x, int y) { return query(x, y, 0, 0, n - 1); }
} SegTree;
int main() {
__;
int n, m;
cin >> n >> m;
vector<vector<pair<ll, int>>> intervalCost(n + 2);
while (m--) {
int l, r, a;
cin >> l >> r >> a;
intervalCost[l].push_back(make_pair(a, l - 1));
intervalCost[r + 1].push_back(make_pair(-a, l - 1));
}
SegTree segTree;
segTree.init(n + 1);
for (int i = 1; i <= n + 1; i++) {
for (auto cost : intervalCost[i])
segTree.update(0, cost.second, cost.first);
ll currVal = segTree.query(0, i - 1).query();
segTree.update(i, i, currVal);
}
cout << segTree.query(0, n).query() << "\n";
return 0;
}
/*
dp[i] = max_j dp[j] + C(j, i);
C(j, i) -> Weight of intervals starting within [l+1, r].
The effect of an interval starting at l affects the DP values from [0, l-1].
C(j, i+1) = C(j, i) + Intervals starting at i+1.
*/
| 32.815029 | 222 | 0.481064 | [
"vector"
] |
06c28b5d6ec8665d675444aa4252f3c93f6061ee | 1,584 | hpp | C++ | icon/endpoint/basic_endpoint/basic_endpoint.hpp | pblxptr/icon | 4426632bcc72f4f9fabfa5e23bf8b3d170632435 | [
"MIT"
] | null | null | null | icon/endpoint/basic_endpoint/basic_endpoint.hpp | pblxptr/icon | 4426632bcc72f4f9fabfa5e23bf8b3d170632435 | [
"MIT"
] | null | null | null | icon/endpoint/basic_endpoint/basic_endpoint.hpp | pblxptr/icon | 4426632bcc72f4f9fabfa5e23bf8b3d170632435 | [
"MIT"
] | null | null | null | #pragma once
#include <icon/icon.hpp>
#include <icon/core/identity.hpp>
#include <icon/core/protocol.hpp>
#include <icon/endpoint/base_endpoint.hpp>
#include <icon/endpoint/consumer_handler.hpp>
#include <icon/endpoint/endpoint.hpp>
#include <icon/endpoint/request.hpp>
#include <icon/endpoint/response.hpp>
#include <icon/protobuf/protobuf_serialization.hpp>
namespace icon::details {
class BasicEndpoint : public BaseEndpoint
{
public:
using BaseEndpoint::Raw_t;
using BaseEndpoint::RawBuffer_t;
using Serializer_t = icon::details::serialization::protobuf::ProtobufSerializer;
using Deserializer_t = icon::details::serialization::protobuf::ProtobufDeserializer;
using Request_t = EndpointRequest<Deserializer_t>;
using ConsumerHandlerBase_t = ConsumerHandler<BasicEndpoint, Request_t>;
BasicEndpoint(
zmq::context_t& zctx,
boost::asio::io_context& bctx,
std::vector<std::string> addresses,
std::unordered_map<size_t, std::unique_ptr<ConsumerHandlerBase_t>>
handlers);
template<MessageToSend Message>
awaitable<void> async_respond(const icon::details::core::Identity& identity,
Message&& message)
{
auto response = EndpointResponse<Message, Serializer_t>{ identity, std::forward<Message>(message) };
co_await async_send_base(std::move(response).build());
}
awaitable<void> run() override;
private:
awaitable<void> handle_recv(RawBuffer_t&&);
ConsumerHandlerBase_t* find_consumer(const size_t);
private:
std::unordered_map<size_t, std::unique_ptr<ConsumerHandlerBase_t>> handlers_;
};
}// namespace icon::details | 32.326531 | 104 | 0.766414 | [
"vector"
] |
06c8674ca6e0fb84c74653fcfe77c9877da97865 | 3,399 | cpp | C++ | src/Comment.cpp | EYH0602/Terminal-Facebook | 88dd4b692b43b491d877b2a0c79522f49a14e0c3 | [
"MIT"
] | null | null | null | src/Comment.cpp | EYH0602/Terminal-Facebook | 88dd4b692b43b491d877b2a0c79522f49a14e0c3 | [
"MIT"
] | null | null | null | src/Comment.cpp | EYH0602/Terminal-Facebook | 88dd4b692b43b491d877b2a0c79522f49a14e0c3 | [
"MIT"
] | null | null | null | #include "Comment.h"
using namespace std;
Comment::Comment(Json::Value jv_arg)
{
#ifdef _DEBUG_MEMORY_LEAK_
cout << "Comment Created" << endl;
#endif
// if this json is an array, exit
if (jv_arg.isArray())
throw runtime_error("Exception: Json Value is array (Comment)");
// get two ids
string id_part1 = jv_arg["id"].asString();
int pos = id_part1.find('_');
if (pos == -1) // spacial case: wrong id, exit
{
cerr << "Error: Invalid Post (Invalid ID)" << endl;
exit(1);
}
this->profile_id = id_part1.substr(0, pos);
string id_part2 = id_part1.substr(pos+1);
pos = id_part2.find('_');
if (pos == -1) // spacial case: wrong id, exit
{
cerr << "Error: Invalid Post (Invalid ID)" << endl;
exit(1);
}
this->post_id = id_part2.substr(0, pos);
this->comment_id = id_part2.substr(pos+1);
// get other attributes
this->author = new Person(jv_arg["from"]);
this->message = new Message(jv_arg["message"].asString());
this->created_time = new JvTime(jv_arg["created_time"].asString().c_str());
// get all reactions
// no need to check is reactions exists because of using for-each loop
this->reactions = new unordered_map<string, Reaction*>;
for(auto var : jv_arg["reactions"]["data"])
{
Reaction* a_reaction = new Reaction(var);
(*this->reactions)[a_reaction->getKey()] = a_reaction;
}
// get all tags
this->tags = new vector<Tag*> (0);
for(auto var : jv_arg["tags"]["data"])
this->tags->push_back(new Tag(var));
}
string Comment::getID()
{
return this->profile_id + "_" +
this->post_id + "_" +
this->comment_id;
}
CommentKeyPair Comment::getKeyPair()
{
return make_pair(this->comment_id, *this->created_time);
}
Comment* Comment::clone()
{
Comment* newComm = new Comment(this->toJson());
return newComm;
}
Json::Value Comment::toJson()
{
Json::Value myv;
myv["id"] = this->getID();
myv["from"] = this->author->toJson();
myv["message"] = this->message->toString();
myv["created_time"] = *this->created_time->getTimeString();
for (auto ptr: *this->reactions)
myv["reactions"]["data"].append(ptr.second->toJson());
myv["reactions"]["count"] = (int)this->reactions->size();
// if there is tag in this comment, need to parse them th Json
if (this->tags->size() > 0)
{
for(auto ptr: *this->tags)
myv["tags"]["data"].append(ptr->toJson());
myv["tags"]["count"] = (int)this->tags->size();
}
return myv;
}
void Comment::operator+=(const Comment& update)
{
// if there is update to the message, update the message
if (update.message)
*(this->message) = *(update.message);
// get all the new reactions
// if there is a new reaction with same key, just update it
for (auto var: *update.reactions)
(*this->reactions)[var.second->getKey()] = var.second->clone();
}
Comment::~Comment()
{
#ifdef _DEBUG_MEMORY_LEAK_
cout << "Comment Destructor Called" << endl;
#endif
delete this->author;
delete this->message;
delete this->created_time;
for (auto pt: *this->reactions)
delete pt.second;
delete this->reactions;
for (auto pt: *this->tags)
delete pt;
this->tags->clear();
delete this->tags;
}
| 27.192 | 79 | 0.601942 | [
"vector"
] |
06d19cab8c065c841f735b663a1706022716f69d | 24,008 | cc | C++ | tuplex/core/src/physical/HashJoinStage.cc | ms705/tuplex | c395041934768e51952c4fa783775b810b2fdec8 | [
"Apache-2.0"
] | 778 | 2021-06-30T03:40:43.000Z | 2022-03-28T20:40:20.000Z | tuplex/core/src/physical/HashJoinStage.cc | ms705/tuplex | c395041934768e51952c4fa783775b810b2fdec8 | [
"Apache-2.0"
] | 41 | 2021-07-05T17:55:56.000Z | 2022-03-31T15:27:19.000Z | tuplex/core/src/physical/HashJoinStage.cc | ms705/tuplex | c395041934768e51952c4fa783775b810b2fdec8 | [
"Apache-2.0"
] | 39 | 2021-07-01T02:40:33.000Z | 2022-03-30T21:46:55.000Z | //--------------------------------------------------------------------------------------------------------------------//
// //
// Tuplex: Blazing Fast Python Data Science //
// //
// //
// (c) 2017 - 2021, Tuplex team //
// Created by Leonhard Spiegelberg first on 1/1/2021 //
// License: Apache 2.0 //
//--------------------------------------------------------------------------------------------------------------------//
#include <physical/HashJoinStage.h>
#include <CodegenHelper.h>
namespace tuplex {
HashJoinStage::HashJoinStage(tuplex::PhysicalPlan *plan, tuplex::IBackend *backend, tuplex::PhysicalStage *left,
tuplex::PhysicalStage *right, int64_t leftKeyIndex, const python::Type &leftRowType,
int64_t rightKeyIndex, const python::Type &rightRowType, const tuplex::JoinType &jt,
int64_t stage_number, int64_t outputDataSetID) : PhysicalStage::PhysicalStage(plan,
backend,
stage_number,
{left,
right}),
_leftKeyIndex(leftKeyIndex),
_rightKeyIndex(rightKeyIndex),
_leftRowType(leftRowType),
_rightRowType(rightRowType),
_joinType(jt),
_outputDataSetID(outputDataSetID) {
}
// @TODO: reuse environment provided to TransformStage as well!
std::string HashJoinStage::generateCode() {
using namespace std;
auto env = make_shared<codegen::LLVMEnvironment>("tuplex_fastCodePath_hash");
// create probe function
using namespace llvm;
auto &context = env->getContext();
// arguments are 1.) userData 2.) the hashmap 3.) input ptr incl. number of rows...
FunctionType *FT = FunctionType::get(Type::getVoidTy(context),
{env->i8ptrType(), env->i8ptrType(), env->i8ptrType()}, false);
auto func = Function::Create(FT, llvm::GlobalValue::ExternalLinkage, probeFunctionName(),
env->getModule().get());
std::vector<llvm::Argument *> args;
vector<string> argNames{"userData", "hmap", "inputPtr"};
map<string, Value *> argMap;
int counter = 0;
for (auto &arg : func->args()) {
// first func arg is the ret Value, store separately!
arg.setName(argNames[counter]);
argMap[argNames[counter]] = &arg;
counter++;
}
BasicBlock *bbEntry = BasicBlock::Create(context, "entry", func);
IRBuilder<> builder(bbEntry);
Value *curPtrVar = builder.CreateAlloca(env->i8ptrType(), 0, nullptr);
builder.CreateStore(argMap["inputPtr"], curPtrVar);
Value *rowCounterVar = builder.CreateAlloca(env->i64Type(), 0, nullptr, "rowCounterVar");
builder.CreateStore(env->i64Const(0), rowCounterVar);
auto hashed_value = builder.CreateAlloca(env->i8ptrType(), 0, nullptr, "hashed_value");
builder.CreateStore(env->i8nullptr(), hashed_value);
// read num rows
Value *numRows = builder.CreateLoad(builder.CreatePointerCast(builder.CreateLoad(curPtrVar), env->i64ptrType()),
"numInputRows");
// move ptr by int64_t
builder.CreateStore(builder.CreateGEP(builder.CreateLoad(curPtrVar), env->i64Const(sizeof(int64_t))),
curPtrVar);
// set up
BasicBlock *bbLoopCondition = BasicBlock::Create(context, "loop_cond", func);
BasicBlock *bbLoopBody = BasicBlock::Create(context, "loop_body", func);
BasicBlock *bbLoopExit = BasicBlock::Create(context, "loop_done", func);
builder.CreateBr(bbLoopCondition);
// loop cond counter < numRows
builder.SetInsertPoint(bbLoopCondition);
auto cond = builder.CreateICmpSLT(builder.CreateLoad(rowCounterVar), numRows);
builder.CreateCondBr(cond, bbLoopBody, bbLoopExit);
// logic here...
builder.SetInsertPoint(bbLoopBody);
generateProbingCode(env, builder, argMap["userData"], argMap["hmap"], curPtrVar, hashed_value, rightType(),
rightKeyIndex(), leftType(), leftKeyIndex(), _joinType);
auto row_number = builder.CreateLoad(rowCounterVar);
//env->debugPrint(builder, "row number: ", row_number);
builder.CreateStore(builder.CreateAdd(env->i64Const(1), builder.CreateLoad(rowCounterVar)), rowCounterVar);
builder.CreateBr(bbLoopCondition);
// loop body done
builder.SetInsertPoint(bbLoopExit);
// rtfree all
env->freeAll(builder);
builder.CreateRetVoid();
return env->getIR();
}
void HashJoinStage::generateProbingCode(std::shared_ptr<codegen::LLVMEnvironment> &env, llvm::IRBuilder<> &builder,
llvm::Value *userData, llvm::Value *hashMap, llvm::Value *ptrVar,
llvm::Value *hashedValueVar, const python::Type &buildType,
int buildKeyIndex, const python::Type &probeType, int probeKeyIndex,
const tuplex::JoinType &jt) {
using namespace llvm;
assert(ptrVar->getType() == env->i8ptrType()->getPointerTo(0)); // i8**
assert(probeType.isTupleType());
auto &context = env->getContext();
auto &logger = Logger::instance().logger("codegen");
#ifndef NDEBUG
std::stringstream ss;
ss << "probe type: " << probeType.desc() << "\n";
ss << "build type: " << buildType.desc();
logger.info(ss.str());
#endif
if (probeType.parameters().size() < buildType.parameters().size())
logger.warn("sanity check: buildType seems bigger than probeType, reasonable?");
// deserialize tuple
codegen::FlattenedTuple ftIn(env.get());
ftIn.init(probeType);
auto curPtr = builder.CreateLoad(ptrVar);
ftIn.deserializationCode(builder, curPtr);
//// debug print first col
//env->debugPrint(builder, "first column: ", ftIn.get(0));
// get key column
assert(0 <= probeKeyIndex && probeKeyIndex < probeType.parameters().size());
auto probeKeyType = probeType.parameters()[probeKeyIndex];
auto keyCol = codegen::SerializableValue(ftIn.get(probeKeyIndex), ftIn.getSize(probeKeyIndex),
ftIn.getIsNull(probeKeyIndex));
// env->debugPrint(builder, "probe key column: ", keyCol.val);
// perform probing
auto key = makeKey(env, builder, probeKeyType, keyCol);
assert(key->getType() == env->i8ptrType());
// probe step
// hmap i8*, i8*, i8**
// old code
// FunctionType *hmap_func_type = FunctionType::get(Type::getInt32Ty(context),
// {env->i8ptrType(), env->i8ptrType(),
// env->i8ptrType()->getPointerTo(0)}, false);
// #if LLVM_VERSION_MAJOR < 9
// auto hmap_get_func = env->getModule()->getOrInsertFunction("hashmap_get", hmap_func_type);
// #else
// auto hmap_get_func = env->getModule()->getOrInsertFunction("hashmap_get", hmap_func_type).getCallee();
// #endif
// auto in_hash_map = builder.CreateCall(hmap_get_func, {hashMap, key, hashedValueVar});
// auto found_val = builder.CreateICmpEQ(in_hash_map, env->i32Const(0));
auto found_val = env->callBytesHashmapGet(builder, hashMap, key, nullptr, hashedValueVar);
// env->debugPrint(builder, "hmap_get result ", in_hash_map);
// env->debugPrint(builder, "found value in hashmap", found_val);
BasicBlock *bbMatchFound = BasicBlock::Create(context, "match_found", builder.GetInsertBlock()->getParent());
BasicBlock *bbNext = BasicBlock::Create(context, "next", builder.GetInsertBlock()->getParent());
// branch here on hashmap lookup ==> depends on join type
if (jt == JoinType::INNER)
builder.CreateCondBr(found_val, bbMatchFound, bbNext);
else if (jt == JoinType::LEFT) {
BasicBlock *bbNullMatch = BasicBlock::Create(context, "right_null", builder.GetInsertBlock()->getParent());
builder.CreateCondBr(found_val, bbMatchFound, bbNullMatch);
// left join. => If match found, then write join result i.e. general join result code from below.
// else: write NULL result
builder.SetInsertPoint(bbNullMatch);
writeBuildNullResult(env, builder, userData, buildType, buildKeyIndex, ftIn, probeKeyIndex);
builder.CreateBr(bbNext);
} else throw std::runtime_error("unknown join type seen in generateProbingCode");
builder.SetInsertPoint(bbMatchFound);
// call join code
writeJoinResult(env, builder, userData, builder.CreateLoad(hashedValueVar), buildType, buildKeyIndex, ftIn,
probeKeyIndex);
builder.CreateBr(bbNext);
builder.SetInsertPoint(bbNext);
// advance ptr
auto serializedSize = ftIn.getSize(builder); // should be 341 for the first row!
//env->debugPrint(builder, "serialized size:", serializedSize);
builder.CreateStore(builder.CreateGEP(curPtr, serializedSize), ptrVar);
}
llvm::Value *HashJoinStage::makeKey(std::shared_ptr<codegen::LLVMEnvironment> &env, llvm::IRBuilder<> &builder,
const python::Type &type, const tuplex::codegen::SerializableValue &key) {
using namespace llvm;
// create key for different types...
auto &context = env->getContext();
if (type == python::Type::STRING)
return key.val;
if (type == python::Type::makeOptionType(python::Type::STRING)) {
// a little more complicated because need to account for nullptr...
assert(key.val && key.is_null);
// TODO: special case for null should be prefixed row!
// i.e. separate null bucket!
// for now: "" is NULL "_" + val is for keys
auto skey_ptr = builder.CreateSelect(key.is_null, env->malloc(builder, env->i64Const(1)),
env->malloc(builder, builder.CreateAdd(key.size, env->i64Const(1))));
BasicBlock *bbNull = BasicBlock::Create(context, "key_is_null", builder.GetInsertBlock()->getParent());
BasicBlock *bbNotNull = BasicBlock::Create(context, "key_not_null", builder.GetInsertBlock()->getParent());
BasicBlock *bbNext = BasicBlock::Create(context, "probe", builder.GetInsertBlock()->getParent());
builder.CreateCondBr(key.is_null, bbNull, bbNotNull);
builder.SetInsertPoint(bbNull);
builder.CreateStore(env->i8Const(0), skey_ptr);
builder.CreateBr(bbNext);
builder.SetInsertPoint(bbNotNull);
builder.CreateStore(env->i8Const('_'), skey_ptr);
#if LLVM_VERSION_MAJOR < 9
builder.CreateMemCpy(builder.CreateGEP(skey_ptr, env->i64Const(1)), key.val, key.size, 0);
#else
builder.CreateMemCpy(builder.CreateGEP(skey_ptr, env->i64Const(1)), 0, key.val, 0, key.size);
#endif
builder.CreateBr(bbNext);
builder.SetInsertPoint(bbNext); // update builder var!
return skey_ptr;
}
throw std::runtime_error("internal error in makeKey " + std::string(__FILE__) + " unsupported type " + type.desc());
return nullptr;
}
void HashJoinStage::writeJoinResult(std::shared_ptr<codegen::LLVMEnvironment> &env,
llvm::IRBuilder<> &builder, llvm::Value *userData, llvm::Value *bucketPtr,
const python::Type &buildType, int buildKeyIndex,
const codegen::FlattenedTuple &ftProbe, int probeKeyIndex) {
using namespace llvm;
using namespace std;
auto &context = env->getContext();
auto func = builder.GetInsertBlock()->getParent();
//env->debugPrint(builder, "joining records with all from bucket :P");
auto numRows = builder.CreateLoad(builder.CreatePointerCast(bucketPtr, env->i64ptrType()));
// env->debugPrint(builder, "bucket contains #rows: ", numRows);
// note: in bucket structure can be further optimized! int64_t row_length = *((int64_t*)rightPtr);
// uint8_t* row_data = rightPtr + sizeof(int64_t);
// rightPtr += sizeof(int64_t) + row_length;
bucketPtr = builder.CreateGEP(bucketPtr, env->i64Const(sizeof(int64_t)));
// TODO: put bucketPtr Var in constructor
auto bucketPtrVar = env->CreateFirstBlockAlloca(builder,
env->i8ptrType()); //builder.CreateAlloca(env->i8ptrType(), 0, nullptr, "bucketPtrVar");
builder.CreateStore(bucketPtr, bucketPtrVar);
// loop over numRows
// TODO: put counter var in constructor block!
auto loopVar = env->CreateFirstBlockAlloca(builder,
env->i64Type()); //builder.CreateAlloca(env->i64Type(), 0, nullptr, "iBucketRowVar");
builder.CreateStore(env->i64Const(0), loopVar);
BasicBlock *bbLoopCond = BasicBlock::Create(context, "inbucket_loop_cond", func);
BasicBlock *bbLoopBody = BasicBlock::Create(context, "inbucket_loop_body", func);
BasicBlock *bbLoopDone = BasicBlock::Create(context, "inbucket_loop_done", func);
builder.CreateBr(bbLoopCond);
builder.SetInsertPoint(bbLoopCond);
auto cond = builder.CreateICmpSLT(builder.CreateLoad(loopVar), numRows);
builder.CreateCondBr(cond, bbLoopBody, bbLoopDone);
builder.SetInsertPoint(bbLoopBody);
bucketPtr = builder.CreateLoad(bucketPtrVar);
auto rowLength = builder.CreateLoad(builder.CreatePointerCast(bucketPtr, env->i64ptrType()));
bucketPtr = builder.CreateGEP(bucketPtr, env->i64Const(sizeof(int64_t)));
// actual data is now in bucketPtr
// ==> deserialize!
// env->debugPrint(builder, "row size is", rowLength);
// Now: deserialize probe row and build row
codegen::FlattenedTuple ftBuild(env.get());
ftBuild.init(buildType);
ftBuild.deserializationCode(builder, bucketPtr);
// print out probe key
// env->debugPrint(builder, "build key column: ", ftBuild.get(buildKeyIndex));
// combine into one row
codegen::FlattenedTuple ftResult(env.get());
ftResult.init(combinedType());
// add all from probe, then build
// !!! direction !!!
int pos = 0;
for (int i = 0; i < ftProbe.numElements(); ++i) {
if (i != probeKeyIndex)
ftResult.assign(pos++, ftProbe.get(i), ftProbe.getSize(i), ftProbe.getIsNull(i));
}
// add key from probe
ftResult.assign(pos, ftProbe.get(probeKeyIndex), ftProbe.getSize(probeKeyIndex),
ftProbe.getIsNull(probeKeyIndex));
pos++;
// add build elements
for (int i = 0; i < ftBuild.numElements(); ++i) {
if (i != buildKeyIndex) {
ftResult.assign(pos++, ftBuild.get(i), ftBuild.getSize(i), ftBuild.getIsNull(i));
//env->debugPrint(builder, "build column " + std::to_string(i) + ", value is: ", ftBuild.get(i));
//env->debugPrint(builder, "build column " + std::to_string(i) + ", size is: ", ftBuild.getSize(i));
//env->debugPrint(builder, "build column " + std::to_string(i) + ", isnull is: ", ftBuild.getIsNull(i));
}
}
auto buf = ftResult.serializeToMemory(builder);
// call writeRow function
FunctionType *writeCallback_type = FunctionType::get(codegen::ctypeToLLVM<int64_t>(context),
{codegen::ctypeToLLVM<void *>(context),
codegen::ctypeToLLVM<uint8_t *>(context),
codegen::ctypeToLLVM<int64_t>(context)}, false);
auto callback_func = env->getModule()->getOrInsertFunction(writeRowFunctionName(), writeCallback_type);
builder.CreateCall(callback_func, {userData, buf.val, buf.size});
// create combined row and write it to output!
// // ==> skip the key column
// // first all left cols, then all right cols
// std::vector<Field> fields;
// for(int i = 0; i < leftRow.getNumColumns(); ++i) {
// if(i != leftKeyIndex)
// fields.push_back(leftRow.get(i));
// }
// fields.push_back(leftRow.get(leftKeyIndex));
// for(int i = 0; i < rightRow.getNumColumns(); ++i) {
// if(i != rightKeyIndex)
// fields.push_back(rightRow.get(i));
// }
// logic here
// move bucketPtr
builder.CreateStore(builder.CreateGEP(builder.CreateLoad(bucketPtrVar),
builder.CreateAdd(env->i64Const(sizeof(int64_t)), rowLength)),
bucketPtrVar);
builder.CreateStore(builder.CreateAdd(builder.CreateLoad(loopVar), env->i64Const(1)), loopVar);
builder.CreateBr(bbLoopCond);
builder.SetInsertPoint(bbLoopDone);
// following is the code to join with data in bucket and write all rows to result partition
// // loop to put out all rows in bucket
// int64_t num_rows = *((int64_t*)value);
//
// uint8_t* rightPtr = (uint8_t*)value; rightPtr += sizeof(int64_t);
//
// auto rightSchema = Schema(Schema::MemoryLayout::ROW, hstage->rightType());
// for(int i = 0; i < num_rows; ++i) {
//
// int64_t row_length = *((int64_t*)rightPtr);
// uint8_t* row_data = rightPtr + sizeof(int64_t);
// rightPtr += sizeof(int64_t) + row_length;
//
// Row rightRow = Row::fromMemory(rightSchema,
// row_data, row_length); // value of hashmap is row length + actual value
//
// //std::cout<<"left row: "<<leftRow.toPythonString()<<" right row: "<<rightRow.toPythonString()<<std::endl;
//
// // create combined row and write it to output!
// // ==> skip the key column
// // first all left cols, then all right cols
// std::vector<Field> fields;
// for(int i = 0; i < leftRow.getNumColumns(); ++i) {
// if(i != leftKeyIndex)
// fields.push_back(leftRow.get(i));
// }
// fields.push_back(leftRow.get(leftKeyIndex));
// for(int i = 0; i < rightRow.getNumColumns(); ++i) {
// if(i != rightKeyIndex)
// fields.push_back(rightRow.get(i));
// }
// // create joined Row
// Row row = Row::from_vector(fields);
//
// // serialize out to partition writer
// pw.writeRow(row);
// }
}
void HashJoinStage::writeBuildNullResult(std::shared_ptr<codegen::LLVMEnvironment> &env, llvm::IRBuilder<> &builder,
llvm::Value *userData, const python::Type &buildType, int buildKeyIndex,
const tuplex::codegen::FlattenedTuple &ftProbe, int probeKeyIndex) {
// Write NULL values for the build row
using namespace llvm;
using namespace std;
auto &context = env->getContext();
auto func = builder.GetInsertBlock()->getParent();
// combine into one row
codegen::FlattenedTuple ftResult(env.get());
ftResult.init(combinedType());
codegen::FlattenedTuple ftBuild(env.get());
ftBuild.init(buildType);
// add all from probe, then build
// !!! direction !!!
int pos = 0;
for (int i = 0; i < ftProbe.numElements(); ++i) {
if (i != probeKeyIndex)
ftResult.assign(pos++, ftProbe.get(i), ftProbe.getSize(i), ftProbe.getIsNull(i));
}
// add key from probe
ftResult.assign(pos, ftProbe.get(probeKeyIndex), ftProbe.getSize(probeKeyIndex),
ftProbe.getIsNull(probeKeyIndex));
pos++;
// add build elements, i.e. simply NULL for all of them
for (int i = 0; i < ftBuild.numElements(); ++i) {
if (i != buildKeyIndex) {
ftResult.assign(pos++, nullptr, nullptr, env->i1Const(true));
}
}
auto buf = ftResult.serializeToMemory(builder);
// call writeRow function
FunctionType *writeCallback_type = FunctionType::get(codegen::ctypeToLLVM<int64_t>(context),
{codegen::ctypeToLLVM<void *>(context),
codegen::ctypeToLLVM<uint8_t *>(context),
codegen::ctypeToLLVM<int64_t>(context)}, false);
auto callback_func = env->getModule()->getOrInsertFunction(writeRowFunctionName(), writeCallback_type);
builder.CreateCall(callback_func, {userData, buf.val, buf.size});
}
} | 50.121086 | 144 | 0.522534 | [
"vector"
] |
06d3eca774071539c74ca6e78f3534e0157c8fe4 | 8,658 | cpp | C++ | Win32-Edit/Edit2.cpp | vectorlist/Win32-Fundamentals-Dev | 51cb2486f2e6f50737a9b5974ee7e4e24b57d860 | [
"MIT"
] | 1 | 2022-03-17T02:48:19.000Z | 2022-03-17T02:48:19.000Z | Win32-Edit/Edit2.cpp | vectorlist/Win32-Fundamentals-Dev | 51cb2486f2e6f50737a9b5974ee7e4e24b57d860 | [
"MIT"
] | null | null | null | Win32-Edit/Edit2.cpp | vectorlist/Win32-Fundamentals-Dev | 51cb2486f2e6f50737a9b5974ee7e4e24b57d860 | [
"MIT"
] | null | null | null | #pragma once
#define no_init_all
#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <iostream>
#include <vector>
#include <strsafe.h>
#include <Richedit.h>
#include <CommCtrl.h>
#pragma comment(lib, "comctl32.lib")
#pragma comment(linker, "\"/manifestdependency:type='win32' \
name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \
processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#include <../Common/Log.h>
#include <../Common/Wnd32.h>
#define WC_WINDOW "WC_WINDOW"
#define CWM_RTF_UPDATE (WM_APP + 401)
#define RTF_LINENUMBER_SPACING 50
LRESULT WINAPI WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
HWND mainHwnd;
HWND edit;
HWND button;
HGDIOBJ pObj[3];
WNDPROC preEditProc;
void SetTxtColor(HWND hwnd, COLORREF col);
void SetFont(HWND hWindow, const char * Font);
LRESULT OnLineNumberUpdate(WPARAM wp, LPARAM lp);
void DrawLineNumber(HDC dc);
LRESULT editProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
CHARFORMAT2 GetCharFormat(HWND hwnd) {
CHARFORMAT2 cf{};
cf.cbSize = sizeof(cf);
SendMessage(hwnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cf);
return cf;
}
int main(int args, char* argv[])
{
InitCommonControls();
HINSTANCE hInst = GetModuleHandle(NULL);
WNDCLASSEX wc{};
wc.cbSize = sizeof(wc);
wc.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);
wc.hInstance = hInst;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = WC_WINDOW;
wc.style = CS_VREDRAW | CS_HREDRAW;
wc.lpfnWndProc = WndProc;
GetClassInfoEx(wc.hInstance, wc.lpszClassName, &wc);
RegisterClassEx(&wc);
mainHwnd = CreateWindowEx(NULL, wc.lpszClassName, WC_WINDOW,
WS_POPUP | WS_VISIBLE | WS_CLIPCHILDREN , 600, 400, 760, 480, nullptr, 0, wc.hInstance, NULL);
wc.lpszClassName = WC_WINDOW;
wc.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH);
RegisterClassEx(&wc);
pObj[0] = CreateSolidBrush(RGB(33, 33, 33));
pObj[1] = CreatePen(PS_SOLID, 1, RGB(22, 22, 22));
lf lf{};
lf.lfHeight = 16;
lf.lfWeight = 0;
lf.lfCharSet = ANSI_CHARSET;
LPCSTR font = { "Consolas" };
memcpy(lf.lfFaceName, font, sizeof(CHAR) * strlen(font));
pObj[2] = CreateFontIndirect(&lf);
auto dll = LoadLibrary("riched20.dll");
edit = CreateWindowEx(NULL, RICHEDIT_CLASS, "",
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VISIBLE | WS_CHILD,
10, 10, 550, 360, mainHwnd, (HMENU)0, hInst, NULL);
preEditProc = (WNDPROC)SetWindowLongPtr(edit, GWLP_WNDPROC, (LONG_PTR)editProc);
RECT rc;
GetClientRect(edit, &rc);
rc.left += RTF_LINENUMBER_SPACING;
SendMessage(edit, EM_SETRECT, 0, (LONG)&rc);
SendMessage(edit, EM_SETBKGNDCOLOR, 0, RGB(32, 32, 32));
SetTxtColor(edit, RGB(220, 220, 220));
SetFont(edit, "Consolas");
DWORD evt = ENM_SELCHANGE | ENM_UPDATE | ENM_CHANGE;
SendMessage(edit, EM_SETEVENTMASK, 0, (LPARAM)evt);
//ENM_SELCHANGE
button = CreateWindowEx(NULL, WC_BUTTON, "Get Text",
WS_VISIBLE | WS_CHILD,
600, 200, 110, 30, mainHwnd, (HMENU)0, hInst, NULL);
//SendMessage(edit, WM_SETFONT, (WPARAM)pObj[2], 0);
ShowWindow(mainHwnd, TRUE);
UpdateWindow(mainHwnd);
//OnLineNumberUpdate(0, 0);
auto dc = GetDC(edit);
DrawLineNumber(dc);
ReleaseDC(edit, dc);
MSG msg{};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (dll) FreeLibrary(dll);
return msg.lParam;
}
void SetTxtColor(HWND hwnd, COLORREF col) {
CHARFORMAT cf{};
cf.cbSize = sizeof(cf);
cf.dwMask = CFM_COLOR;
cf.crTextColor = col;
cf.dwEffects = 0; // add this line
SendMessage(hwnd, EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cf);
LRESULT res;
}
void SetFont(HWND hWindow, const char* Font) {
CHARFORMAT2 cf;
memset(&cf, 0, sizeof cf);
cf.cbSize = sizeof cf;
cf.dwMask = CFM_FACE;
wsprintf(cf.szFaceName, Font);
SendMessage(hWindow, EM_SETCHARFORMAT, SCF_DEFAULT, (LPARAM)&cf);
}
int GetLineIndex(HWND hwnd, int line) {
return SendMessage(hwnd, EM_LINEINDEX, line, 0);
}
POINT GetCharPos(HWND hwnd, int index) {
POINT pos{};
SendMessage(hwnd, EM_POSFROMCHAR, (WPARAM)&pos, index);
return pos;
}
LRESULT OnLineNumberUpdate(WPARAM wp, LPARAM lp) {
RECT rc;
GetClientRect(edit, &rc);
rc.right = RTF_LINENUMBER_SPACING;
HDC dc = GetDC(edit);
//Wnd32::DrawFillRect(dc, rc, RGB(40, 100, 170));
auto br = CreateSolidBrush(RGB(55, 55, 58));
//ReleaseDC(edit, dc);
FillRect(dc, &rc, br);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, RGB(200, 50, 0));
int height = rc.bottom - rc.top;
int fvl = (int)SendMessage(edit, EM_GETFIRSTVISIBLELINE, 0, 0);
int lineCount = SendMessage(edit, EM_GETLINECOUNT, 0, 0);
POINT pt1 = GetCharPos(edit, GetLineIndex(edit, -1));
POINT pt2 = GetCharPos(edit, GetLineIndex(edit, fvl));
//DWORD pp = SendMessage(edit, EM_POSFROMCHAR, 0, (LPARAM)-1);
//POINT ppp{ LOWORD(pp), HIWORD(pp) };
RECT lineRc = rc;
lineRc.left += 10;
std::string msg;
CHAR buffer[128];
for (int i = fvl; i < lineCount;) {
lineRc.top = pt2.y + 4;
lineRc.bottom = pt2.y + 22;
if (lineRc.top > lineRc.bottom) break;
sprintf(buffer, "%ld", i + 1);
DrawText(dc, buffer, -1, &lineRc, DT_LEFT | DT_VCENTER);
pt2 = GetCharPos(edit,GetLineIndex(edit,++i));
if (pt2.y >= height) break;
}
//FillRect(dc, &rc, br);
DeleteObject(br);
return TRUE;
}
void DrawLineNumber(HDC dc) {
RECT rc;
GetClientRect(edit, &rc);
rc.right = RTF_LINENUMBER_SPACING;
SIZE size{ rc.right - rc.left, rc.bottom - rc.top };
HDC mem_dc = CreateCompatibleDC(dc);
HBITMAP hBmp = CreateCompatibleBitmap(dc, size.cx, size.cy);
HBITMAP hOldBmp = (HBITMAP)SelectObject(mem_dc, hBmp);
HBRUSH br = CreateSolidBrush(RGB(100, 100, 100));
//Wnd32::DrawFillRect(mem_dc, rc, RGB(100, 100, 100));
FillRect(mem_dc, &rc, br);
BitBlt(dc, rc.left, rc.top, size.cx, size.cy, mem_dc, 0, 0, SRCCOPY);
SelectObject(mem_dc, hOldBmp);
DeleteObject(hBmp);
DeleteDC(mem_dc);
DeleteObject(br);
}
LRESULT WINAPI WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case WM_NOTIFY: {
NMHDR* hdr = (LPNMHDR)lp;
MSGFILTER* filter = (MSGFILTER*)hdr;
if (hdr->code == EN_MSGFILTER) {
MSGFILTER* filter = (MSGFILTER*)hdr;
//printf("WM_ + %d\n", filter->msg);
LOG::LogWndMessage(filter->msg, 0);
}
if (hdr->code == EN_SELCHANGE) {
SELCHANGE* pSc = (SELCHANGE*)hdr;
printf("EN_SELCHANGE \n");
//return OnLineNumberUpdate(0, 0);
HDC dc = GetDC(edit);
DrawLineNumber(dc);
ReleaseDC(edit,dc);
break;
}
if (hdr->code == EN_CHANGE) {
printf("EN_CHANGE\n");
break;
}
//printf("WM_NOTIFY %s %d\n", Wnd32::GetHwndText(hdr->hwndFrom), hdr->code);
break;
}
case WM_COMMAND: {
if ((HWND)lp == edit) {
switch (HIWORD(wp))
{
case EN_UPDATE: {
printf("EN_UPDATE\n");
//OnLineNumberUpdate(0, 0);
RECT rc;
SendMessage(edit, EM_GETRECT, 0, (LPARAM)&rc);
//BOOL b = ValidateRect(edit, &rc);
//if (b) return b;
HDC dc = GetDC(edit);
DrawLineNumber(dc);
ReleaseDC(edit, dc);
//return TRUE;
//return 0;
break;
}
case EN_CHANGE: {
printf("EN_CHANGE\n");
HDC dc = GetDC(edit);
DrawLineNumber(dc);
ReleaseDC(edit, dc);
break;
}
}
//Sleep(100);
}
break;
}
case WM_SIZE: {
printf("WM_SIZE %s\n", Wnd32::GetHwndText(hwnd));
if (edit) {
RECT rc;
GetClientRect(edit, &rc);
rc.left += RTF_LINENUMBER_SPACING;
SendMessage(edit, EM_SETRECT, 0, (LPARAM)&rc);
printf("EM_SETRECT\n");
}
break;
}
case WM_PAINT: {
printf("WM_PAINT %s\n", Wnd32::GetHwndText(hwnd));
break;
}
}
return DefWindowProc(hwnd, msg, wp, lp);
}
LRESULT editProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case WM_PAINT: {
//HideCaret(hwnd);
//LRESULT ls = CallWindowProc(preEditProc, hwnd, msg, wp, lp);
//RECT rc;
//SendMessage(hwnd, EM_GETRECT, 0, (LONG)&rc);
//rc.left -= 1;
//rc.right += 1;
//HDC dc = GetDC(hwnd);
//Wnd32::DrawFillRect(dc, rc, RGB(32, 32, 32));
//SelectObject(dc, pObj[2]);
//auto txt = Wnd32::GetHwndText(hwnd);
//SetBkMode(dc, TRANSPARENT);
//SetTxtColor(hwnd, RGB(200, 0, 0));
//DrawText(dc, txt, -1, &rc, 0);
////TextOut(dc, 0, 0, txt, 0);
//ReleaseDC(hwnd, dc);
//printf("WM_PAINT\n");
//return OnLineNumberUpdate(wp, lp);
//return ls;
break;
}
case EM_SETCHARFORMAT: {
printf("EM_CHARFORMAT %d\n", wp);
break;
}
case WM_KEYDOWN: {
printf("WM_KEYDOWN\n");
break;
}
case CWM_RTF_UPDATE: {
OnLineNumberUpdate(wp, lp);
InvalidateRect(hwnd, NULL, FALSE);
printf("CWM_RTF_UPDATE\n");
break;
}
case WM_ERASEBKGND: {
printf("WM_ERASEBKGND\n");
//return 0;
break;
}
default:
break;
}
return CallWindowProc(preEditProc, hwnd, msg, wp, lp);
}
| 25.390029 | 96 | 0.677524 | [
"vector"
] |
06dca887bc7372853de39cce8777a5cac3f76111 | 1,680 | cpp | C++ | visplugin/GizmodLibVisualCInterface.cpp | pauljeremyturner/gizmod | 537b8c25360d907b1fde631336ccf723f38d4312 | [
"Apache-2.0"
] | null | null | null | visplugin/GizmodLibVisualCInterface.cpp | pauljeremyturner/gizmod | 537b8c25360d907b1fde631336ccf723f38d4312 | [
"Apache-2.0"
] | null | null | null | visplugin/GizmodLibVisualCInterface.cpp | pauljeremyturner/gizmod | 537b8c25360d907b1fde631336ccf723f38d4312 | [
"Apache-2.0"
] | null | null | null | /**
*********************************************************************
*************************************************************************
***
*** \file GizmodLibVisualCInterface.cpp
*** \brief GizmodLibVisualCInterface class body
***
*****************************************
*****************************************
**/
/*
Copyright (c) 2007, Tim Burrell
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 "GizmodLibVisualPlugin.hpp"
/////////////////////////////////////////////////////////////////////////////
// C interface
///////////////////////////////////////
/**
* The Plugin Object
**/
GizmodLibVisualPlugin Plugin;
extern "C" {
/**
* \brief Initialize
**/
void GizmodLibVisual_Init() {
Plugin.init();
}
/**
* \brief Clean up
**/
void GizmodLibVisual_CleanUp() {
Plugin.shutdown();
}
/**
* \brief Render the audio data
* \param VULeft VU information for the left channel
* \param VURight VU information for the right channel
* \param VUCombined VU information for both channels
**/
void GizmodLibVisual_Render(float VULeft, float VURight, float VUCombined) {
Plugin.render(VULeft, VURight, VUCombined);
}
}
| 24.705882 | 77 | 0.566667 | [
"render",
"object"
] |
06dcd009826fb82c622f0febb6a5be4122016706 | 1,405 | hpp | C++ | include/avatar_locomanipulation/helpers/pseudo_inverse.hpp | stevenjj/icra2020locomanipulation | 414085b68cc1b3b24f7b920b543bba9d95350c16 | [
"MIT"
] | 5 | 2020-01-06T11:43:18.000Z | 2021-12-14T22:59:09.000Z | include/avatar_locomanipulation/helpers/pseudo_inverse.hpp | stevenjj/icra2020locomanipulation | 414085b68cc1b3b24f7b920b543bba9d95350c16 | [
"MIT"
] | null | null | null | include/avatar_locomanipulation/helpers/pseudo_inverse.hpp | stevenjj/icra2020locomanipulation | 414085b68cc1b3b24f7b920b543bba9d95350c16 | [
"MIT"
] | 2 | 2020-09-03T16:08:34.000Z | 2022-02-17T11:13:49.000Z | #ifndef ALM_PSEUDOINVERSE
#define ALM_PSEUDOINVERSE
#include <Eigen/Dense>
#include <Eigen/SVD>
#include <vector>
namespace math_utils{
void pseudoInverse(const Eigen::MatrixXd & A,
Eigen::MatrixXd & Apinv,
double tolerance,
unsigned int computationOptions = Eigen::ComputeThinU | Eigen::ComputeThinV);
void pseudoInverse(const Eigen::MatrixXd & A,
Eigen::MatrixXd & Apinv,
std::vector<double> & singular_values,
double tolerance,
unsigned int computationOptions = Eigen::ComputeThinU | Eigen::ComputeThinV);
void pseudoInverse(const Eigen::MatrixXd & A,
Eigen::JacobiSVD<Eigen::MatrixXd>& svdDecomposition,
Eigen::MatrixXd & Apinv,
double tolerance,
unsigned int computationOptions = Eigen::ComputeThinU | Eigen::ComputeThinV);
void weightedPseudoInverse(const Eigen::MatrixXd & J, const Eigen::MatrixXd & Winv,
Eigen::MatrixXd & Jinv, double tolerance);
void weightedPseudoInverse(const Eigen::MatrixXd & J, const Eigen::MatrixXd & Winv,
Eigen::JacobiSVD<Eigen::MatrixXd> & svdDecomposition,
Eigen::MatrixXd & Jinv,
double tolerance);
}
#endif
| 39.027778 | 98 | 0.585765 | [
"vector"
] |
06e0c6955e9d36ed7ad0dfd5a110bbb9b4ce263f | 4,046 | hh | C++ | include/idf/DualShock3.hh | greck2908/IDF | 0882cc35d88b96b0aea55e112060779654f040a6 | [
"NASA-1.3"
] | 84 | 2016-06-15T21:26:02.000Z | 2022-03-12T15:09:57.000Z | include/idf/DualShock3.hh | greck2908/IDF | 0882cc35d88b96b0aea55e112060779654f040a6 | [
"NASA-1.3"
] | 44 | 2016-10-19T17:35:01.000Z | 2022-03-11T17:20:51.000Z | include/idf/DualShock3.hh | greck2908/IDF | 0882cc35d88b96b0aea55e112060779654f040a6 | [
"NASA-1.3"
] | 46 | 2016-06-25T00:18:52.000Z | 2019-12-19T11:13:15.000Z | /*
PURPOSE:
LIBRARY DEPENDENCIES: (
(idf/DualShock3.cpp)
)
*/
/**
* @trick_parse{everything}
* @trick_link_dependency{idf/DualShock3.cpp}
*/
#ifndef DUAL_SHOCK_3_HH
#define DUAL_SHOCK_3_HH
#include "idf/DualShock.hh"
#include "idf/SingleInput.hh"
namespace idf {
/**
* Sony DUALSHOCK3 SIXAXIS game controller's input layout
*
* @author Derek Bankieris
*/
class DualShock3 : public virtual DualShock {
public:
/** enumeration of the LEDs */
enum LED {One = 3, Two = 2, Three = 1, Four = 0};
/** constructor */
DualShock3();
/** destructor */
virtual ~DualShock3() {};
/** the button labeled select */
SingleInput selectButton;
/** the button labeled start */
SingleInput startButton;
void rumble(Rumbler rumbler, unsigned char data);
/**
* sets the portion of the command packet that corresponds to @a rumbler
*
* @param rumbler the rumble pack to command
* @param duration the length of the vibration in units of 20 ms. 0 = off, 255 = infinite
* @param intensity the magnitude of the vibration. 0 = off, 255 = maximum
*/
virtual void rumble(Rumbler rumbler, unsigned char duration, unsigned char intensity);
/**
* sets the specified @a led. The total cycle period is equal to
* <code>cyclePeriodInteger + cyclePeriodFraction / 256</code>. The actual
* on/off time is some combination of the total cycle period and the on and
* off factors, but documentation is sparse.
*
* @param led the led to command
* @param commandDuration the length of time, in units of 20 ms, that the
* command is valid, after which the LED turns off. 255 = infinite
* @param cyclePeriodInteger the integer portion of the cycle period
* @param cyclePeriodFraction the fractional portion of the cycle period in increments of 1 / 256
* @param offFactor multipled by the cycle period to determine how long the LED is off per cycle
* @param onFactor multipled by the cycle period to determine how long the LED is on per cycle
*/
virtual void setLed(LED led, unsigned char commandDuration,
unsigned char cyclePeriodInteger, unsigned char cyclePeriodFraction,
unsigned char offFactor, unsigned char onFactor);
protected:
/**
* rumble & LED command packet
*
* Rumble Pack Bytes
* report number: always 1
* | duration of weak (right) rumble, units = 20 ms, 0xff = infinity
* | | magnitude of weak (right) rumble
* | | | duration of strong (left) rumble, units = 20 ms, 0xff = infinity
* | | | | magnitude of strong (left) rumble
* | | | | |
* 0x01, 0xfe, 0xff, 0xfe, 0xff
*
* LED Bytes
* the total time this command is applied, after which the LED turns off, units = 20 ms, 0xff = infinity
* | integer part of the cycle period
* | | fractional part of the cycle period in increments of 1 / 256
* | | | multiplied by the cycle period to determine how long the LED is off per cycle
* | | | | multiplied by the cycle period to determine how long the LED is on per cycle
* | | | | |
* 0xff, 0x27, 0x10, 0x32, 0x32
*
* Command Packet Bytes
* 0 - 4 = rumble pack parameters
* 5 - 8 = unused
* 9 = bitwise OR of LEDs to be powered. LED1 = 2, LED2 = 4, LED3 = 8, LED4 = 16
* 10 - 14 = LED4 parameters
* 15 - 19 = LED3 parameters
* 20 - 24 = LED2 parameters
* 25 - 29 = LED1 parameters
*
* Per LED, a command different from it's current state takes effect immediately. Commands that do not
* change the state are ignored, and will not "reset" the LED's cycle. LEDs start their cycle in the off
* stage. Both rumble pack and all LED commands are initially zero.
*/
unsigned char command[30];
protected:
virtual const std::vector<Configurable>& getConfigurables();
};
}
#endif
| 33.438017 | 108 | 0.635195 | [
"vector"
] |
06e53b17a9fa5e7879d31975faba38a2cd983c77 | 3,019 | hpp | C++ | others/optimizers/particle_swarm_optimzer/optimizer_bits/pso/test_function/pso_test_function.hpp | CarbonDDR/al-go-rithms | 8e65affbe812931b7dde0e2933eb06c0f44b4130 | [
"CC0-1.0"
] | 1,253 | 2017-06-06T07:19:25.000Z | 2022-03-30T17:07:58.000Z | others/optimizers/particle_swarm_optimzer/optimizer_bits/pso/test_function/pso_test_function.hpp | rishabh99-rc/al-go-rithms | 4df20d7ef7598fda4bc89101f9a99aac94cdd794 | [
"CC0-1.0"
] | 554 | 2017-09-29T18:56:01.000Z | 2022-02-21T15:48:13.000Z | others/optimizers/particle_swarm_optimzer/optimizer_bits/pso/test_function/pso_test_function.hpp | rishabh99-rc/al-go-rithms | 4df20d7ef7598fda4bc89101f9a99aac94cdd794 | [
"CC0-1.0"
] | 2,226 | 2017-09-29T19:59:59.000Z | 2022-03-25T08:59:55.000Z |
#ifndef OPTIMIZER_BITS_PSO_TEST_FUNCTION_PSO_TEST_FUNCTION_HPP
#define OPTIMIZER_BITS_PSO_TEST_FUNCTION_PSO_TEST_FUNCTION_HPP
namespace optimization
{
namespace testFunction
{
class PSOTestFunction
{
public:
/**
* PSOTestFunction is the function which we will optimize.
*
* @param vecSpace Vector space of the function.
* @param minFuncRange Minimum range of function in every dimension
* of it's vector space.
* @param maxFuncRange Maximum range of function in every dimension
* of it's vector space.
*/
PSOTestFunction(const size_t vecSpace,
double *minFuncRange,
double *maxFuncRange) : vecSpace(vecSpace),
minFuncRange(minFuncRange),
maxFuncRange(maxFuncRange)
{
/* Nothing to do here*/
}
/**
* Evalute function calculate and returns the function value
* at given position.
*
* @param position Current position of the particle.
* @return Value of the function at the current position.
*/
double Evaluate(double *position)
{
double eval = 0.0;
for (size_t i = 0; i < vecSpace; i++)
{
eval += position[i] * position[i];
}
return eval;
}
//! Return1 1 (the number of functions).
size_t NumFunctions() const { return 1; }
//! Get the starting point.
double *GetInitialPoint() const
{
double *initialPoint = new double[vecSpace];
for (size_t j = 0; j < vecSpace; ++j)
{
initialPoint[j] = minFuncRange[j] +
static_cast<double>(rand()) /
(static_cast<double>(RAND_MAX / (maxFuncRange[j] - minFuncRange[j])));
}
return initialPoint;
}
// Get vector space of function.
size_t getVecSpace() const { return vecSpace; }
// Modify vector space of function.
size_t getVecSpace() { return vecSpace; }
// Get minimum range of function in every dimension
// of it's vector space.
double *getMinFuncRange() const { return minFuncRange; }
// Modify minimum range of function in every dimension
// of it's vector space.
double *getMinFuncRange() { return minFuncRange; }
// Get maximum range of function in every dimension
// of it's vector space.
double *getMaxFuncRange() const { return maxFuncRange; }
// Modify maximum range of function in every dimension
// of it's vector space.
double *getMaxFuncRange() { return maxFuncRange; }
private:
// vector space of function.
size_t vecSpace;
// Minimum range of function in every dimension
// of it's vector space.
double *minFuncRange;
// Maximum range of function in every dimension
// of it's vector space.
double *maxFuncRange;
};
} // namespace testFunction
} // namespace optimization
#endif // OPTIMIZER_BITS_PSO_TEST_FUNCTION_PSO_TEST_FUNCTION_HPP | 28.214953 | 99 | 0.62471 | [
"vector"
] |
06eec180f8a216220d0dc443a5d652e119f5d8c3 | 605 | cc | C++ | source/native/HostParasiteEvo.cc | kgskocelas/HostParasiteEvo | 449350bd7356da8b4137498425bf72091f0d2139 | [
"MIT"
] | null | null | null | source/native/HostParasiteEvo.cc | kgskocelas/HostParasiteEvo | 449350bd7356da8b4137498425bf72091f0d2139 | [
"MIT"
] | null | null | null | source/native/HostParasiteEvo.cc | kgskocelas/HostParasiteEvo | 449350bd7356da8b4137498425bf72091f0d2139 | [
"MIT"
] | null | null | null | /**
* @copyright Copyright (C) Katherine Skocelas, MIT Software license; see doc/LICENSE.md
* @date 2020.
*
* @file HostParasiteEvo.cc
* @brief Examining the co-evolution of hosts and parasites.
* @note Status: BETA
*
*/
#include <iostream>
#include "base/vector.h"
#include "config/command_line.h"
#include "../HostParasiteEvo.h"
// This is the main function for the NATIVE version of Host-Parasite Coevolution.
int main(int argc, char* argv[])
{
emp::vector<std::string> args = emp::cl::args_to_strings(argc, argv);
Experiment experiment(args);
experiment.Run();
}
| 22.407407 | 89 | 0.68595 | [
"vector"
] |
06ef5bf7c0ca91cec2e304835d4fa69a107b31a3 | 1,589 | cpp | C++ | src/bits_of_matcha/engine/flow/graph/TensorMask.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | src/bits_of_matcha/engine/flow/graph/TensorMask.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | src/bits_of_matcha/engine/flow/graph/TensorMask.cpp | matcha-ai/matcha | c1375fc2bfc9fadcbd643fc1540e3ac470dd9408 | [
"MIT"
] | null | null | null | #include "bits_of_matcha/engine/flow/graph/TensorMask.h"
namespace matcha::engine {
TensorMask::TensorMask(Graph& graph, bool defaultValue)
: TensorDict(graph, defaultValue)
{}
TensorMask::TensorMask(Graph* graph, bool defaultValue)
: TensorDict(graph, defaultValue)
{}
TensorMask TensorMask::operator~() const {
TensorMask result(graph_);
std::transform(
begin(), end(),
result.begin(),
std::logical_not()
);
return result;
}
TensorMask TensorMask::operator&(const TensorMask& mask) const {
TensorMask result(graph_);
std::transform(
begin(), end(),
mask.begin(),
result.begin(),
std::logical_and()
);
return result;
}
TensorMask TensorMask::operator|(const TensorMask& mask) const {
TensorMask result(graph_);
std::transform(
begin(), end(),
mask.begin(),
result.begin(),
std::logical_or()
);
return result;
}
TensorMask& TensorMask::operator&=(const TensorMask& mask) {
*this = *this & mask;
return *this;
}
TensorMask& TensorMask::operator|=(const TensorMask& mask) {
*this = *this | mask;
return *this;
}
size_t TensorMask::count() const {
return std::count(begin(), end(), true);
}
std::vector<Tensor*> TensorMask::get() const {
std::vector<Tensor*> result;
for (int i = 0; i < size(); i++) {
if (values_[i]) result.push_back(graph_->tensors[i]);
}
return result;
}
std::vector<Tensor*> TensorMask::rget() const {
std::vector<Tensor*> result;
for (int i = (int) size() - 1; i >= 0; i--) {
if (values_[i]) result.push_back(graph_->tensors[i]);
}
return result;
}
}
| 20.636364 | 64 | 0.653241 | [
"vector",
"transform"
] |
06efe28c0b2576359878c5a040709e6afa8c98de | 44,621 | cpp | C++ | execution_path/source/path_manager/PathManager.cpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | execution_path/source/path_manager/PathManager.cpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | execution_path/source/path_manager/PathManager.cpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | /*
* PathManager.cpp
*
* Created on: 05.12.2016
* Author: sload
*/
#include "../../header/path_manager/PathManager.hpp"
#include "../../header/execution_path/Checkpoint.hpp"
#include "../../header/execution_path/ExecutionPath.hpp"
using namespace selection;
using namespace util;
using namespace profiler;
namespace execution_path
{
PathManager::PathManager(vector<shared_ptr<WorkerThread>> workerThreads,
shared_ptr<ExecutionPathFactory> executionPathFactory, shared_ptr<MarkovMatrix> markovMatrix,
unsigned long initialSelectionSize, unsigned int treeSize,
GarbageCollectionThread *garbageCollectionThread, Measurements *measurements)
: workerThreads(workerThreads), executionPathFactory(executionPathFactory), markovMatrix(markovMatrix),
garbageCollectionThread(garbageCollectionThread), selectionSize(initialSelectionSize), treeSize(treeSize),
measurements(measurements)
{
}
void PathManager::main()
{
unsigned long reschedulingCounter = 0;
unsigned long treeSize=0;
unsigned long startTime = Helper::currentTimeMillis();
while (!this->terminate.load() || (this->root != nullptr) || (this->newSelections.isEmpty() == false))
{
if (this->root != nullptr)
this->assignExecutionPathToWorkerThread();
else
this->topKExecutionPaths.clear();
this->checkNewSelections();
this->processNewCgroups();
this->processDeletedCgroups();
this->processUpdatedCgroups();
// master finished
if (this->masterExecutionPathFinished.load())
{
this->masterExecutionPathFinished.store(false); // reset
// check also cgroups
this->processNewCgroups();
this->processDeletedCgroups();
this->processUpdatedCgroups();
ExecutionPathNode *currentMasterExPN = this->executionPathExecutionPathNodeMap[this->masterExecutionPathId];
auto selectionId = currentMasterExPN->getExecutionPath()->getAbstractSelection()->getId();
cout << "PathManager: Master, Selection ID: " << selectionId
<< ", execution path Id: " << this->masterExecutionPathId << endl;
// if(selectionId==4)
// {
// cout<<"selection Id 4: check it"<<endl;
// }
shared_ptr<ExecutionPathNode> newMasterExPN;
if (currentMasterExPN->getChildNode() != nullptr)
{
if (currentMasterExPN->getChildNode()->isBranchNode())
{
newMasterExPN = this->findNextRoot(currentMasterExPN->getChildNode());
}
else // the child is execution path node
{
newMasterExPN = static_pointer_cast<ExecutionPathNode>(currentMasterExPN->getChildNode());
}
}
else
newMasterExPN = nullptr;
/*
* After updating and/or deleting cgroups, the next child should be the correct execution path
* So make it as master
*/
size_t index = this->executionPathWorkThreadMap[this->masterExecutionPathId];
this->workerThreads[index]->receiveExecutionPath(nullptr);
this->executionPathExecutionPathNodeMap.erase(this->masterExecutionPathId);
this->executionPathWorkThreadMap.erase(this->masterExecutionPathId);
this->markovMatrix->executionPathFinished(
currentMasterExPN->getExecutionPath()->getAbstractSelection()->getLastEventSn(), true);
this->treeDepth--;
// Make the selection as ready to be removed. So Splitter can remove it events!
currentMasterExPN->getExecutionPath()->getAbstractSelection()->setReadyToBeRemoved(true);
if (newMasterExPN != nullptr)
{
newMasterExPN->setParentNode(nullptr);
ExecutionPath *newMasterExP = newMasterExPN->getExecutionPath().get();
newMasterExP->setMaster(true);
this->masterExecutionPathId = newMasterExP->getId();
/*
*move root to the garbage collector, so path manager doesn't need to spend
* time on deleting the old root
*/
this->garbageCollectionThread->pushToQueue(this->root);
this->root = newMasterExPN;
// cout << "PathManager: new master: " << newMasterExP->getId() << endl;
}
else
{
// if (this->executionPathExecutionPathNodeMap.size() != 0)
// {
// cout << "Path manager: there are still(" <<
// this->executionPathExecutionPathNodeMap.size()
// << ") but can't schedule" << endl;
// }
this->root = nullptr;
}
}
reschedulingCounter++;
if(treeSize< this->executionPathExecutionPathNodeMap.size())
treeSize=this->executionPathExecutionPathNodeMap.size();
}
ofstream treeSizeFile;
treeSizeFile.open("./tree_size", ios::out);
treeSizeFile<< treeSize;
treeSizeFile.close();
unsigned long endTime = Helper::currentTimeMillis();
this->measurements->getPathManagerReschedulingFrequency()->set(startTime, endTime, reschedulingCounter);
cout << "Path Manager counter: " << reschedulingCounter << endl;
cout << "Path Manager cgroups New counter: " << this->cgroupNewCounter << endl;
cout << "Path Manager cgroups delete counter: " << this->cgroupDeleteCounter << endl;
cout << "Path Manager cgroups update counter: " << this->cgroupUpdateCounter << endl;
// terminate all worker threads
for (auto it = this->workerThreads.begin(); it != this->workerThreads.end(); it++)
it->get()->setTerminate();
}
shared_ptr<ExecutionPathNode> PathManager::findNextRoot(const shared_ptr<AbstractNode> &startNode)
{
// No execution path nodes in the tree
if (startNode == nullptr)
return nullptr;
if (startNode->isBranchNode())
{
shared_ptr<BranchNode> tempBN = static_pointer_cast<BranchNode>(startNode);
// for some reason the validation was late and the master couldn't detect it
if (tempBN->getCgroup()->getValidation() == Cgroup::Validation::VALID)
{
this->bufferedRootCgroups.push_back(tempBN->getCgroup());
// call recursively using, cgroup is valid, so take right child that used this cgroup
return this->findNextRoot(tempBN->getRightChildNode());
}
else if (tempBN->getCgroup()->getValidation() == Cgroup::Validation::INVALID
|| tempBN->getCgroup()->getValidation() == Cgroup::Validation::DELETED)
{
// cgroup is Invalid or deleted, so take left child that didn't use this cgroup
return findNextRoot(tempBN->getLeftChildNode());
}
else // if (tempBN->getCgroup()->getValidation() == Cgroup::Validation::NONE)
{
cout << "Path Manager: found a cgroup with NONE validation, cgroup: " << tempBN->getCgroup()->getId()
<< endl;
exit(-1);
/*
* no information about this cgroup. it is impossible, so we choose both children
* and try to find first execution path node
*/
auto result = findNextRoot(tempBN->getLeftChildNode());
if (result != nullptr)
return result;
result = findNextRoot(tempBN->getRightChildNode());
return result;
}
}
else // found the execution path
{
return static_pointer_cast<ExecutionPathNode>(startNode);
}
}
void PathManager::receiveNewSelection(const shared_ptr<selection::AbstractSelection> &abstractSelection)
{
this->newSelections.push(abstractSelection);
}
void PathManager::checkNewSelections()
{
// don't add too much selection to not overload the path manager
if (this->treeDepth > this->treeSize)
return;
/* get all Selections from newSelections queue and
* create new execution path for each Selection. Then create new execution path
* node and call addNewExecutionPathToTreeNode
*/
shared_ptr<AbstractSelection> newSelection;
while (this->newSelections.pop(newSelection))
{
shared_ptr<ExecutionPath> executionPath = this->executionPathFactory->createNewExecutionPath(newSelection);
// check cgroups from earlier parents
this->checkValidBufferedRootCgroups(newSelection->getStartPosition()->get()->getSn());
unordered_map<unsigned long, pair<shared_ptr<Cgroup>, unsigned int>> onPathCgroups;
for (auto cgroup : this->bufferedRootCgroups)
{
onPathCgroups[cgroup->getId()] = make_pair(cgroup, 0);
}
shared_ptr<ExecutionPathNode> executionPathNode = make_shared<ExecutionPathNode>(executionPath);
if (root == nullptr) // empty tree
{
executionPath->setCgroupsFromParent(onPathCgroups);
// create the initial check point
// executionPath->createCheckpoint(nullptr);
// executionPath->setInitialCheckpoint(executionPath->getCheckpoint(0));
root = executionPathNode;
executionPath->setMaster(true);
this->masterExecutionPathId = executionPath->getId();
// map execution path with execution path node
this->executionPathExecutionPathNodeMap[executionPath->getId()] = executionPathNode.get();
this->treeDepth = 1;
}
else
{
this->treeDepth++;
this->addExecutionPathNodeToTreeNode(this->root.get(), executionPathNode, onPathCgroups);
}
// don't add too much selection to not overload the path manager
// if (this->executionPathExecutionPathNodeMap.size() >= this->treeDepth)
if (this->treeDepth > this->treeSize)
return;
}
}
void PathManager::checkValidBufferedRootCgroups(unsigned long selectionStartEventSn)
{
for (auto it = this->bufferedRootCgroups.begin(); it != this->bufferedRootCgroups.end();)
{
size_t size = it->get()->getEvents().size();
// there is no overlap, delete the buffered cgroup
if (size != 0 && it->get()->getEvents()[size - 1] < selectionStartEventSn)
{
it = this->bufferedRootCgroups.erase(it);
}
else // no need to check next cgroups, because mostly they are ordered and checking costs time
return;
}
}
void PathManager::addExecutionPathNodeToTreeNode(
AbstractNode *startNode, const shared_ptr<ExecutionPathNode> &executionPathNode,
unordered_map<unsigned long, pair<shared_ptr<Cgroup>, unsigned int>> &cgroups)
{
/*
* Then traverse tree node and add the new execution path to its leaves
* ** deep first**
* - collect all cgroups from root to the leaf and add them to right execution path child of a branch node
* * collect only on right children of branch nodes
*/
if (startNode->isBranchNode())
{
BranchNode *temp = static_cast<BranchNode *>(startNode);
// left child
if (temp->getLeftChildNode() != nullptr)
addExecutionPathNodeToTreeNode(temp->getLeftChildNode().get(), executionPathNode, cgroups); // recursively
// leaf node=> add the execution path to it
else
{
shared_ptr<ExecutionPathNode> tempExPN = static_pointer_cast<ExecutionPathNode>(executionPathNode->clone());
// clone execution path inside the execution path node
auto executionPath = tempExPN->getExecutionPath()->clone();
executionPath->setCgroupsFromParent(cgroups);
// create the initial check point
// executionPath->createCheckpoint(nullptr);
// executionPath->setInitialCheckpoint(executionPath->getCheckpoint(0));
// add the execution path to the execution path node
tempExPN->setExecutionPath(executionPath);
// set parent node
tempExPN->setParentNode(temp);
temp->setLeftChildNode(tempExPN);
// map execution path with execution path node
this->executionPathExecutionPathNodeMap[executionPath->getId()] = tempExPN.get();
}
// right child
if (temp->getRightChildNode() != nullptr)
{
/*
*clone cgroup to avoid data race on the cgroup (write by parent, read by children.
* One copy for all children.
* Whenever the cgroup changes, each children performs a local copy!
*/
// lock because the parent can change it in the meanwhile
// temp->getCgroup()->readLock();
// cgroups[temp->getCgroup()->getId()] = temp->getCgroup()->clone(); // collect cgroups
// temp->getCgroup()->readUnlock();
cgroups[temp->getCgroup()->getId()] = make_pair(temp->getCgroup(), 0);
addExecutionPathNodeToTreeNode(temp->getRightChildNode().get(), executionPathNode, cgroups); // recursively
cgroups.erase(temp->getCgroup()->getId()); // remove cgroups
}
else // leaf node=> add the execution path to it
{
// add current cgroup (it is the right child)
// temp->getCgroup()->readLock();
// auto currentCgroup = temp->getCgroup()->clone(); // collect cgroups
// temp->getCgroup()->readUnlock();
auto currentCgroup = temp->getCgroup();
shared_ptr<ExecutionPathNode> tempExPN = static_pointer_cast<ExecutionPathNode>(executionPathNode->clone());
// clone execution path inside the execution path node
auto executionPath = tempExPN->getExecutionPath()->clone();
executionPath->setCgroupsFromParent(cgroups);
executionPath->addCgroupFromParent(currentCgroup, 0);
// create the initial check point
// executionPath->createCheckpoint(nullptr);
// executionPath->setInitialCheckpoint(executionPath->getCheckpoint(0));
// add the execution path to the execution path node
tempExPN->setExecutionPath(executionPath);
// set parent node
tempExPN->setParentNode(temp);
temp->setRightChildNode(tempExPN);
// map execution path with execution path node
this->executionPathExecutionPathNodeMap[tempExPN->getExecutionPath()->getId()] = tempExPN.get();
}
}
else // it is execution path node
{
ExecutionPathNode *temp = static_cast<ExecutionPathNode *>(startNode);
// either there is child execution path node or child branch node but not both together (or not both)!
if (temp->getChildNode() != nullptr)
addExecutionPathNodeToTreeNode(temp->getChildNode().get(), executionPathNode, cgroups); // recursively
else // if leaf node=> add the execution path to it
{
shared_ptr<ExecutionPathNode> tempExPN = static_pointer_cast<ExecutionPathNode>(executionPathNode->clone());
// clone execution path inside the execution path node
auto executionPath = tempExPN->getExecutionPath()->clone();
executionPath->setCgroupsFromParent(cgroups);
// create the initial check point
// executionPath->createCheckpoint(nullptr);
// executionPath->setInitialCheckpoint(executionPath->getCheckpoint(0));
// add the execution path to the execution path node
tempExPN->setExecutionPath(executionPath);
// set parent node
tempExPN->setParentNode(temp);
temp->setChildNode(tempExPN);
// map execution path with execution path node
this->executionPathExecutionPathNodeMap[tempExPN->getExecutionPath()->getId()] = tempExPN.get();
}
}
}
void PathManager::assignExecutionPathToWorkerThread()
{
size_t k = workerThreads.size();
vector<bool> freeIndex(k, true); // check if working
vector<shared_ptr<ExecutionPath>> toBeScheduled;
// vector<shared_ptr<WorkerThread>> freeWorkerThreads = this->workerThreads;
this->topKExecutionPaths = this->getTopKExecutionPath(root, k);
std::unordered_map<unsigned long, unsigned long> executionPathWorkThreadMapNext;
/*
* check if the execution path is already scheduled on any worker thread
* if yes: don't assign it again because (worker logic) is designed to work on
* the scheduled execution path till finishes it unless there is a new execution path
*/
for (size_t i = 0; i < this->topKExecutionPaths.size(); ++i) // Loop executionPaths
{
auto pos = executionPathWorkThreadMap.find(topKExecutionPaths[i]->get()->getId());
// If Execution path with that Id is not scheduled yet -> add it to the toBeScheduled List
if (pos == executionPathWorkThreadMap.end())
{
toBeScheduled.push_back(*topKExecutionPaths[i]);
}
else // else remove the thread executing it from the freeIndex list
{
freeIndex[pos->second] = false;
executionPathWorkThreadMapNext.insert(make_pair(topKExecutionPaths[i]->get()->getId(), pos->second));
}
}
size_t j = 0;
for (size_t i = 0; i < toBeScheduled.size(); ++i) // Loop toBeScheduled
{
while (freeIndex[j] == false)
{
++j;
}
this->workerThreads[j]->receiveExecutionPath(toBeScheduled[i]);
executionPathWorkThreadMapNext.insert(make_pair(toBeScheduled[i]->getId(), j));
freeIndex[j] = false;
++j;
}
for (size_t j = 0; j < k; j++)
{
if (freeIndex[j])
this->workerThreads[j]->receiveExecutionPath(nullptr);
}
// Update Map
executionPathWorkThreadMap = executionPathWorkThreadMapNext;
}
vector<shared_ptr<ExecutionPath> *> PathManager::getTopKExecutionPath(shared_ptr<ExecutionPathNode> root, size_t k)
{
vector<shared_ptr<ExecutionPath> *> A;
A.reserve(k);
priority_queue<AbstractNode *, vector<AbstractNode *>, LessThanByP> B;
root->setProbability(1.0f);
B.push(root.get());
AbstractNode *currentNode;
float probability;
while (A.size() < k && !B.empty())
{
currentNode = B.top();
B.pop();
if (currentNode->isExecutionPathNode()) // if current Node is Execution Path
{
ExecutionPathNode *currentNodeEx = static_cast<ExecutionPathNode *>(currentNode);
if (currentNodeEx->getChildNode())
{
currentNodeEx->getChildNode()->setProbability(currentNodeEx->getProbability());
B.push(currentNodeEx->getChildNode().get());
}
A.push_back(¤tNodeEx->getExecutionPath());
}
else
{
BranchNode *currentNodeBn = static_cast<BranchNode *>(currentNode);
// get execution path that generated this cgroup to compute windowLeft
auto tempExP = this->executionPathExecutionPathNodeMap[currentNodeBn->getCgroup()->getExecutionPathId()]
->getExecutionPath()
.get();
unsigned long windowLeft = tempExP->getEventLeftInSelection(this->selectionSize.load()); // TODO
if (windowLeft == 0) // If the window is still open at least one more event is expected
{
windowLeft = 1;
}
probability = static_cast<float>(
markovMatrix->getProbability(windowLeft, currentNodeBn->getCgroup()->getEventsLeft()));
if (probability < 0)
{
probability = 0.0f;
}
if (currentNodeBn->getLeftChildNode())
{
currentNodeBn->getLeftChildNode()->setProbability(currentNodeBn->getProbability() * (1 - probability));
B.push(currentNodeBn->getLeftChildNode().get());
}
if (currentNodeBn->getRightChildNode())
{
currentNodeBn->getRightChildNode()->setProbability(currentNodeBn->getProbability() * probability);
B.push(currentNodeBn->getRightChildNode().get());
}
}
}
return A;
}
void PathManager::receiveCgroup(const shared_ptr<Cgroup> &cgroup, Cgroup::Status status)
{
switch (status)
{
case Cgroup::Status::NEW:
this->newCgroups.push(cgroup);
break;
case Cgroup::Status::UPDATE:
this->updatedCgroups.push(cgroup);
break;
case Cgroup::Status::DELETE:
this->deletedCgroups.push(cgroup);
break;
}
}
void PathManager::processNewCgroups()
{
shared_ptr<Cgroup> cgroup;
while (this->newCgroups.pop(cgroup))
{
this->cgroupNewCounter++;
// Check if the execution path already has been deleted from the tree
if (this->executionPathExecutionPathNodeMap.count(cgroup->getExecutionPathId()) == 0)
continue;
// if (this->workerThreads.size() == 16)
// {
// size_t index = 0;
// unsigned long CgExecutionPathId = cgroup->getExecutionPathId();
// for (; index < 8; index++)
// if (CgExecutionPathId == this->topKExecutionPaths[index]->getId())
// break;
// if (index == 8)
// {
// this->newCgroupsList.push_back(cgroup);
// continue;
// }
// }
addNewCgroup(cgroup);
}
for (auto it = this->newCgroupsList.begin(); it != this->newCgroupsList.end();)
{
// Check if the execution path already has been deleted from the tree
if (this->executionPathExecutionPathNodeMap.count(it->get()->getExecutionPathId()) == 0)
{
it = this->newCgroupsList.erase(it);
continue;
}
// if (this->workerThreads.size() == 16)
// {
// size_t index = 0;
// unsigned long CgExecutionPathId = it->get()->getExecutionPathId();
// for (; index < 8; index++)
// if (CgExecutionPathId == this->topKExecutionPaths[index]->getId())
// break;
// if (index == 8)
// {
// it++;
// continue;
// }
// }
addNewCgroup(*it);
it = this->newCgroupsList.erase(it);
}
}
void PathManager::addNewCgroup(const shared_ptr<Cgroup> &cgroup)
{
// clean the tree for the execution path that generated the new cgroup
/*
*To prevent adding a new cgroup which is already deleted by parent execution path:
* check if the cgroup is deleted in the meanwhile. If not:
*Also to prevent adding the cgroup as a child of a deleted cgroup from same execution path,
* we first check if there is any deleted cgroup from this path and delete them.
*We can delete all cgroup in deletedCgroupMap, but to reduce the delay for the new cgroup
* check and delete only the cgroup from this execution path
*/
this->readDeletedCgroups();
// If the new cgroup already was deleted, erase it from deletedCgroupMap and continue to next cgroup
if (this->deletedCgroupsMap.count(cgroup->getId()) != 0)
{
this->deletedCgroupsMap.erase(cgroup->getId());
return;
}
else // The new cgroup is not deleted, check if any other cgroup from the same execution path is deleted
{
for (auto it = this->deletedCgroupsMap.begin(); it != this->deletedCgroupsMap.end();)
{
if (it->second->getExecutionPathId() == cgroup->getExecutionPathId()) // same execution path
{
bool result = this->deleteCgroup(it->second); // delete the cgroup
if (result == false) // not found in the tree, so not deleted
it++;
else
it = this->deletedCgroupsMap.erase(it);
}
else
it++;
}
}
// get the execution path that has generated this cgroup
ExecutionPathNode *executionPathNode = executionPathExecutionPathNodeMap[cgroup->getExecutionPathId()];
shared_ptr<BranchNode> newBranchNode = make_shared<BranchNode>(cgroup);
if (executionPathNode->getChildNode() == nullptr)
{
// set parent node
newBranchNode->setParentNode(executionPathNode);
executionPathNode->setChildNode(newBranchNode);
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId() << ", cgroup:" <<
// cgroup->getId()
// << " added as a leaf node to the execution path node itself" << endl;
}
else
{
// add the new cgroup
branch(executionPathNode, executionPathNode->getChildNode(), newBranchNode);
}
}
void PathManager::branch(AbstractNode *parentNode, shared_ptr<AbstractNode> &startNode,
const shared_ptr<BranchNode> &newBranchNode)
{
if (startNode->isBranchNode())
{
BranchNode *temp = static_cast<BranchNode *>(startNode.get());
// left child
if (temp->getLeftChildNode() != nullptr)
{
branch(temp, temp->getLeftChildNode(), newBranchNode);
}
else // it is leaf node, so add the newBranchNode to its children
{
auto tempBN = newBranchNode->clone();
// set the parent node
tempBN->setParentNode(temp);
temp->setLeftChildNode(tempBN);
// auto cgroup = (static_cast<BranchNode *>(tempBN.get()))->getCgroup();
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId()
// << ", New cgroup:" << cgroup->getId() << " added as a leaf node to left child of a branch
// node"
// << endl;
}
// right child
if (temp->getRightChildNode() != nullptr)
{
branch(temp, temp->getRightChildNode(), newBranchNode);
}
else // it is leaf node, so add the newBranchNode to its children
{
auto tempBN = newBranchNode->clone();
// set parent node
tempBN->setParentNode(temp);
temp->setRightChildNode(tempBN);
// auto cgroup = (static_cast<BranchNode *>(tempBN.get()))->getCgroup();
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId()
// << ", New cgroup:" << cgroup->getId() << " added as a leaf node to right child of a
// branch node "
// << endl;
}
}
else // execution path node. Above this execution path node, we insert newBranchNode
{
shared_ptr<BranchNode> tempBN = static_pointer_cast<BranchNode>(newBranchNode->clone());
// insert a copy of newBranchNode. (left child, doesn't change any thing)
tempBN->setLeftChildNode(startNode);
// set the parent node
tempBN->setParentNode(parentNode);
startNode = tempBN;
// auto cgroup = tempBN->getCgroup();
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId() << ", New cgroup:" <<
// cgroup->getId()
// << " added as a parent node for the next (child) execution path node" << endl;
/*
* clone the whole sub tree starting from this execution path node
* and add it as a right child of newBranchNode (also feed all cloned execution path with the new
* cgroup)
*/
// shared_ptr<AbstractNode> startCloneNode = tempBN->getLeftChildNode();
// cloneSubTree(tempBN.get(), startCloneNode, tempBN->getCgroup());
// tempBN->setRightChildNode(startCloneNode);
//-----------------------------------
/*
*clone cgroup to avoid data race on the cgroup (write by parent, read by children.
* One copy for all children.
* Whenever the cgroup changes, each children performs a local copy!
*/
// lock because the parent can change it in the meanwhile
// tempBN->getCgroup()->readLock();
// shared_ptr<Cgroup> cgroupClone = tempBN->getCgroup()->clone();
// tempBN->getCgroup()->readUnlock();
shared_ptr<Cgroup> cgroupClone = tempBN->getCgroup();
shared_ptr<AbstractNode> rightStartCloneNode = NULL;
// AbstractNode *leftStartNode = tempBN->getLeftChildNode().get();
ExecutionPathNode *leftStartNode = static_cast<ExecutionPathNode *>(tempBN->getLeftChildNode().get());
// take a copy of cgroups, take from the initial check point to avoid data race;
unordered_map<unsigned long, pair<shared_ptr<Cgroup>, unsigned int>> cgroups;
// cgroups =
// leftStartNode->getExecutionPath()->getInitialCheckpoint()->getExecutionPath()->getCgroupsFromParent();
cgroups = leftStartNode->getExecutionPath()->getCgroupsFromParent();
// filter all finished and not overlapped cgroups!
for (auto it = cgroups.begin(); it != cgroups.end();)
{
// the execution path is already finished (old master)
if (it->second.first->getExecutionPathId() < this->masterExecutionPathId)
{
// size_t cgroupSize = it->second->getOriginal()->getEvents().size();
// unsigned long lastEventSn = it->second.first.ge->getOriginal()->getEvents()[cgroupSize
// - 1]->getSn();
shared_ptr<Cgroup> tempCgroup = it->second.first->getClonedCopy();
size_t cgroupSize = tempCgroup->getEvents().size();
unsigned long lastEventSn = tempCgroup->getEvents()[cgroupSize - 1];
// check if it doesn't overlap
if (lastEventSn
< leftStartNode->getExecutionPath()->getAbstractSelection()->getStartPosition()->get()->getSn())
it = cgroups.erase(it);
else
{
it->second.second = 0; // reset version number, so new execution path will for sure copy clonedCopy
it++;
}
}
else
{
it->second.second = 0; // reset version number, so new execution path will for sure copy clonedCopy
it++;
}
}
cgroups[cgroupClone->getId()] = make_pair(cgroupClone, 0);
cloneSubTree(tempBN.get(), rightStartCloneNode, leftStartNode, cgroups);
tempBN->setRightChildNode(rightStartCloneNode);
}
}
void PathManager::cloneSubTree(AbstractNode *parentNode, shared_ptr<AbstractNode> &rightStartCloneNode,
AbstractNode *startNode,
const unordered_map<unsigned long, pair<shared_ptr<Cgroup>, unsigned int>> &cgroups)
{
// traverse over all node starting from startNode and replicate them to construct a new branch
/*
* Clone only on execution path per a window (Selection)
*/
if (startNode->isBranchNode())
{
BranchNode *tempBN = static_cast<BranchNode *>(startNode);
/*
* traversing left child is enough.
* Note: we take only one initial copy of only one execution path per a Selection
*/
if (tempBN->getLeftChildNode() != nullptr)
cloneSubTree(parentNode, rightStartCloneNode, tempBN->getLeftChildNode().get(), cgroups);
}
else // Execution path node
{
ExecutionPathNode *tempStartNode = static_cast<ExecutionPathNode *>(startNode);
// get the initial check point
// shared_ptr<Checkpoint> checkpoint = tempStartNode->getExecutionPath()->getInitialCheckpoint();
// clone the check point
// shared_ptr<ExecutionPath> executionPath = checkpoint->getExecutionPath()->clone();
auto selection = tempStartNode->getExecutionPath()->getAbstractSelection()->clone();
selection->setCurrentPosition(selection->getStartPosition());
shared_ptr<ExecutionPath> executionPath = this->executionPathFactory->createNewExecutionPath(selection);
// add the cgroups to the newly created execution path
executionPath->setCgroupsFromParent(cgroups);
// create the initial check point
// executionPath->createCheckpoint(nullptr);
// executionPath->setInitialCheckpoint(executionPath->getCheckpoint(0));
// create a new execution path node
shared_ptr<ExecutionPathNode> newExPN = make_shared<ExecutionPathNode>(executionPath);
// set the parent node
newExPN->setParentNode(parentNode);
// assign the new execution path to rightStartCloneNode (cloning)
rightStartCloneNode = newExPN;
this->executionPathExecutionPathNodeMap[executionPath->getId()] = newExPN.get();
// cout << "PathManager: execution path: , New cgroup: added as a parent node for the next (child)
// execution "
// "path node (cloneSubTree)"
// << endl;
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId() << ", New cgroup:" <<
// cgroup->getId()
// << " added as a parent node for the next (child) execution path node (cloneSubTree)" << endl;
// call recursively for leftStartNode's child
if (tempStartNode->getChildNode().get() != nullptr)
cloneSubTree(newExPN.get(), newExPN->getChildNode(), tempStartNode->getChildNode().get(), cgroups);
}
}
void PathManager::processUpdatedCgroups()
{
vector<shared_ptr<Cgroup>> unfoundedCgroups;
shared_ptr<Cgroup> cgroup;
while (this->updatedCgroups.pop(cgroup))
{
// Check if the execution path already has been deleted from the tree
if (this->executionPathExecutionPathNodeMap.count(cgroup->getExecutionPathId()) == 0)
continue;
// get the execution path that has generated this cgroup
ExecutionPathNode *executionPathNode = executionPathExecutionPathNodeMap.at(cgroup->getExecutionPathId());
bool result = this->deleteBranch(executionPathNode->getChildNode(), cgroup);
// cgroup not found, so return it back to the queue till the cgroup is fetched from newCgroups queue
if (result == false)
unfoundedCgroups.push_back(cgroup);
cgroupUpdateCounter++;
}
for (auto it = unfoundedCgroups.begin(); it != unfoundedCgroups.end(); it++)
this->updatedCgroups.push(*it);
}
void PathManager::readDeletedCgroups()
{
shared_ptr<Cgroup> cgroup;
while (this->deletedCgroups.pop(cgroup))
{
this->deletedCgroupsMap[cgroup->getId()] = cgroup;
this->cgroupDeleteCounter++;
}
}
void PathManager::processDeletedCgroups()
{
vector<shared_ptr<Cgroup>> unfoundedCgroups;
shared_ptr<Cgroup> cgroup;
while (this->deletedCgroups.pop(cgroup))
{
// // Check if the execution path already has been deleted from the tree
// if (this->executionPathExecutionPathNodeMap.count(cgroup->getExecutionPathId()) == 0)
// continue;
// // get the execution path that has generated this cgroup
// ExecutionPathNode *executionPathNode =
// executionPathExecutionPathNodeMap.at(cgroup->getExecutionPathId());
// bool result = this->deleteBranch(executionPathNode->getChildNode().get(), cgroup);
bool result = this->deleteCgroup(cgroup);
// cgroup not found, so return it back to the queue till the cgroup is fetched from newCgroups queue
// cgroup not found, so return it back to the map till the cgroup is fetched from newCgroups queue
if (result == false)
unfoundedCgroups.push_back(cgroup);
cgroupDeleteCounter++;
}
for (auto it = this->deletedCgroupsMap.begin(); it != this->deletedCgroupsMap.end();)
{
bool result = this->deleteCgroup(it->second);
// cgroup not found, so don't erase cgroup, till the cgroup is fetched from newCgroups queue
if (result == false)
it++;
else
it = this->deletedCgroupsMap.erase(it);
}
// Insert undeleted cgroups (which are fetched from the queue) to the map
for (auto it = unfoundedCgroups.begin(); it != unfoundedCgroups.end(); it++)
// this->deletedCgroups.push(*it);
this->deletedCgroupsMap[it->get()->getId()] = *it;
}
bool PathManager::deleteCgroup(const shared_ptr<Cgroup> &cgroup)
{
// Check if the execution path already has been deleted from the tree
if (this->executionPathExecutionPathNodeMap.count(cgroup->getExecutionPathId()) == 0)
return true;
// get the execution path that has generated this cgroup
ExecutionPathNode *executionPathNode = executionPathExecutionPathNodeMap.at(cgroup->getExecutionPathId());
bool result = this->deleteBranch(executionPathNode->getChildNode(), cgroup);
return result;
}
bool PathManager::deleteBranch(const shared_ptr<AbstractNode> &startNode, const shared_ptr<Cgroup> &cgroup)
{
if (startNode == nullptr)
{
// cgroup not found, so return false it back to the queue till the cgroup is fetched from newCgroups queue
return false;
}
if (startNode->isBranchNode())
{
shared_ptr<BranchNode> tempBN = static_pointer_cast<BranchNode>(startNode);
if (tempBN->getCgroup()->getId() == cgroup->getId()) // we reached the deleted/ validated cgroup
{
// remove all execution paths that are children of this path from ExecutionPathExecutionPathNodeMap
AbstractNode *toBeDeletedChild = nullptr;
shared_ptr<AbstractNode> toBeKeptChild = nullptr;
// Valid, delete left child of the branch node and mark the branch node as valid
if (cgroup->getValidation() == Cgroup::Validation::VALID)
{
toBeDeletedChild = tempBN->getLeftChildNode().get(); // delete right child
toBeKeptChild = tempBN->getRightChildNode();
// add the cgroup to the buffer so it can be used by later coming Selections
this->bufferedRootCgroups.push_back(cgroup);
}
// if the cgroup has invalid/deleted status, the right child and the branch node itself will be deleted
else if (cgroup->getValidation() == Cgroup::Validation::INVALID
|| cgroup->getValidation() == Cgroup::Validation::DELETED)
{
toBeDeletedChild = tempBN->getRightChildNode().get(); // delete right child
toBeKeptChild = tempBN->getLeftChildNode();
}
else // NONE, impossible status
{
cout << "Path Manager, deletebranch() has bad cgroup: " << cgroup->getId()
<< " from the execution path: " << cgroup->getExecutionPathId() << endl;
exit(-1);
}
// Start to delete!
if (toBeDeletedChild != nullptr)
{
this->cleanExecutionPathExecutionPathMap(toBeDeletedChild); // recursive function
}
// delete the link to this branch node (i.e. that contains the deleted cgroup)
//(delete the branch node)
AbstractNode *parentNode = tempBN->getParentNode();
if (toBeKeptChild != nullptr)
toBeKeptChild->setParentNode(parentNode);
if (parentNode->isBranchNode())
{
BranchNode *tempBNParent = static_cast<BranchNode *>(parentNode);
if (tempBNParent->getLeftChildNode().get() == tempBN.get()) // tempBN is left child
{
tempBNParent->setLeftChildNode(toBeKeptChild);
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId()
// << ", Delete cgroup:" << cgroup->getId() << ", parent is branch node
// (left child)" << endl;
}
else // tempBN is right child
{
tempBNParent->setRightChildNode(toBeKeptChild);
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId()
// << ", Delete cgroup:" << cgroup->getId() << ", parent is branch node
// (right child) " << endl;
}
}
else // parentNode is an execution path node
{
ExecutionPathNode *tempExPNParent = static_cast<ExecutionPathNode *>(parentNode);
tempExPNParent->setChildNode(toBeKeptChild);
// cout << "PathManager: execution path: " << cgroup->getExecutionPathId()
// << ", Delete cgroup:" << cgroup->getId() << ", parent is the execution path node
// itself " << endl;
}
if (!garbageCollectionThread->pushToQueue(tempBN))
cout << "PathManager: garbage collection queue is full" << endl;
// cgroup has been found and deleted
return true;
}
else // still didn't get the branch node that contains the deleted/validated cgroup
{
/*
* The cgroup is either in both children or not at all in the tree. Therefore, we search first in right
* branch. If the cgroup is not
* found in the right child, it is for sure not on left child as well. So return false.
*/
bool result = deleteBranch(tempBN->getRightChildNode(), cgroup);
if (!result) // cgroup is not found
return false;
deleteBranch(tempBN->getLeftChildNode(), cgroup);
return true;
}
}
else // execution path node:
{
// cgroup not found, so return it back to the queue till the cgroup is fetched from newCgroups queue
return false;
}
}
void PathManager::cleanExecutionPathExecutionPathMap(AbstractNode *startNode)
{
// remove all execution paths starting from 'startNode' from ExecutionPathExecutionPathNodeMap
if (startNode == nullptr)
return;
if (startNode->isBranchNode())
{
BranchNode *temp = static_cast<BranchNode *>(startNode);
cleanExecutionPathExecutionPathMap(temp->getLeftChildNode().get());
cleanExecutionPathExecutionPathMap(temp->getRightChildNode().get());
}
else // execution path node
{
ExecutionPathNode *temp = static_cast<ExecutionPathNode *>(startNode);
this->executionPathExecutionPathNodeMap.erase(temp->getExecutionPath()->getId());
cleanExecutionPathExecutionPathMap(temp->getChildNode().get());
}
}
void PathManager::setMasterExecutionPathFinished(bool value) { this->masterExecutionPathFinished.store(value); }
unsigned long PathManager::getSelectionSize() const { return selectionSize.load(); }
void PathManager::setSelectionSize(unsigned long value) { selectionSize.store(value); }
void PathManager::setTerminate() { this->terminate.store(true); }
PathManager::~PathManager() {}
}
| 41.392393 | 120 | 0.599494 | [
"vector"
] |
06f26ba0a7e862ffc101c6b0ef31cc067ea00341 | 1,691 | cpp | C++ | android-28/android/view/textclassifier/TextClassification_Request.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/view/textclassifier/TextClassification_Request.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-28/android/view/textclassifier/TextClassification_Request.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../os/LocaleList.hpp"
#include "../../os/Parcel.hpp"
#include "../../../JString.hpp"
#include "../../../java/time/ZonedDateTime.hpp"
#include "./TextClassification_Request.hpp"
namespace android::view::textclassifier
{
// Fields
JObject TextClassification_Request::CREATOR()
{
return getStaticObjectField(
"android.view.textclassifier.TextClassification$Request",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
// QJniObject forward
TextClassification_Request::TextClassification_Request(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
jint TextClassification_Request::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
android::os::LocaleList TextClassification_Request::getDefaultLocales() const
{
return callObjectMethod(
"getDefaultLocales",
"()Landroid/os/LocaleList;"
);
}
jint TextClassification_Request::getEndIndex() const
{
return callMethod<jint>(
"getEndIndex",
"()I"
);
}
java::time::ZonedDateTime TextClassification_Request::getReferenceTime() const
{
return callObjectMethod(
"getReferenceTime",
"()Ljava/time/ZonedDateTime;"
);
}
jint TextClassification_Request::getStartIndex() const
{
return callMethod<jint>(
"getStartIndex",
"()I"
);
}
JString TextClassification_Request::getText() const
{
return callObjectMethod(
"getText",
"()Ljava/lang/CharSequence;"
);
}
void TextClassification_Request::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::view::textclassifier
| 21.679487 | 90 | 0.703726 | [
"object"
] |
06f48a3b0780bf6f32a6fbbeb058765b39efadab | 13,923 | cpp | C++ | lib/popops/reduction/ReductionPlan.cpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | 95 | 2020-07-06T17:11:23.000Z | 2022-03-12T14:42:28.000Z | lib/popops/reduction/ReductionPlan.cpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | null | null | null | lib/popops/reduction/ReductionPlan.cpp | graphcore/poplibs | 3fe5a3ecafe995eddb72675d1b4a7af8a622009e | [
"MIT"
] | 14 | 2020-07-15T12:32:57.000Z | 2022-01-26T14:58:45.000Z | // Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#include "ReductionPlan.hpp"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <limits>
#include <numeric>
#include <boost/icl/interval_map.hpp>
#include "poplibs_support/logging.hpp"
#include <poputil/TileMapping.hpp>
#include <poputil/Util.hpp>
#include <poputil/exceptions.hpp>
#include <poplibs_support/IclUtil.hpp>
#include "RegionWrapping.hpp"
using namespace poplar;
using namespace poplibs;
using namespace poplibs_support;
namespace popops {
// Get the maximum number of tiles that a single partial value is spread over.
std::size_t getMaxTileSpread(const Graph::TileToTensorMapping &mapping,
std::size_t outputSize) {
boost::icl::interval_map<std::size_t, std::size_t> spread;
using MapEntry =
std::pair<boost::icl::right_open_interval<std::size_t>, std::size_t>;
auto comp = [](const MapEntry &a, const MapEntry &b) {
return a.second < b.second;
};
for (const auto &tileRegions : mapping) {
boost::icl::interval_set<std::size_t> outputRegionsUsedOnTile;
wrapRegions(tileRegions.begin(), tileRegions.end(), outputSize,
[&](size_t begin, size_t end) {
outputRegionsUsedOnTile +=
boost::icl::interval<std::size_t>::right_open(begin, end);
});
// add in regions used by tile
for (const auto ®ion : outputRegionsUsedOnTile) {
spread.add(std::make_pair(region, 1));
}
}
return std::max_element(spread.begin(), spread.end(), comp)->second;
}
// Get the maximum number of elements on any tile for a mapping.
//
// reducedMapping is a vector of tiles, each of which
// contains a vector of tensor regions. The length of the regions
// on each tile is summed and the maximum total is returned.
static unsigned getMaxElementsPerTile(
const std::vector<std::vector<Interval>> &reducedMapping) {
// The current maximum.
unsigned maxElementsPerTile = 0;
for (const auto &entry : reducedMapping) {
unsigned tileElements =
std::accumulate(entry.begin(), entry.end(), 0U,
[](unsigned sum, const Interval ®ion) {
return sum + region.end() - region.begin();
});
maxElementsPerTile = std::max(maxElementsPerTile, tileElements);
}
return maxElementsPerTile;
}
// Get the maximum number of partial inputs for any output.
static unsigned getMaxPartialsPerElement(const IntermediatePartials &ipIn) {
boost::icl::interval_map<std::size_t, unsigned> numPartials;
for (auto tile : ipIn.tiles()) {
for (const auto &re : ipIn.outputRegions(tile))
numPartials += std::make_pair(re, 1U);
}
return std::max_element(numPartials.begin(), numPartials.end())->second;
}
// Estimate how many cycles the final reduction step will take if we send the
// partials to the tiles where the output is mapped and do the reduction there.
static unsigned
estimateReduceAtDstCost(const Target &target, const IntermediatePartials &ipIn,
const Graph::TileToTensorMapping &outMapping) {
const auto partialType = ipIn.dataType();
const auto partialTypeBytes = target.getTypeSize(partialType);
const auto partialVectorWidth = target.getVectorWidth(partialType);
// The maximum number of partials that are reduced to a single output.
unsigned maxPartialsPerElement = getMaxPartialsPerElement(ipIn);
// Get the maximum number of partials that need to be sent to each tile
// for the reduction.
std::size_t maxElementsPerTile = getMaxElementsPerTile(outMapping);
// How many bytes we might have to send from each tile before computation.
const auto preComputeExchangeBytes = maxElementsPerTile * partialTypeBytes;
// How quickly exchange happens.
const auto exchangeBytesPerCycle = target.getExchangeBytesPerCycle();
// Get the delay caused by syncing i.e. the time before when all tiles
// are done, and when the last tile is released from sync.
const auto syncCycles = target.getMaxIPUSyncDelay();
unsigned cycles = 0;
// Pre-exchange.
cycles += (preComputeExchangeBytes + exchangeBytesPerCycle - 1) /
exchangeBytesPerCycle;
// Compute
cycles +=
maxPartialsPerElement *
((maxElementsPerTile + partialVectorWidth - 1) / partialVectorWidth);
// Sync
cycles += syncCycles;
// There's no post-exchange step here.
return cycles;
}
// Estimate how many cycles the reduce will cost if we send the partials to
// every tile, do the reduction, and then send the reduced values to the tiles
// where the output is mapped.
static unsigned estimateBalancedReduceCost(
const Target &target, const IntermediatePartials &ipIn, Type reducedType,
std::size_t numReducedElements,
const Graph::TileToTensorMapping &outMapping, unsigned grainSize) {
// The type of the elements we are summing.
const auto partialType = ipIn.dataType();
const auto partialTypeBytes = target.getTypeSize(partialType);
const auto partialVectorWidth = target.getVectorWidth(partialType);
const auto reducedTypeBytes = target.getTypeSize(reducedType);
// Split the reduced elements into groups of size `grainSize` and
// get the number of groups.
unsigned numReducedGroups = (numReducedElements + grainSize - 1) / grainSize;
const auto numTiles = target.getNumTiles();
// Work out how many groups would go on each tile (at most).
unsigned maxReducedGroups = (numReducedGroups + numTiles - 1) / numTiles;
// The maximum number of elements on each tile.
const auto maxElementsPerTile = maxReducedGroups * grainSize;
// The maximum number of partials that are reduced to a single output.
unsigned maxPartialsPerElement = getMaxPartialsPerElement(ipIn);
// Worst case exchange to get data onto the tile.
const auto preComputeExchangeBytes =
maxElementsPerTile * maxPartialsPerElement * partialTypeBytes;
// Worse case exchange to get data to the destination.
const auto postComputeExchangeBytes =
getMaxElementsPerTile(outMapping) * reducedTypeBytes;
const auto exchangeBytesPerCycle = target.getExchangeBytesPerCycle();
const auto syncCycles = target.getMaxIPUSyncDelay();
unsigned cycles = 0;
// Pre-exchange
cycles += (preComputeExchangeBytes + exchangeBytesPerCycle - 1) /
exchangeBytesPerCycle;
// Sync.
cycles += syncCycles;
// Compute
cycles +=
maxPartialsPerElement *
((maxElementsPerTile + partialVectorWidth - 1) / partialVectorWidth);
// Post-exchange
cycles += (postComputeExchangeBytes + exchangeBytesPerCycle - 1) /
exchangeBytesPerCycle;
// Sync.
cycles += syncCycles;
return cycles;
}
bool shouldReduceAtDestination(const Target &target,
const IntermediatePartials &ipIn,
const Graph::TileToTensorMapping &outMapping,
Type reducedType,
std::size_t numReducedElements) {
// Is it best to do the reduction spread out over lots of tiles, and
// then copy the result to the destination, or do it at the destination?
auto balancedCycles = estimateBalancedReduceCost(
target, ipIn, reducedType, numReducedElements, outMapping, 8);
auto destCycles = estimateReduceAtDstCost(target, ipIn, outMapping);
if (!(destCycles < balancedCycles)) {
logging::popops::debug("Reduce with temporary balanced output");
}
return destCycles < balancedCycles;
}
boost::icl::split_interval_map<std::size_t, std::size_t>
calculateSplit(const IntermediatePartials &ir, std::size_t grainSize,
std::size_t minPieceCols, std::size_t minPieceRows,
std::size_t minPieceSize, unsigned numPieces) {
// Calculate the pieces we should split this into. Basically, first we get
// the entire set of output regions from every tile (preserving splits).
//
// For example if we have the following regions on each tile:
//
// Tile Output regions on tile
//
// 0 |-------| |-------------------| |------|
// 1 |-------| |---------------------| |------------|
// 2 |--------------------------------------------------|
// 3 |----------------|
//
// Then allOutputRegionsSplitIcl is
//
// |-------|----|-|---------|---------|--|------|-----|
// Get the entire set of output regions from every tile.
boost::icl::split_interval_set<std::size_t> allOutputRegionsSplitIcl;
for (auto tile : ir.tiles()) {
allOutputRegionsSplitIcl += ir.outputRegions(tile);
}
// find minimum non-split output region to decide whether to increase
// minimum number of columns in a piece.
typedef decltype(allOutputRegionsSplitIcl)::interval_type IntervalType;
auto getIntervalSize = [](const IntervalType &it) {
return it.upper() - it.lower();
};
const auto minInterval = *std::min_element(
allOutputRegionsSplitIcl.begin(), allOutputRegionsSplitIcl.end(),
[&](const IntervalType &a, const IntervalType &b) {
return getIntervalSize(a) < getIntervalSize(b);
});
auto minIntervalSize = getIntervalSize(minInterval);
// Work out the total amount of data. This is the total number of partials
// in the reduction.
std::size_t totalDataSize = 0;
for (auto tile : ir.tiles())
totalDataSize += ir.data(tile).numElements();
// Find the average partials per output in this intermediate reduction stage.
// As this is the internediate stage, this gives the average number of
// tiles which have partials to contribute to each output. We use the square
// root of the average number of tiles as the number of output partials.
const auto averageSplit =
static_cast<std::size_t>(std::sqrt(totalDataSize / ir.outputSize()));
// Use a different minimum columns only if the minimum interval size allows
// one to be used. This has the effect of increasing the number of reductions
// per output and also reducing the amount of exchange size as grain size
// per tile is increased.
const auto averageGrainFactor = (minIntervalSize / grainSize) / averageSplit;
const auto minPieceColsToUse =
std::max(minPieceCols, averageGrainFactor * grainSize);
if (minPieceColsToUse != minPieceCols) {
logging::popops::debug(
"Intermediate stage minimum columns changed from {} -> {}",
minPieceCols, minPieceColsToUse);
}
// We should have an output for every element in the final tensor.
assert(allOutputRegionsSplitIcl.size() == ir.outputSize());
auto allOutputRegions = splitIntervalSetToPoplar(allOutputRegionsSplitIcl);
// Add extra splits so that we have at least numPieces pieces.
// splitRegions is used here rather than splitRegionsBetweenWorkers
// because the former never merges regions, and the latter might merge them.
auto split = poputil::splitRegions(allOutputRegions, grainSize, numPieces,
minPieceColsToUse);
// Finally if that is not enough, work out the total amount of data, divide
// it by numPieces to give how much data should be in each piece.
// Then go through the output intervals and set the number of splits so
// that each has roughly that amount of data.
std::size_t idealPieceSize = totalDataSize / numPieces;
// Avoid division by zero later.
if (idealPieceSize < 1)
idealPieceSize = 1;
// Work out the answer.
boost::icl::split_interval_map<std::size_t, std::size_t> splitMap;
const auto &tilesForOutput = ir.getTilesForOutput();
// splitRegions() decides a partition (split is a vector of vectors) but
// we ignore than and just loop over every region, ignoring which partition
// it is in.
for (const auto &partition : split) {
for (const auto &re : partition) {
auto numPartials = tilesForOutput(re.begin()).size();
auto numCols = re.size();
// TODO: T12969 This would be more elegant if we work out how many rows
// each piece is rather than how many there are.
auto N = (numPartials * numCols) / idealPieceSize;
// Prevent divide by zero.
if (N < 1)
N = 1;
if ((numPartials * numCols) / N < minPieceSize)
N = (numPartials * numCols) / minPieceSize;
if (N < 1)
N = 1;
if (numPartials / N < minPieceRows)
N = numPartials / minPieceRows;
if (N < 1)
N = 1;
auto iclRe =
boost::icl::interval<std::size_t>::right_open(re.begin(), re.end());
splitMap.insert(std::make_pair(iclRe, N));
}
}
return splitMap;
}
NextStep calculateNextStep(const Target &target,
const IntermediatePartials &ir) {
// Should we do another intermediate reduction stage, or go straight to the
// destination reduction?
unsigned maxSources = 0;
for (const auto &t : ir.getTilesForOutput()) {
auto numTileSources = t.second.size();
if (maxSources < numTileSources)
maxSources = numTileSources;
}
// If the outputs occupy most of the tiles and the fan-in is low enough go
// straight to an output stage. This should require less exchange and control
// code without being significantly slower.
if ((maxSources < 2 * sqrt(target.getTilesPerIPU())) &&
(ir.tiles().size() > target.getTilesPerIPU() * 3 / 4))
return INTERMEDIATE_TO_OUTPUT;
// Basically, see how much data is left. If it is a lot, do another step.
std::size_t totalDataSize = 0;
for (auto tile : ir.tiles())
totalDataSize += ir.data(tile).numElements();
// Optimisation: reductionFactorThresholdToAddMoreStages was found empirically
// and hasn't been tested a lot. E.g. on different sizes of IPUs.
if (totalDataSize > ir.outputSize() * reductionFactorThresholdToAddMoreStages)
return INTERMEDIATE_TO_INTERMEDIATE;
return INTERMEDIATE_TO_OUTPUT;
}
} // namespace popops
| 38.355372 | 80 | 0.688501 | [
"vector"
] |
06f57fac6318991507d1300ddf5635ec7d86e2fc | 18,368 | cpp | C++ | src/Node.cpp | Sygmei/Kitanai | 745b93fc7a41f4f7eb84b588dc76dd375643c0a6 | [
"MIT"
] | 6 | 2017-12-30T12:16:04.000Z | 2021-05-23T00:08:22.000Z | src/Node.cpp | Mizugola/Kitanai | 745b93fc7a41f4f7eb84b588dc76dd375643c0a6 | [
"MIT"
] | null | null | null | src/Node.cpp | Mizugola/Kitanai | 745b93fc7a41f4f7eb84b588dc76dd375643c0a6 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <sstream>
#include <Node.hpp>
#include <Program.hpp>
#include <StdLib.hpp>
namespace ktn
{
bool Node::_execDebug = false;
bool Node::_compDebug = false;
bool Node::_dispMemAd = false;
int Node::NodeAmount = 0;
Node::Node(TokenType type)
{
this->type = type;
this->id = NodeAmount++;
}
Node::Node(TokenType type, const std::string& value)
{
this->type = type;
this->value = value;
this->id = NodeAmount++;
}
void Node::setParent(Node* parent)
{
this->parent = parent;
this->parentID = this->parent->getID();
}
int Node::getID() const
{
return this->id;
}
std::string Node::getSummary() const
{
std::ostringstream address;
address << (void const *)this;
return "[<" + std::to_string(id) + "> " + this->getPrintableType()
+ ((this->getValue() != "") ? " (" + this->value + ")" : "") +
((_dispMemAd) ? std::string(" @") + address.str() : std::string()) + "]";
}
TokenType Node::getType() const
{
return this->type;
}
std::string Node::getPrintableType() const
{
return Token::FindByType(this->type).name;
}
void Node::setType(TokenType type)
{
this->type = type;
}
std::string Node::getValue() const
{
return this->value;
}
void Node::addParameter(Node token)
{
token.setParent(this);
this->parameters.push_back(token);
}
std::vector<Node>* Node::getParameters()
{
return ¶meters;
}
void Node::insertAfter(int id, Node token)
{
for (int i = 0; i < parameters.size(); i++) {
if (parameters[i].getID() == id) {
token.setParent(this);
parameters.insert(parameters.begin() + i + 1, token);
break;
}
}
}
Node* Node::getParent() const
{
return this->parent;
}
int Node::getParentID() const
{
return this->parentID;
}
void Node::inspect(int depth)
{
for (int i = 0; i < depth; i++) std::cout << " ";
std::cout << getSummary() << std::endl;
for (Node childToken : parameters) {
childToken.inspect(depth + 1);
}
}
void Node::execute(Program* prg)
{
std::vector<Node> parametersExecution = parameters;
doChainAdoption();
if (getType() == TokenType::Condition && prg->canExecute()) {
parametersExecution[0].execute(prg);
}
else if (getType() == TokenType::Function && getValue() == "func") {
}
else
{
for (Node& tok : parametersExecution) {
tok.execute(prg);
}
}
if (getType() != TokenType::Null && parent != nullptr) {
prg->setDepth(getDepth());
if (prg->canExecute()) {
if (_execDebug) std::cout << "[Exe] Execute Node : " << getSummary() << std::endl;
if (getType() == TokenType::Function) {
if (_execDebug) std::cout << "[Exe::Function] Call function : " << getValue()
<< " (" << StdLib::FunctionsName[getValue()].second << " args)" << std::endl;
if (_execDebug) std::cout << "[Exe::Function] Arg List : " << std::endl;
for (Node fctArg : parametersExecution) {
if (_execDebug) std::cout << " [Exe::FunctionArg] : " << fctArg.getSummary() << std::endl;
}
Node returnValue = StdLib::FunctionsName[getValue()].first(parametersExecution);
returnValue.doChainAdoption();
returnValue.setParent(this);
returnValue.execute(prg);
if (_execDebug) std::cout << "[Exe::Function] " << getValue() << " returned : " << returnValue.getValue() << std::endl;
this->type = returnValue.getType();
this->value = returnValue.getValue();
}
else if (getType() == TokenType::StackAt) {
if (getInstructionContent(parametersExecution).getType() == TokenType::String) {
prg->setStackPosition(getInstructionContent(parametersExecution).getValue());
}
else if (getInstructionContent(parametersExecution).getType() == TokenType::Number) {
prg->setStackPosition(std::stoi(getInstructionContent(parametersExecution).getValue()));
}
if (_execDebug) std::cout << "[Exe:StackAt] StackPosition is now at : $" << prg->getStackPosition().first << "+"
<< prg->getStackPosition().second << std::endl;
this->type = TokenType::Null;
this->value = "";
}
else if (getType() == TokenType::Condition) {
Node condition = getInstructionContent(parametersExecution);
if (_execDebug) std::cout << "[Exe:Condition] Condition result : " << condition.getSummary() << std::endl;
if (condition.getType() == TokenType::Number && condition.getValue() == "1") {
if (_execDebug) std::cout << "[Exe::Condition] Condition is fulfilled (First Branch)" << std::endl;
parametersExecution[1].execute(prg);
}
else if (parametersExecution.size() > 2 && condition.getType() == TokenType::Number && condition.getValue() == "0") {
if (_execDebug) std::cout << "[Exe::Condition] Condition is not fulfilled (Second Branch)" << std::endl;
parametersExecution[2].execute(prg);
}
}
else if (getType() == TokenType::CurrentStackValue) {
Node valueAt = prg->getStackAt();
this->type = valueAt.getType();
this->value = valueAt.getValue();
if (_execDebug) std::cout << "[Exe:CurrentStackValue] : Current StackValue (at $" << prg->getStackPosition().first
<< "+" << prg->getStackPosition().second << "): " << valueAt.getSummary() << std::endl;
}
else if (getType() == TokenType::StackSize) {
this->type = TokenType::Number;
this->value = std::to_string(prg->getStackSize());
}
else if (getType() == TokenType::StackLeft) {
prg->setStackPosition(prg->getStackPosition().second - 1);
this->type = TokenType::Null;
this->value = "";
}
else if (getType() == TokenType::StackRight) {
prg->setStackPosition(prg->getStackPosition().second + 1);
this->type = TokenType::Null;
this->value = "";
}
else if (getType() == TokenType::CurrentStackPosition) {
this->type = TokenType::String;
this->value = prg->getStackPosition().first;
}
else if (getType() == TokenType::CurrentSubStackPosition) {
this->type = TokenType::Number;
this->value = std::to_string(prg->getStackPosition().second);
}
else if (getType() == TokenType::StackAccess) {
if (_execDebug) std::cout << "[Exe:StackAccess] : Store value : "
<< getInstructionContent(parametersExecution).getSummary() << " at $"
<< prg->getStackPosition().first << "+" << prg->getStackPosition().second << std::endl;
prg->storeInStack(getInstructionContent(parametersExecution));
this->type = TokenType::Null;
this->value = "";
}
else if (getType() == TokenType::Instruction && getValue() != "Ignore") {
this->type = getInstructionContent(parametersExecution).getType();
this->value = getInstructionContent(parametersExecution).getValue();
}
else if (getType() == TokenType::Goto) {
Node jumpDest = getInstructionContent(parametersExecution);
if (jumpDest.getType() == TokenType::Origin) {
prg->setSeekedFlag(prg->getNextOrigin());
if (_execDebug) std::cout << "[Exe:Goto] : Goto Origin : " << prg->getNextOrigin() << std::endl;
prg->stopExecution(TokenType::Origin);
}
else {
if (_execDebug) std::cout << "[Exe:Goto] : Goto flag : "
<< getInstructionContent(parametersExecution).getValue() << std::endl;
if (_execDebug) std::cout << "[Exe::Goto] : Add Origin Marker : "
<< getInstructionContent(parametersExecution, 1).getValue() << std::endl;
prg->addOrigin(std::stoi(getInstructionContent(parametersExecution, 1).getValue()));
prg->setSeekedFlag(std::stoi(getInstructionContent(parametersExecution).getValue()));
prg->stopExecution(TokenType::Goto);
}
}
else if (getType() == TokenType::GotoNoOrigin) {
prg->setSeekedFlag(std::stoi(getInstructionContent(parametersExecution).getValue()));
prg->stopExecution(TokenType::Goto);
this->type = TokenType::Null;
this->value = "";
}
else if (getType() == TokenType::ToggleExecution) {
prg->stopExecution(TokenType::ToggleExecution);
this->type = TokenType::Null;
this->value = "";
}
else if (getType() == TokenType::End) {
prg->stopProgram();
this->type = TokenType::Null;
this->value = "";
}
}
else if (getType() == TokenType::ToggleExecution && prg->getPauseCause() == TokenType::ToggleExecution) {
prg->startExecution();
this->type = TokenType::Null;
this->value = "";
}
else if (TokenType::Flag == this->getType() && prg->getSeekedFlag() == std::stoi(this->getValue()) && prg->getPauseCause() == TokenType::Goto) {
if (_execDebug) std::cout << "[Exe:Flag] Flag found : Restarting execution" << std::endl;
prg->startExecution();
}
else if (TokenType::DynamicFlag == this->getType() && prg->getSeekedFlag() == std::stoi(this->getValue())) {
if (_execDebug) std::cout << "[Exe:Flag] DynamicFlag found : Restarting execution" << std::endl;
prg->startExecution();
if (prg->getPauseCause() == TokenType::Origin)
prg->removeOriginFlag(*this);
}
}
}
Node Node::getInstructionContent(std::vector<Node>& tokens, int index)
{
int cIndex = 0;
for (Node token : tokens) {
if (token.getType() == TokenType::Instruction && token.getValue() == "Ignore") {
}
else if (token.getType() != TokenType::Null && cIndex == index) {
return token;
}
else if (token.getType() != TokenType::Null) {
cIndex++;
}
}
return Node(TokenType::Null);
}
Node* Node::getAtID(int id)
{
if (this->id == id) {
return this;
}
else
{
for (Node& childToken : parameters) {
if (childToken.getAtID(id) != nullptr) {
return childToken.getAtID(id);
}
}
return nullptr;
}
}
void Node::eraseNodeAtId(int id)
{
for (int i = 0; i < parameters.size(); i++) {
if (parameters[i].getID() == id) {
parameters.erase(parameters.begin() + i);
break;
}
}
}
int Node::getDepth() const
{
int depth = 0;
Node* tParent = getParent();
while (tParent != nullptr) {
depth++;
tParent = tParent->getParent();
}
return depth;
}
void Node::doChainAdoption()
{
for (Node& token : parameters) {
token.setParent(this);
token.doChainAdoption();
}
}
void Node::doAST()
{
for (Node& token : parameters) {
token.doAST();
}
int i = 0;
while (i < parameters.size()) {
Node& tok = parameters[i];
if (_compDebug) std::cout << " [Compilation:AST] Current Node : " << tok.getSummary() << std::endl;
for (int it = 0; it < TypeParameters.size(); it++) {
int blocIndex = i + 1;
if (tok.getType() == TypeParameters[it][0]) {
if (_compDebug) std::cout << " [Compilation:AST:Rule] Trying to apply following rule : ";
for (int ik = 0; ik < TypeParameters[it].size(); ik++) {
if (_compDebug) std::cout << Token::FindByType(TypeParameters[it][ik]).name << ";";
}
if (_compDebug) std::cout << " (Size : " << TypeParameters[it].size() << ")" << std::endl;
bool noAdd = true;
std::vector<Node> toAdd;
for (int iPara = 1; iPara < TypeParameters[it].size(); iPara++) {
if (_compDebug) std::cout << " [Compilation:AST:Rule] Expect : "
<< Token::FindByType(TypeParameters[it][iPara]).name << std::endl;
if (_compDebug) std::cout << " [Compilation:AST:Rule] Got : "
<< parameters[blocIndex].getSummary() << std::endl;
if (TypeParameters[it][iPara] == parameters[blocIndex].getType()) {
if (_compDebug) std::cout << " [Compilation:AST:Rule] Add Parameter : "
<< parameters[blocIndex].getSummary() << std::endl;
noAdd = false;
toAdd.push_back(parameters[blocIndex++]);
}
else {
noAdd = true;
break;
}
}
if (!noAdd) {
for (int i = 0; i < toAdd.size(); i++) {
tok.addParameter(toAdd[i]);
this->eraseNodeAtId(toAdd[i].getID());
}
break;
}
}
}
i++;
}
}
void Node::doParametersAffectation()
{
for (Node& tok : parameters) {
tok.doParametersAffectation();
}
for (int i = 0; i < parameters.size(); i++) {
Node& tok = parameters[i];
if (tok.getType() == TokenType::Function) {
if (_compDebug) std::cout << "[Compilation:FunctionArgs] Searching args for Function : "
<< tok.getSummary() << std::endl;
std::vector<int> indexToErase;
for (int j = i + 1; j < StdLib::FunctionsName[tok.getValue()].second + i + 1; j++) {
if (_compDebug) std::cout << " [Compilation:FunctionsArgs:Parameter] : Adding parameter : "
<< parameters[j].getSummary() << std::endl;
tok.addParameter(parameters[j]);
indexToErase.push_back(j);
}
std::reverse(indexToErase.begin(), indexToErase.end());
for (int j = 0; j < indexToErase.size(); j++) {
parameters.erase(parameters.begin() + indexToErase[j]);
}
}
}
}
void Node::doDynamicFlags(int& flagCounter)
{
for (int i = 0; i < parameters.size(); i++) {
int tokID = parameters[i].getID();
getAtID(tokID)->doDynamicFlags(flagCounter);
if (getAtID(tokID)->getType() == TokenType::Goto || this->getAtID(tokID)->getType() == TokenType::Condition) {
if (getAtID(tokID)->getType() == TokenType::Goto && getAtID(tokID)->getParameters()->size() == 1
&& getAtID(tokID)->getParameters()->at(0).getType() == TokenType::Number) {
if (_compDebug) std::cout << " [Compilation:DynaFlag] Creating DynamicFlag for Goto Instruction : "
<< getAtID(tokID)->getSummary() << std::endl;
this->insertAfter(tokID, Node(TokenType::DynamicFlag, std::to_string(++flagCounter)));
getAtID(tokID)->addParameter(Node(TokenType::Number, std::to_string(flagCounter)));
}
else if (getAtID(tokID)->getType() == TokenType::Condition && getAtID(tokID)->getParameters()->size() == 3
&& getAtID(tokID)->getParameters()->at(1).getType() == TokenType::Instruction) {
if (_compDebug) std::cout << "[Compilation:DynaFlag] Creating DynamicFlag for Condition Instruction : "
<< getAtID(tokID)->getSummary() << std::endl;
this->insertAfter(tokID, Node(TokenType::DynamicFlag, std::to_string(++flagCounter)));
Node firstBranchJump = Node(TokenType::GotoNoOrigin);
firstBranchJump.addParameter(Node(TokenType::Number, std::to_string(flagCounter)));
Node& firstBranch = getAtID(tokID)->getParameters()->at(1);
firstBranch.addParameter(firstBranchJump);
}
}
}
}
} | 45.805486 | 156 | 0.483885 | [
"vector"
] |
06fe15ebc9ee92a915bef7cab60a2b23c2cddd48 | 4,604 | cc | C++ | mts/src/model/QueryCoverJobListResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | mts/src/model/QueryCoverJobListResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | mts/src/model/QueryCoverJobListResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/mts/model/QueryCoverJobListResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Mts;
using namespace AlibabaCloud::Mts::Model;
QueryCoverJobListResult::QueryCoverJobListResult() :
ServiceResult()
{}
QueryCoverJobListResult::QueryCoverJobListResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryCoverJobListResult::~QueryCoverJobListResult()
{}
void QueryCoverJobListResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allCoverJobListNode = value["CoverJobList"]["CoverJob"];
for (auto valueCoverJobListCoverJob : allCoverJobListNode)
{
CoverJob coverJobListObject;
if(!valueCoverJobListCoverJob["CreationTime"].isNull())
coverJobListObject.creationTime = valueCoverJobListCoverJob["CreationTime"].asString();
if(!valueCoverJobListCoverJob["State"].isNull())
coverJobListObject.state = valueCoverJobListCoverJob["State"].asString();
if(!valueCoverJobListCoverJob["UserData"].isNull())
coverJobListObject.userData = valueCoverJobListCoverJob["UserData"].asString();
if(!valueCoverJobListCoverJob["Code"].isNull())
coverJobListObject.code = valueCoverJobListCoverJob["Code"].asString();
if(!valueCoverJobListCoverJob["Message"].isNull())
coverJobListObject.message = valueCoverJobListCoverJob["Message"].asString();
if(!valueCoverJobListCoverJob["PipelineId"].isNull())
coverJobListObject.pipelineId = valueCoverJobListCoverJob["PipelineId"].asString();
if(!valueCoverJobListCoverJob["Id"].isNull())
coverJobListObject.id = valueCoverJobListCoverJob["Id"].asString();
auto allCoverImageListNode = valueCoverJobListCoverJob["CoverImageList"]["CoverImage"];
for (auto valueCoverJobListCoverJobCoverImageListCoverImage : allCoverImageListNode)
{
CoverJob::CoverImage coverImageListObject;
if(!valueCoverJobListCoverJobCoverImageListCoverImage["Time"].isNull())
coverImageListObject.time = valueCoverJobListCoverJobCoverImageListCoverImage["Time"].asString();
if(!valueCoverJobListCoverJobCoverImageListCoverImage["Score"].isNull())
coverImageListObject.score = valueCoverJobListCoverJobCoverImageListCoverImage["Score"].asString();
if(!valueCoverJobListCoverJobCoverImageListCoverImage["Url"].isNull())
coverImageListObject.url = valueCoverJobListCoverJobCoverImageListCoverImage["Url"].asString();
coverJobListObject.coverImageList.push_back(coverImageListObject);
}
auto inputNode = value["Input"];
if(!inputNode["Object"].isNull())
coverJobListObject.input.object = inputNode["Object"].asString();
if(!inputNode["Location"].isNull())
coverJobListObject.input.location = inputNode["Location"].asString();
if(!inputNode["Bucket"].isNull())
coverJobListObject.input.bucket = inputNode["Bucket"].asString();
auto coverConfigNode = value["CoverConfig"];
auto outputFileNode = coverConfigNode["OutputFile"];
if(!outputFileNode["Object"].isNull())
coverJobListObject.coverConfig.outputFile.object = outputFileNode["Object"].asString();
if(!outputFileNode["Location"].isNull())
coverJobListObject.coverConfig.outputFile.location = outputFileNode["Location"].asString();
if(!outputFileNode["Bucket"].isNull())
coverJobListObject.coverConfig.outputFile.bucket = outputFileNode["Bucket"].asString();
coverJobList_.push_back(coverJobListObject);
}
auto allNonExistIds = value["NonExistIds"]["String"];
for (const auto &item : allNonExistIds)
nonExistIds_.push_back(item.asString());
if(!value["NextPageToken"].isNull())
nextPageToken_ = value["NextPageToken"].asString();
}
std::vector<QueryCoverJobListResult::CoverJob> QueryCoverJobListResult::getCoverJobList()const
{
return coverJobList_;
}
std::string QueryCoverJobListResult::getNextPageToken()const
{
return nextPageToken_;
}
std::vector<std::string> QueryCoverJobListResult::getNonExistIds()const
{
return nonExistIds_;
}
| 41.107143 | 103 | 0.776933 | [
"object",
"vector",
"model"
] |
66096b9b0b5c99ec19886d251bc5c4fc101e6d0f | 2,271 | cc | C++ | tests/end_to_end/file_creation_client.cc | xicheng87/cppGFS2.0 | c17ee0b169516c6959bf7782ae98d309a3e9685b | [
"Apache-2.0"
] | 23 | 2021-05-01T19:14:12.000Z | 2022-03-31T08:02:19.000Z | tests/end_to_end/file_creation_client.cc | Michael-Tu/cppGFS2.0 | ce59d04a452697ec257ac3c27aa6c6fe1fd5f597 | [
"Apache-2.0"
] | 23 | 2020-04-29T02:56:25.000Z | 2021-01-25T20:49:27.000Z | tests/end_to_end/file_creation_client.cc | xicheng87/cppGFS2.0 | c17ee0b169516c6959bf7782ae98d309a3e9685b | [
"Apache-2.0"
] | 9 | 2021-08-22T06:48:18.000Z | 2022-03-30T14:36:08.000Z | #include <thread>
#include <vector>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "src/client/gfs_client.h"
#include "src/common/system_logger.h"
// TODO(Xi): Refactor the following and init() into a util.h as many tests
// may reuse this piece
ABSL_FLAG(std::string, config_path, "file_creation_test/config.yaml",
"/path/to/config.yml");
ABSL_FLAG(std::string, master_name, "master_server_01",
"master name for this client to talk to");
// Init function to initialize the client
void init() {
const std::string config_path = absl::GetFlag(FLAGS_config_path);
const std::string master_name = absl::GetFlag(FLAGS_master_name);
const bool resolve_hostname(true);
LOG(INFO) << "Calling init_client...";
auto init_status(gfs::client::init_client(config_path, master_name,
resolve_hostname));
if (!init_status.ok()) {
LOG(ERROR) << "Client initialization failed with error: "
<< init_status.error_message();
exit(-1);
}
}
// Create a single file
void singleFileCreation(const std::string& filename) {
init();
auto create_foo_status(gfs::client::open(filename.c_str(),
gfs::OpenFlag::Create));
if (!create_foo_status.ok()) {
LOG(ERROR) << "Open to create " + filename + " failed with error: "
<< create_foo_status.error_message();
exit(1);
} else {
LOG(INFO) << "Open to create " + filename + " succeeded";
}
}
// Launch multiple threads and have each to create a file concurrently
void concurrentFileCreation(const unsigned int num_of_threads) {
std::vector<std::thread> threads;
for (unsigned int i = 0; i < num_of_threads; i++) {
threads.push_back(std::thread(singleFileCreation, "/foo"
+ std::to_string(i)));
}
for (auto& t : threads) {
t.join();
}
}
int main(int argc, char** argv) {
// Initialize system log and parse command line options
gfs::common::SystemLogger::GetInstance().Initialize(argv[0]);
absl::ParseCommandLine(argc, argv);
// Simple test case, create a single file
singleFileCreation("/foo");
// Conrurrent file creation
concurrentFileCreation(50);
return 0;
}
| 32.442857 | 74 | 0.647292 | [
"vector"
] |
6609cca4425eddcc9b94aa70bb102b1190f6f89d | 2,291 | cpp | C++ | gamegio-library/src/gamegio/ParticlesItem.cpp | tril0byte/HGamer3D | 7979c67d9b4672a5b2d1a50320a6d47b1a97ff05 | [
"Apache-2.0"
] | 27 | 2015-06-08T16:45:47.000Z | 2022-02-22T14:40:52.000Z | gamegio-library/src/gamegio/ParticlesItem.cpp | tril0byte/HGamer3D | 7979c67d9b4672a5b2d1a50320a6d47b1a97ff05 | [
"Apache-2.0"
] | 18 | 2015-04-20T20:42:02.000Z | 2020-12-11T03:46:17.000Z | gamegio-library/src/gamegio/ParticlesItem.cpp | tril0byte/HGamer3D | 7979c67d9b4672a5b2d1a50320a6d47b1a97ff05 | [
"Apache-2.0"
] | 4 | 2017-06-20T13:24:18.000Z | 2021-10-07T19:18:03.000Z | // C++ part of bindings for graphics
// HGamer3D Library (A project to enable 3D game development in Haskell)
// Copyright 2018 Peter Althainz
//
// Distributed under the Apache License, Version 2.0
// (See attached file LICENSE or copy at
// http://www.apache.org/licenses/LICENSE-2.0)
//
// file: HGamer3D/gamegio-library/src/gamegio/ParticlesItem.cpp
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include "Fresco.hpp"
#include "Vec3Cbor.hpp"
#include "UnitQuaternionCbor.hpp"
#include "EntityIdCbor.hpp"
#include "ParentCbor.hpp"
#include "ParticlesItem.hpp"
#include "ParticlesItemCbor.hpp"
#include "VisibleCbor.hpp"
#include "Graphics3DSystem.hpp"
#include <Urho3D/Math/Vector3.h>
#include <Urho3D/Math/Quaternion.h>
#include <Urho3D/Graphics/ParticleEffect.h>
using namespace std;
GIO_METHOD_FUNC(ParticlesItem, ParticlesItem)
GIO_METHOD_FUNC(ParticlesItem, Pos)
GIO_METHOD_FUNC(ParticlesItem, Scale)
GIO_METHOD_FUNC(ParticlesItem, Ori)
GIO_METHOD_FUNC(ParticlesItem, EntityId)
GIO_METHOD_FUNC(ParticlesItem, Parent)
GIO_METHOD_FUNC(ParticlesItem, Visible)
// Factory Implementation
GCO_FACTORY_IMP(ParticlesItem)
GCO_FACTORY_METHOD(ParticlesItem, ctParticles, ParticlesItem)
GCO_FACTORY_METHOD(ParticlesItem, ctPosition, Pos)
GCO_FACTORY_METHOD(ParticlesItem, ctScale, Scale)
GCO_FACTORY_METHOD(ParticlesItem, ctOrientation, Ori)
GCO_FACTORY_METHOD(ParticlesItem, ctEntityId, EntityId)
GCO_FACTORY_METHOD(ParticlesItem, ctParent, Parent)
GCO_FACTORY_METHOD(ParticlesItem, ctVisible, Visible)
GCO_FACTORY_IMP_END
ParticlesItem::ParticlesItem()
{
}
FrItem ParticlesItem::msgCreate(FrMsg m, FrMsgLength l)
{
ParticlesItem *ti = new ParticlesItem();
ti->emitter = ti->node->CreateComponent<ParticleEmitter>();
return (FrItem)ti;
}
ParticlesItem::~ParticlesItem()
{
}
void ParticlesItem::msgDestroy()
{
delete this;
}
void ParticlesItem::msgParticlesItem(FrMsg m, FrMsgLength l) {
CborParser parser; CborValue it;
cbor_parser_init(m, l, 0, &parser, &it);
cbd::Particles part;
cbd::readParticles(&it, &part);
ResourceCache* cache = node->GetSubsystem<ResourceCache>();
emitter->SetEffect(cache->GetResource<ParticleEffect>(part.data.ParticleEffectResource.value0.c_str()));
}
| 27.60241 | 106 | 0.77739 | [
"3d"
] |
660eaed5fba1334979ccbb0495ee644df25d2a6d | 1,272 | cpp | C++ | src/fbw/src/InterpolatingLookupTable.cpp | erso44/a32nx | 8a134d1903f04bf0c722b6ae6af1467f62b72c01 | [
"MIT"
] | 1 | 2021-05-10T17:37:36.000Z | 2021-05-10T17:37:36.000Z | src/fbw/src/InterpolatingLookupTable.cpp | crazytimtimtim/a32nx | df3ae2169b153eb265c8759f029a7e9ffeca3eeb | [
"MIT"
] | null | null | null | src/fbw/src/InterpolatingLookupTable.cpp | crazytimtimtim/a32nx | df3ae2169b153eb265c8759f029a7e9ffeca3eeb | [
"MIT"
] | null | null | null | #include "InterpolatingLookupTable.h"
using namespace std;
void InterpolatingLookupTable::initialize(vector<pair<double, double>> mapping, double minimum, double maximum) {
mappingTable = std::move(mapping);
mappingMinimum = minimum;
mappingMaximum = maximum;
}
double InterpolatingLookupTable::get(double value) {
if (mappingTable.empty()) {
// not initialized yet
return 0;
}
// iterate over values and do interpolation
for (std::size_t i = 0; i < mappingTable.size() - 1; ++i) {
if (mappingTable[i].first <= value && mappingTable[i + 1].first >= value) {
// calculate differences
double diff_x = value - mappingTable[i].first;
double diff_n = mappingTable[i + 1].first - mappingTable[i].first;
// interpolation
double result = mappingTable[i].first;
if (diff_n != 0) {
result = mappingTable[i].second + (mappingTable[i + 1].second - mappingTable[i].second) * diff_x / diff_n;
}
// clip the result to minimum and maximum
if (result < mappingMinimum) {
return mappingMinimum;
} else if (result > mappingMaximum) {
return mappingMaximum;
}
// no clipping needed -> return result
return result;
}
}
// not in range
return 0;
}
| 28.266667 | 114 | 0.647013 | [
"vector"
] |
66141f3cb961c402522a2c14067e776a9bc3b391 | 2,715 | hpp | C++ | third_party/boost/thread.hpp | madsys-dev/flashmob | 1ac0542ef10e2ee31f2c7d587b8c8d3376e98c80 | [
"MIT"
] | 10 | 2021-09-26T05:14:45.000Z | 2022-02-28T20:32:15.000Z | third_party/boost/thread.hpp | flashmobwalk/flashmob | 1ac0542ef10e2ee31f2c7d587b8c8d3376e98c80 | [
"MIT"
] | null | null | null | third_party/boost/thread.hpp | flashmobwalk/flashmob | 1ac0542ef10e2ee31f2c7d587b8c8d3376e98c80 | [
"MIT"
] | 2 | 2022-01-19T08:02:14.000Z | 2022-02-18T01:42:28.000Z | /**
* The code in this file are adapted from
* https://github.com/boostorg/thread/blob/4abafccff4bdeb4b5ac516ff0c2bc7c0dad8bafb/src/pthread/thread.cpp
*/
// Copyright (C) 2001-2003
// William E. Kempf
// Copyright (C) 2007-8 Anthony Williams
// (C) Copyright 2011-2012 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <string>
#include <fstream>
// Get system physical core amount.
int get_max_core_num()
{
try {
using namespace std;
ifstream proc_cpuinfo ("/proc/cpuinfo", ifstream::in);
// const string physical_id("physical id"), core_id("core id");
const string physical_id("physicalid"), core_id("coreid");
typedef std::pair<unsigned, unsigned> core_entry; // [physical ID, core id]
set<core_entry> cores;
core_entry current_core_entry;
string line;
while ( getline(proc_cpuinfo, line) ) {
if (line.empty())
continue;
vector<string> key_val;
// boost::split(key_val, line, boost::is_any_of(":"));
stringstream ss(line);
string item;
while (getline(ss, item, ':')) {
key_val.push_back(item);
}
if (key_val.size() != 2)
continue;
//return std::thread::hardware_concurrency();
string key = key_val[0];
string value = key_val[1];
// boost::trim(key);
// boost::trim(value);
key.erase(remove_if(key.begin(), key.end(), ::isspace), key.end());
value.erase(remove_if(value.begin(), value.end(), ::isspace), value.end());
if (key == physical_id) {
// current_core_entry.first = boost::lexical_cast<unsigned>(value);
current_core_entry.first = stoi(value);
continue;
}
if (key == core_id) {
// current_core_entry.second = boost::lexical_cast<unsigned>(value);
current_core_entry.second = stoi(value);
cores.insert(current_core_entry);
// LOG(WARNING) << current_core_entry.first << " " << current_core_entry.second;
continue;
}
}
// Fall back to hardware_concurrency() in case
// /proc/cpuinfo is formatted differently than we expect.
return cores.size() != 0 ? cores.size() : std::thread::hardware_concurrency();
} catch(...) {
return std::thread::hardware_concurrency();
}
return std::thread::hardware_concurrency();
}
| 33.9375 | 106 | 0.577901 | [
"vector"
] |
661b5110b23676992bbe85841150e7dd678032cc | 1,641 | cpp | C++ | solutions/most_frequent_subtree_sum.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/most_frequent_subtree_sum.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/most_frequent_subtree_sum.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | // Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.
// Examples 1
// Input:
// 5
// / \
// 2 -3
// return [2, -3, 4], since all the values happen only once, return all of them in any order.
// Examples 2
// Input:
// 5
// / \
// 2 -5
// return [2], since 2 happens twice, however -5 only occur once.
// Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
// solution: dfs
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> m;
int maxcount = 0;
int helper(TreeNode* root) {
if (!root) return 0;
int val = root->val + helper(root->left) + helper(root->right);
m[val]++;
maxcount = max(maxcount, m[val]);
return val;
}
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> ans;
helper(root);
for (auto i : m) {
if (i.second == maxcount) ans.push_back(i.first);
}
return ans;
}
}; | 28.293103 | 353 | 0.602072 | [
"vector"
] |
661c28c42b0a0be2127891212337116009df9927 | 3,363 | cpp | C++ | classify.cpp | sathibault/greenlight-poc | bdc5fc22d33503cfcaba3597d757f9d26157a96d | [
"Apache-2.0"
] | null | null | null | classify.cpp | sathibault/greenlight-poc | bdc5fc22d33503cfcaba3597d757f9d26157a96d | [
"Apache-2.0"
] | null | null | null | classify.cpp | sathibault/greenlight-poc | bdc5fc22d33503cfcaba3597d757f9d26157a96d | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <dlib/image_io.h>
#include <dlib/opencv/cv_image.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/svm_threaded.h>
using namespace cv;
extern void init_pose();
extern void update_dets(dlib::array2d<dlib::bgr_pixel>& img, std::vector<dlib::rectangle>& dets);
extern void get_pose(dlib::array2d<dlib::bgr_pixel>&, std::vector<dlib::rectangle>&, int scale, std::vector<dlib::full_object_detection>& shapes, int& closest, dlib::rectangle& bbox);
extern Mat alignFace(Mat image, int indices[], std::vector<Point2f>& landmarks, int size);
extern Mat alignFaceH(Mat image, int indices[], std::vector<Point2f>& landmarks, int size);
extern void init_embedding();
extern void embedding(Mat img, float *features);
std::vector<Point2f> get_image_align_points(dlib::full_object_detection &shape,
int indices[], int n) {
std::vector<Point2f> image_pts;
for (int i = 0; i < n; i++)
image_pts.push_back(cv::Point2f(shape.part(indices[i]).x(),
shape.part(indices[i]).y()));
return image_pts;
}
static int OUTER_EYES_AND_NOSE[3] = {36, 45, 33};
void calc_features(Mat image, float *features) {
}
float diff_time_ms(struct timespec start, struct timespec end) {
return (1e9 * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec)/1e6;
}
typedef dlib::matrix<float,128,1> sample_type;
typedef dlib::linear_kernel<sample_type> lin_kernel;
int main(int argc, char *argv[]) {
float features[128];
dlib::multiclass_linear_decision_function<lin_kernel,std::string> df;
{
std::ifstream inf("faces.svm");
dlib::deserialize(df, inf);
}
init_pose();
init_embedding();
std::vector<std::string> labels;
std::vector<sample_type> samples;
for (int arg=1; arg<argc; arg++) {
DIR *dir = opendir(argv[arg]);
if (dir == NULL) {
fprintf(stderr, "Skipping invalid directory %s\n", argv[arg]);
continue;
}
struct timespec t0,t1a,t1b,t2,t3;
struct dirent *entry;
char filename[255];
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0]=='.') continue;
sprintf(filename, "%s/%s", argv[arg], entry->d_name);
clock_gettime(CLOCK_MONOTONIC, &t0);
Mat image = imread(filename, CV_LOAD_IMAGE_COLOR);
clock_gettime(CLOCK_MONOTONIC, &t1a);
dlib::array2d<dlib::bgr_pixel> dlibImg;
dlib::assign_image(dlibImg, dlib::cv_image<dlib::bgr_pixel>(image));
std::vector<dlib::rectangle> dets;
update_dets(dlibImg, dets);
int closest;
dlib::rectangle loc;
std::vector<dlib::full_object_detection> shapes;
get_pose(dlibImg, dets, 1, shapes, closest, loc);
std::vector<Point2f> alignMarks = get_image_align_points(shapes[closest], OUTER_EYES_AND_NOSE, 3);
Mat face = alignFace(image, OUTER_EYES_AND_NOSE, alignMarks, 96);
clock_gettime(CLOCK_MONOTONIC, &t1b);
embedding(face, features);
clock_gettime(CLOCK_MONOTONIC, &t2);
sample_type mat;
for (int i=0; i<128; i++) mat(i) = features[i];
std::pair<std::string,float> guess = df.predict(mat);
clock_gettime(CLOCK_MONOTONIC, &t3);
printf("%s: %s %f (%0.1f %0.1f %0.1f)\n", filename, guess.first.c_str(), guess.second, diff_time_ms(t0, t1a), diff_time_ms(t1b, t2), diff_time_ms(t2, t3));
}
}
}
| 34.670103 | 183 | 0.681237 | [
"shape",
"vector"
] |
6624e9fdcf6fc784e0fe02dfae2efb775ac8b58c | 11,287 | hpp | C++ | src/advance_functions.hpp | Pressio/pressio4py | 36676dbd112a7c7960ccbf302ff14d4376c819ec | [
"Unlicense",
"BSD-3-Clause"
] | 4 | 2020-07-06T20:01:39.000Z | 2022-03-05T09:23:40.000Z | src/advance_functions.hpp | Pressio/pressio4py | 36676dbd112a7c7960ccbf302ff14d4376c819ec | [
"Unlicense",
"BSD-3-Clause"
] | 19 | 2020-02-27T20:52:53.000Z | 2022-01-13T16:24:49.000Z | src/advance_functions.hpp | Pressio/pressio4py | 36676dbd112a7c7960ccbf302ff14d4376c819ec | [
"Unlicense",
"BSD-3-Clause"
] | 1 | 2022-03-03T16:05:09.000Z | 2022-03-03T16:05:09.000Z | /*
//@HEADER
// ************************************************************************
//
// types.hpp
// Pressio
// Copyright 2019
// National Technology & Engineering Solutions of Sandia, LLC (NTESS)
//
// Under the terms of Contract DE-NA0003525 with NTESS, the
// U.S. Government retains certain rights in this software.
//
// Pressio is licensed under BSD-3-Clause terms of use:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef PRESSIO4PY_PYBINDINGS_ADVANCE_FUNCTIONS_HPP_
#define PRESSIO4PY_PYBINDINGS_ADVANCE_FUNCTIONS_HPP_
namespace pressio4py{
template<class StepperType, class StateType, class TimeType>
void advance_n_steps(StepperType & stepper,
StateType & state,
const TimeType start_time,
const TimeType time_step_size,
const ::pressio::ode::step_count_type num_steps)
{
pressio::ode::advance_n_steps(stepper, state, start_time,
time_step_size, num_steps);
}
template<class StepperType, class StateType, class TimeType, class SolverType>
void advance_n_steps(StepperType & stepper,
StateType & state,
const TimeType start_time,
const TimeType time_step_size,
const ::pressio::ode::step_count_type num_steps,
SolverType & solver)
{
pressio::ode::advance_n_steps(stepper, state, start_time,
time_step_size, num_steps, solver);
}
template<class StepperType, class StateType, class TimeType, class SolverType>
void advance_n_steps_user_solver(StepperType & stepper,
StateType & state,
const TimeType start_time,
const TimeType time_step_size,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pySolver)
{
SolverType sw(pySolver);
pressio::ode::advance_n_steps(stepper, state, start_time,
time_step_size, num_steps, sw);
}
// n_steps, arbitrary dt
template<class StepperType, class StateType, class TimeType, class DtSetter>
void advance_n_steps_dtcb(StepperType & stepper,
StateType & state,
const TimeType start_time,
pybind11::object pyStepSetter,
const ::pressio::ode::step_count_type num_steps)
{
const DtSetter dtSetter(pyStepSetter);
pressio::ode::advance_n_steps(stepper, state, start_time, dtSetter, num_steps);
}
template<
class StepperType, class StateType, class TimeType,
class DtSetter, class SolverType
>
void advance_n_steps_dtcb(StepperType & stepper,
StateType & state,
const TimeType start_time,
pybind11::object pyStepSetter,
const ::pressio::ode::step_count_type num_steps,
SolverType & solver)
{
const DtSetter dtSetter(pyStepSetter);
pressio::ode::advance_n_steps(stepper, state, start_time,
dtSetter, num_steps, solver);
}
template<
class StepperType, class StateType, class TimeType,
class DtSetter, class SolverType
>
void advance_n_steps_dtcb_user_solver(StepperType & stepper,
StateType & state,
const TimeType start_time,
pybind11::object pyStepSetter,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pySolver)
{
SolverType sw(pySolver);
const DtSetter dtSetter(pyStepSetter);
pressio::ode::advance_n_steps(stepper, state, start_time,
dtSetter, num_steps, sw);
}
// observe, fixed dt
template<class StepperType, class StateType, class TimeType, class ObserverType>
void advance_n_steps_and_observe(StepperType & stepper,
StateType & state,
const TimeType start_time,
const TimeType time_step_size,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pyobserver)
{
ObserverType obs(pyobserver);
pressio::ode::advance_n_steps_and_observe(stepper, state, start_time,
time_step_size, num_steps, obs);
}
template<
class StepperType, class StateType, class TimeType,
class ObserverType, class SolverType
>
void advance_n_steps_and_observe(StepperType & stepper,
StateType & state,
const TimeType start_time,
const TimeType time_step_size,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pyobserver,
SolverType & solver)
{
ObserverType obs(pyobserver);
pressio::ode::advance_n_steps_and_observe(stepper, state, start_time,
time_step_size, num_steps,
obs, solver);
}
template<
class StepperType, class StateType, class TimeType,
class ObserverType, class SolverType
>
void advance_n_steps_and_observe_user_solver(StepperType & stepper,
StateType & state,
const TimeType start_time,
const TimeType time_step_size,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pyobserver,
pybind11::object pySolver)
{
SolverType sw(pySolver);
ObserverType obs(pyobserver);
pressio::ode::advance_n_steps_and_observe(stepper, state, start_time,
time_step_size, num_steps, obs, sw);
}
// observe, dt callback
template<
class StepperType, class StateType, class TimeType,
class DtSetter, class ObserverType
>
void advance_n_steps_and_observe_dtcb(StepperType & stepper,
StateType & state,
const TimeType start_time,
pybind11::object pyStepSetter,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pyobserver)
{
const DtSetter dtSetter(pyStepSetter);
ObserverType obs(pyobserver);
pressio::ode::advance_n_steps_and_observe(stepper, state, start_time,
dtSetter, num_steps, obs);
}
template<
class StepperType, class StateType,
class TimeType, class DtSetter,
class ObserverType, class SolverType
>
void advance_n_steps_and_observe_dtcb(StepperType & stepper,
StateType & state,
const TimeType start_time,
pybind11::object pyStepSetter,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pyobserver,
SolverType & solver)
{
const DtSetter dtSetter(pyStepSetter);
ObserverType obs(pyobserver);
pressio::ode::advance_n_steps_and_observe(stepper, state, start_time,
dtSetter, num_steps,
obs, solver);
}
template<
class StepperType, class StateType,
class TimeType, class DtSetter,
class ObserverType, class SolverType
>
void advance_n_steps_and_observe_dtcb_user_solver(StepperType & stepper,
StateType & state,
const TimeType start_time,
pybind11::object pyStepSetter,
const ::pressio::ode::step_count_type num_steps,
pybind11::object pyobserver,
pybind11::object pySolver)
{
SolverType sw(pySolver);
const DtSetter dtSetter(pyStepSetter);
ObserverType obs(pyobserver);
pressio::ode::advance_n_steps_and_observe(stepper, state, start_time,
dtSetter, num_steps, obs, sw);
}
template<typename...> struct BindAdvanceFunctions;
template<class StepperType>
struct BindAdvanceFunctions<std::tuple<StepperType>>
{
template<class ... Args>
static void fixedStepSize(pybind11::module & m)
{
m.def("advance_n_steps",
&advance_n_steps<
StepperType, py_f_arr, ::pressio4py::scalar_t, Args...>);
m.def("advance_n_steps_and_observe",
&advance_n_steps_and_observe<
StepperType, py_f_arr, ::pressio4py::scalar_t, ode_observer_wrapper_type, Args...>);
}
template<class T>
static void fixedStepSizeUserSolver(pybind11::module & m)
{
m.def("advance_n_steps",
&advance_n_steps_user_solver<
StepperType, py_f_arr, ::pressio4py::scalar_t, T>);
m.def("advance_n_steps_and_observe",
&advance_n_steps_and_observe_user_solver<
StepperType, py_f_arr, ::pressio4py::scalar_t, ode_observer_wrapper_type, T>);
}
template<class DtSetter, class ... Args>
static void arbitraryStepSize(pybind11::module & m)
{
m.def("advance_n_steps",
&advance_n_steps_dtcb<
StepperType, py_f_arr, ::pressio4py::scalar_t, DtSetter, Args...>);
m.def("advance_n_steps_and_observe",
&advance_n_steps_and_observe_dtcb<
StepperType, py_f_arr, ::pressio4py::scalar_t, DtSetter, ode_observer_wrapper_type, Args...>);
}
template<class DtSetter, class T>
static void arbitraryStepSizeUserSolver(pybind11::module & m)
{
m.def("advance_n_steps",
&advance_n_steps_dtcb_user_solver<
StepperType, py_f_arr, ::pressio4py::scalar_t, DtSetter, T>);
m.def("advance_n_steps_and_observe",
&advance_n_steps_and_observe_dtcb_user_solver<
StepperType, py_f_arr, ::pressio4py::scalar_t, DtSetter, ode_observer_wrapper_type, T>);
}
};
template<class Head, class ... Tail>
struct BindAdvanceFunctions<std::tuple<Head, Tail...>>
{
template<class ...Args>
static void fixedStepSize(pybind11::module & m)
{
BindAdvanceFunctions<std::tuple<Head>>::template fixedStepSize<Args...>(m);
BindAdvanceFunctions<std::tuple<Tail...>>::template fixedStepSize<Args...>(m);
}
template<class T>
static void fixedStepSizeUserSolver(pybind11::module & m)
{
BindAdvanceFunctions<std::tuple<Head>>::template fixedStepSizeUserSolver<T>(m);
BindAdvanceFunctions<std::tuple<Tail...>>::template fixedStepSizeUserSolver<T>(m);
}
template<class DtSetter, class ... Args>
static void arbitraryStepSize(pybind11::module & m)
{
BindAdvanceFunctions<std::tuple<Head>>::template arbitraryStepSize<DtSetter, Args...>(m);
BindAdvanceFunctions<std::tuple<Tail...>>::template arbitraryStepSize<DtSetter, Args...>(m);
}
template<class DtSetter, class T>
static void arbitraryStepSizeUserSolver(pybind11::module & m)
{
BindAdvanceFunctions<std::tuple<Head>>::template arbitraryStepSizeUserSolver<DtSetter, T>(m);
BindAdvanceFunctions<std::tuple<Tail...>>::template arbitraryStepSizeUserSolver<DtSetter, T>(m);
}
};
}//end namespace pressio4py
#endif
| 33.894895 | 100 | 0.72331 | [
"object"
] |
662a8b07b10fe352468a21704e9f9bc7cc82a9ec | 2,099 | hpp | C++ | Renderer.hpp | Sobaka12345/FastSimpleRayTracer | b8db01558afb85e616a3f1abe92f017e79c265b9 | [
"MIT"
] | null | null | null | Renderer.hpp | Sobaka12345/FastSimpleRayTracer | b8db01558afb85e616a3f1abe92f017e79c265b9 | [
"MIT"
] | null | null | null | Renderer.hpp | Sobaka12345/FastSimpleRayTracer | b8db01558afb85e616a3f1abe92f017e79c265b9 | [
"MIT"
] | null | null | null | #ifndef RENDERER_HPP
#define RENDERER_HPP
#include <memory>
#include <vector>
#include <limits>
#include <glm/ext.hpp>
#include "figures.hpp"
#include "lights.hpp"
class Renderer
{
struct RenderSettings
{
glm::vec3 view_point = { 0.0f, 0.0f, 0.0f };
glm::vec3 view_dir = { 0.0f, 0.0f, 1.0f };
glm::vec3 view_up = { 0.0f, 1.0f, 0.0f };
Color default_color = glm::vec4(0, 0, 0, 0);
float field_of_view_hor = glm::pi<float>() / 3.0f;
float draw_depth_max = std::numeric_limits<float>::max();
float draw_depth_min = 0.00001f;
uint8_t trace_depth = 3;
} settings_;
struct LightSources
{
AmbientLight ambient = AmbientLight(0.2f);
std::vector<PointLight> point_sources;
std::vector<DirectionalLight> directional_sources;
} light_;
std::vector<std::unique_ptr<Figure>> figures_;
std::vector<uint8_t> pixels_;
int width_, height_;
std::tuple<const Figure*, float> GetRayIntersection(const glm::vec3& orig, const glm::vec3& dir, float min_depth, float max_depth) const;
Color RayTrace(const glm::vec3 &orig, const glm::vec3 &dir, size_t depth) const;
public:
Renderer(int width, int height);
Renderer& SetViewCellDistance(float dist);
Renderer& SetView(glm::vec3 view, glm::vec3 dir, glm::vec3 up);
Renderer& SetDrawDepthMax(float depth);
Renderer& SetDrawDepthMin(float depth);
Renderer& SetTraceDepth(uint8_t depth);
Renderer& SetFieldOfViewHor(float fov);
Renderer& SetDefaultColor(Color color);
Renderer& AddDirectionalLightSource(glm::vec3 dir, float intencity);
Renderer& AddPointLightSource(glm::vec3 origin, float intencity);
Renderer& SetAmbientLight(float intencity);
Renderer& AddPlane(glm::vec3 p1, glm::vec3 p2, glm::vec3 p3, Color color, float reflect, float spec);
Renderer& AddSphere(glm::vec3 center, float radius, Color color, float reflect, float spec);
Renderer& AddFigure(std::unique_ptr<Figure> figure);
const std::vector<uint8_t>& RenderToPixelArray();
};
#endif // RENDERER_HPP
| 32.292308 | 141 | 0.684135 | [
"vector"
] |
662d0ec70479f43bcfa830ad67bd76341c500bd1 | 1,101 | cc | C++ | source/interface/pyG4UIExecutive.cc | drbenmorgan/geant4_pybind | d9c774a04156b1518795bafbd7819a1b8a03f7ea | [
"Unlicense"
] | null | null | null | source/interface/pyG4UIExecutive.cc | drbenmorgan/geant4_pybind | d9c774a04156b1518795bafbd7819a1b8a03f7ea | [
"Unlicense"
] | null | null | null | source/interface/pyG4UIExecutive.cc | drbenmorgan/geant4_pybind | d9c774a04156b1518795bafbd7819a1b8a03f7ea | [
"Unlicense"
] | null | null | null | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <G4UIExecutive.hh>
#include "typecast.hh"
#include "opaques.hh"
namespace py = pybind11;
void export_G4UIExecutive(py::module &m)
{
py::class_<G4UIExecutive>(m, "G4UIExecutive")
.def(py::init<>([](G4int argc, const std::vector<std::string> &argv, const G4String &type) {
static std::vector<std::string> arvCopy = std::vector<std::string>(argv);
static std::unique_ptr<char *[]> pArgv = std::make_unique<char *[]>(argc);
for (G4int i = 0; i < argc; i++) {
pArgv.get()[i] = &arvCopy[i][0];
}
return new G4UIExecutive(argc, pArgv.get(), type);
}),
py::arg("argc"), py::arg("argv"), py::arg("type") = "")
//.def("GetSession", &G4UIExecutive::GetSession, py::return_value_policy::reference_internal)
.def("SetPrompt", &G4UIExecutive::SetPrompt)
.def("SetLsColor", &G4UIExecutive::SetLsColor)
.def("SessionStart", &G4UIExecutive::SessionStart)
.def("IsGUI", &G4UIExecutive::IsGUI);
}
| 35.516129 | 99 | 0.599455 | [
"vector"
] |
663269680d71cd60f0c9f4524fbefd6ef132ed4f | 5,130 | cpp | C++ | src/OpenLoco/Map/Tree.cpp | OpenRCT2/OpenLoco | 207513653bf80a047a61aa275b3e815bf3737a19 | [
"MIT"
] | 180 | 2018-01-18T07:56:44.000Z | 2019-02-18T21:33:45.000Z | src/OpenLoco/Map/Tree.cpp | OpenRCT2/OpenLoco | 207513653bf80a047a61aa275b3e815bf3737a19 | [
"MIT"
] | 186 | 2018-01-18T13:17:58.000Z | 2019-02-10T12:28:35.000Z | src/OpenLoco/Map/Tree.cpp | OpenRCT2/OpenLoco | 207513653bf80a047a61aa275b3e815bf3737a19 | [
"MIT"
] | 35 | 2018-01-18T12:38:26.000Z | 2018-11-14T16:01:32.000Z | #include "Tree.h"
#include "../GameCommands/GameCommands.h"
#include "../Math/Trigonometry.hpp"
#include "../Objects/LandObject.h"
#include "../Objects/ObjectManager.h"
#include "../Objects/TreeObject.h"
#include "../Scenario.h"
#include "../Ui.h"
#include "TileManager.h"
namespace OpenLoco::Map
{
// 0x004BDF19
std::optional<uint8_t> getRandomTreeTypeFromSurface(const Map::TilePos2& loc, bool unk)
{
if (!Map::validCoords(loc))
{
return {};
}
auto* surface = Map::TileManager::get(loc).surface();
if (surface == nullptr)
{
return {};
}
uint16_t mustNotTreeFlags = 0;
if (unk)
{
mustNotTreeFlags |= TreeObjectFlags::unk1;
}
uint16_t mustTreeFlags = 0;
if (surface->baseZ() - 4 > Scenario::getCurrentSnowLine())
{
mustTreeFlags |= TreeObjectFlags::hasSnowVariation;
}
if (surface->baseZ() > 68)
{
mustTreeFlags |= TreeObjectFlags::veryHighAltitude;
}
if (surface->baseZ() > 48)
{
mustTreeFlags |= TreeObjectFlags::highAltitude;
}
auto* landObj = ObjectManager::get<LandObject>(surface->terrain());
mustNotTreeFlags |= TreeObjectFlags::droughtResistant;
if (landObj->flags & LandObjectFlags::isDesert)
{
mustTreeFlags |= TreeObjectFlags::droughtResistant;
mustNotTreeFlags &= ~TreeObjectFlags::droughtResistant;
}
if (landObj->flags & LandObjectFlags::noTrees)
{
return {};
}
mustNotTreeFlags |= TreeObjectFlags::requiresWater;
const uint16_t numSameTypeSurfaces = TileManager::countSurroundingWaterTiles(loc);
if (numSameTypeSurfaces >= 8)
{
mustNotTreeFlags &= ~TreeObjectFlags::requiresWater;
}
std::vector<uint8_t> selectableTrees;
for (uint8_t i = 0; i < ObjectManager::getMaxObjects(ObjectType::tree); ++i)
{
auto* treeObj = ObjectManager::get<TreeObject>(i);
if (treeObj == nullptr)
{
continue;
}
if (treeObj->flags & mustNotTreeFlags)
{
continue;
}
if ((treeObj->flags & mustTreeFlags) != mustTreeFlags)
{
continue;
}
selectableTrees.push_back(i);
}
if (selectableTrees.empty())
{
return {};
}
auto& rng = gPrng();
return { selectableTrees[rng.randNext(selectableTrees.size() - 1)] };
}
// 0x004BDC67 (when treeType is nullopt) & 0x004BDDC6 (when treeType is set)
bool placeTreeCluster(const Map::TilePos2& centreLoc, const uint16_t range, const uint16_t density, const std::optional<uint8_t> treeType)
{
const auto numPlacements = (range * range * density) / 8192;
uint16_t numErrors = 0;
for (auto i = 0; i < numPlacements; ++i)
{
// Choose a random offset in a circle
auto& rng = gPrng();
auto randomMagnitude = rng.randNext(std::numeric_limits<uint16_t>::max()) * range / 65536;
auto randomDirection = rng.randNext(Math::Trigonometry::directionPrecisionHigh - 1);
Map::Pos2 randomOffset(
Math::Trigonometry::integerSinePrecisionHigh(randomDirection, randomMagnitude),
Math::Trigonometry::integerCosinePrecisionHigh(randomDirection, randomMagnitude));
GameCommands::TreePlacementArgs args;
Map::Pos2 newLoc = randomOffset + centreLoc;
args.quadrant = Ui::ViewportInteraction::getQuadrantFromPos(newLoc);
args.pos = Map::Pos2(newLoc.x & 0xFFE0, newLoc.y & 0xFFE0);
// Note: this is not the same as the randomDirection above as it is the trees rotation
args.rotation = rng.randNext(3);
args.colour = Colour::black;
// If not set by the caller then a random tree type is selected based on the surface type
std::optional<uint8_t> randTreeType = treeType;
if (!randTreeType.has_value())
{
randTreeType = getRandomTreeTypeFromSurface(newLoc, false);
// It is possible that there are no valid tree types for the surface
if (!randTreeType.has_value())
{
continue;
}
}
args.type = *randTreeType;
args.buildImmediately = true;
args.requiresFullClearance = true;
// First query if we can place a tree at this location; skip if we can't.
auto queryRes = doCommand(args, 0);
if (queryRes == GameCommands::FAILURE)
{
numErrors++;
continue;
}
// Actually place the tree
doCommand(args, GameCommands::Flags::apply);
}
// Have we placed any trees?
return (numErrors < numPlacements);
}
}
| 34.42953 | 142 | 0.566277 | [
"vector"
] |
663d990a05548fc83621954aba582083128d39c8 | 8,753 | cpp | C++ | examples/rotor_thermalExp_2Dt.cpp | gismo/gsElasticity | a94347d4b8d8cd76de79d4b512023be9b68363bf | [
"BSD-3-Clause-Attribution"
] | 7 | 2020-04-24T04:11:02.000Z | 2021-09-18T19:24:10.000Z | examples/rotor_thermalExp_2Dt.cpp | gismo/gsElasticity | a94347d4b8d8cd76de79d4b512023be9b68363bf | [
"BSD-3-Clause-Attribution"
] | 1 | 2021-08-16T20:41:48.000Z | 2021-08-16T20:41:48.000Z | examples/rotor_thermalExp_2Dt.cpp | gismo/gsElasticity | a94347d4b8d8cd76de79d4b512023be9b68363bf | [
"BSD-3-Clause-Attribution"
] | 6 | 2020-05-12T11:11:51.000Z | 2021-10-21T14:13:46.000Z | /// This is an example of using the thermal expansion solver in a time-dependent setting on a 2D geometry.
/// The problems is part of the EU project "MOTOR".
/// The heat equation is solved using the Crank-Nicolson method.
/// At each time step, the current temperature distribution is used as an input for
/// the stationary thermo-elasticity equation to compute the thermal expansion of the body.
///
/// Author: A.Shamanskiy (2016 - ...., TU Kaiserslautern)
#include <gismo.h>
#include <gsElasticity/gsThermoAssembler.h>
#include <gsElasticity/gsWriteParaviewMultiPhysics.h>
using namespace gismo;
int main(int argc, char *argv[])
{
gsInfo << "Testing the thermo-elasticity solver in a time-dependent setting in 2D.\n";
//=====================================//
// Input //
//=====================================//
std::string filename = ELAST_DATA_DIR"/rotor_2D.xml";
real_t fluxValue = 100.; // heat flux on the north boundary
real_t thExpCoef = 2e-4; // thermal expansion coeffcient of the material
real_t initTemp = 20.; // initial temperature
// spatial discretization
index_t numUniRef = 1;
index_t numDegElev = 0;
// time integration
real_t timeSpan = 1.;
real_t timeStep = 0.01;
// output
index_t numPlotPoints = 10000;
// minimalistic user interface for terminal
gsCmdLine cmd("Testing the thermo-elasticity solver in a time-dependent setting in 2D.");
cmd.addInt("r","refine","Number of uniform refinement application",numUniRef);
cmd.addInt("d","degelev","Number of degree elevation application",numDegElev);
cmd.addReal("s","step","Time step",timeStep);
cmd.addReal("t","time","Lenght of time integration period",timeSpan);
cmd.addInt("p","points","Number of points to plot to Paraview",numPlotPoints);
try { cmd.getValues(argc,argv); } catch (int rv) { return rv; }
//=============================================//
// Scanning geometry and creating bases //
//=============================================//
// scanning geometry
gsMultiPatch<> geometry;
gsReadFile<>(filename, geometry);
// creating basis
gsMultiBasis<> basis(geometry);
for (index_t i = 0; i < numDegElev; ++i)
basis.degreeElevate();
for (index_t i = 0; i < numUniRef; ++i)
basis.uniformRefine();
//=============================================//
// Setting loads and boundary conditions //
//=============================================//
// heat source function, rhs for the heat equation
gsConstantFunction<> heatSource(0.,2);
// boundary temperature, dirichlet BC for the heat equation
gsConstantFunction<> bTemp(initTemp,2);
// boundary flux, nuemann BC for the heat equation
gsConstantFunction<> heatFlux(fluxValue,2);
// boundary conditions for the heat equation
gsBoundaryConditions<> bcTemp;
bcTemp.addCondition(0,boundary::south,condition_type::dirichlet,&bTemp);
bcTemp.addCondition(0,boundary::north,condition_type::neumann,&heatFlux);
// gravity, rhs for the linear elasticity equation
gsConstantFunction<> gravity(0.,0.,2);
// boundary conditions for the linear elasticity equation
gsBoundaryConditions<> bcElast;
// Dirichlet BC are imposed separately for every component (coordinate)
for (index_t d = 0; d < 2; ++d)
{ // 0 refers to a patch number, nullptr means that the dirichlet BC is homogeneous, d stats for the displacement component
bcElast.addCondition(0,boundary::south,condition_type::dirichlet,nullptr,d);
bcElast.addCondition(0,boundary::west,condition_type::dirichlet,nullptr,d);
bcElast.addCondition(0,boundary::east,condition_type::dirichlet,nullptr,d);
}
//=============================================//
// Setting assemblers and solvers //
//=============================================//
// solution fields
gsMultiPatch<> temperature, displacement;
// creating an assembler for the heat equation
gsPoissonAssembler<> heatAssembler(geometry,basis,bcTemp,heatSource);
gsHeatEquation<real_t> heatSolver(heatAssembler);
heatSolver.setTheta(0.5);
gsInfo << "Initialized heat equation system with " << heatAssembler.numDofs() << " dofs.\n";
// creating elasticity assembler
gsThermoAssembler<real_t> elastAssembler(geometry,basis,bcElast,gravity,temperature);
elastAssembler.options().setReal("InitTemp",initTemp);
elastAssembler.options().setReal("ThExpCoef",thExpCoef);
gsInfo << "Initialized thermal expansion system with " << elastAssembler.numDofs() << " dofs.\n";
//=============================================//
// Setting output and auxilary //
//=============================================//
// isogeometric fields (geometry + solution)
gsField<> tempField(geometry,temperature);
gsField<> dispField(geometry,displacement);
// setting up Paraview output
std::map<std::string,const gsField<> *> fields;
// plotting initial conditions to Paraview
fields["Temperature"] = &tempField;
fields["Displacement"] = &dispField;
gsParaviewCollection collection("rotor");
gsStopwatch totalClock, iterClock;
gsProgressBar bar;
//=============================================//
// Initial conditions //
//=============================================//
iterClock.restart();
gsInfo<<"Assembling...\n";
heatSolver.assemble();
gsInfo << "Assembled the heat equation system with "
<< heatAssembler.numDofs() << " dofs in " << totalClock.stop() << "s.\n";
// setting initial conditions
gsVector<> solVectorTemp;
solVectorTemp.setOnes(heatAssembler.numDofs());
solVectorTemp *= initTemp;
// constructing solution as an IGA function
heatAssembler.constructSolution(solVectorTemp,temperature);
totalClock.restart();
gsInfo<< "Assembling...\n";
elastAssembler.assemble();
gsInfo << "Assembled the thermal expansion system with "
<< elastAssembler.numDofs() << " dofs in " << totalClock.stop() << "s.\n";
// setting initial conditions
gsVector<> solVectorElast;
solVectorElast.setZero(elastAssembler.numDofs());
// constructing solution as an IGA function
elastAssembler.constructSolution(solVectorElast,elastAssembler.allFixedDofs(),displacement);
if (numPlotPoints > 0)
gsWriteParaviewMultiPhysicsTimeStep(fields,"rotor",collection,0,numPlotPoints);
//=============================================//
// Solving //
//=============================================//
real_t timeTemp = 0.;
real_t timeElast = 0.;
totalClock.restart();
gsInfo << "Running the simulation...\n";
for (int i = 0; i < (index_t)(timeSpan/timeStep); ++i)
{
bar.display(i+1,(index_t)(timeSpan/timeStep));
iterClock.restart();
// prepairing the matrix for the next time step
heatSolver.nextTimeStep(solVectorTemp, timeStep);
#ifdef GISMO_WITH_PARDISO
gsSparseSolver<>::PardisoLDLT solverHeat(heatSolver.matrix());
solVectorTemp = solverHeat.solve(heatSolver.rhs());
#else
gsSparseSolver<>::SimplicialLDLT solverHeat(heatSolver.matrix());
solVectorTemp = solverHeat.solve(heatSolver.rhs());
#endif
heatAssembler.constructSolution(solVectorTemp,temperature);
timeTemp += iterClock.stop();
iterClock.restart();
// assembling the thermal contribution to the RHS of the thermal expansion system
elastAssembler.assembleThermo();
#ifdef GISMO_WITH_PARDISO
gsSparseSolver<>::PardisoLDLT solverElast(elastAssembler.matrix());
solVectorElast = solverElast.solve(elastAssembler.rhs());
#else
gsSparseSolver<>::SimplicialLDLT solverElast(elastAssembler.matrix());
solVectorElast = solverElast.solve(elastAssembler.rhs());
#endif
elastAssembler.constructSolution(solVectorElast,elastAssembler.allFixedDofs(),displacement);
timeElast += iterClock.stop();
// output
if (numPlotPoints > 0)
gsWriteParaviewMultiPhysicsTimeStep(fields,"rotor",collection,i+1,numPlotPoints);
}
//=============================================//
// Final touches //
//=============================================//
gsInfo << "Complete in: " << secToHMS(totalClock.stop())
<< ", temperature time: " << secToHMS(timeTemp)
<< ", thermal expansion time: " << secToHMS(timeElast) << std::endl;
if (numPlotPoints > 0)
{
collection.save();
gsInfo << "Open \"rotor.pvd\" in Paraview for visualization.\n";
}
return 0;
}
| 41.093897 | 129 | 0.620016 | [
"geometry"
] |
6646cd885e6b5b90b6307aa65af2d8f96d8b92df | 34,896 | cpp | C++ | production/libs/fog/Fog/Src/Fog/G2d/Geometry/PathStroker.cpp | Lewerow/DetailIdentifier | bd5e0b3b55b5ce5b24db51ae45ed53298d331687 | [
"MIT"
] | null | null | null | production/libs/fog/Fog/Src/Fog/G2d/Geometry/PathStroker.cpp | Lewerow/DetailIdentifier | bd5e0b3b55b5ce5b24db51ae45ed53298d331687 | [
"MIT"
] | null | null | null | production/libs/fog/Fog/Src/Fog/G2d/Geometry/PathStroker.cpp | Lewerow/DetailIdentifier | bd5e0b3b55b5ce5b24db51ae45ed53298d331687 | [
"MIT"
] | null | null | null | // [Fog-G2d]
//
// [License]
// MIT, See COPYING file in package
// [Precompiled Headers]
#if defined(FOG_PRECOMP)
#include FOG_PRECOMP
#endif // FOG_PRECOMP
// [Dependencies]
#include <Fog/Core/Global/Global.h>
#include <Fog/Core/Global/Private.h>
#include <Fog/Core/Math/Constants.h>
#include <Fog/Core/Math/Math.h>
#include <Fog/Core/Memory/MemBufferTmp_p.h>
#include <Fog/G2d/Geometry/Math2d.h>
#include <Fog/G2d/Geometry/Path.h>
#include <Fog/G2d/Geometry/PathClipper.h>
#include <Fog/G2d/Geometry/PathStroker.h>
#include <Fog/G2d/Geometry/PathTmp_p.h>
#include <Fog/G2d/Geometry/Point.h>
#include <Fog/G2d/Geometry/Shape.h>
#include <Fog/G2d/Geometry/Transform.h>
namespace Fog {
// ============================================================================
// [Fog::PathStrokerContextT<> - Declaration]
// ============================================================================
template<typename NumT>
struct PathStrokerContextT
{
// --------------------------------------------------------------------------
// [Construction / Destruction]
// --------------------------------------------------------------------------
FOG_INLINE PathStrokerContextT(const NumT_(PathStroker)* stroker, NumT_(Path)* dst) :
stroker(stroker),
dst(dst),
distances(NULL),
distancesAlloc(0)
{
dstInitial = dst->getLength();
}
FOG_INLINE ~PathStrokerContextT()
{
}
// --------------------------------------------------------------------------
// [Stroke]
// --------------------------------------------------------------------------
err_t strokeShape(uint32_t shapeType, const void* shapeData);
err_t strokePath(const NumT_(Path)* src);
err_t strokePathPrivate(const NumT_(Path)* src);
// --------------------------------------------------------------------------
// [Prepare / Finalize]
// --------------------------------------------------------------------------
err_t _begin();
err_t _grow();
err_t calcArc(
NumT x, NumT y,
NumT dx1, NumT dy1,
NumT dx2, NumT dy2);
err_t calcMiter(
const NumT_(Point)& v0,
const NumT_(Point)& v1,
const NumT_(Point)& v2,
NumT dx1, NumT dy1,
NumT dx2, NumT dy2,
int lineJoin,
NumT mlimit,
NumT dbevel);
err_t calcCap(
const NumT_(Point)& v0,
const NumT_(Point)& v1,
NumT len,
uint32_t cap);
err_t calcJoin(
const NumT_(Point)& v0,
const NumT_(Point)& v1,
const NumT_(Point)& v2,
NumT len1,
NumT len2);
err_t strokePathFigure(const NumT_(Point)* src, size_t count, bool outline);
// --------------------------------------------------------------------------
// [Members]
// --------------------------------------------------------------------------
const NumT_(PathStroker)* stroker;
NumT_(Path)* dst;
size_t dstInitial;
NumT_(Point)* dstCur;
NumT_(Point)* dstEnd;
// NumT_(Point)* pts;
// uint8_t *cmd;
// size_t remain;
//! @brief Memory buffer used to store distances.
MemBufferTmp<1024> buffer;
NumT* distances;
size_t distancesAlloc;
};
// ============================================================================
// [Fog::PathStrokerContextT<> - Stroke]
// ============================================================================
template<typename NumT>
err_t PathStrokerContextT<NumT>::strokeShape(uint32_t shapeType, const void* shapeData)
{
if (shapeType != SHAPE_TYPE_PATH)
{
NumT_T1(PathTmp, 32) tmp;
tmp.shape(NumT_(Shape)(shapeType, shapeData), PATH_DIRECTION_CW);
return strokePath(&tmp);
}
else
{
return strokePath(reinterpret_cast<const NumT_(Path)*>(shapeData));
}
}
template<typename NumT>
err_t PathStrokerContextT<NumT>::strokePath(const NumT_(Path)* src)
{
// We need:
// - the Path instances have to be different.
// - source path must be flat.
if (dst == src || src->hasBeziers() || !stroker->_transform->isIdentity())
{
NumT_T1(PathTmp, 200) tmp;
FOG_RETURN_ON_ERROR(NumI_(Path)::flatten(tmp, *src, stroker->_flatness));
return strokePathPrivate(&tmp);
}
else
{
return strokePathPrivate(src);
}
}
template<typename NumT>
err_t PathStrokerContextT<NumT>::strokePathPrivate(const NumT_(Path)* src)
{
const uint8_t* commands = src->getCommands();
const NumT_(Point)* vertices = src->getVertices();
// Traverse path, find moveTo / lineTo segments and stroke them.
const uint8_t* subCommand = NULL;
const uint8_t* curCommand = commands;
size_t remain = src->getLength();
while (remain)
{
uint8_t cmd = curCommand[0];
// LineTo is the most used command, so it's first.
if (PathCmd::isLineTo(cmd))
{
// Nothing here...
}
else if (PathCmd::isMoveTo(cmd))
{
// Send path to stroker if there is something.
if (FOG_LIKELY(subCommand != NULL && subCommand != curCommand))
{
size_t subStart = (size_t)(subCommand - commands);
size_t subLength = (size_t)(curCommand - subCommand);
FOG_RETURN_ON_ERROR(
strokePathFigure(vertices + subStart, subLength, false)
);
}
// Advance to new subpath.
subCommand = curCommand;
}
else if (PathCmd::isClose(cmd))
{
// Send path to stroker if there is something.
if (FOG_LIKELY(subCommand != NULL))
{
size_t subStart = (size_t)(subCommand - commands);
size_t subLength = (size_t)(curCommand - subCommand);
FOG_RETURN_ON_ERROR(
strokePathFigure(vertices + subStart, subLength, subLength > 2)
);
}
// We clear beginning mark, because we expect PATH_MOVE_TO command from now.
subCommand = NULL;
}
curCommand++;
remain--;
}
// Send path to stroker if there is something (this is the last, unclosed, figure)
if (subCommand != NULL && subCommand != curCommand)
{
size_t subStart = (size_t)(subCommand - commands);
size_t subLength = (size_t)(curCommand - subCommand);
FOG_RETURN_ON_ERROR(
strokePathFigure(vertices + subStart, subLength, false)
);
}
return ERR_OK;
}
// ============================================================================
// [Fog::PathStrokerContextT<> - Calc]
// ============================================================================
#define ADD_VERTEX(x, y) \
FOG_MACRO_BEGIN \
if (FOG_UNLIKELY(dstCur == dstEnd)) FOG_RETURN_ON_ERROR(_grow()); \
\
dstCur->set(x, y); \
dstCur++; \
FOG_MACRO_END
#define CUR_INDEX() \
( (size_t)(dstCur - dst->_d->vertices) )
template<typename NumT>
err_t PathStrokerContextT<NumT>::_begin()
{
size_t cap = dst->getCapacity();
size_t remain = cap - dst->getLength();
if (remain < 64 || !dst->isDetached())
{
if (cap < 256)
cap = 256;
else
cap *= 2;
FOG_RETURN_ON_ERROR(dst->reserve(cap));
}
dstCur = const_cast<NumT_(Point)*>(dst->getVertices());
dstEnd = dstCur;
dstCur += dst->getLength();
dstEnd += dst->getCapacity();
return ERR_OK;
}
template<typename NumT>
err_t PathStrokerContextT<NumT>::_grow()
{
size_t capacity = dst->_d->capacity;
dst->_d->length = capacity;
if (capacity < 256)
capacity = 512;
else
capacity *= 2;
err_t err = dst->reserve(capacity);
if (FOG_IS_ERROR(err))
return err;
dstCur = const_cast<NumT_(Point)*>(dst->getVertices());
dstEnd = dstCur;
dstCur += dst->getLength();
dstEnd += dst->getCapacity();
return ERR_OK;
};
#if 0
err_t PathStrokerContextT<NumT>::calcArc(
NumT x, NumT y,
NumT dx1, NumT dy1,
NumT dx2, NumT dy2)
{
NumT a1 = Math::atan2(dy1 * stroker->_wSign, dx1 * stroker->_wSign);
NumT a2 = Math::atan2(dy2 * stroker->_wSign, dx2 * stroker->_wSign);
NumT da = stroker->_da;
int i, n;
ADD_VERTEX(x + dx1, y + dy1);
if (stroker->_wSign > 0)
{
if (a1 > a2) a2 += MATH_TWO_PI;
n = int((a2 - a1) / da);
da = (a2 - a1) / (n + 1);
a1 += da;
for (i = 0; i < n; i++)
{
NumT a1Sin, a1Cos;
Math::sincos(a1, &a1Sin, &a1Cos);
ADD_VERTEX(x + a1Cos * stroker->_w, y + a1Sin * stroker->_w);
a1 += da;
}
}
else
{
if (a1 < a2) a2 -= MATH_TWO_PI;
n = int((a1 - a2) / da);
da = (a1 - a2) / (n + 1);
a1 -= da;
for (i = 0; i < n; i++)
{
NumT a1Sin, a1Cos;
Math::sincos(a1, &a1Sin, &a1Cos);
ADD_VERTEX(x + a1Cos * stroker->_w, y + a1Sin * stroker->_w);
a1 -= da;
}
}
ADD_VERTEX(x + dx2, y + dy2);
return ERR_OK;
}
#endif
template<typename NumT>
err_t PathStrokerContextT<NumT>::calcArc(
NumT x, NumT y,
NumT dx1, NumT dy1,
NumT dx2, NumT dy2)
{
NumT a1, a2;
NumT da = stroker->_da;
int i, n;
ADD_VERTEX(x + dx1, y + dy1);
if (stroker->_wSign > 0)
{
a1 = Math::atan2(dy1, dx1);
a2 = Math::atan2(dy2, dx2);
if (a1 > a2) a2 += NumT(MATH_TWO_PI);
n = int((a2 - a1) / da);
}
else
{
a1 = Math::atan2(-dy1, -dx1);
a2 = Math::atan2(-dy2, -dx2);
if (a1 < a2) a2 -= NumT(MATH_TWO_PI);
n = int((a1 - a2) / da);
}
da = (a2 - a1) / (n + 1);
a1 += da;
for (i = 0; i < n; i++)
{
NumT a1Sin, a1Cos;
Math::sincos(a1, &a1Sin, &a1Cos);
ADD_VERTEX(x + a1Cos * stroker->_w, y + a1Sin * stroker->_w);
a1 += da;
}
ADD_VERTEX(x + dx2, y + dy2);
return ERR_OK;
}
template<typename NumT>
err_t PathStrokerContextT<NumT>::calcMiter(
const NumT_(Point)& v0,
const NumT_(Point)& v1,
const NumT_(Point)& v2,
NumT dx1, NumT dy1,
NumT dx2, NumT dy2,
int lineJoin,
NumT mlimit,
NumT dbevel)
{
NumT_(Point) pi(v1.x, v1.y);
NumT di = NumT(1);
NumT lim = stroker->_wAbs * mlimit;
bool intersectionFailed = true; // Assume the worst
if (Math2d::intersectLine(pi,
NumT_(Point)(v0.x + dx1, v0.y - dy1),
NumT_(Point)(v1.x + dx1, v1.y - dy1),
NumT_(Point)(v1.x + dx2, v1.y - dy2),
NumT_(Point)(v2.x + dx2, v2.y - dy2)))
{
// Calculation of the intersection succeeded.
di = Math::euclideanDistance(v1.x, v1.y, pi.x, pi.y);
if (di <= lim)
{
// Inside the miter limit.
ADD_VERTEX(pi.x, pi.y);
return ERR_OK;
}
intersectionFailed = false;
}
else
{
// Calculation of the intersection failed, most probably the three points
// lie one straight line. First check if v0 and v2 lie on the opposite
// sides of vector: (v1.x, v1.y) -> (v1.x+dx1, v1.y-dy1), that is, the
// perpendicular to the line determined by vertices v0 and v1.
//
// This condition determines whether the next line segments continues
// the previous one or goes back.
NumT_(Point) vt(v1.x + dx1, v1.y - dy1);
if ((Math2d::crossProduct(v0, v1, vt) < 0.0) ==
(Math2d::crossProduct(v1, v2, vt) < 0.0))
{
// This case means that the next segment continues the previous one
// (straight line).
ADD_VERTEX(v1.x + dx1, v1.y - dy1);
return ERR_OK;
}
}
// Miter limit exceeded.
switch (lineJoin)
{
case LINE_JOIN_MITER_REVERT:
// For the compatibility with SVG, PDF, etc, we use a simple bevel
// join instead of "smart" bevel.
ADD_VERTEX(v1.x + dx1, v1.y - dy1);
ADD_VERTEX(v1.x + dx2, v1.y - dy2);
break;
case LINE_JOIN_MITER_ROUND:
FOG_RETURN_ON_ERROR( calcArc(v1.x, v1.y, dx1, -dy1, dx2, -dy2) );
break;
default:
// If no miter-revert, calculate new dx1, dy1, dx2, dy2.
if (intersectionFailed)
{
mlimit *= stroker->_wSign;
ADD_VERTEX(v1.x + dx1 + dy1 * mlimit, v1.y - dy1 + dx1 * mlimit);
ADD_VERTEX(v1.x + dx2 - dy2 * mlimit, v1.y - dy2 - dx2 * mlimit);
}
else
{
NumT x1 = v1.x + dx1;
NumT y1 = v1.y - dy1;
NumT x2 = v1.x + dx2;
NumT y2 = v1.y - dy2;
di = (lim - dbevel) / (di - dbevel);
ADD_VERTEX(x1 + (pi.x - x1) * di, y1 + (pi.y - y1) * di);
ADD_VERTEX(x2 + (pi.x - x2) * di, y2 + (pi.y - y2) * di);
}
break;
}
return ERR_OK;
}
template<typename NumT>
err_t PathStrokerContextT<NumT>::calcCap(
const NumT_(Point)& v0,
const NumT_(Point)& v1,
NumT len,
uint32_t cap)
{
NumT ilen = NumT(1.0) / len;
NumT dx1 = (v1.y - v0.y) * ilen;
NumT dy1 = (v1.x - v0.x) * ilen;
dx1 *= stroker->_w;
dy1 *= stroker->_w;
switch (cap)
{
case LINE_CAP_BUTT:
{
ADD_VERTEX(v0.x - dx1, v0.y + dy1);
ADD_VERTEX(v0.x + dx1, v0.y - dy1);
break;
}
case LINE_CAP_SQUARE:
{
NumT dx2 = dy1 * stroker->_wSign;
NumT dy2 = dx1 * stroker->_wSign;
ADD_VERTEX(v0.x - dx1 - dx2, v0.y + dy1 - dy2);
ADD_VERTEX(v0.x + dx1 - dx2, v0.y - dy1 - dy2);
break;
}
case LINE_CAP_ROUND:
{
int i;
int n = int(MATH_PI / stroker->_da);
NumT da = NumT(MATH_PI) / NumT(n + 1);
NumT a1;
ADD_VERTEX(v0.x - dx1, v0.y + dy1);
if (stroker->_wSign > 0)
{
a1 = Math::atan2(dy1, -dx1) + da;
}
else
{
da = -da;
a1 = Math::atan2(-dy1, dx1) + da;
}
for (i = 0; i < n; i++)
{
NumT a1_sin;
NumT a1_cos;
Math::sincos(a1, &a1_sin, &a1_cos);
ADD_VERTEX(v0.x + a1_cos * stroker->_w, v0.y + a1_sin * stroker->_w);
a1 += da;
}
ADD_VERTEX(v0.x + dx1, v0.y - dy1);
break;
}
case LINE_CAP_ROUND_REVERSE:
{
int i;
int n = int(MATH_PI / stroker->_da);
NumT da = NumT(MATH_PI) / NumT(n + 1);
NumT a1;
NumT dx2 = dy1 * stroker->_wSign;
NumT dy2 = dx1 * stroker->_wSign;
NumT vx = v0.x - dx2;
NumT vy = v0.y - dy2;
ADD_VERTEX(vx - dx1, vy + dy1);
if (stroker->_wSign > 0)
{
da = -da;
a1 = Math::atan2(dy1, -dx1) + da;
}
else
{
a1 = Math::atan2(-dy1, dx1) + da;
}
for (i = 0; i < n; i++)
{
NumT a1_sin;
NumT a1_cos;
Math::sincos(a1, &a1_sin, &a1_cos);
ADD_VERTEX(vx + a1_cos * stroker->_w, vy + a1_sin * stroker->_w);
a1 += da;
}
ADD_VERTEX(vx + dx1, vy - dy1);
break;
}
case LINE_CAP_TRIANGLE:
{
NumT dx2 = dy1 * stroker->_wSign;
NumT dy2 = dx1 * stroker->_wSign;
ADD_VERTEX(v0.x - dx1, v0.y + dy1);
ADD_VERTEX(v0.x - dx2, v0.y - dy2);
ADD_VERTEX(v0.x + dx1, v0.y - dy1);
break;
}
case LINE_CAP_TRIANGLE_REVERSE:
{
NumT dx2 = dy1 * stroker->_wSign;
NumT dy2 = dx1 * stroker->_wSign;
ADD_VERTEX(v0.x - dx1 - dx2, v0.y + dy1 - dy2);
ADD_VERTEX(v0.x, v0.y);
ADD_VERTEX(v0.x + dx1 - dx2, v0.y - dy1 - dy2);
}
}
return ERR_OK;
}
// ============================================================================
// [Fog::INNER_JOIN]
// ============================================================================
template<typename NumT>
err_t PathStrokerContextT<NumT>::calcJoin(
const NumT_(Point)& v0,
const NumT_(Point)& v1,
const NumT_(Point)& v2,
NumT len1,
NumT len2)
{
NumT wilen1 = (stroker->_w / len1);
NumT wilen2 = (stroker->_w / len2);
NumT dx1 = (v1.y - v0.y) * wilen1;
NumT dy1 = (v1.x - v0.x) * wilen1;
NumT dx2 = (v2.y - v1.y) * wilen2;
NumT dy2 = (v2.x - v1.x) * wilen2;
NumT cp = Math2d::crossProduct(v0, v1, v2);
if (cp != 0 && (cp > 0) == (stroker->_w > 0))
{
ADD_VERTEX(v1.x + dx1, v1.y - dy1);
ADD_VERTEX(v1.x + dx2, v1.y - dy2);
}
else
{
// Outer join
// Calculate the distance between v1 and the central point of the bevel
// line segment.
NumT dx = (dx1 + dx2) / 2;
NumT dy = (dy1 + dy2) / 2;
NumT dbevel = Math::sqrt(dx * dx + dy * dy);
/*
if (stroker->_params->getLineJoin() == LINE_JOIN_ROUND ||
stroker->_params->getLineJoin() == LINE_JOIN_BEVEL)
{
// This is an optimization that reduces the number of points
// in cases of almost collinear segments. If there's no
// visible difference between bevel and miter joins we'd rather
// use miter join because it adds only one point instead of two.
//
// Here we calculate the middle point between the bevel points
// and then, the distance between v1 and this middle point.
// At outer joins this distance always less than stroke width,
// because it's actually the height of an isosceles triangle of
// v1 and its two bevel points. If the difference between this
// width and this value is small (no visible bevel) we can
// add just one point.
//
// The constant in the expression makes the result approximately
// the same as in round joins and caps. You can safely comment
// out this entire "if".
// TODO: ApproxScale used
if (stroker->_flatness * (stroker->_wAbs - dbevel) < stroker->_wEps)
{
NumT_(Point) pi;
if (Math2d::intersectLine(pi,
NumT_(Point)(v0.x + dx1, v0.y - dy1),
NumT_(Point)(v1.x + dx1, v1.y - dy1),
NumT_(Point)(v1.x + dx2, v1.y - dy2),
NumT_(Point)(v2.x + dx2, v2.y - dy2)))
{
ADD_VERTEX(pi.x, pi.y);
}
else
{
ADD_VERTEX(v1.x + dx1, v1.y - dy1);
}
return ERR_OK;
}
}
*/
switch (stroker->_params->getLineJoin())
{
case LINE_JOIN_MITER:
case LINE_JOIN_MITER_REVERT:
case LINE_JOIN_MITER_ROUND:
FOG_RETURN_ON_ERROR(
calcMiter(v0, v1, v2, dx1, dy1, dx2, dy2,
stroker->_params->getLineJoin(),
stroker->_params->getMiterLimit(), dbevel)
);
break;
case LINE_JOIN_ROUND:
FOG_RETURN_ON_ERROR(
calcArc(v1.x, v1.y, dx1, -dy1, dx2, -dy2)
);
break;
case LINE_JOIN_BEVEL:
ADD_VERTEX(v1.x + dx1, v1.y - dy1);
ADD_VERTEX(v1.x + dx2, v1.y - dy2);
break;
default:
FOG_ASSERT_NOT_REACHED();
}
}
return ERR_OK;
}
template<typename NumT>
err_t PathStrokerContextT<NumT>::strokePathFigure(const NumT_(Point)* src, size_t count, bool outline)
{
// Can't stroke one-vertex array.
if (count <= 1)
return ERR_OK;
//return ERR_GEOMETRY_CANT_STROKE;
// To do outline we need at least three vertices.
if (outline && count <= 2)
return ERR_OK;
// return ERR_GEOMETRY_CANT_STROKE;
const NumT_(Point)* cur;
size_t i;
size_t moveToPosition0 = dst->getLength();
size_t moveToPosition1 = INVALID_INDEX;
FOG_RETURN_ON_ERROR(
_begin()
);
// Alloc or realloc array for our distances (distance between individual
// vertices [0]->[1], [1]->[2], ...). Distance at index[0] means distance
// between src[0] and src[1], etc. Last distance is special and it is 0.0
// if path is not closed, otherwise src[count-1]->src[0].
if (distancesAlloc < count)
{
// Need to realloc, we align count to 128 vertices.
if (distances) buffer.reset();
distancesAlloc = (count + 127) & ~127;
distances = reinterpret_cast<NumT*>(buffer.alloc(distancesAlloc * sizeof(NumT)));
if (distances == NULL)
{
distancesAlloc = 0;
return ERR_RT_OUT_OF_MEMORY;
}
}
NumT *dist;
for (i = 0; i < count - 1; i++)
{
NumT d = Math::euclideanDistance(src[i].x, src[i].y, src[i + 1].x, src[i + 1].y);
if (d <= MathConstant<NumT>::getDistanceEpsilon()) d = NumT(0.0);
distances[i] = d;
}
/*
for (i = count - 1, cur = src, dist = distances; i; i--, cur++, dist++)
{
NumT d = Math::euclideanDistance(cur[0].x, cur[0].y, cur[1].x, cur[1].y);
if (d <= MathConstant<NumT>::getDistanceEpsilon()) d = 0.0;
dist[0] = d;
}
*/
const NumT_(Point)* srcEnd = src + count;
NumT_(Point) cp[3]; // Current points.
NumT cd[3]; // Current distances.
// If something goes wrong:
// for (i = 0; i < count; i++)
// {
// Logger::debug(NULL, NULL, "Vertex [%g, %g]", src[i].x, src[i].y);
// }
// --------------------------------------------------------------------------
// [Outline]
// --------------------------------------------------------------------------
#define IS_DEGENERATED_DIST(_Dist_) ((_Dist_) <= MathConstant<NumT>::getDistanceEpsilon())
if (outline)
{
// We need also to calc distance between first and last point.
{
NumT d = Math::euclideanDistance(src[count - 1].x, src[count - 1].y, src[0].x, src[0].y);
if (d <= MathConstant<NumT>::getDistanceEpsilon()) d = NumT(0.0);
distances[count - 1] = d;
}
NumT_(Point) fp[2]; // First points.
NumT fd[2]; // First distances.
// ------------------------------------------------------------------------
// [Outline 1]
// ------------------------------------------------------------------------
cur = src;
dist = distances;
// Fill the current points / distances and skip degenerate cases.
i = 0;
// FirstI is first point. When first and last points are equal, we need to
// mask the second one as first.
//
// Examine two paths:
//
// - [100, 100] -> [300, 300] -> [100, 300] -> CLOSE
//
// The firstI will be zero in that case. Path is self-closing, but the
// close end-point is not shared with first vertex.
//
// - [100, 100] -> [300, 300] -> [100, 300] -> [100, 100] -> CLOSE
//
// The firstI will be one. Path is self-closing, but unfortunatelly the
// closing point vertex is already there (fourth command).
//
size_t firstI = i;
cp[i] = src[count - 1];
cd[i] = dist[count - 1];
if (FOG_LIKELY(!IS_DEGENERATED_DIST(cd[i]))) { i++; firstI++; }
do {
if (FOG_UNLIKELY(cur == srcEnd))
return ERR_OK;
//return ERR_GEOMETRY_CANT_STROKE;
cp[i] = *cur++;
cd[i] = *dist++;
if (FOG_LIKELY(!IS_DEGENERATED_DIST(cd[i]))) i++;
} while (i < 3);
// Save two first points and distances (we need them to finish the outline).
fp[0] = cp[firstI];
fd[0] = cd[firstI];
fp[1] = cp[firstI + 1];
fd[1] = cd[firstI + 1];
// Make the outline.
for (;;)
{
calcJoin(cp[0], cp[1], cp[2], cd[0], cd[1]);
if (cur == srcEnd) goto _Outline1Done;
while (FOG_UNLIKELY(IS_DEGENERATED_DIST(dist[0])))
{
dist++;
if (++cur == srcEnd) goto _Outline1Done;
}
cp[0] = cp[1];
cd[0] = cd[1];
cp[1] = cp[2];
cd[1] = cd[2];
cp[2] = *cur++;
cd[2] = *dist++;
}
// End joins.
_Outline1Done:
FOG_RETURN_ON_ERROR( calcJoin(cp[1], cp[2], fp[0], cd[1], cd[2]) );
FOG_RETURN_ON_ERROR( calcJoin(cp[2], fp[0], fp[1], cd[2], fd[0]) );
// Close path (CW).
ADD_VERTEX(Math::getQNanT<NumT>(), Math::getQNanT<NumT>());
// ------------------------------------------------------------------------
// [Outline 2]
// ------------------------------------------------------------------------
moveToPosition1 = CUR_INDEX();
cur = src + count;
dist = distances + count;
// Fill the current points / distances and skip degenerate cases.
i = 0;
firstI = 0;
cp[i] = src[0];
cd[i] = distances[0];
if (cd[i] != NumT(0.0)) { i++; firstI++; }
do {
cp[i] = *--cur;
cd[i] = *--dist;
if (FOG_LIKELY(cd[i] != NumT(0.0))) i++;
} while (i < 3);
// Save two first points and distances (we need them to finish the outline).
fp[0] = cp[firstI];
fd[0] = cd[firstI];
fp[1] = cp[firstI + 1];
fd[1] = cd[firstI + 1];
// Make the outline.
for (;;)
{
calcJoin(cp[0], cp[1], cp[2], cd[1], cd[2]);
do {
if (cur == src) goto _Outline2Done;
cur--;
dist--;
} while (FOG_UNLIKELY(dist[0] == NumT(0.0)));
cp[0] = cp[1];
cd[0] = cd[1];
cp[1] = cp[2];
cd[1] = cd[2];
cp[2] = *cur;
cd[2] = *dist;
}
// End joins.
_Outline2Done:
FOG_RETURN_ON_ERROR( calcJoin(cp[1], cp[2], fp[0], cd[2], fd[0]) );
FOG_RETURN_ON_ERROR( calcJoin(cp[2], fp[0], fp[1], fd[0], fd[1]) );
// Close path (CCW).
ADD_VERTEX(Math::getQNanT<NumT>(), Math::getQNanT<NumT>());
}
// --------------------------------------------------------------------------
// [Pen]
// --------------------------------------------------------------------------
else
{
distances[count - 1] = distances[count - 2];
// ------------------------------------------------------------------------
// [Outline 1]
// ------------------------------------------------------------------------
cur = src;
dist = distances;
// Fill the current points / distances and skip degenerate cases.
i = 0;
do {
if (FOG_UNLIKELY(cur == srcEnd))
return ERR_OK;
//return ERR_GEOMETRY_CANT_STROKE;
cp[i] = *cur++;
cd[i] = *dist++;
if (FOG_LIKELY(cd[i] != NumT(0.0))) i++;
} while (i < 2);
// Start cap.
FOG_RETURN_ON_ERROR( calcCap(cp[0], cp[1], cd[0], stroker->_params->getStartCap()) );
// Make the outline.
if (cur == srcEnd) goto _Pen1Done;
while (FOG_UNLIKELY(dist[0] == NumT(0.0)))
{
dist++;
if (++cur == srcEnd) goto _Pen1Done;
}
goto _Pen1Loop;
for (;;)
{
cp[0] = cp[1];
cd[0] = cd[1];
cp[1] = cp[2];
cd[1] = cd[2];
_Pen1Loop:
cp[2] = *cur++;
cd[2] = *dist++;
FOG_RETURN_ON_ERROR( calcJoin(cp[0], cp[1], cp[2], cd[0], cd[1]) );
if (cur == srcEnd) goto _Pen1Done;
while (FOG_UNLIKELY(dist[0] == NumT(0.0)))
{
dist++;
if (++cur == srcEnd) goto _Pen1Done;
}
}
// End joins.
_Pen1Done:
// ------------------------------------------------------------------------
// [Outline 2]
// ------------------------------------------------------------------------
// Fill the current points / distances and skip degenerate cases.
i = 0;
do {
cp[i] = *--cur;
cd[i] = *--dist;
if (FOG_LIKELY(cd[i] != NumT(0.0))) i++;
} while (i < 2);
// End cap.
FOG_RETURN_ON_ERROR( calcCap(cp[0], cp[1], cd[1], stroker->_params->getEndCap()) );
// Make the outline.
if (cur == src) goto _Pen2Done;
cur--;
dist--;
while (FOG_UNLIKELY(dist[0] == NumT(0.0)))
{
if (cur == src) goto _Pen2Done;
dist--;
cur--;
}
goto _Pen2Loop;
for (;;)
{
do {
if (cur == src) goto _Pen2Done;
cur--;
dist--;
} while (FOG_UNLIKELY(dist[0] == NumT(0.0)));
cp[0] = cp[1];
cd[0] = cd[1];
cp[1] = cp[2];
cd[1] = cd[2];
_Pen2Loop:
cp[2] = *cur;
cd[2] = *dist;
FOG_RETURN_ON_ERROR( calcJoin(cp[0], cp[1], cp[2], cd[1], cd[2]) );
}
_Pen2Done:
// Close path (CCW).
ADD_VERTEX(Math::getQNanT<NumT>(), Math::getQNanT<NumT>());
}
{
// Fix the length of the path.
size_t finalLength = CUR_INDEX();
dst->_d->length = finalLength;
FOG_ASSERT(finalLength <= dst->_d->capacity);
// Fix path adding PATH_CMD_MOVE_TO/CLOSE commands at begin of each
// outline and filling rest by PATH_CMD_LINE_TO. This allowed us to
// simplify ADD_VERTEX() macro.
uint8_t* dstCommands = const_cast<uint8_t*>(dst->getCommands());
// Close clockwise path.
if (moveToPosition0 < finalLength)
{
memset(dstCommands + moveToPosition0, (unsigned int)(PATH_CMD_LINE_TO), finalLength - moveToPosition0);
dstCommands[moveToPosition0] = PATH_CMD_MOVE_TO;
dstCommands[finalLength - 1] = PATH_CMD_CLOSE;
}
// Close counter-clockwise path.
if (moveToPosition1 < finalLength)
{
dstCommands[moveToPosition1 - 1] = PATH_CMD_CLOSE;
dstCommands[moveToPosition1 ] = PATH_CMD_MOVE_TO;
}
}
return ERR_OK;
}
// ============================================================================
// [Fog::PathStroker - Construction / Destruction]
// ============================================================================
template<typename NumT>
static void FOG_CDECL PathStrokerT_ctor(NumT_(PathStroker)* self)
{
self->_params.init();
self->_transform.init();
self->_clipBox.reset();
self->_transformedClipBox.reset();
self->_w = NumT(0);
self->_wAbs = NumT(0);
self->_wEps = NumT(0);
self->_da = NumT(0);
self->_flatness = MathConstant<NumT>::getDefaultFlatness();
self->_wSign = 1;
self->_isDirty = true;
self->_isClippingEnabled = false;
self->_isTransformSimple = true;
self->_flattenType = PATH_FLATTEN_DISABLED;
}
template<typename NumT>
static void FOG_CDECL PathStrokerT_ctorCopy(NumT_(PathStroker)* self, const NumT_(PathStroker)* other)
{
self->_params.initCustom1(other->_params);
self->_transform.initCustom1(other->_transform);
self->_clipBox = other->_clipBox;
self->_transformedClipBox = other->_transformedClipBox;
self->_w = other->_w;
self->_wAbs = other->_wAbs;
self->_wEps = other->_wEps;
self->_da = other->_da;
self->_flatness = other->_flatness;
self->_wSign = other->_wSign;
self->_isDirty = other->_isDirty;
self->_isClippingEnabled = other->_isClippingEnabled;
self->_isTransformSimple = other->_isTransformSimple;
self->_flattenType = other->_flattenType;
}
template<typename NumT>
static void FOG_CDECL PathStrokerT_ctorParams(NumT_(PathStroker)* self,
const NumT_(PathStrokerParams)* params, const NumT_(Transform)* tr, const NumT_(Box)* clipBox)
{
if (params != NULL)
self->_params.initCustom1(*params);
else
self->_params.init();
if (tr != NULL)
self->_transform.initCustom1(*tr);
else
self->_transform.init();
if (clipBox != NULL)
self->_clipBox = *clipBox;
else
self->_clipBox.reset();
self->_transformedClipBox.reset();
self->_w = NumT(0);
self->_wAbs = NumT(0);
self->_wEps = NumT(0);
self->_da = NumT(0);
self->_flatness = MathConstant<NumT>::getDefaultFlatness();
self->_wSign = 1;
self->_isDirty = true;
self->_isClippingEnabled = false;
self->_isTransformSimple = true;
self->_flattenType = PATH_FLATTEN_DISABLED;
}
template<typename NumT>
static void FOG_CDECL PathStrokerT_dtor(NumT_(PathStroker)* self)
{
self->_params.destroy();
}
// ============================================================================
// [Fog::PathStroker - Params]
// ============================================================================
template<typename NumT>
static void FOG_CDECL PathStrokerT_setParams(NumT_(PathStroker)* self, const NumT_(PathStrokerParams)* params)
{
self->_params() = *params;
self->_isDirty = true;
}
template<typename NumT>
static void FOG_CDECL PathStrokerT_setOther(NumT_(PathStroker)* self, const NumT_(PathStroker)* other)
{
self->_params() = other->_params();
self->_transform() = other->_transform();
self->_clipBox = other->_clipBox;
self->_transformedClipBox = other->_transformedClipBox;
self->_w = other->_w;
self->_wAbs = other->_wAbs;
self->_wEps = other->_wEps;
self->_da = other->_da;
self->_flatness = other->_flatness;
self->_wSign = other->_wSign;
self->_isDirty = other->_isDirty;
self->_isClippingEnabled = other->_isClippingEnabled;
self->_isTransformSimple = other->_isTransformSimple;
self->_flattenType = other->_flattenType;
}
// ============================================================================
// [Fog::PathStroker - Stroker]
// ============================================================================
template<typename NumT>
static err_t PathStrokerT_postProcess(const NumT_(PathStroker)* self, NumT_(Path)* dst)
{
const NumT_(Transform)& tr = self->getTransform();
if (self->isClippingEnabled())
{
NumT_(PathClipper) clipper(self->_clipBox);
if (tr._getType() != TRANSFORM_TYPE_IDENTITY)
{
NumT_T1(PathTmp, 128) tmp;
FOG_RETURN_ON_ERROR(tr.mapPath(tmp, *dst));
dst->clear();
FOG_RETURN_ON_ERROR(clipper.clipPath(*dst, tmp));
return ERR_OK;
}
else
{
switch (clipper.measurePath(*dst))
{
case PATH_CLIPPER_MEASURE_BOUNDED:
{
return ERR_OK;
}
case PATH_CLIPPER_MEASURE_UNBOUNDED:
{
NumT_(Path) tmp;
FOG_RETURN_ON_ERROR(clipper.continuePath(tmp, *dst));
*dst = tmp;
return ERR_OK;
}
default:
{
dst->clear();
return ERR_GEOMETRY_INVALID;
}
}
}
}
else
{
if (tr._getType() != TRANSFORM_TYPE_IDENTITY)
return tr.mapPath(*dst, *dst);
else
return ERR_OK;
}
}
template<typename NumT>
static err_t FOG_CDECL PathStrokerT_strokeShape(const NumT_(PathStroker)* self, NumT_(Path)* dst, uint32_t shapeType, const void* shapeData)
{
self->update();
{
PathStrokerContextT<NumT> ctx(self, dst);
FOG_RETURN_ON_ERROR(ctx.strokeShape(shapeType, shapeData));
}
return PathStrokerT_postProcess<NumT>(self, dst);
}
// ============================================================================
// [Fog::PathStroker - Update]
// ============================================================================
template<typename NumT>
static void FOG_CDECL PathStrokerT_update(NumT_(PathStroker)* self)
{
self->_w = self->_params->_lineWidth * NumT(0.5);
self->_wAbs = self->_w;
self->_wSign = 1;
if (self->_w < NumT(0.0))
{
self->_wAbs = -self->_w;
self->_wSign = -1;
}
self->_wEps = self->_w / NumT(1024.0);
self->_da = Math::acos(self->_wAbs / (self->_wAbs + NumT(0.125) * self->_flatness)) * NumT(2.0);
self->_isDirty = false;
self->_isTransformSimple = self->_transform->getType() == TRANSFORM_TYPE_IDENTITY;
}
// ============================================================================
// [Init / Fini]
// ============================================================================
FOG_NO_EXPORT void PathStroker_init(void)
{
fog_api.pathstrokerf_ctor = PathStrokerT_ctor<float>;
fog_api.pathstrokerf_ctorCopy = PathStrokerT_ctorCopy<float>;
fog_api.pathstrokerf_ctorParams = PathStrokerT_ctorParams<float>;
fog_api.pathstrokerf_dtor = PathStrokerT_dtor<float>;
fog_api.pathstrokerf_setParams = PathStrokerT_setParams<float>;
fog_api.pathstrokerf_setOther = PathStrokerT_setOther<float>;
fog_api.pathstrokerf_strokeShape = PathStrokerT_strokeShape<float>;
fog_api.pathstrokerf_update = PathStrokerT_update<float>;
fog_api.pathstrokerd_ctor = PathStrokerT_ctor<double>;
fog_api.pathstrokerd_ctorCopy = PathStrokerT_ctorCopy<double>;
fog_api.pathstrokerd_ctorParams = PathStrokerT_ctorParams<double>;
fog_api.pathstrokerd_dtor = PathStrokerT_dtor<double>;
fog_api.pathstrokerd_setParams = PathStrokerT_setParams<double>;
fog_api.pathstrokerd_setOther = PathStrokerT_setOther<double>;
fog_api.pathstrokerd_strokeShape = PathStrokerT_strokeShape<double>;
fog_api.pathstrokerd_update = PathStrokerT_update<double>;
}
} // Fog namespace
| 26.376417 | 140 | 0.547799 | [
"geometry",
"shape",
"vector",
"transform"
] |
59406eb86a0adffa932f8dd4efba7b86ca17b7db | 5,554 | hpp | C++ | include/quadtree.hpp | plefebvre91/demo-quadtree-collision | 5d7168f2219187d08b3745a8c20eb9d4ca2198ce | [
"MIT"
] | null | null | null | include/quadtree.hpp | plefebvre91/demo-quadtree-collision | 5d7168f2219187d08b3745a8c20eb9d4ca2198ce | [
"MIT"
] | null | null | null | include/quadtree.hpp | plefebvre91/demo-quadtree-collision | 5d7168f2219187d08b3745a8c20eb9d4ca2198ce | [
"MIT"
] | null | null | null | /* MIT License
Copyright (c) 2022 Pierre Lefebvre
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. */
#ifndef QUADTREE_HPP
#define QUADTREE_HPP
#include <vector>
#include <SFML/Graphics.hpp>
// A node in the quadtree.
#define NB_SUBNODES 4
#define NORTH_WEST 0
#define NORTH_EAST 1
#define SOUTH_EAST 2
#define SOUTH_WEST 3
#define MAX_ELEMENTS 10
class Node {
using Position = sf::Vector2f;
using Rectangle = sf::Rect<int>;
using EntityId = unsigned int;
public:
/**
* Constructor
* @param screen area associated to the node
*/
Node(const Rectangle& r):_area(r), _elements(), _isLeaf(true) {
for (auto& node: _nodes)
node = nullptr;
}
/**
* Add an element in the tree
* @template type of elements referenced in the tree
* @entities the external array storing all objects
* @param index of object to add in tree
*/
template<typename T>
void add(const T* entities, EntityId id) {
// If this is not a leaf, object should be inserted in the correct child
if (not _isLeaf)
insertInSubnodes<T>(entities, id);
// And if this node is a leaf, object is inserted
else {
_elements.push_back(id);
// If there is too much objects in the same node...
if (_elements.size() >= MAX_ELEMENTS) {
// ...the node is split in 4...
_split();
// ...and its elements are re-dispatched in its children
for (auto id: _elements)
insertInSubnodes<T>(entities, id);
_elements.clear();
}
}
}
/**
* Fill an array with all the tree leaves
* @param output array
*/
void getLeaves(std::vector<Node*>* out) {
// If this node is a leaf, add it to the result...
if (_isLeaf)
out->push_back(this);
// ...else scan its children
else for (auto& node: _nodes)
if (node != nullptr)
node->getLeaves(out);
}
/**
* Getter for node elements
* @param output array
* @return the output size
*/
unsigned int getElements(unsigned int** data) {
*data = _elements.data();
return _elements.size();
}
/**
* Drawing function
*/
void draw(sf::RenderWindow* w) {
sf::RectangleShape rect;
rect.setPosition(sf::Vector2f(_area.left, _area.top));
rect.setSize(sf::Vector2f(_area.width, _area.height));
rect.setOutlineColor(sf::Color::Blue);
rect.setOutlineThickness(1.0);
if (_elements.size() > 0) {
rect.setFillColor(sf::Color(0x00,0x33,0xCC,0x33));
w->draw(rect);
}
else
rect.setFillColor(sf::Color::Transparent);
for (auto node: _nodes)
if (node != nullptr)
node->draw(w);
}
/**
* Clear the tree
*/
void clear() {
for (auto& node: _nodes)
// Depth-first search for non-null nodes
if (node != nullptr) {
node->clear();
delete node;
}
// As this node does not have children anymore, it becomes a leaf
_isLeaf = true;
}
private:
// 4 Children
Node* _nodes[NB_SUBNODES];
// Screen are associated to this node
Rectangle _area;
// Referenced objects
std::vector<EntityId> _elements;
// True if node is a leaf
bool _isLeaf;
/**
* Creates the 4 children of a node
*/
void _split() {
// Get the area coordinates
int x = _area.left;
int y = _area.top;
int width = _area.width;
int height = _area.height;
// Create children nodes
_nodes[NORTH_WEST] = new Node(Rectangle(x, y, width/2, height/2));
_nodes[NORTH_EAST] = new Node(Rectangle(x + width/2, y, width/2, height/2));
_nodes[SOUTH_WEST] = new Node(Rectangle(x, y + height/2, width/2, height/2));
_nodes[SOUTH_EAST] = new Node(Rectangle(x + width/2, y + height/2, width/2, height/2));
// This node is no more a leaf
_isLeaf = false;
}
/**
* Add an element in correct children of a node.
* This is a recursive subroutine of add().
* @template type of elements referenced in the tree
* @entities the external array storing all objects
* @param index of object to add in tree
*/
template<typename T>
void insertInSubnodes(const T* entities, EntityId id) {
// Get the object positions
const Position& position = entities[id].getPosition();
// Search for the correct children for the node to be inserted
for (auto node: _nodes)
if (node->contains(position))
node->add(entities, id);
}
/**
* Return true if the position is in the node area
*/
inline bool contains(const Position& p) const {
return _area.contains(sf::Vector2i(p));
}
};
#endif
| 26.322275 | 91 | 0.660605 | [
"object",
"vector"
] |
5944c2291a34b579e8b1b13ef99749aeb98e0f17 | 2,926 | cpp | C++ | TermPaper/Controller.cpp | VasiliyMatutin/2DPlatformer | 70211cdb10b2746aefed3890723b23aef5de0099 | [
"MIT"
] | null | null | null | TermPaper/Controller.cpp | VasiliyMatutin/2DPlatformer | 70211cdb10b2746aefed3890723b23aef5de0099 | [
"MIT"
] | null | null | null | TermPaper/Controller.cpp | VasiliyMatutin/2DPlatformer | 70211cdb10b2746aefed3890723b23aef5de0099 | [
"MIT"
] | null | null | null | #include "Controller.h"
#include "WinSingleton.h"
Controller::Controller(Model* _model, Viewer* _viewer):
model(_model),
viewer(_viewer)
{
window = WinSingleton::getInstance();
}
void Controller::observe()
{
viewer->handleViewerEvent(ViewEvents::ADDLAYER);
sf::Event event;
while (window->isOpen())
{
if (window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window->close();
break;
case sf::Event::KeyPressed:
switch (event.key.code)
{
case sf::Keyboard::Left:
model->handleEvent(Events::LEFTBUTTON);
break;
case sf::Keyboard::Right:
model->handleEvent(Events::RIGHTBUTTON);
break;
case sf::Keyboard::Up:
model->handleEvent(Events::UPBUTTON);
break;
case sf::Keyboard::I:
model->handleEvent(Events::IBUTTON);
break;
case sf::Keyboard::P:
model->handleEvent(Events::PBUTTON);
break;
case sf::Keyboard::C:
model->handleEvent(Events::CBUTTON);
break;
case sf::Keyboard::Escape:
model->handleEvent(Events::ESCBUTTON);
break;
case sf::Keyboard::Return:
model->handleEvent(Events::ENTERBUTTON);
break;
}
break;
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Left:
model->handleEvent(Events::LEFTBUTTONRELEASED);
break;
case sf::Keyboard::Right:
model->handleEvent(Events::RIGHTBUTTONRELEASED);
break;
case sf::Keyboard::Up:
model->handleEvent(Events::UPBUTTONRELEASED);
break;
}
break;
case sf::Event::MouseWheelScrolled:
if (event.mouseWheelScroll.delta < 0)
{
viewer->handleViewerEvent(ViewEvents::DISTANCEZOOM);
}
else if (event.mouseWheelScroll.delta > 0)
{
viewer->handleViewerEvent(ViewEvents::BRINGZOOMCLOSER);
}
break;
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Left)
{
MouseClickCoordinates::x = event.mouseButton.x / (double)window->getSize().x * X_WIN_SIZE;
MouseClickCoordinates::y = event.mouseButton.y / (double)window->getSize().y * Y_WIN_SIZE;
model->handleEvent(Events::MOUSECLICKED);
}
break;
case sf::Event::Resized:
viewer->handleViewerEvent(ViewEvents::WINRESIZE);
break;
}
}
switch (model->checkResponse())
{
case ModelReaction::ADD:
viewer->handleViewerEvent(ViewEvents::ADDLAYER);
break;
case ModelReaction::REMOVE:
viewer->handleViewerEvent(ViewEvents::DELETELAYER);
break;
case ModelReaction::CLEARALLANDADD:
viewer->handleViewerEvent(ViewEvents::DELETEALLLAYERS);
viewer->handleViewerEvent(ViewEvents::ADDLAYER);
break;
case ModelReaction::CLOSE:
window->close();
return;
case ModelReaction::FULLSCREEN:
WinSingleton::toFullScreen();
break;
case ModelReaction::WINDOWED:
WinSingleton::toWindow();
break;
}
model->update();
viewer->update();
}
}
| 25.008547 | 95 | 0.665072 | [
"model"
] |
5949b5c7e82a487c8ff0a308a17cd6fee258b0f1 | 8,107 | cpp | C++ | src/main.cpp | enp1s0/gpu_monitor | 3d1ebb39803861e57670d08ead883d1208d6e35b | [
"MIT"
] | null | null | null | src/main.cpp | enp1s0/gpu_monitor | 3d1ebb39803861e57670d08ead883d1208d6e35b | [
"MIT"
] | null | null | null | src/main.cpp | enp1s0/gpu_monitor | 3d1ebb39803861e57670d08ead883d1208d6e35b | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <fstream>
#include <random>
#include <string>
#include <ctime>
#include <chrono>
#include <vector>
#include <exception>
#include <filesystem>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <gpu_monitor/gpu_monitor.hpp>
#ifdef ACC_CUDA
#include "gpu_monitor_cuda.hpp"
#endif
#ifdef ACC_HIP
#include "gpu_monitor_hip.hpp"
#endif
// e.g. Input `str` is "0,1,3", then return vector will be `{0, 1, 3}`.
std::vector<unsigned> get_gpu_ids(const std::string str) {
std::stringstream ss(str);
std::string buffer;
std::vector<unsigned> result;
while (std::getline(ss, buffer, ',')) {
result.push_back(std::stoul(buffer));
}
return result;
}
int parse_params(unsigned &time_interval, std::string& output_file_name, std::vector<unsigned>& gpu_ids, int& run_command_head, int& set_default_gpus, int& print_result, int argc, char** argv) {
run_command_head = 1;
output_file_name = "gpu.csv";
time_interval = 100;
set_default_gpus = 0;
gpu_ids = std::vector<unsigned>{0};
print_result = 0;
for (int i = 1; i < argc;) {
if (std::string(argv[i]) == "-i") {
if (i + 1 >= argc) {
throw std::runtime_error("The value of `-i` was not provided");
}
time_interval = std::stoul(argv[i+1]);
i += 2;
} else if (std::string(argv[i]) == "-o") {
if (i + 1 >= argc) {
throw std::runtime_error("The value of `-o` was not provided");
}
output_file_name = argv[i+1];
i += 2;
} else if (std::string(argv[i]) == "-g") {
if (i + 1 >= argc) {
throw std::runtime_error("The value of `-g` was not provided");
}
if (std::string(argv[i+1]) != "ALL") {
gpu_ids = get_gpu_ids(argv[i+1]);
set_default_gpus = 1;
}
i += 2;
} else if (std::string(argv[i]) == "-r") {
print_result = 1;
i += 1;
} else if (std::string(argv[i]) == "-h") {
time_interval = 0; // This means that this execution is invalid and exits with printing help messages.
} else if (std::string(argv[i]).substr(0, 1) == "-") {
const std::string error_message = "Not supported option : " + std::string(argv[i]);
std::fprintf(stderr, "[GPU logger ERROR] %s\n", error_message.c_str());
return 1;
} else {
run_command_head = i;
break;
}
}
return 0;
}
void print_help_message(const char* const program_name) {
std::printf("/*** GPU Logger ***/\n");
std::printf("\n");
std::printf("// Usage\n");
std::printf("%s [-i interval(ms){default=100}] [-o output_file_name{default=gpu.csv}] [-g gpu_ids{default=ALL}] [-r] target_command\n", program_name);
}
namespace process {
constexpr char running = 'R';
constexpr char end = 'E';
} // namespace process
namespace {
void insert_message(const std::string filename, std::ofstream& ofs) {
std::ifstream ifs(filename);
if (!ifs) {
return;
}
std::string buffer;
while (std::getline(ifs, buffer)) {
if (buffer == "\n" || buffer.length() == 0) {
continue;
}
ofs << buffer << std::endl;
}
ifs.close();
std::ofstream ofs_m(filename);
ofs_m.close();
}
} // noname namespace
int main(int argc, char** argv) {
std::string output_file_name;
unsigned time_interval;
std::vector<unsigned> gpu_ids;
int run_command_head;
int set_default_gpus;
int print_result;
const auto res = parse_params(time_interval, output_file_name, gpu_ids, run_command_head, set_default_gpus, print_result, argc, argv);
if (res > 0) {
return 1;
}
if (time_interval < 1 || argc <= 1) {
print_help_message(argv[0]);
return 1;
}
const auto fd = shm_open("/gpu_monitor_smem", O_CREAT | O_RDWR, 0666);
ftruncate(fd, 1);
const auto semaphore = static_cast<char*>(mmap(nullptr, 1, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
*semaphore = process::running;
// interprocess message
std::string temp_dir = std::filesystem::temp_directory_path();
const auto rand = std::random_device{}();
std::string message_file_path = temp_dir + "/gm-" + std::to_string(rand);
setenv(mtk::gpu_monitor::message_file_path_env_name, message_file_path.c_str(), 1);
const auto pid = fork();
if (pid == 0) {
#ifdef ACC_CUDA
mtk::gpu_monitor::gpu_monitor_cuda gpu_monitor;
#endif
#ifdef ACC_HIP
mtk::gpu_monitor::gpu_monitor_hip gpu_monitor;
#endif
gpu_monitor.init();
std::ofstream ofs(output_file_name);
const auto num_devices = gpu_monitor.get_num_devices();
if (set_default_gpus == 0) {
gpu_ids = std::vector<unsigned>(num_devices);
for (unsigned i = 0; i < num_devices; i++) {
gpu_ids[i] = i;
}
}
// Validate given gpu ids
bool invalid_gpu_ids = false;
for (const auto gpu_id : gpu_ids) {
if (gpu_id >= num_devices) {
std::fprintf(stderr, "[ERROR(gpu_monitor)] GPU %u is not found\n", gpu_id);
invalid_gpu_ids = true;
}
}
if (invalid_gpu_ids) {
gpu_monitor.shutdown();
exit(1);
}
// Output csv header
ofs << "index,date,elapsed_time,";
for (const auto gpu_id : gpu_ids) {
ofs << "gpu" << gpu_id << "_temp,";
ofs << "gpu" << gpu_id << "_power,";
ofs << "gpu" << gpu_id << "_memory_usage,";
}
ofs << "\n";
ofs.close();
// record max power, temperature, memory usage
std::vector<double> max_power(gpu_ids.size());
for (auto& max_power_v : max_power) max_power_v = 0.0;
std::vector<double> max_temperature(gpu_ids.size());
for (auto& max_temperature_v : max_temperature) max_temperature_v = 0.0;
std::vector<std::size_t> max_memory_usage(gpu_ids.size());
for (auto& max_memory_usage_v : max_memory_usage) max_memory_usage_v = 0lu;
// Output log
unsigned count = 0;
const auto start_clock = std::chrono::high_resolution_clock::now();
do {
std::ofstream ofs(output_file_name, std::ios::app);
ofs << (count++) << ","
<< std::time(nullptr) << ",";
const auto end_clock = std::chrono::high_resolution_clock::now();
const auto elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>(end_clock - start_clock).count();
ofs << elapsed_time << ",";
for (const auto gpu_id : gpu_ids) {
const auto power = gpu_monitor.get_current_power(gpu_id);
const auto temperature = gpu_monitor.get_current_temperature(gpu_id);
const auto memory_usage = gpu_monitor.get_current_used_memory(gpu_id);
ofs << temperature << ","
<< power << ","
<< memory_usage << ",";
max_power[gpu_id] = std::max(max_power[gpu_id], power);
max_temperature[gpu_id] = std::max(max_temperature[gpu_id], temperature);
max_memory_usage[gpu_id] = std::max(max_memory_usage[gpu_id], memory_usage);
}
ofs << "\n";
insert_message(message_file_path, ofs);
ofs.close();
const auto end_clock_1 = std::chrono::high_resolution_clock::now();
const auto elapsed_time_1 = std::chrono::duration_cast<std::chrono::microseconds>(end_clock_1 - start_clock).count();
usleep(std::max<std::time_t>(time_interval * 1000 * count, elapsed_time_1) - elapsed_time_1);
} while ((*semaphore) == process::running);
gpu_monitor.shutdown();
if (print_result) {
std::printf(
"##### GPU Monitoring result #####\n"
);
const auto end_clock = std::chrono::high_resolution_clock::now();
const auto elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>(end_clock - start_clock).count() * 1e-6;
std::printf("- %10s : %.1f [s]\n", "time", elapsed_time);
for (const auto gpu_id : gpu_ids) {
std::printf("## GPU %u\n", gpu_id);
std::printf("- %10s : %2.1f [C]\n", "max temp", max_temperature[gpu_id]);
std::printf("- %10s : %2.1f [W]\n", "max power", max_power[gpu_id]);
std::printf("- %10s : %.5e [GB]\n", "max mem", max_memory_usage[gpu_id] / 1e9);
}
}
exit(0);
} else {
const auto cmd = argv[run_command_head];
std::vector<char*> cmd_args(argc - run_command_head + 1);
for (int i = run_command_head, v = 0; i < argc; i++, v++) {
cmd_args[v] = argv[i];
}
cmd_args[cmd_args.size() - 1] = nullptr;
const auto command_pid = fork();
if (command_pid == 0) {
execvp(cmd, cmd_args.data());
exit(0);
} else {
wait(nullptr);
*semaphore = process::end;
}
}
std::filesystem::remove(message_file_path);
}
| 30.942748 | 194 | 0.656716 | [
"vector"
] |
5955929b407cea0723454ae4258762794b6ce026 | 7,370 | cpp | C++ | oshgui/Drawing/Direct3D11/Direct3D11GeometryBuffer.cpp | sdkabuser/DEADCELL-CSGO | dfcd31394c5348529b3c098640466db136b89e0c | [
"MIT"
] | 506 | 2019-03-16T08:34:47.000Z | 2022-03-29T14:08:59.000Z | oshgui/Drawing/Direct3D11/Direct3D11GeometryBuffer.cpp | sdkabuser/DEADCELL-CSGO | dfcd31394c5348529b3c098640466db136b89e0c | [
"MIT"
] | 124 | 2019-03-17T02:54:57.000Z | 2021-03-29T01:51:05.000Z | oshgui/Drawing/Direct3D11/Direct3D11GeometryBuffer.cpp | sdkabuser/DEADCELL-CSGO | dfcd31394c5348529b3c098640466db136b89e0c | [
"MIT"
] | 219 | 2019-03-16T21:39:01.000Z | 2022-03-30T08:59:24.000Z | #include "Direct3D11GeometryBuffer.hpp"
#include "Direct3D11Texture.hpp"
#include "../Vertex.hpp"
#include "../../Misc/Exceptions.hpp"
#include <algorithm>
namespace OSHGui {
namespace Drawing {
//---------------------------------------------------------------------------
//Constructor
//---------------------------------------------------------------------------
Direct3D11GeometryBuffer::Direct3D11GeometryBuffer( Direct3D11Renderer &_owner )
: owner( _owner ),
vertexBuffer( nullptr ),
bufferSize( 0 ),
bufferSynched( false ),
clipRect( 0, 0, 0, 0 ),
clippingActive( true ),
translation( 0, 0, 0 ),
rotation( 0, 0, 0 ),
pivot( 0, 0, 0 ),
matrixValid( false ) { }
//---------------------------------------------------------------------------
Direct3D11GeometryBuffer::~Direct3D11GeometryBuffer() {
CleanupVertexBuffer();
}
//---------------------------------------------------------------------------
//Getter/Setter
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SetTranslation( const Vector &translation ) {
this->translation = translation;
matrixValid = false;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SetRotation( const Quaternion &rotation ) {
this->rotation = rotation;
matrixValid = false;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SetPivot( const Vector &pivot ) {
this->pivot = pivot;
matrixValid = false;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SetClippingRegion( const RectangleF ®ion ) {
clipRect.SetTop( std::max( 0.0f, region.GetTop() ) );
clipRect.SetBottom( std::max( 0.0f, region.GetBottom() ) );
clipRect.SetLeft( std::max( 0.0f, region.GetLeft() ) );
clipRect.SetRight( std::max( 0.0f, region.GetRight() ) );
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SetActiveTexture( const TexturePtr &texture ) {
activeTexture = std::static_pointer_cast< Direct3D11Texture >( texture );
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SetClippingActive( const bool active ) {
clippingActive = active;
}
//---------------------------------------------------------------------------
bool Direct3D11GeometryBuffer::IsClippingActive() const {
return clippingActive;
}
//---------------------------------------------------------------------------
//Runtime-Functions
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::AppendVertex( const Vertex &vertex ) {
AppendGeometry( &vertex, 1 );
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::AppendGeometry( const Vertex *const vbuff, uint32_t count ) {
PerformBatchManagement();
batches.back().count += count;
auto vs = vbuff;
for( auto i = 0u; i < count; ++i, ++vs ) {
vertices.emplace_back( vs->Position.x, vs->Position.y, vs->Position.z, vs->Color.GetARGB(),
vs->TextureCoordinates.X, vs->TextureCoordinates.Y );
}
bufferSynched = false;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::Draw() const {
D3D10_RECT clip = { clipRect.GetLeft(), clipRect.GetTop(), clipRect.GetRight(), clipRect.GetBottom() };
owner.GetDevice().Context->RSSetScissorRects( 1, &clip );
if( !bufferSynched ) {
SyncHardwareBuffer();
}
if( !matrixValid ) {
UpdateMatrix();
}
owner.SetWorldMatrix( matrix );
UINT stride = sizeof( D3DVertex );
UINT offset = 0;
owner.GetDevice().Context->IASetVertexBuffers( 0, 1, &vertexBuffer, &stride, &offset );
for( int pass = 0; pass < 1; ++pass ) {
auto pos = 0;
for( auto &batch : batches ) {
owner.GetDevice().Context->IASetPrimitiveTopology( batch.mode == VertexDrawMode::TriangleList
? D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST
: D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP );
owner.SetCurrentTextureShaderResource( batch.texture );
owner.BindTechniquePass( batch.clip );
owner.GetDevice().Context->Draw( batch.count, pos );
pos += batch.count;
}
}
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::Reset() {
batches.clear();
vertices.clear();
activeTexture = nullptr;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::PerformBatchManagement() {
auto texture = activeTexture ? activeTexture->GetDirect3DShaderResourceView() : nullptr;
if( batches.empty() || texture != batches.back().texture || drawMode != batches.back().mode || clippingActive !=
batches.back().clip ) {
batches.emplace_back( texture, 0, drawMode, clippingActive );
}
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::UpdateMatrix() const {
D3DXVECTOR3 p( pivot.x, pivot.y, pivot.z );
D3DXVECTOR3 t( translation.x, translation.y, translation.z );
D3DXQUATERNION r( rotation.x, rotation.y, rotation.z, rotation.w );
D3DXMatrixTransformation( &matrix, nullptr, nullptr, nullptr, &p, &r, &t );
matrixValid = true;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::SyncHardwareBuffer() const {
auto count = vertices.size();
if( count > bufferSize ) {
CleanupVertexBuffer();
AllocateVertexBuffer( count );
}
if( count > 0 ) {
D3D11_MAPPED_SUBRESOURCE mappedSubresource;
if( FAILED(owner.GetDevice().Context->Map(vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedSubresource)) ) {
throw Misc::Exception();
}
std::memcpy( mappedSubresource.pData, vertices.data(), sizeof( D3DVertex ) * count );
owner.GetDevice().Context->Unmap( vertexBuffer, 0 );
}
bufferSynched = true;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::AllocateVertexBuffer( const uint32_t count ) const {
D3D11_BUFFER_DESC bufferDescription;
bufferDescription.Usage = D3D11_USAGE_DYNAMIC;
bufferDescription.ByteWidth = count * sizeof( D3DVertex );
bufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDescription.MiscFlags = 0;
if( FAILED(owner.GetDevice().Device->CreateBuffer(&bufferDescription, 0, &vertexBuffer)) ) {
throw Misc::Exception();
}
bufferSize = count;
}
//---------------------------------------------------------------------------
void Direct3D11GeometryBuffer::CleanupVertexBuffer() const {
if( vertexBuffer ) {
vertexBuffer->Release();
vertexBuffer = nullptr;
bufferSize = 0;
}
}
//---------------------------------------------------------------------------
}
}
| 35.432692 | 115 | 0.514383 | [
"vector"
] |
596988dd919006dd0ad6caabe2f47d4701a191ae | 5,189 | cpp | C++ | Chapter06/CvTrackKalman/main.cpp | PacktPublishing/Hands-On-Algorithms-for-Computer-Vision | 204c69a357f42ac9b7ac641df697cf52ced96416 | [
"MIT"
] | 36 | 2018-06-03T13:53:48.000Z | 2022-03-15T13:52:47.000Z | Chapter06/CvTrackKalman/main.cpp | PacktPublishing/Hands-On-Algorithms-for-Computer-Vision | 204c69a357f42ac9b7ac641df697cf52ced96416 | [
"MIT"
] | null | null | null | Chapter06/CvTrackKalman/main.cpp | PacktPublishing/Hands-On-Algorithms-for-Computer-Vision | 204c69a357f42ac9b7ac641df697cf52ced96416 | [
"MIT"
] | 21 | 2018-08-07T11:04:05.000Z | 2021-04-15T12:51:41.000Z | #include "opencv2/opencv.hpp"
#include <Windows.h>
using namespace std;
using namespace cv;
TermCriteria criteria(TermCriteria::MAX_ITER
+ TermCriteria::EPS,
20,
1.0);
bool selecting = false;
Rect selection;
Point spo; // selection point origin
void onMouse(int event, int x, int y, int, void*)
{
switch(event)
{
case EVENT_LBUTTONDOWN:
{
spo.x = x;
spo.y = y;
selection.x = spo.x;
selection.y = spo.y;
selection.width = 0;
selection.height = 0;
selecting = true;
} break;
case EVENT_LBUTTONUP:
{
selecting = false;
} break;
default:
{
selection.x = min(x, spo.x);
selection.y = min(y, spo.y);
selection.width = abs(x - spo.x);
selection.height = abs(y - spo.y);
} break;
}
}
int main()
{
VideoCapture cam(0);
if(!cam.isOpened())
return -1;
KalmanFilter kalman(4,2);
Mat_<float> tm(4, 4); // transition matrix
tm << 1,0,1,0, // next x = 1x+0y+1x'+0y'
0,1,0,1, // next x'= 0x+1y+0x'+1y'
0,0,1,0, // next y = 0x+0y+1x'+0y
0,0,0,1; // next y'= 0x+0y+0x'+1y'
kalman.transitionMatrix = tm;
Mat_<float> pos(2,1);
pos.at<float>(0) = 0;
pos.at<float>(1) = 0;
kalman.statePre.at<float>(0) = 0; // init x
kalman.statePre.at<float>(1) = 0; // init y
kalman.statePre.at<float>(2) = 0; // init x'
kalman.statePre.at<float>(3) = 0; // init y'
setIdentity(kalman.measurementMatrix);
setIdentity(kalman.processNoiseCov,
Scalar::all(0.00001));
Rect srchWnd;
string outputWindow = "Display";
namedWindow(outputWindow);
cv::setMouseCallback(outputWindow, onMouse);
Mat histogram, backProject, mask;
int key = -1;
while(key != ' ')
{
Mat frame;
cam >> frame;
if(frame.empty())
break;
Mat frmHsv, hue;
vector<Mat> hsvChannels;
cvtColor(frame, frmHsv, COLOR_BGR2HSV);
split(frmHsv, hsvChannels);
hue = hsvChannels[0];
int bins = 120;
int nimages = 1;
int channels[] = {0};
float rangeHue[] = {0, 180};
const float* ranges[] = {rangeHue};
int histSize[] = { bins };
bool uniform = true;
if(selecting && selection.area() > 0)
{
Mat sel(frame, selection);
int lbHue = 00 , hbHue = 180;
int lbSat = 30 , hbSat = 256;
int lbVal = 30 , hbVal = 230;
inRange(frmHsv,
Scalar(lbHue,lbSat,lbVal),
Scalar(hbHue, hbSat, hbVal),
mask);
Mat roi(hue, selection);
Mat maskroi(mask, selection);
calcHist(&roi,
nimages,
channels,
maskroi,
histogram,
1,
histSize,
ranges,
uniform);
normalize(histogram,
histogram, 0, 255, NORM_MINMAX);
bitwise_not(sel, sel);
srchWnd = selection;
}
else if(!histogram.empty())
{
double scale = 1.0;
calcBackProject(&hue,
nimages,
channels,
histogram,
backProject,
ranges,
scale,
uniform);
erode(backProject,
backProject,
Mat());
// meanShift(backProject,
// srchWnd,
// criteria);
CamShift(backProject,
srchWnd,
criteria);
Point objectPos(srchWnd.x + srchWnd.width/2,
srchWnd.y + srchWnd.height/2);
pos(0) = objectPos.x;
pos(1) = objectPos.y;
Mat estimation = kalman.correct(pos);
kalman.predict();
Point estPt(estimation.at<float>(0),
estimation.at<float>(1));
drawMarker(frame,
estPt,
Scalar(0,255,0),
MARKER_CROSS,
30,
2);
cvtColor(backProject, backProject, COLOR_GRAY2BGR);
drawMarker(backProject,
estPt,
Scalar(0,255,0),
MARKER_CROSS,
30,
2);
}
switch(key)
{
case 'b':
if(!backProject.empty()) imshow(outputWindow, backProject);
else imshow(outputWindow, frame);
break;
case 'v': default: imshow(outputWindow, frame);
break;
}
int k = waitKey(10);
if(k > 0)
key = k;
}
cam.release();
return 0;
}
| 24.476415 | 71 | 0.441896 | [
"vector"
] |
596d291952cd12176e83a076504a6941d972ec5e | 1,408 | cpp | C++ | jflow_test/test_euler.cpp | flying-tiger/jflow | 847d45780d1392c22030be28e14edc810cb74d56 | [
"MIT"
] | null | null | null | jflow_test/test_euler.cpp | flying-tiger/jflow | 847d45780d1392c22030be28e14edc810cb74d56 | [
"MIT"
] | null | null | null | jflow_test/test_euler.cpp | flying-tiger/jflow | 847d45780d1392c22030be28e14edc810cb74d56 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "jflow/euler.hpp"
TEST_CASE("Verify Euler flux vector calculation") {
using namespace jflow;
const double gamma = 1.4;
const double Rgas = 287.0;
const double tol = 1e-12;
// Primitive state
const double rho = 1.0;
const double u = 5.0;
const double v = -2.0;
const double p = 1000.0;
const double E = p / rho / (gamma - 1) + 0.5 * (u * u + v * v);
// Conservative state & fluxes
const auto q = euler::state{ rho, rho * u, rho * v, rho * E };
const auto fx = euler::flux{ rho * u, rho * u * u + p, rho * u * v, u * (rho * E + p) };
const auto fy = euler::flux{ rho * v, rho * v * u, rho * v * v + p, v * (rho * E + p) };
// Configure perfect gas model
perfect_gas::set_gas_props(gamma, Rgas);
SECTION("Verify basic flux calculation") {
auto fx_calc = euler::compute_flux(q, vector2{ 1, 0 });
auto fy_calc = euler::compute_flux(q, vector2{ 0, 1 });
REQUIRE(norm(fx_calc - fx) < 1e-12);
REQUIRE(norm(fy_calc - fy) < 1e-12);
}
SECTION("Verify jump flux calculation") {
// F_jump(q,q) should return F(q)
auto fx_calc = euler::compute_jump_flux(q, q, vector2{ 1, 0 });
auto fy_calc = euler::compute_jump_flux(q, q, vector2{ 0, 1 });
REQUIRE(norm(fx_calc - fx) < 1e-12);
REQUIRE(norm(fy_calc - fy) < 1e-12);
}
}
| 33.52381 | 92 | 0.566051 | [
"vector",
"model"
] |
59756a28bc54829768b7e2a1985d4e475e5aaec3 | 1,052 | cpp | C++ | Codeforces/Round-600-Div2/E.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | Codeforces/Round-600-Div2/E.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | Codeforces/Round-600-Div2/E.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | // Tags: DP
// Difficulty: 6.5
// Priority: 3
// Date: 17-11-2021
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int n, m;
cin >> n >> m;
vector <int> vis(m + 1, false);
vector <int> x(n);
vector <int> s(n);
for (int i = 0; i < n; i++) {
cin >> x[i] >> s[i];
for (int j = 1; j <= m; j++) if (x[i] - s[i] <= j and j <= x[i] + s[i]) vis[j] = true;
}
vector <int> dp(m + 2);
dp[m + 1] = 0;
for (int i = m; i >= 1; i--) {
if (vis[i]) {
dp[i] = dp[i + 1];
continue;
}
dp[i] = m - i + 1;
for (int j = 0; j < n; j++) {
int l = x[j] - s[j];
int r = min(m + 1, x[j] + s[j]);
if (i < l) {
int cost = l - i;
dp[i] = min(dp[i], cost + dp[min(m + 1, r + cost + 1)]);
}
}
}
cout << dp[1] << '\n';
return (0);
}
| 21.04 | 90 | 0.461027 | [
"vector"
] |
597b8940b87fb97ff07041174411868e00b775bd | 9,607 | cpp | C++ | src/lisaCore.cpp | bach74/Lisa | 6f79b909f734883cd05a0ccf8679199ae2e301cf | [
"MIT",
"Unlicense"
] | 2 | 2016-06-23T21:20:19.000Z | 2020-03-25T15:01:07.000Z | src/lisaCore.cpp | bach74/Lisa | 6f79b909f734883cd05a0ccf8679199ae2e301cf | [
"MIT",
"Unlicense"
] | null | null | null | src/lisaCore.cpp | bach74/Lisa | 6f79b909f734883cd05a0ccf8679199ae2e301cf | [
"MIT",
"Unlicense"
] | null | null | null | // =============================================================================
// LisaCore.cpp
//
// Copyright (C) 2007-2012 by Bach
// This file is part of the LiSA project.
// The LiSA project is licensed under MIT license.
//
// =============================================================================
#include "stdafx.h"
#include "resource.h"
#include "misc.h"
#include "inputmanager.h"
#include "lisaCore.h"
#include "config.h"
#include "scene.h"
/**-------------------------------------------------------------------------------
construct and initialize LisaCore elements
--------------------------------------------------------------------------------*/
LisaCore::LisaCore()
{
Config::Instance();
}
/**-------------------------------------------------------------------------------
destroy LisaCore elements
--------------------------------------------------------------------------------*/
LisaCore::~LisaCore()
{
}
/**-------------------------------------------------------------------------------
setup graphics OGRE window and resources
\return (int) success?
-----------------------------------------------------------------------------*/
int LisaCore::init()
{
int ret=NO_ERROR;
// wrangle a pointer to the Root Ogre object
// the first param is the name of the plugins cfg file, the second is the name of the ogre cfg file
// we are not using either here, so provide them as empty strings to let Ogre know not to load them
// The third param is the name of the Ogre.log diagnostic file; leave it default for now
mOgre=std::unique_ptr<Ogre::Root>(new Ogre::Root("","","Ogre.log"));
try {
// add resource directory (under the program's root directory) to resources
Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resources","FileSystem","General");
// add all zip resources from the resource directory to the resources
WIN32_FIND_DATA findData;
HANDLE hFile=FindFirstFile("resources\\*.zip",&findData);
while (hFile!=INVALID_HANDLE_VALUE) {
std::string dir("resources\\");
std::string fileName(findData.cFileName);
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(dir+fileName,"Zip","GUI");
if (FindNextFile(hFile,&findData)==0) break;
}
Ogre::ResourceGroupManager::getSingleton().createResourceGroup(OGRE_DEBUG_GROUP);
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation("c:\\windows\\fonts","FileSystem","GUI");
/*DWORD dwDirectXVersion=0;
DWORD dwDirectXVersionMinor=0;
TCHAR wcDirectXVersionLetter;
HRESULT hr=GetDXVersion(&dwDirectXVersion, &dwDirectXVersionMinor, &wcDirectXVersionLetter);
if (SUCCEEDED(hr)) {
std::ostringstream dxinfoStream;
dxinfoStream << "DirectX version: " << dwDirectXVersion<<"."<<dwDirectXVersionMinor<<wcDirectXVersionLetter;
Ogre::LogManager::getSingleton().logMessage(dxinfoStream.str());
if(dwDirectXVersion >= 9) { */
try {
#if _DEBUG
mOgre->loadPlugin("plugin\\RenderSystem_Direct3D9_d");
mOgre->loadPlugin("plugin\\RenderSystem_Direct3D10_d");
#else
mOgre->loadPlugin("plugin\\RenderSystem_Direct3D9");
mOgre->loadPlugin("plugin\\RenderSystem_Direct3D10");
#endif
}
catch(Ogre::Exception& e) {
Ogre::LogManager::getSingleton().logMessage(std::string("Unable to create DirectX RenderSystem: ") + e.getFullDescription());
}
//}
//}
// load common plug-ins
#if _DEBUG
mOgre->loadPlugin("plugin\\RenderSystem_GL_d");
mOgre->loadPlugin("plugin\\Plugin_CgProgramManager_d");
mOgre->loadPlugin("plugin\\Plugin_OctreeSceneManager_d");
#else
mOgre->loadPlugin("plugin\\RenderSystem_GL");
mOgre->loadPlugin("plugin\\Plugin_CgProgramManager");
mOgre->loadPlugin("plugin\\Plugin_OctreeSceneManager");
#endif
// get video options from configuration file
VideoOptions opts;
getOptions(opts);
std::cout<<"Render Device = '"<<opts["device"]<<"'"<<std::endl;
Ogre::RenderSystem* selectedRenderSystem=NULL;
Ogre::RenderSystemList pRenderSystemList=mOgre->getAvailableRenderers();
Ogre::RenderSystemList::iterator pRenderSystem=pRenderSystemList.begin();
for (;pRenderSystem!=pRenderSystemList.end();++pRenderSystem) {
if ((*pRenderSystem)->getName() == opts["renderSystem"]) {
selectedRenderSystem = *pRenderSystem;
break;
}
}
if (pRenderSystem==pRenderSystemList.end()) {
throw VideoInitializationException("Specified render system ("+opts["renderSystem"]+") does not exist");
}
mOgre->setRenderSystem(selectedRenderSystem);
selectedRenderSystem->setConfigOption("Full Screen", opts["fullscreen"]);
selectedRenderSystem->setConfigOption("VSync", opts["vsync"]);
if ((opts["renderSystem"]=="Direct3D9 Rendering Subsystem")||(opts["renderSystem"]=="Direct3D10 Rendering Subsystem")) {
selectedRenderSystem->setConfigOption("Video Mode",opts["resolution"]+" @ "+opts["colourDepth"] + "-bit colour");
selectedRenderSystem->setConfigOption("FSAA","Level "+opts["FSAA"]);
} else {
selectedRenderSystem->setConfigOption("Video Mode",opts["resolution"]);
selectedRenderSystem->setConfigOption("Colour Depth",opts["colourDepth"]);
selectedRenderSystem->setConfigOption("FSAA", opts["FSAA"]);
}
mWindow=std::unique_ptr<Ogre::RenderWindow>(mOgre->initialise(true,getStringFromResource(IDS_APPNAME)));
// change default icon
// Get window handle
HWND hWnd;
mWindow->getCustomAttribute("WINDOW", &hWnd);
//HICON hIcon=::LoadIcon(GetModuleHandle(NULL), (LPCTSTR)IDI_LISA);
//::SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
HICON hIcon=::LoadIcon(GetModuleHandle(NULL), (LPCTSTR)IDI_LISA_SMALL);
::SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
//::SendMessage(hWnd, WM_SETICON, ICON_SMALL2, (LPARAM)hIcon);
}
catch (Ogre::Exception &e) {
std::string msg=e.getFullDescription();
std::cerr<<msg<<std::endl;
throw;
}
return ret;
}
/**-------------------------------------------------------------------------------
release memory
\return (int)
-----------------------------------------------------------------------------*/
int LisaCore::deinit()
{
Ogre::ResourceGroupManager::getSingletonPtr()->removeResourceLocation("resources","General");
Ogre::ResourceGroupManager::getSingletonPtr()->removeResourceLocation("resources/resources.zip","GUI");
//Ogre::ResourceGroupManager::getSingletonPtr()->removeResourceLocation("c:\\windows\\fonts","GUI");
Ogre::ResourceGroupManager::getSingletonPtr()->clearResourceGroup("General");
Ogre::ResourceGroupManager::getSingletonPtr()->clearResourceGroup("GUI");
Ogre::ResourceGroupManager::getSingletonPtr()->clearResourceGroup(OGRE_DEBUG_GROUP);
mOgre->detachRenderTarget(mWindow.get());
return 0;
}
/**-------------------------------------------------------------------------------
load options from a configuration file. Configuration file is a plain .ini file.
\param opts (VideoOptions &) video options parsed from a config file
\return (bool)
-----------------------------------------------------------------------------*/
bool LisaCore::getOptions(VideoOptions& opts) const
{
// read these from the ubiquitous config file...on Win32 we have a nice handy
// API to read config files; on other platforms we'll need to fake one
TCHAR path[MAX_PATH+1];
try {
int i=GetCurrentDirectory(MAX_PATH,path);
path[i]='\\';
path[i+1]='\0';
TCHAR res[1024];
LoadString(NULL,IDS_CONFIG_FILE_NAME,res,1024);
strcat_s(path,MAX_PATH,res);
Ogre::ConfigFile cf;
cf.load(path);
Ogre::ConfigFile::SectionIterator seci=cf.getSectionIterator();
while (seci.hasMoreElements()) {
Ogre::String secName = seci.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap *csettings = seci.getNext();
if (secName=="display") {
Ogre::ConfigFile::SettingsMultiMap::iterator i=csettings->begin();
for (;i!=csettings->end(); ++i) {
opts.insert(VideoOptions::value_type(i->first,i->second));
}
break;
}
}
}
catch(...) {
throw VideoInitializationException(_T("Cannot read video settings"));
}
return true;
}
/**-------------------------------------------------------------------------------
main simulator loop, break on exit
\return (void)
-----------------------------------------------------------------------------*/
void LisaCore::go()
{
init();
//create Scene
mScene=std::unique_ptr<Scene>(new Scene(mWindow.get()));
// get video options from configuration file
VideoOptions opts;
getOptions(opts);
// setup scene (load scene)
std::string val=opts.find("model")->second;
mScene->loadScene(val.c_str());
// get shadow options
val=opts.find("shadows")->second;
mScene->setShadowTechnique((val=="true")?Ogre::SHADOWTYPE_STENCIL_ADDITIVE:Ogre::SHADOWTYPE_NONE);
//mScene->setShadowTechnique((val=="true")?SHADOWTYPE_TEXTURE_ADDITIVE:SHADOWTYPE_NONE);
// start simulation
mScene->run();
// clean up
mScene.release();
deinit();
}
/**----------------------------------------------------------------------------
try to exit the application.
\return (void)
-----------------------------------------------------------------------------*/
void LisaCore::stop()
{
HWND hWnd=::FindWindow(NULL,getStringFromResource(IDS_APPNAME).c_str());
SendMessage(hWnd,WM_CLOSE,0,0);
}
/**----------------------------------------------------------------------------
get Simulation pointer
\return (void)
-----------------------------------------------------------------------------*/
const Simulation* LisaCore::getSimulation() const
{
return mScene->getSimulation();
} | 34.433692 | 131 | 0.609868 | [
"render",
"object",
"model"
] |
597eff361783737f838cfa08040647f38c3b1c8c | 7,297 | cpp | C++ | tenncor/eteq/opsvc/test/test_derive.cpp | mingkaic/tenncor | f2fa9652e55e9ca206de5e9741fe41bde43791c1 | [
"BSL-1.0",
"MIT"
] | 1 | 2020-12-29T20:38:08.000Z | 2020-12-29T20:38:08.000Z | tenncor/eteq/opsvc/test/test_derive.cpp | mingkaic/tenncor | f2fa9652e55e9ca206de5e9741fe41bde43791c1 | [
"BSL-1.0",
"MIT"
] | 16 | 2018-01-28T04:20:19.000Z | 2021-01-23T09:38:52.000Z | tenncor/eteq/opsvc/test/test_derive.cpp | mingkaic/tenncor | f2fa9652e55e9ca206de5e9741fe41bde43791c1 | [
"BSL-1.0",
"MIT"
] | null | null | null |
#ifndef DISABLE_OPSVC_DERIVE_TEST
#include "gtest/gtest.h"
#include "exam/exam.hpp"
#include "testutil/tutil.hpp"
#include "internal/teq/mock/mock.hpp"
#include "tenncor/distr/mock/mock.hpp"
#include "tenncor/distr/iosvc/mock/mock.hpp"
#include "tenncor/eteq/opsvc/mock/mock.hpp"
using ::testing::Invoke;
using ::testing::DoAll;
using ::testing::SaveArg;
const std::string test_service = "tenncor.eteq.opsvc.test";
struct DERIVE : public ::testing::Test, public DistrTestcase
{
protected:
distr::iDistrMgrptrT make_mgr (const std::string& id)
{
return make_mgr(id, reserve_port());
}
distr::iDistrMgrptrT make_mgr (const std::string& id, size_t port)
{
return DistrTestcase::make_local_mgr(port, {
register_mock_iosvc,
[](estd::ConfigMap<>& svcs, const distr::PeerServiceConfig& cfg) -> error::ErrptrT
{
auto iosvc = static_cast<distr::io::DistrIOService*>(svcs.get_obj(distr::io::iosvc_key));
if (nullptr == iosvc)
{
return error::error("opsvc requires iosvc already registered");
}
svcs.add_entry<distr::op::DistrOpService>(distr::op::opsvc_key,
[&]
{
return new distr::op::DistrOpService(
std::make_unique<eigen::Device>(std::numeric_limits<size_t>::max()),
std::make_unique<MockDerivativeFunc>(), cfg, iosvc,
std::make_shared<MockDistrOpCliBuilder>(),
std::make_shared<MockOpService>());
});
return nullptr;
},
}, id);
}
};
TEST_F(DERIVE, RemoteDerivation)
{
teq::Shape shape({2, 2});
std::vector<double> data = {1, 2, 3, 4};
MockDeviceRef devref;
MockMeta mockmeta;
// instance 1
distr::iDistrMgrptrT mgr(make_mgr("mgr1"));
auto a = make_var(data.data(), devref, shape, "a");
auto b = make_var(data.data(), devref, shape, "b");
auto c = make_var(data.data(), devref, shape, "c");
EXPECT_CALL(*a, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*b, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*c, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(mockmeta, type_code()).WillRepeatedly(Return(egen::DOUBLE));
EXPECT_CALL(mockmeta, type_label()).WillRepeatedly(Return("DOUBLE"));
auto d = make_fnc("FUNC5", 0, teq::TensptrsT{b, a});
auto e = make_fnc("FUNC4", 0, teq::TensptrsT{c, d});
auto farg = make_fnc("FUNC3", 0, teq::TensptrsT{d});
auto farg2 = make_fnc("FUNC2", 0, teq::TensptrsT{c});
auto f = make_fnc("FUNC1", 0, teq::TensptrsT{farg, farg2});
EXPECT_CALL(*d, shape()).WillRepeatedly(Return(shape));
EXPECT_CALL(*e, shape()).WillRepeatedly(Return(shape));
EXPECT_CALL(*farg, shape()).WillRepeatedly(Return(shape));
EXPECT_CALL(*farg2, shape()).WillRepeatedly(Return(shape));
EXPECT_CALL(*f, shape()).WillRepeatedly(Return(shape));
EXPECT_CALL(*d, device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(*e, device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(*farg, device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(*farg2, device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(*f, device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(Const(*d), device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(Const(*e), device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(Const(*farg), device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(Const(*farg2), device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(Const(*f), device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(*d, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*e, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*farg, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*farg2, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*f, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
auto root = make_fnc("FUNC", 0, teq::TensptrsT{e, f});
EXPECT_CALL(*root, shape()).WillRepeatedly(Return(shape));
EXPECT_CALL(*root, device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(Const(*root), device()).WillRepeatedly(ReturnRef(devref));
EXPECT_CALL(*root, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
auto& svc = distr::get_iosvc(*mgr);
std::string root_id = svc.expose_node(root);
std::string base_id = svc.expose_node(a);
// instance 2
distr::iDistrMgrptrT mgr2 = make_mgr("mgr2");
auto& svc2 = distr::get_iosvc(*mgr2);
error::ErrptrT err = nullptr;
teq::TensptrT root_ref = svc2.lookup_node(err, root_id);
ASSERT_NOERR(err);
teq::TensptrT base_ref = svc2.lookup_node(err, base_id);
ASSERT_NOERR(err);
MockDerivativeFunc* remotedfunc = dynamic_cast<MockDerivativeFunc*>(
distr::get_opsvc(*mgr).get_derivfuncs());
MockDerivativeFunc* localdfunc = dynamic_cast<MockDerivativeFunc*>(
distr::get_opsvc(*mgr2).get_derivfuncs());
ASSERT_NE(nullptr, remotedfunc);
ASSERT_NE(nullptr, localdfunc);
auto der = make_var(shape, "der");
auto der2 = make_var(shape, "der2");
auto der3 = make_var(shape, "der3");
auto der4 = make_var(shape, "der4");
auto der5 = make_var(shape, "der5");
auto der6 = make_var(shape, "der6");
auto der7 = make_var(shape, "der7");
auto der8 = make_var(shape, "der8");
EXPECT_CALL(*der, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der2, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der3, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der4, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der5, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der6, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der7, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
EXPECT_CALL(*der8, get_meta()).WillRepeatedly(ReturnRef(mockmeta));
teq::TensptrT capder = nullptr;
teq::TensptrT cap2der = nullptr;
EXPECT_CALL(*remotedfunc, lderive(teq::FuncptrT(root), _, 0)).Times(1).
WillOnce(DoAll(SaveArg<1>(&capder),Return(der2)));
EXPECT_CALL(*remotedfunc, lderive(teq::FuncptrT(root), _, 1)).Times(1).
WillOnce(DoAll(SaveArg<1>(&cap2der),Return(der3)));
EXPECT_CALL(*remotedfunc, lderive(teq::FuncptrT(f), teq::TensptrT(der3), 0)).Times(1).
WillOnce(Return(der4));
EXPECT_CALL(*remotedfunc, lderive(teq::FuncptrT(e), teq::TensptrT(der2), 1)).Times(1).
WillOnce(Return(der5));
EXPECT_CALL(*remotedfunc, lderive(teq::FuncptrT(farg), teq::TensptrT(der4), 0)).Times(1).
WillOnce(Return(der6));
EXPECT_CALL(*remotedfunc, lderive(teq::FuncptrT(d), teq::TensptrT(der8), 1)).Times(1).
WillOnce(Return(der7));
EXPECT_CALL(*remotedfunc, add(teq::TensptrsT{der5, der6})).Times(1).WillOnce(Return(der8));
teq::TensMapT<teq::TensptrsT> grads = {
{root_ref.get(), {der}}
};
auto remote_ders = distr::get_opsvc(*mgr2).derive(
grads, {root_ref}, distr::op::BackpropMeta{
teq::TensSetT{base_ref.get()}});
ASSERT_EQ(1, remote_ders.size());
EXPECT_HAS(remote_ders, base_ref.get());
auto dbase = remote_ders[base_ref.get()];
// compare der reference after to ensure that derive automatically references der
EXPECT_EQ(capder, cap2der);
auto derid = svc2.lookup_id(der.get());
ASSERT_TRUE(bool(derid));
auto derref = svc.lookup_node(err, *derid);
ASSERT_NOERR(err);
EXPECT_EQ(derref, capder);
auto der7id = svc.lookup_id(der7.get());
ASSERT_TRUE(bool(der7id));
auto der7ref = svc2.lookup_node(err, *der7id);
ASSERT_NOERR(err);
EXPECT_EQ(der7ref, dbase);
}
#endif // DISABLE_OPSVC_DERIVE_TEST
| 37.613402 | 93 | 0.722078 | [
"shape",
"vector"
] |
5981d6c71981710cc5143abf0c40dbb2ca5b4cba | 975 | cpp | C++ | Core/Entity.cpp | AdamJHowell/CLIExample | ba4cebbb670b51f111a8fb7c0053d4fe508231c1 | [
"MIT"
] | 1 | 2022-01-21T10:16:12.000Z | 2022-01-21T10:16:12.000Z | Core/Entity.cpp | AdamJHowell/CLIExample | ba4cebbb670b51f111a8fb7c0053d4fe508231c1 | [
"MIT"
] | null | null | null | Core/Entity.cpp | AdamJHowell/CLIExample | ba4cebbb670b51f111a8fb7c0053d4fe508231c1 | [
"MIT"
] | null | null | null | //Entity.cpp
#include "Entity.h"
#include <iostream>
#include <string>
namespace Core
{
Entity::Entity( const char* name, int xPos, int yPos )
: m_Name( name ), m_XPos( xPos ), m_YPos( yPos )
{
std::cout << "Created the Entity object!" << std::endl;
}
void Entity::Move( int deltaX, int deltaY )
{
m_XPos += deltaX;
m_YPos += deltaY;
std::cout << "Moved " << m_Name << " to (" << m_XPos << ", " << m_YPos << ")." << std::endl;
}
void Entity::TypeAhead( std::string words, int count )
{
std::vector<std::string> resultVector;// = new std::vector<std::string>;
// Add words to the vector count number of times.
for( int i = 0; i < count; i++ )
{
resultVector.push_back( words );
}
// Print the vector from here to verify it works.
// This is interim code until I can properly return the vector.
for( size_t i = 0; i < resultVector.size(); i++ )
{
std::cout << resultVector.at( i ) << std::endl;
}
stuff = resultVector;
}
}
| 24.375 | 94 | 0.610256 | [
"object",
"vector"
] |
598855e7786179316242b828766358257d0830bc | 31,926 | cpp | C++ | modules/glfw/src/addon.cpp | mzegar/node-rapids | 5b2c3dafbec5f17dcedf8147a8f668a986622cc4 | [
"Apache-2.0"
] | 1 | 2021-06-24T23:08:49.000Z | 2021-06-24T23:08:49.000Z | modules/glfw/src/addon.cpp | love-lena/node-rapids | 27c9e2468372df4fae3779d859089b54c8d32c4f | [
"Apache-2.0"
] | null | null | null | modules/glfw/src/addon.cpp | love-lena/node-rapids | 27c9e2468372df4fae3779d859089b54c8d32c4f | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020-2021, 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 "addon.hpp"
#include "glfw.hpp"
#include "macros.hpp"
#include <nv_node/utilities/args.hpp>
#include <nv_node/utilities/cpp_to_napi.hpp>
std::ostream& operator<<(std::ostream& os, const nv::NapiToCPP& self) {
return os << self.operator std::string();
};
namespace nv {
// GLFWAPI int glfwInit(void);
Napi::Value glfwInit(Napi::CallbackInfo const& info) {
auto env = info.Env();
GLFW_EXPECT_TRUE(env, GLFWAPI::glfwInit());
return info.This();
}
// GLFWAPI void glfwTerminate(void);
void glfwTerminate(Napi::CallbackInfo const& info) {
auto env = info.Env();
GLFW_TRY(env, GLFWAPI::glfwTerminate());
}
// GLFWAPI void glfwInitHint(int hint, int value);
void glfwInitHint(Napi::CallbackInfo const& info) {
auto env = info.Env();
CallbackArgs args{info};
GLFW_TRY(env, GLFWAPI::glfwInitHint(args[0], args[1]));
}
// GLFWAPI void glfwGetVersion(int* major, int* minor, int* rev);
Napi::Value glfwGetVersion(Napi::CallbackInfo const& info) {
auto env = info.Env();
int32_t major{}, minor{}, rev{};
GLFW_TRY(env, GLFWAPI::glfwGetVersion(&major, &minor, &rev));
return CPPToNapi(info)(std::map<std::string, int32_t>{//
{"major", major},
{"minor", minor},
{"rev", rev}});
}
// GLFWAPI const char* glfwGetVersionString(void);
Napi::Value glfwGetVersionString(Napi::CallbackInfo const& info) {
auto version = GLFWAPI::glfwGetVersionString();
return CPPToNapi(info)(std::string{version == nullptr ? "" : version});
}
// GLFWAPI int glfwGetError(const char** description);
Napi::Value glfwGetError(Napi::CallbackInfo const& info) {
auto env = info.Env();
const char* err = nullptr;
const int code = GLFWAPI::glfwGetError(&err);
if (code == GLFW_NO_ERROR) { return env.Undefined(); }
return nv::glfwError(env, code, err, __FILE__, __LINE__).Value();
}
// GLFWAPI const char* glfwGetKeyName(int key, int scancode);
Napi::Value glfwGetKeyName(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
auto name = GLFWAPI::glfwGetKeyName(args[0], args[1]);
return CPPToNapi(info)(std::string{name == nullptr ? "" : name});
}
// GLFWAPI int glfwGetKeyScancode(int key);
Napi::Value glfwGetKeyScancode(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return CPPToNapi(info)(GLFWAPI::glfwGetKeyScancode(args[0]));
}
// GLFWAPI double glfwGetTime(void);
Napi::Value glfwGetTime(Napi::CallbackInfo const& info) {
return CPPToNapi(info)(GLFWAPI::glfwGetTime());
}
// GLFWAPI void glfwSetTime(double time);
void glfwSetTime(Napi::CallbackInfo const& info) {
auto env = info.Env();
CallbackArgs args{info};
GLFW_TRY(env, GLFWAPI::glfwSetTime(args[0]));
}
// GLFWAPI uint64_t glfwGetTimerValue(void);
Napi::Value glfwGetTimerValue(Napi::CallbackInfo const& info) {
return CPPToNapi(info)(GLFWAPI::glfwGetTimerValue());
}
// GLFWAPI uint64_t glfwGetTimerFrequency(void);
Napi::Value glfwGetTimerFrequency(Napi::CallbackInfo const& info) {
return CPPToNapi(info)(GLFWAPI::glfwGetTimerFrequency());
}
// GLFWAPI void glfwSwapInterval(int interval);
void glfwSwapInterval(Napi::CallbackInfo const& info) {
auto env = info.Env();
CallbackArgs args{info};
GLFW_TRY(env, GLFWAPI::glfwSwapInterval(args[0]));
}
// GLFWAPI int glfwExtensionSupported(const char* extension);
Napi::Value glfwExtensionSupported(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
std::string extension = args[0];
auto is_extension_supported = GLFWAPI::glfwExtensionSupported(extension.data());
return CPPToNapi(info)(static_cast<bool>(is_extension_supported));
}
// GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname);
Napi::Value glfwGetProcAddress(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
std::string name = args[0];
auto addr = GLFWAPI::glfwGetProcAddress(name.data());
return CPPToNapi(info)(reinterpret_cast<char*>(addr));
}
// GLFWAPI const char** glfwGetRequiredInstanceExtensions(uint32_t* count);
Napi::Value glfwGetRequiredInstanceExtensions(Napi::CallbackInfo const& info) {
uint32_t count{};
const char** exts = GLFWAPI::glfwGetRequiredInstanceExtensions(&count);
return CPPToNapi(info)(std::vector<std::string>{exts, exts + count});
}
} // namespace nv
Napi::Object initModule(Napi::Env env, Napi::Object exports) {
EXPORT_FUNC(env, exports, "init", nv::glfwInit);
EXPORT_FUNC(env, exports, "terminate", nv::glfwTerminate);
EXPORT_FUNC(env, exports, "initHint", nv::glfwInitHint);
EXPORT_FUNC(env, exports, "getVersion", nv::glfwGetVersion);
EXPORT_FUNC(env, exports, "getVersionString", nv::glfwGetVersionString);
EXPORT_FUNC(env, exports, "setErrorCallback", nv::glfwSetErrorCallback);
EXPORT_FUNC(env, exports, "getMonitors", nv::glfwGetMonitors);
EXPORT_FUNC(env, exports, "getPrimaryMonitor", nv::glfwGetPrimaryMonitor);
EXPORT_FUNC(env, exports, "getMonitorPos", nv::glfwGetMonitorPos);
EXPORT_FUNC(env, exports, "getMonitorWorkarea", nv::glfwGetMonitorWorkarea);
EXPORT_FUNC(env, exports, "getMonitorPhysicalSize", nv::glfwGetMonitorPhysicalSize);
EXPORT_FUNC(env, exports, "getMonitorContentScale", nv::glfwGetMonitorContentScale);
EXPORT_FUNC(env, exports, "getMonitorName", nv::glfwGetMonitorName);
EXPORT_FUNC(env, exports, "setMonitorCallback", nv::glfwSetMonitorCallback);
EXPORT_FUNC(env, exports, "getVideoModes", nv::glfwGetVideoModes);
EXPORT_FUNC(env, exports, "getVideoMode", nv::glfwGetVideoMode);
EXPORT_FUNC(env, exports, "setGamma", nv::glfwSetGamma);
EXPORT_FUNC(env, exports, "getGammaRamp", nv::glfwGetGammaRamp);
EXPORT_FUNC(env, exports, "setGammaRamp", nv::glfwSetGammaRamp);
EXPORT_FUNC(env, exports, "defaultWindowHints", nv::glfwDefaultWindowHints);
EXPORT_FUNC(env, exports, "windowHint", nv::glfwWindowHint);
EXPORT_FUNC(env, exports, "windowHintString", nv::glfwWindowHintString);
EXPORT_FUNC(env, exports, "createWindow", nv::glfwCreateWindow);
#ifdef __linux__
EXPORT_FUNC(env, exports, "reparentWindow", nv::glfwReparentWindow);
#endif
EXPORT_FUNC(env, exports, "destroyWindow", nv::glfwDestroyWindow);
EXPORT_FUNC(env, exports, "windowShouldClose", nv::glfwWindowShouldClose);
EXPORT_FUNC(env, exports, "setWindowShouldClose", nv::glfwSetWindowShouldClose);
EXPORT_FUNC(env, exports, "setWindowTitle", nv::glfwSetWindowTitle);
EXPORT_FUNC(env, exports, "setWindowIcon", nv::glfwSetWindowIcon);
EXPORT_FUNC(env, exports, "getWindowPos", nv::glfwGetWindowPos);
EXPORT_FUNC(env, exports, "setWindowPos", nv::glfwSetWindowPos);
EXPORT_FUNC(env, exports, "getWindowSize", nv::glfwGetWindowSize);
EXPORT_FUNC(env, exports, "setWindowSizeLimits", nv::glfwSetWindowSizeLimits);
EXPORT_FUNC(env, exports, "setWindowAspectRatio", nv::glfwSetWindowAspectRatio);
EXPORT_FUNC(env, exports, "setWindowSize", nv::glfwSetWindowSize);
EXPORT_FUNC(env, exports, "getFramebufferSize", nv::glfwGetFramebufferSize);
EXPORT_FUNC(env, exports, "getWindowFrameSize", nv::glfwGetWindowFrameSize);
EXPORT_FUNC(env, exports, "getWindowContentScale", nv::glfwGetWindowContentScale);
EXPORT_FUNC(env, exports, "getWindowOpacity", nv::glfwGetWindowOpacity);
EXPORT_FUNC(env, exports, "setWindowOpacity", nv::glfwSetWindowOpacity);
EXPORT_FUNC(env, exports, "iconifyWindow", nv::glfwIconifyWindow);
EXPORT_FUNC(env, exports, "restoreWindow", nv::glfwRestoreWindow);
EXPORT_FUNC(env, exports, "maximizeWindow", nv::glfwMaximizeWindow);
EXPORT_FUNC(env, exports, "showWindow", nv::glfwShowWindow);
EXPORT_FUNC(env, exports, "hideWindow", nv::glfwHideWindow);
EXPORT_FUNC(env, exports, "focusWindow", nv::glfwFocusWindow);
EXPORT_FUNC(env, exports, "requestWindowAttention", nv::glfwRequestWindowAttention);
EXPORT_FUNC(env, exports, "getWindowMonitor", nv::glfwGetWindowMonitor);
EXPORT_FUNC(env, exports, "setWindowMonitor", nv::glfwSetWindowMonitor);
EXPORT_FUNC(env, exports, "getWindowAttrib", nv::glfwGetWindowAttrib);
EXPORT_FUNC(env, exports, "setWindowAttrib", nv::glfwSetWindowAttrib);
EXPORT_FUNC(env, exports, "setWindowPosCallback", nv::glfwSetWindowPosCallback);
EXPORT_FUNC(env, exports, "setWindowSizeCallback", nv::glfwSetWindowSizeCallback);
EXPORT_FUNC(env, exports, "setWindowCloseCallback", nv::glfwSetWindowCloseCallback);
EXPORT_FUNC(env, exports, "setWindowRefreshCallback", nv::glfwSetWindowRefreshCallback);
EXPORT_FUNC(env, exports, "setWindowFocusCallback", nv::glfwSetWindowFocusCallback);
EXPORT_FUNC(env, exports, "setWindowIconifyCallback", nv::glfwSetWindowIconifyCallback);
EXPORT_FUNC(env, exports, "setWindowMaximizeCallback", nv::glfwSetWindowMaximizeCallback);
EXPORT_FUNC(env, exports, "setFramebufferSizeCallback", nv::glfwSetFramebufferSizeCallback);
EXPORT_FUNC(env, exports, "setWindowContentScaleCallback", nv::glfwSetWindowContentScaleCallback);
EXPORT_FUNC(env, exports, "pollEvents", nv::glfwPollEvents);
EXPORT_FUNC(env, exports, "waitEvents", nv::glfwWaitEvents);
EXPORT_FUNC(env, exports, "waitEventsTimeout", nv::glfwWaitEventsTimeout);
EXPORT_FUNC(env, exports, "postEmptyEvent", nv::glfwPostEmptyEvent);
EXPORT_FUNC(env, exports, "getInputMode", nv::glfwGetInputMode);
EXPORT_FUNC(env, exports, "setInputMode", nv::glfwSetInputMode);
EXPORT_FUNC(env, exports, "rawMouseMotionSupported", nv::glfwRawMouseMotionSupported);
EXPORT_FUNC(env, exports, "getKeyName", nv::glfwGetKeyName);
EXPORT_FUNC(env, exports, "getKeyScancode", nv::glfwGetKeyScancode);
EXPORT_FUNC(env, exports, "getKey", nv::glfwGetKey);
EXPORT_FUNC(env, exports, "getMouseButton", nv::glfwGetMouseButton);
EXPORT_FUNC(env, exports, "getCursorPos", nv::glfwGetCursorPos);
EXPORT_FUNC(env, exports, "setCursorPos", nv::glfwSetCursorPos);
EXPORT_FUNC(env, exports, "createCursor", nv::glfwCreateCursor);
EXPORT_FUNC(env, exports, "createStandardCursor", nv::glfwCreateStandardCursor);
EXPORT_FUNC(env, exports, "destroyCursor", nv::glfwDestroyCursor);
EXPORT_FUNC(env, exports, "setCursor", nv::glfwSetCursor);
EXPORT_FUNC(env, exports, "setKeyCallback", nv::glfwSetKeyCallback);
EXPORT_FUNC(env, exports, "setCharCallback", nv::glfwSetCharCallback);
EXPORT_FUNC(env, exports, "setCharModsCallback", nv::glfwSetCharModsCallback);
EXPORT_FUNC(env, exports, "setMouseButtonCallback", nv::glfwSetMouseButtonCallback);
EXPORT_FUNC(env, exports, "setCursorPosCallback", nv::glfwSetCursorPosCallback);
EXPORT_FUNC(env, exports, "setCursorEnterCallback", nv::glfwSetCursorEnterCallback);
EXPORT_FUNC(env, exports, "setScrollCallback", nv::glfwSetScrollCallback);
EXPORT_FUNC(env, exports, "setDropCallback", nv::glfwSetDropCallback);
EXPORT_FUNC(env, exports, "joystickPresent", nv::glfwJoystickPresent);
EXPORT_FUNC(env, exports, "getJoystickAxes", nv::glfwGetJoystickAxes);
EXPORT_FUNC(env, exports, "getJoystickButtons", nv::glfwGetJoystickButtons);
EXPORT_FUNC(env, exports, "getJoystickHats", nv::glfwGetJoystickHats);
EXPORT_FUNC(env, exports, "getJoystickName", nv::glfwGetJoystickName);
EXPORT_FUNC(env, exports, "getJoystickGUID", nv::glfwGetJoystickGUID);
EXPORT_FUNC(env, exports, "joystickIsGamepad", nv::glfwJoystickIsGamepad);
EXPORT_FUNC(env, exports, "setJoystickCallback", nv::glfwSetJoystickCallback);
EXPORT_FUNC(env, exports, "updateGamepadMappings", nv::glfwUpdateGamepadMappings);
EXPORT_FUNC(env, exports, "getGamepadName", nv::glfwGetGamepadName);
EXPORT_FUNC(env, exports, "getGamepadState", nv::glfwGetGamepadState);
EXPORT_FUNC(env, exports, "setClipboardString", nv::glfwSetClipboardString);
EXPORT_FUNC(env, exports, "getClipboardString", nv::glfwGetClipboardString);
EXPORT_FUNC(env, exports, "getTime", nv::glfwGetTime);
EXPORT_FUNC(env, exports, "setTime", nv::glfwSetTime);
EXPORT_FUNC(env, exports, "getTimerValue", nv::glfwGetTimerValue);
EXPORT_FUNC(env, exports, "getTimerFrequency", nv::glfwGetTimerFrequency);
EXPORT_FUNC(env, exports, "makeContextCurrent", nv::glfwMakeContextCurrent);
EXPORT_FUNC(env, exports, "getCurrentContext", nv::glfwGetCurrentContext);
EXPORT_FUNC(env, exports, "swapBuffers", nv::glfwSwapBuffers);
EXPORT_FUNC(env, exports, "swapInterval", nv::glfwSwapInterval);
EXPORT_FUNC(env, exports, "extensionSupported", nv::glfwExtensionSupported);
EXPORT_FUNC(env, exports, "getProcAddress", nv::glfwGetProcAddress);
EXPORT_FUNC(env, exports, "vulkanSupported", nv::glfwVulkanSupported);
EXPORT_FUNC(env, exports, "getRequiredInstanceExtensions", nv::glfwGetRequiredInstanceExtensions);
EXPORT_ENUM(env, exports, "VERSION_MAJOR", GLFW_VERSION_MAJOR);
EXPORT_ENUM(env, exports, "VERSION_MINOR", GLFW_VERSION_MINOR);
EXPORT_ENUM(env, exports, "VERSION_REVISION", GLFW_VERSION_REVISION);
EXPORT_ENUM(env, exports, "TRUE", GLFW_TRUE);
EXPORT_ENUM(env, exports, "FALSE", GLFW_FALSE);
EXPORT_ENUM(env, exports, "RELEASE", GLFW_RELEASE);
EXPORT_ENUM(env, exports, "PRESS", GLFW_PRESS);
EXPORT_ENUM(env, exports, "REPEAT", GLFW_REPEAT);
EXPORT_ENUM(env, exports, "HAT_CENTERED", GLFW_HAT_CENTERED);
EXPORT_ENUM(env, exports, "HAT_UP", GLFW_HAT_UP);
EXPORT_ENUM(env, exports, "HAT_RIGHT", GLFW_HAT_RIGHT);
EXPORT_ENUM(env, exports, "HAT_DOWN", GLFW_HAT_DOWN);
EXPORT_ENUM(env, exports, "HAT_LEFT", GLFW_HAT_LEFT);
EXPORT_ENUM(env, exports, "HAT_RIGHT_UP", GLFW_HAT_RIGHT_UP);
EXPORT_ENUM(env, exports, "HAT_RIGHT_DOWN", GLFW_HAT_RIGHT_DOWN);
EXPORT_ENUM(env, exports, "HAT_LEFT_UP", GLFW_HAT_LEFT_UP);
EXPORT_ENUM(env, exports, "HAT_LEFT_DOWN", GLFW_HAT_LEFT_DOWN);
EXPORT_ENUM(env, exports, "KEY_UNKNOWN", GLFW_KEY_UNKNOWN);
EXPORT_ENUM(env, exports, "KEY_SPACE", GLFW_KEY_SPACE);
EXPORT_ENUM(env, exports, "KEY_APOSTROPHE", GLFW_KEY_APOSTROPHE);
EXPORT_ENUM(env, exports, "KEY_COMMA", GLFW_KEY_COMMA);
EXPORT_ENUM(env, exports, "KEY_MINUS", GLFW_KEY_MINUS);
EXPORT_ENUM(env, exports, "KEY_PERIOD", GLFW_KEY_PERIOD);
EXPORT_ENUM(env, exports, "KEY_SLASH", GLFW_KEY_SLASH);
EXPORT_ENUM(env, exports, "KEY_0", GLFW_KEY_0);
EXPORT_ENUM(env, exports, "KEY_1", GLFW_KEY_1);
EXPORT_ENUM(env, exports, "KEY_2", GLFW_KEY_2);
EXPORT_ENUM(env, exports, "KEY_3", GLFW_KEY_3);
EXPORT_ENUM(env, exports, "KEY_4", GLFW_KEY_4);
EXPORT_ENUM(env, exports, "KEY_5", GLFW_KEY_5);
EXPORT_ENUM(env, exports, "KEY_6", GLFW_KEY_6);
EXPORT_ENUM(env, exports, "KEY_7", GLFW_KEY_7);
EXPORT_ENUM(env, exports, "KEY_8", GLFW_KEY_8);
EXPORT_ENUM(env, exports, "KEY_9", GLFW_KEY_9);
EXPORT_ENUM(env, exports, "KEY_SEMICOLON", GLFW_KEY_SEMICOLON);
EXPORT_ENUM(env, exports, "KEY_EQUAL", GLFW_KEY_EQUAL);
EXPORT_ENUM(env, exports, "KEY_A", GLFW_KEY_A);
EXPORT_ENUM(env, exports, "KEY_B", GLFW_KEY_B);
EXPORT_ENUM(env, exports, "KEY_C", GLFW_KEY_C);
EXPORT_ENUM(env, exports, "KEY_D", GLFW_KEY_D);
EXPORT_ENUM(env, exports, "KEY_E", GLFW_KEY_E);
EXPORT_ENUM(env, exports, "KEY_F", GLFW_KEY_F);
EXPORT_ENUM(env, exports, "KEY_G", GLFW_KEY_G);
EXPORT_ENUM(env, exports, "KEY_H", GLFW_KEY_H);
EXPORT_ENUM(env, exports, "KEY_I", GLFW_KEY_I);
EXPORT_ENUM(env, exports, "KEY_J", GLFW_KEY_J);
EXPORT_ENUM(env, exports, "KEY_K", GLFW_KEY_K);
EXPORT_ENUM(env, exports, "KEY_L", GLFW_KEY_L);
EXPORT_ENUM(env, exports, "KEY_M", GLFW_KEY_M);
EXPORT_ENUM(env, exports, "KEY_N", GLFW_KEY_N);
EXPORT_ENUM(env, exports, "KEY_O", GLFW_KEY_O);
EXPORT_ENUM(env, exports, "KEY_P", GLFW_KEY_P);
EXPORT_ENUM(env, exports, "KEY_Q", GLFW_KEY_Q);
EXPORT_ENUM(env, exports, "KEY_R", GLFW_KEY_R);
EXPORT_ENUM(env, exports, "KEY_S", GLFW_KEY_S);
EXPORT_ENUM(env, exports, "KEY_T", GLFW_KEY_T);
EXPORT_ENUM(env, exports, "KEY_U", GLFW_KEY_U);
EXPORT_ENUM(env, exports, "KEY_V", GLFW_KEY_V);
EXPORT_ENUM(env, exports, "KEY_W", GLFW_KEY_W);
EXPORT_ENUM(env, exports, "KEY_X", GLFW_KEY_X);
EXPORT_ENUM(env, exports, "KEY_Y", GLFW_KEY_Y);
EXPORT_ENUM(env, exports, "KEY_Z", GLFW_KEY_Z);
EXPORT_ENUM(env, exports, "KEY_LEFT_BRACKET", GLFW_KEY_LEFT_BRACKET);
EXPORT_ENUM(env, exports, "KEY_BACKSLASH", GLFW_KEY_BACKSLASH);
EXPORT_ENUM(env, exports, "KEY_RIGHT_BRACKET", GLFW_KEY_RIGHT_BRACKET);
EXPORT_ENUM(env, exports, "KEY_GRAVE_ACCENT", GLFW_KEY_GRAVE_ACCENT);
EXPORT_ENUM(env, exports, "KEY_WORLD_1", GLFW_KEY_WORLD_1);
EXPORT_ENUM(env, exports, "KEY_WORLD_2", GLFW_KEY_WORLD_2);
EXPORT_ENUM(env, exports, "KEY_ESCAPE", GLFW_KEY_ESCAPE);
EXPORT_ENUM(env, exports, "KEY_ENTER", GLFW_KEY_ENTER);
EXPORT_ENUM(env, exports, "KEY_TAB", GLFW_KEY_TAB);
EXPORT_ENUM(env, exports, "KEY_BACKSPACE", GLFW_KEY_BACKSPACE);
EXPORT_ENUM(env, exports, "KEY_INSERT", GLFW_KEY_INSERT);
EXPORT_ENUM(env, exports, "KEY_DELETE", GLFW_KEY_DELETE);
EXPORT_ENUM(env, exports, "KEY_RIGHT", GLFW_KEY_RIGHT);
EXPORT_ENUM(env, exports, "KEY_LEFT", GLFW_KEY_LEFT);
EXPORT_ENUM(env, exports, "KEY_DOWN", GLFW_KEY_DOWN);
EXPORT_ENUM(env, exports, "KEY_UP", GLFW_KEY_UP);
EXPORT_ENUM(env, exports, "KEY_PAGE_UP", GLFW_KEY_PAGE_UP);
EXPORT_ENUM(env, exports, "KEY_PAGE_DOWN", GLFW_KEY_PAGE_DOWN);
EXPORT_ENUM(env, exports, "KEY_HOME", GLFW_KEY_HOME);
EXPORT_ENUM(env, exports, "KEY_END", GLFW_KEY_END);
EXPORT_ENUM(env, exports, "KEY_CAPS_LOCK", GLFW_KEY_CAPS_LOCK);
EXPORT_ENUM(env, exports, "KEY_SCROLL_LOCK", GLFW_KEY_SCROLL_LOCK);
EXPORT_ENUM(env, exports, "KEY_NUM_LOCK", GLFW_KEY_NUM_LOCK);
EXPORT_ENUM(env, exports, "KEY_PRINT_SCREEN", GLFW_KEY_PRINT_SCREEN);
EXPORT_ENUM(env, exports, "KEY_PAUSE", GLFW_KEY_PAUSE);
EXPORT_ENUM(env, exports, "KEY_F1", GLFW_KEY_F1);
EXPORT_ENUM(env, exports, "KEY_F2", GLFW_KEY_F2);
EXPORT_ENUM(env, exports, "KEY_F3", GLFW_KEY_F3);
EXPORT_ENUM(env, exports, "KEY_F4", GLFW_KEY_F4);
EXPORT_ENUM(env, exports, "KEY_F5", GLFW_KEY_F5);
EXPORT_ENUM(env, exports, "KEY_F6", GLFW_KEY_F6);
EXPORT_ENUM(env, exports, "KEY_F7", GLFW_KEY_F7);
EXPORT_ENUM(env, exports, "KEY_F8", GLFW_KEY_F8);
EXPORT_ENUM(env, exports, "KEY_F9", GLFW_KEY_F9);
EXPORT_ENUM(env, exports, "KEY_F10", GLFW_KEY_F10);
EXPORT_ENUM(env, exports, "KEY_F11", GLFW_KEY_F11);
EXPORT_ENUM(env, exports, "KEY_F12", GLFW_KEY_F12);
EXPORT_ENUM(env, exports, "KEY_F13", GLFW_KEY_F13);
EXPORT_ENUM(env, exports, "KEY_F14", GLFW_KEY_F14);
EXPORT_ENUM(env, exports, "KEY_F15", GLFW_KEY_F15);
EXPORT_ENUM(env, exports, "KEY_F16", GLFW_KEY_F16);
EXPORT_ENUM(env, exports, "KEY_F17", GLFW_KEY_F17);
EXPORT_ENUM(env, exports, "KEY_F18", GLFW_KEY_F18);
EXPORT_ENUM(env, exports, "KEY_F19", GLFW_KEY_F19);
EXPORT_ENUM(env, exports, "KEY_F20", GLFW_KEY_F20);
EXPORT_ENUM(env, exports, "KEY_F21", GLFW_KEY_F21);
EXPORT_ENUM(env, exports, "KEY_F22", GLFW_KEY_F22);
EXPORT_ENUM(env, exports, "KEY_F23", GLFW_KEY_F23);
EXPORT_ENUM(env, exports, "KEY_F24", GLFW_KEY_F24);
EXPORT_ENUM(env, exports, "KEY_F25", GLFW_KEY_F25);
EXPORT_ENUM(env, exports, "KEY_KP_0", GLFW_KEY_KP_0);
EXPORT_ENUM(env, exports, "KEY_KP_1", GLFW_KEY_KP_1);
EXPORT_ENUM(env, exports, "KEY_KP_2", GLFW_KEY_KP_2);
EXPORT_ENUM(env, exports, "KEY_KP_3", GLFW_KEY_KP_3);
EXPORT_ENUM(env, exports, "KEY_KP_4", GLFW_KEY_KP_4);
EXPORT_ENUM(env, exports, "KEY_KP_5", GLFW_KEY_KP_5);
EXPORT_ENUM(env, exports, "KEY_KP_6", GLFW_KEY_KP_6);
EXPORT_ENUM(env, exports, "KEY_KP_7", GLFW_KEY_KP_7);
EXPORT_ENUM(env, exports, "KEY_KP_8", GLFW_KEY_KP_8);
EXPORT_ENUM(env, exports, "KEY_KP_9", GLFW_KEY_KP_9);
EXPORT_ENUM(env, exports, "KEY_KP_DECIMAL", GLFW_KEY_KP_DECIMAL);
EXPORT_ENUM(env, exports, "KEY_KP_DIVIDE", GLFW_KEY_KP_DIVIDE);
EXPORT_ENUM(env, exports, "KEY_KP_MULTIPLY", GLFW_KEY_KP_MULTIPLY);
EXPORT_ENUM(env, exports, "KEY_KP_SUBTRACT", GLFW_KEY_KP_SUBTRACT);
EXPORT_ENUM(env, exports, "KEY_KP_ADD", GLFW_KEY_KP_ADD);
EXPORT_ENUM(env, exports, "KEY_KP_ENTER", GLFW_KEY_KP_ENTER);
EXPORT_ENUM(env, exports, "KEY_KP_EQUAL", GLFW_KEY_KP_EQUAL);
EXPORT_ENUM(env, exports, "KEY_LEFT_SHIFT", GLFW_KEY_LEFT_SHIFT);
EXPORT_ENUM(env, exports, "KEY_LEFT_CONTROL", GLFW_KEY_LEFT_CONTROL);
EXPORT_ENUM(env, exports, "KEY_LEFT_ALT", GLFW_KEY_LEFT_ALT);
EXPORT_ENUM(env, exports, "KEY_LEFT_SUPER", GLFW_KEY_LEFT_SUPER);
EXPORT_ENUM(env, exports, "KEY_RIGHT_SHIFT", GLFW_KEY_RIGHT_SHIFT);
EXPORT_ENUM(env, exports, "KEY_RIGHT_CONTROL", GLFW_KEY_RIGHT_CONTROL);
EXPORT_ENUM(env, exports, "KEY_RIGHT_ALT", GLFW_KEY_RIGHT_ALT);
EXPORT_ENUM(env, exports, "KEY_RIGHT_SUPER", GLFW_KEY_RIGHT_SUPER);
EXPORT_ENUM(env, exports, "KEY_MENU", GLFW_KEY_MENU);
EXPORT_ENUM(env, exports, "KEY_LAST", GLFW_KEY_LAST);
EXPORT_ENUM(env, exports, "MOD_SHIFT", GLFW_MOD_SHIFT);
EXPORT_ENUM(env, exports, "MOD_CONTROL", GLFW_MOD_CONTROL);
EXPORT_ENUM(env, exports, "MOD_ALT", GLFW_MOD_ALT);
EXPORT_ENUM(env, exports, "MOD_SUPER", GLFW_MOD_SUPER);
EXPORT_ENUM(env, exports, "MOD_CAPS_LOCK", GLFW_MOD_CAPS_LOCK);
EXPORT_ENUM(env, exports, "MOD_NUM_LOCK", GLFW_MOD_NUM_LOCK);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_1", GLFW_MOUSE_BUTTON_1);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_2", GLFW_MOUSE_BUTTON_2);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_3", GLFW_MOUSE_BUTTON_3);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_4", GLFW_MOUSE_BUTTON_4);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_5", GLFW_MOUSE_BUTTON_5);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_6", GLFW_MOUSE_BUTTON_6);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_7", GLFW_MOUSE_BUTTON_7);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_8", GLFW_MOUSE_BUTTON_8);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_LAST", GLFW_MOUSE_BUTTON_LAST);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_LEFT", GLFW_MOUSE_BUTTON_LEFT);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_RIGHT", GLFW_MOUSE_BUTTON_RIGHT);
EXPORT_ENUM(env, exports, "MOUSE_BUTTON_MIDDLE", GLFW_MOUSE_BUTTON_MIDDLE);
EXPORT_ENUM(env, exports, "JOYSTICK_1", GLFW_JOYSTICK_1);
EXPORT_ENUM(env, exports, "JOYSTICK_2", GLFW_JOYSTICK_2);
EXPORT_ENUM(env, exports, "JOYSTICK_3", GLFW_JOYSTICK_3);
EXPORT_ENUM(env, exports, "JOYSTICK_4", GLFW_JOYSTICK_4);
EXPORT_ENUM(env, exports, "JOYSTICK_5", GLFW_JOYSTICK_5);
EXPORT_ENUM(env, exports, "JOYSTICK_6", GLFW_JOYSTICK_6);
EXPORT_ENUM(env, exports, "JOYSTICK_7", GLFW_JOYSTICK_7);
EXPORT_ENUM(env, exports, "JOYSTICK_8", GLFW_JOYSTICK_8);
EXPORT_ENUM(env, exports, "JOYSTICK_9", GLFW_JOYSTICK_9);
EXPORT_ENUM(env, exports, "JOYSTICK_10", GLFW_JOYSTICK_10);
EXPORT_ENUM(env, exports, "JOYSTICK_11", GLFW_JOYSTICK_11);
EXPORT_ENUM(env, exports, "JOYSTICK_12", GLFW_JOYSTICK_12);
EXPORT_ENUM(env, exports, "JOYSTICK_13", GLFW_JOYSTICK_13);
EXPORT_ENUM(env, exports, "JOYSTICK_14", GLFW_JOYSTICK_14);
EXPORT_ENUM(env, exports, "JOYSTICK_15", GLFW_JOYSTICK_15);
EXPORT_ENUM(env, exports, "JOYSTICK_16", GLFW_JOYSTICK_16);
EXPORT_ENUM(env, exports, "JOYSTICK_LAST", GLFW_JOYSTICK_LAST);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_A", GLFW_GAMEPAD_BUTTON_A);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_B", GLFW_GAMEPAD_BUTTON_B);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_X", GLFW_GAMEPAD_BUTTON_X);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_Y", GLFW_GAMEPAD_BUTTON_Y);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_LEFT_BUMPER", GLFW_GAMEPAD_BUTTON_LEFT_BUMPER);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_RIGHT_BUMPER", GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_BACK", GLFW_GAMEPAD_BUTTON_BACK);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_START", GLFW_GAMEPAD_BUTTON_START);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_GUIDE", GLFW_GAMEPAD_BUTTON_GUIDE);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_LEFT_THUMB", GLFW_GAMEPAD_BUTTON_LEFT_THUMB);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_RIGHT_THUMB", GLFW_GAMEPAD_BUTTON_RIGHT_THUMB);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_UP", GLFW_GAMEPAD_BUTTON_DPAD_UP);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_RIGHT", GLFW_GAMEPAD_BUTTON_DPAD_RIGHT);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_DOWN", GLFW_GAMEPAD_BUTTON_DPAD_DOWN);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_DPAD_LEFT", GLFW_GAMEPAD_BUTTON_DPAD_LEFT);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_LAST", GLFW_GAMEPAD_BUTTON_LAST);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_CROSS", GLFW_GAMEPAD_BUTTON_CROSS);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_CIRCLE", GLFW_GAMEPAD_BUTTON_CIRCLE);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_SQUARE", GLFW_GAMEPAD_BUTTON_SQUARE);
EXPORT_ENUM(env, exports, "GAMEPAD_BUTTON_TRIANGLE", GLFW_GAMEPAD_BUTTON_TRIANGLE);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LEFT_X", GLFW_GAMEPAD_AXIS_LEFT_X);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LEFT_Y", GLFW_GAMEPAD_AXIS_LEFT_Y);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_RIGHT_X", GLFW_GAMEPAD_AXIS_RIGHT_X);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_RIGHT_Y", GLFW_GAMEPAD_AXIS_RIGHT_Y);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LEFT_TRIGGER", GLFW_GAMEPAD_AXIS_LEFT_TRIGGER);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_RIGHT_TRIGGER", GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER);
EXPORT_ENUM(env, exports, "GAMEPAD_AXIS_LAST", GLFW_GAMEPAD_AXIS_LAST);
EXPORT_ENUM(env, exports, "NO_ERROR", GLFW_NO_ERROR);
EXPORT_ENUM(env, exports, "NOT_INITIALIZED", GLFW_NOT_INITIALIZED);
EXPORT_ENUM(env, exports, "NO_CURRENT_CONTEXT", GLFW_NO_CURRENT_CONTEXT);
EXPORT_ENUM(env, exports, "INVALID_ENUM", GLFW_INVALID_ENUM);
EXPORT_ENUM(env, exports, "INVALID_VALUE", GLFW_INVALID_VALUE);
EXPORT_ENUM(env, exports, "OUT_OF_MEMORY", GLFW_OUT_OF_MEMORY);
EXPORT_ENUM(env, exports, "API_UNAVAILABLE", GLFW_API_UNAVAILABLE);
EXPORT_ENUM(env, exports, "VERSION_UNAVAILABLE", GLFW_VERSION_UNAVAILABLE);
EXPORT_ENUM(env, exports, "PLATFORM_ERROR", GLFW_PLATFORM_ERROR);
EXPORT_ENUM(env, exports, "FORMAT_UNAVAILABLE", GLFW_FORMAT_UNAVAILABLE);
EXPORT_ENUM(env, exports, "NO_WINDOW_CONTEXT", GLFW_NO_WINDOW_CONTEXT);
EXPORT_ENUM(env, exports, "FOCUSED", GLFW_FOCUSED);
EXPORT_ENUM(env, exports, "ICONIFIED", GLFW_ICONIFIED);
EXPORT_ENUM(env, exports, "RESIZABLE", GLFW_RESIZABLE);
EXPORT_ENUM(env, exports, "VISIBLE", GLFW_VISIBLE);
EXPORT_ENUM(env, exports, "DECORATED", GLFW_DECORATED);
EXPORT_ENUM(env, exports, "AUTO_ICONIFY", GLFW_AUTO_ICONIFY);
EXPORT_ENUM(env, exports, "FLOATING", GLFW_FLOATING);
EXPORT_ENUM(env, exports, "MAXIMIZED", GLFW_MAXIMIZED);
EXPORT_ENUM(env, exports, "CENTER_CURSOR", GLFW_CENTER_CURSOR);
EXPORT_ENUM(env, exports, "TRANSPARENT_FRAMEBUFFER", GLFW_TRANSPARENT_FRAMEBUFFER);
EXPORT_ENUM(env, exports, "HOVERED", GLFW_HOVERED);
EXPORT_ENUM(env, exports, "FOCUS_ON_SHOW", GLFW_FOCUS_ON_SHOW);
EXPORT_ENUM(env, exports, "RED_BITS", GLFW_RED_BITS);
EXPORT_ENUM(env, exports, "GREEN_BITS", GLFW_GREEN_BITS);
EXPORT_ENUM(env, exports, "BLUE_BITS", GLFW_BLUE_BITS);
EXPORT_ENUM(env, exports, "ALPHA_BITS", GLFW_ALPHA_BITS);
EXPORT_ENUM(env, exports, "DEPTH_BITS", GLFW_DEPTH_BITS);
EXPORT_ENUM(env, exports, "STENCIL_BITS", GLFW_STENCIL_BITS);
EXPORT_ENUM(env, exports, "ACCUM_RED_BITS", GLFW_ACCUM_RED_BITS);
EXPORT_ENUM(env, exports, "ACCUM_GREEN_BITS", GLFW_ACCUM_GREEN_BITS);
EXPORT_ENUM(env, exports, "ACCUM_BLUE_BITS", GLFW_ACCUM_BLUE_BITS);
EXPORT_ENUM(env, exports, "ACCUM_ALPHA_BITS", GLFW_ACCUM_ALPHA_BITS);
EXPORT_ENUM(env, exports, "AUX_BUFFERS", GLFW_AUX_BUFFERS);
EXPORT_ENUM(env, exports, "STEREO", GLFW_STEREO);
EXPORT_ENUM(env, exports, "SAMPLES", GLFW_SAMPLES);
EXPORT_ENUM(env, exports, "SRGB_CAPABLE", GLFW_SRGB_CAPABLE);
EXPORT_ENUM(env, exports, "REFRESH_RATE", GLFW_REFRESH_RATE);
EXPORT_ENUM(env, exports, "DOUBLEBUFFER", GLFW_DOUBLEBUFFER);
EXPORT_ENUM(env, exports, "CLIENT_API", GLFW_CLIENT_API);
EXPORT_ENUM(env, exports, "CONTEXT_VERSION_MAJOR", GLFW_CONTEXT_VERSION_MAJOR);
EXPORT_ENUM(env, exports, "CONTEXT_VERSION_MINOR", GLFW_CONTEXT_VERSION_MINOR);
EXPORT_ENUM(env, exports, "CONTEXT_REVISION", GLFW_CONTEXT_REVISION);
EXPORT_ENUM(env, exports, "CONTEXT_ROBUSTNESS", GLFW_CONTEXT_ROBUSTNESS);
EXPORT_ENUM(env, exports, "OPENGL_FORWARD_COMPAT", GLFW_OPENGL_FORWARD_COMPAT);
EXPORT_ENUM(env, exports, "OPENGL_DEBUG_CONTEXT", GLFW_OPENGL_DEBUG_CONTEXT);
EXPORT_ENUM(env, exports, "OPENGL_PROFILE", GLFW_OPENGL_PROFILE);
EXPORT_ENUM(env, exports, "CONTEXT_RELEASE_BEHAVIOR", GLFW_CONTEXT_RELEASE_BEHAVIOR);
EXPORT_ENUM(env, exports, "CONTEXT_NO_ERROR", GLFW_CONTEXT_NO_ERROR);
EXPORT_ENUM(env, exports, "CONTEXT_CREATION_API", GLFW_CONTEXT_CREATION_API);
EXPORT_ENUM(env, exports, "SCALE_TO_MONITOR", GLFW_SCALE_TO_MONITOR);
EXPORT_ENUM(env, exports, "COCOA_RETINA_FRAMEBUFFER", GLFW_COCOA_RETINA_FRAMEBUFFER);
EXPORT_ENUM(env, exports, "COCOA_FRAME_NAME", GLFW_COCOA_FRAME_NAME);
EXPORT_ENUM(env, exports, "COCOA_GRAPHICS_SWITCHING", GLFW_COCOA_GRAPHICS_SWITCHING);
EXPORT_ENUM(env, exports, "X11_CLASS_NAME", GLFW_X11_CLASS_NAME);
EXPORT_ENUM(env, exports, "X11_INSTANCE_NAME", GLFW_X11_INSTANCE_NAME);
EXPORT_ENUM(env, exports, "NO_API", GLFW_NO_API);
EXPORT_ENUM(env, exports, "OPENGL_API", GLFW_OPENGL_API);
EXPORT_ENUM(env, exports, "OPENGL_ES_API", GLFW_OPENGL_ES_API);
EXPORT_ENUM(env, exports, "NO_ROBUSTNESS", GLFW_NO_ROBUSTNESS);
EXPORT_ENUM(env, exports, "NO_RESET_NOTIFICATION", GLFW_NO_RESET_NOTIFICATION);
EXPORT_ENUM(env, exports, "LOSE_CONTEXT_ON_RESET", GLFW_LOSE_CONTEXT_ON_RESET);
EXPORT_ENUM(env, exports, "OPENGL_ANY_PROFILE", GLFW_OPENGL_ANY_PROFILE);
EXPORT_ENUM(env, exports, "OPENGL_CORE_PROFILE", GLFW_OPENGL_CORE_PROFILE);
EXPORT_ENUM(env, exports, "OPENGL_COMPAT_PROFILE", GLFW_OPENGL_COMPAT_PROFILE);
EXPORT_ENUM(env, exports, "CURSOR", GLFW_CURSOR);
EXPORT_ENUM(env, exports, "STICKY_KEYS", GLFW_STICKY_KEYS);
EXPORT_ENUM(env, exports, "STICKY_MOUSE_BUTTONS", GLFW_STICKY_MOUSE_BUTTONS);
EXPORT_ENUM(env, exports, "LOCK_KEY_MODS", GLFW_LOCK_KEY_MODS);
EXPORT_ENUM(env, exports, "RAW_MOUSE_MOTION", GLFW_RAW_MOUSE_MOTION);
EXPORT_ENUM(env, exports, "CURSOR_NORMAL", GLFW_CURSOR_NORMAL);
EXPORT_ENUM(env, exports, "CURSOR_HIDDEN", GLFW_CURSOR_HIDDEN);
EXPORT_ENUM(env, exports, "CURSOR_DISABLED", GLFW_CURSOR_DISABLED);
EXPORT_ENUM(env, exports, "ANY_RELEASE_BEHAVIOR", GLFW_ANY_RELEASE_BEHAVIOR);
EXPORT_ENUM(env, exports, "RELEASE_BEHAVIOR_FLUSH", GLFW_RELEASE_BEHAVIOR_FLUSH);
EXPORT_ENUM(env, exports, "RELEASE_BEHAVIOR_NONE", GLFW_RELEASE_BEHAVIOR_NONE);
EXPORT_ENUM(env, exports, "NATIVE_CONTEXT_API", GLFW_NATIVE_CONTEXT_API);
EXPORT_ENUM(env, exports, "EGL_CONTEXT_API", GLFW_EGL_CONTEXT_API);
EXPORT_ENUM(env, exports, "OSMESA_CONTEXT_API", GLFW_OSMESA_CONTEXT_API);
EXPORT_ENUM(env, exports, "ARROW_CURSOR", GLFW_ARROW_CURSOR);
EXPORT_ENUM(env, exports, "IBEAM_CURSOR", GLFW_IBEAM_CURSOR);
EXPORT_ENUM(env, exports, "CROSSHAIR_CURSOR", GLFW_CROSSHAIR_CURSOR);
EXPORT_ENUM(env, exports, "HAND_CURSOR", GLFW_HAND_CURSOR);
EXPORT_ENUM(env, exports, "HRESIZE_CURSOR", GLFW_HRESIZE_CURSOR);
EXPORT_ENUM(env, exports, "VRESIZE_CURSOR", GLFW_VRESIZE_CURSOR);
EXPORT_ENUM(env, exports, "CONNECTED", GLFW_CONNECTED);
EXPORT_ENUM(env, exports, "DISCONNECTED", GLFW_DISCONNECTED);
EXPORT_ENUM(env, exports, "JOYSTICK_HAT_BUTTONS", GLFW_JOYSTICK_HAT_BUTTONS);
EXPORT_ENUM(env, exports, "COCOA_CHDIR_RESOURCES", GLFW_COCOA_CHDIR_RESOURCES);
EXPORT_ENUM(env, exports, "COCOA_MENUBAR", GLFW_COCOA_MENUBAR);
EXPORT_ENUM(env, exports, "DONT_CARE", GLFW_DONT_CARE);
return exports;
}
NODE_API_MODULE(nv, initModule);
| 55.620209 | 100 | 0.768809 | [
"object",
"vector"
] |
598dbce7e72585ec1a646f18b4e1f8a6ff82407c | 2,888 | hpp | C++ | src/libraries/turbulenceModels/incompressible/LES/SpalartAllmarasDDES/SpalartAllmarasDDES.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/turbulenceModels/incompressible/LES/SpalartAllmarasDDES/SpalartAllmarasDDES.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/turbulenceModels/incompressible/LES/SpalartAllmarasDDES/SpalartAllmarasDDES.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2012 OpenFOAM Foundation
Copyright (C) 2014 Applied CCM
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Description
SpalartAllmaras DDES LES turbulence model for incompressible flows
References:
1) P.R. Spalart, S. Deck, S., M.L.Shur, K.D. Squires, M.Kh Strelets, and
A. Travin. `A new version of detached-eddy simulation, resistant to
ambiguous grid densities'. Theor. Comp. Fluid Dyn., 20:181-195, 2006.
2) Spalart, P. R. and Allmaras, S. R., "A One-Equation Turbulence Model for
Aerodynamic Flows," Recherche Aerospatiale, No. 1, 1994, pp. 5-21.
Author: A. Jemcov
\*---------------------------------------------------------------------------*/
#ifndef SpalartAllmarasDDES_HPP
#define SpalartAllmarasDDES_HPP
#include "SpalartAllmarasDES.hpp"
namespace CML
{
namespace incompressible
{
namespace LESModels
{
class SpalartAllmarasDDES
:
public SpalartAllmarasDES
{
// Private Member Functions
tmp<volScalarField> fd(const volScalarField& S) const;
tmp<volScalarField> rd
(
const volScalarField& visc,
const volScalarField& S
) const;
// Disallow default bitwise copy construct and assignment
SpalartAllmarasDDES(const SpalartAllmarasDDES&);
SpalartAllmarasDDES& operator=(const SpalartAllmarasDDES&);
protected:
// Protected Member Functions
//- Length scale
virtual tmp<volScalarField> dTilda(const volScalarField& S) const;
virtual tmp<volScalarField> S(const volTensorField& gradU) const;
public:
//- Runtime type information
TypeName("SpalartAllmarasDDES");
// Constructors
//- Construct from components
SpalartAllmarasDDES
(
const volVectorField& U,
const surfaceScalarField& phi,
transportModel& transport,
const word& turbulenceModelName = turbulenceModel::typeName,
const word& modelName = typeName
);
//- Destructor
virtual ~SpalartAllmarasDDES()
{}
};
}
}
}
#endif
| 26.740741 | 80 | 0.628463 | [
"model"
] |
5998440bd15f5a24d7be8dec82e0da66d25df85f | 1,118 | hpp | C++ | include/Pulsejet/EncodeHelpers.hpp | logicomacorp/pulsejet | ec73d19ccb71ff05b2122e258fe4b7b16e55fb53 | [
"MIT"
] | 30 | 2021-06-07T20:25:48.000Z | 2022-03-30T00:52:38.000Z | include/Pulsejet/EncodeHelpers.hpp | going-digital/pulsejet | 8452a0311645867d64c038cef7fdf751b26717ee | [
"MIT"
] | null | null | null | include/Pulsejet/EncodeHelpers.hpp | going-digital/pulsejet | 8452a0311645867d64c038cef7fdf751b26717ee | [
"MIT"
] | 1 | 2021-09-21T11:17:45.000Z | 2021-09-21T11:17:45.000Z | #pragma once
#include "Common.hpp"
#include <cstdint>
#include <map>
#include <vector>
namespace Pulsejet::Internal
{
using namespace std;
static const uint8_t BandBinQuantizeScaleBases[NumBands] =
{
200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129,
};
template<typename Key>
double Order0BitsEstimate(const map<Key, uint32_t>& freqs)
{
uint32_t numSymbols = 0;
for (const auto& kvp : freqs)
{
const auto freq = kvp.second;
numSymbols += freq;
}
double bitsEstimate = 0.0;
for (const auto& kvp : freqs)
{
const auto freq = static_cast<double>(kvp.second);
const auto prob = freq / static_cast<double>(numSymbols);
bitsEstimate += -log2(prob) * freq;
}
return bitsEstimate;
}
static void WriteCString(vector<uint8_t>& v, const char *s)
{
while (true)
{
const char c = *s++;
if (!c)
break;
v.push_back(static_cast<uint8_t>(c));
}
}
static void WriteU16LE(vector<uint8_t>& v, uint16_t value)
{
v.push_back(static_cast<uint8_t>(value >> 0));
v.push_back(static_cast<uint8_t>(value >> 8));
}
}
| 20.703704 | 101 | 0.662791 | [
"vector"
] |
599bfa3fa511806ed309a42668d2ad35d436bb02 | 1,137 | cpp | C++ | DSA/Tarjan_Algorithm.cpp | Sneh16Shah/Hacktoberfest2021 | bd27e8d2e3880794cb611748812abe4c3e527a02 | [
"MIT"
] | null | null | null | DSA/Tarjan_Algorithm.cpp | Sneh16Shah/Hacktoberfest2021 | bd27e8d2e3880794cb611748812abe4c3e527a02 | [
"MIT"
] | null | null | null | DSA/Tarjan_Algorithm.cpp | Sneh16Shah/Hacktoberfest2021 | bd27e8d2e3880794cb611748812abe4c3e527a02 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define fo(i,n) for (int i = 1; i <= n; i++)
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define lli long long int
#define endl '\n'
using namespace std;
vi g[1001];
bool vis[1001] , onStack[1001];
int in[1001] , low[1001];
stack<int> st;
int timer = 1 , SCC = 0;
void dfs(int node)
{
vis[node] = 1;
in[node] = low[node] = timer++;
onStack[node] = true;
st.push(node);
for(int u : g[node])
{
if((vis[u] == true) && (onStack[u] == true))
{
low[node] = min(low[node] , in[u]);
}
else
if(vis[u] == false)
{
dfs(u);
if(onStack[u] == true)
low[node] = min(low[node] , low[u]);
}
}
if(in[node] == low[node])
{
SCC++;
cout<<"SCC #"<<SCC<<endl;
int u;
while(1)
{
u = st.top();
st.pop() , onStack[u] = false;
cout<<u<<" ";
if(u == node) break;
}
cout<<endl;
}
}
int main()
{
int n , m, a , b;
cin>>n>>m;
fo(i , m) cin>>a>>b , g[a].pb(b);
fo(i , n) vis[i] = onStack[i] = false;
fo(i , n)
if(vis[i] == false) dfs(i);
}
| 14.766234 | 46 | 0.532102 | [
"vector"
] |
599d9a9e3d762228ace191a8509fc846c97135a1 | 1,414 | cpp | C++ | src/chapter_01_math/problem_006_abundant_numbers.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_01_math/problem_006_abundant_numbers.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_01_math/problem_006_abundant_numbers.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | #include "chapter_01_math/problem_006_abundant_numbers.h"
#include "chapter_01_math/math.h" // divisors
#include "rtc/console.h" // read_positive_number
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <iostream> // cin, cout
#include <istream>
#include <numeric> // accumulate
#include <ostream>
#include <vector>
std::vector<AbundantNumberResult> abundant_numbers_up_to(size_t limit) {
std::vector<AbundantNumberResult> ret{};
for (size_t i{ 1 }; i <= limit; ++i) {
auto d{ tmcppc::math::divisors(i) };
auto sum_of_divisors{ std::accumulate(d.cbegin(), d.cend(), static_cast<size_t>(0)) };
if (sum_of_divisors > i) {
ret.emplace_back(i, sum_of_divisors - i, std::move(d));
}
}
return ret;
}
void problem_6_main(std::istream& is, std::ostream& os) {
auto limit{ rtc::console::read_positive_number(is, os, "Please enter a number (>= 1): ", 1) };
fmt::print(os, "Abundant numbers up to {} [list of divisors] (and their abundance):\n", limit);
for (auto&& result : abundant_numbers_up_to(limit)) {
fmt::print(os, "\t{} {} ({})\n", result.number, result.divisors, result.abundance);
}
fmt::print(os, "\n");
}
// Abundant numbers
//
// Write a program that prints all abundant numbers and their abundance, up to a number entered by the user
void problem_6_main() {
problem_6_main(std::cin, std::cout);
}
| 31.422222 | 107 | 0.658416 | [
"vector"
] |
59b057d82e5e48dc88192f48a1bd8152caefe3f9 | 1,026 | cpp | C++ | c02e04.cpp | vitorgt/SCC0210 | f7689be1b72cbf3066ca051faef995f22f446d90 | [
"MIT"
] | null | null | null | c02e04.cpp | vitorgt/SCC0210 | f7689be1b72cbf3066ca051faef995f22f446d90 | [
"MIT"
] | null | null | null | c02e04.cpp | vitorgt/SCC0210 | f7689be1b72cbf3066ca051faef995f22f446d90 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
struct node{
int id, size;
vector<node *> content;
bool hasGift(){
return content.empty();
}
bool operator<(const node &v) const{
return size < v.size;
}
};
int main(){
ios::sync_with_stdio(false);
int n = 0, m = 0, k = 0, buffer = 0, sum = 0;
cin >> n >> m >> k;
vector<node> adr;
priority_queue<node> open;
for(int i = 0; i < n; i++){
cin >> buffer;
node in;
in.id = i;
in.size = buffer;
adr.push_back(in);
}
for(int i = 0; i < n; i++){
cin >> buffer;
if(buffer != 0){
for(int j = buffer; j > 0; j--){
cin >> buffer;
adr[i].content.push_back(&adr[buffer-1]);
}
}
}
for(int i = 0; i < m; i++){
cin >> buffer;
open.push(adr[buffer-1]);
}
while(!open.empty() && k--){
node pack = open.top();
open.pop();
if(pack.hasGift()){
sum++;
}
else{
for(auto i : pack.content){
open.push(*i);
}
}
}
cout << sum << endl;
return 0;
}
| 16.285714 | 46 | 0.557505 | [
"vector"
] |
59b071bc3414ab1823c26faa9cff6ed5715915c6 | 1,067 | cpp | C++ | LeetCode/Matrix/59. Spiral Matrix II.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | 5 | 2021-02-14T17:48:21.000Z | 2022-01-24T14:29:44.000Z | LeetCode/Matrix/59. Spiral Matrix II.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | LeetCode/Matrix/59. Spiral Matrix II.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int start_row = 0;
int start_col = 0;
int end_row = n-1;
int end_col = n-1;
vector<vector<int>> res(n, vector<int> (n, 0));
int val = 1;
while(start_row<=end_row and start_col<=end_col){
for(int i=start_col;i<=end_col;i++){
res[start_row][i] = val++;
}
for(int i=start_row+1;i<=end_row;i++){
res[i][end_col] = val++;
}
if(start_row<end_row and start_col<end_col){
for(int i=end_col-1;i>start_col;i--){
res[end_row][i] = val++;
}
for(int i = end_row;i>start_row;i--){
res[i][start_col] = val++;
}
}
start_row++;
end_row--;
start_col++;
end_col--;
}
return res;
}
};
| 25.404762 | 57 | 0.39269 | [
"vector"
] |
59bbd155e4eb039d96f6aa4cff0b1748c2d59635 | 11,131 | cc | C++ | modules/compiled/build_condensates_kernel.cc | jkiesele/HGCalML-1 | 23e98b207589b7659ee2bedf1dbd496e8500247c | [
"BSD-3-Clause"
] | null | null | null | modules/compiled/build_condensates_kernel.cc | jkiesele/HGCalML-1 | 23e98b207589b7659ee2bedf1dbd496e8500247c | [
"BSD-3-Clause"
] | null | null | null | modules/compiled/build_condensates_kernel.cc | jkiesele/HGCalML-1 | 23e98b207589b7659ee2bedf1dbd496e8500247c | [
"BSD-3-Clause"
] | null | null | null |
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#endif // GOOGLE_CUDA
#include "tensorflow/core/framework/op_kernel.h"
#include "build_condensates_kernel.h"
#include "helpers.h"
#include <string> //size_t, just for helper function
#include <cmath>
#include <iostream> //remove later DEBUG FIXME
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
namespace functor {
//helpers here
static void set_defaults(
int *asso_idx,
int * is_cpoint,
const float * d_betas,
float * temp_betas,
const int start_vertex,
const int end_vertex,
const int n_vert){
for(size_t i_v=start_vertex;i_v<end_vertex;i_v++){
asso_idx[i_v] = -start_vertex-1;
temp_betas[i_v] = d_betas[i_v];
is_cpoint[i_v] = 0;//not needed on GPU?
}
}
static void copy_to_sum_and_default(
const float * ref,
float * target,
float * target_to_zero,
const int n_vert,
const int n_f
){
for(int i_v=0;i_v<n_vert;i_v++){
for(int i_f=0;i_f<n_f;i_f++){
target[I2D(i_v,i_f,n_f)] = ref[I2D(i_v,i_f,n_f)];
target_to_zero[I2D(i_v,i_f,n_f)]=0;
}
}
}
static void get_max_beta(
const float* temp_betas,
int *asso_idx,
int * is_cpoint,
int * maxidx,
const int n_vert,
const int start_vertex,
const int end_vertex,
const float min_beta){
//this needs to be some smart algo here
//it will be called N_condensate times at least
int ref=-1;
float max = min_beta;
for(int i_v=start_vertex;i_v<end_vertex;i_v++){
float biv = temp_betas[i_v];
if(biv > max && asso_idx[i_v] < 0){
max=biv;
ref=i_v;
}
}
//if none can be found set ref to -1
*maxidx = ref;
if(ref>=0){
is_cpoint[ref]=1;
asso_idx[ref]=ref;
}
}
static float distancesq(const int v_a,
const int v_b,
const float *d_ccoords,
const int n_ccoords){
float distsq=0;
for(size_t i=0;i<n_ccoords;i++){
float xa = d_ccoords[I2D(v_a,i,n_ccoords)];
float xb = d_ccoords[I2D(v_b,i,n_ccoords)];
distsq += (xa-xb)*(xa-xb);
}
return distsq;
}
static void check_and_collect(
const int ref_vertex,
const float ref_beta,
const float *d_ccoords,
const float *d_betas,
const float *d_dist,
const float *d_tosum,
int *asso_idx,
float * temp_betas,
float * temp_tosum,
float * summed,
const int n_vert,
const int n_ccoords,
const int n_sumf,
const int start_vertex,
const int end_vertex,
const float radiussq,
const float min_beta,
const bool soft,
const bool sum){
float modradiussq = d_dist[ref_vertex];
modradiussq *= modradiussq;// squared, as distsq and radius
modradiussq *= radiussq;
for(size_t i_v=start_vertex;i_v<end_vertex;i_v++){
if(asso_idx[i_v] < 0 || i_v == ref_vertex){
float distsq = distancesq(ref_vertex,i_v,d_ccoords,n_ccoords);
float prob = std::exp(-distsq/(2.*modradiussq));//1 sigma at radius
if(soft){
float subtract = prob * ref_beta;
float prebeta = temp_betas[i_v];
float newbeta = prebeta-subtract;
temp_betas[i_v] = newbeta;
}
if(distsq <= modradiussq){
asso_idx[i_v] = ref_vertex;
}
if(sum){
for(int i_f=0;i_f<n_sumf;i_f++){
float tmpfeat = temp_tosum[I2D(i_v,i_f,n_sumf)];
float origfeat = d_tosum[I2D(i_v,i_f,n_sumf)];
if(tmpfeat > 0){
float contrib = prob*origfeat;
if(contrib>tmpfeat)//larger than what's left
contrib = tmpfeat;
summed[I2D(ref_vertex,i_f,n_sumf)] += contrib;
temp_tosum[I2D(i_v,i_f,n_sumf)] -= contrib;
}
}
}//sum
}//asso
}//for
}
// CPU specialization
template<typename dummy>
struct BuildCondensatesOpFunctor<CPUDevice, dummy> {
void operator()(const CPUDevice &d,
const float *d_ccoords,
const float *d_betas,
const float *d_dist,
const float *d_tosum,
const int *row_splits,
int *asso_idx,
int *is_cpoint,
float * temp_betas,
int *n_condensates,
float *temp_tosum,
float *summed,
const int n_vert,
const int n_ccoords,
const int n_sumf,
const int n_rs,
const float radius,
const float min_beta,
const bool soft,
const bool sum) {
if(sum){
copy_to_sum_and_default(d_tosum,temp_tosum,summed,n_vert,n_sumf);
}
for(size_t j_rs=0;j_rs<n_rs-1;j_rs++){
const int start_vertex = row_splits[j_rs];
const int end_vertex = row_splits[j_rs+1];
set_defaults(asso_idx,is_cpoint,d_betas,temp_betas,start_vertex,end_vertex,n_vert);
int ref;
get_max_beta(temp_betas,asso_idx,is_cpoint,&ref,n_vert,start_vertex,end_vertex,min_beta);
//copy ref back
float ref_beta = d_betas[ref];
int ncond=0;
//copy ref and refBeta from GPU to CPU
while(ref>=0){
// if(asso_idx[ref] >=0) continue; //
// if(temp_betas[ref] < min_beta)continue;
//probably better to copy here instead of accessing n_vert times in GPU mem
ncond++;
check_and_collect(
ref,
ref_beta,
d_ccoords,
d_betas,
d_dist,
d_tosum,
asso_idx,
temp_betas,
temp_tosum,
summed,
n_vert,
n_ccoords,
n_sumf,
start_vertex,
end_vertex,
radius,
min_beta,
soft,
sum);
get_max_beta(temp_betas,asso_idx,is_cpoint,&ref,n_vert,start_vertex,end_vertex,min_beta);
//copy ref and refBeta from GPU to CPU
ref_beta = d_betas[ref];
}
n_condensates[j_rs] = ncond;
}
}
};
template<typename Device>
class BuildCondensatesOp : public OpKernel {
public:
explicit BuildCondensatesOp(OpKernelConstruction *context) : OpKernel(context) {
OP_REQUIRES_OK(context,
context->GetAttr("min_beta", &min_beta_));
OP_REQUIRES_OK(context,
context->GetAttr("radius", &radiussq_));
radiussq_*=radiussq_;
OP_REQUIRES_OK(context,
context->GetAttr("soft", &soft_));
OP_REQUIRES_OK(context,
context->GetAttr("sum", &sum_));
}
void Compute(OpKernelContext *context) override {
/*
*
* .Attr("radius: float")
REGISTER_OP("BuildCondensates")
.Attr("radius: float")
.Attr("min_beta: float")
.Attr("soft: bool")
.Input("ccoords: float32")
.Input("betas: float32")
.Input("row_splits: int32")
.Output("asso_idx: int32")
.Output("is_cpoint: int32");
*/
const Tensor &t_ccoords = context->input(0);
const Tensor &t_betas = context->input(1);
const Tensor &t_dist = context->input(2);
const Tensor &t_tosum = context->input(3);
const Tensor &t_row_splits = context->input(4);
const int n_vert = t_ccoords.dim_size(0);
const int n_ccoords = t_ccoords.dim_size(1);
const int n_rs = t_row_splits.dim_size(0);
int n_sumf = t_tosum.dim_size(1);
if(!sum_)
n_sumf=0;
const int n_f_vert = t_tosum.dim_size(0);
if(sum_){
OP_REQUIRES(context, n_f_vert == n_vert,
errors::InvalidArgument("BuildCondensatesOp expects first dimensions of tosum to match number of vertices if sum is activated."));
}
TensorShape outputShape_idx;
outputShape_idx.AddDim(n_vert);
Tensor *t_asso_idx = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, outputShape_idx, &t_asso_idx));
Tensor *t_is_cpoint = NULL;
OP_REQUIRES_OK(context, context->allocate_output(1, outputShape_idx, &t_is_cpoint));
TensorShape rsmone;
rsmone.AddDim(n_rs-1);
Tensor *t_n_condensates = NULL;
OP_REQUIRES_OK(context, context->allocate_output(2, rsmone, &t_n_condensates));
Tensor *t_summed = NULL;
OP_REQUIRES_OK(context, context->allocate_output(3, t_tosum.shape(), &t_summed));
Tensor t_temp_betas;
OP_REQUIRES_OK(context, context->allocate_temp( DT_FLOAT ,outputShape_idx,&t_temp_betas));
Tensor t_temp_to_be_summed;
OP_REQUIRES_OK(context, context->allocate_temp( DT_FLOAT ,t_tosum.shape(),&t_temp_to_be_summed));
BuildCondensatesOpFunctor<Device, int>()
(
context->eigen_device<Device>(), //
// /
t_ccoords.flat<float>().data(), // const float *d_ccoords,
t_betas.flat<float>().data(), // const float *d_betas,
t_dist.flat<float>().data(),
t_tosum.flat<float>().data(),
t_row_splits.flat<int>().data(), // const int *row_splits,
t_asso_idx->flat<int>().data(), // int *asso_idx,
t_is_cpoint->flat<int>().data(),// int *is_cpoint,
t_temp_betas.flat<float>().data(),
t_n_condensates->flat<int>().data(),
t_temp_to_be_summed.flat<float>().data(),
t_summed->flat<float>().data(),
n_vert,
n_ccoords,
n_sumf,
n_rs,
radiussq_,
min_beta_ ,
soft_,
sum_
);
}
private:
float min_beta_;
float radiussq_;
bool soft_,sum_;
};
REGISTER_KERNEL_BUILDER(Name("BuildCondensates").Device(DEVICE_CPU), BuildCondensatesOp<CPUDevice>);
#ifdef GOOGLE_CUDA
extern template struct BuildCondensatesOpFunctor<GPUDevice, int>;
REGISTER_KERNEL_BUILDER(Name("BuildCondensates").Device(DEVICE_GPU), BuildCondensatesOp<GPUDevice>);
#endif // GOOGLE_CUDA
}//functor
}//tensorflow
| 28.836788 | 150 | 0.540742 | [
"shape"
] |
59c174e7b18d87831d17942a86da173d0468071e | 14,362 | cpp | C++ | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/util.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/util.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | s2e/source/s2e/libs2eplugins/src/s2e/Plugins/Profile/util.cpp | Albocoder/KOOBE | dd8acade05b0185771e1ea9950de03ab5445a981 | [
"MIT"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | #include <s2e/S2E.h>
#include <s2e/cpu.h>
#include "util.h"
using namespace klee;
namespace s2e {
namespace plugins {
Solver *g_Solver = NULL;
// Index must be 32-Width long
ref<Expr> readArray(UpdateListPtr &array, ref<Expr> index, unsigned bytes) {
ref<Expr> ret;
assert(bytes > 0);
// assumes little-endian
if (ConstantExpr *ci = dyn_cast<ConstantExpr>(index)) {
uint64_t value = ci->getZExtValue();
ret = ReadExpr::create(array, E_CONST(value, Expr::Int32));
for (unsigned i = 1; i < bytes; i++) {
ret = ConcatExpr::create(
ReadExpr::create(array, E_CONST(value + i, Expr::Int32)), ret);
}
} else {
index = alignExpr(index, Expr::Int32);
ret = ReadExpr::create(array, index);
for (unsigned i = 1; i < bytes; i++) {
ret = ConcatExpr::create(
ReadExpr::create(
array,
AddExpr::create(index, E_CONST(i, index->getWidth()))),
ret);
}
}
return ret;
}
// data may have length larger than 64 bits
bool updateArray(UpdateListPtr &array, ref<Expr> index, ref<Expr> data) {
unsigned bytes = data->getWidth() / CHAR_BIT;
std::vector<ref<Expr>> payload;
if (bytes == 1) {
payload.push_back(data);
} else {
for (unsigned i = 0; i < bytes; i++) {
ref<Expr> charExpr = E_EXTR(data, i * CHAR_BIT, Expr::Int8);
payload.push_back(charExpr);
}
}
// Update array one byte at a time
index = alignExpr(index, Expr::Int32);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(index)) {
uint64_t value = CE->getZExtValue();
for (unsigned i = 0; i < bytes; i++) {
ref<Expr> addr = E_CONST(value + i, Expr::Int32);
array->extend(addr, payload[i]);
}
} else {
for (unsigned i = 0; i < bytes; i++) {
ref<Expr> addr =
AddExpr::create(index, E_CONST(i, index->getWidth()));
array->extend(addr, payload[i]);
}
}
return true;
}
//
// Expression Manipluation
//
std::string getName(std::string symbol_name, std::string prefix) {
size_t start = symbol_name.find(prefix);
if (start == std::string::npos) {
return "";
}
size_t end = symbol_name.rfind('_');
std::string name = symbol_name.substr(start, end - start);
return name;
}
std::string getVariableName(std::string symbol_name) {
std::string symbol = getName(symbol_name, "local_");
if (symbol.size() > 0)
return symbol;
symbol = getName(symbol_name, "ptr_");
return symbol;
}
std::string getOriginName(std::string symbol_name) {
size_t start = symbol_name.find('_');
if (start == std::string::npos) {
return symbol_name;
}
size_t end = symbol_name.rfind('_');
std::string name = symbol_name.substr(start + 1, end - start - 1);
return name;
}
uint64_t getValueFromName(std::string symbol_name, std::string prefix) {
std::string symbol = getName(symbol_name, prefix);
if (symbol.size() == 0)
return 0;
std::string addr =
symbol.substr(prefix.size() + 2); // 2 more characters for "0x"
uint64_t value;
sscanf(addr.c_str(), "%lx", &value);
return value;
}
void collectRead(ref<Expr> expr, std::set<ReadExpr *> &collection,
unsigned depth) {
ref<Expr> ee;
// const Array *arry;
// avoid infinity recursive
static std::set<unsigned> visited;
if (depth == 0) {
visited.clear();
}
unsigned hash = expr->hash();
if (visited.find(hash) != visited.end()) {
return;
}
visited.insert(hash);
switch (expr->getKind()) {
case Expr::Extract:
collectRead(dyn_cast<ExtractExpr>(expr)->getExpr(), collection,
depth + 1);
break;
case Expr::Constant:
break;
case Expr::Read:
collection.insert(dyn_cast<ReadExpr>(expr));
break;
default:
for (unsigned i = 0; i < expr->getNumKids(); i++) {
collectRead(expr->getKid(i), collection, depth + 1);
}
break;
}
}
bool findSymBase(ref<Expr> expr, ref<ReadExpr> &ret, std::string prefix) {
std::set<ReadExpr *> collection;
collectRead(expr, collection);
foreach2(it, collection.begin(), collection.end()) {
std::string name = (*it)->getUpdates()->getRoot()->getName();
size_t pos = name.find(prefix);
if (pos == std::string::npos) {
continue;
}
ret = *it;
return true;
}
return false;
}
bool compactprint(ref<Expr> &expr) {
if (expr->getKind() == Expr::Eq) {
ref<Expr> expr1 = expr->getKid(0);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(expr1)) {
if (CE->getZExtValue() == 0) {
ref<Expr> expr2 = expr->getKid(1);
if (expr2->getKind() == Expr::And) {
return true;
}
}
}
}
return false;
}
void selectSymbols(S2EExecutionState *state,
std::map<std::string, const ArrayPtr> &selected) {
std::map<std::string, std::pair<std::string, const ArrayPtr>> symbol_names;
for (unsigned i = 0; i != state->symbolics.size(); i++) {
std::string name = state->symbolics[i]->getName();
std::string variable = state->symbolics[i]->getRawName();
symbol_names.insert(
{variable,
{name, state->symbolics[i]}}); // always take the latest symbol
}
foreach2(it, symbol_names.begin(), symbol_names.end()) {
selected.insert(it->second);
}
}
uint64_t getValue(Solver *solver, ConstraintManager &manager,
Assignment *assignment, ref<Expr> &expr) {
uint64_t ret;
if (assignment != NULL) {
ref<Expr> result = assignment->evaluate(expr);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(result)) {
ret = CE->getZExtValue();
} else {
assert(false && "Concolic evaluation failed");
}
} else {
ref<ConstantExpr> result;
if (solver->getValue(Query(manager, expr), result)) {
ret = result->getZExtValue();
} else {
assert(false && "Symbolic evaluation failed");
}
}
return ret;
}
static ref<Expr> rebuildRead(ref<ReadExpr> expr) {
std::string name = expr->getUpdates()->getRoot()->getRawName();
size_t start = name.find("alc_");
if (start == std::string::npos) {
return expr;
}
std::string addr = name.substr(6); // 2 more characters for "0x"
uint64_t value;
sscanf(addr.c_str(), "%lx", &value);
ref<Expr> index = expr->getIndex();
if (ConstantExpr *ce = dyn_cast<ConstantExpr>(index)) {
unsigned c_index = ce->getZExtValue();
value = value >> (c_index * 8);
return E_CONST(value & 0xff, Expr::Int8);
}
return expr;
}
ref<Expr> rebuildExpr(ref<Expr> expr, unsigned depth) {
static ExprHashMap<ref<Expr>> visited;
if (depth == 0) visited.clear();
if (isa<ConstantExpr>(expr))
return expr;
auto it = visited.find(expr);
if (it != visited.end()) {
return it->second;
}
ref<Expr> kids[4];
ref<Expr> res;
unsigned i;
switch (expr->getKind()) {
case Expr::Read:
res = rebuildRead(dyn_cast<ReadExpr>(expr));
break;
default:
for (i = 0; i < expr->getNumKids(); i++) {
kids[i] = rebuildExpr(expr->getKid(i), depth+1);
}
res = expr->rebuild(kids);
break;
}
// g_s2e->getDebugStream() << "Prev: " << expr << "\n";
// g_s2e->getDebugStream() << "New: " << res << "\n";
visited.insert(std::make_pair(expr, res));
return res;
}
bool findMin(S2EExecutionState *state, ConstraintManager manager,
ref<Expr> expr, ref<ConstantExpr> &ret, Assignment *assignment,
uint64_t minimum, bool isZero) {
Expr::Width width = expr->getWidth();
Solver *solver = getSolver(state);
uint64_t min;
if (width == 1) {
Solver::Validity result;
if (!solver->evaluate(Query(manager, expr), result))
assert(0 && "computeValidity failed");
switch (result) {
case Solver::True:
min = 1;
break;
case Solver::False:
min = 0;
break;
default:
min = 0;
break;
}
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(expr)) {
min = CE->getZExtValue();
} else {
// fast path
if (isZero) {
g_s2e->getDebugStream() << "Fast path for findMin\n";
bool res;
auto query = Query(manager, ConstantExpr::create(0, Expr::Bool));
if (solver == NULL) {
g_s2e->getDebugStream() << "NULL solver\n";
}
bool success = solver->mayBeTrue(
query.withExpr(E_EQ(expr, E_CONST(0, width))), res);
assert(success && "Unhandled solver failure");
ret = res ? E_CONST(0, width) : E_CONST(1, width);
return true;
}
// binary search for # of useful bits
uint64_t lo = 0, hi, mid;
hi = getValue(solver, manager, assignment, expr);
while (lo < hi) {
mid = lo + (hi - lo) / 2;
bool res = false;
bool success;
if (mid == 0) {
success = solver->mayBeTrue(
Query(manager, E_EQ(expr, E_CONST(0, width))), res);
} else {
success = solver->mayBeTrue(
Query(manager, E_LE(expr, E_CONST(mid, width))), res);
}
assert(success && "Unhandled solver failure");
(void)success;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
if (minimum != 0 && lo > minimum) {
break;
}
}
min = lo;
}
ret = E_CONST(min, width);
return true;
}
std::pair<uint64_t, uint64_t> findMinMax(S2EExecutionState *state,
ConstraintManager &manager,
ref<Expr> &expr,
Assignment *assignment,
uint64_t minimum, uint64_t maximum) {
uint64_t min, max;
Expr::Width width = expr->getWidth();
Solver *solver = getSolver(state);
if (width == 1) {
Solver::Validity result;
if (!solver->evaluate(Query(manager, expr), result))
assert(0 && "computeValidity failed");
switch (result) {
case Solver::True:
min = max = 1;
break;
case Solver::False:
min = max = 0;
break;
default:
min = 0;
max = 1;
break;
}
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(expr)) {
min = max = CE->getZExtValue();
} else {
uint64_t lo, hi, mid;
uint64_t concrete = getValue(solver, manager, assignment, expr);
// binary search for min
lo = minimum == 0 ? 0 : minimum;
hi = (maximum != 0 && maximum < concrete) ? maximum : concrete;
while (lo < hi) {
mid = lo + (hi - lo) / 2;
bool res, success;
success = solver->mayBeTrue(
Query(manager, E_LE(expr, E_CONST(mid, width))), res);
assert(success && "Unhandled solver failture");
(void)success;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
min = lo;
// binary search for max
lo = (minimum != 0 && minimum > concrete) ? minimum : concrete;
hi = (maximum != 0 && maximum < bits64::maxValueOfNBits(width))
? maximum
: bits64::maxValueOfNBits(width);
while (lo < hi) {
mid = lo + (hi - lo) / 2;
bool res, success;
success = solver->mustBeTrue(
Query(manager, E_LE(expr, E_CONST(mid, width))), res);
assert(success && "Unhandled solver failure");
(void)success;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
max = lo;
}
return std::make_pair(min, max);
}
void dumpMemory(S2EExecutionState *state, uint64_t address, unsigned size, std::vector<uint8_t> &bytes) {
unsigned index = 0;
std::stringstream ss;
char buf[17] = {0};
const unsigned length = 16;
if (size > 4096) {
size = 4096;
}
while (index < size) {
unsigned i;
ss << hexval(index, 4, false) << " ";
for (i = 0; i < length; i++) {
if (i + index >= size) {
break;
}
ref<Expr> charExpr =
state->mem()->read(address + index + i, Expr::Int8);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(charExpr)) {
buf[i] = 'C';
ss << hexval(CE->getZExtValue(), 2, false) << " ";
bytes.push_back(CE->getZExtValue());
} else {
buf[i] = 'S';
uint8_t val = readExpr<uint8_t>(state, charExpr);
ss << hexval(val, 2, false) << " ";
bytes.push_back(val);
}
}
for (; i < length; i++) {
buf[i] = '.';
ss << " ";
}
ss << std::string(buf) << "\n";
index += length;
}
g_s2e->getDebugStream() << ss.str();
}
void dumpState(S2EExecutionState *state) {
static char regs[8][4] = {"eax", "ecx", "edx", "ebx",
"esp", "ebp", "esi", "edi"};
for (unsigned i = 0; i < 8; i++) {
unsigned offset = CPU_OFFSET(regs[0]) + i * sizeof(target_ulong);
ref<Expr> expr =
state->regs()->read(offset, sizeof(target_ulong) * CHAR_BIT);
g_s2e->getDebugStream() << regs[i] << ":\n";
g_s2e->getDebugStream() << expr << "\n";
}
}
} // namespace plugins
} // namespace s2e
| 30.952586 | 105 | 0.514692 | [
"vector"
] |
59c3240eb1daa15972a85fe6702923a8d833a359 | 2,094 | cpp | C++ | src/mongo/bson/bsonobjiterator.cpp | TylerBrock/mongo-cxx-driver | 46824e063c897acba234472c0db5b09e9635d3f9 | [
"Apache-2.0"
] | 1 | 2016-06-11T08:08:51.000Z | 2016-06-11T08:08:51.000Z | src/mongo/bson/bsonobjiterator.cpp | TylerBrock/mongo-cxx-driver | 46824e063c897acba234472c0db5b09e9635d3f9 | [
"Apache-2.0"
] | null | null | null | src/mongo/bson/bsonobjiterator.cpp | TylerBrock/mongo-cxx-driver | 46824e063c897acba234472c0db5b09e9635d3f9 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2014 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongo/db/jsobj.h"
#include "mongo/util/stringutils.h"
namespace mongo {
/** Compare two bson elements, provided as const char *'s, by field name. */
class BSONIteratorSorted::ElementFieldCmp {
public:
ElementFieldCmp( bool isArray );
bool operator()( const char *s1, const char *s2 ) const;
private:
LexNumCmp _cmp;
};
BSONIteratorSorted::ElementFieldCmp::ElementFieldCmp( bool isArray ) :
_cmp( !isArray ) {
}
bool BSONIteratorSorted::ElementFieldCmp::operator()( const char *s1, const char *s2 )
const {
// Skip the type byte and compare field names.
return _cmp( s1 + 1, s2 + 1 );
}
BSONIteratorSorted::BSONIteratorSorted( const BSONObj &o, const ElementFieldCmp &cmp ) {
_nfields = o.nFields();
_fields = new const char*[_nfields];
int x = 0;
BSONObjIterator i( o );
while ( i.more() ) {
_fields[x++] = i.next().rawdata();
verify( _fields[x-1] );
}
verify( x == _nfields );
std::sort( _fields , _fields + _nfields , cmp );
_cur = 0;
}
BSONObjIteratorSorted::BSONObjIteratorSorted( const BSONObj &object ) :
BSONIteratorSorted( object, ElementFieldCmp( false ) ) {
}
BSONArrayIteratorSorted::BSONArrayIteratorSorted( const BSONArray &array ) :
BSONIteratorSorted( array, ElementFieldCmp( true ) ) {
}
} // namespace mongo
| 32.71875 | 92 | 0.636581 | [
"object"
] |
59c7231aa400c39c98cdbee64852188bd01f8173 | 285 | cpp | C++ | StiGame/gui/Spacer.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | 8 | 2015-02-03T20:23:49.000Z | 2022-02-15T07:51:05.000Z | StiGame/gui/Spacer.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | null | null | null | StiGame/gui/Spacer.cpp | jordsti/stigame | 6ac0ae737667b1c77da3ef5007f5c4a3a080045a | [
"MIT"
] | 2 | 2017-02-13T18:04:00.000Z | 2020-08-24T03:21:37.000Z | #include "Spacer.h"
namespace StiGame
{
namespace Gui
{
Spacer::Spacer()
: Item("Spacer")
{
//ctor
}
Spacer::~Spacer()
{
//dtor
}
Surface* Spacer::render(void)
{
Surface *buffer = new Surface(width, height);
buffer->fill(background);
return buffer;
}
}
}
| 9.827586 | 49 | 0.607018 | [
"render"
] |
59ce2a4017e56d0d5a2de5f894fefd3d72fc9025 | 2,545 | cpp | C++ | leetcode/game-of-life/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | 1 | 2021-12-06T16:01:55.000Z | 2021-12-06T16:01:55.000Z | leetcode/game-of-life/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | leetcode/game-of-life/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | // link to the problem: https://leetcode.com/problems/game-of-life/
#include <algorithm>
#include <array>
#include <cassert>
#include <iostream>
#include <iterator>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
class Solution {
public:
void gameOfLife(std::vector<std::vector<int>>& board) {
rowsCount = board.size();
colsCount = board[0].size();
std::vector<std::vector<int>> newBoard(board);
for (auto i{0}; i < rowsCount; i++)
for (auto j{0}; j < colsCount; j++) {
point p = {i, j};
int liveNeighboursCount;
int ns = countLiveNeighbours(p, board);
switch (board[i][j]) {
case 0:
if (countLiveNeighbours(p, board) == 3) newBoard[i][j] = 1;
else newBoard[i][j] = 0;
break;
case 1:
liveNeighboursCount = countLiveNeighbours(p, board);
if (liveNeighboursCount < 2 || liveNeighboursCount > 3) newBoard[i][j] = 0;
else newBoard[i][j] = 1;
break;
}
}
board = newBoard;
}
private:
int rowsCount, colsCount;
using point = std::array<int, 2>;
std::vector<point> directions{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
std::vector<point> getNeighbours(const point& p) {
std::vector<point> neighbours;
for (const auto& direction : directions) {
point neighbour = addPoints(direction, p);
if (validatePoint(neighbour)) neighbours.push_back(neighbour);
}
return neighbours;
}
point addPoints(const point& p1, const point& p2) {
return {p1[0] + p2[0], p1[1] + p2[1]};
}
bool validatePoint(const point& p) {
return p[0] >= 0 && p[1] >= 0 && p[0] < rowsCount && p[1] < colsCount;
}
int countLiveNeighbours(const point& p, const std::vector<std::vector<int>>& board) {
int liveCells{0};
for (const point& neighbour : getNeighbours(p))
if (board[neighbour[0]][neighbour[1]] == 1) liveCells++;
return liveCells;
}
};
int main(int argc, char** argv) {
std::vector<std::vector<int>> board{{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
for (const auto& v : board) {
for (const auto& el : v) std::cout << el << " ";
std::cout << '\n';
}
Solution s;
s.gameOfLife(board);
std::cout << "New:\n";
for (const auto& v : board) {
for (const auto& el : v) std::cout << el << " ";
std::cout << '\n';
}
}
| 28.595506 | 102 | 0.577996 | [
"vector"
] |
59d2d6c890d8edc1bd2b7f6b7d662797bb6117ae | 13,537 | cpp | C++ | src/game/client/components/menus_texture.cpp | AssassinTee/Assa-Client | 0ed205d52e0a7b05eea7b0ab651f0c79c361ed74 | [
"Zlib"
] | null | null | null | src/game/client/components/menus_texture.cpp | AssassinTee/Assa-Client | 0ed205d52e0a7b05eea7b0ab651f0c79c361ed74 | [
"Zlib"
] | null | null | null | src/game/client/components/menus_texture.cpp | AssassinTee/Assa-Client | 0ed205d52e0a7b05eea7b0ab651f0c79c361ed74 | [
"Zlib"
] | null | null | null | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <engine/graphics.h>
#include <engine/shared/config.h>
#include <game/generated/client_data.h>
#include <game/client/animstate.h>
#include <game/localization.h>
//#include <game/render.h>//for font
#include "menus.h"
#include "skins.h"
#include "gskins.h"
#include "pskins.h"
#include "eskins.h"
#include "cskins.h"
#include "entskins.h"
#include "bskins.h"
void CMenus::RenderSettingsTexture(CUIRect MainView)
{
static int s_ControlPage = 0;
CUIRect TabBar, Button;
MainView.HSplitTop(20.0f, &TabBar, &MainView);
MainView.Margin(10.0f, &MainView);
// tab bar
{
TabBar.VSplitLeft(TabBar.w/6, &Button, &TabBar);
static int s_Button0 = 0;
if(DoButton_MenuTab(&s_Button0, Localize("Gameskin"), s_ControlPage == 0, &Button, 0))
s_ControlPage = 0;
TabBar.VSplitLeft(TabBar.w/5, &Button, &TabBar);
static int s_Button1 = 0;
if(DoButton_MenuTab(&s_Button1, Localize("Particles"), s_ControlPage == 1, &Button, 0))
s_ControlPage = 1;
TabBar.VSplitLeft(TabBar.w/4, &Button, &TabBar);
static int s_Button2 = 0;
if(DoButton_MenuTab(&s_Button2, Localize("Emoticons"), s_ControlPage == 2, &Button, 0))
s_ControlPage = 2;
TabBar.VSplitLeft(TabBar.w/3, &Button, &TabBar);
static int s_Button3 = 0;
if(DoButton_MenuTab(&s_Button3, Localize("Cursor"), s_ControlPage == 3, &Button, 0))
s_ControlPage = 3;
TabBar.VSplitMid(&Button, &TabBar);
static int s_Button4 = 0;
if(DoButton_MenuTab(&s_Button4, Localize("Entities"), s_ControlPage == 4, &Button, 0))
s_ControlPage = 4;
static int s_Button5 = 0;
if(DoButton_MenuTab(&s_Button5, Localize("Background"), s_ControlPage == 5, &TabBar, 0))
s_ControlPage = 5;
}
// render page
if(s_ControlPage == 0)
RenderSettingsGameskin(MainView);
else if(s_ControlPage == 1)
RenderSettingsParticles(MainView);
else if(s_ControlPage == 2)
RenderSettingsEmoticons(MainView);
else if(s_ControlPage == 3)
RenderSettingsCursor(MainView);
else if(s_ControlPage == 4)
RenderSettingsEntities(MainView);
else if(s_ControlPage == 5)
RenderSettingsBack(MainView);
}
void CMenus::RenderSettingsGameskin(CUIRect MainView)
{
CUIRect Button, Label;
MainView.HSplitTop(10.0f, 0, &MainView);
// skin selector
static bool s_InitSkinlist = true;
static sorted_array<const CgSkins::CgSkin *> s_paSkinList;
static float s_ScrollValue = 0.0f;
if(s_InitSkinlist)
{
s_paSkinList.clear();
for(int i = 0; i < m_pClient->m_pgSkins->Num(); ++i)
{
const CgSkins::CgSkin *s = m_pClient->m_pgSkins->Get(i);
// no special skins
if(s->m_aName[0] == 'x' && s->m_aName[1] == '_')
continue;
s_paSkinList.add(s);
}
s_InitSkinlist = false;
}
int OldSelected = -1;
UiDoListboxStart(&s_InitSkinlist, &MainView, 160.0f, Localize("Texture"), "", s_paSkinList.size(), 2, OldSelected, s_ScrollValue);
for(int i = 0; i < s_paSkinList.size(); ++i)
{
const CgSkins::CgSkin *s = s_paSkinList[i];
if(s == 0)
continue;
if(str_comp(s->m_aName, g_Config.m_GameTexture) == 0)
OldSelected = i;
CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);
if(Item.m_Visible)
{
CUIRect Label;
Item.m_Rect.Margin(5.0f, &Item.m_Rect);
Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);
int gTexture = s->m_Texture;
char gName[512];
str_format(gName, sizeof(gName), "%s", s->m_aName);;
Graphics()->TextureSet(gTexture);
Graphics()->QuadsBegin();
IGraphics::CQuadItem QuadItem(Item.m_Rect.x+Item.m_Rect.w/2 - 120.0f, Item.m_Rect.y+Item.m_Rect.h/2 - 60.0f, 240.0f, 120.0f);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
UI()->DoLabel(&Label, gName, 10.0f, 0);
}
}
const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);
if(OldSelected != NewSelected)
{
mem_copy(g_Config.m_GameTexture, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_GameTexture));
g_pData->m_aImages[IMAGE_GAME].m_Id = s_paSkinList[NewSelected]->m_Texture;
}
}
void CMenus::RenderSettingsParticles(CUIRect MainView)
{
CUIRect Button, Label;
MainView.HSplitTop(10.0f, 0, &MainView);
// skin selector
static bool s_InitSkinlist = true;
static sorted_array<const CpSkins::CpSkin *> s_paSkinList;
static float s_ScrollValue = 0.0f;
if(s_InitSkinlist)
{
s_paSkinList.clear();
for(int i = 0; i < m_pClient->m_ppSkins->Num(); ++i)
{
const CpSkins::CpSkin *s = m_pClient->m_ppSkins->Get(i);
// no special skins
if(s->m_aName[0] == 'x' && s->m_aName[1] == '_')
continue;
s_paSkinList.add(s);
}
s_InitSkinlist = false;
}
int OldSelected = -1;
UiDoListboxStart(&s_InitSkinlist, &MainView, 160.0f, Localize("Particles"), "", s_paSkinList.size(), 3, OldSelected, s_ScrollValue);
for(int i = 0; i < s_paSkinList.size(); ++i)
{
const CpSkins::CpSkin *s = s_paSkinList[i];
if(s == 0)
continue;
if(str_comp(s->m_aName, g_Config.m_GameParticles) == 0)
OldSelected = i;
CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);
if(Item.m_Visible)
{
CUIRect Label;
Item.m_Rect.Margin(5.0f, &Item.m_Rect);
Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);
int gTexture = s->m_Texture;
char gName[512];
str_format(gName, sizeof(gName), "%s", s->m_aName);;
Graphics()->TextureSet(gTexture);
Graphics()->QuadsBegin();
IGraphics::CQuadItem QuadItem(Item.m_Rect.x+Item.m_Rect.w/2 - 60.0f, Item.m_Rect.y+Item.m_Rect.h/2 - 60.0f, 120.0f, 120.0f);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
UI()->DoLabel(&Label, gName, 10.0f, 0);
}
}
const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);
if(OldSelected != NewSelected)
{
mem_copy(g_Config.m_GameParticles, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_GameParticles));
g_pData->m_aImages[IMAGE_PARTICLES].m_Id = s_paSkinList[NewSelected]->m_Texture;
}
}
void CMenus::RenderSettingsEmoticons(CUIRect MainView)
{
CUIRect Button, Label;
MainView.HSplitTop(10.0f, 0, &MainView);
// skin selector
static bool s_InitSkinlist = true;
static sorted_array<const CeSkins::CeSkin *> s_paSkinList;
static float s_ScrollValue = 0.0f;
if(s_InitSkinlist)
{
s_paSkinList.clear();
for(int i = 0; i < m_pClient->m_peSkins->Num(); ++i)
{
const CeSkins::CeSkin *s = m_pClient->m_peSkins->Get(i);
// no special skins
if(s->m_aName[0] == 'x' && s->m_aName[1] == '_')
continue;
s_paSkinList.add(s);
}
s_InitSkinlist = false;
}
int OldSelected = -1;
UiDoListboxStart(&s_InitSkinlist, &MainView, 160.0f, Localize("Emoticons"), "", s_paSkinList.size(), 3, OldSelected, s_ScrollValue);
for(int i = 0; i < s_paSkinList.size(); ++i)
{
const CeSkins::CeSkin *s = s_paSkinList[i];
if(s == 0)
continue;
if(str_comp(s->m_aName, g_Config.m_GameEmoticons) == 0)
OldSelected = i;
CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);
if(Item.m_Visible)
{
CUIRect Label;
Item.m_Rect.Margin(5.0f, &Item.m_Rect);
Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);
int gTexture = s->m_Texture;
char gName[512];
str_format(gName, sizeof(gName), "%s", s->m_aName);;
Graphics()->TextureSet(gTexture);
Graphics()->QuadsBegin();
IGraphics::CQuadItem QuadItem(Item.m_Rect.x+Item.m_Rect.w/2 - 60.0f, Item.m_Rect.y+Item.m_Rect.h/2 - 60.0f, 120.0f, 120.0f);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
UI()->DoLabel(&Label, gName, 10.0f, 0);
}
}
const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);
if(OldSelected != NewSelected)
{
mem_copy(g_Config.m_GameEmoticons, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_GameEmoticons));
g_pData->m_aImages[IMAGE_EMOTICONS].m_Id = s_paSkinList[NewSelected]->m_Texture;
}
}
void CMenus::RenderSettingsCursor(CUIRect MainView)
{
CUIRect Button, Label;
MainView.HSplitTop(10.0f, 0, &MainView);
// skin selector
static bool s_InitSkinlist = true;
static sorted_array<const CcSkins::CcSkin *> s_paSkinList;
static float s_ScrollValue = 0.0f;
if(s_InitSkinlist)
{
s_paSkinList.clear();
for(int i = 0; i < m_pClient->m_pcSkins->Num(); ++i)
{
const CcSkins::CcSkin *s = m_pClient->m_pcSkins->Get(i);
// no special skins
if(s->m_aName[0] == 'x' && s->m_aName[1] == '_')
continue;
s_paSkinList.add(s);
}
s_InitSkinlist = false;
}
int OldSelected = -1;
UiDoListboxStart(&s_InitSkinlist, &MainView, 160.0f, Localize("Cursor"), "", s_paSkinList.size(), 3, OldSelected, s_ScrollValue);
for(int i = 0; i < s_paSkinList.size(); ++i)
{
const CcSkins::CcSkin *s = s_paSkinList[i];
if(s == 0)
continue;
if(str_comp(s->m_aName, g_Config.m_GameCursor) == 0)
OldSelected = i;
CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);
if(Item.m_Visible)
{
CUIRect Label;
Item.m_Rect.Margin(5.0f, &Item.m_Rect);
Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);
int gTexture = s->m_Texture;
char gName[512];
str_format(gName, sizeof(gName), "%s", s->m_aName);;
Graphics()->TextureSet(gTexture);
Graphics()->QuadsBegin();
IGraphics::CQuadItem QuadItem(Item.m_Rect.x+Item.m_Rect.w/2 - 60.0f, Item.m_Rect.y+Item.m_Rect.h/2 - 60.0f, 120.0f, 120.0f);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
UI()->DoLabel(&Label, gName, 10.0f, 0);
}
}
const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);
if(OldSelected != NewSelected)
{
mem_copy(g_Config.m_GameCursor, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_GameCursor));
g_pData->m_aImages[IMAGE_CURSOR].m_Id = s_paSkinList[NewSelected]->m_Texture;
}
}
void CMenus::RenderSettingsEntities(CUIRect MainView)
{
CUIRect Button, Label;
MainView.HSplitTop(10.0f, 0, &MainView);
// skin selector
static bool s_InitSkinlist = true;
static sorted_array<const CentSkins::CentSkin *> s_paSkinList;
static float s_ScrollValue = 0.0f;
if(s_InitSkinlist)
{
s_paSkinList.clear();
for(int i = 0; i < m_pClient->m_pCentSkins->Num(); ++i)
{
const CentSkins::CentSkin *s = m_pClient->m_pCentSkins->Get(i);
// no special skins
if(s->m_aName[0] == 'x' && s->m_aName[1] == '_')
continue;
s_paSkinList.add(s);
}
s_InitSkinlist = false;
}
int OldSelected = -1;
UiDoListboxStart(&s_InitSkinlist, &MainView, 160.0f, Localize("Entities"), "", s_paSkinList.size(), 3, OldSelected, s_ScrollValue);
for(int i = 0; i < s_paSkinList.size(); ++i)
{
const CentSkins::CentSkin *s = s_paSkinList[i];
if(s == 0)
continue;
if(str_comp(s->m_aName, g_Config.m_GameEntities) == 0)
OldSelected = i;
CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);
if(Item.m_Visible)
{
CUIRect Label;
Item.m_Rect.Margin(5.0f, &Item.m_Rect);
Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);
int gTexture = s->m_Texture;
char gName[512];
str_format(gName, sizeof(gName), "%s", s->m_aName);;
Graphics()->TextureSet(gTexture);
Graphics()->QuadsBegin();
IGraphics::CQuadItem QuadItem(Item.m_Rect.x+Item.m_Rect.w/2 - 60.0f, Item.m_Rect.y+Item.m_Rect.h/2 - 60.0f, 120.0f, 120.0f);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
UI()->DoLabel(&Label, gName, 10.0f, 0);
}
}
const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);
if(OldSelected != NewSelected)
{
mem_copy(g_Config.m_GameEntities, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_GameEntities));
g_pData->m_aImages[IMAGE_ENTITIES].m_Id = s_paSkinList[NewSelected]->m_Texture;
}
}
void CMenus::RenderSettingsBack(CUIRect MainView)
{
CUIRect Button, Label;
MainView.HSplitTop(10.0f, 0, &MainView);
// skin selector
static bool s_InitSkinlist = true;
static sorted_array<const CbSkins::CbSkin *> s_paSkinList;
static float s_ScrollValue = 0.0f;
if(s_InitSkinlist)
{
s_paSkinList.clear();
for(int i = 0; i < m_pClient->m_pbSkins->Num(); ++i)
{
const CbSkins::CbSkin *s = m_pClient->m_pbSkins->Get(i);
// no special skins
if(s->m_aName[0] == 'x' && s->m_aName[1] == '_')
continue;
s_paSkinList.add(s);
}
s_InitSkinlist = false;
}
int OldSelected = -1;
UiDoListboxStart(&s_InitSkinlist, &MainView, 160.0f, Localize("Background"), "", s_paSkinList.size(), 3, OldSelected, s_ScrollValue);
for(int i = 0; i < s_paSkinList.size(); ++i)
{
const CbSkins::CbSkin *s = s_paSkinList[i];
if(s == 0)
continue;
if(str_comp(s->m_aName, g_Config.m_GameBack) == 0)
OldSelected = i;
CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);
if(Item.m_Visible)
{
CUIRect Label;
Item.m_Rect.Margin(5.0f, &Item.m_Rect);
Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);
int gTexture = s->m_Texture;
char gName[512];
str_format(gName, sizeof(gName), "%s", s->m_aName);;
Graphics()->TextureSet(gTexture);
Graphics()->QuadsBegin();
IGraphics::CQuadItem QuadItem(Item.m_Rect.x+Item.m_Rect.w/2 - 60.0f, Item.m_Rect.y+Item.m_Rect.h/2 - 60.0f, 120.0f, 120.0f);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
UI()->DoLabel(&Label, gName, 10.0f, 0);
}
}
const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);
if(OldSelected != NewSelected)
{
mem_copy(g_Config.m_GameBack, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_GameBack));
g_pData->m_aImages[IMAGE_BACKGROUND].m_Id = s_paSkinList[NewSelected]->m_Texture;
}
}
| 30.216518 | 134 | 0.68804 | [
"render"
] |
59d44aee5a211561c2765f4e9b8aff2d3d75f118 | 3,626 | cpp | C++ | Source/Graphics/Font.cpp | PandarinDev/Winter | 567bd93f1fc8be8e0b9559409f1c80421d0b8e24 | [
"MIT"
] | 1 | 2019-01-08T12:13:59.000Z | 2019-01-08T12:13:59.000Z | Source/Graphics/Font.cpp | PandarinDev/Winter | 567bd93f1fc8be8e0b9559409f1c80421d0b8e24 | [
"MIT"
] | null | null | null | Source/Graphics/Font.cpp | PandarinDev/Winter | 567bd93f1fc8be8e0b9559409f1c80421d0b8e24 | [
"MIT"
] | null | null | null | #include "Graphics/Font.h"
#include "Factory/MeshFactory.h"
namespace winter {
Font::Font(const std::string &name, short size, unsigned short lineHeight, unsigned short base,
std::unique_ptr<Texture> texture,
std::unordered_map<FontChar::Id, FontChar>&& characters,
std::unordered_map<std::pair<FontChar::Id, FontChar::Id>, short>&& kernings) :
name(name), size(size), lineHeight(lineHeight), base(base), texture(texture.release()),
characters(std::move(characters)), kernings(std::move(kernings)) {}
std::unique_ptr<Text> Font::generateText(const std::string& content) const {
static constexpr auto verticesPerCharacter = 24;
std::vector<float> vertexBuffer(content.size() * verticesPerCharacter);
std::size_t counter = 0;
float cursorX = 0.0f, cursorY = 0.0f;
float textureWidth = texture->getWidth();
float textureHeight = texture->getHeight();
FontChar::Id lastChar = -1u;
for (const auto c : content) {
auto fontChar = getFontChar(c);
float x = cursorX + fontChar.xOffset;
float y = cursorY;
// Bottom right triangle
vertexBuffer[counter++] = x;
vertexBuffer[counter++] = y;
vertexBuffer[counter++] = fontChar.x / textureWidth;
vertexBuffer[counter++] = 1.0f - ((fontChar.y + fontChar.height) / textureHeight);
vertexBuffer[counter++] = x + fontChar.width;
vertexBuffer[counter++] = y;
vertexBuffer[counter++] = (fontChar.x + fontChar.width) / textureWidth;
vertexBuffer[counter++] = 1.0f - ((fontChar.y + fontChar.height) / textureHeight);
vertexBuffer[counter++] = x + fontChar.width;
vertexBuffer[counter++] = y + fontChar.height;
vertexBuffer[counter++] = (fontChar.x + fontChar.width) / textureWidth;
vertexBuffer[counter++] = 1.0f - (fontChar.y / textureHeight);
// Upper left triangle
vertexBuffer[counter++] = x;
vertexBuffer[counter++] = y;
vertexBuffer[counter++] = fontChar.x / textureWidth;
vertexBuffer[counter++] = 1.0f - ((fontChar.y + fontChar.height) / textureHeight);
vertexBuffer[counter++] = x + fontChar.width;
vertexBuffer[counter++] = y + fontChar.height;
vertexBuffer[counter++] = (fontChar.x + fontChar.width) / textureWidth;
vertexBuffer[counter++] = 1.0f - (fontChar.y / textureHeight);
vertexBuffer[counter++] = x;
vertexBuffer[counter++] = y + fontChar.height;
vertexBuffer[counter++] = fontChar.x / textureWidth;
vertexBuffer[counter++] = 1.0f - (fontChar.y / textureHeight);
cursorX += fontChar.xAdvance;
auto kerningIt = kernings.find(std::make_pair(lastChar, fontChar.id));
if (kerningIt != kernings.end()) {
cursorX += kerningIt->second;
}
lastChar = fontChar.id;
}
std::vector<VertexAttribute> attributes = {
{ 0, 2 }, // Geometry
{ 1, 2 } // Texture coordinates
};
return std::make_unique<Text>(MeshFactory::loadGeometry(vertexBuffer, attributes), texture);
}
const std::string& Font::getName() const {
return name;
}
short Font::getSize() const {
return size;
}
unsigned short Font::getLineHeight() const {
return lineHeight;
}
unsigned short Font::getBase() const {
return base;
}
const Texture& Font::getTexture() const {
return *texture;
}
const FontChar& Font::getFontChar(winter::FontChar::Id id) const {
return characters.at(id);
}
short Font::getKerningForPair(winter::FontChar::Id first, winter::FontChar::Id second) const {
return kernings.at(std::make_pair(first, second));
}
} | 36.626263 | 102 | 0.650579 | [
"geometry",
"vector"
] |
59e42e1880fb12b1332cfb5b23c6ddf274c87d0a | 1,524 | cpp | C++ | tap/core/tuple.cpp | tsavola/tap | e7b5dea6b0e9c7ebbb2710842ebfb62352cb54cc | [
"BSD-2-Clause"
] | 1 | 2019-12-09T20:55:59.000Z | 2019-12-09T20:55:59.000Z | tap/core/tuple.cpp | tsavola/tap | e7b5dea6b0e9c7ebbb2710842ebfb62352cb54cc | [
"BSD-2-Clause"
] | null | null | null | tap/core/tuple.cpp | tsavola/tap | e7b5dea6b0e9c7ebbb2710842ebfb62352cb54cc | [
"BSD-2-Clause"
] | null | null | null | #include "core.hpp"
#include "portable.hpp"
namespace tap {
static int tuple_traverse(PyObject *object, visitproc visit, void *arg) noexcept
{
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(object); ++i)
Py_VISIT(PyTuple_GET_ITEM(object, i));
return 0;
}
static Py_ssize_t tuple_marshaled_size(PyObject *object) noexcept
{
return sizeof (Key) * PyTuple_GET_SIZE(object);
}
static int tuple_marshal(PyObject *object, void *buf, Py_ssize_t size, PeerObject &peer) noexcept
{
Key *portable = reinterpret_cast<Key *> (buf);
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(object); ++i) {
Key remote_key = peer.key_for_remote(PyTuple_GET_ITEM(object, i));
if (remote_key < 0)
return -1;
portable[i] = port(remote_key);
}
return 0;
}
static PyObject *tuple_unmarshal_alloc(const void *data, Py_ssize_t size, PeerObject &peer) noexcept
{
if (size % sizeof (Key))
return nullptr;
return PyTuple_New(size / sizeof (Key));
}
static int tuple_unmarshal_init(PyObject *object, const void *data, Py_ssize_t size, PeerObject &peer) noexcept
{
const Key *portable = reinterpret_cast<const Key *> (data);
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(object); ++i) {
PyObject *item = peer.object(port(portable[i]));
if (item == nullptr)
return -1;
Py_INCREF(item);
PyTuple_SET_ITEM(object, i, item);
}
return 0;
}
const TypeHandler tuple_type_handler = {
TUPLE_TYPE_ID,
tuple_traverse,
tuple_marshaled_size,
tuple_marshal,
tuple_unmarshal_alloc,
tuple_unmarshal_init,
};
} // namespace tap
| 22.411765 | 111 | 0.723753 | [
"object"
] |
9403bdbf343f7326749a43b348faebb487f507c1 | 28,758 | cpp | C++ | src/ImgProc/UI/Src/UICfg/CommUICfg.cpp | Passer-D/GameAISDK | a089330a30b7bfe1f6442258a12d8c0086240606 | [
"Apache-2.0"
] | 1,210 | 2020-08-18T07:57:36.000Z | 2022-03-31T15:06:05.000Z | src/ImgProc/UI/Src/UICfg/CommUICfg.cpp | guokaiSama/GameAISDK | a089330a30b7bfe1f6442258a12d8c0086240606 | [
"Apache-2.0"
] | 37 | 2020-08-24T02:48:38.000Z | 2022-01-30T06:41:52.000Z | src/ImgProc/UI/Src/UICfg/CommUICfg.cpp | guokaiSama/GameAISDK | a089330a30b7bfe1f6442258a12d8c0086240606 | [
"Apache-2.0"
] | 275 | 2020-08-18T08:35:16.000Z | 2022-03-31T15:06:07.000Z | /*
* Tencent is pleased to support the open source community by making GameAISDK available.
* This source code file is licensed under the GNU General Public License Version 3.
* For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
*/
#include <algorithm>
#include "UI/Src/UICfg/CommUICfg.h"
CCommUICfg::CCommUICfg() {
m_oVecState.clear();
m_bOldCfg = false;
}
CCommUICfg::~CCommUICfg() {
}
bool CCommUICfg::Initialize(const char *pszRootDir, const char *pszCftPath, CJsonConfig *pConfig) {
// check parameters
if (pConfig == NULL) {
LOGE("Cannot create json config parser.");
return false;
}
// check file exist
char szPath[TQC_PATH_STR_LEN] = { 0 };
SNPRINTF(szPath, TQC_PATH_STR_LEN, "%s/%s", pszRootDir, pszCftPath);
if (!IsFileExist(szPath)) {
LOGE("file is not exist");
return false;
}
// Load configure file.
bool bRst = pConfig->loadFile(szPath);
if (!bRst) {
LOGE("Load file %s failed", szPath);
return false;
}
// read configure
LOGI("Load file %s success", szPath);
bRst = ReadCfg(pszRootDir, pConfig);
return bRst;
}
//
// Get template info from configure file.
//
bool CCommUICfg::ReadTemplateFromJson(const int nIndex, const int nTemplate,
tagUIState *pstUIState, CJsonConfig *pConfig) {
// check parameters
if (NULL == pstUIState) {
LOGE("input point to UIState is NULL");
return false;
}
char buf[TQC_PATH_STR_LEN] = { 0 };
char key[TQC_PATH_STR_LEN] = { 0 };
int nLen = 0;
bool bRst = false;
// For consistent with the old format.
if (nTemplate <= 0) {
return true;
} else if (nTemplate == 1) {
// For template, we should set x, y, width and height of sample in
// the image.
// pUIState->bUseTempMatch = true;
// For single template image, we use the default operator.
pstUIState->tempOp = UI_TEMPLATE_AND;
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "x", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates x: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[0].stTemplParam.nSampleX = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "y", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates y: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[0].stTemplParam.nSampleY = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "w", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates w: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[0].stTemplParam.nSampleW = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "h", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates h: %d", nIndex);
// delete pConfig;
return false;
}
// We can search template in some region, not exact position of sample in
// the image.
pstUIState->szTemplState[0].stTemplParam.nSampleH = atoi(buf);
/*
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "shift", buf, &nLen, DATA_STR);
if (!bRst)
{
LOGE("get state description failed. uiStates shift: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[0].nShift = atoi(buf);
*/
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "templateThreshold",
buf, &nLen, DATA_STR);
if (bRst) {
pstUIState->szTemplState[0].stTemplParam.fThreshold = atof(buf);
}
} else {
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "templateOp", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates x: %d", nIndex);
// delete pConfig;
return false;
}
// All of the template images should be matched.
if (strstr(buf, "and")) {
pstUIState->tempOp = UI_TEMPLATE_AND;
} else if (strstr(buf, "or")) {
pstUIState->tempOp = UI_TEMPLATE_OR;
} else {
// Default template match operator is and
pstUIState->tempOp = UI_TEMPLATE_AND;
}
// For template, we should set x, y, width and height of sample in the image.
// pUIState->bUseTempMatch = true;
for (int i = 0; i < nTemplate; i++) {
memset(buf, 0, TQC_PATH_STR_LEN);
memset(key, 0, TQC_PATH_STR_LEN);
SNPRINTF(key, TQC_PATH_STR_LEN, "x%d", (i + 1));
bRst = pConfig->GetArrayValue("uiStates", nIndex, key, buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates x: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[i].stTemplParam.nSampleX = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
memset(key, 0, TQC_PATH_STR_LEN);
SNPRINTF(key, TQC_PATH_STR_LEN, "y%d", (i + 1));
bRst = pConfig->GetArrayValue("uiStates", nIndex, key, buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates y: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[i].stTemplParam.nSampleY = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
memset(key, 0, TQC_PATH_STR_LEN);
SNPRINTF(key, TQC_PATH_STR_LEN, "w%d", (i + 1));
bRst = pConfig->GetArrayValue("uiStates", nIndex, key, buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates w: %d", nIndex);
// delete pConfig;
return false;
}
pstUIState->szTemplState[i].stTemplParam.nSampleW = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
memset(key, 0, TQC_PATH_STR_LEN);
SNPRINTF(key, TQC_PATH_STR_LEN, "h%d", (i + 1));
bRst = pConfig->GetArrayValue("uiStates", nIndex, key, buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates h: %d", nIndex);
// delete pConfig;
return false;
}
// We can search template in some region, not exact position of sample in
// the image.
pstUIState->szTemplState[i].stTemplParam.nSampleH = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
memset(key, 0, TQC_PATH_STR_LEN);
/*SNPRINTF(key, TQC_PATH_STR_LEN, "shift%d", (i + 1));
bRst = pConfig->GetArrayValue("uiStates", nIndex, key, buf, &nLen, DATA_STR);
if (!bRst)
{
LOGE("get state description failed. uiStates shift: %d", nIndex);
// delete pConfig;
return false;
}
*/
memset(buf, 0, TQC_PATH_STR_LEN);
memset(key, 0, TQC_PATH_STR_LEN);
SNPRINTF(key, TQC_PATH_STR_LEN, "templateThreshold%d", (i + 1));
bRst = pConfig->GetArrayValue("uiStates", nIndex, key, buf, &nLen, DATA_STR);
if (bRst) {
pstUIState->szTemplState[i].stTemplParam.fThreshold = atof(buf);
}
}
}
return true;
}
bool CCommUICfg::ReadDragCheckItem(const char *pszRootDir, const int nIndex,
tagUIState *puiState, CJsonConfig *pConfig) {
// check parameters
if (NULL == puiState) {
LOGE("point to uiState is NULL");
return false;
}
int nLen;
char buf[TQC_PATH_STR_LEN] = { 0 };
memset(buf, 0, TQC_PATH_STR_LEN);
bool bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionDir", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("Getting drag direction failed. uiStates action_dir: %d", nLen);
// delete pConfig;
return false;
}
// 0 for none, 1 for down, 2 for up, 3 for left, 4 for right
if (strstr(buf, "down"))
puiState->stDragCheckState.dragAction = 1;
else if (strstr(buf, "up"))
puiState->stDragCheckState.dragAction = 2;
else if (strstr(buf, "left"))
puiState->stDragCheckState.dragAction = 3;
else if (strstr(buf, "right"))
puiState->stDragCheckState.dragAction = 4;
// Get start x position of drag operation.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "dragX", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get drag start x failed.");
// delete pConfig;
return false;
}
puiState->stDragCheckState.stDragPt.nPointX = atoi(buf);
// Get start y position of drag operation.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "dragY", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get drag start y failed.");
// delete pConfig;
return false;
}
puiState->stDragCheckState.stDragPt.nPointY = atoi(buf);
// Get length of drag operation by pixel.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "dragLen", buf, &nLen, DATA_STR);
if (!bRst) {
puiState->stDragCheckState.dragLen = 80; // default is 80 pixels.
} else {
puiState->stDragCheckState.dragLen = atoi(buf);
}
// Get the count of max drag operation. We will count call of DoDragAndCheck.
// If it exceeds the count of drag operation, we will change game state
// to UI state.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "dragCount", buf, &nLen, DATA_STR);
if (!bRst) {
puiState->stDragCheckState.dragCount = 400; // default is 400.
} else {
puiState->stDragCheckState.dragCount = atoi(buf);
}
// Get target image file.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "targetImg", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("Getting target image failed. uiStates action_dir: %d", nIndex);
// delete pConfig;
return false;
}
memset(puiState->stDragCheckState.strDragTargetFile, 0, TQC_PATH_STR_LEN);
snprintf(puiState->stDragCheckState.strDragTargetFile, TQC_PATH_STR_LEN, "%s/%s",
pszRootDir, buf);
cv::Mat oImage = cv::imread(puiState->stDragCheckState.strDragTargetFile);
if (oImage.empty()) {
LOGE("UI %d read drage check image %s failed", puiState->nId,
puiState->stDragCheckState.strDragTargetFile);
return false;
}
puiState->stDragCheckState.targetImg[0] = oImage;
// Get x position of target template image.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "targetX", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get target x failed.");
// delete pConfig;
return false;
}
puiState->stDragCheckState.stTargetRect.nPointX = atoi(buf);
// Get y position of target template image.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "targetY", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get target y failed.");
// delete pConfig;
return false;
}
puiState->stDragCheckState.stTargetRect.nPointY = atoi(buf);
// Get w position of target template image.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "targetW", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get target w failed.");
// delete pConfig;
return false;
}
puiState->stDragCheckState.stTargetRect.nWidth = atoi(buf);
// Get h position of target template image.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "targetH", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get target h failed.");
// delete pConfig;
return false;
}
puiState->stDragCheckState.stTargetRect.nHeight = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "templateThreshold", buf, &nLen, DATA_STR);
if (!bRst) {
puiState->stDragCheckState.fDragThreshold = GAME_TEMPLATE_THRESHOLD;
} else {
puiState->stDragCheckState.fDragThreshold = atoi(buf);
}
// uiState.tempOp = UI_TEMPLATE_AND;
// uiState.nTemplate = 1;
// uiState.actionType = UI_ACTION_DRAG_AND_CHECK;
puiState->actionType = UI_ACTION_DRAG_AND_CHECK;
// tagTmpl stTmpl;
// stTmpl.oTmplImg = oImage;
// CColorMatchParam oColorMatchParam;
// oColorMatchParam.m_oVecTmpls.push_back(stTmpl);
// uiState.stDragCheckState.targetMatch.Initialize(&oColorMatchParam)
return true;
}
bool CCommUICfg::ReadClickItem(const int nIndex, tagUIState *puiState, CJsonConfig *pConfig) {
if (NULL == puiState) {
LOGE("point to UIState is NULL");
return false;
}
// (x, y) position of click.
char buf[TQC_PATH_STR_LEN] = { 0 };
int nLen;
puiState->actionType = UI_ACTION_CLICK;
memset(buf, 0, TQC_PATH_STR_LEN);
bool bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionX", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates actionX: %d", nIndex);
// delete pConfig;
return false;
}
puiState->stAction1.nActionX = atoi(buf);
// uiState.x1Action = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionY", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates actionY: %d", nIndex);
// delete pConfig;
return false;
}
puiState->stAction1.nActionY = atoi(buf);
// uiState.y1Action = atoi(buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionThreshold", buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.fActionThreshold = atof(buf);
}
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionTmplExpdWPixel",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.nTmplExpdWPixel = atoi(buf);
}
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionTmplExpdHPixel",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.nTmplExpdHPixel = atoi(buf);
}
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionROIExpdWRatio",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.fROIExpdWRatio = atof(buf);
}
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionROIExpdHRatio",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.fROIExpdHRatio = atof(buf);
}
LOGD("index: %d, id: %d, x: %d, y: %d, threshold: %f, EW: %d, EH: %d, EWRatio: %f, EHRatio: %f",
nIndex, puiState->nId, puiState->stAction1.nActionX, puiState->stAction1.nActionY,
puiState->stAction1.fActionThreshold, puiState->stAction1.nTmplExpdWPixel,
puiState->stAction1.nTmplExpdHPixel,
puiState->stAction1.fROIExpdWRatio, puiState->stAction1.fROIExpdHRatio);
puiState->stAction2.nActionX = 0;
puiState->stAction2.nActionY = 0;
return true;
}
bool CCommUICfg::ReadDragItem(const int nIndex, tagUIState *puiState, CJsonConfig *pConfig) {
// check paramters
if (NULL == puiState) {
LOGE("point to UIState is NULL");
return false;
}
puiState->actionType = UI_ACTION_DRAG;
char buf[TQC_PATH_STR_LEN] = { 0 };
int nLen;
// "actionX1"
bool bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionX1", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get actionX1 failed. uiStates actionX1: %d", nIndex);
delete pConfig;
return false;
}
// uiState.x1Action = atoi(buf);
puiState->stAction1.nActionX = atoi(buf);
// "actionY1"
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionY1", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates actionY1: %d", nIndex);
delete pConfig;
return false;
}
puiState->stAction1.nActionY = atoi(buf);
// actionThreshold1
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionThreshold1", buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.fActionThreshold = atof(buf);
}
// actionTmplExpdWPixel1
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionTmplExpdWPixel1",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.nTmplExpdWPixel = atoi(buf);
}
// actionTmplExpdHPixel1
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionTmplExpdHPixel1",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.nTmplExpdHPixel = atoi(buf);
}
// actionROIExpdWRatio1
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionROIExpdWRatio1",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.fROIExpdWRatio = atof(buf);
}
// actionROIExpdHRatio1
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionROIExpdHRatio1",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction1.fROIExpdHRatio = atof(buf);
}
// actionX2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionX2", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates actionX2: %d", nIndex);
delete pConfig;
return false;
}
puiState->stAction2.nActionX = atoi(buf);
// actionY2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionY2", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates actionY2: %d", nIndex);
delete pConfig;
return false;
}
puiState->stAction2.nActionY = atoi(buf);
// actionThreshold2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionThreshold2", buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction2.fActionThreshold = atof(buf);
}
// actionTmplExpdWPixel2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionTmplExpdWPixel2",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction2.nTmplExpdWPixel = atoi(buf);
}
// actionTmplExpdHPixel2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionTmplExpdHPixel2",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction2.nTmplExpdHPixel = atoi(buf);
}
// actionROIExpdWRatio2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionROIExpdWRatio2",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction2.fROIExpdWRatio = atof(buf);
}
// actionROIExpdHRatio2
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionROIExpdHRatio2",
buf, &nLen, DATA_STR);
if (bRst) {
puiState->stAction2.fROIExpdHRatio = atof(buf);
}
return true;
}
bool CCommUICfg::ReadScriptItem(const int nIndex, tagUIState *puiState, CJsonConfig *pConfig) {
// check paramters
if (NULL == puiState) {
LOGE("point to uiState is NULL");
return false;
}
// process for "script" action
puiState->actionType = UI_ACTION_SCRIPT;
char buf[TQC_PATH_STR_LEN] = { 0 };
int nLen = 0;
bool bRst = pConfig->GetArrayValue("uiStates", nIndex, "scriptPath", buf, &nLen, DATA_STR);
memset(puiState->strScriptPath, 0, TQC_PATH_STR_LEN);
memcpy(puiState->strScriptPath, buf, nLen);
LOGI("read script path %s", puiState->strScriptPath);
if (bRst) {
Json::Value jsonUIStates = pConfig->GetJosnValue("uiStates");
Json::Value jsonUITasks = jsonUIStates[nIndex];
puiState->jsonScriptParams["tasks"] = jsonUITasks["tasks"];
puiState->jsonScriptParams["extNum"] = puiState->nScrpitExtNum;
}
return true;
}
bool CCommUICfg::ReadCommItem(const char *pszRootDir, const int nIndex, tagUIState *puiState,
CJsonConfig *pConfig) {
// check paramters
if (NULL == puiState) {
LOGE("point to uiState is NULL");
return false;
}
int nTemplate = 0;
char buf[TQC_PATH_STR_LEN] = { 0 };
int nLen = 0;
// Description of UI state,This will be printed if being matched.
bool bRst = pConfig->GetArrayValue("uiStates", nIndex, "desc", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates desc: %d", nIndex);
delete pConfig;
return false;
}
// ID of each UI state that cannot be duplicated.
memset(puiState->strStateName, 0, TQC_PATH_STR_LEN);
memcpy(puiState->strStateName, buf, nLen);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "id", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates id: %d", nIndex);
delete pConfig;
return false;
}
puiState->nId = atoi(buf);
// ID of each UI state that cannot be duplicated.
memset(puiState->strStateName, 0, TQC_PATH_STR_LEN);
memcpy(puiState->strStateName, buf, nLen);
// "delete"
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "delete", buf, &nLen, DATA_STR);
if (bRst) {
int nDel = atoi(buf);
if (nDel == 1)
puiState->bDelete = true;
}
// Match algorithm of UI state is feature poit match.
// We will set minimun points that should be matched.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "keyPoints", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates keyPoints: %d", nIndex);
delete pConfig;
return false;
}
puiState->nMatched = atoi(buf);
// Load sample image from the path of image.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "imgPath", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates imgPath: %d", nIndex);
delete pConfig;
return false;
}
// If feature point match cannot distinguish the same UI,
// we can add a template match for some UI.
memset(puiState->strSampleFile, 0, TQC_PATH_STR_LEN);
SNPRINTF(puiState->strSampleFile, TQC_PATH_STR_LEN, "%s/%s", pszRootDir, buf);
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "template", buf, &nLen, DATA_STR);
nTemplate = atoi(buf);
if (bRst && nTemplate > 0) {
puiState->nTemplate = nTemplate;
if (ReadTemplateFromJson(nIndex, nTemplate, puiState, pConfig) == false) {
return false;
}
}
// Set action during time.
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "during", buf, &nLen, DATA_STR);
if (bRst) {
puiState->nActionDuringTime = atoi(buf);
}
// "checkSameFrameCnt"
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "checkSameFrameCnt", buf, &nLen, DATA_STR);
if (bRst) {
puiState->nCheckSameFrameCnt = atoi(buf);
}
// "actionSleepTimeMs"
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", nIndex, "actionSleepTimeMs", buf, &nLen, DATA_STR);
if (bRst) {
puiState->nActionSleepTimeMs = atoi(buf);
}
return true;
}
bool CCommUICfg::ReadCfg(const char *pszRootDir, CJsonConfig *pConfig) {
// check parameters
if (NULL == pszRootDir || NULL == pConfig) {
LOGE("input param is invalid, please check");
return false;
}
int nSize = pConfig->GetArraySize("uiStates");
int nLen = 0;
char buf[TQC_PATH_STR_LEN];
bool bRst = false;
// There is no UI state.
if (nSize <= 0) {
LOGE("There is no Hall UI state.");
return true;
}
// Parse each UI state from json string.
for (int i = 0; i < nSize; i++) {
tagUIState uiState;
bRst = ReadCommItem(pszRootDir, i, &uiState, pConfig);
if (!bRst) {
return false;
}
// "actionType"
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("uiStates", i, "actionType", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get state description failed. uiStates actionType: %d", i);
return false;
}
// "click"
if (strstr(buf, "click")) {
bRst = ReadClickItem(i, &uiState, pConfig);
if (!bRst) {
return false;
}
} else if (strstr(buf, "dragcheck")) {
// For drag-check operation, we do not set start point and end point.
// But we should set the direction that drag will go to and the target
// image.
bRst = ReadDragCheckItem(pszRootDir, i, &uiState, pConfig);
if (!bRst) {
return false;
}
} else if (strstr(buf, "drag")) {
// For drag operation, we will set the start point and
// end point. The drag is from (x1, y1) to (x2, y2).
bRst = ReadDragItem(i, &uiState, pConfig);
if (!bRst) {
return false;
}
} else if (strstr(buf, "script")) {
// process for "script" action
bRst = ReadScriptItem(i, &uiState, pConfig);
if (!bRst) {
return false;
}
}
// Load image from the path of sample image.
// memset(buf, 0, TQC_PATH_STR_LEN);
// SNPRINTF(buf, sizeof(buf), "%s/%s", pszRootDir, uiState.strSampleFile);
cv::Mat origImg = cv::imread(uiState.strSampleFile);
if (origImg.empty()) {
LOGE("Cannot open image file: %s", uiState.strSampleFile);
return false;
}
uiState.sampleImg = origImg;
// Saving the current UI state.
// We will check each one of here to match some UI state.
LOGI("load CommonUI: %d configure", uiState.nId);
m_oVecState.push_back(uiState);
}
return true;
}
bool CCommUICfg::ReadStartState(std::vector<int> *pnVecStartID, CJsonConfig *pConfig) {
// check parameters
if (NULL == pnVecStartID) {
LOGE("pointer to start ID vector is None, please cechk");
return false;
}
// "matchStartState"
char buf[TQC_PATH_STR_LEN] = { 0 };
int nSize = pConfig->GetArraySize("matchStartState");
int nLen = 0;
bool bRst = false;
// There is no start state.
if (nSize < 0) {
LOGW("There is no matchStartState.");
return true;
}
// Get the id of start states.
for (int i = 0; i < nSize; i++) {
// "matchStartState"
memset(buf, 0, TQC_PATH_STR_LEN);
bRst = pConfig->GetArrayValue("matchStartState", i, "id", buf, &nLen, DATA_STR);
if (!bRst) {
LOGE("get start state description failed. matchStartState id: %d", i);
return false;
}
pnVecStartID->push_back(atoi(buf));
}
return true;
}
UIStateArray CCommUICfg::GetState() {
return m_oVecState;
}
| 34.033136 | 115 | 0.606092 | [
"vector"
] |
940c316747240db4584381e7bdacfb495b0b05e4 | 2,833 | cpp | C++ | algorithms/visit/CompositorVisIt.cpp | wilsonCernWq/WarmT | 445d2c65094cdbd58bf5f05851afee2b715dcd00 | [
"MIT"
] | 1 | 2018-04-20T21:47:57.000Z | 2018-04-20T21:47:57.000Z | algorithms/visit/CompositorVisIt.cpp | wilsonCernWq/QCT | 445d2c65094cdbd58bf5f05851afee2b715dcd00 | [
"MIT"
] | null | null | null | algorithms/visit/CompositorVisIt.cpp | wilsonCernWq/QCT | 445d2c65094cdbd58bf5f05851afee2b715dcd00 | [
"MIT"
] | null | null | null | #include "CompositorVisIt.h"
#include "avtSLIVRImgMetaData.h"
#include "avtSLIVRImgCommunicator.h"
#include <vector>
static avtSLIVRImgCommunicator* imgComm;
static std::vector<float*> tileBufferList;
namespace QCT {
namespace algorithms {
namespace visit {
Compositor_VisIt::Compositor_VisIt(const Mode& m,
const uint32_t& width,
const uint32_t& height)
: mode(m), W(width), H(height) {
if (mpiRank == 0) { rgba = new float[4 * W * H](); }
imgComm = new avtSLIVRImgCommunicator();
};
Compositor_VisIt::~Compositor_VisIt() {
if (mpiRank == 0) { if (rgba) delete[] rgba; }
for (auto b : tileBufferList) { if (b) delete[] b; }
delete imgComm;
};
//! function to get final results
const void *Compositor_VisIt::MapDepthBuffer() { return depth; };
const void *Compositor_VisIt::MapColorBuffer() { return rgba; };
void Compositor_VisIt::Unmap(const void *mappedMem) {};
//! clear (the specified channels of) this frame buffer
void Compositor_VisIt::Clear(const uint32_t channelFlags) {};
//! status
bool Compositor_VisIt::IsValid() {
switch (mode) {
case(ONENODE):
return imgComm->OneNodeValid();
case(ICET):
return imgComm->IceTValid();
}
};
//! begin frame
void Compositor_VisIt::BeginFrame() {
switch (mode) {
case(ONENODE):
imgComm->OneNodeInit(W, H);
break;
case(ICET):
imgComm->IceTInit(W, H);
break;
}
};
//! end frame
void Compositor_VisIt::EndFrame() {
switch (mode) {
case(ONENODE):
imgComm->OneNodeComposite(rgba);
break;
case(ICET):
imgComm->IceTComposite(rgba);
break;
}
};
//! upload tile
void Compositor_VisIt::SetTile(Tile &tile) {
// convert to tile data format
// (because of the formatting issues)
float* ptr = new float[4 * tile.tileDim[0] * tile.tileDim[1]];
for (auto i = 0; i < tile.tileSize; ++i) {
ptr[4 * i + 0] = tile.r[i];
ptr[4 * i + 1] = tile.g[i];
ptr[4 * i + 2] = tile.b[i];
ptr[4 * i + 3] = tile.a[i];
}
tileBufferList.push_back(ptr);
/* x0 x1 y0 y1 */
int e[4] = {(int)tile.region[0], (int)tile.region[2],
(int)tile.region[1], (int)tile.region[3]};
// set tile
switch (mode) {
case(ONENODE):
imgComm->OneNodeSetTile(ptr, e, *(tile.z));
break;
case(ICET):
imgComm->IceTSetTile(ptr, e, *(tile.z));
break;
}
};
};
};
};
| 28.33 | 70 | 0.523473 | [
"vector"
] |
940d623a541f05ebcae2fb92bd06317254e6d77a | 12,072 | cpp | C++ | ogs6THMC/ChemLib/chemReductionKin.cpp | Yonghui56/NCP | 29680706b7d8dd9b78d51c10d4a36799eb24c38f | [
"BSD-4-Clause"
] | null | null | null | ogs6THMC/ChemLib/chemReductionKin.cpp | Yonghui56/NCP | 29680706b7d8dd9b78d51c10d4a36799eb24c38f | [
"BSD-4-Clause"
] | 1 | 2016-07-08T03:44:02.000Z | 2016-07-08T08:59:45.000Z | ogs6THMC/ChemLib/chemReductionKin.cpp | Yonghui56/NCP | 29680706b7d8dd9b78d51c10d4a36799eb24c38f | [
"BSD-4-Clause"
] | null | null | null | /**
* Copyright (c) 2012, OpenGeoSys Community (http://www.opengeosys.com)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.com/LICENSE.txt
*
*
* \file chemReductionKin.cpp
*
* Created on 2012-08-23 by Haibing Shao
*/
#include "chemReductionKin.h"
#include "logog.hpp"
namespace ogsChem
{
chemReductionKin::chemReductionKin(BaseLib::OrderedMap<std::string, ogsChem::ChemComp*> & map_chemComp,
std::vector<ogsChem::chemReactionKin*> & list_kin_reactions)
: _list_kin_reactions(list_kin_reactions)
{
// by default, the class is not yet initialized
isInitialized = false;
if ( map_chemComp.size() > 0 && _list_kin_reactions.size() > 0 )
{ // if there are reactions.
// cout how many mobile and how many immobile components
countComp(map_chemComp);
// make stoichiometric matrix
buildStoi(map_chemComp, list_kin_reactions);
// calculate the reduction parameters
update_reductionScheme();
// flip the initialization flag
isInitialized = true;
}
}
chemReductionKin::~chemReductionKin()
{}
void chemReductionKin::buildStoi(BaseLib::OrderedMap<std::string, ogsChem::ChemComp*> & map_chemComp,
std::vector<ogsChem::chemReactionKin*> & list_kin_reactions)
{
size_t i,j, tmp_idx;
double tmp_stoi;
std::string tmp_str;
BaseLib::OrderedMap<std::string, ogsChem::ChemComp*>::iterator tmp_Comp;
// obtain the size info
_I = map_chemComp.size();
_J = list_kin_reactions.size();
// creat the memory for Stoi matrix
_matStoi = LocalMatrix::Zero(_I, _J);
// based on the reactions, fill in the stoi matrix
// loop over all reactions
for ( j=0; j < list_kin_reactions.size(); j++ )
{ // for each reaction
// find each participating components
for ( i=0; i < list_kin_reactions[j]->get_vecCompNames().size(); i++ ){
tmp_str = list_kin_reactions[j]->get_vecCompNames()[i];
tmp_Comp = map_chemComp.find(tmp_str);
tmp_idx = tmp_Comp->second->getIndex();
// kinetic reactions, no basis species
// treat them as normal reactions
tmp_stoi = list_kin_reactions[j]->get_vecStoi()[i];
// and put them into Stoi matrix
_matStoi(tmp_idx,j) = tmp_stoi;
} // end of for i
} // end of for j
#ifdef _DEBUG
// debugging--------------------------
std::cout << "Stoichiometric Matrix S: " << std::endl;
std::cout << _matStoi << std::endl;
// end of debugging-------------------
#endif
}
void chemReductionKin::update_reductionScheme(void)
{
// devide mobile and immobile parts
// S1 =S(1:I,:);
_matS_1 = _matStoi.topRows( _I_mob );
// S2 =S(I+1:length(C),:);
_matS_2 = _matStoi.bottomRows( _I_min );
// reveal the rank of S1 and S2
Eigen::FullPivLU<LocalMatrix> lu_decomp_S1(_matS_1);
_mat_s_1 = lu_decomp_S1.image(_matS_1);
Eigen::FullPivLU<LocalMatrix> lu_decomp_S2(_matS_2);
_mat_s_2 = lu_decomp_S2.image(_matS_2);
#ifdef _DEBUG
std::cout << "_mat_S_1: " << std::endl;
std::cout << _matS_1 << std::endl;
std::cout << "_mat_S_2: " << std::endl;
std::cout << _matS_2 << std::endl;
std::cout << "_mat_s_1: " << std::endl;
std::cout << _mat_s_1 << std::endl;
std::cout << "_mat_s_2: " << std::endl;
std::cout << _mat_s_2 << std::endl;
#endif
// Calculate the s1T = S_i^T matrix consisting of a max set of linearly
// independent columns that are orthogonal to each column of S_i^*.
// s1T = orthcomp(s1);
_matS_1_ast = orthcomp( _mat_s_1 );
// s2T = orthcomp(s2);
_matS_2_ast = orthcomp( _mat_s_2 );
#ifdef _DEBUG
std::cout << "s_1*: " << std::endl;
std::cout << _matS_1_ast << std::endl;
std::cout << "s_2*: " << std::endl;
std::cout << _matS_2_ast << std::endl;
#endif
// now store the corresponding size
this->_n_eta_mob = _matS_1_ast.cols();
this->_n_eta_immob = _matS_2_ast.cols();
this->_n_xi_mob = _mat_s_1.cols();
this->_n_xi_immob = _mat_s_2.cols();
this->_n_eta = _n_eta_mob + _n_eta_immob;
this->_n_xi = _n_xi_mob + _n_xi_immob;
// now calculated A1 and A2
// _matA1 = ( _mat_s_1.transpose() * _mat_s_1 ).fullPivHouseholderQr().solve(_mat_s_1.transpose()) * _matS_1 ;
// _matA2 = ( _mat_s_2.transpose() * _mat_s_2 ).fullPivHouseholderQr().solve(_mat_s_2.transpose()) * _matS_2 ;
_matA1 = ( _mat_s_1.transpose() * _mat_s_1 ).fullPivHouseholderQr().solve(_mat_s_1.transpose() * _matS_1);
_matA2 = ( _mat_s_2.transpose() * _mat_s_2 ).fullPivHouseholderQr().solve(_mat_s_2.transpose() * _matS_2);
#ifdef _DEBUG
std::cout << "A_1: " << std::endl;
std::cout << _matA1 << std::endl;
std::cout << "A_2: " << std::endl;
std::cout << _matA2 << std::endl;
#endif
_mat_c_mob_2_eta_mob = ( _matS_1_ast.transpose() * _matS_1_ast ).fullPivHouseholderQr().solve(_matS_1_ast.transpose());
_mat_c_immob_2_eta_immob = ( _matS_2_ast.transpose() * _matS_2_ast ).fullPivHouseholderQr().solve(_matS_2_ast.transpose());
_mat_c_mob_2_xi_mob = ( _mat_s_1.transpose() * _mat_s_1 ).fullPivHouseholderQr().solve(_mat_s_1.transpose());
_mat_c_immob_2_xi_immob = ( _mat_s_2.transpose() * _mat_s_2 ).fullPivHouseholderQr().solve(_mat_s_2.transpose());
#ifdef _DEBUG
std::cout << "_mat_c_mob_2_eta_mob: " << std::endl;
std::cout << _mat_c_mob_2_eta_mob << std::endl;
std::cout << "_mat_c_immob_2_eta_immob: " << std::endl;
std::cout << _mat_c_immob_2_eta_immob << std::endl;
std::cout << "_mat_c_mob_2_xi_mob: " << std::endl;
std::cout << _mat_c_mob_2_xi_mob << std::endl;
std::cout << "_mat_c_immob_2_xi_immob: " << std::endl;
std::cout << _mat_c_immob_2_xi_immob << std::endl;
#endif
}
LocalMatrix chemReductionKin::orthcomp( LocalMatrix & inMat )
{
// initialize it so that they have the same dimension
LocalMatrix outMat;
Eigen::FullPivLU<LocalMatrix> lu_decomp(inMat.transpose());
outMat = lu_decomp.kernel();
// notice that if the kernel returns a matrix with dimension zero,
// then the returned matrix will be a column-vector filled with zeros
// therefore we do a safety check here, and set the number of columns to zero
if ( outMat.cols() == 1 && outMat.col(0).norm() == 0.0 )
outMat = LocalMatrix::Zero(inMat.rows(), 0);
return outMat;
}
void chemReductionKin::countComp(BaseLib::OrderedMap<std::string, ogsChem::ChemComp*> & map_chemComp)
{
_I_mob = 0;
_I_sorp= 0;
_I_min = 0;
BaseLib::OrderedMap<std::string, ogsChem::ChemComp*>::iterator it;
for( it = map_chemComp.begin(); it != map_chemComp.end(); it++ )
{
switch ( it->second->getCompType() )
{
case ogsChem::AQ_PHASE_COMP:
_I_mob++;
break;
case ogsChem::SORPTION_COMP:
_I_sorp++;
break;
case ogsChem::MIN_PHASE_COMP:
_I_min++;
break;
// case ogsChem::KIN_COMP:
// _I_kin++;
// break;
default:
_I_min++;
break;
}
}
}
void chemReductionKin::Conc2EtaXi(ogsChem::LocalVector &local_conc,
ogsChem::LocalVector &local_eta_mob,
ogsChem::LocalVector &local_eta_immob,
ogsChem::LocalVector &local_xi_mob,
ogsChem::LocalVector &local_xi_immob )
{
// declare local temp variable
ogsChem::LocalVector local_c_mob, local_c_immob;
// divide c1 and c2
local_c_mob = local_conc.topRows( this->_I_mob );
local_c_immob = local_conc.bottomRows( this->_I_sorp + this->_I_min );
// convert eta_mob and xi_mob
local_eta_mob = _mat_c_mob_2_eta_mob * local_c_mob;
local_xi_mob = _mat_c_mob_2_xi_mob * local_c_mob;
// convert eta_immob and xi_immob
local_eta_immob = _mat_c_immob_2_eta_immob * local_c_immob;
local_xi_immob = _mat_c_immob_2_xi_immob * local_c_immob;
}
void chemReductionKin::EtaXi2Conc(ogsChem::LocalVector &local_eta_mob,
ogsChem::LocalVector &local_eta_immob,
ogsChem::LocalVector &local_xi_mob,
ogsChem::LocalVector &local_xi_immob,
ogsChem::LocalVector &local_conc )
{
// declare local temp variable
ogsChem::LocalVector local_c_mob, local_c_immob;
local_c_mob = _mat_s_1 * local_xi_mob + _matS_1_ast * local_eta_mob;
local_c_immob = _mat_s_2 * local_xi_immob + _matS_2_ast * local_eta_immob;
local_conc.topRows( this->_I_mob ) = local_c_mob;
local_conc.bottomRows( this->_I_sorp + this->_I_min ) = local_c_immob;
// testing if the non-negative stablilization will help?
for (int i=0; i < local_conc.size(); i++)
{
if ( local_conc(i) < 0.0 )
local_conc(i) = 1.0e-20;
}
// end of testing
}
void chemReductionKin::Calc_Xi_mob_Rate(ogsChem::LocalVector &local_eta_mob,
ogsChem::LocalVector &local_eta_immob,
ogsChem::LocalVector &local_xi_mob,
ogsChem::LocalVector &local_xi_immob,
ogsChem::LocalVector &xi_mob_rate )
{
size_t i;
// the size of vec_rates is equal to the number of kinetic equations
ogsChem::LocalVector vec_rates = ogsChem::LocalVector::Zero(_J);
// the local temp concentration vector
ogsChem::LocalVector vec_conc = ogsChem::LocalVector::Zero(_I);
// first convert these eta and xi to concentrations
EtaXi2Conc( local_eta_mob,
local_eta_immob,
local_xi_mob,
local_xi_immob,
vec_conc );
// then calculate the rates and fill them in the rate vector
for ( i=0; i < _J; i++ )
{
// get to the particular kin equation and calculate its rate
this->_list_kin_reactions[i]->calcReactionRate( vec_conc );
vec_rates(i) = this->_list_kin_reactions[i]->getRate();
}
// multiply the rate vector with the A matrix to get rate for xi_mob and xi_immob
xi_mob_rate = _matA1 * vec_rates;
}
void chemReductionKin::Calc_Xi_immob_Rate(ogsChem::LocalVector &local_eta_mob,
ogsChem::LocalVector &local_eta_immob,
ogsChem::LocalVector &local_xi_mob,
ogsChem::LocalVector &local_xi_immob,
ogsChem::LocalVector &xi_immob_rate )
{
size_t i;
// the size of vec_rates is equal to the number of kinetic equations
ogsChem::LocalVector vec_rates = ogsChem::LocalVector::Zero(_J);
// the local temp concentration vector
ogsChem::LocalVector vec_conc = ogsChem::LocalVector::Zero(_I);
// first convert these eta and xi to concentrations
EtaXi2Conc( local_eta_mob,
local_eta_immob,
local_xi_mob,
local_xi_immob,
vec_conc );
// then calculate the rates and fill them in the rate vector
for ( i=0; i < _J; i++ )
{
// get to the particular kin equation and calculate its rate
this->_list_kin_reactions[i]->calcReactionRate( vec_conc );
vec_rates(i) = this->_list_kin_reactions[i]->getRate();
}
// multiply the rate vector with the A matrix to get rate for xi_mob and xi_immob
xi_immob_rate = _matA2 * vec_rates;
}
void chemReductionKin::Calc_Xi_Rate(ogsChem::LocalVector &local_eta_mob,
ogsChem::LocalVector &local_eta_immob,
ogsChem::LocalVector &local_xi_mob,
ogsChem::LocalVector &local_xi_immob,
ogsChem::LocalVector &xi_mob_rate,
ogsChem::LocalVector &xi_immob_rate)
{
size_t i;
// the size of vec_rates is equal to the number of kinetic equations
ogsChem::LocalVector vec_rates = ogsChem::LocalVector::Zero(_J);
// the local temp concentration vector
ogsChem::LocalVector vec_conc = ogsChem::LocalVector::Zero(_I);
// first convert these eta and xi to concentrations
EtaXi2Conc( local_eta_mob,
local_eta_immob,
local_xi_mob,
local_xi_immob,
vec_conc );
// then calculate the rates and fill them in the rate vector
for ( i=0; i < _J; i++ )
{
// get to the particular kin equation and calculate its rate
this->_list_kin_reactions[i]->calcReactionRate( vec_conc );
vec_rates(i) = this->_list_kin_reactions[i]->getRate();
}
// multiply the rate vector with the A matrix to get rate for xi_mob and xi_immob
xi_mob_rate = _matA1 * vec_rates;
xi_immob_rate = _matA2 * vec_rates;
}
} // end of namespace
| 33.626741 | 128 | 0.675861 | [
"vector"
] |
9410794ab53db966821305f6e6420870fca78418 | 1,379 | cpp | C++ | main.cpp | soda92/test-libcurl | 989994cb8b11c95fed5c78099114b479fb77ac8c | [
"MIT"
] | null | null | null | main.cpp | soda92/test-libcurl | 989994cb8b11c95fed5c78099114b479fb77ac8c | [
"MIT"
] | null | null | null | main.cpp | soda92/test-libcurl | 989994cb8b11c95fed5c78099114b479fb77ac8c | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <fstream>
#include <curl/curl.h>
// #include <filesystem>
#include <iostream>
// #include <format>
size_t writefunc(void *ptr, size_t size, size_t nmemb, std::string *string)
{
string->append(static_cast<char *>(ptr), size * nmemb);
return size * nmemb;
}
void write_callback(void *data, size_t size, size_t nmemb, void *ptr)
{
printf("%d %d\n", size, nmemb);
}
int main(int argc, char **argv)
{
CURL *handle;
/* global initialization */
int rc = curl_global_init(CURL_GLOBAL_ALL);
if (rc)
return rc;
/* initialization of easy handle */
handle = curl_easy_init();
if (!handle)
{
curl_global_cleanup();
return CURLE_OUT_OF_MEMORY;
}
curl_easy_setopt(handle, CURLOPT_URL, "ftp://127.0.0.1/lamp_sample/");
curl_easy_setopt(handle, CURLOPT_USERNAME, "user");
curl_easy_setopt(handle, CURLOPT_PASSWORD, "12345");
// curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, "NLST");
curl_easy_setopt(handle, CURLOPT_DIRLISTONLY, 1L);
printf("%d\n", argc);
if (argc > 1)
{
curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
}
curl_easy_setopt(handle, CURLOPT_NOPROXY, "*");
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_callback);
rc = curl_easy_perform(handle);
curl_easy_cleanup(handle);
return 0;
}
| 25.072727 | 75 | 0.6657 | [
"vector"
] |
941527601f01abfefaf0f7cd402b5e9bfffa257f | 71 | hpp | C++ | src/boost_geometry_strategies_spherical_side_by_cross_track.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_geometry_strategies_spherical_side_by_cross_track.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_geometry_strategies_spherical_side_by_cross_track.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/geometry/strategies/spherical/side_by_cross_track.hpp>
| 35.5 | 70 | 0.859155 | [
"geometry"
] |
9416ed2673fa049679d249ceaf51cff5a238ca98 | 13,326 | cpp | C++ | tf2_src/game/server/tf/tf_ammo_pack.cpp | IamIndeedGamingAsHardAsICan03489/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | tf2_src/game/server/tf/tf_ammo_pack.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | null | null | null | tf2_src/game/server/tf/tf_ammo_pack.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "tf_ammo_pack.h"
#include "tf_shareddefs.h"
#include "ammodef.h"
#include "tf_gamerules.h"
#include "explode.h"
#include "tf_gamestats.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//----------------------------------------------
extern void SendProxy_FuncRotatingAngle( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID);
// Network table.
IMPLEMENT_SERVERCLASS_ST( CTFAmmoPack, DT_AmmoPack )
SendPropVector( SENDINFO( m_vecInitialVelocity ), -1, SPROP_NOSCALE ),
SendPropExclude( "DT_BaseEntity", "m_angRotation" ),
SendPropAngle( SENDINFO_VECTORELEM(m_angRotation, 0), 7, SPROP_CHANGES_OFTEN, SendProxy_FuncRotatingAngle ),
SendPropAngle( SENDINFO_VECTORELEM(m_angRotation, 1), 7, SPROP_CHANGES_OFTEN, SendProxy_FuncRotatingAngle ),
SendPropAngle( SENDINFO_VECTORELEM(m_angRotation, 2), 7, SPROP_CHANGES_OFTEN, SendProxy_FuncRotatingAngle ),
END_SEND_TABLE()
BEGIN_DATADESC( CTFAmmoPack )
DEFINE_THINKFUNC( FlyThink ),
DEFINE_ENTITYFUNC( PackTouch ),
END_DATADESC();
LINK_ENTITY_TO_CLASS( tf_ammo_pack, CTFAmmoPack );
PRECACHE_REGISTER( tf_ammo_pack );
#define HALLOWEEN_MODEL "models/props_halloween/pumpkin_loot.mdl"
#define CHRISTMAS_MODEL "models/items/tf_gift.mdl"
void CTFAmmoPack::Spawn( void )
{
Precache();
SetModel( STRING( GetModelName() ) );
BaseClass::Spawn();
SetNextThink( gpGlobals->curtime + 0.75f );
SetThink( &CTFAmmoPack::FlyThink );
SetTouch( &CTFAmmoPack::PackTouch );
m_flCreationTime = gpGlobals->curtime;
// no pickup until flythink
m_bAllowOwnerPickup = false;
m_bNoPickup = false;
m_bHealthInstead = false;
m_bEmptyPack = false;
m_bObjGib = false;
m_flBonusScale = 1.f;
// no ammo to start
memset( m_iAmmo, 0, sizeof(m_iAmmo) );
// Die in 30 seconds
SetContextThink( &CBaseEntity::SUB_Remove, gpGlobals->curtime + 30, "DieContext" );
if ( IsX360() )
{
RemoveEffects( EF_ITEM_BLINK );
}
}
void CTFAmmoPack::Precache( void )
{
PrecacheModel( "models/items/ammopack_medium.mdl" );
if ( TFGameRules() )
{
if ( TFGameRules()->IsHolidayActive( kHoliday_Halloween ) )
{
PrecacheModel( HALLOWEEN_MODEL );
PrecacheScriptSound( "Halloween.PumpkinDrop" );
PrecacheScriptSound( "Halloween.PumpkinPickup" );
}
else if ( TFGameRules()->IsHolidayActive( kHoliday_Christmas ) )
{
PrecacheModel( CHRISTMAS_MODEL );
PrecacheScriptSound( "Christmas.GiftDrop" );
PrecacheScriptSound( "Christmas.GiftPickup" );
}
}
}
CTFAmmoPack *CTFAmmoPack::Create( const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner, const char *pszModelName )
{
CTFAmmoPack *pAmmoPack = static_cast<CTFAmmoPack*>( CBaseAnimating::CreateNoSpawn( "tf_ammo_pack", vecOrigin, vecAngles, pOwner ) );
if ( pAmmoPack )
{
pAmmoPack->SetModelName( AllocPooledString( pszModelName ) );
DispatchSpawn( pAmmoPack );
}
return pAmmoPack;
}
ConVar tf_weapon_ragdoll_velocity_min( "tf_weapon_ragdoll_velocity_min", "100", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
ConVar tf_weapon_ragdoll_velocity_max( "tf_weapon_ragdoll_velocity_max", "150", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
ConVar tf_weapon_ragdoll_maxspeed( "tf_weapon_ragdoll_maxspeed", "300", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
void CTFAmmoPack::InitWeaponDrop( CTFPlayer *pPlayer, CTFWeaponBase *pWeapon, int nSkin, bool bEmpty, bool bIsSuicide )
{
if ( !bEmpty )
{
// Might be a holiday pack.
if ( !bIsSuicide && ( TFGameRules()->IsHolidayActive( kHoliday_Halloween ) || TFGameRules()->IsHolidayActive( kHoliday_TFBirthday ) ) )
{
float frand = (float)rand() / VALVE_RAND_MAX;
if ( frand < 0.3f )
{
MakeHolidayPack();
}
}
else if ( !bIsSuicide && TFGameRules()->IsHolidayActive( kHoliday_Christmas ) )
{
MakeHolidayPack();
}
// Fill the ammo pack with unused player ammo, if out add a minimum amount.
int iPrimary = Max( 5, pPlayer->GetAmmoCount( TF_AMMO_PRIMARY ) );
int iSecondary = Max( 5, pPlayer->GetAmmoCount( TF_AMMO_SECONDARY ) );
int iMetal = Clamp( pPlayer->GetAmmoCount( TF_AMMO_METAL ), 5 , 100 );
// Fill up the ammo pack.
GiveAmmo( iPrimary, TF_AMMO_PRIMARY ); // Gets recalculated in PackTouch
GiveAmmo( iSecondary, TF_AMMO_SECONDARY ); // Gets recalculated in PackTouch
GiveAmmo( iMetal, TF_AMMO_METAL );
SetHealthInstead( pWeapon->GetWeaponID() == TF_WEAPON_LUNCHBOX && pPlayer->IsPlayerClass( TF_CLASS_HEAVYWEAPONS ) );
}
else
{
// This pack has nothing in it.
MakeEmptyPack();
}
Vector vecRight, vecUp;
AngleVectors( EyeAngles(), NULL, &vecRight, &vecUp );
// Calculate the initial impulse on the weapon.
Vector vecImpulse( 0.0f, 0.0f, 0.0f );
vecImpulse += vecUp * random->RandomFloat( -0.25, 0.25 );
vecImpulse += vecRight * random->RandomFloat( -0.25, 0.25 );
VectorNormalize( vecImpulse );
vecImpulse *= random->RandomFloat( tf_weapon_ragdoll_velocity_min.GetFloat(), tf_weapon_ragdoll_velocity_max.GetFloat() );
vecImpulse += GetAbsVelocity();
// Cap the impulse.
float flSpeed = vecImpulse.Length();
if ( flSpeed > tf_weapon_ragdoll_maxspeed.GetFloat() )
{
VectorScale( vecImpulse, tf_weapon_ragdoll_maxspeed.GetFloat() / flSpeed, vecImpulse );
}
if ( VPhysicsGetObject() )
{
// We can probably remove this when the mass on the weapons is correct!
VPhysicsGetObject()->SetMass( 25.0f );
AngularImpulse angImpulse( 0, random->RandomFloat( 0, 100 ), 0 );
VPhysicsGetObject()->SetVelocityInstantaneous( &vecImpulse, &angImpulse );
}
SetInitialVelocity( vecImpulse );
m_nSkin = nSkin; // Copy the skin from the model we're copying
// Give the ammo pack some health, so that trains can destroy it.
SetCollisionGroup( COLLISION_GROUP_DEBRIS );
m_takedamage = DAMAGE_YES;
SetHealth( 900 );
SetBodygroup( 1, 1 );
}
void CTFAmmoPack::MakeHolidayPack( void )
{
// don't want special ammo packs during a competitive match
if ( TFGameRules()->IsMatchTypeCompetitive() )
return;
// Only do this on the halloween maps.
if ( TFGameRules()->IsHolidayActive( kHoliday_Halloween )
&& TFGameRules()->IsHolidayMap( kHoliday_Halloween )
&& !TFGameRules()->IsHalloweenScenario( CTFGameRules::HALLOWEEN_SCENARIO_HIGHTOWER ) )
{
m_PackType = AP_HALLOWEEN;
SetModelIndex( modelinfo->GetModelIndex( HALLOWEEN_MODEL ) );
SetContextThink( &CTFAmmoPack::DropSoundThink, gpGlobals->curtime + 0.1f, "DROP_SOUND_THINK" );
}
else if ( TFGameRules()->ShouldMakeChristmasAmmoPack() )
{
m_PackType = AP_CHRISTMAS;
SetModelIndex( modelinfo->GetModelIndex( CHRISTMAS_MODEL ) );
SetContextThink( &CTFAmmoPack::DropSoundThink, gpGlobals->curtime + 0.1f, "DROP_SOUND_THINK" );
}
}
void CTFAmmoPack::SetBonusScale( float flBonusScale /*= 1.f*/ )
{
m_flBonusScale = flBonusScale;
}
void CTFAmmoPack::SetInitialVelocity( Vector &vecVelocity )
{
if ( m_PackType != AP_NORMAL )
{
// Unusual physics for the halloween/christmas packs to make them noticable.
SetMoveType( MOVETYPE_FLYGRAVITY );
SetAbsVelocity( vecVelocity * 2.f + Vector(0,0,200) );
SetAbsAngles( QAngle(0,0,0) );
UseClientSideAnimation();
ResetSequence( LookupSequence("idle") );
}
m_vecInitialVelocity = vecVelocity;
}
void CTFAmmoPack::SetPickupThinkTime( float flNewThinkTime )
{
SetNextThink( gpGlobals->curtime + flNewThinkTime );
}
int CTFAmmoPack::GiveAmmo( int iCount, int iAmmoType )
{
if (iAmmoType == -1 || iAmmoType >= TF_AMMO_COUNT )
{
Msg("ERROR: Attempting to give unknown ammo type (%d)\n", iAmmoType);
return 0;
}
m_iAmmo[iAmmoType] = iCount;
return iCount;
}
void CTFAmmoPack::DropSoundThink( void )
{
if ( m_PackType == AP_HALLOWEEN )
{
EmitSound( "Halloween.PumpkinDrop" );
}
else if ( m_PackType == AP_CHRISTMAS )
{
EmitSound( "Christmas.GiftDrop" );
}
}
void CTFAmmoPack::FlyThink( void )
{
m_bAllowOwnerPickup = true;
m_bNoPickup = false;
}
void CTFAmmoPack::PackTouch( CBaseEntity *pOther )
{
Assert( pOther );
if ( pOther->IsWorld() && ( m_PackType != AP_NORMAL ) )
{
Vector absVel = GetAbsVelocity();
SetAbsVelocity( Vector( 0,0,absVel.z ) );
return;
}
if( !pOther->IsPlayer() )
return;
if( !pOther->IsAlive() )
return;
if ( m_bNoPickup )
return;
//Don't let the person who threw this ammo pick it up until it hits the ground.
//This way we can throw ammo to people, but not touch it as soon as we throw it ourselves
if( GetOwnerEntity() == pOther && m_bAllowOwnerPickup == false )
return;
CTFPlayer *pPlayer = ToTFPlayer( pOther );
Assert( pPlayer );
if ( m_bEmptyPack )
{
// Since we drop our empty packs as fakeouts, we never pick up our own empties while stealthed.
if ( GetOwnerEntity() == pOther && ( pPlayer->m_Shared.IsStealthed() ||
pPlayer->m_Shared.InCond( TF_COND_STEALTHED_BLINK ) ) )
return;
// "Empty" packs can be picked up.
// Packs that can't be grabbed don't fit the expectations of the player.
GiveAmmo( 1, TF_AMMO_PRIMARY );
UTIL_Remove( this );
return;
}
// The sandwich gives health instead of ammo
if ( m_bHealthInstead )
{
// Let the sandwich fall to the ground for a bit so that people see it
if ( !m_bAllowOwnerPickup )
return;
// Scouts get a little more, as a reference to the scout movie
int iAmount = ( pPlayer->IsPlayerClass(TF_CLASS_SCOUT) ) ? 75 : 50;
pPlayer->TakeHealth( iAmount, DMG_GENERIC );
IGameEvent *event = gameeventmanager->CreateEvent( "player_healonhit" );
if ( event )
{
event->SetInt( "amount", iAmount );
event->SetInt( "entindex", pPlayer->entindex() );
event->SetInt( "weapon_def_index", INVALID_ITEM_DEF_INDEX );
gameeventmanager->FireEvent( event );
}
event = gameeventmanager->CreateEvent( "player_stealsandvich" );
if ( event )
{
if ( ToTFPlayer( GetOwnerEntity() ) )
{
event->SetInt( "owner", ToTFPlayer( GetOwnerEntity() )->GetUserID() );
}
event->SetInt( "target", pPlayer->GetUserID() );
gameeventmanager->FireEvent( event );
}
UTIL_Remove( this );
return;
}
float flAmmoRatio = 0.5f;
int iMaxPrimary = pPlayer->GetMaxAmmo(TF_AMMO_PRIMARY);
GiveAmmo( ceil( iMaxPrimary * flAmmoRatio ), TF_AMMO_PRIMARY );
int iMaxSecondary = pPlayer->GetMaxAmmo(TF_AMMO_SECONDARY);
GiveAmmo( ceil( iMaxSecondary * flAmmoRatio ), TF_AMMO_SECONDARY );
int iAmmoTaken = 0;
for ( int i=0;i<TF_AMMO_COUNT;i++ )
{
int iAmmoGiven = pPlayer->GiveAmmo( m_iAmmo[i], i );
if ( iAmmoGiven > 0 && i == TF_AMMO_METAL && m_bObjGib && pPlayer->IsPlayerClass( TF_CLASS_ENGINEER ) )
{
pPlayer->AwardAchievement( ACHIEVEMENT_TF_ENGINEER_WASTE_METAL_GRIND, iAmmoGiven );
}
iAmmoTaken += iAmmoGiven;
}
// give them a chunk of cloak power
if ( pPlayer->m_Shared.AddToSpyCloakMeter( 100.0f * flAmmoRatio ) )
{
iAmmoTaken++;
}
if ( pPlayer->AddToSpyKnife( 100.0f * flAmmoRatio, false ) )
{
iAmmoTaken++;
}
// Add Charge if applicable
int iAmmoIsCharge = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER( pPlayer, iAmmoIsCharge, ammo_gives_charge );
if ( iAmmoIsCharge )
{
float flCurrentCharge = pPlayer->m_Shared.GetDemomanChargeMeter();
if ( flCurrentCharge < 100.0f )
{
pPlayer->m_Shared.SetDemomanChargeMeter( flCurrentCharge + flAmmoRatio * 100.0f );
iAmmoTaken++;
}
}
if ( pPlayer->IsPlayerClass( TF_CLASS_ENGINEER ) )
{
int iMaxGrenades1 = pPlayer->GetMaxAmmo( TF_AMMO_GRENADES1 );
iAmmoTaken += pPlayer->GiveAmmo( ceil(iMaxGrenades1 * flAmmoRatio), TF_AMMO_GRENADES1 );
}
if ( m_PackType == AP_HALLOWEEN )
{
// Send a message for the achievement tracking.
IGameEvent *event = gameeventmanager->CreateEvent( "halloween_pumpkin_grab" );
if ( event )
{
event->SetInt( "userid", pPlayer->GetUserID() );
gameeventmanager->FireEvent( event );
}
float flBuffDuration = m_flBonusScale * 3.f;
if ( !pPlayer->m_Shared.InCond( TF_COND_CRITBOOSTED_PUMPKIN ) || (pPlayer->m_Shared.GetConditionDuration(TF_COND_CRITBOOSTED_PUMPKIN) < flBuffDuration) )
{
pPlayer->m_Shared.AddCond( TF_COND_CRITBOOSTED_PUMPKIN, flBuffDuration );
}
pPlayer->EmitSound( "Halloween.PumpkinPickup" );
m_PackType = AP_NORMAL; // Touch once.
iAmmoTaken++;
}
else if ( m_PackType == AP_CHRISTMAS )
{
// Send a message for the achievement tracking.
IGameEvent *event = gameeventmanager->CreateEvent( "christmas_gift_grab" );
if ( event )
{
event->SetInt( "userid", pPlayer->GetUserID() );
gameeventmanager->FireEvent( event );
}
pPlayer->EmitSound( "Christmas.GiftPickup" );
m_PackType = AP_NORMAL; // Touch once.
iAmmoTaken++;
}
if ( iAmmoTaken > 0 )
{
CTF_GameStats.Event_PlayerAmmokitPickup( pPlayer );
IGameEvent * event = gameeventmanager->CreateEvent( "item_pickup" );
if( event )
{
event->SetInt( "userid", pPlayer->GetUserID() );
event->SetString( "item", "tf_ammo_pack" );
gameeventmanager->FireEvent( event );
}
UTIL_Remove( this );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
unsigned int CTFAmmoPack::PhysicsSolidMaskForEntity( void ) const
{
return BaseClass::PhysicsSolidMaskForEntity() | CONTENTS_DEBRIS;
}
| 29.745536 | 155 | 0.703287 | [
"vector",
"model"
] |
941f76481b9e408cc58c44e609002a30f2cbc958 | 3,340 | hpp | C++ | geometry/mercator.hpp | dualword/organicmaps | c0a73aea4835517edef3b5a7d68a3a50d55a4471 | [
"Apache-2.0"
] | 3,062 | 2021-04-09T16:51:55.000Z | 2022-03-31T21:02:51.000Z | geometry/mercator.hpp | dualword/organicmaps | c0a73aea4835517edef3b5a7d68a3a50d55a4471 | [
"Apache-2.0"
] | 1,396 | 2021-04-08T07:26:49.000Z | 2022-03-31T20:27:46.000Z | geometry/mercator.hpp | dualword/organicmaps | c0a73aea4835517edef3b5a7d68a3a50d55a4471 | [
"Apache-2.0"
] | 242 | 2021-04-10T17:10:46.000Z | 2022-03-31T13:41:07.000Z | #pragma once
#include "geometry/latlon.hpp"
#include "geometry/point2d.hpp"
#include "geometry/rect2d.hpp"
#include "base/math.hpp"
namespace mercator
{
// Use to compare/match lat lon coordinates.
static double constexpr kPointEqualityEps = 1e-7;
struct Bounds
{
static double constexpr kMinX = -180.0;
static double constexpr kMaxX = 180.0;
static double constexpr kMinY = -180.0;
static double constexpr kMaxY = 180.0;
static double constexpr kRangeX = kMaxX - kMinX;
static double constexpr kRangeY = kMaxY - kMinY;
// The denominator is the Earth circumference at the Equator in meters.
// The value is a bit off for some reason; 40075160 seems to be correct.
static double constexpr kDegreesInMeter = 360.0 / 40008245.0;
static double constexpr kMetersInDegree = 40008245.0 / 360.0;
static m2::RectD FullRect()
{
return m2::RectD(kMinX, kMinY, kMaxX, kMaxY);
}
};
inline bool ValidLon(double d) { return base::Between(-180.0, 180.0, d); }
inline bool ValidLat(double d) { return base::Between(-90.0, 90.0, d); }
inline bool ValidX(double d) { return base::Between(Bounds::kMinX, Bounds::kMaxX, d); }
inline bool ValidY(double d) { return base::Between(Bounds::kMinY, Bounds::kMaxY, d); }
inline double ClampX(double d) { return base::Clamp(d, Bounds::kMinX, Bounds::kMaxX); }
inline double ClampY(double d) { return base::Clamp(d, Bounds::kMinY, Bounds::kMaxY); }
void ClampPoint(m2::PointD & pt);
double YToLat(double y);
double LatToY(double lat);
inline double XToLon(double x) { return x; }
inline double LonToX(double lon) { return lon; }
inline double MetersToMercator(double meters) { return meters * Bounds::kDegreesInMeter; }
inline double MercatorToMeters(double mercator) { return mercator * Bounds::kMetersInDegree; }
/// @name Get rect for center point (lon, lat) and dimensions in meters.
/// @return mercator rect.
m2::RectD MetersToXY(double lon, double lat, double lonMetersR, double latMetersR);
m2::RectD MetersToXY(double lon, double lat, double metersR);
m2::RectD RectByCenterXYAndSizeInMeters(double centerX, double centerY, double sizeX, double sizeY);
m2::RectD RectByCenterXYAndSizeInMeters(m2::PointD const & center, double size);
m2::RectD RectByCenterXYAndOffset(m2::PointD const & center, double offset);
m2::PointD GetSmPoint(m2::PointD const & pt, double lonMetersR, double latMetersR);
inline m2::PointD FromLatLon(double lat, double lon) { return m2::PointD(LonToX(lon), LatToY(lat)); }
inline m2::PointD FromLatLon(ms::LatLon const & point) { return FromLatLon(point.m_lat, point.m_lon); }
m2::RectD RectByCenterLatLonAndSizeInMeters(double lat, double lon, double size);
inline ms::LatLon ToLatLon(m2::PointD const & point) { return {YToLat(point.y), XToLon(point.x)}; }
/// Converts lat lon rect to mercator one.
m2::RectD FromLatLonRect(m2::RectD const & latLonRect);
m2::RectD ToLatLonRect(m2::RectD const & mercatorRect);
/// Calculates distance on Earth in meters between two mercator points.
double DistanceOnEarth(m2::PointD const & p1, m2::PointD const & p2);
/// Calculates area of a triangle on Earth in m² by three mercator points.
double AreaOnEarth(m2::PointD const & p1, m2::PointD const & p2, m2::PointD const & p3);
/// Calculates area on Earth in m².
double AreaOnEarth(m2::RectD const & mercatorRect);
} // namespace mercator
| 39.294118 | 103 | 0.741018 | [
"geometry"
] |
941f943627e7a55337d363e90eaf01df5aea440b | 3,037 | hpp | C++ | external_libs/link/include/ableton/link/Timeline.hpp | llloret/sp_link | b87ee622517fc68845b8f1d19c735c0e3bd05176 | [
"MIT"
] | null | null | null | external_libs/link/include/ableton/link/Timeline.hpp | llloret/sp_link | b87ee622517fc68845b8f1d19c735c0e3bd05176 | [
"MIT"
] | null | null | null | external_libs/link/include/ableton/link/Timeline.hpp | llloret/sp_link | b87ee622517fc68845b8f1d19c735c0e3bd05176 | [
"MIT"
] | 1 | 2021-02-22T11:37:41.000Z | 2021-02-22T11:37:41.000Z | /* Copyright 2016, Ableton AG, Berlin. 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 as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you would like to incorporate Link into a proprietary software application,
* please contact <link-devs@ableton.com>.
*/
#pragma once
#include <ableton/discovery/NetworkByteStreamSerializable.hpp>
#include <ableton/link/Beats.hpp>
#include <ableton/link/Tempo.hpp>
#include <cmath>
#include <cstdint>
#include <tuple>
namespace ableton
{
namespace link
{
// A tuple of (tempo, beats, time), with integral units
// based on microseconds. This type establishes a bijection between
// beats and wall time, given a valid tempo. It also serves as a
// payload entry.
struct Timeline
{
static const std::int32_t key = 'tmln';
static_assert(key == 0x746d6c6e, "Unexpected byte order");
Beats toBeats(const std::chrono::microseconds time) const
{
return beatOrigin + tempo.microsToBeats(time - timeOrigin);
}
std::chrono::microseconds fromBeats(const Beats beats) const
{
return timeOrigin + tempo.beatsToMicros(beats - beatOrigin);
}
friend bool operator==(const Timeline& lhs, const Timeline& rhs)
{
return std::tie(lhs.tempo, lhs.beatOrigin, lhs.timeOrigin)
== std::tie(rhs.tempo, rhs.beatOrigin, rhs.timeOrigin);
}
friend bool operator!=(const Timeline& lhs, const Timeline& rhs)
{
return !(lhs == rhs);
}
// Model the NetworkByteStreamSerializable concept
friend std::uint32_t sizeInByteStream(const Timeline& tl)
{
return discovery::sizeInByteStream(std::tie(tl.tempo, tl.beatOrigin, tl.timeOrigin));
}
template <typename It>
friend It toNetworkByteStream(const Timeline& tl, It out)
{
return discovery::toNetworkByteStream(
std::tie(tl.tempo, tl.beatOrigin, tl.timeOrigin), std::move(out));
}
template <typename It>
static std::pair<Timeline, It> fromNetworkByteStream(It begin, It end)
{
using namespace std;
using namespace discovery;
Timeline timeline;
auto result =
Deserialize<tuple<Tempo, Beats, chrono::microseconds>>::fromNetworkByteStream(
std::move(begin), std::move(end));
tie(timeline.tempo, timeline.beatOrigin, timeline.timeOrigin) = std::move(result.first);
return make_pair(std::move(timeline), std::move(result.second));
}
Tempo tempo;
Beats beatOrigin;
std::chrono::microseconds timeOrigin;
};
} // namespace link
} // namespace ableton
| 30.989796 | 92 | 0.718143 | [
"model"
] |
942ab36c2487f9252850c8422551fd84bfba5da7 | 1,081 | cpp | C++ | codeforces/div2/1471/C/C.cpp | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | 2 | 2015-08-18T09:51:19.000Z | 2019-01-29T03:18:10.000Z | codeforces/div2/1471/C/C.cpp | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | null | null | null | codeforces/div2/1471/C/C.cpp | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | null | null | null |
/* ========================================
* File Name : C.cpp
* Creation Date : 05-01-2021
* Last Modified : Út 5. ledna 2021, 17:38:07
* Created By : Karel Ha <mathemage@gmail.com>
* URL : https://codeforces.com/contest/1471/problem/C
* Points :
* Total : 1000
* Status : not submitted
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define RFOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define REP(I,N) FOR(I,0,N)
#define ALL(A) (A).begin(), (A).end()
#define REVALL(A) (A).rbegin(), (A).rend()
#define MSG(a) cerr << #a << " == " << (a) << endl;
const int CLEAN = -1;
const int UNDEF = -42;
int main() {
int t,n,m;
cin >> t;
while (t--) {
cin >> n >> m;
vector<int> k(n);
for (auto & ki : k) {
cin >> ki;
}
vector<int> c(m);
for (auto & ci : c) {
cin >> ci;
}
// cout << << end;
}
return 0;
}
| 24.022222 | 143 | 0.46161 | [
"vector"
] |
942cb888eb5a4325c1197d5d3e01900098e36849 | 231 | cpp | C++ | 1967-number-of-strings-that-appear-as-substrings-in-word/1967-number-of-strings-that-appear-as-substrings-in-word.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 1967-number-of-strings-that-appear-as-substrings-in-word/1967-number-of-strings-that-appear-as-substrings-in-word.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 1967-number-of-strings-that-appear-as-substrings-in-word/1967-number-of-strings-that-appear-as-substrings-in-word.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | class Solution {
public:
int numOfStrings(vector<string>& patterns, string word) {
int res=0;
for(string &x: patterns){
if(~word.find(x))
res++;
}
return res;
}
}; | 21 | 61 | 0.484848 | [
"vector"
] |
942e98f71ebf00d79b05ba3fc54355752b24064f | 11,173 | cc | C++ | ns-allinone-3.22/ns-3.22/src/lte/test/lte-test-interference.cc | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | null | null | null | ns-allinone-3.22/ns-3.22/src/lte/test/lte-test-interference.cc | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | null | null | null | ns-allinone-3.22/ns-3.22/src/lte/test/lte-test-interference.cc | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | 2 | 2018-06-06T14:10:23.000Z | 2020-04-07T17:20:55.000Z | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Manuel Requena <manuel.requena@cttc.es>
* Nicola Baldo <nbaldo@cttc.es>
*/
#include "ns3/simulator.h"
#include "ns3/log.h"
#include "ns3/string.h"
#include "ns3/double.h"
#include <ns3/enum.h>
#include "ns3/boolean.h"
#include "ns3/mobility-helper.h"
#include "ns3/lte-helper.h"
#include "ns3/ff-mac-scheduler.h"
#include "ns3/lte-enb-phy.h"
#include "ns3/lte-enb-net-device.h"
#include "ns3/lte-ue-phy.h"
#include "ns3/lte-ue-net-device.h"
#include "lte-test-interference.h"
#include "lte-test-sinr-chunk-processor.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("LteInterferenceTest");
void
LteTestDlSchedulingCallback (LteInterferenceTestCase *testcase, std::string path,
uint32_t frameNo, uint32_t subframeNo, uint16_t rnti,
uint8_t mcsTb1, uint16_t sizeTb1, uint8_t mcsTb2, uint16_t sizeTb2)
{
testcase->DlScheduling (frameNo, subframeNo, rnti, mcsTb1, sizeTb1, mcsTb2, sizeTb2);
}
void
LteTestUlSchedulingCallback (LteInterferenceTestCase *testcase, std::string path,
uint32_t frameNo, uint32_t subframeNo, uint16_t rnti,
uint8_t mcs, uint16_t sizeTb)
{
testcase->UlScheduling (frameNo, subframeNo, rnti, mcs, sizeTb);
}
/**
* TestSuite
*/
LteInterferenceTestSuite::LteInterferenceTestSuite ()
: TestSuite ("lte-interference", SYSTEM)
{
AddTestCase (new LteInterferenceTestCase ("d1=3000, d2=6000", 3000.000000, 6000.000000, 3.844681, 1.714583, 0.761558, 0.389662, 6, 4), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=10", 50.000000, 10.000000, 0.040000, 0.040000, 0.010399, 0.010399, 0, 0), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=20", 50.000000, 20.000000, 0.160000, 0.159998, 0.041154, 0.041153, 0, 0), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=50", 50.000000, 50.000000, 0.999997, 0.999907, 0.239828, 0.239808, 2, 2), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=100", 50.000000, 100.000000, 3.999955, 3.998520, 0.785259, 0.785042, 6, 6), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=200", 50.000000, 200.000000, 15.999282, 15.976339, 1.961072, 1.959533, 14, 14), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=500", 50.000000, 500.000000, 99.971953, 99.082845, 4.254003, 4.241793, 22, 22), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=1000", 50.000000, 1000.000000, 399.551632, 385.718468, 6.194952, 6.144825, 28, 28), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=10000", 50.000000, 10000.000000, 35964.181431, 8505.970614, 12.667381, 10.588084, 28, 28), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=100000", 50.000000, 100000.000000, 327284.773828, 10774.181090, 15.853097, 10.928917, 28, 28), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=50, d2=1000000", 50.000000, 1000000.000000, 356132.574152, 10802.988445, 15.974963, 10.932767, 28, 28), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=4500, d2=12600", 4500.000000, 12600.000000, 6.654462, 1.139831, 1.139781, 0.270399, 8, 2), TestCase::QUICK);
AddTestCase (new LteInterferenceTestCase ("d1=5400, d2=12600", 5400.000000, 12600.000000, 4.621154, 0.791549, 0.876368, 0.193019, 6, 0), TestCase::QUICK);
}
static LteInterferenceTestSuite lteLinkAdaptationWithInterferenceTestSuite;
/**
* TestCase
*/
LteInterferenceTestCase::LteInterferenceTestCase (std::string name, double d1, double d2, double dlSinr, double ulSinr, double dlSe, double ulSe, uint16_t dlMcs, uint16_t ulMcs)
: TestCase (name),
m_d1 (d1),
m_d2 (d2),
m_dlSinrDb (10 * std::log10 (dlSinr)),
m_ulSinrDb (10 * std::log10 (ulSinr)),
m_dlMcs (dlMcs),
m_ulMcs (ulMcs)
{
}
LteInterferenceTestCase::~LteInterferenceTestCase ()
{
}
void
LteInterferenceTestCase::DoRun (void)
{
NS_LOG_INFO (this << GetName ());
Config::SetDefault ("ns3::LteSpectrumPhy::CtrlErrorModelEnabled", BooleanValue (false));
Config::SetDefault ("ns3::LteSpectrumPhy::DataErrorModelEnabled", BooleanValue (false));
Config::SetDefault ("ns3::LteAmc::AmcModel", EnumValue (LteAmc::PiroEW2010));
Config::SetDefault ("ns3::LteAmc::Ber", DoubleValue (0.00005));
Ptr<LteHelper> lteHelper = CreateObject<LteHelper> ();
lteHelper->SetAttribute ("PathlossModel", StringValue ("ns3::FriisSpectrumPropagationLossModel"));
lteHelper->SetAttribute ("UseIdealRrc", BooleanValue (false));
lteHelper->SetAttribute ("UsePdschForCqiGeneration", BooleanValue (true));
//Disable Uplink Power Control
Config::SetDefault ("ns3::LteUePhy::EnableUplinkPowerControl", BooleanValue (false));
// Create Nodes: eNodeB and UE
NodeContainer enbNodes;
NodeContainer ueNodes1;
NodeContainer ueNodes2;
enbNodes.Create (2);
ueNodes1.Create (1);
ueNodes2.Create (1);
NodeContainer allNodes = NodeContainer ( enbNodes, ueNodes1, ueNodes2);
// the topology is the following:
// d2
// UE1-----------eNB2
// | |
// d1| |d1
// | d2 |
// eNB1----------UE2
//
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
positionAlloc->Add (Vector (0.0, 0.0, 0.0)); // eNB1
positionAlloc->Add (Vector (m_d2, m_d1, 0.0)); // eNB2
positionAlloc->Add (Vector (0.0, m_d1, 0.0)); // UE1
positionAlloc->Add (Vector (m_d2, 0.0, 0.0)); // UE2
MobilityHelper mobility;
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.SetPositionAllocator (positionAlloc);
mobility.Install (allNodes);
// Create Devices and install them in the Nodes (eNB and UE)
NetDeviceContainer enbDevs;
NetDeviceContainer ueDevs1;
NetDeviceContainer ueDevs2;
lteHelper->SetSchedulerType ("ns3::RrFfMacScheduler");
lteHelper->SetSchedulerAttribute ("UlCqiFilter", EnumValue (FfMacScheduler::PUSCH_UL_CQI));
enbDevs = lteHelper->InstallEnbDevice (enbNodes);
ueDevs1 = lteHelper->InstallUeDevice (ueNodes1);
ueDevs2 = lteHelper->InstallUeDevice (ueNodes2);
lteHelper->Attach (ueDevs1, enbDevs.Get (0));
lteHelper->Attach (ueDevs2, enbDevs.Get (1));
// Activate an EPS bearer
enum EpsBearer::Qci q = EpsBearer::GBR_CONV_VOICE;
EpsBearer bearer (q);
lteHelper->ActivateDataRadioBearer (ueDevs1, bearer);
lteHelper->ActivateDataRadioBearer (ueDevs2, bearer);
// Use testing chunk processor in the PHY layer
// It will be used to test that the SNR is as intended
// we plug in two instances, one for DL and one for UL
Ptr<LtePhy> ue1Phy = ueDevs1.Get (0)->GetObject<LteUeNetDevice> ()->GetPhy ()->GetObject<LtePhy> ();
Ptr<LteTestSinrChunkProcessor> testDlSinr1 = Create<LteTestSinrChunkProcessor> ();
ue1Phy->GetDownlinkSpectrumPhy ()->AddDataSinrChunkProcessor (testDlSinr1);
Ptr<LtePhy> enb1phy = enbDevs.Get (0)->GetObject<LteEnbNetDevice> ()->GetPhy ()->GetObject<LtePhy> ();
Ptr<LteTestSinrChunkProcessor> testUlSinr1 = Create<LteTestSinrChunkProcessor> ();
enb1phy->GetUplinkSpectrumPhy ()->AddDataSinrChunkProcessor (testUlSinr1);
Config::Connect ("/NodeList/0/DeviceList/0/LteEnbMac/DlScheduling",
MakeBoundCallback (&LteTestDlSchedulingCallback, this));
Config::Connect ("/NodeList/0/DeviceList/0/LteEnbMac/UlScheduling",
MakeBoundCallback (&LteTestUlSchedulingCallback, this));
// same as above for eNB2 and UE2
Ptr<LtePhy> ue2Phy = ueDevs2.Get (0)->GetObject<LteUeNetDevice> ()->GetPhy ()->GetObject<LtePhy> ();
Ptr<LteTestSinrChunkProcessor> testDlSinr2 = Create<LteTestSinrChunkProcessor> ();
ue2Phy->GetDownlinkSpectrumPhy ()->AddDataSinrChunkProcessor (testDlSinr2);
Ptr<LtePhy> enb2phy = enbDevs.Get (1)->GetObject<LteEnbNetDevice> ()->GetPhy ()->GetObject<LtePhy> ();
Ptr<LteTestSinrChunkProcessor> testUlSinr2 = Create<LteTestSinrChunkProcessor> ();
enb1phy->GetUplinkSpectrumPhy ()->AddDataSinrChunkProcessor (testUlSinr2);
Config::Connect ("/NodeList/1/DeviceList/0/LteEnbMac/DlScheduling",
MakeBoundCallback (&LteTestDlSchedulingCallback, this));
Config::Connect ("/NodeList/1/DeviceList/0/LteEnbMac/UlScheduling",
MakeBoundCallback (&LteTestUlSchedulingCallback, this));
// need to allow for RRC connection establishment + SRS
Simulator::Stop (Seconds (0.100));
Simulator::Run ();
if (m_dlMcs > 0)
{
double dlSinr1Db = 10.0 * std::log10 (testDlSinr1->GetSinr ()->operator[] (0));
NS_TEST_ASSERT_MSG_EQ_TOL (dlSinr1Db, m_dlSinrDb, 0.01, "Wrong SINR in DL! (eNB1 --> UE1)");
double dlSinr2Db = 10.0 * std::log10 (testDlSinr2->GetSinr ()->operator[] (0));
NS_TEST_ASSERT_MSG_EQ_TOL (dlSinr2Db, m_dlSinrDb, 0.01, "Wrong SINR in DL! (eNB2 --> UE2)");
}
if (m_ulMcs > 0)
{
double ulSinr1Db = 10.0 * std::log10 (testUlSinr1->GetSinr ()->operator[] (0));
NS_TEST_ASSERT_MSG_EQ_TOL (ulSinr1Db, m_ulSinrDb, 0.01, "Wrong SINR in UL! (UE1 --> eNB1)");
double ulSinr2Db = 10.0 * std::log10 (testUlSinr2->GetSinr ()->operator[] (0));
NS_TEST_ASSERT_MSG_EQ_TOL (ulSinr2Db, m_ulSinrDb, 0.01, "Wrong SINR in UL! (UE2 --> eNB2)");
}
Simulator::Destroy ();
}
void
LteInterferenceTestCase::DlScheduling (uint32_t frameNo, uint32_t subframeNo, uint16_t rnti,
uint8_t mcsTb1, uint16_t sizeTb1, uint8_t mcsTb2, uint16_t sizeTb2)
{
NS_LOG_FUNCTION (frameNo << subframeNo << rnti << (uint32_t) mcsTb1 << sizeTb1 << (uint32_t) mcsTb2 << sizeTb2);
// need to allow for RRC connection establishment + CQI feedback reception + persistent data transmission
if (Simulator::Now () > MilliSeconds (65))
{
NS_TEST_ASSERT_MSG_EQ ((uint32_t)mcsTb1, (uint32_t)m_dlMcs, "Wrong DL MCS ");
}
}
void
LteInterferenceTestCase::UlScheduling (uint32_t frameNo, uint32_t subframeNo, uint16_t rnti,
uint8_t mcs, uint16_t sizeTb)
{
NS_LOG_FUNCTION (frameNo << subframeNo << rnti << (uint32_t) mcs << sizeTb);
// need to allow for RRC connection establishment + SRS transmission
if (Simulator::Now () > MilliSeconds (50))
{
NS_TEST_ASSERT_MSG_EQ ((uint32_t)mcs, (uint32_t)m_ulMcs, "Wrong UL MCS");
}
}
| 43.644531 | 177 | 0.70205 | [
"vector"
] |
9431af2156c82f9e09682e68718b210e01ab84da | 781 | cc | C++ | solutions/mrJudge/paint/main.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/mrJudge/paint/main.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/mrJudge/paint/main.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
bool compare(const std::pair<int, int> &i, const std::pair<int, int>&j) {
return i.first > j.first;
}
int main() {
int n;
std::cin >> n;
std::vector<int> inc(n);
std::vector<int> prc(n);
for (int i = 0; i < n; i++) {
std::cin >> prc.at(i);
}
for (int i = 0; i < n; i++) {
std::cin >> inc.at(i);
}
std::vector<std::pair<int, int>> inc_to_prc(n);
for (int i = 0; i < n; i++) {
inc_to_prc.at(i) = std::make_pair(inc.at(i), prc.at(i));
}
std::sort(inc_to_prc.begin(), inc_to_prc.end(), compare);
int total = 0;
for (int i = 0; i < n; i++) {
auto pair = inc_to_prc.at(i);
total += std::get<0>(pair) * i + std::get<1>(pair);
}
std::cout << total;
} | 21.108108 | 73 | 0.544174 | [
"vector"
] |
94355c3d62b7ab1b869ac978be1ad4fe75104e6e | 2,878 | cpp | C++ | main.cpp | snow482/cpp_capitals | 71636f0336d51670758ceefc65b5012398490879 | [
"MIT"
] | null | null | null | main.cpp | snow482/cpp_capitals | 71636f0336d51670758ceefc65b5012398490879 | [
"MIT"
] | null | null | null | main.cpp | snow482/cpp_capitals | 71636f0336d51670758ceefc65b5012398490879 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <map>
#include <vector>
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::endl;
void CHANGE_CAPITAL (map<string, string>& country_capitals_value, const string& country, const string& capital){
auto it = country_capitals_value.find(country);
if (it != country_capitals_value.end()){
country_capitals_value.insert(std::make_pair(country, capital));
return;
}
/*auto it = country_capitals_value.find(country);
if (it != country_capitals_value.end()){*/
/*auto it = country_capitals_value.find(country);
if (it != country_capitals_value.end()){
//1
//std::pair<string,string> p;
//p.first = country;
//p.second = capital;
//country_capitals_value.insert(p);
//2
//country_capitals_value.insert(std::make_pair(country, capital));
//3
country_capitals_value[country] = capital;
return;
}*/
//const auto& key = it->first;
//auto& value = it->second;
/*for (const auto& countryName : country) {
for (const auto& capitalName: capital){
++country_capitals[capitalName];
}
++country_capitals[countryName];
}*/
}
void RENAME (){
}
/*void ABOUT (std::map<std::string, std::string>& about_all){
for (const auto& item : about_all ){
if(!about_all.empty()){
std::cout << item.first << item.second << std::endl;
}else{
std::cout << "There are no countries in the world" << std::endl;
}
}*/
/*
void DUMP (const map<string, string>& about_all){
if(about_all.empty()){
cout << "There are no countries in the world" << endl;
return;
}
for (const auto& [key,value] : about_all ){
cout << key << " " << value << endl;
}
}
*/
int main() {
/*
* int Q;
std::cin >> Q;
std::string command;
string country, capital;
cin >> country >> capital;
map<string, string> caps;
*
*/
int Q;
std::cin >> Q;
std::string command;
for (int i = 0; i < Q; ++i) {
string country, capital;
cin >> country >> capital;
map<string, string> caps;
if(command == "ABOUT"){
// ABOUT country - вывод столицы country
}
if(command == "DUMP"){
// DUMP country - вывод столиц всех стран
DUMP(caps);
}
if(command == "CHANGE_CAPITAL") {
/*caps = CHANGE_CAPITAL(country, capital);*/
/*for (auto& n : caps){
if(CHANGE_CAPITAL(country, capital) == 0){
}
}*/
// }if(command == "RENAME"){
// RENAME old_country_name new_country_name — переименование
// страны из old_country_name в new_country_name.
// }
// }
return 0;
}
| 24.184874 | 112 | 0.555594 | [
"vector"
] |
94372310848c68622874ed9c74961eaaef0dd633 | 2,444 | cc | C++ | third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/graphics/paint/property_tree_state.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h"
#include <memory>
namespace blink {
const PropertyTreeState& PropertyTreeState::Uninitialized() {
DEFINE_STATIC_REF(const TransformPaintPropertyNode, transform,
TransformPaintPropertyNode::Create(
TransformPaintPropertyNode::Root(), {}));
DEFINE_STATIC_REF(
const ClipPaintPropertyNode, clip,
ClipPaintPropertyNode::Create(
ClipPaintPropertyNode::Root(),
ClipPaintPropertyNode::State(transform, FloatRoundedRect())));
DEFINE_STATIC_REF(const EffectPaintPropertyNode, effect,
EffectPaintPropertyNode::Create(
EffectPaintPropertyNode::Root(), {transform}));
DEFINE_STATIC_LOCAL(const PropertyTreeState, uninitialized,
(*transform, *clip, *effect));
return uninitialized;
}
const PropertyTreeState& PropertyTreeState::Root() {
DEFINE_STATIC_LOCAL(
const PropertyTreeState, root,
(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(),
EffectPaintPropertyNode::Root()));
return root;
}
PropertyTreeState PropertyTreeState::Unalias() const {
return PropertyTreeState(Transform().Unalias(), Clip().Unalias(),
Effect().Unalias());
}
String PropertyTreeState::ToString() const {
return String::Format("t:%p c:%p e:%p", transform_, clip_, effect_);
}
#if DCHECK_IS_ON()
String PropertyTreeState::ToTreeString() const {
return "transform:\n" + Transform().ToTreeString() + "\nclip:\n" +
Clip().ToTreeString() + "\neffect:\n" + Effect().ToTreeString();
}
#endif
std::unique_ptr<JSONObject> PropertyTreeState::ToJSON() const {
std::unique_ptr<JSONObject> result = std::make_unique<JSONObject>();
result->SetObject("transform", transform_->ToJSON());
result->SetObject("clip", clip_->ToJSON());
result->SetObject("effect", effect_->ToJSON());
return result;
}
size_t PropertyTreeState::CacheMemoryUsageInBytes() const {
return Clip().CacheMemoryUsageInBytes() +
Transform().CacheMemoryUsageInBytes();
}
std::ostream& operator<<(std::ostream& os, const PropertyTreeState& state) {
return os << state.ToString().Utf8();
}
} // namespace blink
| 33.944444 | 83 | 0.695581 | [
"transform"
] |
943ae8fbce7672fadda716718f33e45084802e2f | 2,601 | hpp | C++ | include/Sort.hpp | TheExeQ/CommonUtilities | 3abf9f9575b925aaa592d9eb7ce86665eecbba6f | [
"MIT"
] | null | null | null | include/Sort.hpp | TheExeQ/CommonUtilities | 3abf9f9575b925aaa592d9eb7ce86665eecbba6f | [
"MIT"
] | null | null | null | include/Sort.hpp | TheExeQ/CommonUtilities | 3abf9f9575b925aaa592d9eb7ce86665eecbba6f | [
"MIT"
] | null | null | null | #pragma once
namespace CommonUtilities
{
template <class T>
void SelectionSort(std::vector<T>& aVector);
template <class T>
void BubbleSort(std::vector<T>& aVector);
template <class T>
void QuickSort(std::vector<T>& aVector);
template <class T>
void MergeSort(std::vector<T>& aVector);
template<class T>
void SelectionSort(std::vector<T>& aVector)
{
for (size_t i = 0; i < aVector.size(); i++)
{
size_t minIndex = i;
for (size_t j = i + 1; j < aVector.size(); j++)
{
if (aVector[j] < aVector[minIndex])
{
minIndex = j;
}
}
std::swap(aVector[i], aVector[minIndex]);
}
};
template<class T>
void BubbleSort(std::vector<T>& aVector)
{
for (size_t i = 0; i < aVector.size(); i++)
{
for (size_t j = 0; j < aVector.size() - 1; j++)
{
if (aVector[j] > aVector[j + 1])
{
std::swap(aVector[j], aVector[j + 1]);
}
}
}
};
template<class T>
void QuickSort(std::vector<T>& aVector)
{
if (aVector.size() <= 1)
{
return;
}
size_t pivotIndex = aVector.size() / 2;
T pivotValue = aVector[pivotIndex];
aVector.erase(aVector.begin() + pivotIndex);
std::vector<T> leftVector;
std::vector<T> rightVector;
for (size_t i = 0; i < aVector.size(); i++)
{
if (aVector[i] < pivotValue)
{
leftVector.push_back(aVector[i]);
}
else
{
rightVector.push_back(aVector[i]);
}
}
QuickSort(leftVector);
QuickSort(rightVector);
aVector.clear();
aVector.insert(aVector.begin(), leftVector.begin(), leftVector.end());
aVector.push_back(pivotValue);
aVector.insert(aVector.end(), rightVector.begin(), rightVector.end());
};
template<class T>
void MergeSort(std::vector<T>& aVector)
{
if (aVector.size() <= 1)
{
return;
}
size_t middleIndex = aVector.size() / 2;
std::vector<T> leftVector(aVector.begin(), aVector.begin() + middleIndex);
std::vector<T> rightVector(aVector.begin() + middleIndex, aVector.end());
MergeSort(leftVector);
MergeSort(rightVector);
aVector.clear();
size_t leftIndex = 0;
size_t rightIndex = 0;
while (leftIndex < leftVector.size() && rightIndex < rightVector.size())
{
if (leftVector[leftIndex] < rightVector[rightIndex])
{
aVector.push_back(leftVector[leftIndex]);
leftIndex++;
}
else
{
aVector.push_back(rightVector[rightIndex]);
rightIndex++;
}
}
while (leftIndex < leftVector.size())
{
aVector.push_back(leftVector[leftIndex]);
leftIndex++;
}
while (rightIndex < rightVector.size())
{
aVector.push_back(rightVector[rightIndex]);
rightIndex++;
}
};
} | 20.162791 | 76 | 0.62822 | [
"vector"
] |
94446bc74d30924190aa0ade9d7a4c7587c32199 | 6,330 | cpp | C++ | mtlgen/mtlgen.cpp | littlemole/MTL | 1f090c15e107f949d35ef78101dfc2776cbcbc33 | [
"MIT"
] | null | null | null | mtlgen/mtlgen.cpp | littlemole/MTL | 1f090c15e107f949d35ef78101dfc2776cbcbc33 | [
"MIT"
] | null | null | null | mtlgen/mtlgen.cpp | littlemole/MTL | 1f090c15e107f949d35ef78101dfc2776cbcbc33 | [
"MIT"
] | null | null | null |
#include "mtlgen.h"
/////////////////////////////////////////////
// usage
/////////////////////////////////////////////
int usage()
{
std::cout << "Usage: mtlgen show|debug|unreg|disp>|def <midl>" << std::endl;
std::cout << " mtlgen reg|manifest|selfreg <arch> <apartment> <server> <midl>" << std::endl;
std::cout << " mtlgen wix <arch> <apartment> <type> <server> <midl>" << std::endl;
std::cout << " mtlgen isolate <arch> <apartment> <version> <server> <midl> <dependency1.manifest> [dep2.manifest ...]" << std::endl;
std::cout << " mtlgen package <subproj1> [subproj2 ...]" << std::endl;
std::cout << " mtlgen init|setup" << std::endl;
std::cout << std::endl;
std::cout << "where:" << std::endl;
std::cout << " <midl> : midl filename, ie <Project>.idl" << std::endl;
std::cout << " <arch> : target architecture x64|x86. Win32 also works for x86" << std::endl;
std::cout << " <apartment> : com apartment type Apartment|Both|Free " << std::endl;
std::cout << " <type> : registratiom type, reg|iso << std::endl;" << std::endl;
std::cout << " <server> : server file name, like <Project>.dll. for reg command FULL path to file" << std::endl;
std::cout << " <version> : 4 digit version like 1.0.0.0 for regsitry-free com assembly identity" << std::endl;
return 1;
}
Parser* parse(Parser& parser, bool debug, const std::string& midl)
{
Tokenizer tokenizer;
Lexer lexer;
Parser* p = nullptr;
if (!midl.empty())
{
std::fstream fs;
fs.open(midl);
while (fs)
{
std::string line;
std::getline(fs, line);
line = trim(line);
// strip comments
size_t pos = line.find("//");
if (pos != std::string::npos)
{
line = line.substr(0, pos);
}
if (debug)
std::cout << line << std::endl;
if (!line.empty())
{
tokenizer.feed(line);
}
}
fs.close();
if (debug)
tokenizer.print();
lexer.feed(tokenizer.tokens());
if (debug)
lexer.print();
parser.feed(lexer.tokens());
p = &parser;
}
return p;
}
/////////////////////////////////////////////
// main
/////////////////////////////////////////////
int main(int argc, char** argv)
{
// handle cli arguments
if (argc < 2)
{
return usage();
}
std::string cmd = argv[1];
if (cmd == "init")
{
std::string apartment = "Apartment";
if (argc > 2)
{
apartment = argv[2];
}
init(apartment);
return 0;
}
if (cmd == "setup")
{
init_package();
return 0;
}
if (argc < 3)
{
return usage();
}
std::string midl = argv[2];
std::string server;
std::string arch = "win64";
std::string apartment = "Apartment";
std::string version;
std::string package_type;
std::vector<std::string> dependencies;
std::vector<std::string> projects;
if (cmd == "package")
{
if (argc < 3)
{
return usage();
}
for (size_t i = 2; i < argc; i++)
{
projects.push_back(std::string(argv[i]));
}
midl = "";
}
if (cmd == "isolate" )
{
if (argc < 7)
{
return usage();
}
std::string a = argv[2];
if (a == "win32" || a == "x86")
{
arch = "win32";
}
apartment = argv[3];
version = argv[4];
server = argv[5];
midl = argv[6];
for (int i = 7; i < argc; i++)
{
std::string d = trim(argv[i]);
dependencies.push_back(d);
}
}
if (cmd == "reg" || cmd == "manifest" || cmd == "selfreg")
{
if (argc < 5)
{
return usage();
}
std::string a = argv[2];
if (a == "win32" || a == "x86")
{
arch = "win32";
}
apartment = argv[3];
server = argv[4];
if (argc > 5)
{
midl = argv[5];
}
else {
midl = "";
}
}
if (cmd == "wix" )
{
if (argc < 6)
{
return usage();
}
std::string a = argv[2];
if (a == "win32" || a == "x86")
{
arch = "win32";
}
apartment = argv[3];
package_type = argv[4];
server = argv[5];
if (argc > 6)
{
midl = argv[6];
}
else {
midl = "";
}
}
::CoInitialize(NULL);
// PARSE the midl file, if any
Parser parser;
Parser* p = parse(parser, cmd == "debug", midl);
// generate output
if (cmd == "package")
{
Packer packer(projects);
packer.print();
}
if (cmd == "debug" || cmd == "show")
parser.print();
if (cmd == "def")
{
ModuleDef md(parser, midl);
md.print();
}
if (cmd == "unreg")
{
Unreg unreg(parser);
unreg.print();
}
if (cmd == "reg" && p)
{
Reg reg(parser, server, arch, apartment);
reg.print();
}
if (cmd == "selfreg" && p)
{
SelfReg reg(parser, server, arch, apartment);
reg.print();
}
if (cmd == "wix")
{
Wix wix(p, server, arch, apartment, package_type);
wix.print();
}
if (cmd == "disp")
{
DispIds disp(parser);
disp.print();
}
if (cmd == "manifest" && p)
{
Manifest man(parser, server, arch, apartment, midl);
man.print();
}
if (cmd == "isolate")
{
IsoManifest man(parser, server, arch, apartment, version,midl, dependencies);
man.print();
}
::CoUninitialize();
return 0;
}
| 22.446809 | 143 | 0.413744 | [
"vector"
] |
944ab346b20d19fba027de3561b6e320fcddca3d | 3,488 | cpp | C++ | x3d-uml/osgDiagram/osgX3DUML/GraphElement.cpp | internetscooter/diorama | 460d2825e36c732550d6174460c81325f831c387 | [
"MIT"
] | 1 | 2020-02-22T03:08:39.000Z | 2020-02-22T03:08:39.000Z | x3d-uml/osgDiagram/osgX3DUML/GraphElement.cpp | internetscooter/diorama | 460d2825e36c732550d6174460c81325f831c387 | [
"MIT"
] | null | null | null | x3d-uml/osgDiagram/osgX3DUML/GraphElement.cpp | internetscooter/diorama | 460d2825e36c732550d6174460c81325f831c387 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
// GraphElement.cpp
// Implementation of the Class GraphElement
// Created on: 23-Jun-2008 9:33:51 PM
///////////////////////////////////////////////////////////
#include "GraphElement.h"
#include <sstream>
using X3DUML::GraphElement;
GraphElement::GraphElement(){
}
GraphElement::~GraphElement(){
}
std::string GraphElement::addDiagramElement(DiagramElement* element){
// remember your elders
element->parent = this;
// and have that accessible via a string
if(element->type.compare("DiagramView") == 0) // Diagrams are unique and are called by name only
{
element->fullyQualifiedName = this->fullyQualifiedName + element->name + ".";
}
else // elements are not unique and we need to refer to them by number and name
{
std::stringstream elementNumber;
elementNumber << contained.size();
//s = elementNumber.str();
//int x = contained.size();
element->fullyQualifiedName = this->fullyQualifiedName + elementNumber.str() + "_" + element->name + ".";
}
contained.push_back(element);
return element->fullyQualifiedName;
}
std::string GraphElement::addGraphElement(GraphElement* element){
// and keep everything with positions on the diagram at the same plane (for now)
//element->position.z += this->position.z;
return this->addDiagramElement(element);
}
void GraphElement::updateOSGGroup(){
// recurse the structure to create geometry visualisation with osg geodes based on UML parameters
for(size_t i=0;i < contained.size(); i++)
{
contained.at(i)->updateOSGGroup(); // update everyone below first
if (x3dumlDraggable)
{ //insert dragger node if required
draggerSelection->addChild(contained.at(i)->group.get());
// here we will match the object used for dragging bits around with the first object
// in the diagram contained objects. This will work for now for state machines because the first
// object added is the biggest stateview. Later we'll need to update this so the code finds
// the biggest object in all the contained elements and use that as the item that gets selected
// to move things around with.
osg::ref_ptr<osg::Drawable> diagramDrawable = osg::clone(contained.at(0)->geode->getDrawable(1),osg::CopyOp::DEEP_COPY_DRAWABLES);
osgManipulator::setDrawableToAlwaysCull(*diagramDrawable); // this line makes the dragger invisible
osg::ref_ptr<osg::Geode> customDraggerGeode = new osg::Geode();
customDraggerGeode->addDrawable(diagramDrawable.get());
customDraggerxform->removeChildren(0,1); // remove the default dragger geometry
customDraggerxform->addChild(customDraggerGeode.get()); // replace it with the one we just created
// move the dragger into position just above diagram object
X3DUML::GraphElement* graphElement = (X3DUML::GraphElement*)contained.at(0);
dragger->setMatrix(osg::Matrix::translate(graphElement->position.x, graphElement->position.y, -2.0f));
}
else
{
group->addChild(contained.at(i)->group.get());
}
}
}
void GraphElement::setPosition(double x, double y, double z){
//set position
position.x = x;
position.y = y;
position.z = z;
//set OSG position
osg::Matrix m;
m.setTrans(x,y,z);
group->setMatrix(m);
}
bool GraphElement::containsDiagramElement(std::string type, std::string name){
for(size_t i=0;i < contained.size(); i++)
{
if (contained.at(i)->type.compare(type) == 0 && contained.at(i)->name.compare(name))
return true;
}
return false;
} | 33.538462 | 133 | 0.698968 | [
"geometry",
"object"
] |
944b5712078c6004ed68c3895ff8a9db4088151d | 1,247 | cc | C++ | game/Utils.cc | alvaroma94/EDA-Game | f1912f3e726a315e1a850d1a16081e9363bc2d65 | [
"MIT"
] | null | null | null | game/Utils.cc | alvaroma94/EDA-Game | f1912f3e726a315e1a850d1a16081e9363bc2d65 | [
"MIT"
] | null | null | null | game/Utils.cc | alvaroma94/EDA-Game | f1912f3e726a315e1a850d1a16081e9363bc2d65 | [
"MIT"
] | null | null | null | #include "Utils.hh"
// atzar.cc
// SR, febrer/06
// Implementacio d'una classe per treballar amb nombres aleatoris.
atzar::atzar(int llavor) : llavor(llavor) { }
void atzar::seguent() {
int x1, x0, z, z1, z0, w, w1, w0;
x1 = llavor/65536L; x0 = llavor&65535L;
z = 1894L*x0; z1 = z/65536L; z0 = z&65535L;
w = 27319L*x1; w1 = w/32768L; w0 = w&32767L;
llavor = 453816693L + 1894L*x1 + z1 + w1 - 2147483647L;
llavor += 27319L*x0;
if (llavor >= 0L) llavor -= 2147483647L;
llavor += 32768L*z0;
if (llavor >= 0L) llavor -= 2147483647L;
llavor += 65536L*w0;
if (llavor < 0L) llavor += 2147483647L;
}
double atzar::uniforme() {
seguent();
return (double)llavor/(double)2147483647L;
}
int atzar::uniforme(int esquerra, int dreta) {
return esquerra + (int)(((double)(dreta - esquerra + 1))*uniforme());
}
double atzar::uniforme(int esquerra, int dreta, int dig) {
int pow = 1;
while (dig--) pow *= 10;
return ((double)uniforme(esquerra*pow, dreta*pow))/(double)pow;
}
bool atzar::probabilitat(double p) {
return uniforme() < p;
}
vector<int> atzar::permutacio(int n) {
vector<int> V(n);
for (int i = 0; i < n; ++i) V[i] = i;
for (int i = n - 1; i > 0; --i) swap(V[i], V[uniforme(0, i)]);
return V;
}
| 23.092593 | 71 | 0.622294 | [
"vector"
] |
944f7937e5eea9b0c5cdcb36263ca4f7d73bd30d | 1,378 | cpp | C++ | src/commands/ServerDeviceListResult.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 7 | 2018-06-09T05:55:59.000Z | 2021-01-05T05:19:02.000Z | src/commands/ServerDeviceListResult.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 1 | 2019-12-25T10:39:06.000Z | 2020-01-03T08:35:29.000Z | src/commands/ServerDeviceListResult.cpp | jalowiczor/beeon-gateway-with-nemea-sources | 195d8209302a42e03bafe33811236d7aeedb188d | [
"BSD-3-Clause"
] | 11 | 2018-05-10T08:29:05.000Z | 2020-01-22T20:49:32.000Z | #include "commands/ServerDeviceListResult.h"
using namespace Poco;
using namespace BeeeOn;
using namespace std;
ServerDeviceListResult::ServerDeviceListResult(
const Answer::Ptr answer):
Result(answer)
{
}
ServerDeviceListResult::~ServerDeviceListResult()
{
}
void ServerDeviceListResult::setDeviceList(
const vector<DeviceID> &deviceList)
{
ScopedLock guard(*this);
const ModuleValues empty;
for (const auto &id : deviceList)
m_data.emplace(id, empty);
}
vector<DeviceID> ServerDeviceListResult::deviceList() const
{
ScopedLock guard(const_cast<ServerDeviceListResult &>(*this));
vector<DeviceID> ids;
for (const auto &pair : m_data)
ids.emplace_back(pair.first);
return ids;
}
void ServerDeviceListResult::setDevices(const DeviceValues &values)
{
ScopedLock guard(*this);
m_data = values;
}
ServerDeviceListResult::DeviceValues ServerDeviceListResult::devices() const
{
ScopedLock guard(const_cast<ServerDeviceListResult &>(*this));
return m_data;
}
Nullable<double> ServerDeviceListResult::value(
const DeviceID &id,
const ModuleID &module) const
{
ScopedLock guard(const_cast<ServerDeviceListResult &>(*this));
Nullable<double> result;
auto it = m_data.find(id);
if (it == m_data.end())
return result;
auto mit = it->second.find(module);
if (mit == it->second.end())
return result;
result = mit->second;
return result;
}
| 19.138889 | 76 | 0.751089 | [
"vector"
] |
9452e4a0c4bba85780b9aab366508a5ebb8359db | 127,514 | cpp | C++ | Tools/DumpRenderTree/TestRunner.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Tools/DumpRenderTree/TestRunner.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Tools/DumpRenderTree/TestRunner.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2007-2016 Apple Inc. All rights reserved.
* Copyright (C) 2010 Joone Hur <joone@kldp.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") 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 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"
#include "TestRunner.h"
#include "WebCoreTestSupport.h"
#include "WorkQueue.h"
#include "WorkQueueItem.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/ArrayBufferView.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/JSArrayBufferView.h>
#include <JavaScriptCore/JSCTestRunnerUtils.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSGlobalObjectInlines.h>
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSRetainPtr.h>
#include <JavaScriptCore/TypedArrayInlines.h>
#include <JavaScriptCore/VMInlines.h>
#include <WebCore/LogInitialization.h>
#include <cstring>
#include <locale.h>
#include <stdio.h>
#include <wtf/Assertions.h>
#include <wtf/LoggingAccumulator.h>
#include <wtf/MathExtras.h>
#include <wtf/RefPtr.h>
#include <wtf/RunLoop.h>
#include <wtf/StdLibExtras.h>
#include <wtf/UniqueArray.h>
#include <wtf/WallTime.h>
#include <wtf/text/WTFString.h>
#if PLATFORM(IOS_FAMILY)
#include <WebCore/WebCoreThreadRun.h>
#include <wtf/BlockPtr.h>
#endif
#if PLATFORM(MAC) && !PLATFORM(IOS_FAMILY)
#include <Carbon/Carbon.h>
#endif
FILE* testResult = stdout;
const unsigned TestRunner::viewWidth = 800;
const unsigned TestRunner::viewHeight = 600;
const unsigned TestRunner::w3cSVGViewWidth = 480;
const unsigned TestRunner::w3cSVGViewHeight = 360;
TestRunner::TestRunner(const std::string& testURL, const std::string& expectedPixelHash)
: m_testURL(testURL)
, m_expectedPixelHash(expectedPixelHash)
, m_titleTextDirection("ltr")
{
}
Ref<TestRunner> TestRunner::create(const std::string& testURL, const std::string& expectedPixelHash)
{
return adoptRef(*new TestRunner(testURL, expectedPixelHash));
}
// Static Functions
static JSValueRef disallowIncreaseForApplicationCacheQuotaCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDisallowIncreaseForApplicationCacheQuota(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpApplicationCacheDelegateCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpApplicationCacheDelegateCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpAsPDFCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpAsPDF(true);
return JSValueMakeUndefined(context);
}
static JSValueRef setRenderTreeDumpOptionsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
double options = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
controller->setRenderTreeDumpOptions(static_cast<unsigned>(options));
return JSValueMakeUndefined(context);
}
static JSValueRef dumpAsTextCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpAsText(true);
// Optional paramater, describing whether it's allowed to dump pixel results in dumpAsText mode.
controller->setGeneratePixelResults(argumentCount > 0 ? JSValueToBoolean(context, arguments[0]) : false);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpBackForwardListCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpBackForwardList(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpChildFramesAsTextCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpChildFramesAsText(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpChildFrameScrollPositionsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpChildFrameScrollPositions(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpDatabaseCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpDatabaseCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpDOMAsWebArchiveCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpDOMAsWebArchive(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpEditingCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpEditingCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpFrameLoadCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpFrameLoadCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpProgressFinishedCallbackCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpProgressFinishedCallback(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpUserGestureInFrameLoadCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpUserGestureInFrameLoadCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpResourceLoadCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpResourceLoadCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpResourceResponseMIMETypesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpResourceResponseMIMETypes(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpSelectionRectCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpSelectionRect(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpSourceAsWebArchiveCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpSourceAsWebArchive(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpStatusCallbacksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpStatusCallbacks(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpTitleChangesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpTitleChanges(true);
return JSValueMakeUndefined(context);
}
static JSValueRef dumpWillCacheResponseCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpWillCacheResponse(true);
return JSValueMakeUndefined(context);
}
static JSValueRef pathToLocalResourceCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto localPath = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto convertedPath = controller->pathToLocalResource(context, localPath.get());
if (!convertedPath)
return JSValueMakeUndefined(context);
return JSValueMakeString(context, convertedPath.get());
}
static JSValueRef removeAllVisitedLinksCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDumpVisitedLinksCallback(true);
controller->removeAllVisitedLinks();
return JSValueMakeUndefined(context);
}
static JSValueRef repaintSweepHorizontallyCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setTestRepaintSweepHorizontally(true);
return JSValueMakeUndefined(context);
}
static JSValueRef setCallCloseOnWebViewsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setCallCloseOnWebViews(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setCanOpenWindowsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setCanOpenWindows(true);
return JSValueMakeUndefined(context);
}
static JSValueRef setCloseRemainingWindowsWhenCompleteCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setCloseRemainingWindowsWhenComplete(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setAudioResultCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
// FIXME (123058): Use a JSC API to get buffer contents once such is exposed.
JSC::VM& vm = toJS(context)->vm();
JSC::JSLockHolder lock(vm);
JSC::JSArrayBufferView* jsBufferView = JSC::jsDynamicCast<JSC::JSArrayBufferView*>(vm, toJS(toJS(context), arguments[0]));
ASSERT(jsBufferView);
RefPtr<JSC::ArrayBufferView> bufferView = jsBufferView->unsharedImpl();
const char* buffer = static_cast<const char*>(bufferView->baseAddress());
std::vector<char> audioData(buffer, buffer + bufferView->byteLength());
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAudioResult(audioData);
controller->setDumpAsAudio(true);
return JSValueMakeUndefined(context);
}
static JSValueRef testOnscreenCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setTestOnscreen(true);
return JSValueMakeUndefined(context);
}
static JSValueRef testRepaintCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setTestRepaint(true);
return JSValueMakeUndefined(context);
}
static JSValueRef addDisallowedURLCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto url = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->addDisallowedURL(url.get());
return JSValueMakeUndefined(context);
}
static JSValueRef addURLToRedirectCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 2)
return JSValueMakeUndefined(context);
auto origin = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto destination = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
size_t maxLength = JSStringGetMaximumUTF8CStringSize(origin.get());
auto originBuffer = makeUniqueArray<char>(maxLength + 1);
JSStringGetUTF8CString(origin.get(), originBuffer.get(), maxLength + 1);
maxLength = JSStringGetMaximumUTF8CStringSize(destination.get());
auto destinationBuffer = makeUniqueArray<char>(maxLength + 1);
JSStringGetUTF8CString(destination.get(), destinationBuffer.get(), maxLength + 1);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->addURLToRedirect(originBuffer.get(), destinationBuffer.get());
return JSValueMakeUndefined(context);
}
static JSValueRef callShouldCloseOnWebViewCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeBoolean(context, controller->callShouldCloseOnWebView());
}
static JSValueRef clearAllApplicationCachesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->clearAllApplicationCaches();
return JSValueMakeUndefined(context);
}
static JSValueRef clearApplicationCacheForOriginCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto originURL = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->clearApplicationCacheForOrigin(originURL.get());
return JSValueMakeUndefined(context);
}
static JSValueRef applicationCacheDiskUsageForOriginCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto originURL = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->applicationCacheDiskUsageForOrigin(originURL.get()));
}
static JSValueRef originsWithApplicationCacheCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return controller->originsWithApplicationCache(context);
}
static JSValueRef clearAllDatabasesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->clearAllDatabases();
return JSValueMakeUndefined(context);
}
static JSValueRef clearBackForwardListCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->clearBackForwardList();
return JSValueMakeUndefined(context);
}
static JSValueRef clearPersistentUserStyleSheetCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->clearPersistentUserStyleSheet();
return JSValueMakeUndefined(context);
}
static JSValueRef decodeHostNameCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto name = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto decodedHostName = controller->copyDecodedHostName(name.get());
return JSValueMakeString(context, decodedHostName.get());
}
static JSValueRef dispatchPendingLoadRequestsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation, needs windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->dispatchPendingLoadRequests();
return JSValueMakeUndefined(context);
}
static JSValueRef displayCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->display();
return JSValueMakeUndefined(context);
}
static JSValueRef displayAndTrackRepaintsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->displayAndTrackRepaints();
return JSValueMakeUndefined(context);
}
static JSValueRef encodeHostNameCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto name = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto encodedHostName = controller->copyEncodedHostName(name.get());
return JSValueMakeString(context, encodedHostName.get());
}
static JSValueRef execCommandCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac & Windows implementations.
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto name = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
// Ignoring the second parameter (userInterface), as this command emulates a manual action.
JSRetainPtr<JSStringRef> value;
if (argumentCount >= 3) {
value = adopt(JSValueToStringCopy(context, arguments[2], exception));
ASSERT(!*exception);
} else
value = adopt(JSStringCreateWithUTF8CString(""));
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->execCommand(name.get(), value.get());
return JSValueMakeUndefined(context);
}
static JSValueRef findStringCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac implementation.
if (argumentCount < 2)
return JSValueMakeUndefined(context);
auto target = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
JSObjectRef options = JSValueToObject(context, arguments[1], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeBoolean(context, controller->findString(context, target.get(), options));
}
static JSValueRef goBackCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->goBack();
return JSValueMakeUndefined(context);
}
static JSValueRef isCommandEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac implementation.
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto name = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeBoolean(context, controller->isCommandEnabled(name.get()));
}
static JSValueRef overridePreferenceCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 2)
return JSValueMakeUndefined(context);
auto key = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto value = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
// Should use `<!-- webkit-test-runner [ enableBackForwardCache=true ] -->` instead.
RELEASE_ASSERT(!JSStringIsEqualToUTF8CString(key.get(), "WebKitUsesBackForwardCachePreferenceKey"));
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->overridePreference(key.get(), value.get());
return JSValueMakeUndefined(context);
}
static JSValueRef keepWebHistoryCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->keepWebHistory();
return JSValueMakeUndefined(context);
}
static JSValueRef notifyDoneCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->notifyDone();
return JSValueMakeUndefined(context);
}
static JSValueRef numberOfPendingGeolocationPermissionRequestsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->numberOfPendingGeolocationPermissionRequests());
}
static JSValueRef isGeolocationProviderActiveCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeBoolean(context, controller->isGeolocationProviderActive());
}
static JSValueRef queueBackNavigationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
if (argumentCount < 1)
return JSValueMakeUndefined(context);
double howFarBackDouble = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->queueBackNavigation(static_cast<int>(howFarBackDouble));
return JSValueMakeUndefined(context);
}
static JSValueRef queueForwardNavigationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
if (argumentCount < 1)
return JSValueMakeUndefined(context);
double howFarForwardDouble = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->queueForwardNavigation(static_cast<int>(howFarForwardDouble));
return JSValueMakeUndefined(context);
}
static JSValueRef queueLoadCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto url = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
JSRetainPtr<JSStringRef> target;
if (argumentCount >= 2) {
target = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
} else
target = adopt(JSStringCreateWithUTF8CString(""));
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->queueLoad(url.get(), target.get());
return JSValueMakeUndefined(context);
}
static JSValueRef queueLoadHTMLStringCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac & Windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto content = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
JSRetainPtr<JSStringRef> baseURL;
if (argumentCount >= 2) {
baseURL = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
} else
baseURL = adopt(JSStringCreateWithUTF8CString(""));
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
if (argumentCount >= 3) {
auto unreachableURL = adopt(JSValueToStringCopy(context, arguments[2], exception));
ASSERT(!*exception);
controller->queueLoadAlternateHTMLString(content.get(), baseURL.get(), unreachableURL.get());
return JSValueMakeUndefined(context);
}
controller->queueLoadHTMLString(content.get(), baseURL.get());
return JSValueMakeUndefined(context);
}
static JSValueRef queueReloadCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->queueReload();
return JSValueMakeUndefined(context);
}
static JSValueRef queueLoadingScriptCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto script = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->queueLoadingScript(script.get());
return JSValueMakeUndefined(context);
}
static JSValueRef queueNonLoadingScriptCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
// May be able to be made platform independant by using shared WorkQueue
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto script = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->queueNonLoadingScript(script.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setAcceptsEditingCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAcceptsEditing(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setAlwaysAcceptCookiesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAlwaysAcceptCookies(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setOnlyAcceptFirstPartyCookiesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setOnlyAcceptFirstPartyCookies(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setAppCacheMaximumSizeCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
double size = JSValueToNumber(context, arguments[0], NULL);
if (!std::isnan(size))
controller->setAppCacheMaximumSize(static_cast<unsigned long long>(size));
return JSValueMakeUndefined(context);
}
static JSValueRef setAuthenticationPasswordCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto password = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
size_t maxLength = JSStringGetMaximumUTF8CStringSize(password.get());
char* passwordBuffer = new char[maxLength + 1];
JSStringGetUTF8CString(password.get(), passwordBuffer, maxLength + 1);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAuthenticationPassword(passwordBuffer);
delete[] passwordBuffer;
return JSValueMakeUndefined(context);
}
static JSValueRef setAuthenticationUsernameCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto username = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
size_t maxLength = JSStringGetMaximumUTF8CStringSize(username.get());
char* usernameBuffer = new char[maxLength + 1];
JSStringGetUTF8CString(username.get(), usernameBuffer, maxLength + 1);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAuthenticationUsername(usernameBuffer);
delete[] usernameBuffer;
return JSValueMakeUndefined(context);
}
static JSValueRef setAuthorAndUserStylesEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAuthorAndUserStylesEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setCacheModelCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac implementation.
if (argumentCount < 1)
return JSValueMakeUndefined(context);
int cacheModel = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setCacheModel(cacheModel);
return JSValueMakeUndefined(context);
}
static JSValueRef setCustomPolicyDelegateCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
bool permissive = false;
if (argumentCount >= 2)
permissive = JSValueToBoolean(context, arguments[1]);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setCustomPolicyDelegate(JSValueToBoolean(context, arguments[0]), permissive);
return JSValueMakeUndefined(context);
}
static JSValueRef setDatabaseQuotaCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
double quota = JSValueToNumber(context, arguments[0], NULL);
if (!std::isnan(quota))
controller->setDatabaseQuota(static_cast<unsigned long long>(quota));
return JSValueMakeUndefined(context);
}
static JSValueRef setDefersLoadingCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDefersLoading(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setUseDeferredFrameLoadingCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setUseDeferredFrameLoading(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setDomainRelaxationForbiddenForURLSchemeCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac and Windows implementation
if (argumentCount < 2)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
bool forbidden = JSValueToBoolean(context, arguments[0]);
auto scheme = adopt(JSValueToStringCopy(context, arguments[1], 0));
controller->setDomainRelaxationForbiddenForURLScheme(forbidden, scheme.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setMockDeviceOrientationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 6)
return JSValueMakeUndefined(context);
bool canProvideAlpha = JSValueToBoolean(context, arguments[0]);
double alpha = JSValueToNumber(context, arguments[1], exception);
ASSERT(!*exception);
bool canProvideBeta = JSValueToBoolean(context, arguments[2]);
double beta = JSValueToNumber(context, arguments[3], exception);
ASSERT(!*exception);
bool canProvideGamma = JSValueToBoolean(context, arguments[4]);
double gamma = JSValueToNumber(context, arguments[5], exception);
ASSERT(!*exception);
TestRunner* controller = reinterpret_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma);
return JSValueMakeUndefined(context);
}
static JSValueRef setMockGeolocationPositionCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 3)
return JSValueMakeUndefined(context);
double latitude = JSValueToNumber(context, arguments[0], 0);
double longitude = JSValueToNumber(context, arguments[1], 0);
double accuracy = JSValueToNumber(context, arguments[2], 0);
bool canProvideAltitude = false;
double altitude = 0.;
if (argumentCount > 3 && !JSValueIsUndefined(context, arguments[3])) {
canProvideAltitude = true;
altitude = JSValueToNumber(context, arguments[3], 0);
}
bool canProvideAltitudeAccuracy = false;
double altitudeAccuracy = 0.;
if (argumentCount > 4 && !JSValueIsUndefined(context, arguments[4])) {
canProvideAltitudeAccuracy = true;
altitudeAccuracy = JSValueToNumber(context, arguments[4], 0);
}
bool canProvideHeading = false;
double heading = 0.;
if (argumentCount > 5 && !JSValueIsUndefined(context, arguments[5])) {
canProvideHeading = true;
heading = JSValueToNumber(context, arguments[5], 0);
}
bool canProvideSpeed = false;
double speed = 0.;
if (argumentCount > 6 && !JSValueIsUndefined(context, arguments[6])) {
canProvideSpeed = true;
speed = JSValueToNumber(context, arguments[6], 0);
}
bool canProvideFloorLevel = false;
double floorLevel = 0.;
if (argumentCount > 7 && !JSValueIsUndefined(context, arguments[7])) {
canProvideFloorLevel = true;
floorLevel = JSValueToNumber(context, arguments[7], 0);
}
TestRunner* controller = reinterpret_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setMockGeolocationPosition(latitude, longitude, accuracy, canProvideAltitude, altitude, canProvideAltitudeAccuracy, altitudeAccuracy, canProvideHeading, heading, canProvideSpeed, speed, canProvideFloorLevel, floorLevel);
return JSValueMakeUndefined(context);
}
static JSValueRef setMockGeolocationPositionUnavailableErrorCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 1)
return JSValueMakeUndefined(context);
auto message = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = reinterpret_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setMockGeolocationPositionUnavailableError(message.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setNewWindowsCopyBackForwardListCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setNewWindowsCopyBackForwardList(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setGeolocationPermissionCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setGeolocationPermission(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setRejectsProtectionSpaceAndContinueForAuthenticationChallengesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setRejectsProtectionSpaceAndContinueForAuthenticationChallenges(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setHandlesAuthenticationChallengesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setHandlesAuthenticationChallenges(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setPOSIXLocaleCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto locale = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
controller->setPOSIXLocale(locale.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setIconDatabaseEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setIconDatabaseEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setMainFrameIsFirstResponderCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setMainFrameIsFirstResponder(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setPersistentUserStyleSheetLocationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto path = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setPersistentUserStyleSheetLocation(path.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setPrivateBrowsingEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setPrivateBrowsingEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setShouldSwapToEphemeralSessionOnNextNavigationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setShouldSwapToEphemeralSessionOnNextNavigation(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setShouldSwapToDefaultSessionOnNextNavigationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setShouldSwapToDefaultSessionOnNextNavigation(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setJavaScriptCanAccessClipboardCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setJavaScriptCanAccessClipboard(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setXSSAuditorEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setXSSAuditorEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setSpatialNavigationEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation.
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setSpatialNavigationEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setPrintingCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setIsPrinting(true);
return JSValueMakeUndefined(context);
}
static JSValueRef setAllowsAnySSLCertificateCallback(JSContextRef context, JSObjectRef, JSObjectRef, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
bool allowAnyCertificate = false;
if (argumentCount == 1)
allowAnyCertificate = JSValueToBoolean(context, arguments[0]);
TestRunner::setAllowsAnySSLCertificate(allowAnyCertificate);
return JSValueMakeUndefined(context);
}
static JSValueRef setAllowUniversalAccessFromFileURLsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAllowUniversalAccessFromFileURLs(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setAllowFileAccessFromFileURLsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAllowFileAccessFromFileURLs(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setNeedsStorageAccessFromFileURLsQuirkCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setNeedsStorageAccessFromFileURLsQuirk(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setTabKeyCyclesThroughElementsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setTabKeyCyclesThroughElements(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
#if PLATFORM(IOS_FAMILY)
static JSValueRef setTelephoneNumberParsingEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setTelephoneNumberParsingEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setPagePausedCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setPagePaused(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
#endif
static JSValueRef setUserStyleSheetEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setUserStyleSheetEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setUserStyleSheetLocationCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto path = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setUserStyleSheetLocation(path.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setValueForUserCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount != 2)
return JSValueMakeUndefined(context);
auto value = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setValueForUser(context, arguments[0], value.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setWillSendRequestClearHeaderCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto header = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
size_t maxLength = JSStringGetMaximumUTF8CStringSize(header.get());
auto headerBuffer = makeUniqueArray<char>(maxLength + 1);
JSStringGetUTF8CString(header.get(), headerBuffer.get(), maxLength + 1);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setWillSendRequestClearHeader(headerBuffer.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setWillSendRequestReturnsNullCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has cross-platform implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setWillSendRequestReturnsNull(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setWillSendRequestReturnsNullOnRedirectCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has cross-platform implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setWillSendRequestReturnsNullOnRedirect(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setWindowIsKeyCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setWindowIsKey(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setViewSizeCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 2)
return JSValueMakeUndefined(context);
double width = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
double height = JSValueToNumber(context, arguments[1], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setViewSize(width, height);
return JSValueMakeUndefined(context);
}
static JSValueRef waitUntilDoneCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setWaitToDump(true);
return JSValueMakeUndefined(context);
}
static JSValueRef windowCountCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
int windows = controller->windowCount();
return JSValueMakeNumber(context, windows);
}
static JSValueRef setPopupBlockingEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setPopupBlockingEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setPluginsEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setPluginsEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setPageVisibilityCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto visibility = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
size_t maxLength = JSStringGetMaximumUTF8CStringSize(visibility.get());
char* visibilityBuffer = new char[maxLength + 1];
JSStringGetUTF8CString(visibility.get(), visibilityBuffer, maxLength + 1);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setPageVisibility(visibilityBuffer);
delete[] visibilityBuffer;
return JSValueMakeUndefined(context);
}
static JSValueRef resetPageVisibilityCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->resetPageVisibility();
return JSValueMakeUndefined(context);
}
static JSValueRef setAutomaticLinkDetectionEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAutomaticLinkDetectionEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setStopProvisionalFrameLoadsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setStopProvisionalFrameLoads(true);
return JSValueMakeUndefined(context);
}
static JSValueRef showWebInspectorCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->showWebInspector();
return JSValueMakeUndefined(context);
}
static JSValueRef closeWebInspectorCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->closeWebInspector();
return JSValueMakeUndefined(context);
}
static JSValueRef evaluateInWebInspectorCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto script = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
controller->evaluateInWebInspector(script.get());
return JSValueMakeUndefined(context);
}
static JSValueRef evaluateScriptInIsolatedWorldCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
double worldID = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
auto script = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
controller->evaluateScriptInIsolatedWorld(static_cast<unsigned>(worldID), JSContextGetGlobalObject(context), script.get());
return JSValueMakeUndefined(context);
}
static JSValueRef evaluateScriptInIsolatedWorldAndReturnValueCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
double worldID = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
auto script = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
controller->evaluateScriptInIsolatedWorldAndReturnValue(static_cast<unsigned>(worldID), JSContextGetGlobalObject(context), script.get());
return JSValueMakeUndefined(context);
}
static JSValueRef waitForPolicyDelegateCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t, const JSValueRef[], JSValueRef*)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->waitForPolicyDelegate();
return JSValueMakeUndefined(context);
}
static JSValueRef addOriginAccessAllowListEntryCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 4)
return JSValueMakeUndefined(context);
auto sourceOrigin = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto destinationProtocol = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
auto destinationHost = adopt(JSValueToStringCopy(context, arguments[2], exception));
ASSERT(!*exception);
bool allowDestinationSubdomains = JSValueToBoolean(context, arguments[3]);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->addOriginAccessAllowListEntry(sourceOrigin.get(), destinationProtocol.get(), destinationHost.get(), allowDestinationSubdomains);
return JSValueMakeUndefined(context);
}
static JSValueRef removeOriginAccessAllowListEntryCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 4)
return JSValueMakeUndefined(context);
auto sourceOrigin = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto destinationProtocol = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
auto destinationHost = adopt(JSValueToStringCopy(context, arguments[2], exception));
ASSERT(!*exception);
bool allowDestinationSubdomains = JSValueToBoolean(context, arguments[3]);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->removeOriginAccessAllowListEntry(sourceOrigin.get(), destinationProtocol.get(), destinationHost.get(), allowDestinationSubdomains);
return JSValueMakeUndefined(context);
}
static JSValueRef setScrollbarPolicyCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 2)
return JSValueMakeUndefined(context);
auto orientation = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto policy = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setScrollbarPolicy(orientation.get(), policy.get());
return JSValueMakeUndefined(context);
}
static JSValueRef addUserScriptCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 3)
return JSValueMakeUndefined(context);
auto source = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
bool runAtStart = JSValueToBoolean(context, arguments[1]);
bool allFrames = JSValueToBoolean(context, arguments[2]);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->addUserScript(source.get(), runAtStart, allFrames);
return JSValueMakeUndefined(context);
}
static JSValueRef addUserStyleSheetCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 2)
return JSValueMakeUndefined(context);
auto source = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
bool allFrames = JSValueToBoolean(context, arguments[1]);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->addUserStyleSheet(source.get(), allFrames);
return JSValueMakeUndefined(context);
}
static JSValueRef setShouldPaintBrokenImageCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setShouldPaintBrokenImage(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef apiTestNewWindowDataLoadBaseURLCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 2)
return JSValueMakeUndefined(context);
auto utf8Data = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto baseURL = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->apiTestNewWindowDataLoadBaseURL(utf8Data.get(), baseURL.get());
return JSValueMakeUndefined(context);
}
static JSValueRef apiTestGoToCurrentBackForwardItemCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->apiTestGoToCurrentBackForwardItem();
return JSValueMakeUndefined(context);
}
static JSValueRef setWebViewEditableCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Mac implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setWebViewEditable(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef abortModalCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->abortModal();
return JSValueMakeUndefined(context);
}
static JSValueRef authenticateSessionCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// authenticateSession(url, username, password)
if (argumentCount != 3)
return JSValueMakeUndefined(context);
auto url = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
auto username = adopt(JSValueToStringCopy(context, arguments[1], exception));
ASSERT(!*exception);
auto password = adopt(JSValueToStringCopy(context, arguments[2], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->authenticateSession(url.get(), username.get(), password.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setSerializeHTTPLoadsCallback(JSContextRef context, JSObjectRef, JSObjectRef, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
bool serialize = true;
if (argumentCount == 1)
serialize = JSValueToBoolean(context, arguments[0]);
TestRunner::setSerializeHTTPLoads(serialize);
return JSValueMakeUndefined(context);
}
static JSValueRef setShouldStayOnPageAfterHandlingBeforeUnloadCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
if (argumentCount == 1)
controller->setShouldStayOnPageAfterHandlingBeforeUnload(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef addChromeInputFieldCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->addChromeInputField();
// the first argument is a callback that is called once the input field has been added
if (argumentCount == 1)
JSObjectCallAsFunction(context, JSValueToObject(context, arguments[0], 0), thisObject, 0, 0, 0);
return JSValueMakeUndefined(context);
}
static JSValueRef removeChromeInputFieldCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->removeChromeInputField();
// the first argument is a callback that is called once the input field has been added
if (argumentCount == 1)
JSObjectCallAsFunction(context, JSValueToObject(context, arguments[0], 0), thisObject, 0, 0, 0);
return JSValueMakeUndefined(context);
}
static JSValueRef focusWebViewCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->focusWebView();
// the first argument is a callback that is called once the input field has been added
if (argumentCount == 1)
JSObjectCallAsFunction(context, JSValueToObject(context, arguments[0], 0), thisObject, 0, 0, 0);
return JSValueMakeUndefined(context);
}
static JSValueRef setBackingScaleFactorCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 2)
return JSValueMakeUndefined(context);
double backingScaleFactor = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setBackingScaleFactor(backingScaleFactor);
// The second argument is a callback that is called once the backing scale factor has been set.
JSObjectCallAsFunction(context, JSValueToObject(context, arguments[1], 0), thisObject, 0, 0, 0);
return JSValueMakeUndefined(context);
}
static JSValueRef preciseTimeCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
return JSValueMakeNumber(context, WallTime::now().secondsSinceEpoch().seconds());
}
static JSValueRef imageCountInGeneralPasteboardCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has mac & windows implementation
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->imageCountInGeneralPasteboard());
}
static JSValueRef setSpellCheckerLoggingEnabledCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setSpellCheckerLoggingEnabled(JSValueToBoolean(context, arguments[0]));
return JSValueMakeUndefined(context);
}
static JSValueRef setOpenPanelFilesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount == 1)
static_cast<TestRunner*>(JSObjectGetPrivate(thisObject))->setOpenPanelFiles(context, arguments[0]);
return JSValueMakeUndefined(context);
}
static JSValueRef SetOpenPanelFilesMediaIconCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
#if PLATFORM(IOS_FAMILY)
if (argumentCount == 1)
static_cast<TestRunner*>(JSObjectGetPrivate(thisObject))->setOpenPanelFilesMediaIcon(context, arguments[0]);
#endif
return JSValueMakeUndefined(context);
}
// Static Values
static JSValueRef getTimeoutCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->timeout());
}
static JSValueRef getGlobalFlagCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeBoolean(context, controller->globalFlag());
}
static JSValueRef getDidCancelClientRedirect(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeBoolean(context, controller->didCancelClientRedirect());
}
static JSValueRef getDatabaseDefaultQuotaCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->databaseDefaultQuota());
}
static JSValueRef getDatabaseMaxQuotaCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->databaseMaxQuota());
}
static JSValueRef getWebHistoryItemCountCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
return JSValueMakeNumber(context, controller->webHistoryItemCount());
}
static JSValueRef getSecureEventInputIsEnabledCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
#if PLATFORM(MAC) && !PLATFORM(IOS_FAMILY)
return JSValueMakeBoolean(context, IsSecureEventInputEnabled());
#else
return JSValueMakeBoolean(context, false);
#endif
}
static JSValueRef getTitleTextDirectionCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto titleDirection = adopt(JSStringCreateWithUTF8CString(controller->titleTextDirection().c_str()));
return JSValueMakeString(context, titleDirection.get());
}
static JSValueRef getInspectorTestStubURLCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto url = controller->inspectorTestStubURL();
return JSValueMakeString(context, url.get());
}
static bool setGlobalFlagCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setGlobalFlag(JSValueToBoolean(context, value));
return true;
}
static bool setDatabaseDefaultQuotaCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDatabaseDefaultQuota(JSValueToNumber(context, value, exception));
ASSERT(!*exception);
return true;
}
static bool setDatabaseMaxQuotaCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setDatabaseMaxQuota(JSValueToNumber(context, value, exception));
ASSERT(!*exception);
return true;
}
static JSValueRef ignoreLegacyWebNotificationPermissionRequestsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->ignoreLegacyWebNotificationPermissionRequests();
return JSValueMakeUndefined(context);
}
static JSValueRef simulateLegacyWebNotificationClickCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto title = adopt(JSValueToStringCopy(context, arguments[0], exception));
controller->simulateLegacyWebNotificationClick(title.get());
return JSValueMakeUndefined(context);
}
static JSValueRef setTextDirectionCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount == 1) {
auto direction = adopt(JSValueToStringCopy(context, arguments[0], exception));
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setTextDirection(direction.get());
}
return JSValueMakeUndefined(context);
}
static JSValueRef setHasCustomFullScreenBehaviorCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount == 1) {
bool hasCustomBehavior = JSValueToBoolean(context, arguments[0]);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setHasCustomFullScreenBehavior(hasCustomBehavior);
}
return JSValueMakeUndefined(context);
}
static JSValueRef setStorageDatabaseIdleIntervalCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount != 1)
return JSValueMakeUndefined(context);
double interval = JSValueToNumber(context, arguments[0], exception);
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setStorageDatabaseIdleInterval(interval);
return JSValueMakeUndefined(context);
}
static JSValueRef closeIdleLocalStorageDatabasesCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->closeIdleLocalStorageDatabases();
return JSValueMakeUndefined(context);
}
static JSValueRef grantWebNotificationPermissionCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto origin = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
controller->grantWebNotificationPermission(origin.get());
return JSValueMakeUndefined(context);
}
static JSValueRef denyWebNotificationPermissionCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
auto origin = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
controller->denyWebNotificationPermission(origin.get());
return JSValueMakeUndefined(context);
}
static JSValueRef removeAllWebNotificationPermissionsCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->removeAllWebNotificationPermissions();
return JSValueMakeUndefined(context);
}
static JSValueRef simulateWebNotificationClickCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Has Windows implementation
if (argumentCount < 1)
return JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->simulateWebNotificationClick(arguments[0]);
return JSValueMakeUndefined(context);
}
static JSValueRef forceImmediateCompletionCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->forceImmediateCompletion();
return JSValueMakeUndefined(context);
}
static JSValueRef failNextNewCodeBlock(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
return JSC::failNextNewCodeBlock(context);
}
static JSValueRef numberOfDFGCompiles(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
return JSC::numberOfDFGCompiles(context, arguments[0]);
}
static JSValueRef neverInlineFunction(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
return JSC::setNeverInline(context, arguments[0]);
}
static JSValueRef accummulateLogsForChannel(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto channel = adopt(JSValueToStringCopy(context, arguments[0], exception));
ASSERT(!*exception);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->setAccummulateLogsForChannel(channel.get());
return JSValueMakeUndefined(context);
}
static JSValueRef runUIScriptCallback(JSContextRef context, JSObjectRef, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 1)
return JSValueMakeUndefined(context);
auto script = argumentCount > 0 ? adopt(JSValueToStringCopy(context, arguments[0], 0)) : JSRetainPtr<JSStringRef>();
JSValueRef callback = argumentCount > 1 ? arguments[1] : JSValueMakeUndefined(context);
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(thisObject));
controller->runUIScript(context, script.get(), callback);
return JSValueMakeUndefined(context);
}
static void testRunnerObjectFinalize(JSObjectRef object)
{
TestRunner* controller = static_cast<TestRunner*>(JSObjectGetPrivate(object));
controller->deref();
}
// Object Creation
void TestRunner::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
{
auto testRunnerStr = adopt(JSStringCreateWithUTF8CString("testRunner"));
ref();
JSClassRef classRef = getJSClass();
JSValueRef layoutTestContollerObject = JSObjectMake(context, classRef, this);
JSClassRelease(classRef);
JSObjectSetProperty(context, windowObject, testRunnerStr.get(), layoutTestContollerObject, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
}
JSClassRef TestRunner::getJSClass()
{
static JSStaticValue* staticValues = TestRunner::staticValues();
static JSStaticFunction* staticFunctions = TestRunner::staticFunctions();
static JSClassDefinition classDefinition = {
0, kJSClassAttributeNone, "TestRunner", 0, staticValues, staticFunctions,
0, testRunnerObjectFinalize, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
return JSClassCreate(&classDefinition);
}
// Constants
static JSValueRef getRENDER_TREE_SHOW_ALL_LAYERS(JSContextRef context, JSObjectRef, JSStringRef, JSValueRef*)
{
return JSValueMakeNumber(context, 1);
}
static JSValueRef getRENDER_TREE_SHOW_LAYER_NESTING(JSContextRef context, JSObjectRef, JSStringRef, JSValueRef*)
{
return JSValueMakeNumber(context, 2);
}
static JSValueRef getRENDER_TREE_SHOW_COMPOSITED_LAYERS(JSContextRef context, JSObjectRef, JSStringRef, JSValueRef*)
{
return JSValueMakeNumber(context, 4);
}
static JSValueRef getRENDER_TREE_SHOW_OVERFLOW(JSContextRef context, JSObjectRef, JSStringRef, JSValueRef*)
{
return JSValueMakeNumber(context, 8);
}
static JSValueRef getRENDER_TREE_SHOW_SVG_GEOMETRY(JSContextRef context, JSObjectRef, JSStringRef, JSValueRef*)
{
return JSValueMakeNumber(context, 16);
}
static JSValueRef getRENDER_TREE_SHOW_LAYER_FRAGMENTS(JSContextRef context, JSObjectRef, JSStringRef, JSValueRef*)
{
return JSValueMakeNumber(context, 32);
}
JSStaticValue* TestRunner::staticValues()
{
static JSStaticValue staticValues[] = {
{ "didCancelClientRedirect", getDidCancelClientRedirect, 0, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "timeout", getTimeoutCallback, 0, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "globalFlag", getGlobalFlagCallback, setGlobalFlagCallback, kJSPropertyAttributeNone },
{ "webHistoryItemCount", getWebHistoryItemCountCallback, 0, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "secureEventInputIsEnabled", getSecureEventInputIsEnabledCallback, 0, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "titleTextDirection", getTitleTextDirectionCallback, 0, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "databaseDefaultQuota", getDatabaseDefaultQuotaCallback, setDatabaseDefaultQuotaCallback, kJSPropertyAttributeNone },
{ "databaseMaxQuota", getDatabaseMaxQuotaCallback, setDatabaseMaxQuotaCallback, kJSPropertyAttributeNone },
{ "inspectorTestStubURL", getInspectorTestStubURLCallback, 0, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "RENDER_TREE_SHOW_ALL_LAYERS", getRENDER_TREE_SHOW_ALL_LAYERS, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "RENDER_TREE_SHOW_LAYER_NESTING", getRENDER_TREE_SHOW_LAYER_NESTING, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "RENDER_TREE_SHOW_COMPOSITED_LAYERS", getRENDER_TREE_SHOW_COMPOSITED_LAYERS, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "RENDER_TREE_SHOW_OVERFLOW", getRENDER_TREE_SHOW_OVERFLOW, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "RENDER_TREE_SHOW_SVG_GEOMETRY", getRENDER_TREE_SHOW_SVG_GEOMETRY, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ "RENDER_TREE_SHOW_LAYER_FRAGMENTS", getRENDER_TREE_SHOW_LAYER_FRAGMENTS, 0, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
{ 0, 0, 0, 0 }
};
return staticValues;
}
JSStaticFunction* TestRunner::staticFunctions()
{
static JSStaticFunction staticFunctions[] = {
{ "abortModal", abortModalCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "addDisallowedURL", addDisallowedURLCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "addURLToRedirect", addURLToRedirectCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "addUserScript", addUserScriptCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "addUserStyleSheet", addUserStyleSheetCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "apiTestNewWindowDataLoadBaseURL", apiTestNewWindowDataLoadBaseURLCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "apiTestGoToCurrentBackForwardItem", apiTestGoToCurrentBackForwardItemCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "applicationCacheDiskUsageForOrigin", applicationCacheDiskUsageForOriginCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "callShouldCloseOnWebView", callShouldCloseOnWebViewCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "clearAllApplicationCaches", clearAllApplicationCachesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "clearAllDatabases", clearAllDatabasesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "clearApplicationCacheForOrigin", clearApplicationCacheForOriginCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "clearBackForwardList", clearBackForwardListCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "clearPersistentUserStyleSheet", clearPersistentUserStyleSheetCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "closeWebInspector", closeWebInspectorCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "decodeHostName", decodeHostNameCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "disallowIncreaseForApplicationCacheQuota", disallowIncreaseForApplicationCacheQuotaCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dispatchPendingLoadRequests", dispatchPendingLoadRequestsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "display", displayCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "displayAndTrackRepaints", displayAndTrackRepaintsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpApplicationCacheDelegateCallbacks", dumpApplicationCacheDelegateCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setRenderTreeDumpOptions", setRenderTreeDumpOptionsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpAsText", dumpAsTextCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpBackForwardList", dumpBackForwardListCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpChildFrameScrollPositions", dumpChildFrameScrollPositionsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpChildFramesAsText", dumpChildFramesAsTextCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpDOMAsWebArchive", dumpDOMAsWebArchiveCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpDatabaseCallbacks", dumpDatabaseCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpEditingCallbacks", dumpEditingCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpFrameLoadCallbacks", dumpFrameLoadCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpProgressFinishedCallback", dumpProgressFinishedCallbackCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpUserGestureInFrameLoadCallbacks", dumpUserGestureInFrameLoadCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpResourceLoadCallbacks", dumpResourceLoadCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpResourceResponseMIMETypes", dumpResourceResponseMIMETypesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpSelectionRect", dumpSelectionRectCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpSourceAsWebArchive", dumpSourceAsWebArchiveCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpStatusCallbacks", dumpStatusCallbacksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpTitleChanges", dumpTitleChangesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "dumpWillCacheResponse", dumpWillCacheResponseCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "encodeHostName", encodeHostNameCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "evaluateInWebInspector", evaluateInWebInspectorCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "evaluateScriptInIsolatedWorldAndReturnValue", evaluateScriptInIsolatedWorldAndReturnValueCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "evaluateScriptInIsolatedWorld", evaluateScriptInIsolatedWorldCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "execCommand", execCommandCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "findString", findStringCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "originsWithApplicationCache", originsWithApplicationCacheCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "goBack", goBackCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "ignoreLegacyWebNotificationPermissionRequests", ignoreLegacyWebNotificationPermissionRequestsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "isGeolocationProviderActive", isGeolocationProviderActiveCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "isCommandEnabled", isCommandEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "keepWebHistory", keepWebHistoryCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "numberOfPendingGeolocationPermissionRequests", numberOfPendingGeolocationPermissionRequestsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "notifyDone", notifyDoneCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "overridePreference", overridePreferenceCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "pathToLocalResource", pathToLocalResourceCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "printToPDF", dumpAsPDFCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueBackNavigation", queueBackNavigationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueForwardNavigation", queueForwardNavigationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueLoad", queueLoadCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueLoadHTMLString", queueLoadHTMLStringCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueLoadingScript", queueLoadingScriptCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueNonLoadingScript", queueNonLoadingScriptCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "queueReload", queueReloadCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "removeAllVisitedLinks", removeAllVisitedLinksCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "removeOriginAccessAllowListEntry", removeOriginAccessAllowListEntryCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "repaintSweepHorizontally", repaintSweepHorizontallyCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "resetPageVisibility", resetPageVisibilityCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAcceptsEditing", setAcceptsEditingCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAllowUniversalAccessFromFileURLs", setAllowUniversalAccessFromFileURLsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAllowFileAccessFromFileURLs", setAllowFileAccessFromFileURLsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setNeedsStorageAccessFromFileURLsQuirk", setNeedsStorageAccessFromFileURLsQuirkCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAllowsAnySSLCertificate", setAllowsAnySSLCertificateCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAlwaysAcceptCookies", setAlwaysAcceptCookiesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setOnlyAcceptFirstPartyCookies", setOnlyAcceptFirstPartyCookiesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAppCacheMaximumSize", setAppCacheMaximumSizeCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAudioResult", setAudioResultCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAuthenticationPassword", setAuthenticationPasswordCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAuthenticationUsername", setAuthenticationUsernameCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAuthorAndUserStylesEnabled", setAuthorAndUserStylesEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setCacheModel", setCacheModelCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setCallCloseOnWebViews", setCallCloseOnWebViewsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setCanOpenWindows", setCanOpenWindowsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setCloseRemainingWindowsWhenComplete", setCloseRemainingWindowsWhenCompleteCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setCustomPolicyDelegate", setCustomPolicyDelegateCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setDatabaseQuota", setDatabaseQuotaCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setDefersLoading", setDefersLoadingCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setUseDeferredFrameLoading", setUseDeferredFrameLoadingCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setDomainRelaxationForbiddenForURLScheme", setDomainRelaxationForbiddenForURLSchemeCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setGeolocationPermission", setGeolocationPermissionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setRejectsProtectionSpaceAndContinueForAuthenticationChallenges", setRejectsProtectionSpaceAndContinueForAuthenticationChallengesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setHandlesAuthenticationChallenges", setHandlesAuthenticationChallengesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setIconDatabaseEnabled", setIconDatabaseEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setAutomaticLinkDetectionEnabled", setAutomaticLinkDetectionEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setMainFrameIsFirstResponder", setMainFrameIsFirstResponderCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setMockDeviceOrientation", setMockDeviceOrientationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setMockGeolocationPositionUnavailableError", setMockGeolocationPositionUnavailableErrorCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setMockGeolocationPosition", setMockGeolocationPositionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setNewWindowsCopyBackForwardList", setNewWindowsCopyBackForwardListCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPageVisibility", setPageVisibilityCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPOSIXLocale", setPOSIXLocaleCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPersistentUserStyleSheetLocation", setPersistentUserStyleSheetLocationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPopupBlockingEnabled", setPopupBlockingEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPluginsEnabled", setPluginsEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPrinting", setPrintingCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPrivateBrowsingEnabled_DEPRECATED", setPrivateBrowsingEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setShouldSwapToEphemeralSessionOnNextNavigation", setShouldSwapToEphemeralSessionOnNextNavigationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setShouldSwapToDefaultSessionOnNextNavigation", setShouldSwapToDefaultSessionOnNextNavigationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setSerializeHTTPLoads", setSerializeHTTPLoadsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setSpatialNavigationEnabled", setSpatialNavigationEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setStopProvisionalFrameLoads", setStopProvisionalFrameLoadsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setTabKeyCyclesThroughElements", setTabKeyCyclesThroughElementsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
#if PLATFORM(IOS_FAMILY)
{ "setTelephoneNumberParsingEnabled", setTelephoneNumberParsingEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setPagePaused", setPagePausedCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
#endif
{ "setUserStyleSheetEnabled", setUserStyleSheetEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setUserStyleSheetLocation", setUserStyleSheetLocationCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setValueForUser", setValueForUserCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setWebViewEditable", setWebViewEditableCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setWillSendRequestClearHeader", setWillSendRequestClearHeaderCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setWillSendRequestReturnsNull", setWillSendRequestReturnsNullCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setWillSendRequestReturnsNullOnRedirect", setWillSendRequestReturnsNullOnRedirectCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setWindowIsKey", setWindowIsKeyCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setViewSize", setViewSizeCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setJavaScriptCanAccessClipboard", setJavaScriptCanAccessClipboardCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setXSSAuditorEnabled", setXSSAuditorEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "showWebInspector", showWebInspectorCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "simulateLegacyWebNotificationClick", simulateLegacyWebNotificationClickCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "testOnscreen", testOnscreenCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "testRepaint", testRepaintCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "waitForPolicyDelegate", waitForPolicyDelegateCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "waitUntilDone", waitUntilDoneCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "windowCount", windowCountCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "addOriginAccessAllowListEntry", addOriginAccessAllowListEntryCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setScrollbarPolicy", setScrollbarPolicyCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "authenticateSession", authenticateSessionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setShouldPaintBrokenImage", setShouldPaintBrokenImageCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setTextDirection", setTextDirectionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setShouldStayOnPageAfterHandlingBeforeUnload", setShouldStayOnPageAfterHandlingBeforeUnloadCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "addChromeInputField", addChromeInputFieldCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "removeChromeInputField", removeChromeInputFieldCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "focusWebView", focusWebViewCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setBackingScaleFactor", setBackingScaleFactorCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "preciseTime", preciseTimeCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setHasCustomFullScreenBehavior", setHasCustomFullScreenBehaviorCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setStorageDatabaseIdleInterval", setStorageDatabaseIdleIntervalCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "closeIdleLocalStorageDatabases", closeIdleLocalStorageDatabasesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "grantWebNotificationPermission", grantWebNotificationPermissionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "denyWebNotificationPermission", denyWebNotificationPermissionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "removeAllWebNotificationPermissions", removeAllWebNotificationPermissionsCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "simulateWebNotificationClick", simulateWebNotificationClickCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "failNextNewCodeBlock", failNextNewCodeBlock, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "numberOfDFGCompiles", numberOfDFGCompiles, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "neverInlineFunction", neverInlineFunction, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "accummulateLogsForChannel", accummulateLogsForChannel, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "runUIScript", runUIScriptCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "imageCountInGeneralPasteboard", imageCountInGeneralPasteboardCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setSpellCheckerLoggingEnabled", setSpellCheckerLoggingEnabledCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setOpenPanelFiles", setOpenPanelFilesCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "setOpenPanelFilesMediaIcon", SetOpenPanelFilesMediaIconCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ "forceImmediateCompletion", forceImmediateCompletionCallback, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
{ 0, 0, 0 }
};
return staticFunctions;
}
void TestRunner::queueLoadHTMLString(JSStringRef content, JSStringRef baseURL)
{
DRT::WorkQueue::singleton().queue(new LoadHTMLStringItem(content, baseURL));
}
void TestRunner::queueLoadAlternateHTMLString(JSStringRef content, JSStringRef baseURL, JSStringRef unreachableURL)
{
DRT::WorkQueue::singleton().queue(new LoadHTMLStringItem(content, baseURL, unreachableURL));
}
void TestRunner::queueBackNavigation(int howFarBack)
{
DRT::WorkQueue::singleton().queue(new BackItem(howFarBack));
}
void TestRunner::queueForwardNavigation(int howFarForward)
{
DRT::WorkQueue::singleton().queue(new ForwardItem(howFarForward));
}
void TestRunner::queueLoadingScript(JSStringRef script)
{
DRT::WorkQueue::singleton().queue(new LoadingScriptItem(script));
}
void TestRunner::queueNonLoadingScript(JSStringRef script)
{
DRT::WorkQueue::singleton().queue(new NonLoadingScriptItem(script));
}
void TestRunner::queueReload()
{
DRT::WorkQueue::singleton().queue(new ReloadItem);
}
void TestRunner::ignoreLegacyWebNotificationPermissionRequests()
{
m_areLegacyWebNotificationPermissionRequestsIgnored = false;
}
void TestRunner::waitToDumpWatchdogTimerFired()
{
const char* message = "FAIL: Timed out waiting for notifyDone to be called\n";
fprintf(testResult, "%s", message);
auto accumulatedLogs = getAndResetAccumulatedLogs();
if (!accumulatedLogs.isEmpty()) {
const char* message = "Logs accumulated during test run:\n";
fprintf(testResult, "%s%s\n", message, accumulatedLogs.utf8().data());
}
notifyDone();
}
void TestRunner::setGeolocationPermissionCommon(bool allow)
{
m_isGeolocationPermissionSet = true;
m_geolocationPermission = allow;
}
void TestRunner::setPOSIXLocale(JSStringRef locale)
{
char localeBuf[32];
JSStringGetUTF8CString(locale, localeBuf, sizeof(localeBuf));
setlocale(LC_ALL, localeBuf);
}
void TestRunner::addURLToRedirect(std::string origin, std::string destination)
{
m_URLsToRedirect[origin] = destination;
}
const char* TestRunner::redirectionDestinationForURL(const char* origin)
{
if (!origin)
return nullptr;
auto iterator = m_URLsToRedirect.find(origin);
if (iterator == m_URLsToRedirect.end())
return nullptr;
return iterator->second.data();
}
void TestRunner::setRenderTreeDumpOptions(unsigned options)
{
m_renderTreeDumpOptions = options;
}
void TestRunner::setShouldPaintBrokenImage(bool shouldPaintBrokenImage)
{
m_shouldPaintBrokenImage = shouldPaintBrokenImage;
}
void TestRunner::setAccummulateLogsForChannel(JSStringRef channel)
{
size_t maxLength = JSStringGetMaximumUTF8CStringSize(channel);
auto buffer = makeUniqueArray<char>(maxLength + 1);
JSStringGetUTF8CString(channel, buffer.get(), maxLength + 1);
WebCoreTestSupport::setLogChannelToAccumulate({ buffer.get() });
}
typedef WTF::HashMap<unsigned, JSValueRef> CallbackMap;
static CallbackMap& callbackMap()
{
static CallbackMap& map = *new CallbackMap;
return map;
}
void TestRunner::cacheTestRunnerCallback(unsigned index, JSValueRef callback)
{
if (!callback)
return;
if (callbackMap().contains(index)) {
fprintf(stderr, "FAIL: Tried to install a second TestRunner callback for the same event (id %d)\n", index);
return;
}
JSContextRef context = mainFrameJSContext();
JSValueProtect(context, callback);
callbackMap().add(index, callback);
}
void TestRunner::callTestRunnerCallback(unsigned index, size_t argumentCount, const JSValueRef arguments[])
{
if (!callbackMap().contains(index))
return;
JSContextRef context = mainFrameJSContext();
if (JSObjectRef callback = JSValueToObject(context, callbackMap().take(index), 0)) {
JSObjectCallAsFunction(context, callback, JSContextGetGlobalObject(context), argumentCount, arguments, 0);
JSValueUnprotect(context, callback);
}
}
void TestRunner::clearTestRunnerCallbacks()
{
JSContextRef context = mainFrameJSContext();
for (auto& iter : callbackMap()) {
if (JSObjectRef callback = JSValueToObject(context, iter.value, 0))
JSValueUnprotect(context, callback);
}
callbackMap().clear();
}
enum {
FirstUIScriptCallbackID = 100
};
static unsigned nextUIScriptCallbackID()
{
static unsigned callbackID = FirstUIScriptCallbackID;
return callbackID++;
}
void TestRunner::runUIScript(JSContextRef context, JSStringRef script, JSValueRef callback)
{
m_pendingUIScriptInvocationData = nullptr;
unsigned callbackID = nextUIScriptCallbackID();
cacheTestRunnerCallback(callbackID, callback);
if (!m_UIScriptContext)
m_UIScriptContext = makeUniqueWithoutFastMallocCheck<WTR::UIScriptContext>(*this);
String scriptString(reinterpret_cast<const UChar*>(JSStringGetCharactersPtr(script)), JSStringGetLength(script));
m_UIScriptContext->runUIScript(scriptString, callbackID);
}
void TestRunner::callUIScriptCallback(unsigned callbackID, JSStringRef result)
{
JSRetainPtr<JSStringRef> protectedResult(result);
#if !PLATFORM(IOS_FAMILY)
RunLoop::main().dispatch([protectedThis = makeRef(*this), callbackID, protectedResult]() mutable {
JSContextRef context = protectedThis->mainFrameJSContext();
JSValueRef resultValue = JSValueMakeString(context, protectedResult.get());
protectedThis->callTestRunnerCallback(callbackID, 1, &resultValue);
});
#else
WebThreadRun(
makeBlockPtr([protectedThis = makeRef(*this), callbackID, protectedResult] {
JSContextRef context = protectedThis->mainFrameJSContext();
JSValueRef resultValue = JSValueMakeString(context, protectedResult.get());
protectedThis->callTestRunnerCallback(callbackID, 1, &resultValue);
}).get()
);
#endif
}
void TestRunner::uiScriptDidComplete(const String& result, unsigned callbackID)
{
auto stringRef = adopt(JSStringCreateWithUTF8CString(result.utf8().data()));
callUIScriptCallback(callbackID, stringRef.get());
}
void TestRunner::setAllowsAnySSLCertificate(bool allowsAnySSLCertificate)
{
WebCoreTestSupport::setAllowsAnySSLCertificate(allowsAnySSLCertificate);
}
void TestRunner::setOpenPanelFiles(JSContextRef context, JSValueRef filesValue)
{
if (!JSValueIsArray(context, filesValue))
return;
JSObjectRef files = JSValueToObject(context, filesValue, nullptr);
static auto lengthProperty = adopt(JSStringCreateWithUTF8CString("length"));
JSValueRef filesLengthValue = JSObjectGetProperty(context, files, lengthProperty.get(), nullptr);
if (!JSValueIsNumber(context, filesLengthValue))
return;
m_openPanelFiles.clear();
auto filesLength = static_cast<size_t>(JSValueToNumber(context, filesLengthValue, nullptr));
for (size_t i = 0; i < filesLength; ++i) {
JSValueRef fileValue = JSObjectGetPropertyAtIndex(context, files, i, nullptr);
if (!JSValueIsString(context, fileValue))
continue;
auto file = adopt(JSValueToStringCopy(context, fileValue, nullptr));
size_t fileBufferSize = JSStringGetMaximumUTF8CStringSize(file.get()) + 1;
auto fileBuffer = makeUniqueArray<char>(fileBufferSize);
JSStringGetUTF8CString(file.get(), fileBuffer.get(), fileBufferSize);
m_openPanelFiles.push_back(fileBuffer.get());
}
}
#if PLATFORM(IOS_FAMILY)
void TestRunner::setOpenPanelFilesMediaIcon(JSContextRef context, JSValueRef mediaIcon)
{
// FIXME (123058): Use a JSC API to get buffer contents once such is exposed.
JSC::VM& vm = toJS(context)->vm();
JSC::JSLockHolder lock(vm);
JSC::JSArrayBufferView* jsBufferView = JSC::jsDynamicCast<JSC::JSArrayBufferView*>(vm, toJS(toJS(context), mediaIcon));
ASSERT(jsBufferView);
RefPtr<JSC::ArrayBufferView> bufferView = jsBufferView->unsharedImpl();
const char* buffer = static_cast<const char*>(bufferView->baseAddress());
std::vector<char> mediaIconData(buffer, buffer + bufferView->byteLength());
m_openPanelFilesMediaIcon = mediaIconData;
}
#endif
void TestRunner::cleanup()
{
clearTestRunnerCallbacks();
}
void TestRunner::willNavigate()
{
if (m_shouldSwapToEphemeralSessionOnNextNavigation || m_shouldSwapToDefaultSessionOnNextNavigation) {
ASSERT(m_shouldSwapToEphemeralSessionOnNextNavigation != m_shouldSwapToDefaultSessionOnNextNavigation);
setPrivateBrowsingEnabled(m_shouldSwapToEphemeralSessionOnNextNavigation);
m_shouldSwapToEphemeralSessionOnNextNavigation = false;
m_shouldSwapToDefaultSessionOnNextNavigation = false;
}
}
| 49.71306 | 236 | 0.788847 | [
"object",
"vector"
] |
9454aaf06b59d91d6343b40eba84689ab78d5019 | 13,347 | hpp | C++ | Source/TitaniumKit/include/Titanium/Network/HTTPClient.hpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/TitaniumKit/include/Titanium/Network/HTTPClient.hpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/TitaniumKit/include/Titanium/Network/HTTPClient.hpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _TITANIUM_NETWORK_HTTPCLIENT_HPP_
#define _TITANIUM_NETWORK_HTTPCLIENT_HPP_
#include "Titanium/Module.hpp"
#include "Titanium/Blob.hpp"
#include "Titanium/Network/Constants.hpp"
#define BOOST_BIND_NO_PLACEHOLDERS
#include <boost/signals2/signal.hpp>
namespace Titanium
{
namespace Network
{
enum class RequestState {
Unsent,
Opened,
Headers_Received,
Loading,
Done
};
enum class RequestMethod {
Get,
Put,
Post,
Delete,
Head,
Patch,
Options
};
using namespace HAL;
/*!
@class
@discussion This is the Titanium.Network.HTTPClient module.
See http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Network.HTTPClient
*/
class TITANIUMKIT_EXPORT HTTPClient : public Module, public JSExport<HTTPClient>
{
public:
/*!
@property
@abstract allResponseHeaders
@discussion All of the response headers.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::string, allResponseHeaders);
/*!
@property
@abstract autoEncodeUrl
@discussion Determines whether automatic encoding is enabled for the specified URL.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, autoEncodeUrl);
/*!
@property
@abstract autoRedirect
@discussion Determines whether automatic automatic handling of HTTP redirects is enabled.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, autoRedirect);
/*!
@property
@abstract connected
@discussion Indicates whether the response was successful.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(bool, connected);
/*!
@property
@abstract connectionType
@discussion Connection type, normally either `GET` or `POST`.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::string, connectionType);
/*!
@property
@abstract domain
@discussion Sets the domain parameter for authentication credentials.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::string, domain);
/*!
@property
@abstract enableKeepAlive
@discussion Determines whether the client should attempt to keep a persistent connection.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, enableKeepAlive);
/*!
@property
@abstract file
@discussion Target local file to receive data.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::string, file);
/*!
@property
@abstract location
@discussion Absolute URL of the request.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::string, location);
/*!
@property
@abstract password
@discussion Sets the password parameter for authentication credentials.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::string, password);
/*!
@property
@abstract readyState
@discussion The current ready state of this HTTP request.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(RequestState, readyState);
/*!
@property
@abstract responseData
@discussion Response data as a `Blob` object.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::vector<std::uint8_t>, responseData);
/*!
@property
@abstract responseText
@discussion Response as text.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::string, responseText);
/*!
@property
@abstract status
@discussion Response HTTP status code.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::uint32_t, status);
/*!
@property
@abstract statusText
@discussion Human-readable status message associated with the status code.
*/
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::string, statusText);
/*!
@property
@abstract timeout
@discussion Timeout in milliseconds when the connection should be aborted.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::chrono::milliseconds, timeout);
/*!
@property
@abstract username
@discussion Sets the username parameter for authentication credentials.
*/
TITANIUM_PROPERTY_IMPL_DEF(std::string, username);
/*!
@property
@abstract validatesSecureCertificate
@discussion Determines how SSL certification validation is performed on connection.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, validatesSecureCertificate);
/*!
@property
@abstract withCredentials
@discussion Determines whether the request should include any cookies and HTTP authentication information.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, withCredentials);
/*!
@property
@abstract tlsVersion
@discussion Sets the TLS version to use for handshakes.
*/
TITANIUM_PROPERTY_IMPL_DEF(TLS_VERSION, tlsVersion);
/*!
@property
@abstract cache
@discussion Determines whether HTTP responses are cached.
*/
TITANIUM_PROPERTY_IMPL_DEF(bool, cache);
// ----------------------------------------- Methods
/*!
@method
@abstract abort
@discussion Cancel the current HTTP request.
*/
virtual void abort() TITANIUM_NOEXCEPT;
/*!
@method
@abstract clearCookies
@discussion Delete all cookies associated with the domain (url).
*/
virtual void clearCookies(const std::string& url) TITANIUM_NOEXCEPT;
/*!
@method
@abstract getResponseHeader
@discussion Get the header based on the key name.
*/
virtual std::string getResponseHeader(const std::string& key) TITANIUM_NOEXCEPT;
/*!
@method
@abstract open
@discussion Initiate the connect between the client and the server.
*/
virtual void open(const std::string& method, const std::string& url) TITANIUM_NOEXCEPT;
/*!
@method
@abstract send
@discussion Do an HTTP GET request.
*/
virtual void send() TITANIUM_NOEXCEPT;
/*!
@method
@abstract send
@discussion Do an HTTP POST or PUT request with data URL encoded or contained in multipart form.
*/
virtual void send(const std::map<std::string, JSValue>& postDataPairs, const bool& useMultipartForm) TITANIUM_NOEXCEPT;
/*!
@method
@abstract send
@discussion Do an HTTP POST or PUT request with data type text in body.
*/
virtual void send(const std::string& postDataStr) TITANIUM_NOEXCEPT;
/*!
@method
@abstract setRequestHeader
@discussion Set the header key:value pair sent to the server.
*/
virtual void setRequestHeader(const std::string& key, const std::string& value) TITANIUM_NOEXCEPT;
/*!
@method
@abstract _waitForResponse
@discussion Wait for response for the request. Blocks until server responses.
*/
virtual void _waitForResponse() TITANIUM_NOEXCEPT;
HTTPClient(const JSContext&) TITANIUM_NOEXCEPT;
virtual ~HTTPClient() = default;
HTTPClient(const HTTPClient&) = default;
HTTPClient& operator=(const HTTPClient&) = default;
#ifdef TITANIUM_MOVE_CTOR_AND_ASSIGN_DEFAULT_ENABLE
HTTPClient(HTTPClient&&) = default;
HTTPClient& operator=(HTTPClient&&) = default;
#endif
static void JSExportInitialize();
TITANIUM_PROPERTY_DEF(autoEncodeUrl);
TITANIUM_PROPERTY_DEF(autoRedirect);
TITANIUM_PROPERTY_DEF(cache);
TITANIUM_PROPERTY_DEF(domain);
TITANIUM_PROPERTY_DEF(enableKeepAlive);
TITANIUM_PROPERTY_DEF(file);
TITANIUM_PROPERTY_DEF(ondatastream);
TITANIUM_PROPERTY_DEF(onerror);
TITANIUM_PROPERTY_DEF(onload);
TITANIUM_PROPERTY_DEF(onreadystatechange);
TITANIUM_PROPERTY_DEF(onsendstream);
TITANIUM_PROPERTY_DEF(password);
TITANIUM_PROPERTY_DEF(securityManager);
TITANIUM_PROPERTY_DEF(timeout);
TITANIUM_PROPERTY_DEF(tlsVersion);
TITANIUM_PROPERTY_DEF(username);
TITANIUM_PROPERTY_DEF(validatesSecureCertificate);
TITANIUM_PROPERTY_DEF(withCredentials);
TITANIUM_PROPERTY_READONLY_DEF(DONE);
TITANIUM_PROPERTY_READONLY_DEF(HEADERS_RECEIVED);
TITANIUM_PROPERTY_READONLY_DEF(LOADING);
TITANIUM_PROPERTY_READONLY_DEF(OPENED);
TITANIUM_PROPERTY_READONLY_DEF(UNSENT);
TITANIUM_PROPERTY_READONLY_DEF(allResponseHeaders);
TITANIUM_PROPERTY_READONLY_DEF(connected);
TITANIUM_PROPERTY_READONLY_DEF(connectionType);
TITANIUM_PROPERTY_READONLY_DEF(location);
TITANIUM_PROPERTY_READONLY_DEF(readyState);
TITANIUM_PROPERTY_READONLY_DEF(responseData);
TITANIUM_PROPERTY_READONLY_DEF(responseText);
TITANIUM_PROPERTY_READONLY_DEF(responseXML);
TITANIUM_PROPERTY_READONLY_DEF(status);
TITANIUM_PROPERTY_READONLY_DEF(statusText);
TITANIUM_FUNCTION_DEF(abort);
TITANIUM_FUNCTION_DEF(addAuthFactory);
TITANIUM_FUNCTION_DEF(addKeyManager);
TITANIUM_FUNCTION_DEF(addTrustManager);
TITANIUM_FUNCTION_DEF(clearCookies);
TITANIUM_FUNCTION_DEF(getAllResponseHeaders);
TITANIUM_FUNCTION_DEF(getAutoEncodeUrl);
TITANIUM_FUNCTION_DEF(getAutoRedirect);
TITANIUM_FUNCTION_DEF(getCache);
TITANIUM_FUNCTION_DEF(getConnected);
TITANIUM_FUNCTION_DEF(getConnectionType);
TITANIUM_FUNCTION_DEF(getDomain);
TITANIUM_FUNCTION_DEF(getEnableKeepAlive);
TITANIUM_FUNCTION_DEF(getFile);
TITANIUM_FUNCTION_DEF(getLocation);
TITANIUM_FUNCTION_DEF(getOndatastream);
TITANIUM_FUNCTION_DEF(getOnerror);
TITANIUM_FUNCTION_DEF(getOnload);
TITANIUM_FUNCTION_DEF(getOnreadystatechange);
TITANIUM_FUNCTION_DEF(getOnsendstream);
TITANIUM_FUNCTION_DEF(getPassword);
TITANIUM_FUNCTION_DEF(getReadyState);
TITANIUM_FUNCTION_DEF(getResponseData);
TITANIUM_FUNCTION_DEF(getResponseHeader);
TITANIUM_FUNCTION_DEF(getResponseText);
TITANIUM_FUNCTION_DEF(getResponseXML);
TITANIUM_FUNCTION_DEF(getSecurityManager);
TITANIUM_FUNCTION_DEF(getStatus);
TITANIUM_FUNCTION_DEF(getStatusText);
TITANIUM_FUNCTION_DEF(getTimeout);
TITANIUM_FUNCTION_DEF(getTlsVersion);
TITANIUM_FUNCTION_DEF(getUsername);
TITANIUM_FUNCTION_DEF(getValidatesSecureCertificate);
TITANIUM_FUNCTION_DEF(getWithCredentials);
TITANIUM_FUNCTION_DEF(open);
TITANIUM_FUNCTION_DEF(send);
TITANIUM_FUNCTION_DEF(setAutoEncodeUrl);
TITANIUM_FUNCTION_DEF(setAutoRedirect);
TITANIUM_FUNCTION_DEF(setCache);
TITANIUM_FUNCTION_DEF(setDomain);
TITANIUM_FUNCTION_DEF(setEnableKeepAlive);
TITANIUM_FUNCTION_DEF(setFile);
TITANIUM_FUNCTION_DEF(setOndatastream);
TITANIUM_FUNCTION_DEF(setOnerror);
TITANIUM_FUNCTION_DEF(setOnload);
TITANIUM_FUNCTION_DEF(setOnreadystatechange);
TITANIUM_FUNCTION_DEF(setOnsendstream);
TITANIUM_FUNCTION_DEF(setPassword);
TITANIUM_FUNCTION_DEF(setRequestHeader);
TITANIUM_FUNCTION_DEF(setSecurityManager);
TITANIUM_FUNCTION_DEF(setTimeout);
TITANIUM_FUNCTION_DEF(setTlsVersion);
TITANIUM_FUNCTION_DEF(setUsername);
TITANIUM_FUNCTION_DEF(setValidatesSecureCertificate);
TITANIUM_FUNCTION_DEF(setWithCredentials);
TITANIUM_FUNCTION_DEF(_waitForResponse);
/////// slots
void ondatastream(const double progress) TITANIUM_NOEXCEPT;
void onerror(const std::uint32_t id, const std::string error, const bool success) TITANIUM_NOEXCEPT;
void onload(const std::uint32_t id, const std::string error, const bool success) TITANIUM_NOEXCEPT;
void onreadystatechange(const RequestState& state) TITANIUM_NOEXCEPT;
void onsendstream(const double progress) TITANIUM_NOEXCEPT;
#pragma warning(push)
#pragma warning(disable: 4251)
/////// signals
boost::signals2::signal<void(const double progress)> datastream;
boost::signals2::signal<void(const std::uint32_t code, const std::string error, const bool success)> error;
boost::signals2::signal<void(const std::uint32_t code, const std::string error, const bool success)> loaded;
boost::signals2::signal<void(const RequestState& state)> readystatechange;
boost::signals2::signal<void(const double progress)> sendstream;
#pragma warning(pop)
protected:
#pragma warning(push)
#pragma warning(disable: 4251)
JSValue ondatastream__;
JSValue onerror__;
JSValue onload__;
JSValue onreadystatechange__;
JSValue onsendstream__;
std::chrono::milliseconds timeout__;
std::map<uint32_t, std::string> httpStatusPhrase__;
JSValue done__;
JSValue headers_received__;
JSValue loading__;
JSValue opened__;
JSValue unsent__;
std::string allResponseHeaders__;
bool autoEncodeUrl__;
bool autoRedirect__;
bool connected__;
std::string connectionType__;
std::string domain__;
bool enableKeepAlive__;
std::string file__;
std::string location__;
std::string password__;
RequestState readyState__;
std::vector<std::uint8_t> responseData__;
JSValue securityManager__;
std::uint32_t status__;
std::string statusText__;
std::string username__;
bool validatesSecureCertificate__;
bool withCredentials__;
TLS_VERSION tlsVersion__;
bool cache__;
#pragma warning(pop)
void setHTTPStatusPhrase();
};
} // namespace Network
} // namespace Titanium
#endif // _TITANIUM_NETWORK_HTTPCLIENT_HPP_
| 31.111888 | 123 | 0.721885 | [
"object",
"vector"
] |
945a9e47a59cfa5677a38943ed68b2a567b4fe1e | 2,236 | cxx | C++ | src/mlio/text_line_reader.cxx | rizwangilani/ml-io | d9572227281168139c4e99d79a6d2ebc83323a61 | [
"Apache-2.0"
] | null | null | null | src/mlio/text_line_reader.cxx | rizwangilani/ml-io | d9572227281168139c4e99d79a6d2ebc83323a61 | [
"Apache-2.0"
] | 2 | 2020-04-08T01:37:44.000Z | 2020-04-14T20:14:07.000Z | src/mlio/text_line_reader.cxx | rizwangilani/ml-io | d9572227281168139c4e99d79a6d2ebc83323a61 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 "mlio/text_line_reader.h"
#include <string>
#include "mlio/cpu_array.h"
#include "mlio/instance.h"
#include "mlio/instance_batch.h"
#include "mlio/record_readers/text_line_record_reader.h"
#include "mlio/streams/utf8_input_stream.h"
using mlio::detail::text_line_record_reader;
namespace mlio {
inline namespace v1 {
text_line_reader::text_line_reader(data_reader_params rdr_prm)
: parallel_data_reader{std::move(rdr_prm)}
{}
text_line_reader::~text_line_reader()
{
stop();
}
intrusive_ptr<record_reader>
text_line_reader::make_record_reader(data_store const &ds)
{
auto strm = make_utf8_stream(ds.open_read());
return make_intrusive<text_line_record_reader>(std::move(strm), false);
}
intrusive_ptr<schema const>
text_line_reader::infer_schema(std::optional<instance> const &)
{
std::vector<attribute> attrs{
attribute{"value", data_type::string, {params().batch_size, 1}}};
return make_intrusive<schema>(std::move(attrs));
}
intrusive_ptr<example>
text_line_reader::decode(instance_batch const &batch) const
{
std::vector<std::string> strs{};
strs.reserve(batch.instances().size());
for (instance const &ins : batch.instances()) {
auto tmp = as_span<char const>(ins.bits());
strs.emplace_back(tmp.data(), 0, tmp.size());
}
size_vector shp{batch.size(), 1};
auto arr = wrap_cpu_array<data_type::string>(std::move(strs));
std::vector<intrusive_ptr<tensor>> tensors{
make_intrusive<dense_tensor>(std::move(shp), std::move(arr))};
return make_intrusive<example>(get_schema(), std::move(tensors));
}
} // namespace v1
} // namespace mlio
| 28.303797 | 75 | 0.720036 | [
"vector"
] |
9463285fa9f2dfcadda48ba22bd6bcf7c3cca783 | 1,785 | cpp | C++ | LeetCode/cpp/37.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 279 | 2019-02-19T16:00:32.000Z | 2022-03-23T12:16:30.000Z | LeetCode/cpp/37.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 2 | 2019-03-31T08:03:06.000Z | 2021-03-07T04:54:32.000Z | LeetCode/cpp/37.cpp | ZintrulCre/LeetCode_Crawler | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 12 | 2019-01-29T11:45:32.000Z | 2019-02-04T16:31:46.000Z | class Solution {
public:
void solveSudoku(vector<vector<char>> &board) {
vector<vector<bool>> row(9, vector<bool>(9, false)), col(9, vector<bool>(9, false));
vector<vector<vector<bool>>> square(3, vector<vector<bool>>(3, vector<bool>(9, false)));
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (board[i][j] != '.') {
row[i][board[i][j] - '0' - 1] = true;
col[j][board[i][j] - '0' - 1] = true;
square[i / 3][j / 3][board[i][j] - '0' - 1] = true;
}
}
}
Backtrack(0, 0, board, row, col, square);
}
bool Backtrack(int i, int j, vector<vector<char>> &board, vector<vector<bool>> &row, vector<vector<bool>> &col,
vector<vector<vector<bool>>> &square) {
if (i == 9)
return true;
if (board[i][j] != '.') {
if (Backtrack(j == 8 ? i + 1 : i, j == 8 ? 0 : j + 1, board, row, col, square))
return true;
} else {
for (int k = 1; k <= 9; ++k) {
if (row[i][k - 1] || col[j][k - 1] || square[i / 3][j / 3][k - 1])
continue;
board[i][j] = static_cast<char>('0' + k);
row[i][k - 1] = true;
col[j][k - 1] = true;
square[i / 3][j / 3][k - 1] = true;
if (Backtrack(j == 8 ? i + 1 : i, j == 8 ? 0 : j + 1, board, row, col, square))
return true;
board[i][j] = '.';
row[i][k - 1] = false;
col[j][k - 1] = false;
square[i / 3][j / 3][k - 1] = false;
}
}
return false;
}
};
| 40.568182 | 115 | 0.391597 | [
"vector"
] |
946cc7ad30a71f068e8710cdb6c9c8f992300b60 | 2,927 | cpp | C++ | test/manipulate_test.cpp | MCWertGaming/foxterm | 3f884c64100f2f0d4c7c07b56a2b8b093424c06c | [
"MIT"
] | 1 | 2021-10-02T11:23:05.000Z | 2021-10-02T11:23:05.000Z | test/manipulate_test.cpp | MCWertGaming/foxterm | 3f884c64100f2f0d4c7c07b56a2b8b093424c06c | [
"MIT"
] | 1 | 2021-10-05T15:57:23.000Z | 2021-10-05T15:57:23.000Z | test/manipulate_test.cpp | MCWertGaming/foxterm | 3f884c64100f2f0d4c7c07b56a2b8b093424c06c | [
"MIT"
] | 1 | 2021-10-30T23:52:53.000Z | 2021-10-30T23:52:53.000Z | #include <foxterm/manipulate.hpp>
#include <gtest/gtest.h>
TEST(manipulate_test, cursor_up) {
EXPECT_EQ(Fterm::cursor_up(1), "\033[A");
EXPECT_EQ(Fterm::cursor_up(3), "\033[3A");
EXPECT_EQ(Fterm::cursor_up(99), "\033[99A");
}
TEST(manipulate_test, cursor_down) {
EXPECT_EQ(Fterm::cursor_down(1), "\033[B");
EXPECT_EQ(Fterm::cursor_down(3), "\033[3B");
EXPECT_EQ(Fterm::cursor_down(99), "\033[99B");
}
TEST(manipulate_test, cursor_forward) {
EXPECT_EQ(Fterm::cursor_forward(1), "\033[C");
EXPECT_EQ(Fterm::cursor_forward(3), "\033[3C");
EXPECT_EQ(Fterm::cursor_forward(99), "\033[99C");
}
TEST(manipulate_test, cursor_backward) {
EXPECT_EQ(Fterm::cursor_backward(1), "\033[D");
EXPECT_EQ(Fterm::cursor_backward(3), "\033[3D");
EXPECT_EQ(Fterm::cursor_backward(99), "\033[99D");
}
TEST(manipulate_test, cursor_down_start) {
EXPECT_EQ(Fterm::cursor_down_start(1), "\033[E");
EXPECT_EQ(Fterm::cursor_down_start(3), "\033[3E");
EXPECT_EQ(Fterm::cursor_down_start(99), "\033[99E");
}
TEST(manipulate_test, cursor_up_start) {
EXPECT_EQ(Fterm::cursor_up_start(1), "\033[F");
EXPECT_EQ(Fterm::cursor_up_start(3), "\033[3F");
EXPECT_EQ(Fterm::cursor_up_start(99), "\033[99F");
}
TEST(manipulate_test, cursor_column) {
EXPECT_EQ(Fterm::cursor_column(1), "\033[G");
EXPECT_EQ(Fterm::cursor_column(3), "\033[3G");
EXPECT_EQ(Fterm::cursor_column(99), "\033[99G");
}
TEST(manipulate_test, cursor_pos) {
EXPECT_EQ(Fterm::cursor_pos(1, 1), "\033[;H");
EXPECT_EQ(Fterm::cursor_pos(1, 2), "\033[;2H");
EXPECT_EQ(Fterm::cursor_pos(2, 1), "\033[2;H");
EXPECT_EQ(Fterm::cursor_pos(2, 2), "\033[2;2H");
EXPECT_EQ(Fterm::cursor_pos(9, 5), "\033[9;5H");
}
TEST(manipulate_test, cursor_hvpos) {
EXPECT_EQ(Fterm::cursor_hvpos(1, 1), "\033[;f");
EXPECT_EQ(Fterm::cursor_hvpos(1, 2), "\033[;2f");
EXPECT_EQ(Fterm::cursor_hvpos(2, 1), "\033[2;f");
EXPECT_EQ(Fterm::cursor_hvpos(2, 2), "\033[2;2f");
EXPECT_EQ(Fterm::cursor_hvpos(9, 5), "\033[9;5f");
}
TEST(manipulate_test, clear_line) {
EXPECT_STREQ(Fterm::clear_line_end(), "\033[K");
EXPECT_STREQ(Fterm::clear_line_start(), "\033[1K");
EXPECT_STREQ(Fterm::clear_line(), "\033[2K");
}
TEST(manipulate_test, clear_screen) {
EXPECT_STREQ(Fterm::clear_screen_end(), "\033[J");
EXPECT_STREQ(Fterm::clear_screen_start(), "\033[1J");
EXPECT_STREQ(Fterm::clear_screen(), "\033[2J");
EXPECT_STREQ(Fterm::clear_screen_buffer(), "\033[3J");
}
TEST(manipulate_test, scroll_up) {
EXPECT_EQ(Fterm::scroll_up(1), "\033[S");
EXPECT_EQ(Fterm::scroll_up(3), "\033[3S");
EXPECT_EQ(Fterm::scroll_up(99), "\033[99S");
}
TEST(manipulate_test, scroll_down) {
EXPECT_EQ(Fterm::scroll_down(1), "\033[T");
EXPECT_EQ(Fterm::scroll_down(3), "\033[3T");
EXPECT_EQ(Fterm::scroll_down(99), "\033[99T");
}
TEST(manipulate_test, aux_port) {
EXPECT_STREQ(Fterm::serial_port_on(), "\033[5i");
EXPECT_STREQ(Fterm::serial_port_off(), "\033[4i");
}
| 37.525641 | 56 | 0.690126 | [
"3d"
] |
20e5a40a6158e837b7bb85a8fe0f8aad5388cc3a | 117,529 | cpp | C++ | Plugins/AGRPRO/Intermediate/Build/Win64/UnrealGame/Inc/AGRPRO/AGRAnimMasterComponent.gen.cpp | Thomas-A-Forsbergs/basic5_MPCoopAI | 5ea6cbf4c0f591cc7f50c8304522bcfbe8fba6c4 | [
"MIT"
] | null | null | null | Plugins/AGRPRO/Intermediate/Build/Win64/UnrealGame/Inc/AGRPRO/AGRAnimMasterComponent.gen.cpp | Thomas-A-Forsbergs/basic5_MPCoopAI | 5ea6cbf4c0f591cc7f50c8304522bcfbe8fba6c4 | [
"MIT"
] | null | null | null | Plugins/AGRPRO/Intermediate/Build/Win64/UnrealGame/Inc/AGRPRO/AGRAnimMasterComponent.gen.cpp | Thomas-A-Forsbergs/basic5_MPCoopAI | 5ea6cbf4c0f591cc7f50c8304522bcfbe8fba6c4 | [
"MIT"
] | null | null | null | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "AGRPRO/Public/Components/AGRAnimMasterComponent.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeAGRAnimMasterComponent() {}
// Cross Module References
AGRPRO_API UFunction* Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature();
UPackage* Z_Construct_UPackage__Script_AGRPRO();
AGRPRO_API UClass* Z_Construct_UClass_UAGRAnimMasterComponent_NoRegister();
AGRPRO_API UClass* Z_Construct_UClass_UAGRAnimMasterComponent();
ENGINE_API UClass* Z_Construct_UClass_UActorComponent();
GAMEPLAYTAGS_API UScriptStruct* Z_Construct_UScriptStruct_FGameplayTag();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FRotator();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector();
AGRPRO_API UEnum* Z_Construct_UEnum_AGRPRO_ERotationMethod();
AGRPRO_API UEnum* Z_Construct_UEnum_AGRPRO_EAimOffsets();
AGRPRO_API UEnum* Z_Construct_UEnum_AGRPRO_EAimOffsetClamp();
GAMEPLAYTAGS_API UScriptStruct* Z_Construct_UScriptStruct_FGameplayTagContainer();
ENGINE_API UEnum* Z_Construct_UEnum_Engine_ECollisionChannel();
ENGINE_API UClass* Z_Construct_UClass_ACharacter_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_UCharacterMovementComponent_NoRegister();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FColor();
// End Cross Module References
struct Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics
{
struct _Script_AGRPRO_eventOnFirstPerson_Parms
{
bool bIsFirstPersonView;
};
static void NewProp_bIsFirstPersonView_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_bIsFirstPersonView;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::NewProp_bIsFirstPersonView_SetBit(void* Obj)
{
((_Script_AGRPRO_eventOnFirstPerson_Parms*)Obj)->bIsFirstPersonView = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::NewProp_bIsFirstPersonView = { "bIsFirstPersonView", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(_Script_AGRPRO_eventOnFirstPerson_Parms), &Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::NewProp_bIsFirstPersonView_SetBit, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::NewProp_bIsFirstPersonView,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::FuncParams = { (UObject*(*)())Z_Construct_UPackage__Script_AGRPRO, nullptr, "OnFirstPerson__DelegateSignature", nullptr, nullptr, sizeof(_Script_AGRPRO_eventOnFirstPerson_Parms), Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00130000, 0, 0, METADATA_PARAMS(Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature_Statics::FuncParams);
}
return ReturnFunction;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execNetMutiSetLookAt)
{
P_GET_STRUCT(FVector,Z_Param_LookAt);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->NetMutiSetLookAt_Implementation(Z_Param_LookAt);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execServerSetLookAt)
{
P_GET_STRUCT(FVector,Z_Param_LookAt);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ServerSetLookAt_Implementation(Z_Param_LookAt);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execNetMutiSetAimOffset)
{
P_GET_STRUCT(FRotator,Z_Param_InAimOffset);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->NetMutiSetAimOffset_Implementation(Z_Param_InAimOffset);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execServerSetAimOffset)
{
P_GET_STRUCT(FRotator,Z_Param_InAimOffset);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ServerSetAimOffset_Implementation(Z_Param_InAimOffset);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execServerSetupAimOffset)
{
P_GET_ENUM(EAimOffsets,Z_Param_InAimOffsetType);
P_GET_ENUM(EAimOffsetClamp,Z_Param_InAimBehavior);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ServerSetupAimOffset_Implementation(EAimOffsets(Z_Param_InAimOffsetType),EAimOffsetClamp(Z_Param_InAimBehavior));
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execServerSetRotation)
{
P_GET_ENUM(ERotationMethod,Z_Param_InRotationMethod);
P_GET_PROPERTY(FFloatProperty,Z_Param_InRotationSpeed);
P_GET_PROPERTY(FFloatProperty,Z_Param_InTurnStartAngle);
P_GET_PROPERTY(FFloatProperty,Z_Param_InTurnStopTolerance);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ServerSetRotation_Implementation(ERotationMethod(Z_Param_InRotationMethod),Z_Param_InRotationSpeed,Z_Param_InTurnStartAngle,Z_Param_InTurnStopTolerance);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execServerSetOverlayPose)
{
P_GET_STRUCT(FGameplayTag,Z_Param_InOverlayPose);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ServerSetOverlayPose_Implementation(Z_Param_InOverlayPose);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execServerSetBasePose)
{
P_GET_STRUCT(FGameplayTag,Z_Param_InBasePose);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->ServerSetBasePose_Implementation(Z_Param_InBasePose);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execOnRep_RotationSpeed)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->OnRep_RotationSpeed();
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execOnRep_RotationMethod)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->OnRep_RotationMethod();
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execTurnInPlaceTick)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->TurnInPlaceTick();
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execAimTick)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->AimTick();
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execRemoveTag)
{
P_GET_STRUCT(FGameplayTag,Z_Param_InTag);
P_FINISH;
P_NATIVE_BEGIN;
*(bool*)Z_Param__Result=P_THIS->RemoveTag(Z_Param_InTag);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execAddTag)
{
P_GET_STRUCT(FGameplayTag,Z_Param_InTag);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->AddTag(Z_Param_InTag);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execSetupAimOffset)
{
P_GET_ENUM(EAimOffsets,Z_Param_InAimOffsetType);
P_GET_ENUM(EAimOffsetClamp,Z_Param_InAimBehavior);
P_GET_PROPERTY(FFloatProperty,Z_Param_InAimClamp);
P_GET_UBOOL(Z_Param_InCameraBased);
P_GET_PROPERTY(FNameProperty,Z_Param_InAimSocketName);
P_GET_PROPERTY(FNameProperty,Z_Param_InLookAtSocketName);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetupAimOffset(EAimOffsets(Z_Param_InAimOffsetType),EAimOffsetClamp(Z_Param_InAimBehavior),Z_Param_InAimClamp,Z_Param_InCameraBased,Z_Param_InAimSocketName,Z_Param_InLookAtSocketName);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execSetupRotation)
{
P_GET_ENUM(ERotationMethod,Z_Param_InRotationMethod);
P_GET_PROPERTY(FFloatProperty,Z_Param_InRotationSpeed);
P_GET_PROPERTY(FFloatProperty,Z_Param_InTurnStartAngle);
P_GET_PROPERTY(FFloatProperty,Z_Param_InTurnStopTolerance);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetupRotation(ERotationMethod(Z_Param_InRotationMethod),Z_Param_InRotationSpeed,Z_Param_InTurnStartAngle,Z_Param_InTurnStopTolerance);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execSetupFpp)
{
P_GET_UBOOL(Z_Param_bInFirstPerson);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetupFpp(Z_Param_bInFirstPerson);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execSetOverlayPose)
{
P_GET_STRUCT(FGameplayTag,Z_Param_InOverlayPose);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetOverlayPose(Z_Param_InOverlayPose);
P_NATIVE_END;
}
DEFINE_FUNCTION(UAGRAnimMasterComponent::execSetupBasePose)
{
P_GET_STRUCT(FGameplayTag,Z_Param_InBasePose);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->SetupBasePose(Z_Param_InBasePose);
P_NATIVE_END;
}
static FName NAME_UAGRAnimMasterComponent_NetMutiSetAimOffset = FName(TEXT("NetMutiSetAimOffset"));
void UAGRAnimMasterComponent::NetMutiSetAimOffset(FRotator InAimOffset)
{
AGRAnimMasterComponent_eventNetMutiSetAimOffset_Parms Parms;
Parms.InAimOffset=InAimOffset;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_NetMutiSetAimOffset),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_NetMutiSetLookAt = FName(TEXT("NetMutiSetLookAt"));
void UAGRAnimMasterComponent::NetMutiSetLookAt(FVector LookAt)
{
AGRAnimMasterComponent_eventNetMutiSetLookAt_Parms Parms;
Parms.LookAt=LookAt;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_NetMutiSetLookAt),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_ServerSetAimOffset = FName(TEXT("ServerSetAimOffset"));
void UAGRAnimMasterComponent::ServerSetAimOffset(FRotator InAimOffset)
{
AGRAnimMasterComponent_eventServerSetAimOffset_Parms Parms;
Parms.InAimOffset=InAimOffset;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_ServerSetAimOffset),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_ServerSetBasePose = FName(TEXT("ServerSetBasePose"));
void UAGRAnimMasterComponent::ServerSetBasePose(FGameplayTag InBasePose)
{
AGRAnimMasterComponent_eventServerSetBasePose_Parms Parms;
Parms.InBasePose=InBasePose;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_ServerSetBasePose),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_ServerSetLookAt = FName(TEXT("ServerSetLookAt"));
void UAGRAnimMasterComponent::ServerSetLookAt(FVector LookAt)
{
AGRAnimMasterComponent_eventServerSetLookAt_Parms Parms;
Parms.LookAt=LookAt;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_ServerSetLookAt),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_ServerSetOverlayPose = FName(TEXT("ServerSetOverlayPose"));
void UAGRAnimMasterComponent::ServerSetOverlayPose(FGameplayTag InOverlayPose)
{
AGRAnimMasterComponent_eventServerSetOverlayPose_Parms Parms;
Parms.InOverlayPose=InOverlayPose;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_ServerSetOverlayPose),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_ServerSetRotation = FName(TEXT("ServerSetRotation"));
void UAGRAnimMasterComponent::ServerSetRotation(ERotationMethod InRotationMethod, float InRotationSpeed, float InTurnStartAngle, float InTurnStopTolerance)
{
AGRAnimMasterComponent_eventServerSetRotation_Parms Parms;
Parms.InRotationMethod=InRotationMethod;
Parms.InRotationSpeed=InRotationSpeed;
Parms.InTurnStartAngle=InTurnStartAngle;
Parms.InTurnStopTolerance=InTurnStopTolerance;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_ServerSetRotation),&Parms);
}
static FName NAME_UAGRAnimMasterComponent_ServerSetupAimOffset = FName(TEXT("ServerSetupAimOffset"));
void UAGRAnimMasterComponent::ServerSetupAimOffset(EAimOffsets InAimOffsetType, EAimOffsetClamp InAimBehavior)
{
AGRAnimMasterComponent_eventServerSetupAimOffset_Parms Parms;
Parms.InAimOffsetType=InAimOffsetType;
Parms.InAimBehavior=InAimBehavior;
ProcessEvent(FindFunctionChecked(NAME_UAGRAnimMasterComponent_ServerSetupAimOffset),&Parms);
}
void UAGRAnimMasterComponent::StaticRegisterNativesUAGRAnimMasterComponent()
{
UClass* Class = UAGRAnimMasterComponent::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "AddTag", &UAGRAnimMasterComponent::execAddTag },
{ "AimTick", &UAGRAnimMasterComponent::execAimTick },
{ "NetMutiSetAimOffset", &UAGRAnimMasterComponent::execNetMutiSetAimOffset },
{ "NetMutiSetLookAt", &UAGRAnimMasterComponent::execNetMutiSetLookAt },
{ "OnRep_RotationMethod", &UAGRAnimMasterComponent::execOnRep_RotationMethod },
{ "OnRep_RotationSpeed", &UAGRAnimMasterComponent::execOnRep_RotationSpeed },
{ "RemoveTag", &UAGRAnimMasterComponent::execRemoveTag },
{ "ServerSetAimOffset", &UAGRAnimMasterComponent::execServerSetAimOffset },
{ "ServerSetBasePose", &UAGRAnimMasterComponent::execServerSetBasePose },
{ "ServerSetLookAt", &UAGRAnimMasterComponent::execServerSetLookAt },
{ "ServerSetOverlayPose", &UAGRAnimMasterComponent::execServerSetOverlayPose },
{ "ServerSetRotation", &UAGRAnimMasterComponent::execServerSetRotation },
{ "ServerSetupAimOffset", &UAGRAnimMasterComponent::execServerSetupAimOffset },
{ "SetOverlayPose", &UAGRAnimMasterComponent::execSetOverlayPose },
{ "SetupAimOffset", &UAGRAnimMasterComponent::execSetupAimOffset },
{ "SetupBasePose", &UAGRAnimMasterComponent::execSetupBasePose },
{ "SetupFpp", &UAGRAnimMasterComponent::execSetupFpp },
{ "SetupRotation", &UAGRAnimMasterComponent::execSetupRotation },
{ "TurnInPlaceTick", &UAGRAnimMasterComponent::execTurnInPlaceTick },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics
{
struct AGRAnimMasterComponent_eventAddTag_Parms
{
FGameplayTag InTag;
};
static const UECodeGen_Private::FStructPropertyParams NewProp_InTag;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::NewProp_InTag = { "InTag", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventAddTag_Parms, InTag), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::NewProp_InTag,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|AnimTags" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "AddTag", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventAddTag_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick_Statics
{
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|Tick" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "AimTick", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics
{
static const UECodeGen_Private::FStructPropertyParams NewProp_InAimOffset;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::NewProp_InAimOffset = { "InAimOffset", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventNetMutiSetAimOffset_Parms, InAimOffset), Z_Construct_UScriptStruct_FRotator, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::NewProp_InAimOffset,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "NetMutiSetAimOffset", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventNetMutiSetAimOffset_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00844C41, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics
{
static const UECodeGen_Private::FStructPropertyParams NewProp_LookAt;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::NewProp_LookAt = { "LookAt", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventNetMutiSetLookAt_Parms, LookAt), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::NewProp_LookAt,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "NetMutiSetLookAt", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventNetMutiSetLookAt_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00844C41, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod_Statics
{
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "OnRep_RotationMethod", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed_Statics
{
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "OnRep_RotationSpeed", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00040401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics
{
struct AGRAnimMasterComponent_eventRemoveTag_Parms
{
FGameplayTag InTag;
bool ReturnValue;
};
static const UECodeGen_Private::FStructPropertyParams NewProp_InTag;
static void NewProp_ReturnValue_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_ReturnValue;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::NewProp_InTag = { "InTag", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventRemoveTag_Parms, InTag), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(nullptr, 0) };
void Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::NewProp_ReturnValue_SetBit(void* Obj)
{
((AGRAnimMasterComponent_eventRemoveTag_Parms*)Obj)->ReturnValue = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(AGRAnimMasterComponent_eventRemoveTag_Parms), &Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::NewProp_InTag,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|AnimTags" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "RemoveTag", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventRemoveTag_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics
{
static const UECodeGen_Private::FStructPropertyParams NewProp_InAimOffset;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::NewProp_InAimOffset = { "InAimOffset", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetAimOffset_Parms, InAimOffset), Z_Construct_UScriptStruct_FRotator, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::NewProp_InAimOffset,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "ServerSetAimOffset", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventServerSetAimOffset_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00A40C41, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics
{
static const UECodeGen_Private::FStructPropertyParams NewProp_InBasePose;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::NewProp_InBasePose = { "InBasePose", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetBasePose_Parms, InBasePose), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::NewProp_InBasePose,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "ServerSetBasePose", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventServerSetBasePose_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00240CC1, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics
{
static const UECodeGen_Private::FStructPropertyParams NewProp_LookAt;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::NewProp_LookAt = { "LookAt", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetLookAt_Parms, LookAt), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::NewProp_LookAt,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "ServerSetLookAt", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventServerSetLookAt_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00A40C41, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics
{
static const UECodeGen_Private::FStructPropertyParams NewProp_InOverlayPose;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::NewProp_InOverlayPose = { "InOverlayPose", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetOverlayPose_Parms, InOverlayPose), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::NewProp_InOverlayPose,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "ServerSetOverlayPose", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventServerSetOverlayPose_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00240CC1, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics
{
static const UECodeGen_Private::FBytePropertyParams NewProp_InRotationMethod_Underlying;
static const UECodeGen_Private::FEnumPropertyParams NewProp_InRotationMethod;
static const UECodeGen_Private::FFloatPropertyParams NewProp_InRotationSpeed;
static const UECodeGen_Private::FFloatPropertyParams NewProp_InTurnStartAngle;
static const UECodeGen_Private::FFloatPropertyParams NewProp_InTurnStopTolerance;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InRotationMethod_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InRotationMethod = { "InRotationMethod", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetRotation_Parms, InRotationMethod), Z_Construct_UEnum_AGRPRO_ERotationMethod, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InRotationSpeed = { "InRotationSpeed", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetRotation_Parms, InRotationSpeed), METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InTurnStartAngle = { "InTurnStartAngle", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetRotation_Parms, InTurnStartAngle), METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InTurnStopTolerance = { "InTurnStopTolerance", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetRotation_Parms, InTurnStopTolerance), METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InRotationMethod_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InRotationMethod,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InRotationSpeed,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InTurnStartAngle,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::NewProp_InTurnStopTolerance,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "ServerSetRotation", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventServerSetRotation_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00240CC1, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics
{
static const UECodeGen_Private::FBytePropertyParams NewProp_InAimOffsetType_Underlying;
static const UECodeGen_Private::FEnumPropertyParams NewProp_InAimOffsetType;
static const UECodeGen_Private::FBytePropertyParams NewProp_InAimBehavior_Underlying;
static const UECodeGen_Private::FEnumPropertyParams NewProp_InAimBehavior;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimOffsetType_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimOffsetType = { "InAimOffsetType", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetupAimOffset_Parms, InAimOffsetType), Z_Construct_UEnum_AGRPRO_EAimOffsets, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimBehavior_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimBehavior = { "InAimBehavior", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventServerSetupAimOffset_Parms, InAimBehavior), Z_Construct_UEnum_AGRPRO_EAimOffsetClamp, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimOffsetType_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimOffsetType,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimBehavior_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::NewProp_InAimBehavior,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "ServerSetupAimOffset", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventServerSetupAimOffset_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x00240C41, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics
{
struct AGRAnimMasterComponent_eventSetOverlayPose_Parms
{
FGameplayTag InOverlayPose;
};
static const UECodeGen_Private::FStructPropertyParams NewProp_InOverlayPose;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::NewProp_InOverlayPose = { "InOverlayPose", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetOverlayPose_Parms, InOverlayPose), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::NewProp_InOverlayPose,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|Poses" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "SetOverlayPose", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventSetOverlayPose_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics
{
struct AGRAnimMasterComponent_eventSetupAimOffset_Parms
{
EAimOffsets InAimOffsetType;
EAimOffsetClamp InAimBehavior;
float InAimClamp;
bool InCameraBased;
FName InAimSocketName;
FName InLookAtSocketName;
};
static const UECodeGen_Private::FBytePropertyParams NewProp_InAimOffsetType_Underlying;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InAimOffsetType_MetaData[];
#endif
static const UECodeGen_Private::FEnumPropertyParams NewProp_InAimOffsetType;
static const UECodeGen_Private::FBytePropertyParams NewProp_InAimBehavior_Underlying;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InAimBehavior_MetaData[];
#endif
static const UECodeGen_Private::FEnumPropertyParams NewProp_InAimBehavior;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InAimClamp_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_InAimClamp;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InCameraBased_MetaData[];
#endif
static void NewProp_InCameraBased_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_InCameraBased;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InAimSocketName_MetaData[];
#endif
static const UECodeGen_Private::FNamePropertyParams NewProp_InAimSocketName;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InLookAtSocketName_MetaData[];
#endif
static const UECodeGen_Private::FNamePropertyParams NewProp_InLookAtSocketName;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType = { "InAimOffsetType", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupAimOffset_Parms, InAimOffsetType), Z_Construct_UEnum_AGRPRO_EAimOffsets, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType_MetaData)) };
const UECodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior = { "InAimBehavior", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupAimOffset_Parms, InAimBehavior), Z_Construct_UEnum_AGRPRO_EAimOffsetClamp, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimClamp_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimClamp = { "InAimClamp", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupAimOffset_Parms, InAimClamp), METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimClamp_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimClamp_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased_MetaData[] = {
{ "NativeConst", "" },
};
#endif
void Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased_SetBit(void* Obj)
{
((AGRAnimMasterComponent_eventSetupAimOffset_Parms*)Obj)->InCameraBased = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased = { "InCameraBased", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(AGRAnimMasterComponent_eventSetupAimOffset_Parms), &Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased_SetBit, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimSocketName_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FNamePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimSocketName = { "InAimSocketName", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupAimOffset_Parms, InAimSocketName), METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimSocketName_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimSocketName_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InLookAtSocketName_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FNamePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InLookAtSocketName = { "InLookAtSocketName", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupAimOffset_Parms, InLookAtSocketName), METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InLookAtSocketName_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InLookAtSocketName_MetaData)) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimOffsetType,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimBehavior,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimClamp,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InCameraBased,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InAimSocketName,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::NewProp_InLookAtSocketName,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|AimOffset" },
{ "CPP_Default_InAimBehavior", "Nearest" },
{ "CPP_Default_InAimClamp", "90.000000" },
{ "CPP_Default_InAimOffsetType", "NONE" },
{ "CPP_Default_InAimSocketName", "hand_r" },
{ "CPP_Default_InCameraBased", "true" },
{ "CPP_Default_InLookAtSocketName", "head" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "SetupAimOffset", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventSetupAimOffset_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics
{
struct AGRAnimMasterComponent_eventSetupBasePose_Parms
{
FGameplayTag InBasePose;
};
static const UECodeGen_Private::FStructPropertyParams NewProp_InBasePose;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::NewProp_InBasePose = { "InBasePose", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupBasePose_Parms, InBasePose), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::NewProp_InBasePose,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|Poses" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "SetupBasePose", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventSetupBasePose_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics
{
struct AGRAnimMasterComponent_eventSetupFpp_Parms
{
bool bInFirstPerson;
};
static void NewProp_bInFirstPerson_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_bInFirstPerson;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::NewProp_bInFirstPerson_SetBit(void* Obj)
{
((AGRAnimMasterComponent_eventSetupFpp_Parms*)Obj)->bInFirstPerson = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::NewProp_bInFirstPerson = { "bInFirstPerson", nullptr, (EPropertyFlags)0x0010000000000080, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(AGRAnimMasterComponent_eventSetupFpp_Parms), &Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::NewProp_bInFirstPerson_SetBit, METADATA_PARAMS(nullptr, 0) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::NewProp_bInFirstPerson,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|FirstPerson" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "SetupFpp", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventSetupFpp_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics
{
struct AGRAnimMasterComponent_eventSetupRotation_Parms
{
ERotationMethod InRotationMethod;
float InRotationSpeed;
float InTurnStartAngle;
float InTurnStopTolerance;
};
static const UECodeGen_Private::FBytePropertyParams NewProp_InRotationMethod_Underlying;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InRotationMethod_MetaData[];
#endif
static const UECodeGen_Private::FEnumPropertyParams NewProp_InRotationMethod;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InRotationSpeed_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_InRotationSpeed;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InTurnStartAngle_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_InTurnStartAngle;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_InTurnStopTolerance_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_InTurnStopTolerance;
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
const UECodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod = { "InRotationMethod", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupRotation_Parms, InRotationMethod), Z_Construct_UEnum_AGRPRO_ERotationMethod, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationSpeed_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationSpeed = { "InRotationSpeed", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupRotation_Parms, InRotationSpeed), METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationSpeed_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationSpeed_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStartAngle_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStartAngle = { "InTurnStartAngle", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupRotation_Parms, InTurnStartAngle), METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStartAngle_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStartAngle_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStopTolerance_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStopTolerance = { "InTurnStopTolerance", nullptr, (EPropertyFlags)0x0010000000000082, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AGRAnimMasterComponent_eventSetupRotation_Parms, InTurnStopTolerance), METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStopTolerance_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStopTolerance_MetaData)) };
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationMethod,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InRotationSpeed,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStartAngle,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::NewProp_InTurnStopTolerance,
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|Rotation" },
{ "CPP_Default_InRotationMethod", "NONE" },
{ "CPP_Default_InRotationSpeed", "360.000000" },
{ "CPP_Default_InTurnStartAngle", "90.000000" },
{ "CPP_Default_InTurnStopTolerance", "5.000000" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "SetupRotation", nullptr, nullptr, sizeof(AGRAnimMasterComponent_eventSetupRotation_Parms), Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick_Statics
{
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UECodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick_Statics::Function_MetaDataParams[] = {
{ "Category", "AGR|Tick" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFunctionParams Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAGRAnimMasterComponent, nullptr, "TurnInPlaceTick", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UECodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UAGRAnimMasterComponent_NoRegister()
{
return UAGRAnimMasterComponent::StaticClass();
}
struct Z_Construct_UClass_UAGRAnimMasterComponent_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_BasePose_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_BasePose;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_OverlayPose_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_OverlayPose;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_bFirstPerson_MetaData[];
#endif
static void NewProp_bFirstPerson_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_bFirstPerson;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AimOffset_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_AimOffset;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_LookAtLocation_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_LookAtLocation;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AnimModTags_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_AnimModTags;
static const UECodeGen_Private::FBytePropertyParams NewProp_RotationMethod_Underlying;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_RotationMethod_MetaData[];
#endif
static const UECodeGen_Private::FEnumPropertyParams NewProp_RotationMethod;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_RotationSpeed_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_RotationSpeed;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_TurnStartAngle_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_TurnStartAngle;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_TurnStopTolerance_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_TurnStopTolerance;
static const UECodeGen_Private::FBytePropertyParams NewProp_AimOffsetType_Underlying;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AimOffsetType_MetaData[];
#endif
static const UECodeGen_Private::FEnumPropertyParams NewProp_AimOffsetType;
static const UECodeGen_Private::FBytePropertyParams NewProp_AimOffsetBehavior_Underlying;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AimOffsetBehavior_MetaData[];
#endif
static const UECodeGen_Private::FEnumPropertyParams NewProp_AimOffsetBehavior;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AimClamp_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_AimClamp;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_CameraBased_MetaData[];
#endif
static void NewProp_CameraBased_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_CameraBased;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AimSocketName_MetaData[];
#endif
static const UECodeGen_Private::FNamePropertyParams NewProp_AimSocketName;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_LookAtSocketName_MetaData[];
#endif
static const UECodeGen_Private::FNamePropertyParams NewProp_LookAtSocketName;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_TraceChannel_MetaData[];
#endif
static const UECodeGen_Private::FBytePropertyParams NewProp_TraceChannel;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_OwningCharacter_MetaData[];
#endif
static const UECodeGen_Private::FObjectPropertyParams NewProp_OwningCharacter;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_OwnerMovementComponent_MetaData[];
#endif
static const UECodeGen_Private::FObjectPropertyParams NewProp_OwnerMovementComponent;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_OnFirstPerson_MetaData[];
#endif
static const UECodeGen_Private::FMulticastDelegatePropertyParams NewProp_OnFirstPerson;
#if WITH_EDITORONLY_DATA
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_bDebug_MetaData[];
#endif
static void NewProp_bDebug_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_bDebug;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_LookAtLineColor_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_LookAtLineColor;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_AimLineColor_MetaData[];
#endif
static const UECodeGen_Private::FStructPropertyParams NewProp_AimLineColor;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_bLinePersists_MetaData[];
#endif
static void NewProp_bLinePersists_SetBit(void* Obj);
static const UECodeGen_Private::FBoolPropertyParams NewProp_bLinePersists;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_LineThickness_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_LineThickness;
#if WITH_METADATA
static const UECodeGen_Private::FMetaDataPairParam NewProp_LineLifetime_MetaData[];
#endif
static const UECodeGen_Private::FFloatPropertyParams NewProp_LineLifetime;
#endif // WITH_EDITORONLY_DATA
static const UECodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_EDITORONLY_DATA
#endif // WITH_EDITORONLY_DATA
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UECodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UAGRAnimMasterComponent_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UActorComponent,
(UObject* (*)())Z_Construct_UPackage__Script_AGRPRO,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UAGRAnimMasterComponent_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_AddTag, "AddTag" }, // 1607227658
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_AimTick, "AimTick" }, // 2939863369
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetAimOffset, "NetMutiSetAimOffset" }, // 4042399575
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_NetMutiSetLookAt, "NetMutiSetLookAt" }, // 1459667724
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationMethod, "OnRep_RotationMethod" }, // 2114741373
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_OnRep_RotationSpeed, "OnRep_RotationSpeed" }, // 1987308378
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_RemoveTag, "RemoveTag" }, // 3331773005
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetAimOffset, "ServerSetAimOffset" }, // 1423263917
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetBasePose, "ServerSetBasePose" }, // 4048527507
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetLookAt, "ServerSetLookAt" }, // 2286045027
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetOverlayPose, "ServerSetOverlayPose" }, // 815586662
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetRotation, "ServerSetRotation" }, // 3794679191
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_ServerSetupAimOffset, "ServerSetupAimOffset" }, // 3650765383
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_SetOverlayPose, "SetOverlayPose" }, // 3785913494
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_SetupAimOffset, "SetupAimOffset" }, // 1467067547
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_SetupBasePose, "SetupBasePose" }, // 2630175065
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_SetupFpp, "SetupFpp" }, // 719020549
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_SetupRotation, "SetupRotation" }, // 3140346361
{ &Z_Construct_UFunction_UAGRAnimMasterComponent_TurnInPlaceTick, "TurnInPlaceTick" }, // 616986362
};
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::Class_MetaDataParams[] = {
{ "BlueprintSpawnableComponent", "" },
{ "BlueprintType", "true" },
{ "ClassGroupNames", "AGR" },
{ "IncludePath", "Components/AGRAnimMasterComponent.h" },
{ "IsBlueprintBase", "true" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_BasePose_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_BasePose = { "BasePose", nullptr, (EPropertyFlags)0x0010000000000025, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, BasePose), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_BasePose_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_BasePose_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OverlayPose_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OverlayPose = { "OverlayPose", nullptr, (EPropertyFlags)0x0010000000000025, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, OverlayPose), Z_Construct_UScriptStruct_FGameplayTag, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OverlayPose_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OverlayPose_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson_MetaData[] = {
{ "Category", "AGR|Runtime" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
void Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson_SetBit(void* Obj)
{
((UAGRAnimMasterComponent*)Obj)->bFirstPerson = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson = { "bFirstPerson", nullptr, (EPropertyFlags)0x0010000000000005, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAGRAnimMasterComponent), &Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffset_MetaData[] = {
{ "Category", "AGR|Runtime" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffset = { "AimOffset", nullptr, (EPropertyFlags)0x0010000000000005, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AimOffset), Z_Construct_UScriptStruct_FRotator, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffset_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffset_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLocation_MetaData[] = {
{ "Category", "AGR|Runtime" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLocation = { "LookAtLocation", nullptr, (EPropertyFlags)0x0010000000000005, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, LookAtLocation), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLocation_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLocation_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AnimModTags_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AnimModTags = { "AnimModTags", nullptr, (EPropertyFlags)0x0010000000000025, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AnimModTags), Z_Construct_UScriptStruct_FGameplayTagContainer, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AnimModTags_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AnimModTags_MetaData)) };
const UECodeGen_Private::FBytePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod = { "RotationMethod", "OnRep_RotationMethod", (EPropertyFlags)0x0010000100010025, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, RotationMethod), Z_Construct_UEnum_AGRPRO_ERotationMethod, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationSpeed_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationSpeed = { "RotationSpeed", "OnRep_RotationSpeed", (EPropertyFlags)0x0010000100010025, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, RotationSpeed), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationSpeed_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationSpeed_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStartAngle_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStartAngle = { "TurnStartAngle", nullptr, (EPropertyFlags)0x0010000000010025, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, TurnStartAngle), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStartAngle_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStartAngle_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStopTolerance_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStopTolerance = { "TurnStopTolerance", nullptr, (EPropertyFlags)0x0010000000010025, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, TurnStopTolerance), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStopTolerance_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStopTolerance_MetaData)) };
const UECodeGen_Private::FBytePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType = { "AimOffsetType", nullptr, (EPropertyFlags)0x0010000000010025, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AimOffsetType), Z_Construct_UEnum_AGRPRO_EAimOffsets, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType_MetaData)) };
const UECodeGen_Private::FBytePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FEnumPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior = { "AimOffsetBehavior", nullptr, (EPropertyFlags)0x0010000000010025, UECodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AimOffsetBehavior), Z_Construct_UEnum_AGRPRO_EAimOffsetClamp, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimClamp_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimClamp = { "AimClamp", nullptr, (EPropertyFlags)0x0010000000010005, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AimClamp), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimClamp_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimClamp_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
void Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased_SetBit(void* Obj)
{
((UAGRAnimMasterComponent*)Obj)->CameraBased = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased = { "CameraBased", nullptr, (EPropertyFlags)0x0010000000010005, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAGRAnimMasterComponent), &Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimSocketName_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FNamePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimSocketName = { "AimSocketName", nullptr, (EPropertyFlags)0x0010000000010005, UECodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AimSocketName), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimSocketName_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimSocketName_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtSocketName_MetaData[] = {
{ "Category", "AGR|Setup" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FNamePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtSocketName = { "LookAtSocketName", nullptr, (EPropertyFlags)0x0010000000010005, UECodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, LookAtSocketName), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtSocketName_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtSocketName_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TraceChannel_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FBytePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TraceChannel = { "TraceChannel", nullptr, (EPropertyFlags)0x0010000000010005, UECodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, TraceChannel), Z_Construct_UEnum_Engine_ECollisionChannel, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TraceChannel_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TraceChannel_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwningCharacter_MetaData[] = {
{ "Category", "AGR|Components" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwningCharacter = { "OwningCharacter", nullptr, (EPropertyFlags)0x0010000000000014, UECodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, OwningCharacter), Z_Construct_UClass_ACharacter_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwningCharacter_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwningCharacter_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwnerMovementComponent_MetaData[] = {
{ "Category", "AGR|Components" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwnerMovementComponent = { "OwnerMovementComponent", nullptr, (EPropertyFlags)0x001000000008001c, UECodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, OwnerMovementComponent), Z_Construct_UClass_UCharacterMovementComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwnerMovementComponent_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwnerMovementComponent_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OnFirstPerson_MetaData[] = {
{ "Category", "AGR|FirstPerson" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FMulticastDelegatePropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OnFirstPerson = { "OnFirstPerson", nullptr, (EPropertyFlags)0x0010000010080000, UECodeGen_Private::EPropertyGenFlags::InlineMulticastDelegate, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, OnFirstPerson), Z_Construct_UDelegateFunction_AGRPRO_OnFirstPerson__DelegateSignature, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OnFirstPerson_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OnFirstPerson_MetaData)) };
#if WITH_EDITORONLY_DATA
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
void Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug_SetBit(void* Obj)
{
((UAGRAnimMasterComponent*)Obj)->bDebug = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug = { "bDebug", nullptr, (EPropertyFlags)0x0010000800000005, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAGRAnimMasterComponent), &Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLineColor_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "Comment", "//Color of the line drawn to display when the starting point is LookAtSocket.\n" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
{ "ToolTip", "Color of the line drawn to display when the starting point is LookAtSocket." },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLineColor = { "LookAtLineColor", nullptr, (EPropertyFlags)0x0040000800010001, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, LookAtLineColor), Z_Construct_UScriptStruct_FColor, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLineColor_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLineColor_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimLineColor_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "Comment", "//Color of the line drawn to display when the starting point is AimSocket.\n" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
{ "ToolTip", "Color of the line drawn to display when the starting point is AimSocket." },
};
#endif
const UECodeGen_Private::FStructPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimLineColor = { "AimLineColor", nullptr, (EPropertyFlags)0x0040000800010001, UECodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, AimLineColor), Z_Construct_UScriptStruct_FColor, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimLineColor_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimLineColor_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
void Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists_SetBit(void* Obj)
{
((UAGRAnimMasterComponent*)Obj)->bLinePersists = 1;
}
const UECodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists = { "bLinePersists", nullptr, (EPropertyFlags)0x0040000800010001, UECodeGen_Private::EPropertyGenFlags::Bool | UECodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UAGRAnimMasterComponent), &Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists_SetBit, METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineThickness_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineThickness = { "LineThickness", nullptr, (EPropertyFlags)0x0040000800010001, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, LineThickness), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineThickness_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineThickness_MetaData)) };
#if WITH_METADATA
const UECodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineLifetime_MetaData[] = {
{ "Category", "AGR|Debug" },
{ "ModuleRelativePath", "Public/Components/AGRAnimMasterComponent.h" },
};
#endif
const UECodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineLifetime = { "LineLifetime", nullptr, (EPropertyFlags)0x0040000800010001, UECodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UAGRAnimMasterComponent, LineLifetime), METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineLifetime_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineLifetime_MetaData)) };
#endif // WITH_EDITORONLY_DATA
const UECodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UAGRAnimMasterComponent_Statics::PropPointers[] = {
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_BasePose,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OverlayPose,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bFirstPerson,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffset,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLocation,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AnimModTags,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationMethod,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_RotationSpeed,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStartAngle,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TurnStopTolerance,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetType,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior_Underlying,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimOffsetBehavior,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimClamp,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_CameraBased,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimSocketName,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtSocketName,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_TraceChannel,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwningCharacter,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OwnerMovementComponent,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_OnFirstPerson,
#if WITH_EDITORONLY_DATA
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bDebug,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LookAtLineColor,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_AimLineColor,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_bLinePersists,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineThickness,
(const UECodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UAGRAnimMasterComponent_Statics::NewProp_LineLifetime,
#endif // WITH_EDITORONLY_DATA
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UAGRAnimMasterComponent_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UAGRAnimMasterComponent>::IsAbstract,
};
const UECodeGen_Private::FClassParams Z_Construct_UClass_UAGRAnimMasterComponent_Statics::ClassParams = {
&UAGRAnimMasterComponent::StaticClass,
"Engine",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UAGRAnimMasterComponent_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::PropPointers),
0,
0x00B000A4u,
METADATA_PARAMS(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UAGRAnimMasterComponent_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UAGRAnimMasterComponent()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UECodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UAGRAnimMasterComponent_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UAGRAnimMasterComponent, 3273707098);
template<> AGRPRO_API UClass* StaticClass<UAGRAnimMasterComponent>()
{
return UAGRAnimMasterComponent::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UAGRAnimMasterComponent(Z_Construct_UClass_UAGRAnimMasterComponent, &UAGRAnimMasterComponent::StaticClass, TEXT("/Script/AGRPRO"), TEXT("UAGRAnimMasterComponent"), false, nullptr, nullptr, nullptr);
void UAGRAnimMasterComponent::ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const
{
static const FName Name_BasePose(TEXT("BasePose"));
static const FName Name_OverlayPose(TEXT("OverlayPose"));
static const FName Name_AnimModTags(TEXT("AnimModTags"));
static const FName Name_RotationMethod(TEXT("RotationMethod"));
static const FName Name_RotationSpeed(TEXT("RotationSpeed"));
static const FName Name_TurnStartAngle(TEXT("TurnStartAngle"));
static const FName Name_TurnStopTolerance(TEXT("TurnStopTolerance"));
static const FName Name_AimOffsetType(TEXT("AimOffsetType"));
static const FName Name_AimOffsetBehavior(TEXT("AimOffsetBehavior"));
const bool bIsValid = true
&& Name_BasePose == ClassReps[(int32)ENetFields_Private::BasePose].Property->GetFName()
&& Name_OverlayPose == ClassReps[(int32)ENetFields_Private::OverlayPose].Property->GetFName()
&& Name_AnimModTags == ClassReps[(int32)ENetFields_Private::AnimModTags].Property->GetFName()
&& Name_RotationMethod == ClassReps[(int32)ENetFields_Private::RotationMethod].Property->GetFName()
&& Name_RotationSpeed == ClassReps[(int32)ENetFields_Private::RotationSpeed].Property->GetFName()
&& Name_TurnStartAngle == ClassReps[(int32)ENetFields_Private::TurnStartAngle].Property->GetFName()
&& Name_TurnStopTolerance == ClassReps[(int32)ENetFields_Private::TurnStopTolerance].Property->GetFName()
&& Name_AimOffsetType == ClassReps[(int32)ENetFields_Private::AimOffsetType].Property->GetFName()
&& Name_AimOffsetBehavior == ClassReps[(int32)ENetFields_Private::AimOffsetBehavior].Property->GetFName();
checkf(bIsValid, TEXT("UHT Generated Rep Indices do not match runtime populated Rep Indices for properties in UAGRAnimMasterComponent"));
}
DEFINE_VTABLE_PTR_HELPER_CTOR(UAGRAnimMasterComponent);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 78.248336 | 818 | 0.864178 | [
"object"
] |
20eb6581bd69cfe7fc13a9b4e41f934a4db11c9a | 2,247 | cc | C++ | mysql-server/unittest/gunit/thr_template.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/unittest/gunit/thr_template.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/unittest/gunit/thr_template.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /* Copyright (c) 2006, 2018, 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 */
/*
As this file may be included from inside a namespace, we cannot do
#includes here. However, you should
#include "my_systime.h"
#include "mysql/components/services/my_thread_bits.h"
outside that namespace.
*/
#include <atomic>
#include <vector>
std::atomic<int32> bad;
my_thread_attr_t thr_attr;
const int THREADS = 30;
const int CYCLES = 3000;
void test_concurrently(const char *test, my_start_routine handler, int n,
int m) {
std::vector<my_thread_handle> t_vec;
t_vec.resize(n);
ulonglong now = my_getsystime();
int num_threads = n;
my_thread_attr_init(&thr_attr);
bad = 0;
for (; n; n--) {
if (my_thread_create(&t_vec[n - 1], &thr_attr, handler, &m) != 0) {
ADD_FAILURE() << "Could not create thread";
abort();
}
}
for (int i = 0; i < num_threads; ++i) {
my_thread_join(&t_vec[i], nullptr);
}
now = my_getsystime() - now;
EXPECT_FALSE(bad) << "tested " << test << " in " << ((double)now) / 1e7
<< " secs "
<< "(" << bad.load() << ")";
}
| 33.044118 | 79 | 0.685358 | [
"vector"
] |
20ff71567b2e22bc9a88f4285e59db8f9d356fd8 | 2,660 | cpp | C++ | recursive-drawing/ShaderLoader.cpp | Thyix/recursive-fractal | eaadfe25715b7115290f4379354ddc5afa5c4aeb | [
"MIT"
] | null | null | null | recursive-drawing/ShaderLoader.cpp | Thyix/recursive-fractal | eaadfe25715b7115290f4379354ddc5afa5c4aeb | [
"MIT"
] | null | null | null | recursive-drawing/ShaderLoader.cpp | Thyix/recursive-fractal | eaadfe25715b7115290f4379354ddc5afa5c4aeb | [
"MIT"
] | 1 | 2018-10-25T21:41:59.000Z | 2018-10-25T21:41:59.000Z | #include "OpenGLHeaders.h"
ShaderLoader::ShaderLoader(void) {}
ShaderLoader::~ShaderLoader(void) {}
std::string ShaderLoader::ReadShader(char * fileName)
{
std::string shaderCode;
std::ifstream file(fileName, std::ios::in);
if (!file.good()) {
std::cout << "Le fichier est illisible: " << fileName << std::endl;
std::terminate();
}
//find file length
file.seekg(0, std::ios::end); // goto end of file
shaderCode.resize((unsigned int)file.tellg());
// read file
file.seekg(0, std::ios::beg); // goto beginning of file
file.read(&shaderCode[0], shaderCode.size());
file.close();
return shaderCode;
}
GLuint ShaderLoader::CreateShader(GLenum shaderType, std::string source)
{
int compileResult = 0;
// create empty shader object
GLuint shader = glCreateShader(shaderType);
// get shader source informations
const char* shaderCode_prt = source.c_str();
const int shaderCode_size = source.size();
// binding source code to new shader
glShaderSource(shader, 1, &shaderCode_prt, &shaderCode_size);
glCompileShader(shader);
// validate compilation
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileResult);
if (compileResult == GL_FALSE) {
int infoLogLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
std::vector<char> shaderLog(infoLogLength);
glGetShaderInfoLog(shader, infoLogLength, NULL, &shaderLog[0]);
std::cout << "Erreur de compilation des shaders" << std::endl << &shaderLog[0] << std::endl;
return 0;
}
return shader;
}
GLuint ShaderLoader::CreateProgram(char * VertexShaderFileName, char * FragmentShaderFileName)
{
std::string vertexShaderCode = ReadShader(VertexShaderFileName);
std::string fragmentShaderCode = ReadShader(FragmentShaderFileName);
// creating and compiling shaders
GLuint vertexShader = CreateShader(GL_VERTEX_SHADER, vertexShaderCode);
GLuint fragmentShader = CreateShader(GL_FRAGMENT_SHADER, fragmentShaderCode);
int linkResult = 0;
// creating program handle and linking it to shaders
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
// linking program object which will be executed by the gpu
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &linkResult);
// validating the linking status
if (!linkResult) {
int infoLogLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
std::vector<char> programLog(infoLogLength);
glGetProgramInfoLog(program, infoLogLength, NULL, &programLog[0]);
std::cout << "Shader loader : LINKING ERROR" << std::endl << &programLog[0] << std::endl;
return 0;
}
return program;
return GLuint();
}
| 29.88764 | 94 | 0.742481 | [
"object",
"vector"
] |
1f12de0197d9fa3e3fd38def2239022247a9b454 | 4,342 | cpp | C++ | test/SignalTest.cpp | johnhues/aether-game-utils | 3b67cc77d232d43ee8c273a1db3c9373374438b2 | [
"MIT"
] | 4 | 2020-08-26T19:41:32.000Z | 2021-05-09T20:54:56.000Z | test/SignalTest.cpp | johnhues/aether-game-utils | 3b67cc77d232d43ee8c273a1db3c9373374438b2 | [
"MIT"
] | 20 | 2020-07-07T20:06:04.000Z | 2021-02-28T23:09:18.000Z | test/SignalTest.cpp | johnhues/aether-game-utils | 3b67cc77d232d43ee8c273a1db3c9373374438b2 | [
"MIT"
] | 1 | 2021-11-03T14:55:25.000Z | 2021-11-03T14:55:25.000Z | //------------------------------------------------------------------------------
// SignalTest.cpp
//------------------------------------------------------------------------------
// Copyright (c) 2020 John Hughes
//
// 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.
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
#include "ae/aeSignal.h"
#include "catch2/catch.hpp"
//------------------------------------------------------------------------------
// Test helpers
//------------------------------------------------------------------------------
class Thing
{
public:
Thing() : m_refable( this ) {}
AE_REFABLE( Thing );
void Fn();
void FnInt( int i );
int val = 0;
int callCount = 0;
};
void Thing::Fn()
{
val = 1;
callCount++;
}
void Thing::FnInt( int i )
{
val = i;
callCount++;
}
//------------------------------------------------------------------------------
// aeSignalList tests
//------------------------------------------------------------------------------
TEST_CASE( "signal send should result in the correct functions being called", "[aeSignal]" )
{
aeSignalList< int > signal;
REQUIRE( signal.Length() == 0 );
Thing thing;
Thing thingInt;
REQUIRE( thing.val == 0 );
REQUIRE( thingInt.val == 0 );
SECTION( "sending without value should call correct function" )
{
signal.Add( &thing, &Thing::Fn );
signal.Send();
REQUIRE( thing.val == 1 );
}
SECTION( "sending with value should pass value to function" )
{
signal.Add( &thing, &Thing::Fn );
signal.Add( &thingInt, &Thing::FnInt );
signal.Send( 2 );
REQUIRE( thing.val == 1 );
REQUIRE( thingInt.val == 2 );
}
SECTION( "adding object twice should result in only single function call" )
{
REQUIRE( thing.callCount == 0 );
signal.Add( &thing, &Thing::Fn );
signal.Add( &thing, &Thing::Fn );
REQUIRE( signal.Length() == 1 );
signal.Send();
REQUIRE( thing.callCount == 1 );
}
// @TODO: Add two objects by reference
// @TODO: Add one object by reference the other by pointer
SECTION( "removing pointer object from signal should result in no function call" )
{
REQUIRE( thing.callCount == 0 );
signal.Add( &thing, &Thing::Fn );
signal.Send();
REQUIRE( thing.callCount == 1 );
signal.Remove( &thing );
signal.Send();
REQUIRE( thing.callCount == 1 );
}
// @TODO: Remove reference by reference test
// @TODO: Remove reference by pointer test
SECTION( "null pointers to objects should not be added" )
{
Thing* thingP = nullptr;
REQUIRE( signal.Length() == 0 );
signal.Add( thingP, &Thing::Fn );
REQUIRE( signal.Length() == 0 );
}
SECTION( "empty references to objects should not be added" )
{
aeRef< Thing > thingRef;
REQUIRE( signal.Length() == 0 );
signal.Add( thingRef, &Thing::Fn );
REQUIRE( signal.Length() == 0 );
}
SECTION( "destroying referenced object should result in removal on send" )
{
Thing* thingP = ae::New< Thing >( AE_ALLOC_TAG_FIXME );
aeRef< Thing > thingRef( thingP );
signal.Add( thingRef, &Thing::Fn );
ae::Delete( thingP );
signal.Send();
REQUIRE( signal.Length() == 0 );
}
}
| 30.577465 | 92 | 0.561492 | [
"object"
] |
1f136fc6795efcbd5d73abf5e85f6ce40330cee1 | 2,657 | cpp | C++ | 2016/day07/p1/main.cpp | jbaldwin/adventofcode2019 | bdc333330dd5e36458a49f0b7cd64d462c9988c7 | [
"MIT"
] | null | null | null | 2016/day07/p1/main.cpp | jbaldwin/adventofcode2019 | bdc333330dd5e36458a49f0b7cd64d462c9988c7 | [
"MIT"
] | null | null | null | 2016/day07/p1/main.cpp | jbaldwin/adventofcode2019 | bdc333330dd5e36458a49f0b7cd64d462c9988c7 | [
"MIT"
] | null | null | null | #include <lib/file_util.hpp>
#include <chain/chain.hpp>
#include <iostream>
#include <vector>
#include <string>
auto contains_abba(std::string_view data) -> bool
{
for(size_t i = 0; i < data.length() - 3; ++i)
{
// This could fail on AAAA
if(data[i] == data[i + 3] && data[i + 1] == data[i + 2])
{
// So now make sure ABBA
if(data[i] != data[i + 1])
{
return true;
}
}
}
return false;
}
auto strip_brackets(std::string_view data) -> std::string_view
{
if(data[0] == '[' || data[0] == ']')
{
data.remove_prefix(1);
}
if(data[data.length() - 1] == ']' || data[data.length() - 1] == '[')
{
data.remove_suffix(1);
}
return data;
}
int main(int argc, char* argv[])
{
std::vector<std::string> args{argv, argv + argc};
if(args.size() != 2)
{
std::cout << args[0] << " <input_file>" << std::endl;
return 0;
}
auto contents = file::read(args[1]);
size_t support_tls{0};
for(auto& line : chain::str::split(contents, '\n'))
{
// The ip part view and true if its a hypernet part.
std::vector<std::pair<std::string_view, bool>> ip_parts{};
while(true)
{
auto open_pos = chain::str::find(line, "[");
if(open_pos == std::string_view::npos)
{
ip_parts.emplace_back(strip_brackets(line), false);
break;
}
ip_parts.emplace_back(strip_brackets(line.substr(0, open_pos)), false);
line.remove_prefix(open_pos);
auto close_pos = chain::str::find(line, "]");
ip_parts.emplace_back(strip_brackets(line.substr(0, close_pos)), true);
line.remove_prefix(close_pos);
}
bool hypernet_contains_abba{false};
bool ip_contains_abba{false};
for(const auto& [s, b] : ip_parts)
{
if(!b)
{
std::cout << s;
}
else
{
std::cout << '[' << s << "]";
}
if(b && contains_abba(s))
{
hypernet_contains_abba = true;
break;
}
else if(contains_abba(s))
{
ip_contains_abba = true;
}
}
if(!hypernet_contains_abba && ip_contains_abba)
{
++support_tls;
std::cout << " VALID";
}
std::cout << "\n";
}
std::cout << "\n" << support_tls << " IP Addresses support TLS\n";
return 0;
}
| 24.154545 | 83 | 0.47309 | [
"vector"
] |
1f1930b278717e9783d90a42d2bb4f97edd4fa29 | 1,524 | cpp | C++ | leetcode/spiral_matrix.cpp | cwboden/coding-practice | a80aea59d57bfdd55c15ef2fdf01f73aff168031 | [
"MIT"
] | null | null | null | leetcode/spiral_matrix.cpp | cwboden/coding-practice | a80aea59d57bfdd55c15ef2fdf01f73aff168031 | [
"MIT"
] | null | null | null | leetcode/spiral_matrix.cpp | cwboden/coding-practice | a80aea59d57bfdd55c15ef2fdf01f73aff168031 | [
"MIT"
] | null | null | null | /**
* PROMPT:
* Given a matrix of m x n elements (m rows, n columns), return all elements of
* the matrix in spiral order.
*
* @author Carson Boden
*/
#include <iostream>
#include <vector>
std::vector<int> spiral_matrix(std::vector<std::vector<int>>& matrix)
{
std::vector<int> results;
unsigned int x_front = 0, y_front = 0;
unsigned int x_back = matrix.at(0).size() - 1, y_back = matrix.size() - 1;
while (x_front <= x_back && y_front <= y_back) {
for (unsigned int i = x_front; i < x_back; ++i) {
results.push_back(matrix.at(y_front).at(i));
}
for (unsigned int i = y_front; i < y_back; ++i) {
results.push_back(matrix.at(i).at(x_back));
}
for (unsigned int i = x_back; i > x_front; i--) {
results.push_back(matrix.at(y_back).at(i));
}
for (unsigned int i = y_back; i > y_front; i--) {
results.push_back(matrix.at(i).at(x_front));
}
x_front++;
y_front++;
x_back--;
y_back--;
}
return results;
}
void print_vector(std::vector<int>& nums) {
for (int num : nums) {
std::cout << num << ' ';
}
std::cout << std::endl;
}
int main(int argc, char* argv[])
{
std::vector<std::vector<int>> matrix = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
};
auto result = spiral_matrix(matrix);
print_vector(result);
matrix = {
{ 1, 2, 3, 4, 5, 6, 7, 8 },
{ 9, 10, 11, 12, 13, 14, 15, 16 }
};
result = spiral_matrix(matrix);
print_vector(result);
return 0;
}
| 21.166667 | 80 | 0.568898 | [
"vector"
] |
1f1fd26456dd77b7b5fa2760df505aed8d76acc2 | 12,147 | cpp | C++ | 24_Physics/AppClass.cpp | zanthous/OpenGL_AStar | 6f37e659b555e49f118468d101caf24c55870d59 | [
"MIT"
] | null | null | null | 24_Physics/AppClass.cpp | zanthous/OpenGL_AStar | 6f37e659b555e49f118468d101caf24c55870d59 | [
"MIT"
] | null | null | null | 24_Physics/AppClass.cpp | zanthous/OpenGL_AStar | 6f37e659b555e49f118468d101caf24c55870d59 | [
"MIT"
] | null | null | null | #include "AppClass.h"
using namespace Simplex;
//Benjamin Morgan
//references: https://github.com/hjweide/a-star
void Application::InitVariables(void)
{
currentLevel = std::string( "0" );
//Set the position and target of the camera
m_pCameraMngr->SetPositionTargetAndUp(
vector3(0.0f, 5.0f, 10.0f), //Position
playerLocation, //Target
AXIS_Y); //Up
//level manager load first level, hard coded for now
m_pLevelMngr->SetLevel(currentLevel);
m_pLightMngr->SetPosition(vector3(0.0f, 3.0f, 13.0f), 1); //set the position of first light (0 is reserved for ambient light)
m_pEntityMngr->AddEntity("Minecraft\\Steve.obj", "Steve");
m_pEntityMngr->AddEntity( "Minecraft\\Zombie.obj", "Zombie" );
positions = m_pLevelMngr->GetBlockPositions();
objectMap = m_pLevelMngr->getObjectMap();
weights = std::vector<float>(objectMap.size());
int nHoles = 0;
for( int i = 0; i < objectMap.size(); i++ )
{
if( objectMap[i] == 'H' )
{
nHoles++;
weights[i] = INF;
}
else
{
weights[i] = 1;
}
if( objectMap[i] == 'G' )
{
goalIndex = i;
}
else if( objectMap[i] == 'Z' )
{
zombieSpawnIndex = i;
}
}
//no clue if this is right every time but hopefully is
int index = ((int)(m_pLevelMngr->GetLevelWidth() / 2)) * m_pLevelMngr->GetLevelWidth() + (int)m_pLevelMngr->GetLevelHeight() / 2;
float playerHeight = 2.0f;
float playerWidth = 0.5f;
steveID = m_pEntityMngr->GetEntityIndex("Steve");
steveID = m_pEntityMngr->GetEntityIndex( "Zombie" );
//puts player at middle of the map height offset by its dimensions
int spawnIndex = m_pLevelMngr->GetSpawnIndex();
playerIndex = m_pLevelMngr->GetSpawnIndex();
//v3Position.x = -levelWidth / 2 + (float)(index % levelWidth);
//v3Position.z = -levelHeight / 2 + (float)(index / levelWidth);
spawnLocation = vector3();
spawnLocation.x =-m_pLevelMngr->GetLevelWidth()/2 + (spawnIndex % m_pLevelMngr->GetLevelWidth()) + playerWidth;
spawnLocation.y = positions[spawnIndex].y + (0.5f*playerHeight);
spawnLocation.z = -m_pLevelMngr->GetLevelHeight()/2 + (spawnIndex / m_pLevelMngr->GetLevelWidth()) + playerWidth;
playerLocation = spawnLocation;
goalPos = vector3();
goalPos.x = -m_pLevelMngr->GetLevelWidth() / 2 + (goalIndex % m_pLevelMngr->GetLevelWidth()) + playerWidth;
goalPos.y = positions[goalIndex].y + (0.5f*playerHeight);
goalPos.z = -m_pLevelMngr->GetLevelHeight() / 2 + (goalIndex / m_pLevelMngr->GetLevelWidth()) + playerWidth;
zombiePosition = vector3();
zombiePosition.x = -m_pLevelMngr->GetLevelWidth() / 2 + (zombieSpawnIndex % m_pLevelMngr->GetLevelWidth()) + playerWidth;
zombiePosition.y = positions[zombieSpawnIndex].y + (0.5f*playerHeight);
zombiePosition.z = -m_pLevelMngr->GetLevelHeight() / 2 + (zombieSpawnIndex / m_pLevelMngr->GetLevelWidth()) + playerWidth;
//m_pMeshMngr
m_pEntityMngr->SetModelMatrix(glm::translate(spawnLocation.x,spawnLocation.y,spawnLocation.z) * glm::rotate(IDENTITY_M4, 180.0f, AXIS_Y), "Steve");
m_pEntityMngr->SetModelMatrix( glm::translate( zombiePosition.x, zombiePosition.y, zombiePosition.z ) * glm::rotate( IDENTITY_M4, 0.0f, AXIS_Y ), "Zombie" );
for (int i = 0; i < positions.size() - nHoles; i++)
{
m_pEntityMngr->AddEntity("Minecraft\\Cube.obj", "Cube_" + std::to_string(i));
}
int adjustedIndex = 0;
for( int index = 0; index < positions.size(); index++ )
{
if( objectMap[index] == 'H' )
{
}
else
{
m_pEntityMngr->SetModelMatrix( glm::translate( positions[index] ), "Cube_" + std::to_string( adjustedIndex ) );
adjustedIndex++;
}
}
// "allocating space"
for( int index = 0; index < positions.size(); index++ )
{
paths.push_back( -1 );
}
if( !astar( weights, m_pLevelMngr->GetLevelHeight(), m_pLevelMngr->GetLevelWidth(), zombieSpawnIndex, spawnIndex, paths ) )
{
printf( "Astar couldn't find a path" );
//failure variable here
}
int currentIndex = 1;
//using player spawn index as the goal here
finalPath.push_back( spawnIndex );
currentIndex = spawnIndex;
while( true )
{
if( paths[currentIndex] != -1 )
{
finalPath.push_back( paths[currentIndex] );
currentIndex = paths[currentIndex];
}
else
{
break;
}
}
std::reverse( finalPath.begin(), finalPath.end() );
zombiePathIndex = 0;
for( int index = 0; index < finalPath.size(); index++ )
{
printf( "\n%d", finalPath[index] );
}
}
void Application::Recalculate()
{
paths.clear();
for( int index = 0; index < positions.size(); index++ )
{
paths.push_back( -1 );
}
if( !astar( weights, m_pLevelMngr->GetLevelHeight(), m_pLevelMngr->GetLevelWidth(), finalPath[zombiePathIndex], playerIndex, paths ) )
{
printf( "Astar couldn't find a path" );
//failure variable here
}
finalPath.clear();
int currentIndex = 1;
//using player spawn index as the goal here
finalPath.push_back( playerIndex );
currentIndex = playerIndex;
while( true )
{
if( paths[currentIndex] != -1 )
{
finalPath.push_back( paths[currentIndex] );
currentIndex = paths[currentIndex];
}
else
{
break;
}
}
std::reverse( finalPath.begin(), finalPath.end() );
zombiePathIndex = 0;
for( int index = 0; index < finalPath.size(); index++ )
{
printf( "\n%d", finalPath[index] );
}
}
bool Application::astar(
const std::vector<float> weights, const int height, const int width,
const int start, const int goal,
std::vector<int> &paths )
{
const float INF = std::numeric_limits<float>::infinity();
Node start_node( start, 0. );
Node goal_node( goal, 0. );
float* costs = new float[height * width];
for( int i = 0; i < height * width; ++i )
costs[i] = INF;
costs[start] = 0.;
std::priority_queue<Node> nodes_to_visit;
nodes_to_visit.push( start_node );
int* neighbors = new int[4];
bool solution_found = false;
while( !nodes_to_visit.empty() )
{
// .top() doesn't actually remove the node
Node cur = nodes_to_visit.top();
if( cur == goal_node )
{
solution_found = true;
break;
}
nodes_to_visit.pop();
// check bounds and find up to four neighbors
neighbors[0] = (cur.idx / width > 0) ? (cur.idx - width) : -1;
neighbors[1] = (cur.idx % width > 0) ? (cur.idx - 1) : -1;
neighbors[2] = (cur.idx / width + 1 < height) ? (cur.idx + width) : -1;
neighbors[3] = (cur.idx % width + 1 < width) ? (cur.idx + 1) : -1;
for( int i = 0; i < 4; ++i )
{
if( neighbors[i] >= 0 )
{
// the sum of the cost so far and the cost of this move
float new_cost = costs[cur.idx] + weights[neighbors[i]];
if( new_cost < costs[neighbors[i]] )
{
costs[neighbors[i]] = new_cost;
float priority = new_cost + Node::heuristic( neighbors[i] / width,
neighbors[i] % width,
goal / width,
goal % width );
// paths with lower expected cost are explored first
nodes_to_visit.push( Node( neighbors[i], priority ) );
paths[neighbors[i]] = (cur.idx);
}
}
}
}
delete[] costs;
delete[] neighbors;
return solution_found;
}
void Application::Update(void)
{
static float fTimer = 0; //store the new timer
static uint uClock = m_pSystem->GenClock(); //generate a new clock for that timer
fTimer = m_pSystem->GetDeltaTime( uClock ); //get the delta time for that timer
std::vector<vector3> positions = m_pLevelMngr->GetBlockPositions();
int levelHeight = m_pLevelMngr->GetLevelHeight();
int levelWidth = m_pLevelMngr->GetLevelWidth();
//MeshManager::GetInstance()->AddWireCubeToRenderList( glm::translate( IDENTITY_M4, origin ) *
// glm::scale( vector3( halfDimension.x * 2, halfDimension.y * 2, halfDimension.z * 2 ) ), vector3( 50, 0, 255 ), RENDER_WIRE );
if(keyPressedLastFrame == false )
{
//where is keyreleased?
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) )
{
if( playerIndex / levelWidth > 0 && objectMap[playerIndex - levelWidth] != 'H' )
{
playerIndex = (playerIndex - levelWidth);
playerLocation.z -= 1.0f;
keyPressedLastFrame = true;
Recalculate();
}
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) )
{
//is height usage correct?
if( playerIndex / levelWidth + 1 < levelHeight && objectMap[playerIndex + levelWidth] != 'H' )
{
playerIndex = playerIndex + levelWidth;
playerLocation.z += 1.0f;
keyPressedLastFrame = true;
Recalculate();
}
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) )
{
if( playerIndex % levelWidth > 0 && objectMap[playerIndex - 1] != 'H' )
{
playerIndex=playerIndex - 1;
playerLocation.x -= 1.0f;
keyPressedLastFrame = true;
Recalculate();
}
}
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) )
{
if( playerIndex % levelWidth + 1 < levelWidth && objectMap[playerIndex+1] != 'H' )
{
playerIndex=playerIndex + 1;
playerLocation.x += 1.0f;
keyPressedLastFrame = true;
Recalculate();
}
}
}
else
{
keyPressedLastFrame = false;
}
//Is not lined up correctly by half a unit
vector3 positionAdjusted = positions[finalPath[zombiePathIndex]];
positionAdjusted.x += 0.5;
positionAdjusted.z += 0.5;
//do some distance^2 stuff to increase performance
if( glm::distance( vector2( zombiePosition.x, zombiePosition.z ),
vector2( positionAdjusted.x,
positionAdjusted.z ) ) < .2f )
{
if( zombiePathIndex < finalPath.size() - 1 )
{
zombiePathIndex++;
}
}
float speed = 4.0f;
zombiePosition.x = glm::lerp( zombiePosition.x, positionAdjusted.x, fTimer * speed );
zombiePosition.z = glm::lerp( zombiePosition.z, positionAdjusted.z, fTimer * speed );
m_pEntityMngr->GetEntity( zombieID )->SetPosition( zombiePosition ); //thought this would affect the model matrix..
m_pEntityMngr->SetModelMatrix( glm::translate( zombiePosition.x, zombiePosition.y, zombiePosition.z )
* glm::rotate( IDENTITY_M4, 0.0f, AXIS_Y ), "Zombie" );
m_pEntityMngr->SetModelMatrix( glm::translate( playerLocation.x, playerLocation.y, playerLocation.z )
* glm::rotate( IDENTITY_M4, 180.0f, AXIS_Y ), "Steve" );
if (m_pEntityMngr->GetEntity(steveID)->GetPosition().y < -10.0f)
{
//reset
m_pEntityMngr->GetEntity(steveID)->SetPosition(spawnLocation);
m_pEntityMngr->GetEntity(steveID)->SetVelocity(vector3(0.0f,0.0f,0.0f));
//reset level rotation too
}
//Add colored planes above cubes
for (int i = 0; i < positions.size(); i++)
{
vector3 color = vector3( 255.0f, 0.0f, 0.0f );
if( std::find( finalPath.begin(), finalPath.end(),i) != finalPath.end() )
{
color = vector3( 0.0f, 255.0f, 0.0f );
}
if( objectMap[i] == 'H' )
{
//do nothing
}
else
{
vector3 temp = positions[i];
temp.y += 1.05f;
temp.x += 0.5f;
temp.z += 0.5f;
m_pMeshMngr->AddPlaneToRenderList(
glm::translate( temp) *
glm::rotate( IDENTITY_M4, 270.0f, AXIS_X ) *
glm::scale( .9f, .9f, .9f ),
color, RENDER_SOLID );
}
}
m_pEntityMngr->SetModelMatrix(m_pEntityMngr->GetModelMatrix("Ball_" + std::to_string(0)), "Ball_" + std::to_string(0));
//camera follow
m_v3CharPos = m_pEntityMngr->GetRigidBody("Steve")->GetCenterGlobal(); //get character's position vector
m_v3CamPos = m_pEntityMngr->GetRigidBody("Steve")->GetCameraFollow(); //get character's position vector
//Update the system so it knows how much time has passed since the last call
m_pSystem->Update();
//Is the ArcBall active?
ArcBall();
//Is the first person camera active?
CameraRotation();
//Update Entity Manager
m_pEntityMngr->Update();
//Set the model matrix for the main object
//m_pEntityMngr->SetModelMatrix(m_m4Steve, "Steve");
//Add objects to render list
m_pEntityMngr->AddEntityToRenderList(-1, true);
//m_pEntityMngr->AddEntityToRenderList(-1, true);
}
void Application::Display(void)
{
// Clear the screen
ClearScreen();
// draw a skybox
m_pMeshMngr->AddSkyboxToRenderList();
//render list call
m_uRenderCallCount = m_pMeshMngr->Render();
//clear the render list
m_pMeshMngr->ClearRenderList();
//draw gui,
DrawGUI();
//end the current frame (internally swaps the front and back buffers)
m_pWindow->display();
}
void Application::Release(void)
{
//Release MyEntityManager
MyEntityManager::ReleaseInstance();
//release GUI
ShutdownGUI();
} | 26.755507 | 158 | 0.671112 | [
"render",
"object",
"vector",
"model"
] |
1f25bc9a1ab287a84e64648d4b2d489bdf020c44 | 15,820 | cpp | C++ | level_one_utils/hof_matlab_source/lib_hof/src/vector/HoF_Vector_Object.cpp | jedavis82/scene_labeling | a5e819f801a4fa96a1f4b076fc2049519687b1de | [
"MIT"
] | null | null | null | level_one_utils/hof_matlab_source/lib_hof/src/vector/HoF_Vector_Object.cpp | jedavis82/scene_labeling | a5e819f801a4fa96a1f4b076fc2049519687b1de | [
"MIT"
] | null | null | null | level_one_utils/hof_matlab_source/lib_hof/src/vector/HoF_Vector_Object.cpp | jedavis82/scene_labeling | a5e819f801a4fa96a1f4b076fc2049519687b1de | [
"MIT"
] | null | null | null | #include "HoF_Vector_Object.hpp"
void hof::HoF_Vector_Object::readObjectFile( const std::string& filename )
{
std::ifstream ifs;
try
{
ifs.open(filename.c_str(), std::ifstream::in);
}
catch(std::exception &e)
{
std::stringstream ss;
ss << "[hof::HoF_Vector_Object::readObjectFile] failed to open filename=" << filename;
std::cout << "ERROR " << ss.str() << std::endl;
throw std::runtime_error(ss.str());
}
/*
* Read how many alpha layers in this object.
*/
unsigned int alpha_count;
ifs >> alpha_count;
_alpha.clear();
/*
* Scan alpha values.
*/
for(unsigned int alpha_idx=0; alpha_idx < alpha_count; alpha_idx++)
{
double alpha;
ifs >> alpha;
_alpha.push_back(alpha);
}
if ( alpha_count != _alpha.size() )
{
std::stringstream ss;
ss << "[hof::HoF_Vector_Object::readObjectFile] while reading filename=" << filename
<< " alpha_count=" << alpha_count << " does not match with _alpha.size()=" << _alpha.size();
std::cout << "ERROR " << ss.str() << std::endl;
throw std::runtime_error( ss.str() );
}
/*
* Scan the polygon vertices for each alpha layer.
*/
_object.clear();
for(unsigned int alpha_idx=0; alpha_idx < alpha_count; alpha_idx++)
{
/*
* Read total number of vertices from all polygons in this alpha layer.
*/
unsigned int total_vertex_count;
ifs >> total_vertex_count;
std::vector<std::vector<std::vector<std::pair<double,double> > > > alpha_layer_polygons;
std::vector<std::vector<std::pair<double,double> > > polygon_group_vertices;
unsigned int vertex_counter = 0;
while( vertex_counter < total_vertex_count )
{
unsigned int polygon_vertex_counter;
ifs >> polygon_vertex_counter;
vertex_counter += polygon_vertex_counter;
std::vector<std::pair<double,double> > polygon_vertices;
for( unsigned int vertex_idx=0; vertex_idx < polygon_vertex_counter; vertex_idx++)
{
double x, y;
ifs >> x >> y;
polygon_vertices.push_back( std::pair<double,double>(x,y) );
}
/*
* Check if the new polygon is contained within the first polygon in the current
* polygon group.
*/
/*
* polygon_group is empty, insert current polygon into group
* no need to check for containment.
*/
if ( polygon_group_vertices.empty() )
polygon_group_vertices.push_back( polygon_vertices );
else
{
/*
* Current polygon is contained within at least one of the polygons
* in the polygon group. Add current polygon to the group.
*/
if ( polygonIsContainedInPolygonGroup(polygon_vertices, polygon_group_vertices ) )
polygon_group_vertices.push_back( polygon_vertices );
else
{
/*
* Current polygon is not contained within any of the polygons
* in the polygon group. Save polygon group. And start a new
* polygon group with the current polygon as its first member.
*/
alpha_layer_polygons.push_back( polygon_group_vertices );
polygon_group_vertices.clear();
polygon_group_vertices.push_back(polygon_vertices);
}
}
}
alpha_layer_polygons.push_back( polygon_group_vertices );
_object[_alpha[alpha_idx]] = alpha_layer_polygons;
}
ifs.close();
setName( filename );
}
/***************************************************************************************
*
*/
void hof::HoF_Vector_Object::readFileObjectStruct( hof::file_object* file_obj )
{
_alpha.clear();
setName( std::string(file_obj->name) );
/*
* Transfer the number of alpha and the alpha values.
*/
unsigned int alpha_count = static_cast<unsigned int>( file_obj->nalphas );
for( unsigned int i=0; i<alpha_count; i++ )
_alpha.push_back( file_obj->alphas[i] );
/*
* File_Object.numob indicates the number of polygon group in the object across all alpha cuts.
* File_Object.index length is numob+1. It stores indices of vertex that belong
* to each polygon group. There can be multiple polygons in a polygon group.
* But there is no separation for each polygon. One way to detect:
* The beginning polygon vertices (predecessor index is larger than current):
* File_Object.ob[i].pred > i
*
* The end of polygon vertices (successor index is smaller than current):
* File_Object.ob[i].succ < i
*
* Total number of elements in array File_Object.ob can be found in:
*
* File_Object.index[ File_Object.numob ]
*
*/
_object.clear();
std::vector<std::vector<std::pair<double,double> > > polygon_group_vertices;
double curr_alpha = 0;
/*
* Scan vertices in each polygon group.
*/
for(int i=0; i < file_obj->numob; i++ )
{
int start_idx = file_obj->index[i];
int end_idx = file_obj->index[i+1];
if ( file_obj->ob[start_idx].fuzz == file_obj->ob[end_idx-1].fuzz )
{
curr_alpha = file_obj->ob[start_idx].fuzz;
}
else
{
std::stringstream ss;
ss << "[hof::HoF_Vector_Object::readFileObjectStruct] alpha value mismatch for ob[" << start_idx
<< "]=" << file_obj->ob[start_idx].fuzz << " and ob[" << end_idx << "]=" << file_obj->ob[end_idx].fuzz;
std::cout << "ERROR " << ss.str() << std::endl;
throw std::runtime_error( ss.str() );
}
/*
* A polygon group could contain multiple simple polygon.
*/
std::vector<std::pair<double,double> > polygon_vertices;
/*
* Scan the vertices, watch for the end of a simple polygon.
*/
for( int j=start_idx; j<end_idx; j++)
{
polygon_vertices.push_back( std::pair<double,double>(file_obj->ob[j].x, file_obj->ob[j].y) );
/*
* This is the end of a simple polygon. Push it to the polygon group and
* reset the polygon vertices.
*/
if ( file_obj->ob[j].succ < j )
{
polygon_group_vertices.push_back( polygon_vertices );
polygon_vertices.clear();
}
}
/*
* Add this polygon group to an alpha layer.
*/
if ( _object.count(curr_alpha) > 0 )
{
std::vector< std::vector< std::vector< std::pair<double,double> > > > new_alpha_layer;
new_alpha_layer.push_back( polygon_group_vertices );
_object[curr_alpha] = new_alpha_layer;
}
else
_object[curr_alpha].push_back( polygon_group_vertices );
polygon_group_vertices.clear();
}
}
/***************************************************************************************
*
*/
hof::file_object* hof::HoF_Vector_Object::createFileObjectStruct()
{
hof::file_object *fob = (struct hof::file_object *) malloc(sizeof(struct hof::file_object));
fob->name = (char *)malloc(sizeof(char)*(_name.size()+1));
strcpy(fob->name, _name.c_str());
fob->nalphas = static_cast<int>( _alpha.size() );
fob->alphas = (double *)malloc(sizeof(double)*_alpha.size());
for(int i=0; i<fob->nalphas; ++i)
fob->alphas[i] = _alpha.at(i);
unsigned int total_vertices = getTotalVertices();
fob->ob = (struct cell_objet *)malloc(sizeof(struct cell_objet)*total_vertices);
unsigned int total_polygon_group = getTotalPolygonGroup();
fob->numob = total_polygon_group;
fob->index = (int *)malloc(sizeof(int)*(total_polygon_group+1));
fob->index[0] = 0;
/*
* Polygon group index.
*/
unsigned int g = 1;
/*
* Vertices index.
*/
unsigned int v = 0;
/*
* For each alpha
*/
for(unsigned int i=0; i<_alpha.size(); i++)
{
double alpha = _alpha[i];
/*
* For each polygon group in alpha, calculate the number of vertices.
*/
for(unsigned int j=0; j<_object[alpha].size(); j++)
{
int vertices_counter = 0;
/*
* For each simple polygon in the polygon group.
*/
for(unsigned int k=0; k<_object[alpha].at(j).size(); k++)
{
/*
* Get the number of vertices in this simple polygon.
*/
vertices_counter += static_cast<int>(_object[alpha].at(j).at(k).size());
/*
* For each vertex in this simple polygon, transfer (x,y) coordinate.
*/
int v_start = v;
for(unsigned int l=0; l<_object[alpha].at(j).at(k).size(); l++, v++)
{
fob->ob[v].x = _object[alpha].at(j).at(k).at(l).first;
fob->ob[v].y = _object[alpha].at(j).at(k).at(l).second;
fob->ob[v].fuzz = alpha;
fob->ob[v].pred = v-1;
fob->ob[v].succ = v+1;
}
fob->ob[v_start].pred = v-1;
fob->ob[v-1].succ = v_start;
}
fob->index[g] = fob->index[g-1] + vertices_counter;
}
}
return fob;
}
/***************************************************************************************
*
*/
unsigned int hof::HoF_Vector_Object::addAlphaLayer( const double& alpha, const std::vector<std::vector< std::vector < std::pair<double,double> > > >& polygon_group_vertices )
{
_object.erase( _object.find(alpha) );
_object[alpha] = polygon_group_vertices;
/*
* Insert new alpha layer to the ordered list
* Alpha cuts are ordered in increasing order of alpha.
*/
unsigned int inserted_idx = 0;
unsigned int initial_size = static_cast<unsigned int>(_alpha.size());
if ( _alpha.front() > alpha )
{
/*
* Insert new alpha to front.
*/
_alpha.insert( _alpha.begin(), alpha );
return 0;
}
else
if ( _alpha.back() < alpha )
{
/*
* Push new alpha to back;
*/
_alpha.push_back( alpha );
return ( static_cast<unsigned int> ( _alpha.size() - 1 ) );
}
else
{
/*
* Find the first element in _alpha and insert new alpha before it.
*/
for(unsigned int i=0; i<_alpha.size(); ++i)
if ( _alpha.at(i) > alpha )
{
std::vector<double>::iterator it = _alpha.begin();
_alpha.insert( it+i, alpha );
inserted_idx = i;
break;
}
if ( inserted_idx == 0 && initial_size == static_cast<unsigned int>(_alpha.size()) )
{
std::stringstream ss;
ss << "<hof::HoF_Vector_Object::addAlphaLayer> alpha does not get inserted to _alpha";
std::cout << "ERROR " << ss.str() << std::endl;
throw std::runtime_error(ss.str());
}
}
return inserted_idx;
}
/*
*
*/
void hof::HoF_Vector_Object::deleteAlphaLayer( const double& alpha )
{
if ( _object.count(alpha) > 0 )
{
_object.erase( _object.find(alpha) );
for( unsigned int i=0; i<_alpha.size(); ++i)
if ( _alpha.at(i) == alpha )
_alpha.erase( _alpha.begin() + i );
}
}
/*
*
*/
unsigned int hof::HoF_Vector_Object::addPolygonGroup( const double& alpha, std::vector<std::vector<std::pair<double,double> > > polygon_group )
{
if ( _object.count(alpha) > 0 )
{
_object[alpha].push_back( polygon_group );
return ( static_cast<unsigned int> ( _object[alpha].size() - 1 ) );
}
else
{
std::vector<std::vector<std::vector<std::pair<double,double> > > > alpha_layer;
alpha_layer.push_back( polygon_group );
addAlphaLayer( alpha, alpha_layer );
return (0);
}
}
/*
* Returns true if a simple polygon is contained within any simple polygon
* that is a member of a polygon group.
*/
bool hof::HoF_Vector_Object::polygonIsContainedInPolygonGroup ( const std::vector<std::pair<double,double> >& polygon_contained,
const std::vector<std::vector<std::pair<double,double> > >& polygon_group )
{
for( unsigned int i=0; i<polygon_group.size(); i++)
{
if ( polygonIsContainedInPolygon( polygon_contained, polygon_group[i]))
return true;
}
return false;
}
/*
* Returns true if a simple polygon is contained inside another simple polygon.
*
*/
bool hof::HoF_Vector_Object::polygonIsContainedInPolygon ( const std::vector<std::pair<double,double> >& polygon_contained, const std::vector<std::pair<double,double> >& polygon_container )
{
for( unsigned int i=0; i<polygon_contained.size(); i++)
{
if ( !vertexIsContainedInPolygon( polygon_contained[i].first, polygon_contained[i].second, polygon_container ))
return false;
}
return true;
}
/*
* Returns true if a vertex (x,y) is contained within a simple polygon.
*/
bool hof::HoF_Vector_Object::vertexIsContainedInPolygon( const double& x, const double& y, const std::vector<std::pair<double,double> >& polygon )
{
unsigned int i, pred_i, succ_i;
bool up=false, down=false, right=false, left=false;
double segv;
double curr_x, curr_y;
double succ_x, succ_y;
double pred_x, pred_y;
/* for each edge in component */
for(i=0;i<polygon.size();i++)
{
pred_i = i > 0 ? i-1 : polygon.size()-1;
succ_i = i < (polygon.size()-1) ? i+1 : 0;
curr_x = polygon[i].first;
curr_y = polygon[i].second;
pred_x = polygon[pred_i].first;
pred_y = polygon[pred_i].second;
succ_x = polygon[succ_i].first;
succ_y = polygon[succ_i].second;
if((!up || !down) &&
(((x+hof::SEUIL_ZERO)>=curr_x && x<=(succ_x+hof::SEUIL_ZERO)) ||
(x<=(curr_x+hof::SEUIL_ZERO) && (x+hof::SEUIL_ZERO)>=succ_x)))
{
/* coordinate must be under or over edge */
if(fabs(succ_y-curr_y)<hof::SEUIL_ZERO)
{
/* edge is horizontal */
if(curr_y>y)
up=true;
else
down=true;
}
else if(fabs(succ_x-curr_x)>hof::SEUIL_ZERO)
{
/* check for intersect */
segv=(succ_y-curr_y)/(succ_x-curr_x)*(x-curr_x)+curr_y;
if(segv>y)
up=true;
else
down=true;
}
}
if((!right || !left) &&
(((y+hof::SEUIL_ZERO)>=curr_y && y<=(succ_y+hof::SEUIL_ZERO)) ||
(y<=(curr_y+hof::SEUIL_ZERO) && (y+hof::SEUIL_ZERO)>=succ_y))){ /* coordinate mus be to the left or right of edge */
if(fabs(succ_x-curr_x)<hof::SEUIL_ZERO){ /* edge is vertical */
if(curr_x>x)
right=true;
else
left=true;
}
else if(fabs(succ_y-curr_y)>hof::SEUIL_ZERO){ /* check for intersect */
segv=(y-curr_y)/((succ_y-curr_y)/(succ_x-curr_x))+curr_x;
if(segv>x)
right=true;
else
left=true;
}
}
}
if(up && down && right && left)
return(true); /* must have four intersects */
else
return(false);
}
/*
*
*/
unsigned int hof::HoF_Vector_Object::getTotalVertices()
{
unsigned int counter = 0;
std::map<double, std::vector< std::vector< std::vector< std::pair<double,double> > > > >::iterator it;
/*
* For each alpha layer
*/
for( it=_object.begin(); it!=_object.end(); ++it )
{
/*
* For each polygon group in an alpha layer
*/
for( unsigned int i=0; i<it->second.size(); ++i )
{
/*
* For each simple polygon in a polygon group
*/
for( unsigned int j=0; j<it->second.at(i).size(); ++j )
{
counter += it->second.at(i).at(j).size();
}
}
}
return ( counter );
}
/*
*
*/
unsigned int hof::HoF_Vector_Object::getTotalPolygonGroup()
{
unsigned int counter = 0;
std::map<double, std::vector< std::vector< std::vector< std::pair<double,double> > > > >::iterator it;
/*
* For each alpha layer
*/
for( it=_object.begin(); it!=_object.end(); ++it )
{
counter += it->second.size();
}
return ( counter );
}
/*
* Print to stdout.
*/
void hof::HoF_Vector_Object::print()
{
/*
* How many alpha we have.
*/
std::stringstream ss;
ss << "alpha_count " << _alpha.size();
std::cout << ss.str() << std::endl;
ss.str("");
ss << "alpha";
for(unsigned int i=0; i<_alpha.size();++i)
ss << " " << _alpha[i];
std::cout << ss.str() << std::endl;
/*
* For each alpha layers.
*/
for(unsigned int a=0; a<_alpha.size();++a)
{
std::cout << "polygon_group_count " << _object[_alpha.at(a)].size() << std::endl;
/*
* For each polygon group in the alpha layer.
*/
for(unsigned int g=0; g<_object[_alpha.at(a)].size(); ++g)
{
std::cout << g << " polygon_count " << _object[_alpha.at(a)].at(g).size() << std::endl;
/*
* For each simple polygon in the polygon group.
*/
for(unsigned int i=0; i<_object[_alpha.at(a)].at(g).size(); ++i)
{
std::cout << g << " " << i << " vertex_count " << _object[_alpha.at(a)].at(g).at(i).size() << std::endl;
ss.str("");
for(unsigned int j=0; j<_object[_alpha.at(a)].at(g).at(i).size(); ++j)
ss << _object[_alpha.at(a)].at(g).at(i).at(j).first << " " << _object[_alpha.at(a)].at(g).at(i).at(j).second << " ";
std::cout << ss.str() << std::endl;
}
}
}
}
/*
*
*/
void hof::HoF_Vector_Object::write(std::string outpath)
{
;
}
| 25.557351 | 189 | 0.628951 | [
"object",
"vector"
] |
1f36bb1d6dcdee8e37479aac258070c11a2eeeee | 2,508 | cc | C++ | src/object/datatype/support/bytesops.cc | ArgonLang/Argon | 462d3d8721acd5131894bcbfa0214b0cbcffdf66 | [
"Apache-2.0"
] | 13 | 2021-06-24T17:50:20.000Z | 2022-03-13T23:00:16.000Z | src/object/datatype/support/bytesops.cc | ArgonLang/Argon | 462d3d8721acd5131894bcbfa0214b0cbcffdf66 | [
"Apache-2.0"
] | null | null | null | src/object/datatype/support/bytesops.cc | ArgonLang/Argon | 462d3d8721acd5131894bcbfa0214b0cbcffdf66 | [
"Apache-2.0"
] | 1 | 2022-03-31T22:58:42.000Z | 2022-03-31T22:58:42.000Z | // This source file is part of the Argon project.
//
// Licensed under the Apache License v2.0
#include "bytesops.h"
using namespace argon::object;
void FillBadCharTable(int *table, const unsigned char *pattern, ArSSize len, bool reverse) {
// Reset table
for (int i = 0; i < 256; i++)
table[i] = (int) len;
// Fill table
// value = len(pattern) - index - 1
for (int i = 0; i < len; i++)
table[pattern[i]] = reverse ? i : ((int) len) - i - 1;
}
ArSSize DoSearch(int *table, const unsigned char *buf, ArSSize blen, const unsigned char *pattern, ArSSize plen) {
ArSSize cursor = plen - 1;
ArSSize i;
FillBadCharTable(table, pattern, plen, false);
while (cursor < blen) {
for (i = 0; i < plen; i++) {
if (buf[cursor - i] != pattern[(plen - 1) - i]) {
cursor = (cursor - i) + table[buf[cursor - i]];
break;
}
}
if (i == plen)
return cursor - (plen - 1);
}
return -1;
}
ArSSize DoRSearch(int *table, const unsigned char *buf, ArSSize blen, const unsigned char *pattern, ArSSize plen) {
ArSSize cursor = blen - plen;
ArSSize i;
FillBadCharTable(table, pattern, plen, true);
while (cursor >= 0) {
for (i = 0; i < plen; i++) {
if (buf[cursor + i] != pattern[i]) {
cursor = cursor - table[buf[cursor - i]];
break;
}
}
if (i == plen)
return cursor;
}
return -1;
}
long argon::object::support::Count(const unsigned char *buf, ArSSize blen, const unsigned char *pattern,
ArSSize plen, long n) {
ArSSize counter = 0;
ArSSize idx = 0;
ArSSize lmatch;
if (n == 0)
return 0;
while ((counter < n || n == -1) && (lmatch = Find(buf + idx, blen - idx, pattern, plen)) > -1) {
counter++;
idx += lmatch + plen;
}
return counter;
}
long argon::object::support::Find(const unsigned char *buf, ArSSize blen, const unsigned char *pattern,
ArSSize plen, bool reverse) {
/*
* Implementation of Boyer-Moore-Horspool algorithm
*/
int delta1[256] = {}; // Bad Character table
if (((long) blen) < 0)
return -2; // Too big
if (plen > blen)
return -1;
if (reverse)
return DoRSearch(delta1, buf, blen, pattern, plen);
return DoSearch(delta1, buf, blen, pattern, plen);
}
| 25.591837 | 115 | 0.536683 | [
"object"
] |
1f376919975d8b33e0785e6cc88481b8815ead42 | 4,167 | hpp | C++ | test/src_test/include/test_tools_stats.hpp | tvatter/vinecoplib | ae34d56408437e6eeacec40a51a8fa8dac378672 | [
"MIT"
] | 28 | 2017-05-05T13:27:58.000Z | 2021-07-15T23:40:01.000Z | test/src_test/include/test_tools_stats.hpp | vinecopulib/vinecopulib | ae34d56408437e6eeacec40a51a8fa8dac378672 | [
"MIT"
] | 264 | 2017-03-28T10:07:13.000Z | 2022-01-23T10:04:39.000Z | test/src_test/include/test_tools_stats.hpp | tvatter/vinecoplib | ae34d56408437e6eeacec40a51a8fa8dac378672 | [
"MIT"
] | 8 | 2017-04-24T13:54:47.000Z | 2020-10-22T16:56:17.000Z | // Copyright © 2016-2021 Thomas Nagler and Thibault Vatter
//
// This file is part of the vinecopulib library and licensed under the terms of
// the MIT license. For a copy, see the LICENSE file in the root directory of
// vinecopulib or https://vinecopulib.github.io/vinecopulib/.
#pragma once
#include "test_vinecop_sanity_checks.hpp"
#include "gtest/gtest.h"
#include <vinecopulib/bicop/class.hpp>
#include <vinecopulib/misc/tools_stats.hpp>
#include <vinecopulib/misc/tools_stl.hpp>
namespace test_tools_stats {
using namespace vinecopulib;
TEST(test_tools_stats, to_pseudo_obs_is_correct)
{
int n = 9;
// X1 = (1,...,n) and X2 = (n, ..., 1)
// X = (X1, X2)
Eigen::MatrixXd X(n, 2);
X.col(0) = Eigen::VectorXd::LinSpaced(n, 1, n);
X.col(1) = Eigen::VectorXd::LinSpaced(n, n, 1);
// U = pobs(X)
Eigen::MatrixXd U = tools_stats::to_pseudo_obs(X);
for (int i = 0; i < 9; i++) {
EXPECT_NEAR(U(i, 0), (i + 1.0) * 0.1, 1e-2);
EXPECT_NEAR(U(i, 1), 1.0 - (i + 1.0) * 0.1, 1e-2);
}
Eigen::MatrixXd X2 = tools_stats::simulate_uniform(100, 2);
EXPECT_NO_THROW(tools_stats::to_pseudo_obs(X2, "random"));
EXPECT_NO_THROW(tools_stats::to_pseudo_obs(X2, "first"));
EXPECT_ANY_THROW(tools_stats::to_pseudo_obs(X2, "something"));
}
TEST(test_tools_stats, qrng_are_correct)
{
size_t d = 2;
size_t n = 10;
size_t N = 1000;
double Nd = static_cast<double>(N);
auto cop = Bicop(BicopFamily::gaussian);
auto u = cop.simulate(n);
auto U = tools_stats::ghalton(N, d);
auto U1 = tools_stats::sobol(N, d);
auto U2 = tools_stats::simulate_uniform(N, d);
Eigen::VectorXd x(N), p(n), p1(N), x2(N), p2(n);
p2 = Eigen::VectorXd::Zero(n);
for (size_t i = 0; i < n; i++) {
auto f = [i, u](const double& u1, const double& u2) {
return (u1 <= u(i, 0) && u2 <= u(i, 1)) ? 1.0 : 0.0;
};
x = U.col(0).binaryExpr(cop.hinv1(U), f);
p(i) = x.sum() / Nd;
x = U1.col(0).binaryExpr(cop.hinv1(U1), f);
p1(i) = x.sum() / Nd;
x2 = U2.col(0).binaryExpr(cop.hinv1(U2), f);
p2(i) = x2.sum() / Nd;
}
x = cop.cdf(u);
if (p2.isApprox(x, 1e-2)) {
ASSERT_TRUE(p.isApprox(x, 1e-2));
ASSERT_TRUE(p1.isApprox(x, 1e-2));
}
}
TEST(test_tools_stats, mcor_works)
{
std::vector<int> seeds = { 1, 2, 3, 4, 5 };
Eigen::MatrixXd Z = tools_stats::simulate_uniform(10000, 2, true, seeds);
Z = tools_stats::qnorm(Z);
Z.block(0, 1, 5000, 1) =
Z.block(0, 1, 5000, 1) + Z.block(0, 0, 5000, 1).cwiseAbs2();
auto a1 = tools_stats::pairwise_mcor(Z);
Eigen::VectorXd weights = Eigen::VectorXd::Ones(10000);
auto a2 = tools_stats::pairwise_mcor(Z, weights);
ASSERT_TRUE(std::fabs(a1 - a2) < 1e-4);
a1 = tools_stats::pairwise_mcor(Z.block(0, 0, 5000, 2));
weights.block(5000, 0, 5000, 1) = Eigen::VectorXd::Zero(5000);
a2 = tools_stats::pairwise_mcor(Z, weights);
ASSERT_TRUE(std::fabs(a1 - a2) < 0.05);
}
TEST(test_tools_stats, seed_works)
{
size_t d = 2;
size_t n = 10;
std::vector<int> v = { 1, 2, 3 };
auto U1 = tools_stats::simulate_uniform(n, d);
auto U2 = tools_stats::simulate_uniform(n, d, false, v);
auto U3 = tools_stats::simulate_uniform(n, d, false, v);
ASSERT_TRUE(U1.cwiseNotEqual(U2).all());
ASSERT_TRUE(U2.cwiseEqual(U3).all());
}
TEST(test_tools_stats, dpqnorm_are_nan_safe)
{
Eigen::VectorXd X = Eigen::VectorXd::Random(10);
X(0) = std::numeric_limits<double>::quiet_NaN();
EXPECT_NO_THROW(tools_stats::dnorm(X));
EXPECT_NO_THROW(tools_stats::pnorm(X));
EXPECT_NO_THROW(tools_stats::qnorm(tools_stats::pnorm(X)));
}
TEST(test_tools_stats, dpt_are_nan_safe)
{
Eigen::VectorXd X = Eigen::VectorXd::Random(10);
X(0) = std::numeric_limits<double>::quiet_NaN();
double nu = 4.0;
EXPECT_NO_THROW(tools_stats::dt(X, nu));
EXPECT_NO_THROW(tools_stats::pt(X, nu));
EXPECT_NO_THROW(tools_stats::qt(tools_stats::pt(X, nu), nu));
}
TEST(test_tools_stats, pbvt_and_pbvnorm_are_nan_safe)
{
Eigen::MatrixXd X = Eigen::MatrixXd::Random(10, 2);
X(0) = std::numeric_limits<double>::quiet_NaN();
double rho = -0.95;
int nu = 5;
EXPECT_NO_THROW(tools_stats::pbvt(X, nu, rho));
EXPECT_NO_THROW(tools_stats::pbvnorm(X, rho));
}
}
| 29.978417 | 79 | 0.653948 | [
"vector"
] |
1f3800031cfe31cb9c5f2c9b58a5f47f14dba002 | 1,150 | cpp | C++ | aws-cpp-sdk-elasticmapreduce/source/model/AddJobFlowStepsResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-elasticmapreduce/source/model/AddJobFlowStepsResult.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-elasticmapreduce/source/model/AddJobFlowStepsResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/elasticmapreduce/model/AddJobFlowStepsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::EMR::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
AddJobFlowStepsResult::AddJobFlowStepsResult()
{
}
AddJobFlowStepsResult::AddJobFlowStepsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
AddJobFlowStepsResult& AddJobFlowStepsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("StepIds"))
{
Array<JsonView> stepIdsJsonList = jsonValue.GetArray("StepIds");
for(unsigned stepIdsIndex = 0; stepIdsIndex < stepIdsJsonList.GetLength(); ++stepIdsIndex)
{
m_stepIds.push_back(stepIdsJsonList[stepIdsIndex].AsString());
}
}
return *this;
}
| 26.136364 | 110 | 0.755652 | [
"model"
] |
1f385877e30f407894c4e45f33c351d6e9a87f45 | 7,577 | cpp | C++ | oberon/SubcommandCLI.cpp | radman0x/oberon | 365fbae6c4bdce79c36099948ebe5815577a21b4 | [
"Apache-2.0"
] | null | null | null | oberon/SubcommandCLI.cpp | radman0x/oberon | 365fbae6c4bdce79c36099948ebe5815577a21b4 | [
"Apache-2.0"
] | null | null | null | oberon/SubcommandCLI.cpp | radman0x/oberon | 365fbae6c4bdce79c36099948ebe5815577a21b4 | [
"Apache-2.0"
] | null | null | null | /***********************************************************************************************************************
** __________ ___ ________ **
** \______ \_____ __| _/ _____ _____ ____ / _____/ _____ _____ ____ ______ **
** | _/\__ \ / __ | / \ \__ \ / \ / \ ___ \__ \ / \ _/ __ \ / ___/ **
** | | \ / __ \_/ /_/ || Y Y \ / __ \_| | \ \ \_\ \ / __ \_| Y Y \\ ___/ \___ \ **
** |____|_ /(____ /\____ ||__|_| /(____ /|___| / \______ /(____ /|__|_| / \___ \/____ \ **
** \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ **
** 2013 **
***********************************************************************************************************************/
#include "SubcommandCLI.hpp"
#include "OptionPrinter.hpp"
#include "ExceptionTranslater.hpp"
#include <algorithm>
#include <cassert>
namespace
{
namespace po = boost::program_options;
} // namespace
namespace oberon {
//----------------------------------------------------------------------------------------------------------------------
SubcommandCLI::SubcommandCLI(const std::string& applicationName,
const std::string& applicationDesc,
SubcommandCollection subcommands,
const boost::program_options::options_description& mainOptions) :
applicationSubcommands_(subcommands),
globalAppOptions_( mainOptions ),
applicationDescription_(applicationDesc),
applicationName_(applicationName)
{
globalAppOptions_.add_options()
("subcommand", po::value<std::string>(), "The subcommand to execute, see below:");
subcommandOptions_.add_options()
("additional-positional", po::value<std::vector<std::string> >(), "hidden option for dev only");
subcommandPositionalOptions_.add("subcommand", 1);
subcommandPositionalOptions_.add("additional-positional", -1);
visiblePositionalOptions_.add("subcommand", 1);
}
//----------------------------------------------------------------------------------------------------------------------
SubcommandCLI::ParseOutput SubcommandCLI::parseCommandLine(int argc, char** argv)
{
po::options_description all;
all.add(applicationSubcommands_.allUniqueOptions()).add(globalAppOptions_).add(subcommandOptions_);
auto parsingCode = [&]() -> ParseOutput
{
po::parsed_options parsed = po::command_line_parser(argc, argv)
.options(all)
.positional(subcommandPositionalOptions_)
.run();
po::variables_map vm;
po::store(parsed, vm);
po::notify(vm);
if ( ! vm.count("subcommand") )
{
return ParseOutput(vm);
}
std::vector<std::string> subcommandOptions = prepareCommandLine(parsed.options,
vm.count("additional-positional")
? vm["additional-positional"].as<std::vector<std::string> >()
: std::vector<std::string>());
std::string selectedSubcommand = vm["subcommand"].as<std::string>();
if ( ! applicationSubcommands_.exists(selectedSubcommand) )
{
throw CommandLineParsingError("Subcommand used: " + selectedSubcommand + ", is not valid for this application");
}
return ParseOutput( SubcommandParse{ applicationSubcommands_.getSubcommand(selectedSubcommand),
subcommandOptions} );
}; // lambda
return executeAndTranslateExceptions<ParseOutput>(parsingCode, all, subcommandPositionalOptions_);
}
//----------------------------------------------------------------------------------------------------------------------
void SubcommandCLI::displayHelp(boost::optional<std::vector<std::string> > topics, std::ostream& out)
{
if ( topics )
{
for (auto topic : topics.get())
{
if ( applicationSubcommands_.exists(topic) )
{
out << applicationSubcommands_.getSubcommand(topic)->usageDescription() << std::endl
<< std::endl;
}
else
{
out << "Topic requested: " << topic << ", does not exist and no help can be displayed" << std::endl
<< std::endl;
}
} // for
}
else
{
out << applicationUsage() << std::endl;
}
}
//----------------------------------------------------------------------------------------------------------------------
void SubcommandCLI::displayParsingError(CommandLineParsingError& error, std::ostream& out, std::ostream& errorOut)
{
if ( boost::optional<std::string> triggeringSubcommandName = error.subcommandName() )
{
assert( applicationSubcommands_.exists(triggeringSubcommandName.get())
&& "Parsing error should only ever contain the name of a subcommand that exists in the system");
out << applicationSubcommands_.getSubcommand(triggeringSubcommandName.get())->usageDescription();
}
else
{
out << applicationUsage() << std::endl;
}
errorOut << std::endl
<< "ERROR: Parsing command line options failed " << std::endl
<< error.what() << std::endl
<< std::endl;
}
//----------------------------------------------------------------------------------------------------------------------
std::string SubcommandCLI::applicationUsage()
{
OptionPrinter printer(globalAppOptions_, visiblePositionalOptions_);
std::ostringstream applicationDesc;
applicationDesc << applicationDescription_ << std::endl
<< "USAGE: " << applicationName_ << " " << printer.usage()
<< std::endl
<< std::endl
<< printer.optionDetails() << std::endl
<< printer.positionalOptionDetails() << std::endl;
for (auto subcommandName : applicationSubcommands_.allSubcommandKeys())
{
applicationDesc << "\t\t\t\t\t\t" << subcommandName << std::endl;
}
return applicationDesc.str();
}
//----------------------------------------------------------------------------------------------------------------------
std::vector<std::string> SubcommandCLI::prepareCommandLine(const std::vector<boost::program_options::option>& options,
const std::vector<std::string>& posOptions)
{
std::vector<std::string> preparedCmdLine;
if ( posOptions.size() > 0 )
{
preparedCmdLine = posOptions;
}
for (auto option : options)
{
if ( option.position_key == -1 )
{
std::for_each( std::begin(option.original_tokens),
std::end(option.original_tokens),
[&](const std::string& str) { preparedCmdLine.push_back(str); } );
}
}
return preparedCmdLine;
}
//----------------------------------------------------------------------------------------------------------------------
} // namespace
| 39.878947 | 133 | 0.459549 | [
"vector"
] |
1f3c08366e9ae168da672953a64d70b139ec42e4 | 1,878 | hpp | C++ | src/AVM.hpp | jacksonwb/abstractVM | 49ab1901cb540da00a642cbafb80c65e36418223 | [
"MIT"
] | null | null | null | src/AVM.hpp | jacksonwb/abstractVM | 49ab1901cb540da00a642cbafb80c65e36418223 | [
"MIT"
] | null | null | null | src/AVM.hpp | jacksonwb/abstractVM | 49ab1901cb540da00a642cbafb80c65e36418223 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* AVM.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jbeall <jbeall@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/30 13:45:31 by jbeall #+# #+# */
/* Updated: 2019/05/27 15:06:54 by jbeall ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef AVM_HPP
# define AVM_HPP
#include "Lexer.hpp"
#include "Operand.hpp"
#include "utility.hpp"
#include <iostream>
#include <fstream>
#include <vector>
#include <typeinfo>
#include <stdexcept>
class RuntimeErrorException : public std::exception {
std::string message;
public:
RuntimeErrorException(std::string m) {
this->message = std::string(RED_ON) + "runtime error: " + std::string(RESET) + m;
};
virtual const char *what() const throw() {
return message.c_str();
}
};
class AVM {
Lexer *L;
std::vector<std::string> program;
std::vector<const IOperand*> stack;
void readProg(std::istream &);
void push(IOperand const *);
void pop(void);
void dump(void);
void assert(IOperand const *);
void add(void);
void sub(void);
void mul(void);
void div(void);
void mod(void);
void print(void);
void exit(size_t i, const std::vector<Token*> &tokens);
public:
AVM(std::istream &);
~AVM();
void writeProg(std::ostream &);
void run(bool);
};
#endif
| 31.830508 | 84 | 0.406816 | [
"vector"
] |
1f425afdd1b427a37dda1fc98dc3c3b1454529d2 | 17,030 | hpp | C++ | 2007-save_endo/src/rope.hpp | BrendanLeber/icfp_contests | 21b179a8484a832904d99f82fdfccd0c99d88759 | [
"MIT"
] | null | null | null | 2007-save_endo/src/rope.hpp | BrendanLeber/icfp_contests | 21b179a8484a832904d99f82fdfccd0c99d88759 | [
"MIT"
] | null | null | null | 2007-save_endo/src/rope.hpp | BrendanLeber/icfp_contests | 21b179a8484a832904d99f82fdfccd0c99d88759 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
class Rope {
public:
static constexpr size_t npos = static_cast<size_t>(-1);
Rope()
: Rope("")
{
}
Rope(std::string const& str)
: root(std::make_unique<Node>(str))
{
}
Rope(Rope const& src)
{
auto new_root = Node(*src.root);
root = std::make_unique<Node>(new_root);
}
Rope& operator=(Rope const& rhs)
{
if (this != &rhs) {
// delete existing rope to recover memory
root.reset();
// invoke copy constructor
root = std::make_unique<Node>(*(rhs.root.get()));
}
return *this;
}
size_t length() const
{
if (root == nullptr) {
return 0;
}
return root->length();
}
bool empty() const
{
return length() == 0;
}
const char& at(size_t pos) const
{
if (root == nullptr || pos >= length()) {
std::stringstream ss;
ss << "Rope::at: pos (which is " << pos << ") > this->length() (which is " << length() << ')';
throw std::out_of_range(ss.str());
}
return root->at(pos);
}
char& at(size_t pos)
{
if (root == nullptr || pos >= length()) {
std::stringstream ss;
ss << "Rope::at: pos (which is " << pos << ") > this->length() (which is " << length() << ')';
throw std::out_of_range(ss.str());
}
return root->at(pos);
}
std::string to_string() const
{
if (root == nullptr) {
return std::string{};
}
return root->tree_to_string();
}
std::string substring(size_t start, size_t len) const
{
auto total_length = length();
if (start > total_length || (start + len) > total_length) {
throw std::invalid_argument("rope index out of bounds");
}
return root->substring(start, len);
}
// A rope is balanced if and only if its length is greater than or equal to
// fib(d+2) where d refers to the depth of the rope and fib(n) represents
// the nth fibonacci number i.e. in the set {1, 1, 2, 3, 5, 8, etc...}
bool is_balanced() const
{
if (root == nullptr)
return true;
auto d = root->depth();
return length() >= fib(d + 2);
}
void balance()
{
// initiate rebalancing only if rope is unbalanced
if (!is_balanced()) {
// build vector representation of Fibonacci intervals
auto intervals = build_fib_list(length());
std::vector<Node::Handle> nodes(intervals.size());
// get leaf nodes
std::vector<Node*> leaves;
root->get_leaves(leaves);
size_t i;
auto max_i = intervals.size() - 1;
size_t currMaxInterval = 0;
Node::Handle acc = nullptr;
Node::Handle tmp = nullptr;
// attempt to insert each leaf into nodes vector based on length
for (auto& leaf : leaves) {
auto len = leaf->length();
bool inserted = false;
// ignore empty leaf nodes
if (len > 0) {
acc = std::make_unique<Node>(*leaf);
i = 0;
while (!inserted) {
// find appropriate slot for the acc node to be inserted,
// concatenating with nodes encountered along the way
while (i < max_i && len >= intervals[i + 1]) {
if (nodes[i].get() != nullptr) {
// concatenate encountered entries with node to be inserted
tmp = std::make_unique<Node>(*nodes[i].get());
acc = std::make_unique<Node>(*acc.get());
acc = std::make_unique<Node>(std::move(tmp), std::move(acc));
// update len
len = acc->length();
// if new length is sufficiently great that the node must be
// moved to a new slot, we clear out the existing entry
if (len >= intervals[i + 1])
nodes[i] = nullptr;
}
i++;
}
// target slot found -- check if occupied
if (nodes[i].get() == nullptr) {
nodes[i].swap(acc);
inserted = true;
// update currMaxInterval if necessary
if (i > currMaxInterval)
currMaxInterval = i;
}
else {
// concatenate encountered entries with node to be inserted
tmp = std::make_unique<Node>(*nodes[i].get());
acc = std::make_unique<Node>(*acc.get());
acc = std::make_unique<Node>(std::move(tmp), std::move(acc));
// update len
len = acc->length();
// if new length is sufficiently great that the node must be
// moved to a new slot, we clear out the existing entry
if (len >= intervals[i + 1])
nodes[i] = nullptr;
}
}
}
}
// concatenate remaining entries to produce balanced rope
acc = std::move(nodes[currMaxInterval]);
for (int idx = currMaxInterval; idx >= 0; idx--) {
if (nodes[idx] != nullptr) {
tmp = std::make_unique<Node>(*nodes[idx].get());
acc = std::make_unique<Node>(std::move(acc), std::move(tmp));
}
}
root = std::move(acc);
}
}
Rope& prepend(std::string const& str)
{
return prepend(Rope{ str });
}
Rope& prepend(Rope const& rope)
{
return insert(0, rope);
}
Rope& insert(size_t index, std::string const& str)
{
return insert(index, Rope(str));
}
Rope& insert(size_t index, Rope const& rope)
{
if (index > length()) {
std::stringstream ss;
ss << "Rope::insert: index (which is " << index << ") > this->length() (which is " << length() << ')';
throw std::out_of_range(ss.str());
}
Rope tmp{ rope };
auto orig_split = Node::split(std::move(root), index);
auto concat = std::make_unique<Node>(std::move(orig_split.first), std::move(tmp.root));
root = std::make_unique<Node>(std::move(concat), std::move(orig_split.second));
return *this;
}
Rope& append(std::string const& str)
{
Rope tmp{ str };
root = std::make_unique<Node>(std::move(root), std::move(tmp.root));
return *this;
}
Rope& append(Rope const& r)
{
Rope tmp{ r };
root = std::make_unique<Node>(std::move(root), std::move(tmp.root));
return *this;
}
size_t find(char needle)
{
if (root == nullptr) {
return npos;
}
for (size_t pos = 0; pos < length(); ++pos) {
if (at(pos) == needle) {
return pos;
}
}
return npos;
}
size_t search(std::string const& needle, size_t skip = 0)
{
if (skip >= length()) {
return npos;
}
auto table = preprocess(needle);
while (length() - skip >= needle.length()) {
auto i = needle.length() - 1;
while (at(skip + i) == needle[i]) {
if (i == 0) {
return skip;
}
i -= 1;
}
skip += table[at(skip + needle.length() - 1)];
}
return npos;
}
void erase(size_t index = 0, size_t count = npos)
{
auto size = length();
if (index > size) {
std::stringstream ss;
ss << "Rope::erase: index (which is " << index << ") > this->length() (which is " << size << ')';
throw std::out_of_range(ss.str());
}
count = std::min(count, size - index);
if (count > 0) {
auto first = Node::split(std::move(root), index);
auto second = Node::split(std::move(first.second), count);
second.first.reset();
root = std::make_unique<Node>(std::move(first.first), std::move(second.second));
}
}
bool operator==(Rope const& rhs) const
{
return to_string() == rhs.to_string();
}
bool operator!=(Rope const& rhs) const
{
return !(*this == rhs);
}
friend std::ostream& operator<<(std::ostream& os, Rope const& r)
{
return os << r.to_string();
}
private:
class Node {
public:
using Handle = std::unique_ptr<Node>;
Node(Handle l, Handle r)
: left(std::move(l)), right(std::move(r)), weight(left->length())
{
}
Node(std::string const& str)
: left(nullptr), right(nullptr), weight(str.length()), fragment(str)
{
}
Node(Node const& src)
: left(nullptr), right(nullptr), weight(src.weight), fragment(src.fragment)
{
auto temp_l = src.left.get();
if (temp_l != nullptr) {
left = std::make_unique<Node>(*temp_l);
}
auto temp_r = src.right.get();
if (temp_r != nullptr) {
right = std::make_unique<Node>(*temp_r);
}
}
size_t length() const
{
if (is_leaf()) {
return weight;
}
auto tmp = (right == nullptr) ? 0 : right->length();
return weight + tmp;
}
const char& at(size_t pos) const
{
auto w = weight;
if (is_leaf()) {
#if 0 // @TODO(BML) \
// if node is a leaf, return the character at the specified index
if (pos >= weight) {
throw std::invalid_argument("rope index out of bounds");
}
else {
return fragment[pos];
}
#else // the length was already checked so this should be fine
return fragment[pos];
#endif
}
else {
// else search the appropriate child node
if (pos < w) {
return left->at(pos);
}
else {
return right->at(pos - w);
}
}
}
char& at(size_t pos)
{
auto w = weight;
if (is_leaf()) {
#if 0 // @TODO(BML) \
// if node is a leaf, return the character at the specified index
if (pos >= weight) {
throw std::invalid_argument("rope index out of bounds");
}
else {
return fragment[pos];
}
#else // the length was already checked so this should be fine
return fragment[pos];
#endif
}
else {
// else search the appropriate child node
if (pos < w) {
return left->at(pos);
}
else {
return right->at(pos - w);
}
}
}
std::string substring(size_t start, size_t len) const
{
auto w = weight;
if (is_leaf()) {
if (len < w) {
return fragment.substr(start, len);
}
else {
return fragment;
}
}
else {
// check if start index in left subtree
if (start < w) {
std::string lresult = (left == nullptr) ? std::string{ "" } : left->substring(start, len);
if ((start + len) > w) {
// get number of characters in left subtree
auto tmp = w - start;
std::string rresult = (right == nullptr) ? std::string{ "" } : right->substring(w, len - tmp);
return lresult.append(rresult);
}
else {
return lresult;
}
}
else {
// if start index is in the right subtree...
return (right == nullptr) ? std::string{ "" } : right->substring(start - w, len);
}
}
}
std::string tree_to_string() const
{
if (is_leaf()) {
return fragment;
}
std::string lresult = (left == nullptr) ? std::string{ "" } : left->tree_to_string();
std::string rresult = (right == nullptr) ? std::string{ "" } : right->tree_to_string();
return lresult.append(rresult);
}
static std::pair<Handle, Handle> split(Handle node, size_t index)
{
auto w = node->weight;
// if the given node is a leaf, split the leaf
if (node->is_leaf()) {
return std::make_pair(
std::make_unique<Node>(node->fragment.substr(0, index)),
std::make_unique<Node>(node->fragment.substr(index, w - index)));
}
// if the given node is a concat (internal) node, compare index to weight and handle accordingly
Handle old_right = std::move(node->right);
if (index < w) {
node->right = nullptr;
node->weight = index;
auto splitLeftResult = Node::split(std::move(node->left), index);
node->left = std::move(splitLeftResult.first);
return std::make_pair(std::move(node), std::make_unique<Node>(std::move(splitLeftResult.second), std::move(old_right)));
}
else if (w < index) {
auto splitRightResult = Node::split(std::move(old_right), index - w);
node->right = std::move(splitRightResult.first);
return std::make_pair(std::move(node), std::move(splitRightResult.second));
}
else {
return std::make_pair(std::move(node->left), std::move(old_right));
}
}
size_t depth() const
{
if (is_leaf())
return 0;
size_t lresult = (left == nullptr) ? 0 : left->depth();
size_t rresult = (right == nullptr) ? 0 : right->depth();
return std::max(++lresult, ++rresult);
}
void get_leaves(std::vector<Node*>& v)
{
if (is_leaf()) {
v.push_back(this);
}
else {
auto tmpLeft = left.get();
if (tmpLeft != nullptr)
tmpLeft->get_leaves(v);
auto tmpRight = right.get();
if (tmpRight != nullptr)
tmpRight->get_leaves(v);
}
}
private:
bool is_leaf() const
{
return left == nullptr && right == nullptr;
}
Handle left;
Handle right;
size_t weight;
std::string fragment;
};
Node::Handle root;
std::array<int, 256> preprocess(std::string const& pattern)
{
std::array<int, 256> table;
auto plen = static_cast<int>(pattern.length());
for (auto& entry : table) {
entry = plen;
}
for (int i = 0; i < plen - 1; ++i) {
table[pattern[i]] = plen - 1 - i;
}
return table;
}
size_t fib(size_t n) const
{
if (n == 0)
return 0;
size_t a = 0, b = 1, next;
for (size_t i = 2; i <= n; i++) {
next = a + b;
a = b;
b = next;
}
return b;
}
std::vector<size_t> build_fib_list(size_t len)
{
// initialize a and b to the first and second fib numbers respectively
size_t a = 0, b = 1, next;
std::vector<size_t> intervals = std::vector<size_t>();
while (a <= len) {
if (a > 0) {
intervals.push_back(b);
}
next = a + b;
a = b;
b = next;
}
return intervals;
}
};
| 30.088339 | 136 | 0.447446 | [
"vector"
] |
1f4ce989dd397624837c9e6db7ed2766185a424c | 3,112 | hpp | C++ | include/homebot/FakeMoveBaseAction.hpp | mark1-umd/homebot | 578c424b15331de32cc6b32a4cbf7ad27dbb5ffe | [
"BSD-3-Clause"
] | null | null | null | include/homebot/FakeMoveBaseAction.hpp | mark1-umd/homebot | 578c424b15331de32cc6b32a4cbf7ad27dbb5ffe | [
"BSD-3-Clause"
] | null | null | null | include/homebot/FakeMoveBaseAction.hpp | mark1-umd/homebot | 578c424b15331de32cc6b32a4cbf7ad27dbb5ffe | [
"BSD-3-Clause"
] | null | null | null | /**
* @copyright (c) 2017 Mark R. Jenkins. All rights reserved.
* @file FakeMoveBaseAction.hpp
*
* @author MJenkins, ENPM 808X Spring 2017
* @date May 10, 2017 - Creation
*
* @brief Fake MoveBase provides an action server that simulates a navigation stack move_base action server
*
* This class provides a ROS actionlib action server that allows an action client to set a goal
* pose; the action server tracks the progress towards the goal, providing feedback to the
* requestor. When the simulated goal is reached, the action has succeeded.
*
* *
* * BSD 3-Clause License
*
* Copyright (c) 2017, Mark Jenkins
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HOMEBOT_INCLUDE_HOMEBOT_FAKEMOVEBASEACTION_HPP_
#define HOMEBOT_INCLUDE_HOMEBOT_FAKEMOVEBASEACTION_HPP_
#include <cmath>
#include "ros/ros.h"
#include "move_base_msgs/MoveBaseAction.h"
#include "actionlib/server/simple_action_server.h"
/** @brief An object to hold the action server for faking move_base actions in the HomeBot demo
*/
class FakeMoveBaseAction {
public:
FakeMoveBaseAction();
FakeMoveBaseAction(double pFBFreq, double pBaseVel);
virtual ~FakeMoveBaseAction();
void actionExecuteCB(const move_base_msgs::MoveBaseGoalConstPtr &goal);
private:
double fbFreq;
double baseVel;
double posX;
double posY;
double posZ;
double orientX;
double orientY;
double orientZ;
double orientW;
ros::NodeHandle nh;
actionlib::SimpleActionServer<move_base_msgs::MoveBaseAction> as;
double distance(double x1, double y1, double x2, double y2);
};
#endif /* HOMEBOT_INCLUDE_HOMEBOT_FAKEMOVEBASEACTION_HPP_ */
| 39.897436 | 107 | 0.768638 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.