hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e6e177ecabb8032e0cbfe6ca574ed9bc19f6566 | 421 | cpp | C++ | archive/codevs.1010.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | archive/codevs.1010.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | archive/codevs.1010.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
using namespace std;
long long dx[8]={+2,+2,-2,-2,+1,+1,-1,-1};
long long dy[8]={+1,-1,+1,-1,+2,-2,+2,-2};
long long f[20][20],n,m,x,y;
int main(){
scanf("%d%d%d%d",&n,&m,&x,&y);
for(int i=x;i<=n;i++){
for(int j=y;j<=m;j++){
for(int k=0;k<8;k++){
long long tx,ty;
tx+=dx[k]+i;
ty+=dy[k]+j;
}
}
}
}
| 20.047619 | 42 | 0.384798 | woshiluo |
2e730121679a0e9825893bb04949e16672d017f5 | 1,324 | cpp | C++ | src/SensorPaths.cpp | serve-bh-bmc/dbus-sensors | f69fbf998745bf006748c3b6ba6558443b560d21 | [
"Apache-2.0"
] | 15 | 2019-02-26T03:44:55.000Z | 2021-11-04T23:58:51.000Z | src/SensorPaths.cpp | serve-bh-bmc/dbus-sensors | f69fbf998745bf006748c3b6ba6558443b560d21 | [
"Apache-2.0"
] | 17 | 2019-01-23T19:47:44.000Z | 2022-03-31T23:03:43.000Z | src/SensorPaths.cpp | serve-bh-bmc/dbus-sensors | f69fbf998745bf006748c3b6ba6558443b560d21 | [
"Apache-2.0"
] | 21 | 2019-08-07T03:32:20.000Z | 2022-01-27T09:40:22.000Z | #include <SensorPaths.hpp>
#include <cstring>
#include <regex>
#include <string>
namespace sensor_paths
{
// This is an allowlist of the units a sensor can measure. Should be in sync
// with
// phosphor-dbus-interfaces/blob/master/xyz/openbmc_project/Sensor/Value.interface.yaml#L35
std::string getPathForUnits(const std::string& units)
{
if (units == "DegreesC" || units == unitDegreesC)
{
return "temperature";
}
if (units == "RPMS" || units == unitRPMs)
{
return "fan_tach";
}
if (units == "Volts" || units == unitVolts)
{
return "voltage";
}
if (units == "Meters" || units == unitMeters)
{
return "altitude";
}
if (units == "Amperes" || units == unitAmperes)
{
return "current";
}
if (units == "Watts" || units == unitWatts)
{
return "power";
}
if (units == "Joules" || units == unitJoules)
{
return "energy";
}
if (units == "Percent" || units == unitPercent)
{
return "Utilization";
}
if (units == "Pascals" || units == unitPascals)
{
return "pressure";
}
return "";
}
std::string escapePathForDbus(const std::string& name)
{
return std::regex_replace(name, std::regex("[^a-zA-Z0-9_/]+"), "_");
}
} // namespace sensor_paths
| 21.704918 | 91 | 0.570242 | serve-bh-bmc |
2e7413220b0009c6df42a9faafc50ddcc1cfd62b | 18,049 | cpp | C++ | silkworm/db/chaindb.cpp | gcolvin/silkworm | 11cb3ea2aa215185eb96a460f87c67f83bdc6620 | [
"Apache-2.0"
] | null | null | null | silkworm/db/chaindb.cpp | gcolvin/silkworm | 11cb3ea2aa215185eb96a460f87c67f83bdc6620 | [
"Apache-2.0"
] | null | null | null | silkworm/db/chaindb.cpp | gcolvin/silkworm | 11cb3ea2aa215185eb96a460f87c67f83bdc6620 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The Silkworm Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "chaindb.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/interprocess/mapped_region.hpp>
namespace silkworm::lmdb {
void DatabaseConfig::set_readonly(bool value) {
if (value) {
flags |= MDB_RDONLY;
} else {
flags &= ~MDB_RDONLY;
}
}
Environment::Environment(const DatabaseConfig& config) {
if (config.path.empty()) {
throw std::invalid_argument("Invalid argument : config.path");
}
// Check data file exists and get its size
// If it exists then map_size can only be either:
// 0 - map_size is adjusted by LMDB to effective data size
// any value >= data file size
// *WARNING* setting a map_size != 0 && < data_size causes
// LMDB to truncate data file thus losing data
size_t data_file_size{0};
size_t data_map_size{0};
boost::filesystem::path data_path{config.path};
bool nosubdir{(config.flags & MDB_NOSUBDIR) == MDB_NOSUBDIR};
if (!nosubdir) {
data_path /= boost::filesystem::path{"data.mdb"};
}
if (boost::filesystem::exists(data_path)) {
if (!boost::filesystem::is_regular_file(data_path)) {
throw std::runtime_error(data_path.string() + " is not a regular file");
}
data_file_size = boost::filesystem::file_size(data_path);
}
data_map_size = std::max(data_file_size, config.map_size);
// Ensure map_size is multiple of host page_size
if (data_map_size) {
size_t host_page_size{boost::interprocess::mapped_region::get_page_size()};
data_map_size = ((data_map_size + host_page_size - 1) / host_page_size) * host_page_size;
}
err_handler(mdb_env_create(&handle_));
err_handler(mdb_env_set_mapsize(handle_, data_map_size));
err_handler(mdb_env_set_maxdbs(handle_, config.max_tables));
// Eventually open data file (this may throw)
path_ = (nosubdir ? data_path.string() : data_path.parent_path().string());
err_handler(mdb_env_open(handle_, path_.c_str(), config.flags, config.mode));
}
Environment::~Environment() noexcept { close(); }
bool Environment::is_ro(void) {
unsigned int env_flags{0};
err_handler(get_flags(&env_flags));
return ((env_flags & MDB_RDONLY) == MDB_RDONLY);
}
void Environment::close() noexcept {
if (handle_) {
mdb_env_close(handle_);
handle_ = nullptr;
}
}
int Environment::get_info(MDB_envinfo* info) {
if (!info) {
throw std::invalid_argument("Invalid argument : info");
}
return mdb_env_info(handle_, info);
}
int Environment::get_flags(unsigned int* flags) {
if (!flags) {
throw std::invalid_argument("Invalid argument : flags");
}
return mdb_env_get_flags(handle_, flags);
}
int Environment::get_mapsize(size_t* size) {
MDB_envinfo info{};
int rc{get_info(&info)};
if (!rc) {
*size = info.me_mapsize;
}
return rc;
}
int Environment::get_filesize(size_t* size) {
if (!path_.size()) return ENOENT;
uint32_t flags{0};
int rc{get_flags(&flags)};
if (rc) return rc;
boost::filesystem::path data_path{path_};
bool nosubdir{(flags & MDB_NOSUBDIR) == MDB_NOSUBDIR};
if (!nosubdir) data_path /= boost::filesystem::path{"data.mdb"};
if (boost::filesystem::exists(data_path) && boost::filesystem::is_regular_file(data_path)) {
*size = boost::filesystem::file_size(data_path);
return MDB_SUCCESS;
}
return ENOENT;
}
int Environment::get_max_keysize(void) { return mdb_env_get_maxkeysize(handle_); }
int Environment::get_max_readers(unsigned int* count) {
if (!count) {
throw std::invalid_argument("Invalid argument : count");
}
return mdb_env_get_maxreaders(handle_, count);
}
int Environment::set_flags(const unsigned int flags, const bool onoff) {
return mdb_env_set_flags(handle_, flags, onoff ? 1 : 0);
}
int Environment::set_mapsize(size_t size) {
/*
* A size == 0 means LMDB will auto adjust to
* actual data file size.
* In all other cases prevent setting map_size
* to a lower value as it may truncate data file
* (observed on Windows)
*/
if (size) {
size_t actual_map_size{0};
int rc{get_mapsize(&actual_map_size)};
if (rc) return rc;
if (size < actual_map_size) {
throw std::runtime_error("Can't set a map_size lower than data file size.");
}
size_t host_page_size{boost::interprocess::mapped_region::get_page_size()};
size = ((size + host_page_size - 1) / host_page_size) * host_page_size;
}
return mdb_env_set_mapsize(handle_, size);
}
int Environment::set_max_dbs(const unsigned int count) { return mdb_env_set_maxdbs(handle_, count); }
int Environment::set_max_readers(const unsigned int count) { return mdb_env_set_maxreaders(handle_, count); }
int Environment::sync(const bool force) { return mdb_env_sync(handle_, force); }
int Environment::get_ro_txns(void) noexcept { return ro_txns_[std::this_thread::get_id()]; }
int Environment::get_rw_txns(void) noexcept { return rw_txns_[std::this_thread::get_id()]; }
void Environment::touch_ro_txns(int count) noexcept {
std::lock_guard<std::mutex> l(count_mtx_);
ro_txns_[std::this_thread::get_id()] += count;
}
void Environment::touch_rw_txns(int count) noexcept {
std::lock_guard<std::mutex> l(count_mtx_);
rw_txns_[std::this_thread::get_id()] += count;
}
std::unique_ptr<Transaction> Environment::begin_transaction(unsigned int flags) {
if (this->is_ro()) {
flags |= MDB_RDONLY;
}
return std::make_unique<Transaction>(this, flags);
}
std::unique_ptr<Transaction> Environment::begin_ro_transaction(unsigned int flags) {
// Simple overload to ensure MDB_RDONLY is set
flags |= MDB_RDONLY;
return begin_transaction(flags);
}
std::unique_ptr<Transaction> Environment::begin_rw_transaction(unsigned int flags) {
// Simple overload to ensure MDB_RDONLY is NOT set
flags &= ~MDB_RDONLY;
return begin_transaction(flags);
}
/*
* Transactions
*/
Transaction::Transaction(Environment* parent, MDB_txn* txn, unsigned int flags)
: parent_env_{parent}, handle_{txn}, flags_{flags} {}
MDB_txn* Transaction::open_transaction(Environment* parent_env, MDB_txn* parent_txn, unsigned int flags) {
/*
* A transaction and its cursors must only be used by a single thread,
* and a thread may only have one transaction at a time.
* If MDB_NOTLS is in use this does not apply to read-only transactions
*/
if (parent_env->get_rw_txns()) {
throw std::runtime_error("Rw transaction already pending in this thread");
}
// Ensure we don't open a rw tx in a ro env
unsigned int env_flags{0};
err_handler(parent_env->get_flags(&env_flags));
bool env_ro{(env_flags & MDB_RDONLY) == MDB_RDONLY};
bool txn_ro{(flags & MDB_RDONLY) == MDB_RDONLY};
if (env_ro && !txn_ro) {
throw std::runtime_error("Can't open a RW transaction on a RO environment");
}
bool env_notls{(env_flags & MDB_NOTLS) == MDB_NOTLS};
if (txn_ro && !env_notls) {
if (parent_env->get_ro_txns()) {
throw std::runtime_error("RO transaction already pending in this thread");
}
}
MDB_txn* retvar{nullptr};
int maxtries{3};
int rc{0};
do {
rc = mdb_txn_begin(*(parent_env->handle()), parent_txn, flags, &retvar);
if (rc == MDB_MAP_RESIZED) {
/*
* If mapsize is resized by another process call mdb_env_set_mapsize
* with a size of zero to adapt to new size
*/
err_handler(parent_env->set_mapsize(0));
} else if (rc == MDB_SUCCESS) {
if (txn_ro) {
parent_env->touch_ro_txns(1);
} else {
parent_env->touch_rw_txns(1);
}
break;
}
} while (--maxtries > 0);
err_handler(rc);
return retvar;
}
MDB_dbi Transaction::open_dbi(const char* name, unsigned int flags) {
MDB_dbi newdbi{0};
err_handler(mdb_dbi_open(handle_, name, flags, &newdbi));
return newdbi;
}
Transaction::Transaction(Environment* parent, unsigned int flags)
: Transaction(parent, open_transaction(parent, nullptr, flags), flags) {}
Transaction::~Transaction() { abort(); }
size_t Transaction::get_id(void) { return mdb_txn_id(handle_); }
bool Transaction::is_ro(void) { return ((flags_ & MDB_RDONLY) == MDB_RDONLY); }
std::unique_ptr<Table> Transaction::open(const TableConfig& config, unsigned flags) {
flags |= config.flags;
MDB_dbi dbi{open_dbi(config.name, flags)};
// Apply custom comparators (if any)
// Uncomment the following when necessary
// switch (config.key_comparator) // use mdb_set_compare
//{
// default:
// break;
//}
// Apply custom dup comparators (if any)
switch (config.dup_comparator) // use mdb_set_dupsort
{
case TableCustomDupComparator::ExcludeSuffix32:
err_handler(mdb_set_dupsort(handle_, dbi, dup_cmp_exclude_suffix32));
break;
default:
break;
}
return std::make_unique<Table>(this, dbi, config.name);
}
std::unique_ptr<Table> Transaction::open(MDB_dbi dbi) {
if (dbi > 1) {
throw std::invalid_argument("dbi can only be 0 or 1");
}
return std::make_unique<Table>(this, dbi, nullptr);
}
void Transaction::abort(void) {
if (handle_) {
mdb_txn_abort(handle_);
if (is_ro()) {
parent_env_->touch_ro_txns(-1);
} else {
parent_env_->touch_rw_txns(-1);
}
handle_ = nullptr;
}
}
int Transaction::commit(void) {
if (!handle_) return MDB_BAD_TXN;
int rc{mdb_txn_commit(handle_)};
if (rc == MDB_SUCCESS) {
if (is_ro()) {
parent_env_->touch_ro_txns(-1);
} else {
parent_env_->touch_rw_txns(-1);
}
handle_ = nullptr;
}
return rc;
}
/*
* Tables
*/
Table::Table(Transaction* parent, MDB_dbi dbi, const char* name)
: Table::Table(parent, dbi, name, open_cursor(parent, dbi)) {}
Table::~Table() { close(); }
MDB_cursor* Table::open_cursor(Transaction* parent, MDB_dbi dbi) {
if (!*parent->handle()) {
throw std::runtime_error("Database or transaction closed");
}
MDB_cursor* retvar{nullptr};
err_handler(mdb_cursor_open(*parent->handle(), dbi, &retvar));
return retvar;
}
Table::Table(Transaction* parent, MDB_dbi dbi, const char* name, MDB_cursor* cursor)
: parent_txn_{parent}, dbi_{dbi}, name_{name ? name : ""}, handle_{cursor} {}
int Table::get_flags(unsigned int* flags) { return mdb_dbi_flags(*parent_txn_->handle(), dbi_, flags); }
int Table::get_stat(MDB_stat* stat) { return mdb_stat(*parent_txn_->handle(), dbi_, stat); }
int Table::get_rcount(size_t* count) {
MDB_stat stat{};
int rc{get_stat(&stat)};
if (rc == MDB_SUCCESS) {
*count = stat.ms_entries;
}
return rc;
}
std::string Table::get_name(void) {
switch (dbi_) {
case FREE_DBI:
return {"[FREE_DBI]"};
case MAIN_DBI:
return {"[MAIN_DBI]"};
default:
break;
}
return name_;
}
MDB_dbi Table::get_dbi(void) { return dbi_; }
int Table::clear() {
close();
return mdb_drop(parent_txn_->handle_, dbi_, 0);
}
int Table::drop() {
close();
dbi_dropped_ = true;
return mdb_drop(parent_txn_->handle_, dbi_, 1);
}
int Table::get(MDB_val* key, MDB_val* data, MDB_cursor_op operation) {
return mdb_cursor_get(handle_, key, data, operation);
}
int Table::put(MDB_val* key, MDB_val* data, unsigned int flag) { return mdb_cursor_put(handle_, key, data, flag); }
std::optional<ByteView> Table::get(ByteView key) {
MDB_val key_val{db::to_mdb_val(key)};
MDB_val data;
int rc{get(&key_val, &data, MDB_SET)};
if (rc == MDB_NOTFOUND) {
return {};
}
err_handler(rc);
return db::from_mdb_val(data);
}
std::optional<ByteView> Table::get(ByteView key, ByteView sub_key) {
MDB_val key_val{db::to_mdb_val(key)};
MDB_val data{db::to_mdb_val(sub_key)};
int rc{get(&key_val, &data, MDB_GET_BOTH_RANGE)};
if (rc == MDB_NOTFOUND) {
return {};
}
err_handler(rc);
ByteView x{db::from_mdb_val(data)};
if (!has_prefix(x, sub_key)) {
return {};
} else {
x.remove_prefix(sub_key.length());
return x;
}
}
void Table::del(ByteView key) {
if (get(key)) {
err_handler(del_current());
}
}
void Table::del(ByteView key, ByteView sub_key) {
if (get(key, sub_key)) {
err_handler(del_current());
}
}
std::optional<db::Entry> Table::seek(ByteView prefix) {
MDB_val key_val{db::to_mdb_val(prefix)};
MDB_val data;
MDB_cursor_op op{prefix.empty() ? MDB_FIRST : MDB_SET_RANGE};
int rc{get(&key_val, &data, op)};
if (rc == MDB_NOTFOUND) {
return {};
}
err_handler(rc);
db::Entry entry;
entry.key = db::from_mdb_val(key_val);
entry.value = db::from_mdb_val(data);
return entry;
}
int Table::seek(MDB_val* key, MDB_val* data) { return get(key, data, MDB_SET_RANGE); }
int Table::seek_exact(MDB_val* key, MDB_val* data) { return get(key, data, MDB_SET); }
int Table::get_current(MDB_val* key, MDB_val* data) { return get(key, data, MDB_GET_CURRENT); }
int Table::del_current(bool alldupkeys) {
if (alldupkeys) {
unsigned int flags{0};
int rc{get_flags(&flags)};
if (rc) {
return rc;
}
if ((flags & MDB_DUPSORT) != MDB_DUPSORT) {
alldupkeys = false;
}
}
return mdb_cursor_del(handle_, alldupkeys ? MDB_NODUPDATA : 0);
}
int Table::get_first(MDB_val* key, MDB_val* data) { return get(key, data, MDB_FIRST); }
int Table::get_first_dup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_FIRST_DUP); }
int Table::get_prev(MDB_val* key, MDB_val* data) { return get(key, data, MDB_PREV); }
int Table::get_prev_dup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_PREV_DUP); }
int Table::get_next(MDB_val* key, MDB_val* data) { return get(key, data, MDB_NEXT); }
int Table::get_next_dup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_NEXT_DUP); }
int Table::get_next_nodup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_NEXT_NODUP); }
int Table::get_last(MDB_val* key, MDB_val* data) { return get(key, data, MDB_LAST); }
int Table::get_dcount(size_t* count) { return mdb_cursor_count(handle_, count); }
void Table::put(ByteView key, ByteView data, unsigned flags) {
MDB_val key_val{db::to_mdb_val(key)};
MDB_val data_val{db::to_mdb_val(data)};
err_handler(put(&key_val, &data_val, flags));
}
int Table::put_current(MDB_val* key, MDB_val* data) { return put(key, data, MDB_CURRENT); }
int Table::put_nodup(MDB_val* key, MDB_val* data) { return put(key, data, MDB_NODUPDATA); }
int Table::put_noovrw(MDB_val* key, MDB_val* data) { return put(key, data, MDB_NOOVERWRITE); }
int Table::put_reserve(MDB_val* key, MDB_val* data) { return put(key, data, MDB_RESERVE); }
int Table::put_append(MDB_val* key, MDB_val* data) { return put(key, data, MDB_APPEND); }
int Table::put_append_dup(MDB_val* key, MDB_val* data) { return put(key, data, MDB_APPENDDUP); }
int Table::put_multiple(MDB_val* key, MDB_val* data) { return put(key, data, MDB_MULTIPLE); }
void Table::close() {
// Free the cursor handle
// There is no need to close the dbi_ handle
if (handle_) {
mdb_cursor_close(handle_);
handle_ = nullptr;
}
}
std::shared_ptr<Environment> get_env(DatabaseConfig config) {
struct Value {
std::weak_ptr<Environment> wp;
uint32_t flags{0};
};
static std::map<size_t, Value> s_envs;
static std::mutex s_mtx;
// Compute flags for required instance
// We actually don't care for MDB_RDONLY
uint32_t compare_flags{config.flags ? (config.flags &= ~MDB_RDONLY) : 0};
// There's a 1:1 relation among env and the opened
// database file. Build a hash of the path.
// Note that windows is case insensitive
std::string pathstr{boost::algorithm::to_lower_copy(config.path)};
std::hash<std::string> pathhash;
size_t envkey{pathhash(pathstr)};
// Only one thread at a time
std::lock_guard<std::mutex> l(s_mtx);
// Locate env if already exists
auto iter = s_envs.find(envkey);
if (iter != s_envs.end()) {
if (iter->second.flags != compare_flags) {
err_handler(MDB_INCOMPATIBLE);
}
auto item = iter->second.wp.lock();
if (item && item->is_opened()) {
return item;
} else {
s_envs.erase(iter);
}
}
// Create new instance and open db file(s)
// Data file is opened/created on constructor
auto newitem = std::make_shared<Environment>(config);
s_envs[envkey] = {newitem, compare_flags};
return newitem;
}
int dup_cmp_exclude_suffix32(const MDB_val* a, const MDB_val* b) {
size_t lenA{(a->mv_size >= 32) ? a->mv_size - 32 : a->mv_size};
size_t lenB{(b->mv_size >= 32) ? b->mv_size - 32 : b->mv_size};
size_t len{lenA};
int64_t len_diff{(int64_t)lenA - (int64_t)(lenB)};
if (len_diff > 0) {
len = lenB;
len_diff = 1;
}
int diff{memcmp(a->mv_data, b->mv_data, len)};
return diff ? diff : (len_diff < 0 ? -1 : (int)len_diff);
}
} // namespace silkworm::lmdb
| 32.230357 | 115 | 0.653499 | gcolvin |
2e785579f8d9d1af563bbe8c74a7144bb21d7a33 | 2,136 | hpp | C++ | xs/src/boost/range/detail/iterator.hpp | born2b/Slic3r | 589a0b3ac1a50f84de694b89cc10abcac45c0ae6 | [
"CC-BY-3.0"
] | 460 | 2016-01-13T12:49:34.000Z | 2022-02-20T04:10:40.000Z | xs/src/boost/range/detail/iterator.hpp | born2b/Slic3r | 589a0b3ac1a50f84de694b89cc10abcac45c0ae6 | [
"CC-BY-3.0"
] | 197 | 2017-07-06T16:53:59.000Z | 2019-05-31T17:57:51.000Z | xs/src/boost/range/detail/iterator.hpp | born2b/Slic3r | 589a0b3ac1a50f84de694b89cc10abcac45c0ae6 | [
"CC-BY-3.0"
] | 148 | 2016-01-17T03:16:43.000Z | 2022-03-17T12:20:36.000Z | // Boost.Range library
//
// Copyright Thorsten Ottosen 2003-2004. Use, modification and
// distribution is subject to 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)
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_DETAIL_ITERATOR_HPP
#define BOOST_RANGE_DETAIL_ITERATOR_HPP
#include <boost/range/detail/common.hpp>
#include <boost/range/detail/remove_extent.hpp>
#include <boost/static_assert.hpp>
//////////////////////////////////////////////////////////////////////////////
// missing partial specialization workaround.
//////////////////////////////////////////////////////////////////////////////
namespace boost
{
namespace range_detail
{
template< typename T >
struct range_iterator_ {
template< typename C >
struct pts
{
typedef int type;
};
};
template<>
struct range_iterator_<std_container_>
{
template< typename C >
struct pts
{
typedef BOOST_RANGE_DEDUCED_TYPENAME C::iterator type;
};
};
template<>
struct range_iterator_<std_pair_>
{
template< typename P >
struct pts
{
typedef BOOST_RANGE_DEDUCED_TYPENAME P::first_type type;
};
};
template<>
struct range_iterator_<array_>
{
template< typename T >
struct pts
{
typedef BOOST_RANGE_DEDUCED_TYPENAME
remove_extent<T>::type* type;
};
};
}
template< typename C >
class range_mutable_iterator
{
typedef BOOST_RANGE_DEDUCED_TYPENAME range_detail::range<C>::type c_type;
public:
typedef typename range_detail::range_iterator_<c_type>::BOOST_NESTED_TEMPLATE pts<C>::type type;
};
}
#endif
| 27.037975 | 106 | 0.519195 | born2b |
2e848f245b5f81110c8b662c0796f425a6e459c0 | 13,740 | cpp | C++ | src/renderer/displayer/raster/raster.cpp | lPrimemaster/Liquid | 72c11bf96cccb3f93725f46f0e0756a1b732163c | [
"MIT"
] | null | null | null | src/renderer/displayer/raster/raster.cpp | lPrimemaster/Liquid | 72c11bf96cccb3f93725f46f0e0756a1b732163c | [
"MIT"
] | null | null | null | src/renderer/displayer/raster/raster.cpp | lPrimemaster/Liquid | 72c11bf96cccb3f93725f46f0e0756a1b732163c | [
"MIT"
] | null | null | null | #include "raster.h"
#include "../../raycaster/geometry.h"
#include "../overlay.h"
#include "../../../utils/shaderloader.h"
#include "../../raycaster/hittable/model.h"
#include <vector>
#include <tuple>
#include <unordered_map>
internal Vector3 rasterCamFront;
internal Vector3 rasterCamPos;
internal Vector3 rasterCamUp;
internal u32 rasterScreenW;
internal u32 rasterScreenH;
struct RasterData
{
GLuint vao, vbo;
u64 vtxCount;
};
internal std::vector<RasterData> rasterDataArray[Geometry::TYPESIZE];
internal GLuint program;
internal std::vector<Vector3> rasterRandomColors;
internal void CreateRasterSphere(i32 ico_it)
{
std::vector<Vector3> vertices;
std::vector<i32> indices;
f32 t = (1.0f + sqrtf(5.0f)) / 2.0f;
f32 len = sqrtf(1 + t*t);
f32 a = 1 / len;
f32 b = t / len;
// Create initial vertices
vertices.push_back(Vector3(-a, b, 0));
vertices.push_back(Vector3( a, b, 0));
vertices.push_back(Vector3(-a, -b, 0));
vertices.push_back(Vector3( a, -b, 0));
vertices.push_back(Vector3( 0, -a, b));
vertices.push_back(Vector3( 0, a, b));
vertices.push_back(Vector3( 0, -a, -b));
vertices.push_back(Vector3( 0, a, -b));
vertices.push_back(Vector3( b, 0, -a));
vertices.push_back(Vector3( b, 0, a));
vertices.push_back(Vector3(-b, 0, -a));
vertices.push_back(Vector3(-b, 0, a));
// Create initial faces / tris
using FaceVec = std::vector<std::tuple<i32, i32, i32>>;
FaceVec faces;
// 5 faces around point 0
faces.push_back(std::make_tuple(0, 11, 5));
faces.push_back(std::make_tuple(0, 5, 1));
faces.push_back(std::make_tuple(0, 1, 7));
faces.push_back(std::make_tuple(0, 7, 10));
faces.push_back(std::make_tuple(0, 10, 11));
// 5 adjacent faces
faces.push_back(std::make_tuple(1, 5, 9));
faces.push_back(std::make_tuple(5, 11, 4));
faces.push_back(std::make_tuple(11, 10, 2));
faces.push_back(std::make_tuple(10, 7, 6));
faces.push_back(std::make_tuple(7, 1, 8));
// 5 faces around point 3
faces.push_back(std::make_tuple(3, 9, 4));
faces.push_back(std::make_tuple(3, 4, 2));
faces.push_back(std::make_tuple(3, 2, 6));
faces.push_back(std::make_tuple(3, 6, 8));
faces.push_back(std::make_tuple(3, 8, 9));
// 5 adjacent faces
faces.push_back(std::make_tuple(4, 9, 5));
faces.push_back(std::make_tuple(2, 4, 11));
faces.push_back(std::make_tuple(6, 2, 10));
faces.push_back(std::make_tuple(8, 6, 7));
faces.push_back(std::make_tuple(9, 8, 1));
std::unordered_map<i64, i32> middlePointIndexCache;
auto getMiddlePoint = [&](i32 p1, i32 p2) -> i32
{
// first check if we have it already
bool firstIsSmaller = p1 < p2;
i64 smallerIndex = firstIsSmaller ? p1 : p2;
i64 greaterIndex = firstIsSmaller ? p2 : p1;
i64 key = (smallerIndex << 32) + greaterIndex;
if(middlePointIndexCache.find(key) != middlePointIndexCache.end())
{
return middlePointIndexCache.at(key);
}
// not in cache, calculate it
Vector3 point1 = vertices[p1];
Vector3 point2 = vertices[p2];
Vector3 middle = Vector3(
(point1.x + point2.x) / 2.0f,
(point1.y + point2.y) / 2.0f,
(point1.z + point2.z) / 2.0f
);
vertices.push_back(middle.normalized());
i32 i = (i32)vertices.size() - 1;
middlePointIndexCache.emplace(key, i);
return i;
};
// refine triangles with recursion
for (i32 i = 0; i < ico_it; i++)
{
FaceVec facesR;
for(auto t : faces)
{
i32 v1 = std::get<0>(t);
i32 v2 = std::get<1>(t);
i32 v3 = std::get<2>(t);
// replace triangle by 4 triangles
i32 a = getMiddlePoint(v1, v2);
i32 b = getMiddlePoint(v2, v3);
i32 c = getMiddlePoint(v3, v1);
facesR.push_back(std::make_tuple(v1, a, c));
facesR.push_back(std::make_tuple(v2, b, a));
facesR.push_back(std::make_tuple(v3, c, b));
facesR.push_back(std::make_tuple(a, b, c));
}
faces = facesR;
}
std::vector<f32> rawVertexData;
// done we dont use EBO for this
for(auto t : faces)
{
Vector3 v1 = vertices[std::get<0>(t)];
Vector3 v2 = vertices[std::get<1>(t)];
Vector3 v3 = vertices[std::get<2>(t)];
// flat
// Vector3 w = v2 - v1;
// Vector3 u = v3 - v1;
// Vector3 N = Vector3::Cross(w, v);
// smooth
Vector3 n1 = v1;
Vector3 n2 = v2;
Vector3 n3 = v3;
rawVertexData.push_back(v1.x);
rawVertexData.push_back(v1.y);
rawVertexData.push_back(v1.z);
rawVertexData.push_back(n1.x);
rawVertexData.push_back(n1.y);
rawVertexData.push_back(n1.z);
rawVertexData.push_back(v2.x);
rawVertexData.push_back(v2.y);
rawVertexData.push_back(v2.z);
rawVertexData.push_back(n2.x);
rawVertexData.push_back(n2.y);
rawVertexData.push_back(n2.z);
rawVertexData.push_back(v3.x);
rawVertexData.push_back(v3.y);
rawVertexData.push_back(v3.z);
rawVertexData.push_back(n3.x);
rawVertexData.push_back(n3.y);
rawVertexData.push_back(n3.z);
}
// Now fill the opengl buffer
RasterData data;
data.vtxCount = rawVertexData.size() / 2;
glGenVertexArrays(1, &data.vao);
glGenBuffers(1, &data.vbo);
glBindVertexArray(data.vao);
glBindBuffer(GL_ARRAY_BUFFER, data.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(f32) * rawVertexData.size(), rawVertexData.data(), GL_STATIC_DRAW);
// Position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)0);
glEnableVertexAttribArray(0);
// Normals
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)(3 * sizeof(f32)));
glEnableVertexAttribArray(1);
rasterDataArray[Geometry::SPHERE].push_back(data);
}
internal void CreateRasterCube()
{
RasterData& data = rasterDataArray[0].at(0);
glGenVertexArrays(1, &data.vao);
glGenBuffers(1, &data.vbo);
glBindVertexArray(data.vao);
f32 vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 0
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 1
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 2
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 0
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 1
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 2
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 0
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 1
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 2
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 0
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 1
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 2
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, // 0
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, // 1
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, // 2
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, // 0
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, // 1
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, // 2
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // 0
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // 1
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // 2
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // 0
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // 1
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // 2
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, // 0
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, // 1
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, // 2
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, // 0
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, // 1
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, // 2
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // 0
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // 1
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 2
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 0
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 1
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f // 2
};
glBindBuffer(GL_ARRAY_BUFFER, data.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)0);
glEnableVertexAttribArray(0);
// Normals
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)(3 * sizeof(f32)));
glEnableVertexAttribArray(1);
}
// TODO : Refactor this for general callbacks for both raster and rt with switch based on options
internal void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
if(glfwGetMouseButton(window, 1) != GLFW_PRESS) return;
static const f32 D2R = PI / 180.0f;
static f32 pitch = 0;
static f32 yaw = 0;
f32 xoffset = (f32)xpos - rasterScreenW / 2;
f32 yoffset = rasterScreenH / 2 - (f32)ypos;
glfwSetCursorPos(window, rasterScreenW / 2, rasterScreenH / 2);
static const f32 sensitivity = 0.1f;
xoffset *= sensitivity;
yoffset *= sensitivity;
yaw += xoffset;
pitch += yoffset;
if(pitch > 89.0f)
pitch = 89.0f;
if(pitch < -89.0f)
pitch = -89.0f;
Vector3 direction;
direction.x = cosf(D2R * yaw) * cosf(D2R * pitch);
direction.y = sinf(D2R * pitch);
direction.z = sinf(D2R * yaw) * cosf(D2R * pitch);
rasterCamFront = direction.normalized();
}
internal void mousebtn_callback(GLFWwindow* window, int button, int action, int mods)
{
if(button == 1 && action == GLFW_RELEASE)
{
// Update rt camera for current view
// TODO: Make this an option instead in the future
Scene* iworld = (Scene*)glfwGetWindowUserPointer(window);
iworld->renderCamera->updateView(rasterCamPos, rasterCamPos + rasterCamFront);
}
}
void Raster::SetupRaster(GLFWwindow* window, Overlay::RenderSettings* rs)
{
// TODO: Remove hardcode - process viewport dim change
rasterScreenW = 1280;
rasterScreenH = 720;
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetMouseButtonCallback(window, mousebtn_callback);
program = ShaderLoader::LoadSimpleShader("shaders/raster");
// Create default internal rendering models (cube and sphere)
// CreateRasterCube();
CreateRasterSphere(5);
}
void Raster::CleanRaster()
{
for(i32 i = 0; i < Geometry::TYPESIZE; i++)
{
for(auto& v : rasterDataArray[i])
{
glDeleteVertexArrays(1, &v.vao);
glDeleteBuffers(1, &v.vbo);
}
rasterDataArray[i].clear();
}
glDeleteProgram(program);
}
internal Vector3 ProcessInputIncrementFPS(GLFWwindow *window, Vector3& camFront, Vector3& camUp)
{
Vector3 R;
if(glfwGetMouseButton(window, 1) != GLFW_PRESS) return R; // Return zero vec if no right click
static const float cameraSpeed = 0.05f; // adjust accordingly
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
R = R + cameraSpeed * camFront;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
R = R - cameraSpeed * camFront;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
R = R - Vector3::Cross(camFront, camUp).normalized() * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
R = R + Vector3::Cross(camFront, camUp).normalized() * cameraSpeed;
return R;
}
internal Matrix4 UpdateCamera(GLFWwindow* window, Scene* world, Overlay::RenderSettings* rs)
{
rasterCamPos = rasterCamPos + ProcessInputIncrementFPS(window, rasterCamFront, rasterCamUp);
return Matrix4::LookAt(rasterCamPos, rasterCamPos + rasterCamFront, rasterCamUp);
}
void Raster::UpdateRasterSceneOnLoad(Scene* world)
{
rasterCamPos = world->renderCamera->origin;
rasterCamFront = world->renderCamera->direction;
rasterCamUp = world->renderCamera->up;
}
void Raster::RenderRaster(GLFWwindow* window, Scene* world, Overlay::RenderSettings* rs)
{
if(world->top == nullptr || !rs->rasterRender.load()) return;
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearDepth(1.0);
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
Matrix4 P = world->renderCamera->projection;
Matrix4 V = UpdateCamera(window, world, rs);
glUseProgram(program);
glUniformMatrix4fv(
glGetUniformLocation(program, "projection"), 1, GL_FALSE,
&P.data[0][0]
);
glUniformMatrix4fv(
glGetUniformLocation(program, "view"), 1, GL_FALSE,
&V.data[0][0]
);
// Display a cube for each obj in scene
i32 i = 0;
for(auto o : world->objList)
{
if(i >= rasterRandomColors.size())
{
rasterRandomColors.push_back(Vector3(
Random::RandomF32Range(0, 1),
Random::RandomF32Range(0, 1),
Random::RandomF32Range(0, 1)
));
}
// FIX: Redo the bvh's for transform coordinates ....
Matrix4 M = o->transform.tmatrix;
glUniformMatrix4fv(
glGetUniformLocation(program, "model"), 1, GL_FALSE,
&M.data[0][0]
);
glUniform3fv(
glGetUniformLocation(program, "objectColor"), 1,
rasterRandomColors[i++].data
);
RasterData& data = rasterDataArray[o->model->mesh->type].at(0);
glBindVertexArray(data.vao);
glDrawArrays(GL_TRIANGLES, 0, (GLsizei)data.vtxCount);
}
// glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_DEPTH_TEST);
}
| 32.40566 | 108 | 0.586681 | lPrimemaster |
2e872c91eabd0911e4d5b6946e678ef4b55d4e8d | 10,809 | cpp | C++ | G/GeographicLibWrapper/src/GeographicLibWrapper.cpp | sharanry/Yggdrasil | d89cb4ffdc8e96ad39b6242b3574c59561c1b546 | [
"MIT"
] | 195 | 2018-09-14T22:41:36.000Z | 2022-03-16T03:35:17.000Z | G/GeographicLibWrapper/src/GeographicLibWrapper.cpp | sharanry/Yggdrasil | d89cb4ffdc8e96ad39b6242b3574c59561c1b546 | [
"MIT"
] | 2,176 | 2018-12-20T07:05:43.000Z | 2022-03-31T21:39:20.000Z | G/GeographicLibWrapper/src/GeographicLibWrapper.cpp | sharanry/Yggdrasil | d89cb4ffdc8e96ad39b6242b3574c59561c1b546 | [
"MIT"
] | 455 | 2018-09-27T21:28:33.000Z | 2022-03-23T06:27:44.000Z | #include "jlcxx/jlcxx.hpp"
#include <GeographicLib/Geocentric.hpp>
#include <GeographicLib/Geoid.hpp>
#include <GeographicLib/GravityCircle.hpp>
#include <GeographicLib/GravityModel.hpp>
#include <GeographicLib/MagneticCircle.hpp>
#include <GeographicLib/MagneticModel.hpp>
#include <GeographicLib/Math.hpp>
#include <GeographicLib/NormalGravity.hpp>
using namespace GeographicLib;
JLCXX_MODULE define_julia_module(jlcxx::Module &mod) {
typedef Math::real real;
mod.add_type<Geocentric>("Geocentric")
.constructor<real, real>()
.method("forward",
[](const Geocentric &g, real lat, real lon, real h, real &X,
real &Y, real &Z) { return g.Forward(lat, lon, h, X, Y, Z); })
.method("forward",
[](const Geocentric &g, real lat, real lon, real h, real &X,
real &Y, real &Z, std::vector<real> &M) {
return g.Forward(lat, lon, h, X, Y, Z, M);
})
.method("reverse",
[](const Geocentric &g, real X, real Y, real Z, real &lat,
real &lon,
real &h) { return g.Reverse(X, Y, Z, lat, lon, h); })
.method("reverse",
[](const Geocentric &g, real X, real Y, real Z, real &lat,
real &lon, real &h, std::vector<real> &M) {
return g.Reverse(X, Y, Z, lat, lon, h, M);
})
.method("init", &Geocentric::Init)
.method("equatorial_radius", &Geocentric::EquatorialRadius)
.method("flattening", &Geocentric::Flattening)
.method("wgs84_geocentric", &Geocentric::WGS84);
mod.add_bits<Geoid::convertflag>("ConvertFlag", jlcxx::julia_type("CppEnum"));
mod.set_const("ELLIPSOIDTOGEOID", Geoid::ELLIPSOIDTOGEOID);
mod.set_const("NONE", Geoid::NONE);
mod.set_const("GEOIDTOELLIPSOID", Geoid::GEOIDTOELLIPSOID);
mod.add_type<Geoid>("Geoid")
.constructor<const std::string &, const std::string &, bool, bool>()
.method(&Geoid::operator())
.method("cache_area", &Geoid::CacheArea)
.method("cache_all", &Geoid::CacheAll)
.method("cache_clear", &Geoid::CacheClear)
.method("convert_height", &Geoid::ConvertHeight)
.method("description", &Geoid::Description)
.method("date_time", &Geoid::DateTime)
.method("geoid_file", &Geoid::GeoidFile)
.method("geoid_name", &Geoid::GeoidName)
.method("geoid_directory", &Geoid::GeoidDirectory)
.method("interpolation", &Geoid::Interpolation)
.method("max_error", &Geoid::MaxError)
.method("rms_error", &Geoid::RMSError)
.method("offset", &Geoid::Offset)
.method("scale", &Geoid::Scale)
.method("thread_safe", &Geoid::ThreadSafe)
.method("cache", &Geoid::Cache)
.method("cache_west", &Geoid::CacheWest)
.method("cache_east", &Geoid::CacheEast)
.method("cache_north", &Geoid::CacheNorth)
.method("cache_south", &Geoid::CacheSouth)
.method("equatorial_radius", &Geoid::EquatorialRadius)
.method("flattening", &Geoid::Flattening)
.method("default_geoid_path", &Geoid::DefaultGeoidPath)
.method("default_geoid_name", &Geoid::DefaultGeoidName);
mod.add_type<NormalGravity>("NormalGravity")
.constructor<real, real, real, real, bool>()
.method("surface_gravity", &NormalGravity::SurfaceGravity)
.method("gravity", &NormalGravity::Gravity)
.method("u", &NormalGravity::U)
.method("v0", &NormalGravity::V0)
.method("phi", &NormalGravity::Phi)
.method("init", &NormalGravity::Init)
.method("equatorial_radius", &NormalGravity::EquatorialRadius)
.method("mass_constant", &NormalGravity::MassConstant)
.method("dynamical_form_factor", &NormalGravity::DynamicalFormFactor)
.method("angular_velocity", &NormalGravity::AngularVelocity)
.method("flattening", &NormalGravity::Flattening)
.method("equatorial_gravity", &NormalGravity::EquatorialGravity)
.method("polar_gravity", &NormalGravity::PolarGravity)
.method("gravity_flattening", &NormalGravity::GravityFlattening)
.method("surface_potential", &NormalGravity::SurfacePotential)
.method("earth", &NormalGravity::Earth)
.method("wgs84_normal_gravity", &NormalGravity::WGS84)
.method("grs80_normal_gravity", &NormalGravity::GRS80)
.method("j2_to_flattening", &NormalGravity::J2ToFlattening)
.method("flattening_to_j2", &NormalGravity::FlatteningToJ2);
mod.add_type<GravityCircle>("GravityCircle")
.method("gravity", &GravityCircle::Gravity)
.method("disturbance", &GravityCircle::Disturbance)
.method("geoid_height", &GravityCircle::GeoidHeight)
.method("spherical_anomaly", &GravityCircle::SphericalAnomaly)
.method("w", [](const GravityCircle &g, real lon, real &gX, real &gY,
real &gZ) { return g.W(lon, gX, gY, gZ); })
.method("v", [](const GravityCircle &g, real lon, real &GX, real &GY,
real &GZ) { return g.V(lon, GX, GY, GZ); })
.method("t",
[](const GravityCircle &g, real lon, real &deltaX, real &deltaY,
real &deltaZ) { return g.T(lon, deltaX, deltaY, deltaZ); })
.method("t", [](const GravityCircle &g, real lon) { return g.T(lon); })
.method("init", &GravityCircle::Init)
.method("equatorial_radius", &GravityCircle::EquatorialRadius)
.method("flattening", &GravityCircle::Flattening)
.method("latitude", &GravityCircle::Latitude)
.method("height", &GravityCircle::Height)
.method("capabilities",
[](const GravityCircle &g) { return g.Capabilities(); })
.method("capabilities", [](const GravityCircle &g, unsigned testcaps) {
return g.Capabilities(testcaps);
});
mod.add_type<GravityModel>("GravityModel")
.constructor<const std::string &, const std::string &, int, int>()
.method("gravity", &GravityModel::Gravity)
.method("disturbance", &GravityModel::Disturbance)
.method("geoid_height", &GravityModel::GeoidHeight)
.method("spherical_anomaly", &GravityModel::SphericalAnomaly)
.method("w", &GravityModel::W)
.method("v", &GravityModel::V)
.method("t",
[](const GravityModel &g, real X, real Y, real Z, real &deltaX,
real &deltaY,
real &deltaZ) { return g.T(X, Y, Z, deltaX, deltaY, deltaZ); })
.method("t", [](const GravityModel &g, real X, real Y,
real Z) { return g.T(X, Y, Z); })
.method("u", &GravityModel::U)
.method("phi", &GravityModel::Phi)
.method("circle", &GravityModel::Circle)
.method("reference_ellipsoid", &GravityModel::ReferenceEllipsoid)
.method("description", &GravityModel::Description)
.method("date_time", &GravityModel::DateTime)
.method("gravity_file", &GravityModel::GravityFile)
.method("gravity_model_name", &GravityModel::GravityModelName)
.method("gravity_model_directory", &GravityModel::GravityModelDirectory)
.method("equatorial_radius", &GravityModel::EquatorialRadius)
.method("mass_constant", &GravityModel::MassConstant)
.method("reference_mass_constant", &GravityModel::ReferenceMassConstant)
.method("angular_velocity", &GravityModel::AngularVelocity)
.method("flattening", &GravityModel::Flattening)
.method("degree", &GravityModel::Degree)
.method("order", &GravityModel::Order)
.method("default_gravity_path", &GravityModel::DefaultGravityPath)
.method("default_gravity_name", &GravityModel::DefaultGravityName);
mod.add_type<MagneticCircle>("MagneticCircle")
.method([](const MagneticCircle &m, real lon, real &Bx, real &By,
real &Bz) { return m(lon, Bx, By, Bz); })
.method([](const MagneticCircle &m, real lon, real &Bx, real &By,
real &Bz, real &Bxt, real &Byt,
real &Bzt) { return m(lon, Bx, By, Bz, Bxt, Byt, Bzt); })
.method("field_geocentric",
[](const MagneticCircle &m, real lon, real &BX, real &BY,
real &BZ, real &BXt, real &BYt, real &BZt) {
return m.FieldGeocentric(lon, BX, BY, BZ, BXt, BYt, BZt);
})
.method("init", &MagneticCircle::Init)
.method("equatorial_radius", &MagneticCircle::EquatorialRadius)
.method("flattening", &MagneticCircle::Flattening)
.method("latitude", &MagneticCircle::Latitude)
.method("height", &MagneticCircle::Height)
.method("time", &MagneticCircle::Time);
mod.add_type<MagneticModel>("MagneticModel")
.constructor<const std::string &, const std::string &, const Geocentric &,
int, int>()
.method([](const MagneticModel &m, real t, real lat, real lon, real h,
real &Bx, real &By,
real &Bz) { return m(t, lat, lon, h, Bx, By, Bz); })
.method([](const MagneticModel &m, real t, real lat, real lon, real h,
real &Bx, real &By, real &Bz, real &Bxt, real &Byt,
real &Bzt) {
return m(t, lat, lon, h, Bx, By, Bz, Bxt, Byt, Bzt);
})
.method("circle", &MagneticModel::Circle)
.method("field_geocentric", &MagneticModel::FieldGeocentric)
.method("field_components",
[](const MagneticModel &m, real Bx, real By, real Bz, real &H,
real &F, real &D,
real &I) { return m.FieldComponents(Bx, By, Bz, H, F, D, I); })
.method("field_components",
[](const MagneticModel &m, real Bx, real By, real Bz, real Bxt,
real Byt, real Bzt, real &H, real &F, real &D, real &I,
real &Ht, real &Ft, real &Dt, real &It) {
return m.FieldComponents(Bx, By, Bz, Bxt, Byt, Bzt, H, F, D, I,
Ht, Ft, Dt, It);
})
.method("description", &MagneticModel::Description)
.method("date_time", &MagneticModel::DateTime)
.method("magnetic_file", &MagneticModel::MagneticFile)
.method("magnetic_model_name", &MagneticModel::MagneticModelName)
.method("magnetic_model_directory",
&MagneticModel::MagneticModelDirectory)
.method("min_height", &MagneticModel::MinHeight)
.method("max_height", &MagneticModel::MaxHeight)
.method("min_time", &MagneticModel::MinTime)
.method("max_time", &MagneticModel::MaxTime)
.method("equitorial_radius", &MagneticModel::EquatorialRadius)
.method("flattening", &MagneticModel::Flattening)
.method("degree", &MagneticModel::Degree)
.method("order", &MagneticModel::Order)
.method("default_magnetic_path", &MagneticModel::DefaultMagneticPath)
.method("default_magnetic_name", &MagneticModel::DefaultMagneticName);
}
| 50.746479 | 80 | 0.626515 | sharanry |
2e89af6e23e822c321ff6dde00197c26eb6568a0 | 476 | cpp | C++ | TC4/application/torpedo.cpp | rhuancaetano/openGL | 796845b31f0d0b84ac28aabc1c9bf5365648831e | [
"MIT"
] | null | null | null | TC4/application/torpedo.cpp | rhuancaetano/openGL | 796845b31f0d0b84ac28aabc1c9bf5365648831e | [
"MIT"
] | null | null | null | TC4/application/torpedo.cpp | rhuancaetano/openGL | 796845b31f0d0b84ac28aabc1c9bf5365648831e | [
"MIT"
] | null | null | null | #include <GL/glut.h>
#include "torpedo.h"
void desenhaTorpedo(double radius){
glColor3f( 0.0, 0.0, 0.35);
glBegin(GL_QUADS);
glVertex2f( -radius*0.1, radius*0.3);
glVertex2f( -radius*0.1, -radius*0.3);
glVertex2f( radius*0.1, -radius*0.3);
glVertex2f( radius*0.1, radius*0.3);
glEnd();
}
void Torpedo::drawTorpedo(){
glPushMatrix();
glTranslatef(this->x, this->y, 0.0);
glRotatef(this->theta, 0.0, 0.0, 1.0);
desenhaTorpedo(this->radius);
glPopMatrix();
} | 25.052632 | 40 | 0.663866 | rhuancaetano |
2e8a12096e876a21e1bff433bf4669d7fa9ff9c4 | 1,265 | cc | C++ | FlavoEngine/src/entityx/Entity.cc | Thirrash/FlavoEngine | fc3e867dc726d1a37ddd81bb6a1691833014703a | [
"MIT"
] | null | null | null | FlavoEngine/src/entityx/Entity.cc | Thirrash/FlavoEngine | fc3e867dc726d1a37ddd81bb6a1691833014703a | [
"MIT"
] | null | null | null | FlavoEngine/src/entityx/Entity.cc | Thirrash/FlavoEngine | fc3e867dc726d1a37ddd81bb6a1691833014703a | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2012 Alec Thomas <[email protected]>
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* Author: Alec Thomas <[email protected]>
*/
#include <algorithm>
#include "entityx/Entity.h"
namespace Engine {
const Entity::Id Entity::INVALID;
BaseComponent::Family BaseComponent::family_counter_ = 0;
void Entity::invalidate() {
id_ = INVALID;
manager_ = nullptr;
}
void Entity::destroy() {
assert(valid());
manager_->destroy(id_);
invalidate();
}
std::bitset<Engine::MAX_COMPONENTS> Entity::component_mask() const {
return manager_->component_mask(id_);
}
EntityManager::EntityManager(EventManager &event_manager) : event_manager_(event_manager) {
}
EntityManager::~EntityManager() {
reset();
}
void EntityManager::reset() {
for (Entity entity : entities_for_debugging()) entity.destroy();
for (BasePool *pool : component_pools_) {
if (pool) delete pool;
}
component_pools_.clear();
entity_component_mask_.clear();
entity_version_.clear();
free_list_.clear();
index_counter_ = 0;
}
EntityCreatedEvent::~EntityCreatedEvent() {}
EntityDestroyedEvent::~EntityDestroyedEvent() {}
} // namespace entityx
| 21.810345 | 91 | 0.72253 | Thirrash |
2e9b2a25a5037805bf27928d511bd9136237cf6c | 1,104 | cpp | C++ | src/bubblesort.cpp | jtanisha-ee/data_s | 864bdcbaac861e50d3262b0f651e809962fba2f6 | [
"MIT"
] | null | null | null | src/bubblesort.cpp | jtanisha-ee/data_s | 864bdcbaac861e50d3262b0f651e809962fba2f6 | [
"MIT"
] | null | null | null | src/bubblesort.cpp | jtanisha-ee/data_s | 864bdcbaac861e50d3262b0f651e809962fba2f6 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
#include <array>
/*
In the first pass, once the largest element is reached,it keeps on being swapped
until it gets to the last position of the sequence.
In the second pass, once the second largest element is reached, it keeps on being
swapped until it gets to the second-to-last position of the sequence.
In general,at the end of the ith pass,the right-most i elements of the sequence
(that is, those at indices from n − 1 down to n − i) are in final position.
number of passes made by bubble sort is limited to no. elements 'n'
the ith pass can be limited to the first n-i+1 elements
for eg. for a sequence of 5 elemts, the 3rd pass is ltd to the first 3 elems.
time complexity O(n^2)
*/
void bubblesort(int *s[]) {
int len = sizeof(*s)/sizeof(s[0]);
for (int i = 0; i<len; i++) {
for(int j =1; j<len-i;j++) {
int prev = s[j-1];
int next = s[j];
if(prev > next) {
int tmp = prev;
prev = next;
next = tmp;
}
}
}
}
int main () {
int s[] = {16,3,77,40,5,11};
bubblesort(&s);
for (int i = 0;i<6;i++) {
cout <<s[i]<<", ";
}
}
| 20.830189 | 82 | 0.655797 | jtanisha-ee |
2e9b63c03a4058027d44cbc03d6036f140b0986f | 7,616 | cpp | C++ | cpp/mlp_cpu/mlp.cpp | julitopower/LearnMachineLearning | 47526dd1fb52293c8199cc11207978144513bf5c | [
"BSD-2-Clause"
] | null | null | null | cpp/mlp_cpu/mlp.cpp | julitopower/LearnMachineLearning | 47526dd1fb52293c8199cc11207978144513bf5c | [
"BSD-2-Clause"
] | null | null | null | cpp/mlp_cpu/mlp.cpp | julitopower/LearnMachineLearning | 47526dd1fb52293c8199cc11207978144513bf5c | [
"BSD-2-Clause"
] | 1 | 2020-07-19T11:31:10.000Z | 2020-07-19T11:31:10.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <string>
#include <chrono>
#include <thread>
#include "mlp.hpp"
namespace {
namespace mx = mxnet::cpp;
namespace ch = std::chrono;
// The names of the model and params files are
// fixed
const std::string MODEL_FILENAME {"model.json"};
const std::string PARAMS_FILENAME {"model-params.json"};
// Utility function to read an entire file into a string
static void readall (const std::string& path, std::string *content) {
std::ifstream ifs(path, std::ios::in | std::ios::binary);
ifs.seekg(0, std::ios::end);
size_t length = ifs.tellg();
content->resize(length);
ifs.seekg(0, std::ios::beg);
ifs.read(&content->at(0), content->size());
}
}
// This constructor initializes the network, and
// leaves it ready for execution
Mlp::Mlp(const MlpParams& params) : params_{params} {
const std::size_t layers = params.hidden.size();
// Let's define the network first
auto data = mx::Symbol::Variable("data");
auto label = mx::Symbol::Variable("labels");
// Reserve space for parameters
weights_.resize(layers);
biases_.resize(layers);
outputs_.resize(layers);
// Build each layer
for (auto i = 0U; i < layers; i++) {
const auto& istr = std::to_string(i);
weights_[i] = mx::Symbol::Variable(std::string("w") + istr);
biases_[i] = mx::Symbol::Variable(std::string("b") + istr);
mx::Symbol fc = mx::FullyConnected(std::string("fc") + istr,
i == 0 ? data : outputs_[i-1],
weights_[i], biases_[i], params.hidden[i]);
if (i == layers - 1) {
outputs_[i] = fc;
} else {
outputs_[i] = mx::Activation(std::string("act") + istr, fc, mx::ActivationActType::kRelu);
}
}
// Define the outpu
network_ = mx::SoftmaxOutput("softmax", outputs_[layers - 1], label);
////////////////////////////////////////////////////////////////////////////////
// Now that the network has been built, we need to configure it
////////////////////////////////////////////////////////////////////////////////
auto ctx = mx::Context::cpu();
args_["data"] = mx::NDArray(mx::Shape(params.batch_size, params.dim), ctx);
args_["labels"] = mx::NDArray(mx::Shape(params.batch_size), ctx);
// Let MXNet infer shapes other parameters such as weights
network_.InferArgsMap(ctx, &args_, args_);
// Initialize all parameters with uniform distribution U(-0.01, 0.01)
auto initializer = mx::Uniform(0.01);
for (auto& arg : args_) {
// arg.first is parameter name, and arg.second is the value
initializer(arg.first, &arg.second);
}
// Create sgd optimizer
opt_ = mx::OptimizerRegistry::Find("sgd");
opt_->SetParam("lr", params.learning_rate)
->SetParam("wd", params.weight_decay);
// Create executor by binding parameters to the model
exec_ = network_.SimpleBind(ctx, args_);
}
Mlp::Mlp(const std::string& dir) {
// Load the params
const std::string params_filepath = dir + "/" + PARAMS_FILENAME;
args_ = mx::NDArray::LoadToMap(params_filepath);
// Load the network
const std::string model_filepath = dir + "/" + MODEL_FILENAME;
network_ = mx::Symbol::Load(model_filepath);
// Initialize the executor
// Create executor by binding parameters to the model
auto ctx = mx::Context::cpu();
exec_ = network_.SimpleBind(ctx, args_);
}
void Mlp::fit(const std::string& data_train_csv_path,
const std::string& labels_train_csv_path,
const std::string& data_test_path,
const std::string& labels_test_path) {
bool test = true;
if (data_test_path == "" || labels_test_path == "") {
test = false;
}
// Let's load the data
auto train_iter = mx::MXDataIter("CSVIter")
.SetParam("data_csv", data_train_csv_path)
.SetParam("label_csv", labels_train_csv_path)
.SetParam("data_shape", mx::Shape{params_.dim})
.SetParam("label_shape", mx::Shape{1})
.SetParam("batch_size", params_.batch_size)
.CreateDataIter();
auto test_iter = mx::MXDataIter("CSVIter");
if (test) {
test_iter.SetParam("data_csv", data_test_path)
.SetParam("label_csv", labels_test_path)
.SetParam("data_shape", mx::Shape{params_.dim})
.SetParam("label_shape", mx::Shape{1})
.SetParam("batch_size", params_.batch_size)
.CreateDataIter();
}
// There is a bug in MxNet prefetcher, sleeping
// for a little while seems to avoid it
std::this_thread::sleep_for(ch::milliseconds{100});
const auto arg_names = network_.ListArguments();
auto epochs = params_.epochs;
auto tic = ch::system_clock::now();
while (epochs > 0) {
train_iter.Reset();
while (train_iter.Next()) {
auto data_batch = train_iter.GetDataBatch();
// Set data and label
data_batch.data.CopyTo(&args_["data"]);
data_batch.label.CopyTo(&args_["labels"]);
args_["data"].WaitAll();
args_["labels"].WaitAll();
// Compute gradients
exec_->Forward(true);
exec_->Backward();
// Update parameters
for (size_t i = 0; i < arg_names.size(); ++i) {
if (arg_names[i] == "data" || arg_names[i] == "labels") continue;
opt_->Update(i, exec_->arg_arrays[i], exec_->grad_arrays[i]);
}
}
--epochs;
if (!test) {
continue;
}
mx::Accuracy acc;
test_iter.Reset();
while (test_iter.Next()) {
auto data_batch = test_iter.GetDataBatch();
data_batch.data.CopyTo(&args_["data"]);
data_batch.label.CopyTo(&args_["labels"]);
// Forward pass is enough as no gradient is needed when evaluating
exec_->Forward(false);
acc.Update(data_batch.label, exec_->outputs[0]);
}
std::cout << "Epoch: " << epochs << " " << acc.Get() << std::endl;;
}
auto toc = ch::system_clock::now();
std::cout << ch::duration_cast<ch::milliseconds>(toc - tic).count()
<< std::endl;
};
std::vector<mx::NDArray> Mlp::predict(const std::string& filepath) {
// Record start time for reporting purposes
const auto tic = ch::system_clock::now();
// Infer feature dim from the arguments
const std::uint32_t feature_dim = args_["data"].GetShape()[1];
// Let's load the data. By not defining labels, we are telling MxNet
// there are no labels
const mx_uint batch = 16;
auto train_iter = mx::MXDataIter("CSVIter")
.SetParam("data_csv", filepath)
.SetParam("data_shape", mx::Shape{feature_dim})
.SetParam("batch_size", batch)
.CreateDataIter();
train_iter.Reset();
// Iterate through the batches
std::vector<mx::NDArray> results;
const auto ctx = mx::Context::cpu();
while (train_iter.Next()) {
// Get batch
const auto& data_batch = train_iter.GetDataBatch();
// Set data and label
data_batch.data.CopyTo(&args_["data"]);
data_batch.label.CopyTo(&args_["labels"]);
args_["data"].WaitAll();
args_["labels"].WaitAll();
// Compute gradients
exec_->Forward(true);
// Gather results
mx::NDArray res{mx::Shape{exec_->outputs[0].GetShape()}, ctx};
exec_->outputs[0].CopyTo(&res);
res.WaitAll();
results.push_back(res);
}
// Report latency and return
const auto toc = ch::system_clock::now();
std::cout << ch::duration_cast<ch::milliseconds>(toc - tic).count()
<< std::endl;
return results;
}
void Mlp::reset() {};
void Mlp::save_model(const std::string &dir) {
// First save the model
const std::string model_filepath = dir + "/" + MODEL_FILENAME;
network_.Save(model_filepath);
// Now we need to save the parameters
const std::string params_filepath = dir + "/" + PARAMS_FILENAME;
mx::NDArray::Save(params_filepath, args_);
}
| 31.60166 | 96 | 0.637999 | julitopower |
2ea740c58f2e94ecc087bfb77d6d2c9bdb5c5d9e | 6,287 | cpp | C++ | SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp | pifopi/Arduino-Source | e926d9f9154a27a33d976240ae956c9460e64cf9 | [
"MIT"
] | 9 | 2021-03-06T20:37:22.000Z | 2022-03-09T02:34:47.000Z | SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp | pifopi/Arduino-Source | e926d9f9154a27a33d976240ae956c9460e64cf9 | [
"MIT"
] | 44 | 2021-05-31T21:33:14.000Z | 2022-02-25T17:40:50.000Z | SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp | pifopi/Arduino-Source | e926d9f9154a27a33d976240ae956c9460e64cf9 | [
"MIT"
] | 16 | 2021-03-21T16:00:21.000Z | 2022-03-26T08:02:11.000Z | /* Encounter Filter
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <QtGlobal>
#include "Common/Cpp/Exception.h"
#include "Common/Qt/QtJsonTools.h"
#include "Common/Qt/NoWheelComboBox.h"
#include "Pokemon/Resources/Pokemon_PokeballNames.h"
#include "Pokemon/Resources/Pokemon_PokemonSlugs.h"
#include "Pokemon/Options/Pokemon_BallSelectWidget.h"
#include "Pokemon/Options/Pokemon_NameSelectWidget.h"
#include "PokemonSwSh_EncounterFilterEnums.h"
#include "PokemonSwSh_EncounterFilterOverride.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonSwSh{
EncounterFilterOverride::EncounterFilterOverride(bool rare_stars)
: m_rare_stars(rare_stars)
// , shininess(rare_stars ? ShinyFilter::SQUARE_ONLY : ShinyFilter::STAR_ONLY)
{}
void EncounterFilterOverride::load_json(const QJsonValue& json){
QJsonObject obj = json.toObject();
{
QString value;
if (json_get_string(value, obj, "Action")){
auto iter = EncounterAction_MAP.find(value);
if (iter != EncounterAction_MAP.end()){
action = iter->second;
}
}
}
{
QString value;
json_get_string(value, obj, "Ball");
pokeball_slug = value.toUtf8().data();
}
{
QString value;
json_get_string(value, obj, "Species");
pokemon_slug = value.toStdString();
}
{
QString value;
if (json_get_string(value, obj, "ShinyFilter")){
auto iter = ShinyFilter_MAP.find(value);
if (iter != ShinyFilter_MAP.end()){
shininess = iter->second;
}
}
}
}
QJsonValue EncounterFilterOverride::to_json() const{
QJsonObject obj;
obj.insert("Action", EncounterAction_NAMES[(size_t)action]);
obj.insert("Ball", QString::fromStdString(pokeball_slug));
obj.insert("Species", QString::fromStdString(pokemon_slug));
obj.insert("ShinyFilter", ShinyFilter_NAMES[(size_t)shininess]);
return obj;
}
std::unique_ptr<EditableTableRow> EncounterFilterOverride::clone() const{
return std::unique_ptr<EditableTableRow>(new EncounterFilterOverride(*this));
}
std::vector<QWidget*> EncounterFilterOverride::make_widgets(QWidget& parent){
std::vector<QWidget*> widgets;
BallSelectWidget* ball_select = make_ball_select(parent);
widgets.emplace_back(make_action_box(parent, *ball_select));
widgets.emplace_back(ball_select);
widgets.emplace_back(make_species_select(parent));
widgets.emplace_back(make_shiny_box(parent));
return widgets;
}
QWidget* EncounterFilterOverride::make_action_box(QWidget& parent, BallSelectWidget& ball_select){
QComboBox* box = new NoWheelComboBox(&parent);
for (const QString& action : EncounterAction_NAMES){
box->addItem(action);
}
box->setCurrentIndex((int)action);
switch (action){
case EncounterAction::StopProgram:
case EncounterAction::RunAway:
ball_select.setEnabled(false);
break;
case EncounterAction::ThrowBalls:
case EncounterAction::ThrowBallsAndSave:
ball_select.setEnabled(true);
break;
}
box->connect(
box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
box, [&](int index){
if (index < 0){
index = 0;
}
action = (EncounterAction)index;
switch ((EncounterAction)index){
case EncounterAction::StopProgram:
case EncounterAction::RunAway:
ball_select.setEnabled(false);
break;
case EncounterAction::ThrowBalls:
case EncounterAction::ThrowBallsAndSave:
ball_select.setEnabled(true);
break;
}
}
);
return box;
}
BallSelectWidget* EncounterFilterOverride::make_ball_select(QWidget& parent){
using namespace Pokemon;
BallSelectWidget* box = new BallSelectWidget(parent, POKEBALL_SLUGS(), pokeball_slug);
box->connect(
box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
box, [&, box](int index){
pokeball_slug = box->slug();
}
);
return box;
}
QWidget* EncounterFilterOverride::make_species_select(QWidget& parent){
using namespace Pokemon;
NameSelectWidget* box = new NameSelectWidget(parent, NATIONAL_DEX_SLUGS(), pokemon_slug);
box->connect(
box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
box, [&, box](int index){
pokemon_slug = box->slug();
}
);
return box;
}
QWidget* EncounterFilterOverride::make_shiny_box(QWidget& parent){
QComboBox* box = new NoWheelComboBox(&parent);
if (m_rare_stars){
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::NOT_SHINY]);
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::SQUARE_ONLY]);
}else{
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::ANYTHING]);
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::NOT_SHINY]);
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::ANY_SHINY]);
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::STAR_ONLY]);
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::SQUARE_ONLY]);
box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::NOTHING]);
}
ShinyFilter current = shininess;
for (int c = 0; c < box->count(); c++){
if (box->itemText(c) == ShinyFilter_NAMES[(int)current]){
box->setCurrentIndex(c);
break;
}
}
box->connect(
box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
box, [&, box](int index){
if (index < 0){
return;
}
QString text = box->itemText(index);
auto iter = ShinyFilter_MAP.find(text);
if (iter == ShinyFilter_MAP.end()){
PA_THROW_StringException("Invalid option: " + text);
}
shininess = iter->second;
}
);
return box;
}
}
}
}
| 34.168478 | 99 | 0.627803 | pifopi |
2ea765d3f49e91c0220d188cdf92d6192629e78c | 9,293 | cpp | C++ | Source/System/Math/Algebra/Vector2.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | 2 | 2020-01-09T07:48:24.000Z | 2020-01-09T07:48:26.000Z | Source/System/Math/Algebra/Vector2.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null | Source/System/Math/Algebra/Vector2.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null |
#include "Vector2.hpp"
#include "..//Utility/Utility.hpp"
#include <ostream>
#include "Matrix22.hpp"
#include "Vector3.hpp"
#include "Vector4.hpp"
#include "../Utility/VectorDef.hpp"
namespace Engine5
{
Vector2::Vector2(Real x, Real y)
: x(x), y(y)
{
}
Vector2::Vector2(Real arr[2])
: x(arr[0]), y(arr[1])
{
}
Vector2::Vector2(const Vector3& rhs)
: x(rhs.x), y(rhs.y)
{
}
Vector2::Vector2(const Vector4& rhs)
: x(rhs.x), y(rhs.y)
{
}
Vector2::Vector2(const Vector2& rhs)
: x(rhs.x), y(rhs.y)
{
}
Vector2::~Vector2()
{
}
void Vector2::Set(Real _x, Real _y)
{
x = _x;
y = _y;
}
void Vector2::SetZero()
{
x = 0.0f;
y = 0.0f;
}
void Vector2::SetInverse()
{
x = 1.0f / x;
y = 1.0f / y;
}
void Vector2::SetNegate()
{
x = -x;
y = -y;
}
void Vector2::SetNormalize()
{
Real length = sqrtf(x * x + y * y);
if (length > 0.f)
{
(*this) *= (1.f / length);
}
}
void Vector2::SetHalf()
{
this->x *= 0.5f;
this->y *= 0.5f;
}
void Vector2::SetClean()
{
if (Math::IsZero(x))
x = 0.0f;
if (Math::IsZero(y))
y = 0.0f;
}
void Vector2::SetProjection(const Vector2& a, const Vector2& b)
{
Real multiplier = (a.DotProduct(b)) / (b.DotProduct(b));
this->x = b.x * multiplier;
this->y = b.y * multiplier;
}
Real Vector2::Length() const
{
return sqrtf(x * x + y * y);
}
Real Vector2::LengthSquared() const
{
return (x * x + y * y);
}
Real Vector2::DistanceTo(const Vector2& rhs) const
{
Real _x = rhs.x - this->x;
Real _y = rhs.y - this->y;
return sqrtf(_x * _x + _y * _y);
}
Real Vector2::DistanceSquaredTo(const Vector2& rhs) const
{
Real _x = rhs.x - this->x;
Real _y = rhs.y - this->y;
return (_x * _x + _y * _y);
}
Vector2 Vector2::ProjectionTo(const Vector2& rhs) const
{
Vector2 result = rhs;
Real multiplier = ((*this).DotProduct(rhs)) / (rhs.DotProduct(rhs));
result *= multiplier;
return result;
}
Vector2 Vector2::ProjectionFrom(const Vector2& rhs) const
{
Vector2 result = *this;
Real multiplier = (rhs.DotProduct(*this)) / ((*this).DotProduct(*this));
result *= multiplier;
return result;
}
Vector2 Vector2::Unit() const
{
Vector2 result = *this;
result.SetNormalize();
return result;
}
Vector2 Vector2::Half() const
{
Vector2 result = *this;
result.SetHalf();
return result;
}
Vector2 Vector2::Inverse() const
{
return Vector2(
Math::IsZero(x) ? 0.0f : 1.0f / this->x,
Math::IsZero(y) ? 0.0f : 1.0f / this->y);
}
Real Vector2::DotProduct(const Vector2& rhs) const
{
return (x * rhs.x + y * rhs.y);
}
Real Vector2::CrossProduct(const Vector2& rhs) const
{
return (x * rhs.y - y * rhs.x);
}
Vector2 Vector2::CrossProduct(const Real& rhs) const
{
return Vector2(rhs * y, -rhs * x);
}
Matrix22 Vector2::OuterProduct(const Vector2& rhs) const
{
return Matrix22(
this->x * rhs.x, this->x * rhs.y,
this->y * rhs.x, this->y * rhs.y);
}
Vector2 Vector2::HadamardProduct(const Vector2& rhs) const
{
return Vector2(x * rhs.x, y * rhs.y);
}
bool Vector2::IsValid() const
{
return Math::IsValid(x) && Math::IsValid(y);
}
bool Vector2::IsZero() const
{
return Math::IsZero(x) && Math::IsZero(y);
}
bool Vector2::IsEqual(const Vector2& rhs) const
{
return Math::IsEqual(x, rhs.x) && Math::IsEqual(y, rhs.y);
}
bool Vector2::IsNotEqual(const Vector2& rhs) const
{
return Math::IsNotEqual(x, rhs.x) || Math::IsNotEqual(y, rhs.y);
}
Real Vector2::GrepVec1(size_t flag0) const
{
return (*this)[SafeFlag(flag0)];
}
Vector2 Vector2::GrepVec2(size_t flag0, size_t flag1) const
{
return Vector2((*this)[SafeFlag(flag0)], (*this)[SafeFlag(flag1)]);
}
Vector3 Vector2::GrepVec3(size_t flag0, size_t flag1, size_t flag2) const
{
return Vector3((*this)[SafeFlag(flag0)], (*this)[SafeFlag(flag1)], (*this)[SafeFlag(flag2)]);
}
Vector4 Vector2::GrepVec4(size_t flag0, size_t flag1, size_t flag2, size_t flag3) const
{
return Vector4((*this)[SafeFlag(flag0)], (*this)[SafeFlag(flag1)], (*this)[SafeFlag(flag2)], (*this)[SafeFlag(flag3)]);
}
size_t Vector2::SafeFlag(size_t given) const
{
return given > Math::Vector::Y ? Math::Vector::Y : given;
}
bool Vector2::operator==(const Vector2& rhs) const
{
return Math::IsEqual(x, rhs.x) && Math::IsEqual(y, rhs.y);
}
bool Vector2::operator!=(const Vector2& rhs) const
{
return Math::IsNotEqual(x, rhs.x) || Math::IsNotEqual(y, rhs.y);
}
Vector2 Vector2::operator-() const
{
return Vector2(-x, -y);
}
Vector2& Vector2::operator=(const Vector2& rhs)
{
if (this != &rhs)
{
x = rhs.x;
y = rhs.y;
}
return *this;
}
Vector2& Vector2::operator=(const Vector3& rhs)
{
x = rhs.x;
y = rhs.y;
return *this;
}
Vector2& Vector2::operator=(const Vector4& rhs)
{
x = rhs.x;
y = rhs.y;
return *this;
}
Vector2& Vector2::operator=(Real rhs)
{
x = rhs;
y = rhs;
return *this;
}
Vector2& Vector2::operator+=(const Vector2& rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
Vector2& Vector2::operator+=(Real real)
{
x += real;
y += real;
return *this;
}
Vector2& Vector2::operator-=(const Vector2& rhs)
{
x -= rhs.x;
y -= rhs.y;
return *this;
}
Vector2& Vector2::operator-=(Real real)
{
x -= real;
y -= real;
return *this;
}
Vector2& Vector2::operator*=(Real real)
{
x *= real;
y *= real;
return *this;
}
Vector2& Vector2::operator/=(Real real)
{
x /= real;
y /= real;
return *this;
}
Vector2 Vector2::operator+(const Vector2& rhs) const
{
return Vector2(x + rhs.x, y + rhs.y);
}
Vector2 Vector2::operator+(Real real) const
{
return Vector2(x + real, y + real);
}
Vector2 Vector2::operator-(const Vector2& rhs) const
{
return Vector2(x - rhs.x, y - rhs.y);
}
Vector2 Vector2::operator-(Real real) const
{
return Vector2(x - real, y - real);
}
Vector2 Vector2::operator*(Real real) const
{
return Vector2(x * real, y * real);
}
Vector2 Vector2::operator/(Real real) const
{
return Vector2(x / real, y / real);
}
Vector2& Vector2::operator++()
{
++x;
++y;
return *this;
}
Vector2 Vector2::operator++(int)
{
Vector2 result(*this);
++(*this);
return result;
}
Vector2& Vector2::operator--()
{
--x;
--y;
return *this;
}
Vector2 Vector2::operator--(int)
{
Vector2 result(*this);
--(*this);
return result;
}
Real Vector2::operator[](size_t i) const
{
return (&x)[i];
}
Real& Vector2::operator[](size_t i)
{
return (&x)[i];
}
Real DotProduct(const Vector2& vec1, const Vector2& vec2)
{
return vec1.DotProduct(vec2);
}
Real CrossProduct(const Vector2& vec1, const Vector2& vec2)
{
return (vec1.x * vec2.y - vec1.y * vec2.x);
}
Vector2 CrossProduct(Real vec1, const Vector2& vec2)
{
return Vector2(-vec1 * vec2.y, vec1 * vec2.x);
}
Vector2 CrossProduct(const Vector2& vec1, Real vec2)
{
return Vector2(vec2 * vec1.y, -vec2 * vec1.x);
}
Matrix22 OuterProduct(const Vector2& vec1, const Vector2& vec2)
{
return vec1.OuterProduct(vec2);
}
Vector2 HadamardProduct(const Vector2& vec1, const Vector2& vec2)
{
return vec1.HadamardProduct(vec2);
}
Vector2 Projection(const Vector2& vec1, const Vector2& vec2)
{
return vec1.ProjectionTo(vec2);
}
Vector2 LinearInterpolation(const Vector2& start, const Vector2& end, Real t)
{
Vector2 result;
result.x = (1.0f - t) * start.x + t * end.x;
result.y = (1.0f - t) * start.y + t * end.y;
return result;
}
std::ostream& operator<<(std::ostream& os, const Vector2& rhs)
{
os << "[" << rhs.x << ", " << rhs.y << "]";
return os;
}
Vector2 operator*(Real real, const Vector2& vector)
{
return Vector2(vector.x * real, vector.y * real);
}
}
| 21.216895 | 127 | 0.512213 | arian153 |
2eabd19caedf684dddacc7e02a50132630e3b801 | 828 | cpp | C++ | daily_challenge/February_LeetCoding_Challenge_2021/longestWordInDictionaryThroughDeleting.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | 1 | 2021-01-27T16:37:36.000Z | 2021-01-27T16:37:36.000Z | daily_challenge/February_LeetCoding_Challenge_2021/longestWordInDictionaryThroughDeleting.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | null | null | null | daily_challenge/February_LeetCoding_Challenge_2021/longestWordInDictionaryThroughDeleting.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool compare(string &a, string &b) {
if (a.size() == b.size())
return a < b;
return a.size() > b.size();
}
class Solution {
public:
bool find(string &a, string &b, int i, int j) {
// if we have found the string
if (i == a.size())
return true;
// if we have reached the end
if (j == b.size())
return false;
if (a[i] == b[j])
return find(a, b, i + 1, j + 1);
else
return find(a, b, i, j + 1);
}
string findLongestWord(string s, vector<string> &dictionary) {
sort(dictionary.begin(), dictionary.end(), compare);
for (int i = 0; i < dictionary.size(); i++) {
// if this word is a subsequence of s
if (find(dictionary[i], s, 0, 0)) {
return dictionary[i];
}
}
return "";
}
};
| 21.789474 | 64 | 0.539855 | archit-1997 |
2eaf65447a7e7a2f0cf95263fbca227bef909f12 | 1,563 | cpp | C++ | Project/Source/Panels/PanelAudioMixer.cpp | TBD-org/TBD-Engine | 8b45d5a2a92e26bd0ec034047b8188e871fab0f9 | [
"MIT"
] | 7 | 2021-04-26T21:32:12.000Z | 2022-02-14T13:48:53.000Z | Project/Source/Panels/PanelAudioMixer.cpp | TBD-org/RealBugEngine | 0131fde0abc2d86137500acd6f63ed8f0fc2835f | [
"MIT"
] | 66 | 2021-04-24T10:08:07.000Z | 2021-10-05T16:52:56.000Z | Project/Source/Panels/PanelAudioMixer.cpp | TBD-org/TBD-Engine | 8b45d5a2a92e26bd0ec034047b8188e871fab0f9 | [
"MIT"
] | 1 | 2021-07-13T21:26:13.000Z | 2021-07-13T21:26:13.000Z | #include "PanelAudioMixer.h"
#include "Application.h"
#include "Modules/ModuleEditor.h"
#include "Modules/ModuleScene.h"
#include "Modules/ModuleAudio.h"
#include "Utils/Pool.h"
#include "Scene.h"
#include "imgui.h"
#include "IconsForkAwesome.h"
#include <string>
#include "Utils/Logging.h"
#include "Utils/Leaks.h"
PanelAudioMixer::PanelAudioMixer()
: Panel("Audio Mixer", false) {}
void PanelAudioMixer::Update() {
ImGui::SetNextWindowSize(ImVec2(400.0f, 400.0f), ImGuiCond_FirstUseEver);
std::string windowName = std::string(ICON_FK_MUSIC " ") + name;
if (ImGui::Begin(windowName.c_str(), &enabled, ImGuiWindowFlags_AlwaysAutoResize)) {
if (App->scene->scene->audioListenerComponents.Count() == 0) {
ImGui::End();
return;
}
float gainMainChannel = App->audio->GetGainMainChannel();
float gainMusicChannel = App->audio->GetGainMusicChannel();
float gainSFXChannel = App->audio->GetGainSFXChannel();
ImGui::TextColored(App->editor->titleColor, "Main Volume");
if (ImGui::SliderFloat("##main_volume", &gainMainChannel, 0.f, 1.f)) {
App->audio->SetGainMainChannel(gainMainChannel);
}
ImGui::Separator();
ImGui::NewLine();
ImGui::TextColored(App->editor->titleColor, "Music Volume");
if (ImGui::SliderFloat("##music_volume", &gainMusicChannel, 0.f, 1.f)) {
App->audio->SetGainMusicChannel(gainMusicChannel);
}
ImGui::TextColored(App->editor->titleColor, "SFX Volume");
if (ImGui::SliderFloat("##sfx_volume", &gainSFXChannel, 0.f, 1.f)) {
App->audio->SetGainSFXChannel(gainSFXChannel);
}
}
ImGui::End();
}
| 31.26 | 85 | 0.715291 | TBD-org |
2eb35dba0a0e6768130e3de707821abe5197840a | 2,305 | cpp | C++ | interleaving-string/main.cpp | rickytan/LeetCode | 7df9a47928552babaf5d2abf1d153bd92d44be09 | [
"MIT"
] | 1 | 2015-04-04T18:32:31.000Z | 2015-04-04T18:32:31.000Z | interleaving-string/main.cpp | rickytan/LeetCode | 7df9a47928552babaf5d2abf1d153bd92d44be09 | [
"MIT"
] | null | null | null | interleaving-string/main.cpp | rickytan/LeetCode | 7df9a47928552babaf5d2abf1d153bd92d44be09 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <map>
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if(s3.length() != s1.length() + s2.length())
return false;
vector<vector<bool> > table(s1.length() + 1, vector<bool>(s2.length() + 1, false));
for (int i=0; i<= s1.length(); ++i)
{
for (int j=0; j<=s2.length(); ++j)
{
if (i == 0 && j == 0) {
table[i][j] = true;
}
else if (i == 0) {
table[i][j] = table[i][j-1] && s2[j-1] == s3[i+j-1];
}
else if (j == 0) {
table[i][j] = table[i-1][j] && s1[i-1] == s3[i+j-1];
}
else {
table[i][j] = table[i][j-1] && s2[j-1] == s3[i+j-1] || table[i-1][j] && s1[i-1] == s3[i+j-1];
}
}
}
return table[s1.length()][s2.length()];
}
bool isInter(const char *s1, const char *s2, const char *s3) {
int p1 = 0, p2 = 0;
for (int i=0;s3[i];++i)
{
if (s1[p1] == s3[i] &&
s2[p2] == s3[i]) {
if (isInter(s1+p1+1, s2+p2, s3+i+1)) {
return true;
}
if (isInter(s1+p1, s2+p2+1, s3+i+1)) {
return true;
}
return false;
}
else if (s1[p1] == s3[i]) {
p1++;
}
else if (s2[p2] == s3[i]) {
p2++;
}
else
return false;
}
return (!s1[p1] && !s2[p2]);
}
};
int main()
{
Solution s;
cout << s.isInterleave("bbbbbabbbbabaababaaaabbababbaaabbabbaaabaaaaababbbababbbbbabbbbababbabaabababbbaabababababbbaaababaa", "babaaaabbababbbabbbbaabaabbaabbbbaabaaabaababaaaabaaabbaaabaaaabaabaabbbbbbbbbbbabaaabbababbabbabaab", "babbbabbbaaabbababbbbababaabbabaabaaabbbbabbbaaabbbaaaaabbbbaabbaaabababbaaaaaabababbababaababbababbbababbbbaaaabaabbabbaaaaabbabbaaaabbbaabaaabaababaababbaaabbbbbabbbbaabbabaabbbbabaaabbababbabbabbab");
return 0;
} | 32.464789 | 439 | 0.465944 | rickytan |
2eb515a61c830996042031068e594e344273b81c | 22,273 | cc | C++ | pdb/src/storageManager/headers/PDBStorageManagerFrontendTemplate.cc | SeraphL/plinycompute | 7788bc2b01d83f4ff579c13441d0ba90734b54a2 | [
"Apache-2.0"
] | 3 | 2019-05-04T05:17:30.000Z | 2020-02-21T05:01:59.000Z | pdb/src/storageManager/headers/PDBStorageManagerFrontendTemplate.cc | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 3 | 2020-02-20T19:50:46.000Z | 2020-06-25T14:31:51.000Z | pdb/src/storageManager/headers/PDBStorageManagerFrontendTemplate.cc | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 5 | 2019-02-19T23:17:24.000Z | 2020-08-03T01:08:04.000Z | //
// Created by dimitrije on 2/17/19.
//
#ifndef PDB_PDBSTORAGEMANAGERFRONTENDTEMPLATE_H
#define PDB_PDBSTORAGEMANAGERFRONTENDTEMPLATE_H
#include <PDBStorageManagerFrontend.h>
#include <HeapRequestHandler.h>
#include <StoDispatchData.h>
#include <PDBBufferManagerInterface.h>
#include <PDBBufferManagerFrontEnd.h>
#include <StoStoreOnPageRequest.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <fstream>
#include <HeapRequest.h>
#include <StoGetNextPageRequest.h>
#include <StoGetNextPageResult.h>
#include "CatalogServer.h"
#include <StoGetPageRequest.h>
#include <StoGetPageResult.h>
#include <StoGetSetPagesResult.h>
#include <StoRemovePageSetRequest.h>
#include <StoMaterializePageResult.h>
#include <StoFeedPageRequest.h>
template <class T>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleGetPageRequest(const pdb::Handle<pdb::StoGetPageRequest> &request,
std::shared_ptr<T> &sendUsingMe) {
/// 1. Check if we have a page
// create the set identifier
auto set = make_shared<pdb::PDBSet>(request->databaseName, request->setName);
// find the if this page is valid if not try to find another one...
auto res = getValidPage(set, request->page);
// set the result
bool hasPage = res.first;
uint64_t pageNum = res.second;
/// 2. If we don't have it or it is not in a valid state it send back a NACK
if(!hasPage) {
// make an allocation block
const pdb::UseTemporaryAllocationBlock tempBlock{1024};
// create an allocation block to hold the response
pdb::Handle<pdb::StoGetPageResult> response = pdb::makeObject<pdb::StoGetPageResult>(0, 0, false);
// sends result to requester
string error;
sendUsingMe->sendObject(response, error);
// This is an issue we simply return false only a manager can serve pages
return make_pair(false, error);
}
/// 3. Ok we have it, grab the page and compress it.
// grab the page
auto page = this->getFunctionalityPtr<PDBBufferManagerInterface>()->getPage(set, pageNum);
// grab the vector
auto* pageRecord = (pdb::Record<pdb::Vector<pdb::Handle<pdb::Object>>> *) (page->getBytes());
// grab an anonymous page to store the compressed stuff //TODO this kind of sucks since the max compressed size can be larger than the actual size
auto maxCompressedSize = std::min<size_t>(snappy::MaxCompressedLength(pageRecord->numBytes()), 128 * 1024 * 1024);
auto compressedPage = getFunctionalityPtr<PDBBufferManagerInterface>()->getPage(maxCompressedSize);
// compress the record
size_t compressedSize;
snappy::RawCompress((char*) pageRecord, pageRecord->numBytes(), (char*)compressedPage->getBytes(), &compressedSize);
/// 4. Send the compressed page
// make an allocation block
const pdb::UseTemporaryAllocationBlock tempBlock{1024};
// create an allocation block to hold the response
pdb::Handle<pdb::StoGetPageResult> response = pdb::makeObject<pdb::StoGetPageResult>(compressedSize, pageNum, true);
// sends result to requester
string error;
sendUsingMe->sendObject(response, error);
// now, send the bytes
if (!sendUsingMe->sendBytes(compressedPage->getBytes(), compressedSize, error)) {
this->logger->error(error);
this->logger->error("sending page bytes: not able to send data to client.\n");
// we are done here
return make_pair(false, string(error));
}
// we are done!
return make_pair(true, string(""));
}
template <class Communicator, class Requests>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleDispatchedData(pdb::Handle<pdb::StoDispatchData> request, std::shared_ptr<Communicator> sendUsingMe) {
/// 1. Get the page from the distributed storage
// the error
std::string error;
// grab the buffer manager
auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>());
// figure out how large the compressed payload is
size_t numBytes = sendUsingMe->getSizeOfNextObject();
// grab a page to write this
auto page = bufferManager->getPage(numBytes);
// grab the bytes
auto success = sendUsingMe->receiveBytes(page->getBytes(), error);
// did we fail
if(!success) {
// create an allocation block to hold the response
const UseTemporaryAllocationBlock tempBlock{1024};
Handle<SimpleRequestResult> response = makeObject<SimpleRequestResult>(false, error);
// sends result to requester
sendUsingMe->sendObject(response, error);
return std::make_pair(false, error);
}
// figure out the size so we can increment it
// check the uncompressed size
size_t uncompressedSize = 0;
snappy::GetUncompressedLength((char*) page->getBytes(), numBytes, &uncompressedSize);
/// 2. Figure out the page we want to put this thing onto
uint64_t pageNum;
{
// lock the stuff that keeps track of the last page
unique_lock<std::mutex> lck(pageMutex);
// make the set
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
// get the next page
pageNum = getNextFreePage(set);
// indicate that we are writing to this page
startWritingToPage(set, pageNum);
// increment the set size
incrementSetSize(set, uncompressedSize);
}
/// 3. Initiate the storing on the backend
PDBCommunicatorPtr communicatorToBackend = make_shared<PDBCommunicator>();
if (!communicatorToBackend->connectToLocalServer(logger, getConfiguration()->ipcFile, error)) {
return std::make_pair(false, error);
}
// create an allocation block to hold the response
const UseTemporaryAllocationBlock tempBlock{1024};
Handle<StoStoreOnPageRequest> response = makeObject<StoStoreOnPageRequest>(request->databaseName, request->setName, pageNum, request->compressedSize);
// send the thing to the backend
if (!communicatorToBackend->sendObject(response, error)) {
// make the set
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
// set the indicators and send a NACK to the client since we failed
handleDispatchFailure(set, pageNum, uncompressedSize, sendUsingMe);
// finish
return std::make_pair(false, error);
}
/// 4. Forward the page to the backend
// forward the page
if(!bufferManager->forwardPage(page, communicatorToBackend, error)) {
// we could not forward the page
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
// set the indicators and send a NACK to the client since we failed
handleDispatchFailure(set, pageNum, uncompressedSize, sendUsingMe);
// finish
return std::make_pair(false, error);
}
/// 5. Wait for the backend to finish the stuff
success = Requests::template waitHeapRequest<SimpleRequestResult, bool>(logger, communicatorToBackend, false,
[&](Handle<SimpleRequestResult> result) {
// check the result
if (result != nullptr && result->getRes().first) {
return true;
}
// since we failed just invalidate the set
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
{
// lock the stuff
unique_lock<std::mutex> lck(pageMutex);
// finish writing to the set
endWritingToPage(set, pageNum);
// return the page to the free list
freeSetPage(set, pageNum);
// decrement the size of the set
decrementSetSize(set, uncompressedSize);
}
// log the error
error = "Error response from distributed-storage: " + result->getRes().second;
logger->error("Error response from distributed-storage: " + result->getRes().second);
return false;
});
// finish writing to the set
endWritingToPage(std::make_shared<PDBSet>(request->databaseName, request->setName), pageNum);
/// 6. Send the response that we are done
// create an allocation block to hold the response
Handle<SimpleRequestResult> simpleResponse = makeObject<SimpleRequestResult>(success, error);
// sends result to requester
success = sendUsingMe->sendObject(simpleResponse, error) && success;
// finish
return std::make_pair(success, error);
}
template<class Communicator, class Requests>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleGetSetPages(pdb::Handle<pdb::StoGetSetPagesRequest> request, shared_ptr<Communicator> sendUsingMe) {
// the error
std::string error;
bool success;
// check if the set exists
if(!getFunctionalityPtr<pdb::PDBCatalogClient>()->setExists(request->databaseName, request->setName)) {
// set the error
error = "The set the pages were requested does not exist!";
success = false;
// make an allocation block
const UseTemporaryAllocationBlock tempBlock{1024};
// make a NACK response
pdb::Handle<pdb::StoGetSetPagesResult> result = pdb::makeObject<pdb::StoGetSetPagesResult>();
// sends result to requester
sendUsingMe->sendObject(result, error);
// return the result
return std::make_pair(success, error);
}
// make the set identifier
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
std::vector<uint64_t> pages;
{
// lock the stuff
unique_lock<std::mutex> lck(pageMutex);
// try to find the page
auto it = this->pageStats.find(set);
if(it != this->pageStats.end()) {
// reserve the pages
pages.reserve(it->second.lastPage);
// do we even have this page
uint64_t currPage = 0;
while(currPage <= it->second.lastPage) {
// check if the page is valid
if(pageExists(set, currPage) && !isPageBeingWrittenTo(set, currPage) && !isPageFree(set, currPage)) {
pages.emplace_back(currPage);
}
// if not try to go to the next one
currPage++;
}
}
}
// make an allocation block
const UseTemporaryAllocationBlock tempBlock{pages.size() * sizeof(uint64_t) + 1024};
// make the result
pdb::Handle<pdb::StoGetSetPagesResult> result = pdb::makeObject<pdb::StoGetSetPagesResult>(pages, true);
// sends result to requester
success = sendUsingMe->sendObject(result, error);
// return the result
return std::make_pair(success, error);
}
template<class Communicator, class Requests>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleMaterializeSet(pdb::Handle<pdb::StoMaterializePageSetRequest> request,
shared_ptr<Communicator> sendUsingMe) {
/// TODO this has to be more robust, right now this is just here to do the job!
// success indicators
bool success = true;
std::string error;
/// 1. Check if the set exists
// check if the set exists
if(!getFunctionalityPtr<pdb::PDBCatalogClient>()->setExists(request->databaseName, request->setName)) {
// set the error
error = "The set requested to materialize results does not exist!";
success = true;
}
/// 2. send an ACK or NACK depending on whether the set exists
// make an allocation block
const UseTemporaryAllocationBlock tempBlock{1024};
// create an allocation block to hold the response
Handle<SimpleRequestResult> simpleResponse = makeObject<SimpleRequestResult>(success, error);
// sends result to requester
sendUsingMe->sendObject(simpleResponse, error);
// if we failed end here
if(!success) {
// return the result
return std::make_pair(success, error);
}
/// 3. Send pages over the wire to the backend
// grab the buffer manager
auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>());
// make the set
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
// this is going to count the total size of the pages
uint64_t totalSize = 0;
// start forwarding the pages
bool hasNext = true;
while (hasNext) {
uint64_t pageNum;
{
// lock to do the bookkeeping
unique_lock<std::mutex> lck(pageMutex);
// get the next page
pageNum = getNextFreePage(set);
// indicate that we are writing to this page
startWritingToPage(set, pageNum);
}
// get the page
auto page = bufferManager->getPage(set, pageNum);
// forward the page to the backend
success = bufferManager->forwardPage(page, sendUsingMe, error);
// did we fail?
if(!success) {
// lock to do the bookkeeping
unique_lock<std::mutex> lck(pageMutex);
// finish writing to the set
endWritingToPage(set, pageNum);
// return the page to the free list
freeSetPage(set, pageNum);
// free the lock
lck.unlock();
// do we need to update the set size
if(totalSize != 0) {
// broadcast the set size change so far
this->getFunctionalityPtr<PDBCatalogClient>()->incrementSetSize(set->getDBName(), set->getSetName(), totalSize, error);
}
// finish here since this is not recoverable on the backend
return std::make_pair(success, "Error occurred while forwarding the page to the backend.\n" + error);
}
// the size we want to freeze this thing to
size_t freezeSize = 0;
// wait for the storage finish result
success = RequestFactory::waitHeapRequest<StoMaterializePageResult, bool>(logger, sendUsingMe, false,
[&](Handle<StoMaterializePageResult> result) {
// check the result
if (result != nullptr && result->success) {
// set the freeze size
freezeSize = result->materializeSize;
// set the has next
hasNext = result->hasNext;
// finish
return result->success;
}
// set the error
error = "Backend materializing the page failed!";
// we failed return so
return false;
});
// did we fail?
if(!success) {
// lock to do the bookkeeping
unique_lock<std::mutex> lck(pageMutex);
// finish writing to the set
endWritingToPage(set, pageNum);
// return the page to the free list
freeSetPage(set, pageNum);
// free the lock
lck.unlock();
// do we need to update the set size
if(totalSize != 0) {
// broadcast the set size change so far
this->getFunctionalityPtr<PDBCatalogClient>()->incrementSetSize(set->getDBName(), set->getSetName(), totalSize, error);
}
// finish
return std::make_pair(success, error);
}
// ok we did not freeze the page
page->freezeSize(freezeSize);
// end writing to a page
{
// lock to do the bookkeeping
unique_lock<std::mutex> lck(pageMutex);
// finish writing to the set
endWritingToPage(set, pageNum);
// decrement the size of the set
incrementSetSize(set, freezeSize);
}
// increment the set size
totalSize += freezeSize;
}
/// 4. Update the set size
// broadcast the set size change so far
success = this->getFunctionalityPtr<PDBCatalogClient>()->incrementSetSize(set->getDBName(), set->getSetName(), totalSize, error);
/// 5. Finish this
// we succeeded
return std::make_pair(success, error);
}
template <class Communicator>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleRemovePageSet(pdb::Handle<pdb::StoRemovePageSetRequest> &request, std::shared_ptr<Communicator> &sendUsingMe) {
// the error
std::string error;
/// 1. Connect to the backend
// connect to the backend
std::shared_ptr<Communicator> communicatorToBackend = make_shared<Communicator>();
if (!communicatorToBackend->connectToLocalServer(logger, getConfiguration()->ipcFile, error)) {
return std::make_pair(false, error);
}
/// 2. Forward the request
// sends result to requester
bool success = communicatorToBackend->sendObject(request, error, 1024);
// did we succeed in send the stuff
if(!success) {
return std::make_pair(false, error);
}
/// 4. Wait for response
// wait for the storage finish result
success = RequestFactory::waitHeapRequest<SimpleRequestResult, bool>(logger, communicatorToBackend, false,
[&](Handle<SimpleRequestResult> result) {
// check the result
if (result != nullptr && result->getRes().first) {
// finish
return true;
}
// set the error
error = result->getRes().second;
// we failed return so
return false;
});
/// 5. Send a response
// create an allocation block to hold the response
const UseTemporaryAllocationBlock tempBlock{1024};
// create the response
pdb::Handle<pdb::SimpleRequestResult> simpleResponse = pdb::makeObject<pdb::SimpleRequestResult>(success, error);
// sends result to requester
sendUsingMe->sendObject(simpleResponse, error);
// return
return std::make_pair(success, error);
}
template <class Communicator>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleClearSetRequest(pdb::Handle<pdb::StoClearSetRequest> &request,
std::shared_ptr<Communicator> &sendUsingMe) {
std::string error;
// lock the structures
std::unique_lock<std::mutex> lck{pageMutex};
// make the set
auto set = std::make_shared<PDBSet>(request->databaseName, request->setName);
// remove the stats
pageStats.erase(set);
// make sure we have no pages that we are writing to
auto it = pagesBeingWrittenTo.find(set);
if(it != pagesBeingWrittenTo.end() && !it->second.empty()) {
// set the error
error = "There are currently pages being written to, failed to remove the set.";
// create an allocation block to hold the response
const UseTemporaryAllocationBlock tempBlock{1024};
Handle<SimpleRequestResult> response = makeObject<SimpleRequestResult>(false, error);
// sends result to requester
sendUsingMe->sendObject(response, error);
// return
return std::make_pair(false, error);
}
// remove the pages being written to
pagesBeingWrittenTo.erase(set);
// remove the skipped pages
freeSkippedPages.erase(set);
// get the buffer manger
auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>());
// clear the set from the buffer manager
bufferManager->clearSet(set);
// create an allocation block to hold the response
const UseTemporaryAllocationBlock tempBlock{1024};
Handle<SimpleRequestResult> response = makeObject<SimpleRequestResult>(true, error);
// sends result to requester
sendUsingMe->sendObject(response, error);
// return
return std::make_pair(true, error);
}
template <class Communicator>
std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleStartFeedingPageSetRequest(pdb::Handle<pdb::StoStartFeedingPageSetRequest> &request,
std::shared_ptr<Communicator> &sendUsingMe) {
bool success = true;
std::string error;
/// 1. Connect to the backend
// try to connect to the backend
int32_t retries = 0;
PDBCommunicatorPtr communicatorToBackend = make_shared<PDBCommunicator>();
while (!communicatorToBackend->connectToLocalServer(logger, getConfiguration()->ipcFile, error)) {
// if we are out of retries finish
if(retries >= getConfiguration()->maxRetries) {
success = false;
break;
}
// we used up a retry
retries++;
}
// if we could not connect to the backend we failed
if(!success) {
// return
return std::make_pair(success, error);
}
/// 2. Forward the request to the backend
success = communicatorToBackend->sendObject(request, error, 1024);
// if we succeeded in sending the object, we expect an ack
if(success) {
// create an allocation block to hold the response
const UseTemporaryAllocationBlock localBlock{1024};
// get the next object
auto result = communicatorToBackend->template getNextObject<pdb::SimpleRequestResult>(success, error);
// set the success indicator...
success = result != nullptr && result->res;
}
/// 3. Send a response to the other node about the status
// create an allocation block to hold the response
const UseTemporaryAllocationBlock tempBlock{1024};
// create the response for the other node
pdb::Handle<pdb::SimpleRequestResult> simpleResponse = pdb::makeObject<pdb::SimpleRequestResult>(success, error);
// sends result to requester
success = sendUsingMe->sendObject(simpleResponse, error);
/// 4. If everything went well, start getting the pages from the other node
// get the buffer manager
auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>());
// if everything went well start receiving the pages
while(success) {
/// 4.1 Get the signal that there are more pages
// create an allocation block to hold the response
const UseTemporaryAllocationBlock localBlock{1024};
// get the next object
auto hasPage = sendUsingMe->template getNextObject<pdb::StoFeedPageRequest>(success, error);
// if we failed break
if(!success) {
break;
}
/// 4.2 Forward that signal so that the backend knows that there are more pages
// forward the feed page request
success = communicatorToBackend->sendObject<pdb::StoFeedPageRequest>(hasPage, error, 1024);
// if we failed break
if(!success) {
break;
}
// do we have a page, if we don't finish
if(!hasPage->hasNextPage){
break;
}
/// 4.3 Get the page from the other node
// get the page of the size we need
auto page = bufferManager->getPage(hasPage->pageSize);
// grab the bytes
success = sendUsingMe->receiveBytes(page->getBytes(), error);
// if we failed finish
if(!success) {
break;
}
/// 4.4 Forward the page to the backend
// forward the page to the backend
success = bufferManager->forwardPage(page, communicatorToBackend, error);
}
// return
return std::make_pair(success, error);
}
#endif //PDB_PDBSTORAGEMANAGERFRONTENDTEMPLATE_H
| 30.510959 | 178 | 0.690387 | SeraphL |
e481bbb449f85fb3a4e5d64d1e86a9035bc0c598 | 537 | cpp | C++ | third_party/boost/libs/gil/toolbox/test/is_similar.cpp | Jackarain/tinyrpc | 07060e3466776aa992df8574ded6c1616a1a31af | [
"BSL-1.0"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | third_party/boost/libs/gil/toolbox/test/is_similar.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 1 | 2019-04-04T18:00:00.000Z | 2019-04-04T18:00:00.000Z | third_party/boost/libs/gil/toolbox/test/is_similar.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | //
// Copyright 2013 Christian Henning
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/gil.hpp>
#include <boost/gil/extension/toolbox/metafunctions/is_similar.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost;
using namespace gil;
BOOST_AUTO_TEST_SUITE( toolbox_tests )
BOOST_AUTO_TEST_CASE( is_similar_test )
{
// TODO: fill the test
}
BOOST_AUTO_TEST_SUITE_END()
| 22.375 | 68 | 0.735568 | Jackarain |
e487f3b200f80540bf1d3f7c13fe1cea9a296a27 | 25,748 | cpp | C++ | Libraries/RobsJuceModules/rosic/legacy/HighOrderEqualizer.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Libraries/RobsJuceModules/rosic/legacy/HighOrderEqualizer.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Libraries/RobsJuceModules/rosic/legacy/HighOrderEqualizer.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | #include "HighOrderEqualizer.h"
//----------------------------------------------------------------------------
// construction/destruction:
HighOrderEqualizer::HighOrderEqualizer()
{
// init member variables:
sampleRate = 44100.0;
stereoMode = STEREO_LINKED;
bypassAll = false;
int s, c, k; // indices for eq-stage, channel, and frequency-bin
double freq, gain, q;
int mode, order;
// set up the lowpass- and highpass-filters:
for(c=0; c<numChannels; c++)
{
setLpfOrder(0, c);
setLpfCutoff(20000.0, c);
setHpfOrder(0, c);
setHpfCutoff(20.0, c);
}
// set up the equalizer-chains:
for(s=0; s<numEqStages; s++)
{
gain = 1.0;
q = 1.0;
order = 2;
switch(s)
{
case 0:
{
freq = 125.0;
mode = HighOrderEqualizer::PEAK;
//gain = 12.0;
} break;
case 1:
{
freq = 250.0;
mode = HighOrderEqualizer::PEAK;
} break;
case 2:
{
freq = 1000.0;
mode = HighOrderEqualizer::PEAK;
} break;
case 3:
{
freq = 4000.0;
mode = HighOrderEqualizer::PEAK;
} break;
case 4:
{
freq = 8000.0;
mode = HighOrderEqualizer::HIGH_SHELV;
} break;
} // end of switch(s)
for(c=0; c<numChannels; c++)
{
setEqMode(mode, s, c);
setEqOrder(order, s, c);
setEqFreq(freq, s, c);
setEqGain(gain, s, c);
setEqQ(q, s, c);
}
}
// set up the global volume factors:
vol[0] = 1.0;
vol[1] = 1.0;
// init the arrays for the magnitude response plot:
double fMin = 15.625;
double fMax = 32000.0;
double f; // current frequency;
for(k=0; k<numBins; k++)
{
// calculate current frequency:
f = mapLinearToExponential(k, 0, numBins-1, fMin, fMax);
// calculate some dependent quantities and store them into their arrays:
freqs[k] = f;
floatFrequencies[k] = (float) f;
omegas[k] = 2*PI*f/sampleRate;
cosOmegas[k] = cos(omegas[k]);
cos2Omegas[k] = cos(2*omegas[k]);
// init the individual magnitude-arrays with 0.0 dB:
for(c=0; c<numChannels; c++)
{
hpfResponses[c][k] = 0.0;
lpfResponses[c][k] = 0.0;
floatMagnitudes[c][k] = 0.0f;
for(s=0; s<numEqStages; s++)
eqResponses[s][c][k] = 0.0;
}
}
}
HighOrderEqualizer::~HighOrderEqualizer()
{
}
//----------------------------------------------------------------------------
// parameter settings:
void HighOrderEqualizer::setSampleRate(double newSampleRate)
{
intA c, s, k; // for indexing the eq-stage, channel and bin
AudioModule::setSampleRate(newSampleRate); // our member "sampleRate" is up
// to date now
// tell the embedded IirDesigner-object the new sample-rate:
designer.setSampleRate(sampleRate);
// re-calculate coefficients for all the embedded BiquadCascade-objects:
for(c=0; c<numChannels; c++)
{
updateHpfCoeffs(c);
for(s=0; s<numEqStages; s++)
updateEqCoeffs(s,c);
updateLpfCoeffs(c);
}
// re-calculate the omega-arrays for the magnitude response plot:
double f; // for the current frequency
for(k=0; k<numBins; k++)
{
// get the current frequency from the freq-array:
f = freqs[k];
// calculate some dependent quantities and store them into their arrays:
omegas[k] = 2*PI*f/sampleRate;
cosOmegas[k] = cos(omegas[k]);
cos2Omegas[k] = cos(2*omegas[k]);
}
// update the individual magnitude-arrays:
for(c=0; c<numChannels; c++)
{
updateHpfFreqResponse(c);
for(s=0; s<numEqStages; s++)
updateEqFreqResponse(s,c);
updateLpfFreqResponse(c);
updateOverallFreqResponse(c);
}
// make sure, that the filter-chains use the same set of coefficients in
// stereo-linked mode:
setStereoMode(stereoMode);
}
void HighOrderEqualizer::setStereoMode(int newStereoMode)
{
intA slope, s;
hpf[1].initBiquadCoeffs();
for(s=0; s<numEqStages; s++)
eq[s][1].initBiquadCoeffs();
lpf[1].initBiquadCoeffs();
if( newStereoMode == STEREO_LINKED )
{
// tell the BiquadCascade-objects how many biquad stages are to be used:
slope = hpfOrder[0];
if( isEven(slope) )
hpf[1].setNumStages( slope/2 );
else
hpf[1].setNumStages( (slope+1)/2 );
for(s=0; s<numEqStages; s++)
{
slope = eqOrder[s][0];
if( eqMode[s][0] == LOW_SHELV || eqMode[s][0] == HIGH_SHELV )
// filter order is the same as the slope-value - half as many
// biquad-stages are required (up to a left-over one-pole stage):
{
if( isEven(slope) )
eq[s][1].setNumStages( slope/2 );
else
eq[s][1].setNumStages( (slope+1)/2 );
}
else if(eqMode[s][0] == PEAK || eqMode[s][0] == NOTCH)
// filter order is twice the slope-value - just as many biquad-stages
// are required:
eq[s][1].setNumStages( slope );
else if(eqMode[s][0] == BYPASS)
eq[s][1].setNumStages( 0 );
}
slope = lpfOrder[0];
if( isEven(slope) )
lpf[1].setNumStages( slope/2 );
else
lpf[1].setNumStages( (slope+1)/2 );
// pass the coeffs for the left filters to the BiquadCascade-objects for
// right filters when we are in STEREO_LINKED mode:
hpf[1].setCoeffs(&(b0hp[0][0]),
&(b1hp[0][0]),
&(b2hp[0][0]),
&(a1hp[0][0]),
&(a2hp[0][0]) );
for(s=0; s<numEqStages; s++)
{
eq[s][1].setCoeffs(&(b0eq[s][0][0]),
&(b1eq[s][0][0]),
&(b2eq[s][0][0]),
&(a1eq[s][0][0]),
&(a2eq[s][0][0]) );
}
lpf[1].setCoeffs(&(b0lp[0][0]),
&(b1lp[0][0]),
&(b2lp[0][0]),
&(a1lp[0][0]),
&(a2lp[0][0]) );
}
// in the other cases, the right-channel filters use their own sets of
// coefficients:
else
{
// tell the BiquadCascade-objects how many biquad stages are to be used:
slope = hpfOrder[1];
if( isEven(slope) )
hpf[1].setNumStages( slope/2 );
else
hpf[1].setNumStages( (slope+1)/2 );
for(s=0; s<numEqStages; s++)
{
slope = eqOrder[s][1];
if( eqMode[s][1] == LOW_SHELV || eqMode[s][1] == HIGH_SHELV )
// filter order is the same as the slope-value - half as many
// biquad-stages are required (up to a left-over one-pole stage):
{
if( isEven(slope) )
eq[s][1].setNumStages( slope/2 );
else
eq[s][1].setNumStages( (slope+1)/2 );
}
else if(eqMode[s][1] == PEAK || eqMode[s][1] == NOTCH)
// filter order is twice the slope-value - just as many biquad-stages
// are required:
eq[s][1].setNumStages( slope );
else if(eqMode[s][1] == BYPASS)
eq[s][1].setNumStages( 0 );
}
slope = lpfOrder[1];
if( isEven(slope) )
lpf[1].setNumStages( slope/2 );
else
lpf[1].setNumStages( (slope+1)/2 );
// pass the coeffs for the right filters to the BiquadCascade-objects for
// right filters when we are not in STEREO_LINKED mode:
hpf[1].setCoeffs(&(b0hp[1][0]),
&(b1hp[1][0]),
&(b2hp[1][0]),
&(a1hp[1][0]),
&(a2hp[1][0]) );
for(s=0; s<numEqStages; s++)
{
eq[s][1].setCoeffs(&(b0eq[s][1][0]),
&(b1eq[s][1][0]),
&(b2eq[s][1][0]),
&(a1eq[s][1][0]),
&(a2eq[s][1][0]) );
}
lpf[1].setCoeffs(&(b0lp[1][0]),
&(b1lp[1][0]),
&(b2lp[1][0]),
&(a1lp[1][0]),
&(a2lp[1][0]) );
}
// update the frequency-response curves, if the stereo-mode has been changed:
if( newStereoMode != stereoMode )
{
stereoMode = newStereoMode;
updateOverallFreqResponse(0);
}
}
void HighOrderEqualizer::setLpfOrder(int newLpfOrder, int channel)
{
static intA c;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
else if( newLpfOrder >= 0 && newLpfOrder <= 2*maxBiquadsInFilter )
lpfOrder[c] = newLpfOrder;
updateLpfCoeffs(c);
setStereoMode(stereoMode); // makes sure that the new coeffs are passed to the
// right-channel filters in stereo-linked mode
updateLpfFreqResponse(c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setLpfCutoff(double newLpfCutoff, int channel)
{
static intA c;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
else if( newLpfCutoff >= 20.0 && newLpfCutoff <= 20000.0 )
lpfCutoff[c] = newLpfCutoff;
updateLpfCoeffs(c);
setStereoMode(stereoMode);
updateLpfFreqResponse(c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setHpfOrder(int newHpfOrder, int channel)
{
static intA c;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
else if( newHpfOrder >= 0 && newHpfOrder <= 2*maxBiquadsInFilter )
hpfOrder[c] = newHpfOrder;
updateHpfCoeffs(c);
setStereoMode(stereoMode);
updateHpfFreqResponse(c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setHpfCutoff(double newHpfCutoff, int channel)
{
static intA c;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
else if( newHpfCutoff >= 20.0 && newHpfCutoff <= 20000.0 )
hpfCutoff[c] = newHpfCutoff;
updateHpfCoeffs(c);
setStereoMode(stereoMode);
updateHpfFreqResponse(c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setEqMode(int newMode, int stage, int channel)
{
static intA s, c;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
else if( newMode >= HighOrderEqualizer::BYPASS &&
newMode <= HighOrderEqualizer::HIGH_SHELV )
{
eqMode[s][c] = newMode;
}
updateEqCoeffs(s,c);
setStereoMode(stereoMode);
updateEqFreqResponse(s,c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setEqOrder(int newOrder, int stage, int channel)
{
static intA s, c;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
else if( newOrder >= 0 && newOrder <= maxBiquadsInEq )
eqOrder[s][c] = newOrder;
updateEqCoeffs(s,c);
setStereoMode(stereoMode);
updateEqFreqResponse(s,c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setEqFreq(double newFreq, int stage, int channel)
{
static intA s, c;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
else if( newFreq >= 20.0 && newFreq <= 20000.0 )
eqFreq[s][c] = newFreq;
updateEqCoeffs(s,c);
setStereoMode(stereoMode);
updateEqFreqResponse(s,c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setEqGain(double newGain, int stage, int channel)
{
static intA s, c;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
else
eqGain[s][c] = dB2amp(newGain);
updateEqCoeffs(s,c);
setStereoMode(stereoMode);
updateEqFreqResponse(s,c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setEqQ(double newQ, int stage, int channel)
{
static intA s, c;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
else if( newQ > 0.00001 )
eqQ[s][c] = newQ;
updateEqCoeffs(s,c);
setStereoMode(stereoMode);
updateEqFreqResponse(s,c);
updateOverallFreqResponse(c);
}
void HighOrderEqualizer::setLevel(double newLevel, int channel)
{
if( channel == 0 )
vol[0] = dB2amp(newLevel);
else if ( channel == 1 )
vol[1] = dB2amp(newLevel);
updateOverallFreqResponse(channel);
}
void HighOrderEqualizer::setBypassAll(bool newBypassAll)
{
bypassAll = newBypassAll;
}
//----------------------------------------------------------------------------
// others:
void HighOrderEqualizer::resetHpfCoeffs(int channel)
{
static intA c, b; // indices for thechannel and biquad-stage
if( channel >= 0 && channel < numChannels)
c = channel;
else
return;
for(b=0; b<maxBiquadsInFilter; b++)
{
b0hp[c][b] = 1.0;
b1hp[c][b] = 0.0;
b2hp[c][b] = 0.0;
a1hp[c][b] = 0.0;
a2hp[c][b] = 0.0;
}
}
void HighOrderEqualizer::resetEqCoeffs(int stage, int channel)
{
static intA s, c, b;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
else
{
for(b=0; b<maxBiquadsInEq; b++)
{
b0eq[s][c][b] = 1.0;
b1eq[s][c][b] = 0.0;
b2eq[s][c][b] = 0.0;
a1eq[s][c][b] = 0.0;
a2eq[s][c][b] = 0.0;
}
}
// let the embedded BiquadCascade-object reset it's internal copies of the
// coeffcients, too:
eq[s][c].initBiquadCoeffs();
}
void HighOrderEqualizer::resetLpfCoeffs(int channel)
{
static intA c, b; // indices for thechannel and biquad-stage
if( channel >= 0 && channel < numChannels)
c = channel;
else
return;
for(b=0; b<maxBiquadsInFilter; b++)
{
b0lp[c][b] = 1.0;
b1lp[c][b] = 0.0;
b2lp[c][b] = 0.0;
a1lp[c][b] = 0.0;
a2lp[c][b] = 0.0;
}
}
void HighOrderEqualizer::updateHpfCoeffs(int channel)
{
static doubleA freq;
static intA slope;
static intA c;
c = channel;
// reset the highpass-coefficients to neutral values:
resetHpfCoeffs(c);
// select the appropriate parameter-set:
freq = hpfCutoff[c];
slope = hpfOrder[c];
// tell the BiquadCascade-object which realizes the highpass-filter how many
// biquad stages are to be used:
if( isEven(slope) )
hpf[c].setNumStages( slope/2 );
else
hpf[c].setNumStages( (slope+1)/2 );
// set up the filter-designer:
designer.setMode(IirDesigner::HIGHPASS);
designer.setFreq1(freq);
designer.setSlope(slope);
// let the designer calculate the equalizer-coefficients:
designer.getBiquadCascadeCoeffs(&(b0hp[c][0]),
&(b1hp[c][0]),
&(b2hp[c][0]),
&(a1hp[c][0]),
&(a2hp[c][0]) );
// pass the coefficients to the appropriate BiquadCascade-object:
hpf[c].setCoeffs(&(b0hp[c][0]),
&(b1hp[c][0]),
&(b2hp[c][0]),
&(a1hp[c][0]),
&(a2hp[c][0]) );
}
void HighOrderEqualizer::updateEqCoeffs(int stage, int channel)
{
static doubleA freq, lowFreq, highFreq, gain, q;
static intA mode, slope;
static intA s, c;
s = stage;
c = channel;
// reset the equalizer-coefficients to neutral values:
resetEqCoeffs(s,c);
// select the appropriate parameter-set:
freq = eqFreq[s][c];
gain = eqGain[s][c];
q = eqQ[s][c];
mode = eqMode[s][c];
slope = eqOrder[s][c];
// calculate corner frequency for shelving modes or lower and upper
// corner-frequencies for peaking- and notch-modes:
if( mode == HighOrderEqualizer::BYPASS )
{
// tell the embedded IirDesigner-object the corner frequency:
designer.setFreq1(freq);
}
else if( mode == HighOrderEqualizer::LOW_SHELV ||
mode == HighOrderEqualizer::HIGH_SHELV)
{
// tell the embedded IirDesigner-object the corner frequency:
designer.setFreq1(freq);
}
else if( mode == HighOrderEqualizer::PEAK ||
mode == HighOrderEqualizer::NOTCH)
{
// calculate lower and upper corner-frequencies for peaking and
// notch-filters:
lowFreq = freq * ( sqrt(1.0+1.0/(4.0*q*q)) - 1.0/(2.0*q) );
highFreq = lowFreq + freq/q;
// restrict the range of the corner-frequencies:
if( lowFreq > 0.94*0.5*sampleRate )
lowFreq = 0.94*0.5*sampleRate; // should actually never happen for
// sampleRates >= 44.1 kHz
if( highFreq > 0.95*0.5*sampleRate )
highFreq = 0.95*0.5*sampleRate; // this, however, could easily happen
// tell the embedded IirDesigner-object the corner-frequencies:
designer.setFreq1(lowFreq);
designer.setFreq2(highFreq);
}
// "translate" the mode index of the HighOrderEqualizer-class into the
// corresponding mode index of the IirDesigner-class and set up the mode in
// the embedded IirDesigner-object:
switch( mode )
{
case HighOrderEqualizer::BYPASS:
{
designer.setMode(IirDesigner::BYPASS);
eq[s][c].setNumStages(0);
}
break;
case HighOrderEqualizer::LOW_SHELV:
{
designer.setMode(IirDesigner::LOW_SHELV);
if( isEven(slope) )
eq[s][c].setNumStages( slope/2 );
else
eq[s][c].setNumStages( (slope+1)/2 );
}
break;
case HighOrderEqualizer::PEAK:
{
designer.setMode(IirDesigner::PEAK);
eq[s][c].setNumStages(slope);
}
break;
case HighOrderEqualizer::NOTCH:
{
designer.setMode(IirDesigner::BANDREJECT);
eq[s][c].setNumStages(slope);
}
break;
case HighOrderEqualizer::HIGH_SHELV:
{
designer.setMode(IirDesigner::HIGH_SHELV);
if( isEven(eqOrder[s][c]) )
eq[s][c].setNumStages( slope/2 );
else
eq[s][c].setNumStages( (slope+1)/2 );
}
break;
default:
{
designer.setMode(IirDesigner::BYPASS);
eq[s][c].setNumStages(0);
}
} // end of switch(eqMode[stage][channel])
// set up the order- and gain-parameters in the embedded IirDesigner-object:
designer.setSlope(slope);
designer.setGain(gain);
// let the designer calculate the equalizer-coefficients:
designer.getBiquadCascadeCoeffs(&(b0eq[s][c][0]),
&(b1eq[s][c][0]),
&(b2eq[s][c][0]),
&(a1eq[s][c][0]),
&(a2eq[s][c][0]) );
// pass the coefficients to the appropriate BiquadCascade-object:
eq[s][c].setCoeffs(&(b0eq[s][c][0]),
&(b1eq[s][c][0]),
&(b2eq[s][c][0]),
&(a1eq[s][c][0]),
&(a2eq[s][c][0]) );
}
void HighOrderEqualizer::updateLpfCoeffs(int channel)
{
static doubleA freq;
static intA slope;
static intA c;
c = channel;
// reset the highpass-coefficients to neutral values:
resetLpfCoeffs(c);
// select the appropriate parameter-set:
freq = lpfCutoff[c];
slope = lpfOrder[c];
// tell the BiquadCascade-object which realizes the highpass-filter how many
// biquad stages are to be used:
if( isEven(slope) )
lpf[c].setNumStages( slope/2 );
else
lpf[c].setNumStages( (slope+1)/2 );
// set up the filter-designer:
designer.setMode(IirDesigner::LOWPASS);
designer.setFreq1(freq);
designer.setSlope(slope);
// let the designer calculate the equalizer-coefficients:
designer.getBiquadCascadeCoeffs(&(b0lp[c][0]),
&(b1lp[c][0]),
&(b2lp[c][0]),
&(a1lp[c][0]),
&(a2lp[c][0]) );
// pass the coefficients to the appropriate BiquadCascade-object:
lpf[c].setCoeffs(&(b0lp[c][0]),
&(b1lp[c][0]),
&(b2lp[c][0]),
&(a1lp[c][0]),
&(a2lp[c][0]) );
}
void HighOrderEqualizer::updateHpfFreqResponse(int channel)
{
static intA c, k, b; // indices for channel, bin and biquad-stage
static doubleA num, den, accu, tmp;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
for(k=0; k<numBins; k++)
{
// accumulate the squared magnitude responses of the individual
// biquad-stages:
accu = 1.0;
for(b=0; b<maxBiquadsInFilter; b++)
{
// calculate the numerator of the squared magnitude of biquad-stage b:
num = b0hp[c][b] * b0hp[c][b]
+ b1hp[c][b] * b1hp[c][b]
+ b2hp[c][b] * b2hp[c][b]
+ 2*cosOmegas[k] * ( b0hp[c][b]*b1hp[c][b]
+ b1hp[c][b]*b2hp[c][b])
+ 2*cos2Omegas[k] * b0hp[c][b]*b2hp[c][b];
// calculate the denominator of the squared magnitude of biquad-stage b:
den = 1.0 * 1.0
+ a1hp[c][b] * a1hp[c][b]
+ a2hp[c][b] * a2hp[c][b]
+ 2*cosOmegas[k] * ( 1.0*a1hp[c][b]
+ a1hp[c][b]*a2hp[c][b])
+ 2*cos2Omegas[k] * 1.0*a2hp[c][b];
// multiply the accumulator with the squared magnitude of biquad-stage b:
accu *= (num/den);
} // end of "for(b=0; b<maxBiquadsInEq; b++)"
// take the square root of the accumulated squared magnitude response - this
// is the desired magnitude of the biquad cascade at bin k:
tmp = sqrt(accu);
// convert this value to decibels:
tmp = 20.0 * log10(tmp);
// store the calculated dB-value in bin k of the freq-response of the
// highpass-filter for channel c:
hpfResponses[c][k] = tmp;
}
}
void HighOrderEqualizer::updateEqFreqResponse(int stage, int channel)
{
static intA s, c, k, b; // indices for eq-stage, channel, bin and
// biquad-stage inside the eq-stage
static doubleA num, den, accu, tmp;
s = stage;
c = channel;
// make sure that we don't try to access an invalid adress:
if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) )
return;
for(k=0; k<numBins; k++)
{
// accumulate the squared magnitude responses of the individual
// biquad-stages:
accu = 1.0;
for(b=0; b<maxBiquadsInEq; b++)
{
// calculate the numerator of the squared magnitude of biquad-stage b:
num = b0eq[s][c][b] * b0eq[s][c][b]
+ b1eq[s][c][b] * b1eq[s][c][b]
+ b2eq[s][c][b] * b2eq[s][c][b]
+ 2*cosOmegas[k] * ( b0eq[s][c][b]*b1eq[s][c][b]
+ b1eq[s][c][b]*b2eq[s][c][b])
+ 2*cos2Omegas[k] * b0eq[s][c][b]*b2eq[s][c][b];
// calculate the denominator of the squared magnitude of biquad-stage b:
den = 1.0 * 1.0
+ a1eq[s][c][b] * a1eq[s][c][b]
+ a2eq[s][c][b] * a2eq[s][c][b]
+ 2*cosOmegas[k] * ( 1.0*a1eq[s][c][b]
+ a1eq[s][c][b]*a2eq[s][c][b])
+ 2*cos2Omegas[k] * 1.0*a2eq[s][c][b];
// multiply the accumulator with the squared magnitude of biquad-stage b:
accu *= (num/den);
} // end of "for(b=0; b<maxBiquadsInEq; b++)"
// take the square root of the accumulated squared magnitude response - this
// is the desired magnitude of the biquad cascade at bin k:
tmp = sqrt(accu);
// convert this value to decibels:
tmp = 20.0 * log10(tmp);
// store the calculated dB-value in bin k of the freq-response of eq-stage
// s for channel c:
eqResponses[s][c][k] = tmp;
}
}
void HighOrderEqualizer::updateLpfFreqResponse(int channel)
{
static intA c, k, b; // indices for channel, bin and biquad-stage
static doubleA num, den, accu, tmp;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
for(k=0; k<numBins; k++)
{
// accumulate the squared magnitude responses of the individual
// biquad-stages:
accu = 1.0;
for(b=0; b<maxBiquadsInFilter; b++)
{
// calculate the numerator of the squared magnitude of biquad-stage b:
num = b0lp[c][b] * b0lp[c][b]
+ b1lp[c][b] * b1lp[c][b]
+ b2lp[c][b] * b2lp[c][b]
+ 2*cosOmegas[k] * ( b0lp[c][b]*b1lp[c][b]
+ b1lp[c][b]*b2lp[c][b])
+ 2*cos2Omegas[k] * b0lp[c][b]*b2lp[c][b];
// calculate the denominator of the squared magnitude of biquad-stage b:
den = 1.0 * 1.0
+ a1lp[c][b] * a1lp[c][b]
+ a2lp[c][b] * a2lp[c][b]
+ 2*cosOmegas[k] * ( 1.0*a1lp[c][b]
+ a1lp[c][b]*a2lp[c][b])
+ 2*cos2Omegas[k] * 1.0*a2lp[c][b];
// multiply the accumulator with the squared magnitude of biquad-stage b:
accu *= (num/den);
} // end of "for(b=0; b<maxBiquadsInEq; b++)"
// take the square root of the accumulated squared magnitude response - this
// is the desired magnitude of the biquad cascade at bin k:
tmp = sqrt(accu);
// convert this value to decibels:
tmp = 20.0 * log10(tmp);
// store the calculated dB-value in bin k of the freq-response of the
// highpass-filter for channel c:
lpfResponses[c][k] = tmp;
}
}
void HighOrderEqualizer::updateOverallFreqResponse(int channel)
{
static intA s, c, k;
static doubleA accu;
c = channel;
// make sure that we don't try to access an invalid adress:
if( c<0 || c>(numChannels-1) )
return;
for(k=0; k<numBins; k++)
{
if( stereoMode != MONO_10 )
{
accu = amp2dB(vol[c]);
accu += hpfResponses[c][k];
accu += lpfResponses[c][k];
for(s=0; s<numEqStages; s++)
accu += eqResponses[s][c][k];
// typecast and store:
floatMagnitudes[c][k] = (float) accu;
}
else if( stereoMode == MONO_10 )
// we need to add both channels freq responses in this case
{
accu = amp2dB(vol[0]);
accu += amp2dB(vol[1]);
accu += hpfResponses[0][k];
accu += hpfResponses[1][k];
accu += lpfResponses[0][k];
accu += lpfResponses[1][k];
for(s=0; s<numEqStages; s++)
{
accu += eqResponses[s][0][k];
accu += eqResponses[s][1][k];
}
// typecast and store:
floatMagnitudes[0][k] = (float) accu;
}
} // end of for(k=0; k<numBins; k++)
}
void HighOrderEqualizer::getMagnitudeResponse(int channel, int* arrayLengths,
float** freqArray, float** magArray)
{
// assign the number of bins to the output-slot "arrayLengths":
*arrayLengths = numBins;
// assign the output-slot *freqArray to the single-precision frequency-array:
*freqArray = floatFrequencies;
// assign the output-slot *magArray to the single-precision magnitude-array
// for the requested channel:
*magArray = &(floatMagnitudes[channel][0]);
} | 27.131718 | 82 | 0.596901 | RobinSchmidt |
e490a1deae2b20f9c9a4f2a9cb1cff04bb35e725 | 2,840 | cpp | C++ | lang_sim_main.cpp | crabster15/LangEvolve | 76991783ba6ab24b28a62aefdc3d42fc09299cc5 | [
"MIT"
] | null | null | null | lang_sim_main.cpp | crabster15/LangEvolve | 76991783ba6ab24b28a62aefdc3d42fc09299cc5 | [
"MIT"
] | null | null | null | lang_sim_main.cpp | crabster15/LangEvolve | 76991783ba6ab24b28a62aefdc3d42fc09299cc5 | [
"MIT"
] | null | null | null | #include "Base_word.h"
#include "wordMod.hpp"
#include "xmlhandler.h"
#include <iostream>
#include "Constants.h"
#include <vector>
#include <memory>
std::vector<std::shared_ptr<Word>> RunGeneration(std::vector<std::shared_ptr<Word>> Wordlist, std::string characterSet, std::string vowelSet, MeaningHandle* mhandle){
std::vector<std::shared_ptr<Word>> newwordlist;
std::unique_ptr<WordMod> Modhandleptr(new WordMod(characterSet, vowelSet));
srand (time(NULL));
for(int Words = 0; Words < Wordlist.size() - 1; Words++){
int changed = rand() % 100 + 1;
if(changed <= PERCENT_CHANGE){
std::vector<int> WordMask = Modhandleptr->CreateChangedMask(Wordlist[Words]->get_word());
std::string newWordstr = Modhandleptr->ApplyCharMask(Wordlist[Words]->get_word(), WordMask);
int meaningchanged = rand() % 100 + 1;
if(meaningchanged <= MEANING_CHANGE_DEFAULT){
//set it hard coded to false
mhandle->GetMeaning(false,newWordstr);
}
// create a different way to
std::shared_ptr<Word> newwordptr(new Word(newWordstr, Wordlist[Words]->get_word(), Wordlist[Words]->get_meaning()));
newwordlist.push_back(newwordptr);
}
}
std::vector<std::shared_ptr<Word>> purgedwordlist = Modhandleptr->DeleteRepeats(newwordlist);
std::cout << "size of newword list:" << newwordlist.size() << std::endl;
return purgedwordlist;
}
std::vector<std::shared_ptr<Word>> Run_sim(int generations, std::vector<std::shared_ptr<Word>> originDict, std::string characterSet, std::string vowelSet, MeaningHandle* mhandle){
std::vector<std::shared_ptr<Word>> WordList;
for(int WordIndex = 0; WordIndex < originDict.size() - 1; WordIndex++){
WordList.push_back(originDict[WordIndex]);
}
for(int CurrGen = 0; CurrGen < generations; CurrGen++){
std::vector<std::shared_ptr<Word>> NewWordList = RunGeneration(WordList, characterSet, vowelSet, mhandle);
for(int WordIndex = 0; WordIndex < NewWordList.size() - 1; WordIndex++){
WordList.push_back(NewWordList[WordIndex]);
}
// debugging word list
for(int i = 0; i < WordList.size() - 1; i++){
}
}
return WordList;
}
void log_sim(Xmlhandler * handle, std::vector<std::shared_ptr<Word>> WordList){
// log all of the new words into an xml file
handle->LogWords(WordList);
}
int main(int argc, char *argv[]){
Xmlhandler * handleptr = new Xmlhandler(argv[1]);
// second arg is default dictionary of terms
MeaningHandle * Mhandleptr = new MeaningHandle(argv[2]);
int generations = handleptr->GetGenerations();
std::vector<std::shared_ptr<Word>> originDict = handleptr->GetWords();
std::string characterSet = handleptr->GetCharSet();
std::string vowelSet = handleptr->GetVowSet();
std::vector<std::shared_ptr<Word>> GeneratedWords = Run_sim(generations, originDict, characterSet, vowelSet, Mhandleptr);
log_sim(handleptr, GeneratedWords);
return 0;
}
| 41.764706 | 179 | 0.721127 | crabster15 |
e499a4ee0d6914d7563b9ba5ede631c8412527bf | 881 | cpp | C++ | src/terminal/gui/Rectangle.cpp | KeinR/Etermal | 9bf66f6be6ae8585b763dd902701e72013a5abcc | [
"MIT"
] | null | null | null | src/terminal/gui/Rectangle.cpp | KeinR/Etermal | 9bf66f6be6ae8585b763dd902701e72013a5abcc | [
"MIT"
] | null | null | null | src/terminal/gui/Rectangle.cpp | KeinR/Etermal | 9bf66f6be6ae8585b763dd902701e72013a5abcc | [
"MIT"
] | null | null | null | #include "Rectangle.h"
#include "../Resources.h"
etm::Rectangle::Rectangle(Resources *res): res(res) {
}
void etm::Rectangle::setColor(const Color &color) {
this->color = color;
}
void etm::Rectangle::setX(float x) {
model.x = x;
}
void etm::Rectangle::setY(float y) {
model.y = y;
}
void etm::Rectangle::setWidth(float width) {
model.width = width;
}
void etm::Rectangle::setHeight(float height) {
model.height = height;
}
float etm::Rectangle::getX() {
return model.x;
}
float etm::Rectangle::getY() {
return model.y;
}
float etm::Rectangle::getWidth() {
return model.width;
}
float etm::Rectangle::getHeight() {
return model.height;
}
bool etm::Rectangle::hasPoint(float x, float y) {
return model.hasPoint(x, y);
}
void etm::Rectangle::render() {
model.set(res);
color.set(res->getShader());
res->renderRectangle();
}
| 18.744681 | 53 | 0.649262 | KeinR |
e49b5a592e2cadde1a9f4149115932db038c2c73 | 4,265 | hpp | C++ | include/lol/def/LolLootPlayerLoot.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T11:14:55.000Z | 2020-07-22T11:14:55.000Z | include/lol/def/LolLootPlayerLoot.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | null | null | null | include/lol/def/LolLootPlayerLoot.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 4 | 2018-12-01T22:48:21.000Z | 2020-07-22T11:14:56.000Z | #pragma once
#include "../base_def.hpp"
#include "LolLootItemOwnershipStatus.hpp"
#include "LolLootRedeemableStatus.hpp"
namespace lol {
struct LolLootPlayerLoot {
std::string lootName;
std::string lootId;
std::string refId;
std::string localizedName;
std::string localizedDescription;
std::string itemDesc;
std::string displayCategories;
std::string rarity;
std::string tags;
std::string type;
std::string asset;
std::string tilePath;
std::string splashPath;
std::string shadowPath;
std::string upgradeLootName;
std::string upgradeEssenceName;
std::string disenchantLootName;
LolLootItemOwnershipStatus itemStatus;
LolLootItemOwnershipStatus parentItemStatus;
LolLootRedeemableStatus redeemableStatus;
int32_t count;
int32_t rentalGames;
int32_t storeItemId;
int32_t parentStoreItemId;
int32_t value;
int32_t upgradeEssenceValue;
int32_t disenchantValue;
int64_t expiryTime;
int64_t rentalSeconds;
bool isNew;
bool isRental;
};
inline void to_json(json& j, const LolLootPlayerLoot& v) {
j["lootName"] = v.lootName;
j["lootId"] = v.lootId;
j["refId"] = v.refId;
j["localizedName"] = v.localizedName;
j["localizedDescription"] = v.localizedDescription;
j["itemDesc"] = v.itemDesc;
j["displayCategories"] = v.displayCategories;
j["rarity"] = v.rarity;
j["tags"] = v.tags;
j["type"] = v.type;
j["asset"] = v.asset;
j["tilePath"] = v.tilePath;
j["splashPath"] = v.splashPath;
j["shadowPath"] = v.shadowPath;
j["upgradeLootName"] = v.upgradeLootName;
j["upgradeEssenceName"] = v.upgradeEssenceName;
j["disenchantLootName"] = v.disenchantLootName;
j["itemStatus"] = v.itemStatus;
j["parentItemStatus"] = v.parentItemStatus;
j["redeemableStatus"] = v.redeemableStatus;
j["count"] = v.count;
j["rentalGames"] = v.rentalGames;
j["storeItemId"] = v.storeItemId;
j["parentStoreItemId"] = v.parentStoreItemId;
j["value"] = v.value;
j["upgradeEssenceValue"] = v.upgradeEssenceValue;
j["disenchantValue"] = v.disenchantValue;
j["expiryTime"] = v.expiryTime;
j["rentalSeconds"] = v.rentalSeconds;
j["isNew"] = v.isNew;
j["isRental"] = v.isRental;
}
inline void from_json(const json& j, LolLootPlayerLoot& v) {
v.lootName = j.at("lootName").get<std::string>();
v.lootId = j.at("lootId").get<std::string>();
v.refId = j.at("refId").get<std::string>();
v.localizedName = j.at("localizedName").get<std::string>();
v.localizedDescription = j.at("localizedDescription").get<std::string>();
v.itemDesc = j.at("itemDesc").get<std::string>();
v.displayCategories = j.at("displayCategories").get<std::string>();
v.rarity = j.at("rarity").get<std::string>();
v.tags = j.at("tags").get<std::string>();
v.type = j.at("type").get<std::string>();
v.asset = j.at("asset").get<std::string>();
v.tilePath = j.at("tilePath").get<std::string>();
v.splashPath = j.at("splashPath").get<std::string>();
v.shadowPath = j.at("shadowPath").get<std::string>();
v.upgradeLootName = j.at("upgradeLootName").get<std::string>();
v.upgradeEssenceName = j.at("upgradeEssenceName").get<std::string>();
v.disenchantLootName = j.at("disenchantLootName").get<std::string>();
v.itemStatus = j.at("itemStatus").get<LolLootItemOwnershipStatus>();
v.parentItemStatus = j.at("parentItemStatus").get<LolLootItemOwnershipStatus>();
v.redeemableStatus = j.at("redeemableStatus").get<LolLootRedeemableStatus>();
v.count = j.at("count").get<int32_t>();
v.rentalGames = j.at("rentalGames").get<int32_t>();
v.storeItemId = j.at("storeItemId").get<int32_t>();
v.parentStoreItemId = j.at("parentStoreItemId").get<int32_t>();
v.value = j.at("value").get<int32_t>();
v.upgradeEssenceValue = j.at("upgradeEssenceValue").get<int32_t>();
v.disenchantValue = j.at("disenchantValue").get<int32_t>();
v.expiryTime = j.at("expiryTime").get<int64_t>();
v.rentalSeconds = j.at("rentalSeconds").get<int64_t>();
v.isNew = j.at("isNew").get<bool>();
v.isRental = j.at("isRental").get<bool>();
}
} | 40.619048 | 85 | 0.652052 | Maufeat |
e49e32a2edcd3104e05757da2a954d8d12b00832 | 2,181 | cpp | C++ | Raytracer/src/driver.cpp | rickyguerin/Animated-Ray-Tracer | cc1afe776c904b2280e5552f5c4654391658382a | [
"MIT"
] | null | null | null | Raytracer/src/driver.cpp | rickyguerin/Animated-Ray-Tracer | cc1afe776c904b2280e5552f5c4654391658382a | [
"MIT"
] | null | null | null | Raytracer/src/driver.cpp | rickyguerin/Animated-Ray-Tracer | cc1afe776c904b2280e5552f5c4654391658382a | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
#include "../header/world.h"
#include "../header/camera.h"
#include "../header/WorldProgram/cameraProgram.h"
// Turn i into a string padded with 0s up to length n
std::string padInt(int i, int n) {
int numZeros = n - 1;
int copy = i / 10;
while (copy > 0) {
numZeros--;
copy /= 10;
}
std::string pad = "";
pad.append("0000000000", numZeros);
return pad + std::to_string(i);
}
int main() {
// Create the World
World world(glm::vec3(0.0f, 0.3f, 0.5f));
world.addProgram("world/hextree/ground/bottom/backLeft.triangle");
world.addProgram("world/hextree/ground/bottom/frontLeft.triangle");
world.addProgram("world/hextree/ground/bottom/backRight.triangle");
world.addProgram("world/hextree/ground/bottom/frontRight.triangle");
world.addProgram("world/hextree/ground/bottom/right.triangle");
world.addProgram("world/hextree/ground/bottom/left.triangle");
world.addProgram("world/hextree/ground/top/backLeft.triangle");
world.addProgram("world/hextree/ground/top/frontLeft.triangle");
world.addProgram("world/hextree/ground/top/backRight.triangle");
world.addProgram("world/hextree/ground/top/frontRight.triangle");
world.addProgram("world/hextree/ground/top/right.triangle");
world.addProgram("world/hextree/ground/top/left.triangle");
world.addProgram("world/hextree/ground/walls/front.triangle");
world.addProgram("world/hextree/ground/walls/frontRight.triangle");
world.addProgram("world/hextree/ground/walls/right.triangle");
world.addProgram("world/hextree/br.sphere");
world.addProgram("world/hextree/main.light");
// Read the CameraProgram
CameraProgram camProg("world/hextree/main.camera");
// Animation frame information
const float fps = 60.0;
const float duration = 12.0;
const unsigned frames = fps * duration;
// Animation timer
float time = 3.0;
const float spf = duration / frames;
// Render frames
for (int i = 0; i < frames; i++) {
std::cout << "Rendering frame " << padInt(i, 4) << " / " << padInt(frames - 1, 4) << "\n";
camProg.getCamera(time).render(world, "../images/temp/output_" + padInt(i, 4), 2048, 2048, time);
time += spf;
}
return 0;
} | 30.291667 | 99 | 0.715727 | rickyguerin |
e49f9f60bdb3636f69eff0e4436372a34ed41a15 | 1,424 | cpp | C++ | 36.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 36.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 36.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ull = uint64_t;
using ll = int64_t;
using ld = long double;
class Solution
{
public:
const int num = 9;
const int num_sub = 3;
bool isValidSudoku(vector< vector<char> >& board)
{
bitset<10> record; // Use a bitset to record whether an integer repeats
// Check the validality of each row
for (int i = 0; i != num; ++i)
{
record.reset();
for (int j = 0; j != num; ++j)
{
if (board[i][j] != '.')
{
int elem = board[i][j] - '0';
if (record.test(elem))
return false;
else
record.set(elem);
}
}
}
// Check the validality of each column
for (int j = 0; j != num; ++j)
{
record.reset();
for (int i = 0; i != num; ++i)
{
if (board[i][j] != '.')
{
int elem = board[i][j] - '0';
if (record.test(elem))
return false;
else
record.set(elem);
}
}
}
// Check the validality of each sub grid
for (int i = 0; i != num_sub; ++i)
{
for (int j = 0; j != num_sub; ++j)
{
record.reset();
for (int m = 0; m != num_sub; ++m)
{
for (int n = 0; n != num_sub; ++n)
{
if (board[i * num_sub + m][j * num_sub + n] != '.')
{
int elem = board[i * num_sub + m][j * num_sub + n] - '0';
if (record.test(elem))
return false;
else
record.set(elem);
}
}
}
}
}
return true;
}
};
| 19.506849 | 74 | 0.496489 | Alex-Amber |
e4a0875f9ff2c13cb24aa40b14e0842a8e73b35b | 2,188 | cpp | C++ | graph_data_analytic/src/randLocalGraph.cpp | bxtx999/gm_scripts | de1e7a7d5717caf09f9b81fd627ac95ab01e1924 | [
"MIT"
] | null | null | null | graph_data_analytic/src/randLocalGraph.cpp | bxtx999/gm_scripts | de1e7a7d5717caf09f9b81fd627ac95ab01e1924 | [
"MIT"
] | null | null | null | graph_data_analytic/src/randLocalGraph.cpp | bxtx999/gm_scripts | de1e7a7d5717caf09f9b81fd627ac95ab01e1924 | [
"MIT"
] | null | null | null | #include "parseCommandLine.h"
#include "graphIO.h"
#include "utils.h"
#include "parallel.h"
using namespace benchIO;
// Generates an undirected graph with n vertices with approximately degree
// neighbors per vertex.
// Edges are distributed so they appear to come from
// a dim-dimensional space. In particular an edge (i,j) will have
// probability roughly proportional to (1/|i-j|)^{(d+1)/d}, giving
// separators of size about n^{(d-1)/d}.
template<class intT>
edgeArray<intT> edgeRandomWithDimension(intT dim, intT nonZeros, intT numRows) {
double degree = (double) nonZeros / numRows;
edge<intT> *E = newA(edge<intT>, nonZeros);
parallel_for (intT k = 0; k < nonZeros; k++) {
intT i = k / degree;
intT j;
if (dim == 0) {
uintT h = k;
do {
j = ((h = hashInt(h)) % numRows);
if (j < 0 || j >= numRows) {
cout << h << " " << j << endl;
abort();
}
} while (j == i);
} else {
intT pow = dim + 2;
uintT h = k;
do {
while ((((h = hashInt(h)) % 1000003) < 500001)) pow += dim;
j = (i + ((h = hashInt(h)) % (((long) 1) << pow))) % numRows;
} while (j == i);
}
E[k].u = i;
E[k].v = j;
}
return edgeArray<intT>(E, numRows, numRows, nonZeros);
}
//Generates a graph with n vertices and m edges, possibly with
//duplicates, and then removes duplicate edges and symmetrizes the
//graph.
int main(int argc, char *argv[]) {
commandLine P(argc, argv, "[-s] [-m <numedges>] [-d <dims>] n <outFile>");
std::pair<intT, char *> in = P.sizeAndFileName();
long n = in.first;
char *fname = in.second;
int dim = P.getOptionIntValue("-d", 0);
long m = P.getOptionLongValue("-m", 10 * n);
bool sym = P.getOptionValue("-s");
edgeArray<uintT> EA = edgeRandomWithDimension<uintT>(dim, m, n);
graph<uintT> G = graphFromEdges<uintT>(EA, sym);
EA.del();
writeGraphToFile<uintT>(G, fname);
G.del();
return 0;
}
| 35.290323 | 81 | 0.531536 | bxtx999 |
e4a0adec3a081726617c249772a237b663b5ac4b | 568 | hh | C++ | src/Zynga/Framework/StorableObject/V1/Test/Mock/Broken/ValidButHasConstructorArgs.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 19 | 2018-04-23T09:30:48.000Z | 2022-03-06T21:35:18.000Z | src/Zynga/Framework/StorableObject/V1/Test/Mock/Broken/ValidButHasConstructorArgs.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 22 | 2017-11-27T23:39:25.000Z | 2019-08-09T08:56:57.000Z | src/Zynga/Framework/StorableObject/V1/Test/Mock/Broken/ValidButHasConstructorArgs.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 28 | 2017-11-16T20:53:56.000Z | 2021-01-04T11:13:17.000Z | <?hh // strict
namespace Zynga\Framework\StorableObject\V1\Test\Mock\Broken;
use Zynga\Framework\StorableObject\V1\Interfaces\FieldsInterface;
use Zynga\Framework\StorableObject\V1\Test\Mock\Valid;
class ValidButHasConstructorArgs extends Valid {
public function __construct(string $myPrettyArg) {
parent::__construct();
// --
// kaboooomski! as the storable objects as a whole don't typically have args,
// therefor it will explode when fed to some of the systems that expect to
// allocate storable objects with no args.
// --
}
}
| 25.818182 | 81 | 0.735915 | chintan-j-patel |
e4a4bcfee6d925db8fdb261b96b3d77acaa3cb88 | 771 | hpp | C++ | libraries/chain/include/scorum/chain/database/process_user_activity.hpp | scorum/scorum | 1da00651f2fa14bcf8292da34e1cbee06250ae78 | [
"MIT"
] | 53 | 2017-10-28T22:10:35.000Z | 2022-02-18T02:20:48.000Z | libraries/chain/include/scorum/chain/database/process_user_activity.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 38 | 2017-11-25T09:06:51.000Z | 2018-10-31T09:17:22.000Z | libraries/chain/include/scorum/chain/database/process_user_activity.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 27 | 2018-01-08T19:43:35.000Z | 2022-01-14T10:50:42.000Z | #pragma once
#include <scorum/chain/tasks_base.hpp>
#include <scorum/protocol/transaction.hpp>
#include <scorum/protocol/types.hpp>
namespace scorum {
namespace chain {
namespace database_ns {
using scorum::protocol::signed_transaction;
class user_activity_context
{
public:
explicit user_activity_context(data_service_factory_i& services, const signed_transaction&);
data_service_factory_i& services() const
{
return _services;
}
const signed_transaction& transaction() const
{
return _trx;
}
private:
data_service_factory_i& _services;
const signed_transaction& _trx;
};
class process_user_activity_task : public task<user_activity_context>
{
public:
void on_apply(user_activity_context& ctx);
};
}
}
}
| 17.930233 | 96 | 0.743191 | scorum |
e4aa7bc5caa16ee5b317585d134715ca1860f424 | 1,997 | cpp | C++ | data_structure/DISJOINT.cpp | searchstar2017/acmtool | 03392b8909a3d45f10c2711ca4ad9ba69f64a481 | [
"MIT"
] | null | null | null | data_structure/DISJOINT.cpp | searchstar2017/acmtool | 03392b8909a3d45f10c2711ca4ad9ba69f64a481 | [
"MIT"
] | null | null | null | data_structure/DISJOINT.cpp | searchstar2017/acmtool | 03392b8909a3d45f10c2711ca4ad9ba69f64a481 | [
"MIT"
] | null | null | null | struct DISJOINT {
//static const int maxn = MAXN;
int s[maxn];
void Init(int n){
memset(s, -1, (n+1) * sizeof(s[0]));
}
int FindRoot(int a){
return s[a] < 0 ? a : (s[a] = FindRoot(s[a]));
}
void Union(int a, int b){
UnionRoot(FindRoot(a), FindRoot(b));
}
void UnionRoot(int a, int b){
if(a == b)return;
if(s[a] > s[b])
swap(a,b);
s[a] += s[b];
s[b] = a;
}
};
//simple
struct DISJOINT{
int s[MAXN_DISJOINT];
void Init(int n){
memset(s, -1, (n+1) * sizeof(s[0]));
}
int FindRoot(int a){
int b = a;
while(s[a] >= 0)
a = s[a];
while(s[b] >= 0){
int tmp = s[b];
s[b] = a;
b = tmp;
}
return a;
}
void UnionRoot(int a, int b){
if(a != b)
s[b] = a;
}
void Union(int a, int b){
UnionRoot(FindRoot(a), FindRoot(b));
}
};
//DISJOINT with value
template<typename DistType>
struct DISJOINT_VAL{
int s[MAX_NODE_DISJOINT_VAL];
DistType d[MAX_NODE_DISJOINT_VAL];
void Init(int n){
memset(s, -1, (n+1) * sizeof(s[0]));
memset(d, 0, (n+1) * sizeof(d[0]));
}
DistType RootDist(int& a){
int b = a;
DistType sum_d = 0;
DistType pre_d = 0;
while(s[a] >= 0){
sum_d += d[a];
a = s[a];
}
while(b != a){
int tmp = s[b];
s[b] = a;
DistType tmp_d = d[b];
d[b] = sum_d - pre_d;
pre_d += tmp_d;
b = tmp;
}
return sum_d;
}
//d_ba means the distance from b to a
//Assume that a != b
void UnionRoot(int a, int b, DistType d_ba){
s[b] = a;
d[b] = d_ba;
}
void Union(int a, int b, DistType d_ba){
DistType d_a = RootDist(a);
DistType d_b = RootDist(b);
UnionRoot(a, b, d_a + d_ba - d_b);
}
};
| 21.706522 | 54 | 0.440661 | searchstar2017 |
e4ac58e1fef53241e76504df4f18e0de6b8294fc | 3,650 | cpp | C++ | src/gui_scrollframe_glues.cpp | cschreib/lxgui | b317774d9b4296dda8a70b994950987378a05678 | [
"MIT"
] | 50 | 2015-01-15T10:00:31.000Z | 2022-02-04T20:45:25.000Z | src/gui_scrollframe_glues.cpp | cschreib/lxgui | b317774d9b4296dda8a70b994950987378a05678 | [
"MIT"
] | 88 | 2020-03-15T17:40:04.000Z | 2022-03-15T08:21:44.000Z | src/gui_scrollframe_glues.cpp | cschreib/lxgui | b317774d9b4296dda8a70b994950987378a05678 | [
"MIT"
] | 19 | 2017-03-11T04:32:01.000Z | 2022-01-12T22:47:12.000Z | #include "lxgui/gui_scrollframe.hpp"
#include "lxgui/gui_uiobject_tpl.hpp"
#include "lxgui/gui_frame.hpp"
#include "lxgui/gui_out.hpp"
#include "lxgui/gui_manager.hpp"
#include <sol/state.hpp>
/** A @{Frame} with scrollable content.
* This frame has a special child frame, the "scroll child". The scroll
* child is rendered on a separate render target, which is then rendered
* on the screen. This allows clipping the content of the scroll child
* and only display a portion of it (as if scrolling on a page). The
* displayed portion is controlled by the scroll value, which can be
* changed in both the vertical and horizontal directions.
*
* By default, the mouse wheel movement will not trigger any scrolling;
* this has to be explicitly implemented using the `OnMouseWheel` callback
* and the @{ScrollFrame:set_horizontal_scroll} function.
*
* __Events.__ Hard-coded events available to all @{ScrollFrame}s,
* in addition to those from @{Frame}:
*
* - `OnHorizontalScroll`: Triggered by @{ScrollFrame:set_horizontal_scroll}.
* - `OnScrollRangeChanged`: Triggered whenever the range of the scroll value
* changes. This happens either when the size of the scrollable content
* changes, or when the size of the scroll frame changes.
* - `OnVerticalScroll`: Triggered by @{ScrollFrame:set_vertical_scroll}.
*
* Inherits all methods from: @{UIObject}, @{Frame}.
*
* Child classes: none.
* @classmod ScrollFrame
*/
namespace lxgui {
namespace gui
{
void scroll_frame::register_on_lua(sol::state& mLua)
{
auto mClass = mLua.new_usertype<scroll_frame>("ScrollFrame",
sol::base_classes, sol::bases<uiobject, frame>(),
sol::meta_function::index,
member_function<&scroll_frame::get_lua_member_>(),
sol::meta_function::new_index,
member_function<&scroll_frame::set_lua_member_>());
/** @function get_horizontal_scroll
*/
mClass.set_function("get_horizontal_scroll", member_function<&scroll_frame::get_horizontal_scroll>());
/** @function get_horizontal_scroll_range
*/
mClass.set_function("get_horizontal_scroll_range", member_function<&scroll_frame::get_horizontal_scroll_range>());
/** @function get_scroll_child
*/
mClass.set_function("get_scroll_child", member_function< // select the right overload for Lua
static_cast<const utils::observer_ptr<frame>& (scroll_frame::*)()>(&scroll_frame::get_scroll_child)>());
/** @function get_vertical_scroll
*/
mClass.set_function("get_vertical_scroll", member_function<&scroll_frame::get_vertical_scroll>());
/** @function get_vertical_scroll_range
*/
mClass.set_function("get_vertical_scroll_range", member_function<&scroll_frame::get_vertical_scroll_range>());
/** @function set_horizontal_scroll
*/
mClass.set_function("set_horizontal_scroll", member_function<&scroll_frame::set_horizontal_scroll>());
/** @function set_scroll_child
*/
mClass.set_function("set_scroll_child", [](scroll_frame& mSelf,
std::variant<std::string, frame*> mChild)
{
utils::observer_ptr<frame> pChild = get_object<frame>(mSelf.get_manager(), mChild);
utils::owner_ptr<frame> pScrollChild;
if (pChild)
pScrollChild = utils::static_pointer_cast<frame>(pChild->release_from_parent());
mSelf.set_scroll_child(std::move(pScrollChild));
});
/** @function set_vertical_scroll
*/
mClass.set_function("set_vertical_scroll", member_function<&scroll_frame::set_vertical_scroll>());
}
}
}
| 38.020833 | 119 | 0.704932 | cschreib |
e4b1fe8725e8463861252d0160580b68ddaf3698 | 3,071 | cpp | C++ | src/OISBState.cpp | fire-archive/oisb | 2e1a1a5f58dee986122a1aef8a98e5e610a845a4 | [
"Zlib"
] | null | null | null | src/OISBState.cpp | fire-archive/oisb | 2e1a1a5f58dee986122a1aef8a98e5e610a845a4 | [
"Zlib"
] | null | null | null | src/OISBState.cpp | fire-archive/oisb | 2e1a1a5f58dee986122a1aef8a98e5e610a845a4 | [
"Zlib"
] | null | null | null | /*
The zlib/libpng License
Copyright (c) 2009-2010 Martin Preisler
This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not claim that
you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "OISBState.h"
#include "OISBDevice.h"
#include "OISException.h"
namespace OISB
{
State::State(Device* parent, const String& name):
mParent(parent),
mName(name),
mIsActive(false),
mChanged(false)
{}
State::~State()
{}
BindableType State::getBindableType() const
{
return BT_STATE;
}
String State::getBindableName() const
{
return "State: " + getFullName();
}
bool State::isActive() const
{
return mIsActive;
}
bool State::hasChanged() const
{
return mChanged;
}
String State::getFullName() const
{
return mParent->getName() + "/" + getName();
}
void State::listProperties(PropertyList& list)
{
Bindable::listProperties(list);
list.push_back("StateName");
list.push_back("ParentDeviceName");
}
void State::impl_setProperty(const String& name, const String& value)
{
if (name == "StateName")
{
OIS_EXCEPT(OIS::E_InvalidParam, "'StateName' is a read only, you can't set it!");
}
else if (name == "ParentDeviceName")
{
OIS_EXCEPT(OIS::E_InvalidParam, "'ParentDeviceName' is a read only, you can't set it!");
}
else
{
// nothing matched, delegate up
Bindable::impl_setProperty(name, value);
}
}
String State::impl_getProperty(const String& name) const
{
if (name == "StateName")
{
return getName();
}
else if (name == "ParentDeviceName")
{
// no need to check, every state must have a valid parent
return mParent->getName();
}
else
{
// nothing matched, delegate up
return Bindable::impl_getProperty(name);
}
}
void State::activate()
{
mIsActive = true;
notifyActivated();
}
void State::deactivate()
{
mIsActive = false;
notifyDeactivated();
}
}
| 24.96748 | 101 | 0.592966 | fire-archive |
e4b25daf69025b5c61391c1080fe95f41af759d9 | 7,098 | cpp | C++ | src/Ethereum/ABI/ParamFactory.cpp | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | 2 | 2020-11-16T08:06:30.000Z | 2021-06-18T03:21:44.000Z | src/Ethereum/ABI/ParamFactory.cpp | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | null | null | null | src/Ethereum/ABI/ParamFactory.cpp | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | null | null | null | // Copyright © 2017-2020 Khaos Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "ParamFactory.h"
#include "HexCoding.h"
#include <nlohmann/json.hpp>
#include <boost/algorithm/string/predicate.hpp>
using namespace std;
using namespace boost::algorithm;
using json = nlohmann::json;
namespace TW::Ethereum::ABI {
static int parseBitSize(const std::string& type) {
int size = stoi(type);
if (size < 8 || size > 256 || size % 8 != 0 ||
size == 8 || size == 16 || size == 32 || size == 64 || size == 256) {
throw invalid_argument("invalid bit size");
}
return size;
}
static std::shared_ptr<ParamBase> makeUInt(const std::string& type) {
auto bits = parseBitSize(type);
return make_shared<ParamUIntN>(bits);
}
static std::shared_ptr<ParamBase> makeInt(const std::string& type) {
auto bits = parseBitSize(type);
return make_shared<ParamIntN>(bits);
}
static bool isArrayType(const std::string& type) {
return ends_with(type, "[]") && type.length() >= 3;
}
static std::string getArrayElemType(const std::string& arrayType) {
if (ends_with(arrayType, "[]") && arrayType.length() >= 3) {
return arrayType.substr(0, arrayType.length() - 2);
}
return "";
}
std::shared_ptr<ParamBase> ParamFactory::make(const std::string& type) {
shared_ptr<ParamBase> param;
if (isArrayType(type)) {
auto elemType = getArrayElemType(type);
auto elemParam = make(elemType);
if (!elemParam) {
return param;
}
param = make_shared<ParamArray>(elemParam);
} else if (type == "address") {
param = make_shared<ParamAddress>();
} else if (type == "uint8") {
param = make_shared<ParamUInt8>();
} else if (type == "uint16") {
param = make_shared<ParamUInt16>();
} else if (type == "uint32") {
param = make_shared<ParamUInt32>();
} else if (type == "uint64") {
param = make_shared<ParamUInt64>();
} else if (type == "uint256" || type == "uint") {
param = make_shared<ParamUInt256>();
} else if (type == "int8") {
param = make_shared<ParamInt8>();
} else if (type == "int16") {
param = make_shared<ParamInt16>();
} else if (type == "int32") {
param = make_shared<ParamInt32>();
} else if (type == "int64") {
param = make_shared<ParamInt64>();
} else if (type == "int256" || type == "int") {
param = make_shared<ParamInt256>();
} else if (starts_with(type, "uint")) {
param = makeUInt(type.substr(4, type.size() - 1));
} else if (starts_with(type, "int")) {
param = makeInt(type.substr(3, type.size() - 1));
} else if (type == "bool") {
param = make_shared<ParamBool>();
} else if (type == "bytes") {
param = make_shared<ParamByteArray>();
} else if (starts_with(type, "bytes")) {
auto bits = stoi(type.substr(5, type.size() - 1));
param = make_shared<ParamByteArrayFix>(bits);
} else if (type == "string") {
param = make_shared<ParamString>();
}
return param;
}
std::string joinArrayElems(const std::vector<std::string>& strings) {
auto array = json::array();
for (auto i = 0; i < strings.size(); ++i) {
// parse to prevent quotes on simple values
auto value = json::parse(strings[i], nullptr, false);
if (value.is_discarded()) {
// fallback
value = json(strings[i]);
}
array.push_back(value);
}
return array.dump();
}
std::string ParamFactory::getValue(const std::shared_ptr<ParamBase>& param, const std::string& type) {
std::string result = "";
if (isArrayType(type)) {
auto values = getArrayValue(param, type);
result = joinArrayElems(values);
} else if (type == "address") {
auto value = dynamic_pointer_cast<ParamAddress>(param);
result = hexEncoded(value->getData());
} else if (type == "uint8") {
result = boost::lexical_cast<std::string>((uint)dynamic_pointer_cast<ParamUInt8>(param)->getVal());
} else if (type == "uint16") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt16>(param)->getVal());
} else if (type == "uint32") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt32>(param)->getVal());
} else if (type == "uint64") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt64>(param)->getVal());
} else if (type == "uint256" || type == "uint") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt256>(param)->getVal());
} else if (type == "int8") {
result = boost::lexical_cast<std::string>((int)dynamic_pointer_cast<ParamInt8>(param)->getVal());
} else if (type == "int16") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt16>(param)->getVal());
} else if (type == "int32") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt32>(param)->getVal());
} else if (type == "int64") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt64>(param)->getVal());
} else if (type == "int256" || type == "int") {
result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt256>(param)->getVal());
} else if (starts_with(type, "uint")) {
auto value = dynamic_pointer_cast<ParamUIntN>(param);
result = boost::lexical_cast<std::string>(value->getVal());
} else if (starts_with(type, "int")) {
auto value = dynamic_pointer_cast<ParamIntN>(param);
result = boost::lexical_cast<std::string>(value->getVal());
} else if (type == "bool") {
auto value = dynamic_pointer_cast<ParamBool>(param);
result = value->getVal() ? "true" : "false";
} else if (type == "bytes") {
auto value = dynamic_pointer_cast<ParamByteArray>(param);
result = hexEncoded(value->getVal());
} else if (starts_with(type, "bytes")) {
auto value = dynamic_pointer_cast<ParamByteArrayFix>(param);
result = hexEncoded(value->getVal());
} else if (type == "string") {
auto value = dynamic_pointer_cast<ParamString>(param);
result = value->getVal();
}
return result;
}
std::vector<std::string> ParamFactory::getArrayValue(const std::shared_ptr<ParamBase>& param, const std::string& type) {
if (!isArrayType(type)) {
return std::vector<std::string>();
}
auto array = dynamic_pointer_cast<ParamArray>(param);
if (!array) {
return std::vector<std::string>();
}
auto elemType = getArrayElemType(type);
auto elems = array->getVal();
std::vector<std::string> values(elems.size());
for (auto i = 0; i < elems.size(); ++i) {
values[i] = getValue(elems[i], elemType);
}
return values;
}
} // namespace TW::Ethereum::ABI
| 39.653631 | 120 | 0.615807 | Khaos-Labs |
e4b675eaf8699a46535ae1317fdafc07483d5fb8 | 3,426 | hh | C++ | include/ignition/transport/TopicUtils.hh | amtj/ign-transport | 3b386bf46efd2fc0b847aa7fd3911b1d9d27546c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/ignition/transport/TopicUtils.hh | amtj/ign-transport | 3b386bf46efd2fc0b847aa7fd3911b1d9d27546c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/ignition/transport/TopicUtils.hh | amtj/ign-transport | 3b386bf46efd2fc0b847aa7fd3911b1d9d27546c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2014 Open Source Robotics Foundation
*
* 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.
*
*/
#ifndef __IGN_TRANSPORT_TOPICUTILS_HH_INCLUDED__
#define __IGN_TRANSPORT_TOPICUTILS_HH_INCLUDED__
#include <cstdint>
#include <string>
#include "ignition/transport/Helpers.hh"
namespace ignition
{
namespace transport
{
/// \class TopicUtils TopicUtils.hh ignition/transport/TopicUtils.hh
/// \brief This class provides different utilities related with topics.
class IGNITION_TRANSPORT_VISIBLE TopicUtils
{
/// \brief Determines if a namespace is valid. A namespace's length must
/// not exceed kMaxNameLength.
/// \param[in] _ns Namespace to be checked.
/// \return true if the namespace is valid.
public: static bool IsValidNamespace(const std::string &_ns);
/// \brief Determines if a partition is valid.
/// The same rules to validate a topic name applies to a partition with
/// the addition of the empty string, which is a valid partition (meaning
/// no partition is used). A partition name's length must not exceed
/// kMaxNameLength.
/// \param[in] _partition Partition to be checked.
/// \return true if the partition is valid.
public: static bool IsValidPartition(const std::string &_partition);
/// \brief Determines if a topic name is valid. A topic name is any
/// non-empty alphanumeric string. The symbol '/' is also allowed as part
/// of a topic name. The symbol '@' is not allowed in a topic name
/// because it is used as a partition delimitier. A topic name's length
/// must not exceed kMaxNameLength.
/// Examples of valid topics: abc, /abc, /abc/de, /abc/de/
/// \param[in] _topic Topic name to be checked.
/// \return true if the topic name is valid.
public: static bool IsValidTopic(const std::string &_topic);
/// \brief Get the full topic path given a namespace and a topic name.
/// A fully qualified topic name's length must not exceed kMaxNameLength.
/// \param[in] _partition Partition name.
/// \param[in] _ns Namespace.
/// \param[in] _topic Topic name.
/// \param[out] _name Fully qualified topic name.
/// \return True if the fully qualified name is valid
/// (if partition, namespace and topic are correct).
public: static bool FullyQualifiedName(const std::string &_partition,
const std::string &_ns,
const std::string &_topic,
std::string &_name);
/// \brief The kMaxNameLength specifies the maximum number of characters
/// allowed in a namespace, a partition name, a topic name, and a fully
/// qualified topic name.
public: static const uint16_t kMaxNameLength = 65535;
};
}
}
#endif
| 42.296296 | 79 | 0.665791 | amtj |
e4b93506670e4671f2ce9f66df16fe12be3a11c1 | 4,653 | inl | C++ | lib/NoesisGUI-2.2.0/Include/NsCore/Queue.inl | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 44 | 2019-06-06T21:33:30.000Z | 2022-03-26T06:18:23.000Z | lib/NoesisGUI-2.2.0/Include/NsCore/Queue.inl | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 1 | 2019-09-27T12:04:52.000Z | 2019-09-29T13:30:42.000Z | lib/NoesisGUI-2.2.0/Include/NsCore/Queue.inl | guillaume-haerinck/imac-tower-defense | 365a32642ea0d3ad8b2b7d63347d585c44d9f670 | [
"MIT"
] | 8 | 2019-07-26T16:44:26.000Z | 2020-11-24T17:56:18.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
// NoesisGUI - http://www.noesisengine.com
// Copyright (c) 2013 Noesis Technologies S.L. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace eastl
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// queue
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline queue<T, Container>::queue() :
mContainer()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline queue<T, Container>::queue(const this_type& other) :
mContainer(other.mContainer)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::this_type&
queue<T, Container>::operator=(const this_type& other)
{
mContainer = other.mContainer;
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline void queue<T, Container>::push(const value_type& value)
{
mContainer.push_back(value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline void queue<T, Container>::pop()
{
mContainer.pop_front();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::reference
queue<T, Container>::front()
{
return const_cast<reference>(static_cast<const this_type*>(this)->front());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::const_reference
queue<T, Container>::front() const
{
return mContainer.front();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::reference
queue<T, Container>::back()
{
return const_cast<reference>(static_cast<const this_type*>(this)->back());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::const_reference
queue<T, Container>::back() const
{
return mContainer.back();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline bool queue<T, Container>::empty() const
{
return mContainer.empty();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::size_type
queue<T, Container>::size() const
{
return mContainer.size();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename queue<T, Container>::container_type&
queue<T, Container>::get_container()
{
return mContainer;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NsQueue
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline NsQueue<T, Container>::NsQueue() :
BaseType()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline NsQueue<T, Container>::NsQueue(const ThisType& other) :
BaseType(other)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
template<class T, typename Container>
inline typename NsQueue<T, Container>::ThisType&
NsQueue<T, Container>::operator=(const ThisType& other)
{
return static_cast<ThisType&>(BaseType::operator=(other));
}
| 34.984962 | 100 | 0.381689 | guillaume-haerinck |
e4b941a9020b7231e60ddc242dab3041593dd531 | 6,630 | cpp | C++ | Source/Parsing/ParsingAutomaton_EPDA.cpp | milizhang/Vlpp | 34a1217c1738587d0c723ed3227a79777636faf1 | [
"MS-PL"
] | 2 | 2020-04-16T15:51:41.000Z | 2021-06-05T06:38:20.000Z | Source/Parsing/ParsingAutomaton_EPDA.cpp | milizhang/Vlpp | 34a1217c1738587d0c723ed3227a79777636faf1 | [
"MS-PL"
] | null | null | null | Source/Parsing/ParsingAutomaton_EPDA.cpp | milizhang/Vlpp | 34a1217c1738587d0c723ed3227a79777636faf1 | [
"MS-PL"
] | null | null | null | #include "ParsingAutomaton.h"
#include "../Collections/Operation.h"
namespace vl
{
namespace parsing
{
using namespace collections;
using namespace definitions;
namespace analyzing
{
/***********************************************************************
CreateEpsilonPDAVisitor
***********************************************************************/
class CreateEpsilonPDAVisitor : public Object, public ParsingDefinitionGrammar::IVisitor
{
public:
Ptr<Automaton> automaton;
ParsingDefinitionRuleDefinition* rule;
ParsingDefinitionGrammar* ruleGrammar;
State* startState;
State* endState;
Transition* result;
CreateEpsilonPDAVisitor(Ptr<Automaton> _automaton, ParsingDefinitionRuleDefinition* _rule, ParsingDefinitionGrammar* _ruleGrammar, State* _startState, State* _endState)
:automaton(_automaton)
,rule(_rule)
,ruleGrammar(_ruleGrammar)
,startState(_startState)
,endState(_endState)
,result(0)
{
}
static Transition* Create(ParsingDefinitionGrammar* grammar, Ptr<Automaton> automaton, ParsingDefinitionRuleDefinition* rule, ParsingDefinitionGrammar* ruleGrammar, State* startState, State* endState)
{
CreateEpsilonPDAVisitor visitor(automaton, rule, ruleGrammar, startState, endState);
grammar->Accept(&visitor);
return visitor.result;
}
Transition* Create(ParsingDefinitionGrammar* grammar, State* startState, State* endState)
{
return Create(grammar, automaton, rule, ruleGrammar, startState, endState);
}
void Visit(ParsingDefinitionPrimitiveGrammar* node)override
{
result=automaton->Symbol(startState, endState, automaton->symbolManager->CacheGetSymbol(node));
}
void Visit(ParsingDefinitionTextGrammar* node)override
{
result=automaton->Symbol(startState, endState, automaton->symbolManager->CacheGetSymbol(node));
}
void Visit(ParsingDefinitionSequenceGrammar* node)override
{
State* middleState=automaton->EndState(startState->ownerRule, ruleGrammar, node->first.Obj());
Create(node->first.Obj(), startState, middleState);
Create(node->second.Obj(), middleState, endState);
}
void Visit(ParsingDefinitionAlternativeGrammar* node)override
{
Create(node->first.Obj(), startState, endState);
Create(node->second.Obj(), startState, endState);
}
void Visit(ParsingDefinitionLoopGrammar* node)override
{
State* loopStart=automaton->StartState(startState->ownerRule, ruleGrammar, node->grammar.Obj());
automaton->Epsilon(startState, loopStart);
automaton->Epsilon(loopStart, endState);
Create(node->grammar.Obj(), loopStart, loopStart);
}
void Visit(ParsingDefinitionOptionalGrammar* node)override
{
Create(node->grammar.Obj(), startState, endState);
automaton->Epsilon(startState, endState);
}
void Visit(ParsingDefinitionCreateGrammar* node)override
{
State* middleState=automaton->EndState(startState->ownerRule, ruleGrammar, node->grammar.Obj());
Create(node->grammar.Obj(), startState, middleState);
Transition* transition=automaton->Epsilon(middleState, endState);
Ptr<Action> action=new Action;
action->actionType=Action::Create;
action->actionSource=automaton->symbolManager->CacheGetType(node->type.Obj(), 0);
action->creatorRule=rule;
transition->actions.Add(action);
}
void Visit(ParsingDefinitionAssignGrammar* node)override
{
Transition* transition=Create(node->grammar.Obj(), startState, endState);
Ptr<Action> action=new Action;
action->actionType=Action::Assign;
action->actionSource=automaton->symbolManager->CacheGetSymbol(node);
action->creatorRule=rule;
transition->actions.Add(action);
}
void Visit(ParsingDefinitionUseGrammar* node)override
{
Transition* transition=Create(node->grammar.Obj(), startState, endState);
Ptr<Action> action=new Action;
action->actionType=Action::Using;
action->creatorRule=rule;
transition->actions.Add(action);
}
void Visit(ParsingDefinitionSetterGrammar* node)override
{
State* middleState=automaton->EndState(startState->ownerRule, ruleGrammar, node->grammar.Obj());
Create(node->grammar.Obj(), startState, middleState);
Transition* transition=automaton->Epsilon(middleState, endState);
Ptr<Action> action=new Action;
action->actionType=Action::Setter;
action->actionSource=automaton->symbolManager->CacheGetSymbol(node);
action->actionTarget=action->actionSource->GetDescriptorSymbol()->GetSubSymbolByName(node->value);
action->creatorRule=rule;
transition->actions.Add(action);
}
};
/***********************************************************************
CreateRuleEpsilonPDA
***********************************************************************/
void CreateRuleEpsilonPDA(Ptr<Automaton> automaton, Ptr<definitions::ParsingDefinitionRuleDefinition> rule, ParsingSymbolManager* manager)
{
Ptr<RuleInfo> ruleInfo=new RuleInfo;
automaton->ruleInfos.Add(rule.Obj(), ruleInfo);
ruleInfo->rootRuleStartState=automaton->RootRuleStartState(rule.Obj());
ruleInfo->rootRuleEndState=automaton->RootRuleEndState(rule.Obj());
ruleInfo->startState=automaton->RuleStartState(rule.Obj());
automaton->TokenBegin(ruleInfo->rootRuleStartState, ruleInfo->startState);
FOREACH(Ptr<ParsingDefinitionGrammar>, grammar, rule->grammars)
{
State* grammarStartState=automaton->StartState(rule.Obj(), grammar.Obj(), grammar.Obj());
State* grammarEndState=automaton->EndState(rule.Obj(), grammar.Obj(), grammar.Obj());
grammarEndState->stateName+=L".End";
grammarEndState->endState=true;
automaton->Epsilon(ruleInfo->startState, grammarStartState);
automaton->TokenFinish(grammarEndState, ruleInfo->rootRuleEndState);
ruleInfo->endStates.Add(grammarEndState);
CreateEpsilonPDAVisitor::Create(grammar.Obj(), automaton, rule.Obj(), grammar.Obj(), grammarStartState, grammarEndState);
}
}
/***********************************************************************
CreateEpsilonPDA
***********************************************************************/
Ptr<Automaton> CreateEpsilonPDA(Ptr<definitions::ParsingDefinition> definition, ParsingSymbolManager* manager)
{
Ptr<Automaton> automaton=new Automaton(manager);
FOREACH(Ptr<ParsingDefinitionRuleDefinition>, rule, definition->rules)
{
CreateRuleEpsilonPDA(automaton, rule, manager);
}
return automaton;
}
}
}
} | 37.247191 | 204 | 0.679638 | milizhang |
e4baccba4b6fc73c24c6a806d6f405465c6e3878 | 33,016 | cxx | C++ | drs4monitor/src/MonitorFrame.cxx | CMSROMA/DRS4_DAQ | 8ff60a58a1a254d56b2afedaf788ecf5afc67afc | [
"MIT"
] | null | null | null | drs4monitor/src/MonitorFrame.cxx | CMSROMA/DRS4_DAQ | 8ff60a58a1a254d56b2afedaf788ecf5afc67afc | [
"MIT"
] | null | null | null | drs4monitor/src/MonitorFrame.cxx | CMSROMA/DRS4_DAQ | 8ff60a58a1a254d56b2afedaf788ecf5afc67afc | [
"MIT"
] | null | null | null | /*
* MonitorFrame.cxx
*
* Created on: Apr 16, 2017
* Author: S. Lukic
*/
#include "TApplication.h"
#include <TGClient.h>
#include "TGButton.h"
#include "TGTextView.h"
#include "TGText.h"
#include "TGTextEntry.h"
#include "TGTextBuffer.h"
#include "TGComboBox.h"
#include "TGLabel.h"
#include "TGProgressBar.h"
#include "TCanvas.h"
#include "TRootCanvas.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TTimeStamp.h"
#include "TFile.h"
#include "TString.h"
#include "TLegend.h"
#include "TLegendEntry.h"
#include "MonitorFrame.h"
#include "Riostream.h"
#include "TMath.h"
#include "DAQ-config.h"
#include "DRS4_fifo.h"
#include "DRS4_writer.h"
#include "DRS4_reader.h"
#include "observables.h"
using namespace DRS4_data;
MonitorFrame::MonitorFrame(const TGWindow *p, config * const opt, DRS * const _drs) :
TGMainFrame(p, 250, 350),
// limits(opt->histolo, opt->histohi),
options(opt),
// fCanvas01(new TCanvas("DRS4Canvas01", "DRS4 Monitor 01", opt->_w, opt->_h)),
// frCanvas01(new TRootCanvas(fCanvas01, "DRS4 Monitor 01", 0, 200, opt->_w, opt->_h)),
// fCanvas02(new TCanvas("DRS4Canvas02", "DRS4 Monitor 02", opt->_w, opt->_h)),
// frCanvas02(new TRootCanvas(fCanvas02, "DRS4 Monitor 02", 0, 200, opt->_w, opt->_h)),
// fCanvas2D(new TCanvas("DRS4Canvas2D", "DRS4 Monitor 2D", opt->_w*2/3, opt->_h)),
// frCanvas2D(new TRootCanvas(fCanvas2D, "DRS4 Monitor 2D", 0, 200, opt->_w*2/3, opt->_h)),
// fCanvasOsc(new TCanvas("DRS4CanvasOsc", "DRS4 oscillogram", opt->_w/3, opt->_h/2)),
// frCanvasOsc(new TRootCanvas(fCanvasOsc, "DRS4 oscillogram", 0, 200, opt->_w/3, opt->_h/2)),
// tRed(opt->_tRed), tRed2D(opt->_tRed2D),
baseLineWidth(opt->baseLineWidth),
basename("default"), filename("default"), timestamped(false),
// eTot12(NULL), ePrompt12(NULL), time12(NULL), time34(NULL),
timeLastSave(0), lastSpill(0), confStatus(-1), rate(NULL),
drs(_drs), fifo(new DRS4_fifo), writer(NULL),
rawWave(NULL), event(NULL),
headers(NULL), nEvtMax(opt->nEvtMax), iEvtSerial(0), iEvtProcessed(0),
spillSize(10000),interSpillTime(0),
file(NULL),
#ifdef ROOT_OUTPUT
outTree(NULL), h4daqEvent(NULL),
#endif
f_stop(false), f_stopWhenEmpty(false), f_running(false)
// timePoints(NULL), amplitudes(NULL)
// itRed(0), itRed2D(0)
{
// Observables obs;
// for(int iobs=0; iobs<nObservables; iobs++) {
// kObservables kobs = static_cast<kObservables>(iobs);
// histo[0][iobs] = new TH1F(Form("h1%d", iobs), Form("%s - S1; %s_{1} (%s)", obs.Title(kobs), obs.Title(kobs), obs.Unit(kobs)), opt->histoNbins[iobs], opt->histolo[iobs], opt->histohi[iobs]);
// histo[1][iobs] = new TH1F(Form("h2%d", iobs), Form("%s - S2; %s_{2} (%s)", obs.Title(kobs), obs.Title(kobs), obs.Unit(kobs)), opt->histoNbins[iobs], opt->histolo[iobs], opt->histohi[iobs]);
// }
// eTot12 = new TH2F("eTot12", Form("eTot2 vs. eTot1; %s_{1} (%s); %s_{2} (%s)", obs.Title(eTot), obs.Unit(eTot), obs.Title(eTot), obs.Unit(eTot)),
// opt->histoNbins[eTot]/opt->_xRed, opt->histolo[eTot], opt->histohi[eTot],
// opt->histoNbins[eTot]/opt->_xRed, opt->histolo[eTot], opt->histohi[eTot]);
// ePrompt12 = new TH2F("ePrompt12", Form("ePrompt2 vs. ePrompt1; %s_{1} (%s); %s_{2} (%s)", obs.Title(ePrompt), obs.Unit(ePrompt), obs.Title(ePrompt), obs.Unit(ePrompt)),
// opt->histoNbins[ePrompt]/opt->_xRed, opt->histolo[ePrompt], opt->histohi[ePrompt],
// opt->histoNbins[ePrompt]/opt->_xRed, opt->histolo[ePrompt], opt->histohi[ePrompt]);
// time12 = new TH2F("time12", Form("t_{2} vs. t_{1}; %s_{1} (%s); %s_{2} (%s)", obs.Title(arrivalTime), obs.Unit(arrivalTime), obs.Title(arrivalTime), obs.Unit(arrivalTime)),
// opt->histoNbins[arrivalTime]/opt->_xRed, opt->histolo[arrivalTime], opt->histohi[arrivalTime],
// opt->histoNbins[arrivalTime]/opt->_xRed, opt->histolo[arrivalTime], opt->histohi[arrivalTime]);
// time34 = new TH2F("time34", "t_{4} vs. t_{3}; t_{3} (ns); t_{4} (ns)", 100, 0., 100., 100, 0., 100.);
// if( gApplication->Argc() > 1 ) basename = gApplication->Argv()[1];
// std::cout << "basename = " << basename << "\n";
// Placement of histograms
// unsigned ny = int(sqrt(float(nObservables)));
// unsigned nx = int(ceil(nObservables / ny));
// fCanvas01->Divide(nx, ny, .002, .002);
// fCanvas02->Divide(nx, ny, .002, .002);
// for( unsigned ih=0; ih<nObservables; ih++) {
// fCanvas01->cd(ih+1); histo[0][ih]->Draw();
// fCanvas02->cd(ih+1); histo[1][ih]->Draw();
// }
// fCanvas2D->Divide(2, 2, .002, .002);
// fCanvas2D->cd(1); eTot12->Draw("colz");
// fCanvas2D->cd(2); ePrompt12->Draw("colz");
// fCanvas2D->cd(3); time12->Draw("colz");
// fCanvas2D->cd(4); time34->Draw("colz");
// eTot12->SetStats(0);
// ePrompt12->SetStats(0);
// time12->SetStats(0);
// time34->SetStats(0);
// fCanvasOsc->cd();
// fCanvasOsc->GetListOfPrimitives()->SetOwner();
// fCanvasOsc->SetTickx();
// fCanvasOsc->SetTicky();
// TH1F *oscFrame = new TH1F("OscFrame", "Oscillograms; t (ns); A (mV)", 10, 0., 200.);
// oscFrame->SetBit(kCanDelete, false);
// oscFrame->SetMinimum(-550);
// oscFrame->SetMaximum( 50);
// oscFrame->SetStats(false);
// oscFrame->Draw();
// oscFrame=NULL;
// TLegend * oscLeg = new TLegend(.68, .45, .88, .6);
// oscLeg->SetBorderSize(0);
// oscLeg->SetFillStyle(4001);
// oscLeg->SetTextFont(42);
// oscLeg->SetTextSize(.05);
// TLegendEntry *leS1 = oscLeg->AddEntry("S1", " S1", "l");
// leS1->SetLineColor(kBlue);
// leS1->SetLineWidth(2);
// TLegendEntry *leS2 = oscLeg->AddEntry("S2", " S2", "l");
// leS2->SetLineColor(kRed);
// leS2->SetLineWidth(2);
// oscLeg->Draw();
TGFontPool *pool = gClient->GetFontPool();
// family , size (minus value - in pixels, positive value - in points), weight, slant
// kFontWeightNormal, kFontSlantRoman are defined in TGFont.h
TGFont *font = pool->GetFont("helvetica", 14, kFontWeightBold, kFontSlantOblique);
// TGFont *font = pool->GetFont("-adobe-helvetica-bold-r-normal-*-15-*-*-*-*-*-iso8859-1");
// font->Print();
FontStruct_t ft = font->GetFontStruct();
TGHorizontalFrame *hframeI = new TGHorizontalFrame(this,250,60);
TGLabel *nEvtMaxL = new TGLabel(hframeI, "Nevt: ");
nEvtMaxL->SetTextFont(ft);
hframeI->AddFrame(nEvtMaxL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
nEvtMaxT = new TGTextEntry(hframeI, new TGTextBuffer(4));
nEvtMaxT->SetText(Form("%d",nEvtMax));
hframeI->AddFrame(nEvtMaxT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
TGLabel *confL = new TGLabel(hframeI, "Conf: ");
confL->SetTextFont(ft);
hframeI->AddFrame(confL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
// confT = new TGTextEntry(hframeI, new TGTextBuffer(10));
// confT->SetText(basename);
// confT->SetEnabled(true);
confT = new TGComboBox(hframeI);
confT->Resize(80,22);
confT->AddEntry("PED",0);
confT->AddEntry("LED",1);
confT->AddEntry("SOURCE",2);
confT->Select(0);
hframeI->AddFrame(confT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
TGLabel *runIdL = new TGLabel(hframeI, "RunId: ");
runIdL->SetTextFont(ft);
hframeI->AddFrame(runIdL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
runIdT = new TGTextEntry(hframeI, new TGTextBuffer(10));
runIdT->SetText("test");
hframeI->AddFrame(runIdT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
AddFrame(hframeI, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2));
TGHorizontalFrame *hframeI_1 = new TGHorizontalFrame(this,250,60);
TGLabel *spillSizeL = new TGLabel(hframeI_1, "SpillSize: ");
spillSizeL->SetTextFont(ft);
hframeI_1->AddFrame(spillSizeL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
spillSizeT = new TGTextEntry(hframeI_1, new TGTextBuffer(4));
spillSizeT->SetText(Form("%d",spillSize));
hframeI_1->AddFrame(spillSizeT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
TGLabel *interSpillTimeL = new TGLabel(hframeI_1, "InterSpill Time (s): ");
interSpillTimeL->SetTextFont(ft);
hframeI_1->AddFrame(interSpillTimeL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
interSpillTimeT = new TGTextEntry(hframeI_1, new TGTextBuffer(4));
interSpillTimeT->SetText(Form("%d",interSpillTime));
hframeI_1->AddFrame(interSpillTimeT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
ledScan = new TGCheckButton(hframeI_1, "LED SCAN", 4);
ledScan->SetState(kButtonUp);
hframeI_1->AddFrame(ledScan, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
AddFrame(hframeI_1, new TGLayoutHints(kLHintsLeft | kLHintsTop | kLHintsExpandY,2,2,2,2));
TGHorizontalFrame *hframeO = new TGHorizontalFrame(this,250,60);
TGLabel *outFileL = new TGLabel(hframeO, "OutFile: ");
outFileL->SetTextFont(ft);
hframeO->AddFrame(outFileL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
outFileT = new TGTextEntry(hframeO, new TGTextBuffer(40));
outFileT->SetText("");
outFileT->SetEnabled(false);
hframeO->AddFrame(outFileT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
AddFrame(hframeO, new TGLayoutHints(kLHintsLeft | kLHintsTop | kLHintsExpandY,2,2,2,2));
// Create a horizontal frame widget with buttons
TGHorizontalFrame *hframe = new TGHorizontalFrame(this,250,60);
TGTextButton *start = new TGTextButton(hframe,"&Start");
start->Connect("Clicked()","MonitorFrame", this, "Start()");
start->SetFont(ft);
hframe->AddFrame(start, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
TGTextButton *stop = new TGTextButton(hframe,"&Stop");
stop->Connect("Clicked()","MonitorFrame",this,"Stop()");
stop->SetFont(ft);
hframe->AddFrame(stop, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
TGTextButton *hardstop = new TGTextButton(hframe,"&Stop!");
hardstop->Connect("Clicked()","MonitorFrame",this,"HardStop()");
hardstop->SetFont(ft);
hframe->AddFrame(hardstop, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
/* TGTextButton *save = new TGTextButton(hframe,"&Save");
save->Connect("Clicked()","MonitorFrame",this,"Save()");
save->SetFont(ft);
hframe->AddFrame(save, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
TGTextButton *exportText = new TGTextButton(hframe,"&Export Text");
exportText->Connect("Clicked()","MonitorFrame",this,"ExportText()");
exportText->SetFont(ft);
hframe->AddFrame(exportText, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
*/
TGTextButton *exit = new TGTextButton(hframe,"&Exit");
exit->Connect("Clicked()", "MonitorFrame",this,"Exit()");
exit->SetFont(ft);
// exit->Connect("Clicked()", "TApplication", gApplication, "Terminate(0)");
hframe->AddFrame(exit, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
AddFrame(hframe, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2));
// Create a horizontal frame widget with text displays
TGHorizontalFrame *hframeT = new TGHorizontalFrame(this,250,60);
TGLabel *nEvtAcqL = new TGLabel(hframeT, "N acq.: ");
nEvtAcqL->SetTextFont(ft);
hframeT->AddFrame(nEvtAcqL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
nEvtAcqT = new TGLabel(hframeT, Form("%-15i", 0));
nEvtAcqT->SetTextFont(ft);
hframeT->AddFrame(nEvtAcqT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
TGLabel *nEvtProL = new TGLabel(hframeT, "N proc.: ");
nEvtProL->SetTextFont(ft);
hframeT->AddFrame(nEvtProL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
nEvtProT = new TGLabel(hframeT, Form("%-15i", 0));
nEvtProT->SetTextFont(ft);
hframeT->AddFrame(nEvtProT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
TGLabel *rateL = new TGLabel(hframeT, "Rate: ");
rateL->SetTextFont(ft);
hframeT->AddFrame(rateL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
rateT = new TGLabel(hframeT, "0.000 evt/s");
rateT->SetTextFont(ft);
hframeT->AddFrame(rateT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
AddFrame(hframeT, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2));
// Create a horizontal frame widget with displays of board status
TGHorizontalFrame *hframeB = new TGHorizontalFrame(this,250,60);
TGLabel *temperatureL = new TGLabel(hframeB, "T = ");
temperatureL->SetTextFont(ft);
hframeB->AddFrame(temperatureL, new TGLayoutHints(kLHintsCenterX,5,1,3,4));
temperatureT = new TGLabel(
hframeB, Form("%.1f\xB0", drs->GetBoard(0)->GetTemperature()));
temperatureT->SetTextFont(ft);
hframeB->AddFrame(temperatureT, new TGLayoutHints(kLHintsCenterX,1,5,3,4));
TGTextButton *refresh = new TGTextButton(hframeB,"&Refresh");
refresh->Connect("Clicked()","MonitorFrame",this,"RefreshT()");
refresh->SetFont(ft);
hframeB->AddFrame(refresh, new TGLayoutHints(kLHintsCenterX,5,5,3,4));
AddFrame(hframeB, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2));
TGHorizontalFrame *hframeP = new TGHorizontalFrame(this,250,60);
fHProg2 = new TGHProgressBar(hframeP, TGProgressBar::kFancy, 100);
fHProg2->SetBarColor("lightblue");
fHProg2->ShowPosition(kTRUE, kFALSE, "%.0f events");
fHProg2->SetRange(0,nEvtMax);
fHProg2->Reset();
hframeP->AddFrame(fHProg2, new TGLayoutHints(kLHintsTop | kLHintsCenterX | kLHintsExpandX, 1,1,1,1));
AddFrame(hframeP, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandX,2,2,2,2));
std::cout << "Added labels.\n";
// Set a name to the main frame
SetWindowName("DRS4 DAQ Control");
// Map all subwindows of main frame
MapSubwindows();
// Initialize the layout algorithm
Resize(GetDefaultSize());
// Map main frame
MapWindow();
std::cout << "Constructed main window.\n";
#ifdef ROOT_OUTPUT
outTree = new TTree ("H4tree", "H4 testbeam tree") ;
h4daqEvent = new H4DAQ::Event(outTree) ;
#endif
}
MonitorFrame::~MonitorFrame() {
std::cout << "Cleanup main frame.\n";
// for(int iobs=0; iobs<nObservables; iobs++) {
// delete histo[0][iobs];
// histo[0][iobs] = NULL;
// delete histo[1][iobs];
// histo[1][iobs] = NULL;
// }
// delete eTot12; eTot12 = NULL;
// delete ePrompt12; ePrompt12 = NULL;
// delete time12; time12 = NULL;
// delete time34; time34 = NULL;
// if (fCanvas01) delete fCanvas01; fCanvas01 = NULL;
// if (frCanvas01) delete frCanvas01;
// if (fCanvas02) delete fCanvas02;
// if (frCanvas02) delete frCanvas02;
// if (fCanvas2D) delete fCanvas2D;
// if (frCanvas2D) delete frCanvas2D;
// if (fCanvasOsc) delete fCanvasOsc;
// if (frCanvasOsc) delete frCanvasOsc;
if (writer) { delete writer; writer = NULL; }
if (fifo) { delete fifo; fifo = NULL; }
if (drs) {
// Make sure board(s) are idle before exiting
for (int iboard = 0; iboard<drs->GetNumberOfBoards(); iboard++) {
drs->GetBoard(iboard)->Reinit();
}
delete drs; drs = NULL;
}
if (headers) { delete headers; headers = NULL; }
if (rawWave) { delete rawWave; rawWave = NULL; }
if (event) { delete event; event = NULL; }
}
void MonitorFrame::Exit() {
HardStop();
gApplication->SetReturnFromRun(true);
gApplication->Terminate(0);
}
void MonitorFrame::Start() {
if (f_running) { return; }
bool leds=ledScan->GetState()==kButtonDown;
std::cout << "Starting Monitor frame.\n";
if (leds)
std::cout << "Performing LED Scan\n";
nEvtMaxT->SetEnabled(false);
spillSizeT->SetEnabled(false);
interSpillTimeT->SetEnabled(false);
runIdT->SetEnabled(false);
confT->SetEnabled(false);
ledScan->SetEnabled(false);
lastSpill=0;
if(!drs) {
std::cout << "MonitorFrame::Start() - ERROR: DRS object empty." << std::endl;
return;
}
if(drs->GetNumberOfBoards() < 1) {
std::cout << "MonitorFrame::Start() - ERROR: No DRS boards present." << std::endl;
return;
}
ParseConfig();
ConfigDRS();
if(writer) {
if (writer->isRunning() || writer->isJoinable()) {
std::cout << "WARNING: Attempt to start while writer is running.!" << std::endl;
return;
}
delete writer;
}
fifo->Discard();
#ifdef LED_SCAN
writer = new DRS4_writer(drs, fifo,leds);
#else
writer = new DRS4_writer(drs, fifo);
#endif
if(options->triggerSource == 0) {
writer->setAutoTrigger();
}
temperatureT->SetText(Form("%.1f\xB0", writer->Temperature()));
/*** Clear histograms ***/
// for(int iobs=0; iobs<nObservables; iobs++) {
// histo[0][iobs]->Reset();
// histo[1][iobs]->Reset();
// }
// eTot12->Reset();
// ePrompt12->Reset();
// time12->Reset();
// time34->Reset();
fHProg2->Reset();
timer.Start();
timeLastSave = 0;
iEvtProcessed=0;
headers = DRS4_data::DRSHeaders::MakeDRSHeaders(drs);
if (StartNewFile() != 0) {
writer->stop();
delete writer;
writer = NULL;
return;
}
rate = new MonitorFrame::RateEstimator();
rate->Push(0, 1.e-9); // One false time value to avoid division by zero
DoDraw(true);
/*** Start writer ***/
nEvtMax=TString(nEvtMaxT->GetText()).Atoi();
spillSize=TString(spillSizeT->GetText()).Atoi();
interSpillTime=TString(interSpillTimeT->GetText()).Atoi();
writer->setSpillSize(spillSize);
writer->setInterSpillTime(interSpillTime);
writer->setLedScan(leds);
fHProg2->SetRange(0,nEvtMax);
writer->start(nEvtMax);
while (!writer->isRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); };
/*** Start monitor ***/
Run();
/*** Cleanup after the run finishes ***/
#ifndef ROOT_OUTPUT
if (file) {
if (file->is_open()) {
file->close();
}
delete file;
file = NULL;
}
#else
if (file) {
if (file->IsOpen()) {
file->cd() ;
outTree->Write ("",TObject::kOverwrite) ;
file->Close();
outTree->Reset();
}
delete file;
file = NULL;
}
#endif
f_running = false;
if (rate) { delete rate; rate = NULL; }
if (headers) { delete headers; headers = NULL; }
if (writer) { delete writer; writer = NULL; }
#ifdef ROOT_OUTPUT
if (outTree) { delete outTree; outTree = NULL; }
if (h4daqEvent) { delete h4daqEvent; event = NULL; }
#endif
}
int MonitorFrame::Run() {
std::cout << "Monitor on CPU " << sched_getcpu() << "\n";
f_stop = false;
f_stopWhenEmpty = false;
f_running = true;
// Time calibrations
const bool tCalibrated = true; // Whether time points should come calibrated
const bool tRotated = true; // Whether time points should come rotated
// Voltage calibrations
const bool applyResponseCalib = true; // Remove noise and offset variations
const bool adjustToClock = false; // Extra rotation of amplitudes in the calibration step - SET TO FALSE !
const bool adjustToClockForFile = false;
const bool applyOffsetCalib = false; // ?
unsigned iEvtLocal = 0;
while(!f_stop) {
rawWave = fifo->Read();
if(rawWave) {
iEvtSerial = rawWave->header.getEventNumber();
//start new file when reached spill size
if (iEvtLocal>0 && iEvtLocal%spillSize == 0) {
StartNewFile(); //a new spill in H4DAQ language
}
iEvtLocal++;
//std::cout << "Read event #" << iEvtSerial << std::endl;
// std::cout << "Trigger cell is " << rawWave->header.getTriggerCell() << std::endl;
event = new DRS4_data::Event(iEvtSerial, lastSpill, rawWave->header, drs);
// Observables *obs[2] = {NULL, NULL};
int16_t wf[4][kNumberOfBins];
for(int iboard=0; iboard<headers->ChTimes()->size(); iboard++) {
DRSBoard *b = drs->GetBoard(iboard);
/* decode waveform (Y) arrays in mV */
for (unsigned char ichan=0 ; ichan<4 ; ichan++) {
b->GetWave(rawWave->eventWaves.at(iboard)->waveforms, 0, ichan*2, static_cast<short*>(wf[ichan]),
applyResponseCalib, int(rawWave->header.getTriggerCell()), -1,
adjustToClockForFile, 0, applyOffsetCalib);
}
RemoveSpikes(wf, 20, 2);
for (unsigned char ichan=0 ; ichan<4 ; ichan++) {
// float timebins[kNumberOfBins];
// b->GetTime(0, ichan*2, int(rawWave->header.getTriggerCell()), timebins, tCalibrated, tRotated);
// float amplitude[kNumberOfBins];
for (unsigned ibin=0; ibin<kNumberOfBins; ibin++) {
// amplitude[ibin] = static_cast<float>(wf[ichan][ibin]) / 10;
event->getChData(iboard, ichan)->data[ibin] = wf[ichan][ibin] ;
}
// if (ichan<2 && iboard==0) {
// obs[ichan] = WaveProcessor::ProcessOnline(timebins, amplitude, kNumberOfBins, 4., baseLineWidth);
// obs[ichan]->hist->SetName(Form("Oscillogram_ch%d", ichan+1));
// }
} // Loop over the channels
} // Loop over the boards
iEvtProcessed++;
// FillHistos(obs);
// if(obs[0]) {
// delete obs[0]; obs[0] = NULL;
// }
// if(obs[1]) {
// delete obs[1]; obs[1] = NULL;
// }
#ifndef ROOT_OUTPUT
event->write(file);
#else
//Fill H4DAQ event structure
h4daqEvent->clear();
fillH4Event(headers,event,h4daqEvent);
h4daqEvent->Fill();
// std::cout << "Filled event " << h4daqEvent->id.evtNumber << std::endl;
#endif
delete event; event = NULL;
delete rawWave; rawWave = NULL;
// if(iEvtProcessed%500 == 0) {
// std::cout << "Processed event #" << iEvtProcessed << std::endl;
// }
} // If rawWave (fifo not empty)
else {
if( f_stopWhenEmpty ) {
f_stop = true;
break;
}
else {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} // if(f_stopWhenEmpty)
} // if(rawWave)
gClient->ProcessEventsFor(this);
if (!writer->isRunning()) {
f_stopWhenEmpty = true;
}
if ( int(timer.RealTime()*100) % 20 == 0 )
DoDraw(true);
timer.Continue();
} // !f_stop
DoDraw(true);
nEvtMaxT->SetEnabled(true);
spillSizeT->SetEnabled(true);
interSpillTimeT->SetEnabled(true);
runIdT->SetEnabled(true);
confT->SetEnabled(true);
ledScan->SetEnabled(true);
std::cout << "Events processed: " << iEvtProcessed << "\n";
std::cout << Form("Elapsed time: %6.2f s.\n", timer.RealTime());
std::cout << Form("Event rate: %6.2f events/s \n", float(iEvtProcessed)/timer.RealTime());
f_running = false;
return 0;
}
void MonitorFrame::Stop() {
if(!f_running) return;
if (f_stopWhenEmpty) return;
std::cout << "\n\nStopping acquisition.\n";
writer->stop();
timer.Stop();
nEvtMaxT->SetEnabled(true);
spillSizeT->SetEnabled(true);
interSpillTimeT->SetEnabled(true);
runIdT->SetEnabled(true);
confT->SetEnabled(true);
ledScan->SetEnabled(true);
f_stopWhenEmpty = true;
}
void MonitorFrame::HardStop() {
if(!f_running) return;
if(f_stop) return;
std::cout << "\n\nStopping acquisition and monitor.\n";
writer->stop();
timer.Stop();
f_stop = true;
f_stopWhenEmpty = true;
nEvtMaxT->SetEnabled(true);
spillSizeT->SetEnabled(true);
interSpillTimeT->SetEnabled(true);
runIdT->SetEnabled(true);
confT->SetEnabled(true);
ledScan->SetEnabled(true);
fifo->Discard();
}
void MonitorFrame::RefreshT() {
double t;
if (writer) {
t = writer->Temperature();
}
else {
t = drs->GetBoard(0)->GetTemperature();
}
temperatureT->SetText(Form("%.1f\xB0", t));
}
void MonitorFrame::FillHistos(Observables *obs[2])
{
// for(unsigned ichan=0; ichan<2; ichan++) {
// for(int iobs=0; iobs<nObservables; iobs++) {
// histo[ichan][iobs]->Fill(obs[ichan]->Value(static_cast<kObservables>(iobs)));
// }
// }
// eTot12->Fill(obs[0]->Value(eTot), obs[1]->Value(eTot));
// ePrompt12->Fill(obs[0]->Value(ePrompt), obs[1]->Value(ePrompt));
// time12->Fill(obs[0]->Value(arrivalTime), obs[1]->Value(arrivalTime));
// // TODO: calculate and process t3 and t4
// itRed++; itRed2D++;
// if (itRed >= tRed) {
// itRed=0;
// bool draw2D = false;
// if(itRed2D >= tRed2D) {
// itRed2D=0;
// itRed=0;
// draw2D = true;
// }
// DoDraw(draw2D);
// fCanvasOsc->cd();
// // Remove previous oscillograms
// TList *listp = gPad->GetListOfPrimitives();
// TObject *last = listp->Last();
// if (last->IsA() == obs[0]->hist->IsA()) {
// listp->RemoveLast();
// delete dynamic_cast<TH1F*>(last);
// last = listp->Last();
// if (last->IsA() == obs[0]->hist->IsA()) {
// listp->RemoveLast();
// delete dynamic_cast<TH1F*>(last);
// }
// }
// // obs[0]->hist->Rebin(3);
// obs[0]->hist->SetLineColor(kBlue);
// obs[0]->hist->Scale(-1);
// obs[0]->hist->DrawCopy("same hist l")->SetBit(kCanDelete);
// // obs[1]->hist->Rebin(3);
// obs[1]->hist->SetLineColor(kRed);
// obs[1]->hist->Scale(-1);
// obs[1]->hist->DrawCopy("same hist l")->SetBit(kCanDelete);
// fCanvasOsc->Update();
// }
} // FillHistos()
void MonitorFrame::DoDraw(bool all) {
// Draws function graphics in randomly chosen interval
// fCanvas01->Paint();
// fCanvas02->Paint();
// fCanvas01->Update();
// fCanvas02->Update();
// if(all) {
// fCanvas2D->Paint();
// fCanvas2D->Update();
// }
unsigned nAcq = writer->NEvents();
unsigned timeLast = fifo->timeLastEvent();
nEvtAcqT->SetText(Form("%-10i", nAcq));
nEvtProT->SetText(Form("%-10i", iEvtProcessed));
fHProg2->SetPosition(iEvtProcessed);
rate->Push(nAcq, static_cast<double>(timeLast)/1000);
rateT->SetText(Form("%5.3g evt/s", rate->Get()));
temperatureT->SetText(Form("%.1f\xB0", writer->Temperature()));
timer.Continue();
}
void MonitorFrame::AutoSave() {
TTimeStamp ts(std::time(NULL), 0);
filename = basename;
filename += "_autosave_";
filename += ts.GetDate(0);
filename += "-";
filename += ts.GetTime(0);
timestamped = true;
Save();
filename = basename;
timestamped=false;
}
void MonitorFrame::Save() {
// if ( !timestamped ) {
// TTimeStamp ts(std::time(NULL), 0);
// filename = basename;
// filename += "_";
// filename += ts.GetDate(0);
// filename += "-";
// filename += ts.GetTime(0);
// }
// TString rootfilename(filename); rootfilename += ".root";
// TFile output(rootfilename.Data(), "RECREATE");
// if(!(output.IsOpen())) {
// std::cout << "\nCannot open output root file " << rootfilename.Data() << ".\n";
// // gApplication->Terminate(0);
// }
// for(int iobs=0; iobs<nObservables; iobs++) {
// histo[0][iobs]->Clone()->Write();
// histo[1][iobs]->Clone()->Write();
// }
// eTot12->Clone()->Write();
// ePrompt12->Clone()->Write();
// time12->Clone()->Write();
// time34->Clone()->Write();
// output.Close();
// std::cout << "\nSaved data in " << rootfilename.Data() << "\n";
// timeLastSave = timer.RealTime();
timer.Continue();
}
void MonitorFrame::ExportText() {
/*
if ( !timestamped ) {
TTimeStamp ts(std::time(NULL), 0);
filename = basename;
filename += "_";
filename += ts.GetDate(0);
filename += "-";
filename += ts.GetTime(0);
}
TString textfilename(filename); textfilename += ".dat";
std::ofstream exportfile(textfilename.Data(), std::ios::trunc);
if (!exportfile.is_open()) {
std::cout << "\nCannot open file " << textfilename.Data() << " for writing.\n";
return;
}
for (kObservables i=0; i<nObservables; i++) { exportfile << Form(" %s(1) ", obs->Name(i)); }
for (kObservables i=0; i<nObservables; i++) { exportfile << Form(" %s(2) ", obs->Name(i)); }
exportfile << "\n";
for (int iEvt=0; iEvt<events->GetEntries(); iEvt++) {
events->GetEvent(iEvt);
for (kObservables i=0; i<nObservables; i++) { exportfile << Form("%8.3f", ???); }
for (kObservables i=0; i<nObservables; i++) { exportfile << Form("%8.3f", ???); }
exportfile << "\n";
}
exportfile.close();
std::cout << "\nSaved text data in " << textfilename.Data() << "\n";
*/
}
void MonitorFrame::RateEstimator::Push(int count, double time) {
rateCounts.push(count);
rateTimes.push(time);
int nEvtRate = rateCounts.back() - rateCounts.front();
if (nEvtRate) {
evtRate = double(nEvtRate) / (rateTimes.back() - rateTimes.front());
}
else {
evtRate = 0;
}
if(nEvtRate >= rateCountPeriod || rateCounts.size() > maxSize) {
rateCounts.pop();
rateTimes.pop();
}
}
int MonitorFrame::StartNewFile() {
lastSpill++;
TTimeStamp ts(std::time(NULL), 0);
filename = options->outDir+ "/";
filename += TString(runIdT->GetText());
if (!gSystem->OpenDirectory(filename.Data()))
gSystem->mkdir(filename.Data());
filename += Form("/%d",lastSpill);
filename += "_";
filename += ts.GetDate(0);
filename += "-";
filename += ts.GetTime(0);
//filename = outDir / runId / spillNumber_timestamp.dat
#ifndef ROOT_OUTPUT
if (file) {
if (file->is_open()) {
file->close();
}
}
else {
file = new std::ofstream();
}
filename += ".dat";
std::cout << "Opening output file " << filename << std::endl;
file->open(filename, std::ios_base::binary & std::ios_base::trunc) ;
if( file->fail() ) {
std::cout << "ERROR: Cannot open file " << filename << " for writing.\n";
return -1;
}
/*** Write file header and time calibration ***/
std::cout << "Writing headers and time calibration to file." << std::endl;
if (!headers) {
headers = DRS4_data::DRSHeaders::MakeDRSHeaders(drs);
}
headers->write(file);
#else
if (file) {
if (file->IsOpen()) {
file->cd () ;
outTree->Write ("",TObject::kOverwrite) ;
file->Close();
outTree->Reset();
}
}
filename += ".root";
std::cout << "Opening output file " << filename << std::endl;
file = TFile::Open(filename, "RECREATE") ;
if (!file->IsOpen())
{
std::cout << "ERROR: Cannot open file " << filename << " for writing.\n";
return -1;
}
#endif
outFileT->SetText(filename.Data());
return 0;
}
void MonitorFrame::ParseConfig()
{
if (!options)
return;
//do not need reconfig
// if (confStatus == confT->GetSelected())
// return;
//Configuration possibilities
TString inputFile;
if(confT->GetSelected() == 0)
inputFile="conf/ped.conf";
else if(confT->GetSelected() == 1)
inputFile="conf/led.conf";
else if(confT->GetSelected() == 2)
inputFile="conf/source.conf";
std::ifstream input(inputFile);
if(!input.is_open()) {
std::cout << "Cannot open input file " << inputFile << ".\n";
return ;
}
if (options->ParseOptions(&input) < 0) {
std::cout << "Error parsing options.\n";
return;
}
confStatus = confT->GetSelected();
options->DumpOptions();
}
void MonitorFrame::ConfigDRS()
{
if (!drs)
return;
/*
* We allow more than one board with synchronized triggers.
* For simplicity, we assume that 4 channels are acquired from each board.
*/
/* use first board with highest serial number as the master board */
drs->SortBoards();
DRSBoard *mb = drs->GetBoard(0);
/* common configuration for all boards */
for (int iboard=0 ; iboard<drs->GetNumberOfBoards() ; iboard++) {
std::cout << "Configuring board #" << iboard << std::endl;
DRSBoard *b = drs->GetBoard(iboard);
/* initialize board */
std::cout << "Initializing." << std::endl;
b->Init();
/* select external reference clock for slave modules */
/* NOTE: this only works if the clock chain is connected */
if (iboard > 0) {
if (b->GetFirmwareVersion() >= 21260) { // this only works with recent firmware versions
if (b->GetScaler(5) > 300000) // check if external clock is connected
b->SetRefclk(true); // switch to external reference clock
}
}
/* set sampling frequency */
std::cout << "Setting frequency to " << options->sampleRate << " GHz." << std::endl;
b->SetFrequency(options->sampleRate, true);
/* set input range to -0.5V ... +0.5V */
std::cout << "Setting input range to (-0.5V -> +0.5V)." << std::endl;
b->SetInputRange(options->inputRange);
/* enable hardware trigger
* (1, 0) = "fast trigger", "analog trigger"
* Board types 8, 9 always need (1, 0)
* other board types take (1, 0) for external (LEMO/FP/TRBUS)
* and (0, 1) for internal trigger (analog threshold).
*/
b->EnableTrigger(1, 0);
if (iboard == 0) {
/* master board: enable hardware trigger on CH1 at -50 mV negative edge */
std::cout << "Configuring master board." << std::endl;
b->SetTranspMode(1);
b->SetTriggerSource(options->triggerSource); // set CH1 as source
b->SetTriggerLevel(options->triggerLevel); // -50 mV
b->SetTriggerPolarity(options->triggerNegative); // negative edge
b->SetTriggerDelayNs(options->trigDelay); // Trigger delay shifts waveform left
} else {
/* slave boards: enable hardware trigger on Trigger IN */
std::cout << "Configuring slave board." << std::endl;
b->SetTriggerSource(1<<4); // set Trigger IN as source
b->SetTriggerPolarity(false); // positive edge
}
} // End loop for common configuration
}
| 30.884939 | 196 | 0.634026 | CMSROMA |
e4bae3cb7fcc5f993c72157ed02a0e4b90e716e5 | 2,829 | cpp | C++ | targets/all/io/tests/pipes/Pipes.cpp | minuteos/lib | 288fe4f9221fb431e15792421e21084f29dccdce | [
"MIT"
] | null | null | null | targets/all/io/tests/pipes/Pipes.cpp | minuteos/lib | 288fe4f9221fb431e15792421e21084f29dccdce | [
"MIT"
] | null | null | null | targets/all/io/tests/pipes/Pipes.cpp | minuteos/lib | 288fe4f9221fb431e15792421e21084f29dccdce | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 triaxis s.r.o.
* Licensed under the MIT license. See LICENSE.txt file in the repository root
* for full license information.
*
* io/tests/pipes/Pipes.cpp
*/
#include <testrunner/TestCase.h>
#include <kernel/kernel.h>
#include <io/io.h>
namespace
{
using namespace io;
using namespace kernel;
TEST_CASE("01 Simple Pipe")
{
Scheduler s;
Pipe p;
struct S
{
static async(Writer, PipeWriter w)
async_def()
{
await(w.Write, "TEST");
w.Close();
}
async_end
static async(Reader, PipeReader r)
async_def()
{
size_t n;
n = await(r.Read);
AssertEqual(n, 4u);
AssertEqual(r.Available(), 4u);
AssertEqual(r.IsComplete(), true);
Assert(r.Matches("TEST"));
r.Advance(n);
}
async_end
};
s.Add(&S::Reader, p);
s.Add(&S::Writer, p);
s.Run();
Assert(p.IsCompleted());
}
TEST_CASE("02 Multi Write")
{
Scheduler s;
Pipe p;
struct S
{
static async(Writer, PipeWriter w)
async_def()
{
await(w.Write, "TE");
async_yield();
await(w.Write, "ST");
w.Close();
}
async_end
static async(Reader, PipeReader r)
async_def()
{
size_t n;
n = await(r.Read);
AssertEqual(n, 2u);
AssertEqual(r.Available(), 2u);
AssertEqual(r.IsComplete(), false);
Assert(r.Matches("TE"));
n = await(r.Read, 3);
AssertEqual(n, 4u);
AssertEqual(r.Available(), 4u);
AssertEqual(r.IsComplete(), true);
Assert(r.Matches("TEST"));
r.Advance(n);
}
async_end
};
s.Add(&S::Reader, p);
s.Add(&S::Writer, p);
s.Run();
Assert(p.IsCompleted());
}
TEST_CASE("03 Read Until")
{
Scheduler s;
Pipe p;
struct S
{
static async(Writer, PipeWriter w)
async_def()
{
await(w.Write, "Line 1\nLine 2");
w.Close();
}
async_end
static async(Reader, PipeReader r)
async_def()
{
size_t n;
n = await(r.ReadUntil, '\n');
AssertEqual(n, 7u);
Assert(r.Matches("Line 1\n"));
r.Advance(n);
n = await(r.ReadUntil, '\n');
AssertEqual(n, 0u);
AssertEqual(r.IsComplete(), true);
AssertEqual(r.Available(), 6u);
Assert(r.Matches("Line 2")); // no terminator
r.Advance(6);
}
async_end
};
s.Add(&S::Reader, p);
s.Add(&S::Writer, p);
s.Run();
Assert(p.IsCompleted());
}
}
| 20.207143 | 78 | 0.481796 | minuteos |
e4bd71f54771127f3de4aae60424d5533a82ef8b | 1,460 | cpp | C++ | 07-functions/7.22-optional-rectangles-sizes/solution.cpp | trangnart/cis22a | 498a7b37d12a13efa7749849dc95d9892d1786be | [
"MIT"
] | 2 | 2020-09-04T22:06:06.000Z | 2020-09-09T04:00:25.000Z | 07-functions/7.22-optional-rectangles-sizes/solution.cpp | trangnart/cis22a | 498a7b37d12a13efa7749849dc95d9892d1786be | [
"MIT"
] | 14 | 2020-08-24T01:44:36.000Z | 2021-01-01T08:44:17.000Z | 07-functions/7.22-optional-rectangles-sizes/solution.cpp | trangnart/cis22a | 498a7b37d12a13efa7749849dc95d9892d1786be | [
"MIT"
] | 1 | 2020-09-04T22:13:13.000Z | 2020-09-04T22:13:13.000Z | #include <iostream>
#include <string>
#include <fstream>
using namespace std;
bool FirstRectangleSmaller(int, int, int, int, int, int, int, int);
void CompareRectangles(const string &);
int main()
{
const string FILENAME = "input.txt";
// cout << FirstRectangleSmaller(1,1,2,3,0,0,10,10) << endl;
CompareRectangles(FILENAME);
return 0;
}
bool FirstRectangleSmaller(int r1xul, int r1yul, int r1xbr, int r1ybr,
int r2xul, int r2yul, int r2xbr, int r2ybr)
{
int r1Area = (r1xbr - r1xul) * (r1ybr - r1yul);
int r2Area = (r2xbr - r2xul) * (r2ybr - r2yul);
return abs(r1Area) < abs(r2Area);
}
void CompareRectangles(const string &filename)
{
ifstream inFS(filename);
int r1x1, r1y1, r1x2, r1y2,
r2x1, r2y1, r2x2, r2y2;
if (!inFS.is_open())
{
cout << "Cannot open file " << filename << endl;
return;
}
while (!inFS.eof())
{
inFS >> r1x1 >> r1y1 >> r1x2 >> r1y2 >> r2x1 >> r2y1 >> r2x2 >> r2y2;
if (inFS.fail())
{
continue;
}
string tf =
FirstRectangleSmaller(r1x1, r1y1, r1x2, r1y2, r2x1, r2y1, r2x2, r2y2)
? "true" : "false";
cout << "(" << r1x1 << "," << r1y1 << ") "
<< "(" << r1x2 << "," << r1y2 << ") < "
<< "(" << r2x1 << "," << r2y1 << ") "
<< "(" << r2x2 << "," << r2y2 << ") is "
<< tf << endl;
}
} | 24.333333 | 81 | 0.506849 | trangnart |
e4bf33e81a6c08724e9ee4bc7a8ee96aa8056c78 | 12,582 | hpp | C++ | include/message_logger/log/log_messages_ros.hpp | ANYbotics/message_logger | 66f9f0795f3a6395b6ee2ab7ac5f0df2ffd05f42 | [
"BSD-3-Clause"
] | 5 | 2019-12-27T02:04:55.000Z | 2022-01-11T13:29:27.000Z | include/message_logger/log/log_messages_ros.hpp | ANYbotics/message_logger | 66f9f0795f3a6395b6ee2ab7ac5f0df2ffd05f42 | [
"BSD-3-Clause"
] | 1 | 2020-10-22T16:36:03.000Z | 2020-10-23T05:53:12.000Z | include/message_logger/log/log_messages_ros.hpp | ANYbotics/message_logger | 66f9f0795f3a6395b6ee2ab7ac5f0df2ffd05f42 | [
"BSD-3-Clause"
] | 4 | 2019-12-27T02:04:57.000Z | 2020-10-22T16:19:18.000Z | /**********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Christian Gehring
* 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 Autonomous Systems Lab nor ETH Zurich
* nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* @file log_messages_ros.hpp
* @author Christian Gehring
* @date Dec, 2014
* @brief
*/
#pragma once
#include <ros/console.h>
#include "message_logger/log/log_messages_backend.hpp"
namespace message_logger {
namespace log {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG(level, ...) \
{ \
std::stringstream melo_stringstream; \
melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \
switch (level) { \
case message_logger::log::levels::Debug: \
{ \
ROS_DEBUG("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Info: \
{ \
ROS_INFO("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Warn: \
{ \
ROS_WARN("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Error: \
{ \
ROS_ERROR("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Fatal: \
{ \
ROS_FATAL("%s", melo_stringstream.str().c_str()); \
std::stringstream melo_assert_stringstream; \
melo_assert_stringstream << message_logger::log::colorFatal << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \
message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \
} \
break; \
default: \
{ \
ROS_INFO(__VA_ARGS__); \
} \
break; \
} \
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_STREAM(level, message) \
{ \
std::stringstream melo_stringstream; \
melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message << message_logger::log::getResetColor(); \
switch (level) { \
case message_logger::log::levels::Debug: \
{ \
ROS_DEBUG_STREAM(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Info: \
{ \
ROS_INFO_STREAM(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Warn: \
{ \
ROS_WARN_STREAM(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Error: \
{ \
ROS_ERROR_STREAM(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Fatal: \
{ \
ROS_FATAL_STREAM(melo_stringstream.str()); \
std::stringstream melo_assert_stringstream; \
melo_assert_stringstream << message_logger::log::colorFatal << message << message_logger::log::getResetColor(); \
message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \
} \
break; \
default: \
{ \
ROS_INFO_STREAM(message); \
} \
break; \
} \
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_FP(level, ...) MELO_LOG(level, __VA_ARGS__)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_STREAM_FP(level, message) MELO_LOG_STREAM(level, message)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_ONCE(level, ...) \
{ \
std::stringstream melo_stringstream; \
melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \
switch (level) { \
case message_logger::log::levels::Debug: \
{ \
ROS_DEBUG_ONCE("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Info: \
{ \
ROS_INFO_ONCE("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Warn: \
{ \
ROS_WARN_ONCE("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Error: \
{ \
ROS_ERROR_ONCE("%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Fatal: \
{ \
ROS_FATAL_ONCE("%s", melo_stringstream.str().c_str()); \
std::stringstream melo_assert_stringstream; \
melo_assert_stringstream << message_logger::log::colorFatal << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \
message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \
} \
break; \
default: \
{ \
ROS_INFO_ONCE(__VA_ARGS__); \
} \
break; \
} \
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_STREAM_ONCE(level, message) \
{ \
std::stringstream melo_stringstream; \
melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message << message_logger::log::getResetColor(); \
switch (level) { \
case message_logger::log::levels::Debug: \
{ \
ROS_DEBUG_STREAM_ONCE(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Info: \
{ \
ROS_INFO_STREAM_ONCE(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Warn: \
{ \
ROS_WARN_STREAM_ONCE(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Error: \
{ \
ROS_ERROR_STREAM_ONCE(melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Fatal: \
{ \
ROS_FATAL_STREAM_ONCE(melo_stringstream.str()); \
std::stringstream melo_assert_stringstream; \
melo_assert_stringstream << message_logger::log::colorFatal << message << message_logger::log::getResetColor(); \
message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \
} \
break; \
default: \
{ \
ROS_INFO_STREAM_ONCE(message); \
} \
break; \
} \
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_THROTTLE(rate, level, ...) \
{ \
std::stringstream melo_stringstream; \
melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \
switch (level) { \
case message_logger::log::levels::Debug: \
{ \
ROS_DEBUG_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Info: \
{ \
ROS_INFO_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Warn: \
{ \
ROS_WARN_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Error: \
{ \
ROS_ERROR_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \
} \
break; \
case message_logger::log::levels::Fatal: \
{ \
ROS_FATAL_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \
std::stringstream melo_assert_stringstream; \
melo_assert_stringstream << message_logger::log::colorFatal << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \
message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \
} \
break; \
default: \
{ \
ROS_INFO_THROTTLE(rate, __VA_ARGS__); \
} \
break; \
} \
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MELO_LOG_THROTTLE_STREAM(rate, level, message) \
{ \
std::stringstream melo_stringstream; \
melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message << message_logger::log::getResetColor(); \
switch (level) { \
case message_logger::log::levels::Debug: \
{ \
ROS_DEBUG_STREAM_THROTTLE(rate, melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Info: \
{ \
ROS_INFO_STREAM_THROTTLE(rate, melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Warn: \
{ \
ROS_WARN_STREAM_THROTTLE(rate, melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Error: \
{ \
ROS_ERROR_STREAM_THROTTLE(rate, melo_stringstream.str()); \
} \
break; \
case message_logger::log::levels::Fatal: \
{ \
ROS_FATAL_STREAM_THROTTLE(rate, melo_stringstream.str()); \
std::stringstream melo_assert_stringstream; \
melo_assert_stringstream << message_logger::log::colorFatal << message << message_logger::log::getResetColor(); \
message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \
} \
break; \
default: \
{ \
ROS_INFO_STREAM_THROTTLE(rate, message); \
} \
break; \
} \
}
} // namespace log
} // namespace message_logger
| 40.456592 | 239 | 0.57924 | ANYbotics |
e4c2c8ef4dd7da05aa38ce489af1310c13e1027f | 77 | cpp | C++ | Ardulib2d/Arduboy2D.cpp | madya121/Ardulib2d | dc93424975c6a0a584b0d32d115b099bf9d0fbd1 | [
"MIT"
] | null | null | null | Ardulib2d/Arduboy2D.cpp | madya121/Ardulib2d | dc93424975c6a0a584b0d32d115b099bf9d0fbd1 | [
"MIT"
] | null | null | null | Ardulib2d/Arduboy2D.cpp | madya121/Ardulib2d | dc93424975c6a0a584b0d32d115b099bf9d0fbd1 | [
"MIT"
] | null | null | null | #include "Arduboy2D.h"
Arduboy2D::Arduboy2D() {
camera = new Camera();
}
| 11 | 24 | 0.649351 | madya121 |
e4c2d6719bb14bdc1338819e4e17506f48316526 | 1,983 | hpp | C++ | srcs/common/trackgrouptypebox.hpp | Reflectioner/heif | bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab | [
"BSD-3-Clause"
] | null | null | null | srcs/common/trackgrouptypebox.hpp | Reflectioner/heif | bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab | [
"BSD-3-Clause"
] | null | null | null | srcs/common/trackgrouptypebox.hpp | Reflectioner/heif | bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab | [
"BSD-3-Clause"
] | null | null | null | /* This file is part of Nokia HEIF library
*
* Copyright (c) 2015-2020 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: [email protected]
*
* This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its
* subsidiaries. All rights are reserved.
*
* Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior
* written consent of Nokia.
*/
#ifndef TRACKGROUPTYPEBOX_HPP
#define TRACKGROUPTYPEBOX_HPP
#include <cstdint>
#include "bitstream.hpp"
#include "customallocator.hpp"
#include "fullbox.hpp"
/** @brief Track Group Type Box class. Extends from FullBox.
* @details inside 'trgr' box as specified in the ISOBMFF specification
*/
class TrackGroupTypeBox : public FullBox
{
public:
TrackGroupTypeBox(FourCCInt boxType, std::uint32_t trackGroupId = 0);
~TrackGroupTypeBox() override = default;
/** @brief Gets track group id.
* @returns std::uint32_t containing track group id. */
std::uint32_t getTrackGroupId() const;
/** @brief Sets track group id. Applicable to track group type boxes of type obsp.
* The pair of track_group_id and track_group_type identifies a track group
* @param [in] bitstr Bitstream that contains the box data */
void setTrackGroupId(std::uint32_t trackGroupId);
/** @brief Creates the bitstream that represents the box in the ISOBMFF file
* @param [out] bitstr Bitstream that contains the box data. */
void writeBox(ISOBMFF::BitStream& bitstr) const override;
/** @brief Parses an Track Group Type Box bitstream and fills in the necessary member variables
* @param [in] bitstr Bitstream that contains the box data */
void parseBox(ISOBMFF::BitStream& bitstr) override;
virtual TrackGroupTypeBox* clone() const;
private:
std::uint32_t mTrackGroupId; ///< indicates the grouping type
};
#endif /* TRACKGROUPTYPEBOX_HPP */
| 35.410714 | 115 | 0.732728 | Reflectioner |
e4c2e59d9d0f2f2f0dab3bc91641611aaa7602a6 | 4,575 | cxx | C++ | Code/Filter/vtkMimxComputeNormalsFromPolydataFilter.cxx | Piyusha23/IAFEMesh | e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f | [
"BSD-4-Clause-UC"
] | null | null | null | Code/Filter/vtkMimxComputeNormalsFromPolydataFilter.cxx | Piyusha23/IAFEMesh | e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f | [
"BSD-4-Clause-UC"
] | null | null | null | Code/Filter/vtkMimxComputeNormalsFromPolydataFilter.cxx | Piyusha23/IAFEMesh | e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f | [
"BSD-4-Clause-UC"
] | null | null | null | /*=========================================================================
Program: MIMX Meshing Toolkit
Module: $RCSfile: vtkMimxComputeNormalsFromPolydataFilter.cxx,v $
Language: C++
Date: $Date: 2012/12/07 19:08:59 $
Version: $Revision: 1.1.1.1 $
Musculoskeletal Imaging, Modelling and Experimentation (MIMX)
Center for Computer Aided Design
The University of Iowa
Iowa City, IA 52242
http://www.ccad.uiowa.edu/mimx/
Copyright (c) The University of Iowa. All rights reserved.
See MIMXCopyright.txt or http://www.ccad.uiowa.edu/mimx/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "vtkMimxComputeNormalsFromPolydataFilter.h"
#include "vtkPolyData.h"
#include "vtkTriangle.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkPoints.h"
vtkCxxRevisionMacro(vtkMimxComputeNormalsFromPolydataFilter, "$Revision: 1.1.1.1 $");
vtkStandardNewMacro(vtkMimxComputeNormalsFromPolydataFilter);
vtkMimxComputeNormalsFromPolydataFilter::vtkMimxComputeNormalsFromPolydataFilter()
{
}
vtkMimxComputeNormalsFromPolydataFilter::~vtkMimxComputeNormalsFromPolydataFilter()
{
}
//----------------------------------------------------------------------------
int vtkMimxComputeNormalsFromPolydataFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkPolyData *input = vtkPolyData::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPointSet *output = vtkPointSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPoints *Normals = vtkPoints::New( );
double initialValue = -2.0;
vtkIdType numberOfPoints = input->GetNumberOfPoints();
vtkCellArray *cellArray = input->GetPolys(); // Gives number of surface faces
Normals->SetNumberOfPoints( numberOfPoints );
for ( vtkIdType i = 0; i < numberOfPoints; i++ )
{
Normals->InsertPoint( i, initialValue, initialValue, initialValue);
}
vtkIdType* pts=0;
vtkIdType t=0;
int num_neigh;
vtkTriangle* tria = vtkTriangle::New();
for( int j = 0; j < numberOfPoints; j++ )
{
num_neigh = 0;
cellArray->InitTraversal();
vtkPoints* Store_Coor = vtkPoints::New();
Store_Coor->SetNumberOfPoints(1);
while(cellArray->GetNextCell(t,pts))
{
if(pts[0] == j)
{
Store_Coor->InsertPoint(num_neigh,pts[0],pts[1],pts[3]);
num_neigh++;
}
if(pts[1] == j)
{
Store_Coor->InsertPoint(num_neigh,pts[1],pts[2],pts[0]);
num_neigh++;
}
if(pts[2] == j)
{
Store_Coor->InsertPoint(num_neigh,pts[2],pts[3],pts[1]);
num_neigh++;
}
if(pts[3] == j)
{
Store_Coor->InsertPoint(num_neigh,pts[3],pts[0],pts[2]);
num_neigh++;
}
}
int num_ent = Store_Coor->GetNumberOfPoints();
double x_comp = 0, y_comp = 0, z_comp = 0;
double x1[3],x2[3],x3[3],normal[3];
double x[3];
if(num_neigh !=0)
{
for(int i=0;i<num_ent;i++)
{
Store_Coor->GetPoint(i,x);
input->GetPoint(static_cast<int>(x[0]),x1);
input->GetPoint(static_cast<int>(x[1]),x2);
input->GetPoint(static_cast<int>(x[2]),x3);
tria->ComputeNormal(x1,x2,x3,normal);
x_comp = x_comp + normal[0];
y_comp = y_comp + normal[1];
z_comp = z_comp + normal[2];
}
if(num_ent !=0)
{
x_comp = x_comp / num_ent;
y_comp = y_comp / num_ent;
z_comp = z_comp / num_ent;
double norm = sqrt(pow(x_comp,2)+
pow(y_comp,2)+pow(z_comp,2));
x_comp = x_comp / norm;
y_comp = y_comp / norm;
z_comp = z_comp / norm;
Normals->SetPoint( j, x_comp, y_comp, z_comp);
}
}
Store_Coor->Delete();
}
output->SetPoints( Normals );
Normals->Delete();
return 1;
}
void vtkMimxComputeNormalsFromPolydataFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
| 29.707792 | 86 | 0.637377 | Piyusha23 |
e4c4b8226a759244643383bef43e7f5f911968fa | 616 | hpp | C++ | SDL2Cpp/SDL2Cpp/include/SDL2Cpp/Thread.hpp | jasonwnorris/SDL2Cpp | ece3bc247adab1b127303340d8463cb19d585d81 | [
"MIT"
] | 3 | 2015-02-04T20:35:10.000Z | 2015-10-26T16:45:27.000Z | SDL2Cpp/SDL2Cpp/include/SDL2Cpp/Thread.hpp | jasonwnorris/SDL2Cpp | ece3bc247adab1b127303340d8463cb19d585d81 | [
"MIT"
] | null | null | null | SDL2Cpp/SDL2Cpp/include/SDL2Cpp/Thread.hpp | jasonwnorris/SDL2Cpp | ece3bc247adab1b127303340d8463cb19d585d81 | [
"MIT"
] | null | null | null | // Thread.hpp
#ifndef __SDL2_THREAD_H__
#define __SDL2_THREAD_H__
// SDL Includes
#include <SDL.h>
namespace SDL2
{
class Thread
{
public:
Thread();
virtual ~Thread();
void Start(Uint32 pDelay = 0);
void Stop();
void Wait();
void StopAndWait();
void SetPriority(SDL_ThreadPriority pPriority);
int GetID() const;
const char* GetName() const;
bool IsRunning() const;
bool IsStopped() const;
protected:
virtual void Run() = 0;
private:
static int Execute(void* pData);
volatile bool mRunning;
volatile bool mStopped;
SDL_Thread* mThread;
};
}
#endif
| 15.02439 | 50 | 0.663961 | jasonwnorris |
e4c870af5a321951fa3ff9bc318e87486b09b59e | 365 | cpp | C++ | code/main.cpp | fawkesLi-lhh/Vagrant | 15adbf52fb55235f68b3d576c5a8433cf8ee5b41 | [
"Apache-2.0"
] | 3 | 2021-02-19T14:06:26.000Z | 2021-03-11T13:28:03.000Z | code/main.cpp | fawkesLi-lhh/Vagrant | 15adbf52fb55235f68b3d576c5a8433cf8ee5b41 | [
"Apache-2.0"
] | null | null | null | code/main.cpp | fawkesLi-lhh/Vagrant | 15adbf52fb55235f68b3d576c5a8433cf8ee5b41 | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <cstdlib>
#include <iostream>
#include <set>
#include <string>
#include <cstring>
#include <algorithm>
#include <dirent.h>
#include <unistd.h>
#include "Vagrant/vagrant.h"
#include "Vagrant/server/Server.h"
#include "Classes/Login.h"
signed main() {
Server server;
server.addUrl(new Login());
server.loop();
return 0;
} | 17.380952 | 34 | 0.687671 | fawkesLi-lhh |
e4c9b2e839a3a6a8eb1df537cd50049a27d07002 | 514 | cc | C++ | src/tsl_array_map.cc | agutikov/hash-table-shootout | fb98881843b8a3510ff0a9d90a6bf1ba8dbd9690 | [
"CC0-1.0"
] | null | null | null | src/tsl_array_map.cc | agutikov/hash-table-shootout | fb98881843b8a3510ff0a9d90a6bf1ba8dbd9690 | [
"CC0-1.0"
] | null | null | null | src/tsl_array_map.cc | agutikov/hash-table-shootout | fb98881843b8a3510ff0a9d90a6bf1ba8dbd9690 | [
"CC0-1.0"
] | null | null | null | #include <inttypes.h>
#include <string>
#include <tsl/array_map.h>
#include <string_view>
template<class CharT>
struct str_hash {
std::size_t operator()(const CharT* key, std::size_t key_size) const {
return std::hash<std::string_view>()(std::string_view(key, key_size));
}
};
typedef tsl::array_map<char, int64_t, str_hash<char>> str_hash_t;
#include "hash_map_str_base.h"
#undef INSERT_STR_INTO_HASH
#define INSERT_STR_INTO_HASH(key, value) str_hash.insert(key, value)
#include "template.c"
| 24.47619 | 78 | 0.733463 | agutikov |
e4ced3dbe4972567aa73cf3489254377ce7ed420 | 8,558 | cpp | C++ | src/Evaluator.cpp | bmhowe34/qwixxmaster | 106d1da67c8c0e6378b7f55757f84396d124b05b | [
"MIT"
] | 2 | 2019-04-09T10:27:48.000Z | 2020-04-19T23:35:34.000Z | src/Evaluator.cpp | bmhowe34/qwixxmaster | 106d1da67c8c0e6378b7f55757f84396d124b05b | [
"MIT"
] | 2 | 2020-04-20T01:01:20.000Z | 2020-04-22T21:52:53.000Z | src/Evaluator.cpp | bmhowe34/qwixxmaster | 106d1da67c8c0e6378b7f55757f84396d124b05b | [
"MIT"
] | 1 | 2020-04-22T01:10:28.000Z | 2020-04-22T01:10:28.000Z | #include "Evaluator.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include "State.h"
#include "RandomDice.h"
#include "BruteForceRollGenerator.h"
#include "StringUtils.h"
#include "MemoryManager.h"
namespace{
size_t encode_min_max_0_based(size_t first, size_t second){
size_t max=std::max(first, second);
size_t min=std::min(first, second);
return max*(max+1)/2+min;
}
size_t COLOR_MAX_ID=78;
size_t calc_max_index(){
size_t two_colors=encode_min_max_0_based(COLOR_MAX_ID, COLOR_MAX_ID);
return (encode_min_max_0_based(two_colors, two_colors)+1)*5;
}
size_t calc_color_id(const ColorState &cs){
return (cs.last-1)*cs.last/2+cs.cnt;
}
size_t calc_2color_id(const ColorState &cs1, const ColorState &cs2){
size_t first=calc_color_id(cs1);
size_t second=calc_color_id(cs2);
return encode_min_max_0_based(first, second);
}
size_t calc_id(const State &state){
size_t id1=calc_2color_id(state.get_color_state(cRED), state.get_color_state(cYELLOW));
ColorState sGreen=state.get_color_state(cGREEN);
sGreen.last=14-sGreen.last;
ColorState sBlue=state.get_color_state(cBLUE);
sBlue.last=14-sBlue.last;
size_t id2=calc_2color_id(sGreen, sBlue);
size_t id=encode_min_max_0_based(id1, id2);
return id*5+state.get_missed();
}
}
namespace {
double STATE_NOT_EVALUATED=-300.0;//actually -16 is the worst what can happen!
}
size_t Evaluator::get_next_player(size_t current_player) const{
return (current_player+1)%player_number;
}
Evaluator::Evaluator(size_t sampling_number_, size_t player_number_):
sampling_number(sampling_number_), player_number(player_number_),
mem(player_number*(calc_max_index()+1), STATE_NOT_EVALUATED)
{}
float Evaluator::evaluate_state(const State &state, size_t current_player){
size_t id=calc_id(state)+current_player*(calc_max_index()+1);
if(mem.at(id)==STATE_NOT_EVALUATED){
if(state.ended()){
mem.at(id)=state.score();
}
else{
double value=0;
if(current_player==0){//it is my turn
std::unique_ptr<RollGenerator> gen;
if(sampling_number==0)
gen.reset(new BruteForceRollGenerator());
else
gen.reset(new GlobalRollGenerator(sampling_number));
while(gen->has_next()){
RollPair roll_pair=gen->get_next();
value+=roll_pair.probability*evaluate_roll(state, roll_pair.roll);
}
}
else{//it is not my turn, only short roll can be used
std::unique_ptr<ShortRollGenerator> gen;
if(sampling_number==0 || sampling_number>=21) //there are at most 21 different dice rolls!
gen.reset(new BruteForceShortRollGenerator());
else
gen.reset(new GlobalShortRollGenerator(sampling_number));
while(gen->has_next()){
ShortRollPair roll_pair=gen->get_next();
value+=roll_pair.probability*evaluate_roll(state, roll_pair.roll, current_player);
}
}
mem.at(id)=static_cast<float>(value);
}
}
return mem.at(id);
}
float Evaluator::evaluate_without_whites(const State &state, const DiceRoll &roll, size_t current_player){
size_t next_player=get_next_player(current_player);
// no whites!
float best=-1e6;
State cur=state;
for(size_t dice=4;dice<=5;dice++){
if(dice==5 && roll[4]==roll[5])
break;
for(size_t j=0;j<COLOR_CNT;j++){
Color color=static_cast<Color>(j);
unsigned char save_last=cur.last[j];
unsigned char save_cnt=cur.cnt[j];
if(cur.take(color, roll[color]+roll[dice])){
best=std::max(best, evaluate_state(cur, next_player));
cur.last[j]=save_last;
cur.cnt[j]=save_cnt;
}
}
}
return best;
}
float Evaluator::evaluate_roll(const State &state, const DiceRoll &roll){
//for full roll the current player is always 0!
size_t current_player=0;
size_t next_player=get_next_player(0);
//always an option: take miss
State cur=state;
cur.add_miss();
float best=evaluate_state(cur, next_player);
//take whites:
for (size_t i=0;i<COLOR_CNT;i++){
Color color=static_cast<Color>(i);
cur=state;
if(cur.take(color, roll[4]+roll[5])){
best=std::max(best, evaluate_state(cur, next_player));
if (!cur.ended()){
best=std::max(best, evaluate_without_whites(cur, roll, current_player));
}
}
}
return std::max(best, evaluate_without_whites(state, roll, current_player));
}
float Evaluator::evaluate_roll(const State &state, const ShortDiceRoll &roll, size_t current_player){
size_t next_player=get_next_player(current_player);
//it is allowed not to take
float best=evaluate_state(state, next_player);
//take whites:
for (size_t i=0;i<COLOR_CNT;i++){
Color color=static_cast<Color>(i);
State cur=state;
if(cur.take(color, roll.at(0)+roll.at(1))){
best=std::max(best, evaluate_state(cur, next_player));
}
}
return best;
}
void Evaluator::evaluate_without_whites(const State &state, const DiceRoll &roll, MoveInfos &res, const std::string &prefix, size_t current_player){
size_t next_player=get_next_player(current_player);
for(size_t dice=4;dice<=5;dice++)
for(size_t j=0;j<COLOR_CNT;j++){
Color color=static_cast<Color>(j);
State cur=state;
if(cur.take(color, roll[color]+roll[dice]))
res.push_back(std::make_pair(evaluate_state(cur, next_player),prefix+ color2str(color)+" "+stringutils::int2str(roll[color]+roll[dice])));
}
}
Evaluator::MoveInfos Evaluator::get_roll_evaluation(const State &state, const DiceRoll &roll){
MoveInfos res;
//for full roll the current player is always 0!
size_t current_player=0;
size_t next_player=get_next_player(current_player);
//always an option: take miss
State cur=state;
cur.add_miss();
res.push_back(std::make_pair(evaluate_state(cur, next_player), "miss"));
//take whites:
for (size_t i=0;i<COLOR_CNT;i++){
Color color=static_cast<Color>(i);
cur=state;
if(cur.take(color, roll.at(4)+roll.at(5))){
std::string move=color2str(color)+" "+stringutils::int2str(roll.at(4)+roll.at(5));
res.push_back(std::make_pair(evaluate_state(cur, next_player), move));
if (!cur.ended()){
//additional color dice?
evaluate_without_whites(cur, roll, res, move+",", current_player);
}
}
}
// no whites!
evaluate_without_whites(state, roll, res, "", current_player);
sort(res.begin(), res.end(), std::greater<MoveInfo>());
return res;
}
Evaluator::MoveInfos Evaluator::get_short_roll_evaluation(const State &state, const ShortDiceRoll &roll, size_t current_player){
MoveInfos res;
size_t next_player=get_next_player(current_player);
//I'm allowed not to take anything:
res.push_back(std::make_pair(evaluate_state(state, next_player), "nothing"));
//take whites:
for (size_t i=0;i<COLOR_CNT;i++){
Color color=static_cast<Color>(i);
State cur=state;
if(cur.take(color, roll.at(0)+roll.at(1))){
std::string move=color2str(color)+" "+stringutils::int2str(roll.at(0)+roll.at(1));
res.push_back(std::make_pair(evaluate_state(cur, next_player), move));
}
}
sort(res.begin(), res.end(), std::greater<MoveInfo>());
return res;
}
std::pair<size_t, size_t> Evaluator::save_memory_to_file(const std::string &filename) const{
MemoryManager::save_memory(filename, mem);
size_t not_set=std::count(mem.begin(), mem.end(), STATE_NOT_EVALUATED);
return std::make_pair(mem.size(), not_set);
}
std::pair<size_t, size_t> Evaluator::load_memory_from_file(const std::string &filename){
MemoryManager::load_memory(filename, mem);
size_t not_set=std::count(mem.begin(), mem.end(), STATE_NOT_EVALUATED);
return std::make_pair(mem.size(), not_set);
}
size_t Evaluator::get_number_of_players() const{
return player_number;
}
| 33.042471 | 161 | 0.636364 | bmhowe34 |
e4cfad283dd9d846667f11cde2626250066208e2 | 49,214 | cpp | C++ | src/isbiad.cpp | nporsche/fastbit | 91d06c68b9f4a0a0cc39da737d1c880ab21fe947 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/isbiad.cpp | nporsche/fastbit | 91d06c68b9f4a0a0cc39da737d1c880ab21fe947 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/isbiad.cpp | nporsche/fastbit | 91d06c68b9f4a0a0cc39da737d1c880ab21fe947 | [
"BSD-3-Clause-LBNL"
] | null | null | null | // $Id$
// Author: John Wu <John.Wu at ACM.org>
// Copyright (c) 2000-2015 the Regents of the University of California
//
// This file contains the implementation of the class called ibis::sbiad.
//
// The word sbiad is the Italian translation of the English word fade.
//
// fade -- multicomponent range-encoded bitmap index
// sbiad -- multicomponent interval-encoded bitmap index
// sapid -- multicomponent equality-encoded bitmap index
//
#if defined(_WIN32) && defined(_MSC_VER)
#pragma warning(disable:4786) // some identifier longer than 256 characters
#endif
#include "irelic.h"
#include "part.h"
#include "column.h"
#include "resource.h"
////////////////////////////////////////////////////////////////////////
// functions of ibis::sbiad
//
/// Constructor. If an index exists in the specified location, it will be
/// read, otherwise a new bitmap index will be created from current data.
ibis::sbiad::sbiad(const ibis::column* c, const char* f, const uint32_t nbase)
: ibis::fade(0) {
if (c == 0) return; // nothing can be done
col = c;
try {
if (c->partition()->nRows() < 1000000) {
construct1(f, nbase); // uses more temporary space
}
else {
construct2(f, nbase); // scan data twice
}
if (ibis::gVerbose > 2) {
ibis::util::logger lg;
lg() << "sbiad[" << col->partition()->name() << '.' << col->name()
<< "]::ctor -- constructed a " << bases.size()
<< "-component interval index with "
<< bits.size() << " bitmap" << (bits.size()>1?"s":"")
<< " for " << nrows << " row" << (nrows>1?"s":"");
if (ibis::gVerbose > 6) {
lg() << "\n";
print(lg());
}
}
}
catch (...) {
LOGGER(ibis::gVerbose > 1)
<< "Warning -- sbiad[" << col->partition()->name() << '.'
<< col->name() << "]::ctor received an exception, cleaning up ...";
clear();
throw;
}
} // constructor
/// Reconstruct an index from a storage object.
/// The content of the file (following the 8-byte header) is as follows:
///@code
/// nrows(uint32_t) -- the number of bits in a bit sequence
/// nobs (uint32_t) -- the number of bit sequences
/// card (uint32_t) -- the number of distinct values, i.e., cardinality
/// (padding to ensure the next data element is on 8-byte boundary)
/// values (double[card]) -- the distinct values as doubles
/// offset([nobs+1]) -- the starting positions of the bit sequences
/// (as bit vectors)
/// nbases(uint32_t) -- the number of components (bases) used
/// cnts (uint32_t[card]) -- the counts for each distinct value
/// bases(uint32_t[nbases]) -- the bases sizes
/// bitvectors -- the bitvectors one after another
///@endcode
ibis::sbiad::sbiad(const ibis::column* c, ibis::fileManager::storage* st,
size_t start) : ibis::fade(c, st, start) {
if (ibis::gVerbose > 2) {
ibis::util::logger lg;
lg() << "sbiad[" << col->partition()->name() << '.' << col->name()
<< "]::ctor -- initialized a " << bases.size()
<< "-component interval index with "
<< bits.size() << " bitmap" << (bits.size()>1?"s":"")
<< " for " << nrows << " row" << (nrows>1?"s":"")
<< " from a storage object @ " << st;
if (ibis::gVerbose > 6) {
lg() << "\n";
print(lg());
}
}
} // reconstruct data from content of a file
// the argument is the name of the directory or the file name
int ibis::sbiad::write(const char* dt) const {
if (vals.empty()) return -1;
std::string fnm, evt;
evt = "sbiad";
if (col != 0 && ibis::gVerbose > 1) {
evt += '[';
evt += col->fullname();
evt += ']';
}
evt += "::write";
if (ibis::gVerbose > 1 && dt != 0) {
evt += '(';
evt += dt;
evt += ')';
}
indexFileName(fnm, dt);
if (fnm.empty()) {
return 0;
}
else if (0 != str && 0 != str->filename() &&
0 == fnm.compare(str->filename())) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- " << evt << " can not overwrite the index file \""
<< fnm << "\" while it is used as a read-only file map";
return 0;
}
else if (fname != 0 && *fname != 0 && 0 == fnm.compare(fname)) {
activate(); // read everything into memory
fname = 0; // break the link with the named file
}
ibis::fileManager::instance().flushFile(fnm.c_str());
if (fname != 0 || str != 0)
activate(); // need all bitvectors
int fdes = UnixOpen(fnm.c_str(), OPEN_WRITENEW, OPEN_FILEMODE);
if (fdes < 0) {
ibis::fileManager::instance().flushFile(fnm.c_str());
fdes = UnixOpen(fnm.c_str(), OPEN_WRITENEW, OPEN_FILEMODE);
if (fdes < 0) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- " << evt << " failed to open \"" << fnm
<< "\" for writing";
return -2;
}
}
IBIS_BLOCK_GUARD(UnixClose, fdes);
#if defined(_WIN32) && defined(_MSC_VER)
(void)_setmode(fdes, _O_BINARY);
#endif
#if defined(HAVE_FLOCK)
ibis::util::flock flck(fdes);
if (flck.isLocked() == false) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- " << evt << " failed to acquire an exclusive lock "
"on file " << fnm << " for writing, another thread must be "
"writing the index now";
return -6;
}
#endif
#ifdef FASTBIT_USE_LONG_OFFSETS
const bool useoffset64 = true;
#else
const bool useoffset64 = (getSerialSize()+8 > 0x80000000UL);
#endif
char header[] = "#IBIS\13\0\0";
header[5] = (char)ibis::index::SBIAD;
header[6] = (char)(useoffset64 ? 8 : 4);
off_t ierr = UnixWrite(fdes, header, 8);
if (ierr < 8) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- " << evt
<< " failed to write the 8-byte header, ierr = " << ierr;
return -3;
}
if (useoffset64)
ierr = ibis::fade::write64(fdes);
else
ierr = ibis::fade::write32(fdes);
if (ierr >= 0) {
#if defined(FASTBIT_SYNC_WRITE)
#if _POSIX_FSYNC+0 > 0
(void) UnixFlush(fdes); // write to disk
#elif defined(_WIN32) && defined(_MSC_VER)
(void) _commit(fdes);
#endif
#endif
LOGGER(ierr >= 0 && ibis::gVerbose > 5)
<< evt << " wrote " << bits.size() << " bitmap"
<< (bits.size()>1?"s":"") << " to " << fnm;
}
return ierr;
} // ibis::sbiad::write
/// This version of the constructor take one pass throught the data. It
/// constructs a ibis::index::VMap first, then construct the sbiad from the
/// VMap. It uses more computer memory than the two-pass version, but will
/// probably run a little faster.
void ibis::sbiad::construct1(const char* f, const uint32_t nbase) {
VMap bmap; // a map between values and their position
try {
mapValues(f, bmap);
}
catch (...) { // need to clean up bmap
LOGGER(ibis::gVerbose >= 0)
<< "sbiad::construct reclaiming storage "
"allocated to bitvectors (" << bmap.size() << ")";
for (VMap::iterator it = bmap.begin(); it != bmap.end(); ++ it)
delete (*it).second;
bmap.clear();
ibis::fileManager::instance().signalMemoryAvailable();
throw;
}
if (bmap.empty()) return;
nrows = (*(bmap.begin())).second->size();
if (nrows != col->partition()->nRows()) {
for (VMap::iterator it = bmap.begin(); it != bmap.end(); ++ it)
delete (*it).second;
bmap.clear();
ibis::fileManager::instance().signalMemoryAvailable();
LOGGER(ibis::gVerbose >= 0)
<< "Warning -- sbiad::construct1 the bitvectors "
"do not have the expected size(" << col->partition()->nRows()
<< "). stopping..";
throw ibis::bad_alloc("incorrect bitvector sizes");
}
// convert bmap into the current data structure
// fill the arrays vals and cnts
const uint32_t card = bmap.size();
vals.reserve(card);
cnts.reserve(card);
for (VMap::const_iterator it = bmap.begin(); it != bmap.end(); ++it) {
vals.push_back((*it).first);
cnts.push_back((*it).second->cnt());
}
// fill the array bases
setBases(bases, card, nbase);
// count the number of bitvectors to genreate
const uint32_t nb = bases.size();
uint32_t nobs = 0;
uint32_t i;
for (i = 0; i < nb; ++i)
nobs += bases[i];
// allocate enough bitvectors in bits
bits.resize(nobs);
for (i = 0; i < nobs; ++i)
bits[i] = 0;
if (ibis::gVerbose > 5) {
col->logMessage("sbiad::construct", "initialized the array of "
"bitvectors, start converting %lu bitmaps into %lu-"
"component range code (with %lu bitvectors)",
static_cast<long unsigned>(vals.size()),
static_cast<long unsigned>(nb),
static_cast<long unsigned>(nobs));
}
// converting to multi-level equality encoding first
i = 0;
for (VMap::const_iterator it = bmap.begin(); it != bmap.end();
++it, ++i) {
uint32_t offset = 0;
uint32_t ii = i;
for (uint32_t j = 0; j < nb; ++j) {
uint32_t k = ii % bases[j];
if (bits[offset+k]) {
*(bits[offset+k]) |= *((*it).second);
}
else {
bits[offset+k] = new ibis::bitvector();
bits[offset+k]->copy(*((*it).second));
// expected to be operated on more than 64 times
if (vals.size() > 64*bases[j])
bits[offset+k]->decompress();
}
ii /= bases[j];
offset += bases[j];
}
delete (*it).second; // no longer need the bitmap
}
for (i = 0; i < nobs; ++i) {
if (bits[i] == 0) {
bits[i] = new ibis::bitvector();
bits[i]->set(0, nrows);
}
}
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 11) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::construct1 converted"
<< bmap.size() << " bitmaps for each distinct value into "
<< bits.size() << bases.size()
<< "-component equality encoded bitmaps";
}
#endif
// sum up the bitvectors according to the interval-encoding
array_t<bitvector*> beq;
beq.swap(bits);
try { // use a try block to ensure the bitvectors in beq are freed
uint32_t ke = 0;
bits.clear();
for (i = 0; i < nb; ++i) {
if (bases[i] > 2) {
nobs = (bases[i] - 1) / 2;
bits.push_back(new ibis::bitvector);
bits.back()->copy(*(beq[ke]));
if (nobs > 64)
bits.back()->decompress();
for (uint32_t j = ke+1; j <= ke+nobs; ++j)
*(bits.back()) |= *(beq[j]);
bits.back()->compress();
for (uint32_t j = 1; j < bases[i]-nobs; ++j) {
bits.push_back(*(bits.back()) - *(beq[ke+j-1]));
*(bits.back()) |= *(beq[ke+j+nobs]);
bits.back()->compress();
}
for (uint32_t j = ke; j < ke+bases[i]; ++j) {
delete beq[j];
beq[j] = 0;
}
}
else {
bits.push_back(beq[ke]);
if (bases[i] > 1) {
delete beq[ke+1];
beq[ke+1] = 0;
}
}
ke += bases[i];
}
}
catch (...) {
LOGGER(ibis::gVerbose > 1)
<< "Warning -- column::[" << col->name()
<< "]::construct1 encountered an exception while converting "
"to inverval encoding, cleaning up ...";
for (uint32_t i = 0; i < beq.size(); ++ i)
delete beq[i];
throw;
}
beq.clear();
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 11) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::construct1 completed "
<< "converting equality encoding to interval encoding";
}
#endif
optionalUnpack(bits, col->indexSpec());
// write out the current content
if (ibis::gVerbose > 8) {
ibis::util::logger lg;
print(lg());
}
} // ibis::sbiad::construct1
/// Assign bit values for a given key value. Assume that the array @c vals
/// is initialized properly, this function converts the value @cval into a
/// set of bits to be stored in the bit vectors contained in @c bits.
///
/// @note to be used by @c construct2 to build a new ibis::sbiad index.
void ibis::sbiad::setBit(const uint32_t i, const double val) {
if (val > vals.back()) return;
if (val < vals[0]) return;
// perform a binary search to locate position of val in vals
uint32_t ii = 0, jj = vals.size() - 1;
uint32_t kk = (ii + jj) / 2;
while (kk > ii) {
if (vals[kk] < val) {
ii = kk;
kk = (kk + jj) / 2;
}
else if (vals[kk] > val) {
jj = kk;
kk = (ii + kk) / 2;
}
else {
ii = kk;
jj = kk;
}
}
if (vals[jj] == val) { // vals[jj] is the same as val
kk = jj;
}
else if (vals[ii] == val) { // vals[ii] is the same as val
kk = ii;
}
else { // doesn't match a know value -- shouldn't be
return;
}
// now we know what bitvectors to modify
const uint32_t nb = bases.size();
uint32_t offset = 0; // offset into bits
for (ii = 0; ii < nb; ++ ii) {
jj = kk % bases[ii];
bits[offset+jj]->setBit(i, 1);
kk /= bases[ii];
offset += bases[ii];
}
} // ibis::sbiad::setBit
/// Generate a new sbiad index by passing through the data twice.
/// - (1) scan the data to generate a list of distinct values and their count.
/// - (2) scan the data a second time to produce the bit vectors.
void ibis::sbiad::construct2(const char* f, const uint32_t nbase) {
{ // a block to limit the scope of hst
histogram hst;
mapValues(f, hst); // scan the data to produce the histogram
if (hst.empty()) // no data, of course no index
return;
// convert histogram into two arrays
const uint32_t nhst = hst.size();
vals.resize(nhst);
cnts.resize(nhst);
histogram::const_iterator it = hst.begin();
for (uint32_t i = 0; i < nhst; ++i) {
vals[i] = (*it).first;
cnts[i] = (*it).second;
++ it;
}
}
// determine the base sizes
setBases(bases, vals.size(), nbase);
const uint32_t nb = bases.size();
int ierr;
// allocate the correct number of bitvectors
uint32_t nobs = 0;
for (uint32_t ii = 0; ii < nb; ++ii)
nobs += bases[ii];
bits.resize(nobs);
for (uint32_t ii = 0; ii < nobs; ++ii)
bits[ii] = new ibis::bitvector;
std::string fnm; // name of the data file
dataFileName(fnm, f);
nrows = col->partition()->nRows();
ibis::bitvector mask;
{ // name of mask file associated with the data file
array_t<ibis::bitvector::word_t> arr;
std::string mname(fnm);
mname += ".msk";
if (ibis::fileManager::instance().getFile(mname.c_str(), arr) == 0)
mask.copy(ibis::bitvector(arr)); // convert arr to a bitvector
else
mask.set(1, nrows); // default mask
}
// need to do different things for different columns
switch (col->type()) {
case ibis::TEXT:
case ibis::UINT: {// unsigned int
array_t<uint32_t> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::INT: {// signed int
array_t<int32_t> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::ULONG: {// unsigned long int
array_t<uint64_t> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::LONG: {// signed long int
array_t<int64_t> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::USHORT: {// unsigned short int
array_t<uint16_t> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::SHORT: {// signed short int
array_t<int16_t> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::UBYTE: {// unsigned char
array_t<unsigned char> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::BYTE: {// signed char
array_t<signed char> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::FLOAT: {// (4-byte) floating-point values
array_t<float> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::DOUBLE: {// (8-byte) floating-point values
array_t<double> val;
if (! fnm.empty())
ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val);
else
ierr = col->getValuesArray(&val);
if (ierr < 0 || val.empty()) {
LOGGER(ibis::gVerbose > 0)
<< "Warning -- sbiad::construct2 failed to retrieve any value";
break;
}
if (val.size() > mask.size()) {
col->logWarning("sbiad::construct", "the data file \"%s\" "
"contains more elements (%lu) then expected "
"(%lu)", fnm.c_str(),
static_cast<long unsigned>(val.size()),
static_cast<long unsigned>(mask.size()));
mask.adjustSize(nrows, nrows);
}
ibis::bitvector::indexSet iset = mask.firstIndexSet();
uint32_t nind = iset.nIndices();
const ibis::bitvector::word_t *iix = iset.indices();
while (nind) {
if (iset.isRange()) { // a range
uint32_t k = (iix[1] < nrows ? iix[1] : nrows);
for (uint32_t i = *iix; i < k; ++i)
setBit(i, val[i]);
}
else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) {
// a list of indices
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
setBit(k, val[k]);
}
}
else {
for (uint32_t i = 0; i < nind; ++i) {
uint32_t k = iix[i];
if (k < nrows)
setBit(k, val[k]);
}
}
++iset;
nind = iset.nIndices();
if (*iix >= nrows)
nind = 0;
} // while (nind)
break;}
case ibis::CATEGORY: // no need for a separate index
col->logWarning("sbiad::ctor", "no need for another index");
return;
default:
col->logWarning("sbiad::ctor", "failed to create bit sbiad index "
"for column type %s",
ibis::TYPESTRING[(int)col->type()]);
return;
}
// make sure all bit vectors are the same size
for (uint32_t i = 0; i < nobs; ++i) {
bits[i]->adjustSize(0, nrows);
}
// sum up the bitvectors according to interval-encoding
array_t<bitvector*> beq;
beq.swap(bits);
try {
uint32_t ke = 0;
bits.clear();
for (uint32_t i = 0; i < nb; ++i) {
if (bases[i] > 2) {
nobs = (bases[i] - 1) / 2;
bits.push_back(new ibis::bitvector);
bits.back()->copy(*(beq[ke]));
if (nobs > 64)
bits.back()->decompress();
for (uint32_t j = ke+1; j <= ke+nobs; ++j)
*(bits.back()) |= *(beq[j]);
bits.back()->compress();
for (uint32_t j = 1; j < bases[i]-nobs; ++j) {
bits.push_back(*(bits.back()) - *(beq[ke+j-1]));
*(bits.back()) |= *(beq[ke+j+nobs]);
bits.back()->compress();
}
for (uint32_t j = ke; j < ke+bases[i]; ++j) {
delete beq[j];
beq[j] = 0;
}
}
else {
bits.push_back(beq[ke]);
if (bases[i] > 1) {
delete beq[ke+1];
beq[ke+1] = 0;
}
}
ke += bases[i];
}
}
catch (...) {
LOGGER(ibis::gVerbose > 1)
<< "Warning -- column::[" << col->name()
<< "]::construct2 encountered an exception while converting "
"to inverval encoding, cleaning up ...";
for (uint32_t i = 0; i < beq.size(); ++ i)
delete beq[i];
throw;
}
beq.clear();
optionalUnpack(bits, col->indexSpec());
// write out the current content
if (ibis::gVerbose > 8) {
ibis::util::logger lg;
print(lg());
}
} // ibis::sbiad::construct2
// a simple function to test the speed of the bitvector operations
void ibis::sbiad::speedTest(std::ostream& out) const {
if (nrows == 0) return;
uint32_t i, nloops = 1000000000 / nrows;
if (nloops < 2) nloops = 2;
ibis::horometer timer;
col->logMessage("sbiad::speedTest", "testing the speed of operator -");
activate(); // need all bitvectors
for (i = 0; i < bits.size()-1; ++i) {
ibis::bitvector* tmp;
tmp = *(bits[i+1]) & *(bits[i]);
delete tmp;
timer.start();
for (uint32_t j=0; j<nloops; ++j) {
tmp = *(bits[i+1]) & *(bits[i]);
delete tmp;
}
timer.stop();
{
ibis::util::ioLock lock;
out << bits[i]->size() << " "
<< static_cast<double>(bits[i]->bytes() + bits[i+1]->bytes())
* 4.0 / static_cast<double>(bits[i]->size()) << " "
<< bits[i]->cnt() << " " << bits[i+1]->cnt() << " "
<< timer.realTime() / nloops << "\n";
}
}
} // ibis::sbiad::speedTest
// the printing function
void ibis::sbiad::print(std::ostream& out) const {
out << "index(multicomponent interval ncomp=" << bases.size() << ") for "
<< col->partition()->name() << '.' << col->name() << " contains "
<< bits.size() << " bitvectors for " << nrows
<< " objects with " << vals.size()
<< " distinct values\nThe base sizes: ";
for (uint32_t i=0; i<bases.size(); ++i)
out << bases[i] << ' ';
const uint32_t nobs = bits.size();
out << "\nbitvector information (number of set bits, number of "
"bytes)\n";
for (uint32_t i=0; i<nobs; ++i) {
if (bits[i]) {
out << i << '\t' << bits[i]->cnt() << '\t'
<< bits[i]->bytes() << "\n";
}
}
if (ibis::gVerbose > 6) { // also print the list of distinct values
out << "distinct values, number of apparences\n";
for (uint32_t i=0; i<vals.size(); ++i) {
out.precision(12);
out << vals[i] << '\t' << cnts[i] << "\n";
}
}
out << "\n";
} // ibis::sbiad::print
// create index based data in dt -- have to start from data directly
long ibis::sbiad::append(const char* dt, const char* df, uint32_t nnew) {
const uint32_t nb = bases.size();
clear(); // clear the current content
construct2(dt, nb); // scan data twice to build the new index
//write(dt); // write out the new content
return nnew;
} // ibis::sbiad::append
// compute the bitvector that represents the answer for x = b
void ibis::sbiad::evalEQ(ibis::bitvector& res, uint32_t b) const {
#if DEBUG+0 > 0 || _DEBUG+0 > 0
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalEQ(" << b << ")...";
#endif
if (b >= vals.size()) {
res.set(0, nrows);
}
else {
uint32_t nb2;
uint32_t offset = 0;
res.set(1, nrows);
for (uint32_t i = 0; i < bases.size(); ++i) {
uint32_t k = b % bases[i];
if (bases[i] > 2) {
ibis::bitvector *tmp;
nb2 = (bases[i]-1) / 2;
if (k+1+nb2 < bases[i]) {
if (bits[offset+k] == 0)
activate(offset+k);
if (bits[offset+k]) {
if (bits[offset+k+1] == 0)
activate(offset+k+1);
if (bits[offset+k+1])
tmp = *(bits[offset+k]) -
*(bits[offset+k+1]);
else
tmp = new ibis::bitvector(*(bits[offset+k]));
}
else {
tmp = 0;
}
}
else if (k > nb2) {
if (bits[offset+k-nb2] == 0)
activate(offset+k-nb2);
if (bits[offset+k-nb2]) {
if (bits[offset+k-nb2-1] == 0)
activate(offset+k-nb2-1);
if (bits[offset+k-nb2-1])
tmp = *(bits[offset+k-nb2]) -
*(bits[offset+k-nb2-1]);
else
tmp = new ibis::bitvector(*(bits[offset+k-nb2]));
}
else {
tmp = 0;
}
}
else {
if (bits[offset] == 0)
activate(offset);
if (bits[offset+k] == 0)
activate(offset+k);
if (bits[offset] && bits[offset+k])
tmp = *(bits[offset]) & *(bits[offset+k]);
else
tmp = 0;
}
if (tmp)
res &= *tmp;
else
res.set(0, res.size());
delete tmp;
offset += bases[i] - nb2;
}
else {
if (bits[offset] == 0)
activate(offset);
if (0 == k) {
if (bits[offset])
res &= *(bits[offset]);
else
res.set(0, res.size());
}
else if (bits[offset]) {
res -= *(bits[offset]);
}
++ offset;
}
b /= bases[i];
}
}
} // evalEQ
// compute the bitvector that is the answer for the query x <= b
void ibis::sbiad::evalLE(ibis::bitvector& res, uint32_t b) const {
#if DEBUG+0 > 0 || _DEBUG+0 > 0
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLE(" << b << ")...";
#endif
if (b+1 >= vals.size()) {
res.set(1, nrows);
}
else {
uint32_t k, nb2;
uint32_t i = 0; // index into components
uint32_t offset = 0;
// skip till the first component that isn't the maximum value
while (i < bases.size() && b % bases[i] == bases[i]-1) {
offset += (bases[i]>2 ? bases[i]-(bases[i]-1)/2 : 1);
b /= bases[i];
++ i;
}
// copy the first non-maximum component
if (i < bases.size()) {
k = b % bases[i];
if (bits[offset] == 0)
activate(offset);
if (bits[offset])
res.copy(*(bits[offset]));
else
res.set(0, nrows);
if (bases[i] > 2) {
nb2 = (bases[i]-1)/2;
if (k < nb2) {
const uint32_t j = offset+k+1;
if (bits[j] == 0)
activate(j);
if (bits[j])
res -= *(bits[j]);
}
else if (k > nb2) {
const uint32_t j = offset+k-nb2;
if (bits[j] == 0)
activate(j);
if (bits[j])
res |= *(bits[j]);
}
offset += bases[i] - nb2;
}
else {
if (k != 0)
res.flip();
++ offset;
}
b /= bases[i];
}
else {
res.set(1, nrows);
}
++ i;
// deal with the remaining components
while (i < bases.size()) {
k = b % bases[i];
nb2 = (bases[i] - 1) / 2;
if (bases[i] > 2) {
if (k < nb2) {
ibis::bitvector* tmp;
if (bits[offset+k] == 0)
activate(offset+k);
if (bits[offset+k])
res &= *(bits[offset+k]);
else
res.set(0, res.size());
if (bits[offset+k+1] == 0)
activate(offset+k+1);
if (bits[offset+k+1])
res -= *(bits[offset+k+1]);
if (k > 0) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset]) {
if (bits[offset+k]) {
tmp = *(bits[offset]) - *(bits[offset+k]);
res |= *tmp;
delete tmp;
}
else {
res |= *(bits[offset]);
}
}
}
}
else if (k > nb2) {
if (k+1 < bases[i]) {
if (bits[offset+k-nb2] == 0)
activate(offset+k-nb2);
if (bits[offset+k-nb2])
res &= *(bits[offset+k-nb2]);
else
res.set(0, res.size());
}
if (bits[offset+k-nb2-1] == 0)
activate(offset+k-nb2-1);
if (bits[offset+k-nb2-1])
res |= *(bits[offset+k-nb2-1]);
if (k > nb2+1) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset])
res |= *(bits[offset]);
}
}
else { // k = nb2
if (bits[offset] == 0)
activate(offset);
if (bits[offset]) {
if (bits[offset+k] == 0)
activate(offset+k);
if (bits[offset+k]) {
res &= *(bits[offset]);
ibis::bitvector* tmp = *(bits[offset]) -
*(bits[offset+k]);
res |= *tmp;
delete tmp;
}
else {
res.copy(*(bits[offset]));
}
}
else {
res.set(0, res.size());
}
}
offset += (bases[i] - nb2);
}
else {
if (bits[offset] == 0)
activate(offset);
if (bits[offset]) {
if (k == 0)
res &= *(bits[offset]);
else
res |= *(bits[offset]);
}
else if (k == 0) {
res.set(0, res.size());
}
++ offset;
}
b /= bases[i];
++ i;
}
}
} // evalLE
// compute the bitvector that answers the query b0 < x <= b1
void ibis::sbiad::evalLL(ibis::bitvector& res,
uint32_t b0, uint32_t b1) const {
#if DEBUG+0 > 0 || _DEBUG+0 > 0
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLL(" << b0 << ", " << b1 << ")...";
#endif
if (b0 >= b1) { // no hit
res.set(0, nrows);
}
else if (b1+1 >= vals.size()) { // x > b0
evalLE(res, b0);
res.flip();
}
else { // the intended general case
// res temporarily stores the result of x <= b1
ibis::bitvector low; // x <= b0
uint32_t k0, k1, nb2;
uint32_t i = 0;
uint32_t offset = 0;
// skip till the first component that isn't the maximum value
while (i < bases.size()) {
k0 = b0 % bases[i];
k1 = b1 % bases[i];
if (k0 == bases[i]-1 && k1 == bases[i]-1) {
offset += (bases[i]>2 ? bases[i] - (bases[i]-1)/2 : 1);
b0 /= bases[i];
b1 /= bases[i];
++ i;
}
else {
break;
}
}
// the first non-maximum component
if (i < bases.size()) {
k0 = b0 % bases[i];
k1 = b1 % bases[i];
if (bases[i] > 2) {
nb2 = (bases[i]-1) / 2;
if (k0+1 < bases[i]) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset])
low.copy(*(bits[offset]));
else
low.set(0, nrows);
if (k0 < nb2) {
if (bits[offset+k0+1] == 0)
activate(offset+k0+1);
if (bits[offset+k0+1] != 0)
low -= *(bits[offset+k0+1]);
}
else if (k0 > nb2) {
if (bits[offset+k0-nb2] == 0)
activate(offset+k0-nb2);
if (bits[offset+k0-nb2] != 0)
low |= *(bits[offset+k0-nb2]);
}
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 30 ||
(low.bytes() < (1U << ibis::gVerbose))) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLL: low "
"(component[" << i << "] <= " << k0 << ") "
<< low;
}
#endif
}
else {
low.set(1, nrows);
}
if (k1+1 < bases[i]) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset])
res.copy(*(bits[offset]));
else
res.set(0, nrows);
if (k1 < nb2) {
if (bits[offset+k1+1] == 0)
activate(offset+k1+1);
if (bits[offset+k1+1] != 0)
res -= *(bits[offset+k1+1]);
}
else if (k1 > nb2) {
if (bits[offset+k1-nb2] == 0)
activate(offset+k1-nb2);
if (bits[offset+k1-nb2] != 0)
res |= *(bits[offset+k1-nb2]);
}
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 30 ||
(res.bytes() < (1U << ibis::gVerbose))) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLL: high "
"(component[" << i << "] <= " << k1 << ") "
<< res;
}
#endif
}
else {
res.set(1, nrows);
}
offset += bases[i] - nb2;
}
else { // bases[i] >= 2
if (k0 == 0) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0)
low = *(bits[offset]);
else
low.set(0, nrows);
}
else {
low.set(1, nrows);
}
if (k1 == 0) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0)
res = *(bits[offset]);
else
res.set(0, nrows);
}
else {
res.set(1, nrows);
}
++ offset;
}
b0 /= bases[i];
b1 /= bases[i];
}
else {
res.set(0, nrows);
}
++ i;
// deal with the remaining components
while (i < bases.size()) {
ibis::bitvector* tmp;
if (b1 > b0) { // low and res has to be separated
k0 = b0 % bases[i];
k1 = b1 % bases[i];
b0 /= bases[i];
b1 /= bases[i];
if (bases[i] > 2) {
nb2 = (bases[i] - 1) / 2;
// update low according to k0
if (k0+nb2+1 < bases[i]) {
if (bits[offset+k0] == 0)
activate(offset+k0);
if (bits[offset+k0] != 0)
low &= *(bits[offset+k0]);
else
low.set(0, low.size());
if (bits[offset+k0+1] == 0)
activate(offset+k0+1);
if (bits[offset+k0+1] != 0)
low -= *(bits[offset+k0+1]);
if (k0 > 0) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0) {
if (bits[offset+k0] == 0)
activate(offset+k0);
if (bits[offset+k0] != 0) {
tmp = *(bits[offset])
- *(bits[offset+k0]);
low |= *tmp;
delete tmp;
}
}
else {
low |= *(bits[offset]);
}
}
}
else if (k0 > nb2) {
if (k0+1 < bases[i]) {
if (bits[offset+k0-nb2] == 0)
activate(offset+k0-nb2);
if (bits[offset+k0-nb2] != 0)
low &= *(bits[offset+k0-nb2]);
else
low.set(0, low.size());
}
if (bits[offset+k0-nb2-1] == 0)
activate(offset+k0-nb2-1);
if (bits[offset+k0-nb2-1] != 0)
low |= *(bits[offset+k0-nb2-1]);
if (k0 > nb2+1) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0)
low |= *(bits[offset]);
}
}
else { // k0 = nb2
// res &= (bits[offset] & bits[offset+k0])
// res |= (bits[offset] - bits[offset+k0])
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0) {
if (bits[offset+k0] == 0)
activate(offset+k0);
if (bits[offset+k0]) {
low &= *(bits[offset]);
tmp = *(bits[offset]) - *(bits[offset+k0]);
low |= *tmp;
delete tmp;
}
else {
low.copy(*(bits[offset]));
}
}
else {
low.set(0, low.size());
}
}
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 30 ||
(low.bytes() < (1U << ibis::gVerbose))) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLL: low "
"(component[" << i << "] <= " << k0 << ") "
<< low;
}
#endif
// update res according to k1
if (k1+nb2+1 < bases[i]) {
if (bits[offset+k1] == 0)
activate(offset+k1);
if (bits[offset+k1] != 0)
res &= *(bits[offset+k1]);
else
res.set(0, res.size());
if (bits[offset+k1+1] == 0)
activate(offset+k1+1);
if (bits[offset+k1+1] != 0)
res -= *(bits[offset+k1+1]);
if (k1 > 0) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset]) {
if (bits[offset+k1]) {
tmp = *(bits[offset])
- *(bits[offset+k1]);
res |= *tmp;
delete tmp;
}
else {
res |= *(bits[offset]);
}
}
}
}
else if (k1 > nb2) {
if (k1+1 < bases[i]) {
if (bits[offset+k1-nb2] == 0)
activate(offset+k1-nb2);
if (bits[offset+k1-nb2] != 0)
res &= *(bits[offset+k1-nb2]);
else
res.set(0, res.size());
}
if (bits[offset+k1-nb2-1] == 0)
activate(offset+k1-nb2-1);
if (bits[offset+k1-nb2-1] != 0)
res |= *(bits[offset+k1-nb2-1]);
if (k1 > nb2+1) {
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0)
res |= *(bits[offset]);
}
}
else { // k1 = nb2
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0) {
if (bits[offset+k1] == 0)
activate(offset+k1);
if (bits[offset+k1] != 0) {
res &= *(bits[offset]);
tmp = *(bits[offset]) - *(bits[offset+k1]);
res |= *tmp;
delete tmp;
}
else {
res.copy(*bits[offset]);
}
}
else {
res.set(0, res.size());
}
}
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 30 ||
(res.bytes() < (1U << ibis::gVerbose))) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLL: high "
"(component[" << i << "] <= " << k1 << ") "
<< res;
}
#endif
offset += (bases[i] - nb2);
}
else { // bases[i] <= 2
if (bits[offset] == 0)
activate(offset);
if (bits[offset]) {
if (k0 == 0)
low &= *(bits[offset]);
else
low |= *(bits[offset]);
if (k1 == 0)
res &= *(bits[offset]);
else
res |= *(bits[offset]);
}
else {
if (k0 == 0)
low.set(0, low.size());
if (k1 == 0)
res.set(0, low.size());
}
}
}
else { // the more significant components are the same
res -= low;
low.clear(); // no longer need low
while (i < bases.size()) {
k1 = b1 % bases[i];
if (bases[i] > 2) {
nb2 = (bases[i]-1) / 2;
if (k1+1+nb2 < bases[i]) {
if (bits[offset+k1] == 0)
activate(offset+k1);
if (bits[offset+k1] != 0) {
if (bits[offset+k1+1] == 0)
activate(offset+k1+1);
if (bits[offset+k1+1] != 0)
tmp = *(bits[offset+k1]) -
*(bits[offset+k1+1]);
else
tmp = new
ibis::bitvector(*(bits[offset+k1]));
}
else {
tmp = 0;
}
}
else if (k1 > nb2) {
if (bits[offset+k1-nb2] == 0)
activate(offset+k1-nb2);
if (bits[offset+k1-nb2] != 0) {
if (bits[offset+k1-nb2-1] == 0)
activate(offset+k1-nb2-1);
if (bits[offset+k1-nb2-1] != 0)
tmp = *(bits[offset+k1-nb2]) -
*(bits[offset+k1-nb2-1]);
else
tmp = new ibis::bitvector
(*(bits[offset+k1-nb2]));
}
else {
tmp = 0;
}
}
else { // k1 = nb2
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0) {
if (bits[offset+k1] == 0)
activate(offset+k1);
if (bits[offset+k1] != 0)
tmp = *(bits[offset]) &
*(bits[offset+k1]);
else
tmp = new
ibis::bitvector(*(bits[offset]));
}
else {
tmp = 0;
}
}
if (tmp) {
res &= *tmp;
delete tmp;
}
else {
res.set(0, res.size());
}
offset += bases[i] - nb2;
}
else { // bases[i] <= 2
if (bits[offset] == 0)
activate(offset);
if (bits[offset] != 0) {
if (k1 == 0)
res &= *(bits[offset]);
else
res -= *(bits[offset]);
}
else if (k1 == 0) {
res.set(0, res.size());
}
++ offset;
}
#if DEBUG+0 > 0 || _DEBUG+0 > 0
if (ibis::gVerbose > 30 ||
(res.bytes() < (1U << ibis::gVerbose))) {
LOGGER(ibis::gVerbose >= 0)
<< "DEBUG -- sbiad::evalLL: res "
"(component[" << i << "] <= " << k1 << ") "
<< res;
}
#endif
b1 /= bases[i];
++ i;
} // while (i < bases.size())
}
++ i;
}
if (low.size() == res.size()) { // subtract low from res
res -= low;
low.clear();
}
}
} // evalLL
// Evaluate the query expression
long ibis::sbiad::evaluate(const ibis::qContinuousRange& expr,
ibis::bitvector& lower) const {
if (bits.empty()) {
lower.set(0, nrows);
return 0;
}
// values in the range [hit0, hit1) satisfy the query expression
uint32_t hit0, hit1;
locate(expr, hit0, hit1);
// actually accumulate the bits in the range [hit0, hit1)
if (hit1 <= hit0) {
lower.set(0, nrows);
}
else if (hit0+1 == hit1) { // equal to one single value
evalEQ(lower, hit0);
}
else if (hit0 == 0) { // < hit1
evalLE(lower, hit1-1);
}
else if (hit1 == vals.size()) { // >= hit0 (as NOT (<= hit0-1))
evalLE(lower, hit0-1);
lower.flip();
}
else { // need to go through most bitvectors four times
evalLL(lower, hit0-1, hit1-1); // (hit0-1, hit1-1]
}
return lower.cnt();
} // ibis::sbiad::evaluate
// Evaluate a set of discrete range conditions.
long ibis::sbiad::evaluate(const ibis::qDiscreteRange& expr,
ibis::bitvector& lower) const {
const ibis::array_t<double>& varr = expr.getValues();
lower.set(0, nrows);
for (unsigned i = 0; i < varr.size(); ++ i) {
unsigned int itmp = locate(varr[i]);
if (itmp > 0 && vals[itmp-1] == varr[i]) {
-- itmp;
ibis::bitvector tmp;
evalEQ(tmp, itmp);
if (tmp.size() == lower.size())
lower |= tmp;
}
}
return lower.cnt();
} // ibis::sbiad::evaluate
| 27.310766 | 79 | 0.538201 | nporsche |
e4dc1de71d07d72be3859246a17fed274a348476 | 1,317 | hpp | C++ | swizzle/lexer/FileInfo.hpp | SenorAgosto/Swizzle | 52c221de9fa293b0006f07a41b140d2afcc1a9ed | [
"BSD-4-Clause"
] | null | null | null | swizzle/lexer/FileInfo.hpp | SenorAgosto/Swizzle | 52c221de9fa293b0006f07a41b140d2afcc1a9ed | [
"BSD-4-Clause"
] | null | null | null | swizzle/lexer/FileInfo.hpp | SenorAgosto/Swizzle | 52c221de9fa293b0006f07a41b140d2afcc1a9ed | [
"BSD-4-Clause"
] | null | null | null | #pragma once
#include <swizzle/lexer/LineInfo.hpp>
#include <cstddef>
#include <string>
namespace swizzle { namespace lexer {
class Token;
}}
namespace swizzle { namespace lexer {
// Information about where a token starts and ends
class FileInfo
{
public:
FileInfo();
FileInfo(const std::string& filename);
FileInfo(const std::string& filename, const LineInfo& start);
FileInfo(const std::string& filename, const LineInfo& start, const LineInfo& end);
const std::string& filename() const { return filename_; }
const LineInfo& end() const { return end_; }
LineInfo& end() { return end_; }
const LineInfo& start() const { return start_; }
LineInfo& start() { return start_; }
void incrementLine() { end_.incrementLine(); }
void incrementColumn() { end_.incrementColumn(); }
void incrementColumnBy(const std::size_t count) { end_.incrementColumnBy(count); }
void advanceBy(const char c);
void advanceBy(const Token& token);
void advanceTo(const FileInfo& info);
bool empty() const { return start_ == end_; }
private:
std::string filename_;
LineInfo start_;
LineInfo end_;
};
}}
| 27.4375 | 90 | 0.607441 | SenorAgosto |
e4de834d0e9f197ec43b12a7b93efad5ce83e3bc | 2,627 | cpp | C++ | src/utils/fileio/SkeletonFile.cpp | Ibujah/compactskel | 8a54b5f0123490c4e8120537ae2b56d5ec2a34c9 | [
"MIT"
] | 4 | 2019-04-15T08:50:30.000Z | 2021-02-03T10:44:03.000Z | src/utils/fileio/SkeletonFile.cpp | Ibujah/compactskel | 8a54b5f0123490c4e8120537ae2b56d5ec2a34c9 | [
"MIT"
] | null | null | null | src/utils/fileio/SkeletonFile.cpp | Ibujah/compactskel | 8a54b5f0123490c4e8120537ae2b56d5ec2a34c9 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2016 Bastien Durix
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* \file SkeletonFile.h
* \brief Input/output functions for skeletons
* \author Bastien Durix
*/
#include "SkeletonFile.h"
#include <fstream>
namespace fileio
{
void writeSkeleton(const skeleton::GraphSkel2d::Ptr grskel,
const std::map<unsigned int, std::vector<unsigned int> >& deldat,
const std::string& nodname, const std::string& edgname, const std::string& delname)
{
std::ofstream fnod(nodname);
std::ofstream fedg(edgname);
std::ofstream fdel(delname);
if(!fnod || !fedg || !fdel)
{
std::cout << "Problem" << std::endl;
return;
}
std::list<unsigned int> nods;
grskel->getAllNodes(nods);
for(std::list<unsigned int>::iterator it = nods.begin(); it != nods.end(); it++)
{
mathtools::geometry::euclidian::HyperSphere<2> cir1 = grskel->getNode<mathtools::geometry::euclidian::HyperSphere<2> >(*it);
Eigen::Vector2d pt = cir1.getCenter().getCoords();
double rad = cir1.getRadius();
fnod << pt.x() << " " << pt.y() << " " << rad << std::endl;
}
std::list<std::pair<unsigned int,unsigned int> > edges;
grskel->getAllEdges(edges);
for(std::list<std::pair<unsigned int,unsigned int> >::iterator it = edges.begin(); it != edges.end(); it++)
{
fedg << it->first << " " << it->second << std::endl;
}
for(auto it : deldat)
{
fdel << it.first << " : ";
for(auto itn : it.second)
fdel << itn << ", ";
fdel << std::endl;
}
fnod.close();
fedg.close();
fdel.close();
}
}
| 31.650602 | 126 | 0.669204 | Ibujah |
e4dfdfde7542f9293ddd30e45076d4a208f9cc6b | 524 | cpp | C++ | cpp/0238_productExceptSelf.cpp | linhx25/leetcode | 9cf1d6d2372fd8777825c8107780b7f3c934fe20 | [
"MIT"
] | 1 | 2021-04-16T12:54:56.000Z | 2021-04-16T12:54:56.000Z | cpp/0238_productExceptSelf.cpp | linhx25/leetcode | 9cf1d6d2372fd8777825c8107780b7f3c934fe20 | [
"MIT"
] | null | null | null | cpp/0238_productExceptSelf.cpp | linhx25/leetcode | 9cf1d6d2372fd8777825c8107780b7f3c934fe20 | [
"MIT"
] | 1 | 2021-04-26T13:20:41.000Z | 2021-04-26T13:20:41.000Z | // 1.最简单做法:遍历一遍得到连乘,每个元素单独除一遍即可;
// 2.不能使用除法:
// (1)先遍历一遍,得到每个位置的左连乘(不包括该位置)
// (2)从右边开始遍历,获得右连乘,随后更新每个位置的左连乘
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res(nums.size());
int right=1;
res[0]=1;
for(auto i=1;i<nums.size();i++)
res[i]=res[i-1]*nums[i-1];
for(auto i=nums.size()-2;i>0;i--)
{
right*=nums[i+1];
res[i]*=right;
}
res[0]=right*nums[1];
return res;
}
};
| 23.818182 | 54 | 0.51145 | linhx25 |
e4e2f28c025a45a5b1d530ad4f16d9ea7beea7a6 | 928 | cpp | C++ | src/examples/textured_triangle/textured_triangle_shader.cpp | DavidSlayback/megaverse | 6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc | [
"MIT"
] | 149 | 2021-06-09T01:28:57.000Z | 2022-03-30T20:31:25.000Z | src/examples/textured_triangle/textured_triangle_shader.cpp | DavidSlayback/megaverse | 6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc | [
"MIT"
] | 4 | 2021-06-30T17:06:18.000Z | 2022-02-17T21:58:13.000Z | src/examples/textured_triangle/textured_triangle_shader.cpp | DavidSlayback/megaverse | 6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc | [
"MIT"
] | 13 | 2021-07-10T06:49:24.000Z | 2022-03-08T05:11:35.000Z | #include "textured_triangle_shader.hpp"
#include <Corrade/Containers/Reference.h>
#include <Corrade/Utility/Resource.h>
#include <Magnum/GL/Context.h>
#include <Magnum/GL/Shader.h>
#include <Magnum/GL/Version.h>
namespace Magnum {
TexturedTriangleShader::TexturedTriangleShader() {
MAGNUM_ASSERT_GL_VERSION_SUPPORTED(GL::Version::GL330);
const Utility::Resource rs{"textured-triangle-data"};
GL::Shader vert{GL::Version::GL330, GL::Shader::Type::Vertex};
GL::Shader frag{GL::Version::GL330, GL::Shader::Type::Fragment};
vert.addSource(rs.get("textured_triangle_shader.vert"));
frag.addSource(rs.get("textured_triangle_shader.frag"));
CORRADE_INTERNAL_ASSERT_OUTPUT(GL::Shader::compile({vert, frag}));
attachShaders({vert, frag});
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
_colorUniform = uniformLocation("color");
setUniform(uniformLocation("textureData"), TextureUnit);
}
} | 28.121212 | 70 | 0.738147 | DavidSlayback |
e4e3ca21e90fde907f4e39a80b029a65935ce82f | 954 | cpp | C++ | emulator/Hardware.cpp | arturmazurek/dcpu | 0647fc521b04ba71b793eedeb62c7add3111576c | [
"MIT"
] | null | null | null | emulator/Hardware.cpp | arturmazurek/dcpu | 0647fc521b04ba71b793eedeb62c7add3111576c | [
"MIT"
] | null | null | null | emulator/Hardware.cpp | arturmazurek/dcpu | 0647fc521b04ba71b793eedeb62c7add3111576c | [
"MIT"
] | null | null | null | //
// Hardware.cpp
// dcpu
//
// Created by Artur Mazurek on 08.09.2013.
// Copyright (c) 2013 Artur Mazurek. All rights reserved.
//
#include "Hardware.h"
#include <cassert>
#include "Core.h"
#include "DCPUException.h"
Hardware::Hardware(uint32_t hardwareId, uint16_t version, uint32_t manufacturer) :
m_hardwareId{hardwareId}, m_version{version}, m_manufacturer{manufacturer} {
}
void Hardware::attachedTo(Core* ownerCore) {
m_ownerCore = ownerCore;
}
void Hardware::receiveInterrupt() {
assert(m_ownerCore);
if(!m_ownerCore) {
throw UnattachedHardware("Sending interrupt to unattached hardware");
}
doReceiveInterrupt(*m_ownerCore);
}
void Hardware::sendInterrupt(uint16_t message) const {
}
uint32_t Hardware::hardwareId() const {
return m_hardwareId;
}
uint16_t Hardware::version() const {
return m_version;
}
uint32_t Hardware::manufacturer() const {
return m_manufacturer;
} | 19.875 | 82 | 0.708595 | arturmazurek |
e4e62835e3211e21adfb136995ef2f08a3b6901d | 1,397 | cpp | C++ | snippets/cpp/VS_Snippets_CLR_System/system.Runtime.InteropServices.TypelibConverter.ConvertAssemblyToTypelib1/CPP/convert2.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2020-02-22T09:30:21.000Z | 2021-08-02T23:44:31.000Z | snippets/cpp/VS_Snippets_CLR_System/system.Runtime.InteropServices.TypelibConverter.ConvertAssemblyToTypelib1/CPP/convert2.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 555 | 2019-09-23T22:22:58.000Z | 2021-07-15T18:51:12.000Z | snippets/cpp/VS_Snippets_CLR_System/system.Runtime.InteropServices.TypelibConverter.ConvertAssemblyToTypelib1/CPP/convert2.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 3 | 2020-01-29T16:31:15.000Z | 2021-08-24T07:00:15.000Z |
// <snippet1>
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Runtime::InteropServices;
[ComImport,
GuidAttribute("00020406-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType::InterfaceIsIUnknown),
ComVisible(false)]
interface class UCOMICreateITypeLib
{
void CreateTypeInfo();
void SetName();
void SetVersion();
void SetGuid();
void SetDocString();
void SetHelpFileName();
void SetHelpContext();
void SetLcid();
void SetLibFlags();
void SaveAllChanges();
};
public ref class ConversionEventHandler: public ITypeLibExporterNotifySink
{
public:
virtual void ReportEvent( ExporterEventKind eventKind, int eventCode, String^ eventMsg )
{
// Handle the warning event here.
}
virtual Object^ ResolveRef( Assembly^ a )
{
// Resolve the reference here and return a correct type library.
return nullptr;
}
};
int main()
{
Assembly^ a = Assembly::LoadFrom( "MyAssembly.dll" );
TypeLibConverter^ converter = gcnew TypeLibConverter;
ConversionEventHandler^ eventHandler = gcnew ConversionEventHandler;
UCOMICreateITypeLib^ typeLib = dynamic_cast<UCOMICreateITypeLib^>(converter->ConvertAssemblyToTypeLib( a, "MyTypeLib.dll", static_cast<TypeLibExporterFlags>(0), eventHandler ));
typeLib->SaveAllChanges();
}
// </snippet1>
| 27.94 | 180 | 0.745168 | BohdanMosiyuk |
e4e7b247b69c9c62b595db1d8ecd9171b15a29fd | 1,094 | cc | C++ | cpp/Offline_sampling.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | cpp/Offline_sampling.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | cpp/Offline_sampling.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | // Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <iostream>
#include <random>
#include <vector>
#include "./Offline_sampling.h"
using std::cout;
using std::default_random_engine;
using std::endl;
using std::random_device;
using std::swap;
using std::uniform_int_distribution;
using std::vector;
int main(int argc, char* argv[]) {
int n, k;
default_random_engine gen((random_device())());
if (argc == 2) {
n = atoi(argv[1]);
uniform_int_distribution<int> dis(1, n);
k = dis(gen);
} else if (argc == 3) {
n = atoi(argv[1]);
k = atoi(argv[2]);
} else {
uniform_int_distribution<int> n_dis(1, 1000000);
n = n_dis(gen);
uniform_int_distribution<int> k_dis(1, n);
k = k_dis(gen);
}
vector<int> A(n);
iota(A.begin(), A.end(), 0);
cout << n << ' ' << k << endl;
RandomSampling(k, &A);
for (int i = 0; i < A.size(); i++) {
cout << i << ":" << A[i] << " ";
}
cout << endl;
return 0;
}
| 24.311111 | 78 | 0.571298 | iskhanba |
e4e98a060da8913c927916cc83c32fbb5b508fe6 | 4,339 | cpp | C++ | 10-11/VmWriter.cpp | jomiller/nand2tetris | 4be20996e1b5185654ef4de5234a9543f957d6fc | [
"MIT"
] | 1 | 2020-10-13T07:06:37.000Z | 2020-10-13T07:06:37.000Z | 10-11/VmWriter.cpp | jomiller/nand2tetris | 4be20996e1b5185654ef4de5234a9543f957d6fc | [
"MIT"
] | null | null | null | 10-11/VmWriter.cpp | jomiller/nand2tetris | 4be20996e1b5185654ef4de5234a9543f957d6fc | [
"MIT"
] | null | null | null | /*
* This file is part of Nand2Tetris.
*
* Copyright © 2013-2020 Jonathan Miller
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "VmWriter.h"
#include <Assert.h>
#include <Util.h>
#include <frozen/unordered_map.h>
#include <string_view>
#include <utility>
n2t::VmWriter::VmWriter(std::filesystem::path filename) :
m_filename{std::move(filename)},
m_file{m_filename.string().data()}
{
throwUnless<std::runtime_error>(m_file.good(), "Could not open output file ({})", m_filename.string());
}
n2t::VmWriter::~VmWriter() noexcept
{
try
{
if (!m_closed)
{
m_file.close();
std::filesystem::remove(m_filename);
}
}
catch (...)
{
}
}
void n2t::VmWriter::writePush(SegmentType segment, int16_t index)
{
m_file << "push " << toString(segment) << " " << index << '\n';
}
void n2t::VmWriter::writePop(SegmentType segment, int16_t index)
{
m_file << "pop " << toString(segment) << " " << index << '\n';
}
void n2t::VmWriter::writeArithmetic(ArithmeticCommand command)
{
// clang-format off
static constexpr auto commands = frozen::make_unordered_map<ArithmeticCommand, std::string_view>(
{
{ArithmeticCommand::Add, "add"},
{ArithmeticCommand::Sub, "sub"},
{ArithmeticCommand::Neg, "neg"},
{ArithmeticCommand::And, "and"},
{ArithmeticCommand::Or, "or"},
{ArithmeticCommand::Not, "not"},
{ArithmeticCommand::Eq, "eq"},
{ArithmeticCommand::Gt, "gt"},
{ArithmeticCommand::Lt, "lt"}
});
// clang-format on
const auto iter = commands.find(command); // NOLINT(readability-qualified-auto)
N2T_ASSERT((iter != commands.end()) && "Invalid arithmetic command");
m_file << iter->second << '\n';
}
void n2t::VmWriter::writeLabel(const std::string& label)
{
m_file << "label " << label << '\n';
}
void n2t::VmWriter::writeGoto(const std::string& label)
{
m_file << "goto " << label << '\n';
}
void n2t::VmWriter::writeIf(const std::string& label)
{
m_file << "if-goto " << label << '\n';
}
void n2t::VmWriter::writeFunction(const std::string& functionName, int16_t numLocals)
{
m_file << "function " << functionName << " " << numLocals << '\n';
}
void n2t::VmWriter::writeReturn()
{
m_file << "return\n";
}
void n2t::VmWriter::writeCall(const std::string& functionName, int16_t numArguments)
{
m_file << "call " << functionName << " " << numArguments << '\n';
}
void n2t::VmWriter::close()
{
m_file.close();
m_closed = true;
}
std::string_view n2t::VmWriter::toString(SegmentType segment)
{
// clang-format off
static constexpr auto segments = frozen::make_unordered_map<SegmentType, std::string_view>(
{
{SegmentType::Constant, "constant"},
{SegmentType::Static, "static"},
{SegmentType::Pointer, "pointer"},
{SegmentType::Temp, "temp"},
{SegmentType::Argument, "argument"},
{SegmentType::Local, "local"},
{SegmentType::This, "this"},
{SegmentType::That, "that"}
});
// clang-format on
const auto iter = segments.find(segment); // NOLINT(readability-qualified-auto)
N2T_ASSERT((iter != segments.end()) && "Invalid memory segment");
return iter->second;
}
| 29.924138 | 107 | 0.651302 | jomiller |
e4f2bb925d5c929687a8c10830eae36f2b56c563 | 66,448 | cpp | C++ | Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp | gSpera/serenity | 5eb0f63c5463ad69286868978ce65fa4705a457c | [
"BSD-2-Clause"
] | 2 | 2022-02-08T09:18:50.000Z | 2022-02-21T17:57:23.000Z | Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp | gSpera/serenity | 5eb0f63c5463ad69286868978ce65fa4705a457c | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp | gSpera/serenity | 5eb0f63c5463ad69286868978ce65fa4705a457c | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, Andreas Kling <[email protected]>
* Copyright (c) 2021, Linus Groh <[email protected]>
* Copyright (c) 2021, Gunnar Beutner <[email protected]>
* Copyright (c) 2021, Marcin Gasperowicz <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Format.h>
#include <LibJS/AST.h>
#include <LibJS/Bytecode/Generator.h>
#include <LibJS/Bytecode/Instruction.h>
#include <LibJS/Bytecode/Op.h>
#include <LibJS/Bytecode/Register.h>
#include <LibJS/Bytecode/StringTable.h>
#include <LibJS/Runtime/Environment.h>
namespace JS {
Bytecode::CodeGenerationErrorOr<void> ASTNode::generate_bytecode(Bytecode::Generator&) const
{
return Bytecode::CodeGenerationError {
this,
"Missing generate_bytecode()"sv,
};
}
Bytecode::CodeGenerationErrorOr<void> ScopeNode::generate_bytecode(Bytecode::Generator& generator) const
{
Optional<Bytecode::CodeGenerationError> maybe_error;
size_t pushed_scope_count = 0;
auto const failing_completion = Completion(Completion::Type::Throw, {}, {});
if (is<BlockStatement>(*this) || is<SwitchStatement>(*this)) {
// Perform the steps of BlockDeclarationInstantiation.
if (has_lexical_declarations()) {
generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
pushed_scope_count++;
}
(void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
auto is_constant_declaration = declaration.is_constant_declaration();
declaration.for_each_bound_name([&](auto const& name) {
auto index = generator.intern_identifier(name);
if (is_constant_declaration || !generator.has_binding(index)) {
generator.register_binding(index);
generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
}
});
if (is<FunctionDeclaration>(declaration)) {
auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
auto const& name = function_declaration.name();
auto index = generator.intern_identifier(name);
generator.emit<Bytecode::Op::NewFunction>(function_declaration);
generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
}
return {};
});
} else if (is<Program>(*this)) {
// Perform the steps of GlobalDeclarationInstantiation.
generator.begin_variable_scope(Bytecode::Generator::BindingMode::Global, Bytecode::Generator::SurroundingScopeKind::Global);
pushed_scope_count++;
// 1. Let lexNames be the LexicallyDeclaredNames of script.
// 2. Let varNames be the VarDeclaredNames of script.
// 3. For each element name of lexNames, do
(void)for_each_lexically_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
auto identifier = generator.intern_identifier(name);
// a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
// b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
if (generator.has_binding(identifier)) {
// FIXME: Throw an actual SyntaxError instance.
generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
generator.emit<Bytecode::Op::Throw>();
return {};
}
// FIXME: c. If hasRestrictedGlobalProperty is true, throw a SyntaxError exception.
// d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
return {};
});
// 4. For each element name of varNames, do
(void)for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
auto identifier = generator.intern_identifier(name);
// a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
if (generator.has_binding(identifier)) {
// FIXME: Throw an actual SyntaxError instance.
generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
generator.emit<Bytecode::Op::Throw>();
}
return {};
});
// 5. Let varDeclarations be the VarScopedDeclarations of script.
// 6. Let functionsToInitialize be a new empty List.
Vector<FunctionDeclaration const&> functions_to_initialize;
// 7. Let declaredFunctionNames be a new empty List.
HashTable<FlyString> declared_function_names;
// 8. For each element d of varDeclarations, in reverse List order, do
(void)for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
// a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
// i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
// Note: This is checked in for_each_var_function_declaration_in_reverse_order.
// ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
// iii. Let fn be the sole element of the BoundNames of d.
// iv. If fn is not an element of declaredFunctionNames, then
if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
return {};
// FIXME: 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
// FIXME: 2. If fnDefinable is false, throw a TypeError exception.
// 3. Append fn to declaredFunctionNames.
// Note: Already done in step iv. above.
// 4. Insert d as the first element of functionsToInitialize.
functions_to_initialize.prepend(function);
return {};
});
// 9. Let declaredVarNames be a new empty List.
HashTable<FlyString> declared_var_names;
// 10. For each element d of varDeclarations, do
(void)for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
// a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
// Note: This is done in for_each_var_scoped_variable_declaration.
// i. For each String vn of the BoundNames of d, do
return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
// 1. If vn is not an element of declaredFunctionNames, then
if (declared_function_names.contains(name))
return {};
// FIXME: a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
// FIXME: b. If vnDefinable is false, throw a TypeError exception.
// c. If vn is not an element of declaredVarNames, then
// i. Append vn to declaredVarNames.
declared_var_names.set(name);
return {};
});
});
// 11. NOTE: No abnormal terminations occur after this algorithm step if the global object is an ordinary object. However, if the global object is a Proxy exotic object it may exhibit behaviours that cause abnormal terminations in some of the following steps.
// 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
// 12. Let strict be IsStrict of script.
// 13. If strict is false, then
if (!verify_cast<Program>(*this).is_strict_mode()) {
// a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
// b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
(void)for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
// i. Let F be StringValue of the BindingIdentifier of f.
auto& function_name = function_declaration.name();
// ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
// Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
// 1. If env.HasLexicalDeclaration(F) is false, then
auto index = generator.intern_identifier(function_name);
if (generator.has_binding(index, Bytecode::Generator::BindingMode::Lexical))
return;
// FIXME: a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
// b. If fnDefinable is true, then
// i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
// ii. If declaredFunctionOrVarNames does not contain F, then
if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
// i. Perform ? env.CreateGlobalVarBinding(F, false).
generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Var, false);
// ii. Append F to declaredFunctionOrVarNames.
declared_function_names.set(function_name);
}
// iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
// i. Let genv be the running execution context's VariableEnvironment.
// ii. Let benv be the running execution context's LexicalEnvironment.
// iii. Let fobj be ! benv.GetBindingValue(F, false).
// iv. Perform ? genv.SetMutableBinding(F, fobj, false).
// v. Return NormalCompletion(empty).
function_declaration.set_should_do_additional_annexB_steps();
});
}
// 15. For each element d of lexDeclarations, do
(void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
// a. NOTE: Lexically declared names are only instantiated here but not initialized.
// b. For each element dn of the BoundNames of d, do
return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
auto identifier = generator.intern_identifier(name);
// i. If IsConstantDeclaration of d is true, then
generator.register_binding(identifier);
if (declaration.is_constant_declaration()) {
// 1. Perform ? env.CreateImmutableBinding(dn, true).
generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
} else {
// ii. Else,
// 1. Perform ? env.CreateMutableBinding(dn, false).
generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
}
return {};
});
});
// 16. For each Parse Node f of functionsToInitialize, do
for (auto& function_declaration : functions_to_initialize) {
// FIXME: Do this more correctly.
// a. Let fn be the sole element of the BoundNames of f.
// b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
generator.emit<Bytecode::Op::NewFunction>(function_declaration);
// c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
auto const& name = function_declaration.name();
auto index = generator.intern_identifier(name);
if (!generator.has_binding(index)) {
generator.register_binding(index, Bytecode::Generator::BindingMode::Var);
generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
}
generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
}
// 17. For each String vn of declaredVarNames, do
// a. Perform ? env.CreateGlobalVarBinding(vn, false).
for (auto& var_name : declared_var_names)
generator.register_binding(generator.intern_identifier(var_name), Bytecode::Generator::BindingMode::Var);
} else {
// Perform the steps of FunctionDeclarationInstantiation.
generator.begin_variable_scope(Bytecode::Generator::BindingMode::Var, Bytecode::Generator::SurroundingScopeKind::Function);
pushed_scope_count++;
if (has_lexical_declarations()) {
generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Function);
pushed_scope_count++;
}
// FIXME: Implement this boi correctly.
(void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
auto is_constant_declaration = declaration.is_constant_declaration();
declaration.for_each_bound_name([&](auto const& name) {
auto index = generator.intern_identifier(name);
if (is_constant_declaration || !generator.has_binding(index)) {
generator.register_binding(index);
generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
}
});
if (is<FunctionDeclaration>(declaration)) {
auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
if (auto result = function_declaration.generate_bytecode(generator); result.is_error()) {
maybe_error = result.release_error();
// To make `for_each_lexically_scoped_declaration` happy.
return failing_completion;
}
auto const& name = function_declaration.name();
auto index = generator.intern_identifier(name);
if (!generator.has_binding(index)) {
generator.register_binding(index);
generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
}
generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
}
return {};
});
}
if (maybe_error.has_value())
return maybe_error.release_value();
for (auto& child : children()) {
TRY(child.generate_bytecode(generator));
if (generator.is_current_block_terminated())
break;
}
for (size_t i = 0; i < pushed_scope_count; ++i)
generator.end_variable_scope();
return {};
}
Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const
{
return {};
}
Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const
{
return m_expression->generate_bytecode(generator);
}
Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(m_lhs->generate_bytecode(generator));
auto lhs_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(lhs_reg);
TRY(m_rhs->generate_bytecode(generator));
switch (m_op) {
case BinaryOp::Addition:
generator.emit<Bytecode::Op::Add>(lhs_reg);
break;
case BinaryOp::Subtraction:
generator.emit<Bytecode::Op::Sub>(lhs_reg);
break;
case BinaryOp::Multiplication:
generator.emit<Bytecode::Op::Mul>(lhs_reg);
break;
case BinaryOp::Division:
generator.emit<Bytecode::Op::Div>(lhs_reg);
break;
case BinaryOp::Modulo:
generator.emit<Bytecode::Op::Mod>(lhs_reg);
break;
case BinaryOp::Exponentiation:
generator.emit<Bytecode::Op::Exp>(lhs_reg);
break;
case BinaryOp::GreaterThan:
generator.emit<Bytecode::Op::GreaterThan>(lhs_reg);
break;
case BinaryOp::GreaterThanEquals:
generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg);
break;
case BinaryOp::LessThan:
generator.emit<Bytecode::Op::LessThan>(lhs_reg);
break;
case BinaryOp::LessThanEquals:
generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg);
break;
case BinaryOp::LooselyInequals:
generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg);
break;
case BinaryOp::LooselyEquals:
generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg);
break;
case BinaryOp::StrictlyInequals:
generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg);
break;
case BinaryOp::StrictlyEquals:
generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg);
break;
case BinaryOp::BitwiseAnd:
generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
break;
case BinaryOp::BitwiseOr:
generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
break;
case BinaryOp::BitwiseXor:
generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
break;
case BinaryOp::LeftShift:
generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
break;
case BinaryOp::RightShift:
generator.emit<Bytecode::Op::RightShift>(lhs_reg);
break;
case BinaryOp::UnsignedRightShift:
generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
break;
case BinaryOp::In:
generator.emit<Bytecode::Op::In>(lhs_reg);
break;
case BinaryOp::InstanceOf:
generator.emit<Bytecode::Op::InstanceOf>(lhs_reg);
break;
default:
VERIFY_NOT_REACHED();
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(m_lhs->generate_bytecode(generator));
// lhs
// jump op (true) end (false) rhs
// rhs
// jump always (true) end
// end
auto& rhs_block = generator.make_block();
auto& end_block = generator.make_block();
switch (m_op) {
case LogicalOp::And:
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { rhs_block },
Bytecode::Label { end_block });
break;
case LogicalOp::Or:
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { end_block },
Bytecode::Label { rhs_block });
break;
case LogicalOp::NullishCoalescing:
generator.emit<Bytecode::Op::JumpNullish>().set_targets(
Bytecode::Label { rhs_block },
Bytecode::Label { end_block });
break;
default:
VERIFY_NOT_REACHED();
}
generator.switch_to_basic_block(rhs_block);
TRY(m_rhs->generate_bytecode(generator));
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { end_block },
{});
generator.switch_to_basic_block(end_block);
return {};
}
Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(m_lhs->generate_bytecode(generator));
switch (m_op) {
case UnaryOp::BitwiseNot:
generator.emit<Bytecode::Op::BitwiseNot>();
break;
case UnaryOp::Not:
generator.emit<Bytecode::Op::Not>();
break;
case UnaryOp::Plus:
generator.emit<Bytecode::Op::UnaryPlus>();
break;
case UnaryOp::Minus:
generator.emit<Bytecode::Op::UnaryMinus>();
break;
case UnaryOp::Typeof:
generator.emit<Bytecode::Op::Typeof>();
break;
case UnaryOp::Void:
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
break;
default:
return Bytecode::CodeGenerationError {
this,
"Unimplemented operation"sv,
};
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::LoadImmediate>(m_value);
return {};
}
Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value));
return {};
}
Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::LoadImmediate>(js_null());
return {};
}
Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::NewBigInt>(Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
return {};
}
Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value));
return {};
}
Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
auto source_index = generator.intern_string(m_pattern);
auto flags_index = generator.intern_string(m_flags);
generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index);
return {};
}
Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string));
return {};
}
Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const
{
// FIXME: Implement this for BindingPatterns too.
auto& lhs = m_lhs.get<NonnullRefPtr<Expression>>();
if (m_op == AssignmentOp::Assignment) {
TRY(m_rhs->generate_bytecode(generator));
return generator.emit_store_to_reference(lhs);
}
TRY(generator.emit_load_from_reference(lhs));
Bytecode::BasicBlock* rhs_block_ptr { nullptr };
Bytecode::BasicBlock* end_block_ptr { nullptr };
// Logical assignments short circuit.
if (m_op == AssignmentOp::AndAssignment) { // &&=
rhs_block_ptr = &generator.make_block();
end_block_ptr = &generator.make_block();
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { *rhs_block_ptr },
Bytecode::Label { *end_block_ptr });
} else if (m_op == AssignmentOp::OrAssignment) { // ||=
rhs_block_ptr = &generator.make_block();
end_block_ptr = &generator.make_block();
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { *end_block_ptr },
Bytecode::Label { *rhs_block_ptr });
} else if (m_op == AssignmentOp::NullishAssignment) { // ??=
rhs_block_ptr = &generator.make_block();
end_block_ptr = &generator.make_block();
generator.emit<Bytecode::Op::JumpNullish>().set_targets(
Bytecode::Label { *rhs_block_ptr },
Bytecode::Label { *end_block_ptr });
}
if (rhs_block_ptr)
generator.switch_to_basic_block(*rhs_block_ptr);
// lhs_reg is a part of the rhs_block because the store isn't necessary
// if the logical assignment condition fails.
auto lhs_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(lhs_reg);
TRY(m_rhs->generate_bytecode(generator));
switch (m_op) {
case AssignmentOp::AdditionAssignment:
generator.emit<Bytecode::Op::Add>(lhs_reg);
break;
case AssignmentOp::SubtractionAssignment:
generator.emit<Bytecode::Op::Sub>(lhs_reg);
break;
case AssignmentOp::MultiplicationAssignment:
generator.emit<Bytecode::Op::Mul>(lhs_reg);
break;
case AssignmentOp::DivisionAssignment:
generator.emit<Bytecode::Op::Div>(lhs_reg);
break;
case AssignmentOp::ModuloAssignment:
generator.emit<Bytecode::Op::Mod>(lhs_reg);
break;
case AssignmentOp::ExponentiationAssignment:
generator.emit<Bytecode::Op::Exp>(lhs_reg);
break;
case AssignmentOp::BitwiseAndAssignment:
generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
break;
case AssignmentOp::BitwiseOrAssignment:
generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
break;
case AssignmentOp::BitwiseXorAssignment:
generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
break;
case AssignmentOp::LeftShiftAssignment:
generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
break;
case AssignmentOp::RightShiftAssignment:
generator.emit<Bytecode::Op::RightShift>(lhs_reg);
break;
case AssignmentOp::UnsignedRightShiftAssignment:
generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
break;
case AssignmentOp::AndAssignment:
case AssignmentOp::OrAssignment:
case AssignmentOp::NullishAssignment:
break; // These are handled above.
default:
return Bytecode::CodeGenerationError {
this,
"Unimplemented operation"sv,
};
}
TRY(generator.emit_store_to_reference(lhs));
if (end_block_ptr) {
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { *end_block_ptr },
{});
generator.switch_to_basic_block(*end_block_ptr);
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const
{
// test
// jump if_false (true) end (false) body
// body
// jump always (true) test
// end
auto& test_block = generator.make_block();
auto& body_block = generator.make_block();
auto& end_block = generator.make_block();
// Init result register
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
auto result_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(result_reg);
// jump to the test block
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { test_block },
{});
generator.switch_to_basic_block(test_block);
TRY(m_test->generate_bytecode(generator));
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { body_block },
Bytecode::Label { end_block });
generator.switch_to_basic_block(body_block);
generator.begin_continuable_scope(Bytecode::Label { test_block });
generator.begin_breakable_scope(Bytecode::Label { end_block });
TRY(m_body->generate_bytecode(generator));
if (!generator.is_current_block_terminated()) {
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { test_block },
{});
generator.end_continuable_scope();
generator.end_breakable_scope();
generator.switch_to_basic_block(end_block);
generator.emit<Bytecode::Op::Load>(result_reg);
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const
{
// jump always (true) body
// test
// jump if_false (true) end (false) body
// body
// jump always (true) test
// end
auto& test_block = generator.make_block();
auto& body_block = generator.make_block();
auto& end_block = generator.make_block();
// Init result register
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
auto result_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(result_reg);
// jump to the body block
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { body_block },
{});
generator.switch_to_basic_block(test_block);
TRY(m_test->generate_bytecode(generator));
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { body_block },
Bytecode::Label { end_block });
generator.switch_to_basic_block(body_block);
generator.begin_continuable_scope(Bytecode::Label { test_block });
generator.begin_breakable_scope(Bytecode::Label { end_block });
TRY(m_body->generate_bytecode(generator));
if (!generator.is_current_block_terminated()) {
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { test_block },
{});
generator.end_continuable_scope();
generator.end_breakable_scope();
generator.switch_to_basic_block(end_block);
generator.emit<Bytecode::Op::Load>(result_reg);
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const
{
// init
// jump always (true) test
// test
// jump if_true (true) body (false) end
// body
// jump always (true) update
// update
// jump always (true) test
// end
// If 'test' is missing, fuse the 'test' and 'body' basic blocks
// If 'update' is missing, fuse the 'body' and 'update' basic blocks
Bytecode::BasicBlock* test_block_ptr { nullptr };
Bytecode::BasicBlock* body_block_ptr { nullptr };
Bytecode::BasicBlock* update_block_ptr { nullptr };
auto& end_block = generator.make_block();
if (m_init)
TRY(m_init->generate_bytecode(generator));
body_block_ptr = &generator.make_block();
if (m_test)
test_block_ptr = &generator.make_block();
else
test_block_ptr = body_block_ptr;
if (m_update)
update_block_ptr = &generator.make_block();
else
update_block_ptr = body_block_ptr;
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
auto result_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(result_reg);
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { *test_block_ptr },
{});
if (m_test) {
generator.switch_to_basic_block(*test_block_ptr);
TRY(m_test->generate_bytecode(generator));
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { *body_block_ptr },
Bytecode::Label { end_block });
}
generator.switch_to_basic_block(*body_block_ptr);
generator.begin_continuable_scope(Bytecode::Label { *update_block_ptr });
generator.begin_breakable_scope(Bytecode::Label { end_block });
TRY(m_body->generate_bytecode(generator));
generator.end_continuable_scope();
if (!generator.is_current_block_terminated()) {
if (m_update) {
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { *update_block_ptr },
{});
generator.switch_to_basic_block(*update_block_ptr);
TRY(m_update->generate_bytecode(generator));
}
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { *test_block_ptr },
{});
generator.end_breakable_scope();
generator.switch_to_basic_block(end_block);
generator.emit<Bytecode::Op::Load>(result_reg);
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::NewObject>();
if (m_properties.is_empty())
return {};
auto object_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(object_reg);
for (auto& property : m_properties) {
if (property.type() != ObjectProperty::Type::KeyValue)
return Bytecode::CodeGenerationError {
this,
"Unimplemented property kind"sv,
};
if (is<StringLiteral>(property.key())) {
auto& string_literal = static_cast<StringLiteral const&>(property.key());
Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
TRY(property.value().generate_bytecode(generator));
generator.emit<Bytecode::Op::PutById>(object_reg, key_name);
} else {
TRY(property.key().generate_bytecode(generator));
auto property_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(property_reg);
TRY(property.value().generate_bytecode(generator));
generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
}
}
generator.emit<Bytecode::Op::Load>(object_reg);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
{
Vector<Bytecode::Register> element_regs;
for (auto& element : m_elements) {
if (element) {
TRY(element->generate_bytecode(generator));
if (is<SpreadExpression>(*element)) {
return Bytecode::CodeGenerationError {
this,
"Unimplemented element kind: SpreadExpression"sv,
};
}
} else {
generator.emit<Bytecode::Op::LoadImmediate>(Value {});
}
auto element_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(element_reg);
element_regs.append(element_reg);
}
generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(element_regs.size(), element_regs);
return {};
}
Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
{
return generator.emit_load_from_reference(*this);
}
Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
{
if (m_is_hoisted) {
auto index = generator.intern_identifier(name());
generator.emit<Bytecode::Op::GetVariable>(index);
generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Var);
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::NewFunction>(*this);
return {};
}
static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
static Bytecode::CodeGenerationErrorOr<void> generate_object_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
{
Vector<Bytecode::Register> excluded_property_names;
auto has_rest = false;
if (pattern.entries.size() > 0)
has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
if (is_rest) {
VERIFY(name.has<NonnullRefPtr<Identifier>>());
VERIFY(alias.has<Empty>());
VERIFY(!initializer);
auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
auto interned_identifier = generator.intern_identifier(identifier);
generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
return {};
}
Bytecode::StringTableIndex name_index;
if (name.has<NonnullRefPtr<Identifier>>()) {
auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
name_index = generator.intern_string(identifier);
if (has_rest) {
auto excluded_name_reg = generator.allocate_register();
excluded_property_names.append(excluded_name_reg);
generator.emit<Bytecode::Op::NewString>(name_index);
generator.emit<Bytecode::Op::Store>(excluded_name_reg);
}
generator.emit<Bytecode::Op::Load>(value_reg);
generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
} else {
auto expression = name.get<NonnullRefPtr<Expression>>();
TRY(expression->generate_bytecode(generator));
if (has_rest) {
auto excluded_name_reg = generator.allocate_register();
excluded_property_names.append(excluded_name_reg);
generator.emit<Bytecode::Op::Store>(excluded_name_reg);
}
generator.emit<Bytecode::Op::GetByValue>(value_reg);
}
if (initializer) {
auto& if_undefined_block = generator.make_block();
auto& if_not_undefined_block = generator.make_block();
generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
Bytecode::Label { if_undefined_block },
Bytecode::Label { if_not_undefined_block });
generator.switch_to_basic_block(if_undefined_block);
TRY(initializer->generate_bytecode(generator));
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { if_not_undefined_block },
{});
generator.switch_to_basic_block(if_not_undefined_block);
}
if (alias.has<NonnullRefPtr<BindingPattern>>()) {
auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>();
auto nested_value_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(nested_value_reg);
TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
} else if (alias.has<Empty>()) {
if (name.has<NonnullRefPtr<Expression>>()) {
// This needs some sort of SetVariableByValue opcode, as it's a runtime binding
return Bytecode::CodeGenerationError {
name.get<NonnullRefPtr<Expression>>().ptr(),
"Unimplemented name/alias pair: Empty/Expression"sv,
};
}
auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
} else {
auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
}
}
return {};
}
static Bytecode::CodeGenerationErrorOr<void> generate_array_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
{
/*
* Consider the following destructuring assignment:
*
* let [a, b, c, d, e] = o;
*
* It would be fairly trivial to just loop through this iterator, getting the value
* at each step and assigning them to the binding sequentially. However, this is not
* correct: once an iterator is exhausted, it must not be called again. This complicates
* the bytecode. In order to accomplish this, we do the following:
*
* - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
* and false otherwise
* - When we are retrieving the value which should be bound, we first check this register.
* If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
* value from the iterator and store it into the accumulator.
*
* Note that the is_exhausted register does not need to be loaded with false because the
* first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
* unnecessary.
*/
auto is_iterator_exhausted_register = generator.allocate_register();
auto iterator_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Load>(value_reg);
generator.emit<Bytecode::Op::GetIterator>();
generator.emit<Bytecode::Op::Store>(iterator_reg);
bool first = true;
auto temp_iterator_result_reg = generator.allocate_register();
auto assign_accumulator_to_alias = [&](auto& alias) {
return alias.visit(
[&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
// This element is an elision
return {};
},
[&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
auto interned_index = generator.intern_identifier(identifier->string());
generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
return {};
},
[&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
// Store the accumulator value in a permanent register
auto target_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(target_reg);
return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
},
[&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
return Bytecode::CodeGenerationError {
expr.ptr(),
"Unimplemented alias mode: MemberExpression"sv,
};
});
};
for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
VERIFY(name.has<Empty>());
if (is_rest) {
if (first) {
// The iterator has not been called, and is thus known to be not exhausted
generator.emit<Bytecode::Op::Load>(iterator_reg);
generator.emit<Bytecode::Op::IteratorToArray>();
} else {
auto& if_exhausted_block = generator.make_block();
auto& if_not_exhausted_block = generator.make_block();
auto& continuation_block = generator.make_block();
generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { if_exhausted_block },
Bytecode::Label { if_not_exhausted_block });
generator.switch_to_basic_block(if_exhausted_block);
generator.emit<Bytecode::Op::NewArray>();
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { continuation_block },
{});
generator.switch_to_basic_block(if_not_exhausted_block);
generator.emit<Bytecode::Op::Load>(iterator_reg);
generator.emit<Bytecode::Op::IteratorToArray>();
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { continuation_block },
{});
generator.switch_to_basic_block(continuation_block);
}
return assign_accumulator_to_alias(alias);
}
// In the first iteration of the loop, a few things are true which can save
// us some bytecode:
// - the iterator result is still in the accumulator, so we can avoid a load
// - the iterator is not yet exhausted, which can save us a jump and some
// creation
auto& iterator_is_exhausted_block = generator.make_block();
if (!first) {
auto& iterator_is_not_exhausted_block = generator.make_block();
generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { iterator_is_exhausted_block },
Bytecode::Label { iterator_is_not_exhausted_block });
generator.switch_to_basic_block(iterator_is_not_exhausted_block);
generator.emit<Bytecode::Op::Load>(iterator_reg);
}
generator.emit<Bytecode::Op::IteratorNext>();
generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
generator.emit<Bytecode::Op::IteratorResultDone>();
generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
// We still have to check for exhaustion here. If the iterator is exhausted,
// we need to bail before trying to get the value
auto& no_bail_block = generator.make_block();
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { iterator_is_exhausted_block },
Bytecode::Label { no_bail_block });
generator.switch_to_basic_block(no_bail_block);
// Get the next value in the iterator
generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
generator.emit<Bytecode::Op::IteratorResultValue>();
auto& create_binding_block = generator.make_block();
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { create_binding_block },
{});
// The iterator is exhausted, so we just load undefined and continue binding
generator.switch_to_basic_block(iterator_is_exhausted_block);
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { create_binding_block },
{});
// Create the actual binding. The value which this entry must bind is now in the
// accumulator. We can proceed, processing the alias as a nested destructuring
// pattern if necessary.
generator.switch_to_basic_block(create_binding_block);
TRY(assign_accumulator_to_alias(alias));
first = false;
}
return {};
}
static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
{
if (pattern.kind == BindingPattern::Kind::Object)
return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
}
Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
{
for (auto& declarator : m_declarations) {
if (declarator.init())
TRY(declarator.init()->generate_bytecode(generator));
else
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
auto initialization_mode = is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
TRY(declarator.target().visit(
[&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode);
return {};
},
[&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
auto value_register = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(value_register);
return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
}));
}
return {};
}
Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
{
auto callee_reg = generator.allocate_register();
auto this_reg = generator.allocate_register();
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
generator.emit<Bytecode::Op::Store>(this_reg);
if (is<NewExpression>(this)) {
TRY(m_callee->generate_bytecode(generator));
generator.emit<Bytecode::Op::Store>(callee_reg);
} else if (is<SuperExpression>(*m_callee)) {
return Bytecode::CodeGenerationError {
this,
"Unimplemented callee kind: SuperExpression"sv,
};
} else if (is<MemberExpression>(*m_callee)) {
auto& member_expression = static_cast<const MemberExpression&>(*m_callee);
if (is<SuperExpression>(member_expression.object())) {
return Bytecode::CodeGenerationError {
this,
"Unimplemented callee kind: MemberExpression on SuperExpression"sv,
};
}
TRY(member_expression.object().generate_bytecode(generator));
generator.emit<Bytecode::Op::Store>(this_reg);
if (member_expression.is_computed()) {
TRY(member_expression.property().generate_bytecode(generator));
generator.emit<Bytecode::Op::GetByValue>(this_reg);
} else {
auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
}
generator.emit<Bytecode::Op::Store>(callee_reg);
} else {
// FIXME: this = global object in sloppy mode.
TRY(m_callee->generate_bytecode(generator));
generator.emit<Bytecode::Op::Store>(callee_reg);
}
Vector<Bytecode::Register> argument_registers;
for (auto& arg : m_arguments) {
TRY(arg.value->generate_bytecode(generator));
auto arg_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(arg_reg);
argument_registers.append(arg_reg);
}
Bytecode::Op::Call::CallType call_type;
if (is<NewExpression>(*this)) {
call_type = Bytecode::Op::Call::CallType::Construct;
} else {
call_type = Bytecode::Op::Call::CallType::Call;
}
generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
{
if (m_argument)
TRY(m_argument->generate_bytecode(generator));
if (generator.is_in_generator_or_async_function())
generator.emit<Bytecode::Op::Yield>(nullptr);
else
generator.emit<Bytecode::Op::Return>();
return {};
}
Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
{
VERIFY(generator.is_in_generator_function());
if (m_is_yield_from) {
return Bytecode::CodeGenerationError {
this,
"Unimplemented form: `yield*`"sv,
};
}
if (m_argument)
TRY(m_argument->generate_bytecode(generator));
auto& continuation_block = generator.make_block();
generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
generator.switch_to_basic_block(continuation_block);
return {};
}
Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
{
// test
// jump if_true (true) true (false) false
// true
// jump always (true) end
// false
// jump always (true) end
// end
auto& true_block = generator.make_block();
auto& false_block = generator.make_block();
TRY(m_predicate->generate_bytecode(generator));
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { true_block },
Bytecode::Label { false_block });
Bytecode::Op::Jump* true_block_jump { nullptr };
generator.switch_to_basic_block(true_block);
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
TRY(m_consequent->generate_bytecode(generator));
if (!generator.is_current_block_terminated())
true_block_jump = &generator.emit<Bytecode::Op::Jump>();
generator.switch_to_basic_block(false_block);
auto& end_block = generator.make_block();
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
if (m_alternate)
TRY(m_alternate->generate_bytecode(generator));
if (!generator.is_current_block_terminated())
generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
if (true_block_jump)
true_block_jump->set_targets(Bytecode::Label { end_block }, {});
generator.switch_to_basic_block(end_block);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::Jump>().set_targets(
generator.nearest_continuable_scope(),
{});
return {};
}
Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
{
return {};
}
Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
{
// test
// jump if_true (true) true (false) false
// true
// jump always (true) end
// false
// jump always (true) end
// end
auto& true_block = generator.make_block();
auto& false_block = generator.make_block();
auto& end_block = generator.make_block();
TRY(m_test->generate_bytecode(generator));
generator.emit<Bytecode::Op::JumpConditional>().set_targets(
Bytecode::Label { true_block },
Bytecode::Label { false_block });
generator.switch_to_basic_block(true_block);
TRY(m_consequent->generate_bytecode(generator));
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { end_block },
{});
generator.switch_to_basic_block(false_block);
TRY(m_alternate->generate_bytecode(generator));
generator.emit<Bytecode::Op::Jump>().set_targets(
Bytecode::Label { end_block },
{});
generator.switch_to_basic_block(end_block);
return {};
}
Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
{
for (auto& expression : m_expressions)
TRY(expression.generate_bytecode(generator));
return {};
}
Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
auto string_reg = generator.allocate_register();
for (size_t i = 0; i < m_expressions.size(); i++) {
TRY(m_expressions[i].generate_bytecode(generator));
if (i == 0) {
generator.emit<Bytecode::Op::Store>(string_reg);
} else {
generator.emit<Bytecode::Op::ConcatString>(string_reg);
}
}
generator.emit<Bytecode::Op::Load>(string_reg);
return {};
}
Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(m_tag->generate_bytecode(generator));
auto tag_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(tag_reg);
Vector<Bytecode::Register> string_regs;
auto& expressions = m_template_literal->expressions();
for (size_t i = 0; i < expressions.size(); ++i) {
if (i % 2 != 0)
continue;
TRY(expressions[i].generate_bytecode(generator));
auto string_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(string_reg);
string_regs.append(string_reg);
}
generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(string_regs.size(), string_regs);
auto strings_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(strings_reg);
Vector<Bytecode::Register> argument_regs;
argument_regs.append(strings_reg);
for (size_t i = 0; i < expressions.size(); ++i) {
if (i % 2 == 0)
continue;
TRY(expressions[i].generate_bytecode(generator));
auto string_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(string_reg);
argument_regs.append(string_reg);
}
Vector<Bytecode::Register> raw_string_regs;
for (auto& raw_string : m_template_literal->raw_strings()) {
TRY(raw_string.generate_bytecode(generator));
auto raw_string_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(raw_string_reg);
raw_string_regs.append(raw_string_reg);
}
generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(raw_string_regs.size(), raw_string_regs);
auto raw_strings_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(raw_strings_reg);
generator.emit<Bytecode::Op::Load>(strings_reg);
generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw"));
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
auto this_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(this_reg);
generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs));
return {};
}
Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(generator.emit_load_from_reference(*m_argument));
Optional<Bytecode::Register> previous_value_for_postfix_reg;
if (!m_prefixed) {
previous_value_for_postfix_reg = generator.allocate_register();
generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
}
if (m_op == UpdateOp::Increment)
generator.emit<Bytecode::Op::Increment>();
else
generator.emit<Bytecode::Op::Decrement>();
TRY(generator.emit_store_to_reference(*m_argument));
if (!m_prefixed)
generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(m_argument->generate_bytecode(generator));
generator.emit<Bytecode::Op::Throw>();
return {};
}
Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::Jump>().set_targets(
generator.nearest_breakable_scope(),
{});
return {};
}
Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
{
auto& saved_block = generator.current_block();
Optional<Bytecode::Label> handler_target;
Optional<Bytecode::Label> finalizer_target;
Bytecode::BasicBlock* next_block { nullptr };
if (m_finalizer) {
auto& finalizer_block = generator.make_block();
generator.switch_to_basic_block(finalizer_block);
TRY(m_finalizer->generate_bytecode(generator));
if (!generator.is_current_block_terminated()) {
next_block = &generator.make_block();
auto next_target = Bytecode::Label { *next_block };
generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
}
finalizer_target = Bytecode::Label { finalizer_block };
}
if (m_handler) {
auto& handler_block = generator.make_block();
generator.switch_to_basic_block(handler_block);
TRY(m_handler->parameter().visit(
[&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
if (!parameter.is_empty()) {
// FIXME: We need a separate DeclarativeEnvironment here
generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(parameter));
}
return {};
},
[&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> {
// FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
return Bytecode::CodeGenerationError {
this,
"Unimplemented catch argument: BindingPattern"sv,
};
}));
TRY(m_handler->body().generate_bytecode(generator));
handler_target = Bytecode::Label { handler_block };
if (!generator.is_current_block_terminated()) {
if (m_finalizer) {
generator.emit<Bytecode::Op::LeaveUnwindContext>();
generator.emit<Bytecode::Op::Jump>(finalizer_target);
} else {
VERIFY(!next_block);
next_block = &generator.make_block();
auto next_target = Bytecode::Label { *next_block };
generator.emit<Bytecode::Op::Jump>(next_target);
}
}
}
auto& target_block = generator.make_block();
generator.switch_to_basic_block(saved_block);
generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
generator.switch_to_basic_block(target_block);
TRY(m_block->generate_bytecode(generator));
if (!generator.is_current_block_terminated()) {
if (m_finalizer) {
generator.emit<Bytecode::Op::Jump>(finalizer_target);
} else {
auto& block = generator.make_block();
generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block });
next_block = █
}
}
generator.switch_to_basic_block(next_block ? *next_block : saved_block);
return {};
}
Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
{
auto discriminant_reg = generator.allocate_register();
TRY(m_discriminant->generate_bytecode(generator));
generator.emit<Bytecode::Op::Store>(discriminant_reg);
Vector<Bytecode::BasicBlock&> case_blocks;
Bytecode::BasicBlock* default_block { nullptr };
Bytecode::BasicBlock* next_test_block = &generator.make_block();
generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
for (auto& switch_case : m_cases) {
auto& case_block = generator.make_block();
if (switch_case.test()) {
generator.switch_to_basic_block(*next_test_block);
TRY(switch_case.test()->generate_bytecode(generator));
generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
next_test_block = &generator.make_block();
generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
} else {
default_block = &case_block;
}
case_blocks.append(case_block);
}
generator.switch_to_basic_block(*next_test_block);
auto& end_block = generator.make_block();
if (default_block != nullptr) {
generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
} else {
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
}
auto current_block = case_blocks.begin();
generator.begin_breakable_scope(Bytecode::Label { end_block });
for (auto& switch_case : m_cases) {
generator.switch_to_basic_block(*current_block);
generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
for (auto& statement : switch_case.children()) {
TRY(statement.generate_bytecode(generator));
}
if (!generator.is_current_block_terminated()) {
auto next_block = current_block;
next_block++;
if (next_block.is_end()) {
generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
} else {
generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
}
}
current_block++;
}
generator.end_breakable_scope();
generator.switch_to_basic_block(end_block);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
{
TRY(m_class_expression->generate_bytecode(generator));
generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::NewClass>(*this);
return {};
}
Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
{
generator.emit<Bytecode::Op::ResolveThisBinding>();
return {};
}
Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
{
VERIFY(generator.is_in_async_function());
// Transform `await expr` to `yield expr`
TRY(m_argument->generate_bytecode(generator));
auto& continuation_block = generator.make_block();
generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
generator.switch_to_basic_block(continuation_block);
return {};
}
}
| 41.220844 | 267 | 0.660532 | gSpera |
e4f40cc473b23988ba0cc7e6ab9abe4bcd889592 | 1,437 | cpp | C++ | tests/unrepresentable_operation_error.test.cpp | atimholt/rational_geometry | 2738ac352dc527b2c2d5f4d3197692161a0d34b1 | [
"MIT"
] | null | null | null | tests/unrepresentable_operation_error.test.cpp | atimholt/rational_geometry | 2738ac352dc527b2c2d5f4d3197692161a0d34b1 | [
"MIT"
] | null | null | null | tests/unrepresentable_operation_error.test.cpp | atimholt/rational_geometry | 2738ac352dc527b2c2d5f4d3197692161a0d34b1 | [
"MIT"
] | null | null | null |
#include "../src/rational_geometry/unrepresentable_operation_error.hpp"
#include "doctest.h"
#include <ostream>
#include <string>
#include <typeinfo>
namespace rational_geometry {
TEST_CASE("Testing unrepresentable_operation_error.hpp")
{
SUBCASE("class unrepresentable_operation_error")
{
SUBCASE("Constructors")
{
auto a =
unrepresentable_operation_error<int>("This error is a test", 12, 8);
CHECK(a.get_minimum_fix_factor() == 2);
}
SUBCASE("accumulate_fix_factor()")
{
int fix_factor{1};
const int kDenom{12};
try {
throw unrepresentable_operation_error<int>{"An error", kDenom, 8};
}
catch (const unrepresentable_operation_error<int>& e) {
e.accumulate_fix_factor(fix_factor);
}
CHECK(fix_factor == 2);
try {
throw unrepresentable_operation_error<int>{"An error", kDenom, 9};
}
catch (const unrepresentable_operation_error<int>& e) {
e.accumulate_fix_factor(fix_factor);
}
REQUIRE(fix_factor == 2 * 3);
// Runtime returns on what to put into the code manually:
auto kFixFactorAccumulated = 2 * 3;
auto kNewDenom = kDenom * kFixFactorAccumulated;
// These don't throw:
//
// Rational<int, kNewDenom> a{[any int value]};
//
// a / 8; a / 9;
}
}
}
} // namespace rational_geometry
// vim:set et ts=2 sw=2 sts=2:
| 21.447761 | 78 | 0.631176 | atimholt |
e4fd7df13e2271077ed77daa1a65b22b8ed19a5d | 685 | hpp | C++ | include/server/service/utils.hpp | jhermsmeier/osrm-backend | 7b11cd3a11c939c957eeff71af7feddaa86e7f82 | [
"BSD-2-Clause"
] | 13 | 2019-02-21T02:02:41.000Z | 2021-09-09T13:49:31.000Z | include/server/service/utils.hpp | serarca/osrm-backend | 3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb | [
"BSD-2-Clause"
] | 288 | 2019-02-21T01:34:04.000Z | 2021-03-27T12:19:10.000Z | include/server/service/utils.hpp | serarca/osrm-backend | 3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb | [
"BSD-2-Clause"
] | 4 | 2019-06-21T20:51:59.000Z | 2021-01-13T09:22:24.000Z | #include <boost/format.hpp>
namespace osrm
{
namespace server
{
namespace service
{
const constexpr char PARAMETER_SIZE_MISMATCH_MSG[] =
"Number of elements in %1% size %2% does not match coordinate size %3%";
template <typename ParamT>
bool constrainParamSize(const char *msg_template,
const char *name,
const ParamT ¶m,
const std::size_t target_size,
std::string &help)
{
if (param.size() > 0 && param.size() != target_size)
{
help = (boost::format(msg_template) % name % param.size() % target_size).str();
return true;
}
return false;
}
}
}
}
| 22.833333 | 87 | 0.583942 | jhermsmeier |
9000fb3b8702118f57f3a3a312660835ace9ec11 | 1,746 | cpp | C++ | CCSDSlib/source/PacketFixedLength.cpp | nhaflinger/CCSDSlib | 23bd332078c6c8a1a3e70bacdb9a81f0da9403a3 | [
"MIT"
] | 1 | 2021-06-10T13:14:27.000Z | 2021-06-10T13:14:27.000Z | CCSDSlib/source/PacketFixedLength.cpp | nhaflinger/CCSDSlib | 23bd332078c6c8a1a3e70bacdb9a81f0da9403a3 | [
"MIT"
] | null | null | null | CCSDSlib/source/PacketFixedLength.cpp | nhaflinger/CCSDSlib | 23bd332078c6c8a1a3e70bacdb9a81f0da9403a3 | [
"MIT"
] | null | null | null | #ifdef __linux__
//linux code goes here
#elif defined(_WIN32) || defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "PacketFixedLength.h"
using namespace std;
PacketFixedLength::PacketFixedLength()
{
}
PacketFixedLength::~PacketFixedLength()
{
}
map<string, string> PacketFixedLength::loadFile(string file_path)
{
map<string, string> field_map;
ifstream in_file(file_path, ios::binary);
if (in_file.good())
{
in_file.seekg(0, ios::end);
int num_bytes = (int)in_file.tellg();
in_file.seekg(0, ios::beg);
char c = in_file.get();
m_file_bytes.push_back('\0');
while (in_file.good())
{
c = in_file.get();
m_file_bytes.push_back(c);
}
}
else
{
cout << "File does not exist!" << endl;
}
PacketDecode decoder;
decoder.decodeFixedLength(m_file_bytes, m_packet_fields);
field_map = decoder.fieldMap();
m_primary_header = decoder.primaryHeader();
return field_map;
}
map<string, string> PacketFixedLength::decodePacket(const vector<char>& file_bytes)
{
map<string, string> field_map;
m_file_bytes = file_bytes;
PacketDecode decoder;
decoder.decodeFixedLength(m_file_bytes, m_packet_fields);
field_map = decoder.fieldMap();
m_primary_header = decoder.primaryHeader();
return field_map;
}
vector<char> PacketFixedLength::encodePacket(const map<string, string>& field_map, bool secondary_header)
{
PacketEncode encoder;
encoder.setPrimaryHeader(m_primary_header);
if (secondary_header)
{
encoder.setSecondaryHeader(m_secondary_header);
}
encoder.setFieldMap(field_map);
vector<char> packed_bytes = encoder.encodeFixedLength(m_packet_fields, secondary_header);
return packed_bytes;
} | 22.101266 | 106 | 0.71764 | nhaflinger |
07e5868483e4085ce759c4c9760a7f4a5e01bf3b | 15,061 | cpp | C++ | pizjuce/image/src/imagePlugin.cpp | nonameentername/pizmidi | a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2 | [
"BSD-Source-Code"
] | null | null | null | pizjuce/image/src/imagePlugin.cpp | nonameentername/pizmidi | a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2 | [
"BSD-Source-Code"
] | null | null | null | pizjuce/image/src/imagePlugin.cpp | nonameentername/pizmidi | a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2 | [
"BSD-Source-Code"
] | 1 | 2021-01-26T12:25:01.000Z | 2021-01-26T12:25:01.000Z | #include "imagePlugin.h"
#include "imagePluginEditor.h"
//==============================================================================
/*
This function must be implemented to create the actual plugin object that
you want to use.
*/
PizAudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new imagePluginFilter();
}
ImageBank::ImageBank () : ValueTree("ImageBank")
{
//default values
for (int b=0;b<128;b++) {
ValueTree bank("BankValues");
bank.setProperty("bankIndex",b,0);
for (int p=0;p<128;p++)
{
ValueTree pv("ProgValues");
pv.setProperty("progIndex",p,0);
pv.setProperty("name","Bank " + String(b) + " Image " + String(p+1),0);
pv.setProperty("icon",String("Images") + File::separator + "Bank " + String(b) + File::separator + String(p+1) + ".svg",0);
pv.setProperty("text",String::empty,0);
pv.setProperty("bgcolor",Colour(0xFFFFFFFF).toString(),0);
pv.setProperty("textcolor",Colour(0xFF000000).toString(),0);
pv.setProperty("h",400,0);
pv.setProperty("w",400,0);
bank.addChild(pv,p,0);
}
this->addChild(bank,b,0);
}
ValueTree settings("GlobalSettings");
settings.setProperty("lastProgram",0,0);
settings.setProperty("lastBank",0,0);
settings.setProperty("channel",0,0);
settings.setProperty("noteInput",false,0);
settings.setProperty("usePC",true,0);
this->addChild(settings,128,0);
}
//==============================================================================
imagePluginFilter::imagePluginFilter()
{
iconPath = getCurrentPath() + File::separator + "images";
// create built-in programs
programs = new ImageBank();//new JuceProgram[16384];
if (!loadDefaultFxb())
{
//for(int b=0;b<128;b++)
//{
// for(int i=0;i<128;i++){
// programs[b*128+i].icon = String("Images") + File::separator + "Bank " + String(b) + File::separator + String(i+1) + ".svg";
// programs[b*128+i].name = "Bank " + String(b) + " Image " + String(i+1);
// }
//}
}
//start up with the first program
init = true;
curBank = 0;
curProgram = 0;
setCurrentBank (0,0);
}
imagePluginFilter::~imagePluginFilter()
{
if (programs) delete programs;
}
//==============================================================================
float imagePluginFilter::getParameter (int index)
{
return param[index];
}
void imagePluginFilter::setParameter (int index, float newValue)
{
switch(index)
{
case kChannel:
if (param[index] != newValue) {
param[index] = newValue;
programs->getChildWithName("GlobalSettings").setProperty("channel",roundFloatToInt(newValue*16.f),0);
sendChangeMessage ();
}
break;
default:
break;
}
}
const String imagePluginFilter::getParameterName (int index)
{
if (index == kChannel) return "Channel";
return String::empty;
}
const String imagePluginFilter::getParameterText (int index)
{
if (index==kChannel) {
if (roundFloatToInt(param[kChannel]*16.0f)==0) return String("Any");
else return String(roundFloatToInt(param[kChannel]*16.0f));
}
return String::empty;
}
const String imagePluginFilter::getInputChannelName (const int channelIndex) const
{
return String (channelIndex + 1);
}
const String imagePluginFilter::getOutputChannelName (const int channelIndex) const
{
return String (channelIndex + 1);
}
bool imagePluginFilter::isInputChannelStereoPair (int index) const
{
return true;
}
bool imagePluginFilter::isOutputChannelStereoPair (int index) const
{
return true;
}
//======================Programs================================================
void imagePluginFilter::setCurrentProgram (int index)
{
//save non-parameter info to the old program, except the first time
if (!init) {
programs->set(curBank,curProgram,"h",lastUIHeight);
programs->set(curBank,curProgram,"w",lastUIWidth);
programs->set(curBank,curProgram,"icon",icon);
programs->set(curBank,curProgram,"text",text);
programs->set(curBank,curProgram,"bgcolor",bgcolor.toString());
programs->set(curBank,curProgram,"textcolor",textcolor.toString());
}
init = false;
//then set the new program
curProgram = index;
param[kChannel] = (float)programs->getChildWithName("GlobalSettings").getProperty("channel")*0.0625f;
lastUIHeight = programs->get(curBank,curProgram,"h");
lastUIWidth = programs->get(curBank,curProgram,"w");
icon = programs->get(curBank,curProgram,"icon");
text = programs->get(curBank,curProgram,"text");
bgcolor = Colour::fromString(programs->get(curBank,curProgram,"bgcolor"));
textcolor = Colour::fromString(programs->get(curBank,curProgram,"textcolor"));
noteInput = programs->getChildWithName("GlobalSettings").getProperty("noteInput");
usePC = programs->getChildWithName("GlobalSettings").getProperty("usePC");
sendChangeMessage();
}
void imagePluginFilter::setCurrentBank(int index, int program)
{
if (!init) {
programs->set(curBank,curProgram,"h",lastUIHeight);
programs->set(curBank,curProgram,"w",lastUIWidth);
programs->set(curBank,curProgram,"icon",icon);
programs->set(curBank,curProgram,"text",text);
programs->set(curBank,curProgram,"bgcolor",bgcolor.toString());
programs->set(curBank,curProgram,"textcolor",textcolor.toString());
}
init = true;
curBank = index;
if (program==-1)
program = curProgram;
updateHostDisplay();
setCurrentProgram(program);
}
void imagePluginFilter::changeProgramName(int index, const String &newName) {
programs->set(curBank,index,"name",newName);
}
const String imagePluginFilter::getProgramName(int index) {
return programs->get(curBank,index,"name");
}
int imagePluginFilter::getCurrentProgram() {
return curProgram;
}
//==============================================================================
void imagePluginFilter::prepareToPlay (double sampleRate, int samplesPerBlock)
{
// do your pre-playback setup stuff here..
}
void imagePluginFilter::releaseResources()
{
// when playback stops, you can use this as an opportunity to free up any
// spare memory, etc.
}
void imagePluginFilter::processBlock (AudioSampleBuffer& buffer,
MidiBuffer& midiMessages)
{
for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
{
buffer.clear (i, 0, buffer.getNumSamples());
}
const int channel = roundFloatToInt(param[kChannel]*16.0f);
MidiBuffer::Iterator mid_buffer_iter(midiMessages);
MidiMessage midi_message(0xFE);
int sample_number;
while(mid_buffer_iter.getNextEvent(midi_message,sample_number)) {
if (channel==0 || midi_message.isForChannel(channel))
{
if (midi_message.isController() && midi_message.getControllerNumber()==0 && usePC) {
setCurrentBank(midi_message.getControllerValue());
updateHostDisplay();
}
else if (midi_message.isProgramChange() && usePC) {
setCurrentProgram(midi_message.getProgramChangeNumber());
updateHostDisplay();
}
else if (midi_message.isNoteOn() && noteInput) {
setCurrentProgram(midi_message.getNoteNumber());
updateHostDisplay();
}
}
}
midiMessages.clear();
}
//==============================================================================
AudioProcessorEditor* imagePluginFilter::createEditor()
{
return new imagePluginEditor (this);
}
//==============================================================================
void imagePluginFilter::getCurrentProgramStateInformation (MemoryBlock& destData)
{
// make sure the non-parameter settings are copied to the current program
programs->set(curBank,curProgram,"h",lastUIHeight);
programs->set(curBank,curProgram,"w",lastUIWidth);
programs->set(curBank,curProgram,"icon",icon);
programs->set(curBank,curProgram,"text",text);
programs->set(curBank,curProgram,"bgcolor",bgcolor.toString());
programs->set(curBank,curProgram,"textcolor",textcolor.toString());
// you can store your parameters as binary data if you want to or if you've got
// a load of binary to put in there, but if you're not doing anything too heavy,
// XML is a much cleaner way of doing it - here's an example of how to store your
// params as XML..
// create an outer XML element..
XmlElement xmlState ("MYPLUGINSETTINGS");
// add some attributes to it..
xmlState.setAttribute ("pluginVersion", 1);
xmlState.setAttribute ("bank", getCurrentBank());
xmlState.setAttribute ("program", getCurrentProgram());
xmlState.setAttribute ("progname", getProgramName(getCurrentProgram()));
for (int i=0;i<kNumParams;i++) {
xmlState.setAttribute (String(i), param[i]);
}
xmlState.setAttribute ("uiWidth", lastUIWidth);
xmlState.setAttribute ("uiHeight", lastUIHeight);
xmlState.setAttribute ("icon", icon);
xmlState.setAttribute ("text", text);
xmlState.setAttribute ("bgcolor", (int)(bgcolor.getARGB() & 0x00FFFFFF));
xmlState.setAttribute ("textcolor", (int)(textcolor.getARGB() & 0x00FFFFFF));
xmlState.setAttribute ("noteInput", noteInput);
xmlState.setAttribute ("usePC", usePC);
// then use this helper function to stuff it into the binary blob and return it..
copyXmlToBinary (xmlState, destData);
}
void imagePluginFilter::getStateInformation(MemoryBlock &destData) {
// make sure the non-parameter settings are copied to the current program
programs->set(curBank,curProgram,"h",lastUIHeight);
programs->set(curBank,curProgram,"w",lastUIWidth);
programs->set(curBank,curProgram,"icon",icon);
programs->set(curBank,curProgram,"text",text);
programs->set(curBank,curProgram,"bgcolor",bgcolor.toString());
programs->set(curBank,curProgram,"textcolor",textcolor.toString());
programs->getChildWithName("GlobalSettings").setProperty("lastBank",curBank,0);
programs->getChildWithName("GlobalSettings").setProperty("lastProgram",curProgram,0);
programs->getChildWithName("GlobalSettings").setProperty("noteInput",noteInput,0);
programs->getChildWithName("GlobalSettings").setProperty("usePC",usePC,0);
programs->writeToStream(MemoryOutputStream(destData,false));
}
void imagePluginFilter::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
{
// use this helper function to get the XML from this binary blob..
ScopedPointer<XmlElement> const xmlState = getXmlFromBinary (data, sizeInBytes);
if (xmlState != 0)
{
// check that it's the right type of xml..
if (xmlState->hasTagName ("MYPLUGINSETTINGS"))
{
// ok, now pull out our parameters..
changeProgramName(getCurrentProgram(),xmlState->getStringAttribute ("progname", "Default"));
for (int i=0;i<kNumParams;i++) {
param[i] = (float) xmlState->getDoubleAttribute (String(i), param[i]);
}
lastUIWidth = xmlState->getIntAttribute ("uiWidth", lastUIWidth);
lastUIHeight = xmlState->getIntAttribute ("uiHeight", lastUIHeight);
icon = xmlState->getStringAttribute ("icon", icon);
text = xmlState->getStringAttribute ("text", text);
bgcolor = Colour(xmlState->getIntAttribute ("bgcolor", bgcolor.getARGB()) | 0x00000000);
textcolor = Colour(xmlState->getIntAttribute ("textcolor", bgcolor.contrasting(0.8f).getARGB()) | 0x00000000);
noteInput = xmlState->getBoolAttribute ("noteInput", noteInput);
usePC = xmlState->getBoolAttribute ("usePC", usePC);
sendChangeMessage ();
}
}
}
void imagePluginFilter::setStateInformation (const void* data, int sizeInBytes) {
ScopedPointer<XmlElement> const xmlState = getXmlFromBinary (data, sizeInBytes);
if (xmlState == 0)
{
ValueTree vt = ValueTree::readFromStream(MemoryInputStream(data,sizeInBytes,false));
if (vt.isValid())
{
programs->removeAllChildren(0);
for (int i=0;i<vt.getNumChildren();i++)
{
programs->addChild(vt.getChild(i).createCopy(),i,0);
}
}
init=true;
setCurrentBank(vt.getChild(128).getProperty("lastBank",0),vt.getChild(128).getProperty("lastProgram",0));
}
else
{
if (xmlState->hasTagName ("MYPLUGINSETTINGS"))
{
if (xmlState->getIntAttribute("pluginVersion")<2)
{
fullscreen = xmlState->getBoolAttribute ("fullscreen", false);
for (int p=0;p<getNumPrograms();p++) {
String prefix = "P" + String(p) + ".";
programs->set(0,p,"channel",(float) xmlState->getDoubleAttribute (prefix+String(0), 0));
programs->set(0,p,"w",xmlState->getIntAttribute (prefix+"uiWidth", 400));
programs->set(0,p,"h", xmlState->getIntAttribute (prefix+"uiHeight", 400));
programs->set(0,p,"icon", xmlState->getStringAttribute (prefix+"icon", String::empty));
programs->set(0,p,"text", xmlState->getStringAttribute (prefix+"text", String::empty));
programs->set(0,p,"bgcolor", Colour(xmlState->getIntAttribute (prefix+"bgcolor")).toString());
programs->set(0,p,"textcolor", Colour(xmlState->getIntAttribute ("textcolor")).toString());
programs->set(0,p,"name", xmlState->getStringAttribute (prefix+"progname", String::empty));
}
init=true;
setCurrentBank(0,xmlState->getIntAttribute("program", 0));
}
else
{
//fullscreen = xmlState->getBoolAttribute ("fullscreen", false);
//for (int b=0;b<128;b++) {
// XmlElement* xmlBank = xmlState->getChildByName("Bank"+String(b));
// for (int p=0;p<getNumPrograms();p++) {
// int prog = b*128+p;
// String prefix = "P" + String(p) + "_";
// for (int i=0;i<kNumParams;i++) {
// programs[prog].param[i] = (float) xmlBank->getDoubleAttribute (prefix+String(i), programs[prog].param[i]);
// }
// programs[prog].lastUIWidth = xmlBank->getIntAttribute (prefix+"uiWidth", programs[prog].lastUIWidth);
// programs[prog].lastUIHeight = xmlBank->getIntAttribute (prefix+"uiHeight", programs[prog].lastUIHeight);
// programs[prog].icon = xmlBank->getStringAttribute (prefix+"icon", programs[prog].icon);
// programs[prog].text = xmlBank->getStringAttribute (prefix+"text", programs[prog].text);
// programs[prog].bgcolor = Colour(xmlBank->getIntAttribute (prefix+"bgcolor", programs[prog].bgcolor.getARGB()) | 0xFF000000);
// programs[prog].textcolor = Colour(xmlBank->getIntAttribute ("textcolor", programs[prog].bgcolor.contrasting(0.8f).getARGB()) | 0x00000000);
// programs[prog].name = xmlBank->getStringAttribute (prefix+"progname", programs[prog].name);
// }
//}
//init=true;
//setCurrentBank(xmlState->getIntAttribute("bank"),xmlState->getIntAttribute("program"));
}
}
}
}
void imagePluginFilter::setBankColours(Colour colour, Colour text)
{
for (int i=0;i<getNumPrograms();i++)
{
programs->set(curBank,i,"bgcolor",colour.toString());
programs->set(curBank,i,"textcolor",text.toString());
}
}
void imagePluginFilter::applySizeToBank(int h, int w)
{
for (int i=0;i<getNumPrograms();i++)
{
programs->set(curBank,i,"h",h);
programs->set(curBank,i,"w",w);
}
}
void imagePluginFilter::clearAllImages()
{
for (int i=0;i<getNumPrograms();i++)
programs->set(curBank,i,"icon", String(""));
}
| 36.291566 | 147 | 0.66795 | nonameentername |
07f164fc4e58f06307a47c51638aa3831438f707 | 28,524 | cxx | C++ | reduce_includes/reduce_includes.cxx | linev/misc | 4627ab0e62da1e66c3c4d656498463724713e891 | [
"MIT"
] | null | null | null | reduce_includes/reduce_includes.cxx | linev/misc | 4627ab0e62da1e66c3c4d656498463724713e891 | [
"MIT"
] | null | null | null | reduce_includes/reduce_includes.cxx | linev/misc | 4627ab0e62da1e66c3c4d656498463724713e891 | [
"MIT"
] | 1 | 2019-07-05T09:42:45.000Z | 2019-07-05T09:42:45.000Z | #include <cstdio>
#include <string>
#include <fstream>
#include <streambuf>
#include <cstdlib>
#include <cstring>
#include <streambuf>
#include <vector>
#include <algorithm>
#include <stdio.h>
std::string ReadFile(const char *fname)
{
std::ifstream t(fname, std::ios::binary);
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
return str;
}
void WriteFile(const char *fname, const std::string &content)
{
std::ofstream ostrm(fname, std::ios::binary);
ostrm.write(content.c_str(), content.length());
}
const char *exec_cmd = nullptr;
const char *go4arg = "$$go4obj$$";
const char *qtarg = "$$qtobj$$";
int ProcessFile(const char *fname)
{
std::string content = ReadFile(fname);
printf("Processing %s len %d\n", fname, (int) content.length());
if (content.length() < 20) return 0;
auto lastpos = content.length() - 8;
int nremoved = 0;
bool modified = false;
while (true) {
auto pos = content.rfind("#include", lastpos);
if (pos == std::string::npos) break;
content.insert(pos,"//");
WriteFile(fname, content);
std::string exec = exec_cmd;
auto p1 = exec.find(go4arg);
if (p1 != std::string::npos) {
exec.erase(p1, strlen(go4arg));
std::string objname = fname;
auto dot = objname.rfind(".");
objname.resize(dot+1);
objname.append("o"); // replace extension by object file
exec.insert(p1,objname);
std::string rmfile = "rm -f ";
rmfile.append(objname);
system(rmfile.c_str());
} else if ((p1 = exec.find(qtarg)) != std::string::npos) {
exec.erase(p1, strlen(qtarg));
std::string objname = fname;
auto dot = objname.rfind(".");
objname.resize(dot+1);
objname.append("o"); // replace extension by object file
auto slash = objname.rfind("/");
if (slash != std::string::npos)
objname.erase(0, slash+1);
objname.insert(0,".obj/");
exec.insert(p1,objname);
std::string rmfile = "rm -f ";
rmfile.append(objname);
system(rmfile.c_str());
}
int res = system(exec.c_str());
if ((p1 != std::string::npos) && (res==0)) {
std::string info = content.substr(pos, 50);
auto newline = info.find("\n");
if (newline != std::string::npos) info.resize(newline);
printf("Exec %s res %d place %s\n", exec.c_str(), res, info.c_str());
}
if (res == 0) {
nremoved++;
} else {
content.erase(pos,2);
modified = true;
}
if (pos < 8) break; // #include is 8 symbols long
lastpos = pos-8;
}
if (modified)
WriteFile(fname, content);
if (nremoved > 0)
printf("File %s removed %d\n", fname, nremoved);
return nremoved;
}
bool SameInclude(const std::string &name1, const std::string &name2)
{
if (name1 == name2) return true;
if ((name1[0] != 'c') && (name2[0] != 'c')) return false;
static const std::vector<std::string> vect1 =
{ "cassert", "cctype", "cerrno", "cfenv", "cfloat", "inttypes.h",
"climits", "clocale", "cmath", "csetjmp", "csignal", "cstdarg", "cstddef",
"cstdint", "cstdio", "cstring", "cstdlib", "ctime", "cuchar", "cwchar", "cwctype" };
static const std::vector<std::string> vect2 =
{ "assert.h", "ctype.h", "errno.h", "fenv.h", "float.h", "inttypes.h",
"limits.h", "locale.h", "math.h", "setjmp.h", "signal.h", "stdarg.h", "stddef.h",
"stdint.h", "stdio.h", "string.h", "stdlib.h", "time.h", "uchar.h", "wchar.h", "wctype.h" };
std::string n1, n2;
if (name2[0] == 'c') { n1 = name2; n2 = name1; }
else { n1 = name1; n2 = name2; }
auto pos1 = std::find(std::begin(vect1), std::end(vect1), n1);
if (pos1 == std::end(vect1)) return false;
int indx = pos1 - std::begin(vect1);
return vect2[indx] == n2;
}
int FindDuplicate(const char *fname)
{
std::string content = ReadFile(fname);
auto len = content.length();
if (len < 20) return 0;
int lastpos = 0;
std::vector<std::string> includes;
while (lastpos < len) {
auto pos = content.find("#include", lastpos);
if (pos == std::string::npos) break;
if (pos > 5) {
// simple check if include at the begin of the line
auto p0 = pos - 1;
while ((p0 > pos - 5) && ((content[p0] == ' ') || (content[p0] == '\t'))) p0--;
if (content[p0] != '\n') { lastpos = pos + 11; continue; }
}
pos += 9;
while ((pos < len) && (content[pos] == ' ')) pos++;
if (pos>=len) break;
char symb;
while ((pos < len) && (content[pos] == ' ') && (content[pos] != '\"')) pos++;
if (content[pos] == '<') symb = '>'; else
if (content[pos] == '\"') symb = '\"'; else { lastpos = pos+1; continue; }
auto pos2 = pos+1;
while ((pos2 < len) && (content[pos2] != symb)) pos2++;
if (pos2>=len) break;
lastpos = pos2+1;
if (pos2-pos>100) continue;
std::string inclname = content.substr(pos+1, pos2-pos-1);
includes.emplace_back(content.substr(pos+1, pos2-pos-1));
}
if (includes.size() < 2) return 0;
int dupl = 0;
for (int n1=0;n1<includes.size()-1;++n1) {
auto &name1 = includes[n1];
for (int n2=n1+1;n2<includes.size();++n2) {
auto &name2 = includes[n2];
if (SameInclude(name1, name2)) {
printf("File %s has duplicated include %s\n", fname, name1.c_str());
dupl++;
}
}
}
return dupl;
}
int CheckRootHeader(const char *fname)
{
std::string content = ReadFile(fname);
int res = 0;
if (content.find("Rtypes.h") != std::string::npos) {
if ((content.find("ClassDef") == std::string::npos) &&
(content.find("BIT(") == std::string::npos)) {
res = 1;
printf("%s not really using Rtypes.h, replace by RtypesCore.h\n", fname);
}
}
static const std::vector<std::string> std_types = { "vector", "deque", "list", "set", "multiset", "map", "multimap",
"unordered_set", "unordered_multiset", "unordered_map", "unordered_multimap" };
for(auto &name : std_types) {
std::string incl = std::string("<") + name + std::string(">");
std::string srch = std::string("std::") + name + std::string("<");
std::string srch2 = srch;
if (name == "map") { srch2 = "std::multimap"; }
if (name == "unordered_map") { srch2 = "std::unordered_multimap"; }
if (name == "multimap") { incl = "<map>"; srch2 = "std::map"; }
if (name == "unordered_multimap") { incl = "<unordered_map>"; srch2 = "std::unordered_map"; }
if (content.find(incl) != std::string::npos) {
if ((content.find(srch) == std::string::npos) && (content.find(srch2) == std::string::npos)) {
res = 1;
printf("%s not used %s include\n", fname, incl.c_str());
}
} else if (content.find(srch) != std::string::npos) {
res = 1;
printf("%s using std::%s without %s include\n", fname, name.c_str(), incl.c_str());
}
}
auto poss = content.find("#include <string>");
if (poss != std::string::npos) {
if (content.find("std::string", poss+20) == std::string::npos) {
res = 1;
printf("%s not used <string> include\n", fname);
}
} else if (content.find("std::string") != std::string::npos) {
res = 1;
printf("%s using std::string without <string> include\n", fname);
}
poss = content.find("<sstream>");
if (poss != std::string::npos) {
if (content.find("stringstream", poss+10) == std::string::npos) {
res = 1;
printf("%s not used <sstream> include\n", fname);
}
} else if (content.find("stringstream") != std::string::npos) {
res = 1;
printf("%s using std::stringstream without <sstream> include\n", fname);
}
poss = content.find("#include <utility>");
if (poss != std::string::npos) {
if (((content.find("std::pair", poss+20) == std::string::npos) && (content.find("std::tuple", poss+20) == std::string::npos)) ||
(content.find("map>") != std::string::npos)) {
res = 1;
printf("%s check usage of <utility> include\n", fname);
}
} else if (((content.find("std::pair") != std::string::npos) || (content.find("std::tuple") != std::string::npos))
&& (content.find("map>") == std::string::npos)) {
res = 1;
printf("%s using std::pair or std::tuple without <utility> include\n", fname);
}
auto pos0 = content.find("Riostream.h");
if (pos0 != std::string::npos) {
if ((content.find("ostream", pos0+8) == std::string::npos) &&
(content.find("fstream", pos0+8) == std::string::npos) &&
(content.find("std::cout", pos0+8) == std::string::npos) &&
(content.find("std::cerr", pos0+8) == std::string::npos) &&
(content.find("std::endl", pos0+8) == std::string::npos)) {
printf("%s not used Riostream.h\n", fname);
res = 1;
}
} else {
pos0 = content.find("<iostream>");
if (pos0 != std::string::npos) {
if ((content.find("cout", pos0+8) == std::string::npos) &&
(content.find("istream", pos0+8) == std::string::npos) &&
(content.find("ostream", pos0+8) == std::string::npos) &&
(content.find("cin", pos0+8) == std::string::npos) &&
(content.find("cerr", pos0+8) == std::string::npos) &&
(content.find("endl", pos0+8) == std::string::npos)) {
printf("%s not used <iostream>\n", fname);
res = 1;
}
}
pos0 = content.find("<fstream>");
if (pos0 != std::string::npos) {
if ((content.find("fstream", pos0+8) == std::string::npos)) {
printf("%s not used <fstream>\n", fname);
res = 1;
}
}
pos0 = content.find("<iomanip>");
if (pos0 != std::string::npos) {
if ((content.find("setw", pos0+8) == std::string::npos) &&
(content.find("setprecision", pos0+8) == std::string::npos) &&
(content.find("setfill", pos0+8) == std::string::npos) &&
(content.find("setiosflags", pos0+8) == std::string::npos) &&
(content.find("setbase", pos0+8) == std::string::npos)) {
printf("%s not used <iomanip>\n", fname);
res = 1;
}
}
}
static const std::vector<std::string> test_types = { "TObject", "TNamed", "TString" };
for(auto &clname : test_types) {
std::string incname = clname + ".h";
auto pos = content.find(incname);
if (pos != std::string::npos) {
if (content.find(clname, pos+incname.length()) == std::string::npos) {
printf("%s not used %s\n", fname, incname.c_str());
res = 1;
}
}
}
return res;
const char* name1 = strrchr(fname, '/');
if (!name1)
name1 = fname;
else
name1++;
const char* name2 = strrchr(fname, '.');
if (!name2) return 0;
std::string expected = std::string("ROOT_") + std::string(name1, name2-name1);
if (content.find("#pragma once") != std::string::npos) return res;
pos0 = content.find(std::string("#ifndef ") + expected);
if (pos0 == std::string::npos) {
printf("%s not found #ifndef %s\n", fname, expected.c_str());
return 1;
}
auto pos1 = content.find(std::string("#define ") + expected);
if ((pos1 == std::string::npos) || (pos1 < pos0)) {
printf("%s not found #define %s\n", fname, expected.c_str());
return 1;
}
return res;
}
int CheckRootSource(const char *fname)
{
std::string content = ReadFile(fname);
int res = 0;
auto pos0 = content.find("TROOT.h");
if (pos0 != std::string::npos) {
if ((content.find("ROOT::") == std::string::npos) &&
(content.find("gROOT") == std::string::npos) &&
(content.find("TROOT", pos0+6) == std::string::npos)) {
res = 1;
printf("%s not used TROOT.h\n", fname);
}
}
if (content.find("TMath.h") != std::string::npos) {
if (content.find("TMath::") == std::string::npos) {
res = 1;
printf("%s not used TMath.h\n", fname);
}
}
if (content.find("TStyle.h") != std::string::npos) {
if (content.find("gStyle")==std::string::npos) {
res = 1;
printf("%s not used TStyle.h\n", fname);
}
}
if (content.find("TEnv.h") != std::string::npos) {
if (content.find("gEnv")==std::string::npos) {
res = 1;
printf("%s not used TEnv.h\n", fname);
}
}
pos0 = content.find("TVirtualX.h");
if (pos0 != std::string::npos) {
if ((content.find("gVirtualX", pos0+10)==std::string::npos) &&
(content.find("TVirtualX", pos0+10)==std::string::npos)) {
res = 1;
printf("%s not used TVirtualX.h\n", fname);
}
}
if (content.find("RVersion.h") != std::string::npos) {
if ((content.find("ROOT_RELEASE")==std::string::npos) && (content.find("ROOT_VERSION")==std::string::npos)) {
res = 1;
printf("%s not used RVersion.h\n", fname);
}
}
if (content.find("TVirtualGL.h") != std::string::npos) {
if (content.find("gGLManager")==std::string::npos) {
res = 1;
printf("%s not used TVirtualGL.h\n", fname);
}
}
pos0 = content.find("TVirtualPad.h");
if (pos0 != std::string::npos) {
if ((content.find("gPad", pos0+9)==std::string::npos) &&
(content.find("fPad", pos0+9)==std::string::npos) &&
(content.find("GetSelectedPad()", pos0+9)==std::string::npos) &&
(content.find("TVirtualPad", pos0+9)==std::string::npos)) {
res = 1;
printf("%s not used TVirtualPad.h\n", fname);
}
}
if (content.find("TGClient.h") != std::string::npos) {
if ((content.find("gClient")==std::string::npos) && (content.find("fClient")==std::string::npos)) {
res = 1;
printf("%s not used TGClient.h\n", fname);
}
}
if ((content.find("TPad.h") != std::string::npos) && (content.find("TCanvas.h") != std::string::npos)) {
printf("%s both TPad.h and TCanvas.h found\n", fname);
res = 1;
}
pos0 = content.find("TPad.h");
if (pos0 != std::string::npos) {
bool has_gpad = (content.find("gPad", pos0+5) != std::string::npos);
bool has_pad = (content.find("TPad", pos0+5) != std::string::npos);
if (has_gpad && !has_pad) {
printf("%s only gPad used with TPad.h, replace by TVirtualPad.h\n", fname);
res = 1;
}
if (!has_gpad && !has_pad) {
printf("%s not used TPad.h\n", fname);
res = 1;
}
}
pos0 = content.find("TCanvas.h");
if (pos0 != std::string::npos) {
bool has_gpad = (content.find("gPad", pos0+8) != std::string::npos);
bool has_pad = (content.find("TPad", pos0+8) != std::string::npos);
bool has_canvas = (content.find("TCanvas", pos0+8) != std::string::npos);
bool has_get = (content.find("GetCanvas()", pos0+8) != std::string::npos);
if (has_gpad && !has_pad && !has_canvas && !has_get) {
printf("%s only gPad used with TCanvas.h, replace by TVirtualPad.h\n", fname);
res = 1;
}
if (has_gpad && has_pad && !has_canvas && !has_get) {
printf("%s only TPad used with TCanvas.h, replace by TPad.h\n", fname);
res = 1;
}
if (!has_gpad && !has_pad && !has_canvas && !has_get) {
printf("%s not used TCanvas.h\n", fname);
res = 1;
}
}
pos0 = content.find("TSystem.h");
if (pos0 != std::string::npos) {
bool has_gsys = (content.find("gSystem", pos0+8) != std::string::npos);
bool has_sys = (content.find("TSystem", pos0+8) != std::string::npos);
bool has_types = false;
static const std::vector<std::string> sys_types =
{ "FileStat_t", "UserGroup_t", "SysInfo_t", "CpuInfo_t", "MemInfo_t", "ProcInfo_t",
"RedirectHandle_t", "TProcessEventTimer", "gProgPath", "gProgName", "gRootDir", "gSystemMutex" };
if (!has_gsys && !has_sys) {
for (auto &name : sys_types)
if (content.find(name, pos0+8) != std::string::npos) {
has_types = true;
break;
}
printf("%s not used TSystem.h, has types = %s\n", fname, (has_types ? "true" : "false"));
res = 1;
}
}
pos0 = content.find("TDirectory.h");
if (pos0 != std::string::npos) {
if ((content.find("TDirectory",pos0+10)==std::string::npos) &&
(content.find("GetDirectory", pos0+7) == std::string::npos) &&
(content.find("gDirectory",pos0+10)==std::string::npos)) {
res = 1;
printf("%s not used TDirectory.h\n", fname);
}
}
pos0 = content.find("TApplication.h");
if (pos0 != std::string::npos) {
if ((content.find("TApplication",pos0+12)==std::string::npos) &&
(content.find("GetApplication()->",pos0+12)==std::string::npos) &&
(content.find("gApplication",pos0+12)==std::string::npos)) {
res = 1;
printf("%s not used TApplication.h\n", fname);
}
}
pos0 = content.find("TRint.h");
if (pos0 != std::string::npos) {
if (content.find("TRint", pos0+8) == std::string::npos) {
printf("%s not used TRint.h\n", fname);
res = 1;
}
}
pos0 = content.find("TFile.h");
if ((pos0 != std::string::npos) && (content.find("GetCurrentFile", pos0+7) == std::string::npos) &&
(content.find("GetFile", pos0+7) == std::string::npos)) {
bool has_gfile = (content.find("gFile", pos0+7) != std::string::npos);
bool has_gdir = (content.find("gDirectory", pos0+7) != std::string::npos);
bool has_file = (content.find("TFile", pos0+7) != std::string::npos);
if (has_gdir && !has_gfile && !has_file) {
printf("%s only gDirectory used with TFile.h, replace by TDirectory.h\n", fname);
res = 1;
}
if (!has_gdir && !has_gfile && !has_file) {
printf("%s not used TFile.h\n", fname);
res = 1;
}
}
pos0 = content.find("TKey.h");
if (pos0 != std::string::npos) {
if ((content.find("TKey",pos0+10)==std::string::npos) &&
(content.find("GetKey",pos0+10)==std::string::npos)) {
res = 1;
printf("%s not used TKey.h\n", fname);
}
}
pos0 = content.find("TTree.h");
if (pos0 != std::string::npos) {
bool has_gtree = (content.find("gTree", pos0+7) != std::string::npos);
bool has_tree = (content.find("TTree", pos0+7) != std::string::npos);
if (!has_gtree && !has_tree) {
printf("%s not used TTree.h\n", fname);
res = 1;
}
}
pos0 = content.find("TColor.h");
if (pos0 != std::string::npos) {
if (content.find("TColor", pos0+8) == std::string::npos) {
printf("%s not used TColor.h\n", fname);
res = 1;
}
}
pos0 = content.find("Riostream.h");
if (pos0 != std::string::npos) {
if ((content.find("ostream", pos0+8) == std::string::npos) &&
(content.find("fstream", pos0+8) == std::string::npos) &&
(content.find("std::cout", pos0+8) == std::string::npos) &&
(content.find("std::cerr", pos0+8) == std::string::npos) &&
(content.find("std::endl", pos0+8) == std::string::npos)) {
printf("%s not used Riostream.h\n", fname);
res = 1;
}
} else {
pos0 = content.find("<iostream>");
if (pos0 != std::string::npos) {
if ((content.find("cout", pos0+8) == std::string::npos) &&
(content.find("istream", pos0+8) == std::string::npos) &&
(content.find("ostream", pos0+8) == std::string::npos) &&
(content.find("cin", pos0+8) == std::string::npos) &&
(content.find("cerr", pos0+8) == std::string::npos) &&
(content.find("endl", pos0+8) == std::string::npos)) {
printf("%s not used <iostream>\n", fname);
res = 1;
}
}
pos0 = content.find("<fstream>");
if (pos0 != std::string::npos) {
if ((content.find("fstream", pos0+8) == std::string::npos)) {
printf("%s not used <fstream>\n", fname);
res = 1;
}
}
pos0 = content.find("<iomanip>");
if (pos0 != std::string::npos) {
if ((content.find("setw", pos0+8) == std::string::npos) &&
(content.find("setprecision", pos0+8) == std::string::npos) &&
(content.find("setfill", pos0+8) == std::string::npos) &&
(content.find("setiosflags", pos0+8) == std::string::npos) &&
(content.find("setbase", pos0+8) == std::string::npos)) {
printf("%s not used <iomanip>\n", fname);
res = 1;
} else {
printf("OK iostream\n");
}
}
}
pos0 = content.find("TClass.h");
if (pos0 != std::string::npos) {
if ((content.find("IsA()->", pos0+8) == std::string::npos) &&
(content.find("Class()->", pos0+8) == std::string::npos) &&
(content.find("TClass", pos0+8) == std::string::npos)) {
printf("%s not uses TClass.h\n", fname);
res = 1;
}
}
pos0 = content.find("TView.h");
if (pos0 != std::string::npos) {
if ((content.find("TView", pos0+8) == std::string::npos) &&
(content.find("GetView()", pos0+8) == std::string::npos)) {
printf("%s not uses TView.h\n", fname);
res = 1;
}
}
pos0 = content.find("TRandom.h");
if (pos0 != std::string::npos) {
if ((content.find("gRandom", pos0+8) == std::string::npos) &&
(content.find("TRandom", pos0+8) == std::string::npos)) {
printf("%s not uses TRandom.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGMenu.h");
if (pos0 != std::string::npos) {
if ((content.find("TGMenuBar", pos0+8) == std::string::npos) &&
(content.find("TGPopupMenu", pos0+8) == std::string::npos) &&
(content.find("TGMenuEntry", pos0+8) == std::string::npos) &&
(content.find("TGMenuTitle", pos0+8) == std::string::npos)) {
printf("%s not uses TGMenu.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGSplitter.h");
if (pos0 != std::string::npos) {
if ((content.find("TGSplitter", pos0+8) == std::string::npos) &&
(content.find("TGVSplitter", pos0+8) == std::string::npos) &&
(content.find("TGHSplitter", pos0+8) == std::string::npos) &&
(content.find("fSplitter", pos0+8) == std::string::npos)) {
printf("%s not uses TGSplitter.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGTab.h");
if (pos0 != std::string::npos) {
if ((content.find("TGTab", pos0+8) == std::string::npos) &&
(content.find("fTab", pos0+8) == std::string::npos)) {
printf("%s not uses TGTab.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGDockableFrame.h");
if (pos0 != std::string::npos) {
if ((content.find("TGDockableFrame", pos0+8) == std::string::npos) &&
(content.find("GetToolDock()->", pos0+8) == std::string::npos)) {
printf("%s not uses TGDockableFrame.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGDoubleSlider.h");
if (pos0 != std::string::npos) {
if ((content.find("TGDoubleSlider", pos0+8) == std::string::npos) &&
(content.find("TGDoubleVSlider", pos0+8) == std::string::npos) &&
(content.find("TGDoubleHSlider", pos0+8) == std::string::npos) &&
(content.find("GetSlider()", pos0+8) == std::string::npos) &&
(content.find("Slider->", pos0+8) == std::string::npos)) {
printf("%s not uses TGDoubleSlider.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGSlider.h");
if (pos0 != std::string::npos) {
if ((content.find("TGSlider", pos0+8) == std::string::npos) &&
(content.find("TGHSlider", pos0+8) == std::string::npos) &&
(content.find("TGVSlider", pos0+8) == std::string::npos) &&
(content.find("fSlider", pos0+8) == std::string::npos)) {
printf("%s not uses TGSlider.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGButton.h");
if (pos0 != std::string::npos) {
if ((content.find("TGButton", pos0+8) == std::string::npos) &&
(content.find("TGTextButton", pos0+8) == std::string::npos) &&
(content.find("TGPictureButton", pos0+8) == std::string::npos) &&
(content.find("TGCheckButton", pos0+8) == std::string::npos) &&
(content.find("TGRadioButton", pos0+8) == std::string::npos) &&
(content.find("TGSplitButton", pos0+8) == std::string::npos)) {
printf("%s not uses TGButton.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGFSContainer.h");
if (pos0 != std::string::npos) {
if ((content.find("TGFileItem", pos0+8) == std::string::npos) &&
(content.find("TGFileContainer", pos0+8) == std::string::npos)) {
printf("%s not uses TGFSContainer.h\n", fname);
res = 1;
}
}
pos0 = content.find("TGTextEditDialogs.h");
if (pos0 != std::string::npos) {
if ((content.find("TGSearchDialog", pos0+8) == std::string::npos) &&
(content.find("TGPrintDialog", pos0+8) == std::string::npos) &&
(content.find("TGGotoDialog", pos0+8) == std::string::npos)) {
printf("%s not uses TGTextEditDialogs.h\n", fname);
res = 1;
}
}
static const std::vector<std::string> test_types = {
"TObjString", "TTimer", "TUrl", "TBrowser", "TImage",
"TDatime", "TTimeStamp", "TDate", "TVectorD", "TMatrixD",
"THStack", "TArc", "TLine", "TText", "TLatex", "TCutG", "TBox", "TGaxis",
"TPaveText", "TPaveStats", "TGraph", "TMarker", "TPoint", "TEllipse",
"TPolyLine3D", "TPolyMarker3D", "TLegend", "TProfile",
"TH1", "TH2", "TH3", "TF1", "TF2", "TF3", "TBuffer", "TMap",
"TStopwatch", "TExec", "TMemFile", "TNamed", "TObject",
// gui classes
"TGCanvas", "TGColorDialog", "TGColorSelect", "TGComboBox",
"TGFileBrowser", "TGFileDialog", "TGFontDialog",
"TGFont", "TGFrame", "TGFSComboBox", "TGIcon",
"TGInputDialog", "TGLabel", "TGLayout", "TGListBox", "TGListTree", "TGListView",
"TGMdiDecorFrame", "TGMdiFrame", "TGMdi", "TGMdiMainFrame",
"TGMdiMenu", "TGMsgBox", "TGNumberEntry", "TGObject", "TGPack", "TGPasswdDialog",
"TGPicture", "TGProgressBar", "TGScrollBar", "TGSimpleTable", "TGSimpleTableInterface",
"TGSpeedo", "TGSplitFrame", "TGStatusBar", "TGTableCell", "TGTable",
"TGTableHeader", "TGTableLayout", "TGTextBuffer", "TGTextEdit", "TGTextEditor",
"TGTextEntry", "TGText", "TGTextView", "TGToolBar", "TGToolTip", "TGuiBuilder",
"TGView", "TGXYLayout"
};
for(auto &clname : test_types) {
std::string incname = clname + ".h";
auto pos = content.find(incname);
if (pos != std::string::npos) {
if (content.find(clname, pos+incname.length()) == std::string::npos) {
printf("%s not used %s\n", fname, incname.c_str());
res = 1;
}
}
}
return res;
}
int main(int argc, const char **argv)
{
printf("Reduce includes utility v0.5\n");
if (argc < 3) {
printf("Too few arguments\n");
return 1;
}
exec_cmd = argv[1];
printf("Build cmd: %s\n", exec_cmd);
int sum = 0;
const char *kind = "removed";
if (!strcmp(exec_cmd,"duplicate")) {
kind = "duplicated";
for (int n=2; n<argc; ++n)
sum += FindDuplicate(argv[n]);
} else if (!strcmp(exec_cmd,"roothdr")) {
kind = "roothdr";
for (int n=2; n<argc; ++n)
sum += CheckRootHeader(argv[n]);
} else if (!strcmp(exec_cmd,"rootsrc")) {
kind = "rootsrc";
for (int n=2; n<argc; ++n)
sum += CheckRootSource(argv[n]);
} else {
for (int n=2; n<argc; ++n)
sum += ProcessFile(argv[n]);
}
printf("Files %d Total %s includes %d\n", argc-2, kind, sum);
return 0;
}
| 33.957143 | 135 | 0.534743 | linev |
07f1fda9b0cbc86c226ca508d9ff756a62166e8e | 2,868 | cpp | C++ | src/model.cpp | nek0bit/LoopCube | 882296f32bfe3a8b1765950a9b8c9e24af75d009 | [
"MIT"
] | 9 | 2020-04-03T21:20:02.000Z | 2021-08-23T19:57:57.000Z | src/model.cpp | nek0bit/LoopCube | 882296f32bfe3a8b1765950a9b8c9e24af75d009 | [
"MIT"
] | 2 | 2020-12-05T01:05:58.000Z | 2021-01-23T04:41:24.000Z | src/model.cpp | nek0bit/LoopCube | 882296f32bfe3a8b1765950a9b8c9e24af75d009 | [
"MIT"
] | 4 | 2020-07-04T13:47:33.000Z | 2021-09-11T15:29:08.000Z | #include "model.hpp"
Model::Model(const GLuint shader, const std::vector<Vertex>& vertices)
: refCount{std::make_shared<int>(1)},
vao{0},
vbo{0},
size{0},
shader{shader}
{
if (shader != 0)
{
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
if (vertices.size() > 0)
setBufferData(vertices);
}
}
Model::~Model()
{
if (*refCount == 1 && shader != 0)
{
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
(*refCount)--;
}
// Copy
Model::Model(const Model& source)
: refCount{source.refCount},
vao{source.vao},
vbo{source.vbo},
size{source.size},
shader{source.shader}
{
(*refCount)++;
}
// Move
Model::Model(Model&& source)
: refCount{std::move(source.refCount)},
vao{std::move(source.vao)},
vbo{std::move(source.vbo)},
size{std::move(source.size)},
shader{std::move(source.shader)}
{
// Probably simpler to do it this way
(*refCount)++;
}
void Model::setBufferData(const std::vector<Vertex>& vertices, const GLenum usage)
{
if (shader != 0)
{
// Bind both values
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
size = vertices.size(); // Used for glDrawArrays size
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), &vertices[0], usage);
setupVertexLayout();
}
}
void Model::setupVertexLayout()
{
constexpr uint8_t Stride = sizeof(Vertex);
constexpr uint8_t positionSize = 3;
constexpr uint8_t texCoordOffset = sizeof(glm::vec3); // First element in struct
constexpr uint8_t texCoordSize = 2;
const GLuint positionAttribute = glGetAttribLocation(shader, "position");
const GLuint texCoordAttribute = glGetAttribLocation(shader, "texCoord");
// Position
// InputAttrib - valSize - Type - shouldNormalize - Stride - Offset
glVertexAttribPointer(positionAttribute, positionSize, GL_FLOAT, GL_FALSE, Stride, 0);
// texCoord
glVertexAttribPointer(texCoordAttribute, texCoordSize, GL_FLOAT, GL_FALSE,
Stride, (void*)(texCoordOffset));
// Enable Attrib Arrays
glEnableVertexAttribArray(positionAttribute);
glEnableVertexAttribArray(texCoordAttribute);
}
void Model::draw(const GLint& uModel,
const GLint& uTex,
const glm::vec3& translate,
const glm::vec3& scale,
const glm::vec2& texturePos) const noexcept
{
glBindVertexArray(vao);
glm::mat4 model{1.0f};
model = glm::translate(model, translate);
model = glm::scale(model, scale);
glUniformMatrix4fv(uModel, 1, GL_FALSE, glm::value_ptr(model));
glUniform2fv(uTex, 1, glm::value_ptr(texturePos));
glDrawArrays(GL_TRIANGLES, 0, size);
}
| 26.803738 | 93 | 0.623431 | nek0bit |
07f86e762d5471c705dde7af207b48bd25e576bf | 6,958 | hpp | C++ | Engine/Code/Engine/Input/KeyCode.hpp | cugone/Abrams2022 | 54efe5fdd7d2d9697f005ee45a171ecea68d0df8 | [
"MIT"
] | 1 | 2020-07-14T06:58:50.000Z | 2020-07-14T06:58:50.000Z | Engine/Code/Engine/Input/KeyCode.hpp | cugone/Abrams2022 | 54efe5fdd7d2d9697f005ee45a171ecea68d0df8 | [
"MIT"
] | 20 | 2021-11-29T14:09:33.000Z | 2022-03-26T20:12:44.000Z | Engine/Code/Engine/Input/KeyCode.hpp | cugone/Abrams2022 | 54efe5fdd7d2d9697f005ee45a171ecea68d0df8 | [
"MIT"
] | 2 | 2019-05-01T21:49:33.000Z | 2021-04-01T08:22:21.000Z | #pragma once
#include "Engine/Core/TypeUtils.hpp"
// clang-format off
enum class KeyCode : int {
FirstMouseButton_ /* Internal use only. */
, LButton = FirstMouseButton_ /* Left Mouse Button */
, RButton /* Right Mouse Button */
, Cancel /* Control-break processing */
, MButton /* Middle Mouse Button */
, XButton1 /* Xtra Mouse Button 1 */
, XButton2 /* Xtra Mouse Button 2 */
, LastMouseButton_ /* Internal use only. */
, First_ /* Internal use only. */
, Back = First_ /* Also Backspace */
, Backspace = Back /* Also Back */
, Tab
, Clear
, Return /* Also Enter */
, Enter = Return
, Shift /* either RShift or LShift */
, Ctrl /* either RCtrl or LCtrl */
, Menu /* either RMenu or LMenu, Also Alt */
, Alt = Menu /* either RAlt or LAlt, Also Menu */
, Pause
, Capital /* Also CapsLock */
, CapsLock = Capital
, Kana
, Hangul /* Also Hangeul */
, Hangeul = Hangul /* Also Hangul */
, Junja
, Final
, Hanja
, Kanji
, Escape /* Also Esc */
, Esc = Escape
, Convert
, NonConvert
, Accept
, ModeChange
, Space /* Also Spacebar */
, Spacebar = Space
, Prior /* Also PageUp */
, PageUp = Prior
, Next /* Also PageDown and PageDn */
, PageDown = Next /* Also PageDn or Next */
, PageDn = Next /* Also PageDown or Next */
, End
, Home
, Left
, Up
, Right
, Down
, Select
, Print
, Execute
, Snapshot /* Also PrintScreen */
, PrintScreen = Snapshot /* Also Snapshot */
, Insert
, Delete /* Also Del */
, Del = Delete /* Also Delete */
, Help
, Numeric0 /* Number key above keyboard */
, Numeric1 /* Number key above keyboard */
, Numeric2 /* Number key above keyboard */
, Numeric3 /* Number key above keyboard */
, Numeric4 /* Number key above keyboard */
, Numeric5 /* Number key above keyboard */
, Numeric6 /* Number key above keyboard */
, Numeric7 /* Number key above keyboard */
, Numeric8 /* Number key above keyboard */
, Numeric9 /* Number key above keyboard */
, A
, B
, C
, D
, E
, F
, G
, H
, I
, J
, K
, L
, M
, N
, O
, P
, Q
, R
, S
, T
, U
, V
, W
, X
, Y
, Z
, LWin
, RWin
, Apps
, Sleep
, NumPad0
, NumPad1
, NumPad2
, NumPad3
, NumPad4
, NumPad5
, NumPad6
, NumPad7
, NumPad8
, NumPad9
, Multiply /* NumPad * */
, Add /* NumPad + */
, Separator /* Also NumPadEnter */
, NumPadEnter = Separator /* Also Separator */
, Subtract /* NumPad - */
, Decimal /* NumPad . */
, Divide /* NumPad / */
, F1
, F2
, F3
, F4
, F5
, F6
, F7
, F8
, F9
, F10
, F11
, F12
, F13
, F14
, F15
, F16
, F17
, F18
, F19
, F20
, F21
, F22
, F23
, F24
, NumLock
, Scroll /* Also ScrollLock */
, ScrollLock = Scroll /* Also Scroll */
, Oem_Nec_Equal
, Oem_Fj_Jisho
, Oem_Fj_Masshou
, Oem_Fj_Touroku
, Oem_Fj_Loya
, Oem_Fj_Roya
, LShift
, RShift
, LControl /* Also LCtrl */
, LCtrl = LControl /* Also LControl */
, RControl /* Also RCtrl */
, RCtrl = RControl /* Also RControl */
, RMenu /* Also RAlt */
, RAlt = RMenu /* Also RMenu */
, LMenu /* Also LAlt */
, LAlt = LMenu /* Also LMenu */
, Browser_Back
, Browser_Forward
, Browser_Refresh
, Browser_Stop
, Browser_Search
, Browser_Favorites
, Browser_Home
, Volume_Mute
, Volume_Down
, Volume_Up
, Media_Next_Track
, Media_Prev_Track
, Media_Stop
, Media_Play_Pause
, Launch_Mail
, Launch_Media_Select
, Launch_App1
, Launch_App2
, Oem_1 /* Key ;: */
, Semicolon = Oem_1 /* Key ;: */
, Oem_Plus /* Key =+ */
, Equals = Oem_Plus /* Key =+ */
, Oem_Comma /* Key ,< */
, Comma = Oem_Comma /* Key ,< */
, Oem_Minus /* Key -_ */
, Minus = Oem_Minus /* Key -_ */
, Oem_Period /* Key .> */
, Period = Oem_Period /* Key .> */
, Oem_2 /* Key /? */
, ForwardSlash = Oem_2 /* Key /?, Also FSlash */
, FSlash = Oem_2 /* Key /?, Also ForwardSlash */
, Oem_3 /* Key `~ */
, Backquote = Oem_3 /* Key `~, Also Tilde */
, Tilde = Oem_3 /* Key `~, Also Backquote */
, Gamepad_First_ /* Internal use only. */
, Gamepad_A = Gamepad_First_
, Gamepad_FaceButton_Bottom = Gamepad_A /* Also Gamepad_A */
, Gamepad_B
, Gamepad_FaceButton_Right = Gamepad_B /* Also Gamepad_B */
, Gamepad_X
, Gamepad_FaceButton_Left = Gamepad_X /* Also Gamepad_X */
, Gamepad_Y
, Gamepad_FaceButton_Top = Gamepad_Y /* Also Gamepad_Y */
, Gamepad_Right_Shoulder
, Gamepad_Left_Shoulder
, Gamepad_Left_Trigger
, Gamepad_Right_Trigger
, Gamepad_DPad_Up
, Gamepad_DPad_Down
, Gamepad_DPad_Left
, Gamepad_DPad_Right
, Gamepad_Menu
, Gamepad_View
, Gamepad_Left_Thumbstick_Button
, Gamepad_Right_Thumbstick_Button
, Gamepad_Left_Thumbstick_Up
, Gamepad_Left_Thumbstick_Down
, Gamepad_Left_Thumbstick_Right
, Gamepad_Left_Thumbstick_Left
, Gamepad_Right_Thumbstick_Up
, Gamepad_Right_Thumbstick_Down
, Gamepad_Right_Thumbstick_Right
, Gamepad_Right_Thumbstick_Left
, Gamepad_Last_ /* Internal use only. */
, Oem_4 /* Key [{ */
, LeftBracket = Oem_4 /* Key [{, Also LBracket */
, LBracket = Oem_4 /* Key [{, Also LeftBracket */
, Oem_5 /* Key \|, Also Backslash */
, Backslash = Oem_5 /* Key \| */
, Oem_6 /* Key ]} */
, RightBracket = Oem_6 /* Key ]}, Also RBracket */
, RBracket = Oem_6 /* Key ]}, Also RightBracket */
, Oem_7 /* Key '" */
, Apostrophe = Oem_7 /* Key '", Also Apostrophe */
, SingleQuote = Oem_7 /* Key '", Also SingleQuote */
, Oem_8 /* misc. unknown */
, Oem_Ax
, Oem_102 /* RT 102's "<>" or "\|" */
, Ico_Help /* Help key on ICO keyboard */
, Ico_00 /* 00 key on ICO keyboard */
, ProcessKey
, Ico_Clear /* Clear key on ICO keyboard */
, Packet /* Key is packet of data */
, Oem_Reset
, Oem_Jump
, Oem_Pa1
, Oem_Pa2
, Oem_Pa3
, Oem_WsCtrl
, Oem_CuSel
, Oem_Attn
, Oem_Finish
, Oem_Copy
, Oem_Auto
, Oem_EnlW
, Oem_BackTab
, Attn
, CrSel
, ExSel
, ErEof
, Play
, Zoom
, NoName
, Pa1
, Oem_Clear
, Last_ /* Internal use only */
, Unknown = 0xFF /* A manufacturer-specific key was pressed. */
, Max /* Internal use only */
};
// clang-format on
template<>
struct TypeUtils::is_incrementable_enum_type<KeyCode> : std::true_type {};
[[nodiscard]] unsigned char ConvertKeyCodeToWinVK(const KeyCode& code) noexcept;
[[nodiscard]] KeyCode ConvertWinVKToKeyCode(unsigned char winVK) noexcept;
| 24.761566 | 80 | 0.564817 | cugone |
07f9c3bc8ecb9210aff979cedcb847b59ef9df89 | 8,809 | cpp | C++ | LightPOV/ModeTest/communication.cpp | BensonYang1999/sciyen-ES-Lux | 071ce2c29f48eaab45be56208ed88512eb685349 | [
"BSD-3-Clause"
] | 5 | 2021-04-17T10:58:35.000Z | 2021-04-17T11:02:55.000Z | LightPOV/ModeTest/communication.cpp | BensonYang1999/sciyen-ES-Lux | 071ce2c29f48eaab45be56208ed88512eb685349 | [
"BSD-3-Clause"
] | null | null | null | LightPOV/ModeTest/communication.cpp | BensonYang1999/sciyen-ES-Lux | 071ce2c29f48eaab45be56208ed88512eb685349 | [
"BSD-3-Clause"
] | 29 | 2021-01-30T10:19:03.000Z | 2021-04-18T17:40:11.000Z | #include "communication.h"
extern TaskHandle_t LED_UPDATE;
extern TaskHandle_t WIFI_HANDLE;
HTTPClient http;
Communication::Communication(){
}
void Communication::init(){
connect();
OTA();
}
void Communication::OTA()
{
ArduinoOTA.onStart([]() {
vTaskDelete(WIFI_HANDLE);
vTaskDelete(LED_UPDATE);
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
{
type = "sketch";
}
else
{ // U_FS
type = "filesystem";
}
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
{
Serial.println("Auth Failed");
}
else if (error == OTA_BEGIN_ERROR)
{
Serial.println("Begin Failed");
}
else if (error == OTA_CONNECT_ERROR)
{
Serial.println("Connect Failed");
}
else if (error == OTA_RECEIVE_ERROR)
{
Serial.println("Receive Failed");
}
else if (error == OTA_END_ERROR)
{
Serial.println("End Failed");
}
});
ArduinoOTA.begin();
}
void Communication::connect(){
int n = WiFi.scanNetworks();
for (int i = 0; i < n; ++i){
if (WiFi.SSID(i) == WIFI_SSID1){
WiFi.begin(WIFI_SSID1, WIFI_PASS1); //trying to connect the modem
Serial.println();
Serial.print("Connected to ");
Serial.println(WIFI_SSID1);
break;
}
if (WiFi.SSID(i) == WIFI_SSID2){
WiFi.begin(WIFI_SSID2, WIFI_PASS2); //trying to connect the modem
Serial.println();
Serial.print("Connected to ");
Serial.println(WIFI_SSID2);
break;
}
if (WiFi.SSID(i) == WIFI_SSID3){
WiFi.begin(WIFI_SSID3, WIFI_PASS3); //trying to connect the modem
Serial.println();
Serial.print("Connected to ");
Serial.println(WIFI_SSID3);
break;
}
}
Serial.print("Waiting for connection");
// Wait for connection
int connection_times = 0;
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
connection_times++;
if (connection_times >= WIFI_CONNECT_RETRY)
{
Serial.println();
Serial.println("Connection Failed! Rebooting...");
delay(1000);
ESP.restart();
}
}
Serial.println("");
/*Serial.print("Connected to ");
Serial.println(ssid);*/
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void Communication::feed_color_param(ValueParam* p, String s){
int comma = s.indexOf(',');
uint32_t upper = s.substring(0, comma).toInt();
p->func = (SchedulerFunc)((upper >> 16) & 0xff);
p->range = (upper >> 8) & 0xff;
p->lower = upper & 0xff;
uint32_t lower = s.substring(comma+1).toInt();
p->p1 = (lower >> 8) & 0xff;
p->p2 = lower & 0xff;
}
int Communication::feed_data(Mode* m, String s){
int start=0, len=0;
uint32_t checksum = 0;
Serial.println(s);
for (int i=0; i<s.length(); i++){
// If the first charactor is not `M`, return as error
if (i==0 && s[0] != 'M') return 1;
if ((s[i] >= '0' && s[i] <= '9') || s[i] == ',') continue;
// If there is multi times non-number charactor appearing, it
// will skip them till next number comes
if (start != i){
// Length of string must larger than 0
String meta = s.substring(start, i);
/*
// If it failed to convert, it will return 0.
if (len == 0) // Mode Type
(*m).mode = (MODES)meta.toInt();
else if (len == 1) // Start time
(*m).start_time = meta.toInt();
else{ // Other parameter
(*m).param[len-2] = meta.toInt();
checksum += (*m).param[len-2];
}
len++;
*/
char key = s[start-1];
switch(key){
case 'M': (*m).mode = (MODES)meta.toInt(); break;
case 'S': (*m).start_time = meta.toInt(); break;
case 'D': (*m).duration = meta.toInt(); break;
case 'X': feed_color_param(&(m->XH), meta);break;
case 'Y': feed_color_param(&(m->XS), meta);break;
case 'Z': feed_color_param(&(m->XV), meta);break;
case 'U': feed_color_param(&(m->YH), meta);break;
case 'V': feed_color_param(&(m->YS), meta);break;
case 'W': feed_color_param(&(m->YV), meta);break;
case 'P':
int comma = meta.indexOf(',');
uint32_t upper = meta.substring(0, comma).toInt();
m->param[0] = (upper >> 8) & 0xff;
m->param[1] = upper & 0xff;
uint32_t lower = meta.substring(comma+1).toInt();
m->param[2] = (lower >> 8) & 0xff;
m->param[3] = lower & 0xff;
break;
}
}
if (s[i] == ';'){
/*
// Perform checksum and break
String meta = s.substring(start, i);
if (checksum & 0xff == meta.toInt())
return len-2;
else // Checksum failed
*/
return 0;
}
start = i+1;
}
// End without checksum, unusual request
return 0;
}
bool Communication::receive(Mode* m, int current_id){
if (WiFi.status() == WL_CONNECTED){
/* Request data from server */
String url = String(WIFI_REQUEST_URL) + "?id=" + current_id;
http.begin(url);
int httpCode = http.GET();
String web_data = http.getString();
Serial.print("\n\nnumber: ");
Serial.println(current_id);
if (feed_data(m, web_data) != 0){
// Message error, Report it
return false;
}
http.end();
#ifdef DEBUGGER_TASK_REPORT
PrintMode(m);
#endif
}
else WifiErrorHandle();
return true;
}
time_t Communication::check_start_time(uint8_t id, MODES mode, uint8_t* force_start){
if (WiFi.status() == WL_CONNECTED){
/* Request data from server */
String url = String(WIFI_TIME_CHECK_URL) + "?id=" + id + "&effect=" + mode;
http.begin(url);
int httpCode = http.GET();
String web_data = http.getString();
if (web_data[0] == 'A')
*force_start = 0;
else
*force_start = 1;
http.end();
return web_data.substring(1).toInt();
}
else WifiErrorHandle();
return 0;
}
void Communication::WifiErrorHandle(){
#ifdef DEBUGGER
Serial.println("Connection Failed! Rebooting...");
#endif
delay(1000);
ESP.restart();
}
void Communication::updateOTA(){
ArduinoOTA.handle();
}
void PrintColorSch(ValueParam* v){
Serial.print(" func:");
Serial.print(v->func);
Serial.print(", range:");
Serial.print(v->range);
Serial.print(", lower:");
Serial.print(v->lower);
Serial.print(", p1:");
Serial.print(v->p1);
Serial.print(", p2:");
Serial.println(v->p2);
}
void PrintMode(Mode* m){
Serial.print("Mode:");
Serial.print(m->mode);
Serial.print(", start:");
Serial.print(m->start_time);
Serial.print(", dur:");
Serial.println(m->duration);
Serial.print("XH: ");
PrintColorSch(&(m->XH));
Serial.print("XS: ");
PrintColorSch(&(m->XS));
Serial.print("XV: ");
PrintColorSch(&(m->XV));
Serial.print("YH: ");
PrintColorSch(&(m->YH));
Serial.print("YS: ");
PrintColorSch(&(m->YS));
Serial.print("YV: ");
PrintColorSch(&(m->YV));
Serial.println("Param:");
for (int i=0; i<META_PARAMETER_BUF_SIZE; i++){
Serial.print(m->param[i]);
Serial.print(", ");
}
Serial.println("");
} | 30.375862 | 86 | 0.493927 | BensonYang1999 |
07fb9f152e1646e4c63386a2261cfbb1b146f90a | 1,221 | cpp | C++ | vcplotbase.cpp | GalacticSoft/DikuEd | 135f49bba7ce2faf5faac12a355da9813c28d0fa | [
"MIT"
] | null | null | null | vcplotbase.cpp | GalacticSoft/DikuEd | 135f49bba7ce2faf5faac12a355da9813c28d0fa | [
"MIT"
] | null | null | null | vcplotbase.cpp | GalacticSoft/DikuEd | 135f49bba7ce2faf5faac12a355da9813c28d0fa | [
"MIT"
] | null | null | null | // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
#include "stdafx.h"
#include "vcplotbase.h"
// Dispatch interfaces referenced by this interface
#include "VcBrush.h"
#include "VcPen.h"
/////////////////////////////////////////////////////////////////////////////
// CVcPlotBase properties
/////////////////////////////////////////////////////////////////////////////
// CVcPlotBase operations
float CVcPlotBase::GetBaseHeight()
{
float result;
InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_R4, (void*)&result, NULL);
return result;
}
void CVcPlotBase::SetBaseHeight(float newValue)
{
static BYTE parms[] =
VTS_R4;
InvokeHelper(0x1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
newValue);
}
CVcBrush CVcPlotBase::GetBrush()
{
LPDISPATCH pDispatch;
InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CVcBrush(pDispatch);
}
CVcPen CVcPlotBase::GetPen()
{
LPDISPATCH pDispatch;
InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CVcPen(pDispatch);
}
| 24.918367 | 82 | 0.660934 | GalacticSoft |
07fda40a6914f30179570bb04f38921be010988b | 657 | cpp | C++ | legacy/src/physics/collider.cpp | benkyd/Minecraft | ae8b69b96dcecd669f90aa2c7bb675e5f9b37615 | [
"MIT"
] | 19 | 2020-07-18T18:52:39.000Z | 2022-02-27T19:42:06.000Z | legacy/src/physics/collider.cpp | benkyd/Minecraft | ae8b69b96dcecd669f90aa2c7bb675e5f9b37615 | [
"MIT"
] | null | null | null | legacy/src/physics/collider.cpp | benkyd/Minecraft | ae8b69b96dcecd669f90aa2c7bb675e5f9b37615 | [
"MIT"
] | 4 | 2021-03-27T18:36:13.000Z | 2022-03-26T18:59:09.000Z | #include "collider.hpp"
EntityCollider::EntityCollider() {
}
glm::vec3 EntityCollider::TerrainCollide(std::vector<uint8_t> terrain) {
}
bool EntityCollider::m_aabb(ColliderBox a, ColliderBox b) {
return {
(a.Min.x <= b.Min.x + b.Max.x && a.Min.x + a.Max.x >= b.Min.x) &&
(a.Min.y <= b.Min.y + b.Max.y && a.Min.y + a.Max.y >= b.Min.y) &&
(a.Min.z <= b.Min.z + b.Max.z && a.Min.z + a.Max.z >= b.Min.z)
};
}
float EntityCollider::m_xDepth(ColliderBox a, ColliderBox b) {
}
float EntityCollider::m_yDepth(ColliderBox a, ColliderBox b) {
}
float EntityCollider::m_zDepth(ColliderBox a, ColliderBox b) {
}
| 18.25 | 74 | 0.61035 | benkyd |
5800a6131a27023eead1edfcc8fd7c825bc88ff6 | 1,673 | cpp | C++ | misc/cpp/HandleThreadExceptions.cpp | ryanorz/code-camp | 041eb6443a3f0963a7778d3ddfb03a7557257094 | [
"Apache-2.0"
] | null | null | null | misc/cpp/HandleThreadExceptions.cpp | ryanorz/code-camp | 041eb6443a3f0963a7778d3ddfb03a7557257094 | [
"Apache-2.0"
] | null | null | null | misc/cpp/HandleThreadExceptions.cpp | ryanorz/code-camp | 041eb6443a3f0963a7778d3ddfb03a7557257094 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <stdexcept>
using namespace std;
mutex g_lock_cout;
mutex g_lock_queue;
condition_variable g_queuecheck;
queue<exception_ptr> g_exceptions;
bool g_workerdone = false;
void worker(int id)
{
try {
std::this_thread::sleep_for(std::chrono::seconds(id));
throw runtime_error("something wrong, id = " + to_string(id));
} catch(...) {
lock_guard<mutex> lock(g_lock_queue);
g_exceptions.push(current_exception());
g_queuecheck.notify_one();
}
}
void logger()
{
while (!g_workerdone) {
std::unique_lock<mutex> locker(g_lock_queue);
g_queuecheck.wait(locker, [&]() {
// 加入条件函数避免虚假唤醒
return !g_exceptions.empty() || g_workerdone;
});
while (!g_exceptions.empty()) {
try {
auto ep = g_exceptions.front();
if (ep != nullptr)
rethrow_exception(ep);
} catch (const exception &e) {
std::unique_lock<mutex> cout_locker(g_lock_cout);
std::cout << "[logger] exception: " << e.what() << endl;
}
g_exceptions.pop();
}
}
}
int main() {
thread t_logger(logger);
vector<thread> t_workers;
for (int i = 0; i < 5; ++i) {
t_workers.push_back(thread(worker, i));
}
for (auto &t_worker : t_workers)
t_worker.join();
{
lock_guard<mutex> lock(g_lock_queue);
g_workerdone = true;
g_queuecheck.notify_one();
}
t_logger.join();
return 0;
}
| 24.602941 | 72 | 0.57621 | ryanorz |
580533c77032abf202b792f08b0473169aac9cac | 1,346 | cpp | C++ | archsim/src/arch/risc-v/RiscVDecodeContext.cpp | tspink/GenSim | 1c2c608d97ef8a90253b6f0567b43724ba553c6b | [
"MIT"
] | 10 | 2020-07-14T22:09:30.000Z | 2022-01-11T09:57:52.000Z | archsim/src/arch/risc-v/RiscVDecodeContext.cpp | tspink/GenSim | 1c2c608d97ef8a90253b6f0567b43724ba553c6b | [
"MIT"
] | 6 | 2020-07-09T12:01:57.000Z | 2021-04-27T10:23:58.000Z | archsim/src/arch/risc-v/RiscVDecodeContext.cpp | tspink/GenSim | 1c2c608d97ef8a90253b6f0567b43724ba553c6b | [
"MIT"
] | 10 | 2020-07-29T17:05:26.000Z | 2021-12-04T14:57:15.000Z | /* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */
#include "gensim/gensim_decode_context.h"
#include "arch/risc-v/RiscVDecodeContext.h"
#include "util/ComponentManager.h"
#include "core/thread/ThreadInstance.h"
using namespace archsim::arch::riscv;
uint32_t RiscVDecodeContext::DecodeSync(archsim::MemoryInterface &interface, Address address, uint32_t mode, gensim::BaseDecode *&target)
{
target = arch_.GetISA(mode).GetNewDecode();
return arch_.GetISA(mode).DecodeInstr(address, &interface, *target);
}
class RiscV32DecodeTranslationContext : public gensim::DecodeTranslateContext
{
void Translate(archsim::core::thread::ThreadInstance *cpu, const gensim::BaseDecode &insn, gensim::DecodeContext &decode, captive::shared::IRBuilder &builder) override
{
// nothing necessary here
}
};
class RiscV64DecodeTranslationContext : public gensim::DecodeTranslateContext
{
void Translate(archsim::core::thread::ThreadInstance *cpu, const gensim::BaseDecode &insn, gensim::DecodeContext &decode, captive::shared::IRBuilder &builder) override
{
// nothing necessary here
}
};
RegisterComponent(gensim::DecodeTranslateContext, RiscV32DecodeTranslationContext, "riscv32", "risc v 32");
RegisterComponent(gensim::DecodeTranslateContext, RiscV64DecodeTranslationContext, "riscv64", "risc v 64");
| 36.378378 | 168 | 0.788262 | tspink |
5806c40c787757626339588a6e7ac820babf956f | 1,470 | cpp | C++ | code/aoce_vulkan_extra/layer/VkVisualEffectLayer.cpp | msqljj/aoce | b15320acbb9454fb461501c8cf0c598d1b15c495 | [
"MIT"
] | 71 | 2020-10-15T03:13:50.000Z | 2022-03-30T02:04:28.000Z | code/aoce_vulkan_extra/layer/VkVisualEffectLayer.cpp | msqljj/aoce | b15320acbb9454fb461501c8cf0c598d1b15c495 | [
"MIT"
] | 9 | 2021-02-20T10:30:10.000Z | 2022-03-04T07:59:58.000Z | code/aoce_vulkan_extra/layer/VkVisualEffectLayer.cpp | msqljj/aoce | b15320acbb9454fb461501c8cf0c598d1b15c495 | [
"MIT"
] | 19 | 2021-01-01T12:03:02.000Z | 2022-03-21T07:59:59.000Z | #include "VkVisualEffectLayer.hpp"
namespace aoce {
namespace vulkan {
namespace layer {
VkPosterizeLayer::VkPosterizeLayer(/* args */) {
glslPath = "glsl/posterize.comp.spv";
setUBOSize(sizeof(paramet), true);
paramet = 10;
updateUBO(¶met);
}
VkPosterizeLayer::~VkPosterizeLayer() {}
VkVignetteLayer::VkVignetteLayer(/* args */) {
glslPath = "glsl/vignette.comp.spv";
setUBOSize(sizeof(paramet), true);
updateUBO(¶met);
}
VkVignetteLayer::~VkVignetteLayer() {}
VkCGAColorspaceLayer::VkCGAColorspaceLayer(/* args */) {
glslPath = "glsl/cgaColorspace.comp.spv";
}
VkCGAColorspaceLayer::~VkCGAColorspaceLayer() {}
bool VkCGAColorspaceLayer::getSampled(int inIndex) {
if (inIndex == 0) {
return true;
}
return false;
}
VkCrosshatchLayer::VkCrosshatchLayer(/* args */) {
glslPath = "glsl/crosshatch.comp.spv";
setUBOSize(sizeof(paramet), true);
updateUBO(¶met);
}
VkCrosshatchLayer::~VkCrosshatchLayer() {}
VkEmbossLayer::VkEmbossLayer(/* args */) {
glslPath = "glsl/emboss.comp.spv";
setUBOSize(sizeof(paramet), true);
paramet = 1.0f;
updateUBO(¶met);
}
VkEmbossLayer::~VkEmbossLayer() {}
VkKuwaharaLayer::VkKuwaharaLayer(/* args */) {
glslPath = "glsl/median.comp.spv";
setUBOSize(sizeof(paramet), true);
paramet = 5;
updateUBO(¶met);
}
VkKuwaharaLayer::~VkKuwaharaLayer() {}
} // namespace layer
} // namespace vulkan
} // namespace aoce | 22.615385 | 56 | 0.682993 | msqljj |
580acac172ba189fac037a3a09a978185eed69ba | 265 | cpp | C++ | Clase1/suma.cpp | diegostaPy/compuFiuna | e69acd09803f4dacd49d5c6cb1a3173a8fef9cbc | [
"MIT"
] | null | null | null | Clase1/suma.cpp | diegostaPy/compuFiuna | e69acd09803f4dacd49d5c6cb1a3173a8fef9cbc | [
"MIT"
] | null | null | null | Clase1/suma.cpp | diegostaPy/compuFiuna | e69acd09803f4dacd49d5c6cb1a3173a8fef9cbc | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main() {
int a,b,s;
cout<<"Programa para sumar dos numeros introducidos por teclado"<<endl;
cout<<"Ingrese el numero 1: ";
cin>>a;
cout<<"Ingrese el numero 2: ";
cin>>b;
s = a+b;
cout<<"La suma es: "<<s<<endl;
}
| 18.928571 | 72 | 0.641509 | diegostaPy |
580c66cb987903da8c6ca071e4efa2f688fcf6fd | 1,076 | hpp | C++ | include/licon/optim/sgd.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | 93 | 2017-10-25T07:48:42.000Z | 2022-02-02T15:18:11.000Z | include/licon/optim/sgd.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | null | null | null | include/licon/optim/sgd.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | 20 | 2018-02-06T10:01:36.000Z | 2019-07-07T09:26:40.000Z | #ifndef LICON_OPTIM_SGD_HPP_
#define LICON_OPTIM_SGD_HPP_
#include <unordered_map>
#include "licon/optim/optim.hpp"
#include "licon/utils/etensor.hpp"
namespace licon
{
namespace optim
{
/**
* the class of SGD optimizer
*/
class SGD : public Optimizer {
public:
// the creator of SGD optimizer
static std::unique_ptr<Optimizer> CreateSGD(std::vector<std::pair<utils::ETensor<F>*, utils::ETensor<F>* > > register_weights,
F lr, F momentum = 0.9, F weight_decay = 0, bool use_nesterov = false);
void Step();
protected:
void Update(utils::ETensor<F>& W, const utils::ETensor<F>& W_grad);
private:
SGD(std::vector<std::pair<utils::ETensor<F>*, utils::ETensor<F>* > > register_weights,
F lr, F momentum = 0.9, F weight_decay = 0, bool use_nesterov = false);
private:
// the params of optimizer
F m_momentum;
F m_weight_decay;
bool m_use_nesterov;
// to save the previous grad
std::unordered_map<utils::ETensor<F>*, utils::ETensor<F> > m_prev_grad;
};
} //optim
} //licon
#endif /*LICON_OPTIM_SGD_HPP_*/ | 21.098039 | 130 | 0.681227 | wzppengpeng |
580f9ce7d6e2cb4ef71f548df011e4608e401d6d | 9,975 | cpp | C++ | src/optim/nelder_mead_module.cpp | bigginlab/chap | 17de36442e2e80cb01432e84050c4dfce31fc3a2 | [
"MIT"
] | 10 | 2018-06-28T00:21:46.000Z | 2022-03-30T03:31:32.000Z | src/optim/nelder_mead_module.cpp | bigginlab/chap | 17de36442e2e80cb01432e84050c4dfce31fc3a2 | [
"MIT"
] | 35 | 2019-03-19T21:54:46.000Z | 2022-03-17T02:20:42.000Z | src/optim/nelder_mead_module.cpp | bigginlab/chap | 17de36442e2e80cb01432e84050c4dfce31fc3a2 | [
"MIT"
] | 8 | 2018-10-27T19:35:13.000Z | 2022-01-06T01:10:39.000Z | // CHAP - The Channel Annotation Package
//
// Copyright (c) 2016 - 2018 Gianni Klesse, Shanlin Rao, Mark S. P. Sansom, and
// Stephen J. Tucker
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <algorithm>
#include "optim/nelder_mead_module.hpp"
/*!
* Constructor. Creates a NelderMeadModule object, but does not set any of its
* properties.
*/
NelderMeadModule::NelderMeadModule()
{
}
/*!
* Destructor.
*/
NelderMeadModule::~NelderMeadModule()
{
}
/*!
* \brief Setter function for parameters.
*
* Takes a standard map as input, from which it tries to extract the parameters
* required by the Nelder-Mead algorithm. Parameters are specified by using
* their name (as a string) as map key and their value as map value.
* Unrecognised entries will be ignored and an error will be thrown if required
* parameters without default are missing. Available options are:
*
* - nmMaxIter: the maximum number of iterations to perform (required)
* - nmInitShift: shift of initial vertex coordinates with respect to guess point (required)
* - nmContractionPar: factor used in contraction step (defaults to 0.5)
* - nmExpansionPar: factor used in expansion step (defaults to 2.0)
* - nmReflectionPar: factor used in reflection step (defaults to 1.0)
* - nmShrinkagePar: factor used in shrinkage step (defaults to 0.5)
*/
void
NelderMeadModule::setParams(std::map<std::string, real> params)
{
// number of iterations:
if( params.find("nmMaxIter") != params.end() )
{
maxIter_ = params["nmMaxIter"];
}
else
{
std::cerr<<"ERROR: Maximum number of Nelder-Mead iterations not specified!"<<std::endl;
std::abort();
}
// shift factor:
if( params.find("nmInitShift") != params.end() )
{
initShiftFac_ = params["nmInitShift"];
}
else
{
std::cerr<<"ERROR: Shift factor for initial vertex generation not specified!"<<std::endl;
std::abort();
}
// contraction parameter:
if( params.find("nmContractionPar") != params.end() )
{
contractionPar_ = params["nmContractionPar"];
}
else
{
contractionPar_ = 0.5;
}
// expansion parameter:
if( params.find("nmExpansionPar") != params.end() )
{
expansionPar_ = params["nmExpansionPar"];
}
else
{
expansionPar_ = 2.0;
}
// reflection parameter:
if( params.find("nmReflectionPar") != params.end() )
{
reflectionPar_ = params["nmReflectionPar"];
}
else
{
reflectionPar_ = 1.0;
}
// reflection parameter:
if( params.find("nmShrinkagePar") != params.end() )
{
shrinkagePar_ = params["nmShrinkagePar"];
}
else
{
shrinkagePar_ = 0.5;
}
}
/*!
* Sets the objective function to be maximised. An objective function takes a
* vector of reals as its only argument and returns a single real.
*/
void
NelderMeadModule::setObjFun(ObjectiveFunction objFun)
{
this -> objFun_ = objFun;
}
/*!
* Creates the initial simplex from one guess point. The first vertex of the
* initial simplex will simply be the guess point itself. All other vertices
* are calculated by perturbing one coordinate of the guess vector, i.e.
*
* \f[
* \mathbf{x}_i = \mathbf{x}_1 + h\mathbf{e}_i
* \f]
*
* where \f$\mathbf{e}_i\f$ is the \f$i\f$-th unit vector and \f$h\f$ is a
* small shift that can be set as a parameter. The objective function is not
* evaluated at any vertex.
*/
void
NelderMeadModule::setInitGuess(std::vector<real> guess)
{
// add guess point to simplex:
OptimSpacePoint guessPoint;
guessPoint.first = guess;
simplex_.push_back(guessPoint);
// add additional vertices to create a simplex of proper dimensionality:
for(size_t i = 0; i < guess.size(); i++)
{
// copy guess point and perturb j-th component:
OptimSpacePoint vertex = guessPoint;
vertex.first[i] += 1.0*initShiftFac_;
// add vertex to simplex:
simplex_.push_back(vertex);
}
}
/*!
* Performs the Nelder-Mead optimisation loop. Should only be called once
* parameters, objective function, and initial point have been set.
*/
void
NelderMeadModule::optimise()
{
// sanity checks:
if( simplex_.size() != simplex_.back().first.size() + 1 )
{
std::cerr<<"ERROR: Incorrect number of simplex vertices!"<<std::endl;
std::cerr<<"Did you call setInitGuess()?"<<std::endl;
std::abort();
}
// initialise centroid as vector of all zeros:
centroid_.first.insert(centroid_.first.begin(), simplex_.front().first.size(), 0.0);
// evaluate objective function at all vertices:
std::vector<OptimSpacePoint>::iterator vert;
for(vert = simplex_.begin(); vert != simplex_.end(); vert++)
{
vert -> second = objFun_(vert -> first);
}
// Nelder-Mead main loop:
for(int i = 0; i < maxIter_; i++)
{
// sort vertices by function values:
std::sort(simplex_.begin(),
simplex_.end(),
CompOptimSpacePoints());
// recalculate centroid:
calcCentroid();
// calculate the reflected point:
OptimSpacePoint reflectedPoint = centroid_;
reflectedPoint.scale(1.0 + reflectionPar_);
reflectedPoint.addScaled(simplex_.front(), -reflectionPar_);
// evaluate objective function at reflected point:
reflectedPoint.second = objFun_(reflectedPoint.first);
// reflected point better than second worst?
if( comparison_(simplex_[1], reflectedPoint) )
{
// reflected point better than best?
if( comparison_(simplex_.back(), reflectedPoint) )
{
// calculate expansion point:
OptimSpacePoint expandedPoint = centroid_;
expandedPoint.scale(1.0 - expansionPar_);
expandedPoint.addScaled(reflectedPoint, expansionPar_);
// evaluate objective function at expansion point:
expandedPoint.second = objFun_(expandedPoint.first);
// expanded point better than reflected point:
if( expandedPoint.second < reflectedPoint.second )
{
// accept expanded point:
simplex_.front() = expandedPoint;
}
else
{
// accept reflected point:
simplex_.front() = reflectedPoint;
}
}
else
{
// accept reflected point:
simplex_.front() = reflectedPoint;
}
}
else
{
// calculate contraction point:
OptimSpacePoint contractedPoint = centroid_;
contractedPoint.scale(1.0 - contractionPar_);
contractedPoint.addScaled(simplex_.front(), contractionPar_);
// evaluate objective function at contracted point:
contractedPoint.second = objFun_(contractedPoint.first);
// contracted point better than worst?
if( comparison_(simplex_.front(), contractedPoint) )
{
// accept contracted point:
simplex_.front() = contractedPoint;
}
else
{
// update all but the best vertex:
std::vector<OptimSpacePoint>::iterator it;
for(it = simplex_.begin(); it != simplex_.end() - 1; it++)
{
// calculate shrinkage point:
it -> scale(shrinkagePar_);
it -> addScaled(simplex_.back(), 1.0 - shrinkagePar_);
// evaluate objective function at new vertex:
it -> second = objFun_(it -> first);
}
}
}
// ensure vertices are sorted:
std::sort(simplex_.begin(),
simplex_.end(),
CompOptimSpacePoints());
}
}
/*!
* Returns the best point in optimisation space. Only meaningful if called
* after optimise().
*/
OptimSpacePoint
NelderMeadModule::getOptimPoint()
{
return simplex_.back();
}
/*!
* Calculates the centroid of all except the first vertex of the simplex. This
* is usually the worst vertex.
*/
void
NelderMeadModule::calcCentroid()
{
// reset centroid to vector of all zeros:
std::fill(centroid_.first.begin(), centroid_.first.end(), 0.0);
// loop over vertices and add to centroid_:
std::vector<OptimSpacePoint>::iterator it;
for(it = simplex_.begin() + 1; it != simplex_.end(); it++)
{
centroid_.add(*it);
}
// scale all elements by number:
real fac = 1.0/(simplex_.size() - 1);
centroid_.scale(fac);
}
| 30.504587 | 97 | 0.613534 | bigginlab |
58107e4f921de95082e14fcb6e78d8c628d6a427 | 3,519 | cpp | C++ | Runtime/World/CMarkerGrid.cpp | RetroView/RetroCommon | a413a010b50a53ebc6b0c726203181fc179d3370 | [
"MIT"
] | 106 | 2021-04-09T19:42:56.000Z | 2022-03-30T09:13:28.000Z | Runtime/World/CMarkerGrid.cpp | Austint30/metaforce | a491e2e9f229c8db92544b275cd1baa80bacfd17 | [
"MIT"
] | 58 | 2021-04-09T12:48:58.000Z | 2022-03-22T00:11:42.000Z | Runtime/World/CMarkerGrid.cpp | Austint30/metaforce | a491e2e9f229c8db92544b275cd1baa80bacfd17 | [
"MIT"
] | 13 | 2021-04-06T23:23:20.000Z | 2022-03-16T02:09:48.000Z | #include "Runtime/World/CMarkerGrid.hpp"
namespace metaforce {
CMarkerGrid::CMarkerGrid(const zeus::CAABox& bounds) : x0_bounds(bounds) {
x18_gridUnits = zeus::CVector3f((bounds.max - bounds.min) * 0.0625f);
x24_gridState.resize(0x400);
}
void CMarkerGrid::MarkCells(const zeus::CSphere& area, u32 val) {
int width_units = static_cast<int>((area.radius - x18_gridUnits.x()) / x18_gridUnits.x());
int length_units = static_cast<int>((area.radius - x18_gridUnits.y()) / x18_gridUnits.y());
int height_units = static_cast<int>((area.radius - x18_gridUnits.z()) / x18_gridUnits.z());
u32 x_coord, y_coord, z_coord;
if (!GetCoords(area.position, x_coord, y_coord, z_coord)) {
return;
}
for (int i = width_units - z_coord; i < (z_coord + width_units); i++) {
for (int j = length_units - y_coord; j < (y_coord + length_units); j++) {
for (int k = height_units - x_coord; k < (z_coord + height_units); k++) {
u32 new_cell_val = val | GetValue(x_coord, y_coord, z_coord);
SetValue(k, j, i, new_cell_val);
}
}
}
}
bool CMarkerGrid::GetCoords(zeus::CVector3f const& vec, u32& x, u32& y, u32& z) const {
if (x0_bounds.pointInside(vec)) {
x = static_cast<u32>((vec.x() - x0_bounds.min.x()) / x18_gridUnits.x());
y = static_cast<u32>((vec.y() - x0_bounds.min.y()) / x18_gridUnits.y());
z = static_cast<u32>((vec.z() - x0_bounds.min.z()) / x18_gridUnits.z());
return true;
}
return false;
}
u32 CMarkerGrid::GetValue(u32 x, u32 y, u32 z) const {
const u32 bit_offset = (x & 3) << 1;
u8 marker_byte = x24_gridState[(z << 6) + (y << 2) + (x >> 2)];
return static_cast<u32>((marker_byte & (3 << bit_offset)) >> bit_offset);
}
void CMarkerGrid::SetValue(u32 x, u32 y, u32 z, u32 val) {
const u32 bit_offset = (x & 3) << 1;
const u32 grid_offset = (z << 6) + (y << 2) + (x >> 2);
u8 marker_byte = x24_gridState[grid_offset];
marker_byte |= (marker_byte & ~(3 << bit_offset)) | (val << bit_offset);
x24_gridState[grid_offset] = marker_byte;
}
bool CMarkerGrid::AABoxTouchesData(const zeus::CAABox& box, u32 val) const {
if (!x0_bounds.intersects(box)) {
return false;
}
zeus::CAABox in_box = box;
if (!box.inside(x0_bounds)) {
zeus::CVector3f max_of_min(x0_bounds.min.x() > box.min.x() ? x0_bounds.min.x() : box.min.x(),
x0_bounds.min.y() > box.min.y() ? x0_bounds.min.y() : box.min.y(),
x0_bounds.min.z() > box.min.z() ? x0_bounds.min.z() : box.min.z());
zeus::CVector3f min_of_max(x0_bounds.max.x() < box.max.x() ? x0_bounds.max.x() : box.max.x(),
x0_bounds.max.y() < box.max.y() ? x0_bounds.max.y() : box.max.y(),
x0_bounds.max.z() < box.max.z() ? x0_bounds.max.z() : box.max.z());
in_box = zeus::CAABox(max_of_min, min_of_max);
}
u32 c1x, c1y, c1z, c2x, c2y, c2z;
GetCoords(in_box.min, c1x, c1y, c1z);
GetCoords(in_box.max, c2x, c2y, c2z);
for (int i = c1z; i < c2z; i++) {
for (int j = c1y; j < c2y; j++) {
for (int k = c1x; k < c2x; k++) {
if ((GetValue(k, j, i) & val) != 0u) {
return true;
}
}
}
}
return false;
}
zeus::CVector3f CMarkerGrid::GetWorldPositionForCell(u32 x, u32 y, u32 z) const {
// returns the center of a given cell
return zeus::CVector3f(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)) * x18_gridUnits +
x0_bounds.min + (x18_gridUnits / 2.f);
}
} // namespace urde
| 40.448276 | 111 | 0.608411 | RetroView |
58168a80cfb9a97c1621a0ed52f2c5daa219039b | 3,797 | cpp | C++ | src/level_set/RelaxationLSBcCoefs.cpp | hongk45/IBAMR | 698d419fc6688470a8b9400822ba893da9d07ae2 | [
"BSD-3-Clause"
] | null | null | null | src/level_set/RelaxationLSBcCoefs.cpp | hongk45/IBAMR | 698d419fc6688470a8b9400822ba893da9d07ae2 | [
"BSD-3-Clause"
] | 1 | 2020-11-30T14:22:45.000Z | 2020-12-01T21:28:24.000Z | src/level_set/RelaxationLSBcCoefs.cpp | hongk45/IBAMR | 698d419fc6688470a8b9400822ba893da9d07ae2 | [
"BSD-3-Clause"
] | null | null | null | // ---------------------------------------------------------------------
//
// Copyright (c) 2018 - 2019 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "ibamr/RelaxationLSBcCoefs.h"
#include "ibtk/namespaces.h" // IWYU pragma: keep
#include "ArrayData.h"
#include "BoundaryBox.h"
#include "Box.h"
#include "CellData.h"
#include "Index.h"
#include "IntVector.h"
#include "Patch.h"
#include "tbox/Pointer.h"
#include <utility>
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
RelaxationLSBcCoefs::RelaxationLSBcCoefs(std::string object_name) : d_object_name(std::move(object_name))
{
// intentionally blank
return;
} // RelaxationLSBcCoefs
void
RelaxationLSBcCoefs::setLSPatchDataIndex(int phi_idx)
{
#if !defined(NDEBUG)
TBOX_ASSERT(phi_idx >= 0);
#endif
d_phi_idx = phi_idx;
return;
} // setLSPatchDataIndex
void
RelaxationLSBcCoefs::resetLSPatchDataIndex()
{
d_phi_idx = -1;
return;
} // resetLSPatchDataIndex
void
RelaxationLSBcCoefs::setBcCoefs(Pointer<ArrayData<NDIM, double> >& acoef_data,
Pointer<ArrayData<NDIM, double> >& bcoef_data,
Pointer<ArrayData<NDIM, double> >& gcoef_data,
const Pointer<Variable<NDIM> >& /*variable*/,
const Patch<NDIM>& patch,
const BoundaryBox<NDIM>& bdry_box,
double /*fill_time*/) const
{
Pointer<CellData<NDIM, double> > phi_data = patch.getPatchData(d_phi_idx);
const int location_index = bdry_box.getLocationIndex();
const int axis = location_index / 2;
const bool is_upper = (location_index % 2 == 1);
#if !defined(NDEBUG)
TBOX_ASSERT(!acoef_data.isNull());
#endif
const Box<NDIM>& bc_coef_box = acoef_data->getBox();
#if !defined(NDEBUG)
TBOX_ASSERT(bcoef_data.isNull() || bc_coef_box == bcoef_data->getBox());
TBOX_ASSERT(gcoef_data.isNull() || bc_coef_box == gcoef_data->getBox());
#endif
for (Box<NDIM>::Iterator bc(bc_coef_box); bc; bc++)
{
const hier::Index<NDIM>& i = bc();
hier::Index<NDIM> i_bdry = bc();
hier::Index<NDIM> i_intr = bc();
if (is_upper)
{
i_bdry(axis) -= 1;
i_intr(axis) -= 2;
}
else
{
i_intr(axis) += 1;
}
double dummy;
double& a = (!acoef_data.isNull() ? (*acoef_data)(i, 0) : dummy);
double& b = (!bcoef_data.isNull() ? (*bcoef_data)(i, 0) : dummy);
double& g = (!gcoef_data.isNull() ? (*gcoef_data)(i, 0) : dummy);
a = 1.0;
b = 0.0;
g = 1.5 * (*phi_data)(i_bdry, 0) - 0.5 * (*phi_data)(i_intr, 0);
}
return;
} // setBcCoefs
IntVector<NDIM>
RelaxationLSBcCoefs::numberOfExtensionsFillable() const
{
return 128;
} // numberOfExtensionsFillable
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
} // namespace IBAMR
//////////////////////////////////////////////////////////////////////////////
| 30.134921 | 105 | 0.500395 | hongk45 |
5817d21a902758a2d814667fff36a5afe49922cc | 1,298 | cpp | C++ | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 (Operator Overloading)/complex(17).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 (Operator Overloading)/complex(17).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 (Operator Overloading)/complex(17).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | #include "complex.h"
Complex::Complex (float r, float i){
real_ = r;
imaginary_ = i;
}
Complex Complex::operator= (const Complex& rhs){
real_ = rhs.real_;
imaginary_ = rhs.imaginary_;
return *this;
}
Complex Complex::operator+ (const Complex& rhs) const{
Complex result = *this;
result.real_ += rhs.real_;
result.imaginary_ += rhs.imaginary_;
return result;
}
Complex Complex::operator- (const Complex& rhs) const{
Complex result = *this;
result.real_ -= rhs.real_;
result.imaginary_ -= rhs.imaginary_;
return result;
}
Complex Complex::operator* (const Complex& rhs) const{
Complex result = *this; // this-> == *this == (*this)
result.real_ = real_ * rhs.real_ - imaginary_ * rhs.imaginary_;
//cout << result.real_ << "R " << result.imaginary_ << "I "<< "|" << rhs.real_ << "R " << rhs.imaginary_ << "I\n";
result.imaginary_ = (real_ * rhs.imaginary_) + (rhs.real_ * imaginary_);
//cout << result.real_ << "R " << result.imaginary_ << "I "<< "|" << rhs.real_ << "R " << rhs.imaginary_ << "I\n";
return result;
}
string Complex::toString() const {
stringstream ss;
if (imaginary_ > 0){
ss << real_ << " + " << imaginary_ << "i";
}
else {
ss << real_ << " " << imaginary_ << "i";
}
return ss.str();
}
| 27.617021 | 118 | 0.600154 | diptu |
58189ec61b157d53ce90fb63d0476546bac6f851 | 7,728 | cpp | C++ | src/framework/kmdf/src/dma/base/fxcommonbufferapi.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/kmdf/src/dma/base/fxcommonbufferapi.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 13 | 2019-06-13T15:58:03.000Z | 2022-02-18T22:53:35.000Z | src/framework/kmdf/src/dma/base/fxcommonbufferapi.cpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft Corporation
Module Name:
FxCommonBufferAPI.cpp
Abstract:
Base for WDF CommonBuffer APIs
Environment:
Kernel mode only.
Notes:
Revision History:
--*/
#include "FxDmaPCH.hpp"
extern "C" {
#include "FxCommonBufferAPI.tmh"
}
//
// Extern "C" the entire file
//
extern "C" {
_Must_inspect_result_
__drv_maxIRQL(PASSIVE_LEVEL)
NTSTATUS
WDFEXPORT(WdfCommonBufferCreate)(
__in
PWDF_DRIVER_GLOBALS DriverGlobals,
__in
WDFDMAENABLER DmaEnabler,
__in
__drv_when(Length == 0, __drv_reportError(Length cannot be zero))
size_t Length,
__in_opt
WDF_OBJECT_ATTRIBUTES * Attributes,
__out
WDFCOMMONBUFFER * CommonBufferHandle
)
{
FxCommonBuffer * pComBuf;
FxDmaEnabler * pDmaEnabler;
NTSTATUS status;
WDFOBJECT handle;
PFX_DRIVER_GLOBALS pFxDriverGlobals;
//
// Get validate DmaEnabler handle
//
FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
DmaEnabler,
FX_TYPE_DMA_ENABLER,
(PVOID *) &pDmaEnabler,
&pFxDriverGlobals);
FxPointerNotNull(pFxDriverGlobals, CommonBufferHandle);
*CommonBufferHandle = NULL;
status = FxVerifierCheckIrqlLevel(pFxDriverGlobals, PASSIVE_LEVEL);
if (!NT_SUCCESS(status)) {
return status;
}
//
// Basic parameter validation
//
if (Length == 0) {
status = STATUS_INVALID_PARAMETER;
DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA,
"Length is 0, %!STATUS!", status);
return status;
}
status = FxValidateObjectAttributes(pFxDriverGlobals,
Attributes,
FX_VALIDATE_OPTION_PARENT_NOT_ALLOWED
);
if (!NT_SUCCESS(status)) {
return status;
}
//
// Create a new CommonBuffer object
//
pComBuf = new(pFxDriverGlobals, Attributes)
FxCommonBuffer(pFxDriverGlobals, pDmaEnabler);
if (pComBuf == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA,
"Could not allocate memory for a WDFCOMMONBUFFER, "
"%!STATUS!", status);
return status;
}
//
// Assign this FxCommonBuffer to its parent FxDmaEnabler object.
//
status = pComBuf->Commit(Attributes, (WDFOBJECT*)&handle, pDmaEnabler);
if (NT_SUCCESS(status)) {
//
// Ok: now allocate a CommonBuffer via this DmaEnabler
//
status = pComBuf->AllocateCommonBuffer( Length );
}
if (NT_SUCCESS(status)) {
//
// Only return a valid handle on success.
//
*CommonBufferHandle = (WDFCOMMONBUFFER) handle;
}
else {
pComBuf->DeleteFromFailedCreate();
}
return status;
}
_Must_inspect_result_
__drv_maxIRQL(PASSIVE_LEVEL)
NTSTATUS
WDFEXPORT(WdfCommonBufferCreateWithConfig)(
__in
PWDF_DRIVER_GLOBALS DriverGlobals,
__in
WDFDMAENABLER DmaEnabler,
__in
__drv_when(Length == 0, __drv_reportError(Length cannot be zero))
size_t Length,
__in
PWDF_COMMON_BUFFER_CONFIG Config,
__in_opt
WDF_OBJECT_ATTRIBUTES * Attributes,
__out
WDFCOMMONBUFFER * CommonBufferHandle
)
{
FxCommonBuffer * pComBuf;
FxDmaEnabler * pDmaEnabler;
NTSTATUS status;
WDFOBJECT handle;
PFX_DRIVER_GLOBALS pFxDriverGlobals;
//
// Get validate DmaEnabler handle
//
FxObjectHandleGetPtrAndGlobals(GetFxDriverGlobals(DriverGlobals),
DmaEnabler,
FX_TYPE_DMA_ENABLER,
(PVOID *) &pDmaEnabler,
&pFxDriverGlobals);
//
// Basic parameter validation
//
FxPointerNotNull(pFxDriverGlobals, Config);
if (Config->Size != sizeof(WDF_COMMON_BUFFER_CONFIG)) {
status = STATUS_INFO_LENGTH_MISMATCH;
DoTraceLevelMessage(
pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA,
"WDF_COMMON_BUFFER_CONFIG Size 0x%x, expected 0x%x, %!STATUS!",
Config->Size, sizeof(WDF_COMMON_BUFFER_CONFIG), status);
return status;
}
FxPointerNotNull(pFxDriverGlobals, CommonBufferHandle);
*CommonBufferHandle = NULL;
status = FxVerifierCheckIrqlLevel(pFxDriverGlobals, PASSIVE_LEVEL);
if (!NT_SUCCESS(status)) {
return status;
}
if (Length == 0) {
status = STATUS_INVALID_PARAMETER;
DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA,
"Length is 0, %!STATUS!", status);
return status;
}
status = FxValidateObjectAttributes(pFxDriverGlobals,
Attributes,
FX_VALIDATE_OPTION_PARENT_NOT_ALLOWED
);
if (!NT_SUCCESS(status)) {
return status;
}
pComBuf = new(pFxDriverGlobals, Attributes)
FxCommonBuffer(pFxDriverGlobals, pDmaEnabler);
if (pComBuf == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
DoTraceLevelMessage(pFxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGDMA,
"Could not allocate memory for a WDFCOMMONBUFFER, "
"%!STATUS!", status);
return status;
}
//
// Assign this FxCommonBuffer to its parent FxDmaEnabler object.
//
status = pComBuf->Commit(Attributes, (WDFOBJECT*)&handle, pDmaEnabler);
if (NT_SUCCESS(status)) {
//
// Set the alignment value before calling AllocateCommonBuffer.
//
pComBuf->SetAlignment(Config->AlignmentRequirement);
status = pComBuf->AllocateCommonBuffer( Length );
}
if (NT_SUCCESS(status)) {
//
// Only return a valid handle on success.
//
*CommonBufferHandle = (WDFCOMMONBUFFER) handle;
}
else {
pComBuf->DeleteFromFailedCreate();
}
return status;
}
__drv_maxIRQL(DISPATCH_LEVEL)
PVOID
WDFEXPORT(WdfCommonBufferGetAlignedVirtualAddress)(
__in
PWDF_DRIVER_GLOBALS DriverGlobals,
__in
WDFCOMMONBUFFER CommonBuffer
)
{
FxCommonBuffer * pComBuf;
FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
CommonBuffer,
FX_TYPE_COMMON_BUFFER,
(PVOID *) &pComBuf);
return pComBuf->GetAlignedVirtualAddress();
}
__drv_maxIRQL(DISPATCH_LEVEL)
PHYSICAL_ADDRESS
WDFEXPORT(WdfCommonBufferGetAlignedLogicalAddress)(
__in
PWDF_DRIVER_GLOBALS DriverGlobals,
__in
WDFCOMMONBUFFER CommonBuffer
)
{
FxCommonBuffer * pComBuf;
FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
CommonBuffer,
FX_TYPE_COMMON_BUFFER,
(PVOID *) &pComBuf);
return pComBuf->GetAlignedLogicalAddress();
}
__drv_maxIRQL(DISPATCH_LEVEL)
size_t
WDFEXPORT(WdfCommonBufferGetLength)(
__in
PWDF_DRIVER_GLOBALS DriverGlobals,
__in
WDFCOMMONBUFFER CommonBuffer
)
{
FxCommonBuffer * pComBuf;
FxObjectHandleGetPtr(GetFxDriverGlobals(DriverGlobals),
CommonBuffer,
FX_TYPE_COMMON_BUFFER,
(PVOID *) &pComBuf);
return pComBuf->GetLength();
}
} // extern "C"
| 25.421053 | 79 | 0.607013 | IT-Enthusiast-Nepal |
5819329cbc183c156d879117a551fa279dfba621 | 6,770 | cpp | C++ | ModEPP.cpp | hiqsol/reclient | 02c2f0c21a4378a5dbcc058f468d98c34e1d1190 | [
"BSD-3-Clause"
] | 2 | 2018-11-14T11:18:49.000Z | 2018-11-17T05:13:52.000Z | ModEPP.cpp | hiqsol/reclient | 02c2f0c21a4378a5dbcc058f468d98c34e1d1190 | [
"BSD-3-Clause"
] | null | null | null | ModEPP.cpp | hiqsol/reclient | 02c2f0c21a4378a5dbcc058f468d98c34e1d1190 | [
"BSD-3-Clause"
] | null | null | null | // (c) Andrii Vasyliev
// ModEPP
#include "reclient/ModEPP.h"
namespace re {
Hash<EPP> ModEPP::sessions;
data_type ModEPP::init (data_cref a) {
sessions.set(a.getLine("session",0),EPP(a.getLine("host"),a.getIntN("port"),a.getLine("certificate"),a.getLine("cacertfile"),a.getLine("cacertdir")));
if (a.has("serial")) sessions.let(a.getLine("session",0)).setSerialNo(a.getLine("serial"));
return data_null;
};
data_type ModEPP::incBatchNo (data_cref a) { return sessions.let(a.getLine("session",0)).incBatchNo(); };
data_type ModEPP::setNamestoreExtension (data_cref a) {
sessions.let(a.getLine("session",0)).setNamestoreExtension(a.getLine("ext"),a.getLine("data"));
return data_null;
};
// EPP NATIVE COMMANDS
data_type ModEPP::poll (data_cref a) { return sessions.let(a.getLine("session",0)).poll(a); };
data_type ModEPP::hello (data_cref a) { return sessions.let(a.getLine("session",0)).hello(a); };
data_type ModEPP::login (data_cref a) { return sessions.let(a.getLine("session",0)).login(a); };
data_type ModEPP::logout (data_cref a) { return sessions.let(a.getLine("session",0)).logout(a); };
data_type ModEPP::domainInfo (data_cref a) { return sessions.let(a.getLine("session",0)).domainInfo(a); };
data_type ModEPP::domainSync (data_cref a) { return sessions.let(a.getLine("session",0)).domainSync(a); };
data_type ModEPP::domainSimpleCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainSimpleCheck(a); };
data_type ModEPP::domainCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainCheck(a); };
data_type ModEPP::domainRenew (data_cref a) { return sessions.let(a.getLine("session",0)).domainRenew(a); };
data_type ModEPP::domainCreate (data_cref a) { return sessions.let(a.getLine("session",0)).domainCreate(a); };
data_type ModEPP::domainUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainUpdate(a); };
data_type ModEPP::domainDelete (data_cref a) { return sessions.let(a.getLine("session",0)).domainDelete(a); };
data_type ModEPP::domainTransfer (data_cref a) { return sessions.let(a.getLine("session",0)).domainTransfer(a); };
data_type ModEPP::emailFwdInfo (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdInfo(a); };
data_type ModEPP::emailFwdCheck (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdCheck(a); };
data_type ModEPP::emailFwdRenew (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdRenew(a); };
data_type ModEPP::emailFwdCreate (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdCreate(a); };
data_type ModEPP::emailFwdUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdUpdate(a); };
data_type ModEPP::emailFwdDelete (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdDelete(a); };
data_type ModEPP::emailFwdTransfer (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdTransfer(a); };
data_type ModEPP::hostInfo (data_cref a) { return sessions.let(a.getLine("session",0)).hostInfo(a); };
data_type ModEPP::hostCheck (data_cref a) { return sessions.let(a.getLine("session",0)).hostCheck(a); };
data_type ModEPP::hostCreate (data_cref a) { return sessions.let(a.getLine("session",0)).hostCreate(a); };
data_type ModEPP::hostUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).hostUpdate(a); };
data_type ModEPP::hostDelete (data_cref a) { return sessions.let(a.getLine("session",0)).hostDelete(a); };
data_type ModEPP::contactCheck (data_cref a) { return sessions.let(a.getLine("session",0)).contactCheck(a); };
data_type ModEPP::contactCreate (data_cref a) { return sessions.let(a.getLine("session",0)).contactCreate(a); };
data_type ModEPP::contactInfo (data_cref a) { return sessions.let(a.getLine("session",0)).contactInfo(a); };
data_type ModEPP::contactTransfer (data_cref a) { return sessions.let(a.getLine("session",0)).contactTransfer(a); };
data_type ModEPP::contactUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).contactUpdate(a); };
data_type ModEPP::contactDelete (data_cref a) { return sessions.let(a.getLine("session",0)).contactDelete(a); };
// SMART COMMANDS
data_type ModEPP::pollOne (data_cref a) { return sessions.let(a.getLine("session",0)).pollOne(a); };
data_type ModEPP::pollAll (data_cref a) { return sessions.let(a.getLine("session",0)).pollAll(a); };
data_type ModEPP::pollAck (data_cref a) { sessions.let(a.getLine("session",0)).pollAck(a.get("id"));return NULL; };
data_type ModEPP::domainAllowUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainAllowUpdate(a); };
data_type ModEPP::domainProhibitUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainProhibitUpdate(a); };
data_type ModEPP::domainMassCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainMassCheck(a); };
data_type ModEPP::domainSmartCheck (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartCheck(a); };
data_type ModEPP::domainSmartUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartUpdate(a); };
data_type ModEPP::domainSmartDelete (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartDelete(a); };
data_type ModEPP::domainSmartLock (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartLock(a); };
data_type ModEPP::domainSmartUnlock (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartUnlock(a); };
data_type ModEPP::domainSmartHold (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartHold(a); };
data_type ModEPP::domainSmartUnhold (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartUnhold(a); };
data_type ModEPP::domainSmartRenew (data_cref a) { return sessions.let(a.getLine("session",0)).domainSmartRenew(a); };
data_type ModEPP::emailFwdSmartRenew (data_cref a) { return sessions.let(a.getLine("session",0)).emailFwdSmartRenew(a); };
data_type ModEPP::hostSmartCheck (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartCheck(a); };
data_type ModEPP::hostSmartUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartUpdate(a); };
data_type ModEPP::hostSmartDelete (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartDelete(a); };
data_type ModEPP::hostSmartSet (data_cref a) { return sessions.let(a.getLine("session",0)).hostSmartSet(a); };
data_type ModEPP::contactSmartCheck (data_cref a) { return sessions.let(a.getLine("session",0)).contactSmartCheck(a); };
data_type ModEPP::contactSmartUpdate (data_cref a) { return sessions.let(a.getLine("session",0)).contactSmartUpdate(a); };
data_type ModEPP::contactSmartSet (data_cref a) { return sessions.let(a.getLine("session",0)).contactSmartSet(a); };
}; // namespace re
| 83.580247 | 151 | 0.742984 | hiqsol |
581964349ff52128d383dc60f9b26897ee810c0d | 1,024 | cc | C++ | simulation/functional-sim/libss-vpi/lib.src/sim_main.cc | anycore/anycore-pisa | b4dcd040d2850fb19adb1502c3c03bf73ca06c35 | [
"BSD-3-Clause"
] | null | null | null | simulation/functional-sim/libss-vpi/lib.src/sim_main.cc | anycore/anycore-pisa | b4dcd040d2850fb19adb1502c3c03bf73ca06c35 | [
"BSD-3-Clause"
] | null | null | null | simulation/functional-sim/libss-vpi/lib.src/sim_main.cc | anycore/anycore-pisa | b4dcd040d2850fb19adb1502c3c03bf73ca06c35 | [
"BSD-3-Clause"
] | 3 | 2017-10-14T00:51:39.000Z | 2021-03-25T16:37:11.000Z | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include "misc.h"
#include "mt_trace_consume.h"
#include "Thread.h"
#include "global_vars.h"
/////////////////////////////////////////////////////////////////////
void
sim_config(FILE *stream)
{
}
/* exit when this becomes non-zero */
int sim_exit_now = FALSE;
/* longjmp here when simulation is completed */
jmp_buf sim_exit_buf;
/* instruction jump table */
#ifdef sparc
register void **local_op_jump asm("g7");
#else
void **local_op_jump;
#endif
void
sim_main(void)
{
///////////////////////////////////////
// Decode the binaries of each thread.
///////////////////////////////////////
for (unsigned int i = 0; i < NumThreads; i++)
THREAD[i]->decode();
///////////////////////////////////////
// Initialize trace consumer.
///////////////////////////////////////
trace_consume_init();
////////////////////////////////
// Simulator Loop.
////////////////////////////////
trace_consume();
} // sim_main()
| 19.692308 | 69 | 0.482422 | anycore |
5823aa62b92115ca96ff4014c9c5b9f0e6d9c619 | 973 | cpp | C++ | Uva-11677 - Alarm Clock.cpp | Samim-Arefin/UVa-Problem-Solution | 8556639b9e718299f4a52920034dfa0264e06f8e | [
"MIT"
] | 1 | 2020-11-02T22:18:22.000Z | 2020-11-02T22:18:22.000Z | Uva-11677 - Alarm Clock.cpp | Samim-Arefin/UVa-Problem-Solution | 8556639b9e718299f4a52920034dfa0264e06f8e | [
"MIT"
] | null | null | null | Uva-11677 - Alarm Clock.cpp | Samim-Arefin/UVa-Problem-Solution | 8556639b9e718299f4a52920034dfa0264e06f8e | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int H1, M1, H2, M2;
while (cin >> H1 >> M1 >> H2 >> M2)
{
if (H1 == 0 && H2 == 0 && M1 == 0 && M2 == 0)
{
break;
}
else if (H1 > H2)
{
if (M1 > M2)
{
int temp = (60 + M2 - M1) + (60 * (24 + H2 - H1 - 1));
cout << temp << '\n';
}
else
{
int temp = (60 * (24 + H2 - H1)) + (M2 - M1);
cout << temp << '\n';
}
}
else
{
if (M1 > M2 && H1 == H2)
{
int temp = (M2 + 60 - M1) + (60 * (24 + H2 - H1 - 1));
cout << temp << '\n';
}
else if (M1 == M2 && H1 == H2)
{
cout << "0\n";
}
else if (M1 == M2 && H2 > H1)
{
int temp = (M2 - M1) + (60 * (H2 - H1));
cout << temp << '\n';
}
else if (M1 > M2 && H2 > H1)
{
int temp = (M2 + 60 - M1) + (60 * (H2 - H1 - 1));
cout << temp << '\n';
}
else if (M2 > M1 && H2 >= H1)
{
int temp = (M2 - M1) + (60 * (H2 - H1));
cout << temp << '\n';
}
}
}
} | 18.358491 | 58 | 0.362795 | Samim-Arefin |
5824b9f76541e35107a905386262bfc985a1aac8 | 222 | cpp | C++ | src/DesktopCore/System/Services/TimerKillerService.cpp | lurume84/blink-desktop | d6d01f8dc461edd22192a521fbd49669bfa8f684 | [
"MIT"
] | 75 | 2019-03-08T14:15:49.000Z | 2022-01-05T17:30:43.000Z | src/DesktopCore/System/Services/TimerKillerService.cpp | lurume84/blink-desktop | d6d01f8dc461edd22192a521fbd49669bfa8f684 | [
"MIT"
] | 55 | 2019-02-17T01:34:12.000Z | 2022-02-26T21:07:33.000Z | src/DesktopCore/System/Services/TimerKillerService.cpp | lurume84/blink-desktop | d6d01f8dc461edd22192a521fbd49669bfa8f684 | [
"MIT"
] | 20 | 2019-05-21T19:02:31.000Z | 2022-03-28T07:29:28.000Z | #include "TimerKillerService.h"
namespace desktop { namespace core { namespace service {
void TimerKillerService::kill()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_terminate = true;
m_cv.notify_all();
}
}}} | 20.181818 | 56 | 0.716216 | lurume84 |
5826c19e29f2924c6e3478834a6d68c2073aa17e | 859 | cpp | C++ | LeetCode/NonDecreasingArray.cpp | SelvorWhim/competitive | b9daaf21920d6f7669dc0c525e903949f4e33b62 | [
"Unlicense"
] | null | null | null | LeetCode/NonDecreasingArray.cpp | SelvorWhim/competitive | b9daaf21920d6f7669dc0c525e903949f4e33b62 | [
"Unlicense"
] | null | null | null | LeetCode/NonDecreasingArray.cpp | SelvorWhim/competitive | b9daaf21920d6f7669dc0c525e903949f4e33b62 | [
"Unlicense"
] | null | null | null | class Solution {
public:
bool checkPossibility(vector<int>& nums) {
bool found_violation = false;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] < nums[i-1]) {
if (found_violation) {
// 2nd case of decreasing, can't be fixed by changing one element
return false;
}
if (i > 1 && i + 1 < nums.size() && nums[i-2] > nums[i] && nums[i-1] > nums[i+1]) {
// any violation by an edge can be fixed
// and any in the middle can be fixed by setting nums[i-1] = nums[i-2] or nums[i] = nums[i-1]
// anything else (this case) can't be fixed
return false;
}
found_violation = true;
}
}
return true;
}
};
| 37.347826 | 113 | 0.447031 | SelvorWhim |
582ac84325bc1c07a2c9f19ac7e79109a53e495a | 631 | hpp | C++ | include/game/skirmish/meta/boardmetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 3 | 2015-03-28T02:51:58.000Z | 2018-11-08T16:49:53.000Z | include/game/skirmish/meta/boardmetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | 39 | 2015-05-18T08:29:16.000Z | 2020-07-18T21:17:44.000Z | include/game/skirmish/meta/boardmetaclass.hpp | namelessvoid/qrwar | bbc4036cd3bab6b0edcaccbc95286379ef51f12b | [
"MIT"
] | null | null | null | #ifndef QRW_BOARDMETACLASS_HPP
#define QRW_BOARDMETACLASS_HPP
#include "meta/metaclass.hpp"
#include "meta/properties/iproperty.hpp"
#include "engine/board.hpp"
namespace qrw {
class BoardMetaClass final : public MetaClass
{
public:
BoardMetaClass(const MetaManager& metaManager);
~BoardMetaClass() override = default;
virtual void serialize(const Reflectable* object, YAML::Emitter& out) const final override;
virtual Reflectable* deserialize(const YAML::Node& in) const final override;
private:
std::array<std::unique_ptr<IProperty>,4> properties_;
};
} // namespace qrw
#endif // QRW_BOARDMETACLASS_HPP
| 21.033333 | 92 | 0.767036 | namelessvoid |
582b616e9b1b1ae42b7f74c0a6d865ca2723b72a | 412 | cpp | C++ | Lecture7/ArrayStudy/ArrayStudy/main.cpp | sgajaejung/API-Lecture | 904be7efdcc0e2eb40fbb9e4aa600b6598921392 | [
"MIT"
] | 2 | 2015-11-27T07:24:49.000Z | 2017-09-07T09:33:14.000Z | Lecture7/ArrayStudy/ArrayStudy/main.cpp | sgajaejung/API-Lecture | 904be7efdcc0e2eb40fbb9e4aa600b6598921392 | [
"MIT"
] | null | null | null | Lecture7/ArrayStudy/ArrayStudy/main.cpp | sgajaejung/API-Lecture | 904be7efdcc0e2eb40fbb9e4aa600b6598921392 | [
"MIT"
] | 1 | 2021-02-09T15:49:37.000Z | 2021-02-09T15:49:37.000Z |
#include <iostream>
using namespace std;
void main()
{
int ar1[10][10] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int **ar2;
ar2 = new int*[ 10];
for (int i=0; i < 10; ++i)
{
ar2[ i] = new int[ 10];
}
ar2[ 0][ 0] = 1;
ar2[ 0][ 1] = 2;
cout << ar1[ 0][ 0] << endl;
cout << ar2[ 0][ 0] << endl;
cout << *(int*)ar1 << endl;
cout << *(int*)ar2 << endl;
cout << *(int*)*(int*)ar2 << endl;
}
| 12.875 | 35 | 0.444175 | sgajaejung |
582bfcd91b38d45c90dec277ec1fa53a01f3365f | 824 | cpp | C++ | C++/tests/problems/0150_search_suggestions_system_test.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 6 | 2019-03-20T22:23:26.000Z | 2020-08-28T03:10:27.000Z | C++/tests/problems/0150_search_suggestions_system_test.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 15 | 2019-10-13T20:53:53.000Z | 2022-03-31T02:01:35.000Z | C++/tests/problems/0150_search_suggestions_system_test.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 3 | 2019-03-11T10:57:46.000Z | 2020-02-26T21:13:21.000Z | #include "../../problems/0150_search_suggestions_system.hpp"
#include <bits/stdc++.h>
#include "../../frameworks/catch.hpp"
#include "../../frameworks/asserts.hpp"
using namespace std;
TEST_CASE( "Search Suggestions System" ) {
Solution sol;
vector<string> products1 = {"mobile","mouse","moneypot","monitor","mousepad"};
vector<vector<string>> result1 = {{"mobile","moneypot","monitor"},{"mobile","moneypot","monitor"},{"mouse","mousepad"},{"mouse","mousepad"},{"mouse","mousepad"}};
REQUIRE( areVectorsEqual(sol.suggestedProducts(products1,"mouse"),result1) );
vector<string> products2 = {"havana"};
vector<vector<string>> result2 = {{"havana"},{"havana"},{"havana"},{"havana"},{"havana"},{"havana"}};
REQUIRE( areVectorsEqual(sol.suggestedProducts(products2,"havana"),result2) );
} | 43.368421 | 166 | 0.669903 | oxone-999 |
58312b795a02f436a5b1ebe26a7f9d64d2b6db4a | 256 | cpp | C++ | Notes_Week8/Exception/stdException.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | Notes_Week8/Exception/stdException.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | Notes_Week8/Exception/stdException.cpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdexcept>
#include <vector>
int main() {
std::vector<int> v;
v.push_back(10);
try {
std::cout << v.at(15) << std::endl;
}
catch(std::out_of_range e) {
std::cout << e.what() << std::endl;
}
return 0;
} | 17.066667 | 41 | 0.566406 | WeiChienHsu |
5831d734eb7eefb0d9bf00be7c1cad236df1df65 | 543 | hh | C++ | wcd/include/world.hh | lagoproject/sims | bc34510b803136c770ecd9c789dc7cfade2ccbbd | [
"BSD-3-Clause"
] | null | null | null | wcd/include/world.hh | lagoproject/sims | bc34510b803136c770ecd9c789dc7cfade2ccbbd | [
"BSD-3-Clause"
] | null | null | null | wcd/include/world.hh | lagoproject/sims | bc34510b803136c770ecd9c789dc7cfade2ccbbd | [
"BSD-3-Clause"
] | null | null | null | #ifndef world_h
#define world_h 1
// Geant4 Libraries
//
#include "G4Material.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4Box.hh"
// Local Libraries
//
class world
{
public:
world();
virtual ~world();
void DefineMaterials();
void buildDetector(G4bool* overLaps);
G4LogicalVolume* getLogVolume();
G4VPhysicalVolume* getPhysVolume();
private:
G4Material* expHall_mat;
G4Box* expHall_geo;
G4LogicalVolume* expHall_log;
G4VPhysicalVolume* expHall_phys;
};
#endif
| 15.083333 | 41 | 0.697974 | lagoproject |
58329699f0f654ba61c1a53bb753f8ea5a77d38e | 651 | cpp | C++ | s01-installation-openframeworks-basics/01-basics/src/main.cpp | pkmital/MTIID-MTEC-616-01-2017 | c5f7f24c531cda3a48dbd974f46c08fa504dd06d | [
"Apache-2.0"
] | 13 | 2017-01-16T07:16:51.000Z | 2019-07-19T04:11:36.000Z | s01-installation-openframeworks-basics/01-basics/src/main.cpp | pkmital/MTIID-MTEC-616-01-2017 | c5f7f24c531cda3a48dbd974f46c08fa504dd06d | [
"Apache-2.0"
] | null | null | null | s01-installation-openframeworks-basics/01-basics/src/main.cpp | pkmital/MTIID-MTEC-616-01-2017 | c5f7f24c531cda3a48dbd974f46c08fa504dd06d | [
"Apache-2.0"
] | 4 | 2017-05-29T15:43:45.000Z | 2019-07-19T04:11:42.000Z | #include "ofMain.h"
class ofApp : public ofBaseApp{
public:
void setup() {
cam.setup(width, height);
ofSetWindowShape(width, height);
ofSetFrameRate(60);
}
void update() {
cam.update();
}
void draw() {
cam.draw(0, 0, ofGetWidth(), ofGetHeight());
}
void keyPressed(int key) {
if (key == 'f') {
ofToggleFullscreen();
}
}
void mouseMoved( int x, int y ){
}
private:
ofVideoGrabber cam;
int width = 640;
int height = 480;
};
int main(){
ofSetupOpenGL(1024, 768, OF_WINDOW);
ofRunApp(new ofApp());
}
| 16.275 | 52 | 0.519201 | pkmital |
5837fb7499389925fc6205caa772c3f38acc3d6a | 8,762 | cpp | C++ | sycl/test/basic_tests/buffer/subbuffer_interop.cpp | jcranmer-intel/llvm-sycl | 45dbbd128e4793681ed9d40a3c018f44c17449ec | [
"Apache-2.0"
] | null | null | null | sycl/test/basic_tests/buffer/subbuffer_interop.cpp | jcranmer-intel/llvm-sycl | 45dbbd128e4793681ed9d40a3c018f44c17449ec | [
"Apache-2.0"
] | null | null | null | sycl/test/basic_tests/buffer/subbuffer_interop.cpp | jcranmer-intel/llvm-sycl | 45dbbd128e4793681ed9d40a3c018f44c17449ec | [
"Apache-2.0"
] | null | null | null | // RUN: %clangxx -fsycl %s -o %t.out -lOpenCL
// RUN: %CPU_RUN_PLACEHOLDER %t.out
// RUN: %GPU_RUN_PLACEHOLDER %t.out
// RUN: %ACC_RUN_PLACEHOLDER %t.out
//==------------ subbuffer_interop.cpp - SYCL buffer basic test ------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <CL/sycl.hpp>
#include <cassert>
#include <memory>
using namespace cl::sycl;
const std::string clKernelSourceCodeSimple = "\
__kernel void test(__global int* a, __global int* b) {\
int i = get_global_id(0);\
if (i < 256) { \
b[i] = 0; \
} \
}";
const std::string clKernelSourceCodeNonOverlap = "\
__kernel void test(__global int* a, __global int* b, __global int *c) {\
int i = get_global_id(0);\
if (i < 128) { \
b[i] = 0; \
} \
if (i >= 256 && i < 384) { \
c[i - 256] = 0; \
} \
}";
const std::string clKernelSourceCodeOverlap = "\
__kernel void test1(__global int* a, __global int* b) {\
int i = get_global_id(0);\
if (i < 256) { \
b[i] = 0; \
} \
} \
__kernel void test2(__global int* a, __global int* b) {\
int i = get_global_id(0);\
if (i < 128) { \
b[i] = 1; \
} \
}";
int main() {
bool Failed = false;
{
// Test if we can write into subbufer from OpenCL code.
const size_t NSize = 512;
cl_int Error = CL_SUCCESS;
int AMem[NSize];
for (size_t i = 0; i < NSize; i++) {
AMem[i] = i;
}
try {
queue TestQueue;
const char *SrcString[] = {clKernelSourceCodeSimple.c_str()};
const size_t SrcStringSize = clKernelSourceCodeSimple.size();
cl_context clContext = TestQueue.get_context().get();
cl_device_id clDevice = TestQueue.get_device().get();
cl_program clProgram =
clCreateProgramWithSource(clContext, 1, SrcString, &SrcStringSize, &Error);
CHECK_OCL_CODE(Error);
Error = clBuildProgram(clProgram, 1, &clDevice, NULL, NULL, NULL);
CHECK_OCL_CODE(Error);
cl_kernel clKernel = clCreateKernel(clProgram, "test", &Error);
CHECK_OCL_CODE(Error);
buffer<int, 1> BufA(AMem, cl::sycl::range<1>(NSize));
buffer<int, 1> BufB(BufA, NSize / 2, NSize / 2);
kernel TestKernel(clKernel, TestQueue.get_context());
TestQueue.submit([&](handler &cgh) {
auto a_acc = BufA.get_access<access::mode::read>(cgh);
auto b_acc = BufB.get_access<access::mode::write>(cgh);
cgh.set_arg(0, a_acc);
cgh.set_arg(1, b_acc);
cgh.parallel_for(range<1>(NSize), TestKernel);
});
clReleaseKernel(clKernel);
clReleaseProgram(clProgram);
} catch (exception &ex) {
std::cout << ex.what() << std::endl;
}
for (int i = 0; i < NSize; ++i) {
if (i < NSize / 2 && AMem[i] != i) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i
<< std::endl;
assert(false);
Failed = true;
} else if (i >= NSize / 2 && AMem[i] != 0) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0
<< std::endl;
assert(false);
Failed = true;
}
}
}
{
// Test if we can use two sub buffers, pointing to one buffer, from OpenCL.
const size_t NSize = 512;
cl_int Error = CL_SUCCESS;
int AMem[NSize];
for (size_t i = 0; i < NSize; i++) {
AMem[i] = i;
}
try {
queue TestQueue;
const char *SrcString[] = {clKernelSourceCodeNonOverlap.c_str()};
const size_t SrcStringSize = clKernelSourceCodeNonOverlap.size();
cl_context clContext = TestQueue.get_context().get();
cl_device_id clDevice = TestQueue.get_device().get();
cl_program clProgram =
clCreateProgramWithSource(clContext, 1, SrcString, &SrcStringSize, &Error);
CHECK_OCL_CODE(Error);
Error = clBuildProgram(clProgram, 1, &clDevice, NULL, NULL, NULL);
CHECK_OCL_CODE(Error);
cl_kernel clKernel = clCreateKernel(clProgram, "test", &Error);
CHECK_OCL_CODE(Error);
buffer<int, 1> BufA(AMem, cl::sycl::range<1>(NSize));
buffer<int, 1> BufB(BufA, 0, NSize / 4);
buffer<int, 1> BufC(BufA, 2 * NSize / 4, NSize / 4);
kernel TestKernel(clKernel, TestQueue.get_context());
TestQueue.submit([&](handler &cgh) {
auto a_acc = BufA.get_access<access::mode::read>(cgh);
auto b_acc = BufB.get_access<access::mode::write>(cgh);
auto c_acc = BufC.get_access<access::mode::write>(cgh);
cgh.set_arg(0, a_acc);
cgh.set_arg(1, b_acc);
cgh.set_arg(2, c_acc);
cgh.parallel_for(range<1>(NSize), TestKernel);
});
clReleaseKernel(clKernel);
clReleaseProgram(clProgram);
} catch (exception &ex) {
std::cout << ex.what() << std::endl;
}
for (int i = 0; i < NSize; ++i) {
if (i < NSize / 4 && AMem[i] != 0) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0
<< std::endl;
assert(false);
Failed = true;
} else if (i >= NSize / 4 && i < 2 * NSize / 4 && AMem[i] != i) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i
<< std::endl;
assert(false);
Failed = true;
} else if (i >= 2 * NSize / 4 && i < 3 * NSize / 4 && AMem[i] != 0) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0
<< std::endl;
assert(false);
Failed = true;
} else if (i >= 3 * NSize / 4 && AMem[i] != i) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i
<< std::endl;
assert(false);
Failed = true;
}
}
}
{
// Test if we can use two sub buffers, pointing to one buffer, from
// two different OpenCL kernels.
const size_t NSize = 512;
cl_int Error = CL_SUCCESS;
int AMem[NSize];
for (size_t i = 0; i < NSize; i++) {
AMem[i] = i;
}
try {
queue TestQueue;
const char *SrcString[] = {clKernelSourceCodeOverlap.c_str()};
const size_t SrcStringSize = clKernelSourceCodeOverlap.size();
cl_context clContext = TestQueue.get_context().get();
cl_device_id clDevice = TestQueue.get_device().get();
cl_program clProgram =
clCreateProgramWithSource(clContext, 1, SrcString, &SrcStringSize, &Error);
CHECK_OCL_CODE(Error);
Error = clBuildProgram(clProgram, 1, &clDevice, NULL, NULL, NULL);
CHECK_OCL_CODE(Error);
cl_kernel clKernel1 = clCreateKernel(clProgram, "test1", &Error);
CHECK_OCL_CODE(Error);
cl_kernel clKernel2 = clCreateKernel(clProgram, "test2", &Error);
CHECK_OCL_CODE(Error);
buffer<int, 1> BufA(AMem, cl::sycl::range<1>(NSize));
buffer<int, 1> BufB(BufA, 0, NSize / 2);
buffer<int, 1> BufC(BufA, NSize / 4, NSize / 4);
kernel TestKernel1(clKernel1, TestQueue.get_context());
kernel TestKernel2(clKernel2, TestQueue.get_context());
TestQueue.submit([&](handler &cgh) {
auto a_acc = BufA.get_access<access::mode::read>(cgh);
auto b_acc = BufB.get_access<access::mode::write>(cgh);
cgh.set_arg(0, a_acc);
cgh.set_arg(1, b_acc);
cgh.parallel_for(range<1>(NSize), TestKernel1);
});
TestQueue.submit([&](handler &cgh) {
auto a_acc = BufA.get_access<access::mode::read>(cgh);
auto c_acc = BufC.get_access<access::mode::write>(cgh);
cgh.set_arg(0, a_acc);
cgh.set_arg(1, c_acc);
cgh.parallel_for(range<1>(NSize), TestKernel2);
});
clReleaseKernel(clKernel1);
clReleaseKernel(clKernel2);
clReleaseProgram(clProgram);
} catch (exception &ex) {
std::cout << ex.what() << std::endl;
}
for (int i = 0; i < NSize; ++i) {
if (i < NSize / 4 && AMem[i] != 0) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << 0
<< std::endl;
assert(false);
Failed = true;
} else if (i >= NSize / 4 && i < 2 * NSize / 4 && AMem[i] != 1) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i
<< std::endl;
assert(false);
Failed = true;
} else if (i >= 2 * NSize / 4 && AMem[i] != i) {
std::cout << " array[" << i << "] is " << AMem[i] << " expected " << i
<< std::endl;
assert(false);
Failed = true;
}
}
}
return Failed;
}
| 30.74386 | 85 | 0.548505 | jcranmer-intel |
58382202eab09296fbd2a8c829b3ee6d9344e0c4 | 2,533 | cpp | C++ | src/types/Range.cpp | LumpBloom7/cligCore | ddd26787128fbed1724dba66e90673ffa8b5ed2e | [
"MIT"
] | null | null | null | src/types/Range.cpp | LumpBloom7/cligCore | ddd26787128fbed1724dba66e90673ffa8b5ed2e | [
"MIT"
] | 7 | 2018-04-03T07:48:22.000Z | 2018-07-19T12:34:19.000Z | src/types/Range.cpp | LumpBloom7/cligCore | ddd26787128fbed1724dba66e90673ffa8b5ed2e | [
"MIT"
] | 1 | 2018-01-07T05:30:11.000Z | 2018-01-07T05:30:11.000Z | #include "Types/Range.h"
namespace cligCore::types {
Range::Range() : _lower(0), _upper(10), _current(0), _isSelectable(false) {}
Range::Range(int lowerBounds, int upperBounds, bool isSelectable) {
// Differentiate the smaller value from the bigger value to ease processing and to avoid any potential bugs.
_lower = (lowerBounds <= upperBounds) ? lowerBounds : upperBounds;
_upper = (lowerBounds <= upperBounds) ? upperBounds : lowerBounds;
_isSelectable = isSelectable;
_current = _lower;
}
Range::Range(int lowerBounds, int upperBounds, int currentVal) {
// Differentiate the smaller value from the bigger value to ease processing and to avoid any potential bugs.
_lower = (lowerBounds <= upperBounds) ? lowerBounds : upperBounds;
_upper = (lowerBounds <= upperBounds) ? upperBounds : lowerBounds;
_isSelectable = true;
_current = (currentVal >= _lower && currentVal <= _upper) ? currentVal : _lower;
}
int Range::getLower() { return _lower; }
int Range::getUpper() { return _upper; }
void Range::setLower(int value) { _lower = value; }
void Range::setUpper(int value) { _upper = value; }
void Range::shift(int value) {
_lower += value;
_upper += value;
}
void cligCore::types::Range::showChooser(const std::string& title) {
cligCore::console::clear();
int current = _current;
std::cout << rang::style::underline << title << rang::style::reset << "\n"
<< "Please select a value between " << _lower << " and " << _upper << "." << std::endl
<< std::endl
<< (current == _lower ? " " : " < ") << current << (current == _upper ? " " : " > ") << " \r" << std::flush;
bool failsafe = false;
while (true) {
if (!failsafe) {
cligCore::input::getKeyInput();
failsafe = true;
}
switch (cligCore::input::getKeyInput()) {
case cligCore::input::Keys::Right: {
if (current < _upper) current++;
std::cout << (current == _lower ? " " : " < ") << current << (current == _upper ? " " : " > ") << " \r" << std::flush;
break;
}
case cligCore::input::Keys::Left: {
if (current > _lower) current--;
std::cout << (current == _lower ? " " : " < ") << current << (current == _upper ? " " : " > ") << " \r" << std::flush;
break;
}
case cligCore::input::Keys::Enter: {
_current = current;
}
case cligCore::input::Keys::Escape: {
return;
}
}
}
}
int Range::getCurrent() { return _current; }
} | 37.80597 | 143 | 0.591788 | LumpBloom7 |
583a6ed68848eabcc419798f3c580e6c187de8d6 | 2,515 | cpp | C++ | src/bitsyc.cpp | SimplyDanny/bitsy-llvm | 125e404388ef65847eac8cb533c5321a2289bb85 | [
"MIT"
] | 4 | 2021-01-07T10:29:49.000Z | 2021-07-17T22:10:54.000Z | src/bitsyc.cpp | SimplyDanny/bitsy-llvm | 125e404388ef65847eac8cb533c5321a2289bb85 | [
"MIT"
] | null | null | null | src/bitsyc.cpp | SimplyDanny/bitsy-llvm | 125e404388ef65847eac8cb533c5321a2289bb85 | [
"MIT"
] | 2 | 2021-02-07T21:15:20.000Z | 2021-07-17T22:10:55.000Z | #include "ast/ASTPrinter.hpp"
#include "codegen/CodeGenerator.hpp"
#include "codegen/ModuleBuilder.hpp"
#include "execution/ModuleProcessor.hpp"
#include "lexer/Lexer.hpp"
#include "parser/Parser.hpp"
#include "llvm/Support/CommandLine.h"
#include <fstream>
#include <iostream>
#include <iterator>
namespace cl = llvm::cl;
namespace { namespace opt {
cl::OptionCategory category{"Options"};
cl::opt<std::string> input_name{cl::Positional, cl::Required, cl::desc("<bitsy file>"), cl::cat(category)};
cl::opt<std::string> output_name{"o",
cl::desc("Name of the executable output file"),
cl::value_desc("executable"),
cl::init("a.out"),
cl::cat(category)};
cl::opt<bool> compile{"c", cl::desc("Compile Bitsy file to an exectuable output file"), cl::cat(category)};
cl::opt<bool> quiet{"q", cl::desc("Do not execute the program automatically"), cl::cat(category)};
cl::opt<bool> no_optimization{"no-opt", cl::desc("Do not run any optimization"), cl::cat(category)};
cl::opt<bool> show_cfg{"show-cfg", cl::desc("Show CFG or create an image of it"), cl::cat(category)};
cl::opt<bool> show_ast{"show-ast", cl::desc("Print the internally used AST"), cl::cat(category)};
}} // namespace ::opt
int main(int argc, char *argv[]) {
cl::HideUnrelatedOptions(opt::category);
cl::ParseCommandLineOptions(argc, argv, "Compiler for Bitsy programs", nullptr, nullptr, true);
std::ifstream file_stream{opt::input_name};
if (!file_stream.good()) {
std::cerr << "Cannot open the input file." << std::endl;
return 1;
}
Lexer<std::istreambuf_iterator<char>> lexer{file_stream, {}};
std::vector<Token> tokens{lexer, decltype(lexer)()};
Parser parser{tokens};
auto main_block = parser.parse();
ModuleBuilder builder{main_block.get()};
ModuleProcessor processor{builder.build(), opt::output_name};
if (processor.verify()) {
return 2;
}
if (!opt::no_optimization) {
processor.optimize();
}
if (opt::compile) {
if (processor.compile() != 0) {
return 3;
}
}
if (opt::show_cfg) {
if (!processor.show_cfg()) {
return 4;
}
}
if (opt::show_ast) {
ASTPrinter().visit(llvm::cast<Statement>(main_block.get()));
}
if (opt::quiet || opt::show_cfg || opt::show_ast) {
return 0;
}
return processor.execute();
}
| 32.662338 | 107 | 0.612326 | SimplyDanny |
5842b0de946b88bc341d1ff11a4285f995e5a432 | 2,860 | cpp | C++ | tests/TestProgress/TestProgress.cpp | deniskropp/llyx | 33c7dd40921563d116363bd3e0b411aaa61ca29e | [
"MIT"
] | null | null | null | tests/TestProgress/TestProgress.cpp | deniskropp/llyx | 33c7dd40921563d116363bd3e0b411aaa61ca29e | [
"MIT"
] | null | null | null | tests/TestProgress/TestProgress.cpp | deniskropp/llyx | 33c7dd40921563d116363bd3e0b411aaa61ca29e | [
"MIT"
] | null | null | null | /*
TestProgress - llyx test
*/
#include <SFML/Graphics.hpp>
#include <llyx/BaseView.hpp>
#include <llyx/ButtonView.hpp>
#include <llyx/FPSView.hpp>
#include <llyx/ProgressView.hpp>
#include <llyx/RootView.hpp>
#include <llyx/TextView.hpp>
class TestView : public llyx::RootView
{
private:
lli::Event<> timer;
public:
TestView(sf::RenderWindow& window)
:
RootView(window, llyx::RootStyle())
{
llyx::TextStyle text1_style;
text1_style.text_color = llyx::Color(0.0f, 0.66f, 0.79f);
text1_style.text_height = 32;
text1_style.text = "Progress Bar Test";
auto text1 = std::make_shared<llyx::TextView>(text1_style);
text1->SetPosition(300, 70);
AddSubView(text1);
auto fps = std::make_shared<llyx::FPSView>(llyx::FPSStyle());
fps->SetPosition(900, 30);
AddSubView(fps);
llyx::TextButtonStyle tbs;
tbs.border_width = 3;
tbs.border_color = llyx::Color(0.7f, 0.9f, 0.9f);
tbs.color = llyx::Color(0.1f, 0.5f, 0.5f);
tbs.text = "Press me!";
auto button1 = std::make_shared<llyx::TextButtonView>(tbs);
button1->SetPosition(400, 200);
button1->ClickEvent.Attach([&window](int x, int y) { window.close(); });
AddSubView(button1);
for (int i = 0; i < 4; i++) {
llyx::ProgressStyle ps;
ps.border = i+1;
ps.border_color = llyx::Color(0.8f, 0.8f, 0.8f);
ps.color = llyx::Color(0.0f, 0.0f, 0.8f);
auto progress = std::make_shared<llyx::ProgressView>(ps);
auto p = std::make_shared<float>(0.4f + i * 0.2f);
progress->SetProgress(*p);
progress->SetBounds(200, 400 + i * 80, 400, 30);
AddSubView(progress);
timer.Attach([progress,p,i]() {
*p += (i + 1) * 0.01f;
if (*p > 1.0f)
*p = 0.0f;
progress->SetProgress(*p);
});
}
// timer.Attach([this]() { timer.Dispatch(); });
timer.Dispatch();
}
};
int main()
{
// parallel_f::system::instance().setDebugLevel("FrameQueue", 1);
// parallel_f::system::instance().setAutoFlush(parallel_f::system::AutoFlush::EndOfLine);
// lli::EventManager::Instance().Enable();
sf::RenderWindow window(sf::VideoMode(1200, 800), "TestSimple");
std::shared_ptr<TestView> testview = std::make_shared<TestView>(window);
sf::Clock clock;
while (window.isOpen()) {
// lli::EventManager::Instance().Flush();
if (testview->NeedsRepaint() || clock.getElapsedTime().asSeconds() > 1.0f) {
clock.restart();
window.clear(sf::Color::Green);
window.draw(*testview);
window.display();
}
else
sf::sleep(sf::milliseconds(20));
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
default:
testview->ProcessEvent(event);
break;
}
}
}
return 0;
}
| 19.861111 | 90 | 0.61014 | deniskropp |
5843f6db4edc12739e39e69d457870313b4b64f7 | 287 | cpp | C++ | homomorphic_evaluation/ntl-11.3.2/src/CheckBUILTIN_CLZL.cpp | dklee0501/PLDI_20_242_artifact_publication | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | 160 | 2016-05-11T09:45:56.000Z | 2022-03-06T09:32:19.000Z | homomorphic_evaluation/ntl-11.3.2/src/CheckBUILTIN_CLZL.cpp | dklee0501/Lobster | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | 57 | 2016-12-26T07:02:12.000Z | 2022-03-06T16:34:31.000Z | homomorphic_evaluation/ntl-11.3.2/src/CheckBUILTIN_CLZL.cpp | dklee0501/Lobster | f2b73df9165c76e8b521d8ebd639d68321e3862b | [
"MIT"
] | 67 | 2016-10-10T17:56:22.000Z | 2022-03-15T22:56:39.000Z | #include <NTL/mach_desc.h>
#include <cstdlib>
using namespace std;
long CountLeadingZeros(unsigned long x)
{
return __builtin_clzl(x);
}
int main()
{
unsigned long x = atoi("3");
if (CountLeadingZeros(x) == NTL_BITS_PER_LONG-2)
return 0;
else
return -1;
}
| 12.478261 | 51 | 0.651568 | dklee0501 |
5846d4044eaf5a2e4149ff144927bbf99a979009 | 15,060 | hpp | C++ | core123/include/core123/counter_based_engine.hpp | fennm/fs123 | 559b97659352620ce16030824f9acd26f590f4e1 | [
"BSD-3-Clause"
] | 22 | 2019-04-10T18:05:35.000Z | 2021-12-30T12:26:39.000Z | core123/include/core123/counter_based_engine.hpp | fennm/fs123 | 559b97659352620ce16030824f9acd26f590f4e1 | [
"BSD-3-Clause"
] | 13 | 2019-04-09T00:19:29.000Z | 2021-11-04T15:57:13.000Z | core123/include/core123/counter_based_engine.hpp | fennm/fs123 | 559b97659352620ce16030824f9acd26f590f4e1 | [
"BSD-3-Clause"
] | 4 | 2019-04-07T16:33:44.000Z | 2020-07-02T02:58:51.000Z | // counter_based_engine: An adapter that turns a 'psuedo random
// function' (e.g., core123::threefry or core123::philox) into a bona
// fide standard C++ "Random Number Engine", satisfying the
// requirements in [rand.req.eng] for a result_type, constructors,
// seed methods, discard, equality and inequality operators, stream
// insertion and extraction, etc., and also providing an "extended
// API" that exposes desirable features of the counter-based paradigm.
//
// counter_based_engine<BITS>::operator()() can be called
// 2^BITS*PRF::range_size times, after which it throws an out_of_range
// exception. A large value of BITS (e.g., 64) allows for a generator
// that is practically infinite. Smaller value of BITS are useful
// when using the extended API.
//
// The 'extended API allows a counter_based_engine to be
// constructed from a user-supplied pseudo-random function (prf) and
// an initial value in the prf's domain. E.g.,
//
// threefry<4, uint64_t> prf({... master seed...});
//
// for(...){
// ...
// counter_based_engine<threefry<4, uint64_t>, 8> eng(prf, {... per-obj-seed...});
// // or equivalently, with less typing:
// auto eng = make_counter_based_engine<8>(prf, {... per-obj-seed ...});
// std::normal_distribution<float> nd;
// gaussian = nd(eng)
// ...
// }
//
// When constructed this way, one can think of the the pseudo-random
// function's 'key' as a 'master seed', and the counter_based_engine's
// 'initial value', iv, as a separate 'per-object seed' that uniquely
// specifies a finite uncorrelated sequence of result_types. The most
// significant BITS bits of the iv.back() must be zero. (This is why
// one might want BITS<64). In the example above, there are 2^256
// possible prfs, and 2^248 permissible values for the iv, each of
// which defines a sequence of length 1024.
//
// IMPORTANT: If the pseudo-random function is "strong", then all
// sequences generated by counter_based_engine, with differently
// keyed prf's and/or different values of the iv are UNIFORMLY
// DISTRIBUTED AND ARE STATISTICALLY INDEPENDENT FROM ONE ANOTHER.
// This is true EVEN IF ONLY BIT IS DIFFERENT IN THE PRF's KEYS OR THE
// INITIAL VALUES. For strong pseudo-random functions, THERE IS NO
// NEED TO "RANDOMIZE" THE KEYS OR THE IVS. IT IS SUFFICIENT FOR THEM
// TO BE UNIQUE. The pseudo-random functions in core123 (threefry,
// philox and chacha) are all strong in this sense.
//
// Extended API:
// Informational member functions
//
// unsigned long long sequence_length() - returns
// 2^BITS*PRF::range_size if it is representable as an unsigned
// long long, and returns the maximum unsigned long long otherwise.
// It is an error (reported by throwing out_of_range) to request
// more than the maximum number of random values (either by
// operator() or by discard()).
//
// unsigned long long navail() - returns (at least) the number of
// values that are still available to be generated. If the number
// exceeds the maximum value representable by unsigned long long,
// then the maximum unsigned long long value is returned.
//
// Accessor member functions:
//
// prf() - returns a copy of the pseudo-random function
// currently in use by the engine.
// iv()- returns the initial value that began the sequence
// currently being generated.
//
// Seeding and reinitialization:
//
// seed(const PRF& prf, const PRF::domain_type& iv) - resets the
// generator to one equivalent to counter_based_engine(prf(), iv()).
//
// reinit(const PRF::domain_type& iv) - resets the generator
// to one equivalent to counter_based_engine(prf(), iv). I.e.,
// it leaves the prf in place, but resets the initial value to iv.
//
// counter_based_engines that have been constructed or seeded using
// the conventional API (via the default constructor, the result_type
// constructor, the "seed sequence" constructor, or the analogous
// seed() members) will have a "randomly" keyed PRF and a "random" iv.
// The "random" key and iv will be constructed deterministically by
// calling the generate member of a "seed sequence" (either one that
// was provided, or std::seed_seq).
#include "strutils.hpp"
#include "detail/prf_common.hpp"
#include <random>
#include <limits>
#include <stdexcept>
#include <array>
#include <iostream>
#include <type_traits>
namespace core123{
namespace detail{
template <typename SeedSeq, typename EngType, typename ResultType>
using enable_if_seed_seq = typename std::enable_if<!std::is_convertible<SeedSeq, ResultType>::value &&
!std::is_same<std::remove_reference_t<std::remove_cv_t<SeedSeq>>, EngType>::value
>::type;
}
// Details (these could have been done differently, but they all
// have to be consistent):
// - The constructor does *not* call the prf.
// - The prf is called to 'refill' the array of randoms (r) when
// the generator (operator()()) is called the first time, and
// then again on the Ndomain'th time, the 2*Ndomain'th time, etc.
// - In between calls to 'refill', values are returned from the
// randoms (r) array. The index of the next value to return
// is stored in r[0] (saving one word of memory).
// - The first time the prf is called, the high BITS of the counter
// are zero.
// - The counter is incremented immediately after
// the prf is called. Thus, the 'r' member is *not* the prf
// of the 'c' member.
// - The sequence is exhausted when we try to 'refill' the 2^BIT'th
// time, at which point, the high bits of the counter have wrapped
// around to zero. We distinguish this from the very first
// invocation of refill by initializing the structure with an
// otherwise impossible value of r[0]. This adds some special-case
// logic to operator>>, discard, navail, etc., but the constructor
// and operator() are reasonably clean.
// - sequence_length() and navail() are tricky because the "correct"
// answer may not fit in an unsigned long long.
template <typename PRF, unsigned BITS>
struct counter_based_engine{
private:
using domain_type = typename PRF::domain_type;
using range_type = typename PRF::range_type;
using dv_type = typename domain_type::value_type;
using rv_type = typename range_type::value_type;
static constexpr int W = std::numeric_limits<dv_type>::digits;
static_assert(BITS <= W, "BITS must be less than or equal to the PRF's domain value_type");
static constexpr auto Ndomain = PRF::domain_size;
static constexpr auto Nrange = PRF::range_size;
// Shift operators are very weird in two ways:
// 1 - they're undefined when the shift amount is equal
// to the width of the operand
// 2 - they never return anything narrower than unsigned int.
// There are several places in the code below where we'd naturally
// write n << (W-BITS) or n >> (W-BITS). But with BITS==0, those
// expressions would be undefined. A ternary conditional avoids
// the undefined behavior. Wrapping it in a function coerces the
// returned value back to dv_type and also *seems* to silence
// bogus (because the dodgy code is unreachable)
// -Wshift-count-overflow warnings.
static constexpr dv_type LeftWB(dv_type d){
return BITS ? d<<(W-BITS) : 0;
}
static constexpr dv_type RightWB(dv_type d){
return BITS ? d>>(W-BITS) : 0;
}
static constexpr dv_type ctr_mask = LeftWB(~dv_type(0));
static constexpr dv_type incr = LeftWB(dv_type(1));
PRF f;
domain_type c;
range_type r;
rv_type refill(){
if((c.back() & ctr_mask) == 0 &&
(r[0] != Nrange+2)){
r[0] = Nrange; // reset to throw if called again
throw std::out_of_range("counter_based_engine::refill: out of counters");
}
r = f(c);
c.back() += incr;
auto ret = r[0];
r[0] = 1;
return ret;
}
static bool hibitsdirty(dv_type v){
return v & ctr_mask;
}
static constexpr unsigned long long ullmax = std::numeric_limits<unsigned long long>::max();
public:
using result_type = rv_type;
counter_based_engine(const PRF& prf_, const typename PRF::domain_type& iv)
{
seed(prf_, iv);
}
// The seed-oriented constructors all call seed.
template <class SeedSeq, typename = detail::enable_if_seed_seq<SeedSeq, counter_based_engine, result_type>>
explicit counter_based_engine(SeedSeq &q)
{
seed(q);
}
explicit counter_based_engine(result_type s)
{
seed(s);
}
counter_based_engine()
{
seed();
}
// The seed() members all forward to seed(SeedSeq), which
// initializes both the PRF and the IV from a call to
// q.generate().
void seed(result_type s){
static constexpr unsigned N32 = (sizeof(result_type)-1) / sizeof(uint32_t) + 1;
std::array<uint32_t, N32> a;
for(unsigned i=0; i<N32; ++i){
a[i] = s&0xffffffff;
s >>= 32;
}
std::seed_seq q(a.begin(), a.end());
seed(q);
}
void seed(){
// The seed_seq is initialized with little-endian("core123::default")
// (which should be different from anything initialized with either
// a 32-bit or 64-bit result-type). Hopefully this won't "collide"
// with any seed that can be manufactured by the other seed methods.
std::seed_seq q({0x65726f63, 0x3a333231, 0x6665643a, 0x746c756});
seed(q);
}
template <class SeedSeq, typename = detail::enable_if_seed_seq<SeedSeq, counter_based_engine, result_type>>
void seed(SeedSeq &q){
static const size_t Nk32 = detail::u32_for<typename PRF::key_type>();
static const size_t Nd32 = detail::u32_for<typename PRF::domain_type>();
std::array<uint32_t, Nk32+Nd32> a;
// Call q.generate. N.B. the 'seedseq' serves very little
// purpose here. As long as we avoid *identical* keys and
// initial values, counter-based prngs produce independent and
// uncorrelated sequences. The SeedSeq' can't help. It can
// only hurt (by producing the same key from two different
// initializations). Nevertheless, it's required by the standard...
q.generate(a.begin(), a.end());
typename PRF::key_type kk;
typename PRF::domain_type cc;
auto b = std::begin(a);
auto e = std::end(a);
b = detail::stdarray_from_u32(kk, b, e);
f = PRF{kk};
detail::stdarray_from_u32(cc, b, e);
cc.back() &= ~ctr_mask;
reinit(cc);
}
// A non-required seed function corresponding to our non-required constructor:
void seed(const PRF& prf_, const typename PRF::domain_type& iv){
f = prf_;
reinit(iv);
}
result_type operator()(){
auto idx = r[0]++;
if(idx >= Nrange)
return refill();
return r[idx];
}
static constexpr result_type min() { return 0; }
static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
// accessors for the prf and the iv.
PRF prf() const{
return f;
}
typename PRF::domain_type iv() const {
auto ret = c;
ret.back() &= ~ctr_mask;
return ret;
}
// reinit is a mutator that changes the iv but leaves the prf
// alone. There's a seed() member that changes both. There is no
// mutator that changes the key and leaves the iv alone. Should
// reinit be called seed()? If so, we need some extra enable_if
// logic to avoid ambiguity with seed(SeedSeq).
void reinit(const typename PRF::domain_type& iv_){
if( hibitsdirty(iv_.back()) )
throw std::invalid_argument("cbgenerator<BITS>::reset: high BITS of counter not zero");
c = iv_;
r[0] = Nrange+1;
}
void discard(unsigned long long n){
if(n==0)
return;
auto nfill = n/Nrange;
auto nextra = n%Nrange;
auto r0 = (r[0]==Nrange+1) ? Nrange : r[0]; // unwind the tricky first-time special case
r0 += nextra;
if(r0 > Nrange){
nfill++;
r0 -= Nrange;
}
// Check for overflow. Is nfill too big?
if(nfill){
dv_type dv_nfillm1 = nfill-1;
if( RightWB(LeftWB(dv_nfillm1)) != nfill-1 ){
// queue up an overflow if operator() is called again
c.back() &= ~ctr_mask;
r[0] = Nrange;
throw std::out_of_range("discard too large");
}
c.back() += dv_nfillm1*incr;
r[0]++; // more wacky first-time stuff.
refill(); // if this throws, do we
}
r[0] = r0;
}
unsigned long long navail() const {
using ull = unsigned long long;
if(r[0] == Nrange+1)
return sequence_length();
ull ctr = RightWB(c.back());
if(ctr == 0) // we've wrapped. What's in r[] is all that's left.
return Nrange - r[0];
ull cmaxm1 = RightWB(ctr_mask);
ull cleft = cmaxm1 - ctr + 1;
if( cleft > ullmax/Nrange )
return ullmax;
else
return Nrange * cleft + (Nrange-r[0]);
}
static constexpr unsigned long long sequence_length(){
unsigned long long cmax = RightWB(ctr_mask);
if( cmax >= ullmax/Nrange )
return ullmax;
else
return Nrange * (cmax+1);
}
friend bool operator==(const counter_based_engine& lhs, const counter_based_engine& rhs) {
return lhs.c == rhs.c && lhs.r[0] == rhs.r[0] && lhs.f == rhs.f;
}
friend bool operator!=(const counter_based_engine& lhs, const counter_based_engine& rhs) {
return !(lhs==rhs);
}
CORE123_DETAIL_OSTREAM_OPERATOR(os, counter_based_engine, g){
os << g.f;
for(const auto e : g.c)
os << " " << e;
return os << " " << g.r[0];
}
CORE123_DETAIL_ISTREAM_OPERATOR(is, counter_based_engine, g){
PRF inprf;
range_type inc;
result_type inr0;
is >> inprf;
for(auto& cv : inc)
is >> cv;
is >> inr0;
if(is){
if(inr0 > Nrange+1 ||
(inr0 == Nrange+1 && hibitsdirty(inc.back()))){
is.setstate(std::ios::failbit);
return is;
}
g.c = inc;
g.f = std::move(inprf);
inc.back() -= incr; // backwards!
g.r = g.f(inc);
g.r[0] = inr0;
}
return is;
}
};
template <unsigned BITS, typename PRF>
auto make_counter_based_engine(const PRF& prf, const typename PRF::domain_type& c0){
return counter_based_engine<PRF, BITS>(prf, c0);
}
} // namespace core123
| 39.015544 | 132 | 0.626494 | fennm |
58482df3ccc4569c7e1e37a2ca2d070e0aec3f9c | 237 | cpp | C++ | src/eepp/window/cclipboard.cpp | dogtwelve/eepp | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | [
"MIT"
] | null | null | null | src/eepp/window/cclipboard.cpp | dogtwelve/eepp | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | [
"MIT"
] | null | null | null | src/eepp/window/cclipboard.cpp | dogtwelve/eepp | dd672ff0e108ae1e08449ca918dc144018fb4ba4 | [
"MIT"
] | null | null | null | #include <eepp/window/cclipboard.hpp>
namespace EE { namespace Window {
cClipboard::cClipboard( cWindow * window ) :
mWindow( window )
{}
cClipboard::~cClipboard() {}
cWindow * cClipboard::GetWindow() const {
return mWindow;
}
}}
| 14.8125 | 44 | 0.700422 | dogtwelve |
584d8245c86266445eb507f78bf1b2a3379d40e9 | 215 | cpp | C++ | 2/sum_array.cpp | cwaffles/CMPT225Labs | c4c6c2ff90e99ec3a5938a63f48c41dab4a8190b | [
"MIT"
] | 1 | 2016-06-04T07:39:21.000Z | 2016-06-04T07:39:21.000Z | 2/sum_array.cpp | cwaffles/CMPT225Labs | c4c6c2ff90e99ec3a5938a63f48c41dab4a8190b | [
"MIT"
] | null | null | null | 2/sum_array.cpp | cwaffles/CMPT225Labs | c4c6c2ff90e99ec3a5938a63f48c41dab4a8190b | [
"MIT"
] | null | null | null | //
// Created by eric on 24/05/16.
//
#include "sum_array.h"
int sumArray(int arr[], int arrSize)
{
int runningTotal = 0;
for(int i = 0; i < arrSize; i++)
{
runningTotal += arr[i];
}
return runningTotal;
} | 13.4375 | 36 | 0.613953 | cwaffles |
584dd318e960a40948b1b69fde2d4208ae1cb8e9 | 278 | cpp | C++ | Pacman_ASCII/src/Pacman.cpp | SebGrenier/Pacman_ASCII | 6eb6fea809d1bd97d41dee973149b8656fc01846 | [
"MIT"
] | null | null | null | Pacman_ASCII/src/Pacman.cpp | SebGrenier/Pacman_ASCII | 6eb6fea809d1bd97d41dee973149b8656fc01846 | [
"MIT"
] | null | null | null | Pacman_ASCII/src/Pacman.cpp | SebGrenier/Pacman_ASCII | 6eb6fea809d1bd97d41dee973149b8656fc01846 | [
"MIT"
] | null | null | null | #include "Pacman.h"
#include "ConsoleUtils.h"
#include <iostream>
using namespace std;
Pacman::Pacman(char chr)
: _character(chr)
{ }
Pacman::~Pacman(void)
{}
void Pacman::Draw(void) const
{
ConsoleUtils::SetCursorPosition(_position.x, _position.y);
cout << _character;
} | 15.444444 | 59 | 0.719424 | SebGrenier |
584fc3905dd2668afa845d2413808a746a79175f | 1,183 | cpp | C++ | Framework/Sources/o2/Utils/Editor/EditorScope.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Framework/Sources/o2/Utils/Editor/EditorScope.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Framework/Sources/o2/Utils/Editor/EditorScope.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2/stdafx.h"
#include "EditorScope.h"
#include "o2/Events/EventSystem.h"
#include "o2/Utils/Debug/Assert.h"
namespace o2
{
void EditorScope::Enter(int count /*= 1*/)
{
if (count > 0)
{
Actor::SetDefaultCreationMode(ActorCreateMode::NotInScene);
mDepth += count;
}
}
void EditorScope::Exit(int count /*= 1*/)
{
if (count > 0)
{
mDepth -= count;
if (mDepth == 0)
Actor::SetDefaultCreationMode(ActorCreateMode::InScene);
else
Actor::SetDefaultCreationMode(ActorCreateMode::NotInScene);
Assert(mDepth >= 0, "Editor scope Enter/Exit mismatch");
}
}
int EditorScope::GetDepth()
{
return mDepth;
}
bool EditorScope::IsInScope()
{
return mDepth > 0;
}
int EditorScope::mDepth = 0;
PushEditorScopeOnStack::PushEditorScopeOnStack(int count /*= 1*/):
mDepth(count)
{
EditorScope::Enter(count);
}
PushEditorScopeOnStack::~PushEditorScopeOnStack()
{
EditorScope::Exit(mDepth);
}
ForcePopEditorScopeOnStack::ForcePopEditorScopeOnStack()
{
mDepth = EditorScope::GetDepth();
EditorScope::Exit(mDepth);
}
ForcePopEditorScopeOnStack::~ForcePopEditorScopeOnStack()
{
EditorScope::Enter(mDepth);
}
}
| 17.144928 | 67 | 0.688926 | zenkovich |
58574d6340b50c1ba19eb70b6efdb91541ddc805 | 11,669 | cpp | C++ | tests/cuda4.1sdk/tests/simpleTexture3D/simpleTexture3D.cpp | florianjacob/gpuocelot | fa63920ee7c5f9a86e264cd8acd4264657cbd190 | [
"BSD-3-Clause"
] | 221 | 2015-03-29T02:05:49.000Z | 2022-03-25T01:45:36.000Z | tests/cuda4.1sdk/tests/simpleTexture3D/simpleTexture3D.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 106 | 2015-03-29T01:28:42.000Z | 2022-02-15T19:38:23.000Z | tests/cuda4.1sdk/tests/simpleTexture3D/simpleTexture3D.cpp | mprevot/gpuocelot | d9277ef05a110e941aef77031382d0260ff115ef | [
"BSD-3-Clause"
] | 83 | 2015-07-10T23:09:57.000Z | 2022-03-25T03:01:00.000Z | /*
* Copyright 1993-2010 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/*
3D texture sample
This sample loads a 3D volume from disk and displays slices through it
using 3D texture lookups.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <GL/glew.h>
#if defined (__APPLE__) || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/freeglut.h>
#endif
#include <vector_types.h>
#include <driver_functions.h>
#include <cutil_inline.h> // includes cuda.h and cuda_runtime_api.h
#include <cutil_gl_inline.h>
#include <shrQATest.h>
#include <cuda_gl_interop.h>
#include <rendercheck_gl.h>
typedef unsigned int uint;
typedef unsigned char uchar;
#define MAX_EPSILON_ERROR 5.0f
#define THRESHOLD 0.15f
const char *sSDKsample = "simpleTexture3D";
// Define the files that are to be save and the reference images for validation
const char *sOriginal[] =
{
"simpleTex3D.ppm",
NULL
};
const char *sReference[] =
{
"ref_simpleTex3D.ppm",
NULL
};
const char *volumeFilename = "Bucky.raw";
const cudaExtent volumeSize = make_cudaExtent(32, 32, 32);
const uint width = 512, height = 512;
const dim3 blockSize(16, 16, 1);
const dim3 gridSize(width / blockSize.x, height / blockSize.y);
float w = 0.5; // texture coordinate in z
GLuint pbo; // OpenGL pixel buffer object
struct cudaGraphicsResource *cuda_pbo_resource; // CUDA Graphics Resource (to transfer PBO)
bool linearFiltering = true;
bool animate = true;
unsigned int timer = 0;
uint *d_output = NULL;
// Auto-Verification Code
const int frameCheckNumber = 4;
int fpsCount = 0; // FPS count for averaging
int fpsLimit = 1; // FPS limit for sampling
int g_Index = 0;
unsigned int frameCount = 0;
unsigned int g_TotalErrors = 0;
bool g_Verify = false;
bool g_bQAReadback = false;
bool g_bOpenGLQA = false;
// CheckFBO/BackBuffer class objects
CheckRender *g_CheckRender = NULL;
int *pArgc = NULL;
char **pArgv = NULL;
#define MAX(a,b) ((a > b) ? a : b)
extern "C" void setTextureFilterMode(bool bLinearFilter);
extern "C" void initCuda(const uchar *h_volume, cudaExtent volumeSize);
extern "C" void render_kernel(dim3 gridSize, dim3 blockSize, uint *d_output, uint imageW, uint imageH, float w);
void loadVolumeData(char *exec_path);
void AutoQATest()
{
if (g_CheckRender && g_CheckRender->IsQAReadback()) {
char temp[256];
sprintf(temp, "AutoTest: %s", sSDKsample);
glutSetWindowTitle(temp);
shrQAFinishExit2(true, *pArgc, (const char **)pArgv, QA_PASSED);
}
}
void computeFPS()
{
frameCount++;
fpsCount++;
if (fpsCount == fpsLimit-1) {
g_Verify = true;
}
if (fpsCount == fpsLimit) {
char fps[256];
float ifps = 1.f / (cutGetAverageTimerValue(timer) / 1000.f);
sprintf(fps, "%s %s: %3.1f fps", sSDKsample,
((g_CheckRender && g_CheckRender->IsQAReadback()) ? "AutoTest: " : ""), ifps);
glutSetWindowTitle(fps);
fpsCount = 0;
if (g_CheckRender && !g_CheckRender->IsQAReadback()) fpsLimit = (int)MAX(ifps, 1.f);
cutilCheckError(cutResetTimer(timer));
AutoQATest();
}
}
// render image using CUDA
void render()
{
// map PBO to get CUDA device pointer
cutilSafeCall(cudaGraphicsMapResources(1, &cuda_pbo_resource, 0));
size_t num_bytes;
cutilSafeCall(cudaGraphicsResourceGetMappedPointer((void **)&d_output, &num_bytes,
cuda_pbo_resource));
//printf("CUDA mapped PBO: May access %ld bytes\n", num_bytes);
// call CUDA kernel, writing results to PBO
render_kernel(gridSize, blockSize, d_output, width, height, w);
cutilCheckMsg("kernel failed");
cutilSafeCall(cudaGraphicsUnmapResources(1, &cuda_pbo_resource, 0));
}
// display results using OpenGL (called by GLUT)
void display()
{
cutilCheckError(cutStartTimer(timer));
render();
// display results
glClear(GL_COLOR_BUFFER_BIT);
// draw image from PBO
glDisable(GL_DEPTH_TEST);
glRasterPos2i(0, 0);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
if (g_CheckRender && g_CheckRender->IsQAReadback() && g_Verify) {
// readback for QA testing
printf("> (Frame %d) Readback BackBuffer\n", frameCount);
g_CheckRender->readback( width, height );
g_CheckRender->savePPM(sOriginal[g_Index], true, NULL);
if (!g_CheckRender->PPMvsPPM(sOriginal[g_Index], sReference[g_Index], MAX_EPSILON_ERROR, THRESHOLD)) {
g_TotalErrors++;
}
g_Verify = false;
}
glutSwapBuffers();
glutReportErrors();
cutilCheckError(cutStopTimer(timer));
computeFPS();
}
void idle()
{
if (animate) {
w += 0.01f;
glutPostRedisplay();
}
}
void keyboard(unsigned char key, int x, int y)
{
switch(key) {
case 27:
exit(0);
break;
case '=':
case '+':
w += 0.01f;
break;
case '-':
w -= 0.01f;
break;
case 'f':
linearFiltering = !linearFiltering;
setTextureFilterMode(linearFiltering);
break;
case ' ':
animate = !animate;
break;
default:
break;
}
glutPostRedisplay();
}
void reshape(int x, int y)
{
glViewport(0, 0, x, y);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
}
void cleanup()
{
cutilCheckError( cutDeleteTimer( timer));
if (!g_bQAReadback) {
// unregister this buffer object from CUDA C
cudaGraphicsUnregisterResource(cuda_pbo_resource);
glDeleteBuffersARB(1, &pbo);
}
if (g_CheckRender) {
delete g_CheckRender; g_CheckRender = NULL;
}
}
void initGLBuffers()
{
// create pixel buffer object
glGenBuffersARB(1, &pbo);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo);
glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, width*height*sizeof(GLubyte)*4, 0, GL_STREAM_DRAW_ARB);
glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
// register this buffer object with CUDA
cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_pbo_resource, pbo, cudaGraphicsMapFlagsWriteDiscard));
}
// Load raw data from disk
uchar *loadRawFile(const char *filename, size_t size)
{
FILE *fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Error opening file '%s'\n", filename);
return 0;
}
uchar *data = (uchar *) malloc(size);
size_t read = fread(data, 1, size, fp);
fclose(fp);
printf("Read '%s', %lu bytes\n", filename, read);
return data;
}
void initGL( int *argc, char **argv )
{
// initialize GLUT callback functions
glutInit(argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(width, height);
glutCreateWindow("CUDA 3D texture");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glewInit();
if (!glewIsSupported("GL_VERSION_2_0 GL_ARB_pixel_buffer_object")) {
fprintf(stderr, "Required OpenGL extensions missing.");
exit(-1);
}
}
// General initialization call for CUDA Device
int chooseCudaDevice(int argc, char **argv, bool bUseOpenGL)
{
int result = 0;
if (bUseOpenGL) {
result = cutilChooseCudaGLDevice(argc, argv);
} else {
result = cutilChooseCudaDevice(argc, argv);
}
return result;
}
void runAutoTest( int argc, char **argv )
{
g_CheckRender = new CheckBackBuffer(width, height, 4, false);
g_CheckRender->setPixelFormat(GL_RGBA);
g_CheckRender->setExecPath(argv[0]);
g_CheckRender->EnableQAReadback(true);
// use command-line specified CUDA device, otherwise use device with highest Gflops/s
chooseCudaDevice(argc, argv, false);
loadVolumeData(argv[0]);
cutilSafeCall( cudaMalloc((void **)&d_output, width*height*sizeof(GLubyte)*4) );
// render the volumeData
render_kernel(gridSize, blockSize, d_output, width, height, w);
cutilSafeCall( cutilDeviceSynchronize() );
cutilCheckMsg("render_kernel failed");
cutilSafeCall( cudaMemcpy( g_CheckRender->imageData(), d_output, width*height*sizeof(GLubyte)*4, cudaMemcpyDeviceToHost) );
g_CheckRender->dumpBin((void *)g_CheckRender->imageData(), width*height*sizeof(GLubyte)*4, "simpleTexture3D.bin");
if (!g_CheckRender->compareBin2BinFloat("simpleTexture3D.bin", "ref_texture3D.bin", width*height*sizeof(GLubyte)*4, MAX_EPSILON_ERROR, THRESHOLD))
g_TotalErrors++;
cutilSafeCall( cudaFree(d_output) );
}
void loadVolumeData(char *exec_path)
{
// load volume data
const char* path = cutFindFilePath(volumeFilename, exec_path);
if (path == NULL) {
fprintf(stderr, "Error unable to find 3D Volume file: '%s'\n", volumeFilename);
shrQAFinishExit2(false, *pArgc, (const char **)pArgv, QA_FAILED);
}
size_t size = volumeSize.width*volumeSize.height*volumeSize.depth;
uchar *h_volume = loadRawFile(path, size);
initCuda(h_volume, volumeSize);
cutilCheckError( cutCreateTimer( &timer));
free(h_volume);
}
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int
main( int argc, char** argv)
{
pArgc = &argc;
pArgv = argv;
shrQAStart(argc, argv);
printf("[%s] ", sSDKsample);
if (argc > 1) {
if (cutCheckCmdLineFlag(argc, (const char **)argv, "qatest") ||
cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt"))
{
g_bQAReadback = true;
fpsLimit = frameCheckNumber;
}
if (cutCheckCmdLineFlag(argc, (const char **)argv, "glverify"))
{
g_bOpenGLQA = true;
fpsLimit = frameCheckNumber;
}
}
if (g_bQAReadback) printf("(Automated Testing)\n");
if (g_bOpenGLQA) printf("(OpenGL Readback)\n");
if (g_bQAReadback) {
runAutoTest(argc, argv);
cleanup();
cutilDeviceReset();
shrQAFinishExit(argc, (const char **)argv, (g_TotalErrors > 0) ? QA_FAILED : QA_PASSED);
}
else
{
if (g_bOpenGLQA) {
g_CheckRender = new CheckBackBuffer(width, height, 4);
g_CheckRender->setPixelFormat(GL_RGBA);
g_CheckRender->setExecPath(argv[0]);
g_CheckRender->EnableQAReadback(true);
}
// First initialize OpenGL context, so we can properly set the GL for CUDA.
// This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
initGL(&argc, argv);
// use command-line specified CUDA device, otherwise use device with highest Gflops/s
chooseCudaDevice(argc, argv, true);
// OpenGL buffers
initGLBuffers();
loadVolumeData(argv[0]);
}
printf("Press space to toggle animation\n"
"Press '+' and '-' to change displayed slice\n");
atexit(cleanup);
glutMainLoop();
cutilDeviceReset();
shrQAFinishExit(argc, (const char **)argv, QA_PASSED);
}
| 27.200466 | 150 | 0.649327 | florianjacob |
5858ba9538f6b2012a8c637ee0f63e3f56f64114 | 15,197 | cpp | C++ | Proj_Android/app/src/main/cpp/FPolyPath.cpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 3 | 2019-10-10T19:25:42.000Z | 2019-12-17T10:51:23.000Z | Framework/[C++ Core]/FPolyPath.cpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | null | null | null | Framework/[C++ Core]/FPolyPath.cpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 1 | 2021-11-16T15:29:40.000Z | 2021-11-16T15:29:40.000Z | //
// FPolyPath.cpp
// DigMMMac
//
// Created by Nicholas Raptis on 3/30/15.
// Copyright (c) 2015 Nick Raptis. All rights reserved.
//
#include "FPolyPath.hpp"
#include "FApp.hpp"
#include "core_includes.h"
FPolyPathInterp::FPolyPathInterp() {
mValid = false;
mIndexStart = -1;
mIndexEnd = -1;
mPercentInterp = 0.0f;
mX = 0.0f;
mY = 0.0f;
mNormX = 0.0f;
mNormY = -1.0f;
//mWidth = 0.0f;
//mRotation = 0.0f;
}
FPolyPathInterp::~FPolyPathInterp() {
}
FPolyPath::FPolyPath() {
mCount=0;
mSize=0;
mLength = 0.0f;
mRefresh = true;
mClosed = false;
mWrap = false;
mFlipNormals = true;
mX = 0;
mY = 0;
mDistance = 0;
mPercent = 0;
mDirX = 0;
mDirY = 0;
mNormX = 0;
mNormY = 0;
//mLerpX = 0;
//mLerpY = 0;
//mWidth = 0;
//mRotation = 0;
//mFaceCenterX = 0;
//mFaceCenterY = 0;
//mFaceCenterRotation = 0;
mCenterX = 0.0f;
mCenterY = 0.0f;
}
FPolyPath::~FPolyPath() {
Clear();
}
void FPolyPath::Clear() {
delete [] mX;
mCount=0;
mSize=0;
mLength = 0.0f;
mRefresh = true;
mCenterX = 0.0f;
mCenterY = 0.0f;
mX = 0;
mY = 0;
mDistance = 0;
mPercent = 0;
mDirX = 0;
mDirY = 0;
mNormX = 0;
mNormY = 0;
//mLerpX = 0;
//mLerpY = 0;
//mWidth = 0;
//mRotation = 0;
//mFaceCenterX = 0;
//mFaceCenterY = 0;
//mFaceCenterRotation = 0;
}
void FPolyPath::RemoveAll() {
mCount = 0;
mRefresh = true;
}
void FPolyPath::Add(float pX, float pY) {
if (mCount >= mSize) {
Size(mCount + (mCount / 2) + 1);
}
mX[mCount] = pX;
mY[mCount] = pY;
mCount++;
mRefresh = true;
}
void FPolyPath::Add(FPointList *pList) {
if (pList) {
for (int i=0;i<pList->mCount;i++) {
Add(pList->mX[i], pList->mY[i]);
}
}
mRefresh = true;
}
void FPolyPath::Set(int pIndex, float pX, float pY) {
if (pIndex >= mSize) {
SetSize(pIndex + (pIndex / 2) + 1);
}
if (pIndex >= mCount) {
mCount = (pIndex + 1);
}
if (pIndex >= 0) {
mX[pIndex] = pX;
mY[pIndex] = pY;
mRefresh = true;
}
}
void FPolyPath::Size(int pSize) {
if (pSize != mSize) {
if (pSize <= 0) {
Clear();
} else {
if (mCount >= pSize) {
mCount = pSize;
}
int aSize = pSize + 1;
float *aNewX = new float[aSize * 8 + 8];
float *aNewY = aNewX + aSize;
float *aNewDistance = aNewY + aSize;
float *aNewPercent = aNewDistance + aSize;
float *aNewDirX = aNewPercent + aSize;
float *aNewDirY = aNewDirX + aSize;
float *aNewNormX = aNewDirY + aSize;
float *aNewNormY = aNewNormX + aSize;
//float *aNewLerpX = aNewNormY + aSize;
//float *aNewLerpY = aNewLerpX + aSize;
//float *aNewWidth = aNewLerpY + aSize;
//float *aNewRotation = aNewNormY + aSize;
//float *aNewFaceCenterX = aNewRotation + aSize;
//float *aNewFaceCenterY = aNewFaceCenterX + aSize;
//float *aNewFaceCenterRotation = aNewRotation + aSize;
for(int i=0;i<mCount;i++)aNewX[i] = mX[i];
for(int i=0;i<mCount;i++)aNewY[i] = mY[i];
for(int i=0;i<mCount;i++)aNewDistance[i] = mDistance[i];
for(int i=0;i<mCount;i++)aNewPercent[i] = mPercent[i];
for(int i=0;i<mCount;i++)aNewDirX[i] = mDirX[i];
for(int i=0;i<mCount;i++)aNewDirY[i] = mDirY[i];
for(int i=0;i<mCount;i++)aNewNormX[i] = mNormX[i];
for(int i=0;i<mCount;i++)aNewNormY[i] = mNormY[i];
//for(int i=0;i<mCount;i++)aNewLerpX[i] = mLerpX[i];
//for(int i=0;i<mCount;i++)aNewLerpY[i] = mLerpY[i];
//for(int i=0;i<mCount;i++)aNewWidth[i] = mWidth[i];
//for(int i=0;i<mCount;i++)aNewRotation[i] = mRotation[i];
//for(int i=0;i<mCount;i++)aNewFaceCenterX[i] = mFaceCenterX[i];
//for(int i=0;i<mCount;i++)aNewFaceCenterY[i] = mFaceCenterY[i];
//for(int i=0;i<mCount;i++)aNewFaceCenterRotation[i] = mFaceCenterRotation[i];
for(int i=mCount;i<aSize;i++)aNewX[i] = 0.0f;
for(int i=mCount;i<aSize;i++)aNewY[i] = 0.0f;
for(int i=mCount;i<aSize;i++)aNewDistance[i] = 0.0f;
for(int i=mCount;i<aSize;i++)aNewPercent[i] = 0.0f;
for(int i=mCount;i<aSize;i++)aNewDirX[i] = 0.0f;
for(int i=mCount;i<aSize;i++)aNewDirY[i] = -1.0f;
for(int i=mCount;i<aSize;i++)aNewNormX[i] = 1.0f;
for(int i=mCount;i<aSize;i++)aNewNormY[i] = 0.0f;
//for(int i=mCount;i<aSize;i++)aNewLerpX[i] = 1.0f;
//for(int i=mCount;i<aSize;i++)aNewLerpY[i] = 0.0f;
//for(int i=mCount;i<aSize;i++)aNewWidth[i] = 1.0f;
//for(int i=mCount;i<aSize;i++)aNewRotation[i] = 0.0f;
//for(int i=mCount;i<aSize;i++)aNewFaceCenterX[i] = -1.0f;
//for(int i=mCount;i<aSize;i++)aNewFaceCenterY[i] = 0.0f;
//for(int i=mCount;i<aSize;i++)aNewFaceCenterRotation[i] = 0.0f;
delete [] mX;
mX = aNewX;
mY = aNewY;
mDistance = aNewDistance;
mPercent = aNewPercent;
mDirX = aNewDirX;
mDirY = aNewDirY;
mNormX = aNewNormX;
mNormY = aNewNormY;
//mLerpX = aNewLerpX;
//mLerpY = aNewLerpY;
//mWidth = aNewWidth;
//mRotation = aNewRotation;
//mFaceCenterX = aNewFaceCenterX;
//mFaceCenterY = aNewFaceCenterY;
//mFaceCenterRotation = aNewFaceCenterRotation;
mSize = pSize;
mRefresh = true;
}
}
}
void FPolyPath::Draw() {
if (mRefresh == true) {
Generate();
}
DrawPoints();
DrawEdges();
DrawNormals();
Graphics::SetColor();
}
void FPolyPath::DrawPoints() {
float aX = 0.0f;
float aY = 0.0f;
float aSize = 8.0f;
float aSize2 = aSize * 0.5f;
for (int i=0;i<mCount;i++) {
aX = mX[i];
aY = mY[i];
Graphics::DrawRect(aX - aSize2, aY - aSize2, aSize, aSize);
//gAppBase->mSysFont.Center(FString(i).c(), aX, aY - 30.0f);
}
}
void FPolyPath::DrawEdges() {
if (mCount > 1) {
int aIndex = 0;
float aX = 0.0f;
float aY = 0.0f;
float aLastX = aX;
float aLastY = aY;
if (mClosed == true) {
aIndex = 0;
aLastX = mX[mCount - 1];
aLastY = mY[mCount - 1];
} else {
aIndex = 1;
aLastX = mX[0];
aLastY = mY[0];
}
while (aIndex < mCount) {
aX = mX[aIndex];
aY = mY[aIndex];
Graphics::DrawLine(aLastX, aLastY, aX, aY, 1.0f);
aLastX = aX;
aLastY = aY;
aIndex++;
}
}
}
void FPolyPath::DrawNormals() {
float aX = 0.0f;
float aY = 0.0f;
float aDrawX = 0.0f;
float aDrawY = 0.0f;
float aLength = 10.0f;
int aCount = mCount;
if (aCount > 0) {
if (mClosed) {
aCount++;
}
}
for (int aIndex = 0;aIndex < aCount; aIndex++) {
aX = mX[aIndex];
aY = mY[aIndex];
aDrawX = mNormX[aIndex] * aLength;
aDrawY = mNormY[aIndex] * aLength;
aDrawX += aX;
aDrawY += aY;
Graphics::DrawLine(aX, aY, aDrawX, aDrawY);
Graphics::DrawPoint(aDrawX, aDrawY, 3.0f);
}
}
bool FPolyPath::Interpolate(float pLength) {
return Interpolate(&mInterpolater, pLength);
}
bool FPolyPath::Interpolate(FPolyPathInterp *pInterp, float pLength) {
bool aResult = false;
if (mRefresh) {
Generate();
}
if (pInterp) {
pInterp->mValid = false;
pInterp->mIndexStart = -1;
pInterp->mIndexEnd = -1;
if ((mLength > 0.025f) && (mCount > 1)) {
if (mWrap) {
if (pLength > mLength) {
int aLoops = 32;
while ((aLoops > 0) && (pLength > mLength)) {
pLength -= mLength;
aLoops--;
}
}
if (pLength < 0.0f) {
int aLoops = 32;
while ((aLoops > 0) && (pLength < 0.0f)) {
pLength += mLength;
aLoops--;
}
}
} else {
if (pLength > mLength) {
pLength = mLength;
}
}
int aInd1 = 0;
int aInd2 = 0;
int aCount = mCount;
if (mClosed) { aCount++; }
int aMid = 0;
int aHigh = mCount;
while (aInd2 != aHigh) {
aMid = (aInd2 + aHigh) >> 1;
if (mDistance[aMid] <= pLength) {
aInd2 = aMid + 1;
} else {
aHigh = aMid;
}
}
bool aLoopStart = false;
aInd1 = (aInd2 - 1);
if (aInd1 < 0) {
aLoopStart = true;
aInd1 = (aCount - 1);
}
float aLengthStart = mDistance[aInd1];
float aLengthEnd = mDistance[aInd2];
if (aLoopStart == true) {
aLengthEnd += mLength;
}
float aRange = aLengthEnd - aLengthStart;
float aPercent = 0.0f;
if (aRange > SQRT_EPSILON) {
aPercent = (float)(((pLength - aLengthStart)) / aRange);
}
pInterp->mValid = true;
aResult = true;
pInterp->mPercentInterp = aPercent;
pInterp->mIndexStart = aInd1;
pInterp->mIndexEnd = aInd2;
pInterp->mLineX1 = mX[aInd1];
pInterp->mLineY1 = mY[aInd1];
pInterp->mLineX2 = mX[aInd2];
pInterp->mLineY2 = mY[aInd2];
//pInterp->mLineRotation = mRotation[aInd1];
pInterp->mX = mX[aInd1] + (mX[aInd2] - mX[aInd1]) * aPercent;
pInterp->mY = mY[aInd1] + (mY[aInd2] - mY[aInd1]) * aPercent;
}
}
return aResult;
}
void FPolyPath::GetWithDist(float pDistance, float &pX, float &pY) {
Interpolate(pDistance);
pX = mInterpolater.mX;
pY = mInterpolater.mY;
}
void FPolyPath::GetWithPercent(float pPercent, float &pX, float &pY) {
GetWithDist(pPercent * mLength, pX, pY);
}
void FPolyPath::GetRandom(float &pX, float &pY) {
GetWithDist(gRand.GetFloat(mLength), pX, pY);
}
void FPolyPath::Save(FFile *pFile) {
if (pFile) {
pFile->WriteInt(mCount);
for (int i=0;i<mCount;i++) {
pFile->WriteFloat(mX[i]);
pFile->WriteFloat(mY[i]);
}
}
}
void FPolyPath::Load(FFile *pFile) {
Clear();
if (pFile) {
int aCount = pFile->ReadInt();
Size(aCount);
float aReadX = 0.0f;
float aReadY = 0.0f;
for (int i=0;i<aCount;i++) {
aReadX = pFile->ReadFloat();
aReadY = pFile->ReadFloat();
Add(aReadX, aReadY);
}
}
}
void FPolyPath::Generate() {
mRefresh = false;
mLength = 0;
mCenterX = 0.0f;
mCenterY = 0.0f;
if (mCount > 1) {
float aDiffX = 0.0f;
float aDiffY = 0.0f;
float aDist = 0.0f;
int aIndex = 1;
float aX = 0.0f;
float aY = 0.0f;
float aLastX = mX[0];
float aLastY = mY[0];
mDistance[0] = 0.0f;
mPercent[0] = 0.0f;
int aCount = mCount;
if (mClosed) {
aCount++;
mX[mCount] = mX[0];
mY[mCount] = mY[0];
}
while (aIndex < aCount) {
aX = mX[aIndex];
aY = mY[aIndex];
aDiffX = (aX - aLastX);
aDiffY = (aY - aLastY);
aDist = aDiffX * aDiffX + aDiffY * aDiffY;
if (aDist > SQRT_EPSILON) {
aDist = sqrtf(aDist);
aDiffX /= aDist;
aDiffY /= aDist;
} else {
aDist = 0.025f;
aDiffX = 0.0f;
aDiffY = -1.0f;
}
mDirX[aIndex] = aDiffX;
mDirY[aIndex] = aDiffY;
mNormX[aIndex] = -aDiffY;
mNormY[aIndex] = aDiffX;
mLength += aDist;
mDistance[aIndex] = mLength;
aLastX = aX;
aLastY = aY;
aIndex++;
}
mDistance[mCount] = mLength;
mX[mCount] = mX[0];
mY[mCount] = mY[0];
/*
mDirX[mCount] = mDirX[0];
mDirY[mCount] = mDirY[0];
mNormX[mCount] = mNormX[0];
mNormY[mCount] = mNormY[0];
mWidth[mCount] = mWidth[0];
*/
mDirX[0] = mDirX[mCount];
mDirY[0] = mDirY[mCount];
mNormX[0] = mNormX[mCount];
mNormY[0] = mNormY[mCount];
if (mFlipNormals == true) {
aIndex = 0;
while (aIndex < aCount) {
mNormX[aIndex] = -(mNormX[aIndex]);
mNormY[aIndex] = -(mNormY[aIndex]);
aIndex++;
}
}
aIndex = 0;
while (aIndex < mCount) {
mCenterX += mX[aIndex];
mCenterY += mY[aIndex];
aIndex++;
}
mCenterX /= ((float)mCount);
mCenterY /= ((float)mCount);
aIndex = 0;
while (aIndex < mCount) {
aDiffX = mX[aIndex] - mCenterX;
aDiffY = mY[aIndex] - mCenterY;
aDist = aDiffX * aDiffX + aDiffY * aDiffY;
if (aDist > SQRT_EPSILON) {
aDist = sqrtf(aDist);
aDiffX /= aDist;
aDiffY /= aDist;
} else {
aDist = 0.025f;
aDiffX = 0.0f;
aDiffY = -1.0f;
}
aIndex++;
}
if (mLength > SQRT_EPSILON) {
aIndex = 0;
while (aIndex < aCount) {
mPercent[aIndex] = mDistance[aIndex] / mLength;
aIndex++;
}
}
}
}
| 26.02226 | 90 | 0.447852 | nraptis |
5858c55105c62a1eb7e1866d773e0fce05d55ee4 | 5,159 | hpp | C++ | includes/netflex/http/request.hpp | deguangchow/NetFlex | 8fbdee6601dcbaa5be12e467bee82f1f648cd63b | [
"MIT"
] | null | null | null | includes/netflex/http/request.hpp | deguangchow/NetFlex | 8fbdee6601dcbaa5be12e467bee82f1f648cd63b | [
"MIT"
] | null | null | null | includes/netflex/http/request.hpp | deguangchow/NetFlex | 8fbdee6601dcbaa5be12e467bee82f1f648cd63b | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <string>
#include <netflex/http/header.hpp>
#include <netflex/http/method.hpp>
#include <netflex/routing/params.hpp>
namespace netflex {
namespace http {
//!
//! http request representation
//! contains all information related to the received http request
//!
class request {
public:
//! default ctor
request(void) = default;
//! default dtor
~request(void) = default;
//! copy ctor
request(const request&) = default;
//! assignment operator
request& operator=(const request&) = default;
public:
//!
//! \return request http verb
//!
method get_method(void) const;
//!
//! \return request http verb (string version)
//!
const std::string& get_raw_method(void) const;
//!
//! \return status line target
//!
const std::string& get_target(void) const;
//!
//! \return request http version
//!
const std::string& get_http_version(void) const;
//!
//! set new http verb
//!
//! \param method new http verb
//!
void set_method(method method);
//!
//! set new http verb (string version)
//!
//! \param method new http verb
//!
void set_raw_method(const std::string& method);
//!
//! set new status line target
//!
//! \param target new status line target
//!
void set_target(const std::string& target);
//!
//! set new http version
//!
//! \param http_version new http version
//!
void set_http_version(const std::string& http_version);
public:
//!
//! return specific header
//! throws an exception if header does not exist
//!
//! \param name header name to get
//! \return requested header value
//!
const std::string& get_header(const std::string& name) const;
//!
//! \return all headers for request
//!
const header_list_t& get_headers(void) const;
//!
//! set request headers
//!
//! \param headers new headers for request
//!
void set_headers(const header_list_t& headers);
//!
//! add a new header to the request header
//! if header already exists, override its value
//!
//! \param header header to be added
//!
void add_header(const header& header);
//!
//! return whether the request contains a specific header
//!
//! \param name header name to check
//! \return whether the requested header is present or not
//!
bool has_header(const std::string& name) const;
//!
//! remove a header from the request
//! does nothing if header does not exist
//!
//! \param name name of the header to remove
//!
void remove_header(const std::string& name);
public:
//!
//! \return requested path
//!
const std::string& get_path(void) const;
//!
//! \return request params (route params and GET params)
//!
const routing::params_t& get_params(void) const;
//!
//! set requested path
//!
//! \param path new path for request
//!
void set_path(const std::string& path);
//!
//! set request params
//!
//! \param params new request params
//!
void set_params(const routing::params_t& params);
public:
//!
//! \return request body
//!
const std::string& get_body(void) const;
//!
//! set request body
//!
//! \param body new request body
//!
void set_body(const std::string& body);
public:
//!
//! \return printable version of the request (for logging purpose)
//!
std::string to_string(void) const;
private:
//!
//! request http verb
//!
method m_eHttpMethod;
//!
//! request http verb (raw string)
//!
std::string m_sHttpMethod;
//!
//! status line target
//!
std::string m_sTarget;
//!
//! requested http version
//!
std::string m_sHttpVersion;
//!
//! headers
//!
header_list_t m_mapHeaders;
//!
//! requested path
//!
std::string m_sPath;
//!
//! request params
//!
routing::params_t m_mapParams;
//!
//! request body
//!
std::string m_sBody;
};
} // namespace http
} // namespace netflex
| 21.953191 | 80 | 0.65284 | deguangchow |
585c0172f41d5ac958063fd49843ba3aa5457fca | 19,964 | cpp | C++ | src/aspell-60/modules/filter/sgml.cpp | reydajp/build-spell | a88ffbb9ffedae3f20933b187c95851e47e0e4c3 | [
"MIT"
] | 31 | 2016-11-08T05:13:02.000Z | 2022-02-23T19:13:01.000Z | src/aspell-60/modules/filter/sgml.cpp | reydajp/build-spell | a88ffbb9ffedae3f20933b187c95851e47e0e4c3 | [
"MIT"
] | 6 | 2017-01-17T20:21:55.000Z | 2021-09-02T07:36:18.000Z | src/aspell-60/modules/filter/sgml.cpp | reydajp/build-spell | a88ffbb9ffedae3f20933b187c95851e47e0e4c3 | [
"MIT"
] | 5 | 2017-07-11T11:10:55.000Z | 2022-02-14T01:55:16.000Z | // This file is part of The New Aspell
// Copyright (C) 2004 by Tom Snyder
// Copyright (C) 2001-2004 by Kevin Atkinson under the GNU LGPL license
// version 2.0 or 2.1. You should have received a copy of the LGPL
// license along with this library if you did not you can find
// it at http://www.gnu.org/.
//
// The orignal filter was written by Kevin Atkinson.
// Tom Snyder rewrote the filter to support skipping SGML tags
//
// This filter enables the spell checking of sgml, html, and xhtml files
// by skipping the <elements> and such.
// The overall strategy is based on http://www.w3.org/Library/SGML.c.
// We don't use that code (nor the sourceforge 'expat' project code) for
// simplicity's sake. We don't need to fully parse all aspects of HTML -
// we just need to skip and handle a few aspects. The w3.org code had too
// many linkages into their overall SGML/HTML processing engine.
//
// See the comment at the end of this file for examples of what we handle.
// See the config setting docs regarding our config lists: check and skip.
#include <stdio.h> // needed for sprintf
#include "settings.h"
#include "asc_ctype.hpp"
#include "config.hpp"
#include "indiv_filter.hpp"
#include "string_map.hpp"
#include "mutable_container.hpp"
#include "clone_ptr-t.hpp"
#include "filter_char_vector.hpp"
//right now unused option
// static const KeyInfo sgml_options[] = {
// {"sgml-extension", KeyInfoList, "html,htm,php,sgml",
// N_("sgml file extensions")}
// };
namespace {
using namespace acommon;
class ToLowerMap : public StringMap
{
public:
PosibErr<bool> add(ParmStr to_add) {
String new_key;
for (const char * i = to_add; *i; ++i) new_key += asc_tolower(*i);
return StringMap::add(new_key);
}
PosibErr<bool> remove(ParmStr to_rem) {
String new_key;
for (const char * i = to_rem; *i; ++i) new_key += asc_tolower(*i);
return StringMap::remove(new_key);
}
};
class SgmlFilter : public IndividualFilter
{
// State enum. These states track where we are in the HTML/tag/element constructs.
// This diagram shows the main states. The marked number is the state we enter
// *after* we've read that char. Note that some of the state transitions handle
// illegal HTML such as <tag=what?>.
//
// real text <tag attrib = this attrib2='that'> </tag> {
// | | | | || | | | | | |
// 1 2 3 4 56 7 8 10 11 9 12
enum ScanState {
S_text, // 1. raw user text outside of any markup.
S_tag, // 2. reading the 'tag' in <tag>
S_tag_gap,// 3. gap between attributes within an element:
S_attr, // 4. Looking at an attrib name
S_attr_gap,// 5. optional gap after attrib name
S_equals, // 6. Attrib equals sign, also space after the equals.
S_value, // 7. In attrib value.
S_quoted, // 8. In quoted attrib value.
S_end, // 9. Same as S_tag, but this is a </zee> type end tag.
S_ignore_junk, // special case invalid area to ignore.
S_ero, // 10. in the &code; special encoding within HTML.
S_entity, // 11. in the alpha named &nom; special encoding..
S_cro, // 12. after the # of a &#nnn; numerical char reference encoding.
// SGML.. etc can have these special "declarations" within them. We skip them
// in a more raw manners since they don't abide by the attrib= rules.
// Most importantly, some of the attrib quoting rules don't apply.
// <!ENTITY rtfchar "gg" - - (high, low)> <!-- fully commented -->
// | | || |
// 20 21 23 24 25
S_md, // 20. In a declaration (or beginning a comment).
S_mdq, // 21. Declaration in quotes - double or single quotes.
S_com_1, // 23. perhaps a comment beginning.
S_com, // 24. Fully in a comment
S_com_e, // 25. Perhaps ending a comment.
//S_literal, // within a tag pair that means all content should be interpreted literally: <PRE>
// NOT CURRENTLY SUPPORTED FULLY.
//S_esc,S_dollar,S_paren,S_nonasciitext // WOULD BE USED FOR ISO_2022_JP support.
// NOT CURRENTLY SUPPORTED.
};
ScanState in_what;
// which quote char is quoting this attrib value.
FilterChar::Chr quote_val;
// one char prior to this one. For escape handling and such.
FilterChar::Chr lookbehind;
String tag_name; // we accumulate the current tag name here.
String attrib_name; // we accumulate the current attribute name here.
bool include_attrib; // are we in one of the attribs that *should* be spell checked (alt=..)
int skipall; // are we in one of the special skip-all content tags? This is treated
// as a bool and as a nesting level count.
String tag_endskip; // tag name that will end that.
StringMap check_attribs; // list of attribs that we *should* spell check.
StringMap skip_tags; // list of tags that start a no-check-at-all zone.
String which;
bool process_char(FilterChar::Chr c);
public:
SgmlFilter(const char * n) : which(n) {}
PosibErr<bool> setup(Config *);
void reset();
void process(FilterChar * &, FilterChar * &);
};
PosibErr<bool> SgmlFilter::setup(Config * opts)
{
name_ = which + "-filter";
order_num_ = 0.35;
check_attribs.clear();
skip_tags.clear();
opts->retrieve_list("f-" + which + "-skip", &skip_tags);
opts->retrieve_list("f-" + which + "-check", &check_attribs);
reset();
return true;
}
void SgmlFilter::reset()
{
in_what = S_text;
quote_val = lookbehind = '\0';
skipall = 0;
include_attrib = false;
}
// yes this should be inlines, it is only called once
// RETURNS: TRUE if the caller should skip the passed char and
// not do any spell check on it. FALSE if char is a part of the text
// of the document.
bool SgmlFilter::process_char(FilterChar::Chr c) {
bool retval = true; // DEFAULT RETURN VALUE. All returns are done
// via retval and falling out the bottom. Except for
// one case that must manage the lookbehind char.
// PS: this switch will be fast since S_ABCs are an enum and
// any good compiler will build a jump table for it.
// RE the gotos: Sometimes considered bad practice but that is
// how the W3C code (1995) handles it. Could be done also with recursion
// but I doubt that will clarify it. The gotos are done in cases where several
// state changes occur on a single input char.
switch( in_what ) {
case S_text: // 1. raw user text outside of any markup.
s_text:
switch( c ) {
case '&': in_what = S_ero;
break;
case '<': in_what = S_tag; tag_name.clear();
break;
default:
retval = skipall; // ********** RETVAL ASSIGNED
} // **************************
break;
case S_tag: // 2. reading the 'tag' in <tag>
// heads up: <foo/bar will be treated as an end tag. That's what w3c does.
switch( c ) {
case '>': goto all_end_tags;
case '/': in_what = S_end;
tag_name.clear();
break;
case '!': in_what = S_md;
break;
default: // either more alphanum of the tag, or end of tagname:
if( asc_isalpha(c) || asc_isdigit(c) ) {
tag_name += asc_tolower(c);
}
else { // End of the tag:
in_what = S_tag_gap;
goto s_tag_gap; // handle content in that zone.
}
}
break;
// '>' '>' '>' '>'
all_end_tags: // this gets called by several states to handle the
// possibility of a '>' ending a whole <tag...> guy.
if( c != '>' ) break;
in_what = S_text;
if( lookbehind == '/' ) {
// Wowza: this is how we handle the <script stuff /> XML style self
// terminating tag. By clearing the tagname out tag-skip-all code
// will not be invoked.
tag_name.clear();
}
// Does this tag cause us to skip all content?
if( skipall ) {
// already in a skip-all context. See if this is
// the same skipall tag:
if( !strcmp( tag_name.c_str(), tag_endskip.c_str() ) ) {
++skipall; // increment our nesting level count.
}
}
else { // Should we begin a skip all range?
skipall = (skip_tags.have( tag_name.c_str() ) ? 1 : 0);
if( skipall ) {
tag_endskip = tag_name; // remember what tag to end on.
}
}
break;
case S_tag_gap: // 3. gap between attributes within an element:
s_tag_gap:
switch( c ) {
case '>': goto all_end_tags;
case '=': in_what = S_attr_gap;
break; // uncommon - no-name attrib value
default:
if( asc_isspace( c ) ) break; // still in gap.
else {
in_what = S_attr; // start of attribute name;
attrib_name.clear();
attrib_name += asc_tolower( c );
}
break;
}
break;
case S_end: // 9. Same as S_tag, but this is a </zee> type end tag.
if( asc_isalpha(c) || asc_isdigit(c) ) {
tag_name += asc_tolower( c );
}
else {
// See if we have left a skipall tag range.
if( skipall && !strcmp( tag_name.c_str(), tag_endskip.c_str() ) ) {
--skipall; // lessen nesting level count. This usually takes us to zero.
}
if( c == '>' ) in_what = S_text; // --don't go to all_end_tags. Really.
else in_what = S_ignore_junk; // no-mans land: </end whats this??>
}
break;
case S_ignore_junk: // no-mans land state: </end whats this here??>
if( c == '>' ) in_what = S_text;
break;
case S_attr: // 4. Looking at an attrib name
if( asc_isspace(c) ) in_what = S_attr_gap;
else if( c == '=' ) in_what = S_equals;
else if( c == '>' ) goto all_end_tags;
else {
attrib_name += asc_tolower( c );
}
break;
case S_attr_gap: // 5. optional gap after attrib name
if( asc_isspace(c) ) break;
else if( c == '=' ) in_what = S_equals;
else if( c == '>' ) goto all_end_tags;
else { // beginning of a brand new attr
attrib_name.clear();
attrib_name += asc_tolower( c );
}
break;
case S_equals: // 6. Attrib equals sign, also space after the equals.
if( asc_isspace(c) ) break;
switch( c ) {
case '>': goto all_end_tags;
case '\'':
case '"': in_what = S_quoted;
quote_val = c;
break;
default: in_what = S_value;
break;
}
// See if this attrib deserves full checking:
include_attrib=check_attribs.have( attrib_name.c_str() );
// Handle the first value char if that is where we are now:
if( in_what == S_value ) goto s_value;
break;
case S_value: // 7. In attrib value.
s_value:
if( c == '>' ) goto all_end_tags;
else if( asc_isspace(c) ) in_what = S_tag_gap; // end of attrib value
// *****************************
// ********** RETVAL ASSIGNED
else if( include_attrib ) retval = false; // spell check this value.
break;
case S_quoted: // 8. In quoted attrib value.
if( c == quote_val && lookbehind != '\\' ) in_what = S_tag_gap;
else if( c == '\\' && lookbehind == '\\' ) {
// This is an escape of an backslash. Therefore the backslash
// does not escape what follows. Therefore we don't leave it in
// the lookbehind. Yikes!
lookbehind = '\0';
return !include_attrib; // ************* RETURN RETURN RETURN RETURN
}
else retval = !include_attrib;
break;
// note: these three cases - S_ero, S_cro, and S_entity which all handle
// the &stuff; constructs are broken into 3 states for future upgrades. Someday
// you may want to handle the chars these guys represent as individual chars.
// I don't have the desire nor the knowledge to do it now. -Tom, 5/5/04.
case S_ero: // 10. in the &code; special encoding within HTML.
// &# is a 'Char Ref Open'
if( c == '#' ) {
in_what = S_cro;
break;
}
// FALLTHROUGH INTENTIONAL
case S_cro: // 12. after the # of a &#nnn; numerical char reference encoding.
case S_entity: // 11. in the alpha named &nom; special encoding..
if( asc_isalpha(c) || asc_isdigit(c) ) break; // more entity chars.
in_what = S_text;
if( c == ';' ) break; // end of char code.
goto s_text; // ran right into text. Handle it.
// SGML.. etc can have these special "declarations" within them. We skip them
// in a more raw manners since they don't abide by the attrib= rules.
// Most importantly, some of the quoting rules don't apply.
// <!ENTITY rtfchar "gg" 'tt' - - (high, low)> <!-- fully commented -->
// | | | || ||
// 20 21 22 23 24 25 26
case S_md: // 20. In a declaration (or comment).
switch( c ) {
case '-': if( lookbehind == '!' ) {
in_what = S_com_1;
}
break;
case '"': // fallthrough - yes.
case '\'': in_what = S_mdq;
quote_val=c;
break;
case '>': in_what = S_text; // note: NOT all_end_tags cause it's not a real tag.
break;
}
break;
case S_mdq: // 22. Declaration in quotes.
if( c == quote_val ) in_what = S_md;
else if( c == '>' ) in_what = S_text;
break;
case S_com_1: // 23. perhaps a comment beginning.
if( c == '-' ) in_what = S_com;
else if( c == '>' ) in_what = S_text;
else in_what = S_md; // out of possible comment.
break;
case S_com: // 24. Fully in a comment
if( c == '-' && lookbehind == '-' ) in_what = S_com_e;
break;
case S_com_e: // 25. Perhaps ending a comment.
if( c == '>' ) in_what = S_text;
else if( c != '-' ) in_what = S_com; // back to basic comment.
break;
}
// update the lookbehind:
lookbehind = c;
return( retval );
}
void SgmlFilter::process(FilterChar * & str, FilterChar * & stop)
{
FilterChar * cur = str;
while (cur != stop) {
if (process_char(*cur))
*cur = ' ';
++cur;
}
}
//
//
//
class SgmlDecoder : public IndividualFilter
{
FilterCharVector buf;
String which;
public:
SgmlDecoder(const char * n) : which(n) {}
PosibErr<bool> setup(Config *);
void reset() {}
void process(FilterChar * &, FilterChar * &);
};
PosibErr<bool> SgmlDecoder::setup(Config *)
{
name_ = which + "-decoder";
order_num_ = 0.65;
return true;
}
void SgmlDecoder::process(FilterChar * & start, FilterChar * & stop)
{
buf.clear();
FilterChar * i = start;
while (i != stop)
{
if (*i == '&') {
FilterChar * i0 = i;
FilterChar::Chr chr;
++i;
if (i != stop && *i == '#') {
chr = 0;
++i;
while (i != stop && asc_isdigit(*i)) {
chr *= 10;
chr += *i - '0';
++i;
}
} else {
while (i != stop && (asc_isalpha(*i) || asc_isdigit(*i))) {
++i;
}
chr = '?';
}
if (i != stop && *i == ';')
++i;
buf.append(FilterChar(chr, i0, i));
} else {
buf.append(*i);
++i;
}
}
buf.append('\0');
start = buf.pbegin();
stop = buf.pend() - 1;
}
//
// Sgml Encoder - BROKEN do not use
//
// class SgmlEncoder : public IndividualFilter
// {
// FilterCharVector buf;
// String which;
// public:
// SgmlEncoder(const char * n) : which(n) {}
// PosibErr<bool> setup(Config *);
// void reset() {}
// void process(FilterChar * &, FilterChar * &);
// };
// PosibErr<bool> SgmlEncoder::setup(Config *)
// {
// name_ = which + "-encoder";
// order_num_ = 0.99;
// return true;
// }
// void SgmlEncoder::process(FilterChar * & start, FilterChar * & stop)
// {
// buf.clear();
// FilterChar * i = start;
// while (i != stop)
// {
// if (*i > 127) {
// buf.append("&#", i->width);
// char b[10];
// sprintf(b, "%d", i->chr);
// buf.append(b, 0);
// buf.append(';', 0);
// } else {
// buf.append(*i);
// }
// ++i;
// }
// buf.append('\0');
// start = buf.pbegin();
// stop = buf.pend() - 1;
// }
}
C_EXPORT IndividualFilter * new_aspell_sgml_filter()
{
return new SgmlFilter("sgml");
}
C_EXPORT IndividualFilter * new_aspell_sgml_decoder()
{
return new SgmlDecoder("sgml");
}
// C_EXPORT IndividualFilter * new_aspell_sgml_encoder()
// {
// return new SgmlEncoder("sgml");
// }
C_EXPORT IndividualFilter * new_aspell_html_filter()
{
return new SgmlFilter("html");
}
C_EXPORT IndividualFilter * new_aspell_html_decoder()
{
return new SgmlDecoder("html");
}
// C_EXPORT IndividualFilter * new_aspell_html_encoder()
// {
// return new SgmlEncoder("html");
// }
/* Example HTML:
<!--
This file contains several constructs that test the parsing and
handling of SGML/HTML/XML in sgml.cpp.
The only spelling errors you should see will be the word 'report this NNNN'.
There will be 22 of these.
run this by executing:
aspell pipe -H < sgmltest.html
WARNING: this is not really valid HTML. Don't display in a browser!
-->
<!-- phase 1 - SGML comments. -->
reportthiszphaseONE
<!-- ** 1.0 Valid comments... This file is full of them. -->
<!-- ** 1.1 invalid open comment: -->
<!- not in a comment>reportthisyes</!->
<!-- ** 1.2 invalid close comment: -->
<!-- -- > spallwhat DON'T REPORT -> spallwhat DON'T REPORT -->
<!-- phase 1.5 - special entity encodings -->
reportthisphaseONEFIVE
don't report this
 do not report this.
do not>report this.
this & that.
<!-- phase 2 - special skip tags -->
reportthisphaseTWO
<SCRIPT> spallwhat DON'T REPORT </SCRIPT> reportthisyes
<style> spallwhat DON'T REPORT </style> reportthisyes
<STYLE something="yes yes"
> spallwhat DON'T REPORT </style > reportthisyes
<script/> reportthisyes <!-- XHTML style terminated tag -->
<script someattrib=value/> reportthisyes <!-- XHTML style terminated tag -->
<!-- Nested skip tags -->
<script> spallwhatnoreport <script> nonoreport </script><b>hello</b> nonoreport</script>reportthisyes
<!-- phase 3 - special 'include this' attributes -->
reportthisphaseTHREE
<tagname alt="image text reportthisyes" alt2=spallwhat altt="spallwhat don't report">
<tagname ALT="image text reportthisyes" ALT2=spallwhat AL="spallwhat don't report">
<!-- phase 4 - attribute value quoteing and escaping -->
reportthisphaseoneFOUR
<checkthis attribute111=simple/value.value >
<checkagain SOMEattrib = "whoa boy, mimimimspelled ">
<singlequotes gotcha= 'singlypingly quoted///'>
<dblescaped gogogogo="dontcheck \">still in dontcheck\\\" still in dontcheck"> reportthisyes.
<dBLmore TomTomTomTom="so many escapes: \\\\\\\\"> reportthisyes.
<dblescaped gogogogo='dontcheck \'>still in dontcheck\\\' still in dontcheck'> reportthisyes.
<dBLmore TomTomTomTom='so many escapes: \\\\\\\\'> reportthisyes.
<mixnmatch scanhere='">dontcheck \"dontcheck \'dontcheck' alt=reportthisyes>
<!-- phase 5 - questionable (though all too common) constructs -->
reportthisphaseFIVE
<tag=dontreport> reportthisyes <tag hahahahhaha>reportthisyes
<!-- this one is from Yahoo! -->
<td width=1%><img src="http://wellll/thereeee/nowwww" alt="cool stuff">
<td width=1%><img src=http://wellll/thereeee/nowwww alt=real cool stuff>
*/
| 32.998347 | 101 | 0.586806 | reydajp |
585d27f2b0c775e3daf59590674a2556dc83baf8 | 83,348 | cpp | C++ | game/shared/cstrike15/gametypes.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | cstrike15_src/game/shared/cstrike15/gametypes.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | cstrike15_src/game/shared/cstrike15/gametypes.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | //========= Copyright (c) 1996-2011, Valve Corporation, All rights reserved. ============//
//
// Purpose: Game types and modes
//
// $NoKeywords: $
//=============================================================================//
//
// NOTE: This is horrible design to have this file included in multiple projects (client.dll, server.dll, matchmaking.dll)
// which don't have same interfaces applicable to interact with the engine and don't have sufficient context here
// hence these compile-time conditionals to use appropriate interfaces
//
#if defined( CLIENT_DLL ) || defined( GAME_DLL )
#include "cbase.h"
#endif
#if defined( MATCHMAKING_DS_DLL )
#include "eiface.h"
#include "matchmaking/imatchframework.h"
#endif
#include "gametypes.h"
#include "strtools.h"
#include "dlchelper.h"
#include "../engine/filesystem_engine.h"
#include "filesystem.h"
#include "tier2/fileutils.h"
#include "matchmaking/cstrike15/imatchext_cstrike15.h"
#if defined ( MATCHMAKING_DLL )
#include "../../../matchmaking/mm_extensions.h"
#endif
#include "fmtstr.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
void DisplayGameModeConvars( void );
// The following convars depend on the order of the game types and modes in GameModes.txt.
ConVar game_online( "game_online", "1", FCVAR_REPLICATED | FCVAR_HIDDEN | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game is online." );
ConVar game_public( "game_public", "1", FCVAR_REPLICATED | FCVAR_HIDDEN | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game is public." );
ConVar game_type( "game_type", "0", FCVAR_REPLICATED | FCVAR_RELEASE | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game type. See GameModes.txt." );
ConVar game_mode( "game_mode", "0", FCVAR_REPLICATED | FCVAR_RELEASE | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "The current game mode (based on game type). See GameModes.txt." );
ConVar custom_bot_difficulty( "custom_bot_difficulty", "0", FCVAR_REPLICATED | FCVAR_RELEASE | FCVAR_GAMEDLL | FCVAR_CLIENTDLL, "Bot difficulty for offline play." );
#if defined( CLIENT_DLL )
ConCommand cl_game_mode_convars( "cl_game_mode_convars", DisplayGameModeConvars, "Display the values of the convars for the current game_mode." );
#elif defined( GAME_DLL )
ConCommand sv_game_mode_convars( "sv_game_mode_convars", DisplayGameModeConvars, "Display the values of the convars for the current game_mode." );
#endif
// HACKY: Ok, so this file is compiled into 3 different modules so we get three different
// static game types objects... Unfortunately needs to do different things for servers and clients.
// These helpers test if we're on a client and/or server... The exposed interface is always pointing
// to the matchmaking dll instance so using its interfaces to tell where we are.
bool GameTypes_IsOnServer( void )
{
#if defined ( GAME_DLL )
return true;
#endif
#if defined ( MATCHMAKING_DLL )
return ( g_pMatchExtensions->GetIVEngineServer() != NULL );
#endif
return false;
}
bool GameTypes_IsOnClient( void )
{
#if defined ( CLIENT_DLL )
return true;
#endif
#if defined ( MATCHMAKING_DLL )
return ( g_pMatchExtensions->GetIVEngineClient() != NULL );
#endif
return false;
}
static const int g_invalidInteger = -1;
static uint32 g_richPresenceDefault = 0xFFFF;
// ============================================================================================ //
// GameType
// ============================================================================================ //
// -------------------------------------------------------------------------------------------- //
// Purpose: Constructor
// -------------------------------------------------------------------------------------------- //
GameTypes::GameType::GameType()
: m_Index( g_invalidInteger )
{
m_Name[0] = '\0';
m_NameID[0] = '\0';
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Destructor
// -------------------------------------------------------------------------------------------- //
GameTypes::GameType::~GameType()
{
m_GameModes.PurgeAndDeleteElements();
}
// ============================================================================================ //
// GameMode
// ============================================================================================ //
// -------------------------------------------------------------------------------------------- //
// Purpose: Constructor
// -------------------------------------------------------------------------------------------- //
GameTypes::GameMode::GameMode()
: m_Index( g_invalidInteger ),
m_pExecConfings( NULL )
{
m_Name[0] = '\0';
m_NameID[0] = '\0';
m_DescID[0] = '\0';
m_NameID_SP[0] = '\0';
m_DescID_SP[0] = '\0';
m_MaxPlayers = 1;
m_NoResetVoteThresholdCT = -1;
m_NoResetVoteThresholdT = -1;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Destructor
// -------------------------------------------------------------------------------------------- //
GameTypes::GameMode::~GameMode()
{
if ( m_pExecConfings )
{
m_pExecConfings->deleteThis();
}
}
// ============================================================================================ //
// Map
// ============================================================================================ //
// -------------------------------------------------------------------------------------------- //
// Purpose: Constructor
// -------------------------------------------------------------------------------------------- //
GameTypes::Map::Map()
: m_Index( g_invalidInteger ),
m_RichPresence( g_richPresenceDefault )
{
m_Name[0] = '\0';
m_NameID[0] = '\0';
m_ImageName[0] = '\0';
m_RequiresAttr[0] = 0;
m_RequiresAttrValue = -1;
m_RequiresAttrReward[0] = 0;
m_nRewardDropList = -1;
}
// ============================================================================================ //
// MapGroup
// ============================================================================================ //
// -------------------------------------------------------------------------------------------- //
// Purpose: Constructor
// -------------------------------------------------------------------------------------------- //
GameTypes::MapGroup::MapGroup()
{
m_Name[0] = '\0';
m_NameID[0] = '\0';
m_ImageName[0] = '\0';
m_bIsWorkshopMapGroup = false;
}
// ============================================================================================ //
// CustomBotDifficulty
// ============================================================================================ //
// -------------------------------------------------------------------------------------------- //
// Purpose: Constructor
// -------------------------------------------------------------------------------------------- //
GameTypes::CustomBotDifficulty::CustomBotDifficulty()
: m_Index( g_invalidInteger ),
m_pConvars( NULL ),
m_HasBotQuota( false )
{
m_Name[0] = '\0';
m_NameID[0] = '\0';
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Destructor
// -------------------------------------------------------------------------------------------- //
GameTypes::CustomBotDifficulty::~CustomBotDifficulty()
{
if ( m_pConvars )
{
m_pConvars->deleteThis();
}
}
// ============================================================================================ //
// GameTypes
// ============================================================================================ //
// Singleton
static GameTypes s_GameTypes;
IGameTypes *g_pGameTypes = &s_GameTypes;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( GameTypes, IGameTypes, VENGINE_GAMETYPES_VERSION, s_GameTypes );
// -------------------------------------------------------------------------------------------- //
// Purpose: Constructor
// -------------------------------------------------------------------------------------------- //
GameTypes::GameTypes()
: m_Initialized( false ),
m_pExtendedServerInfo( NULL ),
m_pServerMap( NULL ),
m_pServerMapGroup( NULL ),
m_iCurrentServerNumSlots( 0 ),
m_bRunMapWithDefaultGametype( false ),
m_bLoadingScreenDataIsCorrect( true )
{
m_randomStream.SetSeed( (int)Plat_MSTime() );
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Destructor
// -------------------------------------------------------------------------------------------- //
GameTypes::~GameTypes()
{
m_GameTypes.PurgeAndDeleteElements();
m_Maps.PurgeAndDeleteElements();
m_MapGroups.PurgeAndDeleteElements();
m_CustomBotDifficulties.PurgeAndDeleteElements();
if ( m_pExtendedServerInfo )
m_pExtendedServerInfo->deleteThis();
m_pExtendedServerInfo = NULL;
ClearServerMapGroupInfo();
}
void GameTypes::ClearServerMapGroupInfo( void )
{
if ( m_pServerMap )
delete m_pServerMap;
m_pServerMap = NULL;
if ( m_pServerMapGroup )
delete m_pServerMapGroup;
m_pServerMapGroup = NULL;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Loads the contents of GameModes.txt
// -------------------------------------------------------------------------------------------- //
bool GameTypes::Initialize( bool force /* = false*/ )
{
const char *fileName = "GameModes.txt";
if ( m_Initialized &&
!force )
{
return true;
}
m_GameTypes.PurgeAndDeleteElements();
m_Maps.PurgeAndDeleteElements();
m_CustomBotDifficulties.PurgeAndDeleteElements();
ClearServerMapGroupInfo();
KeyValues *pKV = new KeyValues( "" );
KeyValues::AutoDelete autodelete( pKV );
DevMsg( "GameTypes: initializing game types interface from %s.\n", fileName );
// Load the key values from the disc.
if ( !pKV->LoadFromFile( g_pFullFileSystem, fileName ) )
{
Warning( "GameTypes: error loading %s.", fileName );
return false;
}
// pKV->SaveToFile( g_pFullFileSystem, "maps/gamemodes-pre.txt", "GAME" );
// Load key values from any DLC on disc.
DLCHelper::AppendDLCKeyValues( pKV, fileName );
// Merge map sidecar files ( map.kv )
// Map sidecar loading has been moved to CCSGameRules::InitializeGameTypeAndMode
// to eliminate large workshop subscription load times
// InitMapSidecars( pKV );
// Lastly, merge key values from gamemodes_server.txt or from the file specified on the
// command line.
const char *svfileName;
svfileName = CommandLine()->ParmValue( "-gamemodes_serverfile" );
if ( !svfileName )
svfileName = "gamemodes_server.txt";
DevMsg( "GameTypes: merging game types interface from %s.\n", svfileName );
KeyValues *pKV_sv = new KeyValues( "" );
if ( pKV_sv->LoadFromFile( g_pFullFileSystem, svfileName ) )
{
// Merge the section that exec's configs in a special way
for ( KeyValues *psvGameType = pKV_sv->FindKey( "gametypes" )->GetFirstTrueSubKey();
psvGameType; psvGameType = psvGameType->GetNextTrueSubKey() )
{
for ( KeyValues *psvGameMode = psvGameType->FindKey( "gamemodes" )->GetFirstTrueSubKey();
psvGameMode; psvGameMode = psvGameMode->GetNextTrueSubKey() )
{
if ( KeyValues *psvExec = psvGameMode->FindKey( "exec" ) )
{
// We have an override for gametype-mode-exec
if ( KeyValues *pOurExec = pKV->FindKey( CFmtStr( "gametypes/%s/gamemodes/%s/exec", psvGameType->GetName(), psvGameMode->GetName() ) ) )
{
for ( KeyValues *psvConfigEntry = psvExec->GetFirstValue();
psvConfigEntry; psvConfigEntry = psvConfigEntry->GetNextValue() )
{
pOurExec->AddSubKey( psvConfigEntry->MakeCopy() );
}
psvGameMode->RemoveSubKey( psvExec );
psvExec->deleteThis();
}
}
}
}
// for modes that have weapon progressions remove pre-existing weapon progressions if the server file has them
for ( KeyValues *psvGameType = pKV_sv->FindKey( "gametypes" )->GetFirstTrueSubKey();
psvGameType; psvGameType = psvGameType->GetNextTrueSubKey() )
{
for ( KeyValues *psvGameMode = psvGameType->FindKey( "gamemodes" )->GetFirstTrueSubKey();
psvGameMode; psvGameMode = psvGameMode->GetNextTrueSubKey() )
{
if ( KeyValues *psvProgressionCT = psvGameMode->FindKey( "weaponprogression_ct" ) )
{
// We have an override for gametype-mode-weaponprogression_ct
if ( KeyValues *pOurProgressionCT = pKV->FindKey( CFmtStr( "gametypes/%s/gamemodes/%s/weaponprogression_ct", psvGameType->GetName(), psvGameMode->GetName() ) ) )
{
// remove the pre-existing progression
pOurProgressionCT->Clear();
}
}
if ( KeyValues *psvProgressionT = psvGameMode->FindKey( "weaponprogression_t" ) )
{
// We have an override for gametype-mode-weaponprogression_ct
if ( KeyValues *pOurProgressionT = pKV->FindKey( CFmtStr( "gametypes/%s/gamemodes/%s/weaponprogression_t", psvGameType->GetName(), psvGameMode->GetName() ) ) )
{
// remove the pre-existing progression
pOurProgressionT->Clear();
}
}
}
}
pKV->MergeFrom( pKV_sv, KeyValues::MERGE_KV_UPDATE );
}
else
{
DevMsg( "Failed to load %s\n", svfileName );
}
if ( pKV_sv )
{
pKV_sv->deleteThis();
pKV_sv = NULL;
}
// Load the game types.
if ( !LoadGameTypes( pKV ) )
{
return false;
}
// Load the maps.
if ( !LoadMaps( pKV ) )
{
return false;
}
// Load the map groups.
if ( !LoadMapGroups( pKV ) )
{
return false;
}
// Load the bot difficulty levels for Offline games.
if ( !LoadCustomBotDifficulties( pKV ) )
{
return false;
}
m_Initialized = true;
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////
// Purpose: load and merge key values from loose map sidecar files ( "de_dust_joeblow.kv" )
void GameTypes::InitMapSidecars( KeyValues* pKV )
{
KeyValues *pKVMaps = pKV->FindKey( "maps" );
char mapwild[MAX_PATH];
Q_snprintf( mapwild, sizeof( mapwild ), "*.%sbsp", IsX360() ? "360." : "" );
CUtlVector<CUtlString> outList;
// BEGIN Search the maps dir for .kv files that correspond to bsps.
RecursiveFindFilesMatchingName( &outList, "maps", mapwild, "GAME" );
FOR_EACH_VEC( outList, i )
{
const char* curMap = outList[i].Access();
AddMapKVs( pKVMaps, curMap );
}
// END Search
}
////////////////////////////////////////////////////////////////////////////////////////////
// Purpose: shove a map KV data into the main gamemodes data
void GameTypes::AddMapKVs( KeyValues* pKVMaps, const char* curMap )
{
char filename[ MAX_PATH ];
char kvFilename[ MAX_PATH ];
KeyValues *pKVMap;
V_StripExtension( curMap, filename, MAX_PATH );
V_FixSlashes( filename, '/' );
V_snprintf( kvFilename, sizeof( kvFilename ), "%s.kv", filename );
if ( !g_pFullFileSystem->FileExists( kvFilename ) )
{
if ( !StringHasPrefix( filename, "maps/workshop/" ) )
return;
char *pchNameBase = strrchr( filename, '/' );
if ( !pchNameBase )
return;
// For workshop maps attempt sidecars by bare non-ID name too
V_snprintf( kvFilename, sizeof( kvFilename ), "maps/%s.kv", pchNameBase + 1 );
}
if ( !g_pFullFileSystem->FileExists( kvFilename ) )
return;
//
// Load the Map sidecar entry
//
const char* szMapNameBase = filename;
// Strip off the "maps/" to find the correct entry.
if ( !Q_strnicmp( szMapNameBase, "maps/", 5 ) )
{
szMapNameBase += 5;
}
// Delete the existing map subkey if it exists. A map sidecar file stomps existing data for that map.
KeyValues *pKVOld = pKVMaps->FindKey( szMapNameBase );
if ( pKVOld )
{
// Keep the one defined in gamemodes.txt
return;
//
// Msg( "GameTypes: Replacing existing entry for %s.\n", kvFilename );
//
// pKVMaps->RemoveSubKey( pKVOld );
//
// pKV->SaveToFile( g_pFullFileSystem, "maps/map_removed.txt", "GAME" );
}
else
{
DevMsg( "GameTypes: Creating new entry for %s.\n", kvFilename );
}
pKVMap = pKVMaps->CreateNewKey();
if ( pKVMap->LoadFromFile( g_pFullFileSystem, kvFilename ) )
{
// pKV->SaveToFile( g_pFullFileSystem, "maps/map_added.txt", "GAME" );
}
else
{
Warning( "Failed to load %s\n", kvFilename );
}
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Parse the given key values for the weapon progressions
// -------------------------------------------------------------------------------------------- //
void GameTypes::LoadWeaponProgression( KeyValues * pKV_WeaponProgression, CUtlVector< WeaponProgression > & vecWeaponProgression, const char * szGameType, const char * szGameMode )
{
if ( pKV_WeaponProgression )
{
for ( KeyValues *pKV_Weapon = pKV_WeaponProgression->GetFirstTrueSubKey(); pKV_Weapon; pKV_Weapon = pKV_Weapon->GetNextTrueSubKey() )
{
// Get the weapon name.
WeaponProgression wp;
wp.m_Name.Set( pKV_Weapon->GetName() );
// Get the kills.
const char *killsEntry = "kills";
wp.m_Kills = pKV_Weapon->GetInt( killsEntry, g_invalidInteger );
if ( wp.m_Kills == g_invalidInteger )
{
wp.m_Kills = 0;
Warning( "GameTypes: missing %s entry for weapon \"%s\" for game type/mode (%s/%s).\n", killsEntry, pKV_Weapon->GetName(), szGameType, szGameMode );
}
vecWeaponProgression.AddToTail( wp );
}
if ( vecWeaponProgression.Count() == 0 )
{
Warning( "GameTypes: empty %s entry for game type/mode (%s/%s).\n", pKV_WeaponProgression->GetName(), szGameType, szGameMode );
}
}
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Finds the index at which the named weapon resides in the progression index.
// -------------------------------------------------------------------------------------------- //
int GameTypes::FindWeaponProgressionIndex( CUtlVector< WeaponProgression > & vecWeaponProgression, const char * szWeaponName )
{
FOR_EACH_VEC( vecWeaponProgression, tWeapon )
{
if ( !V_strcmp( vecWeaponProgression[tWeapon].m_Name, szWeaponName ) )
{
return tWeapon;
}
}
return -1;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Parse the given key values for the game types and modes.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::LoadGameTypes( KeyValues *pKV )
{
Assert( pKV );
if ( !pKV )
{
return false;
}
Assert( m_GameTypes.Count() == 0 );
if ( m_GameTypes.Count() > 0 )
{
m_GameTypes.PurgeAndDeleteElements();
}
// Get the game types.
const char *gameTypesEntry = "gameTypes";
KeyValues *pKV_GameTypes = pKV->FindKey( gameTypesEntry );
if ( !pKV_GameTypes )
{
Warning( "GameTypes: could not find entry %s.\n", gameTypesEntry );
return false;
}
// Parse the game types.
for ( KeyValues *pKV_GameType = pKV_GameTypes->GetFirstTrueSubKey(); pKV_GameType; pKV_GameType = pKV_GameType->GetNextTrueSubKey() )
{
GameType *pGameType = new GameType();
// Set the name.
V_strncpy( pGameType->m_Name, pKV_GameType->GetName(), sizeof( pGameType->m_Name ) );
// Set the name ID.
const char *nameIDEntry = "nameID";
const char *pTypeNameID = pKV_GameType->GetString( nameIDEntry );
if ( pTypeNameID )
{
V_strncpy( pGameType->m_NameID, pTypeNameID, sizeof( pGameType->m_NameID ) );
}
else
{
Warning( "GameTypes: missing %s entry for game type %s.\n", nameIDEntry, pKV_GameType->GetName() );
}
// Get the modes.
const char *gameModesEntry = "gameModes";
KeyValues *pKV_GameModes = pKV_GameType->FindKey( gameModesEntry );
if ( pKV_GameModes )
{
for ( KeyValues *pKV_GameMode = pKV_GameModes->GetFirstTrueSubKey(); pKV_GameMode; pKV_GameMode = pKV_GameMode->GetNextTrueSubKey() )
{
GameMode *pGameMode = new GameMode();
// Set the name.
V_strncpy( pGameMode->m_Name, pKV_GameMode->GetName(), sizeof( pGameMode->m_Name ) );
// Set the name ID.
const char *pModeNameID = pKV_GameMode->GetString( nameIDEntry );
if ( pModeNameID && *pModeNameID != 0 )
{
V_strncpy( pGameMode->m_NameID, pModeNameID, sizeof( pGameMode->m_NameID ) );
}
else
{
Warning( "GameTypes: missing %s entry for game type/mode (%s/%s).\n", nameIDEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() );
}
// Set the SP name ID.
const char *nameIDEntrySP = "nameID_SP";
const char *pModeNameID_SP = pKV_GameType->GetString( nameIDEntrySP );
if ( pModeNameID_SP && *pModeNameID_SP != 0 )
{
V_strncpy( pGameMode->m_NameID_SP, pModeNameID_SP, sizeof( pGameMode->m_NameID_SP ) );
}
else
{
if ( pModeNameID && *pModeNameID != 0 )
{
V_strncpy( pGameMode->m_NameID_SP, pModeNameID, sizeof( pGameMode->m_NameID_SP ) );
}
}
// Set the description ID.
const char *descIDEntry = "descID";
const char *pDescID = pKV_GameMode->GetString( descIDEntry );
if ( pDescID && *pDescID != 0 )
{
V_strncpy( pGameMode->m_DescID, pDescID, sizeof( pGameMode->m_DescID ) );
}
else
{
Warning( "GameTypes: missing %s entry for game type/mode (%s/%s).\n", descIDEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() );
}
// Set the SP name ID.
const char *descIDEntrySP = "descID_SP";
const char *pDescID_SP = pKV_GameMode->GetString( descIDEntrySP );
if ( pDescID_SP && *pDescID_SP != 0 )
{
V_strncpy( pGameMode->m_DescID_SP, pDescID_SP, sizeof( pGameMode->m_DescID_SP ) );
}
else
{
if ( pDescID && *pDescID != 0 )
{
V_strncpy( pGameMode->m_DescID_SP, pDescID, sizeof( pGameMode->m_DescID_SP ) );
}
}
// check for the command line override first. Otherwise use gamemodes.txt values.
int maxplayers_override = CommandLine()->ParmValue( "-maxplayers_override", -1 );
if ( maxplayers_override >= 1 )
{
pGameMode->m_MaxPlayers = maxplayers_override;
}
else
{
// Set the maxplayers for the type/mode.
const char* maxplayersEntry = "maxplayers";
int maxplayers = pKV_GameMode->GetInt( maxplayersEntry );
if ( maxplayers && maxplayers >= 1 )
{
pGameMode->m_MaxPlayers = maxplayers;
}
else
{
Warning( "GameTypes: missing, < 1, or invalid %s entry for game type/mode (%s/%s).\n", maxplayersEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() );
pGameMode->m_MaxPlayers = 1;
}
}
// Get the single player convars.
const char *configsEntry = "exec";
KeyValues *pKVExecConfig = pKV_GameMode->FindKey( configsEntry );
if ( pKVExecConfig )
{
pGameMode->m_pExecConfings = pKVExecConfig->MakeCopy();
}
else
{
Warning( "GameTypes: missing entry %s for game type/mode (%s/%s).\n", configsEntry, pKV_GameType->GetName(), pKV_GameMode->GetName() );
}
// Get the single player mapgroups.
const char *mapgroupsEntrySP = "mapgroupsSP";
KeyValues *pKV_MapGroupsSP = pKV_GameMode->FindKey( mapgroupsEntrySP );
if ( pKV_MapGroupsSP )
{
for ( KeyValues *pKV_MapGroup = pKV_MapGroupsSP->GetFirstValue(); pKV_MapGroup; pKV_MapGroup = pKV_MapGroup->GetNextValue() )
{
// Ignore the "random" entry.
if ( V_stricmp( pKV_MapGroup->GetName(), "random" ) == 0 )
{
continue;
}
pGameMode->m_MapGroupsSP.CopyAndAddToTail( pKV_MapGroup->GetName() );
}
if ( pGameMode->m_MapGroupsSP.Count() == 0 )
{
Warning( "GameTypes: empty %s entry for game type/mode (%s/%s).\n", mapgroupsEntrySP, pKV_GameType->GetName(), pKV_GameMode->GetName() );
}
}
else
{
Warning( "GameTypes: missing %s entry for game type/mode (%s/%s).\n", mapgroupsEntrySP, pKV_GameType->GetName(), pKV_GameMode->GetName() );
}
// Get the multiplayer mapgroups.
const char *mapgroupsEntryMP = "mapgroupsMP";
KeyValues *pKV_MapGroupsMP = pKV_GameMode->FindKey( mapgroupsEntryMP );
if ( pKV_MapGroupsMP )
{
for ( KeyValues *pKV_MapGroup = pKV_MapGroupsMP->GetFirstValue(); pKV_MapGroup; pKV_MapGroup = pKV_MapGroup->GetNextValue() )
{
// Ignore the "random" entry.
if ( V_stricmp( pKV_MapGroup->GetName(), "random" ) == 0 )
{
continue;
}
pGameMode->m_MapGroupsMP.CopyAndAddToTail( pKV_MapGroup->GetName() );
}
}
// Get the CT weapon progression (optional).
KeyValues * pKV_WeaponProgressionCT = pKV_GameMode->FindKey( "weaponprogression_ct" );
LoadWeaponProgression( pKV_WeaponProgressionCT, pGameMode->m_WeaponProgressionCT, pKV_GameType->GetName(), pKV_GameMode->GetName() );
KeyValues * pKV_WeaponProgressionT = pKV_GameMode->FindKey( "weaponprogression_t" );
LoadWeaponProgression( pKV_WeaponProgressionT, pGameMode->m_WeaponProgressionT, pKV_GameType->GetName(), pKV_GameMode->GetName() );
KeyValues * pKV_noResetVoteThresholdT = pKV_GameMode->FindKey( "no_reset_vote_threshold_t" );
if ( pKV_noResetVoteThresholdT )
{
pGameMode->m_NoResetVoteThresholdT = FindWeaponProgressionIndex( pGameMode->m_WeaponProgressionT, pKV_noResetVoteThresholdT->GetString() );
}
KeyValues * pKV_noResetVoteThresholdCT = pKV_GameMode->FindKey( "no_reset_vote_threshold_ct" );
if ( pKV_noResetVoteThresholdCT )
{
pGameMode->m_NoResetVoteThresholdCT = FindWeaponProgressionIndex( pGameMode->m_WeaponProgressionCT, pKV_noResetVoteThresholdCT->GetString() );
}
pGameMode->m_Index = pGameType->m_GameModes.Count();
pGameType->m_GameModes.AddToTail( pGameMode );
}
}
else
{
Warning( "GameTypes: missing %s entry for game type %s.\n", gameModesEntry, pKV_GameType->GetName() );
}
if ( pGameType->m_GameModes.Count() == 0 )
{
Warning( "GameTypes: empty %s entry for game type %s.\n", gameModesEntry, pKV_GameType->GetName() );
}
pGameType->m_Index = m_GameTypes.Count();
m_GameTypes.AddToTail( pGameType );
}
if ( m_GameTypes.Count() == 0 )
{
Warning( "GameTypes: empty %s entry.\n", gameTypesEntry );
}
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Parse the given key values for the maps.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::LoadMaps( KeyValues *pKV )
{
Assert( pKV );
if ( !pKV )
{
return false;
}
Assert( m_Maps.Count() == 0 );
if ( m_Maps.Count() > 0 )
{
m_Maps.PurgeAndDeleteElements();
}
// Get the maps.
const char *mapsEntry = "maps";
KeyValues *pKV_Maps = pKV->FindKey( mapsEntry );
if ( !pKV_Maps )
{
Warning( "GameTypes: could not find entry %s.\n", mapsEntry );
return false;
}
// Parse the maps.
for ( KeyValues *pKV_Map = pKV_Maps->GetFirstTrueSubKey(); pKV_Map; pKV_Map = pKV_Map->GetNextTrueSubKey() )
{
LoadMapEntry( pKV_Map );
}
if ( m_Maps.Count() == 0 )
{
Warning( "GamesTypes: empty %s entry.\n", mapsEntry );
}
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Loads a single map entry.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::LoadMapEntry( KeyValues *pKV_Map )
{
Assert( pKV_Map );
if ( !pKV_Map )
{
return false;
}
Map *pMap = new Map();
// Set the name.
V_strcpy_safe( pMap->m_Name, pKV_Map->GetName() );
// Set the name ID.
const char *nameIDEntry = "nameID";
const char *pNameID = pKV_Map->GetString( nameIDEntry );
if ( pNameID )
{
V_strncpy( pMap->m_NameID, pNameID, sizeof( pMap->m_NameID ) );
}
else
{
Warning( "GameTypes: missing %s entry for map %s.\n", nameIDEntry, pKV_Map->GetName() );
}
// Set the image name.
const char *imageNameEntry = "imagename";
const char *pImageName = pKV_Map->GetString( imageNameEntry );
if ( pImageName )
{
V_strncpy( pMap->m_ImageName, pImageName, sizeof( pMap->m_ImageName ) );
}
else
{
Warning( "GameTypes: missing %s entry for map %s.\n", imageNameEntry, pKV_Map->GetName() );
}
// Set the economy item requirements
if ( const char *pszRequiresItem = pKV_Map->GetString( "requires_attr", NULL ) )
{
V_strcpy_safe( pMap->m_RequiresAttr, pszRequiresItem );
}
pMap->m_RequiresAttrValue = pKV_Map->GetInt( "requires_attr_value", -1 );
if ( const char *pszRequiresItemAttr = pKV_Map->GetString( "requires_attr_reward", NULL ) )
{
V_strcpy_safe( pMap->m_RequiresAttrReward, pszRequiresItemAttr );
}
pMap->m_nRewardDropList = pKV_Map->GetInt( "reward_drop_list", -1 );
// Set the rich presence (optional).
pMap->m_RichPresence = static_cast<uint32>( pKV_Map->GetInt( "richpresencecontext", g_richPresenceDefault ) );
// Get the list of terrorist models.
const char *tModelsEntry = "t_models";
KeyValues *pKV_TModels = pKV_Map->FindKey( tModelsEntry );
if ( pKV_TModels )
{
for ( KeyValues *pKV_Model = pKV_TModels->GetFirstValue(); pKV_Model; pKV_Model = pKV_Model->GetNextValue() )
{
pMap->m_TModels.CopyAndAddToTail( pKV_Model->GetName() );
}
}
else
{
Warning( "GameTypes: missing %s entry for map %s.\n", tModelsEntry, pKV_Map->GetName() );
}
// Get the list of counter-terrorist models.
const char *ctModelsEntry = "ct_models";
KeyValues *pKV_CTModels = pKV_Map->FindKey( ctModelsEntry );
if ( pKV_CTModels )
{
for ( KeyValues *pKV_Model = pKV_CTModels->GetFirstValue(); pKV_Model; pKV_Model = pKV_Model->GetNextValue() )
{
pMap->m_CTModels.CopyAndAddToTail( pKV_Model->GetName() );
}
}
else
{
Warning( "GameTypes: missing %s entry for map %s.\n", ctModelsEntry, pKV_Map->GetName() );
}
// Get names for the view model arms
pMap->m_TViewModelArms.Set( pKV_Map->GetString( "t_arms" ) );
pMap->m_CTViewModelArms.Set( pKV_Map->GetString( "ct_arms" ) );
pMap->m_nDefaultGameType = pKV_Map->GetInt( "default_game_type" );
pMap->m_nDefaultGameMode = pKV_Map->GetInt( "default_game_mode", 0 );
// Get the list of hostage models if there is one.
const char *hostageModelsEntry = "hostage_models";
KeyValues *pKV_HostageModels = pKV_Map->FindKey( hostageModelsEntry );
if ( pKV_HostageModels )
{
for ( KeyValues *pKV_Model = pKV_HostageModels->GetFirstValue(); pKV_Model; pKV_Model = pKV_Model->GetNextValue() )
{
pMap->m_HostageModels.CopyAndAddToTail( pKV_Model->GetName() );
}
}
// Add the map to the list.
pMap->m_Index = m_Maps.Count();
m_Maps.AddToTail( pMap );
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Parse the given key values for the mapgroups.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::LoadMapGroups( KeyValues *pKV )
{
Assert( pKV );
if ( !pKV )
{
return false;
}
//Assert( m_MapGroups.Count() == 0 );
if ( m_MapGroups.Count() > 0 )
{
//m_MapGroups.PurgeAndDeleteElements();
FOR_EACH_VEC_BACK( m_MapGroups, i )
{
if ( !m_MapGroups[i]->m_bIsWorkshopMapGroup )
{
delete m_MapGroups[i];
m_MapGroups.Remove( i );
}
}
}
// Get the mapgroups.
const char *mapGroupsEntry = "mapGroups";
KeyValues *pKV_MapGroups = pKV->FindKey( mapGroupsEntry );
if ( !pKV_MapGroups )
{
Warning( "GameTypes: could not find entry %s.\n", mapGroupsEntry );
return false;
}
// Parse the mapgroups.
for ( KeyValues *pKV_MapGroup = pKV_MapGroups->GetFirstTrueSubKey(); pKV_MapGroup; pKV_MapGroup = pKV_MapGroup->GetNextTrueSubKey() )
{
MapGroup *pMapGroup = new MapGroup();
// Set the name.
V_strncpy( pMapGroup->m_Name, pKV_MapGroup->GetName(), sizeof( pMapGroup->m_Name ) );
// Set the name ID.
const char *nameIDEntry = "nameID";
const char *pNameID = pKV_MapGroup->GetString( nameIDEntry );
if ( pNameID )
{
V_strncpy( pMapGroup->m_NameID, pNameID, sizeof( pMapGroup->m_NameID ) );
}
else
{
Warning( "GameTypes: missing %s entry for map group %s.\n", nameIDEntry, pKV_MapGroup->GetName() );
}
// Set the image name.
const char *imageNameEntry = "imagename";
const char *pImageName = pKV_MapGroup->GetString( imageNameEntry );
if ( pImageName )
{
V_strncpy( pMapGroup->m_ImageName, pImageName, sizeof( pMapGroup->m_ImageName ) );
}
else
{
Warning( "GameTypes: missing %s entry for map group %s.\n", imageNameEntry, pKV_MapGroup->GetName() );
}
// Get the maps.
const char *mapsEntry = "maps";
KeyValues *pKV_Maps = pKV_MapGroup->FindKey( mapsEntry );
if ( pKV_Maps )
{
for ( KeyValues *pKV_Map = pKV_Maps->GetFirstValue(); pKV_Map; pKV_Map = pKV_Map->GetNextValue() )
{
pMapGroup->m_Maps.CopyAndAddToTail( pKV_Map->GetName() );
}
}
else
{
Warning( "GameTypes: missing %s entry for map group %s.\n", mapsEntry, pKV_MapGroup->GetName() );
}
// Add the map group to the list.
m_MapGroups.AddToTail( pMapGroup );
}
if ( m_MapGroups.Count() == 0 )
{
Warning( "GamesTypes: empty %s entry.\n", mapGroupsEntry );
}
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Parse the given key values for the bot difficulties.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::LoadCustomBotDifficulties( KeyValues *pKV )
{
Assert( pKV );
if ( !pKV )
{
return false;
}
Assert( m_CustomBotDifficulties.Count() == 0 );
if ( m_CustomBotDifficulties.Count() > 0 )
{
m_CustomBotDifficulties.PurgeAndDeleteElements();
}
// Get the bot difficulty levels.
const char *botDifficultyEntry = "botDifficulty";
KeyValues *pKV_BotDiffs = pKV->FindKey( botDifficultyEntry );
if ( !pKV_BotDiffs )
{
Warning( "GameTypes: could not find entry %s.\n", botDifficultyEntry );
return false;
}
// Parse the bot difficulty levels.
for ( KeyValues *pKV_BotDiff = pKV_BotDiffs->GetFirstTrueSubKey(); pKV_BotDiff; pKV_BotDiff = pKV_BotDiff->GetNextTrueSubKey() )
{
CustomBotDifficulty *pBotDiff = new CustomBotDifficulty();
// Set the name.
V_strncpy( pBotDiff->m_Name, pKV_BotDiff->GetName(), sizeof( pBotDiff->m_Name ) );
// Set the name ID.
const char *nameIDEntry = "nameID";
const char *pNameID = pKV_BotDiff->GetString( nameIDEntry );
if ( pNameID )
{
V_strncpy( pBotDiff->m_NameID, pNameID, sizeof( pBotDiff->m_NameID ) );
}
else
{
Warning( "GameTypes: missing %s entry for bot difficulty %s.\n", nameIDEntry, pKV_BotDiff->GetName() );
}
// Get the convars.
const char *convarsEntry = "convars";
KeyValues *pKV_Convars = pKV_BotDiff->FindKey( convarsEntry );
if ( pKV_Convars )
{
pBotDiff->m_pConvars = pKV_Convars->MakeCopy();
}
else
{
Warning( "GameTypes: missing entry %s for bot difficulty %s.\n", convarsEntry, pKV_BotDiff->GetName() );
}
// Check to see if this difficulty level has a bot quota convar.
if ( pKV_Convars )
{
pBotDiff->m_HasBotQuota = ( pKV_Convars->GetInt( "bot_quota", g_invalidInteger ) != g_invalidInteger );
}
pBotDiff->m_Index = m_CustomBotDifficulties.Count();
m_CustomBotDifficulties.AddToTail( pBotDiff );
}
if ( m_CustomBotDifficulties.Count() == 0 )
{
Warning( "GamesTypes: empty %s entry.\n", botDifficultyEntry );
}
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the game type matching the given name.
// -------------------------------------------------------------------------------------------- //
GameTypes::GameType *GameTypes::GetGameType_Internal( const char *gameType )
{
Assert( gameType );
if ( gameType &&
gameType[0] != '\0' )
{
// Find the game type.
FOR_EACH_VEC( m_GameTypes, iType )
{
GameType *pGameType = m_GameTypes[iType];
Assert( pGameType );
if ( pGameType &&
V_stricmp( pGameType->m_Name, gameType ) == 0 )
{
// Found it.
return pGameType;
}
}
}
// Not found.
Warning( "GameTypes: could not find matching game type \"%s\".\n", gameType );
return NULL;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the game mode matching the given name.
// -------------------------------------------------------------------------------------------- //
GameTypes::GameMode *GameTypes::GetGameMode_Internal( GameType *pGameType, const char *gameMode )
{
Assert( pGameType && gameMode );
if ( pGameType &&
gameMode &&
gameMode[0] != '\0' )
{
// Find the game mode.
FOR_EACH_VEC( pGameType->m_GameModes, iMode )
{
GameMode *pGameMode = pGameType->m_GameModes[iMode];
Assert( pGameMode );
if ( pGameMode &&
V_stricmp( pGameMode->m_Name, gameMode ) == 0 )
{
// Found it.
return pGameMode;
}
}
}
// Not found.
Warning( "GameTypes: could not find matching game mode \"%s\" for type \"%s\".\n",
gameMode, ( pGameType ? pGameType->m_Name : "null" ) );
return NULL;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the current game type matching the game_type convar.
// -------------------------------------------------------------------------------------------- //
GameTypes::GameType *GameTypes::GetCurrentGameType_Internal( void )
{
if ( m_GameTypes.Count() == 0 )
{
Warning( "GamesTypes: no game types have been loaded.\n" );
return NULL;
}
int gameType = game_type.GetInt();
if ( gameType < 0 || gameType >= m_GameTypes.Count() )
{
Warning( "GamesTypes: game_type is set to an invalid value (%d). Range [%d,%d].\n", gameType, 0, m_GameTypes.Count() - 1 );
return NULL;
}
return m_GameTypes[gameType];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the current game mode matching the game_mode convar.
// -------------------------------------------------------------------------------------------- //
GameTypes::GameMode *GameTypes::GetCurrentGameMode_Internal( GameType *pGameType )
{
Assert( pGameType );
if ( !pGameType )
{
return NULL;
}
int gameMode = game_mode.GetInt();
if ( gameMode < 0 || gameMode >= pGameType->m_GameModes.Count() )
{
Warning( "GamesTypes: game_mode is set to an invalid value (%d). Range [%d,%d].\n", gameMode, 0, pGameType->m_GameModes.Count() - 1 );
return NULL;
}
return pGameType->m_GameModes[gameMode];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the MapGroup from the mapgroup name
// -------------------------------------------------------------------------------------------- //
GameTypes::MapGroup *GameTypes::GetMapGroup_Internal( const char *mapGroup )
{
Assert( mapGroup );
if ( mapGroup &&
mapGroup[0] != '\0' )
{
#if defined ( MATCHMAKING_DLL )
// On the client and connected to a server, check the networked server values
if ( g_pMatchExtensions->GetIVEngineClient() && g_pMatchExtensions->GetIVEngineClient()->IsConnected() )
{
if ( m_pServerMapGroup && V_stricmp( m_pServerMapGroup->m_Name, mapGroup ) == 0 )
{
return m_pServerMapGroup;
}
}
#endif
// Find the game type in our local list
char const *pchMapGroupToFind = mapGroup;
if ( char const *pchComma = strchr( mapGroup, ',' ) )
{
// Use only the first mapgroup from the list for search
char *pchCopy = ( char * ) stackalloc( pchComma - mapGroup + 1 );
Q_strncpy( pchCopy, mapGroup, pchComma - mapGroup + 1 );
pchCopy[ pchComma - mapGroup ] = 0;
pchMapGroupToFind = pchCopy;
}
FOR_EACH_VEC( m_MapGroups, iMapGroup )
{
MapGroup *pMapGroup = m_MapGroups[iMapGroup];
Assert( pMapGroup );
if ( pMapGroup &&
V_stricmp( pMapGroup->m_Name, pchMapGroupToFind ) == 0 )
{
// Found it.
return pMapGroup;
}
}
// Not found in pre-built array, fake one for workshop
if ( char const *pszWorkshopMapgroup = strstr( pchMapGroupToFind, "@workshop" ) )
{
char const *pszMapId = pszWorkshopMapgroup + 9;
if ( *pszMapId ) ++ pszMapId;
CFmtStr fmtGroupName( "%llu", Q_atoui64( pszMapId ) );
char const *szIndividualMapName = pszWorkshopMapgroup + 1;
CUtlStringList lstMapNames;
lstMapNames.CopyAndAddToTail( szIndividualMapName );
return CreateWorkshopMapGroupInternal( fmtGroupName, lstMapNames );
}
// Not found.
//Warning( "GameTypes: could not find matching mapGroup \"%s\".\n", mapGroup );
}
return NULL;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the map matching the given name.
// -------------------------------------------------------------------------------------------- //
GameTypes::Map *GameTypes::GetMap_Internal( const char *mapName )
{
if ( m_Maps.Count() == 0 )
{
Warning( "GamesTypes: no maps have been loaded.\n" );
return NULL;
}
Assert( mapName );
if ( !mapName ||
mapName[0] == '\0' )
{
Warning( "GamesTypes: invalid map name.\n" );
return NULL;
}
char mapNameNoExt[ MAX_MAP_NAME ];
//V_strcpy_safe( mapNameNoExt, mapName );
V_FileBase( mapName, mapNameNoExt, sizeof( mapNameNoExt ) );
const int extLen = 4;
// Remove the .360 extension from the map name.
char *pExt = mapNameNoExt + V_strlen( mapNameNoExt ) - extLen;
if ( pExt >= mapNameNoExt &&
V_strnicmp( pExt, ".360", extLen ) == 0 )
{
*pExt = '\0';
}
// Remove the .bsp extension from the map name.
pExt = mapNameNoExt + V_strlen( mapNameNoExt ) - extLen;
if ( pExt >= mapNameNoExt &&
V_strnicmp( pExt , ".bsp", extLen ) == 0 )
{
*pExt = '\0';
}
#if defined ( MATCHMAKING_DLL )
// On the client and connected to a server, check the networked server values
if ( m_pServerMap && g_pMatchExtensions->GetIVEngineClient() && g_pMatchExtensions->GetIVEngineClient()->IsConnected() )
{
if( !V_stricmp( m_pServerMap->m_Name, mapNameNoExt ) || !V_stricmp( m_pServerMap->m_Name, mapName ) )
{
return m_pServerMap;
}
}
#endif
// Find the map.
FOR_EACH_VEC( m_Maps, iMap )
{
Map *pMap = m_Maps[iMap];
Assert( pMap );
if ( pMap &&
V_stricmp( pMap->m_Name, mapNameNoExt ) == 0 )
{
// Found it.
return pMap;
}
}
// Not found.
// Squelching this-- community maps won't be found
// Warning( "GameTypes: could not find matching map \"%s\".\n", mapNameNoExt );
return NULL;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the current bot difficulty based on the custom_bot_difficulty convar.
// -------------------------------------------------------------------------------------------- //
GameTypes::CustomBotDifficulty *GameTypes::GetCurrentCustomBotDifficulty_Internal( void )
{
if ( m_CustomBotDifficulties.Count() == 0 )
{
Warning( "GamesTypes: no bot difficulties have been loaded.\n" );
return NULL;
}
int botDiff = custom_bot_difficulty.GetInt();
if ( botDiff < 0 || botDiff >= m_CustomBotDifficulties.Count() )
{
Warning( "GamesTypes: custom_bot_difficulty is set to an invalid value (%d). Range [%d,%d].\n", botDiff, 0, m_CustomBotDifficulties.Count() - 1 );
return NULL;
}
return m_CustomBotDifficulties[botDiff];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Set the game type and mode convars from the given strings.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::SetGameTypeAndMode( const char *gameType, const char *gameMode )
{
int iType = g_invalidInteger;
int iMode = g_invalidInteger;
if ( GetGameModeAndTypeIntsFromStrings( gameType, gameMode, iType, iMode ) )
{
// Set the game type.
return SetGameTypeAndMode( iType, iMode );
}
Warning( "GamesTypes: unable to set game type and mode. Could not find type/mode matching type:%s/mode:%s.\n", gameType, gameMode );
return false;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Set the game type and mode convars from passing and alias.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::GetGameTypeAndModeFromAlias( const char *modeAlias, int& iType, int& iMode )
{
iType = g_invalidInteger;
iMode = g_invalidInteger;
if ( Q_strcmp( "competitive", modeAlias ) == 0 || Q_strcmp( "comp", modeAlias ) == 0 )
{
iType = 0;
iMode = 1;
}
else if ( Q_strcmp( "casual", modeAlias ) == 0 )
{
iType = 0;
iMode = 0;
}
else if ( Q_strcmp( "armsrace", modeAlias ) == 0 || Q_strcmp( "arms", modeAlias ) == 0 || Q_strcmp( "gungame", modeAlias ) == 0 || Q_strcmp( "gg", modeAlias ) == 0 )
{
iType = 1;
iMode = 0;
}
else if ( Q_strcmp( "demolition", modeAlias ) == 0 || Q_strcmp( "demo", modeAlias ) == 0 )
{
iType = 1;
iMode = 1;
}
else if ( Q_strcmp( "deathmatch", modeAlias ) == 0 || Q_strcmp( "dm", modeAlias ) == 0 )
{
iType = 1;
iMode = 2;
}
else if ( Q_strcmp( "training", modeAlias ) == 0 )
{
iType = 2;
iMode = 0;
}
else if ( Q_strcmp( "custom", modeAlias ) == 0 )
{
iType = 3;
iMode = 0;
}
else if ( Q_strcmp( "guardian", modeAlias ) == 0 || Q_strcmp( "guard", modeAlias ) == 0 || Q_strcmp( "cooperative", modeAlias ) == 0 )
{
iType = 4;
iMode = 0;
}
else if ( Q_strcmp( "default", modeAlias ) == 0 || Q_strcmp( "auto", modeAlias ) == 0 )
{
SetRunMapWithDefaultGametype( true );
return false;
}
// return if we matched an alias
return ( iType != g_invalidInteger && iMode != g_invalidInteger );
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Set the game type and mode convars.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::SetGameTypeAndMode( int nGameType, int nGameMode )
{
// if we've launched the map through the menu, we are specifically saying that we should use these settings
// otherwise, use the game type/mode that the made defines as the default
if ( nGameType < CS_GameType_Min || nGameType > CS_GameType_Max )
{
Warning( "GamesTypes: unable to set game type and mode. Game type value is outside valid range. (value == %d)\n", nGameType );
return false;
}
// Set the game type.
DevMsg( "GameTypes: setting game type to %d.\n", nGameType );
game_type.SetValue( nGameType );
// Set the game mode.
DevMsg( "GameTypes: setting game mode to %d.\n", nGameMode );
game_mode.SetValue( nGameMode );
return true;
}
void GameTypes::SetAndParseExtendedServerInfo( KeyValues *pExtendedServerInfo )
{
if ( m_pExtendedServerInfo )
m_pExtendedServerInfo->deleteThis();
ClearServerMapGroupInfo();
m_pExtendedServerInfo = pExtendedServerInfo ? pExtendedServerInfo->MakeCopy() : NULL;
// BUGBUG: Not networking the complete state of a map/mapgroup struct so these have default values
// which may not match the server... Would like to avoid a ton of network traffic if it's not needed, so
// will only clean this up if needed.
if ( m_pExtendedServerInfo )
{
//const char* szMapNameBase = V_GetFileName( m_pServerMap->m_Name );
m_iCurrentServerNumSlots = m_pExtendedServerInfo->GetInt( "numSlots", 0 );
m_pServerMap = new Map;
V_strncpy( m_pServerMap->m_Name, m_pExtendedServerInfo->GetString( "map", "" ), ARRAYSIZE(m_pServerMap->m_Name) );
V_FixSlashes( m_pServerMap->m_Name, '/' );
m_pServerMap->m_TViewModelArms.Set( m_pExtendedServerInfo->GetString( "t_arms", "" ) );
m_pServerMap->m_CTViewModelArms.Set( m_pExtendedServerInfo->GetString( "ct_arms", "" ) );
m_pServerMap->m_nDefaultGameType = m_pExtendedServerInfo->GetInt( "default_game_type" );
m_pServerMap->m_nDefaultGameMode = m_pExtendedServerInfo->GetInt( "default_game_mode", 0 );
KeyValues *pCTModels = m_pExtendedServerInfo->FindKey( "ct_models", false );
if ( pCTModels )
{
for ( KeyValues *pKV = pCTModels->GetFirstValue(); pKV; pKV = pKV->GetNextValue() )
{
m_pServerMap->m_CTModels.CopyAndAddToTail( pKV->GetString() );
}
}
KeyValues *pTModels = m_pExtendedServerInfo->FindKey( "t_models", false );
if ( pTModels )
{
for ( KeyValues *pKV = pTModels->GetFirstValue(); pKV; pKV = pKV->GetNextValue() )
{
m_pServerMap->m_TModels.CopyAndAddToTail( pKV->GetString() );
}
}
if ( m_pExtendedServerInfo->GetBool( "official" ) && !m_pExtendedServerInfo->GetBool( "gotv" ) )
{
V_strcpy_safe( m_pServerMap->m_RequiresAttr, m_pExtendedServerInfo->GetString( "requires_attr" ) );
m_pServerMap->m_RequiresAttrValue = m_pExtendedServerInfo->GetInt( "requires_attr_value" );
V_strcpy_safe( m_pServerMap->m_RequiresAttrReward, m_pExtendedServerInfo->GetString( "requires_attr_reward" ) );
m_pServerMap->m_nRewardDropList = m_pExtendedServerInfo->GetInt( "reward_drop_list" );
}
m_pServerMapGroup = new MapGroup;
V_strncpy( m_pServerMapGroup->m_Name, m_pExtendedServerInfo->GetString( "mapgroup", "" ), ARRAYSIZE(m_pServerMapGroup->m_Name) );
KeyValues *pMapsInGroup = m_pExtendedServerInfo->FindKey( "maplist", false );
if ( pMapsInGroup )
{
for ( KeyValues *pKV = pMapsInGroup->GetFirstValue(); pKV; pKV = pKV->GetNextValue() )
{
m_pServerMapGroup->m_Maps.CopyAndAddToTail( pKV->GetString() );
}
}
#if defined( MATCHMAKING_DLL ) || defined( MATCHMAKING_DS_DLL )
if ( g_pMatchFramework && g_pMatchFramework->GetEventsSubscription() )
{
//char fileBase[MAX_MAP_NAME];
//V_FileBase( m_pServerMap->m_Name, fileBase, sizeof ( fileBase ) );
// Set game type and game mode convars appropriately:
if ( m_pExtendedServerInfo->FindKey( "c_game_type" ) && m_pExtendedServerInfo->FindKey( "c_game_mode" ) )
{
SetGameTypeAndMode( m_pExtendedServerInfo->GetInt( "c_game_type" ), m_pExtendedServerInfo->GetInt( "c_game_mode" ) );
}
g_pMatchFramework->GetEventsSubscription()->BroadcastEvent( new KeyValues(
"OnLevelLoadingSetDefaultGameModeAndType", "mapname", m_pServerMap->m_Name
) );
}
#endif
}
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the index of the current game type.
// -------------------------------------------------------------------------------------------- //
void GameTypes::CheckShouldSetDefaultGameModeAndType( const char* szMapNameFull )
{
// this is only called from CSGameRules()
int iType = 0;
int iMode = 0;
bool bShouldSet = false;
// check we don't have a launch option that defines what game type/mode we should be playing with
KeyValues *mode = NULL;
#if defined( CLIENT_DLL )
return;
#elif defined( GAME_DLL )
mode = engine->GetLaunchOptions();
#elif defined( MATCHMAKING_DLL )
if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) )
{
mode = pIVEngineServer->GetLaunchOptions();
}
#elif defined( MATCHMAKING_DS_DLL )
if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) )
{
mode = pIVEngineServer->GetLaunchOptions();
}
#endif
bool bCommandLineAlias = false;
if ( mode )
{
// start at the third value
KeyValues *kv = mode->GetFirstSubKey()->GetNextKey();
//KeyValuesDumpAsDevMsg( mode );
for ( KeyValues *arg = kv->GetNextKey(); arg != NULL; arg = arg->GetNextKey() )
{
// if "default" gets passed, we set should run with default to true inside this function and return false
if ( GetGameTypeAndModeFromAlias( arg->GetString(), iType, iMode ) )
{
// don't use the default map game mode
bCommandLineAlias = true;
bShouldSet = true;
}
}
}
const char* szMapNameBase = V_GetFileName( szMapNameFull );
if ( !bCommandLineAlias && GetRunMapWithDefaultGametype() )
{
// the default game type hasn't been loaded yet so load it now (pulling it straight from the bsp) if it exists
if ( GetDefaultGameTypeForMap( szMapNameFull ) == -1 )
{
//V_FixSlashes( szMapNameBase, '/' );
char kvFilename[ MAX_PATH ];
V_snprintf( kvFilename, sizeof( kvFilename ), "maps/%s.kv", szMapNameBase );
if ( g_pFullFileSystem->FileExists( kvFilename ) )
{
KeyValues *pKV = new KeyValues( "convars" );
if ( pKV->LoadFromFile( g_pFullFileSystem, kvFilename ) )
{
KeyValuesDumpAsDevMsg( pKV, 1 );
LoadMapEntry( pKV );
}
}
}
iType = GetDefaultGameTypeForMap( szMapNameFull );
iMode = GetDefaultGameModeForMap( szMapNameFull );
bShouldSet = true;
}
// a mode has not been set before this function was called, so set it here
if ( bShouldSet )
{
SetGameTypeAndMode( iType, iMode );
}
// this is the end of the line for loading game types
// once we have all of the data, if you just type "map mapname" in the console, it'll run with the map's default mode
SetRunMapWithDefaultGametype( false );
#if defined( MATCHMAKING_DLL ) || defined( MATCHMAKING_DS_DLL )
if ( g_pMatchFramework && g_pMatchFramework->GetEventsSubscription() )
{
g_pMatchFramework->GetEventsSubscription()->BroadcastEvent( new KeyValues(
"OnLevelLoadingSetDefaultGameModeAndType", "mapname", szMapNameFull
) );
}
#endif
#ifndef CLIENT_DLL
// now force the loading screen to show the correct ghing
// char const *pGameType = GetGameTypeFromInt( iType );
// char const *pGameMode = GetGameModeFromInt( iMode, iType );
// PopulateLevelInfo( szMapNameBase, pGameType, pGameMode );
// BaseModUI::CBaseModPanel *pBaseModPanel = BaseModUI::CBaseModPanel::GetSingletonPtr();
// if ( pBaseModPanel && pBaseModPanel->IsVisible() )
// {
// pBaseModPanel->CreateAndLoadDialogForKeyValues( szMapNameBase );
// }
#endif
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the index of the current game type.
// -------------------------------------------------------------------------------------------- //
int GameTypes::GetCurrentGameType() const
{
return game_type.GetInt();
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the index of the current game mode.
// -------------------------------------------------------------------------------------------- //
int GameTypes::GetCurrentGameMode() const
{
return game_mode.GetInt();
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the current game type UI string.
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetCurrentGameTypeNameID( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return NULL;
}
return pGameType->m_NameID;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the current game mode UI string.
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetCurrentGameModeNameID( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return NULL;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return NULL;
}
if ( pGameMode->m_NameID_SP[0] == '\0' )
return pGameMode->m_NameID_SP;
return pGameMode->m_NameID;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Apply the game mode convars for the given type and mode.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::ApplyConvarsForCurrentMode( bool isMultiplayer )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType || pGameType->m_Index == CS_GameType_Custom )
{
return false;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return false;
}
// Get the convars.
// If there are no multiplayer convars, fall back to single player.
KeyValues *pKV_Convars = pGameMode->m_pExecConfings;
// Validate the convars.
if ( !pKV_Convars )
{
Warning( "GamesTypes: unable to set convars. There are no convars for game type/mode (%s:%d/%s:%d).\n",
pGameType->m_Name, game_type.GetInt(), pGameMode->m_Name, game_mode.GetInt() );
return false;
}
// Apply the convars for this mode.
for ( KeyValues *pKV_Convar = pKV_Convars->GetFirstValue(); pKV_Convar; pKV_Convar = pKV_Convar->GetNextValue() )
{
if ( !Q_stricmp( "exec", pKV_Convar->GetName() ) )
{
CFmtStr sExecCmd( "exec \"%s\"\n", pKV_Convar->GetString() );
//
// NOTE: This is horrible design to have this file included in multiple projects (client.dll, server.dll, matchmaking.dll)
// which don't have same interfaces applicable to interact with the engine and don't have sufficient context here
// hence these compile-time conditionals to use appropriate interfaces
// ---
// to be fair, only server.dll calls this method, just the horrible design is that this method is compiled in a bunch
// of dlls that don't need it...
//
#if defined( CLIENT_DLL )
engine->ExecuteClientCmd( sExecCmd );
#elif defined( GAME_DLL )
engine->ServerCommand( sExecCmd );
engine->ServerExecute();
#elif defined( MATCHMAKING_DLL )
if ( IVEngineClient *pIVEngineClient = ( IVEngineClient * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( VENGINE_CLIENT_INTERFACE_VERSION ) )
{
pIVEngineClient->ExecuteClientCmd( sExecCmd );
}
else if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) )
{
pIVEngineServer->ServerCommand( sExecCmd );
pIVEngineServer->ServerExecute();
}
#elif defined( MATCHMAKING_DS_DLL )
if ( IVEngineServer *pIVEngineServer = ( IVEngineServer * ) g_pMatchFramework->GetMatchExtensions()->GetRegisteredExtensionInterface( INTERFACEVERSION_VENGINESERVER ) )
{
pIVEngineServer->ServerCommand( sExecCmd );
pIVEngineServer->ServerExecute();
}
#else
#error "gametypes.cpp included in an unexpected project"
#endif
}
}
DevMsg( "GameTypes: set convars for game type/mode (%s:%d/%s:%d):\n",
pGameType->m_Name, game_type.GetInt(), pGameMode->m_Name, game_mode.GetInt() );
KeyValuesDumpAsDevMsg( pKV_Convars, 1 );
// If this is offline, then set the bot difficulty convars.
if ( !isMultiplayer )
{
CustomBotDifficulty *pBotDiff = GetCurrentCustomBotDifficulty_Internal();
Assert( pBotDiff );
if ( pBotDiff )
{
KeyValues *pKV_ConvarsBotDiff = pBotDiff->m_pConvars;
if ( pKV_ConvarsBotDiff )
{
// Apply the convars for the bot difficulty.
for ( KeyValues *pKV_Convar = pKV_ConvarsBotDiff->GetFirstValue(); pKV_Convar; pKV_Convar = pKV_Convar->GetNextValue() )
{
// Only allow a certain set of convars to control bot difficulty
char const *arrBotConvars[] = { "bot_difficulty", "bot_dont_shoot", "bot_quota" };
bool bBotConvar = false;
for ( int jj = 0; jj < Q_ARRAYSIZE( arrBotConvars ); ++ jj )
{
if ( !Q_stricmp( pKV_Convar->GetName(), arrBotConvars[jj] ) )
{
bBotConvar = true;
break;
}
}
if ( !bBotConvar )
{
Warning( "GamesTypes: invalid bot difficulty convar [%s] for bot difficulty (%s:%d).\n",
pKV_Convar->GetName(),
pBotDiff->m_Name, custom_bot_difficulty.GetInt() );
continue;
}
ConVarRef conVarRef( pKV_Convar->GetName() );
conVarRef.SetValue( pKV_Convar->GetString() );
}
DevMsg( "GameTypes: set convars for bot difficulty (%s:%d):\n", pBotDiff->m_Name, custom_bot_difficulty.GetInt() );
KeyValuesDumpAsDevMsg( pKV_ConvarsBotDiff, 1 );
}
else
{
Warning( "GamesTypes: unable to set bot difficulty convars. There are no convars for bot difficulty (%s:%d).\n",
pBotDiff->m_Name, custom_bot_difficulty.GetInt() );
}
}
}
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Output the values of the convars for the current game mode.
// -------------------------------------------------------------------------------------------- //
void GameTypes::DisplayConvarsForCurrentMode( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return;
}
// Display the configs
KeyValuesDumpAsDevMsg( pGameMode->m_pExecConfings, 0, 0 );
// Display the offline bot difficulty convars.
CustomBotDifficulty *pBotDiff = GetCurrentCustomBotDifficulty_Internal();
if ( pBotDiff )
{
KeyValues *pKV_ConvarsBotDiff = pBotDiff->m_pConvars;
if ( pKV_ConvarsBotDiff )
{
Msg( "GameTypes: dumping convars for bot difficulty (%s:%d):",
pBotDiff->m_Name, custom_bot_difficulty.GetInt() );
KeyValuesDumpAsDevMsg( pKV_ConvarsBotDiff, 0, 0 );
}
}
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the CT weapon progression for the current game type and mode.
// -------------------------------------------------------------------------------------------- //
const CUtlVector< IGameTypes::WeaponProgression > *GameTypes::GetWeaponProgressionForCurrentModeCT( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return NULL;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return NULL;
}
return &(pGameMode->m_WeaponProgressionCT);
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the T weapon progression for the current game type and mode.
// -------------------------------------------------------------------------------------------- //
const CUtlVector< IGameTypes::WeaponProgression > *GameTypes::GetWeaponProgressionForCurrentModeT( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return NULL;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return NULL;
}
return &(pGameMode->m_WeaponProgressionT);
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get a random mapgroup for the given mode and type.
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetRandomMapGroup( const char *gameType, const char *gameMode )
{
Assert( gameType && gameMode );
if ( !gameType || !gameMode )
{
return NULL;
}
GameType *pGameType = GetGameType_Internal( gameType );
Assert( pGameType );
if ( !pGameType )
{
return NULL;
}
GameMode *pGameMode = GetGameMode_Internal( pGameType, gameMode );
Assert( pGameMode );
if ( !pGameMode )
{
return NULL;
}
if ( pGameMode->m_MapGroupsMP.Count() == 0 )
{
return NULL;
}
// Randomly choose a mapgroup from our map list.
int iRandom = m_randomStream.RandomInt( 0, pGameMode->m_MapGroupsMP.Count() - 1 );
return pGameMode->m_MapGroupsMP[iRandom];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the first map from the mapgroup
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetFirstMap( const char *mapGroup )
{
Assert( mapGroup );
if ( !mapGroup )
{
return NULL;
}
MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup );
Assert( pMapGroup );
if ( !pMapGroup )
{
return NULL;
}
if ( pMapGroup->m_Maps.Count() == 0 )
{
return NULL;
}
return pMapGroup->m_Maps[0];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get a random map from the mapgroup
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetRandomMap( const char *mapGroup )
{
Assert( mapGroup );
if ( !mapGroup )
{
return NULL;
}
MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup );
Assert( pMapGroup );
if ( !pMapGroup )
{
return NULL;
}
if ( pMapGroup->m_Maps.Count() == 0 )
{
return NULL;
}
// Randomly choose a map from our map list.
int iRandom = m_randomStream.RandomInt( 0, pMapGroup->m_Maps.Count() - 1 );
return pMapGroup->m_Maps[iRandom];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the next map from the mapgroup; wrap around to beginning from the end of list
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetNextMap( const char *mapGroup, const char *mapName )
{
Msg( "Looking for next map in mapgroup '%s'...\n", mapGroup );
Assert( mapGroup );
if ( !mapGroup )
{
return NULL;
}
MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup );
Assert( pMapGroup );
if ( !pMapGroup )
{
return NULL;
}
if ( pMapGroup->m_Maps.Count() == 0 )
{
return NULL;
}
int mapIndex = 0;
for ( ; mapIndex < pMapGroup->m_Maps.Count(); ++mapIndex )
{
char szInputName[MAX_PATH];
V_strcpy_safe( szInputName, mapName );
V_FixSlashes( szInputName, '/' );
if ( mapName && !V_stricmp( mapName, pMapGroup->m_Maps[mapIndex] ) )
{
break;
}
}
// get the next map in the list
mapIndex++;
if ( mapIndex >= pMapGroup->m_Maps.Count() )
{ // wrap to the beginning of the list, use first map if the passed map wasn't in the mapgroup
mapIndex = 0;
}
return pMapGroup->m_Maps[mapIndex];
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get the maxplayers value for the type and mode
// NOTE: This is from the local KV file... This will not match the server you're connected to
// remotely if they've changed it from the default!
// -------------------------------------------------------------------------------------------- //
int GameTypes::GetMaxPlayersForTypeAndMode( int iType, int iMode )
{
GameType *pGameType;
GameMode *pGameMode;
const char* szGameType = GetGameTypeFromInt( iType );
const char* szGameMode = GetGameModeFromInt( iType, iMode );
GetGameModeAndTypeFromStrings( szGameType, szGameMode, pGameType, pGameMode );
if ( !pGameMode )
{
return 1;
}
return pGameMode->m_MaxPlayers;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Is this a valid mapgroup name
// -------------------------------------------------------------------------------------------- //
bool GameTypes::IsValidMapGroupName( const char * mapGroup )
{
if ( !mapGroup || mapGroup[0] == '\0' )
{
return false;
}
MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup );
if ( !pMapGroup )
{
return false;
}
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Does this mapname exist within this mapgroup
// -------------------------------------------------------------------------------------------- //
bool GameTypes::IsValidMapInMapGroup( const char * mapGroup, const char *mapName )
{
if ( !IsValidMapGroupName( mapGroup ) )
{
return false;
}
if ( !mapName )
{
return false;
}
MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup );
if ( !pMapGroup )
{
return false;
}
char fileBase[MAX_MAP_NAME];
V_FileBase( mapName, fileBase, sizeof ( fileBase ) );
for ( int mapIndex = 0 ; mapIndex < pMapGroup->m_Maps.Count(); ++mapIndex )
{
if ( !V_stricmp( fileBase, pMapGroup->m_Maps[mapIndex] ) ||
!V_stricmp( mapName, pMapGroup->m_Maps[mapIndex] ) )
{
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Is this mapgroup part of this type and mode
// -------------------------------------------------------------------------------------------- //
bool GameTypes::IsValidMapGroupForTypeAndMode( const char * mapGroup, const char *gameType, const char *gameMode )
{
if ( !IsValidMapGroupName( mapGroup ) )
{
return false;
}
if ( !gameType || !gameMode )
{
return false;
}
GameType *pGameType = GetGameType_Internal( gameType );
if ( !pGameType )
{
return false;
}
GameMode *pGameMode = GetGameMode_Internal( pGameType, gameMode );
if ( !pGameMode )
{
return false;
}
for ( int i = 0 ; i < pGameMode->m_MapGroupsMP.Count(); ++i )
{
if ( V_strcmp( mapGroup, pGameMode->m_MapGroupsMP[i] ) == 0 )
{
return true;
}
}
for ( int i = 0 ; i < pGameMode->m_MapGroupsSP.Count(); ++i )
{
if ( V_strcmp( mapGroup, pGameMode->m_MapGroupsSP[i] ) == 0 )
{
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Apply the convars for the given map.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::ApplyConvarsForMap( const char *mapName, bool isMultiplayer )
{
Map *pMap = GetMap_Internal( mapName );
if ( pMap )
{
// Determine if we need to set the bot quota.
bool setBotQuota = true;
if ( !isMultiplayer )
{
CustomBotDifficulty *pBotDiff = GetCurrentCustomBotDifficulty_Internal();
Assert( pBotDiff );
if ( pBotDiff )
{
setBotQuota = !pBotDiff->m_HasBotQuota;
}
}
return true;
}
// Warning( "GamesTypes: unable to set convars for map %s. Could not find matching map name.\n", mapName );
return false;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Get specifics about a map.
// -------------------------------------------------------------------------------------------- //
bool GameTypes::GetMapInfo( const char *mapName, uint32 &richPresence )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return false;
}
richPresence = pMap->m_RichPresence;
return true;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the available terrorist character model names for the given map.
// -------------------------------------------------------------------------------------------- //
const CUtlStringList *GameTypes::GetTModelsForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return &pMap->m_TModels;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the available counter-terrorist character model names for the given map.
// -------------------------------------------------------------------------------------------- //
const CUtlStringList *GameTypes::GetCTModelsForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return &pMap->m_CTModels;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the available terrorist view model arms name for the given map.
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetTViewModelArmsForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return pMap->m_TViewModelArms.String();
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the available counter-terrorist view model arms name for the given map.
// -------------------------------------------------------------------------------------------- //
const char *GameTypes::GetCTViewModelArmsForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return pMap->m_CTViewModelArms.String();
}
// Item requirements for the map
const char *GameTypes::GetRequiredAttrForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return pMap->m_RequiresAttr;
}
int GameTypes::GetRequiredAttrValueForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return -1;
}
return pMap->m_RequiresAttrValue;
}
const char *GameTypes::GetRequiredAttrRewardForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return pMap->m_RequiresAttrReward;
}
int GameTypes::GetRewardDropListForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return -1;
}
return pMap->m_nRewardDropList;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the available terrorist character model names for the given map.
// -------------------------------------------------------------------------------------------- //
const CUtlStringList *GameTypes::GetHostageModelsForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return NULL;
}
return &pMap->m_HostageModels;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the default game type defined for the map
// -------------------------------------------------------------------------------------------- //
const int GameTypes::GetDefaultGameTypeForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return -1;
}
return pMap->m_nDefaultGameType;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the default game mode defined for the map
// -------------------------------------------------------------------------------------------- //
const int GameTypes::GetDefaultGameModeForMap( const char *mapName )
{
Map *pMap = GetMap_Internal( mapName );
if ( !pMap )
{
return -1;
}
return pMap->m_nDefaultGameMode;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the maps for the given map group name.
// -------------------------------------------------------------------------------------------- //
const CUtlStringList *GameTypes::GetMapGroupMapList( const char *mapGroup )
{
Assert( mapGroup );
if ( !mapGroup || StringIsEmpty( mapGroup ) )
{
return NULL;
}
MapGroup *pMapGroup = GetMapGroup_Internal( mapGroup );
Assert( pMapGroup );
if ( !pMapGroup )
{
return NULL;
}
return &pMapGroup->m_Maps;
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Returns the bot difficulty for Offline Games (where players choose difficulty).
// -------------------------------------------------------------------------------------------- //
int GameTypes::GetCustomBotDifficulty( void )
{
return custom_bot_difficulty.GetInt();
}
// -------------------------------------------------------------------------------------------- //
// Purpose: Sets the bot difficulty for Offline Games (where players choose difficulty).
// -------------------------------------------------------------------------------------------- //
bool GameTypes::SetCustomBotDifficulty( int botDiff )
{
if ( botDiff < 0 ||
botDiff >= m_CustomBotDifficulties.Count() )
{
Warning( "GameTypes: invalid custom bot difficulty (%d). Range [%d,%d].\n", botDiff, 0, m_CustomBotDifficulties.Count() - 1 );
return false;
}
DevMsg( "GameTypes: setting custom_bot_difficulty to %d.\n", botDiff );
custom_bot_difficulty.SetValue( botDiff );
return true;
}
const char* GameTypes::GetGameTypeFromInt( int gameType )
{
// Find the game type.
FOR_EACH_VEC( m_GameTypes, iType )
{
GameType *pGameType = m_GameTypes[iType];
Assert( pGameType );
if ( pGameType && pGameType->m_Index == gameType )
{
// Found it.
return pGameType->m_Name;
}
}
// Not found.
DevWarning( "GameTypes: could not find matching game type for value \"%d\".\n", gameType );
return NULL;
}
const char* GameTypes::GetGameModeFromInt( int gameType, int gameMode )
{
// Find the game type.
FOR_EACH_VEC( m_GameTypes, iType )
{
GameType *pGameType = m_GameTypes[iType];
Assert( pGameType );
if ( pGameType && pGameType->m_Index == gameType )
{
// Find the game mode.
FOR_EACH_VEC( pGameType->m_GameModes, iMode )
{
GameMode *pGameMode = pGameType->m_GameModes[iMode];
Assert( pGameMode );
if ( pGameMode && pGameMode->m_Index == gameMode )
{
// Found it.
return pGameMode->m_Name;
}
}
}
}
// Not found.
DevWarning( "GameTypes: could not find matching game mode value of \"%d\" and type value of \"%d\".\n",
gameType, gameMode );
return NULL;
}
bool GameTypes::GetGameTypeFromMode( const char *szGameMode, const char *&pszGameTypeOut )
{
FOR_EACH_VEC( m_GameTypes, iType )
{
GameType *pGameType = m_GameTypes[ iType ];
Assert( pGameType );
if ( pGameType )
{
// Find the game mode.
FOR_EACH_VEC( pGameType->m_GameModes, iMode )
{
GameMode *pGameMode = pGameType->m_GameModes[ iMode ];
Assert( pGameMode );
if ( pGameMode && !V_strcmp( pGameMode->m_Name, szGameMode ) )
{
// Found it.
pszGameTypeOut = pGameType->m_Name;
return true;
}
}
}
}
// Not found.
DevWarning( "GameTypes: could not find matching game mode value of \"%s\" in any game type.\n",
szGameMode );
return false;
}
bool GameTypes::GetGameModeAndTypeIntsFromStrings( const char* szGameType, const char* szGameMode, int& iOutGameType, int& iOutGameMode )
{
GameType* type = NULL;
GameMode* mode = NULL;
iOutGameType = g_invalidInteger;
iOutGameMode = g_invalidInteger;
if ( V_stricmp( szGameType, "default" ) == 0 )
{
return false;
}
if ( GetGameModeAndTypeFromStrings( szGameType, szGameMode, type, mode ) )
{
if ( mode && type )
{
Assert( type->m_Index >= 0 && type->m_Index < m_GameTypes.Count() );
Assert( mode->m_Index >= 0 && mode->m_Index < type->m_GameModes.Count() );
if ( type->m_Index >= 0 && type->m_Index < m_GameTypes.Count() &&
mode->m_Index >= 0 && mode->m_Index < type->m_GameModes.Count() )
{
iOutGameType = type->m_Index;
iOutGameMode = mode->m_Index;
return true;
}
}
}
return false;
}
bool GameTypes::GetGameModeAndTypeNameIdsFromStrings( const char* szGameType, const char* szGameMode, const char*& szOutGameTypeNameId, const char*& szOutGameModeNameId )
{
GameType* type = NULL;
GameMode* mode = NULL;
szOutGameTypeNameId = NULL;
szOutGameModeNameId = NULL;
if ( GetGameModeAndTypeFromStrings( szGameType, szGameMode, type, mode ) )
{
Assert ( mode && mode->m_NameID );
Assert ( type && type->m_NameID );
if ( mode && mode->m_NameID && type && type->m_NameID )
{
szOutGameTypeNameId = type->m_NameID;
if ( mode->m_NameID_SP[0] != '\0' )
szOutGameModeNameId = mode->m_NameID_SP;
else
szOutGameModeNameId = mode->m_NameID;
return true;
}
}
return false;
}
bool GameTypes::GetGameModeAndTypeFromStrings( const char* szGameType, const char* szGameMode, GameType*& outGameType, GameMode*& outGameMode )
{
outGameType = NULL;
outGameMode = NULL;
Assert( szGameType && szGameMode );
if ( !szGameType || !szGameMode )
{
return false;
}
// we want to use the map's default settings, so don't set the game mode here, we'll do it later
if ( V_stricmp( szGameType, "default" ) == 0 )
{
return false;
}
outGameType = GetGameType_Internal( szGameType );
Assert( outGameType );
if ( outGameType )
{
outGameMode = GetGameMode_Internal( outGameType, szGameMode );
Assert( outGameMode );
if ( outGameMode )
{
return true;
}
}
Warning( "GamesTypes: unable to get game type and mode. Could not find type/mode matching type:%s/mode:%s.\n", szGameType, szGameMode );
return false;
}
int GameTypes::GetNoResetVoteThresholdForCurrentModeCT( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return -1;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return -1;
}
return pGameMode->m_NoResetVoteThresholdCT;
}
int GameTypes::GetNoResetVoteThresholdForCurrentModeT( void )
{
GameType *pGameType = GetCurrentGameType_Internal();
Assert( pGameType );
if ( !pGameType )
{
return -1;
}
GameMode *pGameMode = GetCurrentGameMode_Internal( pGameType );
Assert( pGameMode );
if ( !pGameMode )
{
return -1;
}
return pGameMode->m_NoResetVoteThresholdT;
}
int GameTypes::GetCurrentServerNumSlots( void )
{
// This is only valid if we are connected to a server and received the extended info blob
#if defined ( MATCHMAKING_DLL )
Assert( m_pExtendedServerInfo && g_pMatchExtensions->GetIVEngineClient() && g_pMatchExtensions->GetIVEngineClient()->IsConnected() );
#endif
Assert ( GameTypes_IsOnClient() );
return m_iCurrentServerNumSlots;
}
int GameTypes::GetCurrentServerSettingInt( const char *szSetting, int iDefaultValue )
{
return m_pExtendedServerInfo->GetInt( szSetting, iDefaultValue );
}
bool GameTypes::CreateOrUpdateWorkshopMapGroup( const char* szName, const CUtlStringList & vecMapNames )
{
return !!CreateWorkshopMapGroupInternal( szName, vecMapNames );
}
GameTypes::MapGroup * GameTypes::CreateWorkshopMapGroupInternal( const char* szName, const CUtlStringList & vecMapNames )
{
MapGroup *pMapGroup = GetMapGroup_Internal( szName );
if ( !pMapGroup )
{
pMapGroup = new MapGroup;
V_strcpy_safe( pMapGroup->m_Name, szName );
m_MapGroups.AddToTail( pMapGroup );
}
// Workshop map groups are named their publishfileid, so a nonzero integer.
Assert( V_atoui64( szName ) != 0 );
pMapGroup->m_bIsWorkshopMapGroup = true;
// Clear old map list, stomp with new one
pMapGroup->m_Maps.PurgeAndDeleteElements();
FOR_EACH_VEC( vecMapNames, i )
{
const char* szMap = vecMapNames[i];
pMapGroup->m_Maps.CopyAndAddToTail( szMap );
V_FixSlashes( pMapGroup->m_Maps.Tail(), '/' );
}
return pMapGroup;
}
bool GameTypes::IsWorkshopMapGroup( const char* szMapGroupName )
{
MapGroup *pMapGroup = GetMapGroup_Internal( szMapGroupName );
return pMapGroup && pMapGroup->m_bIsWorkshopMapGroup;
}
// ============================================================================================ //
// Helper functions
// ============================================================================================ //
// -------------------------------------------------------------------------------------------- //
// Purpose: Display the convars for the current game mode.
// -------------------------------------------------------------------------------------------- //
void DisplayGameModeConvars( void )
{
if ( g_pGameTypes )
{
g_pGameTypes->DisplayConvarsForCurrentMode();
}
}
| 31.251594 | 180 | 0.584837 | DannyParker0001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.