hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88692043fdfa2f6c69da81dd154b35c28ab31c1c | 5,417 | cpp | C++ | serving/reagent/serving/core/DecisionService.cpp | kellielu/ReAgent | c538992672220453cdc95044def25c4e0691a8b0 | [
"BSD-3-Clause"
] | 1,156 | 2019-10-02T12:15:31.000Z | 2022-03-31T16:01:27.000Z | serving/reagent/serving/core/DecisionService.cpp | kellielu/ReAgent | c538992672220453cdc95044def25c4e0691a8b0 | [
"BSD-3-Clause"
] | 448 | 2019-10-03T13:40:52.000Z | 2022-03-28T07:49:15.000Z | serving/reagent/serving/core/DecisionService.cpp | kellielu/ReAgent | c538992672220453cdc95044def25c4e0691a8b0 | [
"BSD-3-Clause"
] | 214 | 2019-10-13T13:28:33.000Z | 2022-03-24T04:11:52.000Z | #include "reagent/serving/core/DecisionService.h"
#include "reagent/serving/core/LogJoiner.h"
#include "reagent/serving/core/OperatorFactory.h"
namespace reagent {
DecisionService::DecisionService(
std::shared_ptr<ConfigProvider> configProvider,
std::shared_ptr<ActionValueScorer> actionValueScorer,
std::shared_ptr<LogJoiner> logJoiner,
std::shared_ptr<RealTimeCounter> realTimeCounter,
std::shared_ptr<SharedParameterHandler> sharedParameterHandler)
: configProvider_(configProvider),
actionValueScorer_(actionValueScorer),
logJoiner_(logJoiner),
realTimeCounter_(realTimeCounter),
sharedParameterHandler_(sharedParameterHandler) {
configProvider_->initialize(this);
logJoiner->registerDecisionService(this);
}
std::shared_ptr<DecisionPlan> DecisionService::getPlan(
const std::string& name) {
std::lock_guard<std::mutex> lock(planMutex_);
auto it = planContainer_.find(name);
if (it == planContainer_.end()) {
LOG_AND_THROW("Tried to get a config that doesn't exist: " << name);
}
return it->second;
}
DecisionResponse DecisionService::attachIdAndProcess(DecisionRequest request) {
const auto request_start_time = std::chrono::steady_clock::now();
if (request.request_id.empty()) {
request.request_id = generateUuid4();
}
auto plan = getPlan(request.plan_name);
OperatorData inputOperatorData = request.input;
auto allOperatorData = runner_.run(plan->getOperators(), plan->getConstants(),
request, inputOperatorData);
auto outputDataIt = allOperatorData.find(plan->getOutputOperatorName());
if (outputDataIt == allOperatorData.end()) {
LOG_AND_THROW("Output op missing from plan "
<< request.plan_name << " " << plan->getOutputOperatorName());
}
const RankedActionList outputData =
std::get<RankedActionList>(outputDataIt->second);
DecisionResponse response;
response.request_id = request.request_id;
response.plan_name = request.plan_name;
response.actions = outputData;
const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - request_start_time);
response.duration = duration.count();
logJoiner_->logDecision(request, response, allOperatorData);
return response;
}
void DecisionService::computeRewardAndLogFeedback(Feedback feedback) {
auto plan = getPlan(feedback.plan_name);
// Turn metrics -> rewards
double aggregateReward = 0.0;
for (auto& it : feedback.actions) {
double reward = 0.0;
if (!plan->getConfig().reward_function.empty()) {
reward = plan->evaluateRewardFunction(it.metrics);
}
it.computed_reward = reward;
switch (plan->getConfig().reward_aggregator) {
case DRA_MAX:
aggregateReward = std::max(aggregateReward, reward);
break;
case DRA_SUM:
aggregateReward = aggregateReward + reward;
break;
default:
LOG_AND_THROW("Invalid reward aggregator");
}
}
feedback.computed_reward = aggregateReward;
logJoiner_->logFeedback(feedback);
}
void DecisionService::_giveFeedback(
const DecisionWithFeedback& decisionWithFeedback) {
if (!bool(decisionWithFeedback.decision_request) ||
!bool(decisionWithFeedback.decision_response) ||
!bool(decisionWithFeedback.operator_outputs) ||
!bool(decisionWithFeedback.feedback)) {
json j = decisionWithFeedback;
LOG(FATAL) << "Decision with feedback is missing some elements: "
<< j.dump();
}
const auto& request = *(decisionWithFeedback.decision_request);
const auto& operatorOutputs = *(decisionWithFeedback.operator_outputs);
const auto& feedback = *(decisionWithFeedback.feedback);
auto plan = getPlan(request.plan_name);
// Update all operators with rewards
for (const auto& op : plan->getOperators()) {
StringOperatorDataMap namedInputs;
for (const auto& inputDepEntry : op->getInputDepMap()) {
const auto& inputName = inputDepEntry.first;
const auto& depOperatorName = inputDepEntry.second;
auto it = operatorOutputs.find(depOperatorName);
if (it == operatorOutputs.end()) {
LOG_AND_THROW("Could not find data of "
<< depOperatorName
<< " for finished operator: " << op->getName());
}
namedInputs[inputName] = it->second;
}
auto it = operatorOutputs.find(op->getName());
if (it == operatorOutputs.end()) {
LOG_AND_THROW(
"Could not find data for finished operator: " << op->getName());
}
auto const& pastOutput = it->second;
op->giveFeedback(feedback, namedInputs, pastOutput);
}
}
std::shared_ptr<DecisionPlan> DecisionService::createPlan(
const std::string& planName, const DecisionConfig& config) {
std::vector<std::shared_ptr<Operator>> operators =
OperatorFactory::getInstance()->createFromConfig(planName, config, this);
if (operators.empty()) {
LOG_AND_THROW("Plan has no operators");
}
// Create constants
StringOperatorDataMap constants;
for (const auto& it : config.constants) {
const std::string& constantName = it.name;
constants[constantName] = it.value;
}
auto plan = std::make_shared<DecisionPlan>(config, operators, constants);
std::lock_guard<std::mutex> lock(planMutex_);
planContainer_[planName] = plan;
return plan;
}
} // namespace reagent
| 35.874172 | 80 | 0.703526 | [
"vector"
] |
886f35f75dd2ed6750a4a7cfda2750daccd8d9aa | 962 | cpp | C++ | konsert.cpp | dtlanghoff/nio-2014 | 82752dff22a03dbb2f3fec4e98abc57903f2ae12 | [
"MIT"
] | null | null | null | konsert.cpp | dtlanghoff/nio-2014 | 82752dff22a03dbb2f3fec4e98abc57903f2ae12 | [
"MIT"
] | null | null | null | konsert.cpp | dtlanghoff/nio-2014 | 82752dff22a03dbb2f3fec4e98abc57903f2ae12 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
int cost(const vector<int>& x, const vector<int>& y, const vector<int>& b, int src, int dest) {
if (src == 0)
return abs(x[dest]) + abs(y[dest]) + b[dest];
else
return abs(x[src]-x[dest]) + abs(y[src]-y[dest]) + b[dest];
}
int main() {
int k = 0;
int n, t;
cin >> n >> t;
vector<int> x(n+1), y(n+1), b(n+1);
for (int i = 1; i <= n; i++)
cin >> x[i] >> y[i] >> b[i];
vector< vector<int> > dp(n+1, vector<int>(n+1));
for (int s = 1; s <= n; s++) {
dp[1][s] = cost(x, y, b, 0, s);
if (dp[1][s] <= t)
k = 1;
}
for (int l = 2; l <= n; l++) {
for (int s = l; s <= n; s++) {
int m = numeric_limits<int>::max();
for (int n = l-1; n < s; n++)
m = min(m, dp[l-1][n] + cost(x, y, b, n, s));
dp[l][s] = m;
if (dp[l][s] <= t)
k = l;
}
}
cout << k << endl;
return 0;
}
| 20.468085 | 95 | 0.456341 | [
"vector"
] |
887043d0e0d03f88367f1ab8709a604bdb2095f8 | 1,083 | cpp | C++ | src/core/ChClassRegister.cpp | scpeters/chrono | a7cefda35d8a445963297cbe2dbb3cdfb4397f16 | [
"BSD-3-Clause"
] | 1 | 2020-02-16T16:52:08.000Z | 2020-02-16T16:52:08.000Z | src/core/ChClassRegister.cpp | Milad-Rakhsha/Project-Chrono | 6ab7abcd532cfb3c5e3876478fdd49c7ab783f63 | [
"BSD-3-Clause"
] | null | null | null | src/core/ChClassRegister.cpp | Milad-Rakhsha/Project-Chrono | 6ab7abcd532cfb3c5e3876478fdd49c7ab783f63 | [
"BSD-3-Clause"
] | null | null | null | //
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
///////////////////////////////////////////////////
//
// ChClassRegister.cpp
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include "core/ChClassRegister.h"
namespace chrono
{
/// The root of the list of ChClassRegister<t> objects, each
/// will contain the name ID of the class,and other useful things
/// such as the method which can create a 't' object in runtime.
ChClassRegisterCommon** ChClassRegisterCommon::GetStaticHeadAddr()
{
static ChClassRegisterCommon* mlocalHead = 0; // A STATIC DATA
return &mlocalHead;//&m_pHead;
}
} // END_OF_NAMESPACE____
| 20.826923 | 74 | 0.554017 | [
"object"
] |
887e18fc356211a5ac8b7e17990aecc9b65d9ec9 | 93,928 | hpp | C++ | STL/functional.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | 1 | 2019-09-28T09:40:08.000Z | 2019-09-28T09:40:08.000Z | STL/functional.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | null | null | null | STL/functional.hpp | colorhistory/cplusplus-general-programming | 3ece924a2ab34711a55a45bc41e2b74384956204 | [
"MIT"
] | null | null | null | #ifndef FUNCTIONAL_HPP
#define FUNCTIONAL_HPP
#include "bits/stdc++.h"
namespace GP {
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
template <class T, class T2, class R>
class reference_wrapper : public unary_function<T, R>, public binary_function<T, T2, R> {
public:
// types
typedef T type;
typedef see below result_type; // Not always defined
// construct/copy/destroy
reference_wrapper(T&) noexcept;
reference_wrapper(T&&) = delete; // do not bind to temps
reference_wrapper(const reference_wrapper<T>& x) noexcept;
// assignment
reference_wrapper& operator=(const reference_wrapper<T>& x) noexcept;
// access
operator T&() const noexcept;
T& get() const noexcept;
// invoke
template <class... ArgTypes>
typename std::result_of<T&(ArgTypes&&...)>::type operator()(ArgTypes&&...) const;
};
template <class T>
reference_wrapper<T> ref(T& t) noexcept;
template <class T>
void ref(const T&& t) = delete;
template <class T>
reference_wrapper<T> ref(reference_wrapper<T> t) noexcept;
template <class T>
reference_wrapper<const T> cref(const T& t) noexcept;
template <class T>
void cref(const T&& t) = delete;
template <class T>
reference_wrapper<const T> cref(reference_wrapper<T> t) noexcept;
template <class T>
struct unwrap_reference; // since C++20
template <class T>
struct unwrap_ref_decay : unwrap_reference<decay_t<T>> {}; // since C++20
template <class T>
using unwrap_reference_t = typename unwrap_reference<T>::type; // since C++20
template <class T>
using unwrap_ref_decay_t = typename unwrap_ref_decay<T>::type; // since C++20
template <class T> // <class T=void> in C++14
struct plus : binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct minus : binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct multiplies : binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct divides : binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct modulus : binary_function<T, T, T> {
T operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct negate : unary_function<T, T> {
T operator()(const T& x) const;
};
template <class T> // <class T=void> in C++14
struct equal_to : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct not_equal_to : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct greater : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct less : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct greater_equal : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct less_equal : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct logical_and : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct logical_or : binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct logical_not : unary_function<T, bool> {
bool operator()(const T& x) const;
};
template <class T> // <class T=void> in C++14
struct bit_and : unary_function<T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct bit_or : unary_function<T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T> // <class T=void> in C++14
struct bit_xor : unary_function<T, bool> {
bool operator()(const T& x, const T& y) const;
};
template <class T = void> // C++14
struct bit_xor : unary_function<T, bool> {
bool operator()(const T& x) const;
};
template <class Predicate>
class unary_negate // deprecated in C++17
: public unary_function<typename Predicate::argument_type, bool> {
public:
explicit unary_negate(const Predicate& pred);
bool operator()(const typename Predicate::argument_type& x) const;
};
template <class Predicate> // deprecated in C++17
unary_negate<Predicate> not1(const Predicate& pred);
template <class Predicate>
class binary_negate // deprecated in C++17
: public binary_function<typename Predicate::first_argument_type, typename Predicate::second_argument_type,
bool> {
public:
explicit binary_negate(const Predicate& pred);
bool operator()(const typename Predicate::first_argument_type& x,
const typename Predicate::second_argument_type& y) const;
};
template <class Predicate> // deprecated in C++17
binary_negate<Predicate> not2(const Predicate& pred);
template <class F>
unspecified not_fn(F&& f); // C++17
template <class T>
struct is_bind_expression;
template <class T>
struct is_placeholder;
// See C++14 20.9.9, Function object binders
template <class T>
inline constexpr bool is_bind_expression_v = is_bind_expression<T>::value; // C++17
template <class T>
inline constexpr int is_placeholder_v = is_placeholder<T>::value; // C++17
template <class Fn, class... BoundArgs>
unspecified bind(Fn&&, BoundArgs&&...);
template <class R, class Fn, class... BoundArgs>
unspecified bind(Fn&&, BoundArgs&&...);
namespace placeholders {
// M is the implementation-defined number of placeholders
extern unspecified _1;
extern unspecified _2;
... extern unspecified _Mp;
} // namespace placeholders
template <class Operation>
class binder1st // deprecated in C++11, removed in C++17
: public unary_function<typename Operation::second_argument_type, typename Operation::result_type> {
protected:
Operation op;
typename Operation::first_argument_type value;
public:
binder1st(const Operation& x, const typename Operation::first_argument_type y);
typename Operation::result_type operator()(typename Operation::second_argument_type& x) const;
typename Operation::result_type operator()(const typename Operation::second_argument_type& x) const;
};
template <class Operation, class T>
binder1st<Operation> bind1st(const Operation& op, const T& x); // deprecated in C++11, removed in C++17
template <class Operation>
class binder2nd // deprecated in C++11, removed in C++17
: public unary_function<typename Operation::first_argument_type, typename Operation::result_type> {
protected:
Operation op;
typename Operation::second_argument_type value;
public:
binder2nd(const Operation& x, const typename Operation::second_argument_type y);
typename Operation::result_type operator()(typename Operation::first_argument_type& x) const;
typename Operation::result_type operator()(const typename Operation::first_argument_type& x) const;
};
template <class Operation, class T>
binder2nd<Operation> bind2nd(const Operation& op, const T& x); // deprecated in C++11, removed in C++17
template <class Arg, class Result> // deprecated in C++11, removed in C++17
class pointer_to_unary_function : public unary_function<Arg, Result> {
public:
explicit pointer_to_unary_function(Result (*f)(Arg));
Result operator()(Arg x) const;
};
template <class Arg, class Result>
pointer_to_unary_function<Arg, Result> ptr_fun(Result (*f)(Arg)); // deprecated in C++11, removed in C++17
template <class Arg1, class Arg2, class Result> // deprecated in C++11, removed in C++17
class pointer_to_binary_function : public binary_function<Arg1, Arg2, Result> {
public:
explicit pointer_to_binary_function(Result (*f)(Arg1, Arg2));
Result operator()(Arg1 x, Arg2 y) const;
};
template <class Arg1, class Arg2, class Result>
pointer_to_binary_function<Arg1, Arg2, Result> ptr_fun(Result (*f)(Arg1, Arg2)); // deprecated in C++11, removed in
template <class S, class T> // deprecated in C++11, removed in C++17
class mem_fun_t : public unary_function<T*, S> {
public:
explicit mem_fun_t(S (T::*p)());
S operator()(T* p) const;
};
template <class S, class T, class A>
class mem_fun1_t : public binary_function<T*, A, S> // deprecated in C++11, removed in C++17
{
public:
explicit mem_fun1_t(S (T::*p)(A));
S operator()(T* p, A x) const;
};
template <class S, class T>
mem_fun_t<S, T> mem_fun(S (T::*f)()); // deprecated in C++11, removed in
template <class S, class T, class A>
mem_fun1_t<S, T, A> mem_fun(S (T::*f)(A)); // deprecated in C++11, removed
template <class S, class T>
class mem_fun_ref_t : public unary_function<T, S> // deprecated in C++11, removed in C++17
{
public:
explicit mem_fun_ref_t(S (T::*p)());
S operator()(T& p) const;
};
template <class S, class T, class A>
class mem_fun1_ref_t : public binary_function<T, A, S> // deprecated in C++11, removed in C++17
{
public:
explicit mem_fun1_ref_t(S (T::*p)(A));
S operator()(T& p, A x) const;
};
template <class S, class T>
mem_fun_ref_t<S, T> mem_fun_ref(S (T::*f)()); // deprecated in C++11, removed
template <class S, class T, class A>
mem_fun1_ref_t<S, T, A> mem_fun_ref(S (T::*f)(A)); // deprecated in
template <class S, class T>
class const_mem_fun_t : public unary_function<const T*, S> // deprecated in C++11, removed in C++17
{
public:
explicit const_mem_fun_t(S (T::*p)() const);
S operator()(const T* p) const;
};
template <class S, class T, class A>
class const_mem_fun1_t : public binary_function<const T*, A, S> // deprecated in C++11, removed in C++17
{
public:
explicit const_mem_fun1_t(S (T::*p)(A) const);
S operator()(const T* p, A x) const;
};
template <class S, class T>
const_mem_fun_t<S, T> mem_fun(S (T::*f)() const); // deprecated in C++11,
template <class S, class T, class A>
const_mem_fun1_t<S, T, A> mem_fun(S (T::*f)(A) const); //
template <class S, class T>
class const_mem_fun_ref_t : public unary_function<T, S> // deprecated in C++11, removed in C++17
{
public:
explicit const_mem_fun_ref_t(S (T::*p)() const);
S operator()(const T& p) const;
};
template <class S, class T, class A>
class const_mem_fun1_ref_t : public binary_function<T, A, S> // deprecated in C++11, removed in C++17
{
public:
explicit const_mem_fun1_ref_t(S (T::*p)(A) const);
S operator()(const T& p, A x) const;
};
template <class S, class T>
const_mem_fun_ref_t<S, T> mem_fun_ref(S (T::*f)() const); // deprecated in
template <class S, class T, class A>
const_mem_fun1_ref_t<S, T, A> mem_fun_ref(S (T::*f)(A) const); // deprecated in C++11, remo ved in C++17
template <class R, class T>
unspecified mem_fn(R T::*);
class bad_function_call : public exception {};
template <class>
class function; // undefined
template <class R, class... ArgTypes>
class function<R(ArgTypes...)> : public unary_function<T1, R> // iff sizeof...(ArgTypes) == 1 and
// ArgTypes contains T1
: public binary_function<T1, T2, R> // iff sizeof...(ArgTypes) == 2 and
// ArgTypes contains T1 and T2
{
public:
typedef R result_type;
// construct/copy/destroy:
function() noexcept;
function(std::nullptr_t) noexcept;
function(const function&);
function(function&&) noexcept;
template <class F>
function(F);
template <Allocator Alloc>
function(allocator_arg_t, const Alloc&) noexcept; // removed in C++17
template <Allocator Alloc>
function(allocator_arg_t, const Alloc&, std::nullptr_t) noexcept; // removed in C++17
template <Allocator Alloc>
function(allocator_arg_t, const Alloc&, const function&); // removed in C++17
template <Allocator Alloc>
function(allocator_arg_t, const Alloc&, function&&); // removed in C++17
template <class F, Allocator Alloc>
function(allocator_arg_t, const Alloc&, F); // removed in C++17
function& operator=(const function&);
function& operator=(function&&) noexcept;
function& operator=(std::nullptr_t) noexcept;
template <class F>
function& operator=(F&&);
template <class F>
function& operator=(reference_wrapper<F>) noexcept;
~function();
// function modifiers:
void swap(function&) noexcept;
template <class F, class Alloc>
void assign(F&&, const Alloc&); // Removed in C++17
// function capacity:
explicit operator bool() const noexcept;
// function invocation:
R operator()(ArgTypes...) const;
// function target access:
const std::type_info& target_type() const noexcept;
template <typename T>
T* target() noexcept;
template <typename T>
const T* target() const noexcept;
};
// Null pointer comparisons:
template <class R, class... ArgTypes>
bool operator==(const function<R(ArgTypes...)>&, std::nullptr_t) noexcept;
template <class R, class... ArgTypes>
bool operator==(std::nullptr_t, const function<R(ArgTypes...)>&) noexcept;
template <class R, class... ArgTypes>
bool operator!=(const function<R(ArgTypes...)>&, std::nullptr_t) noexcept;
template <class R, class... ArgTypes>
bool operator!=(std::nullptr_t, const function<R(ArgTypes...)>&) noexcept;
// specialized algorithms:
template <class R, class... ArgTypes>
void swap(function<R(ArgTypes...)>&, function<R(ArgTypes...)>&) noexcept;
template <class T>
struct hash;
template <>
struct hash<bool>;
template <>
struct hash<char>;
template <>
struct hash<signed char>;
template <>
struct hash<unsigned char>;
template <>
struct hash<char16_t>;
template <>
struct hash<char32_t>;
template <>
struct hash<wchar_t>;
template <>
struct hash<short>;
template <>
struct hash<unsigned short>;
template <>
struct hash<int>;
template <>
struct hash<unsigned int>;
template <>
struct hash<long>;
template <>
struct hash<long long>;
template <>
struct hash<unsigned long>;
template <>
struct hash<unsigned long long>;
template <>
struct hash<float>;
template <>
struct hash<double>;
template <>
struct hash<long double>;
template <class T>
struct hash<T*>;
template <>
struct hash<std::nullptr_t>; // C++17
template <class _Tp = void>
struct plus : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x + __y;
}
};
template <>
struct plus<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct minus : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x - __y;
}
};
template <>
struct minus<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct multiplies : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x * __y;
}
};
template <>
struct multiplies<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct divides : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x / __y;
}
};
template <>
struct divides<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct modulus : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x % __y;
}
};
template <>
struct modulus<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct negate : unary_function<_Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x) const {
return -__x;
}
};
template <>
struct negate<void> {
template <class _Tp>
constexpr auto operator()(_Tp&& __x) const _NOEXCEPT_(noexcept(-_VSTD::forward<_Tp>(__x)))
-> decltype(-_VSTD::forward<_Tp>(__x)) {
return -_VSTD::forward<_Tp>(__x);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct equal_to : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x == __y;
}
};
template <>
struct equal_to<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct not_equal_to : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x != __y;
}
};
template <>
struct not_equal_to<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
template <class _Tp = void>
struct greater : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x > __y;
}
};
template <>
struct greater<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
// less in <__functional_base>
template <class _Tp = void>
struct greater_equal : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x >= __y;
}
};
template <>
struct greater_equal<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct less_equal : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x <= __y;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct less_equal<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct logical_and : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x && __y;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct logical_and<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct logical_or : binary_function<_Tp, _Tp, bool> {
constexpr bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x || __y;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct logical_or<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct logical_not : unary_function<_Tp, bool> {
constexpr bool operator()(const _Tp& __x) const {
return !__x;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct logical_not<void> {
template <class _Tp>
constexpr auto operator()(_Tp&& __x) const _NOEXCEPT_(noexcept(!_VSTD::forward<_Tp>(__x)))
-> decltype(!_VSTD::forward<_Tp>(__x)) {
return !_VSTD::forward<_Tp>(__x);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct bit_and : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x & __y;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct bit_and<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct bit_or : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x | __y;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct bit_or<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
#else
template <class _Tp>
#endif
struct bit_xor : binary_function<_Tp, _Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x, const _Tp& __y) const {
return __x ^ __y;
}
};
#if _LIBCPP_STD_VER > 11
template <>
struct bit_xor<void> {
template <class _T1, class _T2>
constexpr auto operator()(_T1&& __t, _T2&& __u) const
_NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u)))
-> decltype(_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u)) {
return _VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u);
}
typedef void is_transparent;
};
#endif
#if _LIBCPP_STD_VER > 11
template <class _Tp = void>
struct bit_not : unary_function<_Tp, _Tp> {
constexpr _Tp operator()(const _Tp& __x) const {
return ~__x;
}
};
template <>
struct bit_not<void> {
template <class _Tp>
constexpr auto operator()(_Tp&& __x) const _NOEXCEPT_(noexcept(~_VSTD::forward<_Tp>(__x)))
-> decltype(~_VSTD::forward<_Tp>(__x)) {
return ~_VSTD::forward<_Tp>(__x);
}
typedef void is_transparent;
};
#endif
template <class _Predicate>
class _LIBCPP_DEPRECATED_IN_CXX17 unary_negate : public unary_function<typename _Predicate::argument_type, bool> {
_Predicate __pred_;
public:
constexpr explicit unary_negate(const _Predicate& __pred) : __pred_(__pred) {
}
constexpr bool operator()(const typename _Predicate::argument_type& __x) const {
return !__pred_(__x);
}
};
template <class _Predicate>
_LIBCPP_DEPRECATED_IN_CXX17 inline constexpr unary_negate<_Predicate> not1(const _Predicate& __pred) {
return unary_negate<_Predicate>(__pred);
}
template <class _Predicate>
class _LIBCPP_DEPRECATED_IN_CXX17 binary_negate
: public binary_function<typename _Predicate::first_argument_type, typename _Predicate::second_argument_type,
bool> {
_Predicate __pred_;
public:
explicit constexpr binary_negate(const _Predicate& __pred) : __pred_(__pred) {
}
constexpr bool operator()(const typename _Predicate::first_argument_type& __x,
const typename _Predicate::second_argument_type& __y) const {
return !__pred_(__x, __y);
}
};
template <class _Predicate>
_LIBCPP_DEPRECATED_IN_CXX17 inline constexpr binary_negate<_Predicate> not2(const _Predicate& __pred) {
return binary_negate<_Predicate>(__pred);
}
#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
template <class __Operation>
class _LIBCPP_DEPRECATED_IN_CXX11 binder1st
: public unary_function<typename __Operation::second_argument_type, typename __Operation::result_type> {
protected:
__Operation op;
typename __Operation::first_argument_type value;
public:
binder1st(const __Operation& __x, const typename __Operation::first_argument_type __y) : op(__x), value(__y) {
}
typename __Operation::result_type operator()(typename __Operation::second_argument_type& __x) const {
return op(value, __x);
}
typename __Operation::result_type operator()(const typename __Operation::second_argument_type& __x) const {
return op(value, __x);
}
};
template <class __Operation, class _Tp>
_LIBCPP_DEPRECATED_IN_CXX11 inline binder1st<__Operation> bind1st(const __Operation& __op, const _Tp& __x) {
return binder1st<__Operation>(__op, __x);
}
template <class __Operation>
class _LIBCPP_DEPRECATED_IN_CXX11 binder2nd
: public unary_function<typename __Operation::first_argument_type, typename __Operation::result_type> {
protected:
__Operation op;
typename __Operation::second_argument_type value;
public:
binder2nd(const __Operation& __x, const typename __Operation::second_argument_type __y) : op(__x), value(__y) {
}
typename __Operation::result_type operator()(typename __Operation::first_argument_type& __x) const {
return op(__x, value);
}
typename __Operation::result_type operator()(const typename __Operation::first_argument_type& __x) const {
return op(__x, value);
}
};
template <class __Operation, class _Tp>
_LIBCPP_DEPRECATED_IN_CXX11 inline binder2nd<__Operation> bind2nd(const __Operation& __op, const _Tp& __x) {
return binder2nd<__Operation>(__op, __x);
}
template <class _Arg, class _Result>
class _LIBCPP_DEPRECATED_IN_CXX11 pointer_to_unary_function : public unary_function<_Arg, _Result> {
_Result (*__f_)(_Arg);
public:
explicit pointer_to_unary_function(_Result (*__f)(_Arg)) : __f_(__f) {
}
_Result operator()(_Arg __x) const {
return __f_(__x);
}
};
template <class _Arg, class _Result>
_LIBCPP_DEPRECATED_IN_CXX11 inline pointer_to_unary_function<_Arg, _Result> ptr_fun(_Result (*__f)(_Arg)) {
return pointer_to_unary_function<_Arg, _Result>(__f);
}
template <class _Arg1, class _Arg2, class _Result>
class _LIBCPP_DEPRECATED_IN_CXX11 pointer_to_binary_function : public binary_function<_Arg1, _Arg2, _Result> {
_Result (*__f_)(_Arg1, _Arg2);
public:
explicit pointer_to_binary_function(_Result (*__f)(_Arg1, _Arg2)) : __f_(__f) {
}
_Result operator()(_Arg1 __x, _Arg2 __y) const {
return __f_(__x, __y);
}
};
template <class _Arg1, class _Arg2, class _Result>
_LIBCPP_DEPRECATED_IN_CXX11 inline pointer_to_binary_function<_Arg1, _Arg2, _Result> ptr_fun(
_Result (*__f)(_Arg1, _Arg2)) {
return pointer_to_binary_function<_Arg1, _Arg2, _Result>(__f);
}
template <class _Sp, class _Tp>
class _LIBCPP_DEPRECATED_IN_CXX11 mem_fun_t : public unary_function<_Tp*, _Sp> {
_Sp (_Tp::*__p_)();
public:
explicit mem_fun_t(_Sp (_Tp::*__p)()) : __p_(__p) {
}
_Sp operator()(_Tp* __p) const {
return (__p->*__p_)();
}
};
template <class _Sp, class _Tp, class _Ap>
class _LIBCPP_DEPRECATED_IN_CXX11 mem_fun1_t : public binary_function<_Tp*, _Ap, _Sp> {
_Sp (_Tp::*__p_)(_Ap);
public:
explicit mem_fun1_t(_Sp (_Tp::*__p)(_Ap)) : __p_(__p) {
}
_Sp operator()(_Tp* __p, _Ap __x) const {
return (__p->*__p_)(__x);
}
};
template <class _Sp, class _Tp>
_LIBCPP_DEPRECATED_IN_CXX11 inline mem_fun_t<_Sp, _Tp> mem_fun(_Sp (_Tp::*__f)()) {
return mem_fun_t<_Sp, _Tp>(__f);
}
template <class _Sp, class _Tp, class _Ap>
_LIBCPP_DEPRECATED_IN_CXX11 inline mem_fun1_t<_Sp, _Tp, _Ap> mem_fun(_Sp (_Tp::*__f)(_Ap)) {
return mem_fun1_t<_Sp, _Tp, _Ap>(__f);
}
template <class _Sp, class _Tp>
class _LIBCPP_DEPRECATED_IN_CXX11 mem_fun_ref_t : public unary_function<_Tp, _Sp> {
_Sp (_Tp::*__p_)();
public:
explicit mem_fun_ref_t(_Sp (_Tp::*__p)()) : __p_(__p) {
}
_Sp operator()(_Tp& __p) const {
return (__p.*__p_)();
}
};
template <class _Sp, class _Tp, class _Ap>
class _LIBCPP_DEPRECATED_IN_CXX11 mem_fun1_ref_t : public binary_function<_Tp, _Ap, _Sp> {
_Sp (_Tp::*__p_)(_Ap);
public:
explicit mem_fun1_ref_t(_Sp (_Tp::*__p)(_Ap)) : __p_(__p) {
}
_Sp operator()(_Tp& __p, _Ap __x) const {
return (__p.*__p_)(__x);
}
};
template <class _Sp, class _Tp>
_LIBCPP_DEPRECATED_IN_CXX11 inline mem_fun_ref_t<_Sp, _Tp> mem_fun_ref(_Sp (_Tp::*__f)()) {
return mem_fun_ref_t<_Sp, _Tp>(__f);
}
template <class _Sp, class _Tp, class _Ap>
_LIBCPP_DEPRECATED_IN_CXX11 inline mem_fun1_ref_t<_Sp, _Tp, _Ap> mem_fun_ref(_Sp (_Tp::*__f)(_Ap)) {
return mem_fun1_ref_t<_Sp, _Tp, _Ap>(__f);
}
template <class _Sp, class _Tp>
class _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun_t : public unary_function<const _Tp*, _Sp> {
_Sp (_Tp::*__p_)() const;
public:
explicit const_mem_fun_t(_Sp (_Tp::*__p)() const) : __p_(__p) {
}
_Sp operator()(const _Tp* __p) const {
return (__p->*__p_)();
}
};
template <class _Sp, class _Tp, class _Ap>
class _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun1_t : public binary_function<const _Tp*, _Ap, _Sp> {
_Sp (_Tp::*__p_)(_Ap) const;
public:
explicit const_mem_fun1_t(_Sp (_Tp::*__p)(_Ap) const) : __p_(__p) {
}
_Sp operator()(const _Tp* __p, _Ap __x) const {
return (__p->*__p_)(__x);
}
};
template <class _Sp, class _Tp>
_LIBCPP_DEPRECATED_IN_CXX11 inline const_mem_fun_t<_Sp, _Tp> mem_fun(_Sp (_Tp::*__f)() const) {
return const_mem_fun_t<_Sp, _Tp>(__f);
}
template <class _Sp, class _Tp, class _Ap>
_LIBCPP_DEPRECATED_IN_CXX11 inline const_mem_fun1_t<_Sp, _Tp, _Ap> mem_fun(_Sp (_Tp::*__f)(_Ap) const) {
return const_mem_fun1_t<_Sp, _Tp, _Ap>(__f);
}
template <class _Sp, class _Tp>
class _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun_ref_t : public unary_function<_Tp, _Sp> {
_Sp (_Tp::*__p_)() const;
public:
explicit const_mem_fun_ref_t(_Sp (_Tp::*__p)() const) : __p_(__p) {
}
_Sp operator()(const _Tp& __p) const {
return (__p.*__p_)();
}
};
template <class _Sp, class _Tp, class _Ap>
class _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun1_ref_t : public binary_function<_Tp, _Ap, _Sp> {
_Sp (_Tp::*__p_)(_Ap) const;
public:
explicit const_mem_fun1_ref_t(_Sp (_Tp::*__p)(_Ap) const) : __p_(__p) {
}
_Sp operator()(const _Tp& __p, _Ap __x) const {
return (__p.*__p_)(__x);
}
};
template <class _Sp, class _Tp>
_LIBCPP_DEPRECATED_IN_CXX11 inline const_mem_fun_ref_t<_Sp, _Tp> mem_fun_ref(_Sp (_Tp::*__f)() const) {
return const_mem_fun_ref_t<_Sp, _Tp>(__f);
}
template <class _Sp, class _Tp, class _Ap>
_LIBCPP_DEPRECATED_IN_CXX11 inline const_mem_fun1_ref_t<_Sp, _Tp, _Ap> mem_fun_ref(_Sp (_Tp::*__f)(_Ap) const) {
return const_mem_fun1_ref_t<_Sp, _Tp, _Ap>(__f);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// MEMFUN
//==============================================================================
template <class _Tp>
class __mem_fn : public __weak_result_type<_Tp> {
public:
// types
typedef _Tp type;
private:
type __f_;
public:
__mem_fn(type __f) _NOEXCEPT : __f_(__f) {
}
#ifndef _LIBCPP_CXX03_LANG
// invoke
template <class... _ArgTypes>
typename __invoke_return<type, _ArgTypes...>::type operator()(_ArgTypes&&... __args) const {
return __invoke(__f_, _VSTD::forward<_ArgTypes>(__args)...);
}
#else
template <class _A0>
typename __invoke_return0<type, _A0>::type operator()(_A0& __a0) const {
return __invoke(__f_, __a0);
}
template <class _A0>
typename __invoke_return0<type, _A0 const>::type operator()(_A0 const& __a0) const {
return __invoke(__f_, __a0);
}
template <class _A0, class _A1>
typename __invoke_return1<type, _A0, _A1>::type operator()(_A0& __a0, _A1& __a1) const {
return __invoke(__f_, __a0, __a1);
}
template <class _A0, class _A1>
typename __invoke_return1<type, _A0 const, _A1>::type operator()(_A0 const& __a0, _A1& __a1) const {
return __invoke(__f_, __a0, __a1);
}
template <class _A0, class _A1>
typename __invoke_return1<type, _A0, _A1 const>::type operator()(_A0& __a0, _A1 const& __a1) const {
return __invoke(__f_, __a0, __a1);
}
template <class _A0, class _A1>
typename __invoke_return1<type, _A0 const, _A1 const>::type operator()(_A0 const& __a0, _A1 const& __a1) const {
return __invoke(__f_, __a0, __a1);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0, _A1, _A2>::type operator()(_A0& __a0, _A1& __a1, _A2& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0 const, _A1, _A2>::type operator()(_A0 const& __a0, _A1& __a1,
_A2& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0, _A1 const, _A2>::type operator()(_A0& __a0, _A1 const& __a1,
_A2& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0, _A1, _A2 const>::type operator()(_A0& __a0, _A1& __a1,
_A2 const& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0 const, _A1 const, _A2>::type operator()(_A0 const& __a0, _A1 const& __a1,
_A2& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0 const, _A1, _A2 const>::type operator()(_A0 const& __a0, _A1& __a1,
_A2 const& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0, _A1 const, _A2 const>::type operator()(_A0& __a0, _A1 const& __a1,
_A2 const& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
template <class _A0, class _A1, class _A2>
typename __invoke_return2<type, _A0 const, _A1 const, _A2 const>::type operator()(_A0 const& __a0,
_A1 const& __a1,
_A2 const& __a2) const {
return __invoke(__f_, __a0, __a1, __a2);
}
#endif
};
template <class _Rp, class _Tp>
inline __mem_fn<_Rp _Tp::*> mem_fn(_Rp _Tp::*__pm) _NOEXCEPT {
return __mem_fn<_Rp _Tp::*>(__pm);
}
////////////////////////////////////////////////////////////////////////////////
// FUNCTION
//==============================================================================
// bad_function_call
class _LIBCPP_EXCEPTION_ABI bad_function_call : public exception {
#ifdef _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION
public:
virtual ~bad_function_call() _NOEXCEPT;
virtual const char* what() const _NOEXCEPT;
#endif
};
_LIBCPP_NORETURN inline void __throw_bad_function_call() {
#ifndef _LIBCPP_NO_EXCEPTIONS
throw bad_function_call();
#else
_VSTD::abort();
#endif
}
template <class _Fp>
class function; // undefined
namespace __function {
template <class _Rp>
struct __maybe_derive_from_unary_function {};
template <class _Rp, class _A1>
struct __maybe_derive_from_unary_function<_Rp(_A1)> : public unary_function<_A1, _Rp> {};
template <class _Rp>
struct __maybe_derive_from_binary_function {};
template <class _Rp, class _A1, class _A2>
struct __maybe_derive_from_binary_function<_Rp(_A1, _A2)> : public binary_function<_A1, _A2, _Rp> {};
template <class _Fp>
bool __not_null(_Fp const&) {
return true;
}
template <class _Fp>
bool __not_null(_Fp* __ptr) {
return __ptr;
}
template <class _Ret, class _Class>
bool __not_null(_Ret _Class::*__ptr) {
return __ptr;
}
template <class _Fp>
bool __not_null(function<_Fp> const& __f) {
return !!__f;
}
} // namespace __function
#ifndef _LIBCPP_CXX03_LANG
namespace __function {
// __alloc_func holds a functor and an allocator.
template <class _Fp, class _Ap, class _FB>
class __alloc_func;
template <class _Fp, class _Ap, class _Rp, class... _ArgTypes>
class __alloc_func<_Fp, _Ap, _Rp(_ArgTypes...)> {
__compressed_pair<_Fp, _Ap> __f_;
public:
typedef _Fp _Target;
typedef _Ap _Alloc;
const _Target& __target() const {
return __f_.first();
}
const _Alloc& __allocator() const {
return __f_.second();
}
explicit __alloc_func(_Target&& __f)
: __f_(piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__f)), _VSTD::forward_as_tuple()) {
}
explicit __alloc_func(const _Target& __f, const _Alloc& __a)
: __f_(piecewise_construct, _VSTD::forward_as_tuple(__f), _VSTD::forward_as_tuple(__a)) {
}
explicit __alloc_func(const _Target& __f, _Alloc&& __a)
: __f_(piecewise_construct, _VSTD::forward_as_tuple(__f), _VSTD::forward_as_tuple(_VSTD::move(__a))) {
}
explicit __alloc_func(_Target&& __f, _Alloc&& __a)
: __f_(piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__f)),
_VSTD::forward_as_tuple(_VSTD::move(__a))) {
}
_Rp operator()(_ArgTypes&&... __arg) {
typedef __invoke_void_return_wrapper<_Rp> _Invoker;
return _Invoker::__call(__f_.first(), _VSTD::forward<_ArgTypes>(__arg)...);
}
__alloc_func* __clone() const {
typedef allocator_traits<_Alloc> __alloc_traits;
typedef typename __rebind_alloc_helper<__alloc_traits, __alloc_func>::type _AA;
_AA __a(__f_.second());
typedef __allocator_destructor<_AA> _Dp;
unique_ptr<__alloc_func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
::new ((void*)__hold.get()) __alloc_func(__f_.first(), _Alloc(__a));
return __hold.release();
}
void destroy() _NOEXCEPT {
__f_.~__compressed_pair<_Target, _Alloc>();
}
};
// __base provides an abstract interface for copyable functors.
template <class _Fp>
class __base;
template <class _Rp, class... _ArgTypes>
class __base<_Rp(_ArgTypes...)> {
__base(const __base&);
__base& operator=(const __base&);
public:
__base() {
}
virtual ~__base() {
}
virtual __base* __clone() const = 0;
virtual void __clone(__base*) const = 0;
virtual void destroy() _NOEXCEPT = 0;
virtual void destroy_deallocate() _NOEXCEPT = 0;
virtual _Rp operator()(_ArgTypes&&...) = 0;
# ifndef _LIBCPP_NO_RTTI
virtual const void* target(const type_info&) const _NOEXCEPT = 0;
virtual const std::type_info& target_type() const _NOEXCEPT = 0;
# endif // _LIBCPP_NO_RTTI
};
// __func implements __base for a given functor type.
template <class _FD, class _Alloc, class _FB>
class __func;
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
class __func<_Fp, _Alloc, _Rp(_ArgTypes...)> : public __base<_Rp(_ArgTypes...)> {
__alloc_func<_Fp, _Alloc, _Rp(_ArgTypes...)> __f_;
public:
explicit __func(_Fp&& __f) : __f_(_VSTD::move(__f)) {
}
explicit __func(const _Fp& __f, const _Alloc& __a) : __f_(__f, __a) {
}
explicit __func(const _Fp& __f, _Alloc&& __a) : __f_(__f, _VSTD::move(__a)) {
}
explicit __func(_Fp&& __f, _Alloc&& __a) : __f_(_VSTD::move(__f), _VSTD::move(__a)) {
}
virtual __base<_Rp(_ArgTypes...)>* __clone() const;
virtual void __clone(__base<_Rp(_ArgTypes...)>*) const;
virtual void destroy() _NOEXCEPT;
virtual void destroy_deallocate() _NOEXCEPT;
virtual _Rp operator()(_ArgTypes&&... __arg);
# ifndef _LIBCPP_NO_RTTI
virtual const void* target(const type_info&) const _NOEXCEPT;
virtual const std::type_info& target_type() const _NOEXCEPT;
# endif // _LIBCPP_NO_RTTI
};
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
__base<_Rp(_ArgTypes...)>* __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__clone() const {
typedef allocator_traits<_Alloc> __alloc_traits;
typedef typename __rebind_alloc_helper<__alloc_traits, __func>::type _Ap;
_Ap __a(__f_.__allocator());
typedef __allocator_destructor<_Ap> _Dp;
unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
::new ((void*)__hold.get()) __func(__f_.__target(), _Alloc(__a));
return __hold.release();
}
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
void __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__clone(__base<_Rp(_ArgTypes...)>* __p) const {
::new (__p) __func(__f_.__target(), __f_.__allocator());
}
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
void __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy() _NOEXCEPT {
__f_.destroy();
}
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
void __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy_deallocate() _NOEXCEPT {
typedef allocator_traits<_Alloc> __alloc_traits;
typedef typename __rebind_alloc_helper<__alloc_traits, __func>::type _Ap;
_Ap __a(__f_.__allocator());
__f_.destroy();
__a.deallocate(this, 1);
}
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
_Rp __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::operator()(_ArgTypes&&... __arg) {
return __f_(_VSTD::forward<_ArgTypes>(__arg)...);
}
# ifndef _LIBCPP_NO_RTTI
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
const void* __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target(const type_info& __ti) const _NOEXCEPT {
if (__ti == typeid(_Fp))
return &__f_.__target();
return (const void*)0;
}
template <class _Fp, class _Alloc, class _Rp, class... _ArgTypes>
const std::type_info& __func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target_type() const _NOEXCEPT {
return typeid(_Fp);
}
# endif // _LIBCPP_NO_RTTI
// __value_func creates a value-type from a __func.
template <class _Fp>
class __value_func;
template <class _Rp, class... _ArgTypes>
class __value_func<_Rp(_ArgTypes...)> {
typename aligned_storage<3 * sizeof(void*)>::type __buf_;
typedef __base<_Rp(_ArgTypes...)> __func;
__func* __f_;
_LIBCPP_NO_CFI static __func* __as_base(void* p) {
return reinterpret_cast<__func*>(p);
}
public:
__value_func() _NOEXCEPT : __f_(0) {
}
template <class _Fp, class _Alloc>
__value_func(_Fp&& __f, const _Alloc __a) : __f_(0) {
typedef allocator_traits<_Alloc> __alloc_traits;
typedef __function::__func<_Fp, _Alloc, _Rp(_ArgTypes...)> _Fun;
typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type _FunAlloc;
if (__function::__not_null(__f)) {
_FunAlloc __af(__a);
if (sizeof(_Fun) <= sizeof(__buf_) && is_nothrow_copy_constructible<_Fp>::value &&
is_nothrow_copy_constructible<_FunAlloc>::value) {
__f_ = ::new ((void*)&__buf_) _Fun(_VSTD::move(__f), _Alloc(__af));
} else {
typedef __allocator_destructor<_FunAlloc> _Dp;
unique_ptr<__func, _Dp> __hold(__af.allocate(1), _Dp(__af, 1));
::new ((void*)__hold.get()) _Fun(_VSTD::move(__f), _Alloc(__a));
__f_ = __hold.release();
}
}
}
__value_func(const __value_func& __f) {
if (__f.__f_ == 0)
__f_ = 0;
else if ((void*)__f.__f_ == &__f.__buf_) {
__f_ = __as_base(&__buf_);
__f.__f_->__clone(__f_);
} else
__f_ = __f.__f_->__clone();
}
__value_func(__value_func&& __f) _NOEXCEPT {
if (__f.__f_ == 0)
__f_ = 0;
else if ((void*)__f.__f_ == &__f.__buf_) {
__f_ = __as_base(&__buf_);
__f.__f_->__clone(__f_);
} else {
__f_ = __f.__f_;
__f.__f_ = 0;
}
}
~__value_func() {
if ((void*)__f_ == &__buf_)
__f_->destroy();
else if (__f_)
__f_->destroy_deallocate();
}
__value_func& operator=(__value_func&& __f) {
*this = nullptr;
if (__f.__f_ == 0)
__f_ = 0;
else if ((void*)__f.__f_ == &__f.__buf_) {
__f_ = __as_base(&__buf_);
__f.__f_->__clone(__f_);
} else {
__f_ = __f.__f_;
__f.__f_ = 0;
}
return *this;
}
__value_func& operator=(std::nullptr_t) {
__func* __f = __f_;
__f_ = 0;
if ((void*)__f == &__buf_)
__f->destroy();
else if (__f)
__f->destroy_deallocate();
return *this;
}
_Rp operator()(_ArgTypes&&... __args) const {
if (__f_ == 0)
__throw_bad_function_call();
return (*__f_)(_VSTD::forward<_ArgTypes>(__args)...);
}
void swap(__value_func& __f) _NOEXCEPT {
if (&__f == this)
return;
if ((void*)__f_ == &__buf_ && (void*)__f.__f_ == &__f.__buf_) {
typename aligned_storage<sizeof(__buf_)>::type __tempbuf;
__func* __t = __as_base(&__tempbuf);
__f_->__clone(__t);
__f_->destroy();
__f_ = 0;
__f.__f_->__clone(__as_base(&__buf_));
__f.__f_->destroy();
__f.__f_ = 0;
__f_ = __as_base(&__buf_);
__t->__clone(__as_base(&__f.__buf_));
__t->destroy();
__f.__f_ = __as_base(&__f.__buf_);
} else if ((void*)__f_ == &__buf_) {
__f_->__clone(__as_base(&__f.__buf_));
__f_->destroy();
__f_ = __f.__f_;
__f.__f_ = __as_base(&__f.__buf_);
} else if ((void*)__f.__f_ == &__f.__buf_) {
__f.__f_->__clone(__as_base(&__buf_));
__f.__f_->destroy();
__f.__f_ = __f_;
__f_ = __as_base(&__buf_);
} else
_VSTD::swap(__f_, __f.__f_);
}
_LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {
return __f_ != 0;
}
# ifndef _LIBCPP_NO_RTTI
const std::type_info& target_type() const _NOEXCEPT {
if (__f_ == 0)
return typeid(void);
return __f_->target_type();
}
template <typename _Tp>
const _Tp* target() const _NOEXCEPT {
if (__f_ == 0)
return 0;
return (const _Tp*)__f_->target(typeid(_Tp));
}
# endif // _LIBCPP_NO_RTTI
};
// Storage for a functor object, to be used with __policy to manage copy and
// destruction.
union __policy_storage {
mutable char __small[sizeof(void*) * 2];
void* __large;
};
// True if _Fun can safely be held in __policy_storage.__small.
template <typename _Fun>
struct __use_small_storage
: public _VSTD::integral_constant<bool, sizeof(_Fun) <= sizeof(__policy_storage) &&
_LIBCPP_ALIGNOF(_Fun) <= _LIBCPP_ALIGNOF(__policy_storage) &&
_VSTD::is_trivially_copy_constructible<_Fun>::value &&
_VSTD::is_trivially_destructible<_Fun>::value> {};
// Policy contains information about how to copy, destroy, and move the
// underlying functor. You can think of it as a vtable of sorts.
struct __policy {
// Used to copy or destroy __large values. null for trivial objects.
void* (*const __clone)(const void*);
void (*const __destroy)(void*);
// True if this is the null policy (no value).
const bool __is_null;
// The target type. May be null if RTTI is disabled.
const std::type_info* const __type_info;
// Returns a pointer to a static policy object suitable for the functor
// type.
template <typename _Fun>
static const __policy* __create() {
return __choose_policy<_Fun>(__use_small_storage<_Fun>());
}
static const __policy* __create_empty() {
static const _LIBCPP_CONSTEXPR __policy __policy_ = {nullptr, nullptr, true,
# ifndef _LIBCPP_NO_RTTI
&typeid(void)
# else
nullptr
# endif
};
return &__policy_;
}
private:
template <typename _Fun>
static void* __large_clone(const void* __s) {
const _Fun* __f = static_cast<const _Fun*>(__s);
return __f->__clone();
}
template <typename _Fun>
static void __large_destroy(void* __s) {
typedef allocator_traits<typename _Fun::_Alloc> __alloc_traits;
typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type _FunAlloc;
_Fun* __f = static_cast<_Fun*>(__s);
_FunAlloc __a(__f->__allocator());
__f->destroy();
__a.deallocate(__f, 1);
}
template <typename _Fun>
static const __policy* __choose_policy(/* is_small = */ false_type) {
static const _LIBCPP_CONSTEXPR __policy __policy_ = {&__large_clone<_Fun>, &__large_destroy<_Fun>,
false,
# ifndef _LIBCPP_NO_RTTI
&typeid(typename _Fun::_Target)
# else
nullptr
# endif
};
return &__policy_;
}
template <typename _Fun>
static const __policy* __choose_policy(/* is_small = */ true_type) {
static const _LIBCPP_CONSTEXPR __policy __policy_ = {nullptr, nullptr, false,
# ifndef _LIBCPP_NO_RTTI
&typeid(typename _Fun::_Target)
# else
nullptr
# endif
};
return &__policy_;
}
};
// Used to choose between perfect forwarding or pass-by-value. Pass-by-value is
// faster for types that can be passed in registers.
template <typename _Tp>
using __fast_forward = typename _VSTD::conditional<_VSTD::is_scalar<_Tp>::value, _Tp, _Tp&&>::type;
// __policy_invoker calls an instance of __alloc_func held in __policy_storage.
template <class _Fp>
struct __policy_invoker;
template <class _Rp, class... _ArgTypes>
struct __policy_invoker<_Rp(_ArgTypes...)> {
typedef _Rp (*__Call)(const __policy_storage*, __fast_forward<_ArgTypes>...);
__Call __call_;
// Creates an invoker that throws bad_function_call.
__policy_invoker() : __call_(&__call_empty) {
}
// Creates an invoker that calls the given instance of __func.
template <typename _Fun>
static __policy_invoker __create() {
return __policy_invoker(&__call_impl<_Fun>);
}
private:
explicit __policy_invoker(__Call __c) : __call_(__c) {
}
static _Rp __call_empty(const __policy_storage*, __fast_forward<_ArgTypes>...) {
__throw_bad_function_call();
}
template <typename _Fun>
static _Rp __call_impl(const __policy_storage* __buf, __fast_forward<_ArgTypes>... __args) {
_Fun* __f =
reinterpret_cast<_Fun*>(__use_small_storage<_Fun>::value ? &__buf->__small : __buf->__large);
return (*__f)(_VSTD::forward<_ArgTypes>(__args)...);
}
};
// __policy_func uses a __policy and __policy_invoker to create a type-erased,
// copyable functor.
template <class _Fp>
class __policy_func;
template <class _Rp, class... _ArgTypes>
class __policy_func<_Rp(_ArgTypes...)> {
// Inline storage for small objects.
__policy_storage __buf_;
// Calls the value stored in __buf_. This could technically be part of
// policy, but storing it here eliminates a level of indirection inside
// operator().
typedef __function::__policy_invoker<_Rp(_ArgTypes...)> __invoker;
__invoker __invoker_;
// The policy that describes how to move / copy / destroy __buf_. Never
// null, even if the function is empty.
const __policy* __policy_;
public:
__policy_func() : __policy_(__policy::__create_empty()) {
}
template <class _Fp, class _Alloc>
__policy_func(_Fp&& __f, const _Alloc& __a) : __policy_(__policy::__create_empty()) {
typedef __alloc_func<_Fp, _Alloc, _Rp(_ArgTypes...)> _Fun;
typedef allocator_traits<_Alloc> __alloc_traits;
typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type _FunAlloc;
if (__function::__not_null(__f)) {
__invoker_ = __invoker::template __create<_Fun>();
__policy_ = __policy::__create<_Fun>();
_FunAlloc __af(__a);
if (__use_small_storage<_Fun>()) {
::new ((void*)&__buf_.__small) _Fun(_VSTD::move(__f), _Alloc(__af));
} else {
typedef __allocator_destructor<_FunAlloc> _Dp;
unique_ptr<_Fun, _Dp> __hold(__af.allocate(1), _Dp(__af, 1));
::new ((void*)__hold.get()) _Fun(_VSTD::move(__f), _Alloc(__af));
__buf_.__large = __hold.release();
}
}
}
__policy_func(const __policy_func& __f)
: __buf_(__f.__buf_), __invoker_(__f.__invoker_), __policy_(__f.__policy_) {
if (__policy_->__clone)
__buf_.__large = __policy_->__clone(__f.__buf_.__large);
}
__policy_func(__policy_func&& __f)
: __buf_(__f.__buf_), __invoker_(__f.__invoker_), __policy_(__f.__policy_) {
if (__policy_->__destroy) {
__f.__policy_ = __policy::__create_empty();
__f.__invoker_ = __invoker();
}
}
~__policy_func() {
if (__policy_->__destroy)
__policy_->__destroy(__buf_.__large);
}
__policy_func& operator=(__policy_func&& __f) {
*this = nullptr;
__buf_ = __f.__buf_;
__invoker_ = __f.__invoker_;
__policy_ = __f.__policy_;
__f.__policy_ = __policy::__create_empty();
__f.__invoker_ = __invoker();
return *this;
}
__policy_func& operator=(std::nullptr_t) {
const __policy* __p = __policy_;
__policy_ = __policy::__create_empty();
__invoker_ = __invoker();
if (__p->__destroy)
__p->__destroy(__buf_.__large);
return *this;
}
_Rp operator()(_ArgTypes&&... __args) const {
return __invoker_.__call_(_VSTD::addressof(__buf_), _VSTD::forward<_ArgTypes>(__args)...);
}
void swap(__policy_func& __f) {
_VSTD::swap(__invoker_, __f.__invoker_);
_VSTD::swap(__policy_, __f.__policy_);
_VSTD::swap(__buf_, __f.__buf_);
}
explicit operator bool() const _NOEXCEPT {
return !__policy_->__is_null;
}
# ifndef _LIBCPP_NO_RTTI
const std::type_info& target_type() const _NOEXCEPT {
return *__policy_->__type_info;
}
template <typename _Tp>
const _Tp* target() const _NOEXCEPT {
if (__policy_->__is_null || typeid(_Tp) != *__policy_->__type_info)
return nullptr;
if (__policy_->__clone) // Out of line storage.
return reinterpret_cast<const _Tp*>(__buf_.__large);
else
return reinterpret_cast<const _Tp*>(&__buf_.__small);
}
# endif // _LIBCPP_NO_RTTI
};
} // namespace __function
template <class _Rp, class... _ArgTypes>
class function<_Rp(_ArgTypes...)> : public __function::__maybe_derive_from_unary_function<_Rp(_ArgTypes...)>,
public __function::__maybe_derive_from_binary_function<_Rp(_ArgTypes...)> {
# ifndef _LIBCPP_ABI_OPTIMIZED_FUNCTION
typedef __function::__value_func<_Rp(_ArgTypes...)> __func;
# else
typedef __function::__policy_func<_Rp(_ArgTypes...)> __func;
# endif
__func __f_;
template <class _Fp, bool = __lazy_and<integral_constant<bool, !is_same<__uncvref_t<_Fp>, function>::value>,
__invokable<_Fp&, _ArgTypes...>>::value>
struct __callable;
template <class _Fp>
struct __callable<_Fp, true> {
static const bool value =
is_same<void, _Rp>::value || is_convertible<typename __invoke_of<_Fp&, _ArgTypes...>::type, _Rp>::value;
};
template <class _Fp>
struct __callable<_Fp, false> {
static const bool value = false;
};
template <class _Fp>
using _EnableIfCallable = typename enable_if<__callable<_Fp>::value>::type;
public:
typedef _Rp result_type;
// construct/copy/destroy:
function() _NOEXCEPT {
}
function(std::nullptr_t) _NOEXCEPT {
}
function(const function&);
function(function&&) _NOEXCEPT;
template <class _Fp, class = _EnableIfCallable<_Fp>>
function(_Fp);
# if _LIBCPP_STD_VER <= 14
template <class _Alloc>
function(allocator_arg_t, const _Alloc&) _NOEXCEPT {
}
template <class _Alloc>
function(allocator_arg_t, const _Alloc&, std::nullptr_t) _NOEXCEPT {
}
template <class _Alloc>
function(allocator_arg_t, const _Alloc&, const function&);
template <class _Alloc>
function(allocator_arg_t, const _Alloc&, function&&);
template <class _Fp, class _Alloc, class = _EnableIfCallable<_Fp>>
function(allocator_arg_t, const _Alloc& __a, _Fp __f);
# endif
function& operator=(const function&);
function& operator=(function&&) _NOEXCEPT;
function& operator=(std::nullptr_t) _NOEXCEPT;
template <class _Fp, class = _EnableIfCallable<_Fp>>
function& operator=(_Fp&&);
~function();
// function modifiers:
void swap(function&) _NOEXCEPT;
# if _LIBCPP_STD_VER <= 14
template <class _Fp, class _Alloc>
void assign(_Fp&& __f, const _Alloc& __a) {
function(allocator_arg, __a, _VSTD::forward<_Fp>(__f)).swap(*this);
}
# endif
// function capacity:
_LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {
return static_cast<bool>(__f_);
}
// deleted overloads close possible hole in the type system
template <class _R2, class... _ArgTypes2>
bool operator==(const function<_R2(_ArgTypes2...)>&) const = delete;
template <class _R2, class... _ArgTypes2>
bool operator!=(const function<_R2(_ArgTypes2...)>&) const = delete;
public:
// function invocation:
_Rp operator()(_ArgTypes...) const;
# ifndef _LIBCPP_NO_RTTI
// function target access:
const std::type_info& target_type() const _NOEXCEPT;
template <typename _Tp>
_Tp* target() _NOEXCEPT;
template <typename _Tp>
const _Tp* target() const _NOEXCEPT;
# endif // _LIBCPP_NO_RTTI
};
template <class _Rp, class... _ArgTypes>
function<_Rp(_ArgTypes...)>::function(const function& __f) : __f_(__f.__f_) {
}
# if _LIBCPP_STD_VER <= 14
template <class _Rp, class... _ArgTypes>
template <class _Alloc>
function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc&, const function& __f) : __f_(__f.__f_) {
}
# endif
template <class _Rp, class... _ArgTypes>
function<_Rp(_ArgTypes...)>::function(function&& __f) _NOEXCEPT : __f_(_VSTD::move(__f.__f_)) {
}
# if _LIBCPP_STD_VER <= 14
template <class _Rp, class... _ArgTypes>
template <class _Alloc>
function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc&, function&& __f)
: __f_(_VSTD::move(__f.__f_)) {
}
# endif
template <class _Rp, class... _ArgTypes>
template <class _Fp, class>
function<_Rp(_ArgTypes...)>::function(_Fp __f) : __f_(_VSTD::move(__f), allocator<_Fp>()) {
}
# if _LIBCPP_STD_VER <= 14
template <class _Rp, class... _ArgTypes>
template <class _Fp, class _Alloc, class>
function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc& __a, _Fp __f) : __f_(_VSTD::move(__f), __a) {
}
# endif
template <class _Rp, class... _ArgTypes>
function<_Rp(_ArgTypes...)>& function<_Rp(_ArgTypes...)>::operator=(const function& __f) {
function(__f).swap(*this);
return *this;
}
template <class _Rp, class... _ArgTypes>
function<_Rp(_ArgTypes...)>& function<_Rp(_ArgTypes...)>::operator=(function&& __f) _NOEXCEPT {
__f_ = std::move(__f.__f_);
return *this;
}
template <class _Rp, class... _ArgTypes>
function<_Rp(_ArgTypes...)>& function<_Rp(_ArgTypes...)>::operator=(std::nullptr_t) _NOEXCEPT {
__f_ = nullptr;
return *this;
}
template <class _Rp, class... _ArgTypes>
template <class _Fp, class>
function<_Rp(_ArgTypes...)>& function<_Rp(_ArgTypes...)>::operator=(_Fp&& __f) {
function(_VSTD::forward<_Fp>(__f)).swap(*this);
return *this;
}
template <class _Rp, class... _ArgTypes>
function<_Rp(_ArgTypes...)>::~function() {
}
template <class _Rp, class... _ArgTypes>
void function<_Rp(_ArgTypes...)>::swap(function& __f) _NOEXCEPT {
__f_.swap(__f.__f_);
}
template <class _Rp, class... _ArgTypes>
_Rp function<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __arg) const {
return __f_(_VSTD::forward<_ArgTypes>(__arg)...);
}
# ifndef _LIBCPP_NO_RTTI
template <class _Rp, class... _ArgTypes>
const std::type_info& function<_Rp(_ArgTypes...)>::target_type() const _NOEXCEPT {
return __f_.target_type();
}
template <class _Rp, class... _ArgTypes>
template <typename _Tp>
_Tp* function<_Rp(_ArgTypes...)>::target() _NOEXCEPT {
return (_Tp*)(__f_.template target<_Tp>());
}
template <class _Rp, class... _ArgTypes>
template <typename _Tp>
const _Tp* function<_Rp(_ArgTypes...)>::target() const _NOEXCEPT {
return __f_.template target<_Tp>();
}
# endif // _LIBCPP_NO_RTTI
template <class _Rp, class... _ArgTypes>
inline bool operator==(const function<_Rp(_ArgTypes...)>& __f, std::nullptr_t) _NOEXCEPT {
return !__f;
}
template <class _Rp, class... _ArgTypes>
inline bool operator==(std::nullptr_t, const function<_Rp(_ArgTypes...)>& __f) _NOEXCEPT {
return !__f;
}
template <class _Rp, class... _ArgTypes>
inline bool operator!=(const function<_Rp(_ArgTypes...)>& __f, std::nullptr_t) _NOEXCEPT {
return (bool)__f;
}
template <class _Rp, class... _ArgTypes>
inline bool operator!=(std::nullptr_t, const function<_Rp(_ArgTypes...)>& __f) _NOEXCEPT {
return (bool)__f;
}
template <class _Rp, class... _ArgTypes>
inline void swap(function<_Rp(_ArgTypes...)>& __x, function<_Rp(_ArgTypes...)>& __y) _NOEXCEPT {
return __x.swap(__y);
}
#else // _LIBCPP_CXX03_LANG
# include <__functional_03>
#endif
////////////////////////////////////////////////////////////////////////////////
// BIND
//==============================================================================
template <class _Tp>
struct __is_bind_expression : public false_type {};
template <class _Tp>
struct is_bind_expression : public __is_bind_expression<typename remove_cv<_Tp>::type> {};
#if _LIBCPP_STD_VER > 14
template <class _Tp>
_LIBCPP_INLINE_VAR constexpr size_t is_bind_expression_v = is_bind_expression<_Tp>::value;
#endif
template <class _Tp>
struct __is_placeholder : public integral_constant<int, 0> {};
template <class _Tp>
struct is_placeholder : public __is_placeholder<typename remove_cv<_Tp>::type> {};
#if _LIBCPP_STD_VER > 14
template <class _Tp>
_LIBCPP_INLINE_VAR constexpr size_t is_placeholder_v = is_placeholder<_Tp>::value;
#endif
namespace placeholders {
template <int _Np>
struct __ph {};
#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
_LIBCPP_FUNC_VIS extern const __ph<1> _1;
_LIBCPP_FUNC_VIS extern const __ph<2> _2;
_LIBCPP_FUNC_VIS extern const __ph<3> _3;
_LIBCPP_FUNC_VIS extern const __ph<4> _4;
_LIBCPP_FUNC_VIS extern const __ph<5> _5;
_LIBCPP_FUNC_VIS extern const __ph<6> _6;
_LIBCPP_FUNC_VIS extern const __ph<7> _7;
_LIBCPP_FUNC_VIS extern const __ph<8> _8;
_LIBCPP_FUNC_VIS extern const __ph<9> _9;
_LIBCPP_FUNC_VIS extern const __ph<10> _10;
#else
/* _LIBCPP_INLINE_VAR */ constexpr __ph<1> _1{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<2> _2{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<3> _3{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<4> _4{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<5> _5{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<6> _6{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<7> _7{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<8> _8{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<9> _9{};
/* _LIBCPP_INLINE_VAR */ constexpr __ph<10> _10{};
#endif // defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
} // namespace placeholders
template <int _Np>
struct __is_placeholder<placeholders::__ph<_Np>> : public integral_constant<int, _Np> {};
#ifndef _LIBCPP_CXX03_LANG
template <class _Tp, class _Uj>
inline _Tp& __mu(reference_wrapper<_Tp> __t, _Uj&) {
return __t.get();
}
template <class _Ti, class... _Uj, size_t... _Indx>
inline typename __invoke_of<_Ti&, _Uj...>::type __mu_expand(_Ti& __ti, tuple<_Uj...>& __uj,
__tuple_indices<_Indx...>) {
return __ti(_VSTD::forward<_Uj>(_VSTD::get<_Indx>(__uj))...);
}
template <class _Ti, class... _Uj>
inline typename __lazy_enable_if<is_bind_expression<_Ti>::value, __invoke_of<_Ti&, _Uj...>>::type __mu(
_Ti& __ti, tuple<_Uj...>& __uj) {
typedef typename __make_tuple_indices<sizeof...(_Uj)>::type __indices;
return __mu_expand(__ti, __uj, __indices());
}
template <bool IsPh, class _Ti, class _Uj>
struct __mu_return2 {};
template <class _Ti, class _Uj>
struct __mu_return2<true, _Ti, _Uj> {
typedef typename tuple_element<is_placeholder<_Ti>::value - 1, _Uj>::type type;
};
template <class _Ti, class _Uj>
inline typename enable_if<0 < is_placeholder<_Ti>::value,
typename __mu_return2<0 < is_placeholder<_Ti>::value, _Ti, _Uj>::type>::type
__mu(_Ti&, _Uj& __uj) {
const size_t _Indx = is_placeholder<_Ti>::value - 1;
return _VSTD::forward<typename tuple_element<_Indx, _Uj>::type>(_VSTD::get<_Indx>(__uj));
}
template <class _Ti, class _Uj>
inline typename enable_if<!is_bind_expression<_Ti>::value && is_placeholder<_Ti>::value == 0 &&
!__is_reference_wrapper<_Ti>::value,
_Ti&>::type
__mu(_Ti& __ti, _Uj&) {
return __ti;
}
template <class _Ti, bool IsReferenceWrapper, bool IsBindEx, bool IsPh, class _TupleUj>
struct __mu_return_impl;
template <bool _Invokable, class _Ti, class... _Uj>
struct __mu_return_invokable // false
{
typedef __nat type;
};
template <class _Ti, class... _Uj>
struct __mu_return_invokable<true, _Ti, _Uj...> {
typedef typename __invoke_of<_Ti&, _Uj...>::type type;
};
template <class _Ti, class... _Uj>
struct __mu_return_impl<_Ti, false, true, false, tuple<_Uj...>>
: public __mu_return_invokable<__invokable<_Ti&, _Uj...>::value, _Ti, _Uj...> {};
template <class _Ti, class _TupleUj>
struct __mu_return_impl<_Ti, false, false, true, _TupleUj> {
typedef typename tuple_element<is_placeholder<_Ti>::value - 1, _TupleUj>::type&& type;
};
template <class _Ti, class _TupleUj>
struct __mu_return_impl<_Ti, true, false, false, _TupleUj> {
typedef typename _Ti::type& type;
};
template <class _Ti, class _TupleUj>
struct __mu_return_impl<_Ti, false, false, false, _TupleUj> {
typedef _Ti& type;
};
template <class _Ti, class _TupleUj>
struct __mu_return
: public __mu_return_impl<
_Ti, __is_reference_wrapper<_Ti>::value, is_bind_expression<_Ti>::value,
0 < is_placeholder<_Ti>::value && is_placeholder<_Ti>::value <= tuple_size<_TupleUj>::value, _TupleUj> {};
template <class _Fp, class _BoundArgs, class _TupleUj>
struct __is_valid_bind_return {
static const bool value = false;
};
template <class _Fp, class... _BoundArgs, class _TupleUj>
struct __is_valid_bind_return<_Fp, tuple<_BoundArgs...>, _TupleUj> {
static const bool value = __invokable<_Fp, typename __mu_return<_BoundArgs, _TupleUj>::type...>::value;
};
template <class _Fp, class... _BoundArgs, class _TupleUj>
struct __is_valid_bind_return<_Fp, const tuple<_BoundArgs...>, _TupleUj> {
static const bool value = __invokable<_Fp, typename __mu_return<const _BoundArgs, _TupleUj>::type...>::value;
};
template <class _Fp, class _BoundArgs, class _TupleUj,
bool = __is_valid_bind_return<_Fp, _BoundArgs, _TupleUj>::value>
struct __bind_return;
template <class _Fp, class... _BoundArgs, class _TupleUj>
struct __bind_return<_Fp, tuple<_BoundArgs...>, _TupleUj, true> {
typedef typename __invoke_of<_Fp&, typename __mu_return<_BoundArgs, _TupleUj>::type...>::type type;
};
template <class _Fp, class... _BoundArgs, class _TupleUj>
struct __bind_return<_Fp, const tuple<_BoundArgs...>, _TupleUj, true> {
typedef typename __invoke_of<_Fp&, typename __mu_return<const _BoundArgs, _TupleUj>::type...>::type type;
};
template <class _Fp, class _BoundArgs, size_t... _Indx, class _Args>
inline typename __bind_return<_Fp, _BoundArgs, _Args>::type __apply_functor(_Fp& __f, _BoundArgs& __bound_args,
__tuple_indices<_Indx...>,
_Args&& __args) {
return _VSTD::__invoke(__f, _VSTD::__mu(_VSTD::get<_Indx>(__bound_args), __args)...);
}
template <class _Fp, class... _BoundArgs>
class __bind : public __weak_result_type<typename decay<_Fp>::type> {
protected:
typedef typename decay<_Fp>::type _Fd;
typedef tuple<typename decay<_BoundArgs>::type...> _Td;
private:
_Fd __f_;
_Td __bound_args_;
typedef typename __make_tuple_indices<sizeof...(_BoundArgs)>::type __indices;
public:
template <class _Gp, class... _BA,
class = typename enable_if<is_constructible<_Fd, _Gp>::value &&
!is_same<typename remove_reference<_Gp>::type, __bind>::value>::type>
explicit __bind(_Gp&& __f, _BA&&... __bound_args)
: __f_(_VSTD::forward<_Gp>(__f)), __bound_args_(_VSTD::forward<_BA>(__bound_args)...) {
}
template <class... _Args>
typename __bind_return<_Fd, _Td, tuple<_Args&&...>>::type operator()(_Args&&... __args) {
return _VSTD::__apply_functor(__f_, __bound_args_, __indices(),
tuple<_Args&&...>(_VSTD::forward<_Args>(__args)...));
}
template <class... _Args>
typename __bind_return<const _Fd, const _Td, tuple<_Args&&...>>::type operator()(_Args&&... __args) const {
return _VSTD::__apply_functor(__f_, __bound_args_, __indices(),
tuple<_Args&&...>(_VSTD::forward<_Args>(__args)...));
}
};
template <class _Fp, class... _BoundArgs>
struct __is_bind_expression<__bind<_Fp, _BoundArgs...>> : public true_type {};
template <class _Rp, class _Fp, class... _BoundArgs>
class __bind_r : public __bind<_Fp, _BoundArgs...> {
typedef __bind<_Fp, _BoundArgs...> base;
typedef typename base::_Fd _Fd;
typedef typename base::_Td _Td;
public:
typedef _Rp result_type;
template <class _Gp, class... _BA,
class = typename enable_if<is_constructible<_Fd, _Gp>::value &&
!is_same<typename remove_reference<_Gp>::type, __bind_r>::value>::type>
explicit __bind_r(_Gp&& __f, _BA&&... __bound_args)
: base(_VSTD::forward<_Gp>(__f), _VSTD::forward<_BA>(__bound_args)...) {
}
template <class... _Args>
typename enable_if<
is_convertible<typename __bind_return<_Fd, _Td, tuple<_Args&&...>>::type, result_type>::value ||
is_void<_Rp>::value,
result_type>::type
operator()(_Args&&... __args) {
typedef __invoke_void_return_wrapper<_Rp> _Invoker;
return _Invoker::__call(static_cast<base&>(*this), _VSTD::forward<_Args>(__args)...);
}
template <class... _Args>
typename enable_if<
is_convertible<typename __bind_return<const _Fd, const _Td, tuple<_Args&&...>>::type, result_type>::value ||
is_void<_Rp>::value,
result_type>::type
operator()(_Args&&... __args) const {
typedef __invoke_void_return_wrapper<_Rp> _Invoker;
return _Invoker::__call(static_cast<base const&>(*this), _VSTD::forward<_Args>(__args)...);
}
};
template <class _Rp, class _Fp, class... _BoundArgs>
struct __is_bind_expression<__bind_r<_Rp, _Fp, _BoundArgs...>> : public true_type {};
template <class _Fp, class... _BoundArgs>
inline __bind<_Fp, _BoundArgs...> bind(_Fp&& __f, _BoundArgs&&... __bound_args) {
typedef __bind<_Fp, _BoundArgs...> type;
return type(_VSTD::forward<_Fp>(__f), _VSTD::forward<_BoundArgs>(__bound_args)...);
}
template <class _Rp, class _Fp, class... _BoundArgs>
inline __bind_r<_Rp, _Fp, _BoundArgs...> bind(_Fp&& __f, _BoundArgs&&... __bound_args) {
typedef __bind_r<_Rp, _Fp, _BoundArgs...> type;
return type(_VSTD::forward<_Fp>(__f), _VSTD::forward<_BoundArgs>(__bound_args)...);
}
#endif // _LIBCPP_CXX03_LANG
#if _LIBCPP_STD_VER > 14
template <class _Fn, class... _Args>
result_of_t<_Fn && (_Args && ...)> invoke(_Fn&& __f, _Args&&... __args) noexcept(
noexcept(_VSTD::__invoke(_VSTD::forward<_Fn>(__f), _VSTD::forward<_Args>(__args)...))) {
return _VSTD::__invoke(_VSTD::forward<_Fn>(__f), _VSTD::forward<_Args>(__args)...);
}
template <class _DecayFunc>
class __not_fn_imp {
_DecayFunc __fd;
public:
__not_fn_imp() = delete;
template <class... _Args>
auto operator()(_Args&&... __args) &
noexcept(noexcept(!_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...)))
-> decltype(!_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...)) {
return !_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...);
}
template <class... _Args>
auto operator()(_Args&&... __args) &&
noexcept(noexcept(!_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...)))
-> decltype(!_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...)) {
return !_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...);
}
template <class... _Args>
auto operator()(_Args&&... __args) const& noexcept(noexcept(!_VSTD::invoke(__fd,
_VSTD::forward<_Args>(__args)...)))
-> decltype(!_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...)) {
return !_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...);
}
template <class... _Args>
auto operator()(_Args&&... __args) const&& noexcept(noexcept(!_VSTD::invoke(_VSTD::move(__fd),
_VSTD::forward<_Args>(__args)...)))
-> decltype(!_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...)) {
return !_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...);
}
private:
template <class _RawFunc, class = enable_if_t<!is_same<decay_t<_RawFunc>, __not_fn_imp>::value>>
explicit __not_fn_imp(_RawFunc&& __rf) : __fd(_VSTD::forward<_RawFunc>(__rf)) {
}
template <class _RawFunc>
friend inline __not_fn_imp<decay_t<_RawFunc>> not_fn(_RawFunc&&);
};
template <class _RawFunc>
inline __not_fn_imp<decay_t<_RawFunc>> not_fn(_RawFunc&& __fn) {
return __not_fn_imp<decay_t<_RawFunc>>(_VSTD::forward<_RawFunc>(__fn));
}
#endif
// struct hash<T*> in <memory>
template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
pair<_ForwardIterator1, _ForwardIterator1> constexpr __search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2, _ForwardIterator2 __last2,
_BinaryPredicate __pred, forward_iterator_tag,
forward_iterator_tag) {
if (__first2 == __last2)
return make_pair(__first1, __first1); // Everything matches an empty sequence
while (true) {
// Find first element in sequence 1 that matchs *__first2, with a mininum of loop checks
while (true) {
if (__first1 == __last1) // return __last1 if no element matches *__first2
return make_pair(__last1, __last1);
if (__pred(*__first1, *__first2))
break;
++__first1;
}
// *__first1 matches *__first2, now match elements after here
_ForwardIterator1 __m1 = __first1;
_ForwardIterator2 __m2 = __first2;
while (true) {
if (++__m2 == __last2) // If pattern exhausted, __first1 is the answer (works for 1 element pattern)
return make_pair(__first1, __m1);
if (++__m1 == __last1) // Otherwise if source exhaused, pattern not found
return make_pair(__last1, __last1);
if (!__pred(*__m1, *__m2)) // if there is a mismatch, restart with a new __first1
{
++__first1;
break;
} // else there is a match, check next elements
}
}
}
template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
constexpr pair<_RandomAccessIterator1, _RandomAccessIterator1> __search(
_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2,
_RandomAccessIterator2 __last2, _BinaryPredicate __pred, random_access_iterator_tag,
random_access_iterator_tag) {
typedef typename iterator_traits<_RandomAccessIterator1>::difference_type _D1;
typedef typename iterator_traits<_RandomAccessIterator2>::difference_type _D2;
// Take advantage of knowing source and pattern lengths. Stop short when source is smaller than pattern
const _D2 __len2 = __last2 - __first2;
if (__len2 == 0)
return make_pair(__first1, __first1);
const _D1 __len1 = __last1 - __first1;
if (__len1 < __len2)
return make_pair(__last1, __last1);
const _RandomAccessIterator1 __s = __last1 - (__len2 - 1); // Start of pattern match can't go beyond here
while (true) {
while (true) {
if (__first1 == __s)
return make_pair(__last1, __last1);
if (__pred(*__first1, *__first2))
break;
++__first1;
}
_RandomAccessIterator1 __m1 = __first1;
_RandomAccessIterator2 __m2 = __first2;
while (true) {
if (++__m2 == __last2)
return make_pair(__first1, __first1 + __len2);
++__m1; // no need to check range on __m1 because __s guarantees we have enough source
if (!__pred(*__m1, *__m2)) {
++__first1;
break;
}
}
}
}
#if _LIBCPP_STD_VER > 14
// default searcher
template <class _ForwardIterator, class _BinaryPredicate = equal_to<>>
class _LIBCPP_TYPE_VIS default_searcher {
public:
default_searcher(_ForwardIterator __f, _ForwardIterator __l, _BinaryPredicate __p = _BinaryPredicate())
: __first_(__f), __last_(__l), __pred_(__p) {
}
template <typename _ForwardIterator2>
pair<_ForwardIterator2, _ForwardIterator2> operator()(_ForwardIterator2 __f, _ForwardIterator2 __l) const {
return _VSTD::__search(__f, __l, __first_, __last_, __pred_,
typename _VSTD::iterator_traits<_ForwardIterator>::iterator_category(),
typename _VSTD::iterator_traits<_ForwardIterator2>::iterator_category());
}
private:
_ForwardIterator __first_;
_ForwardIterator __last_;
_BinaryPredicate __pred_;
};
#endif // _LIBCPP_STD_VER > 14
#if _LIBCPP_STD_VER > 17
template <class _Tp>
using unwrap_reference_t = typename unwrap_reference<_Tp>::type;
template <class _Tp>
using unwrap_ref_decay_t = typename unwrap_ref_decay<_Tp>::type;
#endif // > C++17
template <class _Container, class _Predicate>
inline void __libcpp_erase_if_container(_Container& __c, _Predicate __pred) {
for (typename _Container::iterator __iter = __c.begin(), __last = __c.end(); __iter != __last;) {
if (__pred(*__iter))
__iter = __c.erase(__iter);
else
++__iter;
}
}
_LIBCPP_END_NAMESPACE_STD
} // namespace GP
#endif // FUNCTIONAL_HPP
| 37.273016 | 120 | 0.579763 | [
"object"
] |
8880bd890c9da7dccf05b2b927fd3524798ed560 | 6,151 | ipp | C++ | src/beast/include/beast/http/impl/basic_headers.ipp | mDuo13/rippled | fbb5a753b19a08daec3e8897a72559a6b2bfeb81 | [
"BSL-1.0"
] | null | null | null | src/beast/include/beast/http/impl/basic_headers.ipp | mDuo13/rippled | fbb5a753b19a08daec3e8897a72559a6b2bfeb81 | [
"BSL-1.0"
] | null | null | null | src/beast/include/beast/http/impl/basic_headers.ipp | mDuo13/rippled | fbb5a753b19a08daec3e8897a72559a6b2bfeb81 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
#ifndef BEAST_HTTP_IMPL_BASIC_HEADERS_IPP
#define BEAST_HTTP_IMPL_BASIC_HEADERS_IPP
#include <beast/type_check.hpp>
namespace beast {
namespace http {
namespace detail {
inline
auto
basic_headers_base::begin() const ->
const_iterator
{
return list_.cbegin();
}
inline
auto
basic_headers_base::end() const ->
const_iterator
{
return list_.cend();
}
inline
auto
basic_headers_base::cbegin() const ->
const_iterator
{
return list_.cbegin();
}
inline
auto
basic_headers_base::cend() const ->
const_iterator
{
return list_.cend();
}
} // detail
//------------------------------------------------------------------------------
template<class Allocator>
void
basic_headers<Allocator>::
delete_all()
{
for(auto it = list_.begin(); it != list_.end();)
{
auto& e = *it++;
e.~element();
alloc_traits::deallocate(
this->member(), &e, 1);
}
}
template<class Allocator>
inline
void
basic_headers<Allocator>::
move_assign(basic_headers& other, std::false_type)
{
if(this->member() != other.member())
{
copy_from(other);
other.clear();
}
else
{
set_ = std::move(other.set_);
list_ = std::move(other.list_);
}
}
template<class Allocator>
inline
void
basic_headers<Allocator>::
move_assign(basic_headers& other, std::true_type)
{
this->member() = std::move(other.member());
set_ = std::move(other.set_);
list_ = std::move(other.list_);
}
template<class Allocator>
inline
void
basic_headers<Allocator>::
copy_assign(basic_headers const& other, std::false_type)
{
copy_from(other);
}
template<class Allocator>
inline
void
basic_headers<Allocator>::
copy_assign(basic_headers const& other, std::true_type)
{
this->member() = other.member();
copy_from(other);
}
//------------------------------------------------------------------------------
template<class Allocator>
basic_headers<Allocator>::
~basic_headers()
{
delete_all();
}
template<class Allocator>
basic_headers<Allocator>::
basic_headers(Allocator const& alloc)
: beast::detail::empty_base_optimization<
alloc_type>(alloc)
{
}
template<class Allocator>
basic_headers<Allocator>::
basic_headers(basic_headers&& other)
: beast::detail::empty_base_optimization<alloc_type>(
std::move(other.member()))
, detail::basic_headers_base(
std::move(other.set_), std::move(other.list_))
{
other.list_.clear();
other.set_.clear();
}
template<class Allocator>
auto
basic_headers<Allocator>::
operator=(basic_headers&& other) ->
basic_headers&
{
if(this == &other)
return *this;
clear();
move_assign(other, std::integral_constant<bool,
alloc_traits::propagate_on_container_move_assignment::value>{});
return *this;
}
template<class Allocator>
basic_headers<Allocator>::
basic_headers(basic_headers const& other)
: basic_headers(alloc_traits::
select_on_container_copy_construction(other.member()))
{
copy_from(other);
}
template<class Allocator>
auto
basic_headers<Allocator>::
operator=(basic_headers const& other) ->
basic_headers&
{
clear();
copy_assign(other, std::integral_constant<bool,
alloc_traits::propagate_on_container_copy_assignment::value>{});
return *this;
}
template<class Allocator>
template<class OtherAlloc>
basic_headers<Allocator>::
basic_headers(basic_headers<OtherAlloc> const& other)
{
copy_from(other);
}
template<class Allocator>
template<class OtherAlloc>
auto
basic_headers<Allocator>::
operator=(basic_headers<OtherAlloc> const& other) ->
basic_headers&
{
clear();
copy_from(other);
return *this;
}
template<class Allocator>
template<class FwdIt>
basic_headers<Allocator>::
basic_headers(FwdIt first, FwdIt last)
{
for(;first != last; ++first)
insert(first->name(), first->value());
}
template<class Allocator>
auto
basic_headers<Allocator>::
find(boost::string_ref const& name) const ->
iterator
{
auto const it = set_.find(name, less{});
if(it == set_.end())
return list_.end();
return list_.iterator_to(*it);
}
template<class Allocator>
boost::string_ref
basic_headers<Allocator>::
operator[](boost::string_ref const& name) const
{
// VFALCO This none object looks sketchy
static boost::string_ref const none;
auto const it = find(name);
if(it == end())
return none;
return it->second;
}
template<class Allocator>
void
basic_headers<Allocator>::
clear() noexcept
{
delete_all();
list_.clear();
set_.clear();
}
template<class Allocator>
std::size_t
basic_headers<Allocator>::
erase(boost::string_ref const& name)
{
auto const it = set_.find(name, less{});
if(it == set_.end())
return 0;
auto& e = *it;
set_.erase(set_.iterator_to(e));
list_.erase(list_.iterator_to(e));
alloc_traits::deallocate(this->member(), &e, 1);
return 1;
}
template<class Allocator>
void
basic_headers<Allocator>::
insert(boost::string_ref const& name,
boost::string_ref const& value)
{
typename set_t::insert_commit_data d;
auto const result =
set_.insert_check(name, less{}, d);
if (result.second)
{
auto const p = alloc_traits::allocate(
this->member(), 1);
alloc_traits::construct(
this->member(), p, name, value);
list_.push_back(*p);
set_.insert_commit(*p, d);
return;
}
// If field already exists, insert comma
// separated value as per RFC2616 section 4.2
auto& cur = result.first->data.second;
cur.reserve(cur.size() + 1 + value.size());
cur.append(1, ',');
cur.append(value.data(), value.size());
}
template<class Allocator>
void
basic_headers<Allocator>::
replace(boost::string_ref const& name,
boost::string_ref const& value)
{
erase(name);
insert(name, value);
}
} // http
} // beast
#endif
| 20.503333 | 80 | 0.659242 | [
"object"
] |
888cf05c06cfcb5bea56e291095a5cc1d746d68e | 16,666 | cpp | C++ | Windows/DiodeAmplifier/Source/PluginProcessor.cpp | landonviator/DiodeAmplifier | c26d9096435dc653687912ca9409888037af4958 | [
"MIT"
] | null | null | null | Windows/DiodeAmplifier/Source/PluginProcessor.cpp | landonviator/DiodeAmplifier | c26d9096435dc653687912ca9409888037af4958 | [
"MIT"
] | null | null | null | Windows/DiodeAmplifier/Source/PluginProcessor.cpp | landonviator/DiodeAmplifier | c26d9096435dc653687912ca9409888037af4958 | [
"MIT"
] | null | null | null | /*
==============================================================================
This file contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
DiodeAmplifierAudioProcessor::DiodeAmplifierAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor (BusesProperties()
#if ! JucePlugin_IsMidiEffect
#if ! JucePlugin_IsSynth
.withInput ("Input", juce::AudioChannelSet::stereo(), true)
#endif
.withOutput ("Output", juce::AudioChannelSet::stereo(), true)
#endif
),
treeState (*this, nullptr, "PARAMETER", createParameterLayout())
#endif
{
treeState.addParameterListener (inputGainSliderId, this);
treeState.addParameterListener (driveSliderId, this);
treeState.addParameterListener (lowSliderId, this);
treeState.addParameterListener (midSliderId, this);
treeState.addParameterListener (highSliderId, this);
treeState.addParameterListener (outputGainSliderId, this);
treeState.addParameterListener (brightId, this);
treeState.addParameterListener (cabId, this);
treeState.addParameterListener (menuId, this);
variableTree = {
"DiodeVariables", {},
{
{ "Group", {{ "name", "DiodeVars" }},
{
{ "Parameter", {{ "id", "file" }, { "value", "/" }}},
{ "Parameter", {{ "id", "root" }, { "value", "/" }}},
{ "Parameter", {{ "id", "cabOffGain" }, { "value", -16.0 }}}
}
}
}
};
variableTree.setProperty("cabOffGain", -16.0, nullptr);
convolutionProcessor.loadImpulseResponse
(BinaryData::metalOne_wav,
BinaryData::metalOne_wavSize,
juce::dsp::Convolution::Stereo::yes,
juce::dsp::Convolution::Trim::yes, 0,
juce::dsp::Convolution::Normalise::yes);
}
DiodeAmplifierAudioProcessor::~DiodeAmplifierAudioProcessor()
{
treeState.removeParameterListener (inputGainSliderId, this);
treeState.removeParameterListener (driveSliderId, this);
treeState.removeParameterListener (lowSliderId, this);
treeState.removeParameterListener (midSliderId, this);
treeState.removeParameterListener (highSliderId, this);
treeState.removeParameterListener (outputGainSliderId, this);
treeState.removeParameterListener (brightId, this);
treeState.removeParameterListener (cabId, this);
treeState.removeParameterListener (menuId, this);
}
juce::AudioProcessorValueTreeState::ParameterLayout DiodeAmplifierAudioProcessor::createParameterLayout()
{
std::vector <std::unique_ptr<juce::RangedAudioParameter>> params;
params.reserve(8);
auto inputGainParam = std::make_unique<juce::AudioParameterFloat>(inputGainSliderId, inputGainSliderName, -24.0f, 24.0f, 0.0f);
auto driveParam = std::make_unique<juce::AudioParameterFloat>(driveSliderId, driveSliderName, 0.0f, 10.0f, 0.0f);
auto lowParam = std::make_unique<juce::AudioParameterFloat>(lowSliderId, lowSliderName, -6.0f, 6.0f, 0.0f);
auto midParam = std::make_unique<juce::AudioParameterFloat>(midSliderId, midSliderName, -6.0f, 6.0f, 0.0f);
auto highParam = std::make_unique<juce::AudioParameterFloat>(highSliderId, highSliderName, -6.0f, 6.0f, 0.0f);
auto outputGainParam = std::make_unique<juce::AudioParameterFloat>(outputGainSliderId, outputGainSliderName, -24.0f, 24.0f, 0.0f);
auto brightParam = std::make_unique<juce::AudioParameterBool>(brightId, brightName, false);
auto cabParam = std::make_unique<juce::AudioParameterBool>(cabId, cabName, true);
auto pMenu = std::make_unique<juce::AudioParameterInt>(menuId, menuName, 0, 1, 0);
params.push_back(std::move(inputGainParam));
params.push_back(std::move(driveParam));
params.push_back(std::move(lowParam));
params.push_back(std::move(midParam));
params.push_back(std::move(highParam));
params.push_back(std::move(outputGainParam));
params.push_back(std::move(brightParam));
params.push_back(std::move(cabParam));
params.push_back(std::move(pMenu));
return { params.begin(), params.end() };
}
void DiodeAmplifierAudioProcessor::parameterChanged(const juce::String ¶meterID, float newValue)
{
if (parameterID == inputGainSliderId)
{
inputGainProcessor.setGainDecibels(newValue);
}
else if (parameterID == lowSliderId)
{
updateLowFilter(newValue);
}
else if (parameterID == midSliderId)
{
updateMidFilter(newValue);
}
else if (parameterID == highSliderId)
{
updateHighFilter(newValue);
}
else if (parameterID == outputGainSliderId)
{
outputGainProcessor.setGainDecibels(newValue);
if (!convolutionToggle) variableTree.setProperty("cabOffGain", newValue, nullptr);
}
else if (parameterID == driveSliderId)
{
driveScaled = pow(10.0f, newValue * 0.25f);
}
else if (parameterID == brightId)
{
*highNotchFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(lastSampleRate, 4000.0f, 1.0f, pow(10.0f, -12.0f / 20.0f) * (newValue + 1));
}
else if (parameterID == cabId)
{
convolutionToggle = newValue;
if (newValue == 0)
{
treeState.getParameterAsValue(outputGainSliderId) = variableTree.getProperty("cabOffGain");
DBG(variableTree.getProperty("cabOffGain").toString());
}
else
{
treeState.getParameterAsValue(outputGainSliderId) = 0.0;
}
}
else if (parameterID == menuId)
{
oversamplingToggle = newValue;
}
}
//==============================================================================
const juce::String DiodeAmplifierAudioProcessor::getName() const
{
return JucePlugin_Name;
}
bool DiodeAmplifierAudioProcessor::acceptsMidi() const
{
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool DiodeAmplifierAudioProcessor::producesMidi() const
{
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
bool DiodeAmplifierAudioProcessor::isMidiEffect() const
{
#if JucePlugin_IsMidiEffect
return true;
#else
return false;
#endif
}
double DiodeAmplifierAudioProcessor::getTailLengthSeconds() const
{
return 0.0;
}
int DiodeAmplifierAudioProcessor::getNumPrograms()
{
return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
// so this should be at least 1, even if you're not really implementing programs.
}
int DiodeAmplifierAudioProcessor::getCurrentProgram()
{
return 0;
}
void DiodeAmplifierAudioProcessor::setCurrentProgram (int index)
{
}
const juce::String DiodeAmplifierAudioProcessor::getProgramName (int index)
{
return {};
}
void DiodeAmplifierAudioProcessor::changeProgramName (int index, const juce::String& newName)
{
}
//==============================================================================
void DiodeAmplifierAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
// Initialize spec for dsp modules
juce::dsp::ProcessSpec spec;
spec.maximumBlockSize = samplesPerBlock;
spec.sampleRate = sampleRate * oversamplingProcessor.getOversamplingFactor();
spec.numChannels = getTotalNumOutputChannels();
// Set the sample rate and use it for dsp modules
// We need both samplerates to switch between oversampling states
lastSampleRate = spec.sampleRate;
projectSampleRate = sampleRate;
highPassFilter.prepare(spec);
highPassFilter.reset();
*highPassFilter.state = *juce::dsp::IIR::Coefficients<float>::makeHighPass(projectSampleRate, 200);
preClipFilter.prepare(spec);
preClipFilter.reset();
*preClipFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(projectSampleRate, 1420, 0.5, 6.0);
lowFilter.prepare(spec);
lowFilter.reset();
*lowFilter.state = *juce::dsp::IIR::Coefficients<float>::makeLowShelf(projectSampleRate, 200, 1.3, pow(10, *treeState.getRawParameterValue(lowSliderId) * 0.05));
midFilter.prepare(spec);
midFilter.reset();
*midFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(projectSampleRate, 815, 0.3, pow(10, *treeState.getRawParameterValue(midSliderId) * 0.05));
highFilter.prepare(spec);
highFilter.reset();
*highFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(projectSampleRate, 6000, 0.2, pow(10, *treeState.getRawParameterValue(highSliderId) * 0.05));
highNotchFilter.prepare(spec);
highNotchFilter.reset();
*highNotchFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(projectSampleRate, 4000.0f, 1.0f, pow(10.0f, -12.0f / 20.0f) * (*treeState.getRawParameterValue(brightId) + 1));
inputGainProcessor.prepare(spec);
inputGainProcessor.reset();
inputGainProcessor.setGainDecibels(*treeState.getRawParameterValue(inputGainSliderId));
outputGainProcessor.prepare(spec);
outputGainProcessor.reset();
outputGainProcessor.setGainDecibels(*treeState.getRawParameterValue(outputGainSliderId));
convolutionProcessor.prepare(spec);
convolutionToggle = *treeState.getRawParameterValue(cabId);
driveScaled = pow(10.0f, *treeState.getRawParameterValue(driveSliderId) * 0.25f);
}
void DiodeAmplifierAudioProcessor::releaseResources()
{
}
#ifndef JucePlugin_PreferredChannelConfigurations
bool DiodeAmplifierAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
{
#if JucePlugin_IsMidiEffect
juce::ignoreUnused (layouts);
return true;
#else
// This is the place where you check if the layout is supported.
// In this template code we only support mono or stereo.
// Some plugin hosts, such as certain GarageBand versions, will only
// load plugins that support stereo bus layouts.
if (layouts.getMainOutputChannelSet() != juce::AudioChannelSet::mono()
&& layouts.getMainOutputChannelSet() != juce::AudioChannelSet::stereo())
return false;
// This checks if the input layout matches the output layout
#if ! JucePlugin_IsSynth
if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
return false;
#endif
return true;
#endif
}
#endif
void DiodeAmplifierAudioProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages)
{
juce::ScopedNoDenormals noDenormals;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();
for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
buffer.clear (i, 0, buffer.getNumSamples());
juce::dsp::AudioBlock<float> audioBlock {buffer};
inputGainProcessor.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
highPassFilter.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
preClipFilter.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
for (int channel = 0; channel < totalNumInputChannels; ++channel) {
auto* inputData = buffer.getReadPointer(channel);
auto* outputData = buffer.getWritePointer(channel);
for (int sample = 0; sample < buffer.getNumSamples(); ++sample) {
float diodeClippingAlgorithm = exp((0.1 * inputData[sample]) / (0.0253 * 1.68)) - 1;
outputData[sample] = piDivisor * atan(diodeClippingAlgorithm * (driveScaled * 16));
}
}
lowFilter.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
midFilter.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
highFilter.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
highNotchFilter.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
if (convolutionToggle) convolutionProcessor.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
outputGainProcessor.process(juce::dsp::ProcessContextReplacing<float>(audioBlock));
}
void DiodeAmplifierAudioProcessor::setAllSampleRates(float value)
{
*highPassFilter.state = *juce::dsp::IIR::Coefficients<float>::makeHighPass(value, 200);
*preClipFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(value, 1420, 0.5, 6.0);
*lowFilter.state = *juce::dsp::IIR::Coefficients<float>::makeLowShelf(value, 200, 1.3, pow(10, *treeState.getRawParameterValue(lowSliderId) * 0.05));
*midFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(value, 815, 0.3, pow(10, *treeState.getRawParameterValue(midSliderId) * 0.05));
*highFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(value, 6000, 0.2, pow(10, *treeState.getRawParameterValue(highSliderId) * 0.05));
*highNotchFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(value, 4000.0f, 1.0f, pow(10.0f, -12.0f / 20.0f) * (*treeState.getRawParameterValue(brightId) + 1));
}
void DiodeAmplifierAudioProcessor::updateHighPassFilter(const float &freq){
*highPassFilter.state = *juce::dsp::IIR::Coefficients<float>::makeHighPass(lastSampleRate, 200);
}
void DiodeAmplifierAudioProcessor::updatePreClipFilter(const float &freq){
*preClipFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(lastSampleRate, 1420, 0.5, 6.0);
}
void DiodeAmplifierAudioProcessor::updateLowFilter(const float &gain){
*lowFilter.state = *juce::dsp::IIR::Coefficients<float>::makeLowShelf(lastSampleRate, 200, 1.3, pow(10, gain * 0.05));
}
void DiodeAmplifierAudioProcessor::updateMidFilter(const float &gain){
*midFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(lastSampleRate, 815, 0.3, pow(10, gain * 0.05));
}
void DiodeAmplifierAudioProcessor::updateHighFilter(const float &gain){
*highFilter.state = *juce::dsp::IIR::Coefficients<float>::makePeakFilter(lastSampleRate, 6000, 0.2, pow(10, gain * 0.05));
}
//==============================================================================
bool DiodeAmplifierAudioProcessor::hasEditor() const
{
return true; // (change this to false if you choose to not supply an editor)
}
juce::AudioProcessorEditor* DiodeAmplifierAudioProcessor::createEditor()
{
return new DiodeAmplifierAudioProcessorEditor (*this);
}
//==============================================================================
void DiodeAmplifierAudioProcessor::getStateInformation (juce::MemoryBlock& destData)
{
treeState.state.appendChild(variableTree, nullptr);
juce::MemoryOutputStream stream(destData, false);
treeState.state.writeToStream (stream);
}
void DiodeAmplifierAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
auto tree = juce::ValueTree::readFromData (data, size_t(sizeInBytes));
variableTree = tree.getChildWithName("DiodeVariables");
if (tree.isValid())
{
treeState.state = tree;
}
savedFile = juce::File(variableTree.getProperty("file"));
root = juce::File(variableTree.getProperty("root"));
if (savedFile.existsAsFile())
{
convolutionProcessor.loadImpulseResponse(savedFile, juce::dsp::Convolution::Stereo::yes, juce::dsp::Convolution::Trim::yes, 0);
DBG("Location exists as file");
}
else
{
convolutionProcessor.loadImpulseResponse
(BinaryData::metalOne_wav,
BinaryData::metalOne_wavSize,
juce::dsp::Convolution::Stereo::yes,
juce::dsp::Convolution::Trim::yes, 0,
juce::dsp::Convolution::Normalise::yes);
}
if (!convolutionToggle) treeState.getParameterAsValue(outputGainSliderId) = variableTree.getProperty("cabOffGain");
}
//==============================================================================
// This creates new instances of the plugin..
juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new DiodeAmplifierAudioProcessor();
}
| 37.620767 | 194 | 0.661466 | [
"vector"
] |
8893982d4dc2cbd946c66518af608337fc1dd457 | 40,089 | cpp | C++ | src/chainparams.cpp | lokalnode/LokalCoin | 55572130202013aef57d310bdf8b1f0700ec2168 | [
"MIT"
] | null | null | null | src/chainparams.cpp | lokalnode/LokalCoin | 55572130202013aef57d310bdf8b1f0700ec2168 | [
"MIT"
] | null | null | null | src/chainparams.cpp | lokalnode/LokalCoin | 55572130202013aef57d310bdf8b1f0700ec2168 | [
"MIT"
] | null | null | null | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2014-2020 The Dash Core developers
// Copyright (c) 2018-2020 The PACGlobal developers
// Copyright (c) 2021 The Lokal Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "consensus/merkle.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include "arith_uint256.h"
#include <assert.h>
#include "chainparamsseeds.h"
const int32_t NEVER32 = 400000U;
const int64_t NEVER64 = 4070908800ULL;
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = nVersion;
genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
static CBlock CreateDevNetGenesisBlock(const uint256 &prevBlockHash, const std::string& devNetName, uint32_t nTime, uint32_t nNonce, uint32_t nBits, const CAmount& genesisReward)
{
assert(!devNetName.empty());
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
// put height (BIP34) and devnet name into coinbase
txNew.vin[0].scriptSig = CScript() << 1 << std::vector<unsigned char>(devNetName.begin(), devNetName.end());
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = CScript() << OP_RETURN;
CBlock genesis;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = 4;
genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
genesis.hashPrevBlock = prevBlockHash;
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
/**
* Build the genesis block. Note that the output of its generation
* transaction cannot be spent since it did not originally exist in the
* database.
*
* CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
* CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
* CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
* vMerkleTree: e0028e
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward, bool fTestnet)
{
const char* pszTimestamp = "Bitcoin performed 10 times better than gold in 2020";
const CScript genesisOutputScript = CScript() << ParseHex("0411345e927d2d3abb85541e23b211f5a9019f2b240fb6bd4b1c44234993639793846cfc74154d293a3bf7ba74592f5f358127c0062a621d3b153089d0f5bb84e5") << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout, int64_t nWindowSize, int64_t nThreshold)
{
consensus.vDeployments[d].nStartTime = nStartTime;
consensus.vDeployments[d].nTimeout = nTimeout;
if (nWindowSize != -1) {
consensus.vDeployments[d].nWindowSize = nWindowSize;
}
if (nThreshold != -1) {
consensus.vDeployments[d].nThreshold = nThreshold;
}
}
void CChainParams::UpdateDIP3Parameters(int nActivationHeight, int nEnforcementHeight)
{
consensus.DIP0003Height = nActivationHeight;
consensus.DIP0003EnforcementHeight = nEnforcementHeight;
}
void CChainParams::UpdateBudgetParameters(int nMasternodePaymentsStartBlock, int nBudgetPaymentsStartBlock, int nSuperblockStartBlock)
{
consensus.nMasternodePaymentsStartBlock = nMasternodePaymentsStartBlock;
consensus.nBudgetPaymentsStartBlock = nBudgetPaymentsStartBlock;
consensus.nSuperblockStartBlock = nSuperblockStartBlock;
}
void CChainParams::UpdateSubsidyAndDiffParams(int nMinimumDifficultyBlocks, int nHighSubsidyBlocks, int nHighSubsidyFactor)
{
consensus.nMinimumDifficultyBlocks = nMinimumDifficultyBlocks;
consensus.nHighSubsidyBlocks = nHighSubsidyBlocks;
consensus.nHighSubsidyFactor = nHighSubsidyFactor;
}
void CChainParams::UpdateLLMQChainLocks(Consensus::LLMQType llmqType) {
consensus.llmqTypeChainLocks = llmqType;
}
static CBlock FindDevNetGenesisBlock(const Consensus::Params& params, const CBlock &prevBlock, const CAmount& reward)
{
std::string devNetName = GetDevNetName();
assert(!devNetName.empty());
CBlock block = CreateDevNetGenesisBlock(prevBlock.GetHash(), devNetName.c_str(), prevBlock.nTime + 1, 0, prevBlock.nBits, reward);
arith_uint256 bnTarget;
bnTarget.SetCompact(block.nBits);
for (uint32_t nNonce = 0; nNonce < UINT32_MAX; nNonce++) {
block.nNonce = nNonce;
uint256 hash = block.GetHash();
if (UintToArith256(hash) <= bnTarget)
return block;
}
// This is very unlikely to happen as we start the devnet with a very low difficulty. In many cases even the first
// iteration of the above loop will give a result already
error("FindDevNetGenesisBlock: could not find devnet genesis block for %s", devNetName);
assert(false);
}
// this one is for testing only
static Consensus::LLMQParams llmq5_60 = {
.type = Consensus::LLMQ_5_60,
.name = "llmq_5_60",
.size = 3,
.minSize = 3,
.threshold = 3,
.dkgInterval = 24, // one DKG per hour
.dkgPhaseBlocks = 2,
.dkgMiningWindowStart = 10, // dkgPhaseBlocks * 5 = after finalization
.dkgMiningWindowEnd = 18,
.dkgBadVotesThreshold = 8,
.signingActiveQuorumCount = 2, // just a few ones to allow easier testing
.keepOldConnections = 3,
};
static Consensus::LLMQParams llmq50_60 = {
.type = Consensus::LLMQ_50_60,
.name = "llmq_50_60",
.size = 50,
.minSize = 20,
.threshold = 10,
.dkgInterval = 60, // one DKG per hour
.dkgPhaseBlocks = 5,
.dkgMiningWindowStart = 25, // dkgPhaseBlocks * 5 = after finalization
.dkgMiningWindowEnd = 45,
.dkgBadVotesThreshold = 40,
.signingActiveQuorumCount = 24, // a full day worth of LLMQs
.keepOldConnections = 25,
};
static Consensus::LLMQParams llmq400_60 = {
.type = Consensus::LLMQ_400_60,
.name = "llmq_400_60",
.size = 400,
.minSize = 100,
.threshold = 70,
.dkgInterval = 60 * 12, // one DKG every 12 hours
.dkgPhaseBlocks = 10,
.dkgMiningWindowStart = 50, // dkgPhaseBlocks * 5 = after finalization
.dkgMiningWindowEnd = 70,
.dkgBadVotesThreshold = 150,
.signingActiveQuorumCount = 4, // two days worth of LLMQs
.keepOldConnections = 5,
};
// Used for deployment and min-proto-version signalling, so it needs a higher threshold
static Consensus::LLMQParams llmq400_85 = {
.type = Consensus::LLMQ_400_85,
.name = "llmq_400_85",
.size = 400,
.minSize = 150,
.threshold = 100,
.dkgInterval = 60 * 24, // one DKG every 24 hours
.dkgPhaseBlocks = 10,
.dkgMiningWindowStart = 50, // dkgPhaseBlocks * 5 = after finalization
.dkgMiningWindowEnd = 120, // give it a larger mining window to make sure it is mined
.dkgBadVotesThreshold = 300,
.signingActiveQuorumCount = 4, // four days worth of LLMQs
.keepOldConnections = 5,
};
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
class CMainParams : public CChainParams {
public:
CMainParams() {
strNetworkID = "main";
consensus.nMasternodePaymentsStartBlock = 201;
consensus.nInstantSendConfirmationsRequired = 6;
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = NEVER32; // actual historical value
consensus.nBudgetPaymentsCycleBlocks = NEVER32; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
consensus.nBudgetPaymentsWindowBlocks = NEVER32;
consensus.nSuperblockStartBlock = NEVER32;
consensus.nSuperblockStartHash = uint256S("");
consensus.nSuperblockCycle = NEVER32;
consensus.nGovernanceMinQuorum = 10;
consensus.nGovernanceFilterElements = 20000;
consensus.nHardenedStakeCheckHeight = 387939;
consensus.nMasternodeMinimumConfirmations = 15;
consensus.nMasternodeCollateral = 20000 * COIN;
consensus.BIP34Height = 1;
consensus.BIP34Hash = uint256S("0x");
consensus.BIP65Height = 1;
consensus.BIP66Height = 400;
consensus.DIP0001Height = 2;
consensus.DIP0003Height = 201;
consensus.DIP0003EnforcementHeight = 2000;
consensus.DIP0003EnforcementHash = uint256();
consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.posLimit = uint256S("07ffff0000000000000000000000000000000000000000000000000000000000");
consensus.nLastPoWBlock = 200;
consensus.nPowTargetTimespan = 24 * 60 * 60;
consensus.nPowTargetSpacing = 2 * 60;
consensus.nPosTargetSpacing = consensus.nPowTargetSpacing;
consensus.nPosTargetTimespan = consensus.nPowTargetTimespan;
consensus.nMinimumStakeValue = 3 * COIN;
consensus.nStakeMinAge = 60 * 60;
consensus.nStakeMaxAge = 60 * 60 * 24 * 365;
consensus.nModifierInterval = 60 * 20;
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
consensus.nPowKGWHeight = 20;
consensus.nPowDGWHeight = 60;
consensus.nRuleChangeActivationThreshold = 1916;
consensus.nMinerConfirmationWindow = 2016;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = NEVER64;
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = NEVER64;
// Deployment of DIP0001
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = NEVER64;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nThreshold = 50;
// Deployment of BIP147
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = NEVER64;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nThreshold = 50;
// Deployment of DIP0003
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].bit = 3;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nWindowSize = 2000;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nThreshold = 1000;
// Deployment of DIP0008
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nWindowSize = 3000;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nThreshold = 1500;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000"); // 332500
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000");
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 32-bit integer with any alignment.
*/
pchMessageStart[0] = 0xac;
pchMessageStart[1] = 0xe5;
pchMessageStart[2] = 0xb6;
pchMessageStart[3] = 0x7c;
nDefaultPort = 2513;
nPruneAfterHeight = 100000;
//uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward, bool fTestnet
genesis = CreateGenesisBlock(1613019600, 2024315, 0x1e0ffff0, 1, 0 * COIN, false);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x00000b49f79eaf2a0a99f3d85762a63b410711953933834c9afd5e96ce805a61"));
assert(genesis.hashMerkleRoot == uint256S("0xbafd9ea271b5fdc00fefe68e82c3baaa5b2b9f0770c93713506fb071fe4337fa"));
vSeeds.emplace_back("66.42.72.163");
vSeeds.emplace_back("2001:19f0:8001:1a67:5400:03ff:fe09:0022");
vSeeds.emplace_back("66.42.61.57");
vSeeds.emplace_back("2001:19f0:4400:7a35:5400:03ff:fe08:ffac");
vSeeds.emplace_back("108.61.188.47");
vSeeds.emplace_back("2001:19f0:5001:11a2:5400:03ff:fe08:ffb9");
vSeeds.emplace_back("108.61.209.126");
vSeeds.emplace_back("2a05:f480:1c00:a59:5400:03ff:fe08:ffcc");
vSeeds.emplace_back("192.248.187.37");
vSeeds.emplace_back("2001:19f0:6c01:2e7f:5400:03ff:fe08:ffe6");
vSeeds.emplace_back("216.128.128.44");
vSeeds.emplace_back("2001:19f0:6401:1f0e:5400:03ff:fe08:fffe");
vSeeds.emplace_back("155.138.131.22");
vSeeds.emplace_back("2001:19f0:b001:7e6:5400:03ff:fe09:0011");
vSeeds.emplace_back("45.76.120.11");
vSeeds.emplace_back("2401:c080:1800:410e:5400:03ff:fe09:8fc5");
// LOKAL addresses start with 'L'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 48);
// LOKAL script addresses start with '5'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 10);
// LOKAL private keys start with '7' or 'X'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 204);
// LOKAL BIP32 pubkeys start with 'xpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = { 0x04, 0x88, 0xB2, 0x1E };
// LOKAL BIP32 prvkeys start with 'xprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = { 0x04, 0x88, 0xAD, 0xE4 };
// LOKAL BIP44 coin type is '5'
nExtCoinType = 5;
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
// long living quorum params
consensus.llmqs[Consensus::LLMQ_50_60] = llmq50_60;
consensus.llmqs[Consensus::LLMQ_400_60] = llmq400_60;
consensus.llmqs[Consensus::LLMQ_400_85] = llmq400_85;
consensus.llmqTypeChainLocks = Consensus::LLMQ_400_60;
consensus.llmqForInstaLOKAL = Consensus::LLMQ_50_60;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fRequireRoutableExternalIP = true;
fMineBlocksOnDemand = false;
fAllowMultipleAddressesFromGroup = false;
fAllowMultiplePorts = false;
nPoolMinParticipants = 3;
nPoolMaxParticipants = 5;
nFulfilledRequestExpireTime = 60 * 60; // fulfilled requests expire in 1 hour
vSporkAddresses = { "LYUfeNSmdy5dehc8MJq2zmySt16bWjSNk3" };
nMinSporkKeys = 1;
fBIP9CheckMasternodesUpgraded = true;
checkpointData = (CCheckpointData) {
{
{ 0, uint256S("0x00000b49f79eaf2a0a99f3d85762a63b410711953933834c9afd5e96ce805a61")},
{ 87, uint256S("0x0000002832516c11599844772ae91e71d6aef4d9f20fdd405a930e58aeeb55bc") },
{ 206, uint256S("0xb6c81cf54e68ba3f9e9afc6386ede02d9fa400b3a12394dcf3081561f9e3e16f") },
{ 1523, uint256S("0xc2da096484f77b259a15883b908ea638d98ad2da2a9c6563f50fa0b5fb042410") },
{ 5049, uint256S("0x545ac4052680e138a24e9c1fe1e46e0a66a8aa80ddedaded07f9b9df15431a9f") },
{ 7321, uint256S("0x17e6e184ef23cc8637bebd0d34f0ec6701a99c186cc4c6e8741e64cfeb3ee5d8") },
{ 9301, uint256S("0x939e18fa7935bf86e46d1d34a191c7ee85c4ac2ea33135d9ac7bd21f6df6eeb9") },
}
};
chainTxData = ChainTxData{
1614229693, // * UNIX timestamp of last known number of transactions
20171, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
0.01 // * estimated number of transactions per second after that timestamp
};
}
};
/**
* Testnet (v3)
*/
class CTestNetParams : public CChainParams {
public:
CTestNetParams() {
strNetworkID = "test";
consensus.nMasternodePaymentsStartBlock = 50;
consensus.nInstantSendConfirmationsRequired = 2;
consensus.nInstantSendKeepLock = 6;
consensus.nBudgetPaymentsStartBlock = 50;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 100;
consensus.nSuperblockStartBlock = 100;
consensus.nSuperblockStartHash = uint256();
consensus.nSuperblockCycle = 24;
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 500;
consensus.nMasternodeMinimumConfirmations = 15;
consensus.nMasternodeCollateral = 1000 * COIN;
consensus.BIP34Height = 1;
consensus.BIP34Hash = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000");
consensus.BIP65Height = 0;
consensus.BIP66Height = 0;
consensus.DIP0001Height = 1;
consensus.DIP0003Height = 75;
consensus.DIP0003EnforcementHeight = 363000;
consensus.DIP0003EnforcementHash = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000");
consensus.powLimit = uint256S("0000fffff0000000000000000000000000000000000000000000000000000000");
consensus.posLimit = uint256S("007ffff000000000000000000000000000000000000000000000000000000000");
consensus.nLastPoWBlock = consensus.DIP0003Height;
consensus.nPowTargetTimespan = 60;
consensus.nPowTargetSpacing = 60;
consensus.nPosTargetSpacing = consensus.nPowTargetSpacing;
consensus.nPosTargetTimespan = consensus.nPowTargetTimespan;
consensus.nMinimumStakeValue = 100 * COIN;
consensus.nStakeMinAge = 10 * 60;
consensus.nStakeMaxAge = 60 * 60 * 24 * 30;
consensus.nModifierInterval = 60 * 20;
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
consensus.nPowKGWHeight = NEVER32; // unused
consensus.nPowDGWHeight = NEVER32; // unused
consensus.nRuleChangeActivationThreshold = 1512;
consensus.nMinerConfirmationWindow = 2016;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = NEVER64;
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = NEVER64;
// Deployment of DIP0001
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = NEVER64;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nThreshold = 50;
// Deployment of BIP147
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 1573325000;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = NEVER64;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nThreshold = 50;
// Deployment of DIP0003
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].bit = 3;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nWindowSize = 1000;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nThreshold = 250;
// Deployment of DIP0008
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nWindowSize = 1000;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nThreshold = 250;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x0000000000000000000000000000000000000000000000000000000000000000");
pchMessageStart[0] = 0x22;
pchMessageStart[1] = 0x44;
pchMessageStart[2] = 0x66;
pchMessageStart[3] = 0x88;
nDefaultPort = 29999;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1573325000, 11404, 0x1f00ffff, 1, 0 * COIN, true);
consensus.hashGenesisBlock = genesis.GetHash();
vSeeds.clear();
vFixedSeeds.clear();
// Testnet LOKAL_Coin addresses start with 'y'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 140);
// Testnet LOKAL_Coin script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19);
// Testnet private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);
// Testnet LOKAL_Coin BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = { 0x04, 0x35, 0x87, 0xCF };
// Testnet LOKAL_Coin BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = { 0x04, 0x35, 0x83, 0x94 };
// Testnet LOKAL_Coin BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
// long living quorum params
consensus.llmqs[Consensus::LLMQ_50_60] = llmq50_60;
consensus.llmqs[Consensus::LLMQ_400_60] = llmq400_60;
consensus.llmqs[Consensus::LLMQ_400_85] = llmq400_85;
consensus.llmqTypeChainLocks = Consensus::LLMQ_50_60;
consensus.llmqForInstaLOKAL = Consensus::LLMQ_50_60;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fRequireRoutableExternalIP = false;
fMineBlocksOnDemand = false;
fAllowMultipleAddressesFromGroup = true;
fAllowMultiplePorts = true;
nPoolMinParticipants = 3;
nPoolMaxParticipants = 5;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
vSporkAddresses = { "yTpFjxs3Rtwe7MXfC1i5XACz2K5UYi2GpL" };
nMinSporkKeys = 1;
fBIP9CheckMasternodesUpgraded = true;
checkpointData = (CCheckpointData) {};
chainTxData = ChainTxData{
1567342000, // * UNIX timestamp of last known number of transactions
1, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
1.0 // * estimated number of transactions per second after that timestamp
};
}
};
/**
* Devnet
*/
class CDevNetParams : public CChainParams {
public:
CDevNetParams() {
strNetworkID = "dev";
consensus.nMasternodePaymentsStartBlock = 4010;
consensus.nInstantSendConfirmationsRequired = 2;
consensus.nInstantSendKeepLock = 6;
consensus.nBudgetPaymentsStartBlock = 4100;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nSuperblockStartBlock = 4200; // NOTE: Should satisfy nSuperblockStartBlock > nBudgetPeymentsStartBlock
consensus.nSuperblockStartHash = uint256(); // do not check this on devnet
consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on devnet
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 500;
consensus.nMasternodeMinimumConfirmations = 1;
consensus.nMasternodeCollateral = 500000 * COIN;
consensus.BIP34Height = 1; // BIP34 activated immediately on devnet
consensus.BIP65Height = 1; // BIP65 activated immediately on devnet
consensus.BIP66Height = 1; // BIP66 activated immediately on devnet
consensus.DIP0001Height = 2; // DIP0001 activated immediately on devnet
consensus.DIP0003Height = 2; // DIP0003 activated immediately on devnet
consensus.DIP0003EnforcementHeight = 2; // DIP0003 activated immediately on devnet
consensus.DIP0003EnforcementHash = uint256();
consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // ~uint256(0) >> 1
consensus.posLimit = uint256S("007ffff000000000000000000000000000000000000000000000000000000000");
consensus.nLastPoWBlock = 100;
consensus.nPowTargetTimespan = 24 * 60 * 60; // LOKAL_Coin: 1 day
consensus.nPowTargetSpacing = 2.5 * 60; // LOKAL_Coin: 2.5 minutes
consensus.nPosTargetSpacing = consensus.nPowTargetSpacing;
consensus.nPosTargetTimespan = consensus.nPowTargetTimespan;
consensus.nMinimumStakeValue = 10000 * COIN;
consensus.nStakeMinAge = 10 * 60;
consensus.nStakeMaxAge = 60 * 60 * 24 * 30;
consensus.nModifierInterval = 60 * 20;
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = false;
consensus.nPowKGWHeight = 4001; // nPowKGWHeight >= nPowDGWHeight means "no KGW"
consensus.nPowDGWHeight = 4001;
consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1506556800; // September 28th, 2017
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1538092800; // September 28th, 2018
// Deployment of DIP0001
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 1505692800; // Sep 18th, 2017
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = 1537228800; // Sep 18th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nThreshold = 50; // 50% of 100
// Deployment of BIP147
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 1517792400; // Feb 5th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 1549328400; // Feb 5th, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nThreshold = 50; // 50% of 100
// Deployment of DIP0003
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].bit = 3;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nStartTime = 1535752800; // Sep 1st, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nTimeout = 1567288800; // Sep 1st, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nThreshold = 50; // 50% of 100
// Deployment of DIP0008
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nStartTime = 1553126400; // Mar 21st, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nTimeout = 1584748800; // Mar 21st, 2020
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nThreshold = 50; // 50% of 100
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000000000000000000000000");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x000000000000000000000000000000000000000000000000000000000000000");
pchMessageStart[0] = 0xe2;
pchMessageStart[1] = 0xca;
pchMessageStart[2] = 0xff;
pchMessageStart[3] = 0xce;
nDefaultPort = 19799;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1417713337, 1096447, 0x207fffff, 1, 50 * COIN, false);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"));
assert(genesis.hashMerkleRoot == uint256S("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7"));
devnetGenesis = FindDevNetGenesisBlock(consensus, genesis, 50 * COIN);
consensus.hashDevnetGenesisBlock = devnetGenesis.GetHash();
vFixedSeeds.clear();
vSeeds.clear();
//vSeeds.push_back(CDNSSeedData("lokalevo.org", "devnet-seed.lokalevo.org"));
// Testnet LOKAL_Coin addresses start with 'y'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 140);
// Testnet LOKAL_Coin script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19);
// Testnet private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);
// Testnet LOKAL_Coin BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = { 0x04, 0x35, 0x87, 0xCF };
// Testnet LOKAL_Coin BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = { 0x04, 0x35, 0x83, 0x94 };
// Testnet LOKAL_Coin BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
// long living quorum params
consensus.llmqs[Consensus::LLMQ_50_60] = llmq50_60;
consensus.llmqs[Consensus::LLMQ_400_60] = llmq400_60;
consensus.llmqs[Consensus::LLMQ_400_85] = llmq400_85;
consensus.llmqTypeChainLocks = Consensus::LLMQ_50_60;
consensus.llmqForInstaLOKAL = Consensus::LLMQ_50_60;
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fMineBlocksOnDemand = false;
fAllowMultipleAddressesFromGroup = true;
fAllowMultiplePorts = true;
nPoolMinParticipants = 3;
nPoolMaxParticipants = 5;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
vSporkAddresses = { "yjPtiKh2uwk3bDutTEA2q9mCtXyiZRWn55" };
nMinSporkKeys = 1;
// devnets are started with no blocks and no MN, so we can't check for upgraded MN (as there are none)
fBIP9CheckMasternodesUpgraded = false;
checkpointData = (CCheckpointData) {
{
{ 0, uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")},
{ 1, devnetGenesis.GetHash() },
}
};
chainTxData = ChainTxData{
devnetGenesis.GetBlockTime(), // * UNIX timestamp of devnet genesis block
2, // * we only have 2 coinbase transactions when a devnet is started up
0.01 // * estimated number of transactions per second
};
}
};
/**
* Regression test
*/
class CRegTestParams : public CChainParams {
public:
CRegTestParams() {
strNetworkID = "regtest";
consensus.nMasternodePaymentsStartBlock = 240;
consensus.nInstantSendConfirmationsRequired = 2;
consensus.nInstantSendKeepLock = 6;
consensus.nBudgetPaymentsStartBlock = 1000;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nSuperblockStartBlock = 1500;
consensus.nSuperblockStartHash = uint256(); // do not check this on regtest
consensus.nSuperblockCycle = 10;
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 100;
consensus.nMasternodeMinimumConfirmations = 1;
consensus.nMasternodeCollateral = 500000 * COIN;
consensus.BIP34Height = 100000000; // BIP34 has not activated on regtest (far in the future so block v1 are not rejected in tests)
consensus.BIP34Hash = uint256();
consensus.BIP65Height = 1351; // BIP65 activated on regtest (Used in rpc activation tests)
consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in rpc activation tests)
consensus.DIP0001Height = 2000;
consensus.DIP0003Height = 432;
consensus.DIP0003EnforcementHeight = 500;
consensus.DIP0003EnforcementHash = uint256();
consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // ~uint256(0) >> 1
consensus.posLimit = uint256S("007ffff000000000000000000000000000000000000000000000000000000000");
consensus.nLastPoWBlock = 100;
consensus.nPowTargetTimespan = 24 * 60 * 60; // LOKAL_Coin: 1 day
consensus.nPowTargetSpacing = 2.5 * 60; // LOKAL_Coin: 2.5 minutes
consensus.nPosTargetSpacing = consensus.nPowTargetSpacing;
consensus.nPosTargetTimespan = consensus.nPowTargetTimespan;
consensus.nStakeMinAge = 10 * 60;
consensus.nStakeMaxAge = 60 * 60 * 24 * 30;
consensus.nModifierInterval = 60 * 20;
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = true;
consensus.nPowKGWHeight = 15200; // same as mainnet
consensus.nPowDGWHeight = 34140; // same as mainnet
consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].bit = 3;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0008].nTimeout = 999999999999ULL;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x00");
pchMessageStart[0] = 0xfc;
pchMessageStart[1] = 0xc1;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xdc;
nDefaultPort = 19899;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1417713337, 1096447, 0x207fffff, 1, 50 * COIN, false);
consensus.hashGenesisBlock = genesis.GetHash();
// assert(consensus.hashGenesisBlock == uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"));
// assert(genesis.hashMerkleRoot == uint256S("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7"));
vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds.
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fRequireRoutableExternalIP = false;
fMineBlocksOnDemand = true;
fAllowMultipleAddressesFromGroup = true;
fAllowMultiplePorts = true;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
nPoolMinParticipants = 3;
nPoolMaxParticipants = 5;
// privKey: cP4EKFyJsHT39LDqgdcB43Y3YXjNyjb5Fuas1GQSeAtjnZWmZEQK
vSporkAddresses = { "yj949n1UH6fDhw6HtVE5VMj2iSTaSWBMcW" };
nMinSporkKeys = 1;
// regtest usually has no masternodes in most tests, so don't check for upgraged MNs
fBIP9CheckMasternodesUpgraded = false;
checkpointData = (CCheckpointData) {
{
{0, uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e")},
}
};
chainTxData = ChainTxData{
0,
0,
0
};
// Regtest LOKAL_Coin addresses start with 'y'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 140);
// Regtest LOKAL_Coin script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19);
// Regtest private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);
// Regtest LOKAL_Coin BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = { 0x04, 0x35, 0x87, 0xCF };
// Regtest LOKAL_Coin BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = { 0x04, 0x35, 0x83, 0x94 };
// Regtest LOKAL_Coin BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
// long living quorum params
consensus.llmqs[Consensus::LLMQ_5_60] = llmq5_60;
consensus.llmqs[Consensus::LLMQ_50_60] = llmq50_60;
consensus.llmqTypeChainLocks = Consensus::LLMQ_5_60;
consensus.llmqForInstaLOKAL = Consensus::LLMQ_5_60;
}
};
static std::unique_ptr<CChainParams> globalChainParams;
const CChainParams &Params() {
assert(globalChainParams);
return *globalChainParams;
}
std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CChainParams>(new CMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CChainParams>(new CTestNetParams());
else if (chain == CBaseChainParams::DEVNET) {
return std::unique_ptr<CChainParams>(new CDevNetParams());
}
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CChainParams>(new CRegTestParams());
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
globalChainParams = CreateChainParams(network);
}
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout, int64_t nWindowSize, int64_t nThreshold)
{
globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout, nWindowSize, nThreshold);
}
void UpdateDIP3Parameters(int nActivationHeight, int nEnforcementHeight)
{
globalChainParams->UpdateDIP3Parameters(nActivationHeight, nEnforcementHeight);
}
void UpdateBudgetParameters(int nMasternodePaymentsStartBlock, int nBudgetPaymentsStartBlock, int nSuperblockStartBlock)
{
globalChainParams->UpdateBudgetParameters(nMasternodePaymentsStartBlock, nBudgetPaymentsStartBlock, nSuperblockStartBlock);
}
void UpdateDevnetSubsidyAndDiffParams(int nMinimumDifficultyBlocks, int nHighSubsidyBlocks, int nHighSubsidyFactor)
{
globalChainParams->UpdateSubsidyAndDiffParams(nMinimumDifficultyBlocks, nHighSubsidyBlocks, nHighSubsidyFactor);
}
void UpdateDevnetLLMQChainLocks(Consensus::LLMQType llmqType)
{
globalChainParams->UpdateLLMQChainLocks(llmqType);
}
| 44.053846 | 242 | 0.775874 | [
"vector"
] |
88960eee769ff9ad9fa4fd9a3bdaa57058ae1564 | 5,477 | cpp | C++ | clex/clex/Tokenizer.cpp | kd-code/C-interpreter | cb85836819df9e70076d4edda1bda2d54d2a62ce | [
"MIT"
] | null | null | null | clex/clex/Tokenizer.cpp | kd-code/C-interpreter | cb85836819df9e70076d4edda1bda2d54d2a62ce | [
"MIT"
] | null | null | null | clex/clex/Tokenizer.cpp | kd-code/C-interpreter | cb85836819df9e70076d4edda1bda2d54d2a62ce | [
"MIT"
] | null | null | null | #include <string>
#include <cctype>
#include <vector>
#include "Tokenizer.h"
#include "common.h"
#define CUR (source.at(position))
#define NEXT (source.at(position+1))
#define LEN (source.length())
bool Tokenizer::isdelim(char c)
{
if (std::strchr(" !;,+-<>'/*%^=()[].:\n", c) || c == 9 || c == '\r' || c == 0)
return true;
return false;
}
void Tokenizer::setLineCol()
{
line = 1;
col = 1;
for (size_t i = 0; i < position; i++)
{
if (source.at(i) == '\n')
{
line++;
col = 0;
}
col++;
}
}
std::string Tokenizer::generateErrorMessage(std::string message)
{
setLineCol();
return stringFormat("[Error] " + message + " at line %d col %d", line, col);
}
Tokenizer::Tokenizer(string source)
{
this->source = source;
position = 0;
}
void Tokenizer::StartOver()
{
position = 0;
}
void Tokenizer::setSouce(string source)
{
this->source = source;
position = 0;
}
string Tokenizer::getSource()
{
return this->source;
}
Token Tokenizer::getNextToken()
{
Token result;
if (position == LEN)
{
result.type = Token::TOKEN_TYPE::FINISHED;
result.stringRepresentation = "EOL";
return result;
}
do
{
//skip over whitespace characters
while (position < LEN && std::isspace(CUR))
position++;
//skip comments
if (CUR == '/')
{
if (NEXT == '*')
{
position+=2;
do
{
while (CUR != '*')
position++;
position++;
} while (CUR != '/');
position++;
}
else if (NEXT == '/')
{
position += 2;
while (CUR != '\n' && CUR != '\r')//new line
position++;
}
}
//skip over whitespace characters after comments
while (position < LEN && std::isspace(CUR))
position++;
} while (CUR == '/' && (NEXT == '/' || NEXT == '*'));
//end of file
if (position == LEN )
{
result.type = Token::TOKEN_TYPE::FINISHED;
result.stringRepresentation = "";
return result;
}
//operators
std::vector<string> operators{ "+", "-", "*", "/", "%", "++", "--", "==",
"!=", ">", "<", ">=", "<=", "&&", "||", "!",
"&", "|", "^", "~", "<<", ">>", "=", "+=",
"-=", "*=", "/=", "%=", ">>=", "<<=", "&=",
"^=", "|=", };//using initializer lists
int ind = 0;
string op = "";
//while there is a longer operator keep going
do
{
op += CUR;
position++;
} while ((std::find(operators.begin(), operators.end(), op) != operators.end()));
op.pop_back();//remove last character
position--;
if (op.length() > 0)
{
result.type = Token::TOKEN_TYPE::OPERATOR;
result.stringRepresentation = op;
return result;
}
//delimiters
if (std::strchr("(),;{}[].:", CUR))
{
result.type = Token::TOKEN_TYPE::DELIMITER;
result.stringRepresentation = "";
result.stringRepresentation += CUR;
position++;
return result;
}
string ligit_escape = "0abfnrtv\\\"?";
//string literal
if (CUR == '"')
{
string s = "";
position++;
bool escaped = false;
while (CUR != '"' || escaped)
{
if (CUR == '\n' || CUR == '\r')
{
result.type = Token::TOKEN_TYPE::ERROR;
result.stringRepresentation = generateErrorMessage("New line in string literal");
return result;
}
if (escaped && std::strchr(ligit_escape.c_str(), CUR)==nullptr)
{
result.type = Token::TOKEN_TYPE::ERROR;
result.stringRepresentation = generateErrorMessage("Illegal escape character");
return result;
}
s += CUR;
if (CUR == '\\')
escaped = true;
else
escaped = false;
position++;
}
position++;
result.type = Token::TOKEN_TYPE::STRING_LITERAL;
result.stringRepresentation = s;
return result;
}
//char literal
if (CUR == '\'')
{
position++;
if (CUR == '\\')
{
position++;
}
if (NEXT == '\'')
{
if (CUR == '\n' || CUR == '\r')
{
result.type = Token::TOKEN_TYPE::ERROR;
result.stringRepresentation = generateErrorMessage("New line in character literal");
return result;
}
else
{
result.type = Token::TOKEN_TYPE::CHAR_LITERAL;
result.stringRepresentation = "";
result.stringRepresentation += CUR;
return result;
position += 2;
}
}
else
{
result.type = Token::TOKEN_TYPE::ERROR;
result.stringRepresentation = generateErrorMessage("Character literal too long");
return result;
}
}
//number literal
if (std::isdigit(CUR))
{
string n;
n += CUR;
position++;
while (std::isdigit(CUR))
{
n += CUR;
position++;
}
result.type = Token::TOKEN_TYPE::NUMBER_LITERAL;
result.stringRepresentation = n;
return result;
}
//keywords and identifiers
string word = "";
if (std::isalpha(CUR) || CUR == '_')
{
while (!isdelim(CUR))
{
word += CUR;
position++;
}
}
std::vector<string> keywords{ "auto", "break", "case", "char", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return", "short", "signed", "sizeof",
"static", "struct", "switch", "typedef", "union", "unsigned", "void",
"volatile", "while" };
if (word.length() > 0)
{
if ((std::find(keywords.begin(), keywords.end(), word) != keywords.end()))//its a keyword
{
result.type = Token::TOKEN_TYPE::KEYWORD;
result.stringRepresentation = word;
return result;
}
else
{
result.type = Token::TOKEN_TYPE::IDENTIFIER;
result.stringRepresentation = word;
return result;
}
}
result.type = Token::TOKEN_TYPE::ERROR;
result.stringRepresentation = generateErrorMessage("Unexpected character");
return result;
}
| 21.908 | 95 | 0.57641 | [
"vector"
] |
889742e1123381984e4ee4640e27fc698ff86626 | 1,480 | cc | C++ | src/compliance2.cc | kdungs/codecon-2015 | d54820ab996f7b6ab5f4538bb84509c4960de023 | [
"MIT"
] | 2 | 2015-11-26T03:50:14.000Z | 2018-01-07T01:54:28.000Z | src/compliance2.cc | kdungs/codecon | d54820ab996f7b6ab5f4538bb84509c4960de023 | [
"MIT"
] | null | null | null | src/compliance2.cc | kdungs/codecon | d54820ab996f7b6ab5f4538bb84509c4960de023 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <functional>
#include <numeric>
#include <set>
#include <string>
#include <vector>
constexpr auto factorial(std::size_t n) -> std::size_t {
return (n > 1) ? n * factorial(n - 1) : 1;
}
auto uniquePalindromes(std::string word) -> std::size_t {
auto chars = std::multiset<char>{std::begin(word), std::end(word)};
auto counts = std::vector<std::size_t>{};
auto foundOdd = false;
for (auto it = std::begin(chars); it != std::end(chars);
it = chars.upper_bound(*it)) {
auto count = chars.count(*it);
if (count % 2 == 1) {
if (foundOdd) {
return 0;
}
foundOdd = true;
count -= 1; // aabbc <=> aabb because there is only one position for c
}
counts.emplace_back(count); // extract unqiue counts
}
std::transform(std::begin(counts), std::end(counts), std::begin(counts),
[](std::size_t count) { return count / 2; }); // symmetry
auto sum = std::accumulate(std::begin(counts), std::end(counts), 0u,
std::plus<std::size_t>());
auto prodFactorials =
std::accumulate(std::begin(counts), std::end(counts), 1u,
[](std::size_t acc, std::size_t count) {
return acc * factorial(count);
});
return factorial(sum) / prodFactorials;
}
int main() {
auto word = std::string{};
std::cin >> word;
std::cout << uniquePalindromes(word) << '\n';
}
| 30.833333 | 77 | 0.575 | [
"vector",
"transform"
] |
889acca5e3885ebf5782210267a26b54f3fcaebc | 4,536 | hpp | C++ | include/System/Enum_EnumResult.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Enum_EnumResult.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Enum_EnumResult.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.Enum
#include "System/Enum.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.Enum/ParseFailureKind
#include "System/Enum_ParseFailureKind.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Exception
class Exception;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Size: 0x30
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.Enum/EnumResult
struct Enum::EnumResult/*, public System::ValueType*/ {
public:
// System.Object parsedEnum
// Size: 0x8
// Offset: 0x0
::Il2CppObject* parsedEnum;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// System.Boolean canThrow
// Size: 0x1
// Offset: 0x8
bool canThrow;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: canThrow and: m_failure
char __padding1[0x3] = {};
// System.Enum/ParseFailureKind m_failure
// Size: 0x4
// Offset: 0xC
System::Enum::ParseFailureKind m_failure;
// Field size check
static_assert(sizeof(System::Enum::ParseFailureKind) == 0x4);
// System.String m_failureMessageID
// Size: 0x8
// Offset: 0x10
::Il2CppString* m_failureMessageID;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// System.String m_failureParameter
// Size: 0x8
// Offset: 0x18
::Il2CppString* m_failureParameter;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// System.Object m_failureMessageFormatArgument
// Size: 0x8
// Offset: 0x20
::Il2CppObject* m_failureMessageFormatArgument;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// System.Exception m_innerException
// Size: 0x8
// Offset: 0x28
System::Exception* m_innerException;
// Field size check
static_assert(sizeof(System::Exception*) == 0x8);
// Creating value type constructor for type: EnumResult
constexpr EnumResult(::Il2CppObject* parsedEnum_ = {}, bool canThrow_ = {}, System::Enum::ParseFailureKind m_failure_ = {}, ::Il2CppString* m_failureMessageID_ = {}, ::Il2CppString* m_failureParameter_ = {}, ::Il2CppObject* m_failureMessageFormatArgument_ = {}, System::Exception* m_innerException_ = {}) noexcept : parsedEnum{parsedEnum_}, canThrow{canThrow_}, m_failure{m_failure_}, m_failureMessageID{m_failureMessageID_}, m_failureParameter{m_failureParameter_}, m_failureMessageFormatArgument{m_failureMessageFormatArgument_}, m_innerException{m_innerException_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// System.Void Init(System.Boolean canMethodThrow)
// Offset: 0xEFC83C
void Init(bool canMethodThrow);
// System.Void SetFailure(System.Exception unhandledException)
// Offset: 0xEFC848
void SetFailure(System::Exception* unhandledException);
// System.Void SetFailure(System.Enum/ParseFailureKind failure, System.String failureParameter)
// Offset: 0xEFC858
void SetFailure(System::Enum::ParseFailureKind failure, ::Il2CppString* failureParameter);
// System.Void SetFailure(System.Enum/ParseFailureKind failure, System.String failureMessageID, System.Object failureMessageFormatArgument)
// Offset: 0xEFC860
void SetFailure(System::Enum::ParseFailureKind failure, ::Il2CppString* failureMessageID, ::Il2CppObject* failureMessageFormatArgument);
// System.Exception GetEnumParseException()
// Offset: 0xEFC868
System::Exception* GetEnumParseException();
}; // System.Enum/EnumResult
#pragma pack(pop)
static check_size<sizeof(Enum::EnumResult), 40 + sizeof(System::Exception*)> __System_Enum_EnumResultSizeCheck;
static_assert(sizeof(Enum::EnumResult) == 0x30);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::Enum::EnumResult, "System", "Enum/EnumResult");
| 44.910891 | 575 | 0.701499 | [
"object"
] |
88aad7643dd8a8cb43705ad1d8fd3d76111bc349 | 597 | cc | C++ | node_anjian.cc | wangkun611/anjian | f52f60fcfe351d4505f2d125c4a7aaa4852c0415 | [
"MIT"
] | null | null | null | node_anjian.cc | wangkun611/anjian | f52f60fcfe351d4505f2d125c4a7aaa4852c0415 | [
"MIT"
] | null | null | null | node_anjian.cc | wangkun611/anjian | f52f60fcfe351d4505f2d125c4a7aaa4852c0415 | [
"MIT"
] | null | null | null | #include <node.h>
#include <windows.h>
#include <atlbase.h>
void HookKeyboard();
bool moveTo(int x, int y);
namespace anjian {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
HookKeyboard();
}
NODE_MODULE(addon, init)
} // namespace demo | 19.258065 | 68 | 0.683417 | [
"object"
] |
88ad27f49e1ebf3f21fd7bdc84201a0eb05598ae | 3,921 | cpp | C++ | wave_vision/src/utils.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 80 | 2017-03-12T18:57:33.000Z | 2022-03-30T11:44:33.000Z | wave_vision/src/utils.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 210 | 2017-03-13T15:01:34.000Z | 2022-01-15T03:19:44.000Z | wave_vision/src/utils.cpp | wavelab/wavelib | 7bebff52859c8b77f088e39913223904988c141e | [
"MIT"
] | 31 | 2017-08-14T16:54:52.000Z | 2022-01-21T06:44:16.000Z | #include "wave/vision/utils.hpp"
namespace wave {
double focal_length(double fov, double image_width) {
return (image_width / 2.0) / tan(deg2rad(fov) / 2.0);
}
Vec2 focal_length(double hfov,
double vfov,
double image_width,
double image_height) {
Vec2 focal;
focal(0) = focal_length(hfov, image_width);
focal(1) = focal_length(vfov, image_height);
return focal;
}
bool pinholeProject(const Mat3 &K,
const Mat3 &R_GC,
const Vec3 &G_p_C_G,
const Vec3 &G_p_F_G,
Vec2 &result) {
// Note R_GC is is the orientation of the camera in the world frame.
// R_CG is the rotation that transforms *points* in the world frame to the
// camera frame.
Mat3 R_CG = R_GC.transpose();
// Make extrinsic matrix
MatX extrinsic(3, 4);
extrinsic.topLeftCorner<3, 3>() = R_CG;
extrinsic.topRightCorner<3, 1>() = -R_CG * G_p_C_G;
extrinsic(2, 3) = 1;
Vec4 landmark_homogeneous;
landmark_homogeneous << G_p_F_G, 1.;
// project
Vec3 homogeneous = K * extrinsic * landmark_homogeneous;
// get image coordinates from homogenous coordinates
result = homogeneous.head<2>() / homogeneous(2);
// check cheirality
return (homogeneous(2) > 0);
}
Vec2 convertKeypoint(const cv::KeyPoint &keypoint) {
Vec2 vec_keypoint(keypoint.pt.x, keypoint.pt.y);
return vec_keypoint;
}
Vec2 convertKeypoint(const cv::Point2f &keypoint) {
Vec2 vec_keypoint(keypoint.x, keypoint.y);
return vec_keypoint;
}
cv::Point2f convertKeypoint(const Vec2 &keypoint) {
cv::Point2f cv_keypoint((float) keypoint(0), (float) keypoint(1));
return cv_keypoint;
}
std::vector<Vec2> convertKeypoints(const std::vector<cv::KeyPoint> &keypoints) {
std::vector<Vec2> vec_keypoints;
for (const auto &k : keypoints) {
vec_keypoints.emplace_back(k.pt.x, k.pt.y);
}
return vec_keypoints;
}
std::vector<Vec2> convertKeypoints(const std::vector<cv::Point2f> &keypoints) {
std::vector<Vec2> vec_keypoints;
for (const auto &k : keypoints) {
vec_keypoints.emplace_back(k.x, k.y);
}
return vec_keypoints;
}
std::vector<cv::Point2f> convertKeypoints(const std::vector<Vec2> &keypoints) {
std::vector<cv::Point2f> cv_keypoints;
for (const auto &k : keypoints) {
cv_keypoints.emplace_back((float) k(0), (float) k(1));
}
return cv_keypoints;
}
std::vector<cv::Mat> readImageSequence(const std::string &path) {
cv::String img_path(path);
std::vector<cv::String> files;
std::vector<cv::Mat> image_sequence;
int num_images;
cv::VideoCapture sequence(img_path, cv::CAP_IMAGES);
num_images = (int) sequence.get(cv::CAP_PROP_FRAME_COUNT);
if (sequence.isOpened()) {
for (double i = 0; i < num_images; ++i) {
cv::Mat image;
sequence >> image;
image_sequence.push_back(image);
}
} else {
throw std::length_error("No images in image sequence!");
}
return image_sequence;
}
} // namespace wave
namespace YAML {
bool convert<cv::Mat>::decode(const Node &node, cv::Mat &out) {
int rows = node["rows"].as<int>();
int cols = node["cols"].as<int>();
const auto &data = node["data"];
// Check `rows` and `cols` values
if (rows <= 0 || cols <= 0) {
return false;
}
// Check data node is a list of the right length
std::size_t expected_size = rows * cols;
if (!data.IsSequence() || data.size() != expected_size) {
return false;
}
// Copy it to destination
out = cv::Mat(rows, cols, CV_64F);
for (int i = 0, index = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
out.at<double>(i, j) = node["data"][index++].as<double>();
}
}
return true;
}
} // namespace YAML
| 26.315436 | 80 | 0.614384 | [
"vector"
] |
88ba9cf870b0881b23151f0e8cb108ea315986c6 | 12,655 | cc | C++ | servlib/security/SecurityConfig.cc | delay-tolerant-networking/DTN2 | 1c12a9dea32c5cbae8c46db105012a2031f4161e | [
"Apache-2.0"
] | 14 | 2016-06-27T19:28:23.000Z | 2021-06-28T20:41:17.000Z | servlib/security/SecurityConfig.cc | delay-tolerant-networking/DTN2 | 1c12a9dea32c5cbae8c46db105012a2031f4161e | [
"Apache-2.0"
] | 3 | 2020-09-18T13:48:53.000Z | 2021-05-27T18:28:14.000Z | servlib/security/SecurityConfig.cc | lauramazzuca21/DTNME | c97b598b09a8c8e97c2e4136879d9f0e157c8df7 | [
"Apache-2.0"
] | 10 | 2020-09-26T05:08:40.000Z | 2022-01-25T12:57:55.000Z |
#ifdef HAVE_CONFIG_H
# include <dtn-config.h>
#endif
#include "SecurityConfig.h"
#ifdef BSP_ENABLED
#include "Ciphersuite.h"
#include "BP_Local_CS.h"
#include "bundling/Bundle.h"
using namespace std;
namespace dtn {
static const char * log = "/dtn/bundle/security";
ostream& operator<< (ostream &out, EndpointIDPatternNULL &foo) {
if(foo.isnull) {
out << "NULL";
} else {
out << foo.pat.str();
}
return out;
}
ostream& operator<< (ostream &out, EndpointIDNULL &foo) {
if(foo.isnull) {
out << "NULL";
} else {
out << foo.pat.str();
}
return out;
}
ostream& operator<< (ostream &out, IncomingRule &rule) {
out << rule.src.str() << " " << rule.dest.str() << " " << rule.secsrc << " " << rule.secdest<< " ";
set<int>::iterator it;
for(it=rule.csnums.begin();it!= rule.csnums.end();it++) {
out << *it << " ";
}
return out;
}
ostream& operator<< (ostream &out, OutgoingRule &rule) {
out << rule.src.str() << " " << rule.dest.str() << " " << rule.secdest<< " " << rule.csnum;
return out;
}
EndpointIDPatternNULL::EndpointIDPatternNULL() {
isnull = true;
}
EndpointIDPatternNULL::EndpointIDPatternNULL(const oasys::Builder b) {
(void) b;
}
EndpointIDPatternNULL::EndpointIDPatternNULL(const string s) {
if(s == "NULL") {
isnull = true;
} else {
pat = EndpointIDPattern(s);
isnull = false;
}
}
void EndpointIDPatternNULL::serialize(oasys::SerializeAction* a) {
a->process("isnull", &isnull);
a->process("pat", &pat);
}
string EndpointIDPatternNULL::str() {
if(isnull) {
return string("NULL");
} else {
return pat.str();
}
}
EndpointIDNULL::EndpointIDNULL() {
isnull = true;
}
EndpointIDNULL::EndpointIDNULL(const oasys::Builder b) {
(void) b;
}
EndpointIDNULL::EndpointIDNULL(const string s) {
if(s == "NULL") {
isnull = true;
} else {
pat = EndpointID(s);
isnull = false;
}
}
void EndpointIDNULL::serialize(oasys::SerializeAction* a) {
a->process("isnull", &isnull);
a->process("pat", &pat);
}
string EndpointIDNULL::str() {
if(isnull) {
return string("NULL");
} else {
return pat.str();
}
}
IncomingRule::IncomingRule() {
}
OutgoingRule::OutgoingRule(const oasys::Builder b) {
(void) b;
}
OutgoingRule::OutgoingRule() {
}
void OutgoingRule::serialize(oasys::SerializeAction* a) {
a->process("src", &src);
a->process("dest", &dest);
a->process("secdest", &secdest);
a->process("csnum", &csnum);
}
SecurityConfig::SecurityConfig(): privdir("/usr/local/ssl/private/"), certdir("/usr/local/ssl/certs/"){
// define which keys are used with each ciphersuite
// PIB-RSA-SHA256: ciphersuite value: 0x02
pub_keys_ver[2] = string("RSA_sig_cert_<NODE>.pem");
priv_keys_sig[2] = string("RSA_sig_priv_key.pem");
// PCB-RSA-AES128-PAYLOAD-PIB-PCB: ciphersuite value: 0x03
pub_keys_enc[3] = string("RSA_enc_cert_<NODE>.pem");
priv_keys_dec[3] = string("RSA_enc_priv_key.pem");
// ESB-RSA-AES128-EXT: ciphersuite value: 0x04
pub_keys_enc[4] = string("RSA_enc_cert_<NODE>.pem");
priv_keys_dec[4] = string("RSA_enc_priv_key.pem");
// PIB-ECDSA-SHA256: ciphersuite value: 0x06
pub_keys_ver[6] = string("EC_sig_cert1_<NODE>.pem");
priv_keys_sig[6] = string("EC_sig_priv_key1.pem");
// PCB-ECDH-SHA256-AES128: ciphersuite value: 0x07
pub_keys_enc[7] = string("EC_enc_cert1_<NODE>.pem");
priv_keys_dec[7] = string("EC_enc_priv_key1.pem");
// ESB-ECDH-SHA256-AES128: ciphersuite value: 0x08
pub_keys_enc[8] = string("EC_enc_cert1_<NODE>.pem");
priv_keys_dec[8] = string("EC_enc_priv_key1.pem");
// PIB-ECDSA-SHA384: ciphersuite value: 0x0A
pub_keys_ver[10] = string("EC_sig_cert2_<NODE>.pem");
priv_keys_sig[10] = string("EC_sig_priv_key2.pem");
// PCB-ECDH-SHA384-AES256: ciphersuite value: 0x0B
pub_keys_enc[11] = string("EC_enc_cert2_<NODE>.pem");
priv_keys_dec[11] = string("EC_enc_priv_key2.pem");
// ESB-ECDH-SHA384-AES256: ciphersuite value: 0x0C
pub_keys_enc[12] = string("EC_enc_cert2_<NODE>.pem");
priv_keys_dec[12] = string("EC_enc_priv_key2.pem");
// EIB-RSA-SHA256: ciphersuite value: 0x11
pub_keys_ver[17] = string("RSA_sig_cert_<NODE>.pem");
priv_keys_sig[17] = string("RSA_sig_priv_key.pem");
};
BundleProtocol::bundle_block_type_t SecurityConfig::get_block_type(int csnum) {
if(csnum == 1 || csnum == 5 || csnum == 9) {
return dtn::BundleProtocol::BUNDLE_AUTHENTICATION_BLOCK;
} else if(csnum == 2 || csnum == 6 || csnum == 10) {
return dtn::BundleProtocol::PAYLOAD_SECURITY_BLOCK;
} else if(csnum == 3 || csnum == 7 || csnum == 11) {
return dtn::BundleProtocol::CONFIDENTIALITY_BLOCK;
} else if(csnum == 4 || csnum == 8 || csnum == 12) {
return dtn::BundleProtocol::EXTENSION_SECURITY_BLOCK;
}
return dtn::BundleProtocol::UNKNOWN_BLOCK;
}
string SecurityConfig::list_policy() {
stringstream foo(stringstream::out);
vector<IncomingRule>::iterator it;
vector<OutgoingRule>::iterator it2;
foo << "Incoming rules" << endl;
foo << "<rulenum> <src pattern> <dest pattern> <secsrc pattern|NULL> <secdest pattern|NULL> <csnums>" <<endl;
int i=0;
for(it = incoming.begin();it!=incoming.end();it++) {
foo << i << " " << *it << endl;
i++;
}
i=0;
foo << "Outgoing rules" <<endl;
foo << "<rulenum> <src pattern> <dest pattern> <secdest|NULL> <csnum>"<<endl;
for(it2 = outgoing.begin();it2!=outgoing.end();it2++) {
foo <<i << " " << *it2 <<endl;
i++;
}
return foo.str();
}
string SecurityConfig::list_maps() {
stringstream foo(stringstream::out);
map<int, string>::iterator it;
foo << "certdir = " << certdir << endl;
foo << "privdir = " << privdir << endl << endl;
foo << "pub_keys_enc:" <<endl;
for(it = pub_keys_enc.begin(); it != pub_keys_enc.end();it++) {
foo << "(cs num " << (*it).first << ")" << " => " << (*it).second << endl;
}
foo << endl;
foo << "priv_keys_dec:" <<endl;
for(it = priv_keys_dec.begin(); it != priv_keys_dec.end();it++) {
foo << "(cs num " << (*it).first << ")" << " => " << (*it).second << endl;
}
foo << endl;
foo << "pub_keys_ver:" << endl;
for(it = pub_keys_ver.begin(); it != pub_keys_ver.end();it++) {
foo << "(cs num " << (*it).first << ")" << " => " << (*it).second << endl;
}
foo << endl;
foo << "priv_keys_sig:" << endl;
for(it = priv_keys_sig.begin(); it != priv_keys_sig.end();it++) {
foo << "(cs num " << (*it).first << ")" << " => " << (*it).second << endl;
}
foo << endl;
return foo.str();
}
string SecurityConfig::replace_stuff(string input, const string node) {
string n = string("<NODE>");
if(input.find(n) != string::npos) {
input.replace(input.find(n),n.length(),node);
}
return input;
}
string SecurityConfig::get_pub_key_enc(const string dest, int cs) {
return certdir + replace_stuff(pub_keys_enc[cs], dest);
}
string SecurityConfig::get_pub_key_ver(const string src, const int csnum) {
return certdir + replace_stuff(pub_keys_ver[csnum], src);
}
string SecurityConfig::get_priv_key_sig(const string src, const int csnum) {
return privdir + replace_stuff(priv_keys_sig[csnum], src);
}
string SecurityConfig::get_priv_key_dec(const string dest, const int csnum) {
return privdir + replace_stuff(priv_keys_dec[csnum], dest);
}
int
SecurityConfig::prepare_out_blocks(const Bundle* bundle, const LinkRef& link,
BlockInfoVec* xmit_blocks)
{
std::string bundle_src_str = bundle->source().uri().scheme() + "://" +
bundle->source().uri().host();
EndpointID src_node(bundle_src_str);
std::string bundle_dest_str = bundle->dest().uri().scheme() + "://" +
bundle->dest().uri().host();
EndpointID dest_node(bundle_dest_str);
vector<pair<int, EndpointID> > bps;
vector<pair<int, EndpointID> >::iterator it;
Ciphersuite *bp;
log_debug_p(log, "SecurityConfig::prepare_out_blocks() begin");
EndpointID lastsecdeste = Ciphersuite::find_last_secdeste(bundle);
EndpointID lastsecdestp = Ciphersuite::find_last_secdestp(bundle);
if(!bundle->security_config().is_policy_consistant(src_node, dest_node, lastsecdestp, lastsecdeste)) {
log_err_p(log, "SecurityConfig::prepare_out_blocks dropping bundle because policy is inconsistant");
goto fail;
} else {
log_debug_p(log, "SecurityConfig::prepare_out_blocks security policy is consistant");
}
bps = bundle->security_config().get_outgoing_rules(src_node, dest_node, lastsecdestp, lastsecdeste);
for(it=bps.begin();it!=bps.end();it++) {
bp = Ciphersuite::find_suite(it->first);
if(bp == NULL) {
log_err_p(log, "SecurityConfig::prepare_out_blocks() couldn't find ciphersuite %d which our current policy requires. Therefore, we are not going to send this bundle.", it->first);
goto fail;
}
// Tricky, tricky. We must make a fake source to fool the
// block processor into using our security dest
log_debug_p(log, "SecurityConfig::prepare_out_blocks calling prepare on %d with security_dest=%s", bp->cs_num(), (it->second).str().c_str());
BlockInfo temp(BundleProtocol::find_processor(Ciphersuite::config->get_block_type(it->first)));
bp->init_locals(&temp);
dynamic_cast<BP_Local_CS*>(temp.locals())->set_security_dest((it->second).str());
if(BP_FAIL == bp->prepare(bundle, xmit_blocks, &temp, link,
BlockInfo::LIST_NONE)) {
log_err_p(log, "SecurityConfig::prepare_out_blocks() Ciphersuite number %d->prepare returned BP_FAIL", bp->cs_num());
goto fail;
}
}
log_debug_p(log, "SecurityConfig::prepare_out_blocks() done");
return BP_SUCCESS;
fail:
return BP_FAIL;
}
bool SecurityConfig::verify_one_ciphersuite(set<int> cs, const Bundle *bundle, const BlockInfoVec *recv_blocks,EndpointIDPatternNULL &src, EndpointIDPatternNULL &dest) {
set<int>::iterator it;
if(cs.count(0) > 0) {
// Why is this here anymore?
log_debug_p(log, "Allowing bundle because 0 is in the list of allowed ciphersuites");
return true;
} else {
for(it=cs.begin();it!=cs.end();it++) {
if(Ciphersuite::check_validation(bundle, recv_blocks, *it,src, dest)) {
log_debug_p(log, "Allowing bundle because cs=%d say's it is ok", *it);
return true;
} else {
log_debug_p(log, "cs=%d won't ok the bundle", *it);
}
}
}
return false;
}
bool
SecurityConfig::verify_in_policy(const Bundle* bundle)
{
std::string bundle_dest_str = bundle->dest().uri().scheme() + "://" +
bundle->dest().uri().host();
EndpointID dest_node(bundle_dest_str);
std::string bundle_src_str = bundle->source().uri().scheme() + "://" +
bundle->source().uri().host();
EndpointID src_node(bundle_src_str);
const BlockInfoVec* recv_blocks = &bundle->recv_blocks();
vector<IncomingRule>::iterator it;
for(it= Ciphersuite::config->incoming.begin();it != Ciphersuite::config->incoming.end();it++) {
if(it->src.match(src_node) && it->dest.match(dest_node)) {
std::stringstream foo(stringstream::out);
foo << *it << endl;
log_debug_p(log, "Considering rule %s", foo.str().c_str());
if(!verify_one_ciphersuite(it->csnums, bundle, recv_blocks, it->secsrc, it->secdest)) {
return false;
}
} else {
log_debug_p(log, "Ignoring rule because bundle src/dest doesn't match");
}
}
return true;
}
};
#endif
| 35.849858 | 192 | 0.588542 | [
"vector"
] |
88bc1b7b5ca03292cd6fc5ed28da959e7d1e3180 | 7,717 | cpp | C++ | src_sgct/core/app_internal/CoordinatorNodeInternal.cpp | viscom-ulm/viscom_framework_core | 222aa84cef8337d3e63e2aab356c1ad1772dae70 | [
"BSD-2-Clause"
] | 2 | 2017-06-12T17:21:18.000Z | 2017-10-31T19:15:43.000Z | src_sgct/core/app_internal/CoordinatorNodeInternal.cpp | viscom-ulm/viscom_framework_core | 222aa84cef8337d3e63e2aab356c1ad1772dae70 | [
"BSD-2-Clause"
] | 8 | 2017-08-07T16:37:13.000Z | 2018-08-24T07:54:54.000Z | src_sgct/core/app_internal/CoordinatorNodeInternal.cpp | viscom-ulm/viscom_framework_core | 222aa84cef8337d3e63e2aab356c1ad1772dae70 | [
"BSD-2-Clause"
] | 3 | 2017-07-26T09:22:26.000Z | 2018-10-13T06:41:46.000Z | /**
* @file CoordinatorNodeInternal.cpp
* @author Sebastian Maisch <sebastian.maisch@uni-ulm.de>
* @date 2018.06.15
*
* @brief Implementation of the internal coordinator node.
*/
#include "core/main.h"
#include <sgct.h>
#include "CoordinatorNodeInternal.h"
#include "core/imgui/imgui_impl_glfw.h"
#include "core/imgui/imgui_impl_opengl3.h"
#include <imgui.h>
#include "core/app/ApplicationNodeBase.h"
#include <iostream>
#include <fstream>
namespace viscom {
CoordinatorNodeInternal::CoordinatorNodeInternal(FrameworkInternal& fwInternal) :
ApplicationNodeInternal{ fwInternal }
{
// Setup ImGui binding
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui_ImplGlfw_InitForOpenGL(GetFramework().GetEngine()->getCurrentWindowPtr()->getWindowHandle(), !GetFramework().GetEngine()->isMaster() && SHOW_CLIENT_MOUSE_CURSOR);
ImGui_ImplOpenGL3_Init();
ImGui::StyleColorsDark();
}
CoordinatorNodeInternal::~CoordinatorNodeInternal()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void CoordinatorNodeInternal::InitImplementation()
{
SetApplicationNode(GetFramework().GetCoordinatorNodeFactory()(this));
PUSH_DISABLE_DEPRECATED_WARNINGS
GetApplicationNode()->PreWindow();
GetApplicationNode()->InitOpenGL();
POP_WARNINGS
}
void CoordinatorNodeInternal::PreSync()
{
#ifdef VISCOM_SYNCINPUT
{
std::vector<KeyboardEvent> keybEvts;
keybEvts.swap(keyboardEvents_);
keyboardEventsSynced_.setVal(keybEvts);
}
{
std::vector<CharEvent> charEvts;
charEvts.swap(charEvents_);
charEventsSynced_.setVal(charEvts);
}
{
std::vector<MouseButtonEvent> mBtnEvts;
mBtnEvts.swap(mouseButtonEvents_);
mouseButtonEventsSynced_.setVal(mBtnEvts);
}
{
std::vector<MousePosEvent> mPosEvts;
mPosEvts.swap(mousePosEvents_);
mousePosEventsSynced_.setVal(mPosEvts);
}
{
std::vector<MouseScrollEvent> mScrlEvts;
mScrlEvts.swap(mouseScrollEvents_);
mouseScrollEventsSynced_.setVal(mScrlEvts);
}
#endif
syncInfoLocal_.currentTime_ = sgct::Engine::getTime();
syncInfoLocal_.cameraPosition_ = GetFramework().GetCamera()->GetPosition();
syncInfoLocal_.cameraOrientation_ = GetFramework().GetCamera()->GetOrientation();
glm::vec2 relProjectorPos = glm::vec2(GetFramework().GetViewportScreen(0).position_) / glm::vec2(GetFramework().GetViewportScreen(0).size_);
glm::vec2 relQuadSize = glm::vec2(GetFramework().GetViewportQuadSize(0)) / glm::vec2(GetFramework().GetViewportScreen(0).size_);
glm::vec2 relProjectorSize = 1.0f / relQuadSize;
syncInfoLocal_.pickMatrix_ = glm::mat4{ 1.0f };
syncInfoLocal_.pickMatrix_[0][0] = 2.0f * relProjectorSize.x;
syncInfoLocal_.pickMatrix_[1][1] = -2.0f * relProjectorSize.y;
syncInfoLocal_.pickMatrix_[3][0] = (-2.0f * relProjectorPos.x * relProjectorSize.x) - 1.0f;
syncInfoLocal_.pickMatrix_[3][1] = (-2.0f * relProjectorPos.y * relProjectorSize.y) + 1.0f;
syncInfoLocal_.pickMatrix_[3][2] = 1.0f;
syncInfoLocal_.pickMatrix_[3][3] = 1.0f;
syncInfoLocal_.pickMatrix_ = glm::inverse(GetFramework().GetCamera()->GetCentralViewPerspectiveMatrix()) * syncInfoLocal_.pickMatrix_;
syncInfoSynced_.setVal(syncInfoLocal_);
ParseTrackingFrame();
vrInfoLocal_.displayPosLeftController_ = GetLeftControllerDisplayPosition();
vrInfoLocal_.displayPosRightController_ = GetRightControllerDisplayPosition();
vrInfoSynced_.setVal(vrInfoLocal_);
PollAndParseEvents();
ApplicationNodeInternal::PreSync();
}
void CoordinatorNodeInternal::Draw2D(FrameBuffer& fbo)
{
auto windowId = static_cast<std::size_t>(GetFramework().GetEngine()->getCurrentWindowPtr()->getId());
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame(-GetFramework().GetViewportScreen(windowId).position_,
GetFramework().GetViewportQuadSize(windowId), GetFramework().GetViewportScreen(windowId).size_,
GetFramework().GetViewportScaling(windowId), GetCurrentAppTime(), GetElapsedTime());
ImGui::NewFrame();
if (IsCalibrating()) DisplayCalibrationGUI();
ApplicationNodeInternal::Draw2D(fbo);
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void CoordinatorNodeInternal::KeyboardCallback(int key, int scancode, int action, int mods)
{
#ifdef VISCOM_SYNCINPUT
keyboardEvents_.emplace_back(key, scancode, action, mods);
#endif
ImGui_ImplGlfw_KeyCallback(key, scancode, action, mods);
if (ImGui::GetIO().WantCaptureKeyboard) return;
ApplicationNodeInternal::KeyboardCallback(key, scancode, action, mods);
}
void CoordinatorNodeInternal::CharCallback(unsigned int character, int mods)
{
#ifdef VISCOM_SYNCINPUT
charEvents_.emplace_back(character, mods);
#endif
ImGui_ImplGlfw_CharCallback(character);
if (ImGui::GetIO().WantCaptureKeyboard) return;
ApplicationNodeInternal::CharCallback(character, mods);
}
void CoordinatorNodeInternal::MouseButtonCallback(int button, int action)
{
#ifdef VISCOM_SYNCINPUT
mouseButtonEvents_.emplace_back(button, action);
#endif
ImGui_ImplGlfw_MouseButtonCallback(button, action, 0);
if (ImGui::GetIO().WantCaptureMouse) return;
ApplicationNodeInternal::MouseButtonCallback(button, action);
}
void CoordinatorNodeInternal::MousePosCallback(double x, double y)
{
#ifdef VISCOM_SYNCINPUT
mousePosEvents_.emplace_back(x, y);
#endif
ImGui_ImplGlfw_MousePositionCallback(x, y);
if (ImGui::GetIO().WantCaptureMouse) return;
ApplicationNodeInternal::MousePosCallback(x, y);
}
void CoordinatorNodeInternal::MouseScrollCallback(double xoffset, double yoffset)
{
#ifdef VISCOM_SYNCINPUT
mouseScrollEvents_.emplace_back(xoffset, yoffset);
#endif
ImGui_ImplGlfw_ScrollCallback(xoffset, yoffset);
if (ImGui::GetIO().WantCaptureMouse) return;
ApplicationNodeInternal::MouseScrollCallback(xoffset, yoffset);
}
void CoordinatorNodeInternal::AddTuioCursor(TUIO::TuioCursor* tcur)
{
if (!GetFramework().IsInitialized()) return;
#ifdef VISCOM_USE_TUIO
// TODO: TUIO events will not be synced currently. [5/27/2017 Sebastian Maisch]
ApplicationNodeInternal::AddTuioCursor(tcur);
#endif
}
void CoordinatorNodeInternal::UpdateTuioCursor(TUIO::TuioCursor* tcur)
{
if (!GetFramework().IsInitialized()) return;
#ifdef VISCOM_USE_TUIO
// TODO: TUIO events will not be synced currently. [5/27/2017 Sebastian Maisch]
ApplicationNodeInternal::UpdateTuioCursor(tcur);
#endif
}
void CoordinatorNodeInternal::RemoveTuioCursor(TUIO::TuioCursor* tcur)
{
if (!GetFramework().IsInitialized()) return;
#ifdef VISCOM_USE_TUIO
// TODO: TUIO events will not be synced currently. [5/27/2017 Sebastian Maisch]
ApplicationNodeInternal::RemoveTuioCursor(tcur);
#endif
}
void CoordinatorNodeInternal::EncodeData()
{
sgct::SharedData::instance()->writeObj(&vrInfoSynced_);
}
void CoordinatorNodeInternal::DecodeData()
{
sgct::SharedData::instance()->readObj(&vrInfoSynced_);
}
}
| 34.146018 | 176 | 0.689128 | [
"render",
"vector"
] |
88c1d2c159cce17b4727ded3203deaef749fa174 | 4,201 | cpp | C++ | ds_algo/dynamic_prog/house_robber_2.cpp | shubhamgarg21/mission-unnati | b41e14dc2c72b003973199303efaee633d273895 | [
"MIT"
] | null | null | null | ds_algo/dynamic_prog/house_robber_2.cpp | shubhamgarg21/mission-unnati | b41e14dc2c72b003973199303efaee633d273895 | [
"MIT"
] | null | null | null | ds_algo/dynamic_prog/house_robber_2.cpp | shubhamgarg21/mission-unnati | b41e14dc2c72b003973199303efaee633d273895 | [
"MIT"
] | null | null | null | /*
* Author : Shubham Garg
* Date : March 08, 2020
* Problem : https://leetcode.com/problems/house-robber-ii/
* Solution : http://buttercola.blogspot.com/2015/09/leetcode-house-robber-ii.html
* Build : g++ -std=c++11 -lstdc++ house_robber_2.cpp
*/
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
int rob_1(vector<int>& nums) {
if(nums.size() == 0) return 0;
int *dp = new int[nums.size() + 2];
dp[0] = 0;
dp[1] = 0;
bool even = nums.size()%2 == 0;
int mn = nums[0];
int ind = 0;
if(!even){
for(int i=1; i<nums.size(); i++){
if(nums[i] < mn){
mn = nums[i];
ind = i;
}
}
nums.erase(nums.begin() + ind);
}
int min_val = INT32_MAX;
for(int i=2; i<nums.size() + 2; i++){
dp[i] = max(dp[i-1], nums[i-2] + dp[i-2]);
/*
if(even){
dp[i] = max(dp[i-1], nums[i-2] + dp[i-2]);
}else{
if(i%2 == 0){
// odd house
if(i == 2)
dp[i] = max(dp[i-1], nums[i-2] + dp[i-2]);
else{
dp[i] = max(dp[i-1], nums[i-2] + dp[i-2] - min_val);
}
min_val = min(min_val,nums[i-2]);
}else{
//even
dp[i] = max(dp[i-1], nums[i-2] + dp[i-2]);
}
}
*/
}
return dp[nums.size() + 1];
}
// constant space imp.
int rob_2(vector<int>& nums) {
if(nums.size() == 0) return 0;
int d0 = 0;
int d1 = 0;
int d2;
for(int i=0; i<nums.size(); i++){
d2 = max(d1, nums[i] + d0);
d0 = d1;
d1 = d2;
}
return d2;
}
int rob_util(vector<int>& nums){
if(nums.size() == 0) return 0;
int *dp = new int[nums.size()];
dp[0] = 0;
dp[1] = 0;
for(int i=2; i<nums.size()+2; i++){
dp[i] = max(dp[i-1], nums[i-2] + dp[i-2]);
}
return dp[nums.size() + 1];
}
int rob_notworking(vector<int>& nums) {
if(nums.size() == 0) return 0;
bool fst_house[nums.size() + 2];
memset(fst_house,false,sizeof(fst_house));
int *dp = new int[nums.size()];
dp[0] = 0;
dp[1] = 0;
fst_house[0] = false;
fst_house[1] = false;
while(1){
for(int i=2; i<nums.size()+2; i++){
if(dp[i-1] > nums[i-2] + dp[i-2]){
dp[i] = dp[i-1];
fst_house[i] = fst_house[i-1];
if(i == nums.size() + 1)
fst_house[i] = false;
}else{
dp[i] = nums[i-2] + dp[i-2];
if(i-2 == 0)
fst_house[i] = true;
else
fst_house[i] = fst_house[i-2];
}
//dp[i] = max(dp[i-1], nums[i-2] + dp[i-2]);
}
if(!fst_house[nums.size() + 1] || nums.size() < 3)
return dp[nums.size() + 1];
memset(fst_house,false,sizeof(fst_house));
nums.push_back(nums[0]);
nums.erase(nums.begin());
}
}
/*
* The problem is similar to the last one. The only difference is we can either
* 1 Not rob the last one
* 2 Not rob the first one.
* and calculate the maximum.
*/
int rob(vector<int>& nums) {
if(nums.size() == 0) return 0;
if(nums.size() == 1) return nums[0];
//rob the 1st house
int *dp = new int[nums.size()+1];
dp[0] = 0;
dp[1] = nums[0];
//skip the last house
for(int i=2; i<nums.size(); i++){
dp[i] = max(dp[i-1], nums[i-1] + dp[i-2]);
}
//skip the 1st house, may or may not rob the last house
int *dr = new int[nums.size()+1];
dr[0] = 0;
dr[1] = 0;
//skip the last house
for(int i=2; i<nums.size()+1; i++){
dr[i] = max(dr[i-1], nums[i-1] + dr[i-2]);
}
return max(dp[nums.size()-1],dr[nums.size()]);
}
int main(int argc, char** argv){
//vector<int> nums = {1,2,3,1};
//vector<int> nums = {2,3,2};
//vector<int> nums = {2,3,2,1,5};
vector<int> nums = {2,1,1,2};
cout<<rob(nums)<<endl;
return 0;
}
| 22.831522 | 82 | 0.444656 | [
"vector"
] |
88c954f56cfe8b439393e616f5834856161abb1f | 6,717 | cpp | C++ | src/server/library/sysadm-powerd.cpp | cloudbsdorg/sysadm | d01826355905549bf83c07dcd09fb5e11696debc | [
"BSD-2-Clause"
] | 39 | 2016-06-27T12:57:08.000Z | 2020-05-24T16:56:36.000Z | src/server/library/sysadm-powerd.cpp | cloudbsdorg/sysadm | d01826355905549bf83c07dcd09fb5e11696debc | [
"BSD-2-Clause"
] | 14 | 2016-08-09T09:21:18.000Z | 2019-06-04T18:24:35.000Z | src/server/library/sysadm-powerd.cpp | cloudbsdorg/sysadm | d01826355905549bf83c07dcd09fb5e11696debc | [
"BSD-2-Clause"
] | 14 | 2016-08-18T15:30:51.000Z | 2019-11-05T16:58:06.000Z | //===========================================
// TrueOS source code
// Copyright (c) 2017, TrueOS Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "sysadm-general.h"
#include "sysadm-powerd.h"
#include "sysadm-global.h"
#include "globals.h"
#include "sysadm-servicemanager.h"
#define _POWERD_CONF QString("/etc/conf.d/powerd")
#define _POWERD_SYS_CONF QString("/etc/rc.conf")
#define _POWERD_DEFAULT_CONF QString("/etc/defaults/rc.conf")
using namespace sysadm;
//Service options for individual devices
QJsonObject powerd::listOptions(){
QJsonObject out;
out.insert("ac_power_mode", QJsonArray() << "maximum" << "hiadaptive" << "adaptive" << "minumum"); // "-a" flag
out.insert("battery_power_mode", QJsonArray() << "maximum" << "hiadaptive" << "adaptive" << "minumum"); // "-b" flag
out.insert("unknown_power_mode", QJsonArray() << "maximum" << "hiadaptive" << "adaptive" << "minumum"); // "-n" flag
out.insert("adaptive_lower_threshold_percent", "int min=1 max=100"); // "-i" flag
out.insert("adaptive_raise_threshold_percent", "int min=1 max=100"); // "-r" flag
out.insert("min_cpu_freq", "int frequency(hz)>0"); // "-m" flag
out.insert("max_cpu_freq", "int frequency(hz)>0"); // "-M" flag
out.insert("polling_interval_ms", "int milliseconds>0"); // "-p" flag
return out;
}
QJsonObject powerd::readOptions(){
QString val = General::getConfFileValue(_POWERD_CONF, "powerd_args=" );
if(val.isEmpty()){ General::getConfFileValue(_POWERD_SYS_CONF, "powerd_args=" ); }
if(val.isEmpty()){ General::getConfFileValue(_POWERD_DEFAULT_CONF, "powerd_args=" ); }
val = val.simplified();
if(val.startsWith("\"")){ val.remove(0,1); }
if(val.endsWith("\"")){ val.chop(1); }
QStringList args = val.split(" ");
//qDebug() << " - Arguments:" << args;
QJsonObject out;
//Now parse the arguments and list them in the output object
int index = args.indexOf("-a");
if(index>=0 && index < (args.length()-1) ){
out.insert("ac_power_mode", args[index+1] );
}else{
QString ac = General::getConfFileValue(_POWERD_CONF, "powerd_ac_mode=" );
if(ac.isEmpty()){ ac = "adaptive"; }
out.insert("ac_power_mode",ac);
}
index = args.indexOf("-b");
if(index>=0 && index < (args.length()-1) ){
out.insert("battery_power_mode", args[index+1] );
}else{
QString bat = General::getConfFileValue(_POWERD_CONF, "powerd_battery_mode=" );
if(bat.isEmpty()){ bat = "adaptive"; }
out.insert("battery_power_mode",bat);
}
index = args.indexOf("-n");
if(index>=0 && index < (args.length()-1) ){
out.insert("unknown_power_mode", args[index+1] );
}else{
out.insert("unknown_power_mode", "adaptive");
}
index = args.indexOf("-i");
if(index>=0 && index < (args.length()-1) ){
out.insert("adaptive_lower_threshold_percent", args[index+1] );
}else{
out.insert("adaptive_lower_threshold_percent", "50");
}
index = args.indexOf("-r");
if(index>=0 && index < (args.length()-1) ){
out.insert("adaptive_raise_threshold_percent", args[index+1] );
}else{
out.insert("adaptive_raise_threshold_percent", "75");
}
index = args.indexOf("-m");
if(index>=0 && index < (args.length()-1) ){
out.insert("min_cpu_freq", args[index+1] );
}else{
out.insert("min_cpu_freq", "-1");
}
index = args.indexOf("-M");
if(index>=0 && index < (args.length()-1) ){
out.insert("max_cpu_freq", args[index+1] );
}else{
out.insert("max_cpu_freq", "-1");
}
index = args.indexOf("-p");
if(index>=0 && index < (args.length()-1) ){
out.insert("polling_interval_ms", args[index+1] );
}else{
out.insert("polling_interval_ms", "250");
}
return out;
}
QJsonObject powerd::setOptions(QJsonObject obj){
QJsonObject Cobj = readOptions();
//Overlay the user's settings on top of the current settings
QStringList keys = Cobj.keys();
bool foundchange = false;
for(int i=0; i<keys.length(); i++){
if(obj.contains(keys[i])){ foundchange = true; Cobj.insert(keys[i], obj.value(keys[i])); } //This will replace any current setting with the user-requested one
}
if(!foundchange){ return QJsonObject(); } //invalid inputs - nothing to do
//Assemble the argument list based on the options
QStringList args;
for(int i=0; i<keys.length(); i++){
QString val = Cobj.value(keys[i]).toString();
if(keys[i]=="ac_power_mode"){ General::setConfFileValue(_POWERD_CONF, "powerd_ac_mode=", "powerd_ac_mode=\""+val+"\"" ); }
else if(keys[i]=="battery_power_mode"){ General::setConfFileValue(_POWERD_CONF, "powerd_battery_mode=", "powerd_ac_mode=\""+val+"\"" ); }
else if(keys[i]=="unknown_power_mode"){ args << "-n" << val; }
else if(keys[i]=="adaptive_lower_threshold_percent"){ args << "-i" << val; }
else if(keys[i]=="adaptive_raise_threshold_percent"){ args << "-r" << val; }
else if(keys[i]=="min_cpu_freq" && val.toInt()>=0){ args << "-m" << val; }
else if(keys[i]=="max_cpu_freq" && val.toInt()>=0){ args << "-M" << val; }
else if(keys[i]=="polling_interval_ms"){ args << "-p" << val; }
}
//Save the arguments into the settings file
QString device = obj.value("device").toString();
General::setConfFileValue(_POWERD_CONF, "powerd_args=", "powerd_args=\""+args.join(" ")+"\"" );
//Restart the moused daemon for this device
General::RunQuickCommand("service moused."+device+" restart");
return Cobj; //return the object for the settings we just used
}
//Service status for devices (enable/disable device)
QJsonObject powerd::listStatus(){
ServiceManager SMGR;
Service serv = SMGR.GetService("powerd");
QJsonObject out;
out.insert("running", SMGR.isRunning(serv) ? "true" : "false" );
out.insert("enabled", SMGR.isEnabled(serv) ? "true" : "false" );
return out;
}
QJsonObject powerd::startService(){
ServiceManager SMGR;
Service serv = SMGR.GetService("powerd");
bool ok = SMGR.Start(serv);
QJsonObject out;
out.insert("started", ok ? "true" : "false");
return out;
}
QJsonObject powerd::stopService(){
ServiceManager SMGR;
Service serv = SMGR.GetService("powerd");
bool ok = SMGR.Stop(serv);
QJsonObject out;
out.insert("stopped", ok ? "true" : "false");
return out;
}
QJsonObject powerd::enableService(){
ServiceManager SMGR;
Service serv = SMGR.GetService("powerd");
bool ok = SMGR.Enable(serv);
QJsonObject out;
out.insert("enabled", ok ? "true" : "false");
return out;
}
QJsonObject powerd::disableService(){
ServiceManager SMGR;
Service serv = SMGR.GetService("powerd");
bool ok = SMGR.Disable(serv);
QJsonObject out;
out.insert("disabled", ok ? "true" : "false");
return out;
}
| 37.735955 | 162 | 0.651779 | [
"object"
] |
88ccabfdf00e5ebf9294729111cee1956d98cb8a | 30,130 | cc | C++ | alljoyn_core/samples/securitymgr/agent/unit_test/TestUtil.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 33 | 2018-01-12T00:37:43.000Z | 2022-03-24T02:31:36.000Z | alljoyn_core/samples/securitymgr/agent/unit_test/TestUtil.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 1 | 2020-01-05T05:51:27.000Z | 2020-01-05T05:51:27.000Z | alljoyn_core/samples/securitymgr/agent/unit_test/TestUtil.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 30 | 2017-12-13T23:24:00.000Z | 2022-01-25T02:11:19.000Z | /******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#include "TestUtil.h"
#include <stdlib.h>
#include <errno.h>
#include <qcc/Thread.h>
#include <qcc/Util.h>
#include <qcc/Environ.h>
#include <alljoyn/securitymgr/Util.h>
#include "SQLStorageConfig.h"
using namespace ajn;
using namespace ajn::securitymgr;
using namespace std;
/** @file TestUtil.cc */
namespace secmgr_tests {
TestApplicationListener::TestApplicationListener(Condition& _sem,
Mutex& _lock,
Condition& _errorSem,
Mutex& _errorLock,
Condition& _manifestSem,
Mutex& _manifestLock) :
sem(_sem), lock(_lock),
errorSem(_errorSem), errorLock(_errorLock),
manifestSem(_manifestSem), manifestLock(_manifestLock)
{
}
void TestApplicationListener::OnApplicationStateChange(const OnlineApplication* old,
const OnlineApplication* updated)
{
const OnlineApplication* info = updated ? updated : old;
cout << "TAL>> Old Application info = " << (old == nullptr ? "null" : old->ToString().c_str()) << endl;
cout << "TAL>> New Application info = " << (updated == nullptr ? "null" : updated->ToString().c_str()) << endl;
lock.Lock();
events.push_back(*info);
sem.Broadcast();
lock.Unlock();
}
string ToString(const SyncError* er)
{
string result = "SyncError >>";
result += " busName: " + er->app.busName;
result += " type: " + string(SyncError::SyncErrorTypeToString(er->type));
result += " status: " + string(QCC_StatusText(er->status));
return result;
}
void TestApplicationListener::OnSyncError(const SyncError* er)
{
cout << ToString(er) << endl;
errorLock.Lock();
syncErrors.push_back(*er);
errorSem.Broadcast();
errorLock.Unlock();
}
string ManifestUpdateToString(const ManifestUpdate* update)
{
stringstream result;
result << "ManifestUpdate >> ";
result << update->app.busName << " requested ";
result << update->additionalRules.GetRulesSize();
result << " additional rules";
return result.str();
}
static void GetDefaultStorageFilePath(string& storageFilePath)
{
#if !defined(QCC_OS_GROUP_WINDOWS)
storageFilePath = "/tmp";
#else
/* Same path is returned by qcc::GetHomeDir() too */
storageFilePath = Environ::GetAppEnviron()->Find("LOCALAPPDATA").c_str();
if (storageFilePath.empty()) {
storageFilePath = Environ::GetAppEnviron()->Find("USERPROFILE").c_str();
}
#endif
storageFilePath += "/secmgr.db";
}
void TestApplicationListener::OnManifestUpdate(const ManifestUpdate* manifestUpdate)
{
cout << ManifestUpdateToString(manifestUpdate) << endl;
manifestLock.Lock();
manifestUpdates.push_back(*manifestUpdate);
manifestSem.Broadcast();
manifestLock.Unlock();
}
BasicTest::BasicTest() :
ownBus(nullptr), proxyObjectManager(nullptr), tal(nullptr),
secMgr(nullptr), ba(nullptr), storage(nullptr), ca(nullptr), pg(nullptr)
{
}
void BasicTest::SetUp()
{
string storage_path = Environ::GetAppEnviron()->Find(STORAGE_FILEPATH_KEY).c_str();
if (storage_path.empty()) {
GetDefaultStorageFilePath(storage_path);
QCC_ASSERT(!storage_path.empty());
Environ::GetAppEnviron()->Add(STORAGE_FILEPATH_KEY, storage_path.c_str());
}
int status = remove(storage_path.c_str());
if ((status != 0) && (errno != ENOENT)) {
printf("Removing storage %s failed: %s\n", storage_path.c_str(), strerror(errno));
}
StorageFactory& storageFac = StorageFactory::GetInstance();
ba = new BusAttachment("testsecmgr", true);
ba->DeleteDefaultKeyStore("testsecmgr");
ASSERT_TRUE(ba != nullptr);
ASSERT_EQ(ER_OK, ba->Start());
ASSERT_EQ(ER_OK, ba->Connect());
ba->RegisterAboutListener(testAboutListener);
/* Passing nullptr into WhoImplements will listen for all About announcements */
if (ER_OK != ba->WhoImplements(nullptr)) {
printf("WhoImplements nullptr failed.\n");
}
ASSERT_EQ(ER_OK, storageFac.GetStorage(TEST_STORAGE_NAME, storage));
ASSERT_EQ(ER_OK, storage->GetCaStorage(ca));
GroupInfo adminGroup;
storage->GetAdminGroup(adminGroup);
pg = new PolicyGenerator(adminGroup);
}
void BasicTest::InitSecAgent()
{
secAgentLock.Lock();
SecurityAgentFactory& secFac = SecurityAgentFactory::GetInstance();
ASSERT_EQ(ER_OK, secFac.GetSecurityAgent(GetAgentCAStorage(), secMgr, ba));
ASSERT_NE(nullptr, secMgr);
secMgr->SetClaimListener(&aa);
tal = new TestApplicationListener(sem, lock, errorSem, errorLock, manifestSem, manifestLock);
secMgr->RegisterApplicationListener(tal);
secAgentLock.Unlock();
}
void BasicTest::RemoveSecAgent()
{
secAgentLock.Lock();
if (tal) {
secMgr->UnregisterApplicationListener(tal);
delete tal;
tal = nullptr;
}
secMgr = nullptr;
secAgentLock.Unlock();
}
bool BasicTest::UpdateLastAppInfo(OnlineApplication& lastAppInfo, const OnlineApplication& needed, bool useBusName)
{
lock.Lock();
bool found = false;
vector<OnlineApplication>::iterator it = tal->events.begin();
while (it != tal->events.end()) {
if (useBusName ? needed.busName == it->busName : needed.keyInfo == it->keyInfo) {
lastAppInfo = *it;
tal->events.erase(it);
found = true;
break;
}
it++;
}
lock.Unlock();
return found;
}
QStatus BasicTest::CreateProxyObjectManager()
{
if (nullptr == proxyObjectManager) {
ownBus = new BusAttachment("ownsecmgrtest");
ownBus->DeleteDefaultKeyStore("ownsecmgrtest");
QStatus status = ownBus->Start();
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
status = ownBus->Connect();
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
proxyObjectManager = shared_ptr<ProxyObjectManager>(new ProxyObjectManager(ownBus));
status =
ownBus->EnablePeerSecurity(KEYX_ECDHE_NULL " " KEYX_ECDHE_ECDSA, &proxyObjectManager->listener, nullptr, true);
PermissionPolicy::Rule rule;
rule.SetInterfaceName("*");
PermissionPolicy::Rule::Member member;
member.SetMemberName("*");
member.SetMemberType(PermissionPolicy::Rule::Member::NOT_SPECIFIED);
member.SetActionMask(
PermissionPolicy::Rule::Member::ACTION_OBSERVE | PermissionPolicy::Rule::Member::ACTION_PROVIDE |
PermissionPolicy::Rule::Member::ACTION_MODIFY);
rule.SetMembers(1, &member);
ownBus->GetPermissionConfigurator().SetPermissionManifestTemplate(&rule, 1);
IdentityInfo id;
id.name = "basictest";
storage->StoreIdentity(id);
OnlineApplication me;
me.busName = ownBus->GetUniqueName().c_str();
if (!WaitForState(me, PermissionConfigurator::CLAIMABLE, SYNC_UNKNOWN, true)) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return ER_FAIL;
}
KeyInfoNISTP256 ownPublicKey;
status = ownBus->GetPermissionConfigurator().GetSigningPublicKey(ownPublicKey);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
me.keyInfo.SetPublicKey(ownPublicKey.GetPublicKey());
status = secMgr->Claim(me, id);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
if (!WaitForState(me, PermissionConfigurator::CLAIMED, SYNC_UNKNOWN, true)) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return ER_FAIL;
}
status = ownBus->EnablePeerSecurity(KEYX_ECDHE_ECDSA, &proxyObjectManager->listener);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
GroupInfo adminGroup;
status = storage->GetAdminGroup(adminGroup);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
status = storage->StoreGroup(adminGroup);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
status = storage->InstallMembership(me, adminGroup);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
if (!WaitForUpdatesCompleted(me)) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return ER_FAIL;
}
PermissionPolicy p;
PermissionPolicy::Acl pacl;
PermissionPolicy::Peer peers[2];
peers[1].SetType(PermissionPolicy::Peer::PEER_ANY_TRUSTED);
peers[0].SetType(PermissionPolicy::Peer::PEER_FROM_CERTIFICATE_AUTHORITY);
shared_ptr<AgentCAStorage> ca;
storage->GetCaStorage(ca);
KeyInfoNISTP256 pk;
ca->GetCaPublicKeyInfo(pk);
peers[0].SetKeyInfo(&pk);
pacl.SetPeers(2, peers);
pacl.SetRules(1, &rule);
p.SetAcls(1, &pacl);
status = storage->UpdatePolicy(me, p);
if (ER_OK != status) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return status;
}
if (!WaitForUpdatesCompleted(me)) {
cerr << "Failure in " << __FILE__ << "@" << __LINE__ << endl;
return ER_FAIL;
}
}
return ER_OK;
}
bool BasicTest::WaitForState(const OnlineApplication& appInfoNeeded, PermissionConfigurator::ApplicationState newState,
ApplicationSyncState syncState, bool useBusName)
{
if (SYNC_UNKNOWN == syncState) {
switch (newState) {
case PermissionConfigurator::NOT_CLAIMABLE:
case PermissionConfigurator::CLAIMABLE:
syncState = SYNC_UNMANAGED;
break;
case PermissionConfigurator::CLAIMED:
case PermissionConfigurator::NEED_UPDATE:
syncState = SYNC_OK;
break;
}
}
lock.Lock();
printf("\nWaitForState: waiting for event(s) ...\n");
//Prior to entering this function, the test should have taken an action which leads to one or more events.
//These events are handled in a separate thread.
OnlineApplication appInfo;
do {
if (tal && UpdateLastAppInfo(appInfo, appInfoNeeded, useBusName)) { //if no event is in the queue, we will return immediately
printf("WaitForState: Checking event ... ");
if ((newState == appInfo.applicationState)
&& (syncState == appInfo.syncState)) {
printf("ok\n");
lock.Unlock();
return true;
}
printf("not ok, waiting/checking for next event\n");
} else {
QStatus status = sem.TimedWait(lock, 10000);
if (ER_OK != status) {
printf("timeout- failing test - %i\n", status);
break;
}
QCC_ASSERT(tal->events.size()); // assume TimedWait returns != ER_OK in case of timeout
}
} while (true);
printf("WaitForState failed.\n");
printf("\tClaimableState: expected = %s, got %s\n", PermissionConfigurator::ToString(
newState), PermissionConfigurator::ToString(appInfo.applicationState));
printf("\t Busname appInfo.busName (%s)\n", appInfo.busName.c_str());
printf("\t SyncState : expected = %s, got %s\n",
ToString(syncState), ToString(appInfo.syncState));
lock.Unlock();
return false;
}
bool BasicTest::WaitForEvents(size_t numOfEvents)
{
lock.Lock();
printf("\nWaitForState: waiting for %zu event(s) ...\n", numOfEvents);
//Prior to entering this function, the test should have taken an action which leads to one or more events.
//These events are handled in a separate thread.
do {
if (tal && (tal->events.size() == numOfEvents)) { //if no event is in the queue, we will return immediately
break;
} else {
QStatus status = sem.TimedWait(lock, 10000);
if (ER_OK != status) {
printf("timeout- failing test - %i\n", status);
break;
}
QCC_ASSERT(tal->events.size()); // assume TimedWait returns != ER_OK in case of timeout
}
} while (true);
lock.Unlock();
return false;
}
bool BasicTest::CheckRemotePolicy(const OnlineApplication& app, PermissionPolicy& expected)
{
bool result = true;
CreateProxyObjectManager();
printf("Checking remote policy ... ");
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return false;
}
PermissionPolicy remote;
status = mngdProxy.GetPolicy(remote);
if (ER_OK != status) {
printf("failed to GetPolicy\n");
return false;
}
if (expected != remote) {
printf("mismatching remote policy: expected %s, got %s\n",
expected.ToString().c_str(),
remote.ToString().c_str());
return false;
}
printf("ok\n");
return result;
}
bool BasicTest::CheckStoredPolicy(const OnlineApplication& app, PermissionPolicy& expected)
{
bool result = true;
QStatus status = ER_OK;
CreateProxyObjectManager();
printf("Checking stored policy ... ");
PermissionPolicy stored;
status = ca->GetPolicy(app, stored);
if (ER_OK != status) {
printf("failed to GetPolicy\n");
return false;
}
if (expected != stored) {
printf("mismatching stored policy: expected %s, got %s\n",
expected.ToString().c_str(),
stored.ToString().c_str());
return false;
}
printf("ok\n");
return result;
}
bool BasicTest::CheckPolicy(const OnlineApplication& app, PermissionPolicy& expected)
{
return CheckRemotePolicy(app, expected) && CheckStoredPolicy(app, expected);
}
QStatus BasicTest::Reset(const OnlineApplication& app)
{
CreateProxyObjectManager();
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return status;
}
return mngdProxy.Reset();
}
QStatus BasicTest::GetMembershipSummaries(const OnlineApplication& app, vector<MembershipSummary>& summaries)
{
CreateProxyObjectManager();
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return status;
}
return mngdProxy.GetMembershipSummaries(summaries);
}
QStatus BasicTest::GetPolicyVersion(const OnlineApplication& app, uint32_t& version)
{
CreateProxyObjectManager();
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return status;
}
return mngdProxy.GetPolicyVersion(version);
}
QStatus BasicTest::GetIdentity(const OnlineApplication& app, IdentityCertificateChain& idCertChain)
{
CreateProxyObjectManager();
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return status;
}
return mngdProxy.GetIdentity(idCertChain);
}
QStatus BasicTest::GetClaimCapabilities(const OnlineApplication& app,
PermissionConfigurator::ClaimCapabilities& claimCaps,
PermissionConfigurator::ClaimCapabilityAdditionalInfo& claimCapInfo)
{
CreateProxyObjectManager();
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy, ProxyObjectManager::ECDHE_NULL);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return status;
}
return mngdProxy.GetClaimCapabilities(claimCaps, claimCapInfo);
}
bool BasicTest::CheckDefaultPolicy(const OnlineApplication& app)
{
bool result = true;
CreateProxyObjectManager();
printf("Retrieving default policy ... ");
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to the application\n");
return false;
}
PermissionPolicy defaultPolicy;
status = mngdProxy.GetDefaultPolicy(defaultPolicy);
if (ER_OK != status) {
printf("failed to GetDefaultPolicy\n");
return false;
}
printf("ok\n");
if (!CheckRemotePolicy(app, defaultPolicy)) {
return false;
}
printf("Retrieving stored policy ... ");
PermissionPolicy stored;
status = ca->GetPolicy(app, stored);
QStatus expectedStatus = ER_END_OF_DATA;
if (expectedStatus != status) {
printf("mismatching status: expected %i, got %i\n", expectedStatus, status);
return false;
}
printf("ok\n");
return result;
}
bool BasicTest::CheckRemoteIdentity(const OnlineApplication& app,
IdentityInfo& expected,
ajn::securitymgr::Manifest& expectedManifest,
IdentityCertificate& remoteIdentity,
ajn::securitymgr::Manifest& remoteManifest)
{
CreateProxyObjectManager();
printf("Checking remote identity ... \n");
ProxyObjectManager::ManagedProxyObject mngdProxy(app);
QStatus status = proxyObjectManager->GetProxyObject(mngdProxy);
if (ER_OK != status) {
printf("failed to connect to application\n");
return false;
}
IdentityCertificateChain remoteIdentityChain;
status = mngdProxy.GetIdentity(remoteIdentityChain);
if (ER_OK != status) {
printf("failed to GetIdentity\n");
return false;
}
remoteIdentity = remoteIdentityChain[0];
string expectedAlias = expected.guid.ToString().c_str();
string remoteAlias = remoteIdentity.GetAlias().c_str();
if (expectedAlias != remoteAlias) {
printf("mismatching alias: expected %s, got %s\n", expectedAlias.c_str(), remoteAlias.c_str());
return false;
}
status = mngdProxy.GetManifest(remoteManifest);
if (ER_OK != status) {
printf("failed to GetManifest\n");
return false;
}
if (!remoteManifest.TemplateEquals(expectedManifest)) {
printf("mismatching remote manifest: expected %s, got %s\n",
expectedManifest.ToString().c_str(),
remoteManifest.ToString().c_str());
return false;
}
printf("ok\n");
return true;
}
bool BasicTest::CheckIdentity(const OnlineApplication& app,
IdentityInfo& expected,
ajn::securitymgr::Manifest& expectedManifest)
{
IdentityCertificate remoteIdentity;
ajn::securitymgr::Manifest remoteManifest;
if (!CheckRemoteIdentity(app, expected, expectedManifest,
remoteIdentity, remoteManifest)) {
return false;
}
printf("Checking stored identity ... ");
QStatus status = ER_OK;
IdentityCertificateChain storedIdCerts;
ajn::securitymgr::Manifest storedManifest;
status = ca->GetIdentityCertificatesAndManifest(app, storedIdCerts, storedManifest);
if (ER_OK != status) {
printf("failed to GetIdentityCertificateAndManifest\n");
return false;
}
String storedDer;
status = storedIdCerts[0].EncodeCertificateDER(storedDer);
if (ER_OK != status) {
printf("failed to encode stored certificate\n");
return false;
}
String remoteDer;
status = remoteIdentity.EncodeCertificateDER(remoteDer);
if (ER_OK != status) {
printf("failed to encode remote certificate\n");
return false;
}
if (storedDer != remoteDer) {
printf("mismatching encoded certificates\n");
return false;
}
if (!storedManifest.TemplateEquals(expectedManifest)) {
printf("mismatching stored manifest: expected %s, got %s\n",
expectedManifest.ToString().c_str(),
storedManifest.ToString().c_str());
return false;
}
printf("ok\n");
return true;
}
bool BasicTest::CheckMemberships(const OnlineApplication& app, vector<GroupInfo> expected)
{
printf("Checking remote memberships ... ");
vector<MembershipSummary> remote;
QStatus status = GetMembershipSummaries(app, remote);
if (ER_OK != status) {
printf("failed to GetMembershipSummaries\n");
return false;
}
size_t expectedSize = expected.size();
size_t remoteSize = remote.size();
if (expectedSize != remoteSize) {
printf("mismatching size: expected %lu, got %lu\n",
(unsigned long)expectedSize,
(unsigned long)remoteSize);
return false;
}
vector<MembershipCertificateChain> stored;
status = ca->GetMembershipCertificates(app, stored);
if (ER_OK != status) {
printf("failed to GetMembershipCertificates\n");
return status;
}
vector<GroupInfo>::size_type e;
vector<MembershipCertificate>::size_type s;
vector<MembershipSummary>::size_type r;
// for each expected membership
for (e = 0; e != expected.size(); e++) {
// find serial number from storage
string serial;
for (s = 0; s != stored.size(); s++) {
if (stored[s][0].GetGuild() == expected[e].guid) {
serial = string((const char*)stored[s][0].GetSerial(),
stored[s][0].GetSerialLen());
break;
}
}
if (serial.empty()) {
printf("could not determine serial number for %s\n",
expected[e].name.c_str());
return false;
}
// find serial number in remotes
for (r = 0; r != remote.size(); r++) {
if (remote[r].serial == serial) {
break;
}
}
if (r == remote.size()) {
printf("could not find remote certificate for %s\n",
expected[e].name.c_str());
return false;
}
// remove from remotes
remote.erase(remote.begin() + r);
}
if (remote.size() != 0) {
printf("found unexpected remote certificate\n");
return false;
}
printf("ok\n");
return true;
}
bool BasicTest::CheckSyncState(const OnlineApplication& appinfo, ApplicationSyncState expected)
{
printf("Checking sync state in security agent ... ");
OnlineApplication check;
check.keyInfo = appinfo.keyInfo;
QStatus status = secMgr->GetApplication(check);
if (ER_OK != status) {
printf("failed to GetApplication\n");
return false;
}
ApplicationSyncState actual = check.syncState;
if (expected != actual) {
printf("unexpected syncState: expected %s , got %s\n",
ToString(expected), ToString(actual));
return false;
}
printf("ok\n");
return true;
}
bool BasicTest::WaitForUpdatesCompleted(const OnlineApplication& app)
{
printf("Waiting for updates completed ... ");
bool result = true;
result = WaitForState(app, PermissionConfigurator::CLAIMED, SYNC_PENDING);
if (!result) {
return result;
}
result = WaitForState(app, PermissionConfigurator::CLAIMED, SYNC_OK);
if (!result) {
return result;
}
result = CheckSyncState(app, SYNC_OK);
return result;
}
bool BasicTest::WaitForSyncError(SyncErrorType type, QStatus status)
{
printf("Waiting for sync error ... ");
bool result = false;
errorLock.Lock();
do {
if (tal && tal->syncErrors.size()) {
vector<SyncError>::iterator it = tal->syncErrors.begin();
QStatus errorStatus = it->status;
SyncErrorType errorType = it->type;
result = ((errorType == type) && (errorStatus == status));
tal->syncErrors.erase(it);
errorLock.Unlock();
if (result == true) {
printf("ok\n");
} else if (errorType != type) {
printf("unexpected SyncErrorType: expected %s, got %s\n",
SyncError::SyncErrorTypeToString(type),
SyncError::SyncErrorTypeToString(errorType));
} else if (errorStatus != status) {
printf("unexpected Status: expected %s, got %s\n",
QCC_StatusText(status), QCC_StatusText(errorStatus));
}
return result;
} else {
QStatus status = errorSem.TimedWait(errorLock, 5000);
if (ER_OK != status) {
printf("timeout\n");
break;
}
}
} while (true);
errorLock.Unlock();
return false;
}
bool BasicTest::WaitForManifestUpdate(ManifestUpdate& manifestUpdate)
{
printf("Waiting for manifest update ... ");
manifestLock.Lock();
do {
if (tal && tal->manifestUpdates.size()) {
vector<ManifestUpdate>::iterator it =
tal->manifestUpdates.begin();
manifestUpdate = *it;
tal->manifestUpdates.erase(it);
manifestLock.Unlock();
printf("ok\n");
return true;
} else {
QStatus status = manifestSem.TimedWait(manifestLock, 5000);
if (ER_OK != status) {
printf("timeout\n");
break;
}
}
} while (true);
manifestLock.Unlock();
return false;
}
bool BasicTest::CheckUnexpectedSyncErrors()
{
printf("Checking for unexpected sync errors ... ");
if (tal && tal->syncErrors.size() > 0) {
printf("%lu unexpected sync error(s)\n",
(unsigned long)tal->syncErrors.size());
return false;
}
printf("ok\n");
return true;
}
bool BasicTest::CheckUnexpectedManifestUpdates()
{
printf("Checking for unexpected manifest updates ... ");
if (tal && tal->manifestUpdates.size() > 0) {
printf("%lu unexpected manifest update(s)\n",
(unsigned long)tal->manifestUpdates.size());
return false;
}
printf("ok\n");
return true;
}
void BasicTest::TearDown()
{
EXPECT_TRUE(CheckUnexpectedSyncErrors());
EXPECT_TRUE(CheckUnexpectedManifestUpdates());
proxyObjectManager = nullptr;
if (nullptr != ownBus) {
ownBus->Disconnect();
ownBus->Stop();
ownBus->ClearKeyStore();
ownBus->Join();
delete ownBus;
ownBus = nullptr;
}
delete pg;
pg = nullptr;
if (secMgr) {
RemoveSecAgent();
}
ba->UnregisterAboutListener(testAboutListener);
ba->Disconnect();
ba->Stop();
ba->ClearKeyStore();
ba->Join();
delete ba;
ba = nullptr;
storage->Reset();
}
QStatus BasicTest::GetPublicKey(const TestApplication& app, OnlineApplication& appInfo)
{
appInfo.busName = app.GetBusName();
QStatus status = CreateProxyObjectManager();
if (ER_OK != status) {
EXPECT_EQ(ER_OK, status);
return status;
}
ProxyObjectManager::ManagedProxyObject ta(appInfo);
status = proxyObjectManager->GetProxyObject(ta, app.IsClaimed() ?
ProxyObjectManager::ECDHE_DSA : ProxyObjectManager::ECDHE_NULL);
if (ER_OK != status) {
return status;
}
ECCPublicKey key;
status = ta.GetPublicKey(key);
if (ER_OK != status) {
return status;
}
appInfo.keyInfo.SetPublicKey(&key);
return status;
}
}
| 32.643554 | 133 | 0.612878 | [
"vector"
] |
88d1742d945bdf9d4ac37c94b8249b9ee09cecfe | 16,176 | cpp | C++ | fboss/agent/hw/bcm/BcmCosQueueManagerUtils.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 834 | 2015-03-10T18:12:28.000Z | 2022-03-31T20:16:17.000Z | fboss/agent/hw/bcm/BcmCosQueueManagerUtils.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 82 | 2015-04-07T08:48:29.000Z | 2022-03-11T21:56:58.000Z | fboss/agent/hw/bcm/BcmCosQueueManagerUtils.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 296 | 2015-03-11T03:45:37.000Z | 2022-03-14T22:54:22.000Z | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/bcm/BcmCosQueueManagerUtils.h"
#include "fboss/agent/hw/bcm/BcmCosQueueFBConvertors.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/switch_asics/Tomahawk3Asic.h"
#include "fboss/agent/hw/switch_asics/Tomahawk4Asic.h"
#include "fboss/agent/hw/switch_asics/TomahawkAsic.h"
#include "fboss/agent/hw/switch_asics/Trident2Asic.h"
#include <folly/logging/xlog.h>
#include <thrift/lib/cpp/util/EnumUtils.h>
extern "C" {
#include <bcm/cosq.h>
}
using namespace facebook::fboss;
namespace {
using facebook::fboss::BcmCosQueueStatType;
using facebook::fboss::cfg::QueueCongestionBehavior;
using AqmMap = facebook::fboss::PortQueueFields::AQMMap;
constexpr int kWredDiscardProbability = 100;
const std::map<BcmCosQueueStatType, bcm_cosq_stat_t> kBcmCosqStats = {
{BcmCosQueueStatType::DROPPED_BYTES, bcmCosqStatDroppedBytes},
{BcmCosQueueStatType::DROPPED_PACKETS, bcmCosqStatDroppedPackets},
{BcmCosQueueStatType::OUT_BYTES, bcmCosqStatOutBytes},
{BcmCosQueueStatType::OUT_PACKETS, bcmCosqStatOutPackets},
{BcmCosQueueStatType::OBM_LOSSY_HIGH_PRI_DROPPED_PACKETS,
bcmCosqStatOBMLossyHighPriDroppedPackets},
{BcmCosQueueStatType::OBM_LOSSY_HIGH_PRI_DROPPED_BYTES,
bcmCosqStatOBMLossyHighPriDroppedBytes},
{BcmCosQueueStatType::OBM_LOSSY_LOW_PRI_DROPPED_PACKETS,
bcmCosqStatOBMLossyLowPriDroppedPackets},
{BcmCosQueueStatType::OBM_LOSSY_LOW_PRI_DROPPED_BYTES,
bcmCosqStatOBMLossyLowPriDroppedBytes},
{BcmCosQueueStatType::OBM_HIGH_WATERMARK, bcmCosqStatOBMHighWatermark},
};
// Default Port Queue settings
// Common settings among different chips
constexpr uint8_t kDefaultPortQueueId = 0;
constexpr auto kDefaultPortQueueScheduling =
facebook::fboss::cfg::QueueScheduling::WEIGHTED_ROUND_ROBIN;
constexpr auto kDefaultPortQueueWeight = 1;
const auto kPortQueueNoAqm = AqmMap();
constexpr bcm_cosq_control_drop_limit_alpha_value_t kDefaultPortQueueAlpha =
bcmCosqControlDropLimitAlpha_2;
constexpr int kDefaultPortQueuePacketsPerSecMin = 0;
constexpr int kDefaultPortQueuePacketsPerSecMax = 0;
cfg::Range getRange(uint32_t minimum, uint32_t maximum) {
cfg::Range range;
range.minimum_ref() = minimum;
range.maximum_ref() = maximum;
return range;
}
cfg::PortQueueRate getPortQueueRatePps(uint32_t minimum, uint32_t maximum) {
cfg::PortQueueRate portQueueRate;
portQueueRate.pktsPerSec_ref() = getRange(minimum, maximum);
return portQueueRate;
}
AqmMap makeDefauleAqmMap(int32_t threshold) {
AqmMap aqms;
facebook::fboss::cfg::LinearQueueCongestionDetection detection;
detection.minimumLength_ref() = threshold;
detection.maximumLength_ref() = threshold;
detection.probability_ref() = kWredDiscardProbability;
for (auto behavior :
{QueueCongestionBehavior::EARLY_DROP, QueueCongestionBehavior::ECN}) {
facebook::fboss::cfg::ActiveQueueManagement aqm;
aqm.behavior_ref() = behavior;
aqm.detection_ref()->linear_ref() = detection;
aqms.emplace(behavior, aqm);
}
return aqms;
}
// Unique setting for each single chip
// ======TD2======
// default port queue shared bytes is 8 mmu units
constexpr int kDefaultTD2PortQueueSharedBytes = 1664;
// ======TH======
// default Aqm thresholds
constexpr int32_t kDefaultTHAqmThreshold = 13631280;
const auto kDefaultTHPortQueueAqm = makeDefauleAqmMap(kDefaultTHAqmThreshold);
// default port queue shared bytes is 8 mmu units
constexpr int kDefaultTHPortQueueSharedBytes = 1664;
// ======TH3======
// default port queue shared bytes is 8 mmu units
constexpr int kDefaultTH3PortQueueSharedBytes = 2032;
constexpr int32_t kDefaultTH3AqmThreshold = 13631418;
const auto kDefaultTH3PortQueueAqm = makeDefauleAqmMap(kDefaultTH3AqmThreshold);
// ======TH4======
// TODO(joseph5wu) TH4 default shared bytes is 0, which needs to clarify w/ BRCM
constexpr int kDefaultTH4PortQueueSharedBytes = 0;
// TODO(joseph5wu) It seems like both TH3 and TH4 default aqm threshold is
// 133168898 now. CS00011560232
constexpr int32_t kDefaultTH4AqmThreshold = 13631418;
const auto kDefaultTH4PortQueueAqm = makeDefauleAqmMap(kDefaultTH4AqmThreshold);
} // namespace
namespace facebook::fboss::utility {
bcm_cosq_stat_t getBcmCosqStatType(BcmCosQueueStatType type) {
return kBcmCosqStats.at(type);
}
const PortQueue& getTD2DefaultUCPortQueueSettings() {
// Since the default queue is constant, we can use static to cache this
// object here.
static Trident2Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::UNICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::UNICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTD2PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTHDefaultUCPortQueueSettings() {
static TomahawkAsic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::UNICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::UNICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTHPortQueueSharedBytes,
.aqms = kDefaultTHPortQueueAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTH3DefaultUCPortQueueSettings() {
static Tomahawk3Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::UNICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::UNICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTH3PortQueueSharedBytes,
.aqms = kDefaultTH3PortQueueAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTH4DefaultUCPortQueueSettings() {
static Tomahawk4Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::UNICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::UNICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTH4PortQueueSharedBytes,
.aqms = kDefaultTH4PortQueueAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTD2DefaultMCPortQueueSettings() {
static Trident2Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTD2PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTHDefaultMCPortQueueSettings() {
static TomahawkAsic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTHPortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTH3DefaultMCPortQueueSettings() {
static Tomahawk3Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTH3PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTH4DefaultMCPortQueueSettings() {
static Tomahawk4Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, false /*is front panel port*/),
.scalingFactor = bcmAlphaToCfgAlpha(kDefaultPortQueueAlpha),
.name = std::nullopt,
.sharedBytes = kDefaultTH4PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getDefaultPortQueueSettings(
BcmChip chip,
cfg::StreamType streamType) {
switch (streamType) {
case cfg::StreamType::UNICAST:
switch (chip) {
case BcmChip::TRIDENT2:
return getTD2DefaultUCPortQueueSettings();
case BcmChip::TOMAHAWK:
return getTHDefaultUCPortQueueSettings();
case BcmChip::TOMAHAWK3:
return getTH3DefaultUCPortQueueSettings();
case BcmChip::TOMAHAWK4:
return getTH4DefaultUCPortQueueSettings();
}
case cfg::StreamType::MULTICAST:
switch (chip) {
case BcmChip::TRIDENT2:
return getTD2DefaultMCPortQueueSettings();
case BcmChip::TOMAHAWK:
return getTHDefaultMCPortQueueSettings();
case BcmChip::TOMAHAWK3:
return getTH3DefaultMCPortQueueSettings();
case BcmChip::TOMAHAWK4:
return getTH4DefaultMCPortQueueSettings();
}
case cfg::StreamType::ALL:
break;
}
throw FbossError(
"Port queue doesn't support streamType:",
apache::thrift::util::enumNameSafe(streamType));
}
const PortQueue& getTD2DefaultMCCPUQueueSettings() {
static Trident2Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, true /*cpu port*/),
.scalingFactor = std::nullopt,
.name = std::nullopt,
.sharedBytes = kDefaultTD2PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTHDefaultMCCPUQueueSettings() {
static TomahawkAsic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, true /*cpu port*/),
.scalingFactor = std::nullopt,
.name = std::nullopt,
.sharedBytes = kDefaultTHPortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTH3DefaultMCCPUQueueSettings() {
static Tomahawk3Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, true /*cpu port*/),
.scalingFactor = std::nullopt,
.name = std::nullopt,
.sharedBytes = kDefaultTH3PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getTH4DefaultMCCPUQueueSettings() {
static Tomahawk4Asic asic;
static const PortQueue kPortQueue{PortQueueFields{
.id = kDefaultPortQueueId,
.scheduling = kDefaultPortQueueScheduling,
.streamType = cfg::StreamType::MULTICAST,
.weight = kDefaultPortQueueWeight,
.reservedBytes = asic.getDefaultReservedBytes(
cfg::StreamType::MULTICAST, true /*cpu port*/),
.scalingFactor = std::nullopt,
.name = std::nullopt,
.sharedBytes = kDefaultTH4PortQueueSharedBytes,
.aqms = kPortQueueNoAqm,
.portQueueRate = getPortQueueRatePps(
kDefaultPortQueuePacketsPerSecMin, kDefaultPortQueuePacketsPerSecMax),
}};
return kPortQueue;
}
const PortQueue& getDefaultControlPlaneQueueSettings(
BcmChip chip,
cfg::StreamType streamType) {
switch (streamType) {
case cfg::StreamType::MULTICAST:
switch (chip) {
case BcmChip::TRIDENT2:
return getTD2DefaultMCCPUQueueSettings();
case BcmChip::TOMAHAWK:
return getTHDefaultMCCPUQueueSettings();
case BcmChip::TOMAHAWK3:
return getTH3DefaultMCCPUQueueSettings();
case BcmChip::TOMAHAWK4:
return getTH4DefaultMCCPUQueueSettings();
}
case cfg::StreamType::UNICAST:
case cfg::StreamType::ALL:
throw FbossError("Control Plane doesn't support unicast queue");
}
throw FbossError(
"Control Plane queue doesn't support streamType:",
apache::thrift::util::enumNameSafe(streamType));
;
}
int getMaxCPUQueueSize(int unit) {
int maxQueueNum = 0;
auto rv = bcm_rx_queue_max_get(unit, &maxQueueNum);
bcmCheckError(rv, "failed to get max rx cos queue number");
// bcm_rx_queue_max_get will return the largest queue id for rx port since
// CPU usually has more queues than regular port, this function will basically
// return the leagest queue id for cpu MC queues.
// As Broadcom SDK use 0 as the first queue, so the max size of rx queues will
// be maxQueueNum + 1.
return maxQueueNum + 1;
}
} // namespace facebook::fboss::utility
| 38.061176 | 80 | 0.735843 | [
"object"
] |
88d388d9070a32df949bf30b294b92d5d595194c | 4,268 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/statusbar/policy/AccessibilityController.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/statusbar/policy/AccessibilityController.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/statusbar/policy/AccessibilityController.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/systemui/statusbar/policy/AccessibilityController.h"
#include "Elastos.Droid.Content.h"
#include "Elastos.CoreLibrary.IO.h"
#include "Elastos.CoreLibrary.Utility.h"
using Elastos::Droid::View::Accessibility::IAccessibilityManager;
using Elastos::Droid::View::Accessibility::EIID_IAccessibilityManagerAccessibilityStateChangeListener;
using Elastos::Droid::View::Accessibility::EIID_IAccessibilityManagerTouchExplorationStateChangeListener;
using Elastos::Utility::CArrayList;
namespace Elastos {
namespace Droid {
namespace SystemUI {
namespace StatusBar {
namespace Policy {
CAR_INTERFACE_IMPL_3(AccessibilityController, Object, IAccessibilityController \
, IAccessibilityManagerAccessibilityStateChangeListener
, IAccessibilityManagerTouchExplorationStateChangeListener);
AccessibilityController::AccessibilityController(
/* [in] */ IContext* context)
: mAccessibilityEnabled(FALSE)
, mTouchExplorationEnabled(FALSE)
{
CArrayList::New((IArrayList**)&mChangeCallbacks);
AutoPtr<IInterface> obj;
context->GetSystemService(IContext::ACCESSIBILITY_SERVICE, (IInterface**)&obj);
AutoPtr<IAccessibilityManager> am = IAccessibilityManager::Probe(obj);
Boolean tmp = FALSE;
am->AddTouchExplorationStateChangeListener(this, &tmp);
am->AddAccessibilityStateChangeListener(this, &tmp);
am->IsEnabled(&mAccessibilityEnabled);
am->IsTouchExplorationEnabled(&mTouchExplorationEnabled);
}
ECode AccessibilityController::IsAccessibilityEnabled(
/* [out] */ Boolean* enabled)
{
VALIDATE_NOT_NULL(enabled);
*enabled = mAccessibilityEnabled;
return NOERROR;
}
ECode AccessibilityController::IsTouchExplorationEnabled(
/* [out] */ Boolean* enabled)
{
VALIDATE_NOT_NULL(enabled);
*enabled = mTouchExplorationEnabled;
return NOERROR;
}
ECode AccessibilityController::Dump(
/* [in] */ IFileDescriptor* fd,
/* [in] */ IPrintWriter* pw,
/* [in] */ ArrayOf<String>* args)
{
pw->Println(String("AccessibilityController state:"));
pw->Print(String(" mAccessibilityEnabled="));
pw->Println(mAccessibilityEnabled);
pw->Print(String(" mTouchExplorationEnabled="));
pw->Println(mTouchExplorationEnabled);
return NOERROR;
}
ECode AccessibilityController::AddStateChangedCallback(
/* [in] */ IAccessibilityStateChangedCallback* cb)
{
mChangeCallbacks->Add(cb);
cb->OnStateChanged(mAccessibilityEnabled, mTouchExplorationEnabled);
return NOERROR;
}
ECode AccessibilityController::RemoveStateChangedCallback(
/* [in] */ IAccessibilityStateChangedCallback* cb)
{
mChangeCallbacks->Remove(cb);
return NOERROR;
}
void AccessibilityController::FireChanged()
{
Int32 N = 0;
mChangeCallbacks->GetSize(&N);
for (Int32 i = 0; i < N; i++) {
AutoPtr<IInterface> obj;
mChangeCallbacks->Get(i, (IInterface**)&obj);
IAccessibilityStateChangedCallback::Probe(obj)->OnStateChanged(mAccessibilityEnabled
, mTouchExplorationEnabled);
}
}
ECode AccessibilityController::OnAccessibilityStateChanged(
/* [in] */ Boolean enabled)
{
mAccessibilityEnabled = enabled;
FireChanged();
return NOERROR;
}
ECode AccessibilityController::OnTouchExplorationStateChanged(
/* [in] */ Boolean enabled)
{
mTouchExplorationEnabled = enabled;
FireChanged();
return NOERROR;
}
} // namespace Policy
} // namespace StatusBar
} // namespace SystemUI
} // namespace Droid
} // namespace Elastos
| 33.085271 | 105 | 0.717198 | [
"object"
] |
88d38ff954cb464628b2a6f3bf73d38c2d8d10cd | 15,567 | cpp | C++ | OpenFrameworks/IngoLedMapperApp/src/Layout/GuiManager.cpp | ImanolGo/IngoLedMapper | d0463075aebee6572c696876c14762832dee4ed4 | [
"MIT",
"Unlicense"
] | null | null | null | OpenFrameworks/IngoLedMapperApp/src/Layout/GuiManager.cpp | ImanolGo/IngoLedMapper | d0463075aebee6572c696876c14762832dee4ed4 | [
"MIT",
"Unlicense"
] | null | null | null | OpenFrameworks/IngoLedMapperApp/src/Layout/GuiManager.cpp | ImanolGo/IngoLedMapper | d0463075aebee6572c696876c14762832dee4ed4 | [
"MIT",
"Unlicense"
] | null | null | null | /*
* GuiManager.cpp
* IngoLedMapperApp
*
* Created by Imanol Gomez on 13/08/18.
*
*/
#include "ofMain.h"
#include "AppManager.h"
#include "GuiManager.h"
#include "GuiTheme.h"
const string GuiManager::GUI_SETTINGS_FILE_NAME = "xmls/GuiSettings.xml";
const string GuiManager::GUI_SETTINGS_NAME = "GUI";
const string GuiManager::PRESETS_PREFIX = "xmls/Presets_";
const int GuiManager::GUI_WIDTH = 300;
GuiManager::GuiManager(): Manager(), m_showGui(true)
{
//Intentionally left empty
}
GuiManager::~GuiManager()
{
this->saveGuiValues();
ofLogNotice() <<"GuiManager::Destructor";
}
void GuiManager::setup()
{
if(m_initialized)
return;
Manager::setup();
this->setupGuiParameters();
this->setupScenesGui();
//this->setupFileGui();
this->setupLevelsGui();
this->setupLayoutGui();
this->setupParticlesGui();
this->setupPaletteGui();
this->setupLedsGui();
this->setupGuiEvents();
this->loadGuiValues();
ofLogNotice() <<"GuiManager::initialized";
}
void GuiManager::setupGuiParameters()
{
ofxDatGuiLog::quiet();
//m_gui.setPosition(ofxDatGuiAnchor::TOP_LEFT);
m_gui.setPosition(0,0);
m_gui.setAssetPath(ofToDataPath("fonts/"));
//m_gui.setAssetPath(ofToDataPath("fonts/"));
//m_gui.setAssetPath("../Resources/data/fonts/");
m_gui.setTheme(new GuiTheme());
int margin = LayoutManager::MARGIN;
m_gui.setAutoDraw(false);
auto pos = m_gui.getPosition();
m_gui.setPosition(pos.x + margin, pos.y + margin);
m_gui.addHeader(GUI_SETTINGS_NAME, false);
m_gui.addFRM(0.1);
m_gui.addBreak();
}
void GuiManager::setupFileGui()
{
auto videoManager = &AppManager::getInstance().getVideoManager();
auto ledsManager = &AppManager::getInstance().getLedsManager();
m_modelPath.set("ModelPath", " ");
m_modelPath.addListener(ledsManager, &LedsManager::load);
m_parameters.add(m_modelPath);
m_videoPath.set("VideoPath", " ");
m_videoPath.addListener(videoManager, &VideoManager::load);
m_parameters.add(m_videoPath);
ofxDatGuiFolder* folder = m_gui.addFolder("FILE", ofColor::pink);
folder->addButton("Load Model");
folder->addButton("Load Video");
folder->addButton("Load Test");
folder->expand();
}
void GuiManager::setupScenesGui()
{
auto sceneManager = &AppManager::getInstance().getSceneManager();
vector<string> opts;
for(int i = 0; i < sceneManager->getNumberScenes(); i++)
{
opts.push_back(sceneManager->getSceneName(i));
}
string label = "SCENES";
m_gui.addDropdown(label, opts);
auto menu = m_gui.getDropdown(label);
//menu->expand(); //let's have it open by default
menu->setStripeColor(ofColor::pink);
for (int i=0; i<menu->size(); i++) menu->getChildAt(i)->setStripeColor(ofColor::pink);
m_gui.addBreak();
}
const ofColor& GuiManager::getColor(int index)
{
// string colorName = "COLOR " + ofToString(index);
// return m_gui.getColorPicker(colorName)->getColor();
if(index<0 || index >= m_colors.size() ){
return m_colors[0];
}
return m_colors[index];
}
void GuiManager::setupParticlesGui()
{
auto particlesManager = &AppManager::getInstance().getParticlesManager();
m_particlesDirection.set("Direction", 0.0, 0.0, 360.0);
m_particlesDirection.addListener(particlesManager, &ParticlesManager::setDirecction);
m_presets.add(m_particlesDirection);
m_particlesDirectionMag.set("Dir. Mag.", 0.0, 0.0, 2.0);
m_particlesDirectionMag.addListener(particlesManager, &ParticlesManager::setDirecctionMag);
m_presets.add(m_particlesDirectionMag);
m_particlesSpeed.set("Speed", 0.0, 0.0, 10.0);
m_particlesSpeed.addListener(particlesManager, &ParticlesManager::setSpeed);
m_presets.add(m_particlesSpeed);
m_particlesSize.set("Size", 6.0, 0.0, 200.0);
m_particlesSize.addListener(particlesManager, &ParticlesManager::setSize);
m_presets.add(m_particlesSize);
m_particlesNum.set("Num", 800, 0, 1500);
m_particlesNum.addListener(particlesManager, &ParticlesManager::setNum);
m_presets.add(m_particlesNum);
m_particlesFade.set("Fade", 0.0, 0.0, 60.0);
m_particlesFade.addListener(particlesManager, &ParticlesManager::setFadeTime);
m_presets.add(m_particlesFade);
m_particlesVectSpeed.set("Vect. Speed", 0.2, 0.0, 2.0);
m_particlesVectSpeed.addListener(particlesManager, &ParticlesManager::setVectorSpeed);
m_presets.add(m_particlesVectSpeed);
m_particlesRandomness.set("Randomness", 0.5, 0.0, 5.0);
m_particlesRandomness.addListener(particlesManager, &ParticlesManager::setRandonmess);
m_presets.add(m_particlesRandomness);
m_particlesBlur.set("Blur", 0.05, 0.0, 1.0);
m_particlesBlur.addListener(particlesManager, &ParticlesManager::setBlur);
m_presets.add(m_particlesBlur);
ofxDatGuiFolder* folder = m_gui.addFolder("PARTICLES", ofColor::yellow);
folder->addSlider(m_particlesDirection);
folder->addSlider(m_particlesDirectionMag);
folder->addSlider(m_particlesSpeed);
folder->addSlider(m_particlesSize);
folder->addSlider(m_particlesNum);
folder->addSlider(m_particlesFade);
// folder->addSlider(m_particlesVectSpeed);
folder->addSlider(m_particlesRandomness);
folder->addSlider(m_particlesBlur);
folder->expand();
m_gui.addBreak();
}
void GuiManager::setupPaletteGui()
{
// add some color pickers to color our lines //
ofxDatGuiFolder* f1 = m_gui.addFolder("PALETTE", ofColor::fromHex(0x2FA1D6));
int numColors = 6;
for(int i = 0; i < numColors; i++)
{
string colorName = "COLOR " + ofToString(i);
f1->addColorPicker(colorName);
ofParameter<int> colorHex;
colorHex.set(colorName, 0, 0, 16777215);
m_colorHexVector.push_back(colorHex);
m_presets.add(m_colorHexVector.back());
m_colors.push_back(ofColor(0));
}
f1->expand();
m_gui.addBreak();
}
void GuiManager::setupLayoutGui()
{
auto layoutManager = &AppManager::getInstance().getLayoutManager();
auto sceneManager = &AppManager::getInstance().getSceneManager();
m_sceneTransitionTime.set("TransitionTime", 0.5, 0.0, 8.0);
m_sceneTransitionTime.addListener(sceneManager, &SceneManager::onTransitionTimeChange);
m_parameters.add(m_sceneTransitionTime);
m_sceneTimer.set("ScenesTimer", 30, 1, 120.0);
m_sceneTimer.addListener(sceneManager, &SceneManager::onChangeSceneDuration);
m_presets.add(m_sceneTimer);
ofxDatGuiFolder* folder = m_gui.addFolder("GENERAL", ofColor::pink);
folder->addSlider(m_sceneTransitionTime);
folder->addButton("Save Preset");
//folder->addSlider(m_sceneTimer);
folder->expand();
m_gui.addBreak();
}
void GuiManager::setupLevelsGui()
{
auto sceneManager = &AppManager::getInstance().getSceneManager();
m_contrast.set("Contrast", 1.0, 0.0, 2.0);
m_contrast.addListener(sceneManager, &SceneManager::setContrast);
m_presets.add(m_contrast);
m_saturation.set("Saturation", 1.0, 0.0, 2.0);
m_saturation.addListener(sceneManager, &SceneManager::setSaturation);
m_presets.add(m_saturation);
m_brightness.set("Brightness", 1.0, 0.0, 2.0);
m_brightness.addListener(sceneManager, &SceneManager::setBrightness);
m_presets.add(m_brightness);
m_gamma.set("Gamma", 1.0, 0.0, 2.0);
m_gamma.addListener(sceneManager, &SceneManager::setGamma);
m_presets.add(m_gamma);
m_minInput.set("MinInput", 0.0, 0.0, 1.0);
m_minInput.addListener(sceneManager, &SceneManager::setMinInput);
m_presets.add(m_minInput);
m_maxInput.set("MaxInput", 1.0, 0.0, 1.0);
m_maxInput.addListener(sceneManager, &SceneManager::setMaxInput);
m_presets.add(m_maxInput);
m_minOutput.set("MinOutput", 0.0, 0.0, 1.0);
m_minOutput.addListener(sceneManager, &SceneManager::setMinOutput);
m_presets.add(m_minOutput);
m_maxOutput.set("MaxOutput", 1.0, 0.0, 1.0);
m_maxOutput.addListener(sceneManager, &SceneManager::setMaxOutput);
m_presets.add(m_maxOutput);
ofxDatGuiFolder* folder = m_gui.addFolder("LEVELS", ofColor::purple);
folder->addSlider(m_contrast);
folder->addSlider(m_saturation);
folder->addSlider(m_brightness);
folder->addSlider(m_gamma);
folder->addSlider(m_minInput);
folder->addSlider(m_maxInput);
folder->addSlider(m_minOutput);
folder->addSlider(m_maxOutput);
folder->expand();
m_gui.addBreak();
}
void GuiManager::setupLedsGui()
{
auto ledsManager = &AppManager::getInstance().getLedsManager();
m_ledsSize.set("Size", 0.14, 0.0, 5.0);
m_ledsSize.addListener(ledsManager, &LedsManager::setSize);
m_parameters.add(m_ledsSize);
ofxDatGuiFolder* folder = m_gui.addFolder("LEDS", ofColor::yellow);
folder->addButton("Reset View");
folder->addSlider(m_ledsSize);
folder->expand();
m_gui.addBreak();
}
void GuiManager::update()
{
m_gui.update();
}
void GuiManager::draw()
{
if(!m_showGui)
return;
//this->drawRectangle();
this->drawGui();
}
void GuiManager::drawGui()
{
ofEnableAlphaBlending();
m_gui.draw();
ofDisableAlphaBlending();
}
void GuiManager::setupGuiEvents()
{
m_gui.onDropdownEvent(this, &GuiManager::onDropdownEvent);
m_gui.onColorPickerEvent(this, &GuiManager::onColorPickerEvent);
m_gui.onButtonEvent(this, &GuiManager::onButtonEvent);
m_gui.onToggleEvent(this, &GuiManager::onToggleEvent);
m_gui.onMatrixEvent(this, &GuiManager::onMatrixEvent);
}
void GuiManager::saveGuiValues(string path)
{
ofXml xml;
//ofSerialize(xml, m_parameters);
xml.serialize(m_parameters);
if(path.empty()){
xml.save(GUI_SETTINGS_FILE_NAME);
}
else{
xml.save(path);
}
}
void GuiManager::loadGuiValues(string path)
{
ofXml xml;
if(path.empty()){
xml.load(GUI_SETTINGS_FILE_NAME);
}
else{
xml.load(path);
}
xml.deserialize(m_parameters);
//ofDeserialize(xml, m_parameters);
}
void GuiManager::toggleGui()
{
m_showGui = !m_showGui;
}
void GuiManager::drawRectangle()
{
int margin = LayoutManager::MARGIN;
ofPushStyle();
ofSetColor(15);
ofDrawRectangle( m_gui.getPosition().x - margin, 0, m_gui.getWidth() + 2*margin, ofGetHeight());
ofPopStyle();
}
void GuiManager::onDropdownEvent(ofxDatGuiDropdownEvent e)
{
cout << "onDropdownEvent: " << e.target->getName() << " Selected" << endl;
if(e.target->getName() == "SCENES")
{
AppManager::getInstance().getSceneManager().changeScene(e.child);
//m_gui.getDropdown(e.target->getName())->expand();
m_gui.getDropdown(e.target->getName())->setLabel("SCENES:" + e.target->getLabel());
}
}
void GuiManager::onColorPickerEvent(ofxDatGuiColorPickerEvent e)
{
cout << "onColorPickerEvent: " << e.target->getName() << " Selected" << endl;
for (int i = 0; i< m_colorHexVector.size(); i++)
{
//string colorName = "COLOR " + ofToString(i);
string colorName = m_colorHexVector[i].getName();
if(e.target->getName() == colorName)
{
m_colorHexVector[i] = e.color.getHex();
}
}
}
void GuiManager::onButtonEvent(ofxDatGuiButtonEvent e)
{
cout << "onButtonEvent: " << e.target->getName() << " Selected" << endl;
if(e.target->getName() == "Load Model")
{
AppManager::getInstance().getLedsManager().loadLeds();
}
else if(e.target->getName() == "Load Video")
{
AppManager::getInstance().getVideoManager().loadVideo();
}
else if(e.target->getName() == "Load Test")
{
AppManager::getInstance().getVideoManager().loadTest();
AppManager::getInstance().getLedsManager().loadTest();
}
else if(e.target->getName() == "Reset View")
{
AppManager::getInstance().getModelManager().resetCamera();
}
else if(e.target->getName() == "Save Preset")
{
//this->saveGuiValues();
auto currentSceneName = AppManager::getInstance().getSceneManager().getCurrentSceneName();
this->savePresetsValues(currentSceneName);
}
}
void GuiManager::onToggleEvent(ofxDatGuiToggleEvent e)
{
cout << "onToggleEvent: " << e.target->getName() << " Selected" << endl;
}
void GuiManager::onMatrixEvent(ofxDatGuiMatrixEvent e)
{
cout << "onMatrixEvent " << e.child << " : " << e.enabled << endl;
}
void GuiManager::setColor(string name, ofColor& color)
{
if( m_presets.contains(name)){
auto hexColor = m_presets.getInt(name);
hexColor.set(color.getHex());
ofLogNotice() <<"GuiManager::setColor << set preset color : " << name << "to " << hexColor.get();
}
}
void GuiManager::savePresetsValues(const string& sceneName)
{
ofXml xml;
string xmlName = PRESETS_PREFIX + sceneName +".xml";
// ofSerialize(xml, m_presets);
xml.serialize(m_presets);
xml.save(xmlName);
ofLogNotice() <<"GuiManager::savePresetsValues -> " << xmlName;
}
void GuiManager::loadPresetsValues(const string& sceneName)
{
ofXml xml;
string xmlName = PRESETS_PREFIX + sceneName +".xml";
xml.load(xmlName);
//ofDeserialize(xml, m_presets);
xml.deserialize(m_presets);
this->onResetColors();
ofLogNotice() <<"GuiManager::loadPresetsValues -> " << xmlName;
}
void GuiManager::onResetColors()
{
for (int i = 0; i< m_colorHexVector.size(); i++)
{
//string colorName = "COLOR " + ofToString(i);
string colorName = m_colorHexVector[i].getName();
if( m_presets.contains(colorName)){
auto hexColor = m_presets.getInt(colorName);
int hexValue = hexColor.get();
ofColor c = ofColor::fromHex(hexValue); // c is yellow.
//c = ofColor(ofRandom(255),ofRandom(255),ofRandom(255));
ofLogNotice() <<"GuiManager::onResetColors << set color r: " << ofToString((int)c.r) << ", g: " << ofToString((int)c.g) << ", b:" <<ofToString((int)c.b);
m_gui.getColorPicker(hexColor.getName())->setVisible(true);
m_gui.getColorPicker(hexColor.getName())->setColor(c);
m_colors[i] = c;
ofLogNotice() <<"GuiManager::onResetColors << set color : " << colorName << " to " << hexValue;
}
}
}
void GuiManager::onSceneChange(const string &sceneName)
{
ofLogNotice() <<"GuiManager::onSceneChange << looking for scene: " << sceneName;
int index = AppManager::getInstance().getSceneManager().getIndex(sceneName);
if(index>=0){
this->onSceneChange(index);
ofLogNotice() <<"GuiManager::onSceneChange << Changing to scene: " << sceneName;
}
}
void GuiManager::onSceneChange(int sceneIndex)
{
string dropBoxName = "SCENES";
auto menu = m_gui.getDropdown(dropBoxName);
if(sceneIndex>=0 && sceneIndex< menu->size())
{
ofLogNotice() <<"GuiManager::onSceneChange <<Changing to sccene index " << sceneIndex;
menu->select(sceneIndex);
string label = menu->getChildAt(sceneIndex)->getLabel();
menu->setLabel(dropBoxName + ":" + label);
AppManager::getInstance().getSceneManager().changeScene(sceneIndex);
}
}
| 28.303636 | 166 | 0.656902 | [
"vector",
"model"
] |
88d4828e89c9eb8b2417f41a9b5565a2d9d8b602 | 1,468 | cpp | C++ | c++/binary_tree_postorder_traversal.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/binary_tree_postorder_traversal.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/binary_tree_postorder_traversal.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | /*
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
*/
/*
* Opposite of preorder. Reverse the results.
*/
#include "helper.h"
#include <algorithm>
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
vector<TreeNode*> s;
TreeNode* tmp = root;
while (tmp || !s.empty()) {
if(tmp) {
s.push_back(tmp);
res.push_back(tmp->val);
tmp = tmp->right;
} else {
tmp = s.back();
s.pop_back();
tmp = tmp->left;
}
}
reverse(res.begin(), res.end());
return res;
}
};
int main() {
Solution s;
vector<int> preorder({1, 2, 3}), inorder({1, 3, 2});
TreeNode *root = buildTree(preorder, inorder);
root->print();
cout << s.postorderTraversal(root) << endl;
preorder = {1, 2, 4, 5, 3, 6, 7}, inorder = {4, 2, 5, 1, 6, 3, 7};
root = buildTree(preorder, inorder);
root->print();
cout << s.postorderTraversal(root) << endl;
return 0;
}
| 21.910448 | 73 | 0.525204 | [
"vector"
] |
88da4226bc2a669946fd3ff5ec172d128810371c | 6,421 | cpp | C++ | tetris_sfml/Tetromino.cpp | daemon3000/Tetris | a78b39485c47916bb0e9178163f1cb23d09b5b83 | [
"Zlib",
"MIT"
] | null | null | null | tetris_sfml/Tetromino.cpp | daemon3000/Tetris | a78b39485c47916bb0e9178163f1cb23d09b5b83 | [
"Zlib",
"MIT"
] | null | null | null | tetris_sfml/Tetromino.cpp | daemon3000/Tetris | a78b39485c47916bb0e9178163f1cb23d09b5b83 | [
"Zlib",
"MIT"
] | null | null | null | #include <unordered_map>
#include "Tetromino.h"
using namespace tetris;
static std::unordered_map<TetrominoType, std::unordered_map<Rotation, std::vector<bool>>> TETROMINOS
{
{
TetrominoType::I,
{
{ Rotation::R0, { false, false, false, false, true, true, true, true, false, false, false, false, false, false, false, false } },
{ Rotation::R90, { false, false, true, false, false, false, true, false, false, false, true, false, false, false, true, false } },
{ Rotation::R180, { false, false, false, false, false, false, false, false, true, true, true, true, false, false, false, false } },
{ Rotation::R270, { false, true, false, false, false, true, false, false, false, true, false, false, false, true, false, false } },
}
},
{
TetrominoType::J,
{
{ Rotation::R0, { true, false, false, true, true, true, false, false, false } },
{ Rotation::R90, { false, true, true, false, true, false, false, true, false } },
{ Rotation::R180, { false, false, false, true, true, true, false, false, true } },
{ Rotation::R270, { false, true, false, false, true, false, true, true, false } },
}
},
{
TetrominoType::L,
{
{ Rotation::R0, { false, false, true, true, true, true, false, false, false } },
{ Rotation::R90, { false, true, false, false, true, false, false, true, true } },
{ Rotation::R180, { false, false, false, true, true, true, true, false, false } },
{ Rotation::R270, { true, true, false, false, true, false, false, true, false } },
}
},
{
TetrominoType::O,
{
{ Rotation::R0, { true, true, true, true } },
{ Rotation::R90, { true, true, true, true } },
{ Rotation::R180, { true, true, true, true } },
{ Rotation::R270, { true, true, true, true } },
}
},
{
TetrominoType::S,
{
{ Rotation::R0, { false, true, true, true, true, false, false, false, false } },
{ Rotation::R90, { false, true, false, false, true, true, false, false, true } },
{ Rotation::R180, { false, false, false, false, true, true, true, true, false } },
{ Rotation::R270, { true, false, false, true, true, false, false, true, false } },
}
},
{
TetrominoType::T,
{
{ Rotation::R0, { false, true, false, true, true, true, false, false, false } },
{ Rotation::R90, { false, true, false, false, true, true, false, true, false } },
{ Rotation::R180, { false, false, false, true, true, true, false, true, false } },
{ Rotation::R270, { false, true, false, true, true, false, false, true, false } },
}
},
{
TetrominoType::Z,
{
{ Rotation::R0, { true, true, false, false, true, true, false, false, false } },
{ Rotation::R90, { false, false, true, false, true, true, false, true, false } },
{ Rotation::R180, { false, false, false, true, true, false, false, true, true } },
{ Rotation::R270, { false, true, false, true, true, false, true, false, false } },
}
}
};
Tetromino::Tetromino()
{
m_paddingTop = m_paddingBottom = 0;
m_paddingLeft = m_paddingRight = 0;
m_rotation = Rotation::R0;
setType(TetrominoType::None);
}
Tetromino::Tetromino(TetrominoType type)
{
m_paddingTop = m_paddingBottom = 0;
m_paddingLeft = m_paddingRight = 0;
m_rotation = Rotation::R0;
setType(type);
}
void Tetromino::calculatePadding()
{
for(int y = 0; y < m_height; y++)
{
for(int x = 0; x < m_width; x++)
{
if(m_solid[y * m_width + x])
{
m_paddingTop = y;
y = m_height;
break;
}
}
}
for(int y = m_height - 1; y >= 0; y--)
{
for(int x = 0; x < m_width; x++)
{
if(m_solid[y * m_width + x])
{
m_paddingBottom = (m_height - 1) - y;
y = -1;
break;
}
}
}
for(int x = 0; x < m_width; x++)
{
for(int y = 0; y < m_height; y++)
{
if(m_solid[y * m_width + x])
{
m_paddingLeft = x;
x = m_width;
break;
}
}
}
for(int x = m_width - 1; x >= 0; x--)
{
for(int y = 0; y < m_height; y++)
{
if(m_solid[y * m_width + x])
{
m_paddingRight = (m_width - 1) - x;
x = -1;
break;
}
}
}
}
void Tetromino::rotate()
{
Rotation rotation = m_rotation;
switch(rotation)
{
case tetris::Rotation::R0:
rotation = Rotation::R90;
break;
case tetris::Rotation::R90:
rotation = Rotation::R180;
break;
case tetris::Rotation::R180:
rotation = Rotation::R270;
break;
case tetris::Rotation::R270:
rotation = Rotation::R0;
break;
}
setType(m_type, rotation);
}
void Tetromino::setRotation(Rotation rotation)
{
setType(m_type, rotation);
}
void Tetromino::setType(TetrominoType type)
{
setType(type, m_rotation);
}
void Tetromino::setType(TetrominoType type, Rotation rotation)
{
m_type = type;
m_rotation = rotation;
if(type != TetrominoType::None)
m_solid = TETROMINOS[type][m_rotation];
else
m_solid.clear();
switch(type)
{
case tetris::TetrominoType::I:
m_width = m_height = 4;
m_color = TetrominoColor::Gray;
break;
case tetris::TetrominoType::J:
m_width = m_height = 3;
m_color = TetrominoColor::Purple;
break;
case tetris::TetrominoType::L:
m_width = m_height = 3;
m_color = TetrominoColor::Blue;
break;
case tetris::TetrominoType::O:
m_width = m_height = 2;
m_color = TetrominoColor::Yellow;
break;
case tetris::TetrominoType::S:
m_width = m_height = 3;
m_color = TetrominoColor::Green;
break;
case tetris::TetrominoType::T:
m_width = m_height = 3;
m_color = TetrominoColor::Pink;
break;
case tetris::TetrominoType::Z:
m_width = m_height = 3;
m_color = TetrominoColor::Red;
break;
default:
m_width = m_height = 0;
m_color = TetrominoColor::None;
break;
}
calculatePadding();
}
bool Tetromino::isSolid(int x, int y) const
{
if(x >= 0 && x < m_width && y >= 0 && y < m_height)
return m_solid[y * m_width + x];
return false;
}
bool Tetromino::isValid() const
{
return m_type != TetrominoType::None && m_color != TetrominoColor::None;
}
int Tetromino::getWidth() const
{
return m_width;
}
int Tetromino::getHeight() const
{
return m_height;
}
int Tetromino::getPaddingTop() const
{
return m_paddingTop;
}
int Tetromino::getPaddingBottom() const
{
return m_paddingBottom;
}
int Tetromino::getPaddingLeft() const
{
return m_paddingLeft;
}
int Tetromino::getPaddingRight() const
{
return m_paddingRight;
}
TetrominoType Tetromino::getType() const
{
return m_type;
}
TetrominoColor Tetromino::getColor() const
{
return m_color;
}
Rotation Tetromino::getRotation() const
{
return m_rotation;
}
| 22.609155 | 134 | 0.628874 | [
"vector"
] |
88dc8cb2c89a1d0c9580fd4a4c1f53b567d5608c | 15,889 | cc | C++ | src/modules/TaskDistributor/GreedySelector.cc | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 31 | 2015-12-15T19:14:10.000Z | 2021-12-31T17:40:21.000Z | src/modules/TaskDistributor/GreedySelector.cc | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 5 | 2015-12-04T08:06:47.000Z | 2020-08-09T21:49:46.000Z | src/modules/TaskDistributor/GreedySelector.cc | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 21 | 2015-11-05T08:25:45.000Z | 2021-06-19T02:24:50.000Z | #include <vector>
#include "GreedySelector.hh"
using namespace std;
GreedySelector::td_t::td_t()
{
int i, j;
for (i = 0; i < GreedySelector::NOF_CORE; i++)
for (j = 0; j < GreedySelector::NOF_CFU; j++)
allocTable[i][j] = 0;
}
void GreedySelector::td_t::recursiveCluster(dfg_t* d, set<node_t*> &nodes, set<edge_t*> &edges, node_t* n)
{
d->addVertix(n);
nodes.erase(n);
for (set<edge_t*>::iterator et = edges.begin(); et != edges.end(); et++) {
if ((*et)->des == n || (*et)->src == n) {
d->addEdge(*et);
if (d->vertices.find((*et)->des) == d->vertices.end() || d->vertices.find((*et)->src) == d->vertices.end())
recursiveCluster(d, nodes, edges, ((*et)->src == n) ? (*et)->des : (*et)->src);
}
}
}
void GreedySelector::td_t::cluster(set<dfg_t*> &patterns, set<node_t*> &nodes, set<edge_t*> &edges, int core_id)
{
while (!nodes.empty()) {
set<node_t*>::iterator n = nodes.begin();
dfg_t*d = new dfg_t();
d->core_id = core_id;
recursiveCluster(d, nodes, edges, *n);
patterns.insert(d);
}
}
void GreedySelector::td_t::permuteCFUs(dfg_t *dfg, int coreNo, set<node_t*> &removeNodes)
{
set<node_t*>::iterator ni;
map <int, set<node_t*> > neededCFU;
// enumerate what is needed
for (ni = dfg->vertices.begin(); ni != dfg->vertices.end(); ni++)
neededCFU[(*ni)->func].insert(*ni);
map <int, set<node_t*> >::iterator it;
for (it = neededCFU.begin(); it != neededCFU.end(); it++) {
// if available == 0 remove all
if (allocTable[coreNo][(*it).first] == 0) {
set<node_t*>::iterator jt;
for (jt = (*it).second.begin(); jt != (*it).second.end(); jt++)
removeNodes.insert(*jt);
}
// if (available < needed) select the best subset in dfg
else if ( allocTable[coreNo][(*it).first] < (*it).second.size() ) {
// criteria: select those which have the highest number of available neighbors
map <node_t*, int> count;
set<node_t*>::iterator jt;
// for all the nodes of type (*it).first
for (jt = (*it).second.begin(); jt != (*it).second.end(); jt++) {
// for all the edges if they match (*jt) and if their other end is available, inc count
set<edge_t*>::iterator ei;
if (count.find(*jt) == count.end()) count[*jt] = 0;
if ((*jt)->visited == true) count[*jt] = (-1) * (dfg->vertices.size() + dfg->edges.size());
for (ei = dfg->edges.begin(); ei != dfg->edges.end(); ei++) {
if ( ( (*ei)->des == (*jt) && (allocTable[coreNo][(*ei)->src->func] > 0) ) || ( (*ei)->src == (*jt) && (allocTable[coreNo][(*ei)->des->func] > 0) ) )
count[*jt]++;
}
}
// remove (needed - available)# of CFUs which has the lowest count value from the dfg
for (unsigned int i = 0; i < (*it).second.size() - allocTable[coreNo][(*it).first] ; i++) {
// find the node with minimum count and remove it from "count" and add it to "removeNodes" set
map <node_t*, int>::iterator ci;
int min = dfg->vertices.size();
node_t *min_cnt_node = NULL;
for (ci = count.begin(); ci != count.end(); ci++)
if ((*ci).second <= min) {
min_cnt_node = (*ci).first;
min = (*ci).second;
}
removeNodes.insert(min_cnt_node);
count.erase(min_cnt_node);
}
}
}
}
void GreedySelector::td_t::enumeratePatterns (dfg_t *dfg, int coreNo, set<dfg_t*> &patterns)
{
set<node_t*>removeNodes;
permuteCFUs(dfg, coreNo, removeNodes);
set<edge_t*>removeEdges;
set<node_t*>::iterator ni;
set<edge_t*>::iterator et;
for (ni = removeNodes.begin(); ni != removeNodes.end(); ni++)
for (et = dfg->edges.begin(); et != dfg->edges.end(); et++)
if ((*et)->des == (*ni) || (*et)->src == (*ni))
removeEdges.insert(*et);;
for (ni = removeNodes.begin(); ni != removeNodes.end(); ni++)
dfg->vertices.erase(*ni);
for (et = removeEdges.begin(); et != removeEdges.end(); et++)
dfg->edges.erase(*et);
for (ni = dfg->vertices.begin(); ni != dfg->vertices.end(); ni++)
(*ni)->visited = true;
// cluster the remaining nodes
cluster(patterns, dfg->vertices, dfg->edges, dfg->core_id);
}
void GreedySelector::td_t::generatePatterns(dfg_t *dfg, map<int, set<dfg_t*> > &patterns)
{
int c;
for (c = 0; c < GreedySelector::NOF_CORE; c++) {
dfg_t* newdfg = new dfg_t(dfg->vertices, dfg->edges, c);
//traverseDFG(newdfg, c, patterns[c]);
enumeratePatterns(newdfg, c, patterns[c]);
}
}
void GreedySelector::td_t::findEssentialPatterns(dfg_t* dfg, map<int, set<dfg_t*> > &patterns, set<dfg_t*> &selectedPatterns, map<node_t*, set<dfg_t*> > &coveringPatterns )
{
int c;
set<node_t*>::iterator it;
for (it = dfg->vertices.begin(); it != dfg->vertices.end(); it++) {
for (c = 0; c < GreedySelector::NOF_CORE; c++) {
set<dfg_t*>::iterator jt;
for (jt = patterns[c].begin(); jt != patterns[c].end(); jt++) {
set<node_t*>::iterator kt;
for (kt = (*jt)->vertices.begin(); kt != (*jt)->vertices.end(); kt++) {
if (*kt == *it)
coveringPatterns[*it].insert((*jt));
}
}
}
assert (!coveringPatterns[*it].empty());
if (coveringPatterns[*it].size() == 1)
selectedPatterns.insert(*coveringPatterns[*it].begin());
}
// select the largest pattern if there is no essential
dfg_t* maxSizeDFG = NULL;
int maxSize = 0;
if (selectedPatterns.size() == 0) {
for (int c = 0; c < GreedySelector::NOF_CORE; c++) {
// select the largest pattern
set<dfg_t*>::iterator it = patterns[c].begin();
while (it != patterns[c].end()) {
int size = (*it)->vertices.size();
if (size > maxSize) {
maxSizeDFG = (*it);
maxSize = size;
}
it++;
}
}
assert(maxSize > 0);
selectedPatterns.insert(maxSizeDFG);
}
}
// check all the nodes and find which patterns cover them
// if there is any which is covered by more than one, it returns it, so the greedy approach selects one of them
GreedySelector::node_t *GreedySelector::td_t::checkPatternCoverage(dfg_t* dfg, set<dfg_t*> &selectedPatterns, map<node_t*, set<dfg_t*> > &coveringPatterns)
{
set<node_t*>::iterator it;
node_t *not_single_covered = NULL;
int n;
for (it = dfg->vertices.begin(), n = 0; it != dfg->vertices.end(); it++, n++) {
set<dfg_t*>::iterator jt;
bool clearedOnce = false;
for (jt = selectedPatterns.begin(); jt != selectedPatterns.end(); jt++) {
if ((*jt)->vertices.find(*it) != (*jt)->vertices.end()) {
if (!clearedOnce) {
coveringPatterns[*it].clear();
clearedOnce = true;
}
coveringPatterns[*it].insert(*jt);
}
}
if (coveringPatterns[*it].size() != 1) not_single_covered = *it;
}
return not_single_covered;
}
int GreedySelector::td_t::findCommunicationOverHead(node_t* node, dfg_t* pattern)
{
int commOvhd = 0;
// find the communication overhead between node and (pattern minus node)
set<edge_t*>::iterator it;
for (it = pattern->edges.begin(); it != pattern->edges.end(); it++)
if ((*it)->src == node || (*it)->des == node) commOvhd++;
return commOvhd;
}
int GreedySelector::td_t::findCommunicationOverHead(dfg_t* dfg, dfg_t* pattern, set<dfg_t*> selectedPatterns, set<overlappedNodeInfo_t *> &overlappedNodesInfo)
{
int commOvhd = 0;
// check if there is any overlapped node and compute the case that creates the minimum commOvhd
set<dfg_t*>::iterator it;
set<node_t*>::iterator ni;
for (ni = pattern->vertices.begin(); ni != pattern->vertices.end(); ni++) {
for (it = selectedPatterns.begin(); it != selectedPatterns.end(); it++) {
if (pattern == (*it)) continue;
if ((*it)->vertices.find(*ni) != (*it)->vertices.end()) {
int c1 = findCommunicationOverHead(*ni, pattern);
int c2 = findCommunicationOverHead(*ni, (*it));
commOvhd += (c1 > c2) ? c2 : c1;
if (c1 > c2)
overlappedNodesInfo.insert(new overlappedNodeInfo_t(*ni, (*it), pattern) );
else
overlappedNodesInfo.insert(new overlappedNodeInfo_t(*ni, pattern, (*it)) );
}
}
}
// check all the edges in DFG and see if they connect pattern and selectedPattern
for (it = selectedPatterns.begin(); it != selectedPatterns.end(); it++) {
set<edge_t*>::iterator jt;
for (jt = dfg->edges.begin(); jt != dfg->edges.end(); jt++) {
bool isSrcNodeInPattern = pattern->vertices.find((*jt)->src) != pattern->vertices.end();
bool isDesNodeInPattern = pattern->vertices.find((*jt)->des) != pattern->vertices.end();
bool isSrcNodeInSelectedPattern = (*it)->vertices.find((*jt)->src) != (*it)->vertices.end();
bool isDesNodeInSelectedPattern = (*it)->vertices.find((*jt)->des) != (*it)->vertices.end();
if ( !(isSrcNodeInPattern && isSrcNodeInSelectedPattern) && !(isDesNodeInPattern && isDesNodeInSelectedPattern) ) // node is not overlapped
if ((isSrcNodeInPattern && isDesNodeInSelectedPattern)
|| (isDesNodeInPattern && isSrcNodeInSelectedPattern)) /* there is an edge between selectedPatterns and pattern*/
commOvhd++;
}
}
return commOvhd == 0 ? -1 : commOvhd;
}
void GreedySelector::td_t::selectPatterns(dfg_t *dfg, map<int, set<dfg_t*> > &patterns, set<dfg_t*> &selectedPatterns)
{
set<overlappedNodeInfo_t *> overlappedNodesInfo;
set<overlappedNodeInfo_t *> temp_overlappedNodesInfo;
map<node_t*, set<dfg_t*> > coveringPatterns;
// find essential patterns
findEssentialPatterns(dfg, patterns, selectedPatterns, coveringPatterns);
node_t* not_single_covered = checkPatternCoverage(dfg, selectedPatterns, coveringPatterns);
while (not_single_covered) {
// select the largest patterns that has the minimum communication with the current selection
set<dfg_t*>::iterator it = coveringPatterns[not_single_covered].begin();
dfg_t* minCommPattern = *it;
int minCommOvhd = findCommunicationOverHead(dfg, *it, selectedPatterns, overlappedNodesInfo);
it++;
while (it != coveringPatterns[not_single_covered].end()) {
int commOvhd = findCommunicationOverHead(dfg, *it, selectedPatterns, temp_overlappedNodesInfo);
if (commOvhd < minCommOvhd) {
minCommPattern = *it;
overlappedNodesInfo.clear();
overlappedNodesInfo = temp_overlappedNodesInfo;
}
it++;
}
coveringPatterns[not_single_covered].clear();
coveringPatterns[not_single_covered].insert(minCommPattern);
selectedPatterns.insert(minCommPattern);
// remove the overlapped nodes
set<overlappedNodeInfo_t *>::iterator oi;
for (oi = overlappedNodesInfo.begin(); oi != overlappedNodesInfo.end(); oi++) {
(*oi)->oldP->vertices.erase((*oi)->node);
set<edge_t*>::iterator ei_bak, ei = (*oi)->oldP->edges.begin();
while (ei != (*oi)->oldP->edges.end()) {
if ((*ei)->src == (*oi)->node || (*ei)->des == (*oi)->node ) {
ei_bak = ei;
ei_bak++;
(*oi)->oldP->edges.erase(*ei);
ei = ei_bak;
} else
ei++;
}
}
//check for coverage after the new selection
not_single_covered = checkPatternCoverage(dfg, selectedPatterns, coveringPatterns);
}
}
void GreedySelector::td_t::allocateDFG(dfg_t *dfg, set<dfg_t*> &selectedPatterns)
{
std::map< int, std::set<dfg_t*> > patterns;
generatePatterns(dfg, patterns);
selectPatterns(dfg, patterns, selectedPatterns);
}
bool GreedySelector::td_t::checkFeasibility(dfg_t *dfg)
{
int i, j;
// compute the needed CFU of type i
int sumNeeded[GreedySelector::NOF_CFU];
for (i = 0; i < GreedySelector::NOF_CFU; i++) {
sumNeeded[i] = 0;
}
set<node_t*>::iterator ni;
for (ni = dfg->vertices.begin(); ni != dfg->vertices.end(); ni++) {
sumNeeded[(*ni)->func]++;
}
// compute the available CFU of type i
int sumAvail[GreedySelector::NOF_CFU];
for (i = 0; i < GreedySelector::NOF_CFU; i++) {
sumAvail[i] = 0;
}
for (i = 0; i < GreedySelector::NOF_CORE; i++) {
for (j = 0; j < GreedySelector::NOF_CFU; j++) {
sumAvail[j] += allocTable[i][j];
}
}
for (i = 0; i < GreedySelector::NOF_CFU; i++) {
if (sumNeeded[i] > sumAvail[i]) return false;
}
return true;
}
void GreedySelector::td_t::clearAllocations()
{
for (int i = 0; i < GreedySelector::NOF_CFU; i++) {
for (int j = 0; j < GreedySelector::NOF_CORE; j++) {
allocTable[j][i] = 0;
}
}
}
void GreedySelector::td_t::assignNewAllocation(int core, int cfu)
{
assert(core >= 0);
assert(core < NOF_CORE);
assert(cfu >= 0);
assert(cfu < NOF_CFU);
allocTable[core][cfu]++;
}
const std::string& GreedySelector::GetSelectorName()
{
return selectorName;
}
uint32_t GreedySelector::GetLastCalculationDelay()
{
return 1;
}
bool GreedySelector::FindAssignment(int core, const TDProgram& prog, int cfusPerIsland, const std::vector<CFUIdentifier>& fullSystem, const std::vector<CFUIdentifier>& available, std::vector<CFUIdentifier>& assignment, std::vector<int>& requiredModeSet, bool allowPartial)
{
assert(!allowPartial);
//condense allocations first
std::map<unsigned int, unsigned int> modeToID;
std::map<unsigned int, unsigned int> idToMode;
for (size_t i = 0; i < available.size(); i++) {
if (modeToID.find(available[i].acceleratorID) == modeToID.end()) {
unsigned int id = modeToID.size();
assert(idToMode.find(id) == idToMode.end());
modeToID[available[i].acceleratorID] = id;
idToMode[id] = available[i].acceleratorID;
}
}
td.clearAllocations();
for (size_t i = 0; i < available.size(); i++) {
assert(modeToID.find(available[i].acceleratorID) != modeToID.end());
td.assignNewAllocation(available[i].cpuID, modeToID[available[i].acceleratorID]);
}
std::vector<node_t> nodes;
for (size_t i = 0; i < prog.nodeSet.size(); i++) {
node_t n;
if (modeToID.find(prog.nodeSet[i].computeDesc.opcode) == modeToID.end()) {
return false;
}
n.func = modeToID[prog.nodeSet[i].computeDesc.opcode];
n.visited = false;
nodes.push_back(n);
}
std::vector<edge_t> edges;
for (size_t i = 0; i < prog.edgeSet.size(); i++) {
if (prog.edgeSet[i].from == TransferDescription::MemoryDevice || prog.edgeSet[i].to == TransferDescription::MemoryDevice) {
continue;
}
edge_t e(&nodes[prog.edgeSet[i].from], &nodes[prog.edgeSet[i].to]);
edges.push_back(e);
}
std::set<node_t*> inputNodes;
std::set<edge_t*> inputEdges;
for (size_t i = 0; i < nodes.size(); i++) {
inputNodes.insert(&nodes[i]);
}
for (size_t i = 0; i < edges.size(); i++) {
inputEdges.insert(&edges[i]);
}
set<dfg_t*> selectedPatterns;
dfg_t dfg(inputNodes, inputEdges, -1);
if (!td.checkFeasibility(&dfg)) {
return false;
}
td.allocateDFG(&dfg, selectedPatterns);
set<int> selectionMask;
for (std::set<dfg_t*>::iterator dfgIt = selectedPatterns.begin(); dfgIt != selectedPatterns.end(); dfgIt++) {
for (std::set<node_t*>::iterator nodeIt = (*dfgIt)->vertices.begin(); nodeIt != (*dfgIt)->vertices.end(); nodeIt++) {
assert(idToMode.find((*nodeIt)->func) != idToMode.end());
unsigned int func = idToMode[(*nodeIt)->func];
bool assigned = false;
for (size_t i = 0; i < available.size(); i++) {
if (func == available[i].acceleratorID && (*dfgIt)->core_id == available[i].cpuID && selectionMask.find(available[i].cfuID) == selectionMask.end()) {
assigned = true;
assignment.push_back(available[i]);
selectionMask.insert(available[i].cfuID);
break;
}
}
assert(assigned);
}
}
for (std::set<dfg_t*>::iterator dfgIt = selectedPatterns.begin(); dfgIt != selectedPatterns.end(); dfgIt++) {
delete *dfgIt;
}
return true;
}
| 31.905622 | 272 | 0.618038 | [
"vector"
] |
88e0004b85a4a3f4d0099083d709718a014ee1ca | 17,806 | hpp | C++ | include/opentxs/core/crypto/OTSubcredential.hpp | robertoleksy/opentxs | 2953cfbf3dac85ae1f2239a6546fe2aadf1616e2 | [
"Apache-2.0"
] | null | null | null | include/opentxs/core/crypto/OTSubcredential.hpp | robertoleksy/opentxs | 2953cfbf3dac85ae1f2239a6546fe2aadf1616e2 | [
"Apache-2.0"
] | null | null | null | include/opentxs/core/crypto/OTSubcredential.hpp | robertoleksy/opentxs | 2953cfbf3dac85ae1f2239a6546fe2aadf1616e2 | [
"Apache-2.0"
] | null | null | null | /************************************************************
*
* OTSubcredential.hpp
*
*/
/************************************************************
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
*
* EMAIL:
* FellowTraveler@rayservers.net
*
* BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
*
* KEY FINGERPRINT (PGP Key in license file):
* 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
*
* OFFICIAL PROJECT WIKI(s):
* https://github.com/FellowTraveler/Moneychanger
* https://github.com/FellowTraveler/Open-Transactions/wiki
*
* WEBSITE:
* http://www.OpenTransactions.org/
*
* Components and licensing:
* -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
* -- otlib.........A class library.......LICENSE:...LAGPLv3
* -- otapi.........A client API..........LICENSE:...LAGPLv3
* -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
* -- otserver......Server Application....LICENSE:....AGPLv3
* Github.com/FellowTraveler/Open-Transactions/wiki/Components
*
* All of the above OT components were designed and written by
* Fellow Traveler, with the exception of Moneychanger, which
* was contracted out to Vicky C (bitcointrader4@gmail.com).
* The open-source community has since actively contributed.
*
* -----------------------------------------------------
*
* LICENSE:
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* ADDITIONAL PERMISSION under the GNU Affero GPL version 3
* section 7: (This paragraph applies only to the LAGPLv3
* components listed above.) If you modify this Program, or
* any covered work, by linking or combining it with other
* code, such other code is not for that reason alone subject
* to any of the requirements of the GNU Affero GPL version 3.
* (==> This means if you are only using the OT API, then you
* don't have to open-source your code--only your changes to
* Open-Transactions itself must be open source. Similar to
* LGPLv3, except it applies to software-as-a-service, not
* just to distributing binaries.)
*
* Extra WAIVER for OpenSSL, Lucre, and all other libraries
* used by Open Transactions: This program is released under
* the AGPL with the additional exemption that compiling,
* linking, and/or using OpenSSL is allowed. The same is true
* for any other open source libraries included in this
* project: complete waiver from the AGPL is hereby granted to
* compile, link, and/or use them with Open-Transactions,
* according to their own terms, as long as the rest of the
* Open-Transactions terms remain respected, with regard to
* the Open-Transactions code itself.
*
* Lucre License:
* This code is also "dual-license", meaning that Ben Lau-
* rie's license must also be included and respected, since
* the code for Lucre is also included with Open Transactions.
* See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
* The Laurie requirements are light, but if there is any
* problem with his license, simply remove the Lucre code.
* Although there are no other blind token algorithms in Open
* Transactions (yet. credlib is coming), the other functions
* will continue to operate.
* See Lucre on Github: https://github.com/benlaurie/lucre
* -----------------------------------------------------
* You should have received a copy of the GNU Affero General
* Public License along with this program. If not, see:
* http://www.gnu.org/licenses/
*
* If you would like to use this software outside of the free
* software license, please contact FellowTraveler.
* (Unfortunately many will run anonymously and untraceably,
* so who could really stop them?)
*
* DISCLAIMER:
* This program is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Affero General Public License for
* more details.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
kamH0Y/n11lCvo1oQxM+
=uSzz
-----END PGP SIGNATURE-----
**************************************************************/
#ifndef OPENTXS_CORE_CRYPTO_OTSUBCREDENTIAL_HPP
#define OPENTXS_CORE_CRYPTO_OTSUBCREDENTIAL_HPP
#include <opentxs/core/Contract.hpp>
// A nym contains a list of master credentials, via OTCredential.
// The whole purpose of a Nym is to be an identity, which can have
// master credentials.
//
// Each credential is like a master key for the Nym's identity,
// which can issue its own subkeys.
//
// Each subkey has 3 key pairs: encryption, signing, and authentication.
// Not all subcredentials are a subkey. For example, you might have a
// subcredential that uses Google Authenticator, and thus doesn't contain
// any keys, because it uses alternate methods for its own authentication.
//
// Each OTCredential contains a "master" subkey, and a list of subcredentials
// (some of them subkeys) signed by that master.
//
// The same class (subcredential/subkey) is used because there are master
// credentials and subcredentials, so we're using inheritance for
// "subcredential"
// and "subkey" to encapsulate the credentials, so we don't have to repeat code
// across both.
// We're using a "has-a" model here, since the OTCredential "has a" master
// subkey, and also "has a" list of subcredentials, some of which are subkeys.
//
// Each subcredential must be signed by the subkey that is the master key.
// Each subkey has 3 key pairs: encryption, signing, and authentication.
//
// Each key pair has 2 OTAsymmetricKeys (public and private.)
//
// I'm thinking that the Nym should also have a key pair (for whatever is
// its current key pair, copied from its credentials.)
//
// the master should never be able to do any actions except for sign subkeys.
// the subkeys, meanwhile should only be able to do actions, and not issue
// any new keys.
namespace opentxs
{
class Contract;
class OTCredential;
class Identifier;
class OTPassword;
class String;
// This is stored as an OTContract, and it must be signed by the
// master key. (which is also an OTSubcredential.)
//
class OTSubcredential : public Contract
{
private: // Private prevents erroneous use by other classes.
typedef Contract ot_super;
friend class OTCredential;
protected:
enum CredStoreAs {
credPrivateInfo =
0, // For saving the private keys, too. Default behavior.
credPublicInfo = 1, // For saving a version with public keys only.
credMasterSigned = 2 // For saving a version with the master signature
// included, so the subkey can then countersign on
// top of that. (To prove that the subkey
// authorizes the master key's signature.) Only
// used by subkeys.
};
CredStoreAs m_StoreAs; // Not serialized.
protected:
OTCredential* m_pOwner; // a pointer for convenience only. Do not cleanup.
String m_strMasterCredID; // All subcredentials within the same
// OTCredential share the same
// m_strMasterCredID. It's a hash of the signed
// master credential.
String m_strNymID; // All subcredentials within the same OTCredential
// (including m_MasterKey) must have
String m_strSourceForNymID; // the same NymID and source.
String::Map m_mapPublicInfo; // A map of strings containing the
// credential's public info. This was
// originally 1 string but subclasses ended
// up needing a map of them. Who'da thought.
String::Map m_mapPrivateInfo; // A map of strings containing the
// credential's private info. This was
// originally 1 string but subclasses ended
// up needing a map of them. Who'da thought.
String m_strMasterSigned; // A public version of the credential with the
// master credential's signature on it. (The
// final public version will contain the
// subkey's own signature on top of that.)
String m_strContents; // The actual final public credential as sent to the
// server. Does not include private keys, even on
// client side.
void UpdatePublicContentsToString(String& strAppendTo); // Used in
// UpdateContents.
void UpdatePublicCredentialToString(String& strAppendTo); // Used in
// UpdateContents.
void UpdatePrivateContentsToString(String& strAppendTo); // Used in
// UpdateContents.
inline void SetMasterSigned(const String& strMasterSigned)
{
m_strMasterSigned = strMasterSigned;
}
inline void SetContents(const String& strContents)
{
m_strContents = strContents;
}
void SetNymIDandSource(const String& strNymID,
const String& strSourceForNymID);
void SetMasterCredID(const String& strMasterCredID); // Used in all
// subclasses except
// OTMasterkey. (It
// can't contain its
// own ID, since it
// is signed, and the
// ID is its hash
// AFTER it's signed.
// So it could never
// contain its own
// ID.)
inline void StoreAsMasterSigned()
{
m_StoreAs = credMasterSigned;
} // Upon signing, the credential reverts to credPrivateInfo again.
inline void StoreAsPublic()
{
m_StoreAs = credPublicInfo;
} // Upon signing, the credential reverts to credPrivateInfo again.
virtual bool SetPublicContents(const String::Map& mapPublic);
virtual bool SetPrivateContents(
const String::Map& mapPrivate,
const OTPassword* pImportPassword = nullptr); // if not nullptr, it
// means to
// use
// this password by default.
public:
const String::Map& GetPublicMap() const
{
return m_mapPublicInfo;
}
const String::Map& GetPrivateMap() const
{
return m_mapPrivateInfo;
}
const String& GetMasterCredID() const
{
return m_strMasterCredID;
} // MasterCredentialID (usually applicable.) OTMasterkey doesn't use this.
const String& GetNymID() const
{
return m_strNymID;
} // NymID for this credential.
const String& GetNymIDSource() const
{
return m_strSourceForNymID;
} // Source for NymID for this credential. (Hash it to get ID.)
const String& GetContents() const
{
return m_strContents;
} // The actual, final, signed public credential. Public keys only.
EXPORT const String& GetPubCredential() const; // More intelligent version
// of GetContents. Higher
// level.
const String& GetPriCredential() const; // I needed this for exporting a
// Nym (with credentials) from the
// wallet.
const String& GetMasterSigned() const
{
return m_strMasterSigned;
} // For subkeys, the master credential signs first, then the subkey signs a
// version which contains the "master signed" version. (This proves the
// subkey really authorizes all this.) That "master signed" version is
// stored here in m_strMasterSigned. But the final actual public
// credential (which must be hashed to get the credential ID) is the
// contents, not the master signed. The contents is the public version,
// signed by the subkey, which contains the master-signed version inside
// of it as a data member (this variable in fact, m_strMasterSigned.) You
// might ask: then what's in m_strRawContents? Answer: the version that
// includes the private keys. Well at least, on the client side. On the
// server side, the raw contents will contain only the public version
// because that's all the client will send it. Que sera sera.
virtual bool VerifyInternally(); // Call VerifyNymID. Also verify
// m_strMasterCredID against the hash of
// m_pOwner->m_MasterKey (the master
// credential.) Verify that
// m_pOwner->m_MasterKey and *this have the
// same NymID. Then verify the signature of
// m_pOwner->m_MasterKey on
// m_strMasterSigned.
// We also inherit OTContract::VerifyContractID() which hashes the contents
// and compares to the ID as already set.
// Unlike OTContract, a credential's ID is formed by hashing GetContents(),
// not by hashing m_xmlRawContents,
// (that is, the public info only, not the version containing the private
// keys.) So we override CalculateContractID
// to account for that.
//
EXPORT virtual void CalculateContractID(Identifier& newID) const;
// We also inherit OTContract::VerifyContract() which tries to find the
// "contract" key. Of course, there is no
// "contract" key in this case, so we should override it and provide our own
// version. What should it do? Well, it
// should call VerifyContractID, VerifyInternally, VerifyMaster, and
// VerifyAgainstSource. (If that last step later
// on adds too much slowdown, then we'll modify that function to check a
// signed file left for us by the IDENTITY
// VERIFICATION SREVER which we can stick in a separate process.)
// HOWEVER!! This may add vast unnecessary delay. For example, if we
// "VerifyContract" on EACH subcredential, which
// we SHOULD do, then that means EACH subcredential is going to verify its
// Master (when they share the same master...)
// and EACH subcredential is going to also re-verify its source (when they
// all share the same source!)
// Solution?
// Clearly the master itself only needs to be verified once, including its
// source, when the Nym is first loaded.
// (Verifying it twice would be redundant.) After that, each subcredential
// should be verified internally and against
// its master -- again, when first loaded. No need to verify it again after
// that, since it wouldn't have even loaded.
// After that, any signature for that Nym should be verifiable using one of
// that Nym's subcredentials.
//
virtual bool VerifyContract();
bool VerifyNymID() const; // Verifies that m_strNymID is the same as the
// hash of
// m_strSourceForNymID.
virtual bool VerifySignedByMaster();
void SetOwner(OTCredential& theOwner);
virtual void SetMetadata()
{
} // Only key-based subclasses will use this.
OTSubcredential();
OTSubcredential(OTCredential& theOwner);
virtual ~OTSubcredential();
virtual void Release();
void Release_Subcredential();
virtual void UpdateContents();
virtual int32_t ProcessXMLNode(irr::io::IrrXMLReader*& xml);
};
} // namespace opentxs
#endif // OPENTXS_CORE_CRYPTO_OTSUBCREDENTIAL_HPP
| 46.734908 | 80 | 0.626587 | [
"model"
] |
88e795d263af263d827e66d2a663e48820edc625 | 8,564 | cpp | C++ | lib/JSON/JSONThingy.cpp | rishiDholliwar/adventure2019 | 9bd577e3612b17d89cc217e24890723ec4a9a7f1 | [
"MIT"
] | null | null | null | lib/JSON/JSONThingy.cpp | rishiDholliwar/adventure2019 | 9bd577e3612b17d89cc217e24890723ec4a9a7f1 | [
"MIT"
] | null | null | null | lib/JSON/JSONThingy.cpp | rishiDholliwar/adventure2019 | 9bd577e3612b17d89cc217e24890723ec4a9a7f1 | [
"MIT"
] | null | null | null | #include "JSONThingy.h"
#include <Door.h>
#include <ExtendedDescription.h>
#include <Room.h>
#include <iostream>
// map TaskState values to JSON as strings
NLOHMANN_JSON_SERIALIZE_ENUM( CommandType, {
//USE
{LOGIN, "LOGIN"},
{LOGOUT, "LOGOUT"},
{SIGNUP, "SIGNUP"},
//COMMUNICATION
{SAY, "SAY"},
{YELL, "YELL"},
{BROADCAST, "BROADCAST"},
{TELL, "TELL"},
{WHISPER, "WHISPER"},
//MOVEMENT
{MOVE, "MOVE"},
{NORTH, "NORTH"},
{SOUTH, "SOUTH"},
{WEST, "WEST"},
{EAST, "EAST"},
{NORTHWEST, "NORTHWEST"},
{NORTHEAST, "NORTHEAST"},
{SOUTHWEST, "SOUTHWEST"},
{SOUTHEAST, "SOUTHEAST"},
//INFORMATION
{HELP, "HELP"},
{INFO, "INFO"},
{LOOK, "LOOK"},
{EXAMINE, "EXAMINE"},
{INVENTORY, "INVENTORY"},
//ITEMS
{PICKUP, "PICKUP"},
{DROP, "DROP"},
{GIVE, "GIVE"},
{WEAR, "WEAR"},
{TAKEOFF, "TAKEOFF"},
{PIGEONMAIL, "PIGEONMAIL"},
//SPELLS
{SWAP, "SWAP"},
{CONFUSE, "CONFUSE"},
{DECOY, "DECOY"},
//COMBAT
{COMBAT, "COMBAT"},
{ATTACK, "ATTACK"},
{BATTLES, "BATTLES"},
{FLEE, "FLEE"},
//MINI GAME
{TTT, "TTT"},
{TTTT, "TTTT"}
})
//Resets
void from_json(const json &j, Reset &reset) {
auto action = j.at("action").get<std::string>();
if (action == "npc") {
reset = Reset(action,
j.at("id").get<int>(),
j.at("limit").get<int>(),
j.at("room").get<int>());
} else if (action == "equip" || action == "give") {
reset = Reset(action,
j.at("id").get<int>());
} else if (action == "object") {
reset = Reset(action,
j.at("id").get<int>(),
j.at("room").get<int>());
} else if (action == "door") {
reset = Reset(action,
j.at("id").get<int>(),
j.at("room").get<int>(),
j.at("state").get<std::string>());
}
}
// Doors
void from_json(const json &j, Door &aDoor) {
aDoor = Door(j.at("dir").get<std::string>(),
j.at("desc").get<std::vector<std::string>>(),
j.at("keywords").get<std::vector<std::string>>(),
j.at("to").get<int>());
}
// Extended Descriptions
void from_json(const json &j, ExtendedDescription &extendedDescription) {
extendedDescription = ExtendedDescription(
j.at("keywords").get<std::vector<std::string>>(),
j.at("desc").get<std::vector<std::string>>());
}
// Rooms
void from_json(const json &j, Room &aRoom) {
aRoom = Room(j.at("id").get<int>(),
j.at("name").get<std::string>(),
j.at("desc").get<std::vector<std::string>>(),
j.at("doors").get<std::vector<Door>>(),
j.at("extended_descriptions").get<std::vector<ExtendedDescription>>());
}
void to_json(json &j, const Extra &anExtra) {
j = json{
{"keywords", anExtra.getKeywords() },
{"desc", anExtra.getDesc() }
};
}
// RoomController
void from_json(const json &j, RoomController &roomController) {
roomController = RoomController(j.at("ROOMS").get<std::vector<Room>>());
}
// Objects
void to_json(json &j, const Object &anObject) {
j = json{
{"id", anObject.getObjectID() },
{"keywords", anObject.getKeywords() },
{"shortdesc", anObject.getShortDesc() },
{"longdesc", anObject.getLongDesc() },
{"extra", anObject.getExtra() }
};
}
void from_json(const json &j, Extra &extraDesc) {
extraDesc = Extra(
j.at("keywords").get<std::vector<std::string>>(),
j.at("desc").get<std::vector<std::string>>());
}
void from_json(const json &j, Object &anObject) {
anObject = Object(
j.at("id").get<ID>(),
j.at("keywords").get<std::vector<std::string>>(),
j.at("shortdesc").get<std::string>(),
j.at("longdesc").get<std::vector<std::string>>(),
j.at("extra").get<std::vector<Extra>>());
}
// Inventory
void to_json(json &j, const Inventory &anInventory) {
j = json{
{"objects", anInventory.getObjects() }
};
}
void from_json(const json &j, Inventory &anInventory) {
anInventory = Inventory( j.at("objects").get<std::vector<Object>>());
}
// Characters
void to_json(json &j, const Character &aCharacter) {
if ( !(aCharacter.isNPC()) ) {
std::cout << "xD" << std::endl;
j = json{
{ "name", aCharacter.getName() },
{ "roomID", aCharacter.getRoomID() },
{ "wearing", aCharacter.getWearing() },
{ "inventory", aCharacter.getInventory() },
};
std::cout << j.dump() << std::endl;
}
}
void from_json(const json &j, Character &aCharacter) {
auto isNPC = j.find("shortdesc");
if (isNPC == j.end()) {
aCharacter = Character(
j.at("name").get<std::string>(),
j.at("roomID").get<ID>(),
j.at("inventory").get<Inventory>(),
j.at("wearing").get<std::vector<Object>>());
} else {
aCharacter = Character(
j.at("id").get<ID>(),
j.at("keywords").get<std::vector<std::string>>(),
j.at("shortdesc").get<std::string>(),
j.at("longdesc").get<std::vector<std::string>>(),
j.at("description").get<std::vector<std::string>>());
aCharacter.setNPC();
}
}
void from_json(const json &j, ObjectController &objects) {
objects = ObjectController( j.at("OBJECTS").get<std::vector<Object>>());
}
void JSONThingy::save(Character &aCharacter) {
json j;
to_json(j, aCharacter);
if(!boost::filesystem::exists("./DataFiles/Characters/")) {
boost::filesystem::create_directory("./DataFiles/Characters/");
}
std::ofstream write("./DataFiles/Characters/" + aCharacter.getName() + ".json");
write << std::setw(4) << j << std::endl;
write.close();
}
void JSONThingy::load(Name characterToLoad, Character &aCharacter) {
if(!boost::filesystem::exists("./DataFiles/Characters/" + characterToLoad + ".json")) {
return;
}
std::fstream fs;
fs.open("./DataFiles/Characters/" + characterToLoad + ".json", std::fstream::in);
if(!fs.fail()) {
json j;
fs >> j;
fs.close();
Character tmpChar = j.get<Character>();
tmpChar.giveFullHP(); //todo change later
aCharacter = tmpChar;
}
}
void JSONThingy::load(std::string areaToLoad, ObjectController &objects) {
if(!boost::filesystem::exists("./DataFiles/" + areaToLoad + ".json")) {
return;
}
std::fstream fs;
fs.open("./DataFiles/" + areaToLoad + ".json", std::fstream::in);
if(!fs.fail()) {
json j;
fs >> j;
fs.close();
objects = j.get<ObjectController>();
}
}
void JSONThingy::load(std::string areaToLoad, RoomController &roomController) {
if(!boost::filesystem::exists("./DataFiles/" + areaToLoad + ".json")) {
std::cout << "room file not found" << std::endl;
return;
}
std::cout << "file found" << std::endl;
std::fstream fs;
fs.open("./DataFiles/" + areaToLoad + ".json", std::fstream::in);
if(!fs.fail()) {
json j;
fs >> j;
fs.close();
roomController = j.get<RoomController>();
}
}
void JSONThingy::load(std::string language, CommandTranslator &aTranslator) {
if(!boost::filesystem::exists("./DataFiles/internationalization.json")) {
return;
}
std::fstream fs;
fs.open("./DataFiles/internationalization.json", std::fstream::in);
if(!fs.fail()) {
json j;
fs >> j;
fs.close();
std::map<std::string, CommandType> tmp = j.at(language).get<std::map<std::string, CommandType>>();
for(auto& t : tmp) {
aTranslator.registerTranslation(t.first, t.second);
}
}
}
void JSONThingy::load(std::string areaToLoad, ResetController &resetController) {
if(!boost::filesystem::exists("./DataFiles/" + areaToLoad + ".json")) {
std::cout << "room file not found" << std::endl;
return;
}
std::fstream fs;
fs.open("./DataFiles/" + areaToLoad + ".json", std::fstream::in);
if(!fs.fail()) {
json j;
fs >> j;
fs.close();
resetController.addResets(j.at("RESETS").get<std::vector<Reset>>());
resetController.addNPCs(j.at("NPCS").get<std::vector<Character>>());
}
} | 27.625806 | 106 | 0.540752 | [
"object",
"vector"
] |
88ec3b46cecb68da1640fcfac669520d530cbcc8 | 19,479 | cpp | C++ | toolbox/mex/meshing_mex/meshlib/polyhedron2BSP.cpp | CoMind-Technologies/NIRFAST | b198089aae1a93fcb11c0a8f229e650f3023364e | [
"BSD-3-Clause"
] | 22 | 2017-03-30T06:41:50.000Z | 2021-09-23T08:17:37.000Z | toolbox/mex/meshing_mex/meshlib/polyhedron2BSP.cpp | CoMind-Technologies/NIRFAST | b198089aae1a93fcb11c0a8f229e650f3023364e | [
"BSD-3-Clause"
] | 12 | 2016-02-24T20:20:01.000Z | 2021-03-15T13:21:33.000Z | toolbox/mex/meshing_mex/meshlib/polyhedron2BSP.cpp | CoMind-Technologies/NIRFAST | b198089aae1a93fcb11c0a8f229e650f3023364e | [
"BSD-3-Clause"
] | 17 | 2017-01-06T07:11:33.000Z | 2021-08-10T07:15:24.000Z | #include "polyhedron2BSP.h"
ULONG Polyhedron2BSP::maxdepth = 0;
Polyhedron2BSP::Polyhedron2BSP() : _isbuilt(false) {
this->macheps = exactinit();
}
Polyhedron2BSP::Polyhedron2BSP(std::vector<Polygon *> &inputpoly) {
this->macheps = exactinit();
this->_inputpoly = inputpoly;
this->polygonmarker.assign(this->_inputpoly.size(),false);
SetupRequiredSplitPlanes();
}
Polyhedron2BSP::Polyhedron2BSP(double *p, unsigned long *ele, unsigned long np, unsigned long ne, int nnpe) {
this->macheps = exactinit();
this->_inputpoly.clear();
for (unsigned long i=0; i<ne; ++i) {
std::vector<Point *> fooverts;
for (int j=0; j<nnpe; ++j) {
unsigned long nodeid = (ele[i*nnpe+j]-1) * 3; // *3 for three coordinate components
fooverts.push_back(new Point(p[nodeid], p[nodeid+1], p[nodeid+2]));
}
this->_inputpoly.push_back(new Polygon(fooverts));
}
_bbx = new double[6];
for (unsigned long i=0; i<np; ++i) {
if (i==0) {
for (int j=0; j<6; j=j+3) {
this->_bbx[j] = p[i*3];
this->_bbx[j+1] = p[i*3+1];
this->_bbx[j+2] = p[i*3+2];
}
}
if (p[i*3] < _bbx[0]) _bbx[0] = p[i*3];
if (p[i*3] > _bbx[3]) _bbx[3] = p[i*3];
if (p[i*3+1] < _bbx[1]) _bbx[1] = p[i*3+1];
if (p[i*3+1] > _bbx[4]) _bbx[4] = p[i*3+1];
if (p[i*3+2] < _bbx[2]) _bbx[2] = p[i*3+2];
if (p[i*3+2] > _bbx[5]) _bbx[5] = p[i*3+2];
}
double x,y,z,longest;
x = _bbx[3] - _bbx[0];
y = _bbx[4] - _bbx[1];
z = _bbx[5] - _bbx[2];
longest = sqrt(x * x + y * y + z * z);
if (longest == 0.0) {
std::cerr << "\n\tError: The point set is trivial.\n";
exit(1);
}
// Two identical points are distinguished by '_mindist'.
//_mindist = longest * this->macheps;
_mindist = longest * this->macheps;
// Setup initial split planes
this->polygonmarker.assign(this->_inputpoly.size(),false);
SetupRequiredSplitPlanes();
}
// This is called from a Matlab mex file. Since Matlab stores variables in a column based format we need this function.
void Polyhedron2BSP::InitFromMatlabMex(double *p, unsigned long *ele, unsigned long np, unsigned long ne, int nnpe, int splitType) {
this->macheps = exactinit();
this->_inputpoly.clear();
this->_splitType = splitType;
for (unsigned long i=0; i<ne; ++i) {
std::vector<Point *> fooverts;
for (int j=0; j<nnpe; ++j) {
unsigned long nodeid = (ele[i + ne*j]-1);
fooverts.push_back(new Point(p[nodeid], p[nodeid + np], p[nodeid + np + np]));
this->_points.push_back(fooverts.back());
this->_ele.push_back(nodeid);
}
Polygon *foop = new Polygon(fooverts);
foop->id = i+1;
this->_inputpoly.push_back(foop);
}
_bbx = new double[6];
for (unsigned long i=0; i<np; ++i) {
if (i==0) {
for (int j=0; j<6; j=j+3) {
this->_bbx[j] = p[i]; // p[i + 0*np]
this->_bbx[j+1] = p[i + np];
this->_bbx[j+2] = p[i + np + np];
}
}
if (p[i] < _bbx[0]) _bbx[0] = p[i]; // p[i + 0*np]
if (p[i] > _bbx[3]) _bbx[3] = p[i]; // p[i + 0*np]
if (p[i + np] < _bbx[1]) _bbx[1] = p[i + np];
if (p[i + np] > _bbx[4]) _bbx[4] = p[i + np];
if (p[i + np + np] < _bbx[2]) _bbx[2] = p[i + np + np];
if (p[i + np + np] > _bbx[5]) _bbx[5] = p[i + np + np];
}
double x,y,z,longest;
x = _bbx[3] - _bbx[0];
y = _bbx[4] - _bbx[1];
z = _bbx[5] - _bbx[2];
longest = sqrt(x * x + y * y + z * z);
if (longest == 0.0) {
std::cerr << "\n\tError: The point set is trivial.\n";
exit(1);
}
// Two identical points are distinguished by '_mindist'.
_mindist = longest * this->macheps;
//_mindist = this->macheps;
_inputpoly[0]->GetPlane()->plane_thk_epsilon = _mindist;
// Setup initial split planes
SetupRequiredSplitPlanes();
this->polygonmarker.assign(this->_inputpoly.size(),false);
}
void Polyhedron2BSP::SetInputPolyhedron(std::vector<Polygon *> &inputpoly) {
this->_inputpoly = inputpoly;
this->polygonmarker.assign(this->_inputpoly.size(),false);
}
void Polyhedron2BSP::SetBBX(double BBX[]) {
double x,y,z,longest;
_bbx = new double[6];
for (int i=0; i<6; _bbx[i] = BBX[i], ++i);
x = _bbx[3] - _bbx[0];
y = _bbx[4] - _bbx[1];
z = _bbx[5] - _bbx[2];
longest = sqrt(x * x + y * y + z * z);
if (longest == 0.0) {
std::cerr << "\n\tError: The point set is trivial.\n";
exit(1);
}
// Two identical points are distinguished by '_mindist'.
//_mindist = longest * this->macheps;
_mindist = longest * this->macheps;
SetupRequiredSplitPlanes();
}
void Polyhedron2BSP::SetupRequiredSplitPlanes() {
// Most brain/breast shapes can be considered convex, so we also add 3 more planes parallel to XY/XZ/YZ planes that pass through centroid of object
Point A, B;
Point cen((_bbx[0]+_bbx[3])/2., (_bbx[1]+_bbx[4])/2., (_bbx[2]+_bbx[5])/2.);
Plane3D foo1;
double foomindist = 0.1;
// We require 6 BBX planes to be part of split plane set
Point llc(_bbx[0] - foomindist, _bbx[1] - foomindist, _bbx[2] - foomindist);
Point urc(_bbx[3] + foomindist, _bbx[4] + foomindist, _bbx[5] + foomindist);
A = urc; B = urc;
A.y = urc.y - PrinciplePlaneDelta; B.z = urc.z - PrinciplePlaneDelta;
foo1 = Plane3D(A,B,urc);
this->RequiredSplitPlanes.push_back(foo1);
A = urc; B = urc;
A.z = urc.z - PrinciplePlaneDelta; B.x = urc.x - PrinciplePlaneDelta;
foo1 = Plane3D(A,B,urc);
this->RequiredSplitPlanes.push_back(foo1);
A = llc; B = llc;
A.z = llc.z + PrinciplePlaneDelta; B.y = llc.y + PrinciplePlaneDelta;
foo1 = Plane3D(A,B,llc);
this->RequiredSplitPlanes.push_back(foo1);
A = llc; B = llc;
A.x = llc.x + PrinciplePlaneDelta; B.z = llc.z + PrinciplePlaneDelta;
foo1 = Plane3D(A,B,llc);
this->RequiredSplitPlanes.push_back(foo1);
A = urc; B = urc;
A.x = urc.x - PrinciplePlaneDelta; B.y = urc.y - PrinciplePlaneDelta;
foo1 = Plane3D(A,B,urc);
this->RequiredSplitPlanes.push_back(foo1);
A = llc; B = llc;
A.y = llc.y + PrinciplePlaneDelta; B.x = llc.x + PrinciplePlaneDelta;
foo1 = Plane3D(A,B,llc);
this->RequiredSplitPlanes.push_back(foo1);
/////////////////////////////////////////////
A.x = cen.x; A.y = cen.y + PrinciplePlaneDelta; A.z = cen.z;
B.x = cen.x - PrinciplePlaneDelta; B.y = cen.y; B.z = cen.z;
foo1 = Plane3D(A,B,cen);
this->RequiredSplitPlanes.push_back(foo1);
A.x = cen.x; A.y = cen.y; A.z = cen.z - PrinciplePlaneDelta;
B.x = cen.x - PrinciplePlaneDelta; B.y = cen.y; B.z = cen.z;
foo1 = Plane3D(A,B,cen);
this->RequiredSplitPlanes.push_back(foo1);
A.x = cen.x; A.y = cen.y; A.z = cen.z - PrinciplePlaneDelta;
B.x = cen.x; B.y = cen.y + PrinciplePlaneDelta; B.z = cen.z;
foo1 = Plane3D(A,B,cen);
this->RequiredSplitPlanes.push_back(foo1);
/*this->RequiredSplitPlanes.push_back(foo1);
temp.n = Vector(0.,0.,-1.); // min. XY plane
temp.d = -(_bbx[2] - _mindist);
this->RequiredSplitPlanes.push_back(temp);
temp.n = Vector(0.,0.,1.); // max. XY plane
temp.d = -(_bbx[5] + _mindist);
this->RequiredSplitPlanes.push_back(temp);
temp.n = Vector(0.,-1.,0.); // min. XZ plane
temp.d = -(_bbx[1] - _mindist);
this->RequiredSplitPlanes.push_back(temp);
temp.n = Vector(0.,1.,0.); // max. XZ plane
temp.d = -(_bbx[4] + _mindist);
this->RequiredSplitPlanes.push_back(temp);
temp.n = Vector(-1.,0.,0.); // min. YZ plane
temp.d = -(_bbx[0] - _mindist);
this->RequiredSplitPlanes.push_back(temp);
temp.n = Vector(1.,0.,0.); // max. YZ plane
temp.d = -(_bbx[3] + _mindist);
this->RequiredSplitPlanes.push_back(temp);*/
}
Polyhedron2BSP::~Polyhedron2BSP() {
delete[] _bbx;
for (ULONG i=0; i<_points.size(); delete _points[i], ++i);
_inputpoly.clear();
}
BSPNode* Polyhedron2BSP::_BuildBSPTree_SL_NS(std::vector<Polygon *> &polygons, unsigned long depth, int label, Plane3D& ParentH) {
// Get number of polygons in the input vector
ULONG numPolygons = polygons.size();
if (numPolygons==0) {
return new BSPNode(label);
}
Plane3D splitPlane;
std::vector<Polygon *> frontList, backList;
if (depth > maxdepth) maxdepth = depth;
splitPlane = this->PickSplittingPlane(polygons, depth);
// Test each polygon against the dividing plane, adding them
// to the front list, back list, or both, as appropriate
for (unsigned long i = 0; i < numPolygons; i++) {
Polygon *poly = polygons[i];
switch (poly->ClassifyPolygonToPlane(splitPlane, false)) {
case Polygon::POLYGON_COPLANAR_WITH_PLANE:
/*if (poly->id == splitPlane.id && this->polygonmarker[poly->id - 1])
break;
else if (poly->id == splitPlane.id) {
this->polygonmarker[poly->id - 1] = true;
}*/
break;
case Polygon::POLYGON_IN_FRONT_OF_PLANE:
frontList.push_back(poly);
break;
case Polygon::POLYGON_BEHIND_PLANE:
backList.push_back(poly);
break;
case Polygon::POLYGON_STRADDLING_PLANE:
frontList.push_back(poly);
backList.push_back(poly);
break;
}
}
// Recursively build child subtrees and return new tree root combining them
BSPNode *frontTree = _BuildBSPTree_SL_NS(frontList, depth+1, BSPNode::OUT, splitPlane);
BSPNode *backTree = _BuildBSPTree_SL_NS(backList, depth+1, BSPNode::IN, splitPlane);
return new BSPNode(frontTree, backTree, splitPlane, depth);
}
Plane3D Polyhedron2BSP::PickSplittingPlane(std::vector<Polygon *> &polygons, unsigned long depth)
{
// Blend factor for optimizing for balance or splits (should be tweaked)
const float K = 0.8f;
// Variables for tracking best splitting plane seen so far
Plane3D bestPlane;
// Variable for tracking index of the best plane
ULONG idx = 0;
/*if (this->polygonmarker[ polygons[0]->id - 1])
std::cout << " PickSplittingPlane: polygon's plane has already been used!" << std::endl;*/
if (this->_splitType == 1) {
idx = myrand((ULONG) polygons.size());
//idx = (ULONG)polygons.size()-2;
//idx=0;
assert(idx<(ULONG)polygons.size() && idx>=0);
bestPlane = *(polygons[idx]->GetPlane());
//this->polygonmarker[ polygons[idx]->id - 1] = true;
bestPlane.id = polygons[idx]->id;
return bestPlane;
}
else {
float bestScore = std::numeric_limits<float>::max();
/*if (depth < this->RequiredSplitPlanes.size()) { // We should first split using required splitting planes
return this->RequiredSplitPlanes[depth]; }*/
// Try the plane of each polygon as a dividing plane
for (unsigned long i = 0; i < polygons.size(); i++) {
unsigned long numInFront = 0, numBehind = 0, numStraddling = 0;
Plane3D* plane = polygons[i]->GetPlane();
// Test against all other polygons
for (unsigned long j = 0; j < polygons.size(); j++) {
// Ignore testing against self
if (i == j) continue;
// Keep standing count of the various poly-plane relationships
switch (polygons[j]->ClassifyPolygonToPlane(plane,false)) {
case Polygon::POLYGON_COPLANAR_WITH_PLANE:
/* Coplanar polygons treated as being in front of plane */
case Polygon::POLYGON_IN_FRONT_OF_PLANE:
numInFront++;
break;
case Polygon::POLYGON_BEHIND_PLANE:
numBehind++;
break;
case Polygon::POLYGON_STRADDLING_PLANE:
numStraddling++;
break;
}
}
// Compute score as a weighted combination (based on K, with K in range
// 0..1) between balance and splits (lower score is better)
float score = K * numStraddling + (1.0f - K) * std::fabs((float)((float)numInFront - (float)numBehind));
if (score < bestScore) {
bestScore = score;
bestPlane = *plane;
idx = i;
}
}
/*if (this->polygonmarker[ polygons[0]->id - 1])
std::cout << " PickSplittingPlane: polygon's plane has already been used!" << std::endl;*/
bestPlane.id = polygons[idx]->id;
//this->polygonmarker[ polygons[idx]->id - 1] = true;
return bestPlane;
}
}
BSPNode* Polyhedron2BSP::GetBSP_SolidLeaf_no_split() {
if (_isbuilt)
return this->_root;
else {
if (this->_inputpoly.empty())
return (BSPNode *) NULL;
srand( (unsigned)time( NULL ) ); // Initialize the seed for random generator.
Plane3D foo;
//_root = _BuildBSPTree_SL_NS(this->_inputpoly, 0, BSPNode::OUT, foo);
_root = _AutoPartition(this->_inputpoly, 0, BSPNode::OUT, foo);
_isbuilt = true;
return _root;
}
}
int Polyhedron2BSP::IsInside(Point& p, double PlaneTHK) {
this->SetPlaneThickness(PlaneTHK);
BSPNode *node = this->GetBSP_SolidLeaf_no_split();
//return this->PointInSolidSpace(node, p);
return this->PointInSolidSpace_AutoPartition(node, p);
//return this->PointInSolidSpace(node, p);
}
int Polyhedron2BSP::PointInSolidSpace(BSPNode *node, Point& p)
// Using a solid-leaf BSP, determines if point p is inside, outside
// or on the boundary of polyhedron
// Returns:
// 0 : Outside
// 1 : Inside
// 2 : On the boundary
{
while (!node->IsLeaf()) {
int st = node->myplane.ClassifyPointToPlane(p,true);
if (st == Plane3D::POINT_IN_FRONT_OF_PLANE)
node = node->frontnode;
else if (st == Plane3D::POINT_BEHIND_PLANE)
node = node->backnode;
else if (st == Plane3D::POINT_ON_PLANE) {
int front = -1, back = -1;
if (!(node->frontnode->IsLeaf()))
front = PointInSolidSpace(node->frontnode, p);
if (!(node->backnode->IsLeaf()))
back = PointInSolidSpace(node->backnode, p);
assert(!(front==-1 && back==-1)); // Can both be a leaf ?
if (front==-1)
return back;
else if (back==-1)
return front;
return (front == back) ? front : 2;
}
}
// Now at a leaf, inside/outside status determined by solid flag
return node->IsSolid() ? 1 : 0;
}
int Polyhedron2BSP::PointInSolidSpace_AutoPartition(BSPNode *node, Point& p)
// Using a solid-leaf BSP, determines if point p is inside, outside
// or on the boundary of polyhedron
// Returns:
// 0 : Outside
// 1 : Inside
// 2 : On the polyhedron
{
if (node->IsLeaf()) {
if (node->IsSolid())
return 1;
else
return 0;
}
else {
int st = node->myplane.ClassifyPointToPlane(p,false);
/*int hit;
if (st == Plane3D::POINT_BEHIND_PLANE)
hit = PointInSolidSpace_AutoPartition(node->backnode, p);
else if (st == Plane3D::POINT_IN_FRONT_OF_PLANE)
hit = PointInSolidSpace_AutoPartition(node->frontnode, p);
else if (st = Plane3D::POINT_ON_PLANE) {
int front = 0, back = 0;
if (node->frontnode->IsLeaf())
front = -1;
else {
front = PointInSolidSpace_AutoPartition(node->frontnode, p);
}
if (node->backnode->IsLeaf())
back = -1;
else {
back = PointInSolidSpace_AutoPartition(node->backnode, p);
}
if (front == back && front == -1) {
front = PointInSolidSpace_AutoPartition(node->frontnode, p);
back = PointInSolidSpace_AutoPartition(node->backnode, p);
return front == back ? front : 2;
}
if (front == -1)
return back;
else if (back == -1)
return front;
else {
return front == back ? front : 2;
}
}*/
int hit = 0;
if (st == Plane3D::POINT_BEHIND_PLANE || st == Plane3D::POINT_ON_PLANE)
hit = PointInSolidSpace_AutoPartition(node->backnode, p);
if (!hit && (st == Plane3D::POINT_IN_FRONT_OF_PLANE || st == Plane3D::POINT_ON_PLANE))
hit = PointInSolidSpace_AutoPartition(node->frontnode, p);
/*if (!hit && st == Plane3D::POINT_ON_PLANE) {
int f1 = PointInSolidSpace_AutoPartition(node->frontnode, p);
int f2 = PointInSolidSpace_AutoPartition(node->backnode, p);
if (f1 == f2)
return f1;
else
return 2;
}*/
return hit;
}
}
int Polyhedron2BSP::ReadPolyhedronFromFile(std::string infn) {
CFileOperation myfile;
std::ifstream ifs;
std::string nodefn, elefn;
this->_inputpoly.clear();
// Initiate exact arithmetic
this->macheps = exactinit();
std::string ext = myfile.GetExtension(infn);
size_t elefound, nodefound;
elefound = ext.rfind("ele"); nodefound = ext.rfind("node");
if (elefound==std::string::npos && nodefound==std::string::npos) { // need ele/node extensions
std::cerr << std::endl << " Polyhedron2BSP::ReadPolyhedronFromFile: Need .ele/.node filenames!" << std::endl;
return 1;
}
if (elefound==std::string::npos) {
nodefn = infn;
elefn = myfile.MakeFilename(infn, ".node", ".ele");
}
else {
nodefn = myfile.MakeFilename(infn, ".ele", ".node");
elefn = infn;
}
MeshIO polyio(nodefn, elefn);
/*std::vector<Point *> points;
std::vector<unsigned long> ele; // We assume that we are going to read a triangular faceted polyhedron
*/
int nnpe;
if ((nnpe = polyio.ReadPolyhedron(_points, _ele)) < 0) {
std::cerr << std::endl << "\tError in reading node/ele file!" << std::endl;
return 2;
}
// Populate the input polyhedron
for (unsigned long i=0; i< _ele.size()/nnpe; ++i) {
std::vector<Point *> fooverts;
// get points of each polygonal face of the polyhedron
for (int j=0; j<nnpe; ++j) {
fooverts.push_back(_points[ _ele[i*nnpe+j] - 1 ]);
}
Polygon *foop = new Polygon(fooverts);
foop->id = i+1;
this->_inputpoly.push_back(foop);
}
// Get bbx of the polyhedron
_bbx = new double[6];
for (unsigned long i=0; i<_points.size(); ++i) {
if (i==0) {
for (int j=0; j<6; j=j+3) {
this->_bbx[j] = _points[i]->x;
this->_bbx[j+1] = _points[i]->y;
this->_bbx[j+2] = _points[i]->z;
}
}
if (_points[i]->x < _bbx[0]) _bbx[0] = _points[i]->x;
if (_points[i]->x > _bbx[3]) _bbx[3] = _points[i]->x;
if (_points[i]->y < _bbx[1]) _bbx[1] = _points[i]->y;
if (_points[i]->y > _bbx[4]) _bbx[4] = _points[i]->y;
if (_points[i]->z < _bbx[2]) _bbx[2] = _points[i]->z;
if (_points[i]->z > _bbx[5]) _bbx[5] = _points[i]->z;
}
double x,y,z,longest;
x = _bbx[3] - _bbx[0];
y = _bbx[4] - _bbx[1];
z = _bbx[5] - _bbx[2];
longest = sqrt(x * x + y * y + z * z);
if (longest == 0.0) {
std::cerr << "\n\tError: The point set is trivial.\n";
exit(1);
}
// Two identical points are distinguished by '_mindist'.
_mindist = longest * this->macheps;
//_mindist = this->macheps;
_inputpoly[0]->GetPlane()->plane_thk_epsilon = this->_mindist;
// Setup initial split planes
SetupRequiredSplitPlanes();
this->polygonmarker.assign(this->_inputpoly.size(),false);
return 0;
}
int Polyhedron2BSP::DeleteTree() {
if (!_isbuilt) {
return 0;
}
else {
_delete_node(this->_root);
delete _root;
_isbuilt = false;
return 0;
}
}
BSPNode* Polyhedron2BSP::_delete_node(BSPNode* node) {
if (node->IsLeaf()) {
return node;
}
else {
BSPNode *ret = _delete_node(node->frontnode);
delete ret;
ret = _delete_node(node->backnode);
delete ret;
return node;
}
}
double Polyhedron2BSP::GetPlaneThickness() {
return this->_inputpoly[0]->GetPlane()->plane_thk_epsilon;
}
void Polyhedron2BSP::SetPlaneThickness(double thk) {
this->_inputpoly[0]->GetPlane()->plane_thk_epsilon = thk;
}
BSPNode* Polyhedron2BSP::_AutoPartition(std::vector<Polygon *> &P, unsigned long depth, int label, Plane3D& ParentH) {
ULONG numfacets = P.size();
if (numfacets==0) {
return new BSPNode(label);
}
else {
if (depth > this->maxdepth)
this->maxdepth = depth;
Plane3D H = this->PickSplittingPlane(P, depth);
std::vector<Polygon *> P_positive, P_negative;
for (ULONG i=0; i< numfacets; ++i) {
Polygon* poly = P[i];
int st = poly->ClassifyPolygonToPlane(H,false); // "false" == use distance from plane rather than orient3d
if (st != Polygon::POLYGON_COPLANAR_WITH_PLANE) {
if (st == Polygon::POLYGON_STRADDLING_PLANE) {
P_negative.push_back(poly);
P_positive.push_back(poly);
}
else if (st == Polygon::POLYGON_BEHIND_PLANE) {
P_negative.push_back(poly);
}
else {
P_positive.push_back(poly);
}
}
}
BSPNode *child_negative = _AutoPartition(P_negative, depth+1, BSPNode::IN, H);
BSPNode *child_positive = _AutoPartition(P_positive, depth+1, BSPNode::OUT, H);
return new BSPNode(child_positive, child_negative, H, depth);
}
}
| 32.303483 | 148 | 0.648545 | [
"object",
"vector",
"solid"
] |
88f2716d1be0e3989e656fa86d3758841b538f46 | 3,412 | hpp | C++ | moe/natj/bindigs/third_party/tinyb/tinyb/api/tinyb/BluetoothGattService.hpp | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/natj/bindigs/third_party/tinyb/tinyb/api/tinyb/BluetoothGattService.hpp | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | moe/natj/bindigs/third_party/tinyb/tinyb/api/tinyb/BluetoothGattService.hpp | ark100/multi-os-engine | f71d66a58b3d7e5eb2a68541480b7a0d88c7b908 | [
"Apache-2.0"
] | null | null | null | /*
* Author: Petre Eftime <petre.p.eftime@intel.com>
* Copyright (c) 2015 Intel Corporation.
*
* 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 "BluetoothObject.hpp"
#include "BluetoothManager.hpp"
#include <vector>
/* Forward declaration of types */
struct _Object;
typedef struct _Object Object;
struct _GattService1;
typedef struct _GattService1 GattService1;
/**
* Provides access to Bluetooth GATT characteristic. Follows the BlueZ adapter API
* available at: http://git.kernel.org/cgit/bluetooth/bluez.git/tree/doc/gatt-api.txt
*/
class tinyb::BluetoothGattService: public BluetoothObject
{
friend class tinyb::BluetoothManager;
friend class tinyb::BluetoothEventManager;
friend class tinyb::BluetoothDevice;
friend class tinyb::BluetoothGattCharacteristic;
private:
GattService1 *object;
protected:
BluetoothGattService(GattService1 *object);
static std::unique_ptr<BluetoothGattService> make(Object *object,
BluetoothType type = BluetoothType::GATT_SERVICE,
std::string *name = nullptr,
std::string *identifier = nullptr,
BluetoothObject *parent = nullptr);
public:
static std::string java_class() {
return std::string(JAVA_PACKAGE "/BluetoothGattService");
}
virtual std::string get_java_class() const;
virtual std::string get_class_name() const;
virtual std::string get_object_path() const;
virtual BluetoothType get_bluetooth_type() const;
BluetoothGattService(const BluetoothGattService &object);
~BluetoothGattService();
virtual BluetoothGattService *clone() const;
/* D-Bus property accessors: */
/** Get the UUID of this service
* @return The 128 byte UUID of this service, NULL if an error occurred
*/
std::string get_uuid ();
/** Returns the device to which this service belongs to.
* @return The device.
*/
BluetoothDevice get_device ();
/** Returns true if this service is a primary service, false if secondary.
* @return true if this service is a primary service, false if secondary.
*/
bool get_primary ();
/** Returns a list of BluetoothGattCharacteristics this service exposes.
* @return A list of BluetoothGattCharacteristics exposed by this service
*/
std::vector<std::unique_ptr<BluetoothGattCharacteristic>> get_characteristics ();
};
| 34.816327 | 86 | 0.735053 | [
"object",
"vector"
] |
322ee8ba47ebae666d08cfd918d9a6c545cbc190 | 1,280 | cpp | C++ | Dynamic Programming-1/Boredom.cpp | vineeth2281/Coding-Ninjas-Competitive-programming | 68bd2c7caa7442ef064189d00f5116d9843a2d66 | [
"MIT"
] | 1 | 2020-09-16T08:43:43.000Z | 2020-09-16T08:43:43.000Z | Dynamic Programming-1/Boredom.cpp | vineeth2281/Coding-Ninjas-Competitive-programming | 68bd2c7caa7442ef064189d00f5116d9843a2d66 | [
"MIT"
] | null | null | null | Dynamic Programming-1/Boredom.cpp | vineeth2281/Coding-Ninjas-Competitive-programming | 68bd2c7caa7442ef064189d00f5116d9843a2d66 | [
"MIT"
] | null | null | null | /* Gary is bored and wants to play an interesting but tough game . So he figured out a new board game called "destroy the neighbours" . In this game there are N integers on a board. In one move, he can pick any integer x from the board and then all the integers with value x+1 or x-1 gets destroyed .This move will give him x points.
He plays the game until the board becomes empty . But as he want show this game to his friend Steven, he wants to learn techniques to maximise the points to show off . Can you help Gary in finding out the maximum points he receive grab from the game ?
Input Format :
Line 1 : Integer N
Line 2 : A list of N integers
Output Format :
Maximum points Gary can recieve from the Game setup
Constraints :
1<=N<=10^5
1<=A[i]<=1000
Sample Input :
2
1 2
Sample Output :
2 */
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int solve(int n,vector<int>A)
{
int *freq=new int[1005];
int *dp=new int[1005];
for(int i=0;i<1005;i++)
{
freq[i]=dp[i]=0;
}
for(int i=0;i<n;i++)
freq[A[i]]++;
dp[1]=freq[1];
for(int i=2;i<=1000;i++)
{
dp[i]=max(dp[i-1],dp[i-2]+i*freq[i]);
}
int maximum=dp[1000];
delete[] freq;
delete[] dp;
return maximum;
} | 28.444444 | 333 | 0.660156 | [
"vector"
] |
3231557e910e742c42b709758d4db645f07a75dd | 8,183 | cpp | C++ | tests/sketch/test_tensor.cpp | ajoudaki/Project2020-seq-tensor-sketching | 20b19ddd19751840d33af97abe314d29b34dc0d4 | [
"MIT"
] | 7 | 2020-12-07T11:33:17.000Z | 2022-01-02T07:30:52.000Z | tests/sketch/test_tensor.cpp | ajoudaki/Project2020-seq-tensor-sketching | 20b19ddd19751840d33af97abe314d29b34dc0d4 | [
"MIT"
] | 26 | 2021-01-13T18:15:23.000Z | 2022-02-27T05:52:59.000Z | tests/sketch/test_tensor.cpp | ajoudaki/Project2020-seq-tensor-sketching | 20b19ddd19751840d33af97abe314d29b34dc0d4 | [
"MIT"
] | 2 | 2021-01-06T15:03:10.000Z | 2022-01-02T07:18:45.000Z | #include "sketch/tensor.hpp"
#include "util/utils.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace {
using namespace ts;
using namespace ::testing;
constexpr uint8_t alphabet_size = 4;
const uint32_t set_size = int_pow<uint32_t>(alphabet_size, 3); // k-mers of length 3
constexpr uint32_t sketch_dim = 2;
constexpr uint32_t tuple_length = 3;
template <typename set_type>
void rand_init(uint32_t sketch_size, Vec2D<set_type> *hashes, Vec2D<bool> *signs) {
std::mt19937 gen(3412343);
std::uniform_int_distribution<set_type> rand_hash2(0, sketch_size - 1);
std::uniform_int_distribution<set_type> rand_bool(0, 1);
for (size_t h = 0; h < hashes->size(); h++) {
for (size_t c = 0; c < alphabet_size; c++) {
(*hashes)[h][c] = rand_hash2(gen);
(*signs)[h][c] = rand_bool(gen);
}
}
}
TEST(Tensor, Empty) {
Tensor<uint8_t> under_test(alphabet_size, sketch_dim, tuple_length, /*seed=*/31415);
std::vector<double> sketch = under_test.compute(std::vector<uint8_t>());
ASSERT_EQ(sketch.size(), sketch_dim);
ASSERT_THAT(sketch, ElementsAre(0, 0));
}
/** The sequence has one char, which is shorter than the tuple length, so the sketch will be 0 */
TEST(Tensor, OneChar) {
Tensor<uint8_t> under_test(alphabet_size, sketch_dim, tuple_length, /*seed=*/31415);
for (uint8_t c = 0; c < alphabet_size; ++c) {
std::vector<double> sketch = under_test.compute({ c });
ASSERT_THAT(sketch, ElementsAre(0, 0));
}
}
/** The sequence has one char, the tuple length is 1, so we should have a value of +/-1 on position
* h(seq[0]) */
TEST(Tensor, OneCharTuple1) {
constexpr uint32_t tuple_len = 1;
Tensor<uint8_t> under_test(alphabet_size, sketch_dim, tuple_len, /*seed=*/31415);
Vec2D<uint8_t> hashes = new2D<uint8_t>(tuple_len, alphabet_size);
Vec2D<bool> signs = new2D<bool>(tuple_len, alphabet_size);
rand_init(sketch_dim, &hashes, &signs);
under_test.set_hashes_for_testing(hashes, signs);
for (uint8_t c = 0; c < alphabet_size; ++c) {
std::vector<double> sketch = under_test.compute({ c });
for (uint32_t i = 0; i < sketch_dim; ++i) {
int8_t sign = signs[0][c] ? 1 : -1;
ASSERT_EQ(sketch[i] * sign, hashes[0][c] % sketch_dim == i) << "Char: " << (int)c;
}
}
}
/**
* The size of the sequence equals the size of the tuple, so the sketch will be 1 in one position
* (position H(x)), and 0 in all the other positions
*/
TEST(Tensor, FullStringDistinctChars) {
for (uint32_t sketch_dimension = 3; sketch_dimension < 10; ++sketch_dimension) {
for (uint32_t tuple_len = 2; tuple_len < 10; ++tuple_len) {
Tensor<uint8_t> under_test(tuple_len, sketch_dimension, tuple_len, /*seed=*/31415);
std::vector<uint8_t> sequence(tuple_len);
std::iota(sequence.begin(), sequence.end(), 0U);
std::vector<double> sketch = under_test.compute(sequence);
ASSERT_EQ(sketch.size(), sketch_dimension);
for (uint32_t i = 0; i < sketch_dimension; ++i) {
ASSERT_TRUE(std::abs(sketch[i]) == 0 || std::abs(sketch[i]) == 1);
}
ASSERT_EQ(1, std::abs(std::accumulate(sketch.begin(), sketch.end(), 0)))
<< "D=" << sketch_dimension << " t=" << tuple_len;
}
}
}
/**
* The size of the sequence equals the size of the tuple, so the sketch will be 1 or -1 in one
* position (position H(x)), and 0 in all the other positions.
*/
TEST(Tensor, FullStringRandomChars) {
std::mt19937 gen(1234567);
for (uint32_t sketch_dimension = 3; sketch_dimension < 10; ++sketch_dimension) {
for (uint32_t tuple_len = 2; tuple_len < 10; ++tuple_len) {
std::uniform_int_distribution<uint8_t> rand_char(0, alphabet_size - 1);
Tensor<uint8_t> under_test(alphabet_size, sketch_dimension, tuple_len, /*seed=*/31415);
Vec2D<uint8_t> hashes = new2D<uint8_t>(tuple_len, alphabet_size);
Vec2D<bool> signs = new2D<bool>(tuple_len, alphabet_size);
rand_init(sketch_dim, &hashes, &signs);
under_test.set_hashes_for_testing(hashes, signs);
std::vector<uint8_t> sequence(tuple_len);
for (uint8_t &c : sequence) {
c = rand_char(gen);
}
std::vector<double> sketch = under_test.compute(sequence);
uint32_t pos = 0; // the position where the sketch must be one
int8_t s = 1; // the sign of the sketch
for (uint32_t i = 0; i < sequence.size(); ++i) {
pos += hashes[i][sequence[i]];
s *= signs[i][sequence[i]] ? 1 : -1;
}
pos %= sketch_dimension;
ASSERT_EQ(sketch.size(), sketch_dimension);
for (uint32_t i = 0; i < sketch_dimension; ++i) {
ASSERT_EQ(i == pos ? s : 0, sketch[i]);
}
}
}
}
/**
* If a sequence contains identical characters, its sketch will be +/-1 in one position and 0 in all
* others, because all subsequences of length t are identical.
*/
TEST(Tensor, SameChars) {
std::mt19937 gen(342111);
std::uniform_int_distribution<uint8_t> rand_char(0, alphabet_size - 1);
std::uniform_int_distribution<uint8_t> rand_seq_len(0, 100);
for (uint32_t sketch_dimension = 3; sketch_dimension < 10; ++sketch_dimension) {
for (uint32_t tuple_len = 2; tuple_len < 10; ++tuple_len) {
Tensor<uint8_t> under_test(alphabet_size, sketch_dimension, tuple_len, /*seed=*/31415);
uint8_t sequence_length = tuple_len + rand_seq_len(gen);
std::vector<uint8_t> sequence(sequence_length, rand_char(gen));
std::vector<double> sketch = under_test.compute(sequence);
ASSERT_EQ(sketch.size(), sketch_dimension);
for (uint32_t i = 0; i < sketch_dimension; ++i) {
ASSERT_TRUE(std::abs(sketch[i]) == 0 || std::abs(sketch[i]) == 1);
}
ASSERT_EQ(1, std::abs(std::accumulate(sketch.begin(), sketch.end(), 0)))
<< "Dim=" << sketch_dimension << " t=" << tuple_len;
}
}
}
/**
* If a sequence contains distinct characters, then the tensor sketch for t=1 will contain multiples
* of (1/alphabet_size), because T(a)=1/alphabet_size for all characters a.
*/
TEST(Tensor, DistinctCharsTuple1) {
std::mt19937 gen(321567);
constexpr uint8_t tuple_len = 1;
std::vector<uint8_t> sequence(alphabet_size);
std::iota(sequence.begin(), sequence.end(), 0);
for (uint32_t sketch_dimension = 3; sketch_dimension < 10; ++sketch_dimension) {
Tensor<uint8_t> under_test(alphabet_size, sketch_dimension, tuple_len, /*seed=*/31415);
std::vector<double> sketch = under_test.compute(sequence);
ASSERT_EQ(sketch.size(), sketch_dimension);
for (uint32_t i = 0; i < sketch_dimension; ++i) {
double factor = sketch[i] / (1. / alphabet_size);
ASSERT_NEAR(factor, std::round(factor), 1e-3);
}
}
}
/**
* If a sequence of length seq_len contains distinct characters, then the tensor sketch for
* t=seq_len-1 will contain multiples of (1/seq_len), because T(a)=1/seq_len for all the seq_len
* subsequences of length seq_len-1.
*/
TEST(Tensor, DistinctCharsTupleTMinus1) {
std::mt19937 gen(321567);
for (uint32_t tuple_len = 1; tuple_len < 10; ++tuple_len) {
const uint8_t alphabet_size = tuple_len + 1;
std::vector<uint8_t> sequence(alphabet_size);
std::iota(sequence.begin(), sequence.end(), 0);
for (uint32_t sketch_dimension = 3; sketch_dimension < 10; ++sketch_dimension) {
Tensor<uint8_t> under_test(alphabet_size, sketch_dimension, tuple_len, /*seed=*/31415);
std::vector<double> sketch = under_test.compute(sequence);
ASSERT_EQ(sketch.size(), sketch_dimension);
for (uint32_t i = 0; i < sketch_dimension; ++i) {
double factor = sketch[i] / (1. / alphabet_size);
ASSERT_NEAR(factor, std::round(factor), 1e-3);
}
}
}
}
} // namespace
| 41.75 | 100 | 0.625687 | [
"vector"
] |
3232f142ca22430390beacd14ec377fa80a49915 | 2,251 | cpp | C++ | algorithms/cpp/Problems 301-400/_380_InsertDeleteGetRandomO1.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 301-400/_380_InsertDeleteGetRandomO1.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 301-400/_380_InsertDeleteGetRandomO1.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | /* Source - https://leetcode.com/problems/insert-delete-getrandom-o1/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
class RandomizedSet {
unordered_map<int, int> indexMap;
vector<int> data;
int index;
public:
/** Initialize your data structure here. */
RandomizedSet() {
indexMap.clear();
data.clear();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (indexMap.find(val) == indexMap.end()) {
data.push_back(val);
indexMap[val] = data.size() - 1;
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (indexMap.find(val) != indexMap.end()) {
int lastIndex = data.size() - 1;
if (data[lastIndex] != val) {
int temp = data[indexMap[val]];
data[indexMap[val]] = data[lastIndex];
data[lastIndex] = temp;
indexMap[data[indexMap[val]]] = indexMap[val];
}
data.pop_back();
indexMap.erase(val);
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() {
int random = rand() % data.size();
return data[random];
}
};
int main()
{
RandomizedSet obj;
bool ins, del;
ins = obj.insert(1);
if (ins == true) cout<<"Inserted";
else cout<<"Already present";
cout<<endl;
del = obj.remove(2);
if (del == true) cout<<"Removed";
else cout<<"Not present";
cout<<endl;
ins = obj.insert(2);
if (ins == true) cout<<"Inserted";
else cout<<"Already present";
cout<<endl;
cout<<"Random: "<<obj.getRandom()<<endl;
del = obj.remove(1);
if (del == true) cout<<"Removed";
else cout<<"Not present";
cout<<endl;
ins = obj.insert(2);
if (ins == true) cout<<"Inserted";
else cout<<"Already present";
cout<<endl;
cout<<"Random: "<<obj.getRandom()<<endl;
} | 24.204301 | 109 | 0.530875 | [
"vector"
] |
323f8d94db6ac0d242ea4e73dd4dc9d00073287e | 974 | cpp | C++ | PETCS/Advanced/tle15p2.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | PETCS/Advanced/tle15p2.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | PETCS/Advanced/tle15p2.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
ll N, M, T, ans = INF; vector<pair<ll, ll>> v; multiset<ll> s;
int main() {
cin.tie(0)->sync_with_stdio(0);
#ifndef ONLINE_JUDGE
freopen("../../input.txt", "r", stdin);
freopen("../../output.txt", "w", stdout);
#endif
cin >> N >> M >> T;
for(int i = 0; i < N; i++) {
s.insert(0);
}
for(int i = 0, t, f; i < M; i++) {
cin >> t >> f;
v.push_back({t, f});
}
sort(v.begin(), v.end());
for(int i = 0; i < M; i++) {
multiset<ll>::iterator it = s.upper_bound(v[i].first);
if(it != s.begin()) {
it--;
}
ll tm = *it;
if(v[i].first - tm >= T) {
ans = min(ans, tm);
}
tm = max(tm, v[i].first);
s.erase(it);
s.insert(tm+v[i].second);
}
ans = min(ans, *s.begin());
cout << ans << "\n";
return 0;
}
| 25.631579 | 62 | 0.454825 | [
"vector"
] |
3250615d956f9f7f19a85487d1e4bc0888c743f6 | 253 | cpp | C++ | LeetCode/0035.SearchInsertPosition/SearchInsertPosition.cpp | luspock/algorithms | 91644427f3f683481f911f6bc30c9eeb19934cdd | [
"MIT"
] | 1 | 2017-12-24T07:51:07.000Z | 2017-12-24T07:51:07.000Z | LeetCode/0035.SearchInsertPosition/SearchInsertPosition.cpp | luspock/algorithms | 91644427f3f683481f911f6bc30c9eeb19934cdd | [
"MIT"
] | null | null | null | LeetCode/0035.SearchInsertPosition/SearchInsertPosition.cpp | luspock/algorithms | 91644427f3f683481f911f6bc30c9eeb19934cdd | [
"MIT"
] | null | null | null | class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i=0;
int n = nums.size();
while(i<n){
if(target<=nums[i]) return i;
++i;
}
return i;
}
};
| 19.461538 | 54 | 0.426877 | [
"vector"
] |
325175adc26f6de399ce1d594bcaa790451d427f | 11,540 | cpp | C++ | src/SIPP.cpp | YimingXieUSC/JY_LNS | 396f0198b3e6f644c7601747ac53d6406442c8d4 | [
"MIT"
] | 24 | 2021-05-21T10:40:36.000Z | 2022-03-17T07:34:27.000Z | src/SIPP.cpp | YimingXieUSC/JY_LNS | 396f0198b3e6f644c7601747ac53d6406442c8d4 | [
"MIT"
] | null | null | null | src/SIPP.cpp | YimingXieUSC/JY_LNS | 396f0198b3e6f644c7601747ac53d6406442c8d4 | [
"MIT"
] | 8 | 2021-05-23T23:51:11.000Z | 2022-03-22T13:25:08.000Z | #include "SIPP.h"
void SIPP::updatePath(const LLNode* goal, vector<PathEntry> &path)
{
path.resize(goal->timestep + 1);
// num_of_conflicts = goal->num_of_conflicts;
const auto* curr = goal;
while (curr->parent != nullptr) // non-root node
{
const auto* prev = curr->parent;
int t = prev->timestep + 1;
while (t < curr->timestep)
{
path[t].location = prev->location; // wait at prev location
t++;
}
path[curr->timestep].location = curr->location; // move to curr location
curr = prev;
}
assert(curr->timestep == 0);
path[0].location = curr->location;
}
Path SIPP::findOptimalPath(const HLNode& node, const ConstraintTable& initial_constraints,
const vector<Path*>& paths, int agent, int lowerbound)
{
return findSuboptimalPath(node, initial_constraints, paths, agent, lowerbound, 1).first;
}
// find path by SIPP
// Returns a shortest path that satisfies the constraints of the give node while
// minimizing the number of internal conflicts (that is conflicts with known_paths for other agents found so far).
// lowerbound is an underestimation of the length of the path in order to speed up the search.
pair<Path, int> SIPP::findSuboptimalPath(const HLNode& node, const ConstraintTable& initial_constraints,
const vector<Path*>& paths, int agent, int lowerbound, double w)
{
this->w = w;
Path path;
auto t = clock();
ReservationTable reservation_table(initial_constraints);
reservation_table.build(node, agent);
runtime_build_CT = (double)(clock() - t) / CLOCKS_PER_SEC;
int holding_time = reservation_table.getHoldingTime();
t = clock();
reservation_table.buildCAT(agent, paths);
runtime_build_CAT = (double)(clock() - t) / CLOCKS_PER_SEC;
num_expanded = 0;
num_generated = 0;
Interval interval = reservation_table.get_first_safe_interval(start_location);
if (get<0>(interval) > 0)
return {path, 0};
// generate start and add it to the OPEN list
auto start = new SIPPNode(start_location, 0, my_heuristic[start_location], nullptr, 0, interval, 0, false);
num_generated++;
start->open_handle = open_list.push(start);
start->focal_handle = focal_list.push(start);
start->in_openlist = true;
allNodes_table.insert(start);
min_f_val = max(holding_time, max((int)start->getFVal(), lowerbound));
while (!open_list.empty())
{
updateFocalList(); // update FOCAL if min f-val increased
SIPPNode* curr = focal_list.top(); focal_list.pop();
open_list.erase(curr->open_handle);
curr->in_openlist = false;
num_expanded++;
// check if the popped node is a goal node
if (curr->location == goal_location && // arrive at the goal location
!curr->wait_at_goal && // not wait at the goal location
curr->timestep >= holding_time) // the agent can hold the goal location afterward
{
updatePath(curr, path);
break;
}
for (int next_location : instance.getNeighbors(curr->location)) // move to neighboring locations
{
for (auto interval : reservation_table.get_safe_intervals(
curr->location, next_location, curr->timestep + 1, get<1>(curr->interval) + 1))
{
generateChild(interval, curr, next_location, reservation_table);
}
} // end for loop that generates successors
// wait at the current location
bool found = reservation_table.find_safe_interval(interval, curr->location, get<1>(curr->interval));
if (found)
{
generateChild(interval, curr, curr->location, reservation_table);
}
} // end while loop
// no path found
releaseNodes();
return {path, min_f_val};
}
void SIPP::updateFocalList()
{
auto open_head = open_list.top();
if (open_head->getFVal() > min_f_val)
{
int new_min_f_val = (int)open_head->getFVal();
for (auto n : open_list)
{
if (n->getFVal() > w * min_f_val && n->getFVal() <= w * new_min_f_val)
n->focal_handle = focal_list.push(n);
}
min_f_val = new_min_f_val;
}
}
inline SIPPNode* SIPP::popNode()
{
auto node = focal_list.top(); focal_list.pop();
open_list.erase(node->open_handle);
node->in_openlist = false;
num_expanded++;
return node;
}
inline void SIPP::pushNode(SIPPNode* node)
{
node->open_handle = open_list.push(node);
node->in_openlist = true;
num_generated++;
if (node->getFVal() <= w * min_f_val)
node->focal_handle = focal_list.push(node);
}
void SIPP::releaseNodes()
{
open_list.clear();
focal_list.clear();
for (auto node: allNodes_table)
delete node;
allNodes_table.clear();
}
void SIPP::generateChild(const Interval& interval, SIPPNode* curr, int next_location,
const ReservationTable& reservation_table)
{
// compute cost to next_id via curr node
int next_timestep = max(curr->timestep + 1, (int)get<0>(interval));
int next_g_val = next_timestep;
int next_h_val = my_heuristic[next_location];
if (next_g_val + next_h_val > reservation_table.length_max)
return;
int next_conflicts = curr->num_of_conflicts + (int)get<2>(interval);
// generate (maybe temporary) node
auto next = new SIPPNode(next_location, next_g_val, next_h_val, curr, next_timestep, interval, next_conflicts, false);
if (next_location == goal_location && curr->location == goal_location)
next->wait_at_goal = true;
// try to retrieve it from the hash table
auto it = allNodes_table.find(next);
if (it == allNodes_table.end())
{
pushNode(next);
allNodes_table.insert(next);
return;
}
// update existing node's if needed (only in the open_list)
auto existing_next = *it;
if (existing_next->getFVal() > next->getFVal() || // if f-val decreased through this new path
(existing_next->getFVal() == next->getFVal() &&
existing_next->num_of_conflicts > next->num_of_conflicts)) // or it remains the same but there's fewer conflicts
{
if (!existing_next->in_openlist) // if its in the closed list (reopen)
{
existing_next->copy(*next);
pushNode(existing_next);
}
else
{
bool add_to_focal = false; // check if it was above the focal bound before and now below (thus need to be inserted)
bool update_in_focal = false; // check if it was inside the focal and needs to be updated (because f-val changed)
bool update_open = false;
if ((next_g_val + next_h_val) <= w * min_f_val)
{ // if the new f-val qualify to be in FOCAL
if (existing_next->getFVal() > w * min_f_val)
add_to_focal = true; // and the previous f-val did not qualify to be in FOCAL then add
else
update_in_focal = true; // and the previous f-val did qualify to be in FOCAL then update
}
if (existing_next->getFVal() > next_g_val + next_h_val)
update_open = true;
existing_next->copy(*next); // update existing node
if (update_open)
open_list.increase(existing_next->open_handle); // increase because f-val improved
if (add_to_focal)
existing_next->focal_handle = focal_list.push(existing_next);
if (update_in_focal)
focal_list.update(existing_next->focal_handle); // should we do update? yes, because number of conflicts may go up or down
}
}
delete(next); // not needed anymore -- we already generated it before
}
// TODO:: currently this is implemented in A*, not SIPP
int SIPP::getTravelTime(int start, int end, const ConstraintTable& constraint_table, int upper_bound)
{
int length = MAX_TIMESTEP;
auto root = new SIPPNode(start, 0, compute_heuristic(start, end), nullptr, 0, Interval(0, 1, 0));
root->open_handle = open_list.push(root); // add root to heap
allNodes_table.insert(root); // add root to hash_table (nodes)
SIPPNode* curr = nullptr;
while (!open_list.empty())
{
curr = open_list.top(); open_list.pop();
if (curr->location == end)
{
length = curr->g_val;
break;
}
list<int> next_locations = instance.getNeighbors(curr->location);
next_locations.emplace_back(curr->location);
for (int next_location : next_locations)
{
int next_timestep = curr->timestep + 1;
int next_g_val = curr->g_val + 1;
if (constraint_table.latest_timestep <= curr->timestep)
{
if (curr->location == next_location)
{
continue;
}
next_timestep--;
}
if (!constraint_table.constrained(next_location, next_timestep) &&
!constraint_table.constrained(curr->location, next_location, next_timestep))
{ // if that grid is not blocked
int next_h_val = compute_heuristic(next_location, end);
if (next_g_val + next_h_val >= upper_bound) // the cost of the path is larger than the upper bound
continue;
auto next = new SIPPNode(next_location, next_g_val, next_h_val, nullptr, next_timestep, Interval(next_timestep, next_timestep + 1, 0));
auto it = allNodes_table.find(next);
if (it == allNodes_table.end())
{ // add the newly generated node to heap and hash table
next->open_handle = open_list.push(next);
allNodes_table.insert(next);
}
else { // update existing node's g_val if needed (only in the heap)
delete(next); // not needed anymore -- we already generated it before
auto existing_next = *it;
if (existing_next->g_val > next_g_val)
{
existing_next->g_val = next_g_val;
existing_next->timestep = next_timestep;
open_list.increase(existing_next->open_handle);
}
}
}
}
}
releaseNodes();
return length;
/*int length = INT_MAX;
// generate a heap that can save nodes (and a open_handle)
pairing_heap< SIPPNode*, compare<SIPPNode::compare_node> > open_list;
// boost::heap::pairing_heap< AStarNode*, boost::heap::compare<LLNode::compare_node> >::handle_type open_handle;
unordered_set<SIPPNode*, SIPPNode::NodeHasher, SIPPNode::eqnode> nodes;
Interval interval = reservation_table.get_first_safe_interval(start);
assert(get<0>(interval) == 0);
auto root = new SIPPNode(start, 0, instance.getManhattanDistance(start, end), nullptr, 0, interval);
root->open_handle = open_list.push(root); // add root to heap
nodes.insert(root); // add root to hash_table (nodes)
while (!open_list.empty())
{
auto curr = open_list.top(); open_list.pop();
if (curr->location == end)
{
length = curr->g_val;
break;
}
for (int next_location : instance.getNeighbors(curr->location))
{
if ((curr->location == blocked.first && next_location == blocked.second) ||
(curr->location == blocked.second && next_location == blocked.first)) // use the prohibited edge
{
continue;
}
for (auto interval : reservation_table.get_safe_intervals(
curr->location, next_location, curr->timestep + 1, get<1>(curr->interval) + 1))
{
int next_timestep = max(curr->timestep + 1, (int)get<0>(interval));
int next_g_val = next_timestep;
int next_h_val = instance.getManhattanDistance(next_location, end);
if (next_g_val + next_h_val >= upper_bound) // the cost of the path is larger than the upper bound
continue;
auto next = new SIPPNode(next_location, next_g_val, next_h_val, nullptr, next_timestep, interval);
auto it = nodes.find(next);
if (it == nodes.end())
{ // add the newly generated node to heap and hash table
next->open_handle = open_list.push(next);
nodes.insert(next);
}
else { // update existing node's g_val if needed (only in the heap)
delete(next); // not needed anymore -- we already generated it before
auto existing_next = *it;
if (existing_next->g_val > next_g_val)
{
existing_next->g_val = next_g_val;
existing_next->timestep = next_timestep;
open_list.update(existing_next->open_handle);
}
}
}
}
}
open_list.clear();
for (auto node : nodes)
{
delete node;
}
nodes.clear();
return length;*/
} | 34.345238 | 139 | 0.698007 | [
"vector"
] |
325e5f07ec8f6e4d51b4b7c4effadd222dd52a68 | 68,668 | cpp | C++ | admin/wmi/wbem/providers/win32provider/providers/logicaldisk.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/providers/win32provider/providers/logicaldisk.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/providers/win32provider/providers/logicaldisk.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //=================================================================
//
// LogicalDisk.CPP -- Logical Disk property set provider
//
// Copyright (c) 1996-2002 Microsoft Corporation, All Rights Reserved
//
//
// Strings for ValueMaps for DriveType come from:
// \\trango\slmadd\src\shell\shell32\shel32.rc. Search for
// IDS_DRIVES_REMOVABLE to find the clump.
//=================================================================
// following includes required for Getting if Volume is dirty
// a property for chkdsk.
#include "precomp.h"
#include <assertbreak.h>
#include <winioctl.h>
#include "sid.h"
#include "implogonuser.h"
#include <frqueryex.h>
#include "resource.h"
#include "LogicalDisk.h"
#include "Kernel32Api.h"
#include <lmuse.h>
#include "DllWrapperBase.h"
#include "MprApi.h"
#include <initguid.h>
#include <DskQuota.h>
#include "..\dskquotaprovider\inc\DskQuotaCommon.h"
#include "AdvApi32Api.h"
#include "UserEnvApi.h"
#include "userhive.h"
#ifdef NTONLY
// for chkdisk dll exposed methods
#include <fmifs.h>
#include "mychkdsk.h"
#endif
#define LD_ALL_PROPS 0xffffffff
#define LD_Name_BIT 0x00000001
#define LD_Caption_BIT 0x00000002
#define LD_DeviceID_BIT 0x00000004
#define LD_Description_BIT 0x00000008
#define LD_DriveType_BIT 0x00000010
#define LD_SystemCreationClassName_BIT 0x00000020
#define LD_SystemName_BIT 0x00000040
#define LD_MediaType_BIT 0x00000080
#define LD_ProviderName_BIT 0x00000100
#define LD_VolumeName_BIT 0x00000200
#define LD_FileSystem_BIT 0x00000400
#define LD_VolumeSerialNumber_BIT 0x00000800
#define LD_Compressed_BIT 0x00001000
#define LD_SupportsFileBasedCompression_BIT 0x00002000
#define LD_MaximumComponentLength_BIT 0x00004000
#define LD_Size_BIT 0x00008000
#define LD_FreeSpace_BIT 0x00010000
// for dskQuotas
#define LD_SupportsDiskQuotas 0x00020000
#define LD_QuotasDisabled 0x00040000
#define LD_QuotasIncomplete 0x00080000
#define LD_QuotasRebuilding 0x00100000
//ForChkDsk
#define LD_VolumeDirty 0x00200000
#define LD_GET_VOL_INFO (LD_VolumeName_BIT | \
LD_FileSystem_BIT | \
LD_VolumeSerialNumber_BIT | \
LD_Compressed_BIT | \
LD_SupportsFileBasedCompression_BIT | \
LD_MaximumComponentLength_BIT | \
LD_SupportsDiskQuotas | \
LD_QuotasDisabled | \
LD_QuotasIncomplete | \
LD_QuotasRebuilding | \
LD_VolumeDirty)
#define LD_SPIN_DISK (LD_GET_VOL_INFO | \
LD_Size_BIT | \
LD_FreeSpace_BIT)
#ifdef NTONLY
std::map < DWORD, DWORD > mReturnVal;
#endif
// Property set declaration
//=========================
LogicalDisk MyLogicalDiskSet ( PROPSET_NAME_LOGDISK , IDS_CimWin32Namespace ) ;
/*****************************************************************************
*
* FUNCTION : LogicalDisk::LogicalDisk
*
* DESCRIPTION : Constructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Registers property set with framework
*
*****************************************************************************/
LogicalDisk :: LogicalDisk (
LPCWSTR name,
LPCWSTR pszNamespace
) : Provider ( name , pszNamespace )
{
m_ptrProperties.SetSize(22);
m_ptrProperties[0] = ((LPVOID) IDS_Name);
m_ptrProperties[1] = ((LPVOID) IDS_Caption);
m_ptrProperties[2] = ((LPVOID) IDS_DeviceID);
m_ptrProperties[3] = ((LPVOID) IDS_Description);
m_ptrProperties[4] = ((LPVOID) IDS_DriveType);
m_ptrProperties[5] = ((LPVOID) IDS_SystemCreationClassName);
m_ptrProperties[6] = ((LPVOID) IDS_SystemName);
m_ptrProperties[7] = ((LPVOID) IDS_MediaType);
m_ptrProperties[8] = ((LPVOID) IDS_ProviderName);
m_ptrProperties[9] = ((LPVOID) IDS_VolumeName);
m_ptrProperties[10] = ((LPVOID) IDS_FileSystem);
m_ptrProperties[11] = ((LPVOID) IDS_VolumeSerialNumber);
m_ptrProperties[12] = ((LPVOID) IDS_Compressed);
m_ptrProperties[13] = ((LPVOID) IDS_SupportsFileBasedCompression);
m_ptrProperties[14] = ((LPVOID) IDS_MaximumComponentLength);
m_ptrProperties[15] = ((LPVOID) IDS_Size);
m_ptrProperties[16] = ((LPVOID) IDS_FreeSpace);
m_ptrProperties[17] = ((LPVOID) IDS_SupportsDiskQuotas);
m_ptrProperties[18] = ((LPVOID) IDS_QuotasDisabled);
m_ptrProperties[19] = ((LPVOID) IDS_QuotasIncomplete);
m_ptrProperties[20] = ((LPVOID) IDS_QuotasRebuilding);
m_ptrProperties[21] = ((LPVOID) IDS_VolumeDirty);
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::~LogicalDisk
*
* DESCRIPTION : Destructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Deregisters property set from framework
*
*****************************************************************************/
LogicalDisk :: ~LogicalDisk ()
{
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::~LogicalDisk
*
* DESCRIPTION : Destructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Deregisters property set from framework
*
*****************************************************************************/
HRESULT LogicalDisk :: ExecQuery (
MethodContext *pMethodContext,
CFrameworkQuery &pQuery,
long lFlags /*= 0L*/
)
{
HRESULT hr = WBEM_S_NO_ERROR;
// Use the extended query type
std::vector<int> vectorValues;
DWORD dwTypeSize = 0;
CFrameworkQueryEx *pQuery2 = static_cast <CFrameworkQueryEx *>(&pQuery);
// Find out what properties they asked for
DWORD dwProperties = 0;
pQuery2->GetPropertyBitMask(m_ptrProperties, &dwProperties);
// See if DriveType is part of the where clause
pQuery2->GetValuesForProp(IDS_DriveType, vectorValues);
dwTypeSize = vectorValues.size();
// See if DeviceID is part of the where clause
CHStringArray sDriveLetters;
pQuery.GetValuesForProp ( IDS_DeviceID , sDriveLetters ) ;
DWORD dwLetterSize = sDriveLetters.GetSize () ;
// Format drives so they match what comes back from GetLogicalDriveStrings
for ( DWORD x = 0 ; x < dwLetterSize ; x ++ )
{
sDriveLetters [ x ] += _T('\\') ;
}
CImpersonateLoggedOnUser icu;
icu.Begin () ;
// Get the LogicalDrive letters from the os
TCHAR szDriveStrings [ 320 ] ;
if ( GetLogicalDriveStrings ( ( sizeof(szDriveStrings)/sizeof(TCHAR)) - 1, szDriveStrings ) )
{
// Walk the drive letters
for( TCHAR *pszCurrentDrive = szDriveStrings ; *pszCurrentDrive && SUCCEEDED ( hr ) ; pszCurrentDrive += (lstrlen(pszCurrentDrive) + 1))
{
bool bContinue = true;
// If they specified a DriveType in the where clause
if (dwTypeSize > 0)
{
// If we don't find a match, don't send back an instance
bContinue = false;
// Get the DriveType of the current loop
DWORD dwDriveType = GetDriveType(pszCurrentDrive);
// See if it matches any of the values required
for ( DWORD x = 0; x < dwTypeSize ; x ++ )
{
if ( vectorValues [ x ] == dwDriveType )
{
bContinue = true ;
break;
}
}
}
// If DriveType failed, no point in continuing.
// Otherwise, if they specified a DeviceID
if ( ( bContinue ) && ( dwLetterSize > 0 ) )
{
// Even if DriveType matched, if they specified a DeviceID,
// there's no point continuing if we don't find a match.
bContinue = false;
for ( DWORD x = 0 ; x < dwLetterSize ; x ++ )
{
if ( sDriveLetters [ x ].CompareNoCase ( TOBSTRT ( pszCurrentDrive ) ) == 0 )
{
bContinue = true ;
break;
}
}
}
// If the where clauses haven't filtered out this drive letter
if ( bContinue )
{
CInstancePtr pInstance(CreateNewInstance ( pMethodContext ), false);
CHString currentDrive ( pszCurrentDrive ) ;
currentDrive.MakeUpper();
pInstance->SetCHString(IDS_Name, currentDrive.SpanExcluding(L"\\"));
pInstance->SetCHString(IDS_Caption, currentDrive.SpanExcluding(L"\\"));
pInstance->SetCHString(IDS_DeviceID, currentDrive.SpanExcluding(L"\\"));
GetLogicalDiskInfo ( pInstance, dwProperties ) ;
hr = pInstance->Commit ( ) ;
}
}
}
return hr;
}
/*****************************************************************************
*
* FUNCTION : GetObject
*
* DESCRIPTION : Assigns values to property set according to key value
* already set by framework
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
HRESULT LogicalDisk :: GetObject (
CInstance *pInstance,
long lFlags,
CFrameworkQuery &pQuery
)
{
HRESULT hRetCode = WBEM_E_NOT_FOUND;
CImpersonateLoggedOnUser icu;
icu.Begin () ;
TCHAR szDriveStrings[320] ;
if ( GetLogicalDriveStrings((sizeof(szDriveStrings) - 1) / sizeof(TCHAR), szDriveStrings ) )
{
CHString strName ;
pInstance->GetCHString(IDS_DeviceID, strName);
for ( TCHAR *pszCurrentDrive = szDriveStrings ;
*pszCurrentDrive ;
pszCurrentDrive += (lstrlen(pszCurrentDrive) + 1)
)
{
CHString strDrive = pszCurrentDrive ;
if ( 0 == strName.CompareNoCase( strDrive.SpanExcluding(L"\\") ) )
{
pInstance->SetCHString ( IDS_Name , strName ) ;
pInstance->SetCHString ( IDS_Caption, strName ) ;
// We will want expensive properties in this case
CFrameworkQueryEx *pQuery2 = static_cast <CFrameworkQueryEx *>(&pQuery);
// Find out what properties they asked for
DWORD dwProperties = 0;
pQuery2->GetPropertyBitMask(m_ptrProperties, &dwProperties);
GetLogicalDiskInfo ( pInstance , dwProperties ) ;
hRetCode = WBEM_S_NO_ERROR;
break ;
}
}
}
return hRetCode ;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::EnumerateInstances
*
* DESCRIPTION : Creates instance of property set for each logical disk
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
HRESULT LogicalDisk :: EnumerateInstances (
MethodContext *pMethodContext,
long lFlags /*= 0L*/
)
{
TCHAR szDriveStrings[320] ;
CImpersonateLoggedOnUser icu;
icu.Begin () ;
HRESULT hr = WBEM_S_NO_ERROR;
if ( GetLogicalDriveStrings ( ( sizeof ( szDriveStrings ) / sizeof ( TCHAR ) ) - 1 , szDriveStrings ) )
{
for( TCHAR *pszCurrentDrive = szDriveStrings ;
*pszCurrentDrive && SUCCEEDED ( hr ) ;
pszCurrentDrive += (lstrlen(pszCurrentDrive) + 1)
)
{
CInstancePtr pInstance(CreateNewInstance ( pMethodContext ), false) ;
CHString currentDrive ( pszCurrentDrive ) ;
currentDrive.MakeUpper ();
pInstance->SetCHString ( IDS_Name , currentDrive.SpanExcluding(L"\\"));
pInstance->SetCHString ( IDS_Caption , currentDrive.SpanExcluding(L"\\"));
pInstance->SetCHString ( IDS_DeviceID , currentDrive.SpanExcluding(L"\\"));
GetLogicalDiskInfo ( pInstance , LD_ALL_PROPS ) ;
hr = pInstance->Commit ( ) ;
}
}
return hr;
}
#ifdef NTONLY
/*****************************************************************************
*
* FUNCTION : LogicalDisk::ExecMethod
*
* DESCRIPTION : Providing methods of chkdsk
*
*****************************************************************************/
HRESULT LogicalDisk::ExecMethod (
const CInstance& Instance,
const BSTR bstrMethodName,
CInstance *pInParams,
CInstance *pOutParams,
long lFlags
)
{
HRESULT hRes = WBEM_S_NO_ERROR;
if ( ! pOutParams )
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
if ( SUCCEEDED ( hRes ) )
{
CImpersonateLoggedOnUser icu;
// Do we recognize the method?
if ( _wcsicmp ( bstrMethodName , METHOD_NAME_CHKDSK ) == 0 )
{
icu.Begin () ;
// This method is instance specific
hRes = ExecChkDsk ( Instance , pInParams , pOutParams , lFlags ) ;
}
else
if ( _wcsicmp ( bstrMethodName , METHOD_NAME_SCHEDULEAUTOCHK ) == 0 )
{
icu.Begin () ;
// Following methods are static, i.e. not dependent on the instance
hRes = ExecScheduleChkdsk ( pInParams , pOutParams, lFlags ) ;
}
else
if ( _wcsicmp ( bstrMethodName , METHOD_NAME_EXCLUDEFROMAUTOCHK ) == 0 )
{
icu.Begin () ;
// Following methods are static, i.e. not dependent on the instance
hRes = ExecExcludeFromChkDsk ( pInParams , pOutParams, lFlags ) ;
}
}
return hRes;
}
#endif
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetLogicalDiskInfo
*
* DESCRIPTION : Loads LOGDISK_INFO struct w/property values according to
* disk type
*
* INPUTS : BOOL fGetExpensiveProperties - Exp. Properties flag.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS :
*
*****************************************************************************/
void LogicalDisk :: GetLogicalDiskInfo (
CInstance *pInstance,
DWORD dwProperties
)
{
CHString name;
pInstance->GetCHString ( IDS_Name , name ) ;
ASSERT_BREAK(!name.IsEmpty());
TCHAR szTemp[10] ;
lstrcpy(szTemp, TOBSTRT(name)) ;
lstrcat(szTemp, _T("\\")) ;
// We got a drive letter. If the disk is fixed, removable, or
// a CD-ROM, assume it must be installed. For network drives
// or RAM Disk, "installed" doesn't seem to be applicable.
DWORD dwDriveType = GetDriveType ( szTemp ) ;
switch(dwDriveType)
{
case DRIVE_FIXED:
{
GetFixedDriveInfo ( pInstance, szTemp, dwProperties ) ;
}
break ;
case DRIVE_REMOVABLE :
{
GetRemoveableDriveInfo ( pInstance, szTemp, dwProperties ) ;
}
break ;
case DRIVE_REMOTE :
{
GetRemoteDriveInfo ( pInstance, szTemp, dwProperties ) ;
}
break ;
case DRIVE_CDROM :
{
GetCDROMDriveInfo ( pInstance, szTemp, dwProperties ) ;
}
break ;
case DRIVE_RAMDISK :
{
GetRAMDriveInfo ( pInstance, szTemp, dwProperties ) ;
}
break ;
default :
{
pInstance->SetWCHARSplat(IDS_Description, L"Unknown drive type");
}
break ;
}
pInstance->SetDWORD ( IDS_DriveType , dwDriveType ) ;
SetCreationClassName ( pInstance ) ;
pInstance->SetWCHARSplat ( IDS_SystemCreationClassName , L"Win32_ComputerSystem" ) ;
pInstance->SetCHString ( IDS_SystemName, GetLocalComputerName () ) ;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetFixedDriveInfo
*
* DESCRIPTION : Retrieves property values for fixed-media logical disk
*
* INPUTS : char* pszName - Name of Drive to get info for.
* BOOL fGetExpensiveProperties - Exp. Properties flag.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS :
*
*****************************************************************************/
void LogicalDisk :: GetFixedDriveInfo (
CInstance *pInstance,
LPCTSTR pszName,
DWORD dwProperties
)
{
// Identify the drive type
CHString sTemp2;
LoadStringW(sTemp2, IDR_LocalFixedDisk);
pInstance->SetCHString ( IDS_Description , sTemp2 ) ;
pInstance->SetDWORD ( IDS_MediaType , FixedMedia ) ;
DWORD dwResult = 0 ;
// Get Expensive properties now if appropriate.
if ( dwProperties & LD_GET_VOL_INFO)
{
// Obtain volume information
dwResult = GetDriveVolumeInformation ( pInstance , pszName ) ;
}
if (dwResult == 0)
{
if ( dwProperties &
(LD_Size_BIT |
LD_FreeSpace_BIT) )
{
GetDriveFreeSpace ( pInstance , pszName ) ;
}
}
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetRemoveableDriveInfo
*
* DESCRIPTION : Retrieves property values for removeable drive
*
* INPUTS : char* pszName - Name of Drive to get info for.
* BOOL fGetExpensiveProperties - Exp. Properties flag.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Separates call based on 95 or NT
*
*****************************************************************************/
void LogicalDisk :: GetRemoveableDriveInfo (
CInstance *pInstance,
LPCTSTR pszName,
DWORD dwProperties
)
{
// In case anything goes wrong, at least say we're working with
// a removeable disk.
CHString sTemp2;
LoadStringW(sTemp2, IDR_RemovableDisk);
pInstance->SetCHString ( IDS_Description , sTemp2 ) ;
// Obtaining removeable drive information requires the use of
// the DeviceIoControl function. To further complicate things,
// the method of retrieval is different for NT and 95, so
// let's just farm out the function calls now.
BOOL t_MediaPresent = FALSE ;
#ifdef NTONLY
GetRemoveableDriveInfoNT ( pInstance, pszName , t_MediaPresent, dwProperties );
#endif
DWORD dwResult = 0 ;
// Get Expensive properties now if appropriate.
if ( t_MediaPresent &&
( dwProperties & LD_GET_VOL_INFO ) )
{
dwResult = GetDriveVolumeInformation ( pInstance, pszName );
}
if (t_MediaPresent && dwResult == 0)
{
if ( dwProperties &
(LD_Size_BIT |
LD_FreeSpace_BIT) )
{
GetDriveFreeSpace ( pInstance , pszName ) ;
}
}
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetRemoveableDriveInfoNT
*
* DESCRIPTION : Retrieves property values for removeable drive
*
* INPUTS : char* pszName - Name of Drive to get info for.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Performs operation using DeviceIoControl in NT
*
*****************************************************************************/
#ifdef NTONLY
void LogicalDisk :: GetRemoveableDriveInfoNT (
CInstance *pInstance,
LPCTSTR pszName ,
BOOL &a_MediaPresent,
DWORD dwProperties
)
{
// we have this set globally at system startup time.
// SOMETHING is stepping on it on NT 3.51 *only* This suggests
// that a DLL we load is turning it off.
if ( IsWinNT351 () )
{
UINT oldErrorMode = SetErrorMode ( SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX ) ;
SetErrorMode ( oldErrorMode | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX ) ;
}
// Convert the drive letter to a number (the indeces are 1 based)
int nDrive = ( toupper(*pszName) - 'A' ) + 1;
// The following code was lifted from Knowledge Base Article
// Q163920. The code uses DeviceIoControl to discover the
// type of drive we are dealing with.
TCHAR szDriveName[8];
wsprintf(szDriveName, TEXT("\\\\.\\%c:"), TEXT('@') + nDrive);
SmartCloseHandle hVMWIN32 = CreateFile (
szDriveName,
FILE_ANY_ACCESS,
FILE_SHARE_WRITE | FILE_SHARE_READ,
0,
OPEN_EXISTING,
0,
0
);
if ( hVMWIN32 != INVALID_HANDLE_VALUE )
{
/*
* Verify media present
*/
if (dwProperties & LD_SPIN_DISK)
{
DWORD t_BytesReturned ;
a_MediaPresent = DeviceIoControl (
hVMWIN32,
IOCTL_STORAGE_CHECK_VERIFY2 ,
NULL,
0,
NULL,
0,
&t_BytesReturned,
0
) ;
if (!a_MediaPresent)
{
DWORD t_GetLastError = GetLastError () ;
if ( t_GetLastError != ERROR_NOT_READY )
{
LogErrorMessage2(L"Device IO control returned unexpected error for Check verify: (%d)", t_GetLastError);
}
}
}
else
{
a_MediaPresent = FALSE;
}
/*
* Get media types
*/
DISK_GEOMETRY Geom[20];
DWORD cb ;
BOOL t_Status = DeviceIoControl (
hVMWIN32,
IOCTL_DISK_GET_MEDIA_TYPES,
0,
0,
Geom,
sizeof(Geom),
&cb,
0
) ;
if ( t_Status && cb > 0 )
{
int nGeometries = cb / sizeof(DISK_GEOMETRY) ;
BOOL bFound = FALSE ;
// Go through all geometries. If we find any 3.5 ones,
// put it in Geom[0]. This seems to happen on PC-98s.
for ( int i = 0; i < nGeometries && ! bFound; i++ )
{
switch ( Geom [ i ].MediaType )
{
// Found something 'higher' than a 5.25 drive, so
// move it into Geom[0] and get out.
case RemovableMedia:
case F3_1Pt44_512: // 3.5 1.44MB floppy
case F3_2Pt88_512: // 3.5 2.88MB floppy
case F3_20Pt8_512: // 3.5 20.8MB floppy
case F3_720_512: // 3.5 720K floppy
case F3_120M_512: // 3.5 120MB floppy
{
Geom[0].MediaType = Geom[i].MediaType ;
bFound = TRUE;
}
break;
default:
{
}
break;
}
}
pInstance->SetDWORD ( IDS_MediaType , Geom[0].MediaType ) ;
CHString sTemp2;
switch ( Geom [ 0 ].MediaType )
{
case F5_1Pt2_512: // 5.25 1.2MB floppy
case F5_360_512: // 5.25 360K floppy
case F5_320_512: // 5.25 320K floppy
case F5_320_1024: // 5.25 320K floppy
case F5_180_512: // 5.25 180K floppy
case F5_160_512: // 5.25 160K floppy
{
LoadStringW(sTemp2, IDR_525Floppy);
}
break;
case F3_1Pt44_512: // 3.5 1.44MB floppy
case F3_2Pt88_512: // 3.5 2.88MB floppy
case F3_20Pt8_512: // 3.5 20.8MB floppy
case F3_720_512: // 3.5 720K floppy
case F3_120M_512: // 3.5 120MB floppy
{
LoadStringW(sTemp2, IDR_350Floppy);
}
break;
default: // unknown already defaulted to "Removeable Disk"
{
}
break;
}
pInstance->SetCHString(IDS_Description, sTemp2);
}
}
}
#endif
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetRemoteDriveInfo
*
* DESCRIPTION : Retrieves property values for remote logical drives
*
* INPUTS : char* pszName - Name of Drive to get info for.
* BOOL fGetExpensiveProperties - Exp. Properties flag.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS :
*
*****************************************************************************/
void LogicalDisk::GetRemoteDriveInfo (
CInstance *pInstance,
LPCTSTR pszName,
DWORD dwProperties
)
{
CMprApi *t_MprApi = ( CMprApi * )CResourceManager::sm_TheResourceManager.GetResource ( g_guidMprApi, NULL ) ;
if ( t_MprApi )
{
pInstance->SetDWORD ( IDS_MediaType , Unknown ) ;
CHString sTemp2;
LoadStringW(sTemp2, IDR_NetworkConnection);
pInstance->SetCHString ( IDS_Description , sTemp2 ) ;
// Get Expensive properties now if appropriate.
if ( dwProperties &
(LD_SPIN_DISK |
LD_ProviderName_BIT) )
{
if ( dwProperties & LD_ProviderName_BIT )
{
// Enumerate network resources to identify this drive's share
//===========================================================
// The enumeration will return drives identified by Drive Letter
// and a colon (e.g. M:)
TCHAR szTempDrive[_MAX_PATH] ;
_stprintf(szTempDrive, _T("%c%c"), pszName[0], pszName[1]) ;
TCHAR szProvName[_MAX_PATH];
DWORD dwProvName = sizeof ( szProvName ) ;
DWORD dwRetCode = t_MprApi->WNetGetConnection ( szTempDrive , szProvName , & dwProvName ) ;
if (dwRetCode == NO_ERROR)
{
pInstance->SetCharSplat ( IDS_ProviderName , szProvName ) ;
}
else
{
dwRetCode = GetLastError();
if ( ( dwRetCode == ERROR_MORE_DATA ) && (dwProvName > _MAX_PATH ) )
{
TCHAR *szNewProvName = new TCHAR[dwProvName];
if (szNewProvName != NULL)
{
try
{
dwRetCode = t_MprApi->WNetGetConnection ( szTempDrive , szNewProvName , &dwProvName);
if (dwRetCode == NO_ERROR)
{
pInstance->SetCharSplat(IDS_ProviderName, szNewProvName);
}
}
catch ( ... )
{
delete [] szNewProvName ;
throw ;
}
delete [] szNewProvName ;
}
else
{
throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ;
}
}
}
}
DWORD dwResult = 0 ;
// Get Expensive properties now if appropriate.
if ( dwProperties & LD_GET_VOL_INFO )
{
// Obtain volume information
dwResult = GetDriveVolumeInformation ( pInstance, pszName );
}
if ( dwResult == 0 )
{
if ( dwProperties &
(LD_Size_BIT |
LD_FreeSpace_BIT) )
{
GetDriveFreeSpace ( pInstance , pszName );
}
}
}
CResourceManager::sm_TheResourceManager.ReleaseResource ( g_guidMprApi , t_MprApi ) ;
}
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetCDROMDriveInfo
*
* DESCRIPTION : Retrieves property values for CD-ROM logical drive
*
* INPUTS : char* pszName - Name of Drive to get info for.
* BOOL fGetExpensiveProperties - Exp. Properties flag.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS :
*
*****************************************************************************/
void LogicalDisk :: GetCDROMDriveInfo (
CInstance *pInstance,
LPCTSTR pszName,
DWORD dwProperties
)
{
CHString sTemp2;
LoadStringW(sTemp2, IDR_CDRomDisk);
pInstance->SetCHString ( IDS_Description , sTemp2 ) ;
pInstance->SetDWORD ( IDS_MediaType , RemovableMedia ) ;
// Get Expensive properties now if appropriate.
BOOL t_MediaPresent = FALSE ;
#ifdef NTONLY
GetCDROMDriveInfoNT ( pInstance, pszName , t_MediaPresent, dwProperties );
#endif
DWORD dwResult = 0 ;
if ( t_MediaPresent &&
( dwProperties & LD_GET_VOL_INFO ) )
{
// Obtain volume information
dwResult = GetDriveVolumeInformation ( pInstance , pszName ) ;
}
if ( t_MediaPresent && dwResult == 0 )
{
if ( dwProperties &
(LD_Size_BIT |
LD_FreeSpace_BIT) )
{
GetDriveFreeSpace(pInstance, pszName );
}
}
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetCDROMDriveInfoNT
*
* DESCRIPTION : Retrieves property values for CDROM drive
*
* INPUTS : char* pszName - Name of Drive to get info for.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Performs operation using DeviceIoControl in NT
*
*****************************************************************************/
#ifdef NTONLY
void LogicalDisk :: GetCDROMDriveInfoNT (
CInstance *pInstance,
LPCTSTR pszName ,
BOOL &a_MediaPresent,
DWORD dwProperties
)
{
// we have this set globally at system startup time.
// SOMETHING is stepping on it on NT 3.51 *only* This suggests
// that a DLL we load is turning it off.
if ( IsWinNT351 () )
{
UINT oldErrorMode = SetErrorMode ( SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX ) ;
SetErrorMode ( oldErrorMode | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX ) ;
}
// Convert the drive letter to a number (the indeces are 1 based)
int nDrive = ( toupper(*pszName) - 'A' ) + 1;
// The following code was lifted from Knowledge Base Article
// Q163920. The code uses DeviceIoControl to discover the
// type of drive we are dealing with.
TCHAR szDriveName[8];
wsprintf(szDriveName, TEXT("\\\\.\\%c:"), TEXT('@') + nDrive);
SmartCloseHandle hVMWIN32 = CreateFile (
szDriveName,
FILE_ANY_ACCESS,
FILE_SHARE_WRITE | FILE_SHARE_READ,
0,
OPEN_EXISTING,
0,
0
);
if ( hVMWIN32 != INVALID_HANDLE_VALUE )
{
/*
* Verify media present
*/
if (dwProperties & LD_SPIN_DISK)
{
DWORD t_BytesReturned ;
a_MediaPresent = DeviceIoControl (
hVMWIN32,
IOCTL_STORAGE_CHECK_VERIFY2 ,
NULL,
0,
NULL,
0,
&t_BytesReturned,
0
) ;
if (!a_MediaPresent)
{
DWORD t_GetLastError = GetLastError () ;
if ( t_GetLastError != ERROR_NOT_READY )
{
LogErrorMessage2(L"Device IO control returned unexpected error for Check verify: (%d)", t_GetLastError);
}
}
}
else
{
a_MediaPresent = FALSE;
}
}
else
{
a_MediaPresent = GetLastError() == ERROR_ACCESS_DENIED;
}
}
#endif
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetCDROMDriveInfo95
*
* DESCRIPTION : Retrieves property values for CDROM drive
*
* INPUTS : char* pszName - Name of Drive to get info for.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Performs operation using DeviceIoControl in NT
*
*****************************************************************************/
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetRAMDriveInfo
*
* DESCRIPTION : Retrieves property values for RAM drives
*
* INPUTS : char* pszName - Name of Drive to get info for.
* BOOL fGetExpensiveProperties - Exp. Properties flag.
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS :
*
*****************************************************************************/
void LogicalDisk :: GetRAMDriveInfo (
CInstance *pInstance,
LPCTSTR pszName,
DWORD dwProperties
)
{
CHString sTemp2;
LoadStringW(sTemp2, IDR_RAMDisk);
pInstance->SetCHString ( IDS_Description , sTemp2 ) ;
pInstance->SetDWORD ( IDS_MediaType , Unknown ) ;
DWORD dwResult = 0 ;
// Get Expensive properties now if appropriate.
if ( dwProperties & LD_GET_VOL_INFO )
{
// Obtain volume information
dwResult = GetDriveVolumeInformation ( pInstance , pszName ) ;
}
if ( dwResult == 0 )
{
if ( dwProperties &
(LD_Size_BIT |
LD_FreeSpace_BIT) )
{
GetDriveFreeSpace ( pInstance , pszName ) ;
}
}
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetDriveVolumeInformation
*
* DESCRIPTION : Retrieves property values for fixed-media logical disk
*
* INPUTS : const char* pszName - Name of volume to retrieve
*
* OUTPUTS : none
*
* RETURNS : BOOL TRUE/FALSE - Able/Unable to perform
*
* COMMENTS :
*
*****************************************************************************/
DWORD LogicalDisk :: GetDriveVolumeInformation (
CInstance *pInstance,
LPCTSTR pszName
)
{
#ifdef NTONLY
// we have this set globally at system startup time.
// SOMETHING is stepping on it on NT 3.51 *only* This suggests
// that a DLL we load is turning it off.
if ( IsWinNT351 () )
{
UINT oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
SetErrorMode(oldErrorMode | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
}
#endif
DWORD dwReturn = 0 ;
TCHAR szVolumeName[_MAX_PATH] ;
TCHAR szFileSystem[_MAX_PATH] ;
DWORD dwSerialNumber ;
DWORD dwMaxComponentLength ;
DWORD dwFSFlags ;
BOOL fReturn = GetVolumeInformation (
pszName,
szVolumeName,
sizeof(szVolumeName)/sizeof(TCHAR),
&dwSerialNumber,
&dwMaxComponentLength,
&dwFSFlags,
szFileSystem,
sizeof(szFileSystem)/sizeof(TCHAR)
) ;
if ( fReturn )
{
// Win32 API will return volume information for all drive types.
pInstance->SetCharSplat ( IDS_VolumeName , szVolumeName ) ;
pInstance->SetCharSplat ( IDS_FileSystem , szFileSystem ) ;
// Per raid 50801
if (dwSerialNumber != 0)
{
TCHAR szTemp[_MAX_PATH] ;
_stprintf(szTemp, _T("%.8X"), dwSerialNumber) ;
pInstance->SetCharSplat ( IDS_VolumeSerialNumber , szTemp ) ;
}
pInstance->Setbool ( IDS_Compressed , dwFSFlags & FS_VOL_IS_COMPRESSED ) ;
pInstance->Setbool ( IDS_SupportsFileBasedCompression , dwFSFlags & FS_FILE_COMPRESSION ) ;
pInstance->SetDWORD ( IDS_MaximumComponentLength , dwMaxComponentLength ) ;
#if NTONLY == 5
pInstance->Setbool ( IDS_SupportsDiskQuotas, dwFSFlags & FILE_VOLUME_QUOTAS ) ;
IDiskQuotaControlPtr pIQuotaControl;
// Here Get the State of the volume, we need to get the Interface pointer.
if ( SUCCEEDED ( CoCreateInstance(
CLSID_DiskQuotaControl,
NULL,
CLSCTX_INPROC_SERVER,
IID_IDiskQuotaControl,
(void **)&pIQuotaControl ) ) )
{
CHString t_VolumeName;
HRESULT hRes = WBEM_S_NO_ERROR;
pInstance->GetCHString ( IDS_DeviceID, t_VolumeName );
WCHAR w_VolumePathName [ MAX_PATH + 1 ];
BOOL bRetVal = GetVolumePathName(
t_VolumeName.GetBuffer ( 0 ), // file path
w_VolumePathName, // volume mount point
MAX_PATH // Size of the Buffer
);
if ( bRetVal )
{
if ( SUCCEEDED ( pIQuotaControl->Initialize ( w_VolumePathName, TRUE ) ) )
{
DWORD dwQuotaState;
hRes = pIQuotaControl->GetQuotaState( &dwQuotaState );
if ( SUCCEEDED ( hRes ) )
{
pInstance->Setbool ( IDS_QuotasIncomplete, DISKQUOTA_FILE_INCOMPLETE ( dwQuotaState) ) ;
pInstance->Setbool ( IDS_QuotasRebuilding, DISKQUOTA_FILE_REBUILDING ( dwQuotaState) ) ;
pInstance->Setbool ( IDS_QuotasDisabled, DISKQUOTA_IS_DISABLED (dwQuotaState) );
}
else
{
dwReturn = GetLastError () ;
}
}
}
}
else
{
dwReturn = GetLastError () ;
}
#endif // NTONLY == 5
#ifdef NTONLY
// for chkdsk VolumeDirty Property
BOOLEAN bVolumeDirty = FALSE;
BOOL bSuccess = FALSE;
CHString t_DosDrive ( pszName );
UNICODE_STRING string = { 0 };
try
{
if(RtlDosPathNameToNtPathName_U ( t_DosDrive .GetBuffer( 0 ), &string, NULL, NULL ) &&
string.Buffer)
{
string.Buffer[string.Length/sizeof(WCHAR) - 1] = 0;
CHString nt_drive_name ( string.Buffer);
bSuccess = IsVolumeDirty ( nt_drive_name, &bVolumeDirty );
if ( bSuccess )
{
pInstance->Setbool ( IDS_VolumeDirty, bVolumeDirty);
}
RtlFreeUnicodeString(&string);
string.Buffer = NULL;
}
else
{
dwReturn = -1L;
}
}
catch(...)
{
if(string.Buffer)
{
RtlFreeUnicodeString(&string);
string.Buffer = NULL;
}
throw;
}
#endif
}
else
{
dwReturn = GetLastError () ;
}
return dwReturn ;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetDriveFreeSpace
*
* DESCRIPTION : Retrieves Space Information for the specified Drive.
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : BOOL TRUE/FALSE - Able/Unable to perform
*
* COMMENTS : Uses GetDiskFreeSpaceEx if available.
*
*****************************************************************************/
BOOL LogicalDisk :: GetDriveFreeSpace (
CInstance *pInstance,
LPCTSTR pszName
)
{
BOOL fReturn = FALSE ;
// See if GetDiskFreeSpaceEx() is supported
//=========================================
CKernel32Api *pKernel32 = (CKernel32Api*) CResourceManager::sm_TheResourceManager.GetResource(g_guidKernel32Api, NULL);
if ( pKernel32 != NULL )
{
try
{
BOOL fRetval = FALSE;
ULARGE_INTEGER uliTotalBytes ;
ULARGE_INTEGER uliUserFreeBytes ;
ULARGE_INTEGER uliTotalFreeBytes ;
if ( pKernel32->GetDiskFreeSpaceEx ( pszName, &uliUserFreeBytes, &uliTotalBytes, & uliTotalFreeBytes, & fRetval ) )
{
if ( fRetval )
{
fReturn = TRUE ;
pInstance->SetWBEMINT64(IDS_Size, uliTotalBytes.QuadPart);
pInstance->SetWBEMINT64(IDS_FreeSpace, uliTotalFreeBytes.QuadPart);
}
else
{
// If we couldn't get extended info -- use old API
// (known to be inaccurate on Win95 for >2G drives)
//=================================================
DWORD x = GetLastError();
DWORD dwBytesPerSector ;
DWORD dwSectorsPerCluster ;
DWORD dwFreeClusters ;
DWORD dwTotalClusters ;
BOOL t_Status = GetDiskFreeSpace (
pszName,
&dwSectorsPerCluster,
&dwBytesPerSector,
&dwFreeClusters,
&dwTotalClusters
) ;
if ( t_Status )
{
fReturn = TRUE ;
__int64 i64Temp = (__int64) dwTotalClusters *
(__int64) dwSectorsPerCluster *
(__int64) dwBytesPerSector ;
pInstance->SetWBEMINT64(IDS_Size, i64Temp);
i64Temp = (__int64) dwFreeClusters *
(__int64) dwSectorsPerCluster *
(__int64) dwBytesPerSector ;
pInstance->SetWBEMINT64( IDS_FreeSpace , i64Temp ) ;
}
else
{
DWORD x = GetLastError () ;
fReturn = FALSE ;
}
}
}
}
catch ( ... )
{
CResourceManager::sm_TheResourceManager.ReleaseResource(g_guidKernel32Api, pKernel32);
throw ;
}
CResourceManager::sm_TheResourceManager.ReleaseResource(g_guidKernel32Api, pKernel32);
}
return fReturn;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::PutInstance
*
* DESCRIPTION : Write changed instance
*
* INPUTS : pInstance to store data from
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS :
*
*****************************************************************************/
HRESULT LogicalDisk :: PutInstance (
const CInstance &pInstance,
long lFlags /*= 0L*/
)
{
// Tell the user we can't create a new logicaldisk (much as we might like to)
if ( lFlags & WBEM_FLAG_CREATE_ONLY )
{
return WBEM_E_UNSUPPORTED_PARAMETER ;
}
HRESULT hRet = WBEM_E_FAILED ;
// See if we got a name we can recognize
if ( ! pInstance.IsNull ( IDS_DeviceID ) )
{
CHString sName ;
pInstance.GetCHString ( IDS_DeviceID , sName ) ;
DWORD dwFind = sName.Find (':');
// Check for bad drive names
if ( ( dwFind == -1 ) || (dwFind != sName.GetLength () - 1 ) )
{
hRet = WBEM_E_INVALID_PARAMETER ;
}
else
{
sName = sName.Left(dwFind + 1);
sName += '\\';
DWORD dwDriveType = GetDriveType ( TOBSTRT(sName) ) ;
if ( ( dwDriveType == DRIVE_UNKNOWN ) || ( dwDriveType == DRIVE_NO_ROOT_DIR ) )
{
if ( lFlags & WBEM_FLAG_UPDATE_ONLY )
{
hRet = WBEM_E_NOT_FOUND ;
}
else
{
hRet = WBEM_E_UNSUPPORTED_PARAMETER;
}
}
else
{
hRet = WBEM_S_NO_ERROR;
if ( ! pInstance.IsNull ( IDS_VolumeName ) )
{
CHString sVolume ;
pInstance.GetCHString ( IDS_VolumeName , sVolume ) ;
{
if ( SetVolumeLabel ( TOBSTRT(sName), TOBSTRT(sVolume) ) )
{
hRet = WBEM_NO_ERROR ;
}
else
{
DWORD dwLastError = GetLastError();
if ( dwLastError == ERROR_ACCESS_DENIED )
{
hRet = WBEM_E_ACCESS_DENIED;
}
else
{
hRet = dwLastError | 0x80000000;
}
}
}
}
}
}
}
else
{
hRet = WBEM_E_ILLEGAL_NULL ;
}
return hRet;
}
#ifdef NTONLY
/*****************************************************************************
*
* FUNCTION : LogicalDisk::IsVolumeDirty
*
* DESCRIPTION : This routine opens the given nt drive and sends down
* FSCTL_IS_VOLUME_DIRTY to determine the state of that volume's
* dirty bit.
*
*****************************************************************************/
BOOLEAN LogicalDisk::IsVolumeDirty(
IN CHString &NtDriveName,
OUT BOOLEAN *Result
)
{
UNICODE_STRING u;
OBJECT_ATTRIBUTES obj;
NTSTATUS t_status;
IO_STATUS_BLOCK iosb;
HANDLE h = NULL;
ULONG r = 0;
BOOLEAN bRetVal = FALSE;
u.Length = (USHORT) NtDriveName.GetLength() * sizeof(WCHAR);
u.MaximumLength = u.Length;
u.Buffer = NtDriveName.GetBuffer( 0 );
InitializeObjectAttributes(&obj, &u, OBJ_CASE_INSENSITIVE, 0, 0);
t_status = NtOpenFile(&h,
FILE_WRITE_ATTRIBUTES | SYNCHRONIZE ,
&obj,
&iosb,
FILE_SHARE_READ|FILE_SHARE_WRITE,
FILE_SYNCHRONOUS_IO_ALERT);
if ( NT_SUCCESS(t_status))
{
try
{
t_status = NtFsControlFile(h, NULL, NULL, NULL,
&iosb,
FSCTL_IS_VOLUME_DIRTY,
NULL, 0,
&r, sizeof(r));
if ( NT_SUCCESS(t_status))
{
#if(_WIN32_WINNT >= 0x0500)
*Result = (BOOLEAN)(r & VOLUME_IS_DIRTY);
#else
*Result = (BOOLEAN)r;
#endif
bRetVal = TRUE;
}
}
catch(...)
{
NtClose(h);
h = NULL;
throw;
}
NtClose(h);
h = NULL;
}
return bRetVal;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::ExecChkDsk
*
* DESCRIPTION : This methods checks the disk, and if disk is locked
* Schedules it for autocheck on reboot, if requested by
* the user, by default it will not be scheduled for autocheck
* unless specified by the user.
*
*****************************************************************************/
HRESULT LogicalDisk :: ExecChkDsk (
const CInstance& a_Instance,
CInstance *a_InParams,
CInstance *a_OutParams,
long lFlags
)
{
HRESULT hRes = WBEM_S_NO_ERROR ;
DWORD dwThreadId = GetCurrentThreadId();
hRes = a_InParams && a_OutParams ? hRes : WBEM_E_INVALID_PARAMETER;
UINT unRetVal = 0;
mReturnVal [ dwThreadId ] = unRetVal;
if ( SUCCEEDED ( hRes ) )
{
// Get the drivename from the instance which is the key of the Logical DIsk
CHString t_DriveName;
hRes = a_Instance.GetCHString ( IDS_DeviceID, t_DriveName ) ? hRes : WBEM_E_PROVIDER_FAILURE;
if ( SUCCEEDED ( hRes ) )
{
// checking for the validity of the drive on whick checkdsk can be performed
DWORD dwDriveType = GetDriveType ( t_DriveName );
if ( unRetVal == 0 )
{
hRes = CheckParameters ( a_InParams );
if ( SUCCEEDED ( hRes ) )
{
// now check for the file system type, since chkdsk is applicable only for
// NTFS/FAT volumes by loading the fmifs.dll which exposes a chkdsk method
HINSTANCE hDLL = NULL;
QUERYFILESYSTEMNAME QueryFileSystemName = NULL;
FMIFS_CALLBACK CallBackRoutine = NULL;
hDLL = LoadLibrary( L"fmifs.dll" );
if (hDLL != NULL)
{
try
{
QueryFileSystemName = (QUERYFILESYSTEMNAME)GetProcAddress(hDLL, "QueryFileSystemName");
if ( QueryFileSystemName )
{
CHString t_FileSystemName;
unsigned char MajorVersion;
unsigned char MinorVersion;
LONG ExitStatus;
if ( QueryFileSystemName (
t_DriveName.GetBuffer ( 0 ),
t_FileSystemName.GetBuffer ( _MAX_PATH + 1 ),
&MajorVersion,
&MinorVersion,
&ExitStatus ) )
{
// we need to check for the Filesystem
if ( ( t_FileSystemName.CompareNoCase ( L"FAT" ) == 0 ) || ( t_FileSystemName.CompareNoCase ( L"FAT32" ) == 0 ) || ( t_FileSystemName.CompareNoCase ( L"NTFS" ) == 0) )
{
bool bFixErrors = false;
bool bVigorousIndexCheck = false;
bool bSkipFolderCycle = false;
bool bForceDismount = false;
bool bRecoverBadSectors = false;
bool bCheckAtBootUp = false;
// Get all the parameters from the instance here;
a_InParams->Getbool ( METHOD_ARG_NAME_FIXERRORS, bFixErrors );
a_InParams->Getbool ( METHOD_ARG_NAME_VIGOROUSINDEXCHECK, bVigorousIndexCheck );
a_InParams->Getbool ( METHOD_ARG_NAME_SKIPFOLDERCYCLE, bSkipFolderCycle );
a_InParams->Getbool ( METHOD_ARG_NAME_FORCEDISMOUNT, bForceDismount );
a_InParams->Getbool ( METHOD_ARG_NAME_RECOVERBADSECTORS, bRecoverBadSectors );
a_InParams->Getbool ( METHOD_ARG_NAME_CHKDSKATBOOTUP, bCheckAtBootUp );
// Set the parameters for making a call to chkdsk here
PFMIFS_CHKDSKEX_ROUTINE ChkDskExRoutine = NULL;
ChkDskExRoutine = ( PFMIFS_CHKDSKEX_ROUTINE ) GetProcAddress( hDLL, "ChkdskEx" );
if ( ChkDskExRoutine != NULL )
{
if ( bCheckAtBootUp )
{
CallBackRoutine = ScheduleAutoChkIfLocked;
}
else
{
CallBackRoutine = DontScheduleAutoChkIfLocked;
}
FMIFS_CHKDSKEX_PARAM Param;
Param.Major = 1;
Param.Minor = 0;
Param.Flags = 0; // For the Verbose Flag
Param.Flags |= bRecoverBadSectors ? FMIFS_CHKDSK_RECOVER : 0;
Param.Flags |= bForceDismount ? FMIFS_CHKDSK_FORCE : 0;
Param.Flags |= bVigorousIndexCheck ? FMIFS_CHKDSK_SKIP_INDEX_SCAN : 0;
Param.Flags |= bSkipFolderCycle ? FMIFS_CHKDSK_SKIP_CYCLE_SCAN : 0;
if (bRecoverBadSectors || bForceDismount)
{
bFixErrors = true;
}
ChkDskExRoutine (
t_DriveName.GetBuffer ( 0 ),
t_FileSystemName.GetBuffer ( 0 ),
bFixErrors,
&Param,
CallBackRoutine
);
}
else
{
hRes = WBEM_E_FAILED;
}
}
else
{
mReturnVal [ dwThreadId ] = CHKDSK_UNSUPPORTED_FS;
}
}
else
{
t_FileSystemName.ReleaseBuffer () ;
if ( ! t_FileSystemName.IsEmpty () )
{
mReturnVal [ dwThreadId ] = CHKDSK_UNSUPPORTED_FS;
}
else
{
mReturnVal [ dwThreadId ] = CHKDSK_UNKNOWN_FS;
}
}
}
}
catch ( ... )
{
FreeLibrary(hDLL);
throw;
}
FreeLibrary(hDLL);
}
else
{
hRes = WBEM_E_FAILED;
}
}
}
}
}
// need to set the return value;
if ( SUCCEEDED ( hRes ) )
{
a_OutParams->SetWORD ( METHOD_ARG_NAME_RETURNVALUE, mReturnVal [ dwThreadId ] ) ;
//Initialize/Delete the valuemap entry for this thread
mReturnVal [ dwThreadId ] = 0;
}
return hRes;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::ExecExcludeFromChkDsk
*
* DESCRIPTION : This method makes a chknts exe call to exclude the
* for autocheck on reboot
*
*****************************************************************************/
HRESULT LogicalDisk::ExecExcludeFromChkDsk(
CInstance *a_InParams,
CInstance *a_OutParams,
long lFlags
)
{
HRESULT hRes = WBEM_S_NO_ERROR;
CHString t_ChkNtFsCommand;
DWORD dwRetVal = 0;
// C for Schedule for autocheck on reboot
hRes = GetChkNtfsCommand ( a_InParams, a_OutParams, L'X', t_ChkNtFsCommand, dwRetVal );
// Making a call to execute an Chkntfs exe
if ( SUCCEEDED ( hRes ) && ( dwRetVal == CHKDSKERR_NOERROR ) )
{
hRes = ExecuteCommand ( t_ChkNtFsCommand );
if ( ( (HRESULT_FACILITY(hRes) == FACILITY_WIN32) ? HRESULT_CODE(hRes) : (hRes) ) == ERROR_ACCESS_DENIED )
{
hRes = WBEM_E_ACCESS_DENIED ;
}
}
a_OutParams->SetDWORD ( METHOD_ARG_NAME_RETURNVALUE , dwRetVal );
return hRes;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::ExecScheduleChkdsk
*
* DESCRIPTION : This method makes a chknts exe call to Schedule drives
* for autocheck on reboot
*
*****************************************************************************/
HRESULT LogicalDisk::ExecScheduleChkdsk(
CInstance *a_InParams,
CInstance *a_OutParams,
long lFlags
)
{
HRESULT hRes = WBEM_S_NO_ERROR;
CHString t_ChkNtFsCommand;
DWORD dwRetVal = NOERROR;
// C for Exclude for autocheck on reboot
hRes = GetChkNtfsCommand ( a_InParams, a_OutParams, L'C', t_ChkNtFsCommand, dwRetVal );
// Making a call to execute an Chkntfs exe
if ( SUCCEEDED ( hRes ) && ( dwRetVal == CHKDSKERR_NOERROR ) )
{
hRes = ExecuteCommand ( t_ChkNtFsCommand );
if ( ( (HRESULT_FACILITY(hRes) == FACILITY_WIN32) ? HRESULT_CODE(hRes) : (hRes) ) == ERROR_ACCESS_DENIED )
{
hRes = WBEM_E_ACCESS_DENIED ;
}
}
a_OutParams->SetWORD ( METHOD_ARG_NAME_RETURNVALUE , dwRetVal );
return hRes;
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::GetChkNtfsCommand
*
* DESCRIPTION : This method gets an array of input drives checks if chkntfs
* can be applied to them and puts it in the form of the ChkNtfs
* System command, based on the chk mode, either schedule or
* Exclude.
*
*****************************************************************************/
HRESULT LogicalDisk :: GetChkNtfsCommand (
CInstance *a_InParams,
CInstance *a_OutParams,
WCHAR w_Mode,
CHString &a_ChkNtfsCommand,
DWORD & dwRetVal
)
{
HRESULT hRes = WBEM_S_NO_ERROR;
SAFEARRAY *t_paDrives;
dwRetVal = CHKDSKERR_DRIVE_REMOVABLE;
a_ChkNtfsCommand.Format ( L"%s%s%c", CHKNTFS, L" /", w_Mode );
if ( a_InParams->GetStringArray ( METHOD_ARG_NAME_LOGICALDISKARRAY, t_paDrives ) == FALSE )
{
hRes = WBEM_E_INVALID_PARAMETER;
}
if ( SUCCEEDED ( hRes ) )
{
try
{
UINT unDim = SafeArrayGetDim( t_paDrives );
if ( unDim != 1 )
{
hRes = WBEM_E_INVALID_PARAMETER;
}
if ( SUCCEEDED ( hRes ) )
{
LONG lLbound;
LONG lUbound;
hRes = SafeArrayGetLBound( t_paDrives, unDim, &lLbound );
if ( SUCCEEDED ( hRes ) )
{
hRes = SafeArrayGetUBound( t_paDrives, unDim, &lUbound );
if ( SUCCEEDED ( hRes ) )
{
BSTR bstrElement;
for ( LONG lLbound = 0; lLbound <= lUbound; lLbound++ )
{
// getting the drives and putting them in command form
hRes = SafeArrayGetElement ( t_paDrives, &lLbound , &bstrElement );
if ( SUCCEEDED ( hRes ) )
{
DWORD dwElementLen = SysStringLen ( bstrElement );
if ( dwElementLen == 2 )
{
DWORD dwDriveType;
CHString t_Drive ( bstrElement );
dwDriveType = GetDriveType ( TOBSTRT ( t_Drive ) );
switch (dwDriveType)
{
case DRIVE_REMOTE:
{
dwRetVal = CHKDSKERR_REMOTE_DRIVE;
break;
}
case DRIVE_REMOVABLE:
{
dwRetVal = CHKDSKERR_DRIVE_REMOVABLE;
break;
}
case DRIVE_UNKNOWN:
{
dwRetVal = CHKDSKERR_DRIVE_UNKNOWN;
break;
}
case DRIVE_NO_ROOT_DIR:
{
dwRetVal = CHKDSKERR_DRIVE_NO_ROOT_DIR ;
break;
}
case DRIVE_FIXED:
{
dwRetVal = CHKDSKERR_NOERROR;
break;
}
default:
{
dwRetVal = CHKDSKERR_DRIVE_UNKNOWN;
break;
}
}
a_ChkNtfsCommand += L' ';
a_ChkNtfsCommand += t_Drive;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER;
break;
}
}
else
{
hRes = WBEM_E_INVALID_PARAMETER;
break;
}
}
}
else
{
hRes = WBEM_E_INVALID_PARAMETER;
}
}
else
{
hRes = WBEM_E_INVALID_PARAMETER;
}
}
}
catch ( ... )
{
hRes = SafeArrayDestroy ( t_paDrives );
throw;
}
if ( FAILED ( SafeArrayDestroy ( t_paDrives ) ) )
{
hRes = WBEM_E_FAILED;
}
}
return ( hRes );
}
/*****************************************************************************
*
* FUNCTION : LogicalDisk::CheckParameters
*
* DESCRIPTION : This routine checks for the validity of the parameters
* which are passed as parameters to ChkDsk Method
*
*****************************************************************************/
HRESULT LogicalDisk::CheckParameters (
CInstance *a_InParams
)
{
HRESULT hRes = WBEM_S_NO_ERROR ;
if ( a_InParams == NULL )
{
hRes = WBEM_E_INVALID_PARAMETER;
}
if ( SUCCEEDED ( hRes ) )
{
VARTYPE t_Type ;
bool t_Exists;
if ( a_InParams->GetStatus ( METHOD_ARG_NAME_FIXERRORS , t_Exists , t_Type ) )
{
hRes = t_Exists && ( t_Type == VT_BOOL ) ? hRes : WBEM_E_INVALID_PARAMETER;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
if ( SUCCEEDED ( hRes ) )
{
if ( a_InParams->GetStatus ( METHOD_ARG_NAME_VIGOROUSINDEXCHECK , t_Exists , t_Type ) )
{
hRes = t_Exists && ( t_Type == VT_BOOL ) ? hRes : WBEM_E_INVALID_PARAMETER;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
}
if ( SUCCEEDED ( hRes ) )
{
if ( a_InParams->GetStatus ( METHOD_ARG_NAME_SKIPFOLDERCYCLE , t_Exists , t_Type ) )
{
hRes = t_Exists && ( t_Type == VT_BOOL ) ? hRes : WBEM_E_INVALID_PARAMETER;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
}
if ( SUCCEEDED ( hRes ) )
{
if ( a_InParams->GetStatus ( METHOD_ARG_NAME_FORCEDISMOUNT , t_Exists , t_Type ) )
{
hRes = t_Exists && ( t_Type == VT_BOOL ) ? hRes : hRes = WBEM_E_INVALID_PARAMETER ;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
}
if ( SUCCEEDED ( hRes ) )
{
if ( a_InParams->GetStatus ( METHOD_ARG_NAME_RECOVERBADSECTORS , t_Exists , t_Type ) )
{
hRes = t_Exists && ( t_Type == VT_BOOL ) ? hRes : WBEM_E_INVALID_PARAMETER;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
}
if ( SUCCEEDED ( hRes ) )
{
if ( a_InParams->GetStatus ( METHOD_ARG_NAME_CHKDSKATBOOTUP , t_Exists , t_Type ) )
{
hRes = t_Exists && ( t_Type == VT_BOOL ) ? hRes : WBEM_E_INVALID_PARAMETER;
}
else
{
hRes = WBEM_E_INVALID_PARAMETER ;
}
}
}
return hRes;
}
/*****************************************************************************
*
* FUNCTION : DontScheduleAutoChkIfLocked
*
* DESCRIPTION : A callback routine, which is passed as a parameter to chkdsk method
* a method exposed via FMIFS.h chkdsk interface.
*
*****************************************************************************/
BOOLEAN DontScheduleAutoChkIfLocked(
FMIFS_PACKET_TYPE PacketType,
ULONG PacketLength,
PVOID PacketData
)
{
DWORD dwThreadId = GetCurrentThreadId();
if ( PacketType == FmIfsCheckOnReboot )
{
FMIFS_CHECKONREBOOT_INFORMATION *RebootResult;
mReturnVal [ dwThreadId ] = CHKDSK_VOLUME_LOCKED;
RebootResult = ( FMIFS_CHECKONREBOOT_INFORMATION * ) PacketData;
RebootResult->QueryResult = 0;
}
else
{
ProcessInformation ( PacketType, PacketLength, PacketData );
}
return TRUE;
}
/*****************************************************************************
*
* FUNCTION : ScheduleAutoChkIfLocked
*
* DESCRIPTION : A callback routine, which is passed as a parameter to chkdsk method
* a method exposed via FMIFS.h chkdsk interface.
*
*****************************************************************************/
BOOLEAN ScheduleAutoChkIfLocked(
FMIFS_PACKET_TYPE PacketType,
ULONG PacketLength,
PVOID PacketData
)
{
DWORD dwThreadId = GetCurrentThreadId();
if ( PacketType == FmIfsCheckOnReboot )
{
FMIFS_CHECKONREBOOT_INFORMATION *RebootResult;
mReturnVal [ dwThreadId ] = CHKDSK_VOLUME_LOCKED;
RebootResult = ( FMIFS_CHECKONREBOOT_INFORMATION * ) PacketData;
RebootResult->QueryResult = 1;
}
else
{
ProcessInformation ( PacketType, PacketLength, PacketData );
}
return TRUE;
}
/*****************************************************************************
*
* FUNCTION : ProcessInofrmation
*
* DESCRIPTION : Checks the the dsk and keeps track of the appropriate error
* messages.
*
*****************************************************************************/
BOOLEAN ProcessInformation (
FMIFS_PACKET_TYPE PacketType,
ULONG PacketLength,
PVOID PacketData
)
{
int static unRetVal;
DWORD dwThreadId = GetCurrentThreadId();
switch ( PacketType )
{
case FmIfsTextMessage :
FMIFS_TEXT_MESSAGE *MessageText;
MessageText = ( FMIFS_TEXT_MESSAGE *) PacketData;
// There is no way to access this message ids via a interface exposed hence cannot detect these errors.
/* if ( lstrcmp ( MessageText, MSGCHK_ERRORS_NOT_FIXED ) == 0 )
{
unRetVal = 2;
}
if ( lstrcmp ( MessageText, MSG_CHK_ERRORS_FIXED ) == 0 )
{
unRetVal = 3;
}
*/
break;
case FmIfsFinished:
FMIFS_FINISHED_INFORMATION *Finish;
Finish = ( FMIFS_FINISHED_INFORMATION *) PacketData;
if ( Finish->Success )
{
mReturnVal [ dwThreadId ] = CHKDSKERR_NOERROR;
}
else
{
if (mReturnVal [ dwThreadId ] != CHKDSK_VOLUME_LOCKED)
{
mReturnVal [ dwThreadId ] = CHKDSK_FAILED;
}
}
break;
// although follwoing are the additional message types, callback routine never gets these messages
// hence the detailed code for each of these return type is not written.
/*
case FmIfsIncompatibleFileSystem:
break;
case FmIfsAccessDenied:
break;
case FmIfsBadLabel:
break;
case FmIfsHiddenStatus:
break;
case FmIfsClusterSizeTooSmall:
break;
case FmIfsClusterSizeTooBig:
break;
case FmIfsVolumeTooSmall:
break;
case FmIfsVolumeTooBig:
break;
case FmIfsNoMediaInDevice:
break;
case FmIfsClustersCountBeyond32bits:
break;
case FmIfsIoError:
FMIFS_IO_ERROR_INFORMATION *IoErrorInfo;
IoErrorInfo = ( FMIFS_IO_ERROR_INFORMATION * ) PacketData;
break;
case FmIfsMediaWriteProtected:
break;
case FmIfsIncompatibleMedia:
break;
case FmIfsInsertDisk:
FMIFS_INSERT_DISK_INFORMATION *InsertDiskInfo;
InsertDiskInfo = ( FMIFS_INSERT_DISK_INFORMATION *) PacketData;
unRetVal = 1;
break;
*/
}
return TRUE;
}
HRESULT LogicalDisk::ExecuteCommand ( LPCWSTR wszCommand )
{
HRESULT hRes = WBEM_E_FAILED;
DWORD t_Status = ERROR_SUCCESS ;
SmartCloseHandle t_TokenPrimaryHandle ;
SmartCloseHandle t_TokenImpersonationHandle;
BOOL t_TokenStatus = OpenThreadToken (
GetCurrentThread () ,
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY ,
TRUE ,
& t_TokenImpersonationHandle
) ;
if ( t_TokenStatus )
{
CAdvApi32Api *t_pAdvApi32 = NULL;
if ( ( t_pAdvApi32 = (CAdvApi32Api*) CResourceManager::sm_TheResourceManager.GetResource(g_guidAdvApi32Api, NULL) ) != NULL )
{
t_pAdvApi32->DuplicateTokenEx ( t_TokenImpersonationHandle ,
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY ,
NULL,
SecurityImpersonation,
TokenPrimary ,
&t_TokenPrimaryHandle,
&t_TokenStatus
);
CResourceManager::sm_TheResourceManager.ReleaseResource(g_guidAdvApi32Api, t_pAdvApi32);
t_pAdvApi32 = NULL;
}
else
{
t_TokenStatus = 0;
}
}
if ( t_TokenStatus )
{
CUserHive t_Hive ;
CHString chsSID ;
CHString t_Account ;
DWORD dwCheckKeyPresentStatus = ERROR_SUCCESS ;
TCHAR t_KeyName [ 1024 ] = { L'\0' } ;
TOKEN_INFORMATION_CLASS t_TokenInformationClass = TokenUser ;
TOKEN_USER *t_TokenUser = NULL ;
DWORD t_ReturnLength = 0L;
t_TokenStatus = GetTokenInformation (
t_TokenImpersonationHandle ,
t_TokenInformationClass ,
NULL ,
0 ,
& t_ReturnLength
) ;
if ( ! t_TokenStatus && GetLastError () == ERROR_INSUFFICIENT_BUFFER )
{
if ( ( t_TokenUser = ( TOKEN_USER * ) new UCHAR [ t_ReturnLength ] ) != NULL )
{
try
{
t_TokenStatus = GetTokenInformation (
t_TokenImpersonationHandle ,
t_TokenInformationClass ,
( void * ) t_TokenUser ,
t_ReturnLength ,
& t_ReturnLength
) ;
if ( t_TokenStatus )
{
CSid t_Sid ( t_TokenUser->User.Sid ) ;
if ( t_Sid.IsOK () )
{
chsSID = t_Sid.GetSidString () ;
t_Account = t_Sid.GetAccountName () ;
}
else
{
t_Status = GetLastError () ;
}
}
else
{
t_Status = GetLastError () ;
}
}
catch ( ... )
{
if ( t_TokenUser )
{
delete [] ( UCHAR * ) t_TokenUser ;
t_TokenUser = NULL ;
}
throw ;
}
if ( t_TokenUser )
{
delete [] ( UCHAR * ) t_TokenUser ;
t_TokenUser = NULL ;
}
}
else
{
t_Status = ERROR_NOT_ENOUGH_MEMORY;
}
}
else
{
t_Status = ::GetLastError ();
}
if ( t_Status == ERROR_SUCCESS )
{
CRegistry Reg ;
//check if SID already present under HKEY_USER ...
dwCheckKeyPresentStatus = Reg.Open(HKEY_USERS, chsSID, KEY_READ) ;
Reg.Close() ;
if(dwCheckKeyPresentStatus != ERROR_SUCCESS)
{
t_Status = t_Hive.Load ( t_Account , t_KeyName, 1024 ) ;
}
if ( t_Status == ERROR_FILE_NOT_FOUND )
{
t_Status = ERROR_SUCCESS ;
dwCheckKeyPresentStatus = ERROR_SUCCESS ;
}
}
if ( t_Status == ERROR_SUCCESS )
{
try
{
DWORD t_CreationFlags = 0 ;
STARTUPINFO t_StartupInformation ;
ZeroMemory ( &t_StartupInformation , sizeof ( t_StartupInformation ) ) ;
t_StartupInformation.cb = sizeof ( STARTUPINFO ) ;
t_StartupInformation.dwFlags = STARTF_USESHOWWINDOW;
t_StartupInformation.wShowWindow = SW_HIDE;
t_CreationFlags = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT ;
PROCESS_INFORMATION t_ProcessInformation;
CUserEnvApi *pUserEnv = NULL ;
LPVOID t_Environment = NULL ;
if ( ( pUserEnv = ( CUserEnvApi * ) CResourceManager::sm_TheResourceManager.GetResource ( g_guidUserEnvApi, NULL ) ) != NULL )
{
try
{
pUserEnv->CreateEnvironmentBlock (
& t_Environment ,
t_TokenPrimaryHandle ,
FALSE
);
t_Status = CreateProcessAsUser (
t_TokenPrimaryHandle ,
NULL ,
( LPTSTR ) wszCommand,
NULL ,
NULL ,
FALSE ,
t_CreationFlags ,
( TCHAR * ) t_Environment ,
NULL ,
& t_StartupInformation ,
& t_ProcessInformation
) ;
if ( t_Environment )
{
pUserEnv->DestroyEnvironmentBlock ( t_Environment ) ;
t_Environment = NULL;
}
}
catch ( ... )
{
CResourceManager::sm_TheResourceManager.ReleaseResource ( g_guidUserEnvApi, pUserEnv ) ;
pUserEnv = NULL ;
throw;
}
CResourceManager::sm_TheResourceManager.ReleaseResource ( g_guidUserEnvApi, pUserEnv ) ;
pUserEnv = NULL ;
if ( t_Status )
{
t_Status = ERROR_SUCCESS;
if ( ::WaitForSingleObject ( t_ProcessInformation.hProcess, INFINITE ) == WAIT_OBJECT_0 )
{
DWORD t_ExitCode = 0L;
if ( GetExitCodeProcess ( t_ProcessInformation.hProcess, &t_ExitCode ) )
{
if ( t_ExitCode == 2 )
{
// from chkntfs file
//
// EXIT:
// 0 -- OK, dirty bit not set on drive or bit not checked
// 1 -- OK, and dirty bit set on at least one drive
// 2 -- Error
hRes = WBEM_E_FAILED;
}
else
{
hRes = WBEM_S_NO_ERROR;
}
}
::CloseHandle ( t_ProcessInformation.hProcess ) ;
}
}
else
{
t_Status = ::GetLastError ();
}
}
}
catch ( ... )
{
if(dwCheckKeyPresentStatus != ERROR_SUCCESS)
{
t_Hive.Unload ( t_KeyName ) ;
}
throw;
}
if(dwCheckKeyPresentStatus != ERROR_SUCCESS)
{
t_Hive.Unload ( t_KeyName ) ;
}
}
}
if ( t_Status == ERROR_ACCESS_DENIED )
{
hRes = HRESULT_FROM_WIN32 ( t_Status );
}
return hRes;
}
#endif | 26.309579 | 178 | 0.54363 | [
"vector"
] |
3263ebab0410104eaf7cab5bd4209acafbc73dcc | 13,086 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/fp16/arithmetic_fp16.cc | Joejiong/mindspore | 083fd6565cab1aa1d3114feeacccf1cba0d55e80 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/fp16/arithmetic_fp16.cc | Joejiong/mindspore | 083fd6565cab1aa1d3114feeacccf1cba0d55e80 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/fp16/arithmetic_fp16.cc | Joejiong/mindspore | 083fd6565cab1aa1d3114feeacccf1cba0d55e80 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 "src/runtime/kernel/arm/fp16/arithmetic_fp16.h"
#include "src/runtime/kernel/arm/nnacl/fp16/arithmetic_fp16.h"
#include "src/runtime/kernel/arm/nnacl/fp16/cast_fp16.h"
#include "schema/model_generated.h"
#include "src/kernel_registry.h"
#include "src/runtime/runtime_api.h"
#include "include/errorcode.h"
using mindspore::kernel::KERNEL_ARCH::kCPU;
using mindspore::lite::KernelRegistrar;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
using mindspore::schema::PrimitiveType_Add;
using mindspore::schema::PrimitiveType_Div;
using mindspore::schema::PrimitiveType_Equal;
using mindspore::schema::PrimitiveType_FloorDiv;
using mindspore::schema::PrimitiveType_FloorMod;
using mindspore::schema::PrimitiveType_Greater;
using mindspore::schema::PrimitiveType_GreaterEqual;
using mindspore::schema::PrimitiveType_Less;
using mindspore::schema::PrimitiveType_LessEqual;
using mindspore::schema::PrimitiveType_LogicalAnd;
using mindspore::schema::PrimitiveType_LogicalOr;
using mindspore::schema::PrimitiveType_Maximum;
using mindspore::schema::PrimitiveType_Minimum;
using mindspore::schema::PrimitiveType_Mul;
using mindspore::schema::PrimitiveType_NotEqual;
using mindspore::schema::PrimitiveType_SquaredDifference;
using mindspore::schema::PrimitiveType_Sub;
namespace mindspore::kernel {
void ArithmeticFP16CPUKernel::FreeTmpBuffer() {
if (tile_data0_ != nullptr) {
free(tile_data0_);
tile_data0_ = nullptr;
}
if (tile_data1_ != nullptr) {
free(tile_data1_);
tile_data1_ = nullptr;
}
if (input0_fp16_ != nullptr) {
context_->allocator->Free(input0_fp16_);
input0_fp16_ = nullptr;
}
if (input1_fp16_ != nullptr) {
context_->allocator->Free(input1_fp16_);
input1_fp16_ = nullptr;
}
if (output_fp16_ != nullptr) {
context_->allocator->Free(output_fp16_);
output_fp16_ = nullptr;
}
}
ArithmeticFP16CPUKernel::~ArithmeticFP16CPUKernel() { FreeTmpBuffer(); }
int ArithmeticFP16CPUKernel::Init() {
switch (op_parameter_->type_) {
case PrimitiveType_Mul:
switch (arithmeticParameter_->activation_type_) {
case schema::ActivationType_RELU:
arithmetic_run_ = ElementMulReluFp16;
break;
case schema::ActivationType_RELU6:
arithmetic_run_ = ElementMulRelu6Fp16;
break;
default:
arithmetic_run_ = ElementMulFp16;
break;
}
break;
case PrimitiveType_Add:
switch (arithmeticParameter_->activation_type_) {
case schema::ActivationType_RELU:
arithmetic_run_ = ElementAddReluFp16;
break;
case schema::ActivationType_RELU6:
arithmetic_run_ = ElementAddRelu6Fp16;
break;
default:
arithmetic_run_ = ElementAddFp16;
break;
}
break;
case PrimitiveType_Sub:
switch (arithmeticParameter_->activation_type_) {
case schema::ActivationType_RELU:
arithmetic_run_ = ElementSubReluFp16;
break;
case schema::ActivationType_RELU6:
arithmetic_run_ = ElementSubRelu6Fp16;
break;
default:
arithmetic_run_ = ElementSubFp16;
break;
}
case PrimitiveType_Div:
switch (arithmeticParameter_->activation_type_) {
case schema::ActivationType_RELU:
arithmetic_run_ = ElementDivReluFp16;
break;
case schema::ActivationType_RELU6:
arithmetic_run_ = ElementDivRelu6Fp16;
break;
default:
arithmetic_run_ = ElementDivFp16;
break;
}
case PrimitiveType_FloorMod:
arithmetic_run_ = ElementFloorModFp16;
case PrimitiveType_FloorDiv:
arithmetic_run_ = ElementFloorDivFp16;
case PrimitiveType_LogicalAnd:
arithmetic_run_ = ElementLogicalAndFp16;
case PrimitiveType_LogicalOr:
arithmetic_run_ = ElementLogicalOrFp16;
case PrimitiveType_SquaredDifference:
arithmetic_run_ = ElementSquaredDifferenceFp16;
case PrimitiveType_Maximum:
arithmetic_run_ = ElementMaximumFp16;
case PrimitiveType_Minimum:
arithmetic_run_ = ElementMinimumFp16;
case PrimitiveType_NotEqual:
arithmetic_run_ = ElementNotEqualFp16;
case PrimitiveType_Equal:
arithmetic_run_ = ElementEqualFp16;
case PrimitiveType_Less:
arithmetic_run_ = ElementLessFp16;
case PrimitiveType_LessEqual:
arithmetic_run_ = ElementLessEqual;
case PrimitiveType_Greater:
arithmetic_run_ = ElementGreaterFp16;
case PrimitiveType_GreaterEqual:
arithmetic_run_ = ElementGreaterEqualFp16;
default:
MS_LOG(ERROR) << "Error Operator type " << op_parameter_->type_;
arithmetic_run_ = nullptr;
break;
}
if (!InferShapeDone()) {
return RET_OK;
}
return ReSize();
}
int ArithmeticFP16CPUKernel::ReSize() {
FreeTmpBuffer();
arithmeticParameter_->in_elements_num0_ = in_tensors_[0]->ElementsNum();
arithmeticParameter_->in_elements_num1_ = in_tensors_[1]->ElementsNum();
arithmeticParameter_->out_elements_num_ = out_tensors_[0]->ElementsNum();
if (in_tensors_[0]->data_type() == kNumberTypeFloat32 || in_tensors_[0]->data_type() == kNumberTypeFloat) {
input0_fp16_ = reinterpret_cast<float16_t *>(
context_->allocator->Malloc(arithmeticParameter_->in_elements_num0_ * sizeof(float16_t)));
if (input0_fp16_ == nullptr) {
MS_LOG(ERROR) << "malloc data fail!";
return RET_ERROR;
}
Float32ToFloat16(reinterpret_cast<float *>(in_tensors_[0]->Data()), input0_fp16_,
arithmeticParameter_->in_elements_num0_);
}
if (in_tensors_[1]->data_type() == kNumberTypeFloat32 || in_tensors_[1]->data_type() == kNumberTypeFloat) {
input1_fp16_ = reinterpret_cast<float16_t *>(
context_->allocator->Malloc(arithmeticParameter_->in_elements_num1_ * sizeof(float16_t)));
if (input0_fp16_ == nullptr) {
MS_LOG(ERROR) << "malloc data fail!";
return RET_ERROR;
}
Float32ToFloat16(reinterpret_cast<float *>(in_tensors_[1]->Data()), input1_fp16_,
arithmeticParameter_->in_elements_num1_);
}
if (out_tensors_[0]->data_type() == kNumberTypeFloat32 || out_tensors_[0]->data_type() == kNumberTypeFloat) {
output_fp16_ = reinterpret_cast<float16_t *>(
context_->allocator->Malloc(arithmeticParameter_->out_elements_num_ * sizeof(float16_t)));
if (output_fp16_ == nullptr) {
MS_LOG(ERROR) << "malloc data fail!";
return RET_ERROR;
}
}
if (arithmeticParameter_->in_elements_num0_ == 1 || arithmeticParameter_->in_elements_num1_ == 1) {
if (arithmeticParameter_->activation_type_ == schema::ActivationType_NO_ACTIVATION) {
switch (arithmeticParameter_->op_parameter_.type_) {
case PrimitiveType_Mul:
arithmeticParameter_->broadcasting_ = false;
arithmetic_opt_run_ = ElementOptMulFp16;
break;
case PrimitiveType_Add:
arithmeticParameter_->broadcasting_ = false;
arithmetic_opt_run_ = ElementOptAddFp16;
break;
case PrimitiveType_Sub:
arithmeticParameter_->broadcasting_ = false;
arithmetic_opt_run_ = ElementOptSubFp16;
break;
default:
break;
}
}
}
if (arithmeticParameter_->broadcasting_) {
auto tile_size = arithmeticParameter_->out_elements_num_ * sizeof(float16_t);
tile_data0_ = reinterpret_cast<float16_t *>(malloc(tile_size));
tile_data1_ = reinterpret_cast<float16_t *>(malloc(tile_size));
if (tile_data0_ == nullptr || tile_data1_ == nullptr) {
MS_LOG(ERROR) << "malloc tile data fail!";
return RET_ERROR;
}
}
return RET_OK;
}
int ArithmeticFP16CPUKernel::DoArithmetic(int task_id) {
auto input0 = reinterpret_cast<float16_t *>(in_tensors_[0]->Data());
auto input1 = reinterpret_cast<float16_t *>(in_tensors_[1]->Data());
auto output = reinterpret_cast<float16_t *>(out_tensors_[0]->Data());
auto element_num = out_tensors_[0]->ElementsNum();
float16_t *input0_data = input0_fp16_ == nullptr ? input0 : input0_fp16_;
float16_t *input1_data1 = input1_fp16_ == nullptr ? input1 : input1_fp16_;
auto output_data = output_fp16_ == nullptr ? output : output_fp16_;
int stride = UP_DIV(element_num, context_->thread_num_);
int count = MSMIN(stride, element_num - stride * task_id);
auto thread_stride = stride * task_id;
if (arithmetic_run_ == nullptr) {
MS_LOG(ERROR) << "arithmetic_run function is nullptr!";
return RET_ERROR;
}
int error_code = RET_OK;
if (arithmeticParameter_->broadcasting_) {
error_code =
arithmetic_run_(tile_data0_ + thread_stride, tile_data1_ + thread_stride, output_data + thread_stride, count);
} else if (arithmetic_opt_run_ != nullptr) {
if (arithmeticParameter_->in_elements_num0_ == 1) {
error_code = arithmetic_opt_run_(input0_data, input1_data1 + thread_stride, output_data + thread_stride, count,
arithmeticParameter_);
} else if (arithmeticParameter_->in_elements_num1_ == 1) {
error_code = arithmetic_opt_run_(input0_data + thread_stride, input1_data1, output_data + thread_stride, count,
arithmeticParameter_);
} else {
error_code = arithmetic_opt_run_(input0_data + thread_stride, input1_data1 + thread_stride,
output_data + thread_stride, count, arithmeticParameter_);
}
} else {
error_code =
arithmetic_run_(input0_data + thread_stride, input1_data1 + thread_stride, output_data + thread_stride, count);
}
if (error_code != RET_OK) {
return RET_ERROR;
}
if (output_fp16_ != nullptr) {
auto output_fp32 = reinterpret_cast<float *>(out_tensors_[0]->Data());
Float16ToFloat32(output_data + thread_stride, output_fp32 + thread_stride, count);
}
return RET_OK;
}
int ArithmeticsRun(int task_id, LiteParallelGroupEnv *penv, void *cdata) {
auto arithmetic_kernel = reinterpret_cast<ArithmeticFP16CPUKernel *>(cdata);
auto error_code = arithmetic_kernel->DoArithmetic(task_id);
if (error_code != RET_OK) {
MS_LOG(ERROR) << "ArithmeticsRun error task_id[" << task_id << "] error_code[" << error_code << "]";
return RET_ERROR;
}
return RET_OK;
}
int ArithmeticFP16CPUKernel::Run() {
auto ret = Prepare();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Prepare fail!ret: " << ret;
return ret;
}
if (arithmeticParameter_->broadcasting_) {
auto input_data0 = reinterpret_cast<float16_t *>(in_tensors_[0]->Data());
auto input_data1 = reinterpret_cast<float16_t *>(in_tensors_[1]->Data());
float16_t *input0 = input0_fp16_ == nullptr ? input_data0 : input0_fp16_;
float16_t *input1 = input1_fp16_ == nullptr ? input_data1 : input1_fp16_;
TileDimensionsFp16(input0, input1, tile_data0_, tile_data1_, arithmeticParameter_);
}
ret = LiteBackendParallelLaunch(ArithmeticsRun, this, context_->thread_num_);
if (ret != RET_OK) {
MS_LOG(ERROR) << "Arithmetic function fail!ret: " << ret;
return ret;
}
return RET_OK;
}
kernel::LiteKernel *CpuArithmeticFp16KernelCreator(const std::vector<lite::tensor::Tensor *> &inputs,
const std::vector<lite::tensor::Tensor *> &outputs,
OpParameter *parameter, const lite::Context *ctx,
const kernel::KernelKey &desc, const lite::Primitive *primitive) {
if (parameter == nullptr) {
MS_LOG(ERROR) << "input parameter is null!";
return nullptr;
}
auto kernel = new (std::nothrow) ArithmeticFP16CPUKernel(parameter, inputs, outputs, ctx, primitive);
if (kernel == nullptr) {
MS_LOG(ERROR) << "Create kernel failed, name: " << parameter->name_;
return nullptr;
}
auto ret = kernel->Init();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Init kernel failed, name: " << parameter->name_
<< ", type: " << schema::EnumNamePrimitiveType(static_cast<schema::PrimitiveType>(parameter->type_));
delete kernel;
return nullptr;
}
return kernel;
}
REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_Mul, CpuArithmeticFp16KernelCreator)
REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_Add, CpuArithmeticFp16KernelCreator)
REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_Sub, CpuArithmeticFp16KernelCreator)
} // namespace mindspore::kernel
| 38.830861 | 119 | 0.698456 | [
"vector"
] |
327676d545b3ae183501aba1a16d1f4e25807688 | 4,881 | cpp | C++ | lessons/Lesson3/TestPassParameters.cpp | maychan111/cpp-tdd | ed34561b5c9763e280fd871c1dcfc749f1ad1d7d | [
"MIT"
] | 2 | 2019-04-23T23:27:07.000Z | 2022-03-27T14:43:14.000Z | lessons/Lesson3/TestPassParameters.cpp | maychan111/cpp-tdd | ed34561b5c9763e280fd871c1dcfc749f1ad1d7d | [
"MIT"
] | null | null | null | lessons/Lesson3/TestPassParameters.cpp | maychan111/cpp-tdd | ed34561b5c9763e280fd871c1dcfc749f1ad1d7d | [
"MIT"
] | null | null | null | #include "Person.h"
#include "../gtest/gmock.h"
#include "../gtest/MainTest.h"
#include <memory>
#include <list>
namespace
{
using namespace testing;
/*
Smart Pointer Parameters: How should you prefer to pass smart pointers, and why?
http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/
*/
class Widget
{
public:
Widget(int id) : _id(id)
{
GTEST_PRINTF("[%d] constructor\n", getId());
}
~Widget()
{
GTEST_PRINTF("[%d] destructor\n", getId());
}
int getId() const { return _id; }
void modifyFoo() { _foo++; }
private:
int _id = 0;
int _foo = 0;
};
struct Parameter : public testing::Test
{
Parameter() { GTEST_PRINTF("Parameter constructor\n"); }
~Parameter() { GTEST_PRINTF("Parameter destructor\n"); }
};
TEST_F(Parameter, IsRawPointer)
{
// pass by raw pointer if:
// 1. callee does not participate in lifetime strategy
// 2. the parameter may be optional (nullptr)
// Pro: callee does not need to know how the pointer is managed
// caller does not need to commit to a lifetime strategy
auto call = [](Widget *w)
{
if (w)
w->modifyFoo();
};
auto w = Widget{ 1 };
call(&w);
auto uw = std::make_unique<Widget>(2);
call(uw.get());
auto sw = std::shared_ptr<Widget>(std::move(uw));
call(sw.get());
}
TEST_F(Parameter, IsReference)
{
// pass by raw pointer if:
// 1. callee does not participate in lifetime strategy
// 2. the parameter is not optional
// 3. the callee may change the object
auto call = [](Widget& w) { w.modifyFoo(); };
auto w = Widget{ 1 };
call(w);
auto uw = std::make_unique<Widget>(2);
call(*uw.get());
auto sw = std::shared_ptr<Widget>(std::move(uw));
call(*sw.get());
}
TEST_F(Parameter, IsConstReference)
{
// pass by raw pointer if:
// 1. callee does not participate in lifetime strategy
// 2. the parameter is not optional
// 3. the callee with not change the object
auto call = [](const Widget& w) { return w.getId(); };
const auto w = Widget{ 1 };
call(w);
auto uw = std::make_unique<Widget>(2);
call(*uw.get());
auto sw = std::shared_ptr<Widget>(std::move(uw));
call(*sw.get());
}
TEST_F(Parameter, IsUniquePtrByValue)
{
// pass by unique_ptr by value to indicate callee should take ownership
std::unique_ptr<Widget> result;
EXPECT_THAT(result.get(), IsNull());
auto call = [&](std::unique_ptr<Widget> w)
{
result = std::move(w);
};
auto uw = std::make_unique<Widget>(1);
call(std::move(uw));
EXPECT_THAT(result.get(), NotNull());
}
TEST_F(Parameter, IsUniquePtrByReference)
{
// Use a non-const unique_ptr& parameter only to modify the unique_ptr
auto call = [](std::unique_ptr<Widget>& w)
{
w.reset(new Widget(2)); // w is modified
};
auto w = std::make_unique<Widget>(1);
call(w);
EXPECT_THAT(w.get(), NotNull());
// no reason to have a const unique_ptr reference because lifetime is already managed by caller, so just pass * or &
}
TEST_F(Parameter, IsSharedPtrByValue)
{
// pass by shared_ptr by value means callee should take shared ownership
std::shared_ptr<Widget> result;
EXPECT_THAT(result.get(), IsNull());
auto call = [&result](std::shared_ptr<Widget> w)
{
result = std::move(w);
};
auto w = std::make_shared<Widget>(1);
call(w);
EXPECT_THAT(w.get(), NotNull());
EXPECT_THAT(result.get(), NotNull());
}
TEST_F(Parameter, IsSharedPtrByReference)
{
// pass by shared_ptr by reference for in/out shared_ptr manipulation
auto call = [](std::shared_ptr<Widget>& w)
{
w.reset();
};
auto w = std::make_shared<Widget>(1);
call(w);
EXPECT_THAT(w.get(), IsNull());
}
TEST_F(Parameter, IsSharedPtrByConstReference)
{
// pass by shared_ptr by reference if you are not sure if callee might share ownership
std::shared_ptr<Widget> result;
auto call = [&result](const std::shared_ptr<Widget>& w)
{
if (w)
result = w;
};
auto w = std::make_shared<Widget>(1);
call(nullptr);
EXPECT_THAT(result.get(), IsNull());
call(w);
EXPECT_THAT(result.get(), NotNull());
}
} | 25.554974 | 124 | 0.54538 | [
"object"
] |
32777337f866e76dcf7d9c48a761fef404811e69 | 5,905 | cpp | C++ | Source/ToolCore/Assets/PrefabImporter.cpp | joaovsq/Cross | 8431eb3fd9ba1cef37ac1f3226a6caa6177b5560 | [
"Apache-2.0"
] | null | null | null | Source/ToolCore/Assets/PrefabImporter.cpp | joaovsq/Cross | 8431eb3fd9ba1cef37ac1f3226a6caa6177b5560 | [
"Apache-2.0"
] | null | null | null | Source/ToolCore/Assets/PrefabImporter.cpp | joaovsq/Cross | 8431eb3fd9ba1cef37ac1f3226a6caa6177b5560 | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Cross/Resource/ResourceCache.h>
#include <Cross/Resource/XMLFile.h>
#include <Cross/Scene/Scene.h>
#include <Cross/Scene/PrefabEvents.h>
#include <Cross/Scene/PrefabComponent.h>
#include <Cross/IO/FileSystem.h>
#include "Asset.h"
#include "AssetDatabase.h"
#include "PrefabImporter.h"
namespace ToolCore
{
PrefabImporter::PrefabImporter(Context* context, Asset* asset) : AssetImporter(context, asset),
lastFileStamp_(0xFFFFFFFF)
{
requiresCacheFile_ = true;
SubscribeToEvent(E_PREFABSAVE, CROSS_HANDLER(PrefabImporter, HandlePrefabSave));
}
PrefabImporter::~PrefabImporter()
{
}
void PrefabImporter::SetDefaults()
{
AssetImporter::SetDefaults();
}
bool PrefabImporter::Preload()
{
if (!asset_)
return false;
preloadResourceScene_ = new Scene(context_);
SharedPtr<File> file(new File(context_, asset_->GetCachePath()));
preloadResourceScene_->LoadAsyncXML(file, LOAD_RESOURCES_ONLY);
return true;
}
void PrefabImporter::HandlePrefabSave(StringHash eventType, VariantMap& eventData)
{
using namespace PrefabSave;
PrefabComponent* component = static_cast<PrefabComponent*>(eventData[P_PREFABCOMPONENT].GetPtr());
if (component->GetPrefabGUID() != asset_->GetGUID())
return;
Node* node = component->GetNode();
if (!node)
return;
// flip temporary root children and components to not be temporary for save
const Vector<SharedPtr<Component>>& rootComponents = node->GetComponents();
const Vector<SharedPtr<Node> >& children = node->GetChildren();
PODVector<Component*> tempComponents;
PODVector<Node*> tempChildren;
PODVector<Node*> filterNodes;
for (unsigned i = 0; i < rootComponents.Size(); i++)
{
if (rootComponents[i]->IsTemporary())
{
rootComponents[i]->SetTemporary(false);
tempComponents.Push(rootComponents[i]);
}
}
for (unsigned i = 0; i < children.Size(); i++)
{
if (filterNodes.Contains(children[i].Get()))
continue;
if (children[i]->IsTemporary())
{
children[i]->SetTemporary(false);
tempChildren.Push(children[i]);
}
}
// store original transform
Vector3 pos = node->GetPosition();
Quaternion rot = node->GetRotation();
Vector3 scale = node->GetScale();
node->SetPosition(Vector3::ZERO);
node->SetRotation(Quaternion::IDENTITY);
node->SetScale(Vector3::ONE);
component->SetTemporary(true);
SharedPtr<File> file(new File(context_, asset_->GetPath(), FILE_WRITE));
node->SaveXML(*file);
file->Close();
component->SetTemporary(false);
// restore
node->SetPosition(pos);
node->SetRotation(rot);
node->SetScale(scale);
for (unsigned i = 0; i < tempComponents.Size(); i++)
{
tempComponents[i]->SetTemporary(true);
}
for (unsigned i = 0; i < tempChildren.Size(); i++)
{
tempChildren[i]->SetTemporary(true);
}
FileSystem* fs = GetSubsystem<FileSystem>();
fs->Copy(asset_->GetPath(), asset_->GetCachePath());
asset_->UpdateFileTimestamp();
lastFileStamp_ = asset_->GetFileTimestamp();
OnPrefabFileChanged();
}
bool PrefabImporter::Import()
{
// The asset database will see the file changed, when the file watcher catches it
// though we already loaded/imported in OnPrefabFileChanged
if (lastFileStamp_ == asset_->GetFileTimestamp())
return true;
FileSystem* fs = GetSubsystem<FileSystem>();
fs->Copy(asset_->GetPath(), asset_->GetCachePath());
OnPrefabFileChanged();
return true;
}
void PrefabImporter::OnPrefabFileChanged()
{
// reload it immediately so it is ready for use
ResourceCache* cache = GetSubsystem<ResourceCache>();
XMLFile* xmlfile = cache->GetResource<XMLFile>(asset_->GetGUID());
cache->ReloadResource(xmlfile);
VariantMap changedData;
changedData[PrefabChanged::P_GUID] = asset_->GetGUID();
SendEvent(E_PREFABCHANGED, changedData);
}
bool PrefabImporter::LoadSettingsInternal(JSONValue& jsonRoot)
{
if (!AssetImporter::LoadSettingsInternal(jsonRoot))
return false;
JSONValue import = jsonRoot.Get("PrefabImporter");
return true;
}
bool PrefabImporter::SaveSettingsInternal(JSONValue& jsonRoot)
{
if (!AssetImporter::SaveSettingsInternal(jsonRoot))
return false;
JSONValue import(JSONValue::emptyObject);
jsonRoot.Set("PrefabImporter", import);
return true;
}
Node* PrefabImporter::InstantiateNode(Node* parent, const String& name)
{
Node* node = parent->CreateChild(asset_->GetName());
PrefabComponent* pc = node->CreateComponent<PrefabComponent>();
pc->SetPrefabGUID(asset_->GetGUID());
return node;
}
}
| 27.853774 | 102 | 0.695343 | [
"vector",
"transform"
] |
328d4c0fb29c67f7d7bdfcc39bc20ebd34e276d1 | 18,876 | cpp | C++ | src/CQBaseModel.cpp | Qt-Widgets/CQCharts | 0ee923c5a2794b9e3845d0d88fa519fcdea7694a | [
"MIT"
] | null | null | null | src/CQBaseModel.cpp | Qt-Widgets/CQCharts | 0ee923c5a2794b9e3845d0d88fa519fcdea7694a | [
"MIT"
] | null | null | null | src/CQBaseModel.cpp | Qt-Widgets/CQCharts | 0ee923c5a2794b9e3845d0d88fa519fcdea7694a | [
"MIT"
] | null | null | null | #include <CQBaseModel.h>
#include <CQModelUtil.h>
#include <CQModelNameValues.h>
#include <CMathUtil.h>
#include <cmath>
#include <cassert>
namespace {
using TypeName = std::map<CQBaseModelType,QString>;
using NameType = std::map<QString,CQBaseModelType>;
static TypeName s_typeName;
static NameType s_nameType;
void addType(CQBaseModelType type, const QString &name) {
s_typeName[type] = name;
s_nameType[name] = type;
}
void initTypes() {
if (s_typeName.empty()) {
addType(CQBaseModelType::BOOLEAN , "boolean" );
addType(CQBaseModelType::INTEGER , "integer" );
addType(CQBaseModelType::REAL , "real" );
addType(CQBaseModelType::STRING , "string" );
addType(CQBaseModelType::STRINGS , "string_list" );
addType(CQBaseModelType::POINT , "point" );
addType(CQBaseModelType::LINE , "line" );
addType(CQBaseModelType::RECT , "rectangle" );
addType(CQBaseModelType::SIZE , "size" );
addType(CQBaseModelType::POLYGON , "polygon" );
addType(CQBaseModelType::POLYGON_LIST , "polygon_list" );
addType(CQBaseModelType::COLOR , "color" );
addType(CQBaseModelType::PEN , "pen" );
addType(CQBaseModelType::BRUSH , "brush" );
addType(CQBaseModelType::IMAGE , "image" );
addType(CQBaseModelType::TIME , "time" );
addType(CQBaseModelType::SYMBOL , "symbol" );
addType(CQBaseModelType::SYMBOL_SIZE , "symbol_size" );
addType(CQBaseModelType::FONT_SIZE , "font_size" );
addType(CQBaseModelType::PATH , "path" );
addType(CQBaseModelType::STYLE , "style" );
addType(CQBaseModelType::CONNECTION_LIST, "connection_list");
addType(CQBaseModelType::NAME_PAIR , "name_pair" );
addType(CQBaseModelType::COLUMN , "column" );
addType(CQBaseModelType::COLUMN_LIST , "column_list" );
addType(CQBaseModelType::ENUM , "enum" );
}
}
};
//---
CQBaseModel::
CQBaseModel()
{
setObjectName("baseModel");
initTypes();
}
void
CQBaseModel::
genColumnTypes()
{
resetColumnTypes();
// auto determine type for each column. Do column by column to allow early out
int nc = columnCount();
for (int column = 0; column < nc; ++column)
genColumnType(column);
}
void
CQBaseModel::
genColumnType(int column)
{
ColumnData &columnData = getColumnData(column);
genColumnType(columnData);
emit columnTypeChanged(columnData.column);
}
void
CQBaseModel::
genColumnType(const ColumnData &columnData) const
{
if (columnData.type == CQBaseModelType::NONE) {
std::unique_lock<std::mutex> lock(typeMutex_);
if (columnData.type == CQBaseModelType::NONE) {
CQBaseModel *th = const_cast<CQBaseModel *>(this);
th->genColumnTypeI(const_cast<ColumnData &>(columnData));
}
}
}
void
CQBaseModel::
genColumnTypeI(ColumnData &columnData)
{
int maxRows = maxTypeRows();
if (maxRows <= 0)
maxRows = 1000;
//---
columnData.type = CQBaseModelType::STRING;
columnData.baseType = CQBaseModelType::STRING;
//---
ColumnTypeData columnTypeData;
columnTypeData.type = CQModelUtil::calcColumnType(this, columnData.column, maxRows);
// if inderminate (no values or all reals or integers) then use real if any reals,
// integer if any integers and string if no values.
if (columnTypeData.type == CQBaseModelType::NONE) {
if (columnTypeData.numReal)
columnTypeData.type = CQBaseModelType::REAL;
else if (columnTypeData.numInt)
columnTypeData.type = CQBaseModelType::INTEGER;
else
columnTypeData.type = CQBaseModelType::STRING;
}
columnTypeData.baseType = columnTypeData.type;
if (columnTypeData.type != columnData.type) {
columnData.type = columnTypeData.type;
columnData.baseType = columnTypeData.baseType;
}
}
CQBaseModelType
CQBaseModel::
columnType(int column) const
{
if (column < 0 || column >= columnCount())
return CQBaseModelType::NONE;
const ColumnData &columnData = getColumnData(column);
if (columnData.type == CQBaseModelType::NONE)
genColumnType(columnData);
return columnData.type;
}
bool
CQBaseModel::
setColumnType(int column, CQBaseModelType type)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
if (columnData.baseType == CQBaseModelType::NONE)
genColumnType(columnData);
if (type != columnData.type) {
columnData.type = type;
emit columnTypeChanged(column);
}
return true;
}
CQBaseModelType
CQBaseModel::
columnBaseType(int column) const
{
if (column < 0 || column >= columnCount())
return CQBaseModelType::NONE;
const ColumnData &columnData = getColumnData(column);
if (columnData.type == CQBaseModelType::NONE)
genColumnType(columnData);
return columnData.baseType;
}
bool
CQBaseModel::
setColumnBaseType(int column, CQBaseModelType type)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
if (type != columnData.baseType) {
columnData.baseType = type;
emit columnBaseTypeChanged(column);
}
return true;
}
QString
CQBaseModel::
columnTypeValues(int column) const
{
if (column < 0 || column >= columnCount())
return QString();
const ColumnData &columnData = getColumnData(column);
return columnData.typeValues;
}
bool
CQBaseModel::
setColumnTypeValues(int column, const QString &str)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.typeValues = str;
emit columnTypeChanged(column);
return true;
}
QVariant
CQBaseModel::
columnMin(int column) const
{
if (column < 0 || column >= columnCount())
return QVariant();
const ColumnData &columnData = getColumnData(column);
return columnData.min;
}
bool
CQBaseModel::
setColumnMin(int column, const QVariant &v)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.min = v;
emit columnRangeChanged(column);
return true;
}
QVariant
CQBaseModel::
columnMax(int column) const
{
if (column < 0 || column >= columnCount())
return QVariant();
const ColumnData &columnData = getColumnData(column);
return columnData.max;
}
bool
CQBaseModel::
setColumnMax(int column, const QVariant &v)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.max = v;
emit columnRangeChanged(column);
return true;
}
bool
CQBaseModel::
isColumnKey(int column) const
{
if (column < 0 || column >= columnCount())
return false;
const ColumnData &columnData = getColumnData(column);
return columnData.key;
}
bool
CQBaseModel::
setColumnKey(int column, bool b)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.key = b;
emit columnKeyChanged(column);
return true;
}
bool
CQBaseModel::
isColumnSorted(int column) const
{
if (column < 0 || column >= columnCount())
return false;
const ColumnData &columnData = getColumnData(column);
return columnData.sorted;
}
bool
CQBaseModel::
setColumnSorted(int column, bool b)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.sorted = b;
emit columnSortedChanged(column);
return true;
}
int
CQBaseModel::
columnSortOrder(int column) const
{
if (column < 0 || column >= columnCount())
return Qt::AscendingOrder;
const ColumnData &columnData = getColumnData(column);
return columnData.sortOrder;
}
bool
CQBaseModel::
setColumnSortOrder(int column, int i)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.sortOrder = i;
emit columnSortOrderChanged(column);
return true;
}
QString
CQBaseModel::
columnTitle(int column) const
{
if (column < 0 || column >= columnCount())
return "";
const ColumnData &columnData = getColumnData(column);
return columnData.title;
}
bool
CQBaseModel::
setColumnTitle(int column, const QString &s)
{
if (column < 0 || column >= columnCount())
return false;
ColumnData &columnData = getColumnData(column);
columnData.title = s;
emit columnTitleChanged(column);
return true;
}
QVariant
CQBaseModel::
columnNameValue(int column, const QString &name) const
{
if (column < 0 || column >= columnCount())
return "";
QString values = columnTypeValues(column);
CQModelNameValues nameValues(values);
QVariant value;
if (! nameValues.nameValue(name, value))
return QVariant();
return value;
}
bool
CQBaseModel::
setColumnNameValue(int column, const QString &name, const QVariant &value)
{
if (column < 0 || column >= columnCount())
return false;
QString values = columnTypeValues(column);
CQModelNameValues nameValues(values);
nameValues.setNameValue(name, value);
setColumnTypeValues(column, nameValues.toString());
return true;
}
const CQBaseModel::ColumnData &
CQBaseModel::
getColumnData(int column) const
{
return const_cast<CQBaseModel *>(this)->getColumnData(column);
}
CQBaseModel::ColumnData &
CQBaseModel::
getColumnData(int column)
{
assert(column >= 0 || column < columnCount());
auto p = columnDatas_.find(column);
if (p != columnDatas_.end()) {
ColumnData &columnData = (*p).second;
assert(columnData.column == column);
return columnData;
}
//---
std::unique_lock<std::mutex> lock(mutex_);
CQBaseModel *th = const_cast<CQBaseModel *>(this);
auto p1 = th->columnDatas_.find(column);
if (p1 == th->columnDatas_.end())
p1 = th->columnDatas_.insert(p1, ColumnDatas::value_type(column, ColumnData(column)));
return (*p1).second;
}
void
CQBaseModel::
resetColumnType(int column)
{
auto p = columnDatas_.find(column);
if (p != columnDatas_.end())
columnDatas_.erase(p);
}
void
CQBaseModel::
resetColumnTypes()
{
for (auto &p : columnDatas_) {
ColumnData &columnData = p.second;
columnData.type = CQBaseModelType::NONE;
}
}
//------
QVariant
CQBaseModel::
rowGroup(int row) const
{
if (row < 0 || row >= rowCount())
return QVariant();
const RowData &rowData = getRowData(row);
return rowData.group;
}
bool
CQBaseModel::
setRowGroup(int row, const QVariant &v)
{
if (row < 0 || row >= rowCount())
return false;
RowData &rowData = getRowData(row);
rowData.group = v;
return true;
}
const CQBaseModel::RowData &
CQBaseModel::
getRowData(int row) const
{
return const_cast<CQBaseModel *>(this)->getRowData(row);
}
CQBaseModel::RowData &
CQBaseModel::
getRowData(int row)
{
assert(row >= 0 || row < rowCount());
auto p = rowDatas_.find(row);
if (p != rowDatas_.end()) {
RowData &rowData = (*p).second;
assert(rowData.row == row);
return rowData;
}
//---
std::unique_lock<std::mutex> lock(mutex_);
CQBaseModel *th = const_cast<CQBaseModel *>(this);
auto p1 = th->rowDatas_.find(row);
if (p1 == th->rowDatas_.end())
p1 = th->rowDatas_.insert(p1, RowDatas::value_type(row, RowData(row)));
return (*p1).second;
}
//------
QVariant
CQBaseModel::
headerData(int section, Qt::Orientation orientation, int role) const
{
// generic column data
if (orientation == Qt::Horizontal) {
if (role == static_cast<int>(CQBaseModelRole::Type)) {
CQBaseModelType type = columnType(section);
if (type == CQBaseModelType::NONE)
return QVariant();
return QVariant((int) type);
}
else if (role == static_cast<int>(CQBaseModelRole::BaseType)) {
CQBaseModelType type = columnBaseType(section);
if (type == CQBaseModelType::NONE)
return QVariant();
return QVariant((int) type);
}
else if (role == static_cast<int>(CQBaseModelRole::TypeValues)) {
return QVariant(columnTypeValues(section));
}
else if (role == static_cast<int>(CQBaseModelRole::Min)) {
return columnMin(section);
}
else if (role == static_cast<int>(CQBaseModelRole::Max)) {
return columnMax(section);
}
else if (role == static_cast<int>(CQBaseModelRole::Key)) {
return isColumnKey(section);
}
else if (role == static_cast<int>(CQBaseModelRole::Sorted)) {
return isColumnSorted(section);
}
else if (role == static_cast<int>(CQBaseModelRole::SortOrder)) {
return columnSortOrder(section);
}
else if (role == static_cast<int>(CQBaseModelRole::Title)) {
return columnTitle(section);
}
else if (role == static_cast<int>(CQBaseModelRole::DataMin)) {
return columnMin(section);
}
else if (role == static_cast<int>(CQBaseModelRole::DataMax)) {
return columnMax(section);
}
else {
return QAbstractItemModel::headerData(section, orientation, role);
}
}
// generic row data
else if (orientation == Qt::Vertical) {
if (role == static_cast<int>(CQBaseModelRole::Group)) {
return rowGroup(section);
}
else {
return QAbstractItemModel::headerData(section, orientation, role);
}
}
else {
assert(false);
}
return QVariant();
}
bool
CQBaseModel::
setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
{
// generic column data
if (orientation == Qt::Horizontal) {
if (role == static_cast<int>(CQBaseModelRole::Type)) {
bool ok;
CQBaseModelType type = variantToType(value, &ok);
if (! ok) return false;
return setColumnType(section, type);
}
else if (role == static_cast<int>(CQBaseModelRole::BaseType)) {
bool ok;
CQBaseModelType type = variantToType(value, &ok);
if (! ok) return false;
return setColumnBaseType(section, type);
}
else if (role == static_cast<int>(CQBaseModelRole::TypeValues)) {
QString str = value.toString();
return setColumnTypeValues(section, str);
}
else if (role == static_cast<int>(CQBaseModelRole::Min)) {
return setColumnMin(section, value);
}
else if (role == static_cast<int>(CQBaseModelRole::Max)) {
return setColumnMax(section, value);
}
else if (role == static_cast<int>(CQBaseModelRole::Key)) {
return setColumnKey(section, value.toBool());
}
else if (role == static_cast<int>(CQBaseModelRole::Sorted)) {
return setColumnSorted(section, value.toBool());
}
else if (role == static_cast<int>(CQBaseModelRole::SortOrder)) {
return setColumnSortOrder(section, value.toInt());
}
else if (role == static_cast<int>(CQBaseModelRole::Title)) {
return setColumnTitle(section, value.toString());
}
else if (role == static_cast<int>(CQBaseModelRole::DataMin)) {
assert(false);
}
else if (role == static_cast<int>(CQBaseModelRole::DataMax)) {
assert(false);
}
else {
return QAbstractItemModel::setHeaderData(section, orientation, role);
}
}
// generic row data
else if (orientation == Qt::Vertical) {
if (role == static_cast<int>(CQBaseModelRole::Group)) {
return setRowGroup(section, value);
}
else {
return QAbstractItemModel::setHeaderData(section, orientation, role);
}
}
else {
assert(false);
}
return false;
}
QVariant
CQBaseModel::
data(const QModelIndex &index, int role) const
{
if (role == Qt::TextAlignmentRole) {
CQBaseModelType type = columnType(index.column());
if (type == CQBaseModelType::INTEGER || type == CQBaseModelType::REAL)
return QVariant(Qt::AlignRight | Qt::AlignVCenter);
else
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
}
//return QAbstractItemModel::data(index, role);
return QVariant();
}
//------
int
CQBaseModel::
modelColumnNameToInd(const QString &name) const
{
return modelColumnNameToInd(this, name);
}
int
CQBaseModel::
modelColumnNameToInd(const QAbstractItemModel *model, const QString &name)
{
int role = Qt::DisplayRole;
for (int icolumn = 0; icolumn < model->columnCount(); ++icolumn) {
QVariant var = model->headerData(icolumn, Qt::Horizontal, role);
if (! var.isValid())
continue;
QString name1 = var.toString();
if (name == name1)
return icolumn;
}
//---
bool ok;
int column = name.toInt(&ok);
if (ok)
return column;
return -1;
}
//------
CQBaseModelType
CQBaseModel::
variantToType(const QVariant &var, bool *ok)
{
CQBaseModelType type = CQBaseModelType::NONE;
if (var.type() == QVariant::Int) {
type = (CQBaseModelType) var.toInt(ok);
}
else {
QString str = var.toString();
type = nameType(str);
}
if (! isType((int) type)) {
if (ok)
*ok = false;
}
return type;
}
QVariant
CQBaseModel::
typeToVariant(CQBaseModelType type)
{
return QVariant((int) type);
}
bool
CQBaseModel::
isSameType(const QVariant &var, CQBaseModelType type)
{
if (type == CQBaseModelType::REAL && var.type() == QVariant::Double)
return true;
if (type == CQBaseModelType::INTEGER && var.type() == QVariant::Int)
return true;
#if 0
if (type == CQBaseModelType::TIME && var.type() == QVariant::Double)
return true;
#endif
return false;
}
QVariant
CQBaseModel::
typeStringToVariant(const QString &str, CQBaseModelType type)
{
if (type == CQBaseModelType::REAL) {
bool ok;
double real = toReal(str, ok);
if (ok)
return QVariant(real);
}
else if (type == CQBaseModelType::INTEGER) {
bool ok;
long integer = toInt(str, ok);
if (ok)
return QVariant(int(integer));
}
#if 0
else if (type == CQBaseModelType::TIME) {
bool ok;
double real = toReal(str, ok);
if (ok)
return QVariant(real);
}
#endif
return QVariant(str);
}
bool
CQBaseModel::
isType(int type)
{
initTypes();
return (s_typeName.find((CQBaseModelType) type) != s_typeName.end());
}
QString
CQBaseModel::
typeName(CQBaseModelType type)
{
initTypes();
auto p = s_typeName.find(type);
if (p == s_typeName.end())
return "none";
return (*p).second;
}
CQBaseModelType
CQBaseModel::
nameType(const QString &name)
{
initTypes();
auto p = s_nameType.find(name);
if (p == s_nameType.end())
return CQBaseModelType::NONE;
return (*p).second;
}
double
CQBaseModel::
toReal(const QString &str, bool &ok)
{
return str.toDouble(&ok);
}
long
CQBaseModel::
toInt(const QString &str, bool &ok)
{
return str.toInt(&ok);
}
bool
CQBaseModel::
isInteger(double r)
{
return CMathUtil::isInteger(r);
}
| 20.834437 | 90 | 0.661051 | [
"model"
] |
328f42e715e7ca7d2af979826ce87ffb7a1d6665 | 17,982 | cc | C++ | 057_Pure_GLFW_OpenGL_Test/src/main.cc | DreamWaterFound/Codes | e7d80eb8bfd7d6f104abd18724cb4bface419233 | [
"WTFPL"
] | 13 | 2019-02-28T14:28:23.000Z | 2021-12-04T04:55:19.000Z | 057_Pure_GLFW_OpenGL_Test/src/main.cc | DreamWaterFound/Codes | e7d80eb8bfd7d6f104abd18724cb4bface419233 | [
"WTFPL"
] | 1 | 2019-09-07T09:00:50.000Z | 2019-12-04T02:13:25.000Z | 057_Pure_GLFW_OpenGL_Test/src/main.cc | DreamWaterFound/Codes | e7d80eb8bfd7d6f104abd18724cb4bface419233 | [
"WTFPL"
] | 1 | 2020-03-11T16:47:31.000Z | 2020-03-11T16:47:31.000Z | #include <iostream>
#include <string>
#include <cmath>
// gl3w
#include <GL/gl3w.h>
// GLFW
#include <GLFW/glfw3.h>
#include <cstring>
#define M3D_PI (3.141562954f)
#define GLT_ATTRIBUTE_VERTEX 1
using namespace std;
float gfpProjectMatrix[16];
float gfpModelViewMatrix[16];
float gfpCameraFrame[16];
float gfpObjectFrame[16];
float gfpTmp1[16], gfpTmp2[16], gfpTmp3[16], gfpTmp4[16];
// ========== 函数原型 ===============
void GenerateProjectionMatrix(float fFov, float fAspect, float fNear, float fFar, float* fProjectMatrix);
void m3dLoadIdentity44(float* m);
void GetCameraFrame(float* pfCameraFrame);
void GetObjectFrame(float* pfObjectFrame);
void m3dCrossProduct3(float* result, const float* u, const float* v);
void m3dTranslationMatrix44(float* m, float x, float y, float z);
void m3dMatrixMultiply44(float* product, const float* a, const float* b );
void m3dSetMatrixColumn44(float* dst, const float* src, const int column);
void DisplayMatrix(float* mat);
// =======================
GLuint InitTraigleBatch(GLuint& hVAO, GLuint& hVBO)
{
// 原始的三棱锥数据
GLfloat vVerts[12][3] = { -2.0f, 0.0f, -2.0f,
2.0f, 0.0f, -2.0f,
0.0f, 4.0f, 0.0f,
2.0f, 0.0f, -2.0f,
2.0f, 0.0f, 2.0f,
0.0f, 4.0f, 0.0f,
2.0f, 0.0f, 2.0f,
-2.0f, 0.0f, 2.0f,
0.0f, 4.0f, 0.0f,
-2.0f, 0.0f, 2.0f,
-2.0f, 0.0f, -2.0f,
0.0f, 4.0f, 0.0f};
// 12 个点
GLuint nNumVerts = 12;
// 创建 VAO 对象
GLuint hVertexArrayObject;
glGenVertexArrays(1, &hVertexArrayObject);
glBindVertexArray(hVertexArrayObject);
// 创建缓冲区, 并且进行绑定, 存储顶点坐标信息, 充当 VBO
GLuint hVertexArray;
glGenBuffers(1, &hVertexArray);
glBindBuffer(GL_ARRAY_BUFFER, hVertexArray);
// TODO 缓冲区的那一章会有介绍
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * nNumVerts, vVerts, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(GLT_ATTRIBUTE_VERTEX);
glVertexAttribPointer(GLT_ATTRIBUTE_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
// 不再使用之前的 VAO 对象
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindVertexArray(0);
hVAO = hVertexArrayObject;
hVBO = hVertexArray;
return hVertexArrayObject;
}
// 绘制顶点batch
void DrawTraigles(GLuint nPrimitiveType, GLuint hVAO, GLuint hVBO)
{
GLuint nNumVerts = 12;
glBindVertexArray(hVAO);
glEnableVertexAttribArray(GLT_ATTRIBUTE_VERTEX);
glDrawArrays(nPrimitiveType, 0, nNumVerts);
glDisableVertexAttribArray(GLT_ATTRIBUTE_VERTEX);
glBindVertexArray(0);
}
// 加载着色器并构建渲染管线
GLuint InitShaders(void)
{
// Temporary Shader objects
GLuint hVertexShader; // 顶点着色器句柄
GLuint hFragmentShader; // 片段着色器句柄
GLuint hReturn = 0; // 构建好的着色器程序
GLint testVal; // 用于检测着色器程序是否编译成功
// 单位着色器程序
const char *szFlatShaderVP = "uniform mat4 mvpMatrix;"
"attribute vec4 vVertex;"
"void main(void) "
"{ gl_Position = mvpMatrix * vVertex; "
"}";
const char *szFlatShaderFP = "uniform vec4 vColor;"
"void main(void) "
"{ gl_FragColor = vColor; "
"}";
// Create shader objects -- 创建着色器对象
hVertexShader = glCreateShader(GL_VERTEX_SHADER);
hFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
// Load them.
{
GLchar *fsStringPtr[1];
fsStringPtr[0] = (GLchar *)szFlatShaderVP;
glShaderSource(hVertexShader, 1, (const GLchar **)fsStringPtr, NULL);
}
{
GLchar *fsStringPtr[1];
fsStringPtr[0] = (GLchar *)szFlatShaderFP;
glShaderSource(hFragmentShader, 1, (const GLchar **)fsStringPtr, NULL);
}
// Compile them
glCompileShader(hVertexShader);
glCompileShader(hFragmentShader);
// Check for errors
glGetShaderiv(hVertexShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
{
char infoLog[1024];
glGetShaderInfoLog(hVertexShader, 1024, NULL, infoLog);
cout << "The shader at " << endl << szFlatShaderVP << endl;
cout << "failed to compile with the following error:" <<endl;
cout << infoLog << endl;
glDeleteShader(hVertexShader);
glDeleteShader(hFragmentShader);
return (GLuint)NULL;
}
glGetShaderiv(hFragmentShader, GL_COMPILE_STATUS, &testVal);
if(testVal == GL_FALSE)
{
char infoLog[1024];
glGetShaderInfoLog(hFragmentShader, 1024, NULL, infoLog);
cout << "The shader at " << endl << szFlatShaderFP << endl;
cout << "failed to compile with the following error:" <<endl;
cout << infoLog << endl;
glDeleteShader(hVertexShader);
glDeleteShader(hFragmentShader);
return (GLuint)NULL;
}
// Link them - assuming it works...
hReturn = glCreateProgram();
glAttachShader(hReturn, hVertexShader);
glAttachShader(hReturn, hFragmentShader);
// 添加属性信息
glBindAttribLocation(hReturn, GLT_ATTRIBUTE_VERTEX,"vVertex");
glLinkProgram(hReturn);
// These are no longer needed
glDeleteShader(hVertexShader);
glDeleteShader(hFragmentShader);
// Make sure link worked too
glGetProgramiv(hReturn, GL_LINK_STATUS, &testVal);
if(testVal == GL_FALSE)
{
glDeleteProgram(hReturn);
cout << "failed to generate a shader program." << endl;
return (GLuint)NULL;
}
return hReturn;
}
// 启用之前生成的着色器对象
void EnableShaders(GLuint hProgram, GLfloat* fColors, GLfloat* mvpMatrix)
{
// 使用指定的着色器程序
glUseProgram(hProgram);
// 设置统一值 -- 颜色
GLint iColor = glGetUniformLocation(hProgram, "vColor");
glUniform4fv(iColor, 1, fColors);
// 设置统一值 -- 变换投影矩阵
GLint iTransform = glGetUniformLocation(hProgram, "mvpMatrix");
glUniformMatrix4fv(iTransform, 1, GL_FALSE, mvpMatrix);
}
// 主动按键处理
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)//获取按键,如果等于esc
glfwSetWindowShouldClose(window, true);//利用强制窗口应该关闭
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)//这个是窗口变化的回调函数。。注意输入参数
//是一个glfw的窗口,一个宽度和高度
{
glViewport(0, 0, width, height);//这个是回调函数内的内容
//这里是将视口改成变化后的的窗口大小
//注意需要的注册该回调函数
//glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
//两个参数是,glfw的窗口以及回调函数
GenerateProjectionMatrix(35.0f, float(width) / float(height), 1.0f, 500.0f, gfpProjectMatrix);
cout << "Window resized [" << width << " , " << height << "] !" << endl;
}
//按键回调函数
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS)
return;
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
cout << "ESC Pressed." <<endl;
break;
default:
break;
}
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (action == GLFW_PRESS) switch(button)
{
case GLFW_MOUSE_BUTTON_LEFT:
cout << "Mosue left button clicked!" << endl;
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
cout << "Mosue middle button clicked!" << endl;
break;
case GLFW_MOUSE_BUTTON_RIGHT:
cout << "Mosue right button clicked!" <<endl;
break;
default:
return;
}
return;
}
void cursor_position_callback(GLFWwindow* window, double x, double y)
{
cout << "Mouse position move to [" << int(x) << " : " << int(y) << "]" <<endl;
return;
}
void scroll_callback(GLFWwindow* window, double x, double y)
{
cout << "Mouse position scroll at [" << int(x) << " : " << int(y) << "]" <<endl;
return;
}
int main(void)
{
glfwSetErrorCallback([](int err, const char* desc) { std::cerr << "glfw error " << err << ": " << desc << std::endl; });
if(!glfwInit()) {
std::cerr << "failed to initialize GLFW" << std::endl;
return false;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);//设置主版本号
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);//设置次版本号
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
auto window = glfwCreateWindow(640, 480, "Pure OpenGL Test", nullptr, nullptr);
if(window == nullptr) {
return false;
}
// 设置各种事件的回调函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
if (gl3wInit()) {
fprintf(stderr, "failed to initialize OpenGL\n");
return -1;
}
if (!gl3wIsSupported(3, 2)) {
fprintf(stderr, "OpenGL 3.2 not supported\n");
return -1;
}
printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION),
glGetString(GL_SHADING_LANGUAGE_VERSION));
// 初始化着色器
GLuint hShaderProgram = InitShaders();
if(hShaderProgram == GLuint(NULL))
{
cout << "init shaders failed." << endl;
glfwDestroyWindow(window);
glfwTerminate();
}
else
{
cout << "init shaders OK." << endl;
}
// 初始化要绘制的图像
GLuint hVertexArray;
GLuint hVertexArrayObject;
InitTraigleBatch(hVertexArrayObject, hVertexArray);
glEnable(GL_DEPTH_TEST);
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
framebuffer_size_callback(window, display_w, display_h);
// Main loop
while (!glfwWindowShouldClose(window))
{
// 处理系统信息(键鼠输入, 其他窗口交互信息等)
glfwPollEvents();
// processInput(window);
GetCameraFrame(gfpCameraFrame);
GetObjectFrame(gfpObjectFrame);
m3dMatrixMultiply44(gfpModelViewMatrix, gfpCameraFrame, gfpObjectFrame);
m3dMatrixMultiply44(gfpTmp1, gfpProjectMatrix, gfpModelViewMatrix);
// 准备绘图
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
// 这里就是对背景进行绘图的地方
// GLfloat afColorRed[] = {1.0f, 0.0f, 0.0f, 1.0f};
GLfloat afColorGreen[] = {0.0f, 1.0f, 0.0f, 1.0f};
GLfloat afColorBlack[] = {0.0f, 0.0f, 0.0f, 1.0f};
EnableShaders(hShaderProgram, afColorGreen, gfpTmp1);
DrawTraigles(GL_TRIANGLES, hVertexArrayObject, hVertexArray);
glPolygonOffset(-1.0f, -1.0f); // Shift depth values
glEnable(GL_POLYGON_OFFSET_LINE);
// Draw lines antialiased
// 启用抗锯齿效果
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Draw black wireframe version of geometry
// 绘制线
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glLineWidth(2.5f);
EnableShaders(hShaderProgram, afColorBlack, gfpTmp1);
DrawTraigles(GL_TRIANGLES, hVertexArrayObject, hVertexArray);
// Put everything back the way we found it
// 恢复正常
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_POLYGON_OFFSET_LINE);
glLineWidth(1.0f);
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glfwSwapBuffers(window);
}
// 注意需要删除着色器程序
glDeleteProgram(hShaderProgram);
// 删除顶点
glDeleteVertexArrays(1, &hVertexArrayObject);
// 删除缓冲区
glDeleteBuffers(1, &hVertexArray);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
// 生成投影矩阵
void GenerateProjectionMatrix(float fFov, float fAspect, float fNear, float fFar, float* fpProjectMatrix)
{
float xmin, xmax, ymin, ymax; // Dimensions of near clipping plane
// float xFmin, xFmax, yFmin, yFmax; // Dimensions of far clipping plane
// Do the Math for the near clipping plane
ymax = fNear * float(tan( fFov * M3D_PI / 360.0 ));
ymin = -ymax;
xmin = ymin * fAspect;
xmax = -xmin;
// Construct the projection matrix
m3dLoadIdentity44(fpProjectMatrix);
// 看来这个是有单独的计算公式
fpProjectMatrix[0] = (2.0f * fNear)/(xmax - xmin);
fpProjectMatrix[5] = (2.0f * fNear)/(ymax - ymin);
fpProjectMatrix[8] = (xmax + xmin) / (xmax - xmin);
fpProjectMatrix[9] = (ymax + ymin) / (ymax - ymin);
fpProjectMatrix[10] = -((fFar + fNear)/(fFar - fNear));
fpProjectMatrix[11] = -1.0f;
fpProjectMatrix[14] = -((2.0f * fFar * fNear)/(fFar - fNear));
fpProjectMatrix[15] = 0.0f;
}
// 4x4 double
void m3dLoadIdentity44(float* m)
{
m[ 0] = 1.0f;
m[ 1] = 0.0f;
m[ 2] = 0.0f;
m[ 3] = 0.0f;
m[ 4] = 0.0f;
m[ 5] = 1.0f;
m[ 6] = 0.0f;
m[ 7] = 0.0f;
m[ 8] = 0.0f;
m[ 9] = 0.0f;
m[10] = 1.0f;
m[11] = 0.0f;
m[12] = 0.0f;
m[13] = 0.0f;
m[14] = 0.0f;
m[15] = 1.0f;
}
void GetCameraFrame(float* m)
{
float vOrigin[3], vUp[3], vForward[3];
// At origin
vOrigin[0] = 0.0f; vOrigin[1] = 0.0f; vOrigin[2] = 0.0f;
// Up is up (+Y)
vUp[0] = 0.0f; vUp[1] = 1.0f; vUp[2] = 0.0f;
// Forward is -Z (default OpenGL)
vForward[0] = 0.0f; vForward[1] = 0.0f; vForward[2] = -1.0f;
float fDelta = -15.0f;
vOrigin[0] += vForward[0] * fDelta;
vOrigin[1] += vForward[1] * fDelta;
vOrigin[2] += vForward[2] * fDelta;
float x[3], z[3];
// Make rotation matrix
// Z vector is reversed
z[0] = -vForward[0];
z[1] = -vForward[1];
z[2] = -vForward[2];
// X vector = Y cross Z
m3dCrossProduct3(x, vUp, z);
// Matrix has no translation information and is
// transposed.... (rows instead of columns)
#define M(row,col) m[col*4+row]
M(0, 0) = x[0];
M(0, 1) = x[1];
M(0, 2) = x[2];
M(0, 3) = 0.0;
M(1, 0) = vUp[0];
M(1, 1) = vUp[1];
M(1, 2) = vUp[2];
M(1, 3) = 0.0;
M(2, 0) = z[0];
M(2, 1) = z[1];
M(2, 2) = z[2];
M(2, 3) = 0.0;
M(3, 0) = 0.0;
M(3, 1) = 0.0;
M(3, 2) = 0.0;
M(3, 3) = 1.0;
#undef M
// Apply translation too
float trans[16], M[16];
m3dTranslationMatrix44(trans, -vOrigin[0], -vOrigin[1], -vOrigin[2]);
m3dMatrixMultiply44(M, m, trans);
// Copy result back into m
memcpy(m, M, sizeof(float)*16);
}
// 计算物体的坐标系
void GetObjectFrame(float* pfObjectFrame)
{
// 物体的位置进行调节
float vOrigin[3], vUp[3], vForward[3];
// At origin
vOrigin[0] = 0.0f; vOrigin[1] = 0.0f; vOrigin[2] = 0.0f;
// Up is up (+Y)
vUp[0] = 0.0f; vUp[1] = 1.0f; vUp[2] = 0.0f;
// Forward is -Z (default OpenGL)
vForward[0] = 0.0f; vForward[1] = 0.0f; vForward[2] = -1.0f;
// Calculate the right side (x) vector, drop it right into the matrix
float vXAxis[3];
m3dCrossProduct3(vXAxis, vUp, vForward);
// Set matrix column does not fill in the fourth value...
m3dSetMatrixColumn44(pfObjectFrame, vXAxis, 0);
pfObjectFrame[3] = 0.0f;
// Y Column
m3dSetMatrixColumn44(pfObjectFrame, vUp, 1);
pfObjectFrame[7] = 0.0f;
// Z Column
m3dSetMatrixColumn44(pfObjectFrame, vForward, 2);
pfObjectFrame[11] = 0.0f;
m3dSetMatrixColumn44(pfObjectFrame, vOrigin, 3);
pfObjectFrame[15] = 1.0f;
}
void m3dCrossProduct3(float* result, const float* u, const float* v)
{
result[0] = u[1]*v[2] - v[1]*u[2];
result[1] = -u[0]*v[2] + v[0]*u[2];
result[2] = u[0]*v[1] - v[0]*u[1];
}
void m3dTranslationMatrix44(float* m, float x, float y, float z)
{ m3dLoadIdentity44(m); m[12] = x; m[13] = y; m[14] = z; }
void m3dMatrixMultiply44(float* product, const float* a, const float* b )
{
#define A(row,col) a[(col<<2)+row]
#define B(row,col) b[(col<<2)+row]
#define P(row,col) product[(col<<2)+row]
// for (int i = 0; i < 3; i++) {
// double ai0=A33(i,0), ai1=A33(i,1), ai2=A33(i,2);
// P33(i,0) = ai0 * B33(0,0) + ai1 * B33(1,0) + ai2 * B33(2,0);
// P33(i,1) = ai0 * B33(0,1) + ai1 * B33(1,1) + ai2 * B33(2,1);
// P33(i,2) = ai0 * B33(0,2) + ai1 * B33(1,2) + ai2 * B33(2,2);
// }
for (int i = 0; i < 4; i++) {
float ai0=A(i,0), ai1=A(i,1), ai2=A(i,2), ai3=A(i,3);
P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0);
P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1);
P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2);
P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3);
}
#undef A
#undef B
#undef P
}
// DEBUG
void DisplayMatrix(float* mat)
{
using namespace std;
cout << "=================" << endl;
cout << mat[0] << " " << mat[1] << " " << mat[2] << " " << mat[3] << endl;
cout << mat[4] << " " << mat[5] << " " << mat[6] << " " << mat[7] << endl;
cout << mat[8] << " " << mat[9] << " " << mat[10] << " " << mat[11] << endl;
cout << mat[12] << " " << mat[13] << " " << mat[14] << " " << mat[15] << endl;
cout << "=================" << endl;
}
void m3dSetMatrixColumn44(float* dst, const float* src, const int column)
{ memcpy(dst + (4 * column), src, sizeof(float) * 4); } | 30.020033 | 124 | 0.575186 | [
"geometry",
"vector"
] |
32905f709114ebd5b744cc697ad5576200166524 | 4,268 | cpp | C++ | src/MapHandler.cpp | wlue/codename_portal | c7409cf9e756417974a7f284ade0bba24026c212 | [
"MIT",
"Unlicense"
] | 1 | 2021-03-27T03:00:34.000Z | 2021-03-27T03:00:34.000Z | src/MapHandler.cpp | wlue/codename_portal | c7409cf9e756417974a7f284ade0bba24026c212 | [
"MIT",
"Unlicense"
] | null | null | null | src/MapHandler.cpp | wlue/codename_portal | c7409cf9e756417974a7f284ade0bba24026c212 | [
"MIT",
"Unlicense"
] | null | null | null |
#include "MapHandler.h"
#include "CTile.h"
#include "CTurret.h"
MapHandler::MapHandler(string file)
{
OpenFile(file);
}
MapHandler::MapHandler()
{
datInfo = datKey = datMap = "";
loaded = false;
}
MapHandler::~MapHandler()
{
}
void MapHandler::OpenFile(string file)
{
ClearData();
filename = file;
LoadData();
ParseData();
}
void MapHandler::ClearData()
{
filename = "";
datInfo = datKey = datMap = "";
loaded = false;
mapKey.clear();
}
void MapHandler::ParseTile(string& objtype, string& tiletype, string parse)
{
objtype = parse.substr(0, parse.find('('));
tiletype = parse.substr(parse.find('(') + 1, parse.length() - objtype.length() - 2);
}
void MapHandler::ParseAttributes(string& tiletype, string& tileatr, string tileinfo, char delim)
{
string::size_type loc = tileinfo.find(delim, 0);
if(loc != string::npos) // if delim was found
{
tiletype = tileinfo.substr(0, loc);
tileatr = tileinfo.substr(loc + 1, tileinfo.length());
}
else
{
tiletype = tileinfo;
}
}
void MapHandler::LoadMap()
{
if(!loaded)
{
cout << "Error: Cannot load map when data not loaded and parsed." << endl;
return;
}
map_maxx = w;
map_maxy = h;
MAP_WIDTH = w * TILE_WIDTH;
MAP_HEIGHT = h * TILE_HEIGHT;
// load through map tiles
stringstream stream (stringstream::in | stringstream::out);
stream << datMap;
for(int y=0; y < (int) map_maxy; ++y)
{
for(int x=0; x < (int) map_maxx; ++x)
{
string tText; stream >> tText;
if(tText.empty()) { cout << "Error: Map ran out of bounds." << endl; return; };
map<string, string> tiles = getKeyMap(tText);
map<string, string>::iterator tilesItr;
for(tilesItr = tiles.begin(); tilesItr != tiles.end(); ++tilesItr)
{
string objtype = tilesItr->first;
string tileinfo = tilesItr->second;
string tiletype, tileatr;
ParseAttributes(tiletype, tileatr, tileinfo, '|');
CObject* newObj = NULL;
if(objtype == "tile") newObj = new CTile(tiletype, x, y);
if(objtype == "turret") newObj = new CTurret(x, y);
if(newObj != NULL)
{
// if(!tileatr.empty())
// newObj->SetAttributes(tileatr);
}
else
{
cout << "Unknown type: " << tiletype << endl;
}
}
}
}
}
void MapHandler::ParseData()
{
// parse info
stringstream info_stream (stringstream::in | stringstream::out);
info_stream << datInfo;
string data = "";
while(info_stream >> data)
{
string key;
int value;
GetSides<string, int> (key, value, data, "=");
if(key == "width") w = value;
if(key == "height") h = value;
data = "";
}
// parse keys
stringstream key_stream (stringstream::in | stringstream::out);
key_stream << datKey;
string keylines = "";
while(key_stream >> keylines)
{
string key, value;
GetSides<string, string> (key, value, keylines, "=");
vector<string> valList;
SplitValues(valList, value, '+');
map<string, string> typeIdent;
for(vector<string>::iterator valItr = valList.begin(); valItr != valList.end(); ++valItr)
{
string tval = *valItr; // a string formatted as such: objtype(tiletype)
string objtype, tiletype;
ParseTile(objtype, tiletype, tval);
if(objtype.empty()) {
cout << "Error: objtype empty: '" << tval << "'."; return;
}
typeIdent[objtype] = tiletype;
}
mapKey[key] = typeIdent;
keylines = "";
}
loaded = true;
}
void MapHandler::LoadData()
{
ifstream file (filename.c_str());
if(!file.is_open())
{
cout << "Error: Could not open file '" << filename << "'." << endl;
return;
}
int status = 0;
while(!file.eof())
{
string line = "";
getline(file, line);
if(line == "/*") status |= READIGNORE;
if(line == "*/") status &= ~READIGNORE;
if(status & READIGNORE || line.substr(0, 1) == "!") continue; // comments
if(line == infoTag) status ^= READINFO;
else if(line == keyTag) status ^= READKEY;
else if(line == mapTag) status ^= READMAP;
else if(status)
{
switch(status)
{
case READINFO:
if(!datInfo.empty()) datInfo = datInfo + " ";
datInfo += line;
break;
case READKEY:
if(!datKey.empty()) datKey = datKey + " ";
datKey += line;
break;
case READMAP:
if(!datMap.empty()) datMap = datMap + " ";
datMap += line;
break;
}
}
}
file.close();
} | 20.037559 | 96 | 0.616917 | [
"vector"
] |
32929e54a436d887ad1fa4c7f40bb004064cfb65 | 94,273 | cpp | C++ | Engine/Source/Programs/UnrealLightmass/Private/ImportExport/LightmassScene.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Programs/UnrealLightmass/Private/ImportExport/LightmassScene.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Programs/UnrealLightmass/Private/ImportExport/LightmassScene.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "LightmassScene.h"
#include "Importer.h"
#include "MonteCarlo.h"
#include "LightingSystem.h"
#include "LMDebug.h"
namespace Lightmass
{
/** Copy ctor that doesn't modify padding in FSceneFileHeader. */
FSceneFileHeader::FSceneFileHeader(const FSceneFileHeader& Other)
{
/** FourCC cookie: 'SCEN' */
Cookie = Other.Cookie;
FormatVersion = Other.FormatVersion;
Guid = Other.Guid;
GeneralSettings = Other.GeneralSettings;
SceneConstants = Other.SceneConstants;
DynamicObjectSettings = Other.DynamicObjectSettings;
VolumetricLightmapSettings = Other.VolumetricLightmapSettings;
PrecomputedVisibilitySettings = Other.PrecomputedVisibilitySettings;
VolumeDistanceFieldSettings = Other.VolumeDistanceFieldSettings;
MeshAreaLightSettings = Other.MeshAreaLightSettings;
AmbientOcclusionSettings = Other.AmbientOcclusionSettings;
ShadowSettings = Other.ShadowSettings;
ImportanceTracingSettings = Other.ImportanceTracingSettings;
PhotonMappingSettings = Other.PhotonMappingSettings;
IrradianceCachingSettings = Other.IrradianceCachingSettings;
MaterialSettings = Other.MaterialSettings;
DebugInput = Other.DebugInput;
/** If true, pad the mappings (shrink the requested size and then pad) */
bPadMappings = Other.bPadMappings;
/** If true, draw a solid border as the padding around mappings */
bDebugPadding = Other.bDebugPadding;
bOnlyCalcDebugTexelMappings = Other.bOnlyCalcDebugTexelMappings;
bColorBordersGreen = Other.bColorBordersGreen;
bUseRandomColors = Other.bUseRandomColors;
bColorByExecutionTime = Other.bColorByExecutionTime;
ExecutionTimeDivisor = Other.ExecutionTimeDivisor;
NumImportanceVolumes = Other.NumImportanceVolumes;
NumCharacterIndirectDetailVolumes = Other.NumCharacterIndirectDetailVolumes;
NumDirectionalLights = Other.NumDirectionalLights;
NumPointLights = Other.NumPointLights;
NumSpotLights = Other.NumSpotLights;
NumSkyLights = Other.NumSkyLights;
NumStaticMeshes = Other.NumStaticMeshes;
NumStaticMeshInstances = Other.NumStaticMeshInstances;
NumFluidSurfaceInstances = Other.NumFluidSurfaceInstances;
NumLandscapeInstances = Other.NumLandscapeInstances;
NumBSPMappings = Other.NumBSPMappings;
NumStaticMeshTextureMappings = Other.NumStaticMeshTextureMappings;
NumFluidSurfaceTextureMappings = Other.NumFluidSurfaceTextureMappings;
NumLandscapeTextureMappings = Other.NumLandscapeTextureMappings;
NumSpeedTreeMappings = Other.NumSpeedTreeMappings;
NumPortals = Other.NumPortals;
}
//----------------------------------------------------------------------------
// Scene class
//----------------------------------------------------------------------------
FScene::FScene() :
EmbreeDevice(NULL),
bVerifyEmbree(false)
{
FMemory::Memzero( (FSceneFileHeader*)this, sizeof(FSceneFileHeader) );
}
FScene::~FScene()
{
#if USE_EMBREE
rtcDeleteDevice(EmbreeDevice);
#endif
}
void FScene::Import( FLightmassImporter& Importer )
{
FSceneFileHeader TempHeader;
// Import into a temp header, since padding in the header overlaps with data members in FScene and ImportData stomps on that padding
Importer.ImportData(&TempHeader);
// Copy header members without modifying padding in FSceneFileHeader
(FSceneFileHeader&)(*this) = TempHeader;
#if USE_EMBREE
if (TempHeader.GeneralSettings.bUseEmbree)
{
EmbreeDevice = rtcNewDevice(NULL);
check(rtcDeviceGetError(EmbreeDevice) == RTC_NO_ERROR);
bVerifyEmbree = TempHeader.GeneralSettings.bVerifyEmbree;
}
#endif
// The assignment above overwrites ImportanceVolumes since FSceneFileHeader has some padding which coincides with ImportanceVolumes
FMemory::Memzero(&ImportanceVolumes, sizeof(ImportanceVolumes));
Importer.SetLevelScale(SceneConstants.StaticLightingLevelScale);
ApplyStaticLightingScale();
FStaticLightingMapping::s_bShowLightmapBorders = bDebugPadding;
TArray<TCHAR>& InstigatorUserNameArray = InstigatorUserName.GetCharArray();
int32 UserNameLen;
Importer.ImportData(&UserNameLen);
Importer.ImportArray(InstigatorUserNameArray, UserNameLen);
InstigatorUserNameArray.Add('\0');
FString PersistentLevelName;
TArray<TCHAR>& PersistentLevelNameArray = PersistentLevelName.GetCharArray();
int32 PersistentLevelNameLen;
Importer.ImportData(&PersistentLevelNameLen);
Importer.ImportArray(PersistentLevelNameArray, PersistentLevelNameLen);
PersistentLevelNameArray.Add('\0');
ImportanceBoundingBox.Init();
for (int32 VolumeIndex = 0; VolumeIndex < NumImportanceVolumes; VolumeIndex++)
{
FBox LMBox;
Importer.ImportData(&LMBox);
ImportanceBoundingBox += LMBox;
ImportanceVolumes.Add(LMBox);
}
if (NumImportanceVolumes == 0)
{
ImportanceBoundingBox = FBox(FVector4(0,0,0), FVector4(0,0,0));
}
for (int32 VolumeIndex = 0; VolumeIndex < NumCharacterIndirectDetailVolumes; VolumeIndex++)
{
FBox LMBox;
Importer.ImportData(&LMBox);
CharacterIndirectDetailVolumes.Add(LMBox);
}
for (int32 PortalIndex = 0; PortalIndex < NumPortals; PortalIndex++)
{
FMatrix LMPortal;
Importer.ImportData(&LMPortal);
Portals.Add(FSphere(LMPortal.GetOrigin(), FVector2D(LMPortal.GetScaleVector().Y, LMPortal.GetScaleVector().Z).Size()));
}
Importer.ImportArray(VisibilityBucketGuids, NumPrecomputedVisibilityBuckets);
int32 NumVisVolumes;
Importer.ImportData(&NumVisVolumes);
PrecomputedVisibilityVolumes.Empty(NumVisVolumes);
PrecomputedVisibilityVolumes.AddZeroed(NumVisVolumes);
for (int32 VolumeIndex = 0; VolumeIndex < NumVisVolumes; VolumeIndex++)
{
FPrecomputedVisibilityVolume& CurrentVolume = PrecomputedVisibilityVolumes[VolumeIndex];
Importer.ImportData(&CurrentVolume.Bounds);
int32 NumPlanes;
Importer.ImportData(&NumPlanes);
Importer.ImportArray(CurrentVolume.Planes, NumPlanes);
}
int32 NumVisOverrideVolumes;
Importer.ImportData(&NumVisOverrideVolumes);
PrecomputedVisibilityOverrideVolumes.Empty(NumVisOverrideVolumes);
PrecomputedVisibilityOverrideVolumes.AddZeroed(NumVisOverrideVolumes);
for (int32 VolumeIndex = 0; VolumeIndex < NumVisOverrideVolumes; VolumeIndex++)
{
FPrecomputedVisibilityOverrideVolume& CurrentVolume = PrecomputedVisibilityOverrideVolumes[VolumeIndex];
Importer.ImportData(&CurrentVolume.Bounds);
int32 NumVisibilityIds;
Importer.ImportData(&NumVisibilityIds);
Importer.ImportArray(CurrentVolume.OverrideVisibilityIds, NumVisibilityIds);
int32 NumInvisibilityIds;
Importer.ImportData(&NumInvisibilityIds);
Importer.ImportArray(CurrentVolume.OverrideInvisibilityIds, NumInvisibilityIds);
}
int32 NumCameraTrackPositions;
Importer.ImportData(&NumCameraTrackPositions);
Importer.ImportArray(CameraTrackPositions, NumCameraTrackPositions);
Importer.ImportArray(VolumetricLightmapTaskGuids, NumVolumetricLightmapTasks);
Importer.ImportObjectArray( DirectionalLights, NumDirectionalLights, Importer.GetLights() );
Importer.ImportObjectArray( PointLights, NumPointLights, Importer.GetLights() );
Importer.ImportObjectArray( SpotLights, NumSpotLights, Importer.GetLights() );
Importer.ImportObjectArray( SkyLights, NumSkyLights, Importer.GetLights() );
Importer.ImportObjectArray( StaticMeshInstances, NumStaticMeshInstances, Importer.GetStaticMeshInstances() );
Importer.ImportObjectArray( FluidMeshInstances, NumFluidSurfaceInstances, Importer.GetFluidMeshInstances() );
Importer.ImportObjectArray( LandscapeMeshInstances, NumLandscapeInstances, Importer.GetLandscapeMeshInstances() );
Importer.ImportObjectArray( BspMappings, NumBSPMappings, Importer.GetBSPMappings() );
Importer.ImportObjectArray( TextureLightingMappings, NumStaticMeshTextureMappings, Importer.GetTextureMappings() );
Importer.ImportObjectArray( FluidMappings, NumFluidSurfaceTextureMappings, Importer.GetFluidMappings() );
Importer.ImportObjectArray( LandscapeMappings, NumLandscapeTextureMappings, Importer.GetLandscapeMappings() );
DebugMapping = FindMappingByGuid(DebugInput.MappingGuid);
if (DebugMapping)
{
const FStaticLightingTextureMapping* TextureMapping = DebugMapping->GetTextureMapping();
// Verify debug input is valid, otherwise there will be an access violation later
if (TextureMapping)
{
check(DebugInput.LocalX >= 0 && DebugInput.LocalX < TextureMapping->CachedSizeX);
check(DebugInput.LocalY >= 0 && DebugInput.LocalY < TextureMapping->CachedSizeY);
check(DebugInput.MappingSizeX == TextureMapping->CachedSizeX && DebugInput.MappingSizeY == TextureMapping->CachedSizeY);
}
}
if (bPadMappings == true)
{
// BSP mappings
for (int32 MappingIdx = 0; MappingIdx < BspMappings.Num(); MappingIdx++)
{
int32 SizeX = BspMappings[MappingIdx].Mapping.SizeX;
int32 SizeY = BspMappings[MappingIdx].Mapping.SizeY;
if (((SizeX - 2) > 0) && ((SizeY - 2) > 0))
{
BspMappings[MappingIdx].Mapping.CachedSizeX = FMath::Clamp<int32>(SizeX, 0, SizeX - 2);
BspMappings[MappingIdx].Mapping.CachedSizeY = FMath::Clamp<int32>(SizeY, 0, SizeY - 2);
BspMappings[MappingIdx].Mapping.bPadded = true;
}
}
// Static mesh texture mappings
for (int32 MappingIdx = 0; MappingIdx < TextureLightingMappings.Num(); MappingIdx++)
{
int32 SizeX = TextureLightingMappings[MappingIdx].SizeX;
int32 SizeY = TextureLightingMappings[MappingIdx].SizeY;
if (((SizeX - 2) > 0) && ((SizeY - 2) > 0))
{
TextureLightingMappings[MappingIdx].CachedSizeX = FMath::Clamp<int32>(SizeX, 0, SizeX - 2);
TextureLightingMappings[MappingIdx].CachedSizeY = FMath::Clamp<int32>(SizeY, 0, SizeY - 2);
TextureLightingMappings[MappingIdx].bPadded = true;
}
}
// Fluid mappings
for (int32 MappingIdx = 0; MappingIdx < FluidMappings.Num(); MappingIdx++)
{
int32 SizeX = FluidMappings[MappingIdx].SizeX;
int32 SizeY = FluidMappings[MappingIdx].SizeY;
if (((SizeX - 2) > 0) && ((SizeY - 2) > 0))
{
FluidMappings[MappingIdx].CachedSizeX = FMath::Clamp<int32>(SizeX, 0, SizeX - 2);
FluidMappings[MappingIdx].CachedSizeY = FMath::Clamp<int32>(SizeY, 0, SizeY - 2);
FluidMappings[MappingIdx].bPadded = true;
}
}
// Landscape mappings - do not get padded by Lightmass...
for (int32 MappingIdx = 0; MappingIdx < LandscapeMappings.Num(); MappingIdx++)
{
LandscapeMappings[MappingIdx].CachedSizeX = LandscapeMappings[MappingIdx].SizeX;
LandscapeMappings[MappingIdx].CachedSizeY = LandscapeMappings[MappingIdx].SizeY;
LandscapeMappings[MappingIdx].bPadded = false;
}
}
if (DebugMapping)
{
const FStaticLightingTextureMapping* TextureMapping = DebugMapping->GetTextureMapping();
// Verify debug input is valid, otherwise there will be an access violation later
if (TextureMapping)
{
check(DebugInput.LocalX >= 0 && DebugInput.LocalX < TextureMapping->CachedSizeX);
check(DebugInput.LocalY >= 0 && DebugInput.LocalY < TextureMapping->CachedSizeY);
check(DebugInput.MappingSizeX == TextureMapping->SizeX && DebugInput.MappingSizeY == TextureMapping->SizeY);
}
}
}
FBoxSphereBounds FScene::GetImportanceBounds() const
{
const FBoxSphereBounds ImportanceBoundSphere(ImportanceBoundingBox);
return ImportanceBoundSphere;
}
const FLight* FScene::FindLightByGuid(const FGuid& InGuid) const
{
for (int32 i = 0; i < DirectionalLights.Num(); i++)
{
if (DirectionalLights[i].Guid == InGuid)
{
return &DirectionalLights[i];
}
}
for (int32 i = 0; i < PointLights.Num(); i++)
{
if (PointLights[i].Guid == InGuid)
{
return &PointLights[i];
}
}
for (int32 i = 0; i < SpotLights.Num(); i++)
{
if (SpotLights[i].Guid == InGuid)
{
return &SpotLights[i];
}
}
for (int32 i = 0; i < SkyLights.Num(); i++)
{
if (SkyLights[i].Guid == InGuid)
{
return &SkyLights[i];
}
}
return NULL;
}
/** Searches through all mapping arrays for the mapping matching FindGuid. */
const FStaticLightingMapping* FScene::FindMappingByGuid(FGuid FindGuid) const
{
// Note: FindGuid can be all 0's and still be valid due to deterministic lighting overriding the Guid
for (int32 i = 0; i < BspMappings.Num(); i++)
{
if (BspMappings[i].Mapping.Guid == FindGuid)
{
return &BspMappings[i].Mapping;
}
}
for (int32 i = 0; i < TextureLightingMappings.Num(); i++)
{
if (TextureLightingMappings[i].Guid == FindGuid)
{
return &TextureLightingMappings[i];
}
}
for (int32 i = 0; i < FluidMappings.Num(); i++)
{
if (FluidMappings[i].Guid == FindGuid)
{
return &FluidMappings[i];
}
}
for (int32 i = 0; i < LandscapeMappings.Num(); i++)
{
if (LandscapeMappings[i].Guid == FindGuid)
{
return &LandscapeMappings[i];
}
}
return NULL;
}
/** Returns true if the specified position is inside any of the importance volumes. */
bool FScene::IsPointInImportanceVolume(const FVector4& Position, float Tolerance) const
{
for (int32 VolumeIndex = 0; VolumeIndex < ImportanceVolumes.Num(); VolumeIndex++)
{
FBox Volume = ImportanceVolumes[VolumeIndex];
if (Position.X + Tolerance > Volume.Min.X && Position.X - Tolerance < Volume.Max.X
&& Position.Y + Tolerance > Volume.Min.Y && Position.Y - Tolerance < Volume.Max.Y
&& Position.Z + Tolerance > Volume.Min.Z && Position.Z - Tolerance < Volume.Max.Z)
{
return true;
}
}
return false;
}
bool FScene::IsBoxInImportanceVolume(const FBox& QueryBox) const
{
for (int32 VolumeIndex = 0; VolumeIndex < ImportanceVolumes.Num(); VolumeIndex++)
{
FBox Volume = ImportanceVolumes[VolumeIndex];
if (Volume.Intersect(QueryBox))
{
return true;
}
}
return false;
}
/** Returns true if the specified position is inside any of the visibility volumes. */
bool FScene::IsPointInVisibilityVolume(const FVector4& Position) const
{
for (int32 VolumeIndex = 0; VolumeIndex < PrecomputedVisibilityVolumes.Num(); VolumeIndex++)
{
const FPrecomputedVisibilityVolume& Volume = PrecomputedVisibilityVolumes[VolumeIndex];
bool bInsideAllPlanes = true;
for (int32 PlaneIndex = 0; PlaneIndex < Volume.Planes.Num() && bInsideAllPlanes; PlaneIndex++)
{
const FPlane& Plane = Volume.Planes[PlaneIndex];
bInsideAllPlanes = bInsideAllPlanes && Plane.PlaneDot(Position) < 0.0f;
}
if (bInsideAllPlanes)
{
return true;
}
}
return false;
}
bool FScene::DoesBoxIntersectVisibilityVolume(const FBox& TestBounds) const
{
for (int32 VolumeIndex = 0; VolumeIndex < PrecomputedVisibilityVolumes.Num(); VolumeIndex++)
{
const FPrecomputedVisibilityVolume& Volume = PrecomputedVisibilityVolumes[VolumeIndex];
if (Volume.Bounds.Intersect(TestBounds))
{
return true;
}
}
return false;
}
/** Returns accumulated bounds from all the visibility volumes. */
FBox FScene::GetVisibilityVolumeBounds() const
{
FBox Bounds(ForceInit);
for (int32 VolumeIndex = 0; VolumeIndex < PrecomputedVisibilityVolumes.Num(); VolumeIndex++)
{
const FPrecomputedVisibilityVolume& Volume = PrecomputedVisibilityVolumes[VolumeIndex];
Bounds += Volume.Bounds;
}
if (PrecomputedVisibilityVolumes.Num() > 0)
{
FVector4 DoubleExtent = Bounds.GetExtent() * 2;
DoubleExtent.X = DoubleExtent.X - FMath::Fmod(DoubleExtent.X, PrecomputedVisibilitySettings.CellSize) + PrecomputedVisibilitySettings.CellSize;
DoubleExtent.Y = DoubleExtent.Y - FMath::Fmod(DoubleExtent.Y, PrecomputedVisibilitySettings.CellSize) + PrecomputedVisibilitySettings.CellSize;
// Round the max up to the next cell boundary
Bounds.Max = Bounds.Min + DoubleExtent;
return Bounds;
}
else
{
return FBox(FVector4(0,0,0),FVector4(0,0,0));
}
}
/** Applies GeneralSettings.StaticLightingLevelScale to all scale dependent settings. */
void FScene::ApplyStaticLightingScale()
{
// Scale world space distances directly
SceneConstants.VisibilityRayOffsetDistance *= SceneConstants.StaticLightingLevelScale;
SceneConstants.VisibilityNormalOffsetDistance *= SceneConstants.StaticLightingLevelScale;
SceneConstants.SmallestTexelRadius *= SceneConstants.StaticLightingLevelScale;
MeshAreaLightSettings.MeshAreaLightSimplifyCornerDistanceThreshold *= SceneConstants.StaticLightingLevelScale;
MeshAreaLightSettings.MeshAreaLightGeneratedDynamicLightSurfaceOffset *= SceneConstants.StaticLightingLevelScale;
DynamicObjectSettings.FirstSurfaceSampleLayerHeight *= SceneConstants.StaticLightingLevelScale;
DynamicObjectSettings.SurfaceLightSampleSpacing *= SceneConstants.StaticLightingLevelScale;
DynamicObjectSettings.SurfaceSampleLayerHeightSpacing *= SceneConstants.StaticLightingLevelScale;
DynamicObjectSettings.DetailVolumeSampleSpacing *= SceneConstants.StaticLightingLevelScale;
DynamicObjectSettings.VolumeLightSampleSpacing *= SceneConstants.StaticLightingLevelScale;
VolumeDistanceFieldSettings.VoxelSize *= SceneConstants.StaticLightingLevelScale;
VolumeDistanceFieldSettings.VolumeMaxDistance *= SceneConstants.StaticLightingLevelScale;
ShadowSettings.MaxTransitionDistanceWorldSpace *= SceneConstants.StaticLightingLevelScale;
ShadowSettings.StaticShadowDepthMapTransitionSampleDistanceX *= SceneConstants.StaticLightingLevelScale;
ShadowSettings.StaticShadowDepthMapTransitionSampleDistanceY *= SceneConstants.StaticLightingLevelScale;
IrradianceCachingSettings.RecordRadiusScale *= SceneConstants.StaticLightingLevelScale;
IrradianceCachingSettings.MaxRecordRadius *= SceneConstants.StaticLightingLevelScale;
// Photon mapping does not scale down properly, so this is disabled
/*
PhotonMappingSettings.IndirectPhotonEmitDiskRadius *= SceneConstants.StaticLightingLevelScale;
PhotonMappingSettings.MaxImportancePhotonSearchDistance *= SceneConstants.StaticLightingLevelScale;
PhotonMappingSettings.MinImportancePhotonSearchDistance *= SceneConstants.StaticLightingLevelScale;
// Scale surface densities in world units
const float ScaleSquared = SceneConstants.StaticLightingLevelScale * SceneConstants.StaticLightingLevelScale;
PhotonMappingSettings.DirectPhotonDensity /= ScaleSquared;
PhotonMappingSettings.DirectIrradiancePhotonDensity /= ScaleSquared;
PhotonMappingSettings.DirectPhotonSearchDistance *= SceneConstants.StaticLightingLevelScale;
PhotonMappingSettings.IndirectPhotonPathDensity /= ScaleSquared;
PhotonMappingSettings.IndirectPhotonDensity /= ScaleSquared;
PhotonMappingSettings.IndirectIrradiancePhotonDensity /= ScaleSquared;
PhotonMappingSettings.IndirectPhotonSearchDistance *= SceneConstants.StaticLightingLevelScale;
*/
}
//----------------------------------------------------------------------------
// Light base class
//----------------------------------------------------------------------------
void FLight::Import( FLightmassImporter& Importer )
{
Importer.ImportData( (FLightData*)this );
// The read above stomps on CachedLightSurfaceSamples since that memory is padding in FLightData
FMemory::Memzero(&CachedLightSurfaceSamples, sizeof(CachedLightSurfaceSamples));
// Precalculate the light's indirect color
IndirectColor = FLinearColorUtils::AdjustSaturation(FLinearColor(Color), IndirectLightingSaturation) * IndirectLightingScale;
}
/**
* Tests whether the light affects the given bounding volume.
* @param Bounds - The bounding volume to test.
* @return True if the light affects the bounding volume
*/
bool FLight::AffectsBounds(const FBoxSphereBounds& Bounds) const
{
return true;
}
FSphere FLight::GetBoundingSphere() const
{
// Directional lights will have a radius of WORLD_MAX
return FSphere(FVector(0, 0, 0), (float)WORLD_MAX);
}
/**
* Computes the intensity of the direct lighting from this light on a specific point.
*/
FLinearColor FLight::GetDirectIntensity(const FVector4& Point, bool bCalculateForIndirectLighting) const
{
// light profile (IES)
float LightProfileAttenuation;
{
FVector4 NegLightVector = (Position - Point).GetSafeNormal();
LightProfileAttenuation = ComputeLightProfileMultiplier(Dot3(NegLightVector, Direction));
}
if (bCalculateForIndirectLighting)
{
return IndirectColor * (LightProfileAttenuation * Brightness);
}
else
{
return FLinearColor(Color) * (LightProfileAttenuation * Brightness);
}
}
/** Generates and caches samples on the light's surface. */
void FLight::CacheSurfaceSamples(int32 BounceIndex, int32 NumSamples, int32 NumPenumbraSamples, FLMRandomStream& RandomStream)
{
checkSlow(NumSamples > 0);
// Assuming bounce number starts from 0 and increments each time
//@todo - remove the slack
CachedLightSurfaceSamples.AddZeroed(1);
// Allocate for both normal and penumbra even if there aren't any penumbra samples, so we can return an empty array from GetCachedSurfaceSamples
CachedLightSurfaceSamples[BounceIndex].AddZeroed(2);
const int32 NumPenumbraTypes = NumPenumbraSamples > 0 ? 2 : 1;
for (int32 PenumbraType = 0; PenumbraType < NumPenumbraTypes; PenumbraType++)
{
const int32 CurrentNumSamples = PenumbraType == 0 ? NumSamples : NumPenumbraSamples;
CachedLightSurfaceSamples[BounceIndex][PenumbraType].Empty(CurrentNumSamples);
for (int32 SampleIndex = 0; SampleIndex < CurrentNumSamples; SampleIndex++)
{
FLightSurfaceSample LightSample;
SampleLightSurface(RandomStream, LightSample);
CachedLightSurfaceSamples[BounceIndex][PenumbraType].Add(LightSample);
}
}
}
/** Retrieves the array of cached light surface samples. */
const TArray<FLightSurfaceSample>& FLight::GetCachedSurfaceSamples(int32 BounceIndex, bool bPenumbra) const
{
return CachedLightSurfaceSamples[BounceIndex][bPenumbra];
}
//----------------------------------------------------------------------------
// Directional light class
//----------------------------------------------------------------------------
void FDirectionalLight::Import( FLightmassImporter& Importer )
{
FLight::Import( Importer );
Importer.ImportData( (FDirectionalLightData*)this );
}
void FDirectionalLight::Initialize(
const FBoxSphereBounds& InSceneBounds,
bool bInEmitPhotonsOutsideImportanceVolume,
const FBoxSphereBounds& InImportanceBounds,
float InIndirectDiskRadius,
int32 InGridSize,
float InDirectPhotonDensity,
float InOutsideImportanceVolumeDensity)
{
GenerateCoordinateSystem(Direction, XAxis, YAxis);
SceneBounds = InSceneBounds;
ImportanceBounds = InImportanceBounds;
// Vector through the scene bound's origin, along the direction of the light
const FVector4 SceneAxis = (SceneBounds.Origin + Direction * SceneBounds.SphereRadius) - (SceneBounds.Origin - Direction * SceneBounds.SphereRadius);
const float SceneAxisLength = SceneBounds.SphereRadius * 2.0f;
const FVector4 DirectionalLightOriginToImportanceOrigin = ImportanceBounds.Origin - (SceneBounds.Origin - Direction * SceneBounds.SphereRadius);
// Find the closest point on the scene's axis to the importance volume's origin by projecting DirectionalLightOriginToImportanceOrigin onto SceneAxis.
// This gives the offset in the directional light's disk from the scene bound's origin.
const FVector4 ClosestPositionOnAxis = Dot3(SceneAxis, DirectionalLightOriginToImportanceOrigin) / (SceneAxisLength * SceneAxisLength) * SceneAxis + SceneBounds.Origin - Direction * SceneBounds.SphereRadius;
// Find the disk offset from the world space origin and transform into the [-1,1] space of the directional light's disk, still in 3d.
const FVector4 DiskOffset = (ImportanceBounds.Origin - ClosestPositionOnAxis) / SceneBounds.SphereRadius;
const float DebugLength = (ImportanceBounds.Origin - ClosestPositionOnAxis).Size();
const float DebugDot = ((ImportanceBounds.Origin - ClosestPositionOnAxis) / DebugLength) | Direction;
// Verify that ImportanceBounds.Origin is either on the scene's axis or the vector between it and ClosestPositionOnAxis is orthogonal to the light's direction
//checkSlow(DebugLength < KINDA_SMALL_NUMBER * 10.0f || FMath::Abs(DebugDot) < DELTA * 10.0f);
// Decompose DiskOffset into it's corresponding parts along XAxis and YAxis
const FVector4 XAxisProjection = Dot3(XAxis, DiskOffset) * XAxis;
const FVector4 YAxisProjection = Dot3(YAxis, DiskOffset) * YAxis;
ImportanceDiskOrigin = FVector2D(Dot3(XAxisProjection, XAxis), Dot3(YAxisProjection, YAxis));
// Transform the importance volume's radius into the [-1,1] space of the directional light's disk
LightSpaceImportanceDiskRadius = ImportanceBounds.SphereRadius / SceneBounds.SphereRadius;
const FVector4 DebugPosition = (ImportanceDiskOrigin.X * XAxis + ImportanceDiskOrigin.Y * YAxis);
const float DebugLength2 = (DiskOffset - DebugPosition).Size3();
// Verify that DiskOffset was decomposed correctly by reconstructing it
checkSlow(DebugLength2 < KINDA_SMALL_NUMBER);
IndirectDiskRadius = InIndirectDiskRadius;
GridSize = InGridSize;
OutsideImportanceVolumeDensity = InOutsideImportanceVolumeDensity;
const float ImportanceDiskAreaMillions = (float)PI * FMath::Square(ImportanceBounds.SphereRadius) / 1000000.0f;
checkSlow(SceneBounds.SphereRadius >= ImportanceBounds.SphereRadius);
const float OutsideImportanceDiskAreaMillions = (float)PI * (FMath::Square(SceneBounds.SphereRadius) - FMath::Square(ImportanceBounds.SphereRadius)) / 1000000.0f;
// Calculate the probability that a generated sample will be in the importance volume,
// Based on the fraction of total photons that should be gathered in the importance volume.
ImportanceBoundsSampleProbability = ImportanceDiskAreaMillions * InDirectPhotonDensity
/ (ImportanceDiskAreaMillions * InDirectPhotonDensity + OutsideImportanceDiskAreaMillions * OutsideImportanceVolumeDensity);
// Calculate the size of the directional light source using Tangent(LightSourceAngle) = LightSourceRadius / DistanceToReceiver
LightSourceRadius = 2.0f * SceneBounds.SphereRadius * FMath::Tan(LightSourceAngle);
if (!bInEmitPhotonsOutsideImportanceVolume && ImportanceBounds.SphereRadius > DELTA)
{
// Always sample inside the importance volume
ImportanceBoundsSampleProbability = 1.0f;
OutsideImportanceVolumeDensity = 0.0f;
}
}
/** Returns the number of direct photons to gather required by this light. */
int32 FDirectionalLight::GetNumDirectPhotons(float DirectPhotonDensity) const
{
int32 NumDirectPhotons = 0;
if (ImportanceBounds.SphereRadius > DELTA)
{
// The importance volume is valid, so only gather enough direct photons to meet DirectPhotonDensity inside the importance volume
const float ImportanceDiskAreaMillions = (float)PI * FMath::Square(ImportanceBounds.SphereRadius) / 1000000.0f;
checkSlow(SceneBounds.SphereRadius > ImportanceBounds.SphereRadius);
const float OutsideImportanceDiskAreaMillions = (float)PI * (FMath::Square(SceneBounds.SphereRadius) - FMath::Square(ImportanceBounds.SphereRadius)) / 1000000.0f;
NumDirectPhotons = FMath::TruncToInt(ImportanceDiskAreaMillions * DirectPhotonDensity + OutsideImportanceDiskAreaMillions * OutsideImportanceVolumeDensity);
}
else
{
// Gather enough photons to meet DirectPhotonDensity everywhere in the scene
const float SceneDiskAreaMillions = (float)PI * FMath::Square(SceneBounds.SphereRadius) / 1000000.0f;
NumDirectPhotons = FMath::TruncToInt(SceneDiskAreaMillions * DirectPhotonDensity);
}
return NumDirectPhotons == appTruncErrorCode ? INT_MAX : NumDirectPhotons;
}
/** Generates a direction sample from the light's domain */
void FDirectionalLight::SampleDirection(FLMRandomStream& RandomStream, FLightRay& SampleRay, FVector4& LightSourceNormal, FVector2D& LightSurfacePosition, float& RayPDF, FLinearColor& Power) const
{
FVector4 DiskPosition3D;
// If the importance volume is valid, generate samples in the importance volume with a probability of ImportanceBoundsSampleProbability
if (ImportanceBounds.SphereRadius > DELTA
&& RandomStream.GetFraction() < ImportanceBoundsSampleProbability)
{
const FVector2D DiskPosition2D = GetUniformUnitDiskPosition(RandomStream);
LightSurfacePosition = ImportanceDiskOrigin + DiskPosition2D * LightSpaceImportanceDiskRadius;
DiskPosition3D = SceneBounds.Origin + SceneBounds.SphereRadius * (LightSurfacePosition.X * XAxis + LightSurfacePosition.Y * YAxis);
RayPDF = ImportanceBoundsSampleProbability / ((float)PI * FMath::Square(ImportanceBounds.SphereRadius));
}
else
{
float DistanceToImportanceDiskOriginSq;
do
{
LightSurfacePosition = GetUniformUnitDiskPosition(RandomStream);
DistanceToImportanceDiskOriginSq = (LightSurfacePosition - ImportanceDiskOrigin).SizeSquared();
}
// Use rejection sampling to prevent any samples from being generated inside the importance volume
while (DistanceToImportanceDiskOriginSq < FMath::Square(LightSpaceImportanceDiskRadius));
// Create the ray using a disk centered at the scene's origin, whose radius is the size of the scene
DiskPosition3D = SceneBounds.Origin + SceneBounds.SphereRadius * (LightSurfacePosition.X * XAxis + LightSurfacePosition.Y * YAxis);
// Calculate the probability of generating a uniform disk sample in the scene, minus the importance volume's disk
RayPDF = (1.0f - ImportanceBoundsSampleProbability) / ((float)PI * (FMath::Square(SceneBounds.SphereRadius) - FMath::Square(ImportanceBounds.SphereRadius)));
}
//@todo - take light source radius into account
SampleRay = FLightRay(
DiskPosition3D - SceneBounds.SphereRadius * Direction,
DiskPosition3D + SceneBounds.SphereRadius * Direction,
NULL,
this
);
LightSourceNormal = Direction;
checkSlow(RayPDF > 0);
Power = IndirectColor * Brightness;
}
/** Gives the light an opportunity to precalculate information about the indirect path rays that will be used to generate new directions. */
void FDirectionalLight::CachePathRays(const TArray<FIndirectPathRay>& IndirectPathRays)
{
if (IndirectPathRays.Num() == 0)
{
return;
}
// The indirect disk radius in the [-1, 1] space of the directional light's disk
const float LightSpaceIndirectDiskRadius = IndirectDiskRadius / SceneBounds.SphereRadius;
// Find the minimum and maximum position in the [-1, 1] space of the directional light's disk
// That a position can be generated from in FDirectionalLight::SampleDirection
FVector2D GridMin(1.0f, 1.0f);
FVector2D GridMax(-1.0f, -1.0f);
for (int32 RayIndex = 0; RayIndex < IndirectPathRays.Num(); RayIndex++)
{
const FIndirectPathRay& CurrentRay = IndirectPathRays[RayIndex];
GridMin.X = FMath::Min(GridMin.X, CurrentRay.LightSurfacePosition.X - LightSpaceIndirectDiskRadius);
GridMin.Y = FMath::Min(GridMin.Y, CurrentRay.LightSurfacePosition.Y - LightSpaceIndirectDiskRadius);
GridMax.X = FMath::Max(GridMax.X, CurrentRay.LightSurfacePosition.X + LightSpaceIndirectDiskRadius);
GridMax.Y = FMath::Max(GridMax.Y, CurrentRay.LightSurfacePosition.Y + LightSpaceIndirectDiskRadius);
}
GridMin.X = FMath::Min(GridMin.X, 1.0f);
GridMin.Y = FMath::Min(GridMin.Y, 1.0f);
GridMax.X = FMath::Max(GridMax.X, -1.0f);
GridMax.Y = FMath::Max(GridMax.Y, -1.0f);
checkSlow(GridMax > GridMin);
const FVector2D GridExtent2D = 0.5f * (GridMax - GridMin);
// Keep the grid space square to simplify logic
GridExtent = FMath::Max(GridExtent2D.X, GridExtent2D.Y);
GridCenter = 0.5f * (GridMin + GridMax);
// Allocate the grid
PathRayGrid.Empty(GridSize * GridSize);
PathRayGrid.AddZeroed(GridSize * GridSize);
const float GridSpaceIndirectDiskRadius = IndirectDiskRadius * GridExtent / SceneBounds.SphereRadius;
const float InvGridSize = 1.0f / (float)GridSize;
// For each grid cell, store the indices into IndirectPathRays of the path rays that affect the grid cell
for (int32 Y = 0; Y < GridSize; Y++)
{
for (int32 X = 0; X < GridSize; X++)
{
// Center and Extent of the cell in the [0, 1] grid space
const FVector2D BoxCenter((X + .5f) * InvGridSize, (Y + .5f) * InvGridSize);
const float BoxExtent = .5f * InvGridSize;
// Corners of the cell
const int32 NumBoxCorners = 4;
FVector2D BoxCorners[NumBoxCorners];
BoxCorners[0] = BoxCenter + FVector2D(BoxExtent, BoxExtent);
BoxCorners[1] = BoxCenter + FVector2D(-BoxExtent, BoxExtent);
BoxCorners[2] = BoxCenter + FVector2D(BoxExtent, -BoxExtent);
BoxCorners[3] = BoxCenter + FVector2D(-BoxExtent, -BoxExtent);
// Calculate the world space positions of each corner of the cell
FVector4 WorldBoxCorners[NumBoxCorners];
for (int32 i = 0; i < NumBoxCorners; i++)
{
// Transform the cell corner from [0, 1] grid space to [-1, 1] in the directional light's disk
const FVector2D LightBoxCorner(2.0f * GridExtent * BoxCorners[i] + GridCenter - FVector2D(GridExtent, GridExtent));
// Calculate the world position of the cell corner
WorldBoxCorners[i] = SceneBounds.Origin + SceneBounds.SphereRadius * (LightBoxCorner.X * XAxis + LightBoxCorner.Y * YAxis) - SceneBounds.SphereRadius * Direction;
}
// Calculate the world space distance along the diagonal of the box
const float DiagonalBoxDistance = (WorldBoxCorners[0] - WorldBoxCorners[3]).Size3();
const float DiagonalBoxDistanceAndRadiusSquared = FMath::Square(DiagonalBoxDistance + IndirectDiskRadius);
for (int32 RayIndex = 0; RayIndex < IndirectPathRays.Num(); RayIndex++)
{
const FIndirectPathRay& CurrentRay = IndirectPathRays[RayIndex];
bool bAnyCornerInCircle = false;
bool bWithinDiagonalDistance = true;
// If any of the box corners lie within the disk around the current path ray, then they intersect
for (int32 i = 0; i < NumBoxCorners; i++)
{
const float SampleDistanceSquared = (WorldBoxCorners[i] - CurrentRay.Start).SizeSquared3();
bWithinDiagonalDistance = bWithinDiagonalDistance && SampleDistanceSquared < DiagonalBoxDistanceAndRadiusSquared;
if (SampleDistanceSquared < IndirectDiskRadius * IndirectDiskRadius)
{
bAnyCornerInCircle = true;
PathRayGrid[Y * GridSize + X].Add(RayIndex);
break;
}
}
// If none of the box corners lie within the disk but the disk is less than the diagonal + the disk radius, treat them as intersecting.
// This is a conservative test, they might not actually intersect.
if (!bAnyCornerInCircle && bWithinDiagonalDistance)
{
PathRayGrid[Y * GridSize + X].Add(RayIndex);
}
}
}
}
}
/** Generates a direction sample from the light based on the given rays */
void FDirectionalLight::SampleDirection(
const TArray<FIndirectPathRay>& IndirectPathRays,
FLMRandomStream& RandomStream,
FLightRay& SampleRay,
float& RayPDF,
FLinearColor& Power) const
{
checkSlow(IndirectPathRays.Num() > 0);
const FVector2D DiskPosition2D = GetUniformUnitDiskPosition(RandomStream);
const int32 RayIndex = FMath::TruncToInt(RandomStream.GetFraction() * IndirectPathRays.Num());
checkSlow(RayIndex >= 0 && RayIndex < IndirectPathRays.Num());
// Create the ray using a disk centered at the scene's origin, whose radius is the size of the scene
const FVector4 DiskPosition3D = IndirectPathRays[RayIndex].Start + IndirectDiskRadius * (DiskPosition2D.X * XAxis + DiskPosition2D.Y * YAxis);
SampleRay = FLightRay(
DiskPosition3D,
DiskPosition3D + 2.0f * SceneBounds.SphereRadius * Direction,
NULL,
this
);
const float DiskPDF = 1.0f / ((float)PI * IndirectDiskRadius * IndirectDiskRadius);
const float LightSpaceIndirectDiskRadius = IndirectDiskRadius / SceneBounds.SphereRadius;
FVector2D SampleLightSurfacePosition;
// Clamp the generated position to lie within the [-1, 1] space of the directional light's disk
SampleLightSurfacePosition.X = FMath::Clamp(DiskPosition2D.X * LightSpaceIndirectDiskRadius + IndirectPathRays[RayIndex].LightSurfacePosition.X, -1.0f, 1.0f - DELTA);
SampleLightSurfacePosition.Y = FMath::Clamp(DiskPosition2D.Y * LightSpaceIndirectDiskRadius + IndirectPathRays[RayIndex].LightSurfacePosition.Y, -1.0f, 1.0f - DELTA);
checkSlow(SampleLightSurfacePosition.X >= GridCenter.X - GridExtent && SampleLightSurfacePosition.X <= GridCenter.X + GridExtent);
checkSlow(SampleLightSurfacePosition.Y >= GridCenter.Y - GridExtent && SampleLightSurfacePosition.Y <= GridCenter.Y + GridExtent);
// Calculate the cell indices that the generated position falls into
const int32 CellX = FMath::Clamp(FMath::TruncToInt(GridSize * (SampleLightSurfacePosition.X - GridCenter.X + GridExtent) / (2.0f * GridExtent)), 0, GridSize - 1);
const int32 CellY = FMath::Clamp(FMath::TruncToInt(GridSize * (SampleLightSurfacePosition.Y - GridCenter.Y + GridExtent) / (2.0f * GridExtent)), 0, GridSize - 1);
const TArray<int32>& CurrentGridCell = PathRayGrid[CellY * GridSize + CellX];
// The cell containing the sample position must contain at least the index of the path used to generate this sample position
checkSlow(CurrentGridCell.Num() > 0);
// Initialize the total PDF to the PDF contribution from the path used to generate this sample position
RayPDF = DiskPDF;
// Calculate the probability that this sample was chosen by other paths
// Iterating only over paths that affect the sample position's cell as an optimization
for (int32 OtherRayIndex = 0; OtherRayIndex < CurrentGridCell.Num(); OtherRayIndex++)
{
const int32 CurrentPathIndex = CurrentGridCell[OtherRayIndex];
const FIndirectPathRay& CurrentPath = IndirectPathRays[CurrentPathIndex];
const float SampleDistanceSquared = (DiskPosition3D - CurrentPath.Start).SizeSquared3();
// Accumulate the disk probability for all the disks which contain the sample position
if (SampleDistanceSquared < IndirectDiskRadius * IndirectDiskRadius
// The path that was used to generate the sample has already been counted
&& CurrentPathIndex != RayIndex)
{
RayPDF += DiskPDF;
}
}
RayPDF /= IndirectPathRays.Num();
check(RayPDF > 0);
Power = IndirectColor * Brightness;
}
/** Returns the light's radiant power. */
float FDirectionalLight::Power() const
{
const float EffectiveRadius = ImportanceBounds.SphereRadius > DELTA ? ImportanceBounds.SphereRadius : SceneBounds.SphereRadius;
const FLinearColor LightPower = GetDirectIntensity(FVector4(0,0,0), false) * IndirectLightingScale * (float)PI * EffectiveRadius * EffectiveRadius;
return FLinearColorUtils::LinearRGBToXYZ(LightPower).G;
}
/** Validates a surface sample given the position that sample is affecting. */
void FDirectionalLight::ValidateSurfaceSample(const FVector4& Point, FLightSurfaceSample& Sample) const
{
// Directional light samples are generated on a disk the size of the light source radius, centered on the origin
// Move the disk to the other side of the scene along the light's reverse direction
Sample.Position += Point - Direction * 2.0f * SceneBounds.SphereRadius;
}
/** Gets a single position which represents the center of the area light source from the ReceivingPosition's point of view. */
FVector4 FDirectionalLight::LightCenterPosition(const FVector4& ReceivingPosition, const FVector4& ReceivingNormal) const
{
return ReceivingPosition - Direction * 2.0f * SceneBounds.SphereRadius;
}
/** Returns true if all parts of the light are behind the surface being tested. */
bool FDirectionalLight::BehindSurface(const FVector4& TrianglePoint, const FVector4& TriangleNormal) const
{
const float NormalDotLight = Dot3(TriangleNormal, FDirectionalLight::GetDirectLightingDirection(TrianglePoint, TriangleNormal));
return NormalDotLight < 0.0f;
}
/** Gets a single direction to use for direct lighting that is representative of the whole area light. */
FVector4 FDirectionalLight::GetDirectLightingDirection(const FVector4& Point, const FVector4& PointNormal) const
{
// The position on the directional light surface disk that will first be visible to a triangle rotating toward the light
const FVector4 FirstVisibleLightPoint = Point - Direction * 2.0f * SceneBounds.SphereRadius + PointNormal * LightSourceRadius;
return FirstVisibleLightPoint - Point;
}
/** Generates a sample on the light's surface. */
void FDirectionalLight::SampleLightSurface(FLMRandomStream& RandomStream, FLightSurfaceSample& Sample) const
{
// Create samples on a disk the size of the light source radius, centered at the origin
// This disk will be moved based on the receiver position
//@todo - stratify
Sample.DiskPosition = GetUniformUnitDiskPosition(RandomStream);
Sample.Position = LightSourceRadius * (Sample.DiskPosition.X * XAxis + Sample.DiskPosition.Y * YAxis);
Sample.Normal = Direction;
Sample.PDF = 1.0f / ((float)PI * LightSourceRadius * LightSourceRadius);
}
//----------------------------------------------------------------------------
// Point light class
//----------------------------------------------------------------------------
void FPointLight::Import( FLightmassImporter& Importer )
{
FLight::Import( Importer );
Importer.ImportData( (FPointLightData*)this );
}
void FPointLight::Initialize(float InIndirectPhotonEmitConeAngle)
{
CosIndirectPhotonEmitConeAngle = FMath::Cos(InIndirectPhotonEmitConeAngle);
}
/** Returns the number of direct photons to gather required by this light. */
int32 FPointLight::GetNumDirectPhotons(float DirectPhotonDensity) const
{
// Gather enough photons to meet DirectPhotonDensity at the influence radius of the point light.
const float InfluenceSphereSurfaceAreaMillions = 4.0f * (float)PI * FMath::Square(Radius) / 1000000.0f;
const int32 NumDirectPhotons = FMath::TruncToInt(InfluenceSphereSurfaceAreaMillions * DirectPhotonDensity);
return NumDirectPhotons == appTruncErrorCode ? INT_MAX : NumDirectPhotons;
}
/**
* Tests whether the light affects the given bounding volume.
* @param Bounds - The bounding volume to test.
* @return True if the light affects the bounding volume
*/
bool FPointLight::AffectsBounds(const FBoxSphereBounds& Bounds) const
{
if((Bounds.Origin - Position).SizeSquared() > FMath::Square(Radius + Bounds.SphereRadius))
{
return false;
}
if(!FLight::AffectsBounds(Bounds))
{
return false;
}
return true;
}
/**
* Computes the intensity of the direct lighting from this light on a specific point.
*/
FLinearColor FPointLight::GetDirectIntensity(const FVector4& Point, bool bCalculateForIndirectLighting) const
{
if (LightFlags & GI_LIGHT_INVERSE_SQUARED)
{
FVector4 ToLight = Position - Point;
float DistanceSqr = ToLight.SizeSquared3();
float DistanceAttenuation = 0.0f;
if( LightSourceLength > 0.0f )
{
// Line segment irradiance
FVector4 L01 = Direction * LightSourceLength;
FVector4 L0 = ToLight - 0.5f * L01;
FVector4 L1 = ToLight + 0.5f * L01;
float LengthL0 = L0.Size3();
float LengthL1 = L1.Size3();
DistanceAttenuation = 1.0f / ( ( LengthL0 * LengthL1 + Dot3( L0, L1 ) ) * 0.5f + 1.0f );
DistanceAttenuation *= 0.5 * ( L0 / LengthL0 + L1 / LengthL1 ).Size3();
}
else
{
// Sphere irradiance (technically just 1/d^2 but this avoids inf)
DistanceAttenuation = 1.0f / ( DistanceSqr + 1.0f );
}
// lumens
DistanceAttenuation *= 16.0f;
float LightRadiusMask = FMath::Square(FMath::Max(0.0f, 1.0f - FMath::Square(DistanceSqr / (Radius * Radius))));
DistanceAttenuation *= LightRadiusMask;
return FLight::GetDirectIntensity(Point, bCalculateForIndirectLighting) * DistanceAttenuation;
}
else
{
float RadialAttenuation = FMath::Pow(FMath::Max(1.0f - ((Position - Point) / Radius).SizeSquared3(), 0.0f), FalloffExponent);
return FLight::GetDirectIntensity(Point, bCalculateForIndirectLighting) * RadialAttenuation;
}
}
/** Returns an intensity scale based on the receiving point. */
float FPointLight::CustomAttenuation(const FVector4& Point, FLMRandomStream& RandomStream) const
{
// Remove the physical attenuation, then attenuation using Unreal point light radial falloff
const float PointDistanceSquared = (Position - Point).SizeSquared3();
const float PhysicalAttenuation = 1.0f / ( PointDistanceSquared + 0.0001f );
float UnrealAttenuation = 1.0f;
if( LightFlags & GI_LIGHT_INVERSE_SQUARED )
{
const float LightRadiusMask = FMath::Square( FMath::Max( 0.0f, 1.0f - FMath::Square( PointDistanceSquared / (Radius * Radius) ) ) );
UnrealAttenuation = 16.0f * PhysicalAttenuation * LightRadiusMask;
}
else
{
UnrealAttenuation = FMath::Pow(FMath::Max(1.0f - ((Position - Point) / Radius).SizeSquared3(), 0.0f), FalloffExponent);
}
// light profile (IES)
{
FVector4 NegLightVector = (Position - Point).GetSafeNormal();
UnrealAttenuation *= ComputeLightProfileMultiplier(Dot3(NegLightVector, Direction));
}
// Thin out photons near the light source.
// This is partly an optimization since the photon density near light sources doesn't need to be high, and the natural 1 / R^2 density is overkill,
// But this also improves quality since we are doing a nearest N photon neighbor search when calculating irradiance.
// If the photon map has a high density of low power photons near light sources,
// Combined with sparse, high power photons from other light sources (directional lights for example), the result will be very splotchy.
const float FullProbabilityDistance = .5f * Radius;
const float DepositProbability = FMath::Clamp(PointDistanceSquared / (FullProbabilityDistance * FullProbabilityDistance), 0.0f, 1.0f);
if (RandomStream.GetFraction() < DepositProbability)
{
// Re-weight the photon since it survived the thinning based on the probability of being deposited
return UnrealAttenuation / (PhysicalAttenuation * DepositProbability);
}
else
{
return 0.0f;
}
}
// Fudge factor to get point light photon intensities to match direct lighting more closely.
static const float PointLightIntensityScale = 1.5f;
/** Generates a direction sample from the light's domain */
void FPointLight::SampleDirection(FLMRandomStream& RandomStream, FLightRay& SampleRay, FVector4& LightSourceNormal, FVector2D& LightSurfacePosition, float& RayPDF, FLinearColor& Power) const
{
const FVector4 RandomDirection = GetUnitVector(RandomStream);
FLightSurfaceSample SurfaceSample;
SampleLightSurface(RandomStream, SurfaceSample);
const float SurfacePositionDotDirection = Dot3((SurfaceSample.Position - Position), RandomDirection);
if (SurfacePositionDotDirection < 0.0f)
{
// Reflect the surface position about the origin so that it lies in the same hemisphere as the RandomDirection
const FVector4 LocalSamplePosition = SurfaceSample.Position - Position;
SurfaceSample.Position = -LocalSamplePosition + Position;
}
SampleRay = FLightRay(
SurfaceSample.Position,
SurfaceSample.Position + RandomDirection * FMath::Max((Radius - LightSourceRadius), 0.0f),
NULL,
this
);
LightSourceNormal = (SurfaceSample.Position - Position).GetSafeNormal();
// Approximate the probability of generating this direction as uniform over all the solid angles
// This diverges from the actual probability for positions inside the light source radius
RayPDF = 1.0f / (4.0f * (float)PI);
Power = IndirectColor * Brightness * PointLightIntensityScale;
}
/** Generates a direction sample from the light based on the given rays */
void FPointLight::SampleDirection(
const TArray<FIndirectPathRay>& IndirectPathRays,
FLMRandomStream& RandomStream,
FLightRay& SampleRay,
float& RayPDF,
FLinearColor& Power) const
{
checkSlow(IndirectPathRays.Num() > 0);
// Pick an indirect path ray with uniform probability
const int32 RayIndex = FMath::TruncToInt(RandomStream.GetFraction() * IndirectPathRays.Num());
checkSlow(RayIndex >= 0 && RayIndex < IndirectPathRays.Num());
const FVector4 PathRayDirection = IndirectPathRays[RayIndex].UnitDirection;
FVector4 XAxis(0,0,0);
FVector4 YAxis(0,0,0);
GenerateCoordinateSystem(PathRayDirection, XAxis, YAxis);
// Generate a sample direction within a cone about the indirect path
const FVector4 ConeSampleDirection = UniformSampleCone(RandomStream, CosIndirectPhotonEmitConeAngle, XAxis, YAxis, PathRayDirection);
FLightSurfaceSample SurfaceSample;
// Generate a surface sample, not taking the indirect path into account
SampleLightSurface(RandomStream, SurfaceSample);
const float SurfacePositionDotDirection = Dot3((SurfaceSample.Position - Position), ConeSampleDirection);
if (SurfacePositionDotDirection < 0.0f)
{
// Reflect the surface position about the origin so that it lies in the same hemisphere as the ConeSampleDirection
const FVector4 LocalSamplePosition = SurfaceSample.Position - Position;
SurfaceSample.Position = -LocalSamplePosition + Position;
}
SampleRay = FLightRay(
SurfaceSample.Position,
SurfaceSample.Position + ConeSampleDirection * FMath::Max((Radius - LightSourceRadius), 0.0f),
NULL,
this
);
const float ConePDF = UniformConePDF(CosIndirectPhotonEmitConeAngle);
RayPDF = 0.0f;
// Calculate the probability that this direction was chosen
for (int32 OtherRayIndex = 0; OtherRayIndex < IndirectPathRays.Num(); OtherRayIndex++)
{
// Accumulate the disk probability for all the disks which contain the sample position
if (Dot3(IndirectPathRays[OtherRayIndex].UnitDirection, ConeSampleDirection) > (1.0f - DELTA) * CosIndirectPhotonEmitConeAngle)
{
RayPDF += ConePDF;
}
}
RayPDF /= IndirectPathRays.Num();
checkSlow(RayPDF > 0);
Power = IndirectColor * Brightness * PointLightIntensityScale;
}
/** Validates a surface sample given the position that sample is affecting. */
void FPointLight::ValidateSurfaceSample(const FVector4& Point, FLightSurfaceSample& Sample) const
{
// Only attempt to fixup sphere light source sample positions as the light source is radially symmetric
if (LightSourceLength <= 0)
{
const FVector4 LightToPoint = Point - Position;
const float LightToPointDistanceSquared = LightToPoint.SizeSquared3();
if (LightToPointDistanceSquared < FMath::Square(LightSourceRadius * 2.0f))
{
// Point is inside the light source radius * 2
FVector4 LocalSamplePosition = Sample.Position - Position;
// Reposition the light surface sample on a sphere whose radius is half of the distance from the light to Point
LocalSamplePosition *= FMath::Sqrt(LightToPointDistanceSquared) / (2.0f * LightSourceRadius);
Sample.Position = LocalSamplePosition + Position;
}
const float SurfacePositionDotDirection = Dot3((Sample.Position - Position), LightToPoint);
if (SurfacePositionDotDirection < 0.0f)
{
// Reflect the surface position about the origin so that it lies in the hemisphere facing Point
// The sample's PDF is unchanged
const FVector4 LocalSamplePosition = Sample.Position - Position;
Sample.Position = -LocalSamplePosition + Position;
}
}
}
/** Returns the light's radiant power. */
float FPointLight::Power() const
{
FLinearColor IncidentPower = FLinearColor(Color) * Brightness * IndirectLightingScale;
// Approximate power of the light by the total amount of light passing through a sphere at half the light's radius
const float RadiusFraction = .5f;
const float DistanceToEvaluate = RadiusFraction * Radius;
if (LightFlags & GI_LIGHT_INVERSE_SQUARED)
{
IncidentPower = IncidentPower * 16 / (DistanceToEvaluate * DistanceToEvaluate);
}
else
{
float UnrealAttenuation = FMath::Pow(FMath::Max(1.0f - RadiusFraction * RadiusFraction, 0.0f), FalloffExponent);
// Point light power is proportional to its radius squared
IncidentPower = IncidentPower * UnrealAttenuation;
}
const FLinearColor LightPower = IncidentPower * 4.f * PI * DistanceToEvaluate * DistanceToEvaluate;
return FLinearColorUtils::LinearRGBToXYZ(LightPower).G;
}
FVector4 FPointLight::LightCenterPosition(const FVector4& ReceivingPosition, const FVector4& ReceivingNormal) const
{
if( LightSourceLength > 0 )
{
FVector4 ToLight = Position - ReceivingPosition;
FVector4 Dir = GetLightTangent();
if( Dot3( ReceivingNormal, Dir ) < 0.0f )
{
Dir = -Dir;
}
// Clip to hemisphere
float Proj = FMath::Min( Dot3( ToLight, Dir ), Dot3( ReceivingNormal, ToLight) / Dot3( ReceivingNormal, Dir ) );
// Point on line segment closest to Point
return Position - Dir * FMath::Clamp( Proj, -0.5f * LightSourceLength, 0.5f * LightSourceLength );
}
else
{
return Position;
}
}
/** Returns true if all parts of the light are behind the surface being tested. */
bool FPointLight::BehindSurface(const FVector4& TrianglePoint, const FVector4& TriangleNormal) const
{
const float NormalDotLight = Dot3(TriangleNormal, FPointLight::GetDirectLightingDirection(TrianglePoint, TriangleNormal));
return NormalDotLight < 0.0f;
}
/** Gets a single direction to use for direct lighting that is representative of the whole area light. */
FVector4 FPointLight::GetDirectLightingDirection(const FVector4& Point, const FVector4& PointNormal) const
{
FVector4 LightPosition = Position;
if( LightSourceLength > 0 )
{
FVector4 ToLight = Position - Point;
FVector4 L01 = Direction * LightSourceLength;
FVector4 L0 = ToLight - 0.5 * L01;
FVector4 L1 = ToLight + 0.5 * L01;
#if 0
// Point on line segment with smallest angle to normal
float A = LightSourceLength * LightSourceLength;
float B = 2.0f * Dot3( L0, L01 );
float C = Dot3( L0, L0 );
float D = Dot3( PointNormal, L0 );
float E = Dot3( PointNormal, L01 );
float t = FMath::Clamp( (B*D - 2.0f * C*E) / (B*E - 2.0f * A*D), 0.0f, 1.0f );
return L0 + t * L01;
#else
// Line segment irradiance
float LengthL0 = L0.Size3();
float LengthL1 = L1.Size3();
return ( L0 * LengthL1 + L1 * LengthL0 ) / ( LengthL0 + LengthL1 );
#endif
}
else
{
// The position on the point light surface sphere that will first be visible to a triangle rotating toward the light
const FVector4 FirstVisibleLightPoint = LightPosition + PointNormal * LightSourceRadius;
return FirstVisibleLightPoint - Point;
}
}
FVector FPointLight::GetLightTangent() const
{
// For point lights, light tangent is not provided, however it doesn't matter much since point lights are omni-directional
return Direction;
}
/** Generates a sample on the light's surface. */
void FPointLight::SampleLightSurface(FLMRandomStream& RandomStream, FLightSurfaceSample& Sample) const
{
Sample.DiskPosition = FVector2D(0, 0);
if (LightSourceLength <= 0)
{
// Generate a sample on the surface of the sphere with uniform density over the surface area of the sphere
//@todo - stratify
const FVector4 UnitSpherePosition = GetUnitVector(RandomStream);
Sample.Position = UnitSpherePosition * LightSourceRadius + Position;
Sample.Normal = UnitSpherePosition;
// Probability of generating this surface position is 1 / SurfaceArea
Sample.PDF = 1.0f / (4.0f * (float)PI * LightSourceRadius * LightSourceRadius);
}
else
{
const float ClampedLightSourceRadius = FMath::Max(DELTA, LightSourceRadius);
float CylinderSurfaceArea = 2.0f * (float)PI * ClampedLightSourceRadius * LightSourceLength;
float SphereSurfaceArea = 4.0f * (float)PI * ClampedLightSourceRadius * ClampedLightSourceRadius;
float TotalSurfaceArea = CylinderSurfaceArea + SphereSurfaceArea;
const FVector TubeLightDirection = GetLightTangent();
// Cylinder End caps
// The chance of calculating a point on the end sphere is equal to it's percentage of total surface area
if (RandomStream.GetFraction() < SphereSurfaceArea / TotalSurfaceArea)
{
// Generate a sample on the surface of the sphere with uniform density over the surface area of the sphere
//@todo - stratify
const FVector4 UnitSpherePosition = GetUnitVector(RandomStream);
Sample.Position = UnitSpherePosition * ClampedLightSourceRadius + Position;
if (Dot3(UnitSpherePosition, TubeLightDirection) > 0)
{
Sample.Position += TubeLightDirection * (LightSourceLength * 0.5f);
}
else
{
Sample.Position += -TubeLightDirection * (LightSourceLength * 0.5f);
}
Sample.Normal = UnitSpherePosition;
}
// Cylinder body
else
{
// Get point along center line
FVector4 CentreLinePosition = Position + TubeLightDirection * LightSourceLength * (RandomStream.GetFraction() - 0.5f);
// Get point radius away from center line at random angle
float Theta = 2.0f * (float)PI * RandomStream.GetFraction();
FVector4 CylEdgePos = FVector4(0, FMath::Cos(Theta), FMath::Sin(Theta), 1);
CylEdgePos = FRotationMatrix::MakeFromZ( TubeLightDirection ).TransformVector( CylEdgePos );
Sample.Position = CylEdgePos * ClampedLightSourceRadius + CentreLinePosition;
Sample.Normal = CylEdgePos;
}
// Probability of generating this surface position is 1 / SurfaceArea
Sample.PDF = 1.0f / TotalSurfaceArea;
}
}
//----------------------------------------------------------------------------
// Spot light class
//----------------------------------------------------------------------------
void FSpotLight::Import( FLightmassImporter& Importer )
{
FPointLight::Import( Importer );
Importer.ImportData( (FSpotLightData*)this );
}
void FSpotLight::Initialize(float InIndirectPhotonEmitConeAngle)
{
FPointLight::Initialize(InIndirectPhotonEmitConeAngle);
float ClampedInnerConeAngle = FMath::Clamp(InnerConeAngle, 0.0f, 89.0f) * (float)PI / 180.0f;
float ClampedOuterConeAngle = FMath::Clamp(OuterConeAngle * (float)PI / 180.0f,ClampedInnerConeAngle + 0.001f,89.0f * (float)PI / 180.0f + 0.001f);
SinOuterConeAngle = FMath::Sin(ClampedOuterConeAngle),
CosOuterConeAngle = FMath::Cos(ClampedOuterConeAngle);
CosInnerConeAngle = FMath::Cos(ClampedInnerConeAngle);
}
/**
* Tests whether the light affects the given bounding volume.
* @param Bounds - The bounding volume to test.
* @return True if the light affects the bounding volume
*/
bool FSpotLight::AffectsBounds(const FBoxSphereBounds& Bounds) const
{
if(!FLight::AffectsBounds(Bounds))
{
return false;
}
// Radial check
if((Bounds.Origin - Position).SizeSquared() > FMath::Square(Radius + Bounds.SphereRadius))
{
return false;
}
// Cone check
FVector4 U = Position - (Bounds.SphereRadius / SinOuterConeAngle) * Direction,
D = Bounds.Origin - U;
float dsqr = Dot3(D, D),
E = Dot3(Direction, D);
if(E > 0.0f && E * E >= dsqr * FMath::Square(CosOuterConeAngle))
{
D = Bounds.Origin - Position;
dsqr = Dot3(D, D);
E = -Dot3(Direction, D);
if(E > 0.0f && E * E >= dsqr * FMath::Square(SinOuterConeAngle))
return dsqr <= FMath::Square(Bounds.SphereRadius);
else
return true;
}
return false;
}
FSphere FSpotLight::GetBoundingSphere() const
{
// Use the law of cosines to find the distance to the furthest edge of the spotlight cone from a position that is halfway down the spotlight direction
const float BoundsRadius = FMath::Sqrt(1.25f * Radius * Radius - Radius * Radius * CosOuterConeAngle);
return FSphere(Position + .5f * Direction * Radius, BoundsRadius);
}
/**
* Computes the intensity of the direct lighting from this light on a specific point.
*/
FLinearColor FSpotLight::GetDirectIntensity(const FVector4& Point, bool bCalculateForIndirectLighting) const
{
FVector4 LightVector = (Point - Position).GetSafeNormal();
float SpotAttenuation = FMath::Square(FMath::Clamp<float>((Dot3(LightVector, Direction) - CosOuterConeAngle) / (CosInnerConeAngle - CosOuterConeAngle),0.0f,1.0f));
if( LightFlags & GI_LIGHT_INVERSE_SQUARED )
{
FVector4 ToLight = Position - Point;
float DistanceSqr = ToLight.SizeSquared3();
float DistanceAttenuation = 0.0f;
if( LightSourceLength > 0.0f )
{
// Line segment irradiance
FVector4 L01 = Direction * LightSourceLength;
FVector4 L0 = ToLight - 0.5 * L01;
FVector4 L1 = ToLight + 0.5 * L01;
float LengthL0 = L0.Size3();
float LengthL1 = L1.Size3();
DistanceAttenuation = 1.0f / ( ( LengthL0 * LengthL1 + Dot3( L0, L1 ) ) * 0.5f + 1.0f );
}
else
{
// Sphere irradiance (technically just 1/d^2 but this avoids inf)
DistanceAttenuation = 1.0f / ( DistanceSqr + 1.0f );
}
// lumens
DistanceAttenuation *= 16.0f;
float LightRadiusMask = FMath::Square( FMath::Max( 0.0f, 1.0f - FMath::Square( DistanceSqr / (Radius * Radius) ) ) );
DistanceAttenuation *= LightRadiusMask;
return FLight::GetDirectIntensity(Point, bCalculateForIndirectLighting) * DistanceAttenuation * SpotAttenuation;
}
else
{
float RadialAttenuation = FMath::Pow( FMath::Max(1.0f - ((Position - Point) / Radius).SizeSquared3(),0.0f), FalloffExponent );
return FLight::GetDirectIntensity(Point, bCalculateForIndirectLighting) * RadialAttenuation * SpotAttenuation;
}
}
/** Returns the number of direct photons to gather required by this light. */
int32 FSpotLight::GetNumDirectPhotons(float DirectPhotonDensity) const
{
const float InfluenceSphereSurfaceAreaMillions = 4.0f * (float)PI * FMath::Square(Radius) / 1000000.0f;
const float ConeSolidAngle = 2.0f * float(PI) * (1.0f - CosOuterConeAngle);
// Find the fraction of the sphere's surface area that is inside the cone
const float ConeSurfaceAreaSphereFraction = ConeSolidAngle / (4.0f * (float)PI);
// Gather enough photons to meet DirectPhotonDensity on the spherical cap at the influence radius of the spot light.
const int32 NumDirectPhotons = FMath::TruncToInt(InfluenceSphereSurfaceAreaMillions * ConeSurfaceAreaSphereFraction * DirectPhotonDensity);
return NumDirectPhotons == appTruncErrorCode ? INT_MAX : NumDirectPhotons;
}
/** Generates a direction sample from the light's domain */
void FSpotLight::SampleDirection(FLMRandomStream& RandomStream, FLightRay& SampleRay, FVector4& LightSourceNormal, FVector2D& LightSurfacePosition, float& RayPDF, FLinearColor& Power) const
{
FVector4 XAxis(0,0,0);
FVector4 YAxis(0,0,0);
GenerateCoordinateSystem(Direction, XAxis, YAxis);
//@todo - the PDF should be affected by inner cone angle too
const FVector4 ConeSampleDirection = UniformSampleCone(RandomStream, CosOuterConeAngle, XAxis, YAxis, Direction);
//@todo - take light source radius into account
SampleRay = FLightRay(
Position,
Position + ConeSampleDirection * Radius,
NULL,
this
);
LightSourceNormal = Direction;
RayPDF = UniformConePDF(CosOuterConeAngle);
checkSlow(RayPDF > 0.0f);
Power = IndirectColor * Brightness * PointLightIntensityScale;
}
FVector FSpotLight::GetLightTangent() const
{
return LightTangent;
}
//----------------------------------------------------------------------------
// Sky light class
//----------------------------------------------------------------------------
void FSkyLight::Import( FLightmassImporter& Importer )
{
FLight::Import( Importer );
Importer.ImportData( (FSkyLightData*)this );
TArray<FFloat16Color> RadianceEnvironmentMap;
Importer.ImportArray(RadianceEnvironmentMap, RadianceEnvironmentMapDataSize);
CubemapSize = FMath::Sqrt(RadianceEnvironmentMapDataSize / 6);
NumMips = FMath::CeilLogTwo(CubemapSize) + 1;
check(FMath::IsPowerOfTwo(CubemapSize));
check(NumMips > 0);
check(RadianceEnvironmentMapDataSize == CubemapSize * CubemapSize * 6);
if (bUseFilteredCubemap && CubemapSize > 0)
{
const double StartTime = FPlatformTime::Seconds();
PrefilteredRadiance.Empty(NumMips);
PrefilteredRadiance.AddZeroed(NumMips);
PrefilteredRadiance[0].Empty(CubemapSize * CubemapSize * 6);
PrefilteredRadiance[0].AddZeroed(CubemapSize * CubemapSize * 6);
for (int32 TexelIndex = 0; TexelIndex < CubemapSize * CubemapSize * 6; TexelIndex++)
{
FLinearColor Lighting = FLinearColor(RadianceEnvironmentMap[TexelIndex]);
PrefilteredRadiance[0][TexelIndex] = Lighting;
}
FIntPoint SubCellOffsets[4] =
{
FIntPoint(0, 0),
FIntPoint(1, 0),
FIntPoint(0, 1),
FIntPoint(1, 1)
};
const float SubCellWeight = 1.0f / (float)ARRAY_COUNT(SubCellOffsets);
for (int32 MipIndex = 1; MipIndex < NumMips; MipIndex++)
{
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
const int32 ParentMipSize = MipSize * 2;
const int32 CubeFaceSize = MipSize * MipSize;
PrefilteredRadiance[MipIndex].Empty(CubeFaceSize * 6);
PrefilteredRadiance[MipIndex].AddZeroed(CubeFaceSize * 6);
for (int32 FaceIndex = 0; FaceIndex < 6; FaceIndex++)
{
for (int32 Y = 0; Y < MipSize; Y++)
{
for (int32 X = 0; X < MipSize; X++)
{
FLinearColor FilteredValue(0, 0, 0, 0);
for (int32 OffsetIndex = 0; OffsetIndex < ARRAY_COUNT(SubCellOffsets); OffsetIndex++)
{
FIntPoint ParentOffset = FIntPoint(X, Y) * 2 + SubCellOffsets[OffsetIndex];
int32 ParentTexelIndex = FaceIndex * ParentMipSize * ParentMipSize + ParentOffset.Y * ParentMipSize + ParentOffset.X;
FLinearColor ParentLighting = PrefilteredRadiance[MipIndex - 1][ParentTexelIndex];
FilteredValue += ParentLighting;
}
FilteredValue *= SubCellWeight;
PrefilteredRadiance[MipIndex][FaceIndex * CubeFaceSize + Y * MipSize + X] = FilteredValue;
}
}
}
}
ComputePrefilteredVariance();
const double EndTime = FPlatformTime::Seconds();
UE_LOG(LogLightmass, Log, TEXT("Skylight import processing %.3fs with CubemapSize %u"), (float)(EndTime - StartTime), CubemapSize);
}
}
void FSkyLight::ComputePrefilteredVariance()
{
PrefilteredVariance.Empty(NumMips);
PrefilteredVariance.AddZeroed(NumMips);
TArray<float> TempMaxVariance;
TempMaxVariance.Empty(NumMips);
TempMaxVariance.AddZeroed(NumMips);
for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++)
{
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
const int32 CubeFaceSize = MipSize * MipSize;
const int32 BaseMipTexelSize = CubemapSize / MipSize;
const float NormalizeFactor = 1.0f / FMath::Max(BaseMipTexelSize * BaseMipTexelSize - 1, 1);
PrefilteredVariance[MipIndex].Empty(CubeFaceSize * 6);
PrefilteredVariance[MipIndex].AddZeroed(CubeFaceSize * 6);
for (int32 FaceIndex = 0; FaceIndex < 6; FaceIndex++)
{
for (int32 Y = 0; Y < MipSize; Y++)
{
for (int32 X = 0; X < MipSize; X++)
{
int32 TexelIndex = FaceIndex * CubeFaceSize + Y * MipSize + X;
float Mean = PrefilteredRadiance[MipIndex][TexelIndex].GetLuminance();
int32 BaseTexelOffset = FaceIndex * CubemapSize * CubemapSize + X * BaseMipTexelSize + Y * BaseMipTexelSize * CubemapSize;
float SumOfSquares = 0;
//@todo - implement in terms of the previous mip level, not the bottom mip level
for (int32 BaseY = 0; BaseY < BaseMipTexelSize; BaseY++)
{
for (int32 BaseX = 0; BaseX < BaseMipTexelSize; BaseX++)
{
int32 BaseTexelIndex = BaseTexelOffset + BaseY * CubemapSize + BaseX;
float BaseValue = PrefilteredRadiance[0][BaseTexelIndex].GetLuminance();
SumOfSquares += (BaseValue - Mean) * (BaseValue - Mean);
}
}
PrefilteredVariance[MipIndex][TexelIndex] = SumOfSquares * NormalizeFactor;
TempMaxVariance[MipIndex] = FMath::Max(TempMaxVariance[MipIndex], SumOfSquares * NormalizeFactor);
}
}
}
}
}
FLinearColor FSkyLight::SampleRadianceCubemap(float Mip, int32 CubeFaceIndex, FVector2D FaceUV) const
{
checkSlow(bUseFilteredCubemap);
FLinearColor HighMipRadiance;
{
const int32 MipIndex = FMath::CeilToInt(Mip);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
const int32 CubeFaceSize = MipSize * MipSize;
FIntPoint FaceCoordinate(FaceUV.X * MipSize, FaceUV.Y * MipSize);
check(FaceCoordinate.X >= 0 && FaceCoordinate.X < MipSize);
check(FaceCoordinate.Y >= 0 && FaceCoordinate.Y < MipSize);
HighMipRadiance = PrefilteredRadiance[MipIndex][CubeFaceIndex * CubeFaceSize + FaceCoordinate.Y * MipSize + FaceCoordinate.X];
}
FLinearColor LowMipRadiance;
{
const int32 MipIndex = FMath::FloorToInt(Mip);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
const int32 CubeFaceSize = MipSize * MipSize;
FIntPoint FaceCoordinate(FaceUV.X * MipSize, FaceUV.Y * MipSize);
check(FaceCoordinate.X >= 0 && FaceCoordinate.X < MipSize);
check(FaceCoordinate.Y >= 0 && FaceCoordinate.Y < MipSize);
LowMipRadiance = PrefilteredRadiance[MipIndex][CubeFaceIndex * CubeFaceSize + FaceCoordinate.Y * MipSize + FaceCoordinate.X];
}
return FMath::Lerp(LowMipRadiance, HighMipRadiance, FMath::Fractional(Mip));
}
float FSkyLight::SampleVarianceCubemap(float Mip, int32 CubeFaceIndex, FVector2D FaceUV) const
{
checkSlow(bUseFilteredCubemap);
float HighMipVariance;
{
const int32 MipIndex = FMath::CeilToInt(Mip);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
const int32 CubeFaceSize = MipSize * MipSize;
FIntPoint FaceCoordinate(FaceUV.X * MipSize, FaceUV.Y * MipSize);
check(FaceCoordinate.X >= 0 && FaceCoordinate.X < MipSize);
check(FaceCoordinate.Y >= 0 && FaceCoordinate.Y < MipSize);
HighMipVariance = PrefilteredVariance[MipIndex][CubeFaceIndex * CubeFaceSize + FaceCoordinate.Y * MipSize + FaceCoordinate.X];
}
float LowMipVariance;
{
const int32 MipIndex = FMath::FloorToInt(Mip);
const int32 MipSize = 1 << (NumMips - MipIndex - 1);
const int32 CubeFaceSize = MipSize * MipSize;
FIntPoint FaceCoordinate(FaceUV.X * MipSize, FaceUV.Y * MipSize);
check(FaceCoordinate.X >= 0 && FaceCoordinate.X < MipSize);
check(FaceCoordinate.Y >= 0 && FaceCoordinate.Y < MipSize);
LowMipVariance = PrefilteredVariance[MipIndex][CubeFaceIndex * CubeFaceSize + FaceCoordinate.Y * MipSize + FaceCoordinate.X];
}
return FMath::Lerp(LowMipVariance, HighMipVariance, FMath::Fractional(Mip));
}
void GetCubeFaceAndUVFromDirection(const FVector4& IncomingDirection, int32& CubeFaceIndex, FVector2D& FaceUVs)
{
FVector AbsIncomingDirection(FMath::Abs(IncomingDirection.X), FMath::Abs(IncomingDirection.Y), FMath::Abs(IncomingDirection.Z));
int32 LargestChannelIndex = 0;
if (AbsIncomingDirection.Y > AbsIncomingDirection.X)
{
LargestChannelIndex = 1;
}
if (AbsIncomingDirection.Z > AbsIncomingDirection.Y && AbsIncomingDirection.Z > AbsIncomingDirection.X)
{
LargestChannelIndex = 2;
}
CubeFaceIndex = LargestChannelIndex * 2 + (IncomingDirection[LargestChannelIndex] < 0 ? 1 : 0);
if (CubeFaceIndex == 0)
{
FaceUVs = FVector2D(-IncomingDirection.Z, -IncomingDirection.Y);
//CubeCoordinates = float3(1, -ScaledUVs.y, -ScaledUVs.x);
}
else if (CubeFaceIndex == 1)
{
FaceUVs = FVector2D(IncomingDirection.Z, -IncomingDirection.Y);
//CubeCoordinates = float3(-1, -ScaledUVs.y, ScaledUVs.x);
}
else if (CubeFaceIndex == 2)
{
FaceUVs = FVector2D(IncomingDirection.X, IncomingDirection.Z);
//CubeCoordinates = float3(ScaledUVs.x, 1, ScaledUVs.y);
}
else if (CubeFaceIndex == 3)
{
FaceUVs = FVector2D(IncomingDirection.X, -IncomingDirection.Z);
//CubeCoordinates = float3(ScaledUVs.x, -1, -ScaledUVs.y);
}
else if (CubeFaceIndex == 4)
{
FaceUVs = FVector2D(IncomingDirection.X, -IncomingDirection.Y);
//CubeCoordinates = float3(ScaledUVs.x, -ScaledUVs.y, 1);
}
else
{
FaceUVs = FVector2D(-IncomingDirection.X, -IncomingDirection.Y);
//CubeCoordinates = float3(-ScaledUVs.x, -ScaledUVs.y, -1);
}
FaceUVs = FaceUVs / AbsIncomingDirection[LargestChannelIndex] * .5f + .5f;
// When exactly on the edge of two faces, snap to the nearest addressable texel
FaceUVs.X = FMath::Min(FaceUVs.X, .999f);
FaceUVs.Y = FMath::Min(FaceUVs.Y, .999f);
}
float FSkyLight::GetMipIndexForSolidAngle(float SolidAngle) const
{
//@todo - corners of the cube should use a different mip
const float AverageTexelSolidAngle = 4 * PI / (6 * CubemapSize * CubemapSize) * 2;
float Mip = 0.5 * FMath::Log2(SolidAngle / AverageTexelSolidAngle);
return FMath::Clamp<float>(Mip, 0.0f, NumMips - 1);
}
FLinearColor FSkyLight::GetPathLighting(const FVector4& IncomingDirection, float PathSolidAngle, bool bCalculateForIndirectLighting) const
{
if (CubemapSize == 0)
{
return FLinearColor::Black;
}
FLinearColor Lighting = FLinearColor::Black;
if (bUseFilteredCubemap)
{
int32 CubeFaceIndex;
FVector2D FaceUVs;
GetCubeFaceAndUVFromDirection(IncomingDirection, CubeFaceIndex, FaceUVs);
const float MipIndex = GetMipIndexForSolidAngle(PathSolidAngle);
Lighting = SampleRadianceCubemap(MipIndex, CubeFaceIndex, FaceUVs);
}
else
{
FSHVector3 SH = FSHVector3::SHBasisFunction(IncomingDirection);
Lighting = Dot(IrradianceEnvironmentMap, SH);
}
const float LightingScale = bCalculateForIndirectLighting ? IndirectLightingScale : 1.0f;
Lighting = (Lighting * Brightness * LightingScale) * FLinearColor(Color);
Lighting.R = FMath::Max(Lighting.R, 0.0f);
Lighting.G = FMath::Max(Lighting.G, 0.0f);
Lighting.B = FMath::Max(Lighting.B, 0.0f);
return Lighting;
}
float FSkyLight::GetPathVariance(const FVector4& IncomingDirection, float PathSolidAngle) const
{
if (CubemapSize == 0 || !bUseFilteredCubemap)
{
return 0;
}
int32 CubeFaceIndex;
FVector2D FaceUVs;
GetCubeFaceAndUVFromDirection(IncomingDirection, CubeFaceIndex, FaceUVs);
const float MipIndex = GetMipIndexForSolidAngle(PathSolidAngle);
return SampleVarianceCubemap(MipIndex, CubeFaceIndex, FaceUVs);
}
void FMeshLightPrimitive::AddSubPrimitive(const FTexelToCorners& TexelToCorners, const FIntPoint& Coordinates, const FLinearColor& InTexelPower, float NormalOffset)
{
const FVector4 FirstTriangleNormal = (TexelToCorners.Corners[0].WorldPosition - TexelToCorners.Corners[1].WorldPosition) ^ (TexelToCorners.Corners[2].WorldPosition - TexelToCorners.Corners[1].WorldPosition);
const float FirstTriangleArea = .5f * FirstTriangleNormal.Size3();
const FVector4 SecondTriangleNormal = (TexelToCorners.Corners[2].WorldPosition - TexelToCorners.Corners[1].WorldPosition) ^ (TexelToCorners.Corners[2].WorldPosition - TexelToCorners.Corners[3].WorldPosition);
const float SecondTriangleArea = .5f * SecondTriangleNormal.Size3();
const float SubPrimitiveSurfaceArea = FirstTriangleArea + SecondTriangleArea;
// Convert power per texel into power per texel surface area
const FLinearColor SubPrimitivePower = InTexelPower * SubPrimitiveSurfaceArea;
// If this is the first sub primitive, initialize
if (NumSubPrimitives == 0)
{
SurfaceNormal = TexelToCorners.WorldTangentZ;
const FVector4 OffsetAmount = NormalOffset * TexelToCorners.WorldTangentZ;
for (int32 CornerIndex = 0; CornerIndex < NumTexelCorners; CornerIndex++)
{
Corners[CornerIndex].WorldPosition = TexelToCorners.Corners[CornerIndex].WorldPosition + OffsetAmount;
Corners[CornerIndex].FurthestCoordinates = Coordinates;
}
SurfaceArea = SubPrimitiveSurfaceArea;
Power = SubPrimitivePower;
}
else
{
// Average sub primitive normals
SurfaceNormal += TexelToCorners.WorldTangentZ;
// Directions corresponding to CornerOffsets in FStaticLightingSystem::CalculateTexelCorners
static const FIntPoint CornerDirections[NumTexelCorners] =
{
FIntPoint(-1, -1),
FIntPoint(1, -1),
FIntPoint(-1, 1),
FIntPoint(1, 1)
};
const FVector4 OffsetAmount = NormalOffset * TexelToCorners.WorldTangentZ;
for (int32 CornerIndex = 0; CornerIndex < NumTexelCorners; CornerIndex++)
{
const FIntPoint& ExistingFurthestCoordinates = Corners[CornerIndex].FurthestCoordinates;
// Store the new position if this coordinate is greater or equal to the previous coordinate for this corner in texture space, in the direction of the corner.
if (CornerDirections[CornerIndex].X * (Coordinates.X - ExistingFurthestCoordinates.X) >=0
&& CornerDirections[CornerIndex].Y * (Coordinates.Y - ExistingFurthestCoordinates.Y) >=0)
{
Corners[CornerIndex].WorldPosition = TexelToCorners.Corners[CornerIndex].WorldPosition + OffsetAmount;
Corners[CornerIndex].FurthestCoordinates = Coordinates;
}
}
// Accumulate the area and power that this simplified primitive represents
SurfaceArea += SubPrimitiveSurfaceArea;
Power += SubPrimitivePower;
}
NumSubPrimitives++;
}
void FMeshLightPrimitive::Finalize()
{
SurfaceNormal = SurfaceNormal.SizeSquared3() > SMALL_NUMBER ? SurfaceNormal.GetUnsafeNormal3() : FVector4(0, 0, 1);
}
//----------------------------------------------------------------------------
// Mesh Area Light class
//----------------------------------------------------------------------------
void FMeshAreaLight::Initialize(float InIndirectPhotonEmitConeAngle, const FBoxSphereBounds& InImportanceBounds)
{
CosIndirectPhotonEmitConeAngle = FMath::Cos(InIndirectPhotonEmitConeAngle);
ImportanceBounds = InImportanceBounds;
}
/** Returns the number of direct photons to gather required by this light. */
int32 FMeshAreaLight::GetNumDirectPhotons(float DirectPhotonDensity) const
{
// Gather enough photons to meet DirectPhotonDensity at the influence radius of the mesh area light.
// Clamp the influence radius to the importance or scene radius for the purposes of emitting photons
// This prevents huge mesh area lights from emitting more photons than are needed
const float InfluenceSphereSurfaceAreaMillions = 4.0f * (float)PI * FMath::Square(FMath::Min(ImportanceBounds.SphereRadius, InfluenceRadius)) / 1000000.0f;
const int32 NumDirectPhotons = FMath::TruncToInt(InfluenceSphereSurfaceAreaMillions * DirectPhotonDensity);
return NumDirectPhotons == appTruncErrorCode ? INT_MAX : NumDirectPhotons;
}
/** Initializes the mesh area light with primitives */
void FMeshAreaLight::SetPrimitives(
const TArray<FMeshLightPrimitive>& InPrimitives,
float EmissiveLightFalloffExponent,
float EmissiveLightExplicitInfluenceRadius,
int32 InMeshAreaLightGridSize,
FGuid InLevelGuid)
{
check(InPrimitives.Num() > 0);
Primitives = InPrimitives;
MeshAreaLightGridSize = InMeshAreaLightGridSize;
LevelGuid = InLevelGuid;
TotalSurfaceArea = 0.0f;
TotalPower = FLinearColor::Black;
Position = FVector4(0,0,0);
FBox Bounds(ForceInit);
CachedPrimitiveNormals.Empty(MeshAreaLightGridSize * MeshAreaLightGridSize);
CachedPrimitiveNormals.AddZeroed(MeshAreaLightGridSize * MeshAreaLightGridSize);
PrimitivePDFs.Empty(Primitives.Num());
for (int32 PrimitiveIndex = 0; PrimitiveIndex < Primitives.Num(); PrimitiveIndex++)
{
const FMeshLightPrimitive& CurrentPrimitive = Primitives[PrimitiveIndex];
TotalSurfaceArea += CurrentPrimitive.SurfaceArea;
TotalPower += CurrentPrimitive.Power;
PrimitivePDFs.Add(CurrentPrimitive.SurfaceArea);
for (int32 CornerIndex = 0; CornerIndex < NumTexelCorners; CornerIndex++)
{
Bounds += CurrentPrimitive.Corners[CornerIndex].WorldPosition;
}
const FVector2D SphericalCoordinates = FVector(CurrentPrimitive.SurfaceNormal).UnitCartesianToSpherical();
// Determine grid cell the primitive's normal falls into based on spherical coordinates
const int32 CacheX = FMath::Clamp(FMath::TruncToInt(SphericalCoordinates.X / (float)PI * MeshAreaLightGridSize), 0, MeshAreaLightGridSize - 1);
const int32 CacheY = FMath::Clamp(FMath::TruncToInt((SphericalCoordinates.Y + (float)PI) / (2 * (float)PI) * MeshAreaLightGridSize), 0, MeshAreaLightGridSize - 1);
CachedPrimitiveNormals[CacheY * MeshAreaLightGridSize + CacheX].Add(CurrentPrimitive.SurfaceNormal);
}
for (int32 PhiStep = 0; PhiStep < MeshAreaLightGridSize; PhiStep++)
{
for (int32 ThetaStep = 0; ThetaStep < MeshAreaLightGridSize; ThetaStep++)
{
const TArray<FVector4>& CurrentCachedNormals = CachedPrimitiveNormals[PhiStep * MeshAreaLightGridSize + ThetaStep];
if (CurrentCachedNormals.Num() > 0)
{
OccupiedCachedPrimitiveNormalCells.Add(FIntPoint(ThetaStep, PhiStep));
}
}
}
// Compute the Cumulative Distribution Function for our step function of primitive surface areas
CalculateStep1dCDF(PrimitivePDFs, PrimitiveCDFs, UnnormalizedIntegral);
SourceBounds = FBoxSphereBounds(Bounds);
Position = SourceBounds.Origin;
Position.W = 1.0f;
check(TotalSurfaceArea > 0.0f);
check(TotalPower.R > 0.0f || TotalPower.G > 0.0f || TotalPower.B > 0.0f);
// The irradiance value at which to place the light's influence radius
const float IrradianceCutoff = .002f;
// If EmissiveLightExplicitInfluenceRadius is 0, automatically generate the influence radius based on the light's power
// Solve Irradiance = Power / Distance ^2 for Radius
//@todo - should the SourceBounds also factor into the InfluenceRadius calculation?
InfluenceRadius = EmissiveLightExplicitInfluenceRadius > DELTA ? EmissiveLightExplicitInfluenceRadius : FMath::Sqrt(FLinearColorUtils::LinearRGBToXYZ(TotalPower).G / IrradianceCutoff);
FalloffExponent = EmissiveLightFalloffExponent;
// Using the default for point lights
ShadowExponent = 2.0f;
}
/**
* Tests whether the light affects the given bounding volume.
* @param Bounds - The bounding volume to test.
* @return True if the light affects the bounding volume
*/
bool FMeshAreaLight::AffectsBounds(const FBoxSphereBounds& Bounds) const
{
if((Bounds.Origin - Position).SizeSquared() > FMath::Square(InfluenceRadius + Bounds.SphereRadius + SourceBounds.SphereRadius))
{
return false;
}
if(!FLight::AffectsBounds(Bounds))
{
return false;
}
return true;
}
/**
* Computes the intensity of the direct lighting from this light on a specific point.
*/
FLinearColor FMeshAreaLight::GetDirectIntensity(const FVector4& Point, bool bCalculateForIndirectLighting) const
{
FLinearColor AccumulatedPower(ForceInit);
float AccumulatedSurfaceArea = 0.0f;
for (int32 PrimitiveIndex = 0; PrimitiveIndex < Primitives.Num(); PrimitiveIndex++)
{
const FMeshLightPrimitive& CurrentPrimitive = Primitives[PrimitiveIndex];
FVector4 PrimitiveCenter(0,0,0);
for (int32 CornerIndex = 0; CornerIndex < NumTexelCorners; CornerIndex++)
{
PrimitiveCenter += CurrentPrimitive.Corners[CornerIndex].WorldPosition / 4.0f;
}
const FVector4 LightVector = (Point - PrimitiveCenter).GetSafeNormal();
const float NDotL = Dot3(LightVector, CurrentPrimitive.SurfaceNormal);
if (NDotL >= 0)
{
// Using standard Unreal attenuation for point lights for each primitive
const float RadialAttenuation = FMath::Pow(FMath::Max(1.0f - ((PrimitiveCenter - Point) / InfluenceRadius).SizeSquared3(), 0.0f), FalloffExponent);
// Weight exitant power by the distance attenuation to this primitive and the light's cosine distribution around the primitive's normal
//@todo - photon emitting does not take the cosine distribution into account
AccumulatedPower += CurrentPrimitive.Power * RadialAttenuation * NDotL;
}
}
return AccumulatedPower / TotalSurfaceArea * (bCalculateForIndirectLighting ? IndirectLightingScale : 1.0f);
}
/** Returns an intensity scale based on the receiving point. */
float FMeshAreaLight::CustomAttenuation(const FVector4& Point, FLMRandomStream& RandomStream) const
{
const float FullProbabilityDistance = .5f * InfluenceRadius;
float PowerWeightedAttenuation = 0.0f;
float PowerWeightedPhysicalAttenuation = 0.0f;
float DepositProbability = 0.0f;
for (int32 PrimitiveIndex = 0; PrimitiveIndex < Primitives.Num(); PrimitiveIndex++)
{
const FMeshLightPrimitive& CurrentPrimitive = Primitives[PrimitiveIndex];
FVector4 PrimitiveCenter(0,0,0);
for (int32 CornerIndex = 0; CornerIndex < NumTexelCorners; CornerIndex++)
{
PrimitiveCenter += CurrentPrimitive.Corners[CornerIndex].WorldPosition / 4.0f;
}
const float NDotL = Dot3((Point - PrimitiveCenter), CurrentPrimitive.SurfaceNormal);
if (NDotL >= 0)
{
const float RadialAttenuation = FMath::Pow(FMath::Max(1.0f - ((PrimitiveCenter - Point) / InfluenceRadius).SizeSquared3(), 0.0f), FalloffExponent);
const float PowerWeight = FLinearColorUtils::LinearRGBToXYZ(CurrentPrimitive.Power).G;
// Weight the attenuation factors by how much power this primitive emits, and its distance attenuation
PowerWeightedAttenuation += PowerWeight * RadialAttenuation;
// Also accumulate physical attenuation
const float DistanceSquared = (PrimitiveCenter - Point).SizeSquared3();
PowerWeightedPhysicalAttenuation += PowerWeight / DistanceSquared;
DepositProbability += CurrentPrimitive.SurfaceArea / TotalSurfaceArea * FMath::Min(DistanceSquared / (FullProbabilityDistance * FullProbabilityDistance), 1.0f);
}
}
DepositProbability = FMath::Clamp(DepositProbability, 0.0f, 1.0f);
// Thin out photons near the light source.
// This is partly an optimization since the photon density near light sources doesn't need to be high, and the natural 1 / R^2 density is overkill,
// But this also improves quality since we are doing a nearest N photon neighbor search when calculating irradiance.
// If the photon map has a high density of low power photons near light sources,
// Combined with sparse, high power photons from other light sources (directional lights for example), the result will be very splotchy.
if (RandomStream.GetFraction() < DepositProbability)
{
// Remove physical attenuation, apply standard Unreal point light attenuation from each primitive
return PowerWeightedAttenuation / (PowerWeightedPhysicalAttenuation * DepositProbability);
}
else
{
return 0.0f;
}
}
// Fudge factor to get mesh area light photon intensities to match direct lighting more closely.
static const float MeshAreaLightIntensityScale = 2.5f;
/** Generates a direction sample from the light's domain */
void FMeshAreaLight::SampleDirection(FLMRandomStream& RandomStream, FLightRay& SampleRay, FVector4& LightSourceNormal, FVector2D& LightSurfacePosition, float& RayPDF, FLinearColor& Power) const
{
FLightSurfaceSample SurfaceSample;
FMeshAreaLight::SampleLightSurface(RandomStream, SurfaceSample);
const float DistanceFromCenter = (SurfaceSample.Position - Position).Size3();
// Generate a sample direction from a distribution that is uniform over all directions
FVector4 SampleDir;
do
{
SampleDir = GetUnitVector(RandomStream);
}
// Regenerate the direction vector until it is less than .1 of a degree from perpendicular to the light's surface normal
// This prevents generating directions that are deemed outside of the light source primitive's hemisphere by later calculations due to fp imprecision
while(FMath::Abs(Dot3(SampleDir, SurfaceSample.Normal)) < .0017);
if (Dot3(SampleDir, SurfaceSample.Normal) < 0.0f)
{
// Reflect the sample direction across the origin so that it lies in the same hemisphere as the primitive normal
SampleDir *= -1.0f;
}
SampleRay = FLightRay(
SurfaceSample.Position,
SurfaceSample.Position + SampleDir * FMath::Max(InfluenceRadius - DistanceFromCenter, 0.0f),
NULL,
this
);
LightSourceNormal = SurfaceSample.Normal;
// The probability of selecting any direction in a hemisphere defined by each primitive normal
const float HemispherePDF = 1.0f / (2.0f * (float)PI);
RayPDF = 0.0f;
const FIntPoint Corners[] =
{
FIntPoint(0,0),
FIntPoint(0,1),
FIntPoint(1,0),
FIntPoint(1,1)
};
// Use a grid which contains cached primitive normals to accelerate PDF calculation
// This prevents the need to iterate over all of the mesh area light's primitives, of which there may be thousands
for (int32 OccupiedCellIndex = 0; OccupiedCellIndex < OccupiedCachedPrimitiveNormalCells.Num(); OccupiedCellIndex++)
{
const int32 ThetaStep = OccupiedCachedPrimitiveNormalCells[OccupiedCellIndex].X;
const int32 PhiStep = OccupiedCachedPrimitiveNormalCells[OccupiedCellIndex].Y;
const TArray<FVector4>& CurrentCachedNormals = CachedPrimitiveNormals[PhiStep * MeshAreaLightGridSize + ThetaStep];
if (CurrentCachedNormals.Num() > 0)
{
bool bAllCornersInSameHemisphere = true;
bool bAllCornersInOppositeHemisphere = true;
// Determine whether the cell is completely in the same hemisphere as the sample direction, completely on the other side or spanning the terminator
// This is done by checking each cell's corners
for (int32 CornerIndex = 0; CornerIndex < ARRAY_COUNT(Corners); CornerIndex++)
{
const float Theta = (ThetaStep + Corners[CornerIndex].X) / (float)MeshAreaLightGridSize * (float)PI;
const float Phi = (PhiStep + Corners[CornerIndex].Y) / (float)MeshAreaLightGridSize * 2 * (float)PI - (float)PI;
// Calculate the cartesian unit direction corresponding to this corner
const FVector4 CurrentCornerDirection = FVector2D(Theta, Phi).SphericalToUnitCartesian();
bAllCornersInSameHemisphere = bAllCornersInSameHemisphere && Dot3(CurrentCornerDirection, SampleDir) > 0.0f;
bAllCornersInOppositeHemisphere = bAllCornersInOppositeHemisphere && Dot3(CurrentCornerDirection, SampleDir) < 0.0f;
}
if (bAllCornersInSameHemisphere)
{
// If the entire cell is in the same hemisphere as the sample direction, the sample could have been generated from any of them
RayPDF += CurrentCachedNormals.Num() * HemispherePDF;
}
else if (!bAllCornersInOppositeHemisphere)
{
// If the cell spans both hemispheres, we have to test each normal individually
for (int32 CachedNormalIndex = 0; CachedNormalIndex < CurrentCachedNormals.Num(); CachedNormalIndex++)
{
if (Dot3(CurrentCachedNormals[CachedNormalIndex], SampleDir) > 0.0f)
{
// Accumulate the probability that this direction was generated by each primitive
RayPDF += HemispherePDF;
}
}
}
}
}
RayPDF /= Primitives.Num();
checkSlow(RayPDF > 0.0f);
Power = TotalPower / TotalSurfaceArea * MeshAreaLightIntensityScale;
}
/** Generates a direction sample from the light based on the given rays */
void FMeshAreaLight::SampleDirection(
const TArray<FIndirectPathRay>& IndirectPathRays,
FLMRandomStream& RandomStream,
FLightRay& SampleRay,
float& RayPDF,
FLinearColor& Power) const
{
checkSlow(IndirectPathRays.Num() > 0);
// Pick an indirect path ray with uniform probability
const int32 RayIndex = FMath::TruncToInt(RandomStream.GetFraction() * IndirectPathRays.Num());
checkSlow(RayIndex >= 0 && RayIndex < IndirectPathRays.Num());
const FIndirectPathRay& ChosenPathRay = IndirectPathRays[RayIndex];
const FVector4 PathRayDirection = ChosenPathRay.UnitDirection;
FVector4 XAxis(0,0,0);
FVector4 YAxis(0,0,0);
GenerateCoordinateSystem(PathRayDirection, XAxis, YAxis);
// Calculate Cos of the angle between the direction and the light source normal.
// This is also the Sin of the angle between the direction and the plane perpendicular to the normal.
const float DirectionDotLightNormal = Dot3(PathRayDirection, ChosenPathRay.LightSourceNormal);
checkSlow(DirectionDotLightNormal > 0.0f);
// Calculate Cos of the angle between the direction and the plane perpendicular to the normal using cos^2 + sin^2 = 1
const float CosDirectionNormalPlaneAngle = FMath::Sqrt(1.0f - DirectionDotLightNormal * DirectionDotLightNormal);
// Clamp the cone angle to CosDirectionNormalPlaneAngle so that any direction generated from the cone lies in the same hemisphere
// As the light source normal that was used to generate that direction.
// This is necessary to make sure we only generate directions that the light actually emits in.
// Within the range [0, PI / 2], smaller angles have a larger cosine
// The DELTA bias is to avoid generating directions that are so close to being perpendicular to the normal that their dot product is negative due to fp imprecision.
const float CosEmitConeAngle = FMath::Max(CosIndirectPhotonEmitConeAngle, FMath::Min(CosDirectionNormalPlaneAngle + DELTA, 1.0f));
// Generate a sample direction within a cone about the indirect path
const FVector4 ConeSampleDirection = UniformSampleCone(RandomStream, CosEmitConeAngle, XAxis, YAxis, PathRayDirection);
FLightSurfaceSample SurfaceSample;
float NormalDotSampleDirection = 0.0f;
do
{
// Generate a surface sample
FMeshAreaLight::SampleLightSurface(RandomStream, SurfaceSample);
NormalDotSampleDirection = Dot3(SurfaceSample.Normal, ConeSampleDirection);
}
// Use rejection sampling to find a surface position that is valid for ConeSampleDirection
while(NormalDotSampleDirection < 0.0f);
const float DistanceFromCenter = (SurfaceSample.Position - Position).Size3();
SampleRay = FLightRay(
SurfaceSample.Position,
SurfaceSample.Position + ConeSampleDirection * FMath::Max(InfluenceRadius - DistanceFromCenter, 0.0f),
NULL,
this
);
const float ConePDF = UniformConePDF(CosEmitConeAngle);
RayPDF = 0.0f;
// Calculate the probability that this direction was chosen
for (int32 OtherRayIndex = 0; OtherRayIndex < IndirectPathRays.Num(); OtherRayIndex++)
{
// Accumulate the cone probability for all the cones which contain the sample position
if (Dot3(IndirectPathRays[OtherRayIndex].UnitDirection, ConeSampleDirection) > (1.0f - DELTA) * CosEmitConeAngle)
{
RayPDF += ConePDF;
}
}
RayPDF /= IndirectPathRays.Num();
checkSlow(RayPDF > 0);
Power = TotalPower / TotalSurfaceArea * MeshAreaLightIntensityScale;
}
/** Validates a surface sample given the position that sample is affecting. */
void FMeshAreaLight::ValidateSurfaceSample(const FVector4& Point, FLightSurfaceSample& Sample) const
{
}
/** Returns the light's radiant power. */
float FMeshAreaLight::Power() const
{
const FLinearColor LightPower = TotalPower / TotalSurfaceArea * 2.0f * (float)PI * InfluenceRadius * InfluenceRadius;
return FLinearColorUtils::LinearRGBToXYZ(LightPower).G;
}
/** Generates a sample on the light's surface. */
void FMeshAreaLight::SampleLightSurface(FLMRandomStream& RandomStream, FLightSurfaceSample& Sample) const
{
float PrimitivePDF;
float FloatPrimitiveIndex;
// Pick a primitive with probability proportional to the primitive's fraction of the light's total surface area
Sample1dCDF(PrimitivePDFs, PrimitiveCDFs, UnnormalizedIntegral, RandomStream, PrimitivePDF, FloatPrimitiveIndex);
const int32 PrimitiveIndex = FMath::TruncToInt(FloatPrimitiveIndex * Primitives.Num());
check(PrimitiveIndex >= 0 && PrimitiveIndex < Primitives.Num());
const FMeshLightPrimitive& SelectedPrimitive = Primitives[PrimitiveIndex];
// Approximate the primitive as a coplanar square, and sample uniformly by area
const float Alpha1 = RandomStream.GetFraction();
const FVector4 InterpolatedPosition1 = FMath::Lerp(SelectedPrimitive.Corners[0].WorldPosition, SelectedPrimitive.Corners[1].WorldPosition, Alpha1);
const FVector4 InterpolatedPosition2 = FMath::Lerp(SelectedPrimitive.Corners[2].WorldPosition, SelectedPrimitive.Corners[3].WorldPosition, Alpha1);
const float Alpha2 = RandomStream.GetFraction();
const FVector4 SamplePosition = FMath::Lerp(InterpolatedPosition1, InterpolatedPosition2, Alpha2);
const float SamplePDF = PrimitivePDF / SelectedPrimitive.SurfaceArea;
Sample = FLightSurfaceSample(SamplePosition, SelectedPrimitive.SurfaceNormal, FVector2D(0,0), SamplePDF);
}
/** Returns true if all parts of the light are behind the surface being tested. */
bool FMeshAreaLight::BehindSurface(const FVector4& TrianglePoint, const FVector4& TriangleNormal) const
{
const float NormalDotLight = Dot3(TriangleNormal, FMeshAreaLight::GetDirectLightingDirection(TrianglePoint, TriangleNormal));
return NormalDotLight < 0.0f;
}
/** Gets a single direction to use for direct lighting that is representative of the whole area light. */
FVector4 FMeshAreaLight::GetDirectLightingDirection(const FVector4& Point, const FVector4& PointNormal) const
{
// The position on a sphere approximating the area light surface that will first be visible to a triangle rotating toward the light
const FVector4 FirstVisibleLightPoint = Position + PointNormal * SourceBounds.SphereRadius;
return FirstVisibleLightPoint - Point;
}
}
| 41.695268 | 209 | 0.758276 | [
"mesh",
"vector",
"transform",
"3d",
"solid"
] |
329a1969f2fe837139f69afc97055b625d40f5b1 | 13,421 | hpp | C++ | src/include/miopen/solver.hpp | marty1885/MIOpen | e4fb0b24872505d5cb6009007d2030d4a03e70f8 | [
"MIT"
] | 4 | 2017-07-12T12:05:37.000Z | 2018-09-07T04:00:51.000Z | src/include/miopen/solver.hpp | marty1885/MIOpen | e4fb0b24872505d5cb6009007d2030d4a03e70f8 | [
"MIT"
] | null | null | null | src/include/miopen/solver.hpp | marty1885/MIOpen | e4fb0b24872505d5cb6009007d2030d4a03e70f8 | [
"MIT"
] | 1 | 2020-11-19T11:09:35.000Z | 2020-11-19T11:09:35.000Z | /*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_SOLVER_HPP
#define GUARD_MIOPEN_SOLVER_HPP
#include <vector>
#include <memory>
#include "miopen/mlo_internal.hpp"
#include "miopen/miopen.h"
namespace miopen {
#if __cplusplus < 201402L // For ex. hip is not C++14 yet.
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); // NOLINT
}
#else
using std::make_unique; // re-use as miopen::make_unique
#endif
namespace solver {
/// Describes a kernel source and whatever information required in order
/// to build and run it (the former is unused for binary kernels).
struct KernelInfo
{
std::string comp_options;
std::vector<size_t> l_wk;
std::vector<size_t> g_wk;
std::string kernel_file;
std::string kernel_name;
};
/// Information required to build and run a kernel (or a set of kernels),
/// which is expected to perform computatons as per the problem config.
///
/// TODO: Currently best suits a subset of existing solvers,
/// namely some OpenCL-written forward direct convolutions.
/// Shall be refactored (possibly, to a class hierarchy).
class ConvSolution
{
public:
std::vector<KernelInfo> construction_params; // impl may consist of multiple kernels.
miopenStatus_t status;
int passes;
size_t workspce_sz;
int grp_tile1;
int grp_tile0;
int in_tile1;
int in_tile0;
int out_pix_tile1;
int out_pix_tile0;
int n_out_pix_tiles;
int n_in_data_tiles;
int n_stacks;
ConvSolution(miopenStatus_t status_ = miopenStatusSuccess, int passes_ = 1)
: status(status_),
passes(passes_),
workspce_sz(0),
grp_tile1(-1),
grp_tile0(-1),
in_tile1(-1),
in_tile0(-1),
out_pix_tile1(-1),
out_pix_tile0(-1),
n_out_pix_tiles(-1),
n_in_data_tiles(-1),
n_stacks(-1)
{
}
inline bool Succeeded() const { return status == miopenStatusSuccess; }
};
/// Base class for problem solvers.
///
/// Solvers are to be instantiated as const objects and shall not have any variable
/// internal state. Any non-const state information, if required, to be stored in the
/// solver-specific context objects.
///
/// There could be multiple solvers of the same algorithm for a problem config.
/// For example, ConvAsm3x3U and ConvOclDirectFwd3x3
/// are able to solve overlapping sets of 3x3 Direct convolution problems.
class Solver
{
public:
/// The descendants of this class comprise an solution-specific
/// set of optimization parameters, i.e. those which expected to be used by
/// the solution to optimize its kernel(s) for the best performance.
///
/// This class provides its descendants with polymorphism and supplies syntax
/// glue at the source text level. Also serves as en "empty set of parameters"
/// for solutions which do not have parameters that affect performance
/// (e.g. for 3x3 Wingrad convolutions).
class PerformanceConfig
{
public:
PerformanceConfig() noexcept {}
virtual ~PerformanceConfig() {}
};
virtual ~Solver() {}
/// Returns true if solution can work on given SW/HW platform (runtime/device)
/// and provides correct result for the problem config.
virtual bool IsApplicable(const ConvolutionContext&) const { return true; }
/// Legacy euristic method which shall return false when a solution
/// is known to be slower than some another solution for the same problem config.
/// Intended to be used for performance optimization.
/// Warning: Non-trivial implementations introduce implicit dependencies between solutions.
virtual bool IsFast(const ConvolutionContext&) const { return true; }
/// Given the specific problem config, finds optimization parameters for the solution.
/// Could take long if an exhaustive search is performed/requested.
/// Limitations: The solution shall be adequate for the proglem config.
/// Otherwise, the function may return incorrect results or fail.
///
/// Possible implementation which tries to find optimal configuration
/// in the perfDb (legacy behavior):
///
/// Lookup for a suitable config in the perfDb;
/// if (found) {
/// return (config);
/// } else if (exhaustive search is requested) {
/// Do exhaustive search to find optimal config; // May be slow.
/// Add config to the PerfDb;
/// return (config);
/// }
/// return (solution-specific defaults); // May involve some heuristic math.
///
virtual std::unique_ptr<PerformanceConfig> Find(const ConvolutionContext&) const
{
return miopen::make_unique<PerformanceConfig>();
}
/// Takes problem config, optimization parameters and other info
/// and computes information required to build and run the kernel(s).
virtual ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const = 0;
};
class ConvAsm3x3U : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
bool IsFast(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvAsm5x10u2v2f1 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvAsm5x10u2v2b1 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvAsm7x7c3h224w224k64u2v2p3q3f1 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclDirectFwd11x11 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclDirectFwdGen : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclDirectFwd3x3 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclDirectFwdLegacyExhaustiveSearch : public Solver
{
public:
class PerformanceConfigImpl : public PerformanceConfig
{
public:
int grp_tile1;
int grp_tile0;
int in_tile1;
int in_tile0;
int out_pix_tile1;
int out_pix_tile0;
int n_out_pix_tiles;
int n_in_data_tiles;
int n_stacks;
PerformanceConfigImpl() noexcept : grp_tile1(),
grp_tile0(),
in_tile1(),
in_tile0(),
out_pix_tile1(),
out_pix_tile0(),
n_out_pix_tiles(),
n_in_data_tiles(),
n_stacks()
{
}
inline void CopyTo(ConvSolution& iud) const
{
iud.grp_tile0 = grp_tile0;
iud.grp_tile1 = grp_tile1;
iud.in_tile0 = in_tile0;
iud.in_tile1 = in_tile1;
iud.out_pix_tile0 = out_pix_tile0;
iud.out_pix_tile1 = out_pix_tile1;
iud.n_out_pix_tiles = n_out_pix_tiles;
iud.n_in_data_tiles = n_in_data_tiles;
iud.n_stacks = n_stacks;
}
};
std::unique_ptr<PerformanceConfig> Find(const ConvolutionContext& params) const override;
private:
void SearchDirect2D(const ConvolutionContext& params, PerformanceConfigImpl& result) const;
int MeasureLoop(miopen::Handle* profile_h,
Data_t bot_ocl_buf,
Data_t top_ocl_buf,
Data_t wei_ocl_buf,
Data_t bias_ocl_buf,
double& processing_time,
const ConvolutionContext& params,
const PerformanceConfigImpl& result) const;
static const std::vector<std::unique_ptr<const Solver>>& GetImplementationsToMeasure();
};
class ConvOclDirectFwd : public ConvOclDirectFwdLegacyExhaustiveSearch
{
public:
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclDirectFwd1x1 : public ConvOclDirectFwdLegacyExhaustiveSearch
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclDirectFwdC : public ConvOclDirectFwdLegacyExhaustiveSearch
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvBinWinograd3x3U : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvBinWinogradRxSFwd : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvAsmBwdWrW3x3 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
bool IsFast(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclBwdWrW2 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclBwdWrW53 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
class ConvOclBwdWrW1x1 : public Solver
{
public:
bool IsApplicable(const ConvolutionContext& params) const override;
ConvSolution GetSolution(const ConvolutionContext& params,
const PerformanceConfig& exhaustive_search_result) const override;
};
} // namespace solver
} // namespace miopen
#endif // GUARD_MIOPEN_SOLVER_HPP
| 37.074586 | 98 | 0.669101 | [
"vector"
] |
329decc693b102228d465b42458a5394d22a405d | 1,035 | cpp | C++ | src/IO/H5/Header.cpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/IO/H5/Header.cpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/IO/H5/Header.cpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "IO/H5/Header.hpp"
#include <algorithm>
#include <regex>
#include <sstream>
#include <vector>
#include "IO/H5/Helpers.hpp"
#include "Informer/InfoFromBuild.hpp"
#include "Utilities/StdHelpers.hpp"
namespace h5 {
/// \cond HIDDEN_SYMOLS
Header::Header(const bool exists, detail::OpenGroup&& group,
const hid_t location, const std::string& name)
: group_(std::move(group)) {
if (exists) {
header_info_ =
h5::read_rank1_attribute<std::string>(location, name + extension())[0];
} else {
std::vector<std::string> header_info{[]() {
std::stringstream ss;
ss << "#\n# File created on " << current_date_and_time() << "# ";
auto build_info = info_from_build();
ss << std::regex_replace(build_info, std::regex{"\n"}, "\n# ");
return ss.str();
}()};
write_to_attribute(location, name + extension(), header_info);
header_info_ = header_info[0];
}
}
/// \endcond
} // namespace h5
| 27.972973 | 79 | 0.644444 | [
"vector"
] |
32b738c8ba4d38f6b98520676574c7d528d07ce5 | 1,430 | cpp | C++ | test/src/meshTestUtils.cpp | milindasf/Dendro-5.01 | ea92ba54860c500b656921ebbd2f5cf2d8dfc55d | [
"MIT"
] | 16 | 2018-12-22T02:05:46.000Z | 2021-12-16T23:47:43.000Z | test/src/meshTestUtils.cpp | milindasf/Dendro-5.01 | ea92ba54860c500b656921ebbd2f5cf2d8dfc55d | [
"MIT"
] | 1 | 2019-11-06T22:17:32.000Z | 2019-11-07T20:23:44.000Z | test/src/meshTestUtils.cpp | milindasf/Dendro-5.01 | ea92ba54860c500b656921ebbd2f5cf2d8dfc55d | [
"MIT"
] | 5 | 2019-07-09T02:59:27.000Z | 2020-12-12T16:57:45.000Z | /**
* @file meshTestUtils.cpp
* @author Milinda Fernando (milinda@cs.utah.edu)
* @brief meshTest utility functiuons.
* @version 0.1
* @date 2020-01-16
*
* School of Computing, University of Utah.
* @copyright Copyright (c) 2020
*
*/
#include "meshTestUtils.h"
bool ot::test::isBlkFlagsValid(const ot::Mesh* pMesh)
{
if(pMesh->isActive())
{
const ot::TreeNode * pNodes= &(*(pMesh->getAllElements().begin()));
const unsigned int nodeLocalBegin = pMesh->getNodeLocalBegin();
const unsigned int nodeLocalEnd = pMesh->getNodeLocalEnd();
const unsigned int* e2n_cg = &(*(pMesh->getE2NMapping().begin()));
const unsigned int* e2e = &(*(pMesh->getE2EMapping().begin()));
const std::vector<ot::Block>& blkList = pMesh->getLocalBlockList();
const unsigned int nPe = pMesh->getNumNodesPerElement();
unsigned int lookup,node_cg;
unsigned int child[NUM_CHILDREN];
for(unsigned int blk =0; blk < blkList.size(); blk ++)
{
std::vector<unsigned int > gid;
computeBlockUnzipGhostNodes(pMesh,blk,gid);
if( (gid.empty() && blkList[blk].getBlockType() == ot::BlockType::UNZIP_DEPENDENT ) || (!gid.empty() && blkList[blk].getBlockType() == ot::BlockType::UNZIP_INDEPENDENT ))
return false;
}
return true;
}else
return true;
}
| 28.039216 | 183 | 0.606294 | [
"mesh",
"vector"
] |
32be4e88a1bd13b2a36f7925abbdf318380c3b7a | 4,269 | cpp | C++ | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Edge gesture invocation sample (Windows 8)/C++/ScenarioInput1.xaml.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Edge gesture invocation sample (Windows 8)/C++/ScenarioInput1.xaml.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Edge gesture invocation sample (Windows 8)/C++/ScenarioInput1.xaml.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
//
// ScenarioInput1.xaml.cpp
// Implementation of the ScenarioInput1 class
//
#include "pch.h"
#include "ScenarioInput1.xaml.h"
using namespace EdgeGestureSample;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::ViewManagement;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
ScenarioInput1::ScenarioInput1()
{
InitializeComponent();
}
ScenarioInput1::~ScenarioInput1()
{
}
#pragma region Template-Related Code - Do not remove
void ScenarioInput1::OnNavigatedTo(NavigationEventArgs^ e)
{
// Get a pointer to our main page.
rootPage = dynamic_cast<MainPage^>(e->Parameter);
// We want to be notified when the OutputFrame is loaded so we can get to the content.
_frameLoadedToken = rootPage->OutputFrameLoaded += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &ScenarioInput1::rootPage_OutputFrameLoaded);
}
void ScenarioInput1::OnNavigatedFrom(NavigationEventArgs^ e)
{
rootPage->RightTapped -= RightClickEventToken;
EdgeGesture^ edgeGesture = Windows::UI::Input::EdgeGesture::GetForCurrentView();
edgeGesture->Starting -= EdgeGestureStartingEventToken;
edgeGesture->Completed -= EdgeGestureCompletedEventToken;
edgeGesture->Canceled -= EdgeGestureCanceledEventToken;
rootPage->OutputFrameLoaded -= _frameLoadedToken;
}
#pragma endregion
#pragma region Use this code if you need access to elements in the output frame - otherwise delete
void ScenarioInput1::rootPage_OutputFrameLoaded(Object^ sender, Object^ e)
{
// Get a pointer to the content within the OutputFrame.
Page^ outputFrame = dynamic_cast<Page^>(rootPage->OutputFrame->Content);
outputText = dynamic_cast<TextBlock^>(outputFrame->FindName("OutputText"));
InitializeEdgeGestureHandlers();
}
#pragma endregion
#pragma region Event handlers
void ScenarioInput1::OnStarting(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
{
outputText->Text = "Invoking with touch.";
}
void ScenarioInput1::OnCompleted(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
{
// Determine whether it was touch or keyboard invocation
if (e->Kind == Windows::UI::Input::EdgeGestureKind::Touch)
{
outputText->Text = "Invoked with touch.";
}
else if (e->Kind == Windows::UI::Input::EdgeGestureKind::Keyboard)
{
outputText->Text = "Invoked with keyboard.";
}
else if (e->Kind == Windows::UI::Input::EdgeGestureKind::Mouse)
{
outputText->Text = "Invoked with right-click.";
}
}
void ScenarioInput1::OnCanceled(EdgeGesture^ sender, EdgeGestureEventArgs^ e)
{
outputText->Text = "Canceled with touch.";
}
void ScenarioInput1::OnContextMenu(Object^ sender, RightTappedRoutedEventArgs^ e)
{
outputText->Text = "Invoked with right-click.";
}
void ScenarioInput1::InitializeEdgeGestureHandlers()
{
EdgeGesture^ edgeGesture = Windows::UI::Input::EdgeGesture::GetForCurrentView();
EdgeGestureStartingEventToken = edgeGesture->Starting += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput1::OnStarting);
EdgeGestureCompletedEventToken = edgeGesture->Completed += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput1::OnCompleted);
EdgeGestureCanceledEventToken = edgeGesture->Canceled += ref new TypedEventHandler<EdgeGesture^, EdgeGestureEventArgs^>(this, &ScenarioInput1::OnCanceled);
RightClickEventToken = rootPage->RightTapped += ref new RightTappedEventHandler(this, &ScenarioInput1::OnContextMenu);
outputText->Text = "Sample initialized and events registered.";
}
#pragma endregion
| 34.427419 | 167 | 0.757086 | [
"object"
] |
77f7ae33c6d0183d43df87489d13f69180b1cbe5 | 4,649 | cpp | C++ | com/netfx/src/clr/managedlibraries/custommarshalers/enumeratorviewofenumvariant.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/clr/managedlibraries/custommarshalers/enumeratorviewofenumvariant.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/clr/managedlibraries/custommarshalers/enumeratorviewofenumvariant.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//*****************************************************************************
// EnumeratorToEnumVariantMarshaler.cpp
//
// This file provides the implemention of the EnumeratorToEnumVariantMarshaler
// class. This class is used to convert an IEnumerator to an IEnumVariant.
//
//*****************************************************************************
#using <mscorlib.dll>
#include "EnumeratorViewOfEnumVariant.h"
OPEN_CUSTOM_MARSHALERS_NAMESPACE()
#include <malloc.h>
// The count of VARIANTS to that are requested every time we call Next.
// ! changed from 64 to 1 (see B#93197)
static const int NUM_VARS_REQUESTED = 1;
EnumeratorViewOfEnumVariant::EnumeratorViewOfEnumVariant(Object *pEnumVariantObj)
: m_pEnumVariantObj(pEnumVariantObj)
, m_CurrIndex(0)
, m_apObjs(new Object*[0])
, m_bFetchedLastBatch(false)
{
}
bool EnumeratorViewOfEnumVariant::MoveNext()
{
// Increment the current index.
m_CurrIndex++;
// If we have reached the end of the cached array of objects, then
// we need to retrieve more elements from the IEnumVARIANT.
if (m_CurrIndex >= m_apObjs.Length)
return GetNextElems();
// We have not yet reached the end of the cached array of objects.
m_pCurrObj = m_apObjs[m_CurrIndex];
return true;
}
Object *EnumeratorViewOfEnumVariant::get_Current()
{
return m_pCurrObj;
}
void EnumeratorViewOfEnumVariant::Reset()
{
IEnumVARIANT *pEnumVariant = NULL;
try
{
pEnumVariant = GetEnumVariant();
IfFailThrow(pEnumVariant->Reset());
m_apObjs = new Object*[0];
m_pCurrObj = NULL;
m_CurrIndex = 0;
m_bFetchedLastBatch = false;
}
__finally
{
if (pEnumVariant)
pEnumVariant->Release();
}
}
IEnumVARIANT *EnumeratorViewOfEnumVariant::GetEnumVariant()
{
IUnknown *pUnk = NULL;
IEnumVARIANT *pEnumVariant = NULL;
try
{
pUnk = (IUnknown *)FROMINTPTR(Marshal::GetIUnknownForObject(m_pEnumVariantObj));
IfFailThrow(pUnk->QueryInterface(IID_IEnumVARIANT, (void**)&pEnumVariant));
}
__finally
{
if (pUnk)
pUnk->Release();
}
return pEnumVariant;
}
bool EnumeratorViewOfEnumVariant::GetNextElems()
{
VARIANT *aVars;
ULONG cFetched = 0;
HRESULT hr;
IEnumVARIANT *pEnumVariant = NULL;
// If we have already retrieved the last batch, then do not try to retrieve
// more. This is required because some IEnumVARIANT implementations reset
// themselves and restart from the beginning if they are called after having
// returned S_FALSE;
if (m_bFetchedLastBatch)
{
m_apObjs = new Object*[0];
m_pCurrObj = NULL;
return false;
}
// Initialize the variant array before we call Next().
aVars = reinterpret_cast<VARIANT*>(_alloca(NUM_VARS_REQUESTED * sizeof(VARIANT)));
memset(aVars, 0, NUM_VARS_REQUESTED * sizeof(VARIANT));
try
{
// Retrieve the IEnumVARIANT pointer.
pEnumVariant = GetEnumVariant();
// Go to the native IEnumVariant to get the next element.
IfFailThrow(hr = pEnumVariant->Next(NUM_VARS_REQUESTED, aVars, &cFetched));
// Check for end of enumeration condition.
if (hr == S_FALSE)
{
// Remember this is the last batch.
m_bFetchedLastBatch = true;
// If the last batch is empty, then return false right away.
if (cFetched == 0)
{
// There are no more elements.
m_apObjs = new Object*[0];
m_pCurrObj = NULL;
return false;
}
}
// Convert the variants to objects.
m_apObjs = Marshal::GetObjectsForNativeVariants((IntPtr)aVars, cFetched);
// Set the current index back to 0.
m_CurrIndex = 0;
// Retrieve the current object.
m_pCurrObj = m_apObjs[m_CurrIndex];
}
__finally
{
// If we managed to retrieve an IDispatch pointer then release it.
if (pEnumVariant)
pEnumVariant->Release();
// Clear the variants we got back from Next.
for (int i = 0; i < cFetched; i++)
VariantClear(&aVars[i]);
}
// We have not yet reached the end of the enumeration.
return true;
}
CLOSE_CUSTOM_MARSHALERS_NAMESPACE()
| 27.187135 | 89 | 0.594536 | [
"object"
] |
77fe4dd50c3ae5ee4d84338aed47a95949954c24 | 12,391 | hpp | C++ | Sources/SolarTears/Rendering/Vulkan/VulkanShaders.hpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | 4 | 2021-06-30T16:00:20.000Z | 2021-10-13T06:17:56.000Z | Sources/SolarTears/Rendering/Vulkan/VulkanShaders.hpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | Sources/SolarTears/Rendering/Vulkan/VulkanShaders.hpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "../../../3rdParty/SPIRV-Reflect/spirv_reflect.h"
#include <vulkan/vulkan.h>
#include <span>
#include <unordered_map>
#include "../../Core/DataStructures/Span.hpp"
#include "../Common/FrameGraph/ModernFrameGraphMisc.hpp"
#include "FrameGraph/VulkanRenderPass.hpp"
#include "FrameGraph/VulkanFrameGraphMisc.hpp"
#include "VulkanDescriptors.hpp"
class LoggerQueue;
namespace Vulkan
{
//Shader database for render passes.
//We can't load shaders individually for each pass when needed because of a complex problem.
//Suppose pass A accesses scene textures in vertex shader and pass B accesses them in fragment shader.
//This means the (common) texture descriptor set layout must have VERTEX | FRAGMENT shader flags.
//Since we create descriptor set layouts based on reflection data, we have to:
//1) Load all possible shaders for passes;
//2) Go through the whole reflection data for all shaders and build descriptor set layouts;
//3) Create passes only after that, giving them descriptor set layouts.
//This is all to avoid loading the shaders twice - once to obtain the reflection data, once to create pipelines
class SamplerManager;
class DescriptorDatabase;
class SharedDescriptorDatabaseBuilder;
class PassDescriptorDatabaseBuilder;
class ShaderDatabase
{
using BindingDomain = uint16_t;
using BindingType = uint16_t;
static constexpr BindingDomain UndefinedSetDomain = 0xffff;
static constexpr BindingDomain SharedSetDomain = 0x0000;
//The data structure to store information about the binding domain (Shared, Pass 1, Pass 2, etc)
struct DomainRecord
{
RenderPassType PassType;
uint32_t FirstLayoutNodeIndex;
};
//The data structure to store information about which passes use which bindings
struct BindingRecord
{
BindingDomain Domain; //Type of the pass that uses the set (Shared, Pass 1, Pass 2, etc.)
uint16_t Type; //Per-domain binding type
VkDescriptorType DescriptorType; //Descriptor type for the binding (used for validation purposes)
uint32_t DescriptorFlags; //Descriptor flags for the binding (used for validation purposes)
};
//The node of a set layout information for a particular domain
//All layouts for a domain are stored in an array-backed linked list
struct SetLayoutRecordNode
{
VkDescriptorSetLayout SetLayout; //Set layout object
Span<uint32_t> BindingSpan; //Binding span for the set
uint32_t NextNodeIndex; //The index of the next binding span node in the same domain
};
//The data structure to store information about pass constants used by a shader group
struct PushConstantRecord
{
std::string_view Name;
uint32_t Offset;
VkShaderStageFlags ShaderStages;
};
//The data structure to refer to ranges of push constant infos
struct PushConstantSpans
{
Span<uint32_t> RecordSpan; //Span of PushConstantRecords
Span<uint32_t> RangeSpan; //Span of VkPushConstantRanges
};
//The data structure to create descriptor set span
struct DescriptorSetSpanMetadata
{
uint32_t PassId; //Frame graph-specific pass id for pass sets or -1 for shared sets
Span<uint32_t> SetLayoutNodeSpan; //The span in mSetLayoutIndicesPerGroupSequences for this descriptor set span
};
public:
ShaderDatabase(VkDevice device, SamplerManager* samplerManager, LoggerQueue* logger);
~ShaderDatabase();
//Registers a render pass in the database
void RegisterPass(RenderPassType passType);
//Registers a shader group in the database
void RegisterShaderGroup(std::string_view groupName, std::span<std::wstring> shaderPaths);
//Get the byte-code and byte-code size of the registered shader in path
void GetRegisteredShaderInfo(const std::wstring& path, const uint32_t** outShaderData, uint32_t* outShaderSize) const;
//Get the offset + shader stages for the registered push constant pushConstantName in shader group groupName
void GetPushConstantInfo(std::string_view groupName, std::string_view pushConstantName, uint32_t* outPushConstantOffset, VkShaderStageFlags* outShaderStages) const;
//Create set layouts from the database infos
void BuildSetLayouts(const DeviceParameters* deviceParameters);
//Creates a pipeline layout compatible for multiple shader groups
//The set layouts in the pipeline layout are minimal matching set in groupNamesForSets
//The push constants are minimal matching set in groupNamesForPushConstants
//Returns nullptr if no matching pipeline layout can be created
void CreateMatchingPipelineLayout(std::span<std::string_view> groupNamesForSets, std::span<std::string_view> groupNamesForPushConstants, VkPipelineLayout* outPipelineLayout) const;
//Calculates and returns the optimal VkDescriptorSet span for shaderGroupSequence. The span returned is not yet ready-to-be-used; it's gonna be revalidated after a call to FillPassSets
//The span is built in such a way that binding pipelines according to order in shaderGroupSequence would produce the least amount of descriptors needed to be rebound
//Returns the descriptor sub-span for each entry in shaderGroupSequence in outBindSubspansPerGroup
//Returns the firstSet parameter for vkBindDescriptorSets for each entry in shaderGroupSequence in outBindPointsPerGroup
std::span<VkDescriptorSet> AssignPassSets(uint32_t passIndex, std::span<const std::string_view> shaderGroupSequence, std::span<DescriptorSetBindRange> outBindRangesPerGroup);
//Registers the set create infos in databases and transfers the ownership of all set layouts from shared domain to shared descriptor database
void FlushDescriptorSetData(SharedDescriptorDatabaseBuilder* sharedDatabaseBuilder, PassDescriptorDatabaseBuilder* passDatabaseBuilder);
//Returns the start of the mock spans that AssignPassSets calls return
//DO NOT dereference this pointer! It's only used in address calculations
VkDescriptorSet* GetOriginalDescriptorSpanStart() const;
private:
//Functions for collecting bindings and push constants
void RegisterBindings(const std::string_view groupName, const std::span<std::wstring> shaderModuleNames);
void RegisterPushConstants(std::string_view groupName, const std::span<std::wstring> shaderModuleNames);
private:
//Divides inoutSpvSets into two parts: already known sets (with .set < pivotSetIndex) and new sets (with .set >= pivotSetIndex)
void SplitSetsByPivot(uint32_t pivotSetIndex, std::vector<SpvReflectDescriptorSet*>& inoutSpvSets, std::span<SpvReflectDescriptorSet*>* outExistingSetSpan, std::span<SpvReflectDescriptorSet*>* outNewSetSpan);
//Finds the necessary set sizes for each of moduleUpdatedSets
void CalculateUpdatedSetSizes(const std::span<SpvReflectDescriptorSet*> moduleUpdatedSets, const std::vector<Span<uint32_t>>& existingBindingSpansPerSet, std::vector<uint32_t>& outUpdatedSetSizes);
//Updates inoutBindings with new set data
void MergeExistingSetBindings(const std::span<SpvReflectDescriptorSet*> setUpdates, std::vector<SpvReflectDescriptorBinding*>& inoutBindings, std::vector<Span<uint32_t>>& inoutSetSpans);
void MergeNewSetBindings(const std::span<SpvReflectDescriptorSet*> newSets, std::vector<SpvReflectDescriptorBinding*>& inoutBindings, std::vector<Span<uint32_t>>& inoutSetSpans);
private:
//Add set layout info to the database
uint32_t RegisterSetLayout(uint16_t setDomain, const std::span<VkDescriptorSetLayoutBinding> setBindings, const std::span<BindingRecord> setBindingRecords);
//Validate set domain for binding list
uint16_t ValidateSetDomain(const std::span<BindingRecord> setBindingRecords);
private:
//Collects all push constant records from shader modules
void CollectPushConstantRecords(const std::span<std::wstring> shaderModuleNames, std::vector<PushConstantRecord>& outPushConstantRecords);
//Registers push constant records in the database
//The records are expected to be lexicographically sorted
//Returns the span of the new records
Span<uint32_t> RegisterPushConstantRecords(const std::span<PushConstantRecord> lexicographicallySortedRecords);
//Registers push constant ranges in the database, created from provided push constant records
//Returns the span of the new ranges
Span<uint32_t> RegisterPushConstantRanges(const std::span<PushConstantRecord> records);
private:
//Finds a span in mSetLayoutsFlat
Span<uint32_t> FindMatchingSetLayoutSpan(std::span<std::string_view> groupNames) const;
//Finds a span in mPushConstantRanges
Span<uint32_t> FindMatchingPushConstantRangeSpan(std::span<std::string_view> groupNames) const;
private:
//Transform SPIR-V Reflect types to Vulkan types
VkShaderStageFlagBits SpvToVkShaderStage(SpvReflectShaderStageFlagBits spvShaderStage) const;
VkDescriptorType SpvToVkDescriptorType(SpvReflectDescriptorType spvDescriptorType) const;
//Validate a new binding against the database reference binding with the same name
bool ValidateNewBinding(const VkDescriptorSetLayoutBinding& bindingInfo, VkDescriptorType expectedDescriptorType, VkDescriptorBindingFlags expectedDescriptorFlags) const;
//Validate a new binding against an already registered binding
bool ValidateExistingBinding(const VkDescriptorSetLayoutBinding& newBindingInfo, const VkDescriptorSetLayoutBinding& existingBindingInfo) const;
private:
LoggerQueue* mLogger;
const VkDevice mDeviceRef;
const SamplerManager* mSamplerManagerRef;
//Loaded shader modules per shader path
std::unordered_map<std::wstring, spv_reflect::ShaderModule> mLoadedShaderModules;
//Set layout records for each shader group name
//Each entry in mLayoutNodeRecordIndexSpansPerShaderGroup references a span in mLayoutRecordNodeIndicesFlat and a span in mSetLayoutsForCreatePipelineFlat
//Each entry in mLayoutRecordNodeIndicesFlat references an entry in mSetLayoutRecordNodes
//The mSetLayoutsForCreatePipelineFlat list is non-owning and only used by vkCreatePipelineLayout call
std::unordered_map<std::string_view, Span<uint32_t>> mLayoutNodeRecordIndexSpansPerShaderGroup;
std::vector<uint32_t> mLayoutRecordNodeIndicesFlat;
std::vector<VkDescriptorSetLayout> mSetLayoutsForCreatePipelineFlat;
//Push constant ranges and records for each shader group name
//Each entry in mPushConstantSpansPerShaderGroup references a span in mPushConstantRecordsFlat and a span in mPushConstantRangesFlat
//Each push constant span in mPushConstantRecordsFlat is lexicographically sorted by the push constant name
std::unordered_map<std::string_view, PushConstantSpans> mPushConstantSpansPerShaderGroup;
std::vector<PushConstantRecord> mPushConstantRecordsFlat;
std::vector<VkPushConstantRange> mPushConstantRangesFlat;
//The flat list of domain records.
//Each domain record references the head of the linked sublist in mSetLayoutRecordNodes, allowing to traverse all the layouts for the domain
std::vector<DomainRecord> mDomainRecords;
//The flat list of registered set layouts.
//Each record references a span in mLayoutBindingsFlat, mLayoutBindingFlagsFlat, and mLayoutBindingTypesFlat, which describe the bindings for the layout
//Layout records for the same domain form linked sublists in the array
std::vector<SetLayoutRecordNode> mSetLayoutRecordNodes;
//Bindings per layout
//These are stored separately because mLayoutBindingsFlat and mLayoutBindingFlagsFlat are needed as separate arrays
std::vector<VkDescriptorSetLayoutBinding> mLayoutBindingsFlat; //Binding infos
std::vector<VkDescriptorBindingFlags> mLayoutBindingFlagsFlat; //Binding flags
std::vector<uint16_t> mLayoutBindingTypesFlat; //Pass-specific binding types
//Registered information needed to create optimal descriptor sets for shader group sequences
std::vector<DescriptorSetSpanMetadata> mSetSpanMetadatasPerGroupSequences;
std::vector<uint32_t> mSetLayoutIndicesForGroupSequences;
//Domain records per pass type
std::unordered_map<RenderPassType, BindingDomain> mPassDomainMap;
//Indices in mLayoutBindingRecordsFlat/mLayoutBindingFlagsFlat/mLayoutBindingTypesFlat for each binding record name
std::unordered_map<std::string_view, BindingRecord> mBindingRecordMap;
};
} | 54.346491 | 210 | 0.790574 | [
"render",
"object",
"vector",
"transform"
] |
ae0865fba8f910c157bf19f6e8269fd67183f93e | 3,517 | cpp | C++ | mp/src/old/dlls/te_killplayerattachments.cpp | MaartenS11/Team-Fortress-Invasion | f36b96d27f834d94e0db2d2a9470b05b42e9b460 | [
"Unlicense"
] | 1 | 2021-03-20T14:27:45.000Z | 2021-03-20T14:27:45.000Z | mp/src/old/dlls/te_killplayerattachments.cpp | MaartenS11/Team-Fortress-Invasion | f36b96d27f834d94e0db2d2a9470b05b42e9b460 | [
"Unlicense"
] | null | null | null | mp/src/old/dlls/te_killplayerattachments.cpp | MaartenS11/Team-Fortress-Invasion | f36b96d27f834d94e0db2d2a9470b05b42e9b460 | [
"Unlicense"
] | null | null | null | //======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "basetempentity.h"
//-----------------------------------------------------------------------------
// Purpose: Dispatches blood stream tempentity
//-----------------------------------------------------------------------------
class CTEKillPlayerAttachments : public CBaseTempEntity
{
public:
DECLARE_CLASS( CTEKillPlayerAttachments, CBaseTempEntity );
CTEKillPlayerAttachments( const char *name );
virtual ~CTEKillPlayerAttachments( void );
virtual void Test( const Vector& current_origin, const QAngle& current_angles );
virtual void Create( IRecipientFilter& filter, float delay = 0.0f );
DECLARE_SERVERCLASS();
public:
CNetworkVar( int, m_nPlayer );
};
//-----------------------------------------------------------------------------
// Purpose:
// Input : *name -
//-----------------------------------------------------------------------------
CTEKillPlayerAttachments::CTEKillPlayerAttachments( const char *name ) :
CBaseTempEntity( name )
{
m_nPlayer = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTEKillPlayerAttachments::~CTEKillPlayerAttachments( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *current_origin -
// *current_angles -
//-----------------------------------------------------------------------------
void CTEKillPlayerAttachments::Test( const Vector& current_origin, const QAngle& current_angles )
{
m_nPlayer = 1;
CBroadcastRecipientFilter filter;
Create( filter, 0.0 );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : msg_dest -
// delay -
// *origin -
// *recipient -
//-----------------------------------------------------------------------------
void CTEKillPlayerAttachments::Create( IRecipientFilter& filter, float delay )
{
engine->PlaybackTempEntity( filter, delay,
(void *)this, GetServerClass()->m_pTable, GetServerClass()->m_ClassID );
}
IMPLEMENT_SERVERCLASS_ST(CTEKillPlayerAttachments, DT_TEKillPlayerAttachments)
SendPropInt( SENDINFO(m_nPlayer), 5, SPROP_UNSIGNED ),
END_SEND_TABLE()
// Singleton to fire TEKillPlayerAttachments objects
static CTEKillPlayerAttachments g_TEKillPlayerAttachments( "KillPlayerAttachments" );
//-----------------------------------------------------------------------------
// Purpose:
// Input : msg_dest -
// delay -
// *origin -
// *recipient -
// player -
//-----------------------------------------------------------------------------
void TE_KillPlayerAttachments( IRecipientFilter& filter, float delay,
int player )
{
g_TEKillPlayerAttachments.m_nPlayer = player;
// Send it over the wire
g_TEKillPlayerAttachments.Create( filter, delay );
} | 32.869159 | 97 | 0.490759 | [
"vector"
] |
ae0b6e1fbb51c89cdc68d202644e4234c7dd0d4e | 6,910 | hpp | C++ | sciplot/specs/BorderSpecs.hpp | Overhatted/sciplot | ca0bd2ceb70e799d2d55ba7e28f6d73a5d3f2854 | [
"MIT"
] | 397 | 2019-01-13T13:05:11.000Z | 2022-03-27T09:30:27.000Z | sciplot/specs/BorderSpecs.hpp | Overhatted/sciplot | ca0bd2ceb70e799d2d55ba7e28f6d73a5d3f2854 | [
"MIT"
] | 76 | 2019-01-14T06:56:59.000Z | 2022-02-02T09:37:47.000Z | sciplot/specs/BorderSpecs.hpp | Overhatted/sciplot | ca0bd2ceb70e799d2d55ba7e28f6d73a5d3f2854 | [
"MIT"
] | 56 | 2019-01-13T16:00:18.000Z | 2022-03-25T14:12:36.000Z | // sciplot - a modern C++ scientific plotting library powered by gnuplot
// https://github.com/sciplot/sciplot
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2018-2021 Allan Leal
//
// 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
// C++ includes
#include <bitset>
#include <sciplot/Default.hpp>
#include <sciplot/specs/DepthSpecsOf.hpp>
#include <sciplot/specs/LineSpecsOf.hpp>
#include <sciplot/Utils.hpp>
// sciplot includes
namespace sciplot {
/// The class used to specify options for plot border.
class BorderSpecs : public LineSpecsOf<BorderSpecs>, public DepthSpecsOf<BorderSpecs>
{
public:
/// Construct a default border instance.
BorderSpecs();
/// Remove all border edges from a 2d or 3d plot.
auto clear() -> BorderSpecs&;
/// Set all border edges to inactive. Methods none and clear have identical effect.
auto none() -> BorderSpecs&;
/// Activate the bottom border edge on the xy plane for a 2d plot.
auto bottom() -> BorderSpecs&;
/// Activate the left border edge on the xy plane for a 2d plot.
auto left() -> BorderSpecs&;
/// Activate the top border edge on the xy plane for a 2d plot.
auto top() -> BorderSpecs&;
/// Activate the right border edge on the xy plane for a 2d plot.
auto right() -> BorderSpecs&;
/// Activate the border edge on the bottom xy plane going from the left corner to front corner in a 3d perspective.
auto bottomLeftFront() -> BorderSpecs&;
/// Activate the border edge on the bottom xy plane going from the left corder to back corner in a 3d perspective.
auto bottomLeftBack() -> BorderSpecs&;
/// Activate the border edge on the bottom xy plane going from the right corner to front corner in a 3d perspective.
auto bottomRightFront() -> BorderSpecs&;
/// Activate the border edge on the bottom xy plane going from the right corder to back corner in a 3d perspective.
auto bottomRightBack() -> BorderSpecs&;
/// Activate the left vertical border edge in a 3d perspective.
auto leftVertical() -> BorderSpecs&;
/// Activate the back vertical border edge in a 3d perspective.
auto backVertical() -> BorderSpecs&;
/// Activate the right vertical border edge in a 3d perspective.
auto rightVertical() -> BorderSpecs&;
/// Activate the front vertical border edge in a 3d perspective.
auto frontVertical() -> BorderSpecs&;
/// Activate the border edge on the top xy plane going from the left corner to back corner in a 3d perspective.
auto topLeftBack() -> BorderSpecs&;
/// Activate the border edge on the top xy plane going from the right corder to back corner in a 3d perspective.
auto topRightBack() -> BorderSpecs&;
/// Activate the border edge on the top xy plane going from the left corner to front corner in a 3d perspective.
auto topLeftFront() -> BorderSpecs&;
/// Activate the border edge on the top xy plane going from the right corder to front corner in a 3d perspective.
auto topRightFront() -> BorderSpecs&;
/// Set the border for polar plot.
auto polar() -> BorderSpecs&;
/// Convert this BorderSpecs object into a gnuplot formatted string.
auto repr() const -> std::string;
private:
/// The bits encoding the active and inactive borders.
std::bitset<13> m_encoding;
/// The placement depth of the borders.
std::string m_depth;
};
inline BorderSpecs::BorderSpecs()
{
left();
bottom();
lineType(internal::DEFAULT_BORDER_LINETYPE);
lineWidth(internal::DEFAULT_BORDER_LINEWIDTH);
lineColor(internal::DEFAULT_BORDER_LINECOLOR);
front();
}
inline auto BorderSpecs::clear() -> BorderSpecs&
{
m_encoding.reset();
return *this;
}
inline auto BorderSpecs::none() -> BorderSpecs&
{
return clear();
}
inline auto BorderSpecs::bottom() -> BorderSpecs&
{
m_encoding.set(0);
return *this;
}
inline auto BorderSpecs::left() -> BorderSpecs&
{
m_encoding.set(1);
return *this;
}
inline auto BorderSpecs::top() -> BorderSpecs&
{
m_encoding.set(2);
return *this;
}
inline auto BorderSpecs::right() -> BorderSpecs&
{
m_encoding.set(3);
return *this;
}
inline auto BorderSpecs::bottomLeftFront() -> BorderSpecs&
{
m_encoding.set(0);
return *this;
}
inline auto BorderSpecs::bottomLeftBack() -> BorderSpecs&
{
m_encoding.set(1);
return *this;
}
inline auto BorderSpecs::bottomRightFront() -> BorderSpecs&
{
m_encoding.set(2);
return *this;
}
inline auto BorderSpecs::bottomRightBack() -> BorderSpecs&
{
m_encoding.set(3);
return *this;
}
inline auto BorderSpecs::leftVertical() -> BorderSpecs&
{
m_encoding.set(4);
return *this;
}
inline auto BorderSpecs::backVertical() -> BorderSpecs&
{
m_encoding.set(5);
return *this;
}
inline auto BorderSpecs::rightVertical() -> BorderSpecs&
{
m_encoding.set(6);
return *this;
}
inline auto BorderSpecs::frontVertical() -> BorderSpecs&
{
m_encoding.set(7);
return *this;
}
inline auto BorderSpecs::topLeftBack() -> BorderSpecs&
{
m_encoding.set(8);
return *this;
}
inline auto BorderSpecs::topRightBack() -> BorderSpecs&
{
m_encoding.set(9);
return *this;
}
inline auto BorderSpecs::topLeftFront() -> BorderSpecs&
{
m_encoding.set(10);
return *this;
}
inline auto BorderSpecs::topRightFront() -> BorderSpecs&
{
m_encoding.set(11);
return *this;
}
inline auto BorderSpecs::polar() -> BorderSpecs&
{
m_encoding.set(2);
return *this;
}
inline auto BorderSpecs::repr() const -> std::string
{
std::stringstream ss;
ss << "set border " << m_encoding.to_ulong() << " ";
ss << DepthSpecsOf<BorderSpecs>::repr() << " ";
ss << LineSpecsOf<BorderSpecs>::repr();
return internal::removeExtraWhitespaces(ss.str());
}
} // namespace sciplot
| 27.975709 | 120 | 0.697974 | [
"object",
"3d"
] |
ae1266f09d8834d7f391ae8a58842d60f2232734 | 4,355 | hpp | C++ | shared/src/shared/wind/base_functions.hpp | dumheter/wind_simulation | adf731847cb6145a85792a0ebceacc725a3acf9e | [
"MIT"
] | 1 | 2021-04-26T11:24:02.000Z | 2021-04-26T11:24:02.000Z | shared/src/shared/wind/base_functions.hpp | dumheter/wind_simulation | adf731847cb6145a85792a0ebceacc725a3acf9e | [
"MIT"
] | 1 | 2020-06-09T08:53:07.000Z | 2020-06-16T13:37:15.000Z | shared/src/shared/wind/base_functions.hpp | dumheter/wind_simulation | adf731847cb6145a85792a0ebceacc725a3acf9e | [
"MIT"
] | null | null | null | #pragma once
#include "shared/math/math.hpp"
#include "shared/types.hpp"
#include <variant>
#include <vector>
#include <ThirdParty/json.hpp>
namespace alflib {
class RawMemoryWriter;
class RawMemoryReader;
} // namespace alflib
namespace wind {
namespace baseFunctions {
enum class Type : u32 {
kConstant = 0,
kPolynomial,
kSpline,
kSplineCollection,
};
String typeToString(Type type);
Type stringToType(const String &type);
// ============================================================ //
struct Constant {
Vec3F dir;
f32 magnitude;
Vec3F operator()(const Vec3F) const { return dir * magnitude; }
void toJson(nlohmann::json &value) const;
static Constant fromJson(const nlohmann::json &value);
bool ToBytes(alflib::RawMemoryWriter &mw) const;
static Constant FromBytes(alflib::RawMemoryReader &mr);
};
struct Polynomial {
Vec3F origo;
f32 x0;
f32 x1;
f32 x2;
f32 y0;
f32 y1;
f32 y2;
f32 z0;
f32 z1;
f32 z2;
Vec3F operator()(const Vec3F point) const {
const Vec3F p = point - origo;
return Vec3F{(x0) + (x1 * p.x) + (x2 * p.x * p.x),
(y0) + (y1 * p.y) + (y2 * p.y * p.y),
(z0) + (z1 * p.z) + (z2 * p.z * p.z)};
}
void toJson(nlohmann::json &value) const;
static Polynomial fromJson(const nlohmann::json &value);
bool ToBytes(alflib::RawMemoryWriter &mw) const;
static Polynomial FromBytes(alflib::RawMemoryReader &mr);
};
/// SplineBase represents a single spline.
/// @pre points must be more than 2
struct Spline;
struct SplineBase {
friend struct Spline;
std::vector<Vec3F> points;
std::vector<f32> forces;
u32 degree;
u32 samples;
Vec3F operator()(Vec3F point) const;
void toJson(nlohmann::json &value) const;
static SplineBase fromJson(const nlohmann::json &value);
bool ToBytes(alflib::RawMemoryWriter &mw) const;
static SplineBase FromBytes(alflib::RawMemoryReader &mr);
private:
struct ClosestPoint {
u32 idx;
f32 dist;
};
/// @return Index in the list of points and distance to it.
ClosestPoint findClosestPoint(Vec3F point) const;
/// @param index Index in the list of points.
Vec3F getForce(u32 index) const;
};
/// Spline has a collection of SplineBase.
struct Spline {
std::vector<SplineBase> splines;
Vec3F operator()(Vec3F point) const;
void toJson(nlohmann::json &value) const;
static Spline fromJson(const nlohmann::json &value);
bool ToBytes(alflib::RawMemoryWriter &mw) const;
static Spline FromBytes(alflib::RawMemoryReader &mr);
};
} // namespace baseFunctions
// ============================================================ //
struct BaseFn {
using Constant = baseFunctions::Constant;
using Polynomial = baseFunctions::Polynomial;
using SplineBase = baseFunctions::SplineBase;
using Spline = baseFunctions::Spline;
using Variant = std::variant<Constant, Polynomial, Spline>;
Variant fn;
template <typename T> bool isType() const {
return std::holds_alternative<T>(fn);
}
static BaseFn fnConstant(Vec3F dir, f32 magnitude) {
return BaseFn{Constant{dir, magnitude}};
}
static BaseFn fnPolynomial(Vec3F origo, f32 x0, f32 x1, f32 x2, f32 y0,
f32 y1, f32 y2, f32 z0, f32 z1, f32 z2) {
return BaseFn{Polynomial{origo, x0, x1, x2, y0, y1, y2, z0, z1, z2}};
}
static BaseFn fnSpline(std::vector<SplineBase> &&splines) {
return BaseFn{Spline{std::move(splines)}};
}
/// Construct a BaseFn from json object.
/// @param value Should be an object.
/// ex:
/// {
/// "type" : "constant",
/// "magnitude" : 20,
/// "direction" : [ 0.0, 1.0, 1.0 ]
/// }
static BaseFn fromJson(const nlohmann::json &value);
/// Dump the BaseFn into a json representation.
/// @param value Should be an (empty) object.
/// ex:
/// {}
void toJson(nlohmann::json &value) const;
/// Calculate function value at point.
Vec3F operator()(Vec3F point) const {
return std::visit([point](auto &&arg) { return arg(point); }, fn);
}
bool ToBytes(alflib::RawMemoryWriter &mw) const;
static BaseFn FromBytes(alflib::RawMemoryReader &mr);
String typeToString() const;
// static String toString(baseFunctions::Type fn);
// static BaseFn fromString(const String &fn);
};
// ============================================================ //
} // namespace wind
| 24.329609 | 73 | 0.641561 | [
"object",
"vector"
] |
ae12b3eb3bf50f29dbbdb4b519f130d32aba2692 | 21,923 | cpp | C++ | src/trace/D3DPixRunPlayer/D3D9PixRunPlayer.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 23 | 2016-01-14T04:47:13.000Z | 2022-01-13T14:02:08.000Z | src/trace/D3DPixRunPlayer/D3D9PixRunPlayer.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 2 | 2018-03-25T14:39:20.000Z | 2022-03-18T05:11:21.000Z | src/trace/D3DPixRunPlayer/D3D9PixRunPlayer.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 17 | 2016-02-13T05:35:35.000Z | 2022-03-24T16:05:40.000Z | /**************************************************************************
*
* Copyright (c) 2002 - 2011 by Computer Architecture Department,
* Universitat Politecnica de Catalunya.
* All rights reserved.
*
* The contents of this file may not be disclosed to third parties,
* copied or duplicated in any form, in whole or in part, without the
* prior permission of the authors, Computer Architecture Department
* and Universitat Politecnica de Catalunya.
*
*/
#include "stdafx.h"
#include "D3DPlayer.h"
#include <D3DTrace.h>
#include "D3DBuffer.h"
#include "IniFile.h"
#include "D3DConfiguration.h"
#include "D3D9Status.h"
#include "D3DPixRunReader.h"
#include "D3D9PixRunPlayer.h"
#include "IncludeLog.h"
#ifdef D3D9_USER_STADISTICS
//#include <D3D9Stadistics.h>
#include <D3D9Stats.h>
#endif
using namespace std;
/**********************************************************************
Panics
**********************************************************************/
#define D3D9OP_IDIRECT3D9_REGISTERSOFTWAREDEVICE_SPECIFIC_PANIC
#define D3D9OP_IDIRECT3DDEVICE9_CREATEADDITIONALSWAPCHAIN_PANIC
#define D3D9OP_IDIRECT3DDEVICE9_DRAWTRIPATCH_PANIC
#define D3D9OP_IDIRECT3DDEVICE9_DRAWRECTPATCH_PANIC
#define D3D9OP_IDIRECT3DSWAPCHAIN9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DSWAPCHAIN9_GETFRONTBUFFERDATA_PANIC
// FOLLOWING PANIC IS COMMENTED BECAUSE OF A PATCH FOR THE GAME OBLIVION
// #define D3D9OP_IDIRECT3DTEXTURE9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DVOLUMETEXTURE9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DCUBETEXTURE9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DVERTEXBUFFER9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DINDEXBUFFER9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DSURFACE9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DVOLUME9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DVERTEXDECLARATION9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DPIXELSHADER9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DSTATEBLOCK9_QUERYINTERFACE_PANIC
#define D3D9OP_IDIRECT3DQUERY9_QUERYINTERFACE_PANIC
/**********************************************************************
Specific Code definitions
**********************************************************************/
/*********************************************
This call returns an interface and autogeneration
doesn't handle this case.
**********************************************/
inline void D3D9PixRunPlayer::Direct3DCreate9_SPECIFIC_PRE()
{
u32bit oip_Result;
IDirect3D9 *sip_Result;
reader.readParameter<u32bit>(&oip_Result);
UINT ov_SDKVersion;
UINT sv_SDKVersion;
reader.readParameter<UINT>(&ov_SDKVersion);
sv_SDKVersion = ov_SDKVersion;
sip_Result = Direct3DCreate9(sv_SDKVersion);
status.setSubstitute(oip_Result, sip_Result);
}
#define D3D9OP_DIRECT3DCREATE9_SPECIFIC_PRE \
Direct3DCreate9_SPECIFIC_PRE();
inline void D3D9PixRunPlayer::IDirect3D9_CreateDevice_SPECIFIC_POST(HRESULT result, IDirect3DDevice9* returnedDeviceInterface)
{
if (result != D3D_OK)
panic("D3D9PixRunPlayer", "D3D9OP_IDIRECT3D9_CREATEDEVICE", "CreateDevice returned an error.");
status.newMainSubstituteDevice(returnedDeviceInterface);
}
#define D3D9OP_IDIRECT3D9_CREATEDEVICE_SPECIFIC_POST \
IDirect3D9_CreateDevice_SPECIFIC_POST(sv_Return, sip_ppReturnedDeviceInterface);
inline void D3D9PixRunPlayer::IDirect3D9_CreateDevice_SPECIFIC_PRE(UINT &adapter, D3DDEVTYPE &deviceType,
HWND &hFocusWindow,
DWORD &behaviorFlags,
D3DPRESENT_PARAMETERS *&pp)
{
status.onCreateDevice(adapter, deviceType, hFocusWindow, behaviorFlags, pp);
}
#define D3D9OP_IDIRECT3D9_CREATEDEVICE_SPECIFIC_PRE \
IDirect3D9_CreateDevice_SPECIFIC_PRE(sv_Adapter, sv_DeviceType, sv_hFocusWindow, sv_BehaviorFlags, spv_pPresentationParameters);
// Patch for traces captured on ATI that use float point depth buffers.
#define D3D9OP_IDIRECT3DDEVICE9_CREATEDEPTHSTENCILSURFACE_USER_POST \
if ((sv_Format == D3DFMT_D24FS8) && (sv_Return != D3D_OK) && status.isEnabledATIFPDepthBufferHack()) \
sv_Return = sip_This -> CreateDepthStencilSurface( \
sv_Width, sv_Height, \
D3DFMT_D24S8, \
sv_MultiSample, \
sv_MultisampleQuality, \
sv_Discard, \
spip_ppSurface, \
sv_pSharedHandle);
// Support for Texture9 LockRect/UnlockRect with mip levels.
/*inline void D3D9PixRunPlayer::IDirect3D9_CreateTexture_SPECIFIC_PRE(IDirect3DTexture9* texture)
{
for(UINT currLevel = 0; currLevel < texture->GetLevelCount(); currLevel++)
{
IDirect3DSurface9 *surface;
texture->GetSurfaceLevel(currLevel, &surface);
status.addLockUpdater((void *) surface);
surface->Release();
};
}*/
//#define D3D9OP_IDIRECT3DDEVICE9_CREATETEXTURE_SPECIFIC_POST \
// IDirect3D9_CreateTexture_SPECIFIC_POST(sip_ppTexture);
#define D3D9OP_IDIRECT3DDEVICE9_CREATETEXTURE_SPECIFIC_PRE \
if (sv_Format == MAKEFOURCC('A', 'T', 'I', '2') && status.isEnabledATI2FormatHack()) \
sv_Format = D3DFMT_DXT5;
//else if (sv_Format == D3DFMT_D24S8) \
// sv_Format = D3DFMT_D16_LOCKABLE;
/*#define D3D9OP_IDIRECT3DCUBETEXTURE9_LOCKRECT_SPECIFIC_POST \
IDirect3DSurface9 *surface;\
sip_This->GetCubeMapSurface(sv_FaceType, sv_Level, &surface);\
D3DSURFACE_DESC desc;\
surface->GetDesc(&desc);\
surface->Release();\
status.lockSurface(oip_This, &desc, spv_pLockedRect, spv_pRect);
*/
inline void D3D9PixRunPlayer::IDirect3DCubeTexture9_LockRect_SPECIFIC_POST(IDirect3DCubeTexture9 *sip_This,
D3DCUBEMAP_FACES faceType, UINT level,
D3DLOCKED_RECT *lockedRect, RECT *pRect)
{
IDirect3DSurface9 *surface;
sip_This->GetCubeMapSurface(faceType, level, &surface);
D3DSURFACE_DESC desc;
surface->GetDesc(&desc);
surface->Release();
status.lockSurface((void *) surface, &desc, lockedRect, pRect);
}
#define D3D9OP_IDIRECT3DCUBETEXTURE9_LOCKRECT_SPECIFIC_POST \
IDirect3DCubeTexture9_LockRect_SPECIFIC_POST(sip_This, sv_FaceType, sv_Level, spv_pLockedRect, spv_pRect);
/*#define D3D9OP_IDIRECT3DCUBETEXTURE9_UNLOCKRECT_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
status.unlock(oip_This, buffer.getSize(), pdata);\
buffer.unlock();
*/
inline void D3D9PixRunPlayer::IDirect3DCubeTexture9_UnlockRect_SPECIFIC_PRE(IDirect3DCubeTexture9 *sip_This,
D3DCUBEMAP_FACES faceType, UINT level)
{
IDirect3DSurface9 *surface;
sip_This->GetCubeMapSurface(faceType, level, &surface);
surface->Release();
D3DBuffer buffer;
reader.readParameter(&buffer);
void *pdata;
buffer.lock(&pdata);
status.unlock((void *) surface, buffer.getSize(), pdata);
buffer.unlock();
}
#define D3D9OP_IDIRECT3DCUBETEXTURE9_UNLOCKRECT_SPECIFIC_PRE \
IDirect3DCubeTexture9_UnlockRect_SPECIFIC_PRE(sip_This, sv_FaceType, sv_Level);
#define D3D9OP_IDIRECT3DDEVICE9_CREATEPIXELSHADER_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
sv_pFunction = static_cast< DWORD * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_CREATEVERTEXDECLARATION_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
sv_pVertexElements = static_cast< D3DVERTEXELEMENT9 * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_CREATEVERTEXSHADER_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
sv_pFunction = static_cast< DWORD * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_DRAWINDEXEDPRIMITIVEUP_SPECIFIC_PRE \
D3DBuffer buffer1;\
reader.readParameter(&buffer1);\
void *spmr1;\
buffer1.lock(&spmr1);\
sv_pVertexStreamZeroData = spmr1;\
D3DBuffer buffer2;\
reader.readParameter(&buffer2);\
void *spmr2;\
buffer2.lock(&spmr2);\
sv_pIndexData = spmr2;
#define D3D9OP_IDIRECT3DDEVICE9_DRAWPRIMITIVEUP_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
sv_pVertexStreamZeroData = spmr;
#define D3D9OP_IDIRECT3DDEVICE9_PRESENT_SPECIFIC_PRE \
sv_hDestWindowOverride = 0;
#define D3D9OP_IDIRECT3DDEVICE9_RESET_SPECIFIC_PRE \
status.onDeviceReset(spv_pPresentationParameters);
/* The problem here is that codegen treat float * as a pointer to value
and in this case the float * refers to a vector of 4 float's that
follows the pointer. As it's the last parameter we are lucky and can
read it. */
#define D3D9OP_IDIRECT3DDEVICE9_SETCLIPPLANE_SPECIFIC_PRE \
float specific_spv_pPlane[4];\
specific_spv_pPlane[0] = sv_pPlane;\
reader.readParameter<float>(&specific_spv_pPlane[1]);\
reader.readParameter<float>(&specific_spv_pPlane[2]);\
reader.readParameter<float>(&specific_spv_pPlane[3]);\
spv_pPlane = (opv_pPlane == 0 ) ? 0: specific_spv_pPlane;
#define D3D9OP_IDIRECT3DDEVICE9_SETPIXELSHADERCONSTANTB_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
spv_pConstantData = static_cast< BOOL * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_SETPIXELSHADERCONSTANTF_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
spv_pConstantData = static_cast< float * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_SETPIXELSHADERCONSTANTI_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
spv_pConstantData = static_cast< int * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_SETVERTEXSHADERCONSTANTB_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
spv_pConstantData = static_cast< BOOL * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_SETVERTEXSHADERCONSTANTF_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
spv_pConstantData = static_cast< float * >(spmr);
#define D3D9OP_IDIRECT3DDEVICE9_SETVERTEXSHADERCONSTANTI_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *spmr;\
buffer.lock(&spmr);\
spv_pConstantData = static_cast< int * >(spmr);
#define D3D9OP_IDIRECT3DINDEXBUFFER9_LOCK_SPECIFIC_POST \
D3DINDEXBUFFER_DESC desc;\
sip_This->GetDesc(&desc);\
status.lockIndexBuffer((void *) sip_This, &desc, sv_OffsetToLock, sv_SizeToLock, specific_sv_ppbData);
/* The problem here is that codegen treat void ** as a value because Pix doesn't
store the referenced void * in pixRun file. We must create a void * and put
the void ** pointing to it. */
#define D3D9OP_IDIRECT3DINDEXBUFFER9_LOCK_SPECIFIC_PRE \
void *specific_sv_ppbData;\
sv_ppbData = &specific_sv_ppbData;
#define D3D9OP_IDIRECT3DINDEXBUFFER9_UNLOCK_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
status.unlock((void *) sip_This, buffer.getSize(), pdata);\
buffer.unlock();
//#define D3D9OP_IDIRECT3DSURFACE9_GETCONTAINER_SPECIFIC_POST \
// status.setSubstitute(specific_ov_ppContainer, specific_sv_ppContainer);
/* The problem here is that codegen treat void ** as a value
and in this case a void * with the original container address
follows it. As it's the last parameter we are lucky and can
read it. Finally we redirect the pointer to the specific void *
*/
#define D3D9OP_IDIRECT3DSURFACE9_GETCONTAINER_SPECIFIC_PRE \
u32bit specific_ov_ppContainer;\
reader.readParameter<u32bit>(&specific_ov_ppContainer);\
void *specific_sv_ppContainer;\
sv_ppContainer = &specific_sv_ppContainer;
#define D3D9OP_IDIRECT3DSURFACE9_LOCKRECT_SPECIFIC_POST \
D3DSURFACE_DESC desc;\
sip_This->GetDesc(&desc);\
status.lockSurface((void *) sip_This, &desc, spv_pLockedRect, spv_pRect);
#define D3D9OP_IDIRECT3DSURFACE9_UNLOCKRECT_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
status.unlock((void *) sip_This, buffer.getSize(), pdata);\
buffer.unlock();
#define D3D9OP_IDIRECT3DTEXTURE9_LOCKRECT_SPECIFIC_POST \
IDirect3DSurface9 *surface;\
sip_This->GetSurfaceLevel(sv_Level, &surface);\
D3DSURFACE_DESC desc;\
surface->GetDesc(&desc);\
surface->Release();\
status.lockSurface((void *) surface, &desc, spv_pLockedRect, spv_pRect);
#define D3D9OP_IDIRECT3DTEXTURE9_UNLOCKRECT_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
IDirect3DSurface9 *surface;\
sip_This->GetSurfaceLevel(sv_Level, &surface);\
surface->Release();\
status.unlock((void *) surface, buffer.getSize(), pdata);\
buffer.unlock();
#define D3D9OP_IDIRECT3DVERTEXBUFFER9_LOCK_SPECIFIC_POST \
D3DVERTEXBUFFER_DESC desc;\
sip_This->GetDesc(&desc);\
status.lockVertexBuffer((void *) sip_This, &desc, sv_OffsetToLock, sv_SizeToLock, specific_sv_ppbData);
/* The problem here is that codegen treat void ** as a value because Pix doesn't
store the referenced void * in pixRun file. We must create a void * and put
the void ** pointing to it. */
#define D3D9OP_IDIRECT3DVERTEXBUFFER9_LOCK_SPECIFIC_PRE \
void * specific_sv_ppbData;\
sv_ppbData = &specific_sv_ppbData;
#define D3D9OP_IDIRECT3DVERTEXBUFFER9_UNLOCK_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
status.unlock((void *) sip_This, buffer.getSize(), pdata);\
buffer.unlock();
//#define D3D9OP_IDIRECT3DVOLUME9_GETCONTAINER_SPECIFIC_POST \
// status.setSubstitute(specific_ov_ppContainer, specific_sv_ppContainer);
/* The problem here is that codegen treat void ** as a value
and in this case a void * with the original container address
follows it. As it's the last parameter we are lucky and can
read it. Finally we redirect the pointer to the specific void *
*/
#define D3D9OP_IDIRECT3DVOLUME9_GETCONTAINER_SPECIFIC_PRE \
PIXPointer specific_ov_ppContainer;\
reader.readParameter<PIXPointer>(&specific_ov_ppContainer);\
void *specific_sv_ppContainer;\
sv_ppContainer = &specific_sv_ppContainer;
#define D3D9OP_IDIRECT3DVOLUME9_LOCKBOX_SPECIFIC_POST \
D3DVOLUME_DESC desc;\
sip_This->GetDesc(&desc);\
status.lockVolume((void *) sip_This, &desc, spv_pLockedVolume, spv_pBox);
#define D3D9OP_IDIRECT3DVOLUME9_UNLOCKBOX_SPECIFIC_PRE \
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
status.unlock((void *) sip_This, buffer.getSize(), pdata);\
buffer.unlock();
#define D3D9OP_IDIRECT3DVOLUMETEXTURE9_LOCKBOX_SPECIFIC_POST \
IDirect3DVolume9 *volume;\
sip_This->GetVolumeLevel(sv_Level, &volume);\
D3DVOLUME_DESC desc;\
volume->GetDesc(&desc);\
volume->Release();\
status.lockVolume((void *) volume, &desc, spv_pLockedVolume, spv_pBox);
#define D3D9OP_IDIRECT3DVOLUMETEXTURE9_UNLOCKBOX_SPECIFIC_PRE \
IDirect3DVolume9 *volume;\
sip_This->GetVolumeLevel(sv_Level, &volume);\
volume->Release();\
D3DBuffer buffer;\
reader.readParameter(&buffer);\
void *pdata;\
buffer.lock(&pdata);\
status.unlock((void *) volume, buffer.getSize(), pdata);\
buffer.unlock();
// FOLLOWING LINE IS A PATCH FOR THE GAME OBLIVION
#define D3D9OP_IDIRECT3DTEXTURE9_QUERYINTERFACE_SPECIFIC_PRE \
u32bit ov_Return; \
HRESULT sv_Return; \
reader.readParameter<u32bit>(&ov_Return); \
sv_Return = ov_Return; \
\
PIXPointer oip_This; \
IDirect3DTexture9 * sip_This; \
reader.readParameter<PIXPointer>(&oip_This); \
sip_This = static_cast<IDirect3DTexture9 *>(status.getSubstitute(oip_This)); \
\
GUID ov_riid; \
GUID sv_riid; \
reader.readParameter<GUID>(&ov_riid); \
sv_riid = ov_riid; \
\
PIXPointer opip_ppvObj; \
PIXPointer oip_ppvObj; \
void ** spip_ppvObj; \
void * sip_ppvObj; \
reader.readParameter<PIXPointer>(&opip_ppvObj); \
reader.readParameter<PIXPointer>(&oip_ppvObj); \
spip_ppvObj = &sip_ppvObj; \
\
sv_Return = sip_This -> QueryInterface( \
sv_riid ,spip_ppvObj); \
\
status.setSubstitute(oip_ppvObj, sip_ppvObj );
void D3D9PixRunPlayer::open(string filename) {
reader.open(filename);
callOffset = 0;
status.reset();
#ifdef D3D9_USER_BEGIN
/* A user initialization code */
D3D9_USER_BEGIN
#endif
}
void D3D9PixRunPlayer::close() {
#ifdef D3D9_USER_END
/* User cleanup code */
D3D9_USER_END
#endif
reader.close();
}
bool D3D9PixRunPlayer::playBatch()
{
// Execute commands until a "batch" command is found
bool foundNextDraw = false;
bool foundPresent = false;
bool fetched = true;
while(fetched && !foundNextDraw && !foundPresent)
{
fetched = reader.fetch();
if (fetched)
{
// Check if the next draw call was found.
foundNextDraw = (reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_DRAWPRIMITIVE) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_DRAWINDEXEDPRIMITIVE) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_DRAWPRIMITIVEUP) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_DRAWINDEXEDPRIMITIVEUP) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_DRAWRECTPATCH) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_DRAWTRIPATCH);
// Check if present (end of frame) was found.
foundPresent = (reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_PRESENT) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DSWAPCHAIN9_PRESENT);
execute();
}
}
if (fetched)
{
if (!foundPresent)
{
// Present batch results.
status.mainSubstituteDevicePresentBatch();
currentBatch++;
}
else
{
currentBatch = 0;
endOfFrame = true;
}
}
return foundNextDraw;
}
bool D3D9PixRunPlayer::playFrame()
{
currentBatch = 0;
// Execute commands until a "present" command is found
bool foundPresent= false;
bool fetched = true;
// Execute until a present (end of frame) is found.
while(fetched & !foundPresent)
{
fetched = reader.fetch();
if (fetched)
{
foundPresent = (reader.getFetchedCID() == D3D9CID_IDIRECT3DDEVICE9_PRESENT) ||
(reader.getFetchedCID() == D3D9CID_IDIRECT3DSWAPCHAIN9_PRESENT);
execute();
}
}
if(foundPresent)
{
endOfFrame = true;
}
return foundPresent;
}
unsigned long D3D9PixRunPlayer::getCallOffset() {
return callOffset;
}
void D3D9PixRunPlayer::setWindow(HWND window)
{
status.setMainSubstituteWindow(window);
}
bool D3D9PixRunPlayer::isEndOfFrame()
{
bool end = endOfFrame;
endOfFrame = false;
return end;
}
D3D9PixRunPlayer::D3D9PixRunPlayer()
{
D3DConfiguration &cfg = D3DConfiguration::instance();
cfg.load("D3D9PixRunPlayer.ini");
status.updateConfiguration();
frameEnded = false;
callOffset = 0;
currentFrame = 0;
currentBatch = 0;
endOfFrame = false;
}
void D3D9PixRunPlayer::execute() {
bool isD3D9Call = true;
D3D9CID cid = static_cast<D3D9CID>(reader.getFetchedCID());
switch (cid) {
#include "D3D9PixRunSwitchBranches.gen"
default:
// The call id doesn't match any D3D9 call (perhaps is a D3D9X call id)
isD3D9Call = false;
}
// Increment offset
if(isD3D9Call) {
callOffset++;
}
// Frame ended
if((cid == D3D9CID_IDIRECT3DDEVICE9_PRESENT) || (cid == D3D9CID_IDIRECT3DSWAPCHAIN9_PRESENT) )
{
frameEnded = true;
}
else
{
if (frameEnded)
{
char buffer[256];
sprintf(buffer, "Frame %d was rendered\n", currentFrame);
includelog::logfile().write(includelog::Debug, buffer);
currentFrame++;
}
frameEnded = false;
}
}
bool D3D9PixRunPlayer::next()
{
bool fetched = reader.fetch();
if(fetched)
execute();
return fetched;
}
bool D3D9PixRunPlayer::getFrameEnded()
{
return frameEnded;
}
u32bit D3D9PixRunPlayer::getCurrentEventID()
{
return reader.getFetchedEID();
}
bool D3D9PixRunPlayer::isPreloadCall()
{
return reader.isPreloadCall();
}
void *D3D9PixRunPlayer::getDirect3DDevice()
{
return (void *) status.getSubstituteDevice();
}
#include "D3D9PixRunDefinitions.gen"
D3DPlayer *createD3D9Player(HWND window) {
D3D9PixRunPlayer *p = new D3D9PixRunPlayer();
p->setWindow(window);
return p;
}
D3DTrace *create_d3d_trace(char *file_name)
{
D3D9PixRunPlayer *p = new D3D9PixRunPlayer();
p->setWindow(0);
string filenameStr = file_name;
p->open(filenameStr);
return p;
}
| 32.430473 | 132 | 0.680655 | [
"vector"
] |
ae1330271c4a32a44d78ccff01be97461a4d5280 | 5,096 | hpp | C++ | component/oai-amf/src/nas/msgs/RegistrationAccept.hpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/nas/msgs/RegistrationAccept.hpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/nas/msgs/RegistrationAccept.hpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/*! \file
\brief
\author Keliang DU, BUPT
\date 2020
\email: contact@openairinterface.org
*/
#ifndef _RegistrationAccept_H_
#define _RegistrationAccept_H_
#include "nas_ie_header.hpp"
namespace nas {
class RegistrationAccept {
public:
RegistrationAccept();
~RegistrationAccept();
int encode2buffer(uint8_t* buf, int len);
int decodefrombuffer(NasMmPlainHeader* header, uint8_t* buf, int len);
void setHeader(uint8_t security_header_type);
void setSOR_Transparent_Container(uint8_t header, uint8_t* value);
void set_5GS_Registration_Result(
bool emergency, bool nssaa, bool sms, uint8_t value);
/*** belongs to _5GSMobilityIdentity**/
void setSUCI_SUPI_format_IMSI(
const string mcc, const string mnc, const string routingInd,
uint8_t protection_sch_id, const string msin);
void setSUCI_SUPI_format_IMSI(
const string mcc, const string mnc, const string routingInd,
uint8_t protection_sch_id, uint8_t hnpki, const string msin);
void set5G_GUTI(
const string mcc, const string mnc, const string amfRegionId,
const string amfSetId, const string amfPointer, const uint32_t tmsi);
void setIMEI_IMEISV();
void set5G_S_TMSI();
/*** belongs to _5GSMobilityIdentity**/
void setEquivalent_PLMNs(
uint8_t MNC_MCC1, uint8_t MNC_MCC2, uint8_t MNC_MCC3);
void setALLOWED_NSSAI(std::vector<struct SNSSAI_s> nssai);
void setRejected_NSSAI(uint8_t cause, uint8_t value);
void setCONFIGURED_NSSAI(std::vector<struct SNSSAI_s> nssai);
void set_5GS_Network_Feature_Support(uint8_t value, uint8_t value2);
void setPDU_session_status(uint16_t value);
void setPDU_session_reactivation_result(uint16_t value);
void setPDU_session_reactivation_result_error_cause(
uint8_t session_id, uint8_t value);
void setMICO_Indication(bool sprti, bool raai);
void setNetwork_Slicing_Indication(bool dcni, bool nssci);
void setT3512_Value(uint8_t unit, uint8_t value);
void setNon_3GPP_de_registration_timer_value(uint8_t value);
void setT3502_value(uint8_t value);
void setEAP_Message(bstring eap);
void setNSSAI_Inclusion_Mode(uint8_t value);
void set_5GS_DRX_arameters(uint8_t value);
void setNon_3GPP_NW_Provided_Policies(uint8_t value);
void setEPS_Bearer_Context_Status(uint16_t value);
void setExtended_DRX_Parameters(uint8_t paging_time, uint8_t value);
void setT3447_Value(uint8_t unit, uint8_t value);
void setT3448_Value(uint8_t unit, uint8_t value);
void setT3324_Value(uint8_t unit, uint8_t value);
void setUE_Radio_Capability_ID(uint8_t value);
void setPending_NSSAI(std::vector<struct SNSSAI_s> nssai);
void setTaiList(std::vector<p_tai_t> tai_list);
public:
NasMmPlainHeader* plain_header;
_5GS_Registration_Result* ie_5gs_registration_result;
_5GSMobilityIdentity* ie_5g_guti;
PLMN_List* ie_equivalent_plmns;
NSSAI* ie_allowed_nssai;
Rejected_NSSAI* ie_rejected_nssai;
NSSAI* ie_configured_nssai;
_5GS_Network_Feature_Support* ie_5gs_network_feature_support;
PDU_Session_Status* ie_PDU_session_status;
PDU_Session_Reactivation_Result* ie_pdu_session_reactivation_result;
PDU_Session_Reactivation_Result_Error_Cause*
ie_pdu_session_reactivation_result_error_cause;
MICO_Indication* ie_MICO_indicationl;
Network_Slicing_Indication* ie_network_slicing_indication;
GPRS_Timer_3* ie_T3512_value;
GPRS_Timer_2* ie_Non_3GPP_de_registration_timer_value;
GPRS_Timer_2* ie_T3502_value;
SOR_Transparent_Container* ie_sor_transparent_container;
EAP_Message* ie_eap_message;
NSSAI_Inclusion_Mode* ie_nssai_inclusion_mode;
_5GS_DRX_arameters* ie_negotiated_drx_parameters;
Non_3GPP_NW_Provided_Policies* ie_non_3gpp_nw_policies;
EPS_Bearer_Context_Status* ie_eps_bearer_context_status;
Extended_DRX_Parameters* ie_extended_drx_parameters;
GPRS_Timer_3* ie_T3447_value;
GPRS_Timer_3* ie_T3448_value;
GPRS_Timer_3* ie_T3324_value;
UE_Radio_Capability_ID* ie_ue_radio_capability_id;
NSSAI* ie_pending_nssai;
_5GSTrackingAreaIdList* ie_tai_list;
};
} // namespace nas
#endif
| 41.430894 | 81 | 0.787873 | [
"vector"
] |
ae1599a0829872b2ab8cfd99a22013bb4d4aa92d | 6,559 | cpp | C++ | Utilities/PDBLigandUtils.cpp | ElianeBriand/SMolDock | de0cb746ef995ae0eef0f812ebd61727311c332f | [
"Apache-2.0"
] | 1 | 2019-05-30T02:33:13.000Z | 2019-05-30T02:33:13.000Z | Utilities/PDBLigandUtils.cpp | ElianeBriand/SMolDock | de0cb746ef995ae0eef0f812ebd61727311c332f | [
"Apache-2.0"
] | null | null | null | Utilities/PDBLigandUtils.cpp | ElianeBriand/SMolDock | de0cb746ef995ae0eef0f812ebd61727311c332f | [
"Apache-2.0"
] | 3 | 2020-12-30T19:11:51.000Z | 2021-06-25T02:45:49.000Z | //
// Created by eliane on 23/12/18.
//
#include "PDBLigandUtils.h"
#include <boost/log/trivial.hpp>
namespace SmolDock {
void AssignBondOrderFromTemplateSMILES(std::shared_ptr<RDKit::RWMol> mol, const std::string &smiles) {
RDKit::RWMol* attempt_ptr = nullptr;
try {
/* This can throw */
attempt_ptr = RDKit::SmilesToMol(smiles);
}
catch (...) {
attempt_ptr = nullptr;
}
if (attempt_ptr == nullptr) {
BOOST_LOG_TRIVIAL(error)
<< "Error in AssignBondOrderFromTemplateSMILES(std::shared_ptr<RDKit::RWMol> mol,const std::string& smiles)";
BOOST_LOG_TRIVIAL(error) << "for teplate smiles = " << smiles;
BOOST_LOG_TRIVIAL(error) << "The SMILES string was not correctly parsed by RDKit.";
BOOST_LOG_TRIVIAL(error)
<< "This often indicated a malformed SMILES. (but not always, RDKit has parsing bugs)";
BOOST_LOG_TRIVIAL(error) << "Non-modified mol will be used (likely with incorrect bond order)";
}
std::shared_ptr<RDKit::RWMol> templatemol(attempt_ptr);
RDKit::MolOps::removeHs(*(mol));
// The following code, until the END RDKIT CODE comment, is a C++ translation
// of python code from RDKit, in particular, the function AssignBondOrdersFromTemplate
//
// As a reminder, the copyright for this code is
// Copyright (C) 2001-2017 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// The contents are covered by the terms of the BSD license
// which is included in the file COPYING
//
// RDKit::MatchVectType matches = std::vector<std::pair<int, int>>
// The format is (queryAtomIdx, molAtomIdx)
RDKit::MatchVectType matches;
bool matching = RDKit::SubstructMatch(*(RDKit::ROMol*)(mol.get()), *(RDKit::ROMol*)(templatemol.get()), matches);
if (!matching) {
// We make a copy on which we will remove all double bond/charges/... to compare
std::shared_ptr<RDKit::RWMol> templatemol_plainstruct(new RDKit::RWMol(*templatemol));
// Set all bonds to single, non-aromatic
for (unsigned int i = 0; i < mol->getNumBonds(); i++) {
auto bond = mol->getBondWithIdx(i);
bond->setIsAromatic(false);
bond->setBondType(RDKit::Bond::BondType::SINGLE);
}
// Also in templatemol_plainstruct
for (unsigned int i = 0; i < templatemol_plainstruct->getNumBonds(); i++) {
auto bond = templatemol_plainstruct->getBondWithIdx(i);
bond->setIsAromatic(false);
bond->setBondType(RDKit::Bond::BondType::SINGLE);
}
// Remove all charges
for (unsigned int i = 0; i < mol->getNumAtoms(); i++) {
auto atom = mol->getAtomWithIdx(i);
atom->setFormalCharge(0);
}
for (unsigned int i = 0; i < templatemol_plainstruct->getNumAtoms(); i++) {
auto atom = templatemol_plainstruct->getAtomWithIdx(i);
atom->setFormalCharge(0);
}
bool matching = RDKit::SubstructMatch(*(RDKit::ROMol*)(mol.get()), *(RDKit::ROMol*)(templatemol_plainstruct.get()),
matches);
if (!matching) // Cant reconcile even without charges or double bond
{
BOOST_LOG_TRIVIAL(error)
<< "Cannot match molecule with SMILES template, thus cannot adjust bond order ";
BOOST_LOG_TRIVIAL(error) << "Plain mol will be used (all bond order single, no charges, no nothing)";
return;
}
}
// After this point, we are matching (or we returned)
// And we have matches in RDKit::MatchVectType matches
// For each bond of the template, we find the corresponding one in the molecule to edit
// Then we set it to the same characteristics
for (unsigned int i = 0; i < templatemol->getNumBonds(); i++) {
auto template_bond = templatemol->getBondWithIdx(i);
// RDKit::MatchVectType matches = std::vector<std::pair<int, int>>
// The format is (queryAtomIdx, molAtomIdx)
// So we find_if for matching queryAtomIdx to the beginning and end of the bond
int idx_atom1 = std::get<1>(*(std::find_if(matches.begin(), matches.end(),
[&](const std::pair<int, int> &e) {
return (std::get<0>(e) == (int) template_bond->getBeginAtomIdx());
})));
int idx_atom2 = std::get<1>(*(std::find_if(matches.begin(), matches.end(),
[&](const std::pair<int, int> &e) {
return (std::get<0>(e) == (int) template_bond->getEndAtomIdx());
})));
auto bond_to_edit = mol->getBondBetweenAtoms(idx_atom1, idx_atom2);
bond_to_edit->setBondType(template_bond->getBondType());
bond_to_edit->setIsAromatic(template_bond->getIsAromatic());
}
for (unsigned int i = 0; i < templatemol->getNumAtoms(); i++) {
auto template_atom = templatemol->getAtomWithIdx(i);
int idx_atom_to_edit = std::get<1>(*(std::find_if(matches.begin(), matches.end(),
[&](const std::pair<int, int> &e) {
return (std::get<0>(e) == (int) i);
})));
auto atom_to_edit = mol->getAtomWithIdx(idx_atom_to_edit);
atom_to_edit->setHybridization(template_atom->getHybridization());
atom_to_edit->setIsAromatic(template_atom->getIsAromatic());
atom_to_edit->setNumExplicitHs(template_atom->getNumExplicitHs());
atom_to_edit->setFormalCharge(template_atom->getFormalCharge());
atom_to_edit->setChiralTag(template_atom->getChiralTag());
}
RDKit::MolOps::sanitizeMol(*mol);
// //////////////// END RDKIT CODE //////////////////////////////////
}
} | 46.51773 | 127 | 0.541241 | [
"vector"
] |
ae193ddb05518a29542ce32cf42060df17082a4f | 4,428 | hpp | C++ | Axis/System/Include/Axis/Function.hpp | SimmyPeet/Axis | a58c073d13f74d0224fbfca34a4dcd4b9d0c6726 | [
"Apache-2.0"
] | 1 | 2022-01-23T14:51:51.000Z | 2022-01-23T14:51:51.000Z | Axis/System/Include/Axis/Function.hpp | SimmyPeet/Axis | a58c073d13f74d0224fbfca34a4dcd4b9d0c6726 | [
"Apache-2.0"
] | null | null | null | Axis/System/Include/Axis/Function.hpp | SimmyPeet/Axis | a58c073d13f74d0224fbfca34a4dcd4b9d0c6726 | [
"Apache-2.0"
] | 1 | 2022-01-10T21:01:54.000Z | 2022-01-10T21:01:54.000Z | /// \copyright Simmypeet - Copyright (C)
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE', which is part of this source code package.
#ifndef AXIS_SYSTEM_FUNCTION_HPP
#define AXIS_SYSTEM_FUNCTION_HPP
#pragma once
#include "Memory.hpp"
#include "Trait.hpp"
#include "Utility.hpp"
namespace Axis
{
namespace System
{
/// \brief Template type erasure container class for containing all callable objects.
template <class T, AllocatorType Allocator = DefaultAllocator>
struct Function;
/// \brief Template type erasure container class for containing all callable objects.
///
/// To use this class, the functor object that you want to store must have the following conditions:
/// - Must have noexcept copy and move constructors.
/// - The functor object must have a function call operator.
template <AllocatorType Allocator, class ReturnType, class... Args>
struct Function<ReturnType(Args...), Allocator>
{
public:
/// \brief Default constructor
///
/// The object can't be called if it was constructed with this constructor
Function() noexcept;
/// \brief Constructs object in null state.
///
/// The object can't be called if it was constructed with this constructor
Function(NullptrType) noexcept;
/// \brief Constructs and copies the functor object into this `Axis::Function` object.
///
/// \param[in] f Callable object to copy.
template <Callable<ReturnType, Args...> Functor, typename = std::enable_if_t<!std::is_same_v<Functor, Function>>>
Function(const Functor& f);
/// \brief Constructs and moves the functor object into this `Axis::Function` object.
///
/// \param[in] f Callable object to move.
template <Callable<ReturnType, Args...> Functor, typename = std::enable_if_t<!std::is_same_v<Functor, Function>>>
Function(Functor&& f);
/// \brief Copy constructor
///
/// \param[in] other Instance to copy
Function(const Function& other);
/// \brief Move constructor
///
/// \param[in] other Instance to move
Function(Function&& other) noexcept;
/// \brief Destructor
~Function() noexcept;
/// \brief Invokes the underlying function object with specified arguments.
///
/// \param[in] args Variadic template arguments to invoke the underlying callable object.
ReturnType operator()(Args&&... args);
/// \brief Copy assignemt operator
///
/// \param[in] other Instance to copy
Function& operator=(const Function& other);
/// \brief Move assignment operator
///
/// \param[in] other Instance to move
Function& operator=(Function&& other) noexcept;
/// \brief Checks whether the object is in null state or not.
Bool operator==(NullptrType) const noexcept;
/// \brief Checks whether the object is in null state or not.
Bool operator!=(NullptrType) const noexcept;
/// \brief Turns this object into null state.
Function& operator=(NullptrType) noexcept;
/// \brief Specifies whether this `Axis::Function` object is callable.
operator Bool() const noexcept;
private:
/// Size of small buffer contained in the object.
static constexpr Size SmallBufferOptimizationSize = Axis::PointerSize;
/// Function pointer signature using
using InvokePtr = ReturnType (*)(void*, Args&&...);
using DestructorPtr = void (*)(void*);
using CopyConstructPtr = void (*)(void*, const void*);
using MoveConstructPtr = void (*)(void*, void*);
/// Emulates the vtable that stores different kinds of functions.
struct VTable final
{
InvokePtr Invoke = nullptr; // Invokes the functor's operator()
DestructorPtr Destruct = nullptr; // Invokes the functor's destructor
CopyConstructPtr CopyConstruct = nullptr; // Invokes copy constructor
MoveConstructPtr MoveConstruct = nullptr; // Invokes move constructor
};
void Destroy() noexcept;
const VTable* _pVtable = nullptr; // Pointer to the vtable object
Size _dynamicBufferSize = 0; // Size of dynamic buffer
union
{
PVoid DynamicBuffer;
StaticStorage<SmallBufferOptimizationSize> Storage;
};
};
} // namespace System
} // namespace Axis
#include "../../Private/Axis/FunctionImpl.inl"
#endif // AXIS_SYSTEM_FUNCTION_HPP | 33.801527 | 117 | 0.673893 | [
"object"
] |
ae2e2cf46963c299be4b51eaaedab14a58ffb5cb | 7,600 | cc | C++ | fwdmodel_pet_1TCM.cc | pauldmccarthy/fabber_models_pet | ffef95482a1285fad5785e0d666dfac9b522f6be | [
"Apache-2.0"
] | null | null | null | fwdmodel_pet_1TCM.cc | pauldmccarthy/fabber_models_pet | ffef95482a1285fad5785e0d666dfac9b522f6be | [
"Apache-2.0"
] | null | null | null | fwdmodel_pet_1TCM.cc | pauldmccarthy/fabber_models_pet | ffef95482a1285fad5785e0d666dfac9b522f6be | [
"Apache-2.0"
] | 1 | 2021-06-09T13:47:08.000Z | 2021-06-09T13:47:08.000Z | /**
* fwdmodel_pet_1TCM.cc
*
* Implementation of one tissue compartment model for PET
* Moss Zhao - Center for Advanced Functional Neuroimaging (CAFN), Stanford University
*/
/* CCOPYRIGHT */
#include "fwdmodel_pet_1TCM.h"
#include <fabber_core/easylog.h>
#include <fabber_core/priors.h>
#include <miscmaths/miscprob.h>
#include <newimage/newimageall.h>
#include <newmatio.h>
#include <iostream>
#include <stdexcept>
using namespace NEWMAT;
FactoryRegistration<FwdModelFactory, PET_1TCM_FwdModel> PET_1TCM_FwdModel::registration("pet_1TCM");
std::string PET_1TCM_FwdModel::GetDescription() const
{
return "PET one tissue compartment model";
}
static OptionSpec OPTIONS[] = {
{ "K1", OPT_FLOAT, "Flow in min-1", OPT_NONREQ, "0.01" },
{ "k2", OPT_FLOAT, "Flow in min-1", OPT_NONREQ, "0.1" },
{ "vB", OPT_FLOAT, "Blood volume in 1", OPT_NONREQ, "0.05" },
//{ "fp", OPT_FLOAT, "Flow in min-1", OPT_NONREQ, "0.5" },
//{ "ps", OPT_FLOAT, "Permeability surface area product in min-1", OPT_NONREQ, "0.5" },
//{ "vp", OPT_FLOAT, "Plasma volume in decimal between zero and one", OPT_NONREQ, "0.5" },
//{ "ve", OPT_FLOAT, "Extracellular space volume in decimal between zero and one", OPT_NONREQ, "0.05" },
//{ "conv-method", OPT_STR, "Method to compute convolution, trapezium, matrix or iterative. Default is iterative", OPT_REQ, "iterative"},
{ "" },
};
void PET_1TCM_FwdModel::GetOptions(vector<OptionSpec> &opts) const
{
PETFwdModel::GetOptions(opts);
for (int i = 0; OPTIONS[i].name != ""; i++)
{
opts.push_back(OPTIONS[i]);
}
}
void PET_1TCM_FwdModel::Initialize(FabberRunData &rundata)
{
PETFwdModel::Initialize(rundata);
// Initial values of main parameters
m_K1 = rundata.GetDoubleDefault("K1", 0.05);
m_k2 = rundata.GetDoubleDefault("k2", 0.05);
m_vB = rundata.GetDoubleDefault("vB", 0.03);
// Initial values of main parameters
//m_fp = rundata.GetDoubleDefault("fp", 0.5);
//m_ps = rundata.GetDoubleDefault("ps", 0.5);
//m_ve = rundata.GetDoubleDefault("ve", 0.5);
//m_vp = rundata.GetDoubleDefault("vp", 0.05);
// Other model options
//m_conv_method = rundata.GetStringDefault("conv-method", "iterative");
}
void PET_1TCM_FwdModel::GetParameterDefaults(std::vector<Parameter> ¶ms) const
{
params.clear();
// Basic model parameters
int p = 0;
// This set of parameters worked
//params.push_back(Parameter(p++, "K1", DistParams(m_K1, 1e5), DistParams(m_K1, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
//params.push_back(Parameter(p++, "k2", DistParams(m_k2, 1e5), DistParams(m_k2, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
//params.push_back(Parameter(p++, "vB", DistParams(m_vB, 1e5), DistParams(m_vB, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
params.push_back(Parameter(p++, "K1", DistParams(m_K1, 100), DistParams(m_K1, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
params.push_back(Parameter(p++, "k2", DistParams(m_k2, 100), DistParams(m_k2, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
params.push_back(Parameter(p++, "vB", DistParams(m_vB, 100), DistParams(m_vB, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
//params.push_back(Parameter(p++, "fp", DistParams(m_fp, 1e5), DistParams(m_fp, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
//params.push_back(Parameter(p++, "ps", DistParams(m_ps, 1e5), DistParams(m_ps, 100), PRIOR_NORMAL, TRANSFORM_LOG()));
//params.push_back(Parameter(p++, "ve", DistParams(m_ve, 1e5), DistParams(m_ve, 1), PRIOR_NORMAL, TRANSFORM_FRACTIONAL()));
//params.push_back(Parameter(p++, "vp", DistParams(m_vp, 1), DistParams(m_vp, 1), PRIOR_NORMAL, TRANSFORM_FRACTIONAL()));
// Standard DCE parameters
PETFwdModel::GetParameterDefaults(params);
}
ColumnVector PET_1TCM_FwdModel::compute_convolution(const ColumnVector &vector_1, const ColumnVector &vector_2, const ColumnVector &vector_time) const
{
ColumnVector convolution_result(data.Nrows());
int vector_length_1 = vector_1.Nrows();
int vector_length_2 = vector_2.Nrows();
//cout << data.Nrows() << endl;
//getchar();
// Length of the full convolution results
int temp_length = vector_length_1 + vector_length_2 - 1;
ColumnVector convolution_full(temp_length);
int time_0 = 0;
// Compute convolution
// Source code from here
// https://toto-share.com/2011/11/cc-convolution-source-code/
for (int i = 0; i < temp_length; i++) {
int i1 = i;
double temp = 0.0;
for (int j = 0; j < vector_length_2; j++) {
if(i1 >= 0 && i1 < vector_length_1) {
temp = temp + vector_1(i1 + 1) * vector_2(j + 1);
}
i1 = i1 - 1;
convolution_full(i + 1) = temp;
}
}
// Do the 'same' operation for the final convolution results
/*
int start_point = floor(temp_length / 2) + 1;
for (int i = 1; i <= vector_length_1; i++) {
//cout << start_point << endl;
convolution_result(i) = convolution_full(start_point);
start_point++;
}
*/
// Here we only need the first x elements of the convolution result
for (int i = 1; i <= vector_length_1; i++) {
/*
if(i == 1) {
convolution_result(i) = (vector_time(i) - time_0) * convolution_full(i);
}
else {
convolution_result(i) = (vector_time(i) - vector_time(i - 1)) * convolution_full(i);
}
*/
convolution_result(i) = convolution_full(i);
}
return convolution_result;
}
void PET_1TCM_FwdModel::Evaluate(const ColumnVector ¶ms, ColumnVector &result) const
{
// Parameters that are inferred - extract and give sensible names
int p = 1;
double K1 = params(p++);
double k2 = params(p++);
double vB = params(p++);
/*
double fp = params(p++);
double ps = params(p++);
double ve = params(p++);
double vp = params(p++);
// Standard DCE parameters - may be inferred
double sig0 = m_sig0;
double delay = m_delay;
double t10 = m_t10;
if (m_infer_sig0)
{
sig0 = params(p++);
}
if (m_infer_delay)
{
delay = params(p++);
}
if (m_infer_t10)
{
t10 = params(p++);
}
*/
// Tissue concentration results
//ColumnVector concentration_tissue = compute_concentration(K1, k2);
//double pre_delay = 30.2;
//int vector_length_1 = m_time.Nrows();
//ColumnVector time_new(vector_length_1);
//for (int i = 1; i <= vector_length_1; i++) {
// time_new(i) = m_time(i) + pre_delay;
// //cout << time_new(i) << endl;
//}
ColumnVector exp_results = exp((-k2) * m_time);
ColumnVector convolution_result = compute_convolution(exp_results, m_aif, m_time);
// Converts concentration back to DCE signal
/*
result.ReSize(data.Nrows());
for (int i = 1; i <= data.Nrows(); i++)
{
result(i) = SignalFromConcentration(concentration_tissue(i), t10, sig0);
}
*/
//result = K1 * convolution_result;
result = (1 - vB) * K1 * convolution_result + vB * m_aif;
//result = K1 * exp_results;
for (int i = 1; i <= data.Nrows(); i++)
{
if (isnan(result(i)) || isinf(result(i)))
{
LOG << "Warning NaN or inf in result" << endl;
LOG << "result: " << result.t() << endl;
LOG << "params: " << params.t() << endl;
result = 0.0;
break;
}
}
}
FwdModel *PET_1TCM_FwdModel::NewInstance()
{
return new PET_1TCM_FwdModel();
}
| 31.53527 | 150 | 0.626184 | [
"vector",
"model"
] |
ae2f77dacdf0354d305aca68e29d2d88ab3ba7ef | 31,205 | cxx | C++ | motionbuilder/plugins/Device_LiveBridge/shared.cxx | Neill3d/ACT | 367e6648d255f4dfb38816ce6b4ecc47880b9aaa | [
"MIT"
] | 29 | 2019-11-21T16:24:20.000Z | 2021-01-20T03:52:44.000Z | motionbuilder/plugins/Device_LiveBridge/shared.cxx | Neill3d/ACT | 367e6648d255f4dfb38816ce6b4ecc47880b9aaa | [
"MIT"
] | null | null | null | motionbuilder/plugins/Device_LiveBridge/shared.cxx | Neill3d/ACT | 367e6648d255f4dfb38816ce6b4ecc47880b9aaa | [
"MIT"
] | 3 | 2019-11-22T04:43:35.000Z | 2020-09-25T08:23:56.000Z | /*
#
# Copyright(c) 2020 Avalanche Studios.All rights reserved.
# Licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE
#
*/
// shared.cpp
//
#include <windows.h>
#include "shared.h"
#include "tinyxml.h"
#include <AnimLiveBridge/AnimLiveBridge.h>
#include <algorithm>
#define DEVICE__PREFIX "AnimBridge"
/////////////////////////
//
namespace NShared
{
std::string g_ReferenceName("");
std::vector<std::string> g_JointSet;
const char* GetRootName()
{
return g_ReferenceName.c_str();
}
const int GetSetJointsCount()
{
return static_cast<int>(g_JointSet.size());
}
const char* GetTestJointName(const int index)
{
if (index >= 0 && index < static_cast<int>(g_JointSet.size()))
{
return g_JointSet[index].c_str();
}
return nullptr;
}
bool FindParentInList(FBModel* model, FBModelList* models)
{
if (model)
{
for (int i = 0; i < models->GetCount(); ++i)
{
if (model == models->GetAt(i))
{
return true;
}
}
if (FindParentInList(model->Parent, models))
return true;
}
return false;
}
bool ImportJointSet(const char* filename)
{
TiXmlDocument doc;
if (doc.LoadFile(filename) == false)
{
return false;
}
//
g_ReferenceName = "";
g_JointSet.clear();
TiXmlNode *node = nullptr;
TiXmlElement *head = nullptr;
TiXmlElement *item = nullptr;
node = doc.FirstChild("JointSet");
if (node == nullptr)
{
return false;
}
head = node->ToElement();
if (!head)
return false;
item = node->FirstChildElement("Model");
int count = 0;
head->Attribute("count", &count);
if (const char* root_name = head->Attribute("root"))
{
g_ReferenceName = root_name;
}
if (count == 0 || g_ReferenceName.empty())
return false;
for (; nullptr != item; item = item->NextSiblingElement())
{
const char* model_name = item->Attribute("name");
g_JointSet.push_back(model_name);
}
return true;
}
bool ExportJointSet(const char* filename)
{
TiXmlDocument doc;
FBModelList models;
FBGetSelectedModels(models);
const int count = models.GetCount();
if (count == 0)
return false;
FBModel* root = nullptr;
for (int i = 0; i < count; ++i)
{
FBModel* model = models[i];
// try to find parent in a selection list
if (!FindParentInList(model->Parent, &models))
{
root = model->Parent;
break;
}
}
TiXmlElement head("JointSet");
head.SetAttribute("count", count);
head.SetAttribute("root", (root) ? root->Name : "_Empty_");
head.SetAttribute("version", 1);
for (int i = 0; i < count; ++i)
{
TiXmlElement item("Model");
item.SetAttribute("name", models[i]->Name);
head.InsertEndChild(item);
}
doc.InsertEndChild(head);
doc.SaveFile(filename);
if (doc.Error())
{
printf("%s", doc.ErrorDesc());
return false;
}
return true;
}
bool StoreJointSet(FBFbxObject* pFbxObject)
{
if (g_ReferenceName.empty() || g_JointSet.empty())
return false;
pFbxObject->FieldWriteBegin("Reference");
pFbxObject->FieldWriteC(g_ReferenceName.c_str());
pFbxObject->FieldWriteEnd();
const int count = static_cast<int>(g_JointSet.size());
pFbxObject->FieldWriteBegin("JointSet");
pFbxObject->FieldWriteI(count);
for (int i = 0; i < count; ++i)
{
pFbxObject->FieldWriteC(g_JointSet[i].c_str());
}
pFbxObject->FieldWriteEnd();
return true;
}
bool RetrieveJointSet(FBFbxObject* pFbxObject)
{
g_ReferenceName.clear();
g_JointSet.clear();
if (pFbxObject->FieldReadBegin("Reference"))
{
g_ReferenceName = pFbxObject->FieldReadC();
pFbxObject->FieldReadEnd();
}
if (pFbxObject->FieldReadBegin("JointSet"))
{
const int count = pFbxObject->FieldReadI();
g_JointSet.resize(count);
for (int i = 0; i < count; ++i)
{
g_JointSet[i] = pFbxObject->FieldReadC();
}
pFbxObject->FieldReadEnd();
}
return (!g_ReferenceName.empty());
}
};
/////////////////////////////////////////////////////////////////
// STimeChangeManager
STimeChangeManager::STimeChangeManager()
{
mLocalTimeChanged = false;
mRemoteTimeChanged = false;
mIsPlaying = false;
}
void STimeChangeManager::CheckLocalTimeline()
{
FBTime localTime(mSystem.LocalTime);
mIsPlaying = mPlayerControl.IsPlaying;
if (mIsPlaying)
{
mLocalTimeChanged = true;
mLocalLastTime = localTime;
mRemoteTimeChanged = false;
}
else
if (localTime != mLocalLastTime && false == mRemoteTimeChanged)
{
mLocalTimeChanged = true;
mLocalLastTime = localTime;
}
}
// we could read from server or client data values
void STimeChangeManager::ReadFromData(const bool server, SSharedModelData& data)
{
SPlayerInfo& playerInfo = (server) ? data.m_ServerPlayer : data.m_ClientPlayer;
const double secs = playerInfo.m_LocalTime + mOffsetTime.GetSecondDouble();
FBTime packet_time;
packet_time.SetSecondDouble(secs);
if (playerInfo.m_TimeChangedEvent > 0.0f)
{
playerInfo.m_TimeChangedEvent = 0.0f;
mRemoteTimeChanged = true;
mRemoteLastTime = packet_time;
}
}
// write to server or client data values
void STimeChangeManager::WriteToData(const bool server, SSharedModelData& data)
{
SPlayerInfo& playerInfo = (server) ? data.m_ServerPlayer : data.m_ClientPlayer;
CheckLocalTimeline();
if (!mRemoteTimeChanged && (mLocalTimeChanged || mIsPlaying))
{
mLocalTimeChanged = false;
mLocalLastTime = mSystem.LocalTime;
playerInfo.m_LocalTime = mLocalLastTime.GetSecondDouble() - mOffsetTime.GetSecondDouble();
playerInfo.m_TimeChangedEvent = 1.0f;
}
else
{
playerInfo.m_TimeChangedEvent = 0.0f;
}
}
void STimeChangeManager::OnUIIdle()
{
if (mRemoteTimeChanged)
{
mRemoteTimeChanged = false;
//
FBTime curr_time(mSystem.LocalTime);
mIsPlaying = mPlayerControl.IsPlaying;
if (mRemoteLastTime != curr_time && false == mIsPlaying)
{
mPlayerControl.Goto(mRemoteLastTime);
//
mLocalTimeChanged = false;
mLocalLastTime = mRemoteLastTime;
}
}
}
void STimeChangeManager::SetOffsetTime(const FBTime& time)
{
mOffsetTime = time;
}
void STimeChangeManager::SetIsPlaying(const bool value)
{
mIsPlaying = value;
}
const bool STimeChangeManager::IsRemoteTimeChanged() const
{
return mRemoteTimeChanged;
}
const FBTime& STimeChangeManager::GetRemoteTime() const
{
return mRemoteLastTime;
}
////////////////////////////////////////////////////////////////
// CDataChannelManager
bool CDataChannelManager::SaveModelsInfoToXML(const char* file_name)
{
TiXmlDocument doc;
const int numberOfModels = GetNumberOfChannels();
TiXmlElement head("Header");
head.SetAttribute("numberOfModels", numberOfModels);
head.SetAttribute("version", 1);
for (DataChannel* pChannel : mChannels)
{
if (false == pChannel->mIsUsed)
continue;
TiXmlElement modelItem("Model");
modelItem.SetAttribute("name", pChannel->mName);
if (FBModel* pModel = pChannel->mModelTemplate->Model)
{
// Rotation limits
TiXmlElement rotItem("Rotation");
rotItem.SetAttribute("order", int(pModel->RotationOrder));
rotItem.SetAttribute("active", (pModel->RotationActive) ? 1 : 0);
rotItem.SetAttribute("minX", (pModel->RotationMinX) ? 1 : 0);
rotItem.SetAttribute("minY", (pModel->RotationMinY) ? 1 : 0);
rotItem.SetAttribute("minZ", (pModel->RotationMinZ) ? 1 : 0);
rotItem.SetAttribute("maxX", (pModel->RotationMaxX) ? 1 : 0);
rotItem.SetAttribute("maxY", (pModel->RotationMaxY) ? 1 : 0);
rotItem.SetAttribute("maxZ", (pModel->RotationMaxZ) ? 1 : 0);
FBVector3d r = pModel->PreRotation;
TiXmlElement preRotItem("PreRotation");
preRotItem.SetDoubleAttribute("x", r[0]);
preRotItem.SetDoubleAttribute("y", r[1]);
preRotItem.SetDoubleAttribute("z", r[2]);
rotItem.InsertEndChild(preRotItem);
r = pModel->PostRotation;
TiXmlElement postRotItem("PostRotation");
postRotItem.SetDoubleAttribute("x", r[0]);
postRotItem.SetDoubleAttribute("y", r[1]);
postRotItem.SetDoubleAttribute("z", r[2]);
rotItem.InsertEndChild(postRotItem);
r = pModel->RotationMin;
TiXmlElement minRotItem("RotationMin");
minRotItem.SetDoubleAttribute("x", r[0]);
minRotItem.SetDoubleAttribute("y", r[1]);
minRotItem.SetDoubleAttribute("z", r[2]);
rotItem.InsertEndChild(minRotItem);
r = pModel->RotationMax;
TiXmlElement maxRotItem("RotationMax");
maxRotItem.SetDoubleAttribute("x", r[0]);
maxRotItem.SetDoubleAttribute("y", r[1]);
maxRotItem.SetDoubleAttribute("z", r[2]);
rotItem.InsertEndChild(maxRotItem);
modelItem.InsertEndChild(rotItem);
//
// Geometric Offset
r = pModel->GeometricTranslation;
TiXmlElement geomTranslation("GeometricTranslation");
geomTranslation.SetDoubleAttribute("x", r[0]);
geomTranslation.SetDoubleAttribute("y", r[1]);
geomTranslation.SetDoubleAttribute("z", r[2]);
modelItem.InsertEndChild(geomTranslation);
r = pModel->GeometricRotation;
TiXmlElement geomRot("GeometricRotation");
geomRot.SetDoubleAttribute("x", r[0]);
geomRot.SetDoubleAttribute("y", r[1]);
geomRot.SetDoubleAttribute("z", r[2]);
modelItem.InsertEndChild(geomRot);
r = pModel->GeometricScaling;
TiXmlElement geomScl("GeometricScaling");
geomScl.SetDoubleAttribute("x", r[0]);
geomScl.SetDoubleAttribute("y", r[1]);
geomScl.SetDoubleAttribute("z", r[2]);
modelItem.InsertEndChild(geomScl);
}
head.InsertEndChild(modelItem);
}
doc.InsertEndChild(head);
doc.SaveFile(file_name);
if (doc.Error())
{
printf("%s", doc.ErrorDesc());
return false;
}
return true;
}
bool CDataChannelManager::LoadModelsInfoFromXML(const char* file_name)
{
TiXmlDocument doc;
if (doc.LoadFile(file_name) == false)
{
return false;
}
TiXmlNode *node = nullptr;
TiXmlElement *headElement = nullptr;
TiXmlElement *modelElement = nullptr;
node = doc.FirstChild("Header");
if (node == nullptr)
{
return false;
}
headElement = node->ToElement();
if (headElement)
{
modelElement = node->FirstChildElement("Model");
}
for (; nullptr != modelElement; modelElement = modelElement->NextSiblingElement())
{
const char* model_name = modelElement->Attribute("name");
if (nullptr == model_name)
continue;
for (DataChannel* pChannel : mChannels)
{
if (0 == strcmp(model_name, pChannel->mName) && pChannel->mIsUsed)
{
FBModel* pModel = pChannel->mModelTemplate->Model;
if (TiXmlElement *element = modelElement->FirstChildElement("Rotation"))
{
int ivalue = 0;
// double dvalue = 0.0;
if (nullptr != element->Attribute("active", &ivalue))
{
pModel->RotationActive = (ivalue > 0) ? true : false;
}
if (nullptr != element->Attribute("order", &ivalue))
{
pModel->RotationOrder = (FBModelRotationOrder)ivalue;
}
if (nullptr != element->Attribute("minX", &ivalue))
pModel->RotationMinX = static_cast<bool>(ivalue);
if (nullptr != element->Attribute("minY", &ivalue))
pModel->RotationMinY = static_cast<bool>(ivalue);
if (nullptr != element->Attribute("minZ", &ivalue))
pModel->RotationMinZ = static_cast<bool>(ivalue);
if (nullptr != element->Attribute("maxX", &ivalue))
pModel->RotationMaxX = static_cast<bool>(ivalue);
if (nullptr != element->Attribute("maxY", &ivalue))
pModel->RotationMaxY = static_cast<bool>(ivalue);
if (nullptr != element->Attribute("maxZ", &ivalue))
pModel->RotationMaxZ = static_cast<bool>(ivalue);
if (TiXmlElement* child = element->FirstChildElement("PreRotation"))
{
FBVector3d v;
if (nullptr != child->Attribute("x", &v[0])
&& nullptr != child->Attribute("y", &v[1])
&& nullptr != child->Attribute("z", &v[2]))
{
pModel->PreRotation = v;
}
}
if (TiXmlElement* child = element->FirstChildElement("PostRotation"))
{
FBVector3d v;
if (nullptr != child->Attribute("x", &v[0])
&& nullptr != child->Attribute("y", &v[1])
&& nullptr != child->Attribute("z", &v[2]))
{
pModel->PostRotation = v;
}
}
if (TiXmlElement* child = element->FirstChildElement("RotationMin"))
{
FBVector3d v;
if (nullptr != child->Attribute("x", &v[0])
&& nullptr != child->Attribute("y", &v[1])
&& nullptr != child->Attribute("z", &v[2]))
{
pModel->RotationMin = v;
}
}
if (TiXmlElement* child = element->FirstChildElement("RotationMax"))
{
FBVector3d v;
if (nullptr != child->Attribute("x", &v[0])
&& nullptr != child->Attribute("y", &v[1])
&& nullptr != child->Attribute("z", &v[2]))
{
pModel->RotationMax = v;
}
}
}
if (TiXmlElement* element = modelElement->FirstChildElement("GeometricTranslation"))
{
FBVector3d v;
if (nullptr != element->Attribute("x", &v[0])
&& nullptr != element->Attribute("y", &v[1])
&& nullptr != element->Attribute("z", &v[2]))
{
pModel->GeometricTranslation = v;
}
}
if (TiXmlElement* element = modelElement->FirstChildElement("GeometricRotation"))
{
FBVector3d v;
if (nullptr != element->Attribute("x", &v[0])
&& nullptr != element->Attribute("y", &v[1])
&& nullptr != element->Attribute("z", &v[2]))
{
pModel->GeometricRotation = v;
}
}
if (TiXmlElement* element = modelElement->FirstChildElement("GeometricScaling"))
{
FBVector3d v;
if (nullptr != element->Attribute("x", &v[0])
&& nullptr != element->Attribute("y", &v[1])
&& nullptr != element->Attribute("z", &v[2]))
{
pModel->GeometricScaling = v;
}
}
}
}
}
return true;
}
bool CDataChannelManager::FbxStore(FBFbxObject* pFbxObject, kFbxObjectStore pStoreWhat)
{
if (pStoreWhat & kAttributes)
{
if (GetRootTemplate())
{
if (FBModel* pRootModel = GetRootTemplate()->Model)
{
pFbxObject->FieldWriteBegin("RootTransform");
for (int i = 0; i < 16; ++i)
{
pFbxObject->FieldWriteD(mRootDefaultMatrix[i]);
}
FBString model_name(pRootModel->LongName);
pFbxObject->FieldWriteC(model_name);
pFbxObject->FieldWriteEnd();
//
pFbxObject->FieldWriteBegin("Models");
const int count = GetNumberOfChannels();
pFbxObject->FieldWriteI(count);
for (int i = 0; i < count; ++i)
{
pFbxObject->FieldWriteC(GetChannelName(i));
if (FBModel* pModel = GetChannelModel(i))
{
pFbxObject->FieldWriteC(pModel->LongName);
}
else
{
pFbxObject->FieldWriteC("None");
}
//
const double* pos = mChannels[i]->GetPosition();
const double* rot = mChannels[i]->GetRotation();
for (int j = 0; j < 3; ++j)
{
pFbxObject->FieldWriteD(pos[j]);
pFbxObject->FieldWriteD(rot[j]);
}
}
pFbxObject->FieldWriteEnd();
}
}
}
return true;
}
bool CDataChannelManager::FbxRetrieve(FBFbxObject* pFbxObject, kFbxObjectStore pStoreWhat)
{
if (pStoreWhat & kAttributes)
{
if (pFbxObject->FieldReadBegin("RootTransform"))
{
for (int i = 0; i < 16; ++i)
{
mRootDefaultMatrix[i] = pFbxObject->FieldReadD();
}
mRetrieveRootModelName = pFbxObject->FieldReadC();
pFbxObject->FieldReadEnd();
}
if (pFbxObject->FieldReadBegin("Models"))
{
const int count = pFbxObject->FieldReadI();
for (int i = 0; i < count; ++i)
{
FBString channel_name = pFbxObject->FieldReadC();
FBString model_longname = pFbxObject->FieldReadC();
double pos[3], rot[3];
for (int j = 0; j < 3; ++j)
{
pos[j] = pFbxObject->FieldReadD();
rot[j] = pFbxObject->FieldReadD();
}
for (DataChannel* pChannel : mChannels)
{
if (pChannel->mName == channel_name)
{
pChannel->SetTransform(pos, rot);
break;
}
}
}
pFbxObject->FieldReadEnd();
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////////////
// CDataChannelManager
CDataChannelManager::CDataChannelManager()
{
mDevice = nullptr;
mHierarchyIsDefined = false;
mRootTemplate = nullptr;
mUseReadNodes = false;
mRetrieveRootModelName = "";
}
//! a destructor
CDataChannelManager::~CDataChannelManager()
{
for (DataChannel* channel : mChannels)
{
channel->mIsUsed = false;
}
EndChannelSetDefinition();
}
void CDataChannelManager::Init(FBDevice* pdevice, const char* root_name, bool use_read_nodes)
{
mDevice = pdevice;
if (nullptr == mRootTemplate)
{
mRootTemplate = new FBModelTemplate(DEVICE__PREFIX, root_name, kFBModelTemplateSkeleton);
mHierarchyIsDefined = false;
}
else
{
mRootTemplate->Name = root_name;
}
mUseReadNodes = use_read_nodes;
}
void CDataChannelManager::Free()
{
}
/************************************************
* Define model template hierarchy.
************************************************/
void CDataChannelManager::DefineHierarchy()
{
if (mChannels.size() == 0)
{
mHierarchyIsDefined = false;
FBTrace("hierarchy is empty\n");
}
if (!mHierarchyIsDefined && mChannels.size() > 0)
{
for (DataChannel* pChannel : mChannels)
{
mRootTemplate->Children.Add(pChannel->mModelTemplate);
}
mHierarchyIsDefined = true;
}
}
/************************************************
* Start defining the channel set.
************************************************/
void CDataChannelManager::BeginChannelSetDefinition()
{
// Enter edit mode: tag all channels as unused.
for (DataChannel* pChannel : mChannels)
{
pChannel->mIsUsed = false;
}
}
/************************************************
* End the channel set definition.
************************************************/
void CDataChannelManager::EndChannelSetDefinition()
{
// Exit edit mode:
// All used channels: if already defined, don't touch, if new: create animation node and model template
// All unused channels: delete animation nodes and associated model template
int count_to_remove = 0;
for (DataChannel* pChannel : mChannels)
{
if (pChannel->mIsUsed)
{
// Create new translation and rotation animation nodes if necessary
if (!pChannel->mTAnimNode)
{
// We must use a unique name for our connector.
FBString lName(pChannel->mName, " T");
pChannel->mTAnimNode = mDevice->AnimationNodeOutCreate(0, lName, ANIMATIONNODE_TYPE_LOCAL_TRANSLATION);
}
if (!pChannel->mRAnimNode)
{
// We must use a unique name for our connector.
FBString lName(pChannel->mName, " R");
pChannel->mRAnimNode = mDevice->AnimationNodeOutCreate(0, lName, ANIMATIONNODE_TYPE_LOCAL_ROTATION);
}
if (mUseReadNodes && !pChannel->mTFBNode)
{
FBString lName(pChannel->mName, " T OUT");
pChannel->mTFBNode = mDevice->AnimationNodeInCreate(0, lName, ANIMATIONNODE_TYPE_LOCAL_TRANSLATION);
}
if (mUseReadNodes && !pChannel->mRFBNode)
{
FBString lName(pChannel->mName, " R OUT");
pChannel->mRFBNode = mDevice->AnimationNodeInCreate(0, lName, ANIMATIONNODE_TYPE_LOCAL_ROTATION);
}
// Create new model templates
if (!pChannel->mModelTemplate)
{
pChannel->mModelTemplate = new FBModelTemplate(DEVICE__PREFIX, pChannel->mName, kFBModelTemplateSkeleton);
// Bind model template to T and R animation nodes
pChannel->mModelTemplate->Bindings.Add(pChannel->mTAnimNode);
pChannel->mModelTemplate->Bindings.Add(pChannel->mRAnimNode);
}
}
else //Unused channels: cleanup
{
count_to_remove += 1;
// Unbind model templates from T and R animation nodes
if (pChannel->mTAnimNode)
{
if (pChannel->mModelTemplate)
{
pChannel->mModelTemplate->Bindings.Remove(pChannel->mTAnimNode);
}
}
if (pChannel->mRAnimNode)
{
if (pChannel->mModelTemplate)
{
pChannel->mModelTemplate->Bindings.Remove(pChannel->mRAnimNode);
}
}
// Remove as child of root template
if (mRootTemplate->Children.Find(pChannel->mModelTemplate) >= 0)
{
mRootTemplate->Children.Remove(pChannel->mModelTemplate);
}
if (pChannel->mModelTemplate)
{
for (int j = 0; j < pChannel->mModelTemplate->Children.GetCount(); j++)
{
pChannel->mModelTemplate->Children.RemoveAt(0);
}
}
// Delete model template
delete pChannel->mModelTemplate;
pChannel->mModelTemplate = nullptr;
// Destroy unused animation nodes
if (pChannel->mTAnimNode)
{
mDevice->AnimationNodeDestroy(pChannel->mTAnimNode);
}
if (pChannel->mRAnimNode)
{
mDevice->AnimationNodeDestroy(pChannel->mRAnimNode);
}
if (pChannel->mTFBNode)
{
mDevice->AnimationNodeDestroy(pChannel->mTFBNode);
}
if (pChannel->mRFBNode)
{
mDevice->AnimationNodeDestroy(pChannel->mRFBNode);
}
pChannel->mTAnimNode = nullptr;
pChannel->mRAnimNode = nullptr;
pChannel->mTFBNode = nullptr;
pChannel->mRFBNode = nullptr;
}
}
//Delete entry in list for all unused channels
if (count_to_remove == static_cast<int>(mChannels.size()))
{
for (DataChannel* channel : mChannels)
{
delete channel;
}
mChannels.clear();
}
else
{
mChannels.erase(
std::remove_if(begin(mChannels), end(mChannels), [](DataChannel* channel)->bool
{
bool need_to_remove = (!channel->mIsUsed);
if (need_to_remove)
{
delete channel;
}
return need_to_remove;
}),
end(mChannels));
}
//Make sure reference number still match
for (size_t i = 0; i < mChannels.size(); ++i)
{
if (mChannels[i]->mTAnimNode)
{
mChannels[i]->mTAnimNode->Reference = static_cast<kReference>(i);
}
if (mChannels[i]->mRAnimNode)
{
mChannels[i]->mRAnimNode->Reference = static_cast<kReference>(i);
}
if (mChannels[i]->mTFBNode)
{
mChannels[i]->mTFBNode->Reference = static_cast<kReference>(i);
}
if (mChannels[i]->mRFBNode)
{
mChannels[i]->mRFBNode->Reference = static_cast<kReference>(i);
}
}
//Define hierarchy if needed
DefineHierarchy();
}
void CDataChannelManager::UpdateDefaultTransforms()
{
if (mRetrieveRootModelName.GetLen() == 0)
{
if (mRootTemplate)
{
if (FBModel* pModel = mRootTemplate->Model)
{
pModel->GetMatrix(mRootDefaultMatrix, kModelTransformation, false);
}
}
for (DataChannel* pChannel : mChannels)
{
pChannel->AssignDefaultTransform();
}
}
}
void CDataChannelManager::RestoreDefaultTransforms()
{
if (mRootTemplate)
{
if (FBModel* pModel = mRootTemplate->Model)
{
pModel->SetMatrix(mRootDefaultMatrix, kModelTransformation, false);
}
}
for (DataChannel* pChannel : mChannels)
{
pChannel->RestoreDefaultTransform();
}
mRetrieveRootModelName = "";
}
/************************************************
* Use the channel pName.
************************************************/
int CDataChannelManager::UseChannel(const char *pName)
{
char lName[256];
strcpy_s(lName, sizeof(char)*256, pName);
// FB cannot deal with spaces in names replace with '_'
for (unsigned int j = 0; j < strlen(lName); j++)
{
if (lName[j] == ' ') lName[j] = '_';
}
for (size_t i = 0; i < mChannels.size(); ++i)
{
if (mChannels[i]->mName == lName)
{
mChannels[i]->mIsUsed = true;
return (int)i;
}
}
DataChannel *newChannel = new DataChannel;
newChannel->mName = lName;
newChannel->mIsUsed = true;
mChannels.push_back(newChannel);
return (int)(mChannels.size() - 1);
}
bool CDataChannelManager::ReadInputData(const int Index, double* Pos, double* Rot, FBEvaluateInfo* pEvaluateInfo)
{
if (mChannels[Index]->mTFBNode && mChannels[Index]->mRFBNode)
{
mChannels[Index]->mTFBNode->ReadData(Pos, pEvaluateInfo);
mChannels[Index]->mRFBNode->ReadData(Rot, pEvaluateInfo);
return true;
}
return false;
}
bool CDataChannelManager::ReadOutputData(const int Index, double* Pos, double* Rot, FBEvaluateInfo* pEvaluateInfo)
{
if (mChannels[Index]->mTAnimNode && mChannels[Index]->mRAnimNode)
{
mChannels[Index]->mTAnimNode->ReadData(Pos, pEvaluateInfo);
mChannels[Index]->mRAnimNode->ReadData(Rot, pEvaluateInfo);
return true;
}
return false;
}
bool CDataChannelManager::WriteData(const int Index, const double* Pos, const double* Rot, FBEvaluateInfo* pEvaluateInfo)
{
if (mChannels[Index]->mTAnimNode && mChannels[Index]->mRAnimNode)
{
mChannels[Index]->mTAnimNode->WriteData((double*)Pos, pEvaluateInfo);
mChannels[Index]->mRAnimNode->WriteData((double*)Rot, pEvaluateInfo);
return true;
}
return false;
}
bool CDataChannelManager::RecordData(const int index, const double* pos, const double* rot, FBTime* time)
{
DataChannel* pChannel = mChannels[index];
if (pChannel->mIsUsed)
{
// Translation information.
if (pChannel->mTAnimNode)
{
if (FBAnimationNode* Data = pChannel->mTAnimNode->GetAnimationToRecord())
{
if (nullptr == time)
{
Data->KeyAdd((double*)pos);
}
else
{
Data->KeyAdd(*time, (double*)pos);
}
}
}
//
if (pChannel->mRAnimNode)
{
if (FBAnimationNode* Data = pChannel->mRAnimNode->GetAnimationToRecord())
{
if (nullptr == time)
{
Data->KeyAdd((double*)rot);
}
else
{
Data->KeyAdd(*time, (double*)rot);
}
}
}
}
return true;
}
bool ExportTargetAnimation(FBModel* pFacialRoot, FBModel* pRoot, FBModel* pLeft, FBModel* pRight)
{
if (nullptr == pFacialRoot || nullptr == pRoot || 0 == pLeft || 0 == pRight)
{
FBMessageBox("Client Device", "We have nothing to sync!", "Ok");
return false;
}
bool lResult = false;
FBSystem lSystem;
FBApplication lApp;
FBString full_name_root(LOOKAT_RIG_NS, ":");
full_name_root = full_name_root + LOOKAT_CTRL_ROOT;
FBString full_name_left(LOOKAT_RIG_NS, ":");
full_name_left = full_name_left + LOOKAT_CTRL_LEFT;
FBString full_name_right(LOOKAT_RIG_NS, ":");
full_name_right = full_name_right + LOOKAT_CTRL_RIGHT;
FBModel* obj_root = FBFindModelByLabelName(full_name_root);
if (obj_root != nullptr)
obj_root->LongName = FBString(full_name_root, "_temp_temp");
FBModel* obj_left = FBFindModelByLabelName(full_name_left);
if (obj_left != nullptr)
obj_left->LongName = FBString(full_name_left, "_temp_temp");
FBModel* obj_right = FBFindModelByLabelName(full_name_right);
if (obj_right != nullptr)
obj_right->LongName = FBString(full_name_right, "_temp_temp");
FBModelNull* tmpRoot = new FBModelNull(full_name_root);
tmpRoot->Show = true;
tmpRoot->Parent = pFacialRoot;
FBModelNull* tmpLeft = new FBModelNull(full_name_left);
tmpLeft->Show = true;
tmpLeft->Parent = tmpRoot;
FBModelNull* tmpRight = new FBModelNull(full_name_right);
tmpRight->Show = true;
tmpRight->Parent = tmpRoot;
FBConstraint* constraint = FBConstraintManager::TheOne().TypeCreateConstraint("Parent/Child");
if (constraint) // && constraintL && constraintR)
{
constraint->ReferenceAdd(0, tmpRoot);
constraint->ReferenceAdd(1, pRoot);
constraint->Lock = true;
constraint->Active = true;
FBTime lPeriod(0, 0, 0, 1);
FBArrayTemplate<FBBox*> objs;
objs.Add(tmpRoot);
FBTake* currTake = lSystem.CurrentTake;
currTake->PlotTakeOnObjects(lPeriod, &objs);
constraint->Active = false;
tmpRoot->Scaling = pRoot->Scaling;
FBFbxOptions lOptions(false);
lOptions.SaveSelectedModelsOnly = true;
lOptions.SetAll(kFBElementActionDiscard, false);
lOptions.Models = kFBElementActionSave;
lOptions.ModelsAnimation = true;
lOptions.UpdateRecentFiles = false;
for (int i = 0, count = lOptions.GetTakeCount(); i < count; ++i)
{
if (0 == strcmp(currTake->LongName, lOptions.GetTakeName(i)))
{
lOptions.SetTakeSelect(i, true);
lOptions.SetTakeDestinationName(i, "Take 001");
}
else
{
lOptions.SetTakeSelect(i, false);
}
}
tmpRoot->Selected = true;
tmpLeft->Selected = true;
tmpRight->Selected = true;
FBString filename(lSystem.TempPath, SHARED_SYNC_TEMP_FILE);
lApp.FileSave(filename, &lOptions);
lResult = true;
constraint->FBDelete();
}
tmpRoot->FBDelete();
tmpLeft->FBDelete();
tmpRight->FBDelete();
if (obj_root != nullptr)
obj_root->LongName = full_name_root;
if (obj_left != nullptr)
obj_left->LongName = full_name_left;
if (obj_right != nullptr)
obj_right->LongName = full_name_right;
return lResult;
}
bool IsFileExists(const char *filename) {
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(filename, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
return false;
}
else
{
FindClose(hFind);
return true;
}
}
bool ImportTargetAnimation(FBModel* pFacialRoot, FBModel* pRoot, FBModel* pLeft, FBModel* pRight)
{
FBSystem lSystem;
FBApplication lApp;
// DONE: check if sync file is exist
FBString filename(lSystem.TempPath, SHARED_SYNC_TEMP_FILE);
if (false == IsFileExists(filename))
{
FBMessageBox("Server Device", "Sync file is not found!", "Ok");
return false;
}
if (nullptr == pRoot || nullptr == pLeft || nullptr == pRight)
{
FBMessageBox("Server Device", "Couldnt locate a LookAtRoot object in the scene", "Ok");
return false;
}
pRoot->Parent = pFacialRoot;
FBString temp_root_name = pRoot->LongName;
FBString temp_left_name = pLeft->LongName;
FBString temp_right_name = pRight->LongName;
FBString full_name_root(LOOKAT_RIG_NS, ":");
full_name_root = full_name_root + LOOKAT_CTRL_ROOT;
FBString full_name_left(LOOKAT_RIG_NS, ":");
full_name_left = full_name_left + LOOKAT_CTRL_LEFT;
FBString full_name_right(LOOKAT_RIG_NS, ":");
full_name_right = full_name_right + LOOKAT_CTRL_RIGHT;
pRoot->LongName = full_name_root;
pLeft->LongName = full_name_left;
pRight->LongName = full_name_right;
// DONE: merge sync file with a current take and LookAtCtrl model
FBFbxOptions lOptions(true, filename);
lOptions.SetAll(kFBElementActionDiscard, false);
lOptions.Models = kFBElementActionDiscard;
lOptions.ModelsAnimation = true;
lOptions.UpdateRecentFiles = false;
for (int i = 0, count = lOptions.GetTakeCount(); i < count; ++i)
{
lOptions.SetTakeSelect(i, false);
}
FBTake* currTake = lSystem.CurrentTake;
lOptions.SetTakeSelect(0, true);
lOptions.SetTakeDestinationName(0, currTake->LongName);
bool lResult = lApp.FileMerge(filename, false, &lOptions);
pRoot->LongName = temp_root_name;
pLeft->LongName = temp_left_name;
pRight->LongName = temp_right_name;
return lResult;
}
| 24.227484 | 121 | 0.668419 | [
"object",
"vector",
"model"
] |
ae4734361ca87b62808bce33a8a363f6836b3162 | 17,491 | cpp | C++ | elf2mif/elf2mif.cpp | emmicro-us/elf2mif | 981983a02f0c1a9ac3adb6a844ee1bd02d4d1e7f | [
"BSD-2-Clause"
] | null | null | null | elf2mif/elf2mif.cpp | emmicro-us/elf2mif | 981983a02f0c1a9ac3adb6a844ee1bd02d4d1e7f | [
"BSD-2-Clause"
] | null | null | null | elf2mif/elf2mif.cpp | emmicro-us/elf2mif | 981983a02f0c1a9ac3adb6a844ee1bd02d4d1e7f | [
"BSD-2-Clause"
] | 2 | 2020-04-09T23:31:10.000Z | 2020-04-22T13:53:28.000Z | ////////////////////////////////////////////////////////////////////////////////
///
/// @file elf2mif/elf2mif.cpp
///
/// @project elf2mif
///
/// @brief Tool to generate a Memory Initilization File (MIF) for a given
/// memory region.
///
////////////////////////////////////////////////////////////////////////////////
///
////////////////////////////////////////////////////////////////////////////////
///
/// @copyright Copyright (C) 2015-2020 EM Microelectronic
/// @cond
///
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
////////////////////////////////////////////////////////////////////////////////
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
/// @endcond
////////////////////////////////////////////////////////////////////////////////
#define XSTR(s) STR(s)
#define STR(s) #s
#define ELF2MIF_VERSION \
XSTR(ELF2MIF_MAJOR) \
"." XSTR(ELF2MIF_MINOR) "." XSTR(ELF2MIF_REVISION)
#define __STDC_FORMAT_MACROS 1
#include <OptionParser.h>
#include <elfio/elfio2.hpp>
#include <cstdio>
#include <cstdlib>
// #define DEBUG_PRINT (1)
#if WIN32
#include <Windows.h>
#include <io.h>
#define PRIx64 "I64x"
#define err(code, ...) \
do \
{ \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
exit(code); \
} while (0)
#define errx(code, ...) \
do \
{ \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
exit(code); \
} while (0)
#define sscanf sscanf_s
FILE *my_fopen(const char *filename, const char *mode)
{
FILE *pFile = NULL;
if (0 != fopen_s(&pFile, filename, mode))
return NULL;
return pFile;
}
#else
#include <err.h>
#include <unistd.h>
#include <sys/queue.h>
#include <inttypes.h>
#define my_fopen(filename, mode) fopen(filename, mode)
#endif // WIN32
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#define HEX_PREFIX ("0x")
#define FILL_BYTE (0x00)
using namespace ELFIO;
bool gOutputHex = false;
uint8_t *ExtractSegments(void *elf, uint32_t startAddress,
uint32_t endAddress, uint32_t size)
{
// Pointer to the memory region to dump data into.
elfio2 *pElf = (elfio2 *)elf;
uint8_t *pMemory = 0;
uint32_t segmentStartAddress;
uint32_t segmentEndAddress;
uint32_t segmentSize;
//
// Allocate and fill the memory region.
//
pMemory = new uint8_t[size];
memset(pMemory, FILL_BYTE, size);
//
// Dump all segments (at least partially) within the memory region.
//
for (std::vector<segment *>::const_iterator it = pElf->segments.begin();
it != pElf->segments.end(); ++it)
{
const segment *pSegment = *it;
segmentStartAddress = (uint32_t)pSegment->get_physical_address();
segmentSize = (uint32_t)pSegment->get_file_size();
segmentEndAddress = segmentStartAddress + segmentSize;
if (PT_LOAD == pSegment->get_type() &&
((segmentEndAddress > startAddress && segmentEndAddress <= endAddress) || // Ends within the region.
(segmentStartAddress >= startAddress && segmentStartAddress < endAddress) || // Starts within the region.
(segmentStartAddress <= startAddress && segmentEndAddress >= endAddress)) // Completely contains the region.
)
{
bool truncating = false;
//
// At least 1 byte from this section is within the memory region.
//
uint32_t sourceOffset;
uint32_t destOffset;
if (segmentStartAddress >= startAddress)
{
destOffset = segmentStartAddress - startAddress;
sourceOffset = 0;
}
else
{
destOffset = 0;
sourceOffset = startAddress - segmentStartAddress;
segmentSize -= sourceOffset;
}
if (segmentEndAddress > endAddress)
{
truncating = true;
segmentSize -= (segmentEndAddress - endAddress);
}
// Check if the end address of the section is within the memory
// region of if the region should be clipped.
#ifdef DEBUG_PRINT
printf("Copying from 0x%08x to 0x%08x (0x%08x bytes)\n",
sourceOffset, destOffset, segmentSize);
printf("Segment: 0x%08x-0x%08x %s(%u bytes)\n",
segmentStartAddress, segmentEndAddress, (truncating || sourceOffset) ? "(truncated) " : "", segmentSize);
#endif // DEBUG_PRINT
// Read the section data.
memcpy(&pMemory[destOffset], &pSegment->get_data()[sourceOffset], segmentSize);
}
}
return pMemory;
}
uint8_t *ExtractSegments(const char *pInFile, const char *pStartSymbol,
const char *pEndSymbol, uint32_t *size)
{
// Create the elfio reader.
elfio2 elf;
//
// Open the input ELF file.
//
if (!elf.load(pInFile))
{
return 0;
}
symbol *start_symbol = elf.symbols[pStartSymbol];
symbol *end_symbol = elf.symbols[pEndSymbol];
if (!start_symbol)
{
fprintf(stderr, "Error: unable to locate symbol '%s'\n", pStartSymbol);
exit(-1);
}
if (!end_symbol)
{
fprintf(stderr, "Error: unable to locate symbol '%s'\n", pEndSymbol);
exit(-1);
}
if (!size)
{
return 0;
}
uint32_t start_addr = (uint32_t)start_symbol->get_value();
uint32_t end_addr = (uint32_t)end_symbol->get_value() - 1;
if (end_addr < start_addr)
{
fprintf(stderr, "Error: unable to dump from 0x%08x to 0x%08x\n", start_addr, end_addr);
exit(-1);
}
*size = end_addr - start_addr + 1;
return ExtractSegments((void *)&elf, start_addr, end_addr, *size);
}
uint8_t *ExtractSegments(const char *pInFile, uint32_t startAddress,
uint32_t endAddress, uint32_t size)
{
// Create the elfio reader.
elfio2 elf;
//
// Open the input ELF file.
//
if (!elf.load(pInFile))
{
return 0;
}
return ExtractSegments((void *)&elf, startAddress, endAddress, size);
}
/**
* Function to sort a vector or list of segments by virtual address with the
* std::sort function.
* @param pSegmentA First segment to compare.
* @param pSegmentB Second segment to compare.
* @returns true if the first segment comes before the second segment.
*/
static bool SortSegmentsByVirtAddr(segment *pSegmentA, segment *pSegmentB)
{
return pSegmentA->get_virtual_address() < pSegmentB->get_virtual_address();
}
uint8_t *ExtractAllSegments(const char *pInFile, uint32_t *pSize)
{
bool foundStart = false;
uint32_t startAddress = 0;
uint32_t endAddress = 0;
// Create the elfio reader.
elfio2 elf;
// Pointer to the memory region to dump data into.
uint8_t *pMemory = 0;
if (pSize)
{
*pSize = 0;
}
else
{
return 0;
}
//
// Open the input ELF file.
//
if (!elf.load(pInFile))
{
return 0;
}
int segmentID = 1;
// Copy the segments and sort the list.
std::vector<segment *> segments(elf.segments.begin(), elf.segments.end());
std::sort(segments.begin(), segments.end(), SortSegmentsByVirtAddr);
//
// Determine the actual size of the buffer needed.
//
for (std::vector<segment *>::const_iterator it = segments.begin();
it != segments.end(); ++it, ++segmentID)
{
const segment *pSegment = *it;
if (PT_LOAD == pSegment->get_type())
{
if (!foundStart)
{
foundStart = true;
startAddress = (uint32_t)pSegment->get_virtual_address();
}
else
{
if ((uint32_t)pSegment->get_virtual_address() > endAddress)
{
uint32_t bytes = (uint32_t)pSegment->get_virtual_address() - endAddress;
if (bytes < 8)
{
// Don't throw and error for expected alignment.
}
else if (bytes > 1024 * 1024)
{
printf("Error: inserting %u bytes of padding before segment %d\n", bytes, segmentID);
exit(-1);
}
else
{
/* Between 8 and 128 bytes of padding. */
printf("Warning: inserting %u bytes of padding before segment %d\n", bytes, segmentID);
}
}
else if ((uint32_t)pSegment->get_virtual_address() != endAddress)
{
printf("Warning: inserting %u bytes in a possibly already allocated region for segment %d\n", (uint32_t)pSegment->get_memory_size(), segmentID);
}
}
uint32_t currentEndAddress = (uint32_t)pSegment->get_virtual_address() + (uint32_t)pSegment->get_memory_size();
if (currentEndAddress > endAddress)
{
endAddress = currentEndAddress;
}
}
}
*pSize = endAddress - startAddress;
if (!*pSize)
{
return 0;
}
#ifdef DEBUG_PRINT
printf("Allocating %d bytes for the output.\n", *pSize);
#endif
//
// Allocate and fill the memory region.
//
pMemory = new uint8_t[*pSize];
memset(pMemory, FILL_BYTE, *pSize);
segmentID = 1;
//
// Dump all segments.
//
for (std::vector<segment *>::const_iterator it = elf.segments.begin();
it != elf.segments.end(); ++it, ++segmentID)
{
uint32_t segmentStartAddress;
uint32_t segmentEndAddress;
uint32_t segmentSize;
const segment *pSegment = *it;
segmentStartAddress = (uint32_t)pSegment->get_virtual_address();
segmentSize = (uint32_t)pSegment->get_file_size();
segmentEndAddress = segmentStartAddress + segmentSize;
if (PT_LOAD == pSegment->get_type())
{
// Remove the offset from the start address to use it as an index
// into the memory region buffer.
segmentStartAddress -= startAddress;
#ifdef DEBUG_PRINT
printf("Copying segment %d: 0x%08x-0x%08x (%u bytes) to %u\n",
segmentID, segmentStartAddress + startAddress, segmentEndAddress, segmentSize, segmentStartAddress);
#endif // DEBUG_PRINT
// Read the segment data.
memcpy(&pMemory[segmentStartAddress], pSegment->get_data(),
segmentSize);
}
}
#ifdef DEBUG_PRINT
printf("All segments copied.\n");
#endif
return pMemory;
}
int WriteMifLine(FILE *pOut, uint32_t data)
{
if (gOutputHex)
{
fprintf(pOut, "%08X\n", data);
}
else
{
uint32_t i;
for (i = 0; i < 32; ++i)
{
if (1 == ((data >> (31 - i)) & 1))
{
fputc('1', pOut);
}
else
{
fputc('0', pOut);
}
}
fputc('\n', pOut);
}
return 0;
}
int WriteBuffer(uint8_t *pMemory, const char *pOutFile, uint32_t size)
{
FILE *pOut;
if (0 == pMemory)
{
return -1;
}
//
// Dump the memory region to the output file.
//
if (NULL == (pOut = my_fopen(pOutFile, "wb")))
{
fprintf(stderr, "Filed to open file for writing: %s\n", pOutFile);
return -1;
}
for (uint32_t i = 0; i < size; i += sizeof(uint32_t))
{
if (0 != WriteMifLine(pOut, *((uint32_t *)&pMemory[i])))
{
return -1;
}
}
//
// Close the elf file.
//
fclose(pOut);
delete[] pMemory;
return 0;
}
int ExtractSegments(const char *pInFile, const char *pOutFile,
uint32_t startAddress, uint32_t endAddress, uint32_t size)
{
// Pointer to the memory region to dump data into.
uint8_t *pMemory;
pMemory = ExtractSegments(pInFile, startAddress, endAddress, size);
return WriteBuffer(pMemory, pOutFile, size);
}
int ExtractSegments(const char *pInFile, const char *pOutFile,
const char *pStartSymbol, const char *pEndSymbol)
{
// Pointer to the memory region to dump data into.
uint8_t *pMemory;
uint32_t size = 0;
pMemory = ExtractSegments(pInFile, pStartSymbol, pEndSymbol, &size);
return WriteBuffer(pMemory, pOutFile, size);
}
int ExtractAllSegments(const char *pInFile, const char *pOutFile)
{
// Pointer to the memory region to dump data into.
uint8_t *pMemory;
uint32_t size;
pMemory = ExtractAllSegments(pInFile, &size);
return WriteBuffer(pMemory, pOutFile, size);
}
int main(int argc, const char *argv[])
{
const char *pStartSymbol = 0;
const char *pEndSymbol = 0;
uint32_t startAddress = 0;
uint32_t endAddress = 0;
uint32_t size = 0;
const char *pInFile;
const char *pOutFile;
int argoff = 0;
optparse::OptionParser parser;
parser.description("Tool to generate Memory Initialization Files (MIFs)");
parser.add_option("-H", "--hex").action("store_true").dest("hex").set_default("0").help("output a hex MIF instead of a binary MIF");
parser.usage("%prog [options] ELF MIF [ADDR_START SIZE] [SYMBOL_START SYMBOL_END]");
parser.epilog("Additional arguments:\n"
" ELF Input ELF file.\n"
" MIF Output Memory Initilization File (MIF).\n"
" ADDR_START Start address of the memory region (in hex) to dump.\n"
" SIZE Size of the memory region to dump (in decimal bytes).\n"
" SYMBOL_START Start address of the memory region (symbol) to dump.\n"
" SYMBOL_END End address of the (symbol) to dump.\n");
parser.version(ELF2MIF_VERSION);
optparse::Values options = parser.parse_args(argc, argv);
std::vector<std::string> args = parser.args();
gOutputHex = options.get("hex");
if (2 != args.size() && 4 != args.size())
{
parser.print_help();
return EXIT_FAILURE;
}
pInFile = args[0].c_str();
pOutFile = args[1].c_str();
if (2 < args.size())
{
if (strlen(HEX_PREFIX) <= args[2].length() && 0 == memcmp(HEX_PREFIX, args[2].c_str(), strlen(HEX_PREFIX)))
{
if (1 != sscanf(&args[2].c_str()[strlen(HEX_PREFIX)], "%x", &startAddress))
{
pStartSymbol = args[2].c_str();
}
}
else
{
if (1 != sscanf(args[2].c_str(), "%x", &startAddress))
{
pStartSymbol = args[2].c_str();
}
}
if (1 != sscanf(args[3].c_str(), "%u", &size))
{
pEndSymbol = args[3].c_str();
#ifdef DEBUG_PRINT
printf("Input file: %s\n", pInFile);
printf("Output file: %s\n", pOutFile);
printf("Start Symbol: %s\n", pStartSymbol);
printf("End Symbol: %s\n", pEndSymbol);
printf("Size: %lu\n", size);
#endif // DEBUG_PRINT
return ExtractSegments(pInFile, pOutFile, pStartSymbol, pEndSymbol);
}
else
{
endAddress = startAddress + size;
#ifdef DEBUG_PRINT
printf("Input file: %s\n", pInFile);
printf("Output file: %s\n", pOutFile);
printf("Start Address: 0x%08x\n", startAddress);
printf("End Address: 0x%08x\n", endAddress);
printf("Size: %lu\n", size);
#endif // DEBUG_PRINT
return ExtractSegments(pInFile, pOutFile, startAddress, endAddress,
size);
}
}
else
{
return ExtractAllSegments(pInFile, pOutFile);
}
return EXIT_FAILURE;
}
| 29.249164 | 164 | 0.560574 | [
"vector"
] |
ae4eac7b18af2af8a61257aa6159b135220bfc8c | 1,634 | cpp | C++ | Dojo/C++ Programming Practices and Principles - Stroustrup/ch5/trythisareaerrorcatcher.cpp | miguelraz/PathToPerformance | 4f098e55023007e62c338d31a7ed2a46a3c99752 | [
"MIT"
] | 5 | 2017-05-04T22:25:06.000Z | 2022-02-15T13:44:50.000Z | Dojo/C++ Programming Practices and Principles - Stroustrup/ch5/trythisareaerrorcatcher.cpp | miguelraz/PathToPerformance | 4f098e55023007e62c338d31a7ed2a46a3c99752 | [
"MIT"
] | null | null | null | Dojo/C++ Programming Practices and Principles - Stroustrup/ch5/trythisareaerrorcatcher.cpp | miguelraz/PathToPerformance | 4f098e55023007e62c338d31a7ed2a46a3c99752 | [
"MIT"
] | null | null | null | // Ex. 17 - Quadratic root solver
#include "std_lib_facilities.h"
#include <vector>
#include <iostream>
using namespace std;
int area(int length, int width) {
//Check for area stuff
if (length <= 0 || width <= 0) return -1;
//Output.
cout << "area(::int, ::int) returns " << length*width << endl;
return length*width;
}
int frame_area(int x, int y) {
//Check arguments and calculate frame
constexpr int frame_width = 2;
if (x - frame_width <= 0 || y - frame_width <= 0) error("non-positive area yo");
// Output results.
cout << "frame_area returns " << area(x - frame_width, y - frame_width) << endl;
return area(x - frame_width, y - frame_width);
}
int f(int x, int y, int z) {
// Calculate and print areas.
int area1 = area(x, y);
if (area1 <= 0) error("non positive area ");
cout << "First pass. " << endl;
int area2 = frame_area(3, z); // Mistake was here.
cout << "Second pass. " << endl;
int area3 = frame_area(y, z);
cout << "Third pass. " << endl;
double ratio = double(area1) / area3;
// Output results.
cout << "Area1 " << area1 << endl;
cout << "Area2 " << area2 << endl;
cout << "Area3 " << area3 << endl;
cout << "Ratio " << ratio << endl;
//Return.
return ratio;
}
int main()
{
// Take user inputs.
cout << "Gimme x, y, and frame_width " << endl;
int x, y, z;
cin >> x >> y >> z;
cout << "area(x,y) in main returns " << area(x, y) << endl;
cout << endl;
cout << "frame_area(x,y) in main returns " << frame_area(x, y) << endl;
cout << endl;
cout << "f(x,y,z) in main returns " << f(x, y, z) << endl;;
}
| 24.38806 | 82 | 0.576499 | [
"vector"
] |
ae5208c7b876300b8ff19560c86c925797baaf8d | 3,393 | cpp | C++ | src/Core/src/convert_to_space_boundaries.cpp | rosecodym/space-boundary-tool | 300db4084cd19b092bdf2e8432da065daeaa7c55 | [
"FSFAP"
] | 6 | 2016-11-01T11:09:00.000Z | 2022-02-15T06:31:58.000Z | src/Core/src/convert_to_space_boundaries.cpp | rosecodym/space-boundary-tool | 300db4084cd19b092bdf2e8432da065daeaa7c55 | [
"FSFAP"
] | null | null | null | src/Core/src/convert_to_space_boundaries.cpp | rosecodym/space-boundary-tool | 300db4084cd19b092bdf2e8432da065daeaa7c55 | [
"FSFAP"
] | null | null | null | #include "precompiled.h"
#include "exceptions.h"
#include "report.h"
#include "sbt-core.h"
#include "space.h"
#include "surface.h"
#include "convert_to_space_boundaries.h"
using namespace reporting;
namespace interface_conversion {
namespace impl {
namespace {
void set_vertex(polyloop * loop, size_t ix, double x, double y, double z) {
loop->vertices[ix].x = x;
loop->vertices[ix].y = y;
loop->vertices[ix].z = z;
}
template <typename PointRange>
void set_geometry(space_boundary * sb, const PointRange & geometry) {
sb->geometry.vertex_count = geometry.size();
sb->geometry.vertices = (point *)malloc(sizeof(point) * geometry.size());
size_t i = 0;
boost::for_each(geometry, [sb, &i](const point_3 & p) {
set_vertex(&sb->geometry, i++, CGAL::to_double(p.x()), CGAL::to_double(p.y()), CGAL::to_double(p.z()));
});
}
} // namespace
space_boundary * create_unlinked_space_boundary(
const surface & s,
double output_eps)
{
using namespace CGAL;
typedef boost::format fmt;
space_boundary * newsb = (space_boundary *)malloc(sizeof(space_boundary));
if (!newsb) { throw failed_malloc_exception(); }
bool stack_overflowed = false;
try {
strncpy(newsb->global_id, s.guid().c_str(), SB_ID_MAX_LEN);
strncpy(
newsb->element_name,
s.is_virtual() ? "" : s.bounded_element()->name().c_str(),
ELEMENT_NAME_MAX_LEN);
auto cleaned_geometry = s.geometry().to_3d(true).front().outer();
if (!geometry_common::cleanup_loop(&cleaned_geometry, output_eps)) {
free(newsb);
return nullptr;
}
if (s.geometry().sense()) {
set_geometry(newsb, cleaned_geometry);
}
else {
set_geometry(newsb, cleaned_geometry | boost::adaptors::reversed);
}
direction_3 norm =
s.geometry().sense() ?
s.geometry().orientation().direction() :
-s.geometry().orientation().direction();
newsb->normal_x = CGAL::to_double(norm.dx());
newsb->normal_y = CGAL::to_double(norm.dy());
newsb->normal_z = CGAL::to_double(norm.dz());
newsb->opposite = nullptr;
newsb->parent = nullptr;
equality_context lc(g_opts.tolernace_in_meters);
newsb->material_layer_count = s.material_layers().size();
if (newsb->material_layer_count > 0) {
auto ids_sz = sizeof(element_id_t) * newsb->material_layer_count;
auto layers_sz = sizeof(double) * newsb->material_layer_count;
newsb->layers = (element_id_t *)malloc(ids_sz);
newsb->thicknesses = (double *)malloc(layers_sz);
if (!newsb->layers || !newsb->thicknesses) {
throw failed_malloc_exception();
}
for (size_t j = 0; j < newsb->material_layer_count; ++j) {
auto id = s.material_layers()[j].layer_element().material();
auto thickness = *s.material_layers()[j].thickness();
newsb->layers[j] = id;
newsb->thicknesses[j] = to_double(lc.snap_height(thickness));
}
}
else {
newsb->layers = nullptr;
newsb->thicknesses = nullptr;
}
newsb->bounded_space = s.bounded_space().original_info();
newsb->is_external = s.is_external();
newsb->is_virtual = s.is_virtual();
}
catch (stack_overflow_exception &) {
// do as little possible here because the stack is still damaged
stack_overflowed = true;
}
if (stack_overflowed) {
_resetstkoflw();
report_warning("Internal error: stack overflow. Please report this SBT"
"bug.");
newsb = nullptr;
}
return newsb;
}
} // namespace
} // namespace interface_conversion | 27.362903 | 105 | 0.687592 | [
"geometry"
] |
ae536912d5eb6d6b4482cc9357f9bd6c4bb89e6f | 28,341 | cpp | C++ | 02-Bubble/02-Bubble/02-Bubble/Player.cpp | Xilef09/2DGame | d33cbca6cce78ca05d08d32e4aa7d61745495ef6 | [
"Apache-2.0"
] | null | null | null | 02-Bubble/02-Bubble/02-Bubble/Player.cpp | Xilef09/2DGame | d33cbca6cce78ca05d08d32e4aa7d61745495ef6 | [
"Apache-2.0"
] | null | null | null | 02-Bubble/02-Bubble/02-Bubble/Player.cpp | Xilef09/2DGame | d33cbca6cce78ca05d08d32e4aa7d61745495ef6 | [
"Apache-2.0"
] | null | null | null | #include <cmath>
#include <iostream>
#include <GL/glew.h>
#include <GL/glut.h>
#include "Player.h"
#include "Game.h"
#define JUMP_ANGLE_STEP 2
#define JUMP_HEIGHT 65
#define FALL_STEP 4
enum PlayerAnims
{
STAND_LEFT, STAND_RIGHT, MOVE_LEFT, MOVE_RIGHT, JUMP_RIGHT, JUMP_LEFT, JUMP_RUN_RIGHT, JUMP_RUN_LEFT,
JUMP_STAND_LEFT, CHANGE_DIRECTION_LEFT, CHANGE_DIRECTION_RIGHT, JUMP_STAND_RIGHT, START_MOVING_RIGHT,
START_MOVING_LEFT, CLIMB_RIGHT, CLIMB_LEFT, ATTACK_RIGHT, ATTACK_LEFT, SPIKE_DEATH_LEFT, SPIKE_DEATH_RIGHT,
SPIKE_DOOR_DEATH_RIGHT, SPIKE_DOOR_DEATH_LEFT, DEATH_LEFT, DEATH_RIGHT, MOVE_SLOW_RIGHT, MOVE_SLOW_LEFT
};
enum LiveAnims{
LIVES
};
enum FireballAnims {
NOTHING, MOVING_RIGHT, MOVING_LEFT
};
void Player::init(const glm::ivec2 &tileMapPos, ShaderProgram &shaderProgram, Scene *scene)
{
this->scene = scene;
hasFireball = false;
//this->fireball = fireball;
//this->fireball->init(tileMapPos, shaderProgram);
lives = 3;
direccion = "";
bJumping = false;
//Barra de vida
spritesheet1Live.setWrapS(GL_MIRRORED_REPEAT);
spritesheet1Live.loadFromFile("images/livebar1.png", TEXTURE_PIXEL_FORMAT_RGBA);
spritesheet2Live.setWrapS(GL_MIRRORED_REPEAT);
spritesheet2Live.loadFromFile("images/livebar2.png", TEXTURE_PIXEL_FORMAT_RGBA);
spritesheet3Live.setWrapS(GL_MIRRORED_REPEAT);
spritesheet3Live.loadFromFile("images/livebar3.png", TEXTURE_PIXEL_FORMAT_RGBA);
spritesheetGameOver.setWrapS(GL_MIRRORED_REPEAT);
spritesheetGameOver.loadFromFile("images/livebarover.png", TEXTURE_PIXEL_FORMAT_RGBA);
spriteLive = Sprite::createSprite(glm::ivec2(320, 10), glm::vec2(1, 1), &spritesheet3Live, &shaderProgram);
spriteLive->setNumberAnimations(1);
spriteLive->setAnimationSpeed(LIVES, 8);
spriteLive->addKeyframe(LIVES, glm::vec2(0.f, 0.f));
spriteLive->changeAnimation(LIVES);
spriteLive->setPosition(glm::vec2(0.f, 320.f));
//Fireball
spritesheetFireball.setWrapS(GL_MIRRORED_REPEAT);
spritesheetFireball.loadFromFile("images/fireballSpriteSheet.png", TEXTURE_PIXEL_FORMAT_RGBA);
spriteFireball = Sprite::createSprite(glm::ivec2(64, 64), glm::vec2(0.1, 0.1), &spritesheetFireball, &shaderProgram);
spriteFireball->setNumberAnimations(3);
spriteFireball->setAnimationSpeed(NOTHING, 8);
spriteFireball->addKeyframe(NOTHING, glm::vec2(0.9f, 0.0f));
spriteFireball->setAnimationSpeed(MOVING_RIGHT, 8);
spriteFireball->addKeyframe(MOVING_RIGHT, glm::vec2(0.1f, 0.0f));
spriteFireball->addKeyframe(MOVING_RIGHT, glm::vec2(0.2f, 0.0f));
spriteFireball->addKeyframe(MOVING_RIGHT, glm::vec2(0.3f, 0.0f));
spriteFireball->addKeyframe(MOVING_RIGHT, glm::vec2(0.4f, 0.0f));
spriteFireball->addKeyframe(MOVING_RIGHT, glm::vec2(0.5f, 0.0f));
spriteFireball->addKeyframe(MOVING_RIGHT, glm::vec2(0.6f, 0.0f));
spriteFireball->setAnimationSpeed(MOVING_LEFT, 8);
spriteFireball->addKeyframe(MOVING_LEFT, glm::vec2(-0.1f, 0.0f));
spriteFireball->addKeyframe(MOVING_LEFT, glm::vec2(-0.2f, 0.0f));
spriteFireball->addKeyframe(MOVING_LEFT, glm::vec2(-0.3f, 0.0f));
spriteFireball->addKeyframe(MOVING_LEFT, glm::vec2(-0.4f, 0.0f));
spriteFireball->addKeyframe(MOVING_LEFT, glm::vec2(-0.5f, 0.0f));
spriteFireball->addKeyframe(MOVING_LEFT, glm::vec2(-0.6f, 0.0f));
spriteFireball->changeAnimation(NOTHING);
spriteFireball->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y)));
//Player sprites
spritesheet.setWrapS(GL_MIRRORED_REPEAT);
spritesheet.loadFromFile("images/princeSpriteSheet2.png", TEXTURE_PIXEL_FORMAT_RGBA);
sprite = Sprite::createSprite(glm::ivec2(64, 64), glm::vec2(0.1, 0.1), &spritesheet, &shaderProgram);
sprite->setNumberAnimations(26);
sprite->setAnimationSpeed(STAND_LEFT, 8);
sprite->addKeyframe(STAND_LEFT, glm::vec2(-0.1f, 0.f));
sprite->setAnimationSpeed(STAND_RIGHT, 8);
sprite->addKeyframe(STAND_RIGHT, glm::vec2(0.f, 0.f));
sprite->setAnimationSpeed(START_MOVING_LEFT, 8);
sprite->addKeyframe(START_MOVING_LEFT, glm::vec2(-0.1f, 0.1f));
sprite->addKeyframe(START_MOVING_LEFT, glm::vec2(-0.2f, 0.1f));
sprite->addKeyframe(START_MOVING_LEFT, glm::vec2(-0.3f, 0.1f));
sprite->addKeyframe(START_MOVING_LEFT, glm::vec2(-0.4f, 0.1f));
sprite->setAnimationSpeed(SPIKE_DEATH_LEFT, 8);
sprite->addKeyframe(SPIKE_DEATH_LEFT, glm::vec2(-0.0f, 0.8f));
sprite->addKeyframe(SPIKE_DEATH_LEFT, glm::vec2(-0.1f, 0.8f));
sprite->addKeyframe(SPIKE_DEATH_LEFT, glm::vec2(-0.2f, 0.8f));
sprite->setAnimationSpeed(SPIKE_DEATH_RIGHT, 8);
sprite->addKeyframe(SPIKE_DEATH_RIGHT, glm::vec2(0.0f, 0.8f));
sprite->addKeyframe(SPIKE_DEATH_RIGHT, glm::vec2(0.1f, 0.8f));
sprite->addKeyframe(SPIKE_DEATH_RIGHT, glm::vec2(0.2f, 0.8f));
sprite->setAnimationSpeed(DEATH_LEFT, 8);
sprite->addKeyframe(DEATH_LEFT, glm::vec2(-0.4f, 0.8f));
sprite->addKeyframe(DEATH_LEFT, glm::vec2(-0.5f, 0.8f));
sprite->addKeyframe(DEATH_LEFT, glm::vec2(-0.6f, 0.8f));
sprite->setAnimationSpeed(DEATH_RIGHT, 8);
sprite->addKeyframe(DEATH_RIGHT, glm::vec2(0.4f, 0.8f));
sprite->addKeyframe(DEATH_RIGHT, glm::vec2(0.5f, 0.8f));
sprite->addKeyframe(DEATH_RIGHT, glm::vec2(0.6f, 0.8f));
sprite->setAnimationSpeed(SPIKE_DOOR_DEATH_RIGHT, 8);
sprite->addKeyframe(SPIKE_DOOR_DEATH_RIGHT, glm::vec2(0.7f, 0.8f));
sprite->addKeyframe(SPIKE_DOOR_DEATH_RIGHT, glm::vec2(0.8f, 0.8f));
sprite->addKeyframe(SPIKE_DOOR_DEATH_RIGHT, glm::vec2(0.9f, 0.8f));
sprite->setAnimationSpeed(SPIKE_DOOR_DEATH_LEFT, 8);
sprite->addKeyframe(SPIKE_DOOR_DEATH_LEFT, glm::vec2(-0.7f, 0.8f));
sprite->addKeyframe(SPIKE_DOOR_DEATH_LEFT, glm::vec2(-0.8f, 0.8f));
sprite->addKeyframe(SPIKE_DOOR_DEATH_LEFT, glm::vec2(-0.9f, 0.8f));
sprite->setAnimationSpeed(START_MOVING_RIGHT, 8);
sprite->addKeyframe(START_MOVING_RIGHT, glm::vec2(0.1f, 0.1f));
sprite->addKeyframe(START_MOVING_RIGHT, glm::vec2(0.2f, 0.1f));
sprite->addKeyframe(START_MOVING_RIGHT, glm::vec2(0.3f, 0.1f));
sprite->addKeyframe(START_MOVING_RIGHT, glm::vec2(0.4f, 0.1f));
sprite->setAnimationSpeed(MOVE_LEFT, 8);
sprite->addKeyframe(MOVE_LEFT, glm::vec2(-0.5f, 0.1f));
sprite->addKeyframe(MOVE_LEFT, glm::vec2(-0.6f, 0.1f));
sprite->addKeyframe(MOVE_LEFT, glm::vec2(-0.7f, 0.1f));
sprite->addKeyframe(MOVE_LEFT, glm::vec2(-0.8f, 0.1f));
sprite->addKeyframe(MOVE_LEFT, glm::vec2(-0.9f, 0.1f));
sprite->setAnimationSpeed(MOVE_RIGHT, 8);
sprite->addKeyframe(MOVE_RIGHT, glm::vec2(0.5f, 0.1f));
sprite->addKeyframe(MOVE_RIGHT, glm::vec2(0.6f, 0.1f));
sprite->addKeyframe(MOVE_RIGHT, glm::vec2(0.7f, 0.1f));
sprite->addKeyframe(MOVE_RIGHT, glm::vec2(0.8f, 0.1f));
sprite->addKeyframe(MOVE_RIGHT, glm::vec2(0.9f, 0.1f));
sprite->setAnimationSpeed(JUMP_RIGHT, 8);
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.1f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.2f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.3f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.4f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.5f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.6f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.7f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.8f, 0.2f));
sprite->addKeyframe(JUMP_RIGHT, glm::vec2(0.9f, 0.2f));
sprite->setAnimationSpeed(JUMP_LEFT, 8);
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.1f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.2f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.3f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.4f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.5f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.6f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.7f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.8f, 0.2f));
sprite->addKeyframe(JUMP_LEFT, glm::vec2(-0.9f, 0.2f));
sprite->setAnimationSpeed(JUMP_RUN_RIGHT, 8);
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.0f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.1f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.2f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.3f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.4f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.5f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.6f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.7f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.8f, 0.3f));
sprite->addKeyframe(JUMP_RUN_RIGHT, glm::vec2(0.9f, 0.3f));
sprite->setAnimationSpeed(JUMP_RUN_LEFT, 8);
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.1f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.2f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.3f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.4f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.5f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.6f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.7f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.8f, 0.3f));
sprite->addKeyframe(JUMP_RUN_LEFT, glm::vec2(-0.9f, 0.3f));
sprite->setAnimationSpeed(JUMP_STAND_RIGHT, 10);
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.1f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.2f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.3f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.4f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.5f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.6f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.7f, 0.5f));
sprite->addKeyframe(JUMP_STAND_RIGHT, glm::vec2(0.8f, 0.5f));
sprite->setAnimationSpeed(JUMP_STAND_LEFT, 10);
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.1f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.2f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.3f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.4f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.5f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.6f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.7f, 0.5f));
sprite->addKeyframe(JUMP_STAND_LEFT, glm::vec2(-0.8f, 0.5f));
sprite->setAnimationSpeed(CHANGE_DIRECTION_LEFT, 8);
sprite->addKeyframe(CHANGE_DIRECTION_LEFT, glm::vec2(0.4f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_LEFT, glm::vec2(0.5f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_LEFT, glm::vec2(0.6f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_LEFT, glm::vec2(0.7f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_LEFT, glm::vec2(0.8f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_LEFT, glm::vec2(0.9f, 0.4f));
sprite->setAnimationSpeed(CHANGE_DIRECTION_RIGHT, 8);
sprite->addKeyframe(CHANGE_DIRECTION_RIGHT, glm::vec2(-0.4f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_RIGHT, glm::vec2(-0.5f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_RIGHT, glm::vec2(-0.6f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_RIGHT, glm::vec2(-0.7f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_RIGHT, glm::vec2(-0.8f, 0.4f));
sprite->addKeyframe(CHANGE_DIRECTION_RIGHT, glm::vec2(-0.9f, 0.4f));
sprite->setAnimationSpeed(CLIMB_RIGHT, 8);
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.1f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.2f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.3f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.4f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.5f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.6f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.7f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.8f, 0.6f));
sprite->addKeyframe(CLIMB_RIGHT, glm::vec2(0.9f, 0.6f));
sprite->setAnimationSpeed(CLIMB_LEFT, 8);
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.1f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.2f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.3f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.4f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.5f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.6f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.7f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.8f, 0.6f));
sprite->addKeyframe(CLIMB_LEFT, glm::vec2(-0.9f, 0.6f));
sprite->setAnimationSpeed(ATTACK_RIGHT, 8);
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.1f, 0.7f));
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.2f, 0.7f));
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.3f, 0.7f));
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.4f, 0.7f));
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.5f, 0.7f));
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.6f, 0.7f));
sprite->addKeyframe(ATTACK_RIGHT, glm::vec2(0.7f, 0.7f));
sprite->setAnimationSpeed(ATTACK_LEFT, 8);
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.1f, 0.7f));
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.2f, 0.7f));
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.3f, 0.7f));
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.4f, 0.7f));
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.5f, 0.7f));
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.6f, 0.7f));
sprite->addKeyframe(ATTACK_LEFT, glm::vec2(-0.7f, 0.7f));
sprite->setAnimationSpeed(MOVE_SLOW_LEFT, 8);
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.1f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.2f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.3f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.4f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.5f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.6f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_LEFT, glm::vec2(-0.7f, 0.9f));
sprite->setAnimationSpeed(MOVE_SLOW_RIGHT, 8);
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.0f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.1f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.2f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.3f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.4f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.5f, 0.9f));
sprite->addKeyframe(MOVE_SLOW_RIGHT, glm::vec2(0.6f, 0.9f));
sprite->changeAnimation(0);
tileMapDispl = tileMapPos;
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y)));
}
void Player::update(int deltaTime)
{
bool b = false;
bool fireballAcabada = spriteFireball->update(deltaTime);
if (fireballAcabada) {
if (hasFireball && fireballDirection == "RIGHT")
spriteFireball->changeAnimation(MOVING_RIGHT);
else if (hasFireball && fireballDirection == "LEFT")
spriteFireball->changeAnimation(MOVING_LEFT);
else
spriteFireball->changeAnimation(NOTHING);
}
bool acabada = sprite->update(deltaTime);
if (acabada) {
switch (sprite->animation())
{
case STAND_LEFT:
direccion = "LEFT";
if (Game::instance().getSpecialKey(GLUT_KEY_LEFT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_LEFT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(START_MOVING_LEFT);
else if (Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_STAND_LEFT);
else if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(STAND_RIGHT);
else if (Game::instance().getSpecialKey(112)) sprite->changeAnimation(ATTACK_LEFT); // 112 shift
else if (Game::instance().getKey(9)) sprite->changeAnimation(MOVE_SLOW_LEFT);
else if (Game::instance().getKey(32)) {
hasFireball = true;
posFireball.x = posPlayer.x - 32.0f;
posFireball.y = posPlayer.y + 10.0f;
fireballDirection = "LEFT";
scene->playMusic("music/fireball.ogg");
}
else sprite->changeAnimation(STAND_LEFT);
scene->stopSound();
break;
case STAND_RIGHT:
direccion = "RIGHT";
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(START_MOVING_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_STAND_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(STAND_LEFT);
else if (Game::instance().getSpecialKey(112)) sprite->changeAnimation(ATTACK_RIGHT); // 112 shift
else if (Game::instance().getKey(9)) sprite->changeAnimation(MOVE_SLOW_RIGHT);
else if (Game::instance().getKey(32)) {
hasFireball = true;
posFireball.x = posPlayer.x + 32.0f;
posFireball.y = posPlayer.y + 10.f;
fireballDirection = "RIGHT";
scene->playMusic("music/fireball.ogg");
}
else sprite->changeAnimation(STAND_RIGHT);
scene->stopSound();
break;
case MOVE_SLOW_LEFT:
posPlayer.x -= 8.0f;
sprite->changeAnimation(STAND_LEFT);
break;
case MOVE_SLOW_RIGHT:
posPlayer.x += 8.0f;
sprite->changeAnimation(STAND_RIGHT);
break;
case START_MOVING_RIGHT:
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RUN_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(START_MOVING_RIGHT);
else sprite->changeAnimation(MOVE_RIGHT);
scene->playSound("music/walking.ogg");
break;
case START_MOVING_LEFT:
if (Game::instance().getSpecialKey(GLUT_KEY_LEFT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RUN_LEFT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(START_MOVING_LEFT);
else sprite->changeAnimation(MOVE_LEFT);
scene->playSound("music/walking.ogg");
break;
case MOVE_LEFT:
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(CHANGE_DIRECTION_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RUN_LEFT);
else sprite->changeAnimation(STAND_LEFT);
scene->playSound("music/walking.ogg");
break;
case MOVE_RIGHT:
if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(CHANGE_DIRECTION_LEFT);
else if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RUN_RIGHT);
else sprite->changeAnimation(STAND_RIGHT);
scene->playSound("music/walking.ogg");
break;
case JUMP_RIGHT:
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(MOVE_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(STAND_LEFT);
else sprite->changeAnimation(STAND_RIGHT);
break;
case JUMP_LEFT:
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(STAND_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(MOVE_LEFT);
else sprite->changeAnimation(STAND_LEFT);
break;
case JUMP_RUN_RIGHT:
if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(CHANGE_DIRECTION_LEFT);
else sprite->changeAnimation(MOVE_RIGHT);
break;
case JUMP_RUN_LEFT:
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(CHANGE_DIRECTION_RIGHT);
else sprite->changeAnimation(MOVE_LEFT);
break;
case JUMP_STAND_RIGHT:
//mirar el caso en el que se puede subir ---> CLIMB_RIGHT
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(START_MOVING_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(STAND_LEFT);
else sprite->changeAnimation(STAND_RIGHT);
break;
case JUMP_STAND_LEFT:
//mirar el caso en el que se puede subir ---> CLIMB_LEFT
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT)) sprite->changeAnimation(STAND_RIGHT);
else if (Game::instance().getSpecialKey(GLUT_KEY_LEFT)) sprite->changeAnimation(START_MOVING_LEFT);
else sprite->changeAnimation(STAND_LEFT);
break;
case CHANGE_DIRECTION_LEFT:
if (Game::instance().getSpecialKey(GLUT_KEY_LEFT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RUN_LEFT);
else sprite->changeAnimation(MOVE_LEFT);
break;
case CHANGE_DIRECTION_RIGHT:
if (Game::instance().getSpecialKey(GLUT_KEY_RIGHT) && Game::instance().getSpecialKey(GLUT_KEY_UP)) sprite->changeAnimation(JUMP_RUN_RIGHT);
else sprite->changeAnimation(MOVE_RIGHT);
break;
case CLIMB_RIGHT:
sprite->changeAnimation(STAND_RIGHT);
posPlayer.x += 2.0f;
// faltaria mover al personaje al lugar adecuado
break;
case CLIMB_LEFT:
sprite->changeAnimation(STAND_LEFT);
posPlayer.x -= 2.0f;
// faltaria mover al personaje al lugar adecuado
break;
case ATTACK_RIGHT:
sprite->changeAnimation(STAND_RIGHT);
break;
case ATTACK_LEFT:
sprite->changeAnimation(STAND_LEFT);
break;
case SPIKE_DEATH_RIGHT:
//restart level
break;
case SPIKE_DEATH_LEFT:
//restart leve:
break;
case SPIKE_DOOR_DEATH_RIGHT:
//restart level
break;
case DEATH_RIGHT:
//restart level
break;
case DEATH_LEFT:
//restart level
break;
}
}
/*
if (sprite->animation() == JUMP_LEFT || sprite->animation() == START_MOVING_LEFT || sprite->animation() == MOVE_LEFT || sprite->animation() == JUMP_RUN_LEFT ||
sprite->animation() == CHANGE_DIRECTION_RIGHT) {
if (!map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))) posPlayer.x -= 1;
else sprite->changeAnimation(STAND_LEFT);
}
else if (sprite->animation() == JUMP_RIGHT || sprite->animation() == START_MOVING_RIGHT || sprite->animation() == JUMP_RUN_RIGHT || sprite->animation() == MOVE_RIGHT ||
sprite->animation() == CHANGE_DIRECTION_LEFT) {
if (!map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))) posPlayer.x += 1;
else sprite->changeAnimation(STAND_RIGHT);
}
*/
if (sprite->animation() == CLIMB_LEFT && (sprite->getCurrentKeyFrame() == 5 || sprite->getCurrentKeyFrame() == 6
|| sprite->getCurrentKeyFrame() == 8 || sprite->getCurrentKeyFrame() == 8)) posPlayer.x -= 1.0f;
else if (sprite->animation() == CLIMB_RIGHT && (sprite->getCurrentKeyFrame() == 5 || sprite->getCurrentKeyFrame() == 6
|| sprite->getCurrentKeyFrame() == 8 || sprite->getCurrentKeyFrame() == 8)) posPlayer.x += 1.0f;
if (sprite->animation() == JUMP_LEFT && !map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))){
bJumping = false;
posPlayer.x -= 1;
}
else if (sprite->animation() == START_MOVING_LEFT && !map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))) posPlayer.x -= 1;
else if (sprite->animation() == MOVE_LEFT && !map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))) posPlayer.x -= 1;
//else if (sprite->animation() == MOVE_SLOW_LEFT && !map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))) posPlayer.x -= 0.5f;
else if (sprite->animation() == JUMP_RUN_LEFT && !map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))) posPlayer.x -= 1;
else if (sprite->animation() == CHANGE_DIRECTION_RIGHT && !map->collisionMoveLeft(posPlayer, glm::ivec2(32, 64))) posPlayer.x += 0.5;
else if (sprite->animation() == JUMP_LEFT || sprite->animation() == START_MOVING_LEFT || sprite->animation() == MOVE_LEFT || sprite->animation() == JUMP_RUN_LEFT ||
sprite->animation() == CHANGE_DIRECTION_RIGHT) {
sprite->changeAnimation(STAND_LEFT);
posPlayer.x += 2; // sin esta linea detecta colision siempre y no te puedes mover
scene->playSound("music/collision.ogg");
}
else if (sprite->animation() == JUMP_RIGHT && !map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))){
bJumping = false;
posPlayer.x += 1;
}
else if (sprite->animation() == START_MOVING_RIGHT && !map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))) posPlayer.x += 1;
else if (sprite->animation() == JUMP_RUN_RIGHT && !map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))) posPlayer.x += 1;
else if (sprite->animation() == MOVE_RIGHT && !map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))) posPlayer.x += 1;
//else if (sprite->animation() == MOVE_SLOW_RIGHT && !map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))) posPlayer.x += 0.6f;
else if (sprite->animation() == CHANGE_DIRECTION_LEFT && !map->collisionMoveRight(posPlayer, glm::ivec2(32, 64))) posPlayer.x -= 0.5;
else if (sprite->animation() == JUMP_RIGHT || sprite->animation() == START_MOVING_RIGHT || sprite->animation() == JUMP_RUN_RIGHT || sprite->animation() == MOVE_RIGHT ||
sprite->animation() == CHANGE_DIRECTION_LEFT) {
sprite->changeAnimation(STAND_RIGHT);
posPlayer.x -= 2; // igual que en el caso anterior
scene->playSound("music/collision.ogg");
}
if ((sprite->animation() == JUMP_STAND_LEFT || sprite->animation() == JUMP_STAND_RIGHT)
&& map->canClimb(posPlayer, glm::ivec2(32, 63), direccion)) {
if (direccion =="LEFT") sprite->changeAnimation(CLIMB_LEFT);
else if (direccion == "RIGHT") sprite->changeAnimation(CLIMB_RIGHT);
//jumpAngle -= JUMP_ANGLE_STEP / 2;
b = true;
}
/*FIREBALL collisions*/
if (spriteFireball->animation() == MOVING_RIGHT && map->collisionMoveRight(posFireball, glm::ivec2(50, 64))) {
hasFireball = false;
fireballDirection = "";
}
else if (spriteFireball->animation() == MOVING_LEFT && map->collisionMoveLeft(posFireball, glm::ivec2(50, 64))) {
hasFireball = false;
fireballDirection = "";
}
if(bJumping && !map->collisionMoveUp(posPlayer,glm::ivec2(32,63)))
{
jumpAngle += JUMP_ANGLE_STEP;
if(jumpAngle == 180)
{
bJumping = false;
posPlayer.y = startY;
}
else
{
if (!b) posPlayer.y = int(startY - JUMP_HEIGHT * sin(3.14159f * jumpAngle / 180.f));
else posPlayer.y = int(startY - JUMP_HEIGHT * sin(3.14159f * jumpAngle / 360.f));
if(jumpAngle > 90)
bJumping = !map->collisionMoveDown(posPlayer, glm::ivec2(32, 64), &posPlayer.y);
}
}
else
{
bJumping = false;
if (sprite->animation() != JUMP_RUN_LEFT
&& sprite->animation() != JUMP_RUN_RIGHT
&& sprite->animation() != JUMP_LEFT
&& sprite->animation() != JUMP_RIGHT
&& sprite->animation() != JUMP_STAND_RIGHT
&& sprite->animation() != JUMP_STAND_LEFT) posPlayer.y += FALL_STEP;
if (map->collisionMoveDown(posPlayer, glm::ivec2(32, 64), &posPlayer.y)) //A partir d'aquests numeros es defineix el padding de la tile a terra
{
if (Game::instance().getSpecialKey(GLUT_KEY_UP)
&& (sprite->animation() == STAND_RIGHT || sprite->animation() == STAND_LEFT))
{
bJumping = true;
jumpAngle = 0;
startY = posPlayer.y;
}
}
}
if (lives == 2) spriteLive->changeSpitesheet(&spritesheet2Live);
else if (lives == 1) spriteLive->changeSpitesheet(&spritesheet1Live);
else if (lives <= 0) {
spriteLive->changeSpitesheet(&spritesheetGameOver);
if (Game::instance().getSpecialKey(GLUT_KEY_F5)) {
if (scene->getCurrentLevel() == 2) scene->changeToLevel02();
else if (scene->getCurrentLevel() == 1) scene->changeToLevel01();
}
}
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y)));
if (hasFireball) {
if (fireballDirection == "LEFT") posFireball.x -= 1.0f;
else posFireball.x += 1.0f;
spriteFireball->setPosition(glm::vec2(float(tileMapDispl.x + posFireball.x), float(tileMapDispl.y + posFireball.y)));
}
//28 i 29 tiles puerta
if (map->collisionWithFinalDoor(posPlayer, glm::ivec2(32, 64))) {
scene->nextLevel2 = true;
scene->playMusic("music/intro_theme.ogg"); // change for win sound
}
}
void Player::render()
{
sprite->render();
}
void Player::renderLive(){
spriteLive->render();
}
void Player::renderFireball() {
spriteFireball->render();
}
void Player::setTileMap(TileMap *tileMap)
{
map = tileMap;
}
void Player::setPosition(const glm::vec2 &pos)
{
posPlayer = pos;
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y)));
spriteFireball->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y)));
}
void Player::isDead(bool isDead) {
if (isDead) {
sprite->changeAnimation(SPIKE_DEATH_RIGHT);
//sprite->changeAnimation(SPIKE_DOOR_DEATH_RIGHT);
}
}
void Player::isDeadByDoor(bool isDead) {
if (isDead) {
//sprite->changeAnimation(SPIKE_DEATH_RIGHT);
sprite->changeAnimation(SPIKE_DOOR_DEATH_RIGHT);
}
}
void Player::setLives(){
lives = lives -1;
}
int Player::getLives(){
return lives;
}
void Player::setLivePosition(const glm::vec2 &pos){
spriteLive->setPosition(glm::vec2(float(pos.x), float(pos.y)));
}
| 43.939535 | 169 | 0.725168 | [
"render"
] |
ae5a695bf9efdb304c686a8f89a159b3571f3cd2 | 3,641 | cpp | C++ | code/1095_Cars on Campus.cpp | BitterPotato/PATInC | c4bd2e0cbd98b82b5393f3b95a3c7f68b40cab49 | [
"MIT"
] | null | null | null | code/1095_Cars on Campus.cpp | BitterPotato/PATInC | c4bd2e0cbd98b82b5393f3b95a3c7f68b40cab49 | [
"MIT"
] | 1 | 2017-03-06T07:58:32.000Z | 2017-03-06T08:00:54.000Z | code/1095_Cars on Campus.cpp | BitterPotato/PATInC | c4bd2e0cbd98b82b5393f3b95a3c7f68b40cab49 | [
"MIT"
] | null | null | null | //--1095--
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <math.h>
#include <vector>
#include <map>
#include <algorithm>
#define debug 0
using namespace std;
struct Record {
char plate[6];
int date;
int status;
};
bool cmp1(Record a, Record b) {
if(strcmp(a.plate, b.plate) == 0) {
return a.date < b.date;
}
return strcmp(a.plate, b.plate) < 0;
}
bool cmp2(Record a, Record b) {
return a.date < b.date;
}
int main() {
int recordSize, queriesSize;
scanf("%d%d", &recordSize, &queriesSize);
//todo
vector<Record> recordList(recordSize);
vector<Record> validList;
int queries[queriesSize+1];
// store plate - total time
map<string, int> resMap;
char status[3];
int h, m, s;
int dateSec, statusInt;
for(int i=0; i<recordSize; i++) {
scanf("%s %d:%d:%d %s", &recordList[i].plate, &h, &m, &s, &status);
dateSec = 3600*h + 60*m + s;
// status to int, 1 or -1
if(strcmp(status, "in") == 0) {
statusInt = 1;
}
else {
statusInt = -1;
}
recordList[i].date = dateSec;
recordList[i].status = statusInt;
}
sort(recordList.begin(), recordList.end(), cmp1);
if(debug == 1) {
for(int i=0; i<recordSize; i++) {
printf("%s %d %d\n", recordList[i].plate, recordList[i].date, recordList[i].status);
}
}
for(int i=1; i<=queriesSize; i++) {
scanf("%d:%d:%d", &h, &m, &s);
dateSec = dateSec = 3600*h + 60*m + s;;
queries[i] = dateSec;
if(debug == 1)
printf("%d\n", dateSec);
}
int maxTime = -1;
for(int i=0; i<recordList.size()-1; i++) {
if(strcmp(recordList[i].plate, recordList[i+1].plate) == 0
&& recordList[i].status == 1
&& recordList[i+1].status == -1) {
resMap[recordList[i].plate] += recordList[i+1].date - recordList[i].date;
validList.push_back(recordList[i]);
validList.push_back(recordList[i+1]);
if(resMap[recordList[i].plate] > maxTime) {
maxTime = resMap[recordList[i].plate];
}
}
}
if(debug == 1) {
printf("%d\n", maxTime);
for(int i=0; i<validList.size(); i++) {
printf("%s %d %d\n", validList[i].plate, validList[i].date, validList[i].status);
}
}
sort(validList.begin(), validList.end(), cmp2);
if(debug == 1) {
for(int i=0; i<validList.size(); i++) {
printf("%s %d %d\n", validList[i].plate, validList[i].date, validList[i].status);
}
}
int tempCarNum = 0;
if(queriesSize > 0) {
int index = 1;
int queryClip = queries[index];
for(int i=0; i<validList.size(); ) {
// printf("%d %d %d\n", validList[i].date, queryClip, tempCarNum);
if(validList[i].date <= queryClip) {
tempCarNum += validList[i].status;
i++;
}
else {
printf("%d\n", tempCarNum);
if(++index <= queriesSize) {
queryClip = queries[index];
}
else {
break;
}
}
}
}
map<string, int>::iterator it=resMap.begin();
for(; it != resMap.end(); it++) {
// printf("%s %d\n", it->first.c_str(), it->second);
if(it->second == maxTime)
printf("%s ", it->first.c_str());
}
printf("%02d:%02d:%02d", maxTime/3600, (maxTime/60)%60, maxTime%60);
return 0;
} | 25.640845 | 96 | 0.500412 | [
"vector"
] |
ae5ed15a71285bb7e7f6cc3c12ff13dbddce8731 | 646 | cpp | C++ | CodeForces/Complete/200-299/246C-BeautyPageant.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/200-299/246C-BeautyPageant.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/200-299/246C-BeautyPageant.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <vector>
int main(){
long n, k; scanf("%ld %ld\n", &n, &k);
std::vector<long> beauty(n);
for(int p = 0; p < n; p++){scanf("%ld", &beauty[p]);}
long remaining = k;
for(int p = 0; p < n; p++){
if(remaining <= 0){break;}
printf("1 %ld\n", beauty[p]);
--remaining;
}
for(int first = 0; first < n; first++){
if(remaining <= 0){break;}
for(int second = first + 1; second < n; second++){
if(remaining <= 0){break;}
printf("2 %ld %ld\n", beauty[first], beauty[second]);
--remaining;
}
}
return 0;
}
| 20.83871 | 65 | 0.46904 | [
"vector"
] |
ae64b6a8e807851824e17a1689ebd4f70666b990 | 7,929 | cpp | C++ | Examples/Plugins/org.mitk.example.gui.imaging/src/internal/surfaceutilities/mitkSurfaceModifier.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | 5 | 2015-05-27T06:57:53.000Z | 2020-03-12T21:08:23.000Z | Examples/Plugins/org.mitk.example.gui.imaging/src/internal/surfaceutilities/mitkSurfaceModifier.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Examples/Plugins/org.mitk.example.gui.imaging/src/internal/surfaceutilities/mitkSurfaceModifier.cpp | danielknorr/MITK | b1b9780b2a6671d8118313c5ef71e9aa128362be | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
//mitk headers
#include "mitkSurfaceModifier.h"
#include "mitkSurfaceToPointSetFilter.h"
//vtk headers
#include <vtkSmartPointer.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkMath.h>
mitk::SurfaceModifier::SurfaceModifier()
{
m_myRandomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
}
mitk::SurfaceModifier::~SurfaceModifier()
{
}
mitk::Point3D mitk::SurfaceModifier::PerturbePointAlongAxis(mitk::Point3D point, mitk::Vector3D axis, double variance)
{
if (m_myRandomGenerator.IsNull()) m_myRandomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
mitk::Point3D returnValue;
//normalize axis
mitk::Vector3D normalizedAxis = axis;
normalizedAxis.Normalize();
//create noise
double noise = m_myRandomGenerator->GetNormalVariate(0.0, variance);
//std::cout <<point<<std::endl;
//add noise to point along axis
returnValue[0] = point[0] + axis[0] * noise;
returnValue[1] = point[1] + axis[1] * noise;
returnValue[2] = point[2] + axis[2] * noise;
//std::cout<<returnValue;
return returnValue;
}
mitk::Point3D mitk::SurfaceModifier::PerturbePoint(mitk::Point3D point, double varianceX, double varianceY, double varianceZ, double maxNoiseVectorLenght)
{
if (m_myRandomGenerator.IsNull()) m_myRandomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
mitk::Point3D returnValue;
returnValue[0] = point[0] + m_myRandomGenerator->GetNormalVariate(0.0, varianceX);
returnValue[1] = point[1] + m_myRandomGenerator->GetNormalVariate(0.0, varianceY);
returnValue[2] = point[2] + m_myRandomGenerator->GetNormalVariate(0.0, varianceZ);
return returnValue;
}
bool mitk::SurfaceModifier::TransformSurface(mitk::Surface::Pointer surface, itk::Matrix<double,3,3> TransformationR, itk::Vector<double,3> TransformationT)
{
//apply transformation
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->ShallowCopy(surface->GetVtkPolyData()->GetPoints());
for(unsigned int i = 0; i < points->GetNumberOfPoints(); i++)
{
double p[3];
points->GetPoint(i, p);
mitk::Point3D point;
point[0] = p[0];
point[1] = p[1];
point[2] = p[2];
point = TransformPoint(point,TransformationR,TransformationT);
p[0] = point[0];
p[1] = point[1];
p[2] = point[2];
points->SetPoint(i, p);
}
surface->GetVtkPolyData()->SetPoints(points);
return true;
}
bool mitk::SurfaceModifier::TransformSurfaceCoGCoordinates(mitk::Surface::Pointer surface, itk::Matrix<double,3,3> TransformationR, itk::Vector<double,3> TransformationT, itk::Matrix<double,3,3> &OverallTransformationR, itk::Vector<double,3> &OverallTransformationT)
{
//initialize return values
OverallTransformationR.SetIdentity();
OverallTransformationT.Fill(0);
//move surface to center of gravity and store transformation
itk::Matrix<double,3,3> TransformRToCenter;
itk::Vector<double,3> TransformTToCenter;
MoveSurfaceToCenter(surface,TransformRToCenter,TransformTToCenter);
OverallTransformationR = TransformRToCenter;
OverallTransformationT = TransformTToCenter;
//apply transformation
TransformSurface(surface,TransformationR,TransformationT);
OverallTransformationR = TransformationR * OverallTransformationR;
OverallTransformationT = (TransformationR * OverallTransformationT) + TransformationT;
//move surface back to original position (build inverse transformation andy apply it)
TransformRToCenter = TransformRToCenter.GetInverse();
TransformTToCenter = (TransformRToCenter * TransformTToCenter) * -1.;
TransformSurface(surface,TransformRToCenter,TransformTToCenter);
OverallTransformationR = TransformRToCenter * OverallTransformationR;
OverallTransformationT = (TransformRToCenter * OverallTransformationT) + TransformTToCenter;
return true;
}
mitk::Point3D mitk::SurfaceModifier::TransformPoint(mitk::Point3D point, itk::Matrix<double,3,3> TransformationR, itk::Vector<double,3> TransformationT)
{
mitk::Point3D returnValue = TransformationR * point + TransformationT;
return returnValue;
}
bool mitk::SurfaceModifier::AddOutlierToSurface(mitk::Surface::Pointer surface, double varianceX, double varianceY, double varianceZ, double outlierChance)
{
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->ShallowCopy(surface->GetVtkPolyData()->GetPoints());
for(unsigned int i = 0; i < points->GetNumberOfPoints(); i++)
{
double p[3];
points->GetPoint(i, p);
mitk::Point3D point;
point[0] = p[0];
point[1] = p[1];
point[2] = p[2];
if((outlierChance-vtkMath::Random(0,1))>0) point = PerturbePoint(point,varianceX,varianceY,varianceZ);
p[0] = point[0];
p[1] = point[1];
p[2] = point[2];
points->SetPoint(i, p);
}
surface->GetVtkPolyData()->SetPoints(points);
return true;
}
bool mitk::SurfaceModifier::PerturbeSurface(mitk::Surface::Pointer surface, double varianceX, double varianceY, double varianceZ, double maxNoiseVectorLenght)
{
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->ShallowCopy(surface->GetVtkPolyData()->GetPoints());
for(unsigned int i = 0; i < points->GetNumberOfPoints(); i++)
{
double p[3];
points->GetPoint(i, p);
mitk::Point3D point;
point[0] = p[0];
point[1] = p[1];
point[2] = p[2];
point = PerturbePoint(point,varianceX,varianceY,varianceZ,maxNoiseVectorLenght);
p[0] = point[0];
p[1] = point[1];
p[2] = point[2];
points->SetPoint(i, p);
}
surface->GetVtkPolyData()->SetPoints(points);
return true;
}
bool mitk::SurfaceModifier::MoveSurfaceToCenter(mitk::Surface::Pointer surface)
{
itk::Matrix<double,3,3> dummyR;
itk::Vector<double,3> dummyT;
return MoveSurfaceToCenter(surface,dummyR,dummyT);
}
bool mitk::SurfaceModifier::MoveSurfaceToCenter(mitk::Surface::Pointer surface, itk::Matrix<double,3,3> &TransformR, itk::Vector<double,3> &TransformT)
{
//get center of cravity
mitk::Point3D CoG = GetCenterOfGravity(surface);
//initialize transforms
TransformR.SetIdentity();
TransformT.Fill(0);
TransformT[0] = -CoG[0];
TransformT[1] = -CoG[1];
TransformT[2] = -CoG[2];
//apply transform
return TransformSurface(surface,TransformR,TransformT);
}
mitk::Point3D mitk::SurfaceModifier::GetCenterOfGravity(mitk::Surface::Pointer surface)
{
//convert surface to point set
mitk::SurfaceToPointSetFilter::Pointer myConverter = mitk::SurfaceToPointSetFilter::New();
myConverter->SetInput(surface);
myConverter->Update();
mitk::PointSet::Pointer pointSet = myConverter->GetOutput();
//calculate center of gravity
mitk::Point3D cog;
cog.Fill(0);
for (int i=0; i<pointSet->GetSize(); i++)
{
cog[0] += pointSet->GetPoint(i)[0];
cog[1] += pointSet->GetPoint(i)[1];
cog[2] += pointSet->GetPoint(i)[2];
}
cog[0] /= pointSet->GetSize();
cog[1] /= pointSet->GetSize();
cog[2] /= pointSet->GetSize();
return cog;
}
mitk::Surface::Pointer mitk::SurfaceModifier::DeepCopy(mitk::Surface::Pointer originalSurface)
{
mitk::Surface::Pointer clonedSurface = mitk::Surface::New();
vtkSmartPointer<vtkPolyData> clonedPolyData = vtkSmartPointer<vtkPolyData>::New();
clonedPolyData->DeepCopy(originalSurface->GetVtkPolyData());
clonedSurface->SetVtkPolyData(clonedPolyData);
return clonedSurface;
}
| 34.324675 | 267 | 0.715475 | [
"vector",
"transform"
] |
ae65fd9c1c4e4aa793f04adf4740179d380a0418 | 13,727 | cpp | C++ | apiwznm/PnlWznmSteDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | apiwznm/PnlWznmSteDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | apiwznm/PnlWznmSteDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file PnlWznmSteDetail.cpp
* API code for job PnlWznmSteDetail (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#include "PnlWznmSteDetail.h"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class PnlWznmSteDetail::VecVDo
******************************************************************************/
uint PnlWznmSteDetail::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butsaveclick") return BUTSAVECLICK;
if (s == "butseqviewclick") return BUTSEQVIEWCLICK;
return(0);
};
string PnlWznmSteDetail::VecVDo::getSref(
const uint ix
) {
if (ix == BUTSAVECLICK) return("ButSaveClick");
if (ix == BUTSEQVIEWCLICK) return("ButSeqViewClick");
return("");
};
/******************************************************************************
class PnlWznmSteDetail::ContIac
******************************************************************************/
PnlWznmSteDetail::ContIac::ContIac(
const string& TxfCmt
) :
Block()
{
this->TxfCmt = TxfCmt;
mask = {TXFCMT};
};
bool PnlWznmSteDetail::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmSteDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacWznmSteDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxfCmt", TxfCmt)) add(TXFCMT);
};
return basefound;
};
void PnlWznmSteDetail::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacWznmSteDetail";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacWznmSteDetail";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeStringAttr(wr, itemtag, "sref", "TxfCmt", TxfCmt);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmSteDetail::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (TxfCmt == comp->TxfCmt) insert(items, TXFCMT);
return(items);
};
set<uint> PnlWznmSteDetail::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TXFCMT};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmSteDetail::ContInf
******************************************************************************/
PnlWznmSteDetail::ContInf::ContInf(
const string& TxtSrf
, const string& TxtSeq
) :
Block()
{
this->TxtSrf = TxtSrf;
this->TxtSeq = TxtSeq;
mask = {TXTSRF, TXTSEQ};
};
bool PnlWznmSteDetail::ContInf::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWznmSteDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemInfWznmSteDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtSrf", TxtSrf)) add(TXTSRF);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtSeq", TxtSeq)) add(TXTSEQ);
};
return basefound;
};
set<uint> PnlWznmSteDetail::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (TxtSrf == comp->TxtSrf) insert(items, TXTSRF);
if (TxtSeq == comp->TxtSeq) insert(items, TXTSEQ);
return(items);
};
set<uint> PnlWznmSteDetail::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TXTSRF, TXTSEQ};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmSteDetail::StatApp
******************************************************************************/
PnlWznmSteDetail::StatApp::StatApp(
const uint ixWznmVExpstate
) :
Block()
{
this->ixWznmVExpstate = ixWznmVExpstate;
mask = {IXWZNMVEXPSTATE};
};
bool PnlWznmSteDetail::StatApp::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string srefIxWznmVExpstate;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWznmSteDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemAppWznmSteDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWznmVExpstate", srefIxWznmVExpstate)) {
ixWznmVExpstate = VecWznmVExpstate::getIx(srefIxWznmVExpstate);
add(IXWZNMVEXPSTATE);
};
};
return basefound;
};
set<uint> PnlWznmSteDetail::StatApp::comm(
const StatApp* comp
) {
set<uint> items;
if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE);
return(items);
};
set<uint> PnlWznmSteDetail::StatApp::diff(
const StatApp* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {IXWZNMVEXPSTATE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmSteDetail::StatShr
******************************************************************************/
PnlWznmSteDetail::StatShr::StatShr(
const bool ButSaveAvail
, const bool ButSaveActive
, const bool TxtSrfActive
, const bool TxtSeqActive
, const bool ButSeqViewAvail
, const bool ButSeqViewActive
, const bool TxfCmtActive
) :
Block()
{
this->ButSaveAvail = ButSaveAvail;
this->ButSaveActive = ButSaveActive;
this->TxtSrfActive = TxtSrfActive;
this->TxtSeqActive = TxtSeqActive;
this->ButSeqViewAvail = ButSeqViewAvail;
this->ButSeqViewActive = ButSeqViewActive;
this->TxfCmtActive = TxfCmtActive;
mask = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, TXTSEQACTIVE, BUTSEQVIEWAVAIL, BUTSEQVIEWACTIVE, TXFCMTACTIVE};
};
bool PnlWznmSteDetail::StatShr::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWznmSteDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemShrWznmSteDetail";
if (basefound) {
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSaveAvail", ButSaveAvail)) add(BUTSAVEAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSaveActive", ButSaveActive)) add(BUTSAVEACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtSrfActive", TxtSrfActive)) add(TXTSRFACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtSeqActive", TxtSeqActive)) add(TXTSEQACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSeqViewAvail", ButSeqViewAvail)) add(BUTSEQVIEWAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSeqViewActive", ButSeqViewActive)) add(BUTSEQVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxfCmtActive", TxfCmtActive)) add(TXFCMTACTIVE);
};
return basefound;
};
set<uint> PnlWznmSteDetail::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (ButSaveAvail == comp->ButSaveAvail) insert(items, BUTSAVEAVAIL);
if (ButSaveActive == comp->ButSaveActive) insert(items, BUTSAVEACTIVE);
if (TxtSrfActive == comp->TxtSrfActive) insert(items, TXTSRFACTIVE);
if (TxtSeqActive == comp->TxtSeqActive) insert(items, TXTSEQACTIVE);
if (ButSeqViewAvail == comp->ButSeqViewAvail) insert(items, BUTSEQVIEWAVAIL);
if (ButSeqViewActive == comp->ButSeqViewActive) insert(items, BUTSEQVIEWACTIVE);
if (TxfCmtActive == comp->TxfCmtActive) insert(items, TXFCMTACTIVE);
return(items);
};
set<uint> PnlWznmSteDetail::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, TXTSEQACTIVE, BUTSEQVIEWAVAIL, BUTSEQVIEWACTIVE, TXFCMTACTIVE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmSteDetail::Tag
******************************************************************************/
PnlWznmSteDetail::Tag::Tag(
const string& Cpt
, const string& CptSrf
, const string& CptSeq
, const string& CptCmt
) :
Block()
{
this->Cpt = Cpt;
this->CptSrf = CptSrf;
this->CptSeq = CptSeq;
this->CptCmt = CptCmt;
mask = {CPT, CPTSRF, CPTSEQ, CPTCMT};
};
bool PnlWznmSteDetail::Tag::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWznmSteDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "TagitemWznmSteDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptSrf", CptSrf)) add(CPTSRF);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptSeq", CptSeq)) add(CPTSEQ);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptCmt", CptCmt)) add(CPTCMT);
};
return basefound;
};
/******************************************************************************
class PnlWznmSteDetail::DpchAppData
******************************************************************************/
PnlWznmSteDetail::DpchAppData::DpchAppData(
const string& scrJref
, ContIac* contiac
, const set<uint>& mask
) :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMSTEDETAILDATA, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
};
string PnlWznmSteDetail::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmSteDetail::DpchAppData::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmSteDetailData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(CONTIAC)) contiac.writeXML(wr);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmSteDetail::DpchAppDo
******************************************************************************/
PnlWznmSteDetail::DpchAppDo::DpchAppDo(
const string& scrJref
, const uint ixVDo
, const set<uint>& mask
) :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMSTEDETAILDO, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO};
else this->mask = mask;
this->ixVDo = ixVDo;
};
string PnlWznmSteDetail::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmSteDetail::DpchAppDo::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmSteDetailDo");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmSteDetail::DpchEngData
******************************************************************************/
PnlWznmSteDetail::DpchEngData::DpchEngData() :
DpchEngWznm(VecWznmVDpch::DPCHENGWZNMSTEDETAILDATA)
{
};
string PnlWznmSteDetail::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(CONTINF)) ss.push_back("continf");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmSteDetail::DpchEngData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWznmSteDetailData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF);
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
if (continf.readXML(docctx, basexpath, true)) add(CONTINF);
if (statapp.readXML(docctx, basexpath, true)) add(STATAPP);
if (statshr.readXML(docctx, basexpath, true)) add(STATSHR);
if (tag.readXML(docctx, basexpath, true)) add(TAG);
} else {
contiac = ContIac();
continf = ContInf();
statapp = StatApp();
statshr = StatShr();
tag = Tag();
};
};
| 26.863014 | 129 | 0.638304 | [
"vector"
] |
ae6784c8378eea655cd2d96042769e441b7c9d45 | 1,241 | hh | C++ | src/pks/multiphase/WRMmp_Simple.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/pks/multiphase/WRMmp_Simple.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/pks/multiphase/WRMmp_Simple.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
This is the multiphase component of the Amanzi code.
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Authors: Quan Bui (mquanbui@math.umd.edu)
We use this class to set up simple water retention model
for decoupled multiphase flow
*/
#ifndef AMANZI_MULTIPHASE_WRM_SIMPLE_HH_
#define AMANZI_MULTIPHASE_WRM_SIMPLE_HH_
#include "Teuchos_ParameterList.hpp"
#include "Factory.hh"
#include "WRMmp.hh"
namespace Amanzi {
namespace Multiphase {
class WRMmp_Simple : public WRMmp {
public:
WRMmp_Simple(Teuchos::ParameterList& plist);
~WRMmp_Simple() {};
// required methods from the base class
virtual double k_relative(double Sw, int phase);
virtual double capillaryPressure(double saturation);
virtual double dPc_dS(double saturation);
virtual double dKdS(double Sw, int phase);
private:
void Init_(double S_rw, double S_rn, double coef);
private:
double S_rw_, S_rn_, coef_, exponent_;
static Utils::RegisteredFactory<WRMmp, WRMmp_Simple> factory_;
};
} // namespace Multiphase
} // namespace Amanzi
#endif
| 24.333333 | 65 | 0.753425 | [
"model"
] |
ae6daae0b6e76b9bd6cab178b873a5295fc3c46b | 2,151 | cpp | C++ | src/applications/demos/dairy_farm/storage_udl.cpp | yw2399/cascade | 5aa0e750851affc0583bea125fa5d6714ca07d97 | [
"BSD-3-Clause"
] | 21 | 2020-09-07T20:57:00.000Z | 2022-03-30T18:18:37.000Z | src/applications/demos/dairy_farm/storage_udl.cpp | yw2399/cascade | 5aa0e750851affc0583bea125fa5d6714ca07d97 | [
"BSD-3-Clause"
] | 17 | 2020-09-10T11:09:08.000Z | 2021-12-28T04:56:23.000Z | src/applications/demos/dairy_farm/storage_udl.cpp | yw2399/cascade | 5aa0e750851affc0583bea125fa5d6714ca07d97 | [
"BSD-3-Clause"
] | 17 | 2020-09-10T11:00:13.000Z | 2022-02-26T22:00:27.000Z | #include <cascade/user_defined_logic_interface.hpp>
#include <iostream>
#include <vector>
#include "time_probes.hpp"
namespace derecho{
namespace cascade{
#define MY_UUID "36590e58-4ca2-11ec-b26b-0242ac110002"
#define MY_DESC "The Dairy Farm DEMO: Storage UDL for evaluation"
std::string get_uuid() {
return MY_UUID;
}
std::string get_description() {
return MY_DESC;
}
class DairyFarmStorageOCDPO: public OffCriticalDataPathObserver {
virtual void operator () (const std::string&,
const uint32_t,
persistent::version_t,
const mutils::ByteRepresentable* const value_ptr,
const std::unordered_map<std::string,bool>&,
ICascadeContext* ctxt,
uint32_t) override {
// test if there is a cow in the incoming frame.
auto* typed_ctxt = dynamic_cast<DefaultCascadeContextType*>(ctxt);
#ifdef ENABLE_EVALUATION
if (std::is_base_of<IHasMessageID,ObjectWithStringKey>::value) {
global_timestamp_logger.log(TLT_STORAGE_TRIGGERED,
typed_ctxt->get_service_client_ref().get_my_id(),
reinterpret_cast<const ObjectWithStringKey*>(value_ptr)->get_message_id(),
get_walltime());
}
#endif
}
static std::shared_ptr<OffCriticalDataPathObserver> ocdpo_ptr;
public:
static void initialize() {
if(!ocdpo_ptr) {
ocdpo_ptr = std::make_shared<DairyFarmStorageOCDPO>();
}
}
static auto get() {
return ocdpo_ptr;
}
};
std::shared_ptr<OffCriticalDataPathObserver> DairyFarmStorageOCDPO::ocdpo_ptr;
void initialize(ICascadeContext*) {
DairyFarmStorageOCDPO::initialize();
}
std::shared_ptr<OffCriticalDataPathObserver> get_observer(
ICascadeContext*,const nlohmann::json&) {
return DairyFarmStorageOCDPO::get();
}
void release(ICascadeContext*) {
// nothing to release
return;
}
} // namespace cascade
} // namespace derecho
| 30.295775 | 114 | 0.625291 | [
"vector"
] |
ae760ef731965a08d6fd26ce175f1383b280f63d | 33,366 | cpp | C++ | src/qt/metadexdialog.cpp | huluha/omnicore | c806479765feb0dd7dce35414e3602200315c8c9 | [
"MIT"
] | 1 | 2021-06-16T02:32:09.000Z | 2021-06-16T02:32:09.000Z | src/qt/metadexdialog.cpp | huluha/omnicore | c806479765feb0dd7dce35414e3602200315c8c9 | [
"MIT"
] | null | null | null | src/qt/metadexdialog.cpp | huluha/omnicore | c806479765feb0dd7dce35414e3602200315c8c9 | [
"MIT"
] | null | null | null | // Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "metadexdialog.h"
#include "ui_metadexdialog.h"
#include "omnicore_qtutils.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "omnicore/createpayload.h"
#include "omnicore/errors.h"
#include "omnicore/mdex.h"
#include "omnicore/omnicore.h"
#include "omnicore/parse_string.h"
#include "omnicore/pending.h"
#include "omnicore/rules.h"
#include "omnicore/sp.h"
#include "omnicore/tally.h"
#include "omnicore/utilsbitcoin.h"
#include "omnicore/wallettxs.h"
#include "omnicore/uint256_extensions.h"
#include "amount.h"
#include "sync.h"
#include "uint256.h"
#include "wallet_ismine.h"
#include <boost/lexical_cast.hpp>
#include <stdint.h>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <QAbstractItemView>
#include <QDialog>
#include <QDateTime>
#include <QFont>
#include <QHeaderView>
#include <QMessageBox>
#include <QString>
#include <QTableWidgetItem>
#include <QWidget>
using std::ostringstream;
using std::string;
using namespace mastercore;
MetaDExDialog::MetaDExDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MetaDExDialog),
clientModel(0),
walletModel(0),
global_metadex_market(3)
{
ui->setupUi(this);
//prep lists
ui->buyList->setColumnCount(3);
ui->sellList->setColumnCount(3);
ui->buyList->verticalHeader()->setVisible(false);
#if QT_VERSION < 0x050000
ui->buyList->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#else
ui->buyList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#endif
ui->buyList->setShowGrid(false);
ui->buyList->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->buyList->setSelectionMode(QAbstractItemView::NoSelection);
ui->buyList->setFocusPolicy(Qt::NoFocus);
ui->buyList->setAlternatingRowColors(true);
ui->sellList->verticalHeader()->setVisible(false);
#if QT_VERSION < 0x050000
ui->sellList->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#else
ui->sellList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#endif
ui->sellList->setShowGrid(false);
ui->sellList->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->sellList->setSelectionMode(QAbstractItemView::NoSelection);
ui->sellList->setFocusPolicy(Qt::NoFocus);
ui->sellList->setAlternatingRowColors(true);
connect(ui->switchButton, SIGNAL(clicked()), this, SLOT(switchButtonClicked()));
connect(ui->buyButton, SIGNAL(clicked()), this, SLOT(buyTrade()));
connect(ui->sellButton, SIGNAL(clicked()), this, SLOT(sellTrade()));
connect(ui->sellAddressCombo, SIGNAL(activated(int)), this, SLOT(sellAddressComboBoxChanged(int)));
connect(ui->buyAddressCombo, SIGNAL(activated(int)), this, SLOT(buyAddressComboBoxChanged(int)));
connect(ui->sellAmountLE, SIGNAL(textEdited(const QString &)), this, SLOT(recalcSellTotal()));
connect(ui->sellPriceLE, SIGNAL(textEdited(const QString &)), this, SLOT(recalcSellTotal()));
connect(ui->buyAmountLE, SIGNAL(textEdited(const QString &)), this, SLOT(recalcBuyTotal()));
connect(ui->buyPriceLE, SIGNAL(textEdited(const QString &)), this, SLOT(recalcBuyTotal()));
connect(ui->sellList, SIGNAL(cellClicked(int,int)), this, SLOT(sellClicked(int,int)));
connect(ui->buyList, SIGNAL(cellClicked(int,int)), this, SLOT(buyClicked(int,int)));
FullRefresh();
}
MetaDExDialog::~MetaDExDialog()
{
delete ui;
}
void MetaDExDialog::setClientModel(ClientModel *model)
{
this->clientModel = model;
if (NULL != model) {
connect(model, SIGNAL(refreshOmniState()), this, SLOT(OrderRefresh()));
connect(model, SIGNAL(refreshOmniBalance()), this, SLOT(BalanceOrderRefresh()));
connect(model, SIGNAL(reinitOmniState()), this, SLOT(FullRefresh()));
}
}
void MetaDExDialog::setWalletModel(WalletModel *model)
{
// use wallet model to get visibility into BTC balance changes for fees
this->walletModel = model;
if (model != NULL) {
connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(UpdateBalances()));
}
}
void MetaDExDialog::PopulateAddresses()
{
{ // restrict scope of lock to address updates only (don't hold for balance update too)
LOCK(cs_tally);
uint32_t propertyId = global_metadex_market;
bool testeco = false;
if (propertyId >= TEST_ECO_PROPERTY_1) testeco = true;
// get currently selected addresses
QString currentSetBuyAddress = ui->buyAddressCombo->currentText();
QString currentSetSellAddress = ui->sellAddressCombo->currentText();
// clear address selectors
ui->buyAddressCombo->clear();
ui->sellAddressCombo->clear();
// populate buy and sell addresses
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
string address = (my_it->first).c_str();
unsigned int id;
(my_it->second).init();
while (0 != (id = (my_it->second).next())) {
if (id == propertyId) {
if (!getUserAvailableMPbalance(address, propertyId)) continue; // ignore this address, has no available balance to spend
if (IsMyAddress(address) == ISMINE_SPENDABLE) ui->sellAddressCombo->addItem((my_it->first).c_str()); // only include wallet addresses
}
if (id == OMNI_PROPERTY_MSC && !testeco) {
if (!getUserAvailableMPbalance(address, OMNI_PROPERTY_MSC)) continue;
if (IsMyAddress(address) == ISMINE_SPENDABLE) ui->buyAddressCombo->addItem((my_it->first).c_str());
}
if (id == OMNI_PROPERTY_TMSC && testeco) {
if (!getUserAvailableMPbalance(address, OMNI_PROPERTY_TMSC)) continue;
if (IsMyAddress(address) == ISMINE_SPENDABLE) ui->buyAddressCombo->addItem((my_it->first).c_str());
}
}
}
// attempt to set buy and sell addresses back to values before refresh - may not be possible if it's a new market
int sellIdx = ui->sellAddressCombo->findText(currentSetSellAddress);
if (sellIdx != -1) { ui->sellAddressCombo->setCurrentIndex(sellIdx); }
int buyIdx = ui->buyAddressCombo->findText(currentSetBuyAddress);
if (buyIdx != -1) { ui->buyAddressCombo->setCurrentIndex(buyIdx); }
}
// update balances
UpdateBalances();
}
void MetaDExDialog::BalanceOrderRefresh()
{
// balances have been updated, there may be a new address
PopulateAddresses();
// refresh orders
OrderRefresh();
}
void MetaDExDialog::OrderRefresh()
{
UpdateOffers();
}
// Executed when the switch market button is clicked
void MetaDExDialog::SwitchMarket()
{
// perform some checks on the input data before attempting to switch market
int64_t searchPropertyId = 0;
string searchText = ui->switchLineEdit->text().toStdString();
// check for empty field
if (searchText.empty()) {
QMessageBox::critical( this, "Unable to switch market",
"You must enter a property ID to switch the market." );
return;
}
// check that we can cast the field to numerical OK
try {
searchPropertyId = boost::lexical_cast<int64_t>(searchText);
} catch(const boost::bad_lexical_cast &e) { // error casting, searchText likely not numerical
QMessageBox::critical( this, "Unable to switch market",
"The property ID entered was not a valid number." );
return;
}
// check that the value is in range
if ((searchPropertyId < 0) || (searchPropertyId > 4294967295L)) {
QMessageBox::critical( this, "Unable to switch market",
"The property ID entered is outside the allowed range." );
return;
}
// check that not trying to trade primary for primary (eg market 1 or 2)
if ((searchPropertyId == 1) || (searchPropertyId == 2)) {
QMessageBox::critical( this, "Unable to switch market",
"You cannot trade OMNI/TOMNI against itself." );
return;
}
// check that the property exists
bool spExists = false;
{
LOCK(cs_tally);
spExists = _my_sps->hasSP(searchPropertyId);
}
if (!spExists) {
QMessageBox::critical( this, "Unable to switch market",
"The property ID entered was not found." );
return;
}
// with checks complete change the market to the entered property ID and perform a full refresh
global_metadex_market = searchPropertyId;
ui->buyAmountLE->clear();
ui->buyPriceLE->clear();
ui->sellAmountLE->clear();
ui->sellPriceLE->clear();
FullRefresh();
}
/**
* When a row on the buy side is clicked, populate the sell fields to allow easy selling into the offer accordingly
*/
void MetaDExDialog::buyClicked(int row, int col)
{
// Populate the sell price field with the price clicked
QTableWidgetItem* priceCell = ui->buyList->item(row,2);
ui->sellPriceLE->setText(priceCell->text());
// If the cheapest price is not chosen, make the assumption that user wants to sell down to that price point
if (row != 0) {
int64_t totalAmount = 0;
bool divisible = isPropertyDivisible(global_metadex_market);
for (int i = 0; i <= row; i++) {
QTableWidgetItem* amountCell = ui->buyList->item(i,1);
int64_t amount = StrToInt64(amountCell->text().toStdString(), divisible);
totalAmount += amount;
}
if (divisible) {
ui->sellAmountLE->setText(QString::fromStdString(FormatDivisibleShortMP(totalAmount)));
} else {
ui->sellAmountLE->setText(QString::fromStdString(FormatIndivisibleMP(totalAmount)));
}
} else {
QTableWidgetItem* amountCell = ui->buyList->item(row,1);
ui->sellAmountLE->setText(amountCell->text());
}
// Update the total
recalcTotal(false);
}
/**
* When a row on the sell side is clicked, populate the buy fields to allow easy buying into the offer accordingly
*/
void MetaDExDialog::sellClicked(int row, int col)
{
// Populate the buy price field with the price clicked
QTableWidgetItem* priceCell = ui->sellList->item(row,0);
ui->buyPriceLE->setText(priceCell->text());
// If the cheapest price is not chosen, make the assumption that user wants to buy all available up to that price point
if (row != 0) {
int64_t totalAmount = 0;
bool divisible = isPropertyDivisible(global_metadex_market);
for (int i = 0; i <= row; i++) {
QTableWidgetItem* amountCell = ui->sellList->item(i,1);
int64_t amount = StrToInt64(amountCell->text().toStdString(), divisible);
totalAmount += amount;
}
if (divisible) {
ui->buyAmountLE->setText(QString::fromStdString(FormatDivisibleShortMP(totalAmount)));
} else {
ui->buyAmountLE->setText(QString::fromStdString(FormatIndivisibleMP(totalAmount)));
}
} else {
QTableWidgetItem* amountCell = ui->sellList->item(row,1);
ui->buyAmountLE->setText(amountCell->text());
}
// Update the total
recalcTotal(true);
}
// This function adds a row to the buy or sell offer list
void MetaDExDialog::AddRow(bool useBuyList, bool includesMe, const string& price, const string& available, const string& total)
{
int workingRow;
if (useBuyList) {
workingRow = ui->buyList->rowCount();
ui->buyList->insertRow(workingRow);
} else {
workingRow = ui->sellList->rowCount();
ui->sellList->insertRow(workingRow);
}
QTableWidgetItem *priceCell = new QTableWidgetItem(QString::fromStdString(price));
QTableWidgetItem *availableCell = new QTableWidgetItem(QString::fromStdString(available));
QTableWidgetItem *totalCell = new QTableWidgetItem(QString::fromStdString(total));
if(includesMe) {
QFont font;
font.setBold(true);
priceCell->setFont(font);
availableCell->setFont(font);
totalCell->setFont(font);
}
if (useBuyList) {
priceCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
availableCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
totalCell->setTextAlignment(Qt::AlignRight + Qt::AlignVCenter);
ui->buyList->setItem(workingRow, 0, totalCell);
ui->buyList->setItem(workingRow, 1, availableCell);
ui->buyList->setItem(workingRow, 2, priceCell);
} else {
priceCell->setTextAlignment(Qt::AlignLeft + Qt::AlignVCenter);
availableCell->setTextAlignment(Qt::AlignLeft + Qt::AlignVCenter);
totalCell->setTextAlignment(Qt::AlignLeft + Qt::AlignVCenter);
ui->sellList->setItem(workingRow, 0, priceCell);
ui->sellList->setItem(workingRow, 1, availableCell);
ui->sellList->setItem(workingRow, 2, totalCell);
}
}
void MetaDExDialog::UpdateBalances()
{
// update the balances for the buy and sell addreses
UpdateBuyAddressBalance();
UpdateSellAddressBalance();
}
// This function loops through the MetaDEx and updates the list of buy/sell offers
void MetaDExDialog::UpdateOffers()
{
for (int useBuyList = 0; useBuyList < 2; ++useBuyList) {
if (useBuyList) { ui->buyList->setRowCount(0); } else { ui->sellList->setRowCount(0); }
bool testeco = isTestEcosystemProperty(global_metadex_market);
LOCK(cs_tally);
for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
if ((!useBuyList) && (my_it->first != global_metadex_market)) { continue; } // not the property we're looking for, don't waste any more work
if ((useBuyList) && (((!testeco) && (my_it->first != OMNI_PROPERTY_MSC)) || ((testeco) && (my_it->first != OMNI_PROPERTY_TMSC)))) continue;
md_PricesMap & prices = my_it->second;
for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // loop through the sell prices for the property
std::string unitPriceStr;
int64_t available = 0, total = 0;
bool includesMe = false;
md_Set & indexes = (it->second);
for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // multiple sell offers can exist at the same price, sum them for the UI
const CMPMetaDEx& obj = *it;
if (obj.displayUnitPrice() == "0.00000000") continue; // hide trades that have a lower than 0.00000001 MSC unit price
if(IsMyAddress(obj.getAddr())) includesMe = true;
unitPriceStr = obj.displayUnitPrice();
if (useBuyList) {
if (obj.getDesProperty()==global_metadex_market) {
available += obj.getAmountToFill();
total += obj.getAmountRemaining();
}
} else {
if ( ((testeco) && (obj.getDesProperty() == 2)) || ((!testeco) && (obj.getDesProperty() == 1)) ) {
available += obj.getAmountRemaining();
total += obj.getAmountToFill();
}
}
}
if ((available > 0) && (total > 0)) { // if there are any available at this price, add to the sell list
string strAvail;
if (isPropertyDivisible(global_metadex_market)) { strAvail = FormatDivisibleShortMP(available); } else { strAvail = FormatIndivisibleMP(available); }
AddRow(useBuyList, includesMe, StripTrailingZeros(unitPriceStr), strAvail, FormatDivisibleShortMP(total));
}
}
}
}
}
// This function updates the balance for the currently selected sell address
void MetaDExDialog::UpdateSellAddressBalance()
{
QString currentSetSellAddress = ui->sellAddressCombo->currentText();
if (currentSetSellAddress.isEmpty()) {
ui->yourSellBalanceLabel->setText(QString::fromStdString("Your balance: N/A"));
ui->sellAddressFeeWarningLabel->setVisible(false);
} else {
unsigned int propertyId = global_metadex_market;
int64_t balanceAvailable = getUserAvailableMPbalance(currentSetSellAddress.toStdString(), propertyId);
string sellBalStr;
if (isPropertyDivisible(propertyId)) { sellBalStr = FormatDivisibleMP(balanceAvailable); } else { sellBalStr = FormatIndivisibleMP(balanceAvailable); }
ui->yourSellBalanceLabel->setText(QString::fromStdString("Your balance: " + sellBalStr + " SPT"));
// warning label will be lit if insufficient fees for MetaDEx payload (28 bytes)
if (CheckFee(currentSetSellAddress.toStdString(), 28)) {
ui->sellAddressFeeWarningLabel->setVisible(false);
} else {
ui->sellAddressFeeWarningLabel->setText("WARNING: The address is low on BTC for transaction fees.");
ui->sellAddressFeeWarningLabel->setVisible(true);
}
}
}
// This function updates the balance for the currently selected buy address
void MetaDExDialog::UpdateBuyAddressBalance()
{
QString currentSetBuyAddress = ui->buyAddressCombo->currentText();
if (currentSetBuyAddress.isEmpty()) {
ui->yourBuyBalanceLabel->setText(QString::fromStdString("Your balance: N/A"));
ui->buyAddressFeeWarningLabel->setVisible(false);
} else {
unsigned int propertyId = OMNI_PROPERTY_MSC;
if (global_metadex_market >= TEST_ECO_PROPERTY_1) propertyId = OMNI_PROPERTY_TMSC;
int64_t balanceAvailable = getUserAvailableMPbalance(currentSetBuyAddress.toStdString(), propertyId);
ui->yourBuyBalanceLabel->setText(QString::fromStdString("Your balance: " + FormatDivisibleMP(balanceAvailable) + getTokenLabel(propertyId)));
// warning label will be lit if insufficient fees for MetaDEx payload (28 bytes)
if (CheckFee(currentSetBuyAddress.toStdString(), 28)) {
ui->buyAddressFeeWarningLabel->setVisible(false);
} else {
ui->buyAddressFeeWarningLabel->setText("WARNING: The address is low on BTC for transaction fees.");
ui->buyAddressFeeWarningLabel->setVisible(true);
}
}
}
// This function performs a full refresh of all elements - for example when switching markets
void MetaDExDialog::FullRefresh()
{
// populate market information
unsigned int propertyId = global_metadex_market;
string propNameStr = getPropertyName(propertyId);
bool testeco = false;
if (propertyId >= TEST_ECO_PROPERTY_1) testeco = true;
if(testeco) {
ui->marketLabel->setText(QString::fromStdString("Trade " + propNameStr + " (#" + FormatIndivisibleMP(propertyId) + ") for Test Omni"));
} else {
ui->marketLabel->setText(QString::fromStdString("Trade " + propNameStr + " (#" + FormatIndivisibleMP(propertyId) + ") for Omni"));
}
// update form labels to reflect market
std::string primaryToken;
if (testeco) { primaryToken = "TOMNI"; } else { primaryToken = "OMNI"; }
ui->exchangeLabel->setText("Exchange - SP#" + QString::fromStdString(FormatIndivisibleMP(propertyId) + "/" + primaryToken));
ui->buyTotalLabel->setText("0.00000000 " + QString::fromStdString(primaryToken));
ui->sellTotalLabel->setText("0.00000000 " + QString::fromStdString(primaryToken));
ui->sellTM->setText(QString::fromStdString(primaryToken));
ui->buyTM->setText(QString::fromStdString(primaryToken));
ui->buyList->setHorizontalHeaderItem(0, new QTableWidgetItem("Total " + QString::fromStdString(primaryToken)));
ui->buyList->setHorizontalHeaderItem(1, new QTableWidgetItem("Total SP#" + QString::fromStdString(FormatIndivisibleMP(global_metadex_market))));
ui->buyList->setHorizontalHeaderItem(2, new QTableWidgetItem("Unit Price (" + QString::fromStdString(primaryToken) + ")"));
ui->sellList->setHorizontalHeaderItem(0, new QTableWidgetItem("Unit Price (" + QString::fromStdString(primaryToken) + ")"));
ui->sellList->setHorizontalHeaderItem(1, new QTableWidgetItem("Total SP#" + QString::fromStdString(FormatIndivisibleMP(global_metadex_market))));
ui->sellList->setHorizontalHeaderItem(2, new QTableWidgetItem("Total " + QString::fromStdString(primaryToken)));
ui->buyMarketLabel->setText("BUY SP#" + QString::fromStdString(FormatIndivisibleMP(propertyId)));
ui->sellMarketLabel->setText("SELL SP#" + QString::fromStdString(FormatIndivisibleMP(propertyId)));
ui->sellButton->setText("Sell SP#" + QString::fromStdString(FormatIndivisibleMP(propertyId)));
ui->buyButton->setText("Buy SP#" + QString::fromStdString(FormatIndivisibleMP(propertyId)));
// populate buy and sell addresses
PopulateAddresses();
// update the buy and sell offers
UpdateOffers();
}
void MetaDExDialog::buyAddressComboBoxChanged(int idx)
{
UpdateBuyAddressBalance();
}
void MetaDExDialog::sellAddressComboBoxChanged(int idx)
{
UpdateSellAddressBalance();
}
void MetaDExDialog::switchButtonClicked()
{
SwitchMarket();
}
void MetaDExDialog::sellTrade()
{
sendTrade(true);
}
void MetaDExDialog::buyTrade()
{
sendTrade(false);
}
void MetaDExDialog::recalcBuyTotal()
{
recalcTotal(true);
}
void MetaDExDialog::recalcSellTotal()
{
recalcTotal(false);
}
// This function recalulates a total price display from user fields
void MetaDExDialog::recalcTotal(bool useBuyFields)
{
unsigned int propertyId = global_metadex_market;
bool divisible = isPropertyDivisible(propertyId);
bool testeco = isTestEcosystemProperty(propertyId);
int64_t price = 0, amount = 0, totalPrice = 0;
if (useBuyFields) {
amount = StrToInt64(ui->buyAmountLE->text().toStdString(),divisible);
price = StrToInt64(ui->buyPriceLE->text().toStdString(),true);
} else {
amount = StrToInt64(ui->sellAmountLE->text().toStdString(),divisible);
price = StrToInt64(ui->sellPriceLE->text().toStdString(),true);
}
if (0 >= amount || 0 >= price) {
if (useBuyFields) {
ui->buyTotalLabel->setText("N/A");
} else {
ui->sellTotalLabel->setText("N/A");
}
return;
}
uint256 amount256 = ConvertTo256(amount);
uint256 price256 = ConvertTo256(price);
uint256 totalPrice256 = amount256 * price256;
if (divisible) totalPrice256 = totalPrice256 / COIN;
if (totalPrice256 > uint256_const::max_int64) {
QMessageBox::critical( this, "Unable to calculate total",
"The total amount for the entered trade details would exceed the maximum amount of tokens." );
if (useBuyFields) {
ui->buyPriceLE->setText("");
ui->buyTotalLabel->setText("N/A");
} else {
ui->sellPriceLE->setText("");
ui->sellTotalLabel->setText("N/A");
}
return;
}
totalPrice = ConvertTo64(totalPrice256);
QString totalLabel = QString::fromStdString(FormatDivisibleMP(totalPrice));
if (testeco) {
if (useBuyFields) { ui->buyTotalLabel->setText(totalLabel + " TOMNI"); } else { ui->sellTotalLabel->setText(totalLabel + " TOMNI"); }
} else {
if (useBuyFields) { ui->buyTotalLabel->setText(totalLabel + " OMNI"); } else { ui->sellTotalLabel->setText(totalLabel + " OMNI"); }
}
}
void MetaDExDialog::sendTrade(bool sell)
{
int blockHeight = GetHeight();
uint32_t propertyId = global_metadex_market;
bool divisible = isPropertyDivisible(propertyId);
bool testeco = isTestEcosystemProperty(propertyId);
// check if main net trading is allowed
if (!IsTransactionTypeAllowed(blockHeight, propertyId, MSC_TYPE_METADEX_TRADE, MP_TX_PKT_V0)) {
QMessageBox::critical( this, "Unable to send MetaDEx transaction",
"Trading on main ecosystem properties is not yet active.\n\nPlease switch to a test ecosystem market to send trade transactions." );
return;
}
// obtain the selected sender address
string strFromAddress;
if (!sell) { strFromAddress = ui->buyAddressCombo->currentText().toStdString(); } else { strFromAddress = ui->sellAddressCombo->currentText().toStdString(); }
// warn if we have to truncate the amount due to a decimal amount for an indivisible property, but allow send to continue
string strAmount;
if (!sell) { strAmount = ui->buyAmountLE->text().toStdString(); } else { strAmount = ui->sellAmountLE->text().toStdString(); }
if (!divisible) {
size_t pos = strAmount.find(".");
if (pos!=std::string::npos) {
string tmpStrAmount = strAmount.substr(0,pos);
string strMsgText = "The amount entered contains a decimal however the property being transacted is indivisible.\n\nThe amount entered will be truncated as follows:\n";
strMsgText += "Original amount entered: " + strAmount + "\nAmount that will be used: " + tmpStrAmount + "\n\n";
strMsgText += "Do you still wish to proceed with the transaction?";
QString msgText = QString::fromStdString(strMsgText);
QMessageBox::StandardButton responseClick;
responseClick = QMessageBox::question(this, "Amount truncation warning", msgText, QMessageBox::Yes|QMessageBox::No);
if (responseClick == QMessageBox::No) {
QMessageBox::critical( this, "MetaDEx transaction cancelled",
"The MetaDEx transaction has been cancelled.\n\nPlease double-check the transction details thoroughly before retrying your transaction." );
return;
}
strAmount = tmpStrAmount;
if (!sell) { ui->buyAmountLE->setText(QString::fromStdString(strAmount)); } else { ui->sellAmountLE->setText(QString::fromStdString(strAmount)); }
}
}
// use strToInt64 function to get the amounts, using divisibility of the property
int64_t amountDes;
int64_t amountSell;
int64_t price;
unsigned int propertyIdDes;
unsigned int propertyIdSell;
if(sell) {
amountSell = StrToInt64(ui->sellAmountLE->text().toStdString(),divisible);
price = StrToInt64(ui->sellPriceLE->text().toStdString(),true);
uint256 amountSell256 = ConvertTo256(amountSell);
uint256 priceSell256 = ConvertTo256(price);
uint256 totalPrice256 = amountSell256 * priceSell256;
if (divisible) totalPrice256 = totalPrice256 / COIN;
if (totalPrice256 > uint256_const::max_int64) {
QMessageBox::critical( this, "Unable to send MetaDEx trade",
"The total amount for the entered trade details would exceed the maximum amount of tokens." );
return;
}
amountDes = ConvertTo64(totalPrice256);
if(testeco) { propertyIdDes = 2; } else { propertyIdDes = 1; }
propertyIdSell = global_metadex_market;
} else {
amountDes = StrToInt64(ui->buyAmountLE->text().toStdString(),divisible);
price = StrToInt64(ui->buyPriceLE->text().toStdString(),true);
uint256 amountDes256 = ConvertTo256(amountDes);
uint256 priceDes256 = ConvertTo256(price);
uint256 totalPrice256 = amountDes256 * priceDes256;
if (divisible) totalPrice256 = totalPrice256 / COIN;
if (totalPrice256 > uint256_const::max_int64) {
QMessageBox::critical( this, "Unable to send MetaDEx trade",
"The total amount for the entered trade details would exceed the maximum amount of tokens." );
return;
}
amountSell = ConvertTo64(totalPrice256);
if(testeco) { propertyIdSell = 2; } else { propertyIdSell = 1; }
propertyIdDes = global_metadex_market;
}
if ((0>=amountDes) || (0>=amountSell) || (0>=propertyIdDes) || (0>=propertyIdSell)) {
QMessageBox::critical( this, "Unable to send MetaDEx transaction",
"The amount entered is not valid.\n\nPlease double-check the transction details thoroughly before retrying your transaction." );
return;
}
// check if sending address has enough funds
int64_t balanceAvailable = 0;
balanceAvailable = getUserAvailableMPbalance(strFromAddress, propertyIdSell);
if (amountSell>balanceAvailable) {
QMessageBox::critical( this, "Unable to send MetaDEx transaction",
"The selected sending address does not have a sufficient balance to cover the amount entered.\n\nPlease double-check the transction details thoroughly before retrying your transaction." );
return;
}
// check if wallet is still syncing, as this will currently cause a lockup if we try to send - compare our chain to peers to see if we're up to date
// Bitcoin Core devs have removed GetNumBlocksOfPeers, switching to a time based best guess scenario
uint32_t intBlockDate = GetLatestBlockTime(); // uint32, not using time_t for portability
QDateTime currentDate = QDateTime::currentDateTime();
int secs = QDateTime::fromTime_t(intBlockDate).secsTo(currentDate);
if(secs > 90*60) {
QMessageBox::critical( this, "Unable to send MetaDEx transaction",
"The client is still synchronizing. Sending transactions can currently be performed only when the client has completed synchronizing." );
return;
}
// validation checks all look ok, let's throw up a confirmation dialog
string strMsgText = "You are about to send the following MetaDEx transaction, please check the details thoroughly:\n\n";
string spNum = static_cast<ostringstream*>( &(ostringstream() << propertyId) )->str();
string propDetails = "#" + spNum;
string buyStr;
string sellStr;
if (!sell) strMsgText += "Your buy will be inverted into a sell offer.\n\n";
strMsgText += "Type: Trade Request\nFrom: " + strFromAddress + "\n\n";
if (!sell) { // clicked buy
if (divisible) { buyStr = FormatDivisibleMP(amountDes); } else { buyStr = FormatIndivisibleMP(amountDes); }
buyStr += " SPT " + propDetails + "";
sellStr = FormatDivisibleMP(amountSell);
if (testeco) { sellStr += " TOMNI"; } else { sellStr += " OMNI"; }
strMsgText += "Buying: " + buyStr + "\nPrice: " + FormatDivisibleMP(price) + " SP" + propDetails + "/";
if (testeco) { strMsgText += "TOMNI"; } else { strMsgText += "OMNI"; }
strMsgText += "\nTotal: " + sellStr;
} else { // clicked sell
buyStr = FormatDivisibleMP(amountDes);
if (divisible) { sellStr = FormatDivisibleMP(amountSell); } else { sellStr = FormatIndivisibleMP(amountSell); }
if (testeco) { buyStr += " TOMNI"; } else { buyStr += " OMNI"; }
sellStr += " SPT " + propDetails + "";
strMsgText += "Selling: " + sellStr + "\nPrice: " + FormatDivisibleMP(price) + " SP" + propDetails + "/";
if (testeco) { strMsgText += "TOMNI"; } else { strMsgText += "OMNI"; }
strMsgText += "\nTotal: " + buyStr;
}
strMsgText += "\n\nAre you sure you wish to send this transaction?";
QString msgText = QString::fromStdString(strMsgText);
QMessageBox::StandardButton responseClick;
responseClick = QMessageBox::question(this, "Confirm MetaDEx transaction", msgText, QMessageBox::Yes|QMessageBox::No);
if (responseClick == QMessageBox::No)
{
QMessageBox::critical( this, "MetaDEx transaction cancelled",
"The transaction has been cancelled.\n\nPlease double-check the transction details thoroughly before retrying your transaction." );
return;
}
// unlock the wallet
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled/failed
QMessageBox::critical( this, "MetaDEx transaction failed",
"The transaction has been cancelled.\n\nThe wallet unlock process must be completed to send a transaction." );
return;
}
// create a payload for the transaction
std::vector<unsigned char> payload = CreatePayload_MetaDExTrade(propertyIdSell, amountSell, propertyIdDes, amountDes);
// request the wallet build the transaction (and if needed commit it)
uint256 txid = 0;
std::string rawHex;
int result = ClassAgnosticWalletTXBuilder(strFromAddress, "", "", 0, payload, txid, rawHex, autoCommit);
// check error and return the txid (or raw hex depending on autocommit)
if (result != 0) {
string strError = error_str(result);
QMessageBox::critical( this, "MetaDEx transaction failed",
"The MetaDEx transaction has failed.\n\nThe error code was: " + QString::number(result) + "\nThe error message was:\n" + QString::fromStdString(strError));
return;
} else {
if (!autoCommit) {
PopulateSimpleDialog(rawHex, "Raw Hex (auto commit is disabled)", "Raw transaction hex");
} else {
PendingAdd(txid, strFromAddress, MSC_TYPE_METADEX_TRADE, propertyIdSell, amountSell);
PopulateTXSentDialog(txid.GetHex());
}
}
}
| 44.726542 | 196 | 0.665708 | [
"vector",
"model"
] |
ae797933dc0efe0084f5bf83f46f92e14d8c3902 | 2,747 | hpp | C++ | musicasm/sheet.hpp | fleebness/musicasm | 5ad2582687fa5836e1357bd72a951ec26025f528 | [
"Apache-2.0"
] | 2 | 2016-02-22T15:59:37.000Z | 2016-02-29T00:32:21.000Z | musicasm/sheet.hpp | fleebness/musicasm | 5ad2582687fa5836e1357bd72a951ec26025f528 | [
"Apache-2.0"
] | null | null | null | musicasm/sheet.hpp | fleebness/musicasm | 5ad2582687fa5836e1357bd72a951ec26025f528 | [
"Apache-2.0"
] | null | null | null | #if !defined SHEET_HPP
#define SHEET_HPP
#include <map>
#include <memory>
#include <ratio>
#include <vector>
#include "_base_obs.hpp"
#include "_basic_value.hpp"
#include "adsr.hpp"
#include "base_note.hpp"
#include "voice.hpp"
namespace tvr
{
namespace ma
{
/// Interface for the tempo data type, allowing for different kinds of tempos.
struct _tempo
{
virtual std::intmax_t num() const = 0;
virtual std::intmax_t den() const = 0;
};
/// Provides a way to express different tempos using std::ratio.
template <typename Ratio>
struct tempo : public _tempo
{
virtual std::intmax_t num() const { return Ratio::num; }
virtual std::intmax_t den() const { return Ratio::den; }
};
/// Provides a system for handling metered rhythms in music.
class sheet
{
public:
typedef std::shared_ptr< sheet > ptr;
typedef std::vector< _dur::ptr > durations_t;
typedef std::vector< _freq::ptr > frequencies_t;
typedef std::vector< ptr > sheets_t;
typedef std::map< std::size_t, _dur::ptr > duration_map_t;
typedef std::map< std::size_t, _freq::ptr > frequency_map_t;
typedef std::map< std::size_t, voice::ptr > voice_map_t;
typedef std::map< std::size_t, adsr::ptr > adsr_map_t;
public:
/// Default constructor.
sheet():
_beat_dur(0.5),
_max(0.0)
{}
/// Constructor with a tempo.
sheet(const _tempo& tmpo)
{
(*this) << tmpo;
}
sheet& operator<<(const _tempo& tmpo)
{
// This probably looks weird.
// We expect this ratio to represent a count of beats to a quantity of time.
// So, for example, 120 beats a minute is 120 beats every 60 seconds.
// To figure out how long a beat lasts, you can't say 120/60, since that
// gives you 2 (the number of beats a second)... instead, you need 60/120,
// which gives 0.5 (how long the beat must last in seconds).
_beat_dur = static_cast<double>(tmpo.den()) / static_cast<double>(tmpo.num());
calculate_durations();
return *this;
}
/// Destructor
~sheet() {}
private:
void set_duration(duration dur)
{
// Everything we play must fit within this duration.
_max = dur;
calculate_durations();
}
void calculate_durations()
{
// If we have a _max, ensure everything we play fits within it.
// If we do not have a _max, we need to go through everything and
// calculate their durations according to _beat_dur.
}
private:
duration _beat_dur;
duration _max;
duration_map_t _tempos;
duration_map_t _durs;
frequency_map_t _pitches;
voice_map_t _voices;
adsr_map_t _envs;
};
}
}
#endif // SHEET_HPP
| 25.915094 | 83 | 0.640335 | [
"vector"
] |
ae7aebf844b02685c8ac2111f20bd5aa492ecc2e | 39,186 | cpp | C++ | DicomWebStorge/Orthanc-1.7.4/OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp | a2609194449/Assistant-decision-making-system-for-gallbladder-cancer- | 75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84 | [
"MIT"
] | 1 | 2020-11-05T08:34:23.000Z | 2020-11-05T08:34:23.000Z | DicomWebStorge/Orthanc-1.7.4/OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp | a2609194449/Assistant-decision-making-system-for-gallbladder-cancer- | 75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84 | [
"MIT"
] | null | null | null | DicomWebStorge/Orthanc-1.7.4/OrthancServer/Sources/Database/SQLiteDatabaseWrapper.cpp | a2609194449/Assistant-decision-making-system-for-gallbladder-cancer- | 75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84 | [
"MIT"
] | 1 | 2020-11-12T09:00:30.000Z | 2020-11-12T09:00:30.000Z | /**
* Orthanc - A Lightweight, RESTful DICOM Store
* Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
* Department, University Hospital of Liege, Belgium
* Copyright (C) 2017-2020 Osimis S.A., Belgium
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* In addition, as a special exception, the copyright holders of this
* program give permission to link the code of its release with the
* OpenSSL project's "OpenSSL" library (or with modified versions of it
* that use the same license as the "OpenSSL" library), and distribute
* the linked executables. You must obey the GNU General Public License
* in all respects for all of the code used other than "OpenSSL". If you
* modify file(s) with this exception, you may extend this exception to
* your version of the file(s), but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source files
* in the program, then also delete it here.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include "../PrecompiledHeadersServer.h"
#include "SQLiteDatabaseWrapper.h"
#include "../../../OrthancFramework/Sources/DicomFormat/DicomArray.h"
#include "../../../OrthancFramework/Sources/Logging.h"
#include "../../../OrthancFramework/Sources/SQLite/Transaction.h"
#include "../Search/ISqlLookupFormatter.h"
#include "../ServerToolbox.h"
#include <OrthancServerResources.h>
#include <stdio.h>
#include <boost/lexical_cast.hpp>
namespace Orthanc
{
namespace Internals
{
class SignalFileDeleted : public SQLite::IScalarFunction
{
private:
IDatabaseListener& listener_;
public:
SignalFileDeleted(IDatabaseListener& listener) :
listener_(listener)
{
}
virtual const char* GetName() const
{
return "SignalFileDeleted";
}
virtual unsigned int GetCardinality() const
{
return 7;
}
virtual void Compute(SQLite::FunctionContext& context)
{
std::string uncompressedMD5, compressedMD5;
if (!context.IsNullValue(5))
{
uncompressedMD5 = context.GetStringValue(5);
}
if (!context.IsNullValue(6))
{
compressedMD5 = context.GetStringValue(6);
}
FileInfo info(context.GetStringValue(0),
static_cast<FileContentType>(context.GetIntValue(1)),
static_cast<uint64_t>(context.GetInt64Value(2)),
uncompressedMD5,
static_cast<CompressionType>(context.GetIntValue(3)),
static_cast<uint64_t>(context.GetInt64Value(4)),
compressedMD5);
listener_.SignalFileDeleted(info);
}
};
class SignalResourceDeleted : public SQLite::IScalarFunction
{
private:
IDatabaseListener& listener_;
public:
SignalResourceDeleted(IDatabaseListener& listener) :
listener_(listener)
{
}
virtual const char* GetName() const
{
return "SignalResourceDeleted";
}
virtual unsigned int GetCardinality() const
{
return 2;
}
virtual void Compute(SQLite::FunctionContext& context)
{
ResourceType type = static_cast<ResourceType>(context.GetIntValue(1));
ServerIndexChange change(ChangeType_Deleted, type, context.GetStringValue(0));
listener_.SignalChange(change);
}
};
class SignalRemainingAncestor : public SQLite::IScalarFunction
{
private:
bool hasRemainingAncestor_;
std::string remainingPublicId_;
ResourceType remainingType_;
public:
SignalRemainingAncestor() :
hasRemainingAncestor_(false)
{
}
void Reset()
{
hasRemainingAncestor_ = false;
}
virtual const char* GetName() const
{
return "SignalRemainingAncestor";
}
virtual unsigned int GetCardinality() const
{
return 2;
}
virtual void Compute(SQLite::FunctionContext& context)
{
VLOG(1) << "There exists a remaining ancestor with public ID \""
<< context.GetStringValue(0)
<< "\" of type "
<< context.GetIntValue(1);
if (!hasRemainingAncestor_ ||
remainingType_ >= context.GetIntValue(1))
{
hasRemainingAncestor_ = true;
remainingPublicId_ = context.GetStringValue(0);
remainingType_ = static_cast<ResourceType>(context.GetIntValue(1));
}
}
bool HasRemainingAncestor() const
{
return hasRemainingAncestor_;
}
const std::string& GetRemainingAncestorId() const
{
assert(hasRemainingAncestor_);
return remainingPublicId_;
}
ResourceType GetRemainingAncestorType() const
{
assert(hasRemainingAncestor_);
return remainingType_;
}
};
}
void SQLiteDatabaseWrapper::GetChangesInternal(std::list<ServerIndexChange>& target,
bool& done,
SQLite::Statement& s,
uint32_t maxResults)
{
target.clear();
while (target.size() < maxResults && s.Step())
{
int64_t seq = s.ColumnInt64(0);
ChangeType changeType = static_cast<ChangeType>(s.ColumnInt(1));
ResourceType resourceType = static_cast<ResourceType>(s.ColumnInt(3));
const std::string& date = s.ColumnString(4);
int64_t internalId = s.ColumnInt64(2);
std::string publicId = GetPublicId(internalId);
target.push_back(ServerIndexChange(seq, changeType, resourceType, publicId, date));
}
done = !(target.size() == maxResults && s.Step());
}
void SQLiteDatabaseWrapper::GetExportedResourcesInternal(std::list<ExportedResource>& target,
bool& done,
SQLite::Statement& s,
uint32_t maxResults)
{
target.clear();
while (target.size() < maxResults && s.Step())
{
int64_t seq = s.ColumnInt64(0);
ResourceType resourceType = static_cast<ResourceType>(s.ColumnInt(1));
std::string publicId = s.ColumnString(2);
ExportedResource resource(seq,
resourceType,
publicId,
s.ColumnString(3), // modality
s.ColumnString(8), // date
s.ColumnString(4), // patient ID
s.ColumnString(5), // study instance UID
s.ColumnString(6), // series instance UID
s.ColumnString(7)); // sop instance UID
target.push_back(resource);
}
done = !(target.size() == maxResults && s.Step());
}
void SQLiteDatabaseWrapper::GetChildren(std::list<std::string>& childrenPublicIds,
int64_t id)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT publicId FROM Resources WHERE parentId=?");
s.BindInt64(0, id);
childrenPublicIds.clear();
while (s.Step())
{
childrenPublicIds.push_back(s.ColumnString(0));
}
}
void SQLiteDatabaseWrapper::DeleteResource(int64_t id)
{
signalRemainingAncestor_->Reset();
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM Resources WHERE internalId=?");
s.BindInt64(0, id);
s.Run();
if (signalRemainingAncestor_->HasRemainingAncestor() &&
listener_ != NULL)
{
listener_->SignalRemainingAncestor(signalRemainingAncestor_->GetRemainingAncestorType(),
signalRemainingAncestor_->GetRemainingAncestorId());
}
}
bool SQLiteDatabaseWrapper::GetParentPublicId(std::string& target,
int64_t id)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT a.publicId FROM Resources AS a, Resources AS b "
"WHERE a.internalId = b.parentId AND b.internalId = ?");
s.BindInt64(0, id);
if (s.Step())
{
target = s.ColumnString(0);
return true;
}
else
{
return false;
}
}
int64_t SQLiteDatabaseWrapper::GetTableRecordCount(const std::string& table)
{
/**
* "Generally one cannot use SQL parameters/placeholders for
* database identifiers (tables, columns, views, schemas, etc.) or
* database functions (e.g., CURRENT_DATE), but instead only for
* binding literal values." => To avoid any SQL injection, we
* check that the "table" parameter has only alphabetic
* characters.
* https://stackoverflow.com/a/1274764/881731
**/
for (size_t i = 0; i < table.size(); i++)
{
if (!isalpha(table[i]))
{
throw OrthancException(ErrorCode_ParameterOutOfRange);
}
}
// Don't use "SQLITE_FROM_HERE", otherwise "table" would be cached
SQLite::Statement s(db_, "SELECT COUNT(*) FROM " + table);
if (s.Step())
{
int64_t c = s.ColumnInt(0);
assert(!s.Step());
return c;
}
else
{
throw OrthancException(ErrorCode_InternalError);
}
}
SQLiteDatabaseWrapper::SQLiteDatabaseWrapper(const std::string& path) :
listener_(NULL),
signalRemainingAncestor_(NULL),
version_(0)
{
db_.Open(path);
}
SQLiteDatabaseWrapper::SQLiteDatabaseWrapper() :
listener_(NULL),
signalRemainingAncestor_(NULL),
version_(0)
{
db_.OpenInMemory();
}
int SQLiteDatabaseWrapper::GetGlobalIntegerProperty(GlobalProperty property,
int defaultValue)
{
std::string tmp;
if (!LookupGlobalProperty(tmp, GlobalProperty_DatabasePatchLevel))
{
return defaultValue;
}
else
{
try
{
return boost::lexical_cast<int>(tmp);
}
catch (boost::bad_lexical_cast&)
{
throw OrthancException(ErrorCode_ParameterOutOfRange,
"Global property " + boost::lexical_cast<std::string>(property) +
" should be an integer, but found: " + tmp);
}
}
}
void SQLiteDatabaseWrapper::Open()
{
db_.Execute("PRAGMA ENCODING=\"UTF-8\";");
// Performance tuning of SQLite with PRAGMAs
// http://www.sqlite.org/pragma.html
db_.Execute("PRAGMA SYNCHRONOUS=NORMAL;");
db_.Execute("PRAGMA JOURNAL_MODE=WAL;");
db_.Execute("PRAGMA LOCKING_MODE=EXCLUSIVE;");
db_.Execute("PRAGMA WAL_AUTOCHECKPOINT=1000;");
//db_.Execute("PRAGMA TEMP_STORE=memory");
// Make "LIKE" case-sensitive in SQLite
db_.Execute("PRAGMA case_sensitive_like = true;");
{
SQLite::Transaction t(db_);
t.Begin();
if (!db_.DoesTableExist("GlobalProperties"))
{
LOG(INFO) << "Creating the database";
std::string query;
ServerResources::GetFileResource(query, ServerResources::PREPARE_DATABASE);
db_.Execute(query);
}
// Check the version of the database
std::string tmp;
if (!LookupGlobalProperty(tmp, GlobalProperty_DatabaseSchemaVersion))
{
tmp = "Unknown";
}
bool ok = false;
try
{
LOG(INFO) << "Version of the Orthanc database: " << tmp;
version_ = boost::lexical_cast<unsigned int>(tmp);
ok = true;
}
catch (boost::bad_lexical_cast&)
{
}
if (!ok)
{
throw OrthancException(ErrorCode_IncompatibleDatabaseVersion,
"Incompatible version of the Orthanc database: " + tmp);
}
// New in Orthanc 1.5.1
if (version_ == 6)
{
if (!LookupGlobalProperty(tmp, GlobalProperty_GetTotalSizeIsFast) ||
tmp != "1")
{
LOG(INFO) << "Installing the SQLite triggers to track the size of the attachments";
std::string query;
ServerResources::GetFileResource(query, ServerResources::INSTALL_TRACK_ATTACHMENTS_SIZE);
db_.Execute(query);
}
}
t.Commit();
}
signalRemainingAncestor_ = new Internals::SignalRemainingAncestor;
db_.Register(signalRemainingAncestor_);
}
static void ExecuteUpgradeScript(SQLite::Connection& db,
ServerResources::FileResourceId script)
{
std::string upgrade;
ServerResources::GetFileResource(upgrade, script);
db.BeginTransaction();
db.Execute(upgrade);
db.CommitTransaction();
}
void SQLiteDatabaseWrapper::Upgrade(unsigned int targetVersion,
IStorageArea& storageArea)
{
if (targetVersion != 6)
{
throw OrthancException(ErrorCode_IncompatibleDatabaseVersion);
}
// This version of Orthanc is only compatible with versions 3, 4,
// 5 and 6 of the DB schema
if (version_ != 3 &&
version_ != 4 &&
version_ != 5 &&
version_ != 6)
{
throw OrthancException(ErrorCode_IncompatibleDatabaseVersion);
}
if (version_ == 3)
{
LOG(WARNING) << "Upgrading database version from 3 to 4";
ExecuteUpgradeScript(db_, ServerResources::UPGRADE_DATABASE_3_TO_4);
version_ = 4;
}
if (version_ == 4)
{
LOG(WARNING) << "Upgrading database version from 4 to 5";
ExecuteUpgradeScript(db_, ServerResources::UPGRADE_DATABASE_4_TO_5);
version_ = 5;
}
if (version_ == 5)
{
LOG(WARNING) << "Upgrading database version from 5 to 6";
// No change in the DB schema, the step from version 5 to 6 only
// consists in reconstructing the main DICOM tags information
// (as more tags got included).
db_.BeginTransaction();
ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Patient);
ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Study);
ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Series);
ServerToolbox::ReconstructMainDicomTags(*this, storageArea, ResourceType_Instance);
db_.Execute("UPDATE GlobalProperties SET value=\"6\" WHERE property=" +
boost::lexical_cast<std::string>(GlobalProperty_DatabaseSchemaVersion) + ";");
db_.CommitTransaction();
version_ = 6;
}
}
void SQLiteDatabaseWrapper::SetListener(IDatabaseListener& listener)
{
listener_ = &listener;
db_.Register(new Internals::SignalFileDeleted(listener));
db_.Register(new Internals::SignalResourceDeleted(listener));
}
void SQLiteDatabaseWrapper::ClearTable(const std::string& tableName)
{
db_.Execute("DELETE FROM " + tableName);
}
bool SQLiteDatabaseWrapper::LookupParent(int64_t& parentId,
int64_t resourceId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT parentId FROM Resources WHERE internalId=?");
s.BindInt64(0, resourceId);
if (!s.Step())
{
throw OrthancException(ErrorCode_UnknownResource);
}
if (s.ColumnIsNull(0))
{
return false;
}
else
{
parentId = s.ColumnInt(0);
return true;
}
}
ResourceType SQLiteDatabaseWrapper::GetResourceType(int64_t resourceId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT resourceType FROM Resources WHERE internalId=?");
s.BindInt64(0, resourceId);
if (s.Step())
{
return static_cast<ResourceType>(s.ColumnInt(0));
}
else
{
throw OrthancException(ErrorCode_UnknownResource);
}
}
std::string SQLiteDatabaseWrapper::GetPublicId(int64_t resourceId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT publicId FROM Resources WHERE internalId=?");
s.BindInt64(0, resourceId);
if (s.Step())
{
return s.ColumnString(0);
}
else
{
throw OrthancException(ErrorCode_UnknownResource);
}
}
void SQLiteDatabaseWrapper::GetChanges(std::list<ServerIndexChange>& target /*out*/,
bool& done /*out*/,
int64_t since,
uint32_t maxResults)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT * FROM Changes WHERE seq>? ORDER BY seq LIMIT ?");
s.BindInt64(0, since);
s.BindInt(1, maxResults + 1);
GetChangesInternal(target, done, s, maxResults);
}
void SQLiteDatabaseWrapper::GetLastChange(std::list<ServerIndexChange>& target /*out*/)
{
bool done; // Ignored
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT * FROM Changes ORDER BY seq DESC LIMIT 1");
GetChangesInternal(target, done, s, 1);
}
class SQLiteDatabaseWrapper::Transaction : public IDatabaseWrapper::ITransaction
{
private:
SQLiteDatabaseWrapper& that_;
std::unique_ptr<SQLite::Transaction> transaction_;
int64_t initialDiskSize_;
public:
Transaction(SQLiteDatabaseWrapper& that) :
that_(that),
transaction_(new SQLite::Transaction(that_.db_))
{
#if defined(NDEBUG)
// Release mode
initialDiskSize_ = 0;
#else
// Debug mode
initialDiskSize_ = static_cast<int64_t>(that_.GetTotalCompressedSize());
#endif
}
virtual void Begin()
{
transaction_->Begin();
}
virtual void Rollback()
{
transaction_->Rollback();
}
virtual void Commit(int64_t fileSizeDelta /* only used in debug */)
{
transaction_->Commit();
assert(initialDiskSize_ + fileSizeDelta >= 0 &&
initialDiskSize_ + fileSizeDelta == static_cast<int64_t>(that_.GetTotalCompressedSize()));
}
};
IDatabaseWrapper::ITransaction* SQLiteDatabaseWrapper::StartTransaction()
{
return new Transaction(*this);
}
void SQLiteDatabaseWrapper::GetAllMetadata(std::map<MetadataType, std::string>& target,
int64_t id)
{
target.clear();
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT type, value FROM Metadata WHERE id=?");
s.BindInt64(0, id);
while (s.Step())
{
MetadataType key = static_cast<MetadataType>(s.ColumnInt(0));
target[key] = s.ColumnString(1);
}
}
void SQLiteDatabaseWrapper::SetGlobalProperty(GlobalProperty property,
const std::string& value)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT OR REPLACE INTO GlobalProperties VALUES(?, ?)");
s.BindInt(0, property);
s.BindString(1, value);
s.Run();
}
bool SQLiteDatabaseWrapper::LookupGlobalProperty(std::string& target,
GlobalProperty property)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT value FROM GlobalProperties WHERE property=?");
s.BindInt(0, property);
if (!s.Step())
{
return false;
}
else
{
target = s.ColumnString(0);
return true;
}
}
int64_t SQLiteDatabaseWrapper::CreateResource(const std::string& publicId,
ResourceType type)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO Resources VALUES(NULL, ?, ?, NULL)");
s.BindInt(0, type);
s.BindString(1, publicId);
s.Run();
return db_.GetLastInsertRowId();
}
bool SQLiteDatabaseWrapper::LookupResource(int64_t& id,
ResourceType& type,
const std::string& publicId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT internalId, resourceType FROM Resources WHERE publicId=?");
s.BindString(0, publicId);
if (!s.Step())
{
return false;
}
else
{
id = s.ColumnInt(0);
type = static_cast<ResourceType>(s.ColumnInt(1));
// Check whether there is a single resource with this public id
assert(!s.Step());
return true;
}
}
void SQLiteDatabaseWrapper::AttachChild(int64_t parent,
int64_t child)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "UPDATE Resources SET parentId = ? WHERE internalId = ?");
s.BindInt64(0, parent);
s.BindInt64(1, child);
s.Run();
}
void SQLiteDatabaseWrapper::SetMetadata(int64_t id,
MetadataType type,
const std::string& value)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT OR REPLACE INTO Metadata VALUES(?, ?, ?)");
s.BindInt64(0, id);
s.BindInt(1, type);
s.BindString(2, value);
s.Run();
}
void SQLiteDatabaseWrapper::DeleteMetadata(int64_t id,
MetadataType type)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM Metadata WHERE id=? and type=?");
s.BindInt64(0, id);
s.BindInt(1, type);
s.Run();
}
bool SQLiteDatabaseWrapper::LookupMetadata(std::string& target,
int64_t id,
MetadataType type)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT value FROM Metadata WHERE id=? AND type=?");
s.BindInt64(0, id);
s.BindInt(1, type);
if (!s.Step())
{
return false;
}
else
{
target = s.ColumnString(0);
return true;
}
}
void SQLiteDatabaseWrapper::AddAttachment(int64_t id,
const FileInfo& attachment)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO AttachedFiles VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
s.BindInt64(0, id);
s.BindInt(1, attachment.GetContentType());
s.BindString(2, attachment.GetUuid());
s.BindInt64(3, attachment.GetCompressedSize());
s.BindInt64(4, attachment.GetUncompressedSize());
s.BindInt(5, attachment.GetCompressionType());
s.BindString(6, attachment.GetUncompressedMD5());
s.BindString(7, attachment.GetCompressedMD5());
s.Run();
}
void SQLiteDatabaseWrapper::DeleteAttachment(int64_t id,
FileContentType attachment)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM AttachedFiles WHERE id=? AND fileType=?");
s.BindInt64(0, id);
s.BindInt(1, attachment);
s.Run();
}
void SQLiteDatabaseWrapper::ListAvailableAttachments(std::list<FileContentType>& target,
int64_t id)
{
target.clear();
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT fileType FROM AttachedFiles WHERE id=?");
s.BindInt64(0, id);
while (s.Step())
{
target.push_back(static_cast<FileContentType>(s.ColumnInt(0)));
}
}
bool SQLiteDatabaseWrapper::LookupAttachment(FileInfo& attachment,
int64_t id,
FileContentType contentType)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT uuid, uncompressedSize, compressionType, compressedSize, "
"uncompressedMD5, compressedMD5 FROM AttachedFiles WHERE id=? AND fileType=?");
s.BindInt64(0, id);
s.BindInt(1, contentType);
if (!s.Step())
{
return false;
}
else
{
attachment = FileInfo(s.ColumnString(0),
contentType,
s.ColumnInt64(1),
s.ColumnString(4),
static_cast<CompressionType>(s.ColumnInt(2)),
s.ColumnInt64(3),
s.ColumnString(5));
return true;
}
}
void SQLiteDatabaseWrapper::ClearMainDicomTags(int64_t id)
{
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM DicomIdentifiers WHERE id=?");
s.BindInt64(0, id);
s.Run();
}
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM MainDicomTags WHERE id=?");
s.BindInt64(0, id);
s.Run();
}
}
void SQLiteDatabaseWrapper::SetMainDicomTag(int64_t id,
const DicomTag& tag,
const std::string& value)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO MainDicomTags VALUES(?, ?, ?, ?)");
s.BindInt64(0, id);
s.BindInt(1, tag.GetGroup());
s.BindInt(2, tag.GetElement());
s.BindString(3, value);
s.Run();
}
void SQLiteDatabaseWrapper::SetIdentifierTag(int64_t id,
const DicomTag& tag,
const std::string& value)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO DicomIdentifiers VALUES(?, ?, ?, ?)");
s.BindInt64(0, id);
s.BindInt(1, tag.GetGroup());
s.BindInt(2, tag.GetElement());
s.BindString(3, value);
s.Run();
}
void SQLiteDatabaseWrapper::GetMainDicomTags(DicomMap& map,
int64_t id)
{
map.Clear();
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT * FROM MainDicomTags WHERE id=?");
s.BindInt64(0, id);
while (s.Step())
{
map.SetValue(s.ColumnInt(1),
s.ColumnInt(2),
s.ColumnString(3), false);
}
}
void SQLiteDatabaseWrapper::GetChildrenPublicId(std::list<std::string>& target,
int64_t id)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT a.publicId FROM Resources AS a, Resources AS b "
"WHERE a.parentId = b.internalId AND b.internalId = ?");
s.BindInt64(0, id);
target.clear();
while (s.Step())
{
target.push_back(s.ColumnString(0));
}
}
void SQLiteDatabaseWrapper::GetChildrenInternalId(std::list<int64_t>& target,
int64_t id)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT a.internalId FROM Resources AS a, Resources AS b "
"WHERE a.parentId = b.internalId AND b.internalId = ?");
s.BindInt64(0, id);
target.clear();
while (s.Step())
{
target.push_back(s.ColumnInt64(0));
}
}
void SQLiteDatabaseWrapper::LogChange(int64_t internalId,
const ServerIndexChange& change)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO Changes VALUES(NULL, ?, ?, ?, ?)");
s.BindInt(0, change.GetChangeType());
s.BindInt64(1, internalId);
s.BindInt(2, change.GetResourceType());
s.BindString(3, change.GetDate());
s.Run();
}
void SQLiteDatabaseWrapper::LogExportedResource(const ExportedResource& resource)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"INSERT INTO ExportedResources VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?)");
s.BindInt(0, resource.GetResourceType());
s.BindString(1, resource.GetPublicId());
s.BindString(2, resource.GetModality());
s.BindString(3, resource.GetPatientId());
s.BindString(4, resource.GetStudyInstanceUid());
s.BindString(5, resource.GetSeriesInstanceUid());
s.BindString(6, resource.GetSopInstanceUid());
s.BindString(7, resource.GetDate());
s.Run();
}
void SQLiteDatabaseWrapper::GetExportedResources(std::list<ExportedResource>& target,
bool& done,
int64_t since,
uint32_t maxResults)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT * FROM ExportedResources WHERE seq>? ORDER BY seq LIMIT ?");
s.BindInt64(0, since);
s.BindInt(1, maxResults + 1);
GetExportedResourcesInternal(target, done, s, maxResults);
}
void SQLiteDatabaseWrapper::GetLastExportedResource(std::list<ExportedResource>& target)
{
bool done; // Ignored
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT * FROM ExportedResources ORDER BY seq DESC LIMIT 1");
GetExportedResourcesInternal(target, done, s, 1);
}
uint64_t SQLiteDatabaseWrapper::GetTotalCompressedSize()
{
// Old SQL query that was used in Orthanc <= 1.5.0:
// SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT SUM(compressedSize) FROM AttachedFiles");
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT value FROM GlobalIntegers WHERE key=0");
s.Run();
return static_cast<uint64_t>(s.ColumnInt64(0));
}
uint64_t SQLiteDatabaseWrapper::GetTotalUncompressedSize()
{
// Old SQL query that was used in Orthanc <= 1.5.0:
// SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT SUM(uncompressedSize) FROM AttachedFiles");
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT value FROM GlobalIntegers WHERE key=1");
s.Run();
return static_cast<uint64_t>(s.ColumnInt64(0));
}
uint64_t SQLiteDatabaseWrapper::GetResourceCount(ResourceType resourceType)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT COUNT(*) FROM Resources WHERE resourceType=?");
s.BindInt(0, resourceType);
if (!s.Step())
{
return 0;
}
else
{
int64_t c = s.ColumnInt(0);
assert(!s.Step());
return c;
}
}
void SQLiteDatabaseWrapper::GetAllPublicIds(std::list<std::string>& target,
ResourceType resourceType)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT publicId FROM Resources WHERE resourceType=?");
s.BindInt(0, resourceType);
target.clear();
while (s.Step())
{
target.push_back(s.ColumnString(0));
}
}
void SQLiteDatabaseWrapper::GetAllPublicIds(std::list<std::string>& target,
ResourceType resourceType,
size_t since,
size_t limit)
{
if (limit == 0)
{
target.clear();
return;
}
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT publicId FROM Resources WHERE "
"resourceType=? LIMIT ? OFFSET ?");
s.BindInt(0, resourceType);
s.BindInt64(1, limit);
s.BindInt64(2, since);
target.clear();
while (s.Step())
{
target.push_back(s.ColumnString(0));
}
}
bool SQLiteDatabaseWrapper::SelectPatientToRecycle(int64_t& internalId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT patientId FROM PatientRecyclingOrder ORDER BY seq ASC LIMIT 1");
if (!s.Step())
{
// No patient remaining or all the patients are protected
return false;
}
else
{
internalId = s.ColumnInt(0);
return true;
}
}
bool SQLiteDatabaseWrapper::SelectPatientToRecycle(int64_t& internalId,
int64_t patientIdToAvoid)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT patientId FROM PatientRecyclingOrder "
"WHERE patientId != ? ORDER BY seq ASC LIMIT 1");
s.BindInt64(0, patientIdToAvoid);
if (!s.Step())
{
// No patient remaining or all the patients are protected
return false;
}
else
{
internalId = s.ColumnInt(0);
return true;
}
}
bool SQLiteDatabaseWrapper::IsProtectedPatient(int64_t internalId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT * FROM PatientRecyclingOrder WHERE patientId = ?");
s.BindInt64(0, internalId);
return !s.Step();
}
void SQLiteDatabaseWrapper::SetProtectedPatient(int64_t internalId,
bool isProtected)
{
if (isProtected)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DELETE FROM PatientRecyclingOrder WHERE patientId=?");
s.BindInt64(0, internalId);
s.Run();
}
else if (IsProtectedPatient(internalId))
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "INSERT INTO PatientRecyclingOrder VALUES(NULL, ?)");
s.BindInt64(0, internalId);
s.Run();
}
else
{
// Nothing to do: The patient is already unprotected
}
}
bool SQLiteDatabaseWrapper::IsExistingResource(int64_t internalId)
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT * FROM Resources WHERE internalId=?");
s.BindInt64(0, internalId);
return s.Step();
}
bool SQLiteDatabaseWrapper::IsDiskSizeAbove(uint64_t threshold)
{
return GetTotalCompressedSize() > threshold;
}
class SQLiteDatabaseWrapper::LookupFormatter : public ISqlLookupFormatter
{
private:
std::list<std::string> values_;
public:
virtual std::string GenerateParameter(const std::string& value)
{
values_.push_back(value);
return "?";
}
virtual std::string FormatResourceType(ResourceType level)
{
return boost::lexical_cast<std::string>(level);
}
virtual std::string FormatWildcardEscape()
{
return "ESCAPE '\\'";
}
void Bind(SQLite::Statement& statement) const
{
size_t pos = 0;
for (std::list<std::string>::const_iterator
it = values_.begin(); it != values_.end(); ++it, pos++)
{
statement.BindString(pos, *it);
}
}
};
static void AnswerLookup(std::list<std::string>& resourcesId,
std::list<std::string>& instancesId,
SQLite::Connection& db,
ResourceType level)
{
resourcesId.clear();
instancesId.clear();
std::unique_ptr<SQLite::Statement> statement;
switch (level)
{
case ResourceType_Patient:
{
statement.reset(
new SQLite::Statement(
db, SQLITE_FROM_HERE,
"SELECT patients.publicId, instances.publicID FROM Lookup AS patients "
"INNER JOIN Resources studies ON patients.internalId=studies.parentId "
"INNER JOIN Resources series ON studies.internalId=series.parentId "
"INNER JOIN Resources instances ON series.internalId=instances.parentId "
"GROUP BY patients.publicId"));
break;
}
case ResourceType_Study:
{
statement.reset(
new SQLite::Statement(
db, SQLITE_FROM_HERE,
"SELECT studies.publicId, instances.publicID FROM Lookup AS studies "
"INNER JOIN Resources series ON studies.internalId=series.parentId "
"INNER JOIN Resources instances ON series.internalId=instances.parentId "
"GROUP BY studies.publicId"));
break;
}
case ResourceType_Series:
{
statement.reset(
new SQLite::Statement(
db, SQLITE_FROM_HERE,
"SELECT series.publicId, instances.publicID FROM Lookup AS series "
"INNER JOIN Resources instances ON series.internalId=instances.parentId "
"GROUP BY series.publicId"));
break;
}
case ResourceType_Instance:
{
statement.reset(
new SQLite::Statement(
db, SQLITE_FROM_HERE, "SELECT publicId, publicId FROM Lookup"));
break;
}
default:
throw OrthancException(ErrorCode_InternalError);
}
assert(statement.get() != NULL);
while (statement->Step())
{
resourcesId.push_back(statement->ColumnString(0));
instancesId.push_back(statement->ColumnString(1));
}
}
void SQLiteDatabaseWrapper::ApplyLookupResources(std::list<std::string>& resourcesId,
std::list<std::string>* instancesId,
const std::vector<DatabaseConstraint>& lookup,
ResourceType queryLevel,
size_t limit)
{
LookupFormatter formatter;
std::string sql;
LookupFormatter::Apply(sql, formatter, lookup, queryLevel, limit);
sql = "CREATE TEMPORARY TABLE Lookup AS " + sql;
{
SQLite::Statement s(db_, SQLITE_FROM_HERE, "DROP TABLE IF EXISTS Lookup");
s.Run();
}
{
SQLite::Statement statement(db_, sql);
formatter.Bind(statement);
statement.Run();
}
if (instancesId != NULL)
{
AnswerLookup(resourcesId, *instancesId, db_, queryLevel);
}
else
{
resourcesId.clear();
SQLite::Statement s(db_, SQLITE_FROM_HERE, "SELECT publicId FROM Lookup");
while (s.Step())
{
resourcesId.push_back(s.ColumnString(0));
}
}
}
int64_t SQLiteDatabaseWrapper::GetLastChangeIndex()
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"SELECT seq FROM sqlite_sequence WHERE name='Changes'");
if (s.Step())
{
int64_t c = s.ColumnInt(0);
assert(!s.Step());
return c;
}
else
{
// No change has been recorded so far in the database
return 0;
}
}
void SQLiteDatabaseWrapper::TagMostRecentPatient(int64_t patient)
{
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"DELETE FROM PatientRecyclingOrder WHERE patientId=?");
s.BindInt64(0, patient);
s.Run();
assert(db_.GetLastChangeCount() == 0 ||
db_.GetLastChangeCount() == 1);
if (db_.GetLastChangeCount() == 0)
{
// The patient was protected, there was nothing to delete from the recycling order
return;
}
}
{
SQLite::Statement s(db_, SQLITE_FROM_HERE,
"INSERT INTO PatientRecyclingOrder VALUES(NULL, ?)");
s.BindInt64(0, patient);
s.Run();
}
}
}
| 28.940916 | 107 | 0.587812 | [
"vector"
] |
ae7dd577d94d9808cd13cb0e9db8532df24e1367 | 774 | hpp | C++ | cpp/include/cmeans.hpp | billsioros/MMGP | d9cdd206e9baa4991ade1304dc4be53e1859b49d | [
"MIT"
] | 3 | 2018-08-21T14:47:32.000Z | 2019-10-31T21:02:35.000Z | cpp/include/cmeans.hpp | billsioros/MMGP | d9cdd206e9baa4991ade1304dc4be53e1859b49d | [
"MIT"
] | 1 | 2019-11-14T22:59:07.000Z | 2019-11-15T13:18:47.000Z | include/cmeans.hpp | billsioros/cmeans | 96bf9fd89cb9f86a52cb9ceecbe17d379db4e24d | [
"MIT"
] | null | null | null |
#pragma once
#include <unordered_set> // std::unordered_set
#include <vector> // std::vector
#include <functional> // std::function
template <typename T>
class Cluster
{
T _centroid;
std::unordered_set<const T *> _elements;
public:
Cluster(const T&);
Cluster(const Cluster&);
Cluster(Cluster&&) noexcept;
Cluster& operator=(const Cluster&);
Cluster& operator=(Cluster&&) noexcept;
const T& centroid() const;
const std::unordered_set<const T *>& elements() const;
static std::vector<Cluster<T>> cmeans
(
const std::vector<T>&,
std::size_t,
const std::function<double(const T&, const T&)>&,
const std::function<std::size_t(const T&)>&
);
};
#include "cmeans.ipp"
| 20.918919 | 58 | 0.614987 | [
"vector"
] |
ae841ba74e7c4fed3ae097a83950cb4251fdb307 | 12,768 | hh | C++ | RAVL2/Core/IO/AttributeCtrl.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Core/IO/AttributeCtrl.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Core/IO/AttributeCtrl.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2003, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVL_ATTRIBUTECTRL_HEADER
#define RAVL_ATTRIBUTECTRL_HEADER 1
//! author="Charles Galambos"
//! date="23/8/2003"
//! rcsid="$Id: AttributeCtrl.hh 7646 2010-03-08 14:43:10Z robowaz $"
//! lib=RavlIO
//! file="Ravl/Core/IO/AttributeCtrl.hh"
//! docentry="Ravl.API.Core.Data_Processing.Attributes"
#include "Ravl/DP/Entity.hh"
#include "Ravl/String.hh"
namespace RavlN {
class AttributeTypeC;
class AttributeCtrlC;
class TriggerC;
template<class DataT> class DListC;
class AttributeCtrlInternalC;
class AttributeSetBodyC;
class XMLIStreamC;
class XMLOStreamC;
//! userlevel=Develop
//: Interface for reading and writing attribute values.
class AttributeCtrlBodyC
: virtual public DPEntityBodyC
{
public:
AttributeCtrlBodyC();
//: Default constructor.
AttributeCtrlBodyC(istream &in);
//: Stream constructor.
AttributeCtrlBodyC(const AttributeCtrlBodyC &bod);
//: Copy constructor.
virtual ~AttributeCtrlBodyC();
//: Destructor.
AttributeCtrlBodyC &operator=(const AttributeCtrlBodyC &);
//: Assignment operator.
virtual AttributeCtrlC ParentCtrl() const;
//: Get Parent attribute control.
StringC GetAttr(const StringC &attrName);
//: Get named attribute.
virtual bool GetAttr(const StringC &attrName,StringC &attrValue);
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool SetAttr(const StringC &attrName,const StringC &attrValue);
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool GetAttr(const StringC &attrName,IntT &attrValue);
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool SetAttr(const StringC &attrName,const IntT &attrValue);
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool GetAttr(const StringC &attrName,Int64T &attrValue);
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool SetAttr(const StringC &attrName,const Int64T &attrValue);
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool GetAttr(const StringC &attrName,RealT &attrValue);
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool SetAttr(const StringC &attrName,const RealT &attrValue);
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool GetAttr(const StringC &attrName,bool &attrValue);
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool SetAttr(const StringC &attrName,const bool &attrValue);
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
virtual bool GetComponent(const StringC &attrName,AttributeCtrlC &attr);
//: Get a sub component.
// Returns false if the attribute name is unknown.
virtual bool GetAttrList(DListC<StringC> &list) const;
//: Get list of attributes available.
// This method will ADD all available attribute names to 'list'.
virtual bool GetAttrTypes(DListC<AttributeTypeC> &list) const;
//: Get a list of available attribute types.
virtual AttributeTypeC GetAttrType(const StringC &attrName) const;
//: Get type of a particular attribute.
// Returns an invalid handle if attribute is unknown.
virtual IntT RegisterChangedSignal(const StringC &attrName,const TriggerC &trig);
//: Register a value changed signal.
// Note: This method may not be implemented for all AttributeCtrl's.
// Returns an id for the trigger, or -1 if operation fails.
virtual bool RemoveChangedSignal(IntT id);
//: Remove a changed signal.
// Note: This method may not be implemented for all AttributeCtrl's.
virtual bool MapBackChangedSignal(const StringC &name);
//: Map attribute changed signal to parent even if its an attribute at this level.
virtual bool RegisterAttribute(const AttributeTypeC &attr);
//: Register a new attribute type.
bool SaveAttributes(XMLOStreamC &strm,bool useEnclosingTag = true) const;
//: Save setup to XML stream.
bool LoadAttributes(XMLIStreamC &strm,bool expectEnclosingTag = true);
//: Load setup from XML stream.
bool RestoreDefaults();
//: Set all attributes to default values.
AttributeCtrlC AttributeCtrl();
//: Access this access control as a handle object.
protected:
virtual bool SignalChange(const StringC &attrName);
//: Signal that an attribute has changed.
bool ReparentAttributeCtrl(const AttributeCtrlC &newParent);
//: Let the attribute ctrl know its parent has changed.
bool SignalAttributeRefresh();
//: Signal refresh for all registered attributes.
private:
AttributeCtrlInternalC *attrInfo;
friend class AttributeSetBodyC;
};
//! userlevel=Normal
//: Interface for reading and writing attribute values.
class AttributeCtrlC
: virtual public DPEntityC
{
public:
AttributeCtrlC()
: DPEntityC(true)
{}
//: Default constructor.
// Creates an invalid handle.
AttributeCtrlC(istream &strm)
: DPEntityC(strm)
{}
//: Stream constructor.
AttributeCtrlC(const DPEntityC &base)
: DPEntityC(dynamic_cast<const AttributeCtrlBodyC *>(BodyPtr(base)))
{}
//: Create from base handle.
// Handle is invalid if object is not derived from AttributeCtrlC.
protected:
AttributeCtrlC(AttributeCtrlBodyC &bod)
: DPEntityC(bod)
{}
//: Body constructor.
AttributeCtrlC(const AttributeCtrlBodyC *bod)
: DPEntityC(bod)
{}
//: Body constructor.
inline AttributeCtrlBodyC &Body()
{ return dynamic_cast<AttributeCtrlBodyC &> (DPEntityC::Body()); }
//: Access body.
inline const AttributeCtrlBodyC &Body() const
{ return dynamic_cast<const AttributeCtrlBodyC &> (DPEntityC::Body()); }
//: Access body.
public:
StringC GetAttr(const StringC &attrName);
//: Get a attribute.
// Return the value of an attribute or an empty string if its unkown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool GetAttr(const StringC &attrName,StringC &attrValue)
{ return Body().GetAttr(attrName,attrValue); }
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool SetAttr(const StringC &attrName,const StringC &attrValue)
{ return Body().SetAttr(attrName,attrValue); }
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool SetAttr(const StringC &attrName,const char * value)
{ return Body().SetAttr(attrName,StringC(value)); }
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool GetAttr(const StringC &attrName,IntT &attrValue)
{ return Body().GetAttr(attrName,attrValue); }
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool SetAttr(const StringC &attrName,const IntT &attrValue)
{ return Body().SetAttr(attrName,attrValue); }
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool GetAttr(const StringC &attrName,Int64T &attrValue)
{ return Body().GetAttr(attrName,attrValue); }
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool SetAttr(const StringC &attrName,const Int64T &attrValue)
{ return Body().SetAttr(attrName,attrValue); }
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool GetAttr(const StringC &attrName,RealT &attrValue)
{ return Body().GetAttr(attrName,attrValue); }
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool SetAttr(const StringC &attrName,const RealT &attrValue)
{ return Body().SetAttr(attrName,attrValue); }
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool GetAttr(const StringC &attrName,bool &attrValue)
{ return Body().GetAttr(attrName,attrValue); }
//: Get a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool SetAttr(const StringC &attrName,const bool &attrValue)
{ return Body().SetAttr(attrName,attrValue); }
//: Set a attribute.
// Returns false if the attribute name is unknown.
// This is for handling attributes such as frame rate, and compression ratios.
inline bool GetComponent(const StringC &attrName,AttributeCtrlC &attr)
{ return Body().GetComponent(attrName,attr); }
//: Get a sub component.
// Returns false if the attribute name is unknown.
inline bool GetAttrList(DListC<StringC> &list) const
{ return Body().GetAttrList(list); }
//: Get list of attributes available.
inline bool GetAttrTypes(DListC<AttributeTypeC> &list) const
{ return Body().GetAttrTypes(list); }
//: Get a list of available attribute types.
AttributeTypeC GetAttrType(const StringC &attrName) const;
//: Get type of a particular attribute.
// Returns an invalid handle if attribute is unknown.
IntT RegisterChangedSignal(const StringC &attrName,const TriggerC &trig)
{ return Body().RegisterChangedSignal(attrName,trig); }
//: Register a value changed signal.
// Note: This method may not be implemented for all AttributeCtrl's.
// Returns an id for the trigger, or -1 if operation fails.
bool RemoveChangedSignal(IntT id)
{ return Body().RemoveChangedSignal(id); }
//: Remove a changed signal.
// Note: This method may not be implemented for all AttributeCtrl's.
bool MapBackChangedSignal(const StringC &name)
{ return Body().MapBackChangedSignal(name); }
//: Map attribute changed signal to parent even if its an attribute at this level.
bool RegisterAttribute(const AttributeTypeC &attr)
{ return Body().RegisterAttribute(attr); }
//: Register a new attribute type.
bool SaveAttributes(XMLOStreamC &strm,bool useEnclosingTag = true) const
{ return Body().SaveAttributes(strm,useEnclosingTag); }
//: Save setup to XML stream.
bool LoadAttributes(XMLIStreamC &strm,bool expectEnclosingTag = true)
{ return Body().LoadAttributes(strm,expectEnclosingTag); }
//: Load setup from XML stream.
bool RestoreDefaults()
{ return Body().RestoreDefaults(); }
//: Set all attributes to default values.
friend class AttributeCtrlBodyC;
};
}
#endif
| 38.227545 | 86 | 0.696742 | [
"object"
] |
ae87fa37f76da9730e137e9f9a59d941259937e8 | 4,468 | cpp | C++ | src/circuit_reader.cpp | geochrist/dctk | 6bda842ae8ee2259aa1a969a08be5bcb126ec534 | [
"MIT"
] | 16 | 2019-10-23T02:34:08.000Z | 2022-03-14T06:08:21.000Z | src/circuit_reader.cpp | geochrist/dctk | 6bda842ae8ee2259aa1a969a08be5bcb126ec534 | [
"MIT"
] | 1 | 2019-11-11T03:35:27.000Z | 2019-11-11T05:07:22.000Z | src/circuit_reader.cpp | geochrist/dctk | 6bda842ae8ee2259aa1a969a08be5bcb126ec534 | [
"MIT"
] | 11 | 2019-10-20T10:47:35.000Z | 2021-07-02T04:53:28.000Z | // Circuits Reader
//#include <experimental/filesystem>
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
#include <fstream>
#include <iostream>
#include <yaml-cpp/yaml.h>
#include "Circuit.hpp"
#include <string>
#include "dctk.hpp"
#include "circuit_reader.hpp"
#include "Circuit.hpp"
#include "Benchmarks.hpp"
int read_circuits(char *circuit_file_name, dctk::CircuitPtrVec *circuitMgr, dctk::Benchmarks* benchmarks) {
std::ifstream infile(circuit_file_name);
if (!infile.good()) {
std::cerr << "can't find " << circuit_file_name << '\n';
return(1);
}
std::cout << "Reading circuits from " << circuit_file_name << std::endl;
// load the circuit list file
const YAML::Node& config = YAML::LoadFile(circuit_file_name);
// check for valid circuit config file
if (config["Circuits"]) {
const std::size_t& num_circuits = config["Circuits"].size();
std::cout << "Processing " << num_circuits << " circuits." << std::endl;
} else {
std::cout << "Could not find 'Circuits' key in " << circuit_file_name << std::endl;
return(1);
}
const YAML::Node& circuits_yaml = config["Circuits"];
for (std::size_t i = 0 ; i < circuits_yaml.size(); i++) {
// Transfer from yaml file into CircuitMgr object
const YAML::Node& circuit = circuits_yaml[i];
const std::string& name = circuit["name"].as<std::string>();
dctk::Circuit* cir = new dctk::Circuit(name);
const std::string& str_vs=circuit["input_waveform"].as<std::string>();
cir->set_input_waveform(str_vs);
const std::string& str_driver=circuit["driver"].as<std::string>();
cir->set_driver(str_driver);
const std::string& str_driver_celltype=circuit["driver_celltype"].as<std::string>();
cir->set_driver_celltype(str_driver_celltype);
const std::string& str_load=circuit["load"].as<std::string>();
cir->set_load(str_load);
const std::string& str_load_celltype=circuit["load_celltype"].as<std::string>();
cir->set_load_celltype(str_load_celltype);
const std::string& str_load_interconnect=circuit["load_interconnect"].as<std::string>();
cir->set_load_interconnect(str_load_interconnect);
const std::string& str_spice_rise_delay=circuit["spice_rise_delay"].as<std::string>();
cir->set_spice_rise_delay(atof(str_spice_rise_delay.c_str()));
const std::string& str_spice_fall_delay=circuit["spice_fall_delay"].as<std::string>();
cir->set_spice_fall_delay(atof(str_spice_fall_delay.c_str()));
const std::string& str_spice_rise_slew=circuit["spice_rise_slew"].as<std::string>();
cir->set_spice_rise_slew(atof(str_spice_rise_slew.c_str()));
const std::string& str_spice_fall_slew=circuit["spice_fall_slew"].as<std::string>();
cir->set_spice_fall_slew(atof(str_spice_fall_slew.c_str()));
const std::string& str_ccs_rise_delay=circuit["ccs_rise_delay"].as<std::string>();
cir->set_ccs_rise_delay(atof(str_ccs_rise_delay.c_str()));
const std::string& str_ccs_fall_delay=circuit["ccs_fall_delay"].as<std::string>();
cir->set_ccs_fall_delay(atof(str_ccs_fall_delay.c_str()));
const std::string& str_ccs_rise_slew=circuit["ccs_rise_slew"].as<std::string>();
cir->set_ccs_rise_slew(atof(str_ccs_rise_slew.c_str()));
const std::string& str_ccs_fall_slew=circuit["ccs_fall_slew"].as<std::string>();
cir->set_ccs_fall_slew(atof(str_ccs_fall_slew.c_str()));
circuitMgr->push_back(cir);
}
if (config["Statistics"]) {
const YAML::Node& stats_yaml = config["Statistics"];
// cpu time
if (stats_yaml["cpu_time"]) {
benchmarks->cpu_time = stats_yaml["cpu_time"].as<float>();
}
if (stats_yaml["elapsed_time"]) {
benchmarks->elapsed_time = stats_yaml["elapsed_time"].as<float>();
}
if (stats_yaml["incremental_memory"]) {
benchmarks->incremental_memory = stats_yaml["incremental_memory"].as<float>();
}
if (stats_yaml["rms_delay_diff"]) {
benchmarks->rms_delay_diff = stats_yaml["rms_delay_diff"].as<float>();
}
if (stats_yaml["rms_slew_diff"]) {
benchmarks->rms_slew_diff = stats_yaml["rms_slew_diff"].as<float>();
}
}
return 0;
}
| 36.325203 | 107 | 0.648165 | [
"object"
] |
ae97939980c2fe8b9f9fe8c6ce42c5df85112d71 | 7,149 | cxx | C++ | GPU/TPCFastTransformation/IrregularSpline1D.cxx | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | null | null | null | GPU/TPCFastTransformation/IrregularSpline1D.cxx | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | null | null | null | GPU/TPCFastTransformation/IrregularSpline1D.cxx | mpoghos/AliRoot | e81490f640ad6f2a6189f679de96b07a94304b58 | [
"BSD-3-Clause"
] | 1 | 2022-01-24T11:11:42.000Z | 2022-01-24T11:11:42.000Z | // Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/// \file IrregularSpline1D.cxx
/// \brief Implementation of IrregularSpline1D class
///
/// \author Sergey Gorbunov <sergey.gorbunov@cern.ch>
#include "IrregularSpline1D.h"
#include <cmath>
#include <vector>
#if !defined(GPUCA_GPUCODE)
#include <iostream>
#endif
using namespace GPUCA_NAMESPACE::gpu;
IrregularSpline1D::IrregularSpline1D() : FlatObject(), mNumberOfKnots(0), mNumberOfAxisBins(0), mBin2KnotMapOffset(0)
{
/// Default constructor. Creates an empty uninitialised object
}
void IrregularSpline1D::destroy()
{
/// See FlatObject for description
mNumberOfKnots = 0;
mNumberOfAxisBins = 0;
mBin2KnotMapOffset = 0;
FlatObject::destroy();
}
void IrregularSpline1D::cloneFromObject(const IrregularSpline1D& obj, char* newFlatBufferPtr)
{
/// See FlatObject for description
FlatObject::cloneFromObject(obj, newFlatBufferPtr);
mNumberOfKnots = obj.mNumberOfKnots;
mNumberOfAxisBins = obj.mNumberOfAxisBins;
mBin2KnotMapOffset = obj.mBin2KnotMapOffset;
}
void IrregularSpline1D::construct(int numberOfKnots, const float inputKnots[], int numberOfAxisBins)
{
/// Constructor.
/// Initialises the spline with a grid with numberOfKnots knots in the interval [0,1]
/// array inputKnots[] has numberOfKnots entries, ordered from 0. to 1.
/// knots on the edges u==0. & u==1. are obligatory
///
/// The number of knots created and their values may change during initialisation:
/// - Edge knots 0.f and 1.f will be added if they are not present.
/// - Knot values are rounded to closest axis bins: k*1./numberOfAxisBins.
/// - Knots which are too close to each other will be merged
/// - At least 5 knots and at least 4 axis bins will be created for consistency reason
///
/// \param numberOfKnots Number of knots in knots[] array
/// \param knots Array of knots.
/// \param numberOfAxisBins Number of axis bins to map U coordinate to
/// an appropriate [knot(i),knot(i+1)] interval.
/// The knot positions have a "granularity" of 1./(numberOfAxisBins-1)
///
numberOfAxisBins -= 1;
FlatObject::startConstruction();
if (numberOfAxisBins < 4) {
numberOfAxisBins = 4;
}
std::vector<int> vKnotBins;
{ // reorganize knots
int lastBin = numberOfAxisBins; // last bin starts with U value 1.f, therefore it is outside of the [0.,1.] interval
vKnotBins.push_back(0); // obligatory knot at 0.0
for (int i = 0; i < numberOfKnots; ++i) {
int bin = (int)roundf(inputKnots[i] * numberOfAxisBins);
if (bin <= vKnotBins.back() || bin >= lastBin) {
continue; // same knot
}
vKnotBins.push_back(bin);
}
vKnotBins.push_back(lastBin); // obligatory knot at 1.0
if (vKnotBins.size() < 5) { // too less knots, make a grid with 5 knots
vKnotBins.clear();
vKnotBins.push_back(0);
vKnotBins.push_back((int)roundf(0.25 * numberOfAxisBins));
vKnotBins.push_back((int)roundf(0.50 * numberOfAxisBins));
vKnotBins.push_back((int)roundf(0.75 * numberOfAxisBins));
vKnotBins.push_back(lastBin);
}
}
mNumberOfKnots = vKnotBins.size();
mNumberOfAxisBins = numberOfAxisBins;
mBin2KnotMapOffset = mNumberOfKnots * sizeof(IrregularSpline1D::Knot);
FlatObject::finishConstruction(mBin2KnotMapOffset + (numberOfAxisBins + 1) * sizeof(int));
IrregularSpline1D::Knot* s = getKnotsNonConst();
for (int i = 0; i < mNumberOfKnots; i++) {
s[i].u = vKnotBins[i] / ((double)mNumberOfAxisBins); // do division in double
}
{ // values will not be used, we define them for consistency
int i = 0;
double du = (s[i + 1].u - s[i].u);
double x3 = (s[i + 2].u - s[i].u) / du;
s[i].scale = 1. / du;
s[i].scaleL0 = 0.; // undefined
s[i].scaleL2 = 0.; // undefined
s[i].scaleR2 = (x3 - 2.) / (x3 - 1.);
s[i].scaleR3 = 1. / (x3 * (x3 - 1.));
}
for (int i = 1; i < mNumberOfKnots - 2; i++) {
double du = (s[i + 1].u - s[i].u);
double x0 = (s[i - 1].u - s[i].u) / du;
double x3 = (s[i + 2].u - s[i].u) / du;
s[i].scale = 1. / du;
s[i].scaleL0 = -1. / (x0 * (x0 - 1.));
s[i].scaleL2 = x0 / (x0 - 1.);
s[i].scaleR2 = (x3 - 2.) / (x3 - 1.);
s[i].scaleR3 = 1. / (x3 * (x3 - 1.));
}
{ // values will not be used, we define them for consistency
int i = mNumberOfKnots - 2;
double du = (s[i + 1].u - s[i].u);
double x0 = (s[i - 1].u - s[i].u) / du;
s[i].scale = 1. / du;
s[i].scaleL0 = -1. / (x0 * (x0 - 1.));
s[i].scaleL2 = x0 / (x0 - 1.);
s[i].scaleR2 = 0; // undefined
s[i].scaleR3 = 0; // undefined
}
{ // values will not be used, we define them for consistency
int i = mNumberOfKnots - 1;
s[i].scale = 0; // undefined
s[i].scaleL0 = 0; // undefined
s[i].scaleL2 = 0; // undefined
s[i].scaleR2 = 0; // undefined
s[i].scaleR3 = 0; // undefined
}
// Set up map (U bin) -> (knot index)
int* map = getBin2KnotMapNonConst();
int iKnotMin = 1;
int iKnotMax = mNumberOfKnots - 3;
//
// With iKnotMin=1, iKnotMax=nKnots-3 we release edge intervals:
//
// Map U coordinates from the first segment [knot0,knot1] to the second segment [knot1,knot2].
// Map coordinates from segment [knot{n-2},knot{n-1}] to the previous segment [knot{n-3},knot{n-4}]
//
// This trick allows one to use splines without special conditions for edge cases.
// Any U from [0,1] is mapped to some knote i, where i-1, i, i+1, and i+2 knots always exist
//
for (int iBin = 0, iKnot = iKnotMin; iBin <= mNumberOfAxisBins; iBin++) {
if ((iKnot < iKnotMax) && vKnotBins[iKnot + 1] == iBin) {
iKnot = iKnot + 1;
}
map[iBin] = iKnot;
}
}
void IrregularSpline1D::constructRegular(int numberOfKnots)
{
/// Constructor for a regular spline
/// \param numberOfKnots Number of knots
///
if (numberOfKnots < 5)
numberOfKnots = 5;
std::vector<float> knots(numberOfKnots);
double du = 1. / (numberOfKnots - 1.);
for (int i = 1; i < numberOfKnots - 1; i++) {
knots[i] = i * du;
}
knots[0] = 0.f;
knots[numberOfKnots - 1] = 1.f;
construct(numberOfKnots, knots.data(), numberOfKnots);
}
void IrregularSpline1D::print() const
{
#if !defined(GPUCA_GPUCODE)
std::cout << " Irregular Spline 1D: " << std::endl;
std::cout << " mNumberOfKnots = " << mNumberOfKnots << std::endl;
std::cout << " mNumberOfAxisBins = " << mNumberOfAxisBins << std::endl;
std::cout << " mBin2KnotMapOffset = " << mBin2KnotMapOffset << std::endl;
std::cout << " knots: ";
for (int i = 0; i < mNumberOfKnots; i++) {
std::cout << getKnot(i).u << " ";
}
std::cout << std::endl;
#endif
}
| 32.9447 | 120 | 0.637292 | [
"object",
"vector"
] |
000c0bf0306ccacdd76e7a05adde976f95c51c15 | 688 | cpp | C++ | Codeforces/div3#481/D.cpp | igortakeo/Solutions-CF | d945f0ae21c691120b69db78ff3d240b7dedc0a7 | [
"MIT"
] | 1 | 2020-05-25T15:32:23.000Z | 2020-05-25T15:32:23.000Z | Codeforces/div3#481/D.cpp | igortakeo/Solutions-CF | d945f0ae21c691120b69db78ff3d240b7dedc0a7 | [
"MIT"
] | null | null | null | Codeforces/div3#481/D.cpp | igortakeo/Solutions-CF | d945f0ae21c691120b69db78ff3d240b7dedc0a7 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define MAX 1000005
using namespace std;
int main(){
int n, ans = MAX;
int c[3] = {-1, 0, 1};
cin >> n;
vector<int>a(n), b(n);
for(int i=0; i<n; i++) cin >> b[i];
for(int i=0; i<3; i++){
a[0] = b[0] + c[i];
for(int j=0; j<3; j++){
a[1] = b[1] + c[j];
int diff = a[1] - a[0];
int cnt = abs(a[0]-b[0]) + abs(a[1]-b[1]);
bool flag = true;
for(int k=2; k<n; k++){
a[k] = a[k-1] + diff;
if(abs(a[k]-b[k]) == 1) cnt++;
else if(abs(a[k]-b[k]) > 1){
flag = false;
break;
}
}
if(flag) ans = min(cnt, ans);
}
}
if(ans == MAX) cout << -1 << endl;
else cout << ans << endl;
return 0;
}
| 15.288889 | 46 | 0.438953 | [
"vector"
] |
000f0c2840e328234f66255783704b45faf96dce | 1,433 | cpp | C++ | Modules/Serialization/Source/Core/BlueprintReader.cpp | larsoad/pargon-framework | 0f616c889c329d66ea89a6358ccb0ce1efe13c41 | [
"MIT"
] | null | null | null | Modules/Serialization/Source/Core/BlueprintReader.cpp | larsoad/pargon-framework | 0f616c889c329d66ea89a6358ccb0ce1efe13c41 | [
"MIT"
] | null | null | null | Modules/Serialization/Source/Core/BlueprintReader.cpp | larsoad/pargon-framework | 0f616c889c329d66ea89a6358ccb0ce1efe13c41 | [
"MIT"
] | null | null | null | #include "Pargon/Serialization/BlueprintReader.h"
using namespace Pargon;
BlueprintReader::BlueprintReader(const Blueprint& blueprint) :
_current(std::addressof(blueprint)),
_currentIndex(0u)
{
}
auto BlueprintReader::ReadBoolean() -> bool
{
return _current->AsBoolean();
}
auto BlueprintReader::ReadInteger() -> long long
{
return _current->AsInteger();
}
auto BlueprintReader::ReadFloatingPoint() -> double
{
return _current->AsFloatingPoint();
}
auto BlueprintReader::ReadString() -> std::string_view
{
return _current->AsStringView();
}
auto BlueprintReader::MoveDown(int index) -> bool
{
auto array = _current->AsList();
if (array == nullptr || array->empty() || index >= array->size())
return false;
_tree.push_back({ _current, _currentIndex });
_current = std::addressof(array->at(index));
_currentIndex = 0u;
return true;
}
auto BlueprintReader::MoveDown(std::string_view name) -> bool
{
auto object = _current->AsMap();
if (object == nullptr || object->empty())
return false;
auto location = object->find(std::string(name)); // PENDING: C++20 has heterogenous lookup.
if (location == object->end())
return false;
_tree.push_back({ _current, _currentIndex });
_current = std::addressof(location->second);
_currentIndex = 0u;
return true;
}
void BlueprintReader::MoveUp()
{
auto parent = _tree.back();
_current = parent.Node;
_currentIndex = parent.Index;
_tree.pop_back();
}
| 19.630137 | 92 | 0.710398 | [
"object"
] |
00101f6135d8f75b1a3d030f46d6c2576906ad0b | 2,517 | cpp | C++ | 2021/Feb/04-feb/Diego_is_the_best_Brazilian_robber.cpp | pdet/cqc | 14d096274d4d3670ba28f3279102fb817ae795be | [
"MIT"
] | 2 | 2020-11-27T12:31:08.000Z | 2021-02-01T07:01:14.000Z | 2021/Feb/04-feb/Diego_is_the_best_Brazilian_robber.cpp | pdet/cqc | 14d096274d4d3670ba28f3279102fb817ae795be | [
"MIT"
] | null | null | null | 2021/Feb/04-feb/Diego_is_the_best_Brazilian_robber.cpp | pdet/cqc | 14d096274d4d3670ba28f3279102fb817ae795be | [
"MIT"
] | 1 | 2020-11-27T19:16:15.000Z | 2020-11-27T19:16:15.000Z | //! You are a professional brazilian planning to rob houses along a street. Each house has a certain amount of money stashed.
//! All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one.
//! Meanwhile, adjacent houses have a security system connected,
//! and it will automatically contact the police if two adjacent houses were broken into on the same night.
//! Given a list of non-negative integers nums representing the amount of money of each house,
//! return the maximum amount of money you can rob tonight without alerting the police.
//! Constraints:
//! 1 <= nums.length <= 100
//! 0 <= nums[i] <= 1000
#include <string>
#include <algorithm>
#include <vector>
#include <cassert>
#include <numeric>
using namespace std;
size_t max_two(std::vector<int> &nums, size_t left, size_t right)
{
// max_a stores the previous max_b f(n-2)
// max_b stores the previous max_sum f(n-1)
// max_c stores the current max_sum f(n)
size_t max_a{0}, max_b{0}, max_c{0};
// current max_sum is either the max_b(f(n-1)) or max_a + current_value(f(n-2) + nums[i]);
for (size_t i = left; i <= right; ++i)
{
max_c = std::max(max_a + nums[i], max_b); //
max_a = max_b;
max_b = max_c;
}
return max_b;
}
// int rob_helper(vector<int>& nums, size_t count, size_t offset) {
// if (offset >= count) {
// return 0;
// }
// int pick;
// if (offset == 0) {
// pick = nums[offset] + rob_helper(nums, count - 1, offset + 2);
// } else {
// pick = nums[offset] + rob_helper(nums, count, offset + 2);
// }
// int skip = rob_helper(nums, count, offset + 1);
// return std::max(pick, skip);
// }
int rob(vector<int> &nums)
{
// return rob_helper(nums, nums.size(), 0);
if (nums.size() <= 1)
{
return std::accumulate(nums.begin(), nums.end(), 0);
}
int consider_first = max_two(nums, 0, nums.size() - 2);
int skip_first = max_two(nums, 1, nums.size() - 1);
return std::max(consider_first, skip_first);
}
int main()
{
//! Matheus cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
vector<int> test1 = {2, 3, 2};
assert(rob(test1) == 3);
//! Diego robs house 1 (money = 1) and then robs house 3 (money = 3).
vector<int> test2 = {1, 2, 3, 1};
assert(rob(test2) == 4);
//! As just an honorary brazilian, Mark sucks at robbing and jumps in an empty house
vector<int> test3 = {0};
assert(rob(test3) == 0);
vector<int> test4 = {1, 1, 10, 1, 10};
assert(rob(test4) == 20);
}
| 30.695122 | 125 | 0.653159 | [
"vector"
] |
001297687e1b6ff47d52684290804dfe4b5632fa | 3,256 | cpp | C++ | example/draw/draw.cpp | bigno78/drag | a7fc1ff77a0e743bbe9a9e72a310a015f6f3b098 | [
"BSD-3-Clause"
] | 3 | 2020-07-29T19:38:51.000Z | 2022-01-28T05:13:55.000Z | example/draw/draw.cpp | bigno78/drag | a7fc1ff77a0e743bbe9a9e72a310a015f6f3b098 | [
"BSD-3-Clause"
] | 2 | 2020-09-05T19:59:15.000Z | 2021-12-05T20:50:41.000Z | example/draw/draw.cpp | bigno78/drag | a7fc1ff77a0e743bbe9a9e72a310a015f6f3b098 | [
"BSD-3-Clause"
] | 2 | 2020-07-29T19:44:52.000Z | 2022-01-28T05:13:59.000Z | #include "parser.hpp"
#include <drag/drag.hpp>
#include <drag/drawing/draw.hpp>
#include <iostream>
#include <string>
#include <string_view>
#include <filesystem>
namespace fs = std::filesystem;
/**
* Return all regular files in the specified directory with the given extension.
*
* The names don't contain the directory path.
* If no extension or an empty extension is given, returns all regular files.
*
* @param path the path to the directory
* @param file_extension the extension to search for
*
* @return all files in the directory with the given extension
*/
std::vector<fs::path> dir_contents(const fs::path& dir_path, const std::string file_extension="") {
std::vector<fs::path> contents;
for (const auto& entry : std::filesystem::directory_iterator(dir_path)) {
if (entry.is_regular_file()) {
if (file_extension == "" || entry.path().extension() == file_extension) {
contents.push_back( entry.path() );
}
}
}
return contents;
}
float to_pt(float x) {
return x*72;
}
void draw_graph(const fs::path& input_path, const fs::path& output_path, bool convert_to_pt) {
drag::drawing_options opts;
drag::graph g = drag::parse(input_path.string(), opts);
if (convert_to_pt) {
g.node_size = to_pt(g.node_size);
g.node_dist = to_pt(g.node_dist);
g.layer_dist = to_pt(g.layer_dist);
g.loop_size = to_pt(g.loop_size);
}
auto image = drag::draw_svg_image(g, opts);
image.save(output_path.string());
}
std::string usage_string =
R"(Create an SVG image of a graph or a set of graphs.
USAGE: ./draw [ options ] -d <input_dir> <output_dir>
./draw [ options ] <input_file> <output_file>
OPTIONS:
-d Draw all .gv files in the input directory to the output directory.
-i Interpret the sizes as inches (for compatibility with dot).
The default unit are points (pt).
)";
void print_help() {
std::cout << usage_string;
}
int main(int argc, char **argv) {
std::vector< std::string_view > args;
for (int i = 1; i < argc; ++i) {
args.emplace_back(argv[i]);
}
argc--;
if (argc > 0 && (args.front() == "-h" || args.front() == "--help")) {
std::cout << usage_string;
return 0;
}
if (argc < 2) {
std::cerr << "Not enough arguments.\n\n";
std::cerr << usage_string;
}
fs::path input(args[argc - 2]);
fs::path output(args[argc - 1]);
bool dir_input = false;
bool inches = false;
for (int i = 0; i < argc - 2; ++i) {
auto arg = args[i];
if (arg == "-h" | arg == "--help") {
std::cout << usage_string;
return 0;
} else if (arg == "-d") {
dir_input = true;
} else if (arg == "-i") {
inches = true;
} else {
std::cerr << "Uknown option: '" << arg << "'\n\n";
std::cerr << usage_string;
}
}
if (dir_input) {
for (auto& f : dir_contents(input, ".gv")) {
auto out_file = f.filename().replace_extension(".svg");
draw_graph(f, output/out_file, inches);
}
} else {
draw_graph(input, output, inches);
}
return 0;
}
| 25.84127 | 99 | 0.582617 | [
"vector"
] |
0016e96ba27b48c4b569453f6b6c78f305e23497 | 24,413 | cpp | C++ | Source/AnimAssistantLib/Private/AnimAssistantLibBPLibrary.cpp | wuguyannian/AnimAssistant | 3aec90344795d1c5bc21c644ddd09e2f958276f5 | [
"MIT"
] | 2 | 2021-03-26T12:43:20.000Z | 2021-11-03T07:18:29.000Z | Source/AnimAssistantLib/Private/AnimAssistantLibBPLibrary.cpp | wuguyannian/AnimAssistant | 3aec90344795d1c5bc21c644ddd09e2f958276f5 | [
"MIT"
] | null | null | null | Source/AnimAssistantLib/Private/AnimAssistantLibBPLibrary.cpp | wuguyannian/AnimAssistant | 3aec90344795d1c5bc21c644ddd09e2f958276f5 | [
"MIT"
] | 5 | 2021-03-28T20:49:48.000Z | 2022-03-13T09:57:51.000Z | // Copyright (C) 2021 Wuguyannian - All Rights Reserved
#include "AnimAssistantLibBPLibrary.h"
#include "AnimAssistantLib.h"
#include "Animation/Skeleton.h"
#include "Serialization/ArchiveReplaceObjectRef.h"
#include "Animation/AnimationAsset.h"
#include "Animation/AnimSequence.h"
#include "Animation/AnimBlueprint.h"
#include "Animation/AnimBlueprintGeneratedClass.h"
#include "EditorAnimUtils.h"
#include "ObjectEditorUtils.h"
#include "AssetToolsModule.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "Kismet2/KismetEditorUtilities.h"
#include "Framework/Notifications/NotificationManager.h"
#include "ObjectEditorUtils.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "IContentBrowserSingleton.h"
#include "ContentBrowserModule.h"
#include "Subsystems/AssetEditorSubsystem.h"
#include "Editor.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"
#define LOCTEXT_NAMESPACE "AnimAssistantLib"
DEFINE_LOG_CATEGORY_STATIC(LogAnimAssistantLib, Log, All);
UAnimAssistantLibBPLibrary::UAnimAssistantLibBPLibrary(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
void UAnimAssistantLibBPLibrary::PrintVirtualBone(class USkeleton* Skeleton)
{
if (Skeleton)
{
const int32 NumVirtualBones = Skeleton->GetVirtualBones().Num();
if (NumVirtualBones > 0)
{
for (int32 VBIndex = 0; VBIndex < NumVirtualBones; ++VBIndex)
{
const FVirtualBone& Bone = Skeleton->GetVirtualBones()[VBIndex];
UE_LOG(LogAnimAssistantLib, Display, TEXT("Virtual Bone [%s] SourceBone [%s] TargetBone [%s]"),
*Bone.VirtualBoneName.ToString(), *Bone.SourceBoneName.ToString(), *Bone.TargetBoneName.ToString());
}
}
else
{
UE_LOG(LogAnimAssistantLib, Display, TEXT("Skeleton [%s] Has no Virtual Bone"), *Skeleton->GetName());
}
}
}
/** Helper archive class to find all references, used by the cycle finder **/
class FFindAnimAssetRefs : public FArchiveUObject
{
public:
/**
* Constructor
*
* @param Src the object to serialize which may contain a references
*/
FFindAnimAssetRefs(UObject* Src, TArray<UAnimationAsset*>& OutAnimationAssets) : AnimationAssets(OutAnimationAssets)
{
// use the optimized RefLink to skip over properties which don't contain object references
ArIsObjectReferenceCollector = true;
ArIgnoreArchetypeRef = false;
ArIgnoreOuterRef = true;
ArIgnoreClassRef = false;
Src->Serialize(*this);
}
virtual FString GetArchiveName() const { return TEXT("FFindAnimAssetRefs"); }
private:
/** Serialize a reference **/
FArchive& operator<<(class UObject*& Obj)
{
if (UAnimationAsset* Anim = Cast<UAnimationAsset>(Obj))
{
AnimationAssets.AddUnique(Anim);
}
return *this;
}
TArray<UAnimationAsset*>& AnimationAssets;
};
void GetAllAnimationSequencesReferredInBlueprint(UAnimBlueprint* AnimBlueprint, TArray<UAnimationAsset*>& AnimationAssets)
{
UObject* DefaultObject = AnimBlueprint->GetAnimBlueprintGeneratedClass()->GetDefaultObject();
FFindAnimAssetRefs AnimRefFinderObject(DefaultObject, AnimationAssets);
// For assets referenced in the event graph (either pin default values or variable-get nodes)
// we need to serialize the nodes in that graph
for (UEdGraph* GraphPage : AnimBlueprint->UbergraphPages)
{
for (UEdGraphNode* Node : GraphPage->Nodes)
{
FFindAnimAssetRefs AnimRefFinderBlueprint(Node, AnimationAssets);
}
}
// Gather references in functions
for (UEdGraph* GraphPage : AnimBlueprint->FunctionGraphs)
{
for (UEdGraphNode* Node : GraphPage->Nodes)
{
FFindAnimAssetRefs AnimRefFinderBlueprint(Node, AnimationAssets);
}
}
}
//////////////////////////////////////////////////////////////////
// FAnimationRetargetContext
struct FNameDuplicationRule
{
FString Prefix;
FString Suffix;
// replace string
FString ReplaceFrom;
FString ReplaceTo;
// folder path
FString FolderPath;
FNameDuplicationRule()
: Prefix(), Suffix(), ReplaceFrom(), ReplaceTo(), FolderPath(TEXT("/Game"))
{}
bool ShouldRename()
{
// should be able to replace "XXX" to ""
return (!Prefix.IsEmpty() || !Suffix.IsEmpty() || !ReplaceFrom.IsEmpty());
}
FString Rename(const UObject* Asset) const;
};
FString FNameDuplicationRule::Rename(const UObject* Asset) const
{
check(Asset);
FString NewName = Asset->GetName();
NewName = NewName.Replace(*ReplaceFrom, *ReplaceTo);
return FString::Printf(TEXT("%s%s%s"), *Prefix, *NewName, *Suffix);
}
class FAnimationRetargetContext
{
public:
FAnimationRetargetContext(const TArray<FAssetData>& AssetsToRetarget, bool bRetargetReferredAssets, bool bInConvertAnimationDataInComponentSpaces, const FNameDuplicationRule& NameRule = FNameDuplicationRule());
FAnimationRetargetContext(TArray<TWeakObjectPtr<UObject>> AssetsToRetarget, bool bRetargetReferredAssets, bool bInConvertAnimationDataInComponentSpaces, const FNameDuplicationRule& NameRule = FNameDuplicationRule());
/** Were we supplied anything that we can retarget */
bool HasAssetsToRetarget() const;
/** Did we duplicate any assets */
bool HasDuplicates() const;
/** Returns the UObject that was chosen to retarget if there was only one in the first place */
UObject* GetSingleTargetObject() const;
/** Returns the duplicate of the supplied object if there is one, otherwise NULL */
UObject* GetDuplicate(const UObject* OriginalObject) const;
/** return all duplicates */
TArray<UObject*> GetAllDuplicates() const;
/** Duplicates the assets stored for retargetting, populating maps of original assets to new asset */
void DuplicateAssetsToRetarget(UPackage* DestinationPackage, const FNameDuplicationRule* NameRule);
/** Retarget the contained assets */
void RetargetAnimations(USkeleton* OldSkeleton, USkeleton* NewSkeleton);
void AddRemappedAsset(UAnimationAsset* OriginalAsset, UAnimationAsset* NewAsset);
private:
/** Lists of assets to retarget. Populated from FAssetData supplied to constructor */
TArray<UAnimationAsset*> AnimationAssetsToRetarget;
TArray<UAnimBlueprint*> AnimBlueprintsToRetarget;
/** Lists of original assets map to duplicate assets */
TMap<UAnimationAsset*, UAnimationAsset*> DuplicatedAnimAssets;
TMap<UAnimBlueprint*, UAnimBlueprint*> DuplicatedBlueprints;
TMap<UAnimationAsset*, UAnimationAsset*> RemappedAnimAssets;
/** If we only chose one object to retarget store it here */
UObject* SingleTargetObject;
/** whether to convert animation data in component spaces */
bool bConvertAnimationDataInComponentSpaces;
/** Initialize the object, only to be called by constructors */
void Initialize(TArray<TWeakObjectPtr<UObject>> AssetsToRetarget, bool bRetargetReferredAssets);
};
FAnimationRetargetContext::FAnimationRetargetContext(const TArray<FAssetData>& AssetsToRetarget, bool bRetargetReferredAssets, bool bInConvertAnimationDataInComponentSpaces, const FNameDuplicationRule& NameRule)
: SingleTargetObject(NULL)
, bConvertAnimationDataInComponentSpaces(bInConvertAnimationDataInComponentSpaces)
{
TArray<UObject*> Objects;
for (auto Iter = AssetsToRetarget.CreateConstIterator(); Iter; ++Iter)
{
Objects.Add((*Iter).GetAsset());
}
auto WeakObjectList = FObjectEditorUtils::GetTypedWeakObjectPtrs<UObject>(Objects);
Initialize(WeakObjectList, bRetargetReferredAssets);
}
FAnimationRetargetContext::FAnimationRetargetContext(TArray<TWeakObjectPtr<UObject>> AssetsToRetarget, bool bRetargetReferredAssets, bool bInConvertAnimationDataInComponentSpaces, const FNameDuplicationRule& NameRule)
: SingleTargetObject(NULL)
, bConvertAnimationDataInComponentSpaces(bInConvertAnimationDataInComponentSpaces)
{
Initialize(AssetsToRetarget, bRetargetReferredAssets);
}
void FAnimationRetargetContext::Initialize(TArray<TWeakObjectPtr<UObject>> AssetsToRetarget, bool bRetargetReferredAssets)
{
for (auto Iter = AssetsToRetarget.CreateConstIterator(); Iter; ++Iter)
{
UObject* Asset = (*Iter).Get();
if (UAnimationAsset* AnimAsset = Cast<UAnimationAsset>(Asset))
{
AnimationAssetsToRetarget.AddUnique(AnimAsset);
}
else if (UAnimBlueprint* AnimBlueprint = Cast<UAnimBlueprint>(Asset))
{
// Add parents blueprint.
UAnimBlueprint* ParentBP = Cast<UAnimBlueprint>(AnimBlueprint->ParentClass->ClassGeneratedBy);
while (ParentBP)
{
AnimBlueprintsToRetarget.AddUnique(ParentBP);
ParentBP = Cast<UAnimBlueprint>(ParentBP->ParentClass->ClassGeneratedBy);
}
AnimBlueprintsToRetarget.AddUnique(AnimBlueprint);
}
}
if (AssetsToRetarget.Num() == 1)
{
//Only chose one object to retarget, keep track of it
SingleTargetObject = AssetsToRetarget[0].Get();
}
if (bRetargetReferredAssets)
{
// Grab assets from the blueprint. Do this first as it can add complex assets to the retarget array
// which will need to be processed next.
for (auto Iter = AnimBlueprintsToRetarget.CreateConstIterator(); Iter; ++Iter)
{
GetAllAnimationSequencesReferredInBlueprint((*Iter), AnimationAssetsToRetarget);
}
int32 AssetIndex = 0;
while (AssetIndex < AnimationAssetsToRetarget.Num())
{
UAnimationAsset* AnimAsset = AnimationAssetsToRetarget[AssetIndex++];
AnimAsset->HandleAnimReferenceCollection(AnimationAssetsToRetarget, true);
}
}
}
bool FAnimationRetargetContext::HasAssetsToRetarget() const
{
return AnimationAssetsToRetarget.Num() > 0 ||
AnimBlueprintsToRetarget.Num() > 0;
}
bool FAnimationRetargetContext::HasDuplicates() const
{
return DuplicatedAnimAssets.Num() > 0 ||
DuplicatedBlueprints.Num() > 0;
}
TArray<UObject*> FAnimationRetargetContext::GetAllDuplicates() const
{
TArray<UObject*> Duplicates;
if (AnimationAssetsToRetarget.Num() > 0)
{
Duplicates.Append(AnimationAssetsToRetarget);
}
if (AnimBlueprintsToRetarget.Num() > 0)
{
Duplicates.Append(AnimBlueprintsToRetarget);
}
return Duplicates;
}
UObject* FAnimationRetargetContext::GetSingleTargetObject() const
{
return SingleTargetObject;
}
UObject* FAnimationRetargetContext::GetDuplicate(const UObject* OriginalObject) const
{
if (HasDuplicates())
{
if (const UAnimationAsset* Asset = Cast<const UAnimationAsset>(OriginalObject))
{
if (DuplicatedAnimAssets.Contains(Asset))
{
return DuplicatedAnimAssets.FindRef(Asset);
}
}
if (const UAnimBlueprint* AnimBlueprint = Cast<const UAnimBlueprint>(OriginalObject))
{
if (DuplicatedBlueprints.Contains(AnimBlueprint))
{
return DuplicatedBlueprints.FindRef(AnimBlueprint);
}
}
}
return NULL;
}
FString CreateDesiredName(UObject* Asset, const FNameDuplicationRule* NameRule)
{
check(Asset);
FString NewName = Asset->GetName();
if (NameRule)
{
NewName = NameRule->Rename(Asset);
}
return NewName;
}
TMap<UObject*, UObject*> DuplicateAssetsInternal(const TArray<UObject*>& AssetsToDuplicate, UPackage* DestinationPackage, const FNameDuplicationRule* NameRule)
{
FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
TMap<UObject*, UObject*> DuplicateMap;
for (auto Iter = AssetsToDuplicate.CreateConstIterator(); Iter; ++Iter)
{
UObject* Asset = (*Iter);
if (!DuplicateMap.Contains(Asset))
{
FString PathName = (NameRule) ? NameRule->FolderPath : FPackageName::GetLongPackagePath(DestinationPackage->GetName());
FString ObjectName;
FString NewPackageName;
AssetToolsModule.Get().CreateUniqueAssetName(PathName + "/" + CreateDesiredName(Asset, NameRule), TEXT(""), NewPackageName, ObjectName);
// create one on skeleton folder
UObject* NewAsset = AssetToolsModule.Get().DuplicateAsset(ObjectName, PathName, Asset);
if (NewAsset)
{
DuplicateMap.Add(Asset, NewAsset);
}
}
}
return DuplicateMap;
}
/**
* Duplicates the supplied AssetsToDuplicate and returns a map of original asset to duplicate. Templated wrapper that calls DuplicateAssetInternal.
*
* @param AssetsToDuplicate The animations to duplicate
* @param DestinationPackage The package that the duplicates should be placed in
*
* @return TMap of original animation to duplicate
*/
template<class AssetType>
TMap<AssetType*, AssetType*> DuplicateAssets(const TArray<AssetType*>& AssetsToDuplicate, UPackage* DestinationPackage, const FNameDuplicationRule* NameRule)
{
TArray<UObject*> Assets;
for (auto Iter = AssetsToDuplicate.CreateConstIterator(); Iter; ++Iter)
{
Assets.Add(*Iter);
}
TMap<UObject*, UObject*> AssetMap = DuplicateAssetsInternal(Assets, DestinationPackage, NameRule);
TMap<AssetType*, AssetType*> ReturnMap;
for (auto Iter = AssetMap.CreateIterator(); Iter; ++Iter)
{
ReturnMap.Add(Cast<AssetType>(Iter->Key), Cast<AssetType>(Iter->Value));
}
return ReturnMap;
}
void FAnimationRetargetContext::DuplicateAssetsToRetarget(UPackage* DestinationPackage, const FNameDuplicationRule* NameRule)
{
if (!HasDuplicates())
{
TArray<UAnimationAsset*> AnimationAssetsToDuplicate = AnimationAssetsToRetarget;
TArray<UAnimBlueprint*> AnimBlueprintsToDuplicate = AnimBlueprintsToRetarget;
// We only want to duplicate unmapped assets, so we remove mapped assets from the list we're duplicating
for (TPair<UAnimationAsset*, UAnimationAsset*>& Pair : RemappedAnimAssets)
{
AnimationAssetsToDuplicate.Remove(Pair.Key);
}
DuplicatedAnimAssets = DuplicateAssets<UAnimationAsset>(AnimationAssetsToDuplicate, DestinationPackage, NameRule);
DuplicatedBlueprints = DuplicateAssets<UAnimBlueprint>(AnimBlueprintsToDuplicate, DestinationPackage, NameRule);
// Remapped assets needs the duplicated ones added
RemappedAnimAssets.Append(DuplicatedAnimAssets);
DuplicatedAnimAssets.GenerateValueArray(AnimationAssetsToRetarget);
DuplicatedBlueprints.GenerateValueArray(AnimBlueprintsToRetarget);
}
}
void ReplaceReferredAnimationsInBlueprint(UAnimBlueprint* AnimBlueprint, const TMap<UAnimationAsset*, UAnimationAsset*>& AnimAssetReplacementMap)
{
UObject* DefaultObject = AnimBlueprint->GetAnimBlueprintGeneratedClass()->GetDefaultObject();
FArchiveReplaceObjectRef<UAnimationAsset> ReplaceAr(DefaultObject, AnimAssetReplacementMap, false, false, false);//bNullPrivateRefs, bIgnoreOuterRef, bIgnoreArchetypeRef);
FArchiveReplaceObjectRef<UAnimationAsset> ReplaceAr2(AnimBlueprint, AnimAssetReplacementMap, false, false, false);//bNullPrivateRefs, bIgnoreOuterRef, bIgnoreArchetypeRef);
// Replace event graph references
for (UEdGraph* GraphPage : AnimBlueprint->UbergraphPages)
{
for (UEdGraphNode* Node : GraphPage->Nodes)
{
FArchiveReplaceObjectRef<UAnimationAsset> ReplaceGraphAr(Node, AnimAssetReplacementMap, false, false, false);
}
}
// Replace references in functions
for (UEdGraph* GraphPage : AnimBlueprint->FunctionGraphs)
{
for (UEdGraphNode* Node : GraphPage->Nodes)
{
FArchiveReplaceObjectRef<UAnimationAsset> ReplaceGraphAr(Node, AnimAssetReplacementMap, false, false, false);
}
}
}
void FAnimationRetargetContext::RetargetAnimations(USkeleton* OldSkeleton, USkeleton* NewSkeleton)
{
check(!bConvertAnimationDataInComponentSpaces || OldSkeleton);
check(NewSkeleton);
if (bConvertAnimationDataInComponentSpaces)
{
// we need to update reference pose before retargeting.
// this is to ensure the skeleton has the latest pose you're looking at.
USkeletalMesh* PreviewMesh = NULL;
if (OldSkeleton != NULL)
{
PreviewMesh = OldSkeleton->GetPreviewMesh(true);
if (PreviewMesh)
{
OldSkeleton->UpdateReferencePoseFromMesh(PreviewMesh);
}
}
PreviewMesh = NewSkeleton->GetPreviewMesh(true);
if (PreviewMesh)
{
NewSkeleton->UpdateReferencePoseFromMesh(PreviewMesh);
}
}
// anim sequences will be retargeted first becauseReplaceSkeleton forces it to change skeleton
// @todo: please note that I think we can merge two loops
//(without separating two loops - one for AnimSequence and one for everybody else)
// but if you have animation asssets that does replace skeleton, it will try fix up internal asset also
// so I think you might be doing twice - look at AnimationAsset:ReplaceSkeleton
// for safety, I'm doing Sequence first and then everything else
// however this can be re-investigated and fixed better in the future
for (auto Iter = AnimationAssetsToRetarget.CreateIterator(); Iter; ++Iter)
{
UAnimSequence* AnimSequenceToRetarget = Cast<UAnimSequence>(*Iter);
if (AnimSequenceToRetarget)
{
// Copy curve data from source asset, preserving data in the target if present.
if (OldSkeleton)
{
EditorAnimUtils::CopyAnimCurves(OldSkeleton, NewSkeleton, AnimSequenceToRetarget, USkeleton::AnimCurveMappingName, ERawCurveTrackTypes::RCT_Float);
// clear transform curves since those curves won't work in new skeleton
// since we're deleting curves, mark this rebake flag off
AnimSequenceToRetarget->RawCurveData.TransformCurves.Empty();
AnimSequenceToRetarget->bNeedsRebake = false;
// I can't copy transform curves yet because transform curves need retargeting.
//EditorAnimUtils::CopyAnimCurves(OldSkeleton, NewSkeleton, AssetToRetarget, USkeleton::AnimTrackCurveMappingName, FRawCurveTracks::TransformType);
}
}
}
for (auto Iter = AnimationAssetsToRetarget.CreateIterator(); Iter; ++Iter)
{
UAnimationAsset* AssetToRetarget = (*Iter);
if (HasDuplicates())
{
AssetToRetarget->ReplaceReferredAnimations(RemappedAnimAssets);
}
AssetToRetarget->ReplaceSkeleton(NewSkeleton, bConvertAnimationDataInComponentSpaces);
AssetToRetarget->MarkPackageDirty();
}
// convert all Animation Blueprints and compile
for (auto AnimBPIter = AnimBlueprintsToRetarget.CreateIterator(); AnimBPIter; ++AnimBPIter)
{
UAnimBlueprint* AnimBlueprint = (*AnimBPIter);
AnimBlueprint->TargetSkeleton = NewSkeleton;
if (HasDuplicates())
{
// if they have parent blueprint, make sure to re-link to the new one also
UAnimBlueprint* CurrentParentBP = Cast<UAnimBlueprint>(AnimBlueprint->ParentClass->ClassGeneratedBy);
if (CurrentParentBP)
{
UAnimBlueprint* const* ParentBP = DuplicatedBlueprints.Find(CurrentParentBP);
if (ParentBP)
{
AnimBlueprint->ParentClass = (*ParentBP)->GeneratedClass;
}
}
}
if (RemappedAnimAssets.Num() > 0)
{
ReplaceReferredAnimationsInBlueprint(AnimBlueprint, RemappedAnimAssets);
}
FBlueprintEditorUtils::RefreshAllNodes(AnimBlueprint);
FKismetEditorUtilities::CompileBlueprint(AnimBlueprint, EBlueprintCompileOptions::SkipGarbageCollection);
AnimBlueprint->PostEditChange();
AnimBlueprint->MarkPackageDirty();
}
}
void FAnimationRetargetContext::AddRemappedAsset(UAnimationAsset* OriginalAsset, UAnimationAsset* NewAsset)
{
RemappedAnimAssets.Add(OriginalAsset, NewAsset);
}
void OpenAssetFromNotify(UObject* AssetToOpen)
{
GEditor->GetEditorSubsystem<UAssetEditorSubsystem>()->OpenEditorForAsset(AssetToOpen);
}
//////////////////////////////////////////////////////////////////
UObject* RetargetAnimations(USkeleton* OldSkeleton, USkeleton* NewSkeleton, FAnimationRetargetContext& RetargetContext, bool bRetargetReferredAssets, const FNameDuplicationRule* NameRule)
{
check(NewSkeleton);
UObject* OriginalObject = RetargetContext.GetSingleTargetObject();
UPackage* DuplicationDestPackage = NewSkeleton->GetOutermost();
if (RetargetContext.HasAssetsToRetarget())
{
if (NameRule)
{
RetargetContext.DuplicateAssetsToRetarget(DuplicationDestPackage, NameRule);
}
RetargetContext.RetargetAnimations(OldSkeleton, NewSkeleton);
}
FNotificationInfo Notification(FText::GetEmpty());
Notification.ExpireDuration = 5.f;
UObject* NotifyLinkObject = OriginalObject;
if (OriginalObject && NameRule)
{
NotifyLinkObject = RetargetContext.GetDuplicate(OriginalObject);
}
if (!NameRule)
{
if (OriginalObject)
{
Notification.Text = FText::Format(LOCTEXT("SingleNonDuplicatedAsset", "'{0}' retargeted to new skeleton '{1}'"), FText::FromString(OriginalObject->GetName()), FText::FromString(NewSkeleton->GetName()));
}
else
{
Notification.Text = FText::Format(LOCTEXT("MultiNonDuplicatedAsset", "Assets retargeted to new skeleton '{0}'"), FText::FromString(NewSkeleton->GetName()));
}
}
else
{
if (OriginalObject)
{
Notification.Text = FText::Format(LOCTEXT("SingleDuplicatedAsset", "'{0}' duplicated to '{1}' and retargeted"), FText::FromString(OriginalObject->GetName()), FText::FromString(DuplicationDestPackage->GetName()));
}
else
{
Notification.Text = FText::Format(LOCTEXT("MultiDuplicatedAsset", "Assets duplicated to '{0}' and retargeted"), FText::FromString(DuplicationDestPackage->GetName()));
}
}
if (NotifyLinkObject)
{
Notification.Hyperlink = FSimpleDelegate::CreateStatic(&OpenAssetFromNotify, NotifyLinkObject);
Notification.HyperlinkText = LOCTEXT("OpenAssetLink", "Open");
}
FSlateNotificationManager::Get().AddNotification(Notification);
// sync newly created objects on CB
if (NotifyLinkObject)
{
TArray<UObject*> NewObjects = RetargetContext.GetAllDuplicates();
TArray<FAssetData> CurrentSelection;
for (auto& NewObject : NewObjects)
{
CurrentSelection.Add(FAssetData(NewObject));
}
FContentBrowserModule& ContentBrowserModule = FModuleManager::Get().LoadModuleChecked<FContentBrowserModule>("ContentBrowser");
ContentBrowserModule.Get().SyncBrowserToAssets(CurrentSelection);
}
if (OriginalObject && NameRule)
{
return RetargetContext.GetDuplicate(OriginalObject);
}
return NULL;
}
void UAnimAssistantLibBPLibrary::RetargetAnim(class USkeleton* Source, USkeleton* Dest, class UAnimBlueprint* AnimBP, const FString FolderPath)
{
if (Source && Dest && AnimBP)
{
FNameDuplicationRule NameRule;
NameRule.FolderPath = FolderPath;
TArray<TWeakObjectPtr<UObject>> InAnimAssets;
InAnimAssets.Add(AnimBP);
FAnimationRetargetContext RetargetContext(InAnimAssets, true, true);
RetargetAnimations(Source, Dest, RetargetContext, true, &NameRule);
}
}
void UAnimAssistantLibBPLibrary::CreateVirtualBone(USkeleton* Dest, FString JsonBoneList)
{
static const FString KeyBoneName = "BoneName";
static const FString KeySourceName = "SourceBone";
static const FString KeyTargetName = "TargetBone";
const TSharedRef< TJsonReader<> >& Reader = TJsonReaderFactory<>::Create(JsonBoneList);
TSharedPtr<FJsonObject> RootObject;
if (FJsonSerializer::Deserialize(Reader, /*out*/ RootObject) && RootObject.IsValid())
{
const TArray< TSharedPtr<FJsonValue> >* BoneList;
if (RootObject->TryGetArrayField(TEXT("BoneList"), BoneList))
{
uint32 IndexBone = 0;
for (TSharedPtr<FJsonValue> Bone : *BoneList)
{
TSharedPtr<FJsonObject> BoneObj = Bone->AsObject();
IndexBone++;
if (!BoneObj->HasField(KeyBoneName))
{
UE_LOG(LogAnimAssistantLib, Warning, TEXT("Bone[%d] No KeyWord: %s"), IndexBone, *KeyBoneName);
continue;
}
if (!BoneObj->HasField(KeySourceName))
{
UE_LOG(LogAnimAssistantLib, Warning, TEXT("Bone[%d] No KeyWord: %s"), IndexBone, *KeySourceName);
continue;
}
if (!BoneObj->HasField(KeyTargetName))
{
UE_LOG(LogAnimAssistantLib, Warning, TEXT("Bone[%d] No KeyWord: %s"), IndexBone, *KeyTargetName);
continue;
}
FName BoneName;
FName SourceName = *BoneObj->GetStringField(KeySourceName);
FName TargetName = *BoneObj->GetStringField(KeyTargetName);
if (!Dest->AddNewVirtualBone(SourceName, TargetName, BoneName))
{
UE_LOG(LogAnimAssistantLib, Warning, TEXT("Bone[%d] Create Failed SourceName[%s] TargetName[%s]"), IndexBone, *BoneName.ToString(), *SourceName.ToString(), *TargetName.ToString());
continue;
}
Dest->RenameVirtualBone(BoneName, *BoneObj->GetStringField(KeyBoneName));
}
}
else
{
UE_LOG(LogAnimAssistantLib, Warning, TEXT("No KeyWord: BoneList"));
}
}
else
{
UE_LOG(LogAnimAssistantLib, Warning, TEXT("Failed to parse Bone List"));
}
} | 34.336146 | 218 | 0.741326 | [
"object",
"transform"
] |
00175e426e5074a931a12c51b33220bc2738d8a3 | 408 | cpp | C++ | source/Ch08/orai_anyag/undef.cpp | Vada200/UDProg-Introduction | c424b2676d6e5bfc4d53d61c5d0deded566c1c84 | [
"CC0-1.0"
] | null | null | null | source/Ch08/orai_anyag/undef.cpp | Vada200/UDProg-Introduction | c424b2676d6e5bfc4d53d61c5d0deded566c1c84 | [
"CC0-1.0"
] | null | null | null | source/Ch08/orai_anyag/undef.cpp | Vada200/UDProg-Introduction | c424b2676d6e5bfc4d53d61c5d0deded566c1c84 | [
"CC0-1.0"
] | null | null | null | #include "std_lib_facilities.h"
void f (int a, int b)
{
cout << a << ' ' << b << endl;
}
int main()
{
vector<int> v (10);
int i = 0;
while (i<9)
v[i] = i++; //kiértékelési sorrend nincs meghatározva c++-ban -> error
for (const auto& e : v)
cout << e << endl;
int x =i++ + i++; //változó érték módosítás --> error
cout << x << endl;
f(++i, ++i);
return 0;
} | 15.692308 | 73 | 0.495098 | [
"vector"
] |
0027f3071874e212effe13803099ab74dde2f3a7 | 8,402 | hpp | C++ | src/ct_icp/odometry.hpp | xiang-1208/ct_icp | 42928e584c24595c49e147e2ea120f8cc31ec716 | [
"MIT"
] | 123 | 2021-10-08T01:51:45.000Z | 2022-03-31T08:55:15.000Z | src/ct_icp/odometry.hpp | ZuoJiaxing/ct_icp | 1c371331aad833faec157c015fb8f72143019caa | [
"MIT"
] | 9 | 2021-10-19T07:25:46.000Z | 2022-03-31T03:20:19.000Z | src/ct_icp/odometry.hpp | ZuoJiaxing/ct_icp | 1c371331aad833faec157c015fb8f72143019caa | [
"MIT"
] | 23 | 2021-10-08T01:49:01.000Z | 2022-03-24T15:35:07.000Z | #ifndef CT_ICP_ODOMETRY_H
#define CT_ICP_ODOMETRY_H
#include "ct_icp.hpp"
#include <map>
namespace ct_icp {
enum MOTION_COMPENSATION {
NONE = 0, // No compensation of the motion
CONSTANT_VELOCITY = 1, // Initial distortion of the point cloud based on the estimated velocity
ITERATIVE = 2, // Iterative refinement after each ICP iteration
CONTINUOUS = 3 // Continuous estimation of the pose
};
enum INITIALIZATION {
INIT_NONE = 0,
INIT_CONSTANT_VELOCITY = 1
};
struct OdometryOptions {
/* Parameters for initialization of the map */
double init_voxel_size = 0.2;
double init_sample_voxel_size = 1.0;
int init_num_frames = 20; // The number of frames defining the initialization of the map
double voxel_size = 0.5;
double sample_voxel_size = 1.5;
double max_distance = 100.0; // The threshold on the voxel size to remove points from the map
int max_num_points_in_voxel = 20; // The maximum number of points in a voxel
double min_distance_points = 0.1; // The minimal distance between points in the map
double distance_error_threshold = 5.0; // The Ego-Motion Distance considered as an error
// Whether to assess the quality of the registration,
// And try a new registration with more conservative parameters in case of failure
int robust_minimal_level = 0;
bool robust_registration = false;
double robust_full_voxel_threshold = 0.7;
double robust_empty_voxel_threshold = 0.1;
double robust_neighborhood_min_dist = 0.10; // The minimum relative distance to launch a robust neighborhood test
double robust_neighborhood_min_orientation = 0.1; // The minimum relative orientation to launch a robust neighborhood
// Threshold on the relative transform (all motion at 10Hz should be below this value)
double robust_relative_trans_threshold = 1.0;
bool robust_fail_early = false; // Stop iterations if the final assessment of the registration is unsucessful
int robust_num_attempts = 6;
int robust_num_attempts_when_rotation = 2;
short robust_max_voxel_neighborhood = 3;
double robust_threshold_ego_orientation = 3; // Angle in degrees
double robust_threshold_relative_orientation = 3; // Angle in degrees
CTICPOptions ct_icp_options;
MOTION_COMPENSATION motion_compensation = CONTINUOUS;
INITIALIZATION initialization = INIT_CONSTANT_VELOCITY;
// Debug Parameters
bool debug_print = true; // Whether to print debug information into the console
bool debug_viz = false; // Whether to display the Local Map in a window
bool log_to_file = false;
std::string log_file_destination = "/tmp/ct_icp.log";
////////////////////////
/// DEFAULT PROFILES ///
////////////////////////
// Returns the default parameters for driving scenarios
// e.g. Used for the dataset KITTI
static OdometryOptions DefaultDrivingProfile();
// Returns the default parameters for sensor with high frequency acceleration changes
// e.g. Used for the dataset NCLT
static OdometryOptions DefaultRobustOutdoorLowInertia();
// Returns the default parameters for a robust Driving Profile
static OdometryOptions RobustDrivingProfile();
// TODO: INDOOR
};
// Add Points To the Map
void AddPointsToMap(VoxelHashMap &map, const std::vector<Point3D> &points,
double voxel_size, int max_num_points_in_voxel,
double min_distance_points, int min_num_points = 0);
// Add Points To the Map
void AddPointsToMap(VoxelHashMap &map, const ArrayVector3d &points, double voxel_size,
int max_num_points_in_voxel, double min_distance_points);
// Remove voxels far from the given location
void RemovePointsFarFromLocation(VoxelHashMap &map, const Eigen::Vector3d &location, double distance);
// Extracts points of the local map into a PointCloud
ArrayVector3d MapAsPointcloud(const VoxelHashMap &map);
// Compute the size of a VoxelHashMap
size_t MapSize(const VoxelHashMap &map);
class Odometry {
public:
// The Output of a registration, including metrics,
struct RegistrationSummary {
TrajectoryFrame frame;
int sample_size = 0; // The number of points sampled
int number_of_residuals = 0; // The number of keypoints used for ICP registration
int robust_level = 0;
double distance_correction = 0.0; // The correction between the last frame's end, and the new frame's beginning
double relative_distance = 0.0; // The distance between the beginning of the new frame and the end
double relative_orientation = 0.0; // The distance between the beginning of the new frame and the end
double ego_orientation = 0.0; // The angular distance between the beginning and the end of the frame
bool success = true; // Whether the registration was a success
int number_of_attempts = 0; // The number of attempts at registering the new frame
std::string error_message;
std::vector<Point3D> corrected_points; // Sampled points expressed in the initial frame
std::vector<Point3D> all_corrected_points; // Initial points expressed in the initial frame
std::vector<Point3D> keypoints; // Last Keypoints selected
};
explicit Odometry(const OdometryOptions &options);
explicit Odometry(const OdometryOptions *options) : Odometry(*options) {}
// Registers a new Frame to the Map
RegistrationSummary RegisterFrame(const std::vector<Point3D> &frame);
// Registers a new Frame to the Map with an initial estimate
RegistrationSummary RegisterFrameWithEstimate(const std::vector<Point3D> &frame,
const TrajectoryFrame &initial_estimate);
// Returns the currently registered trajectory
[[nodiscard]] std::vector<TrajectoryFrame> Trajectory() const;
// Returns the Aggregated PointCloud of the Local Map
[[nodiscard]] ArrayVector3d GetLocalMap() const;
// Num Points in the Map
// Note: This requires a traversal of the whole map which is in O(n)
[[nodiscard]] size_t MapSize() const;
private:
std::vector<TrajectoryFrame> trajectory_;
VoxelHashMap voxel_map_;
int registered_frames_ = 0;
int robust_num_consecutive_failures_ = 0;
bool suspect_registration_error_ = false;
int next_robust_level_ = 0;
OdometryOptions options_;
std::ostream *log_out_ = nullptr;
std::unique_ptr<std::ofstream> log_file_ = nullptr;
// Initialize the Frame
std::vector<Point3D> InitializeFrame(const std::vector<Point3D> &const_frame,
int index_frame);
// Registers a frame after the motion was initialized
// When the Robust Registration profile is activated, it can call TryRegister
// Multiple times changing the options in order to increase the chance of registration
RegistrationSummary DoRegister(const std::vector<Point3D> &frame, int frame_index);
// Tries to register a frame given a set of options
RegistrationSummary TryRegister(std::vector<Point3D> &frame,
int frame_index,
const CTICPOptions &options,
RegistrationSummary ®istration_summary,
double sample_voxel_size);
// Insert a New Trajectory Frame, and initializes the motion for this new frame
int InitializeMotion(const TrajectoryFrame *initial_estimate = nullptr);
// Try to insert Points to the map
// Returns false if it fails
bool AssessRegistration(const std::vector<Point3D> &points, RegistrationSummary &summary,
std::ostream *log_stream = nullptr) const;
};
} // namespace ct_icp
#endif //CT_ICP_ODOMETRY_H
| 40.009524 | 125 | 0.658534 | [
"vector",
"transform"
] |
0030ee8eb048faa7d06d411fc5309e1168b2e54d | 6,625 | cpp | C++ | JPSvisUE/Source/JPSvisUE/Structure/Actors/Building.cpp | Neloress/JPSvisUE | 010d321333979edb76dc8eb20cb8e088f312d3b3 | [
"MIT"
] | null | null | null | JPSvisUE/Source/JPSvisUE/Structure/Actors/Building.cpp | Neloress/JPSvisUE | 010d321333979edb76dc8eb20cb8e088f312d3b3 | [
"MIT"
] | null | null | null | JPSvisUE/Source/JPSvisUE/Structure/Actors/Building.cpp | Neloress/JPSvisUE | 010d321333979edb76dc8eb20cb8e088f312d3b3 | [
"MIT"
] | 2 | 2021-03-30T08:29:07.000Z | 2021-08-04T13:36:34.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "Building.h"
#include "Floor.h"
#include "../Data/Line.h"
#include "FloorStructure.h"
#include "../../Settings/GlobalSettings.h"
#include "../../DataManagment/Cache/CacheEntry.h"
#include "Pedestrian.h"
#include "../../RuntimeControl/FloorPosition.h"
#include "../../RuntimeControl/FramePosition.h"
#include "../../RuntimeControl/AutoPlaySpeed.h"
#include "../../DataManagment/FileReaders/StructureFile/StructureFileReader.h"
// Sets default values
ABuilding::ABuilding()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
m_cacheIsSet = false;
}
// Called when the game starts or when spawned
void ABuilding::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ABuilding::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
GlobalSettings* settings = GlobalSettings::GetInstance();
if (settings->GetStructureFileChanged())
{
LoadStructure();
}
if (settings->GetTrajectoryFileChanged())
{
LoadPedestrians();
}
SetAutoPlayFrame(DeltaTime);
MovePedestrians();
}
void ABuilding::DestroyAll(bool bNetForce, bool bShouldModifyLevel)
{
for (int i = 0; i < m_pedestrians.size(); i++)
{
m_pedestrians.at(i)->DestroyAll(bNetForce, bShouldModifyLevel);
}
for (int i = 0; i < m_floors.size(); i++)
{
m_floors.at(i)->DestroyAll(bNetForce, bShouldModifyLevel);
}
Destroy(bNetForce, bShouldModifyLevel);
}
void ABuilding::SetAutoPlayFrame(float delta)
{
GlobalSettings* settings = GlobalSettings::GetInstance();
if (settings->GetIsAutoPlay())
{
delta = delta * settings->GetAutoPlaySpeed().get()->GetSpeedUpFactor();
settings->GetFramePosition().get()->TimeSensitiveChange(delta);
}
}
void ABuilding::LoadPedestrians()
{
GlobalSettings* settings = GlobalSettings::GetInstance();
m_cache = Cache(settings->GetCacheBitsAssociativeness(), settings->GetCacheBitsIndex(), settings->GetCacheBitsWordOffset(), settings->GetTrajectoryFilePath());
settings->SetTimePerFrame(m_cache.GetFileReader().get()->GetTimePerFrame());
int lastPos = settings->GetFramePosition().get()->GetPosition();
std::shared_ptr<FramePosition> framePosition = std::make_shared<FramePosition>(m_cache.GetFramesCount(), settings->GetTimePerFrame());
framePosition.get()->SetPositionWithClamp(lastPos);
settings->SetFramePosition(framePosition);
for (int i = 0; i < m_pedestrians.size(); i++)
{
m_pedestrians.at(i)->DestroyAll();
}
m_cacheIsSet = true;
}
void ABuilding::LoadStructure()
{
GlobalSettings* settings = GlobalSettings::GetInstance();
std::vector<FloorWithHeight> lines = StructureFileReader::LoadStructure(settings->GetStructureFilePath());
m_floors = SpawnItems<AFloorStructure>(lines.size(), m_floorStructureClass);
for (int i = 0; i < lines.size(); i++)
{
m_floors.at(i)->Init(*lines.at(i).lines.get(), i);
}
std::vector<float> floorHeights = std::vector<float>();
floorHeights.resize(lines.size());
for (int i = 0; i < lines.size(); i++)
{
floorHeights.at(i) = lines.at(i).height;
}
settings->SetFloorHeights(floorHeights);
int lastFloorPosition = settings->GetFloorPosition().get()->GetPosition();
std::shared_ptr<FloorPosition> floorPosition = std::make_shared<FloorPosition>(lines.size());
floorPosition.get()->SetPositionWithClamp(lastFloorPosition);
settings->SetFloorPosition(floorPosition);
}
void ABuilding::MovePedestrians()
{
if (m_cacheIsSet)
{
GlobalSettings* settings = GlobalSettings::GetInstance();
int pos = settings->GetFramePosition().get()->GetPosition();
//pre load forward
for (int i = settings->GetPreFetchCacheForward(); i >= 1; i--)
{
if (settings->GetFramePosition().get()->CheckPositionValid(pos + i))
{
m_cache.LoadCacheEntryAsync(pos + i);
}
}
//pre load backward
for (int i = settings->GetPreFetchCacheBackward(); i >= 1; i--)
{
if (settings->GetFramePosition().get()->CheckPositionValid(pos - i))
{
m_cache.LoadCacheEntryAsync(pos - i);
}
}
float time = (float)pos * settings->GetTimePerFrame();
//load needed value
CacheEntry entry = m_cache.LoadCacheEntrySync(pos);
std::vector<Person> persons = entry.GetPersons();
std::vector<Person> toCreate;
//toDelete
for (int i = 0;i< m_pedestrians.size();i++)
{
bool found = false;
for (int n = 0;n< persons.size();n++)
{
if (persons.at(n).id==m_pedestrians.at(i)->GetID())
{
found = true;
break;
}
}
if (!found)
{
m_pedestrians.at(i)->DestroyAll();
m_pedestrians.erase(m_pedestrians.begin()+i);
i--;
}
}
//toCreate
for (int n = 0;n<persons.size();n++)
{
bool found = false;
for (int i = 0; i < m_pedestrians.size(); i++)
{
if (persons.at(n).id == m_pedestrians.at(i)->GetID())
{
found = true;
break;
}
}
if (!found)
{
toCreate.push_back(persons.at(n));
}
}
//sync
for (int i = 0; i < m_pedestrians.size(); i++)
{
for (int n = 0; n < persons.size(); n++)
{
Person person = persons.at(n);
if (person.id == m_pedestrians.at(i)->GetID())
{
if (GetShouldBeHidden(person.z))
{
m_pedestrians.at(i)->SetActorHiddenInGame(true);
}
else
{
m_pedestrians.at(i)->SetActorHiddenInGame(false);
}
m_pedestrians.at(i)->SetPosition(person, time);
break;
}
}
}
//create
for (int i = 0; i < toCreate.size(); i++)
{
Person person = toCreate.at(i);
APedestrian* pedestrian = SpawnItem<APedestrian>(m_pedestrianClass);
pedestrian->InitVariables(person.id,time,FVector(person.x,person.y,person.z));
pedestrian->SetPosition(person, time);
if (GetShouldBeHidden(person.z))
{
pedestrian->SetVisible();
}
m_pedestrians.push_back(pedestrian);
}
}
}
bool ABuilding::GetShouldBeHidden(float height)
{
GlobalSettings* settings = GlobalSettings::GetInstance();
float minDis = FLT_MAX;
int pos = 0;
for (int i = 0; i < settings->GetFloorHeights().size(); i++)
{
float distance = std::abs(settings->GetFloorHeights().at(i) - height);
if (distance < minDis)
{
minDis = distance;
pos = i;
}
}
int currentFloor = settings->GetFloorPosition().get()->GetPosition();
switch (GlobalSettings::GetInstance()->GetFloorViewType())
{
case FloorViewType::ALL_BELOW_VIEW:
if (pos <= currentFloor)
{
return false;
}
break;
case FloorViewType::ALL_VIEW:
return false;
break;
case FloorViewType::ONLY_VIEW:
if (pos == currentFloor)
{
return false;
}
break;
default:
break;
}
return true;
}
| 26.185771 | 160 | 0.68166 | [
"vector"
] |
0034bc3f9abad3661c74aa668cd490e2c462a4ce | 1,741 | cpp | C++ | days/Day07.cpp | willkill07/AdventOfCode2021 | 06e62cd8a8c7f1e99374075b7302f6dcfb770bb0 | [
"Apache-2.0"
] | 12 | 2021-12-02T01:44:53.000Z | 2022-02-02T17:22:23.000Z | days/Day07.cpp | willkill07/AdventOfCode2021 | 06e62cd8a8c7f1e99374075b7302f6dcfb770bb0 | [
"Apache-2.0"
] | null | null | null | days/Day07.cpp | willkill07/AdventOfCode2021 | 06e62cd8a8c7f1e99374075b7302f6dcfb770bb0 | [
"Apache-2.0"
] | 1 | 2021-12-03T04:25:32.000Z | 2021-12-03T04:25:32.000Z | #include <algorithm>
#include <limits>
#include <numeric>
#include <ranges>
#include <vector>
#include <scn/all.h>
#include "AdventDay.hpp"
#include "Day07.hpp"
namespace detail {
using namespace day07;
using Day = AdventDay<id, parsed, result1, result2>;
}
using detail::Day;
template <>
Day::parsed_type
Day::parse(std::string const& filename) {
scn::basic_mapped_file<char> file{filename.c_str()};
std::vector<int> result;
result.reserve(1000);
int num{0};
for (auto&& c : file) {
if (::isdigit(c)) {
num = 10 * num + (c - '0');
} else {
result.push_back(std::exchange(num, 0));
}
}
if (num != 0) {
result.push_back(num);
}
return result;
}
template <>
template <bool solve_part2>
Day::answer<solve_part2>
Day::solve(Day::parsed_type const& data, Day::opt_answer) {
auto cost_fn = [] (int loc) {
return [loc] (int x) {
if constexpr (int const diff = std::abs(x - loc); solve_part2) {
return (diff + 1) * diff / 2;
} else {
return diff;
}
};
};
auto get_cost = [&] (int x) {
auto const deltas = data | std::ranges::views::transform(cost_fn(x));
return std::accumulate(std::ranges::begin(deltas), std::ranges::end(deltas), 0);
};
// wanted to have a mutable lambda with min local, but that doesn't compile
int min {std::numeric_limits<int>::max()};
auto decreasing = [&] (int curr) {
return (curr == (min = std::min(min, curr)));
};
return (std::ranges::views::iota(std::ranges::min(data))
| std::ranges::views::transform(get_cost)
| std::ranges::views::take_while(decreasing)
| std::ranges::views::reverse
).front();
}
INSTANTIATE(Day, true);
INSTANTIATE(Day, false);
| 23.849315 | 84 | 0.612292 | [
"vector",
"transform"
] |
003d59e072269fa30627dc140e2b34b27fc8b392 | 16,123 | cpp | C++ | src/wrap-clfft.cpp | isuruf/pycl-fft | 7380fd573dcd6ff43fa8c1cdd99a861558fc8166 | [
"MIT"
] | 1 | 2022-03-24T16:20:27.000Z | 2022-03-24T16:20:27.000Z | src/wrap-clfft.cpp | isuruf/pycl-fft | 7380fd573dcd6ff43fa8c1cdd99a861558fc8166 | [
"MIT"
] | 1 | 2022-03-24T20:40:18.000Z | 2022-03-24T20:40:18.000Z | src/wrap-clfft.cpp | isuruf/pycl-fft | 7380fd573dcd6ff43fa8c1cdd99a861558fc8166 | [
"MIT"
] | 1 | 2022-03-24T20:07:03.000Z | 2022-03-24T20:07:03.000Z | // Copyright (C) 2021 Zachary J Weiner
//
// 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 <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
#include <clFFT.h>
#include <clFFT.version.h>
#define CALL_GUARDED(err, CALL) \
clfftStatus err = CALL; \
if (err != 0) throw std::runtime_error(std::to_string((int)err));
#define DEF_SIMPLE_RW(name) \
def_readwrite(#name, &cls::name)
#define set_plan_attr(Name, T) \
[](cls *self, T val) \
{ \
CALL_GUARDED(err, clfftSet##Name(self->plan_handle, (T)val)) \
}
#define get_plan_attr(Name, T) \
[](cls *self) \
{ \
T out; \
CALL_GUARDED(err, clfftGet##Name(self->plan_handle, &out)) \
return out; \
}
#define DEF_PLAN_RW(name, Name, T) \
def_property(#name, get_plan_attr(Name, T), set_plan_attr(Name, T))
#define set_plan_attr_dir(Name, T, dir) \
[](cls *self, T val) \
{ \
CALL_GUARDED(err, clfftSet##Name(self->plan_handle, dir, (T)val)) \
}
#define get_plan_attr_dir(Name, T, dir) \
[](cls *self) \
{ \
T out; \
CALL_GUARDED(err, clfftGet##Name(self->plan_handle, dir, &out)) \
return out; \
}
#define DEF_PLAN_RW_DIR(name, Name, T, dir) \
def_property(#name, get_plan_attr_dir(Name, T, dir), set_plan_attr_dir(Name, T, dir))
#define set_plan_attr_vec(Name, T) \
[](cls *self, const std::vector<T> &val) \
{ \
CALL_GUARDED(err, clfftSet##Name(self->plan_handle, (clfftDim)val.size(), const_cast<T*>(val.data()))) \
}
#define get_plan_attr_vec(Name, T) \
[](cls *self) \
{ \
clfftDim dim = self->get_dim(); \
std::vector<T> result(dim); \
CALL_GUARDED(err, clfftGet##Name(self->plan_handle, dim, const_cast<T*>(result.data()))) \
return result; \
}
#define DEF_PLAN_RW_VEC(name, Name, T) \
def_property(#name, get_plan_attr_vec(Name, T), set_plan_attr_vec(Name, T))
#define DEF_PREFIXED_VALUE(name) \
value(#name, CLFFT_##name)
#define py_obj_to_cl_ptr(name, ClType) \
[](cls *self, py::object obj) \
{ \
ClType *clobj = new ClType; \
*clobj = (ClType)(obj.attr("int_ptr").cast<intptr_t>()); \
self->name = clobj; \
}
#define cl_ptr_to_py_obj(name, pyType) \
[](cls *self) -> py::object \
{ \
if(self->name == 0) return py::object(py::cast(nullptr)); \
intptr_t int_ptr = (intptr_t) *self->name; \
py::object cl = py::module_::import("pyopencl"); \
return cl.attr(#pyType).attr("from_int_ptr")(int_ptr); \
}
#define DEF_CL_PROPERTY(name, ClType, pyType) \
def_property(#name, cl_ptr_to_py_obj(name, pyType), py_obj_to_cl_ptr(name, ClType))
clfftSetupData init_setup_data() {
clfftSetupData setup_data;
CALL_GUARDED(err, clfftInitSetupData(&setup_data))
CALL_GUARDED(err2, clfftSetup(&setup_data))
return setup_data;
}
std::tuple<int, int, int> get_clfft_version() {
cl_uint libMajor, libMinor, libPatch;
CALL_GUARDED(err, clfftGetVersion(&libMajor, &libMinor, &libPatch))
return std::make_tuple((int)libMajor, (int)libMinor, (int)libPatch);
}
#define py_objs_to_ptr_vector(py_list, name, type) \
std::vector<type> name; \
if (! py_list.is(py::none())) \
{ \
for (py::handle obj: py_list) \
name.push_back((type)(obj.attr("int_ptr").cast<intptr_t>())); \
}
class plan {
private:
bool destroyed = false;
public:
clfftPlanHandle plan_handle;
cl_context* context;
plan(py::object ctx, const int dimension, const std::vector<size_t> lens)
{
context = new cl_context;
*context = (cl_context)(ctx.attr("int_ptr").cast<intptr_t>());
CALL_GUARDED(err, clfftCreateDefaultPlan(
&plan_handle, *context, (clfftDim)dimension, lens.data())
)
}
void destroy() {
if (!destroyed)
{
CALL_GUARDED(err, clfftDestroyPlan(&plan_handle))
destroyed = true;
}
}
void bake(py::object py_queues) {
py_objs_to_ptr_vector(py_queues, queues, cl_command_queue)
cl_uint num_queues = queues.size();
CALL_GUARDED(err, clfftBakePlan(
plan_handle, num_queues, queues.data(), nullptr, nullptr)
)
}
std::vector<py::object> enqueue_transform(
clfftDirection dir, py::object queues, py::object wait_for,
py::object inputs, py::object outputs, py::object temp_buffer) {
py_objs_to_ptr_vector(queues, cl_queues, cl_command_queue)
cl_uint num_queues = cl_queues.size();
py_objs_to_ptr_vector(wait_for, cl_wait_for, cl_event)
cl_uint num_wait_for = cl_wait_for.size();
std::vector<cl_event> cl_events(num_queues);
py_objs_to_ptr_vector(inputs, cl_inputs, cl_mem)
py_objs_to_ptr_vector(outputs, cl_outputs, cl_mem)
cl_mem temp_buffer_ptr = nullptr;
if (! temp_buffer.is(py::none()))
{
temp_buffer_ptr = (cl_mem)(temp_buffer.attr("int_ptr").cast<intptr_t>());
}
CALL_GUARDED(err, clfftEnqueueTransform(
plan_handle, dir, num_queues, cl_queues.data(), num_wait_for,
cl_wait_for.data(), cl_events.data(), cl_inputs.data(), cl_outputs.data(),
temp_buffer_ptr)
)
std::vector<py::object> events;
py::object cl = py::module_::import("pyopencl");
for (cl_event evt: cl_events)
{
intptr_t int_ptr = (intptr_t)evt;
events.push_back(cl.attr("Event").attr("from_int_ptr")(int_ptr));
}
return events;
}
void set_callback(
const char* funcName, const char* funcString, int localMemSize,
clfftCallbackType callbackType, cl_mem *userdata, int numUserdataBuffers) {
CALL_GUARDED(err, clfftSetPlanCallback(
plan_handle, funcName, funcString, localMemSize, callbackType,
userdata, numUserdataBuffers)
)
}
clfftDim get_dim() {
clfftDim dimension;
cl_uint size;
CALL_GUARDED(err, clfftGetPlanDim(plan_handle, &dimension, &size))
return dimension;
}
size_t get_in_distance() {
size_t idist, odist;
CALL_GUARDED(err, clfftGetPlanDistance(plan_handle, &idist, &odist))
return idist;
}
size_t get_out_distance() {
size_t idist, odist;
CALL_GUARDED(err, clfftGetPlanDistance(plan_handle, &idist, &odist))
return odist;
}
void set_in_distance(size_t idist) {
size_t tmp;
size_t odist;
CALL_GUARDED(err, clfftGetPlanDistance(plan_handle, &tmp, &odist))
CALL_GUARDED(err2, clfftSetPlanDistance(plan_handle, idist, odist))
}
void set_out_distance(size_t odist) {
size_t idist;
size_t tmp;
CALL_GUARDED(err, clfftGetPlanDistance(plan_handle, &idist, &tmp))
CALL_GUARDED(err2, clfftSetPlanDistance(plan_handle, idist, odist))
}
clfftLayout get_in_layout() {
clfftLayout ilayout, olayout;
CALL_GUARDED(err, clfftGetLayout(plan_handle, &ilayout, &olayout))
return ilayout;
}
clfftLayout get_out_layout() {
clfftLayout ilayout, olayout;
CALL_GUARDED(err, clfftGetLayout(plan_handle, &ilayout, &olayout))
return olayout;
}
void set_in_layout(clfftLayout ilayout) {
clfftLayout tmp;
clfftLayout olayout;
CALL_GUARDED(err, clfftGetLayout(plan_handle, &tmp, &olayout))
if (ilayout == CLFFT_REAL)
{
// if (olayout != CLFFT_HERMITIAN_PLANAR)
olayout = CLFFT_HERMITIAN_INTERLEAVED;
}
else if (ilayout == CLFFT_HERMITIAN_INTERLEAVED
|| ilayout == CLFFT_HERMITIAN_PLANAR)
olayout = CLFFT_REAL;
else
olayout = ilayout;
CALL_GUARDED(err2, clfftSetLayout(plan_handle, ilayout, olayout))
}
void set_out_layout(clfftLayout olayout) {
clfftLayout ilayout;
clfftLayout tmp;
CALL_GUARDED(err, clfftGetLayout(plan_handle, &ilayout, &tmp))
if (olayout == CLFFT_HERMITIAN_INTERLEAVED || olayout == CLFFT_HERMITIAN_PLANAR)
ilayout = CLFFT_REAL;
else if (olayout == CLFFT_REAL)
{
// if (ilayout != CLFFT_HERMITIAN_PLANAR)
ilayout = CLFFT_HERMITIAN_INTERLEAVED;
}
else
ilayout = olayout;
CALL_GUARDED(err2, clfftSetLayout(plan_handle, ilayout, olayout))
}
};
PYBIND11_MODULE(_clfft, m)
{
{
typedef clfftSetupData cls;
py::class_<cls>(m, "SetupData")
.def(py::init(&init_setup_data))
.DEF_SIMPLE_RW(major)
.DEF_SIMPLE_RW(minor)
.DEF_SIMPLE_RW(patch)
.DEF_SIMPLE_RW(debugFlags)
;
}
{
typedef plan cls;
py::class_<cls>(m, "Plan")
.def(py::init<py::object, const int, const std::vector<size_t>>())
.def("destroy", &plan::destroy)
.def_property_readonly("context", cl_ptr_to_py_obj(context, Context))
.DEF_PLAN_RW(precision, PlanPrecision, clfftPrecision)
.DEF_PLAN_RW_DIR(forward_scale, PlanScale, cl_float, CLFFT_FORWARD)
.DEF_PLAN_RW_DIR(backward_scale, PlanScale, cl_float, CLFFT_BACKWARD)
.DEF_PLAN_RW(batch_size, PlanBatchSize, size_t)
.def_property("dimension", &plan::get_dim, set_plan_attr(PlanDim, clfftDim))
.DEF_PLAN_RW_VEC(lengths, PlanLength, size_t)
.DEF_PLAN_RW_VEC(input_strides, PlanInStride, size_t)
.DEF_PLAN_RW_VEC(output_strides, PlanOutStride, size_t)
.def_property("input_distance", &plan::get_in_distance, &plan::set_in_distance)
.def_property("output_distance", &plan::get_out_distance, &plan::set_out_distance)
.def_property("input_layout", &plan::get_in_layout, &plan::set_in_layout)
.def_property("output_layout", &plan::get_out_layout, &plan::set_out_layout)
.DEF_PLAN_RW(placeness, ResultLocation, clfftResultLocation)
.DEF_PLAN_RW(transposed, PlanTransposeResult, clfftResultTransposed)
.def_property_readonly("temp_buffer_size", get_plan_attr(TmpBufSize, size_t))
.def("bake", &plan::bake)
.def("enqueue_transform", &plan::enqueue_transform)
// unimplemented: clfftCopyPlan, clfftSetPlanCallback
;
}
py::enum_<clfftStatus>(m, "Status")
.DEF_PREFIXED_VALUE(INVALID_GLOBAL_WORK_SIZE)
.DEF_PREFIXED_VALUE(INVALID_MIP_LEVEL)
.DEF_PREFIXED_VALUE(INVALID_BUFFER_SIZE)
.DEF_PREFIXED_VALUE(INVALID_GL_OBJECT)
.DEF_PREFIXED_VALUE(INVALID_OPERATION)
.DEF_PREFIXED_VALUE(INVALID_EVENT)
.DEF_PREFIXED_VALUE(INVALID_EVENT_WAIT_LIST)
.DEF_PREFIXED_VALUE(INVALID_GLOBAL_OFFSET)
.DEF_PREFIXED_VALUE(INVALID_WORK_ITEM_SIZE)
.DEF_PREFIXED_VALUE(INVALID_WORK_GROUP_SIZE)
.DEF_PREFIXED_VALUE(INVALID_WORK_DIMENSION)
.DEF_PREFIXED_VALUE(INVALID_KERNEL_ARGS)
.DEF_PREFIXED_VALUE(INVALID_ARG_SIZE)
.DEF_PREFIXED_VALUE(INVALID_ARG_VALUE)
.DEF_PREFIXED_VALUE(INVALID_ARG_INDEX)
.DEF_PREFIXED_VALUE(INVALID_KERNEL)
.DEF_PREFIXED_VALUE(INVALID_KERNEL_DEFINITION)
.DEF_PREFIXED_VALUE(INVALID_KERNEL_NAME)
.DEF_PREFIXED_VALUE(INVALID_PROGRAM_EXECUTABLE)
.DEF_PREFIXED_VALUE(INVALID_PROGRAM)
.DEF_PREFIXED_VALUE(INVALID_BUILD_OPTIONS)
.DEF_PREFIXED_VALUE(INVALID_BINARY)
.DEF_PREFIXED_VALUE(INVALID_SAMPLER)
.DEF_PREFIXED_VALUE(INVALID_IMAGE_SIZE)
.DEF_PREFIXED_VALUE(INVALID_IMAGE_FORMAT_DESCRIPTOR)
.DEF_PREFIXED_VALUE(INVALID_MEM_OBJECT)
.DEF_PREFIXED_VALUE(INVALID_HOST_PTR)
.DEF_PREFIXED_VALUE(INVALID_COMMAND_QUEUE)
.DEF_PREFIXED_VALUE(INVALID_QUEUE_PROPERTIES)
.DEF_PREFIXED_VALUE(INVALID_CONTEXT)
.DEF_PREFIXED_VALUE(INVALID_DEVICE)
.DEF_PREFIXED_VALUE(INVALID_PLATFORM)
.DEF_PREFIXED_VALUE(INVALID_DEVICE_TYPE)
.DEF_PREFIXED_VALUE(INVALID_VALUE)
.DEF_PREFIXED_VALUE(MAP_FAILURE)
.DEF_PREFIXED_VALUE(BUILD_PROGRAM_FAILURE)
.DEF_PREFIXED_VALUE(IMAGE_FORMAT_NOT_SUPPORTED)
.DEF_PREFIXED_VALUE(IMAGE_FORMAT_MISMATCH)
.DEF_PREFIXED_VALUE(MEM_COPY_OVERLAP)
.DEF_PREFIXED_VALUE(PROFILING_INFO_NOT_AVAILABLE)
.DEF_PREFIXED_VALUE(OUT_OF_HOST_MEMORY)
.DEF_PREFIXED_VALUE(OUT_OF_RESOURCES)
.DEF_PREFIXED_VALUE(MEM_OBJECT_ALLOCATION_FAILURE)
.DEF_PREFIXED_VALUE(COMPILER_NOT_AVAILABLE)
.DEF_PREFIXED_VALUE(DEVICE_NOT_AVAILABLE)
.DEF_PREFIXED_VALUE(DEVICE_NOT_FOUND)
.DEF_PREFIXED_VALUE(SUCCESS)
.DEF_PREFIXED_VALUE(BUGCHECK)
.DEF_PREFIXED_VALUE(NOTIMPLEMENTED)
.DEF_PREFIXED_VALUE(TRANSPOSED_NOTIMPLEMENTED)
.DEF_PREFIXED_VALUE(FILE_NOT_FOUND)
.DEF_PREFIXED_VALUE(FILE_CREATE_FAILURE)
.DEF_PREFIXED_VALUE(VERSION_MISMATCH)
.DEF_PREFIXED_VALUE(INVALID_PLAN)
.DEF_PREFIXED_VALUE(DEVICE_NO_DOUBLE)
.DEF_PREFIXED_VALUE(DEVICE_MISMATCH)
;
py::enum_<clfftDim>(m, "Dimension")
.DEF_PREFIXED_VALUE(1D)
.DEF_PREFIXED_VALUE(2D)
.DEF_PREFIXED_VALUE(3D)
;
py::enum_<clfftLayout>(m, "Layout")
.DEF_PREFIXED_VALUE(COMPLEX_INTERLEAVED)
.DEF_PREFIXED_VALUE(COMPLEX_PLANAR)
.DEF_PREFIXED_VALUE(HERMITIAN_INTERLEAVED)
.DEF_PREFIXED_VALUE(HERMITIAN_PLANAR)
.DEF_PREFIXED_VALUE(REAL)
;
py::enum_<clfftPrecision>(m, "Precision")
.DEF_PREFIXED_VALUE(SINGLE)
.DEF_PREFIXED_VALUE(DOUBLE)
.DEF_PREFIXED_VALUE(SINGLE_FAST)
.DEF_PREFIXED_VALUE(DOUBLE_FAST)
;
py::enum_<clfftDirection>(m, "Direction")
.DEF_PREFIXED_VALUE(FORWARD)
.DEF_PREFIXED_VALUE(BACKWARD)
.DEF_PREFIXED_VALUE(MINUS)
.DEF_PREFIXED_VALUE(PLUS)
;
py::enum_<clfftResultLocation>(m, "ResultLocation")
.DEF_PREFIXED_VALUE(INPLACE)
.DEF_PREFIXED_VALUE(OUTOFPLACE)
;
py::enum_<clfftResultTransposed>(m, "ResultTransposition")
.DEF_PREFIXED_VALUE(NOTRANSPOSE)
.DEF_PREFIXED_VALUE(TRANSPOSED)
;
py::enum_<clfftCallbackType>(m, "CallbackType")
.value("PRECALLBACK", PRECALLBACK)
.value("POSTCALLBACK", POSTCALLBACK)
;
m.def("teardown", &clfftTeardown);
m.attr("__version__") = get_clfft_version();
}
| 36.894737 | 112 | 0.641072 | [
"object",
"vector",
"3d"
] |
003fdd4a1ef12e62d0cd58d314679e74505a1bd9 | 24,552 | cpp | C++ | KeePass.1.39.a/KeePassLibCpp/Util/PwUtil.cpp | rrvt/KeePassLastPass | 217b627d906cf0af21ac69643a2d2e24e88f934b | [
"MIT"
] | null | null | null | KeePass.1.39.a/KeePassLibCpp/Util/PwUtil.cpp | rrvt/KeePassLastPass | 217b627d906cf0af21ac69643a2d2e24e88f934b | [
"MIT"
] | null | null | null | KeePass.1.39.a/KeePassLibCpp/Util/PwUtil.cpp | rrvt/KeePassLastPass | 217b627d906cf0af21ac69643a2d2e24e88f934b | [
"MIT"
] | null | null | null | /*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2021 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "StdAfx.h"
#include <math.h>
#include <set>
#include "PwUtil.h"
#include "MemUtil.h"
#include "StrUtil.h"
#include "TranslateEx.h"
#include "../Crypto/ARCFour.h"
static const BYTE g_uuidZero[16] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
CPwUtil::CPwUtil()
{
}
BOOL CPwUtil::LoadHexKey32(FILE *fp, BYTE *pBuf)
{
char buf[65], ch1, ch2;
BYTE bt;
ASSERT(fp != NULL); if(fp == NULL) return FALSE;
ASSERT(pBuf != NULL); if(pBuf == NULL) return FALSE;
buf[64] = 0;
if(fread(buf, 1, 64, fp) != 64) { ASSERT(FALSE); return FALSE; }
for(int i = 0; i < 32; ++i)
{
ch1 = buf[i * 2];
ch2 = buf[i * 2 + 1];
if(CPwUtil::ConvertStrToHex(ch1, ch2, bt) == FALSE) return FALSE;
pBuf[i] = bt;
}
mem_erase(buf, 64);
return TRUE;
}
BOOL CPwUtil::SaveHexKey32(FILE *fp, BYTE *pBuf)
{
char buf[65], ch1, ch2;
BYTE bt;
ASSERT(fp != NULL); if(fp == NULL) return FALSE;
ASSERT(pBuf != NULL); if(pBuf == NULL) return FALSE;
buf[64] = 0;
for(int i = 0; i < 32; ++i)
{
bt = pBuf[i];
CPwUtil::ConvertHexToStr(bt, ch1, ch2);
buf[i * 2] = ch1;
buf[i * 2 + 1] = ch2;
}
fwrite(buf, 1, 64, fp);
mem_erase(buf, 64);
return TRUE;
}
LPCTSTR CPwUtil::GetUniCvtPtr(LPCTSTR lpBase, BOOL bTranslate)
{
if(lpBase == NULL) return PWU_CVT_EX; // NULL is allowed, return unique default pointer
if(bTranslate != FALSE) return _TRL(lpBase);
return lpBase; // Untranslated
}
BOOL CPwUtil::ConvertStrToHex(char ch1, char ch2, BYTE& bt)
{
if((ch1 >= '0') && (ch1 <= '9')) bt = static_cast<BYTE>(ch1 - '0');
else if((ch1 >= 'a') && (ch1 <= 'f')) bt = static_cast<BYTE>(ch1 - 'a' + 10);
else if((ch1 >= 'A') && (ch1 <= 'F')) bt = static_cast<BYTE>(ch1 - 'A' + 10);
else return FALSE;
bt <<= 4;
if((ch2 >= '0') && (ch2 <= '9')) bt |= static_cast<BYTE>(ch2 - '0');
else if((ch2 >= 'a') && (ch2 <= 'f')) bt |= static_cast<BYTE>(ch2 - 'a' + 10);
else if((ch2 >= 'A') && (ch2 <= 'F')) bt |= static_cast<BYTE>(ch2 - 'A' + 10);
else return FALSE;
return TRUE;
}
void CPwUtil::ConvertHexToStr(BYTE bt, char& ch1, char& ch2)
{
char chq = static_cast<char>(bt >> 4);
if(chq < 10) ch1 = static_cast<char>(chq + '0');
else ch1 = static_cast<char>(chq - 10 + 'a');
chq = static_cast<char>(bt & 0x0F);
if(chq < 10) ch2 = static_cast<char>(chq + '0');
else ch2 = static_cast<char>(chq - 10 + 'a');
}
CString CPwUtil::FormatError(int nErrorCode, DWORD dwFlags)
{
CString str;
if(nErrorCode != PWE_SUCCESS)
{
TCHAR tszTemp[24];
_stprintf_s(tszTemp, _T("%08X"), static_cast<unsigned int>(nErrorCode));
if((dwFlags & PWFF_NO_INTRO) == 0)
{
str = TRL("An error occurred"); str += _T("!\r\n");
}
str += TRL("Error code"); str += _T(": 0x");
str += tszTemp;
str += _T(".");
if((dwFlags & PWFF_NO_INTRO) == 0) str += _T("\r\n\r\n");
else str += _T("\r\n");
}
if(((nErrorCode == PWE_INVALID_KEY) && ((dwFlags & PWFF_INVKEY_WITH_CODE) == 0)) ||
(nErrorCode == PWE_UNSUPPORTED_KDBX) || ((dwFlags & PWFF_MAIN_TEXT_ONLY) != 0) ||
(nErrorCode == PWE_GETLASTERROR))
str.Empty();
switch(nErrorCode)
{
case PWE_UNKNOWN:
str += TRL("Unknown error");
break;
case PWE_SUCCESS:
str += TRL("Success");
break;
case PWE_INVALID_PARAM:
str += TRL("Invalid parameter");
break;
case PWE_NO_MEM:
str += TRL("Out of memory");
break;
case PWE_INVALID_KEY:
str += TRL("Invalid/wrong key");
break;
case PWE_NOFILEACCESS_READ:
str += TRL("File access error: failed to open file in read mode");
break;
case PWE_NOFILEACCESS_WRITE:
str += TRL("File access error: failed to open file in write mode");
break;
case PWE_FILEERROR_READ:
str += TRL("File error: error while reading from the file");
break;
case PWE_FILEERROR_WRITE:
str += TRL("File error: error while writing to the file");
break;
case PWE_INVALID_RANDOMSOURCE:
str += TRL("Internal error"); str += _T(": ");
str += TRL("Invalid random source");
break;
case PWE_INVALID_FILESTRUCTURE:
str += TRL("Invalid/corrupted file structure");
break;
case PWE_CRYPT_ERROR:
str += TRL("Encryption/decryption error");
break;
case PWE_INVALID_FILESIZE:
str += TRL("Invalid/corrupted file structure");
break;
case PWE_INVALID_FILESIGNATURE:
str += TRL("Invalid/corrupted file structure");
break;
case PWE_INVALID_FILEHEADER:
str += TRL("Invalid/corrupted file structure");
break;
case PWE_NOFILEACCESS_READ_KEY:
str += TRL("File access error: failed to open file in read mode");
break;
case PWE_KEYPROV_INVALID_KEY:
str += TRL("The key provider plugin did not supply a valid key");
break;
case PWE_FILEERROR_VERIFY:
str += TRL("File error: error while writing to the file"); // Same as write
break;
case PWE_UNSUPPORTED_KDBX:
str += TRL("KeePass 1.x cannot open KDBX files.");
str += _T("\r\n\r\n");
str += TRL("Use the KeePass 2.x 'Export' feature to migrate this file");
break;
case PWE_GETLASTERROR:
str += CPwUtil::FormatSystemMessage(GetLastError()).c_str();
str = str.TrimRight(_T(".!\r\n"));
break;
case PWE_DB_EMPTY:
str += TRL("The database is empty");
break;
case PWE_ATTACH_TOOLARGE:
str += TRL("The attachment is too large");
break;
default:
ASSERT(FALSE);
str += TRL("Unknown error");
break;
}
str += _T(".");
if(nErrorCode == PWE_NOFILEACCESS_READ_KEY)
{
str += _T("\r\n\r\n");
str += TRL("Make sure the media that contains the key file is inserted and that KeePass has the rights to access it (check file access rights, ensure that no other application is blocking the file, ...).");
}
if((dwFlags & PWFF_DATALOSS_WITHOUT_SAVE) != 0)
{
str += _T("\r\n\r\n");
str += TRL("The target file might be in a corrupted state. Please try saving again, and if that fails, save the database to a different location.");
}
return str;
}
BOOL CPwUtil::MemAllocCopyEntry(_In_ const PW_ENTRY *pExisting,
_Out_ PW_ENTRY *pDestination)
{
ASSERT_ENTRY(pExisting); ASSERT(pDestination != NULL);
if((pExisting == NULL) || (pDestination == NULL)) return FALSE;
ZeroMemory(pDestination, sizeof(PW_ENTRY));
pDestination->uBinaryDataLen = pExisting->uBinaryDataLen;
if(pExisting->pBinaryData != NULL)
{
pDestination->pBinaryData = new BYTE[pExisting->uBinaryDataLen + 1];
ASSERT(pDestination->pBinaryData != NULL); if(pDestination->pBinaryData == NULL) return FALSE;
pDestination->pBinaryData[pExisting->uBinaryDataLen] = 0;
memcpy(pDestination->pBinaryData, pExisting->pBinaryData, pExisting->uBinaryDataLen);
}
pDestination->pszAdditional = _TcsSafeDupAlloc(pExisting->pszAdditional);
pDestination->pszBinaryDesc = _TcsSafeDupAlloc(pExisting->pszBinaryDesc);
pDestination->pszPassword = _TcsCryptDupAlloc(pExisting->pszPassword);
pDestination->pszTitle = _TcsSafeDupAlloc(pExisting->pszTitle);
pDestination->pszURL = _TcsSafeDupAlloc(pExisting->pszURL);
pDestination->pszUserName = _TcsSafeDupAlloc(pExisting->pszUserName);
pDestination->tCreation = pExisting->tCreation;
pDestination->tExpire = pExisting->tExpire;
pDestination->tLastAccess = pExisting->tLastAccess;
pDestination->tLastMod = pExisting->tLastMod;
pDestination->uGroupId = pExisting->uGroupId;
pDestination->uImageId = pExisting->uImageId;
pDestination->uPasswordLen = pExisting->uPasswordLen;
memcpy(pDestination->uuid, pExisting->uuid, 16);
return TRUE;
}
void CPwUtil::MemFreeEntry(_Inout_ PW_ENTRY *pEntry)
{
ASSERT_ENTRY(pEntry); if(pEntry == NULL) return;
SAFE_DELETE_ARRAY(pEntry->pBinaryData);
SAFE_DELETE_ARRAY(pEntry->pszAdditional);
SAFE_DELETE_ARRAY(pEntry->pszBinaryDesc);
SAFE_DELETE_ARRAY(pEntry->pszPassword);
SAFE_DELETE_ARRAY(pEntry->pszTitle);
SAFE_DELETE_ARRAY(pEntry->pszURL);
SAFE_DELETE_ARRAY(pEntry->pszUserName);
ZeroMemory(pEntry, sizeof(PW_ENTRY));
}
void CPwUtil::TimeToPwTime(_In_bytecount_c_(5) const BYTE *pCompressedTime,
_Out_ PW_TIME *pPwTime)
{
DWORD dwYear, dwMonth, dwDay, dwHour, dwMinute, dwSecond;
ASSERT((pCompressedTime != NULL) && (pPwTime != NULL));
if(pPwTime == NULL) return;
_UnpackStructToTime(pCompressedTime, &dwYear, &dwMonth, &dwDay, &dwHour, &dwMinute, &dwSecond);
pPwTime->shYear = (USHORT)dwYear;
pPwTime->btMonth = (BYTE)dwMonth;
pPwTime->btDay = (BYTE)dwDay;
pPwTime->btHour = (BYTE)dwHour;
pPwTime->btMinute = (BYTE)dwMinute;
pPwTime->btSecond = (BYTE)dwSecond;
}
void CPwUtil::PwTimeToTime(_In_ const PW_TIME *pPwTime,
_Out_bytecap_c_(5) BYTE *pCompressedTime)
{
ASSERT((pPwTime != NULL) && (pCompressedTime != NULL));
if(pPwTime == NULL) return;
_PackTimeToStruct(pCompressedTime, (DWORD)pPwTime->shYear, (DWORD)pPwTime->btMonth,
(DWORD)pPwTime->btDay, (DWORD)pPwTime->btHour, (DWORD)pPwTime->btMinute,
(DWORD)pPwTime->btSecond);
}
/* void CPwUtil::PwEntryStlToKpEntry(const PW_ENTRY_STL* pIn, KP_ENTRY* pOut,
const PW_ENTRY* pOriginalEntry, const CPwManager* pMgr)
{
if((pIn == NULL) || (pOut == NULL)) { ASSERT(FALSE); return; }
// pOriginalEntry may be NULL
if(pMgr == NULL) { ASSERT(FALSE); return; }
ZeroMemory(pOut, sizeof(KP_ENTRY));
pOut->pOriginalEntry = pOriginalEntry;
memcpy(pOut->uuid, pIn->uuid, 16);
pOut->uGroupIndex = pMgr->GetGroupByIdN(pIn->uGroupId);
pOut->uImageId = pIn->uImageId;
pOut->lpTitle = _TcsSafeDupAlloc(pIn->strTitle.c_str());
pOut->lpURL = _TcsSafeDupAlloc(pIn->strURL.c_str());
pOut->lpUserName = _TcsSafeDupAlloc(pIn->strUserName.c_str());
pOut->lpPassword = _TcsSafeDupAlloc(pIn->strPassword.c_str());
pOut->lpAdditional = _TcsSafeDupAlloc(pIn->strAdditional.c_str());
}
void CPwUtil::ClearPwEntryStl(PW_ENTRY_STL* p)
{
if(p == NULL) { ASSERT(FALSE); return; }
ZeroMemory(p->uuid, 16);
p->uGroupId = 0;
p->uImageId = 0;
p->strTitle.clear();
p->strURL.clear();
p->strUserName.clear();
p->strPassword.clear();
p->strAdditional.clear();
CPwManager::GetNeverExpireTime(&p->tCreation);
CPwManager::GetNeverExpireTime(&p->tLastMod);
CPwManager::GetNeverExpireTime(&p->tLastAccess);
CPwManager::GetNeverExpireTime(&p->tExpire);
p->strBinaryDesc.clear();
p->vBinaryData.clear();
} */
void CPwUtil::FreeKpEntry(KP_ENTRY* p)
{
if(p == NULL) { ASSERT(FALSE); return; }
SAFE_DELETE_ARRAY(p->lpTitle);
SAFE_DELETE_ARRAY(p->lpURL);
SAFE_DELETE_ARRAY(p->lpUserName);
SAFE_DELETE_ARRAY(p->lpAdditional);
if(p->lpPassword != NULL)
mem_erase(const_cast<LPTSTR>(p->lpPassword), _tcslen(p->lpPassword) * sizeof(TCHAR));
SAFE_DELETE_ARRAY(p->lpPassword);
}
/* bool CPwUtil::EqualsPwEntryStl(const PW_ENTRY_STL* p1, const PW_ENTRY_STL* p2)
{
if((p1 == NULL) || (p2 == NULL)) { ASSERT(FALSE); return false; }
if(memcmp(p1->uuid, p2->uuid, 16) != 0) return false;
if(p1->uGroupId != p2->uGroupId) return false;
if(p1->uImageId != p2->uImageId) return false;
if(p1->strTitle != p2->strTitle) return false;
if(p1->strURL != p2->strURL) return false;
if(p1->strUserName != p2->strUserName) return false;
if(p1->strPassword != p2->strPassword) return false;
if(p1->strAdditional != p2->strAdditional) return false;
// Do not compare times
if(p1->strBinaryDesc != p2->strBinaryDesc) return false;
if(p1->vBinaryData.size() != p2->vBinaryData.size()) return false;
if(p1->vBinaryData.size() > 0)
{
if(memcmp(&p1->vBinaryData[0], &p2->vBinaryData[0],
p1->vBinaryData.size()) != 0) return false;
}
return true;
} */
void CPwUtil::HashKpEntry(const KP_ENTRY* pEntry, BYTE* pHash32)
{
if((pEntry == NULL) || (pHash32 == NULL)) { ASSERT(FALSE); return; }
sha256_ctx sha32;
sha256_begin(&sha32);
sha256_hash(pEntry->uuid, 16, &sha32);
sha256_hash((const BYTE*)&pEntry->uGroupIndex, sizeof(DWORD), &sha32);
sha256_hash((const BYTE*)&pEntry->uImageId, sizeof(DWORD), &sha32);
HashStringWithTerm(pEntry->lpTitle, sha32);
HashStringWithTerm(pEntry->lpURL, sha32);
HashStringWithTerm(pEntry->lpUserName, sha32);
HashStringWithTerm(pEntry->lpPassword, sha32);
HashStringWithTerm(pEntry->lpAdditional, sha32);
sha256_end(pHash32, &sha32);
}
void CPwUtil::HashStringWithTerm(LPCTSTR lp, sha256_ctx& sha32)
{
if(lp != NULL)
sha256_hash((BYTE*)lp, static_cast<unsigned long>((_tcslen(lp) + 1) *
sizeof(TCHAR)), &sha32);
else // lp == NULL
{
const TCHAR tch0 = 0;
sha256_hash((const BYTE*)&tch0, sizeof(TCHAR), &sha32);
}
}
int CPwUtil::AttachFileAsBinaryData(_Inout_ PW_ENTRY *pEntry,
const TCHAR *lpFile)
{
ASSERT_ENTRY(pEntry); if(pEntry == NULL) return PWE_INVALID_PARAM;
ASSERT(lpFile != NULL); if(lpFile == NULL) return PWE_INVALID_PARAM;
FILE *fp = NULL;
_tfopen_s(&fp, lpFile, _T("rb"));
if(fp == NULL) return PWE_NOFILEACCESS_READ;
_fseeki64(fp, 0, SEEK_END);
const INT64 qwFileLen = _ftelli64(fp);
_fseeki64(fp, 0, SEEK_SET);
if(qwFileLen <= 0) { fclose(fp); return PWE_FILEERROR_READ; }
// Use the same maximum as KeePass 2.x;
// https://sourceforge.net/p/keepass/discussion/329221/thread/42ddc71a/
const INT64 qwMax = 512 * 1024 * 1024;
if(qwFileLen > qwMax) { fclose(fp); return PWE_ATTACH_TOOLARGE; }
int i = static_cast<int>(_tcslen(lpFile)) - 1;
while(i >= 0)
{
if((lpFile[i] == '/') || (lpFile[i] == '\\')) break;
--i;
}
LPCTSTR lpBinaryDesc = &lpFile[i + 1];
int e = PWE_SUCCESS;
try
{
// CPwUtil::RemoveBinaryData(pEntry); // Doesn't free desc.
SAFE_DELETE_ARRAY(pEntry->pszBinaryDesc);
SAFE_DELETE_ARRAY(pEntry->pBinaryData);
const size_t dwPathLen = _tcslen(lpBinaryDesc);
pEntry->pszBinaryDesc = new TCHAR[dwPathLen + 1];
_tcscpy_s(pEntry->pszBinaryDesc, dwPathLen + 1, lpBinaryDesc);
const DWORD dwFileLen = static_cast<DWORD>(qwFileLen);
pEntry->pBinaryData = new BYTE[dwFileLen];
if(fread(pEntry->pBinaryData, 1, dwFileLen, fp) != dwFileLen)
e = PWE_FILEERROR_READ;
pEntry->uBinaryDataLen = dwFileLen;
}
catch(...) { e = PWE_NO_MEM; }
if(e != PWE_SUCCESS) CPwUtil::RemoveBinaryData(pEntry);
fclose(fp);
return e;
}
BOOL CPwUtil::SaveBinaryData(_In_ const PW_ENTRY *pEntry,
const TCHAR *lpFile)
{
ASSERT_ENTRY(pEntry); if(pEntry == NULL) return FALSE;
ASSERT(lpFile != NULL); if(lpFile == NULL) return FALSE;
if(pEntry->pszBinaryDesc[0] == _T('\0')) return FALSE;
FILE *fp = NULL;
_tfopen_s(&fp, lpFile, _T("wb"));
if(fp == NULL) return FALSE;
if(pEntry->uBinaryDataLen != 0)
fwrite(pEntry->pBinaryData, 1, pEntry->uBinaryDataLen, fp);
fclose(fp);
return TRUE;
}
BOOL CPwUtil::RemoveBinaryData(_Inout_ PW_ENTRY *pEntry)
{
ASSERT_ENTRY(pEntry); if(pEntry == NULL) return FALSE;
SAFE_DELETE_ARRAY(pEntry->pBinaryData);
SAFE_DELETE_ARRAY(pEntry->pszBinaryDesc);
pEntry->pszBinaryDesc = new TCHAR[1];
pEntry->pszBinaryDesc[0] = _T('\0');
pEntry->uBinaryDataLen = 0;
return TRUE;
}
BOOL CPwUtil::IsAllowedStoreGroup(LPCTSTR lpGroupName, LPCTSTR lpSearchGroupName)
{
ASSERT(lpGroupName != NULL); if(lpGroupName == NULL) return FALSE;
if(_tcscmp(lpGroupName, lpSearchGroupName) == 0) return FALSE;
return TRUE;
}
BOOL CPwUtil::IsZeroUUID(_In_bytecount_c_(16) const BYTE *pUUID)
{
if(pUUID == NULL) return TRUE;
return ((memcmp(pUUID, g_uuidZero, 16) == 0) ? TRUE : FALSE);
}
BOOL CPwUtil::IsTANEntry(const PW_ENTRY *pe)
{
ASSERT(pe != NULL); if(pe == NULL) return FALSE;
return ((_tcscmp(pe->pszTitle, PWS_TAN_ENTRY) != 0) ? FALSE : TRUE);
}
/* void CPwUtil::ProtectMemory(UINT8 *pMem, size_t uBytes, bool bEncrypt)
{
#ifdef _WIN32
DWORD dwBytes = static_cast<DWORD>(uBytes);
dwBytes += CRYPTPROTECTMEMORY_BLOCK_SIZE - (dwBytes % CRYPTPROTECTMEMORY_BLOCK_SIZE);
ASSERT((uBytes <= dwBytes) && (dwBytes <= uBytes + CRYPTPROTECTMEMORY_BLOCK_SIZE));
ASSERT((dwBytes % CRYPTPROTECTMEMORY_BLOCK_SIZE) == 0);
if(bEncrypt)
{
VERIFY(CryptProtectMemory(pMem, dwBytes, CRYPTPROTECTMEMORY_SAME_PROCESS));
}
else
{
VERIFY(CryptUnprotectMemory(pMem, dwBytes, CRYPTPROTECTMEMORY_SAME_PROCESS));
}
#endif
} */
/* CPwErrorInfo::CPwErrorInfo()
{
m_nPwErrorCode = PWE_SUCCESS;
m_dwLastError = 0;
}
void CPwErrorInfo::SetInfo(const std::basic_string<TCHAR>& strText,
int nPwErrorCode, BOOL bUseLastError)
{
m_strText = strText;
m_nPwErrorCode = nPwErrorCode;
if(bUseLastError == TRUE) m_dwLastError = GetLastError();
else m_dwLastError = 0;
this->FormatInfo();
}
void CPwErrorInfo::FormatInfo()
{
std::basic_string<TCHAR> str;
if(m_strText.size() > 0)
{
str += m_strText;
str += _T("\r\n\r\n");
}
str += PWM_FormatStaticError(m_nPwErrorCode, 0);
str += _T("\r\n\r\n");
if(m_dwLastError != 0)
{
LPTSTR lpBuffer = NULL;
if(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, m_dwLastError, 0, (LPTSTR)&lpBuffer, 1, NULL) != 0)
{
str += lpBuffer;
}
if(lpBuffer != NULL) { LocalFree(lpBuffer); lpBuffer = NULL; }
}
m_strFinal = str;
}
std::basic_string<TCHAR> CPwErrorInfo::ToString() const
{
return m_strFinal;
}
*/
CString CPwUtil::CreateUUIDStr(CNewRandom* pRandomSource)
{
if(pRandomSource == NULL) { ASSERT(FALSE); return CString(); }
BYTE pbUuid[16];
randCreateUUID(&pbUuid[0], pRandomSource);
CString str;
_UuidToString(&pbUuid[0], &str);
return str;
}
DWORD CPwUtil::GetUniCPT(LPCTSTR lp)
{
DWORD dwRel = 0; // See CPT specs
while(*lp != 0) { dwRel = (ROTL32UE(dwRel, 5) + *lp); ++lp; }
return dwRel;
}
PG_TREENODE CPwUtil::GroupsToTree(CPwManager* pMgr)
{
PG_TREENODE v;
ZeroMemory(&v.g, sizeof(PW_GROUP));
if(pMgr == NULL) { ASSERT(FALSE); return v; }
const DWORD dwGroupCount = pMgr->GetNumberOfGroups();
for(DWORD i = 0; i < dwGroupCount; ++i)
pMgr->GetGroup(i)->dwFlags &= ~PWGF_TEMP_BIT; // Clear
DWORD dwAllocCount = 0;
for(DWORD i = 0; i < dwGroupCount; ++i)
{
PW_GROUP* pg = pMgr->GetGroup(i);
if(pg->usLevel == 0)
{
ASSERT((pg->dwFlags & PWGF_TEMP_BIT) == 0);
v.vChildNodes.push_back(GroupToTreeNode(pMgr, i, dwAllocCount));
}
else { ASSERT((pg->dwFlags & PWGF_TEMP_BIT) != 0); }
}
ASSERT((pMgr->GetNumberOfGroups() == dwGroupCount) && (dwAllocCount == dwGroupCount));
return v;
}
boost::shared_ptr<PG_TREENODE> CPwUtil::GroupToTreeNode(CPwManager* pMgr,
DWORD dwIndex, DWORD& dwAllocCount)
{
boost::shared_ptr<PG_TREENODE> p(new PG_TREENODE());
PW_GROUP* pg = pMgr->GetGroup(dwIndex);
++dwAllocCount;
p->g = *pg;
pg->dwFlags |= PWGF_TEMP_BIT;
while(true)
{
++dwIndex;
if(dwIndex >= pMgr->GetNumberOfGroups()) break;
PW_GROUP* pgSub = pMgr->GetGroup(dwIndex);
if(pgSub->usLevel <= pg->usLevel) break;
if((pgSub->dwFlags & PWGF_TEMP_BIT) == 0)
p->vChildNodes.push_back(GroupToTreeNode(pMgr, dwIndex, dwAllocCount));
}
return p;
}
boost::shared_ptr<PG_TREENODE> CPwUtil::FindGroupInTree(PG_TREENODE* pRoot,
DWORD dwGroupId, bool bUnlinkGroup, int iMoveGroup)
{
boost::shared_ptr<PG_TREENODE> pNull;
if(pRoot == NULL) { ASSERT(FALSE); return pNull; }
std::vector<boost::shared_ptr<PG_TREENODE> >& v = pRoot->vChildNodes;
size_t uCurrent = 0;
for(std::vector<boost::shared_ptr<PG_TREENODE> >::iterator it = v.begin();
it != v.end(); ++it)
{
boost::shared_ptr<PG_TREENODE> p = *it;
if(p->g.uGroupId == dwGroupId)
{
if(bUnlinkGroup) v.erase(it);
else if(v.size() >= 2)
{
if((iMoveGroup == -2) && (uCurrent > 0))
{
v.erase(it);
v.insert(v.begin(), p);
}
else if((iMoveGroup == 2) && (uCurrent < (v.size() - 1)))
{
v.erase(it);
v.push_back(p);
}
else if((iMoveGroup == -1) && (uCurrent > 0))
{
v[uCurrent] = v[uCurrent - 1];
v[uCurrent - 1] = p;
}
else if((iMoveGroup == 1) && (uCurrent < (v.size() - 1)))
{
v[uCurrent] = v[uCurrent + 1];
v[uCurrent + 1] = p;
}
}
return p;
}
else
{
boost::shared_ptr<PG_TREENODE> pSub = FindGroupInTree(p.get(),
dwGroupId, bUnlinkGroup, iMoveGroup);
if(pSub.get() != NULL) return pSub;
}
++uCurrent;
}
return pNull;
}
void CPwUtil::FlattenGroupTree(PW_GROUP* pStorage, PG_TREENODE* pRoot,
DWORD dwStorageCount)
{
DWORD dwIndex = 0;
FlattenGroupTreeInternal(pStorage, pRoot, dwIndex, dwStorageCount, 0);
ASSERT(dwIndex == dwStorageCount);
}
void CPwUtil::FlattenGroupTreeInternal(PW_GROUP* pStorage, PG_TREENODE* pRoot,
DWORD& dwIndex, DWORD dwStorageCount, USHORT usLevel)
{
for(size_t i = 0; i < pRoot->vChildNodes.size(); ++i)
{
if(dwIndex >= dwStorageCount) { ASSERT(FALSE); return; }
pStorage[dwIndex] = pRoot->vChildNodes[i]->g;
pStorage[dwIndex].usLevel = usLevel;
++dwIndex;
FlattenGroupTreeInternal(pStorage, pRoot->vChildNodes[i].get(), dwIndex,
dwStorageCount, usLevel + 1);
}
}
#ifdef _DEBUG
void CPwUtil::CheckGroupList(CPwManager* pMgr)
{
std::set<DWORD> vIds;
USHORT usLastLevel = 0;
for(DWORD i = 0; i < pMgr->GetNumberOfGroups(); ++i)
{
PW_GROUP* pg = pMgr->GetGroup(i);
ASSERT(pg != NULL);
ASSERT((pg->uGroupId != 0) && (pg->uGroupId != DWORD_MAX));
const DWORD dwGroupId = pg->uGroupId;
ASSERT(vIds.find(dwGroupId) == vIds.end());
ASSERT(pg->usLevel <= (usLastLevel + 1));
vIds.insert(dwGroupId);
usLastLevel = pg->usLevel;
}
}
#endif
std::basic_string<TCHAR> CPwUtil::FormatSystemMessage(DWORD dwLastErrorCode)
{
std::basic_string<TCHAR> str;
LPTSTR lpBuffer = NULL;
if(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, dwLastErrorCode, 0, (LPTSTR)&lpBuffer, 1, NULL) != 0)
{
str = lpBuffer;
}
if(lpBuffer != NULL) { LocalFree(lpBuffer); lpBuffer = NULL; }
return str;
}
bool CPwUtil::UnhideFile(LPCTSTR lpFile)
{
if(lpFile == NULL) { ASSERT(FALSE); return false; }
const DWORD dwAttrib = GetFileAttributes(lpFile);
if(dwAttrib == INVALID_FILE_ATTRIBUTES) return false;
if((dwAttrib & FILE_ATTRIBUTE_HIDDEN) == 0) return false;
return CPwUtil::HideFile(lpFile, false);
}
bool CPwUtil::HideFile(LPCTSTR lpFile, bool bHide)
{
if(lpFile == NULL) { ASSERT(FALSE); return false; }
DWORD dwAttrib = GetFileAttributes(lpFile);
if(dwAttrib == INVALID_FILE_ATTRIBUTES) return false;
if(bHide) dwAttrib = ((dwAttrib & ~FILE_ATTRIBUTE_NORMAL) | FILE_ATTRIBUTE_HIDDEN);
else // Unhide
{
dwAttrib &= ~FILE_ATTRIBUTE_HIDDEN;
if(dwAttrib == 0) dwAttrib |= FILE_ATTRIBUTE_NORMAL;
}
return (SetFileAttributes(lpFile, dwAttrib) != FALSE);
}
CNullableEx<FILETIME> CPwUtil::GetFileCreationTime(LPCTSTR lpFile)
{
if(lpFile == NULL) { ASSERT(FALSE); return CNullableEx<FILETIME>(); }
HANDLE h = CreateFile(lpFile, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
if(h == INVALID_HANDLE_VALUE) return CNullableEx<FILETIME>();
FILETIME t;
FILETIME vDummy[2];
const BOOL bResult = GetFileTime(h, &t, &vDummy[0], &vDummy[1]);
VERIFY(CloseHandle(h));
if(bResult != FALSE)
{
SYSTEMTIME st;
ZeroMemory(&st, sizeof(SYSTEMTIME));
if(FileTimeToSystemTime(&t, &st) != FALSE)
{
if(st.wYear >= 1971) return CNullableEx<FILETIME>(t);
}
}
ASSERT(FALSE);
return CNullableEx<FILETIME>();
}
bool CPwUtil::SetFileCreationTime(LPCTSTR lpFile, const FILETIME* pTime)
{
if(lpFile == NULL) { ASSERT(FALSE); return false; }
HANDLE h = CreateFile(lpFile, FILE_WRITE_ATTRIBUTES, 0, NULL,
OPEN_EXISTING, 0, NULL);
if(h == INVALID_HANDLE_VALUE) return false;
VERIFY(SetFileTime(h, pTime, NULL, NULL));
VERIFY(CloseHandle(h));
return true;
}
bool CPwUtil::IsDatabaseFile(LPCTSTR lpFile)
{
if(lpFile == NULL) { ASSERT(FALSE); return false; }
FILE* fp = NULL;
_tfopen_s(&fp, lpFile, _T("rb"));
if(fp == NULL) return false;
fseek(fp, 0, SEEK_END);
const long lFileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
bool bResult = false;
if(lFileSize >= 8)
{
BYTE vStart[8];
if(fread(vStart, 1, 8, fp) == 8)
{
const DWORD dwSig1 = *(DWORD*)&vStart[0];
const DWORD dwSig2 = *(DWORD*)&vStart[4];
if(((dwSig1 == PWM_DBSIG_1) && (dwSig2 == PWM_DBSIG_2)) ||
((dwSig1 == PWM_DBSIG_1_KDBX_P) && (dwSig2 == PWM_DBSIG_2_KDBX_P)) ||
((dwSig1 == PWM_DBSIG_1_KDBX_R) && (dwSig2 == PWM_DBSIG_2_KDBX_R)))
bResult = true;
}
else { ASSERT(FALSE); }
}
fclose(fp);
return bResult;
}
| 27.009901 | 208 | 0.689475 | [
"vector"
] |
0046d8cb946c48f33ada884d6c993246f8983900 | 932 | hpp | C++ | src/map/room-description.hpp | Pfeifenjoy/Theseus | 9b427c16deaaacfff2e174e3dd133feed9724d3b | [
"MIT"
] | 6 | 2016-10-28T15:39:09.000Z | 2019-04-16T09:00:03.000Z | src/map/room-description.hpp | Pfeifenjoy/Theseus | 9b427c16deaaacfff2e174e3dd133feed9724d3b | [
"MIT"
] | null | null | null | src/map/room-description.hpp | Pfeifenjoy/Theseus | 9b427c16deaaacfff2e174e3dd133feed9724d3b | [
"MIT"
] | 6 | 2017-02-22T17:25:32.000Z | 2021-02-03T19:17:06.000Z | /**
* @autor Arwed Mett
*/
#ifndef THESEUS_MAP_ROOMDESCRIPTION
#define THESEUS_MAP_ROOMDESCRIPTION
#include <vector>
#include <memory>
#include "../engine/gameobject.hpp"
#include <SFML/Graphics.hpp>
#include "../engine/components/positionable.hpp"
namespace theseus {
namespace map {
/**
* Describes special rooms.
* Will be called by the Layer / Generator.
*/
class RoomDescription {
private:
sf::Vector2f position;
float width;
float height;
std::vector<std::unique_ptr<theseus::engine::components::Positionable> > gameobjects;
public:
RoomDescription(float width, float height);
//Don't call it manually. It will not work.
void setPosition(sf::Vector2f);
void addGameObject(std::unique_ptr<theseus::engine::components::Positionable>);
float getWidth();
float getHeight();
std::vector<std::unique_ptr<theseus::engine::components::Positionable> > getGameObjects();
};
}
}
#endif
| 24.526316 | 93 | 0.72103 | [
"vector"
] |
004c4c6a6a9d8812f3629c49735d693f2f7a0451 | 10,457 | cpp | C++ | dll_unit_tests.cpp | tobiasherzke/dll | 6db2d71f1d588f510a5546774aa0e44368ea8462 | [
"Unlicense"
] | null | null | null | dll_unit_tests.cpp | tobiasherzke/dll | 6db2d71f1d588f510a5546774aa0e44368ea8462 | [
"Unlicense"
] | null | null | null | dll_unit_tests.cpp | tobiasherzke/dll | 6db2d71f1d588f510a5546774aa0e44368ea8462 | [
"Unlicense"
] | null | null | null | #include "dll.hh"
#include <gmock/gmock.h>
#include <mha_algo_comm.hh>
class public_if_t : public t::plugins::dll::if_t {
public:
using t::plugins::dll::if_t::if_t; // inherit constructor
using t::plugins::dll::if_t::poll_config;// make poll_config test-accessible
};
class mock_if_t : public public_if_t {
public:
using public_if_t::public_if_t; // inherit constructor
MOCK_METHOD(void, update, (), (override)); // detect callbacks to update()
};
class if_t_fixture : public ::testing::Test {
public:
MHAKernel::algo_comm_class_t algo_comm;
mock_if_t dll = {algo_comm.get_c_handle(), "", "dllplugin"};
mhaconfig_t signal_dimensions =
{.channels=1, .domain=MHA_WAVEFORM, .fragsize=96, .wndlen=400,
.fftlen=800, .srate=44100};
};
TEST_F(if_t_fixture, has_patchbay_connect_bandwidth_to_update) {
(void) dll.patchbay; // has patchbay member
(void) dll.bandwidth;// has bandwidth member
EXPECT_CALL(dll, update()).Times(1);
dll.parse("bandwidth=0.2");
}
TEST_F(if_t_fixture, prepare_pushes_config_replaces_NaN) {
public_if_t dll = {algo_comm.get_c_handle(), "", "dllplugin"};
EXPECT_EQ("nan", dll.parse("bandwidth?val"));
EXPECT_THROW(dll.poll_config(), MHA_Error);
dll.prepare_(signal_dimensions);
EXPECT_EQ(MHAParser::StrCnv::val2str(0.2f), dll.parse("bandwidth?val"));
ASSERT_NO_THROW(dll.poll_config());
}
TEST_F(if_t_fixture, all_clock_sources) {
const std::vector<std::string> clock_source_names =
{// from the clock_gettime man page:
"CLOCK_REALTIME",
"CLOCK_BOOTTIME",
"CLOCK_MONOTONIC",
"CLOCK_MONOTONIC_COARSE",
"CLOCK_MONOTONIC_RAW",
"CLOCK_PROCESS_CPUTIME_ID",
"CLOCK_REALTIME_COARSE",
"CLOCK_THREAD_CPUTIME_ID"};
EXPECT_CALL(dll, update()).Times(clock_source_names.size());
for (const std::string & name : clock_source_names) {
EXPECT_NO_THROW(dll.parse("clock_source="+name)) << name;
EXPECT_EQ(name, dll.parse("clock_source?val"));
}
EXPECT_THROW(dll.parse("clock_source=invalid_name"), MHA_Error);
}
TEST_F(if_t_fixture, prepare_propagates_correct_parameters) {
public_if_t dll02 = {algo_comm.get_c_handle(), "", "dllplugin02"};
public_if_t dll10 = {algo_comm.get_c_handle(), "", "dllplugin10"};
dll02.parse("bandwidth=0.2");
dll10.parse("bandwidth=1.0");
dll02.prepare_(signal_dimensions);
dll10.prepare_(signal_dimensions);
// Next line tests also that the namespace exists!
t::plugins::dll::cfg_t * cfg02 = dll02.poll_config();
t::plugins::dll::cfg_t * cfg10 = dll10.poll_config();
// test block update rate
EXPECT_EQ(signal_dimensions.srate / signal_dimensions.fragsize, cfg02->F);
EXPECT_EQ(signal_dimensions.srate / signal_dimensions.fragsize, cfg10->F);
EXPECT_EQ(459.375, cfg10->F); // expected value computed with matlab
// test bandwidth
EXPECT_EQ(0.2f, float(cfg02->B));
EXPECT_EQ(1.0, cfg10->B);
// test 0th order parameter, always 0
EXPECT_EQ(0.0, cfg02->a);
EXPECT_EQ(0.0, cfg10->a);
double omega02 = 2*M_PI*cfg02->B/cfg02->F;
EXPECT_FLOAT_EQ(0.0027355364602686632, omega02);
double omega10 = 2*M_PI*cfg10->B/cfg10->F;
// test 1st order parameter
EXPECT_EQ(sqrt(2)*omega02, cfg02->b);
EXPECT_FLOAT_EQ(0.0038686327624780333, cfg02->b);
EXPECT_EQ(sqrt(2)*omega10, cfg10->b);
// test 2nd order parameter
EXPECT_NEAR(omega02*omega02, cfg02->c,1e-17);
EXPECT_FLOAT_EQ(7.483159725459208e-06,cfg02->c);
EXPECT_NEAR(omega10*omega10, cfg10->c,1e-17);
// test nper and tper constants
EXPECT_EQ(signal_dimensions.fragsize, cfg02->nper);
EXPECT_EQ(signal_dimensions.fragsize/double(signal_dimensions.srate),
cfg02->tper);
EXPECT_EQ(signal_dimensions.fragsize, cfg10->nper);
EXPECT_EQ(signal_dimensions.fragsize/double(signal_dimensions.srate),
cfg10->tper);
}
TEST_F(if_t_fixture, propagate_clock_sources) {
public_if_t dll = {algo_comm.get_c_handle(), "", "dllplugin"};
const std::map<std::string, clockid_t> clock_sources =
{{"CLOCK_REALTIME", CLOCK_REALTIME},
{"CLOCK_BOOTTIME", CLOCK_BOOTTIME},
{"CLOCK_MONOTONIC", CLOCK_MONOTONIC},
{"CLOCK_MONOTONIC_COARSE", CLOCK_MONOTONIC_COARSE},
{"CLOCK_MONOTONIC_RAW", CLOCK_MONOTONIC_RAW},
{"CLOCK_PROCESS_CPUTIME_ID", CLOCK_PROCESS_CPUTIME_ID},
{"CLOCK_REALTIME_COARSE", CLOCK_REALTIME_COARSE},
{"CLOCK_THREAD_CPUTIME_ID", CLOCK_THREAD_CPUTIME_ID}};
dll.prepare_(signal_dimensions);
for (const auto & [name,id] : clock_sources) {
dll.parse("clock_source="+name);
EXPECT_EQ(id, dll.poll_config()->clock_source) << name;
}
}
TEST(cfg_t, process_queries_correct_clock) {
const mhaconfig_t signal_dimensions =
{.channels=1, .domain=MHA_WAVEFORM, .fragsize=96, .wndlen=400,
.fftlen=800, .srate=44100};
const float bandwidth = 0.2f;
t::plugins::dll::cfg_t cfg = {signal_dimensions,bandwidth,"CLOCK_REALTIME"};
struct timespec ts_expected = {.tv_sec=0, .tv_nsec=0};
double d_expected = std::numeric_limits<double>::quiet_NaN();
ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts_expected));
d_expected = ts_expected.tv_sec + ts_expected.tv_nsec / 1e9;
double d_actual = cfg.process().first;
EXPECT_NEAR(d_expected, d_actual, 5e-6); // tolerance may need extension
EXPECT_LT(d_expected, d_actual);
}
TEST(cfg_t, filter_sample_times) {
const mhaconfig_t signal_dimensions = // used to record example timestamps
{.channels=1, .domain=MHA_WAVEFORM, .fragsize=96, .wndlen=400,
.fftlen=800, .srate=44100};
const double bandwidth = 0.2f;
// example raw time stamps measured with MHA on C.H.I.P.
const std::vector<double> sample_times = {1592895666.1088159, 1592895666.1109021, 1592895666.1131172, 1592895666.1152732, 1592895666.1174834, 1592895666.1196198, 1592895666.1218386, 1592895666.1239738, 1592895666.1261997, 1592895666.1283414, 1592895666.1305478, 1592895666.1326807, 1592895666.1349058, 1592895666.1370356, 1592895666.1392608, 1592895666.1413927, 1592895666.1436231, 1592895666.1457472, 1592895666.1479685, 1592895666.1501029, 1592895666.1523242, 1592895666.1544883, 1592895666.1566846, 1592895666.1588211, 1592895666.1610236, 1592895666.1632135, 1592895666.1653957, 1592895666.1675234, 1592895666.1697488, 1592895666.1718788, 1592895666.1741023, 1592895666.1762333, 1592895666.178458, 1592895666.1806433, 1592895666.1828544, 1592895666.184948, 1592895666.1871665, 1592895666.1893029, 1592895666.1915221, 1592895666.1936634, 1592895666.1958764, 1592895666.1980085, 1592895666.2002325, 1592895666.2023649, 1592895666.2045894, 1592895666.2067277, 1592895666.2089686, 1592895666.2110639, 1592895666.2132988, 1592895666.2154362, 1592895666.2176545, 1592895666.2197888, 1592895666.2220149, 1592895666.2241435, 1592895666.226362, 1592895666.2284987, 1592895666.2307184, 1592895666.2328515, 1592895666.2350538, 1592895666.2371776, 1592895666.2393961, 1592895666.2415266, 1592895666.2437637, 1592895666.2458768, 1592895666.2480986, 1592895666.2502327, 1592895666.2524529, 1592895666.2545946, 1592895666.2568157, 1592895666.2589486, 1592895666.2611694, 1592895666.2633095, 1592895666.265527, 1592895666.267657, 1592895666.2698805, 1592895666.2720122, 1592895666.2742357, 1592895666.2763674, 1592895666.2785947, 1592895666.2807238, 1592895666.2829463, 1592895666.2850873, 1592895666.2873015, 1592895666.2894516, 1592895666.2916584, 1592895666.2937942, 1592895666.296011, 1592895666.2981436, 1592895666.3003664, 1592895666.3024993, 1592895666.3047228, 1592895666.3068485, 1592895666.309077, 1592895666.3112099, 1592895666.3134329, 1592895666.3155673, 1592895666.3177974, 1592895666.3199213, 1592895666.3221421, 1592895666.324276};
// smoothed time stamps precomputed with matlab from the raw timestamps
const std::vector<double> t_smooth_expected = {1592895666.1088159, 1592895666.1109927, 1592895666.1131692, 1592895666.1153457, 1592895666.1175222, 1592895666.1196988, 1592895666.1218753, 1592895666.1240518, 1592895666.1262283, 1592895666.1284051, 1592895666.1305816, 1592895666.1327581, 1592895666.1349347, 1592895666.1371114, 1592895666.1392879, 1592895666.1414647, 1592895666.1436412, 1592895666.145818, 1592895666.1479945, 1592895666.1501713, 1592895666.1523478, 1592895666.1545246, 1592895666.1567011, 1592895666.1588778, 1592895666.1610544, 1592895666.1632311, 1592895666.1654079, 1592895666.1675847, 1592895666.1697612, 1592895666.1719379, 1592895666.1741145, 1592895666.1762912, 1592895666.1784678, 1592895666.1806445, 1592895666.1828213, 1592895666.1849983, 1592895666.1871748, 1592895666.1893516, 1592895666.1915281, 1592895666.1937048, 1592895666.1958814, 1592895666.1980581, 1592895666.2002347, 1592895666.2024114, 1592895666.2045879, 1592895666.2067647, 1592895666.2089412, 1592895666.211118, 1592895666.2132945, 1592895666.2154713, 1592895666.2176478, 1592895666.2198246, 1592895666.2220011, 1592895666.2241778, 1592895666.2263544, 1592895666.2285311, 1592895666.2307076, 1592895666.2328844, 1592895666.2350609, 1592895666.2372377, 1592895666.2394142, 1592895666.241591, 1592895666.2437675, 1592895666.2459443, 1592895666.2481208, 1592895666.2502975, 1592895666.2524741, 1592895666.2546508, 1592895666.2568274, 1592895666.2590041, 1592895666.2611806, 1592895666.2633574, 1592895666.2655339, 1592895666.2677107, 1592895666.2698872, 1592895666.272064, 1592895666.2742405, 1592895666.2764173, 1592895666.2785938, 1592895666.2807705, 1592895666.2829471, 1592895666.2851238, 1592895666.2873003, 1592895666.2894771, 1592895666.2916539, 1592895666.2938306, 1592895666.2960072, 1592895666.2981839, 1592895666.3003604, 1592895666.3025372, 1592895666.3047137, 1592895666.3068905, 1592895666.309067, 1592895666.3112438, 1592895666.3134203, 1592895666.3155971, 1592895666.3177738, 1592895666.3199506, 1592895666.3221273, 1592895666.3243041};
ASSERT_EQ(sample_times.size(), t_smooth_expected.size());
t::plugins::dll::cfg_t cfg = {signal_dimensions,bandwidth,"CLOCK_REALTIME"};
for (size_t i = 0; i < sample_times.size(); ++i) {
double actual = cfg.filter_time(sample_times[i]);
EXPECT_NEAR(t_smooth_expected[i],actual,1e-6)
<< "index i=" << i;
}
}
// Local variables:
// compile-command: "make unit-tests"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
| 65.767296 | 2,046 | 0.750024 | [
"vector"
] |
004de372c768a479038fe7cade91b3320820c3ab | 997 | cpp | C++ | tests/test_stat.cpp | puv13/nsptpp | 278c3e1ebb49b5a89884b7dacba8021c699b4e64 | [
"MIT"
] | 3 | 2019-10-11T05:51:42.000Z | 2021-12-15T13:22:57.000Z | tests/test_stat.cpp | puv13/nsptpp | 278c3e1ebb49b5a89884b7dacba8021c699b4e64 | [
"MIT"
] | null | null | null | tests/test_stat.cpp | puv13/nsptpp | 278c3e1ebb49b5a89884b7dacba8021c699b4e64 | [
"MIT"
] | null | null | null | /// file
///
/// Tests for the statistical functions in stat.h
#include "stat.h"
#include <gtest/gtest.h>
#include <valarray>
#include <vector>
TEST(STAT, CanComputeRunningStatistics)
{
RunningStatistics<double> rs;
double max = 1000.;
for (auto x = 1.0; x <= max; ++x) {
rs.push(x);
}
EXPECT_NEAR(rs.mean(), (max + 1.) / 2., 1.e-13 * max);
EXPECT_NEAR(rs.variance(), (max + 1.) * max / 12., 1.e-13 * max);
EXPECT_NEAR(rs.std() * rs.std(), (max + 1.) * max / 12., 1.e-13 * max);
}
TEST(STAT, CanComputeRunningStatisticsArray)
{
RunningStatisticsArray<double, 3L> rsa;
double max = 1000.;
for (auto x = 1.0; x <= max; ++x) {
std::valarray<double> X(x, 3);
rsa.push(X);
}
for (auto i = 0LU; i < 3LU; ++i) {
EXPECT_NEAR(rsa.mean()[i], (max + 1.) / 2., 1.e-13 * max);
EXPECT_NEAR(rsa.variance()[i], (max + 1.) * max / 12., 1.e-13 * max);
EXPECT_NEAR(rsa.std()[i] * rsa.std()[i], (max + 1.) * max / 12.,
1.e-13 * max);
}
}
| 21.212766 | 73 | 0.555667 | [
"vector"
] |
00504af0a7763e72020fdd47a5b4b46e1992fd78 | 9,024 | cpp | C++ | Samples/Step02-Creating_Swapchain.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 5 | 2019-03-02T16:29:15.000Z | 2021-11-07T11:07:53.000Z | Samples/Step02-Creating_Swapchain.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | null | null | null | Samples/Step02-Creating_Swapchain.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 2 | 2018-07-10T18:15:40.000Z | 2020-01-03T04:02:32.000Z | //
// Created by aicdg on 2017/6/23.
//
#include "CookbookSampleFramework.h"
#include "All_Lib.h"
using namespace VKCookbook;
class Sample : public VulkanCookbookSampleBase {
VkDestroyer<VkInstance> Instance;
VkPhysicalDevice PhysicalDevice;
VkDestroyer<VkSurfaceKHR> PresentationSurface;
VkDestroyer<VkDevice> LogicalDevice;
uint32_t GraphicsQueueFamilyIndex;
uint32_t PresentQueueFamilyIndex;
VkQueue GraphicsQueue;
VkQueue PresentQueue;
VkDestroyer<VkSwapchainKHR> Swapchain;
std::vector<VkImage> SwapchainImages;
VkDestroyer<VkSemaphore> ImageAcquiredSemaphore;
VkDestroyer<VkSemaphore> ReadyToPresentSemaphore;
VkDestroyer<VkCommandPool> CommandPool;
VkCommandBuffer CommandBuffer;
virtual bool Initialize( WindowParameters window_parameters ) override {
// Instance creation
if( !ConnectWithVulkanLoaderLibrary( VulkanLibrary ) ) {
return false;
}
if( !LoadFunctionExportedFromVulkanLoaderLibrary( VulkanLibrary ) ) {
return false;
}
if( !LoadGlobalLevelFunctions() ) {
return false;
}
std::vector<char const *> instance_extensions;
if( !CreateVulkanInstanceWithWsiExtensionsEnabled( instance_extensions, "Vulkan Cookbook", *Instance ) ) {
return false;
}
if( !LoadInstanceLevelFunctions( *Instance, instance_extensions ) ) {
return false;
}
// Presentation surface creation
InitVkDestroyer( Instance, PresentationSurface );
if( !CreatePresentationSurface( *Instance, window_parameters, *PresentationSurface ) ) {
return false;
}
// Logical device creation
std::vector<VkPhysicalDevice> physical_devices;
EnumerateAvailablePhysicalDevices( *Instance, physical_devices );
for( auto & physical_device : physical_devices ) {
if( !SelectIndexOfQueueFamilyWithDesiredCapabilities( physical_device, VK_QUEUE_GRAPHICS_BIT, GraphicsQueueFamilyIndex ) ) {
continue;
}
if( !SelectQueueFamilyThatSupportsPresentationToGivenSurface( physical_device, *PresentationSurface, PresentQueueFamilyIndex ) ) {
continue;
}
std::vector<QueueInfo> requested_queues = { { GraphicsQueueFamilyIndex, { 1.0f } } };
if( GraphicsQueueFamilyIndex != PresentQueueFamilyIndex ) {
requested_queues.push_back( { PresentQueueFamilyIndex, { 1.0f } } );
}
VkDestroyer<VkDevice> logical_device;
std::vector<char const *> device_extensions;
if( !CreateLogicalDeviceWithWsiExtensionsEnabled( physical_device, requested_queues, device_extensions, nullptr, *logical_device ) ) {
continue;
} else {
if( !LoadDeviceLevelFunctions( *logical_device, device_extensions ) ) {
continue;
}
PhysicalDevice = physical_device;
LogicalDevice = std::move( logical_device );
GetDeviceQueue( *LogicalDevice, GraphicsQueueFamilyIndex, 0, GraphicsQueue );
GetDeviceQueue( *LogicalDevice, PresentQueueFamilyIndex, 0, PresentQueue );
break;
}
}
if( !LogicalDevice ) {
return false;
}
// Swapchain creation
if( !CreateSwapchain() ) {
return false;
}
InitVkDestroyer( LogicalDevice, ImageAcquiredSemaphore );
if( !CreateSemaphore( *LogicalDevice, *ImageAcquiredSemaphore ) ) {
return false;
}
InitVkDestroyer( LogicalDevice, ReadyToPresentSemaphore );
if( !CreateSemaphore( *LogicalDevice, *ReadyToPresentSemaphore ) ) {
return false;
}
// Command buffers creation
InitVkDestroyer( LogicalDevice, CommandPool );
if( !CreateCommandPool( *LogicalDevice, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, GraphicsQueueFamilyIndex, *CommandPool ) ) {
return false;
}
std::vector<VkCommandBuffer> command_buffers;
if( !AllocateCommandBuffers( *LogicalDevice, *CommandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1, command_buffers ) ) {
return false;
}
CommandBuffer = command_buffers[0];
return true;
}
bool CreateSwapchain() {
WaitForAllSubmittedCommandsToBeFinished( *LogicalDevice );
Ready = false;
VkFormat swapchain_image_format;
VkExtent2D swapchain_image_size;
VkDestroyer<VkSwapchainKHR> old_swapchain = std::move( Swapchain );
InitVkDestroyer( LogicalDevice, Swapchain );
if( !CreateSwapchainWithR8G8B8A8FormatAndMailboxPresentMode( PhysicalDevice, *PresentationSurface, *LogicalDevice, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, swapchain_image_size, swapchain_image_format, *old_swapchain, *Swapchain, SwapchainImages ) ) {
return false;
}
if( *Swapchain ) {
Ready = true;
}
return true;
}
virtual bool Draw() override {
WaitForAllSubmittedCommandsToBeFinished( *LogicalDevice );
uint32_t image_index;
if( !AcquireSwapchainImage( *LogicalDevice, *Swapchain, *ImageAcquiredSemaphore, VK_NULL_HANDLE, image_index ) ) {
return false;
}
if( !BeginCommandBufferRecordingOperation( CommandBuffer, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr ) ) {
return false;
}
ImageTransition image_transition_before_drawing = {
SwapchainImages[image_index], // VkImage Image
0, // VkAccessFlags CurrentAccess
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags NewAccess
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout CurrentLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout NewLayout
VK_QUEUE_FAMILY_IGNORED, // uint32_t CurrentQueueFamily
VK_QUEUE_FAMILY_IGNORED, // uint32_t NewQueueFamily
VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect
};
SetImageMemoryBarrier( CommandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, { image_transition_before_drawing } );
// Put drawing code here
// ...
ImageTransition image_transition_before_present = {
SwapchainImages[image_index], // VkImage Image
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags CurrentAccess
VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags NewAccess
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout CurrentLayout
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout NewLayout
VK_QUEUE_FAMILY_IGNORED, // uint32_t CurrentQueueFamily
VK_QUEUE_FAMILY_IGNORED, // uint32_t NewQueueFamily
VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect
};
SetImageMemoryBarrier( CommandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { image_transition_before_present } );
if( !EndCommandBufferRecordingOperation( CommandBuffer ) ) {
return false;
}
WaitSemaphoreInfo wait_semaphore_info = {
*ImageAcquiredSemaphore, // VkSemaphore Semaphore
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT // VkPipelineStageFlags WaitingStage
};
if( !SubmitCommandBuffersToQueue( PresentQueue, { wait_semaphore_info }, { CommandBuffer }, { *ReadyToPresentSemaphore }, VK_NULL_HANDLE ) ) {
return false;
}
PresentInfo present_info = {
*Swapchain, // VkSwapchainKHR Swapchain
image_index // uint32_t ImageIndex
};
if( !PresentImage( PresentQueue, { *ReadyToPresentSemaphore }, { present_info } ) ) {
return false;
}
return true;
}
virtual bool Resize() override {
if( !CreateSwapchain() ) {
return false;
}
return true;
}
virtual void Deinitialize() override {
if( LogicalDevice ) {
WaitForAllSubmittedCommandsToBeFinished( *LogicalDevice );
}
}
};
VULKAN_COOKBOOK_SAMPLE_FRAMEWORK( "02 - Creating Swapchain", 50, 25, 1280, 800, Sample )
| 41.585253 | 255 | 0.617908 | [
"vector"
] |
0052f01c8bb16e6c50866af8a8c92331f1ba89cd | 4,457 | cpp | C++ | dlls/fmod_ambient.cpp | BryanHaley/halflife-updated | b0c072ca496ece59a83008240958833f1e3684a2 | [
"Unlicense"
] | 1 | 2022-03-20T04:00:59.000Z | 2022-03-20T04:00:59.000Z | dlls/fmod_ambient.cpp | BryanHaley/halflife-updated-fmod | b0c072ca496ece59a83008240958833f1e3684a2 | [
"Unlicense"
] | null | null | null | dlls/fmod_ambient.cpp | BryanHaley/halflife-updated-fmod | b0c072ca496ece59a83008240958833f1e3684a2 | [
"Unlicense"
] | null | null | null | #include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "UserMessages.h"
#include <string>
#include <iostream>
class CFmodAmbient : public CBaseEntity
{
public:
void Spawn() override;
void Use(CBaseEntity* pActivator, CBaseEntity* pOther, USE_TYPE useType, float value) override;
bool KeyValue(KeyValueData* pkvd) override;
void EXPORT SendMsg(void);
bool m_fLooping;
bool m_fPlayOnStart;
private:
float volume;
float min_atten;
float max_atten;
float pitch;
};
LINK_ENTITY_TO_CLASS(fmod_ambient, CFmodAmbient);
#define FMOD_AMBIENT_LOOPING 1
#define FMOD_AMBIENT_PLAYONSTART 2
void CFmodAmbient::Spawn()
{
if (FStringNull(pev->message))
{
ALERT(at_error, "EMPTY FMOD_AMBIENT AT: %f, %f, %f\n", pev->origin.x, pev->origin.y, pev->origin.z);
REMOVE_ENTITY(ENT(pev));
return;
}
if (FBitSet(pev->spawnflags, FMOD_AMBIENT_LOOPING))
m_fLooping = true;
if (FBitSet(pev->spawnflags, FMOD_AMBIENT_PLAYONSTART))
m_fPlayOnStart = true;
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_NONE;
if (m_fPlayOnStart)
{
SetThink(&CFmodAmbient::SendMsg);
pev->nextthink = gpGlobals->time + 0.2f; // TODO: Make sure this is a long enough delay or the message might get dropped
}
}
void CFmodAmbient::Use(CBaseEntity* pActivator, CBaseEntity* pOther, USE_TYPE useType, float value)
{
SendMsg();
}
void CFmodAmbient::SendMsg(void)
{
// IF YOU MODIFY THIS DON'T FORGET TO UPDATE MsgFunc_FmodSave/Load
// Name of the channel and path of the sound
std::string msg = STRING(pev->targetname) + std::string("\n") + STRING(pev->message);
// TODO: Figure out if we can truly only write one string in a message or if I'm doing something wrong
MESSAGE_BEGIN(MSG_ALL, gmsgFmodAmb, NULL);
WRITE_STRING(msg.c_str());
WRITE_BYTE(m_fLooping);
WRITE_COORD(pev->origin.x);
WRITE_COORD(pev->origin.y);
WRITE_COORD(pev->origin.z);
WRITE_COORD(volume); // Default: 1.0
WRITE_COORD(min_atten); // Default: 40.0
WRITE_COORD(max_atten); // Default: 40000.0
WRITE_COORD(pitch); // Default: 1.0 (2.0 = one octave up, 0.5 = one octave down)
MESSAGE_END();
// TODO: sanitize inputs
}
// Load key/value pairs
bool CFmodAmbient::KeyValue(KeyValueData* pkvd)
{
// volume
if (FStrEq(pkvd->szKeyName, "volume"))
{
volume = atof(pkvd->szValue);
return true;
}
// minatten
if (FStrEq(pkvd->szKeyName, "minatten"))
{
min_atten = atof(pkvd->szValue);
return true;
}
// maxatten
else if (FStrEq(pkvd->szKeyName, "maxatten"))
{
max_atten = atof(pkvd->szValue);
return true;
}
// pitch
else if (FStrEq(pkvd->szKeyName, "pitch"))
{
pitch = atof(pkvd->szValue);
return true;
}
return CBaseEntity::KeyValue(pkvd);
}
// -----------------------------------------------------------------------------------------------
class CFmodPause : public CBaseEntity
{
public:
void Spawn() override;
void Use(CBaseEntity* pActivator, CBaseEntity* pOther, USE_TYPE useType, float value) override;
};
LINK_ENTITY_TO_CLASS(fmod_pause, CFmodPause);
void CFmodPause::Spawn()
{
if (FStringNull(pev->targetname) || FStringNull(pev->target))
{
ALERT(at_error, "EMPTY FMOD_PAUSE AT: %f, %f, %f\n", pev->origin.x, pev->origin.y, pev->origin.z);
REMOVE_ENTITY(ENT(pev));
return;
}
}
void CFmodPause::Use(CBaseEntity* pActivator, CBaseEntity* pOther, USE_TYPE useType, float value)
{
MESSAGE_BEGIN(MSG_ALL, gmsgFmodPause, NULL);
WRITE_STRING(STRING(pev->target));
MESSAGE_END();
}
// -----------------------------------------------------------------------------------------------
class CFmodSeek : public CBaseEntity
{
public:
void Spawn() override;
void Use(CBaseEntity* pActivator, CBaseEntity* pOther, USE_TYPE useType, float value) override;
bool KeyValue(KeyValueData* pkvd) override;
private:
float seek_to;
};
LINK_ENTITY_TO_CLASS(fmod_seek, CFmodSeek);
void CFmodSeek::Spawn()
{
if (FStringNull(pev->targetname) || FStringNull(pev->target))
{
ALERT(at_error, "EMPTY FMOD_SEEK AT: %f, %f, %f\n", pev->origin.x, pev->origin.y, pev->origin.z);
REMOVE_ENTITY(ENT(pev));
return;
}
}
void CFmodSeek::Use(CBaseEntity* pActivator, CBaseEntity* pOther, USE_TYPE useType, float value)
{
MESSAGE_BEGIN(MSG_ALL, gmsgFmodSeek, NULL);
WRITE_STRING(STRING(pev->target));
WRITE_COORD(seek_to);
MESSAGE_END();
}
bool CFmodSeek::KeyValue(KeyValueData* pkvd)
{
// seek
if (FStrEq(pkvd->szKeyName, "seek"))
{
seek_to = atof(pkvd->szValue);
return true;
}
return CBaseEntity::KeyValue(pkvd);
} | 23.834225 | 122 | 0.686785 | [
"solid"
] |
00553647ee135706596c599b8131652148cd2965 | 2,259 | cpp | C++ | src/clotho/fitness/normal_fitness_generator.cpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-06-16T21:27:57.000Z | 2022-01-25T23:26:54.000Z | src/clotho/fitness/normal_fitness_generator.cpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2015-06-16T21:12:42.000Z | 2015-06-23T12:41:00.000Z | src/clotho/fitness/normal_fitness_generator.cpp | putnampp/clotho | 6dbfd82ef37b4265381cd78888cd6da8c61c68c2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright 2015 Patrick Putnam
//
// 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 "clotho/fitness/normal_fitness_generator.hpp"
#include "clotho/fitness/fitness_toolkit.hpp"
normal_fitness_generator::normal_fitness_generator() :
mutation_rate_parameter< double >()
{
fitness_toolkit::getInstance()->register_tool( this );
}
normal_fitness_generator::normal_fitness_generator( boost::property_tree::ptree & config ) :
mutation_rate_parameter( config )
{ }
std::shared_ptr< ifitness_generator > normal_fitness_generator::create( boost::property_tree::ptree & config ) const {
std::shared_ptr< ifitness_generator > t( new normal_fitness_generator( config ) );
return t;
}
std::shared_ptr< ifitness > normal_fitness_generator::generate( const std::vector< std::vector< double > > & pop_traits ) {
return generate( pop_traits.size() );
}
std::shared_ptr< ifitness > normal_fitness_generator::generate( size_t N ) {
// theoretical standard deviation:
// sqrt( 2 * P * N * mu), where
// N - is the individual count
// P - is the ploidy of an individual = 2.0
// mu - mutation rate per sequence
//
// NP = haploid sequence count of the population
double n = 4.0 * (double)N;
n *= m_mu;
n = sqrt(n); // theoretical standard deviation
std::shared_ptr< ifitness > r( new result_type( 0., n ) );
return r;
}
const std::string normal_fitness_generator::name() const {
return NORM_NAME;
}
void normal_fitness_generator::log( std::ostream & out ) const {
out << "{" << NORM_NAME << "_gen"
<< ", " << m_mu
<< "}\n";
}
normal_fitness_generator::~normal_fitness_generator() {}
static const normal_fitness_generator nfg_reg;
| 33.716418 | 123 | 0.697211 | [
"vector"
] |
0067857c48a0d002881852f2caf4650dbae22e52 | 1,103 | cpp | C++ | unittests/workers.cpp | dandycheung/taskflow | 96620cce7cf3bb67e039dad4ecd556ba61347787 | [
"MIT"
] | 3,457 | 2018-06-09T15:36:42.000Z | 2020-06-01T22:09:25.000Z | unittests/workers.cpp | dandycheung/taskflow | 96620cce7cf3bb67e039dad4ecd556ba61347787 | [
"MIT"
] | 146 | 2018-06-11T04:11:22.000Z | 2020-06-01T20:59:21.000Z | unittests/workers.cpp | dandycheung/taskflow | 96620cce7cf3bb67e039dad4ecd556ba61347787 | [
"MIT"
] | 426 | 2018-06-06T18:01:16.000Z | 2020-06-01T05:26:17.000Z | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest.h>
#include <taskflow/taskflow.hpp>
class CustomWorkerBehavior : public tf::WorkerInterface {
public:
CustomWorkerBehavior(std::atomic<size_t>& counter, std::vector<size_t>& ids) :
_counter {counter},
_ids {ids} {
}
void scheduler_prologue(tf::Worker& wv) override {
_counter++;
std::scoped_lock lock(_mutex);
_ids.push_back(wv.id());
}
void scheduler_epilogue(tf::Worker&, std::exception_ptr) override {
_counter++;
}
std::atomic<size_t>& _counter;
std::vector<size_t>& _ids;
std::mutex _mutex;
};
TEST_CASE("WorkerInterface" * doctest::timeout(300)) {
const size_t N = 10;
for(size_t n=1; n<=N; n++) {
std::atomic<size_t> counter{0};
std::vector<size_t> ids;
{
tf::Executor executor(n, std::make_shared<CustomWorkerBehavior>(counter, ids));
}
REQUIRE(counter == n*2);
REQUIRE(ids.size() == n);
std::sort(ids.begin(), ids.end(), std::less<int>{});
for(size_t i=0; i<n; i++) {
REQUIRE(ids[i] == i);
}
}
}
| 15.757143 | 85 | 0.621034 | [
"vector"
] |
006e20814c6334c2292fce2de7e4a049e3203d1f | 1,919 | cpp | C++ | Educational-Round-86/Multiple_Testcases.cpp | error400-del/CodeForces-Solution | 33d5117283d46977b75127dd0a1ed16d570eba4d | [
"MIT"
] | 1 | 2020-10-17T19:38:22.000Z | 2020-10-17T19:38:22.000Z | Educational-Round-86/Multiple_Testcases.cpp | error400-del/CodeForces-Solution | 33d5117283d46977b75127dd0a1ed16d570eba4d | [
"MIT"
] | 4 | 2020-10-17T12:12:55.000Z | 2020-10-20T06:34:08.000Z | Educational-Round-86/Multiple_Testcases.cpp | error400-del/CodeForces-Solution | 33d5117283d46977b75127dd0a1ed16d570eba4d | [
"MIT"
] | 7 | 2020-10-17T12:22:21.000Z | 2020-10-20T06:54:25.000Z | // #pragma GCC optimize("O3", "unroll-loops")
// #pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef long long int ll;
#define endl '\n'
#define ld long double
#define all(a) a.begin(),a.end()
#define int long long
#define pb push_back
#define pii pair <int, int>
#define ff first
#define ss second
#define sz(v) (int)v.size()
#define UB upper_bound
#define LB lower_bound
#define OST tree<pii, null_type,less<pii>, rb_tree_tag,tree_order_statistics_node_update>
const int INF = 1e15 + 0;
const int mod = 1e9 + 7;
//const int mod = 998244353;
set <pii> s;
void solve() {
int n, k, x, steps = 1;
pii p;
cin >> n >> k;
int data[n+5], C[k+5];
vector <int> ans[n+5];
for(int i = 1; i <= n; i++) {
int x; cin >> x;
data[i] = x;
}
for(int i = 1; i <= k; i++) {
int x; cin >> x;
C[i] = x;
}
sort(data + 1, data + n + 1);
int left = C[1]; ans[0].pb(data[n]); s.insert({1,0});
for(int i = n-1; i >= 1; i--) {
x = C[data[i]];
p = *(s.begin());
auto it = s.begin();
if(p.ff >= x) {
s.insert({1,steps}); ans[steps].pb(data[i]); steps++;
}
else {
s.erase(it);
s.insert({p.ff+1,p.ss});
ans[p.ss].pb(data[i]);
}
}
cout << steps << endl;
for(int i = 0; i < steps; i++) {
cout << sz(ans[i]) << " ";
for(auto l : ans[i]) cout << l << " ";
cout << '\n';
}
}
signed main() {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t = 1; // cin >> t;
for(int i = 1; i <= t; i++) {
solve();
}
}
| 22.057471 | 89 | 0.510683 | [
"vector"
] |
007bc08c864a175e9a9055204434b7baf01fec09 | 13,239 | hpp | C++ | include/coring/io_context.hpp | rzbdz/libcoring | dffd4c2193ac4f2ab8822b5e047c056d6eb11f8d | [
"MIT"
] | 4 | 2022-01-08T21:03:07.000Z | 2022-02-18T11:15:10.000Z | include/coring/io_context.hpp | rzbdz/libcoring | dffd4c2193ac4f2ab8822b5e047c056d6eb11f8d | [
"MIT"
] | null | null | null | include/coring/io_context.hpp | rzbdz/libcoring | dffd4c2193ac4f2ab8822b5e047c056d6eb11f8d | [
"MIT"
] | null | null | null |
#pragma once
#ifndef CORING_IO_CONTEXT_HPP
#define CORING_IO_CONTEXT_HPP
#include <functional>
#include <thread>
#include <latch>
#include <sys/poll.h>
#include <sys/signalfd.h>
#include <sys/eventfd.h>
#include <deque>
#include "coring/coring_config.hpp"
#include "coring/detail/io/io_uring_context.hpp"
#include "coring/detail/noncopyable.hpp"
#include "coring/detail/debug.hpp"
#include "coring/task.hpp"
#include "coring/async_task.hpp"
#include "coring/when_all.hpp"
#include "coring/async_scope.hpp"
#include "coring/single_consumer_async_auto_reset_event.hpp"
#include "coring/detail/thread.hpp"
#include "coring/execute.hpp"
#include "timer.hpp"
#include "signals.hpp"
#include "sync_wait.hpp"
namespace coring {
class io_context;
struct coro {
inline static auto get_io_context() {
auto ptr = reinterpret_cast<coring::io_context *>(io_context_thread_local);
// NO exception thrown, just make it support nullptr
return ptr;
}
static io_context &get_io_context_ref() {
auto ptr = reinterpret_cast<coring::io_context *>(io_context_thread_local);
if (ptr == nullptr) {
throw std::runtime_error{"no io_context bind"};
}
return *ptr;
}
inline static thread_local io_context *io_context_thread_local;
void static provide(io_context *ctx) { io_context_thread_local = ctx; }
/// Just make sure you are in a coroutine before calling this,
/// it's not the same spawn as the one in boost::asio.
inline static void spawn(task<> &&t) {}
};
} // namespace coring
namespace coring {
///
/// Manual for multi-thread or SQPOLL usage
/// @param entries Maximum sqe can be gotten without submitting
/// @param p a params structure, you can only specify flags which can be used to set various flags and sq_thread_cpu
/// and sq_thread_idle fields
/// < p>p.flags could be one of these (most used):</p>
/// < p>IORING_SETUP_IOPOLL</p>
/// < p>IORING_SETUP_SQPOLL</p>
/// < p>IORING_SETUP_ATTACH_WQ, with this set, the wq_fd should be set to same fd to avoid multiple thread pool</p>
/// < p>other filed of the params are:</p>
/// < p>sq_thread_cpu: the cpuid, you can get one from gcc utility or something, I didn't find detailed document for
/// this field</p>
/// < p>sq_thread_idle: a milliseconds to stop sq polling thread.</p>
///
class io_context : public coring::detail::io_uring_context {
// use inheritance here because it's too long...
public:
typedef io_context *executor_t;
private:
typedef coring::task<> my_todo_t;
static constexpr uint64_t EV_BIG_VALUE = 0x1fffffffffffffff;
static constexpr uint64_t EV_SMALL_VALUE = 0x1;
static constexpr uint64_t EV_STOP_MSG = EV_BIG_VALUE;
static constexpr uint64_t EV_WAKEUP_MSG = EV_SMALL_VALUE;
void create_eventfd() {
// NONBLOCK for direct write, no influence on io_uring_read
// internal_event_fd_ = ::eventfd(0, EFD_NONBLOCK);
internal_event_fd_ = ::eventfd(0, 0);
if (internal_event_fd_ == -1) {
// TODO: error handling
// it's another story.
// either use the exception or simply print some logs and abort.
// https://isocpp.org/wiki/faq/exceptions#ctors-can-throw
throw std::runtime_error("o/s fails to allocate more fd");
}
}
void create_signalfd(signal_set &s) {
internal_signal_fd_ = ::signalfd(-1, s.get_set(), 0);
if (internal_signal_fd_ == -1) {
// TODO: error handling
// it's another story.
// either use the exception or simply print some logs and abort.
// https://isocpp.org/wiki/faq/exceptions#ctors-can-throw
throw std::runtime_error("o/s fails to allocate more fd");
}
}
public:
io_context(int entries = 64, uint32_t flags = 0, uint32_t wq_fd = 0)
: detail::io_uring_context{entries, flags, wq_fd} {
create_eventfd();
}
/// stupid name, only for dev channel...
/// \return a io_context isntance.
static inline io_context dup_from_big_brother(io_context *bro, int entries = 64) {
auto fl = bro->ring.flags;
if (fl & IORING_SETUP_SQPOLL) {
// You can only get real entries from ring->sz or the para when you init one ,we just pass in one...
// RVO should work here.
return io_context{entries, fl | IORING_SETUP_ATTACH_WQ, static_cast<uint32_t>(bro->ring_fd())};
} else {
return io_context{entries, fl};
}
}
io_context(int entries, io_uring_params p) : detail::io_uring_context{entries, p} { create_eventfd(); }
io_context(int entries, io_uring_params *p) : detail::io_uring_context{entries, p} { create_eventfd(); }
void register_signals(signal_set &s, __sighandler_t func = nullptr) {
create_signalfd(s);
signal_func_ = func;
}
private:
coring::async_run init_signalfd(__sighandler_t func) {
struct signalfd_siginfo siginfo {};
do {
co_await read(internal_signal_fd_, &siginfo, sizeof(siginfo), 0, 0);
if (func != nullptr) {
func(siginfo.ssi_signo);
}
if (siginfo.ssi_signo == SIGINT) {
stopped_ = true;
}
} while (!stopped_);
}
/// this coroutine should start (and be suspended) at io_context start
coring::async_run init_eventfd() {
uint64_t msg;
while (!stopped_) {
// Don't use LOG_DEBUG_RAW since it's not thread safe (only use when testing)
// LOG_DEBUG_RAW("co_await the eventfd!, must be inside of the loop");
co_await read(internal_event_fd_, &msg, 8, 0, 0);
// TODO: I don't know if this is a good solution..
// since strict-ordering memory model are available on current x86 CPUs.
// But if volatile restrict program to read from memory, it would be costly.
if (msg >= EV_STOP_MSG) {
stopped_ = true;
}
}
}
/// TODO: I just find a other approaches to implement user level timer...
/// In the current version, I just post requests of timeout everytime I wakeup, that is
/// stupid since there is a api- timeout who rely on a hrtimer in the kernel.
/// @see https://lwn.net/Articles/800308/
/// But the order of completions rises by prep_timeout is not guaranteed and thus I think
/// we do need a user timer...(or just use linked request). Also, when the amount is large,
/// I don't think the hrtimer(rbtree) would be better (we can do testing though).
/// The other approach is just use wait_cqe_with_timeout/io_uring_enter,
/// just like what we did with epoll before.
/// @see: https://github.com/axboe/liburing/issues/4
/// \return
async_run init_timeout_callback() {
while (!stopped_) {
while (timer_.has_more_timeouts()) {
auto tmp = timer_.get_next_expiration();
co_await timeout(&tmp);
timer_.handle_events();
}
co_await timer_event_;
}
}
void notify(uint64_t msg) {
if (::write(internal_event_fd_, &msg, sizeof(msg)) == -1) {
// TODO: do something
// it's ok since eventfd isn't been read.
// when it's going to stop, it's fine
// to stop it synchronously.
;
}
// TODO: do something (logging)
}
void do_todo_list() {
std::vector<my_todo_t> local_copy{};
local_copy.swap(todo_list_);
for (auto &t : local_copy) {
// user should not pass any long running task in here.
// that is to say, a task with co_await inside instead of
// some blocking task...
execute(std::move(t));
}
}
// TODO: I won't deal with cancellation now...(2)
// Cancellation is complicated, what boost.asio do is
// just provide interface to cancel all async operations on specific socket (by closing it).
// Maybe std::stop_source would be enough for most cases.
// If need to close a socket/file, please make sure you use the IORING_OP_CLOSE with io_uring
// for revoking all previous posts.
// @see: https://patchwork.kernel.org/project/linux-fsdevel/patch/20191213183632.19441-9-axboe@kernel.dk/
void do_cancel_list() { throw std::invalid_argument("not available in this channel"); }
public:
inline executor_t as_executor() { return this; }
bool inline on_this_thread() { return reinterpret_cast<decltype(this)>(coro::get_io_context()) == this; }
/// Immediate issue a one-way-task to run the awaitable.
/// Make sure you are in the current thread (or, inside of a coroutine running on the io_context).
/// check io_context::spawn(...).
template <typename AWAITABLE>
void execute(AWAITABLE &&awaitable) {
// now it was call inside of the wait_for_completion,
// so it would be submitted soon (at next round of run)
my_scope_.spawn(std::forward<AWAITABLE>(awaitable));
}
/// Just don't use this, check io_context::spawn(...).
void schedule(my_todo_t &&awaitable) { todo_list_.emplace_back(std::move(awaitable)); }
void schedule(std::vector<my_todo_t> &task_list) {
if (todo_list_.empty()) {
std::swap(todo_list_, task_list);
} else {
std::move(task_list.begin(), task_list.end(), std::back_inserter(todo_list_));
task_list.clear();
}
}
/// set timeout
/// \tparam AWAITABLE
/// \param awaitable
template <typename AWAITABLE, typename Duration>
void run_after(AWAITABLE &&awaitable, Duration &&duration) {}
public:
// on the same thread...
void register_timeout(std::coroutine_handle<> cont, std::chrono::microseconds exp) {
// TODO: if no this wrapper, the async_run would be exposed to user.
// Actually this two argument is all POD...no move required.
timer_.add_event(cont, exp);
timer_event_.set();
}
void wakeup() { notify(EV_WAKEUP_MSG); }
inline void submit() { wakeup(); }
/// Spawn a task on current event loop
///
/// Since liburing is not thread-safe(especially with io_uring_get_sqe), we
/// CANNOT spawn anything related to a io_context sqe manipulation outside of
/// the context thread, usually new task would be spawned when the get_completion
/// goes to.
///
/// Updates: after some investigation, I think we don't need any multithreading here,
/// just forbids it. If we need threading, do our own or checkout another branch to try it out.
///
/// \param awaitable a task, must be void return such as task<>
template <typename AWAITABLE>
void inline spawn(AWAITABLE &&awaitable) {
execute(std::forward<AWAITABLE>(awaitable));
}
~io_context() noexcept override {
// have to free resources
::close(internal_event_fd_);
if (internal_signal_fd_ != -1) {
::close(internal_signal_fd_);
}
// have to co_await async_scope
// FIXME: dangerous here.. we lost the scope, memory leaking
// we can maintain a list of task/coroutine, then destroy then all, but it's not simple to impl.
// another better solution would be using a timeout for all operation, but it damage the performance for
// creating lots of linked timeout to the hrtimer in kernel.
// a better one should be done using the cancellation, we can just keep a list of user_data (maybe using a
// std::unordered_set) and cancel all of them.
[a = this]() -> async_run { co_await a->my_scope_.join(); }();
}
private:
/// the best practice might be using a eventfd in io_uring_context
/// or manage your timing event using a rb-tree timing wheel etc. to
/// use IORING_OP_TIMEOUT like timerfd in epoll?
/// more info: @see:https://kernel.dk/io_uring_context-whatsnew.pdf
void do_run() {
// bind thread.
stopped_ = false;
init_eventfd();
// do scheduled tasks
if (internal_signal_fd_ != -1) {
init_signalfd(signal_func_);
}
do_todo_list();
init_timeout_callback();
while (!stopped_) {
// the coroutine would be resumed inside io_token.resolve() method
// blocking syscall. Call io_uring_submit_and_wait.
wait_for_completions_then_handle();
do_todo_list();
}
// TODO: handle stop event, deal with async_scope (issue cancellations then call join) exiting
}
public:
void run() {
coro::provide(this);
do_run();
coro::provide(nullptr);
}
void run(std::latch &cd) {
coro::provide(this);
cd.count_down();
do_run();
coro::provide(nullptr);
}
void stop() {
// LOG_TRACE("server done!");
if (reinterpret_cast<coring::io_context *>(coro::get_io_context()) == this) {
stopped_ = true;
} else {
// lazy stop
// notify this context, then fall into the run()-while loop-break,
notify(EV_STOP_MSG);
}
}
private:
// io_uring_context engine inherited from uio
// a event fd for many uses
int internal_event_fd_{-1};
int internal_signal_fd_{-1};
std::mutex mutex_;
// no volatile for all changes are made in the same thread
// not using stop_token for better performance.
// TODO: should we use a atomic and stop using eventfd msg to demux ?
bool stopped_{true};
// for co_spawn
std::vector<my_todo_t> todo_list_{};
// TODO: I won't deal with cancellation now...(1)
// for cancelling
std::vector<io_cancel_token> to_cancel_list_{};
coring::async_scope my_scope_{};
coring::timer timer_{};
coring::single_consumer_async_auto_reset_event timer_event_;
__sighandler_t signal_func_{nullptr};
};
inline void co_spawn(task<> &&t) { coro::get_io_context_ref().spawn(std::move(t)); }
} // namespace coring
#endif // CORING_IO_CONTEXT_HPP
| 36.073569 | 116 | 0.686608 | [
"vector",
"model"
] |
0084278ded8bdb88fdc9a6486cd06c08466c56df | 5,250 | cpp | C++ | test/explorerTest.cpp | ajeetwankhede/The-Explorer-Robot | b1693cdeb5b657ee7dfd720107d91bb35559c031 | [
"MIT"
] | 2 | 2019-06-03T03:12:20.000Z | 2020-04-25T08:04:50.000Z | test/explorerTest.cpp | ajeetwankhede/The-Explorer-Robot | b1693cdeb5b657ee7dfd720107d91bb35559c031 | [
"MIT"
] | null | null | null | test/explorerTest.cpp | ajeetwankhede/The-Explorer-Robot | b1693cdeb5b657ee7dfd720107d91bb35559c031 | [
"MIT"
] | 1 | 2019-10-09T09:02:03.000Z | 2019-10-09T09:02:03.000Z | /************************************************************************
MIT License
Copyright (c) 2018 Ajeet Wankhede
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.
*************************************************************************/
/**
* @copyright MIT License 2018 Ajeet Wankhede
* @file explorerTest.cpp
* @author Ajeet Wankhede (driver) and Likhita Madiraju (navigator)
* @date 12/10/2018
* @version 1.0
*
* @brief UMD ENPM 808X, Final Project, The Explorer Robot
*
* @section DESCRIPTION
*
* This is a test source file for testing Explorer class
*/
#include <ros/ros.h>
#include <gtest/gtest.h>
#include <std_srvs/Empty.h>
#include <ros/service_client.h>
#include "std_msgs/Float64.h"
#include "sensor_msgs/LaserScan.h"
#include "geometry_msgs/Twist.h"
#include "the_explorer_robot/change_speed.h"
#include "explorer.hpp"
/**
* @brief This is a test to check the existence of ROS service change_speed
* provided by explorer node
*/
TEST(testexplorerTest, serviceExistenceTest) {
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
// Setup a client to the service
ros::ServiceClient client =
n.serviceClient<the_explorer_robot::change_speed>("change_speed");
// Check if the service created by talker node exists
bool exists(client.waitForExistence(ros::Duration(10)));
EXPECT_TRUE(exists);
}
/**
* @brief This is a test to check if the change speed service works correctly
*/
TEST(testexplorerTest, serviceTest) {
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
// Setup a client to request the service
ros::ServiceClient client =
n.serviceClient<the_explorer_robot::change_speed>("change_speed");
// Create a service object
the_explorer_robot::change_speed srv;
// Assign the speed that needs to be changed
srv.request.newSpeedX = 2.0;
srv.request.newRotateZ = 1.0;
// Call the service
client.call(srv);
// Check the response
EXPECT_EQ(2.0, srv.response.respSpeedX);
EXPECT_EQ(1.0, srv.response.respRotateZ);
}
/**
* @brief This is a test to check if the obstacle is correctly initialized
*/
TEST(explorerTest, initTest) {
Explorer testObject;
EXPECT_FALSE(testObject.obstacle);
EXPECT_TRUE(testObject.turn);
EXPECT_EQ(0, testObject.count);
}
/**
* @brief This is a test to check if the sensorCallback works correctly
*/
// TEST(testexplorerTest, sensorCallbackTest) {
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
/* ros::NodeHandle n;
ros::Subscriber sub;
Explorer testObject;
testObject.sensorCallback(sensor_msgs::LaserScan::ConstPtr& msg);
// Check the obstacle status
EXPECT_TRUE(testObject.obstacle);
}*/
/**
* @brief This is a test to check if the planner works correctly
*/
TEST(testexplorerTest, plannerTest1) {
Explorer testObject;
testObject.obstacle = true;
testObject.planner();
// Check the msg
EXPECT_EQ(testObject.msg.linear.x, 0.0);
EXPECT_EQ(testObject.msg.angular.z, testObject.rotateZ);
}
/**
* @brief This is a test to check if the planner works correctly
*/
TEST(testexplorerTest, plannerTest2) {
Explorer testObject;
testObject.planner();
// Check the msg
EXPECT_EQ(testObject.msg.linear.x, 0.0);
EXPECT_EQ(testObject.msg.angular.z, testObject.rotateZ * 4);
EXPECT_EQ(testObject.count, 1);
testObject.count = 300;
testObject.planner();
EXPECT_EQ(testObject.msg.linear.x, testObject.speedX);
EXPECT_EQ(testObject.msg.angular.z, 0.0);
EXPECT_FALSE(testObject.turn);
testObject.count = 700;
testObject.planner();
EXPECT_EQ(testObject.count, 1);
testObject.planner();
EXPECT_EQ(testObject.msg.linear.x, 0.0);
EXPECT_EQ(testObject.msg.angular.z, -testObject.rotateZ * 4);
}
| 35 | 83 | 0.720952 | [
"object"
] |
00861ba466c545a407ab4346df96767770d1ed2f | 1,130 | cpp | C++ | C++/Data Structure/detect_cycle_in_undirected_graph.cpp | IM-RAHUL-RAJ/hacktoberfest2021-1 | f9eaa2e621aa751485551383f7b1fbe894a13de6 | [
"MIT"
] | null | null | null | C++/Data Structure/detect_cycle_in_undirected_graph.cpp | IM-RAHUL-RAJ/hacktoberfest2021-1 | f9eaa2e621aa751485551383f7b1fbe894a13de6 | [
"MIT"
] | null | null | null | C++/Data Structure/detect_cycle_in_undirected_graph.cpp | IM-RAHUL-RAJ/hacktoberfest2021-1 | f9eaa2e621aa751485551383f7b1fbe894a13de6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
// Function to detect cycle in an undirected graph.
vector<bool> vis;
bool ans;
void dfs(vector<int> adj[], int v, int p) {
vis[v] = true;
for (auto x : adj[v]) {
if (x == p)continue;
if (vis[x]) {
ans = true;
return;
}
else dfs(adj, x, v);
}
}
bool isCycle(int n, vector<int> adj[]) {
// Code here
vis.assign(n + 1, false);
ans = false;
for (int i = 0; i < n; i++)if (!vis[i])dfs(adj, i, -1);
return ans;
}
};
// { Driver Code Starts.
int main() {
int tc;
cin >> tc;
while (tc--) {
int V, E;
cin >> V >> E;
vector<int> adj[V];
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
Solution obj;
bool ans = obj.isCycle(V, adj);
if (ans)
cout << "1\n";
else
cout << "0\n";
}
return 0;
} // } Driver Code Ends | 20.925926 | 59 | 0.438053 | [
"vector"
] |
0a594b8598e2907ac9d006c35150de53b0d4dc4f | 854 | cpp | C++ | 06/park/1644.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | 2 | 2021-01-09T10:05:21.000Z | 2021-01-10T06:14:03.000Z | 06/park/1644.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | null | null | null | 06/park/1644.cpp | Dcom-KHU/2021-Winter-Algorithm-Study | ea32826abe7d8245ee9d3dc8d0161f7ba018a02f | [
"MIT"
] | 1 | 2021-02-03T13:09:09.000Z | 2021-02-03T13:09:09.000Z | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int result = 0;
bool not_prime[4000001] = { false };
vector<int> vec;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
// 에레토스테네스의 채
for (int i = 2; i <= 2000; i++)
{
if (!not_prime[i]) {
for (int j = i * i; j <= 4000000; j += i)
{
not_prime[j] = true;
}
}
}
// 소수 push
for (int i = 2; i <= 4000001; i++)
{
if (!not_prime[i])
vec.push_back(i);
}
cin >> n;
// 변수 초기화
int left = 0, right = 0;
int sum = vec[0];
int size = vec.size();
while (left <= right)
{
if (sum > n) {
sum -= vec[left];
left += 1;
}
else if (sum < n) {
right += 1;
sum += vec[right];
}
else {
result += 1;
right += 1;
sum += vec[right];
}
}
cout << result << endl;
return 0;
} | 13.555556 | 44 | 0.519906 | [
"vector"
] |
0a59d2bebe811ae60bd04cc3c6aad69753aa3f8e | 883 | hpp | C++ | header_files/qt_screenshot.hpp | bryansb/gavo | 3396115329255ac7dd4c22ea758c81dce4c8fb99 | [
"MIT"
] | null | null | null | header_files/qt_screenshot.hpp | bryansb/gavo | 3396115329255ac7dd4c22ea758c81dce4c8fb99 | [
"MIT"
] | null | null | null | header_files/qt_screenshot.hpp | bryansb/gavo | 3396115329255ac7dd4c22ea758c81dce4c8fb99 | [
"MIT"
] | null | null | null | #include <QApplication>
#include <QScreen>
#include <QPixmap>
#include <QImage>
#include <QDebug>
#include <cstdint>
#include <cstring>
#include <vector>
#ifndef OPENCVCORE_INCLUDED
#define OPENCVCORE_INCLUDED
#include "./opencv_core.hpp"
#endif
#ifndef CORE_INCLUDED
#define CORE_INCLUDED
#include "./core.hpp"
#endif
#ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
#define OS_Windows 0
#elif defined(_WIN32) || defined(WIN32) /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems */
#define OS_Windows 1
#endif
class QtScreenshot {
public:
QtScreenshot();
void take(int x, int y, int w, int h, cv::Mat &out);
QScreen *getScreen();
void setScreen(QScreen *screen);
private:
QScreen *screen;
QImage qpx_image;
}; | 22.075 | 129 | 0.670442 | [
"vector"
] |
0a5b8926e66ab2874b27b4a8176c5741ff337d3e | 4,230 | cc | C++ | model-view/el-sel/main.cc | gusenov/examples-qt | 083a51feedf6cefe82b6de79d701da23d1da2a2f | [
"MIT"
] | 2 | 2020-09-01T18:37:30.000Z | 2021-11-28T16:25:04.000Z | model-view/el-sel/main.cc | gusenov/examples-qt | 083a51feedf6cefe82b6de79d701da23d1da2a2f | [
"MIT"
] | null | null | null | model-view/el-sel/main.cc | gusenov/examples-qt | 083a51feedf6cefe82b6de79d701da23d1da2a2f | [
"MIT"
] | null | null | null | // Программа выполняет разделение выделения элементов между тремя
// представлениями. Выделение элемента в одном из представлений приведет к
// выделению этого же элемента и в остальных представлениях.
#include <QtWidgets>
#include "SelectionHandler.h"
int main(int argc, char** argv) {
QApplication app(argc, argv);
QWidget wgt;
// Создаем модель списка строк (объект model), которую инициализируем
// тремя элементами. Каждый элемент является строкой:
QStringListModel model;
model.setStringList(QStringList() << "Первая строка"
<< "Вторая строка"
<< "Третья строка");
// Создаем три разных представления (указатели pTreeView, pListView и
// pTableView) и устанавливаем в них нашу модель, вызывая метод setModel():
auto* pTreeView = new QTreeView;
pTreeView->setModel(&model);
auto* pListView = new QListView;
pListView->setModel(&model);
auto* pTableView = new QTableView;
pTableView->setModel(&model);
// Управление выделением осуществляется при помощи специальной модели, реализованной
// в классе QItemSelectionModel.
// Создание модели выделения (объекта класса QItemSelectionModel). При
// создании этот объект инициализируется оригинальной моделью
// (объект model):
QItemSelectionModel selection(&model);
// Для получения модели выделения элементов,
// установленной в представлении, нужно вызвать метод QAbstractItemView::selectionМodel(),
// а установить новую модель можно с помощью метода QAbstractItemView::setSelectionМodel().
pTreeView->setSelectionModel(&selection);
pListView->setSelectionModel(&selection);
pTableView->setSelectionModel(&selection);
// Индексы текущих выделенных позиций можно получить вызовом метода
// QItemSelectionModel::selectedIndexes(). А выделять элементы программно
// можно с помощью метода QItemSelectionModel::select(). При изменениях
// выделения модель выделений отсылает сигналы currentChanged(),
// selectionChanged(), currentColumnChanged() и currentRowChanged().
QObject::connect(&selection,
&QItemSelectionModel::currentChanged,
[](const QModelIndex ¤t, const QModelIndex &previous)
{
qDebug() << "QItemSelectionModel::currentChanged { current = " << current << "; previous = " << previous << " }";
});
// Вызывается сразу при старте приложения.
// Хотя визуально синее выделение не устанавливается.
// При клике на 0-й элемент повторно вызван не будет.
// QItemSelectionModel::currentChanged { current = QModelIndex(0,0,0x0,QStringListModel(0x7ffee2afba30)) ; previous = QModelIndex(-1,-1,0x0,QObject(0x0)) }
SelectionHandler selectionHandler;
QObject::connect(&selection,
SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
&selectionHandler,
SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
// При старте приложения не будет вызван.
// Но будет вызван при установке выделения (даже на 0-й элемент).
// QItemSelectionModel::selectionChanged { selected = (QItemSelectionRange(QModelIndex(0,0,0x0,QStringListModel(0x7ffeeacefa30)),QModelIndex(0,0,0x0,QStringListModel(0x7ffeeacefa30)))) ; deselected = () }
QObject::connect(&selection,
SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)),
&selectionHandler,
SLOT(onCurrentRowChanged(const QModelIndex &, const QModelIndex &)));
// Вызывается сразу при старте приложения.
// Хотя визуально синее выделение не устанавливается.
// При клике на 0-й элемент повторно вызван не будет.
// QItemSelectionModel::currentRowChanged { current = QModelIndex(0,0,0x0,QStringListModel(0x7ffee0901a30)) ; previous = QModelIndex(-1,-1,0x0,QObject(0x0)) }
// Layout setup
auto* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pTreeView);
phbxLayout->addWidget(pListView);
phbxLayout->addWidget(pTableView);
wgt.setLayout(phbxLayout);
wgt.show();
return app.exec();
} | 46.483516 | 211 | 0.69409 | [
"model"
] |
0a6e6e938af259cbff8cd76dca28bef931f33b1d | 10,354 | cpp | C++ | src/Sparrow/Sparrow/Implementations/GenericMethodWrapper.cpp | DockBio/sparrow | f82cf86584e9edfc6f2c78af4896dc6f2ee8a455 | [
"BSD-3-Clause"
] | null | null | null | src/Sparrow/Sparrow/Implementations/GenericMethodWrapper.cpp | DockBio/sparrow | f82cf86584e9edfc6f2c78af4896dc6f2ee8a455 | [
"BSD-3-Clause"
] | null | null | null | src/Sparrow/Sparrow/Implementations/GenericMethodWrapper.cpp | DockBio/sparrow | f82cf86584e9edfc6f2c78af4896dc6f2ee8a455 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
/* Internal Includes */
#include "GenericMethodWrapper.h"
#include "DipoleMatrixCalculator.h"
#include "DipoleMomentCalculator.h"
#include "MoldenFileGenerator.h"
#include <Utils/CalculatorBasics/PropertyList.h>
/* External Includes */
#include <Core/Exceptions.h>
#include <Sparrow/StatesHandling/SparrowState.h>
#include <Utils/CalculatorBasics.h>
#include <Utils/GeometricDerivatives/NumericalHessianCalculator.h>
#include <Utils/Geometry/AtomCollection.h>
#include <Utils/IO/NativeFilenames.h>
#include <Utils/Scf/MethodExceptions.h>
#include <Utils/Scf/MethodInterfaces/LcaoMethod.h>
#include <Utils/Settings.h>
#include <Utils/UniversalSettings/SettingsNames.h>
#include <boost/filesystem.hpp>
#include <fstream>
#include <memory>
namespace Scine {
namespace Sparrow {
GenericMethodWrapper::GenericMethodWrapper() = default;
GenericMethodWrapper::~GenericMethodWrapper() = default;
Utils::Settings& GenericMethodWrapper::settings() {
return *settings_;
}
const Utils::Settings& GenericMethodWrapper::settings() const {
return *settings_;
}
Utils::Results& GenericMethodWrapper::results() {
return results_;
}
const Utils::Results& GenericMethodWrapper::results() const {
return results_;
}
const Utils::Results& GenericMethodWrapper::calculate(std::string description) {
if (getPositions().rows() == 0) {
throw Core::EmptyMolecularStructureException();
}
auto requiredDerivative = highestDerivativeRequired();
bool requiredHessian = requiredProperties_.containsSubSet(Utils::Property::Hessian) ||
requiredProperties_.containsSubSet(Utils::Property::Thermochemistry);
bool requiredDipoleGradient = requiredProperties_.containsSubSet(Utils::Property::DipoleGradient);
bool requiredSemiNumericalHessian = requiredHessian && !canCalculateAnalyticalHessian();
results_ = Utils::Results{};
if (dipoleMatrixCalculator_)
dipoleMatrixCalculator_->invalidate();
applySettings();
calculateImpl(requiredDerivative);
// If you want the Hessian, but cannot calculate it analytically,
// calculate it semi-numerically. Same with Dipole Gradient.
if (requiredSemiNumericalHessian || requiredDipoleGradient) {
Utils::NumericalHessianCalculator hessianCalculator(*this);
if (requiredDipoleGradient) {
hessianCalculator.requiredDipoleGradient(true);
}
auto numericalResult = hessianCalculator.calculate();
results_.set<Utils::Property::Hessian>(numericalResult.take<Utils::Property::Hessian>());
if (requiredDipoleGradient) {
results_.set<Utils::Property::DipoleGradient>(numericalResult.take<Utils::Property::DipoleGradient>());
}
}
// If you want it, calculate and save the dipole.
if (requiredProperties_.containsSubSet(Utils::Property::Dipole)) {
results_.set<Utils::Property::Dipole>(dipoleCalculator_->calculate());
}
results_.set<Utils::Property::SuccessfulCalculation>(successfulCalculation());
assembleResults(description);
return results_;
};
void GenericMethodWrapper::setStructure(const Utils::AtomCollection& structure) {
getLcaoMethod().setAtomCollection(structure);
// applySettings() is here to prevent logging wrong settings due to the call to initialize.
applySettings();
initialize();
}
std::unique_ptr<Utils::AtomCollection> GenericMethodWrapper::getStructure() const {
return std::make_unique<Utils::AtomCollection>(getLcaoMethod().getElementTypes(), getLcaoMethod().getPositions());
}
void GenericMethodWrapper::modifyPositions(Utils::PositionCollection newPositions) {
if (getLcaoMethod().getElementTypes().size() != newPositions.rows()) {
throw std::runtime_error("Position/ElementTypeCollection dimensionality mismatch.");
}
getLcaoMethod().setPositions(std::move(newPositions));
}
const Utils::PositionCollection& GenericMethodWrapper::getPositions() const {
return getLcaoMethod().getPositions();
}
void GenericMethodWrapper::setRequiredProperties(const Utils::PropertyList& requiredProperties) {
requiredProperties_ = requiredProperties;
}
Utils::PropertyList GenericMethodWrapper::getRequiredProperties() const {
return requiredProperties_;
}
Utils::PropertyList GenericMethodWrapper::possibleProperties() const {
return Utils::Property::Energy | Utils::Property::Gradients | Utils::Property::Hessian |
Utils::Property::BondOrderMatrix | Utils::Property::DensityMatrix | Utils::Property::AtomicCharges |
Utils::Property::OverlapMatrix | Utils::Property::OrbitalEnergies | Utils::Property::CoefficientMatrix |
Utils::Property::ElectronicOccupation | Utils::Property::Thermochemistry | Utils::Property::Description |
Utils::Property::Dipole | Utils::Property::SuccessfulCalculation;
}
Utils::derivativeType GenericMethodWrapper::highestDerivativeRequired() const {
// If gradient or hessian is contained in the requiredProperties_, then calculate the corresponding derivative.
bool gradientsRequired = requiredProperties_.containsSubSet(Utils::Property::Gradients);
bool hessianRequired = requiredProperties_.containsSubSet(Utils::Property::Hessian) ||
requiredProperties_.containsSubSet(Utils::Property::Thermochemistry);
Utils::derivativeType requiredDerivative = Utils::derivativeType::none;
if (gradientsRequired && possibleProperties().containsSubSet(Utils::Property::Gradients)) {
requiredDerivative = Utils::derivativeType::first;
}
if (hessianRequired && canCalculateAnalyticalHessian()) {
requiredDerivative = Utils::derivativeType::second_full;
}
return requiredDerivative;
}
void GenericMethodWrapper::assembleResults(const std::string& description) {
results_.set<Utils::Property::Description>(description);
results_.set<Utils::Property::Energy>(getLcaoMethod().getEnergy());
if (requiredProperties_.containsSubSet(Utils::Property::Gradients)) {
results_.set<Utils::Property::Gradients>(getLcaoMethod().getGradients());
}
if (highestDerivativeRequired() >= Utils::derivativeType::second_full) {
results_.set<Utils::Property::Hessian>(getLcaoMethod().getFullSecondDerivatives().getHessianMatrix());
}
if (requiredProperties_.containsSubSet(Utils::Property::BondOrderMatrix)) {
results_.set<Utils::Property::BondOrderMatrix>(getLcaoMethod().getBondOrderCollection());
}
if (requiredProperties_.containsSubSet(Utils::Property::DensityMatrix)) {
results_.set<Utils::Property::DensityMatrix>(getLcaoMethod().getDensityMatrix());
}
if (requiredProperties_.containsSubSet(Utils::Property::AtomicCharges)) {
results_.set<Utils::Property::AtomicCharges>(getLcaoMethod().getAtomicCharges());
}
if (requiredProperties_.containsSubSet(Utils::Property::OverlapMatrix)) {
results_.set<Utils::Property::OverlapMatrix>(getLcaoMethod().getOverlapMatrix());
}
if (requiredProperties_.containsSubSet(Utils::Property::OrbitalEnergies)) {
results_.set<Utils::Property::OrbitalEnergies>(getLcaoMethod().getSingleParticleEnergies());
}
if (requiredProperties_.containsSubSet(Utils::Property::CoefficientMatrix) ||
requiredProperties_.containsSubSet(Utils::Property::Thermochemistry)) {
results_.set<Utils::Property::CoefficientMatrix>(getLcaoMethod().getMolecularOrbitals());
}
if (requiredProperties_.containsSubSet(Utils::Property::ElectronicOccupation) ||
requiredProperties_.containsSubSet(Utils::Property::Thermochemistry)) {
results_.set<Utils::Property::ElectronicOccupation>(getLcaoMethod().getElectronicOccupation());
}
Utils::ResultsAutoCompleter resultsAutoCompleter(*getStructure());
resultsAutoCompleter.setCoreCharges(getLcaoMethod().getAtomicCharges());
auto zpveInclusion = getZPVEInclusion() ? Utils::ZPVEInclusion::alreadyIncluded : Utils::ZPVEInclusion::notIncluded;
resultsAutoCompleter.setZPVEInclusion(zpveInclusion);
if (requiredProperties_.containsSubSet(Utils::Property::Thermochemistry)) {
resultsAutoCompleter.addOneWantedProperty(Utils::Property::Thermochemistry);
resultsAutoCompleter.setTemperature(settings().getDouble(Utils::SettingsNames::temperature));
}
resultsAutoCompleter.generateProperties(results_, *getStructure());
}
bool GenericMethodWrapper::supportsMethodFamily(const std::string& methodFamily) const {
return methodFamily == name();
}
void GenericMethodWrapper::loadState(std::shared_ptr<Core::State> state) {
auto sparrowState = std::dynamic_pointer_cast<SparrowState>(state);
if (!sparrowState)
throw Core::StateCastingException();
if (getLcaoMethod().getNumberElectrons() != sparrowState->getDensityMatrix().numberElectrons()) {
throw IncompatibleStateException();
}
getLcaoMethod().setDensityMatrix(sparrowState->getDensityMatrix());
}
std::shared_ptr<Core::State> GenericMethodWrapper::getState() const {
return std::make_shared<SparrowState>(getLcaoMethod().getDensityMatrix());
}
std::string GenericMethodWrapper::getStoNGExpansionPath() const {
auto path = Utils::NativeFilenames::combinePathSegments(settings().getString(Utils::SettingsNames::parameterRootDirectory),
settings().getString(Utils::SettingsNames::parameterFile));
boost::filesystem::path methodRoot(path);
auto pathToBasis = methodRoot.parent_path();
if (name() == "DFTB0" || name() == "DFTB2" || name() == "DFTB3")
pathToBasis = pathToBasis.parent_path();
pathToBasis = pathToBasis / "STO-6G.basis";
return pathToBasis.string();
}
bool GenericMethodWrapper::canCalculateAnalyticalHessian() const {
return false;
}
void GenericMethodWrapper::generateWavefunctionInformation(const std::string& filename) {
std::ofstream fileOut(filename);
if (!fileOut.is_open())
throw std::runtime_error("Impossible to open file " + filename + ".");
generateWavefunctionInformation(fileOut);
}
void GenericMethodWrapper::generateWavefunctionInformation(std::ostream& out) {
getLcaoMethod().calculate(Utils::derivativeType::none);
MoldenFileGenerator sparrow2molden(*this);
sparrow2molden.generateWavefunctionInformation(out);
}
void GenericMethodWrapper::applySettings() {
}
} /* namespace Sparrow */
} // namespace Scine
| 40.76378 | 125 | 0.765115 | [
"geometry"
] |
0a6f632ce573b61963f999324fbd50d6eb85251c | 902 | cpp | C++ | Deitel/Chapter09/examples/9.11/CreateAndDestroy.cpp | SebastianTirado/Cpp-Learning-Archive | fb83379d0cc3f9b2390cef00119464ec946753f4 | [
"MIT"
] | 19 | 2019-09-15T12:23:51.000Z | 2020-06-18T08:31:26.000Z | Deitel/Chapter09/examples/9.11/CreateAndDestroy.cpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | Deitel/Chapter09/examples/9.11/CreateAndDestroy.cpp | eirichan/CppLearingArchive | 07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac | [
"MIT"
] | 13 | 2019-06-29T02:58:27.000Z | 2020-05-07T08:52:22.000Z | /*
* =====================================================================================
*
* Filename:
*
* Description:
*
* Version: 1.0
* Created: Thanks to github you know it
* Revision: none
* Compiler: g++
*
* Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com
*
*
* =====================================================================================
*/
#include "CreateAndDestroy.hpp"
CreateAndDestroy::CreateAndDestroy(int ID, std::string messageString) {
objectID = ID;
message = messageString;
std::cout << "Object " << objectID << " constructor runs " << message
<< std::endl;
}
CreateAndDestroy::~CreateAndDestroy() {
std::cout << (objectID == 1 || objectID == 6 ? "\n" : "");
std::cout << "Object " << objectID << " destructor runs " << message
<< std::endl;
}
| 27.333333 | 88 | 0.43459 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.