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
58d603e614fb3cb494508ad6affac29ce4b7b880
1,060
cpp
C++
analysis/Utilities.cpp
3bmwhunter/wordle-tas
d6237a0e4c99c90bde8a8026b5e108480069bc95
[ "MIT" ]
null
null
null
analysis/Utilities.cpp
3bmwhunter/wordle-tas
d6237a0e4c99c90bde8a8026b5e108480069bc95
[ "MIT" ]
null
null
null
analysis/Utilities.cpp
3bmwhunter/wordle-tas
d6237a0e4c99c90bde8a8026b5e108480069bc95
[ "MIT" ]
null
null
null
#include "Utilities.h" bool hasOverlap(const std::u32string &a, const std::u32string &b) { for(auto aLetter : a) { for(auto bLetter : b) { if(aLetter == bLetter) { return true; } } } return false; } double average(const std::vector<int>& input) { double value = 0.0; for(auto in : input) { value += double(in); } return value / input.size(); } std::u32string toLowerCase(std::u32string input) { for(char32_t i = U'A'; i <= U'Z'; i++) { std::replace( input.begin(), input.end(), i, char32_t(i + 32) ); } std::replace( input.begin(), input.end(), U'Ä', U'ä' ); std::replace( input.begin(), input.end(), U'Ö', U'ö' ); std::replace( input.begin(), input.end(), U'Ü', U'ü' ); return input; }
18.596491
68
0.409434
[ "vector" ]
58f1488cc5bde5a34b5610ab2c56a6d59ee437ad
8,508
hpp
C++
rcraam/inst/include/craam/algorithms/values_mdp.hpp
marekpetrik/craam2
b07f4547d578626c698cbc660495dbf6f179a672
[ "MIT" ]
4
2020-08-11T17:30:58.000Z
2022-03-25T11:08:11.000Z
rcraam/inst/include/craam/algorithms/values_mdp.hpp
marekpetrik/craam2
b07f4547d578626c698cbc660495dbf6f179a672
[ "MIT" ]
null
null
null
rcraam/inst/include/craam/algorithms/values_mdp.hpp
marekpetrik/craam2
b07f4547d578626c698cbc660495dbf6f179a672
[ "MIT" ]
2
2020-05-15T17:42:53.000Z
2022-03-25T11:08:16.000Z
// This file is part of CRAAM, a C++ library for solving plain // and robust Markov decision processes. // // 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. /** Value-function based methods (value iteration and policy iteration) style algorithms. Provides abstractions that allow generalization to both robust and regular MDPs. */ #pragma once #include "craam/MDP.hpp" #include "craam/algorithms/nature_declarations.hpp" #include <functional> /// Main namespace for algorithms that operate on MDPs and MDPOs namespace craam { namespace algorithms { using namespace std; // ******************************************************* // Plain Action // ******************************************************* /** * Computes the average value of the action. * * @param action Action for which to compute the value * @param valuefunction State value function to use * @param discount Discount factor * @return Action value */ inline prec_t value_action(const Action& action, const numvec& valuefunction, prec_t discount) { return action.value(valuefunction, discount); } /** * Computes a value of the action for a given distribution. This function can be * used to evaluate a robust solution which may modify the transition * probabilities. * * The new distribution may be non-zero only for states for which the original * distribution is not zero. * * @param action Action for which to compute the value * @param valuefunction State value function to use * @param discount Discount factor * @param distribution New distribution. The length must match the number of * states to which the original transition probabilities are strictly * greater than 0. The order of states is the same as in the underlying transition. * @return Action value */ inline prec_t value_action(const Action& action, const numvec& valuefunction, prec_t discount, const numvec& distribution) { return action.value(valuefunction, discount, distribution); } // ******************************************************* // Robust Action // ******************************************************* /** * The function computes the value of each transition by adding the * reward function to the discounted value function * @param action Action for which to compute the z-values * @param valuefunction Value function over ALL states * @param discount Discount facto * @return The length of the zvalues is the same as the number of * transitions with positive probabilities. */ inline numvec compute_zvalues(const Action& action, const numvec& valuefunction, prec_t discount) { const numvec& rewards = action.get_rewards(); const indvec& nonzero_indices = action.get_indices(); if (nonzero_indices.empty()) return numvec(rewards.size(), std::nan("")); numvec zvalues(rewards.size()); // values for individual states - used by nature. #pragma omp simd for (size_t i = 0; i < rewards.size(); i++) { zvalues[i] = rewards[i] + discount * valuefunction[nonzero_indices[i]]; } return zvalues; } /** * Computes an ambiguous value (e.g. robust) of the action, depending on the type * of nature that is provided. * * @param action Action for which to compute the value * @param valuefunction State value function to use * @param discount Discount factor * @param nature Method used to compute the response of nature. */ inline vec_scal_t value_action(const Action& action, const numvec& valuefunction, prec_t discount, long stateid, long actionid, const SANature& nature) { numvec zvalues = compute_zvalues(action, valuefunction, discount); return nature(stateid, actionid, action.get_probabilities(), zvalues); } // ******************************************************* // State methods // ******************************************************* /** * Constructs and returns a vector of nominal probabilities for each subsequent * state that has positive transition probabilities. * * @param state The state for which to compute the nominal probabilities * @return The length of the outer vector is the number of actions, the length * of the inner vector is the number of non-zero transition * probabilities */ inline vector<numvec> compute_probabilities(const State& state) { vector<numvec> result; result.reserve(state.size()); for (const auto& action : state.get_actions()) { result.push_back(action.get_probabilities()); } return result; } /** * Constructs and returns a vector of z-values for each action in the state * @param state The state for which to compute the nominal probabilities * @param value function over the entire state space * @param discount The discount factor * @return The length of the outer vector is the number of actions, the length * of the inner vector is the number of non-zero transition * probabilities */ inline vector<numvec> compute_zvalues(const State& state, const numvec& valuefunction, prec_t discount) { numvecvec result; result.reserve(state.size()); for (const auto& action : state.get_actions()) { result.push_back(compute_zvalues(action, valuefunction, discount)); } return result; } /** * Computes the value of a probability distribution over actions. * * @param state State to compute the value for * @param valuefunction Value function to use in computing value of states. * @param discount Discount factor * @param actiondist Distribution over actions * * @return Value of state, 0 if it's terminal regardless of the action index */ inline prec_t value_fix_state(const State& state, numvec const& valuefunction, prec_t discount, const numvec& actiondist) { // this is the terminal state, return 0 if (state.is_terminal()) return 0; assert(actiondist.size() == state.size()); assert((1.0 - accumulate(actiondist.cbegin(), actiondist.cend(), 0.0) - 1.0) < 1e-5); prec_t result = 0.0; #pragma omp simd reduction(+ : result) for (size_t actionid = 0; actionid < state.size(); actionid++) { assert(actiondist[actionid] >= 0); result += actiondist[actionid] * value_action(state[actionid], valuefunction, discount); } return result; } // ******************************************************* // Compute Q-function // ******************************************************* /** * Computes the Q function given an MDP and a value function. * @param mdp Definition of the MDP * @param valuefunction The value function to be used to compute the Q-function * @param discount discount factor * @return The q-function for each state and action of the MDP */ inline vector<numvec> compute_qfunction(const MDP& mdp, const numvec& valuefunction, prec_t discount) { vector<numvec> qfunction; qfunction.reserve(mdp.size()); //for (const State& s : mdp) { for (size_t is = 0; is < mdp.size(); ++is) { const State& s = mdp[is]; numvec qa; qa.reserve(s.size()); for (size_t ia = 0; ia < s.size(); ++ia) qa.push_back(value_action(s[ia], valuefunction, discount)); qfunction.push_back(move(qa)); } return qfunction; } }} // namespace craam::algorithms
37.646018
90
0.663493
[ "vector" ]
45028c431f20b7d7136001bfe1866ab2e76e7069
977
cpp
C++
count-and-say/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
3
2018-05-08T14:08:50.000Z
2019-02-28T00:10:14.000Z
count-and-say/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
count-and-say/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <numeric> class Solution { public: static const std::vector<char> init; std::string countAndSay(int n) { std::vector<char> now = init; for (/* */; n > 1; --n) { std::vector<char> nxt; next(now, nxt); now = nxt; } return std::accumulate( now.begin(), now.end(), std::string(""), [](std::string a, int b) { return a + std::to_string(b); } ); } void next(const std::vector<char> &st, std::vector<char> &out) { auto i = 0U; while (i < st.size()) { // count auto j = i; for (/* */; j < st.size() && st[j] == st[i]; ++j) ; // say out.push_back(j-i); out.push_back(st[i]); i = j; } } }; const std::vector<char> Solution::init = std::vector<char>({1});
24.425
68
0.423746
[ "vector" ]
4508ddc5e9ed6b2f1a5632ceb22bebe41adb808f
5,182
cpp
C++
leetcode/weeklyContest/WC221to230.cpp
fyabc/LeetCode
4a5c7dfdf8537059b98849f2a8ab1b5fafa45b9c
[ "MIT" ]
null
null
null
leetcode/weeklyContest/WC221to230.cpp
fyabc/LeetCode
4a5c7dfdf8537059b98849f2a8ab1b5fafa45b9c
[ "MIT" ]
null
null
null
leetcode/weeklyContest/WC221to230.cpp
fyabc/LeetCode
4a5c7dfdf8537059b98849f2a8ab1b5fafa45b9c
[ "MIT" ]
null
null
null
// // Created by fyabc on 2021/3/12. // #include "support/IO.h" #include <algorithm> #include <numeric> #include <vector> #include <unordered_map> using namespace std; class WC224Q2_Problem1726 { /** * WC224Q2_Problem1726: https://leetcode.com/contest/weekly-contest-224/problems/tuple-with-same-product/ * * Solution: count all product values. */ public: static int tupleSameProduct(vector<int>& nums) { unordered_map<int, int> products; for (int i = 0; i < nums.size() - 1; ++i) { auto ni = nums[i]; for (int j = i + 1; j < nums.size(); ++j) { ++products[ni * nums[j]]; } } // Result = sum(4n(n-1)) auto result = 4 * accumulate( products.begin(), products.end(), 0, [](int sum, const pair<int, int>& item) { return sum + item.second * (item.second - 1); }); return result; } }; class WC224Q3_Problem1727 { /** * WC224Q3_Problem1727: https://leetcode.com/contest/weekly-contest-224/problems/largest-submatrix-with-rearrangements/ * * Solution: calculate the height of each cell. */ public: static int largestSubmatrix(vector<vector<int>>& matrix) { // 1. Calculate "height" of each cell. for (int i = 1; i < matrix.size(); ++i) { auto& row = matrix[i]; for (int j = 0; j < row.size(); ++j) { if (row[j] != 0) { row[j] = matrix[i - 1][j] + 1; } } } int result = 0; for (auto& row : matrix) { sort(row.begin(), row.end()); auto N = static_cast<int>(row.size()); for (int j = 0; j < N; ++j) { int thisResult = (N - j) * row[j]; if (thisResult > result) { result = thisResult; } } } return result; } }; class WC225Q2_Problem1737 { /** * WC225Q2_Problem1737: https://leetcode.com/contest/weekly-contest-225/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/ * * Solution: count all (a <= ch && b > ch) and (a > ch && b <= ch) and condition 3. */ public: static int minCharacters(const string& a, const string& b) { auto M = static_cast<int>(a.size()), N = static_cast<int>(b.size()); auto totalSize = static_cast<int>(a.size() + b.size()); vector<int> charCounter(charMax, 0), charCounterA(charMax, 0), charCounterB(charMax, 0); for (char ch : a) { ++charCounterA[char2Idx(ch)]; ++charCounter[char2Idx(ch)]; } for (char ch : b) { ++charCounterB[char2Idx(ch)]; ++charCounter[char2Idx(ch)]; } int cond3Steps = totalSize - *max_element(charCounter.begin(), charCounter.end()); int cond1Steps = totalSize, cond2Steps = totalSize; int numLessEqualA = 0, numLessEqualB = 0; for (int i = 0; i < charMax - 1; ++i) { numLessEqualA += charCounterA[i]; numLessEqualB += charCounterB[i]; int newCond1Steps = numLessEqualB + (M - numLessEqualA); int newCond2Steps = numLessEqualA + (N - numLessEqualB); if (newCond1Steps < cond1Steps) { cond1Steps = newCond1Steps; } if (newCond2Steps < cond2Steps) { cond2Steps = newCond2Steps; } } return min({cond1Steps, cond2Steps, cond3Steps}); } private: static constexpr int charMax = 26; static constexpr size_t char2Idx(char ch) { return static_cast<size_t>(ch - 'a'); } }; class WC225Q3_Problem1738 { /** * WC225Q3_Problem1738: https://leetcode.com/contest/weekly-contest-225/problems/find-kth-largest-xor-coordinate-value/ * * Solution: result[i,j] = result[i-1,j-1] ^ result[i-1,j] ^ result[i,j-1] ^ result[i,j] */ public: static int kthLargestValue(vector<vector<int>>& matrix, int k) { vector<int> values(matrix.size() * matrix[0].size()); auto& row0 = matrix[0]; values.push_back(row0[0]); for (int j = 1; j < row0.size(); ++j) { row0[j] = row0[j - 1] ^ row0[j]; values.push_back(row0[j]); } for (int i = 1; i < matrix.size(); ++i) { auto& row = matrix[i]; row[0] = matrix[i - 1][0] ^ row[0]; values.push_back(row[0]); for (int j = 1; j < row.size(); ++j) { row[j] = matrix[i - 1][j - 1] ^ matrix[i - 1][j] ^ row[j - 1] ^ row[j]; values.push_back(row[j]); } } if (k <= values.size() / 2) { auto nthIter = values.begin() + k - 1; nth_element(values.begin(), nthIter, values.end(), greater<>()); return *nthIter; } else { auto nthIter = values.begin() + static_cast<decltype(values)::difference_type>(values.size()) - k; nth_element(values.begin(), nthIter, values.end()); return *nthIter; } } };
30.482353
146
0.522192
[ "vector" ]
450ac9a110afc122294a9a6315eeced3a24f4383
255
cc
C++
ll_graphic/tests/misc/test_camera.cc
LoSealL/lltech
5acb399820c99f84345e88537c7db259e13d63e4
[ "MIT" ]
1
2019-09-11T11:55:07.000Z
2019-09-11T11:55:07.000Z
ll_graphic/tests/misc/test_camera.cc
LoSealL/lltech
5acb399820c99f84345e88537c7db259e13d63e4
[ "MIT" ]
null
null
null
ll_graphic/tests/misc/test_camera.cc
LoSealL/lltech
5acb399820c99f84345e88537c7db259e13d63e4
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "ll_graphic/math/math.h" #include "ll_graphic/model/camera.h" using namespace ll::engine::model; TEST(camera, lookat) { Camera c; c.LookAt({ 1,0,0 }); c.LookAt({ 0,0,1 }); c.SetPosition(0, 0, 0); c.Reset(); }
18.214286
36
0.643137
[ "model" ]
450c368f00c8b6aa0f00a87008e50b846c7a8a20
20,621
cpp
C++
engine/sorted_collection/rebuilder.cpp
iyupeng/kvdk
35e882bf6adc5e931d57fb07c648d0478b9ea146
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
engine/sorted_collection/rebuilder.cpp
iyupeng/kvdk
35e882bf6adc5e931d57fb07c648d0478b9ea146
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
engine/sorted_collection/rebuilder.cpp
iyupeng/kvdk
35e882bf6adc5e931d57fb07c648d0478b9ea146
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2021 Intel Corporation */ #include "rebuilder.hpp" #include <future> #include "../kv_engine.hpp" #include "kvdk/namespace.hpp" namespace KVDK_NAMESPACE { SortedCollectionRebuilder::SortedCollectionRebuilder( KVEngine* kv_engine, bool segment_based_rebuild, uint64_t num_rebuild_threads, const CheckPoint& checkpoint) : kv_engine_(kv_engine), checkpoint_(checkpoint), segment_based_rebuild_(segment_based_rebuild), num_rebuild_threads_(std::min(num_rebuild_threads, kv_engine->configs_.max_access_threads)), recovery_segments_(), rebuild_skiplits_(), invalid_skiplists_() { rebuilder_thread_cache_.resize(num_rebuild_threads_); } SortedCollectionRebuilder::RebuildResult SortedCollectionRebuilder::Rebuild() { RebuildResult ret; if (rebuild_skiplits_.size() == 0) { return ret; } if (segment_based_rebuild_) { ret.s = segmentBasedIndexRebuild(); } else { ret.s = listBasedIndexRebuild(); } if (ret.s == Status::Ok) { ret.max_id = max_recovered_id_; ret.rebuild_skiplits.swap(rebuild_skiplits_); } cleanInvalidRecords(); return ret; } Status SortedCollectionRebuilder::AddHeader(DLRecord* header_record) { assert(header_record->entry.meta.type == SortedHeaderRecord); std::string collection_name = string_view_2_string(header_record->Key()); CollectionIDType id; SortedCollectionConfigs s_configs; Status s = Skiplist::DecodeSortedCollectionValue(header_record->Value(), id, s_configs); if (s != Status::Ok) { GlobalLogger.Error("Decode id and configs of sorted collection %s error\n", string_view_2_string(header_record->Key()).c_str()); return s; } auto comparator = kv_engine_->comparators_.GetComparator(s_configs.comparator_name); if (comparator == nullptr) { GlobalLogger.Error( "Compare function %s of restoring sorted collection %s is not " "registered\n", s_configs.comparator_name.c_str(), string_view_2_string(header_record->Key()).c_str()); return Status::Abort; } bool expired = TimeUtils::CheckIsExpired(header_record->GetExpireTime()); bool invalid_version = recoverToCheckpoint() && header_record->entry.meta.timestamp > checkpoint_.CheckpointTS(); // Check if this skiplist has newer version than checkpoint bool invalid_skiplist = expired || invalid_version; auto skiplist = std:: make_shared<Skiplist>(header_record, collection_name, id, comparator, kv_engine_->pmem_allocator_, kv_engine_->hash_table_, s_configs.index_with_hashtable && invalid_skiplist /* we do not build hash index for a invalid skiplist as it will be destroyed soon */); if (invalid_skiplist) { std::lock_guard<SpinMutex> lg(lock_); invalid_skiplists_.insert({id, skiplist}); max_recovered_id_ = std::max(max_recovered_id_, id); s = Status::Ok; } else { { // TODO: maybe return a skiplist map in rebuild finish, instead of access // engine directly std::lock_guard<SpinMutex> lg(lock_); rebuild_skiplits_.insert({id, skiplist}); max_recovered_id_ = std::max(max_recovered_id_, id); } if (segment_based_rebuild_) { // Always use header as a recovery segment addRecoverySegment(skiplist->Header()); } // Always index skiplist header with hash table s = insertHashIndex(skiplist->Name(), skiplist.get(), HashIndexType::Skiplist); } return s; } Status SortedCollectionRebuilder::AddElement(DLRecord* record) { kvdk_assert(record->entry.meta.type == SortedDataRecord || record->entry.meta.type == SortedDeleteRecord, "wrong record type in RestoreSkiplistRecord"); bool linked_record = checkAndRepairRecordLinkage(record); if (!linked_record) { if (!recoverToCheckpoint()) { kv_engine_->purgeAndFree(record); } else { // We do not know if this is a checkpoint version record, so we can't free // it here addUnlinkedRecord(record); } } else { if (segment_based_rebuild_ && ++rebuilder_thread_cache_[access_thread.id] .visited_skiplists[Skiplist::SkiplistID(record)] % kRestoreSkiplistStride == 0 && findValidVersion(record, nullptr) == record) { SkiplistNode* start_node = nullptr; while (start_node == nullptr) { // Always build dram node for a recovery segment start record start_node = Skiplist::NewNodeBuild(record); } addRecoverySegment(start_node); } } return Status::Ok; } Status SortedCollectionRebuilder::segmentBasedIndexRebuild() { GlobalLogger.Info("segment based rebuild start\n"); std::vector<std::future<Status>> fs; auto rebuild_segments_index = [&]() -> Status { Status s = this->kv_engine_->MaybeInitAccessThread(); if (s != Status::Ok) { return s; } defer(this->kv_engine_->ReleaseAccessThread()); for (auto iter = this->recovery_segments_.begin(); iter != this->recovery_segments_.end(); iter++) { if (!iter->second.visited) { std::lock_guard<SpinMutex> lg(this->lock_); if (!iter->second.visited) { iter->second.visited = true; } else { continue; } } else { continue; } auto rebuild_skiplist_iter = rebuild_skiplits_.find( Skiplist::SkiplistID(iter->second.start_node->record)); if (rebuild_skiplist_iter == rebuild_skiplits_.end()) { // this start point belong to a invalid skiplist kvdk_assert( invalid_skiplists_.find(Skiplist::SkiplistID( iter->second.start_node->record)) != invalid_skiplists_.end(), "Start record of a recovery segment should belong to a skiplist"); } else { bool build_hash_index = rebuild_skiplist_iter->second->IndexWithHashtable(); Status s = rebuildSegmentIndex(iter->second.start_node, build_hash_index); if (s != Status::Ok) { return s; } } } return Status::Ok; }; GlobalLogger.Info("build segment index\n"); for (uint32_t thread_num = 0; thread_num < num_rebuild_threads_; ++thread_num) { fs.push_back(std::async(rebuild_segments_index)); } for (auto& f : fs) { Status s = f.get(); if (s != Status::Ok) { return s; } } fs.clear(); GlobalLogger.Info("link dram nodes\n"); int i = 0; for (auto& s : rebuild_skiplits_) { i++; fs.push_back(std::async(&SortedCollectionRebuilder::linkHighDramNodes, this, s.second.get())); if (i % num_rebuild_threads_ == 0 || i == rebuild_skiplits_.size()) { for (auto& f : fs) { Status s = f.get(); if (s != Status::Ok) { return s; } } fs.clear(); } } recovery_segments_.clear(); GlobalLogger.Info("segment based rebuild done\n"); return Status::Ok; } Status SortedCollectionRebuilder::rebuildSegmentIndex(SkiplistNode* start_node, bool build_hash_index) { Status s; // First insert hash index for the start node if (build_hash_index && start_node->record->entry.meta.type != SortedHeaderRecord) { s = insertHashIndex(start_node->record->Key(), start_node, HashIndexType::SkiplistNode); if (s != Status::Ok) { return s; } } SkiplistNode* cur_node = start_node; DLRecord* cur_record = cur_node->record; while (true) { DLRecord* next_record = kv_engine_->pmem_allocator_->offset2addr_checked<DLRecord>( cur_record->next); if (next_record->entry.meta.type == SortedHeaderRecord) { cur_node->RelaxedSetNext(1, nullptr); break; } auto iter = recovery_segments_.find(next_record); if (iter == recovery_segments_.end()) { HashEntry hash_entry; DataEntry data_entry; HashEntry* entry_ptr = nullptr; StringView internal_key = next_record->Key(); auto hash_hint = kv_engine_->hash_table_->GetHint(internal_key); while (true) { std::lock_guard<SpinMutex> lg(*hash_hint.spin); DLRecord* valid_version_record = findValidVersion(next_record, nullptr); if (valid_version_record == nullptr) { if (!Skiplist::Purge(next_record, hash_hint.spin, nullptr, kv_engine_->pmem_allocator_.get(), kv_engine_->hash_table_.get())) { continue; } addUnlinkedRecord(next_record); } else { if (valid_version_record != next_record) { if (!Skiplist::Replace(next_record, valid_version_record, hash_hint.spin, nullptr, kv_engine_->pmem_allocator_.get(), kv_engine_->hash_table_.get())) { continue; } addUnlinkedRecord(next_record); } assert(valid_version_record != nullptr); SkiplistNode* dram_node = Skiplist::NewNodeBuild(valid_version_record); if (dram_node != nullptr) { cur_node->RelaxedSetNext(1, dram_node); dram_node->RelaxedSetNext(1, nullptr); cur_node = dram_node; } if (build_hash_index) { if (dram_node) { s = insertHashIndex(internal_key, dram_node, HashIndexType::SkiplistNode); } else { s = insertHashIndex(internal_key, valid_version_record, HashIndexType::DLRecord); } if (s != Status::Ok) { return s; } } cur_record = valid_version_record; } break; } } else { // link end node of this segment to adjacent segment if (iter->second.start_node->record->entry.meta.type != SortedHeaderRecord) { cur_node->RelaxedSetNext(1, iter->second.start_node); } else { cur_node->RelaxedSetNext(1, nullptr); } break; } } return Status::Ok; } void SortedCollectionRebuilder::linkSegmentDramNodes(SkiplistNode* start_node, int height) { assert(height > 1); while (start_node->Height() < height) { start_node = start_node->RelaxedNext(height - 1).RawPointer(); if (start_node == nullptr || recovery_segments_.find(start_node->record) != recovery_segments_.end()) { return; } } SkiplistNode* cur_node = start_node; SkiplistNode* next_node = cur_node->RelaxedNext(height - 1).RawPointer(); assert(start_node && start_node->Height() >= height); bool finish = false; while (true) { if (next_node == nullptr) { cur_node->RelaxedSetNext(height, nullptr); break; } if (recovery_segments_.find(next_node->record) != recovery_segments_.end()) { // link end point of this segment while (true) { if (next_node == nullptr || next_node->Height() >= height) { cur_node->RelaxedSetNext(height, next_node); break; } else { next_node = next_node->RelaxedNext(height - 1).RawPointer(); } } break; } if (next_node->Height() >= height) { cur_node->RelaxedSetNext(height, next_node); next_node->RelaxedSetNext(height, nullptr); cur_node = next_node; } next_node = next_node->RelaxedNext(height - 1).RawPointer(); } } Status SortedCollectionRebuilder::linkHighDramNodes(Skiplist* skiplist) { Splice splice(skiplist); for (uint8_t i = 1; i <= kMaxHeight; i++) { splice.prevs[i] = skiplist->Header(); } SkiplistNode* next_node = splice.prevs[1]->RelaxedNext(1).RawPointer(); while (next_node != nullptr) { assert(splice.prevs[1]->RelaxedNext(1).RawPointer() == next_node); splice.prevs[1] = next_node; if (next_node->Height() > 1) { for (uint8_t i = 2; i <= next_node->Height(); i++) { splice.prevs[i]->RelaxedSetNext(i, next_node); splice.prevs[i] = next_node; } } next_node = next_node->RelaxedNext(1).RawPointer(); } for (uint8_t i = 1; i <= kMaxHeight; i++) { splice.prevs[i]->RelaxedSetNext(i, nullptr); } return Status::Ok; } Status SortedCollectionRebuilder::rebuildSkiplistIndex(Skiplist* skiplist) { Status s = kv_engine_->MaybeInitAccessThread(); if (s != Status::Ok) { GlobalLogger.Error("too many threads repair skiplist linkage\n"); return s; } defer(kv_engine_->ReleaseAccessThread()); if (s != Status::Ok) { return s; } Splice splice(skiplist); HashEntry hash_entry; for (uint8_t i = 1; i <= kMaxHeight; i++) { splice.prevs[i] = skiplist->Header(); splice.prev_pmem_record = skiplist->Header()->record; } while (true) { uint64_t next_offset = splice.prev_pmem_record->next; DLRecord* next_record = kv_engine_->pmem_allocator_->offset2addr_checked<DLRecord>(next_offset); if (next_record == skiplist->Header()->record) { break; } StringView internal_key = next_record->Key(); auto hash_hint = kv_engine_->hash_table_->GetHint(internal_key); while (true) { std::lock_guard<SpinMutex> lg(*hash_hint.spin); DLRecord* valid_version_record = findValidVersion(next_record, nullptr); if (valid_version_record == nullptr) { // purge invalid version record from list if (!Skiplist::Purge(next_record, hash_hint.spin, nullptr, kv_engine_->pmem_allocator_.get(), kv_engine_->hash_table_.get())) { asm volatile("pause"); continue; } addUnlinkedRecord(next_record); } else { if (valid_version_record != next_record) { // repair linkage of checkpoint version if (!Skiplist::Replace(next_record, valid_version_record, hash_hint.spin, nullptr, kv_engine_->pmem_allocator_.get(), kv_engine_->hash_table_.get())) { continue; } addUnlinkedRecord(next_record); } // Rebuild dram node assert(valid_version_record != nullptr); SkiplistNode* dram_node = Skiplist::NewNodeBuild(valid_version_record); if (dram_node != nullptr) { auto height = dram_node->Height(); for (uint8_t i = 1; i <= height; i++) { splice.prevs[i]->RelaxedSetNext(i, dram_node); dram_node->RelaxedSetNext(i, nullptr); splice.prevs[i] = dram_node; } } // Rebuild hash index if (skiplist->IndexWithHashtable()) { Status s; if (dram_node) { s = insertHashIndex(internal_key, dram_node, HashIndexType::SkiplistNode); } else { s = insertHashIndex(internal_key, valid_version_record, HashIndexType::DLRecord); } if (s != Status::Ok) { return s; } } splice.prev_pmem_record = valid_version_record; } break; } } return Status::Ok; } Status SortedCollectionRebuilder::listBasedIndexRebuild() { std::vector<std::future<Status>> fs; int i = 0; for (auto skiplist : rebuild_skiplits_) { i++; fs.push_back(std::async(&SortedCollectionRebuilder::rebuildSkiplistIndex, this, skiplist.second.get())); if (i % num_rebuild_threads_ == 0 || i == rebuild_skiplits_.size()) { for (auto& f : fs) { Status s = f.get(); if (s != Status::Ok) { return s; } } fs.clear(); } } return Status::Ok; } bool SortedCollectionRebuilder::checkRecordLinkage(DLRecord* record) { PMEMAllocator* pmem_allocator = kv_engine_->pmem_allocator_.get(); uint64_t offset = pmem_allocator->addr2offset_checked(record); DLRecord* prev = pmem_allocator->offset2addr_checked<DLRecord>(record->prev); DLRecord* next = pmem_allocator->offset2addr_checked<DLRecord>(record->next); return prev->next == offset && next->prev == offset; } bool SortedCollectionRebuilder::checkAndRepairRecordLinkage(DLRecord* record) { PMEMAllocator* pmem_allocator = kv_engine_->pmem_allocator_.get(); uint64_t offset = pmem_allocator->addr2offset_checked(record); DLRecord* prev = pmem_allocator->offset2addr_checked<DLRecord>(record->prev); DLRecord* next = pmem_allocator->offset2addr_checked<DLRecord>(record->next); if (prev->next != offset && next->prev != offset) { return false; } // Repair un-finished write if (next->prev != offset) { next->prev = offset; pmem_persist(&next->prev, 8); } return true; } void SortedCollectionRebuilder::cleanInvalidRecords() { std::vector<SpaceEntry> to_free; // clean unlinked records for (auto& thread_cache : rebuilder_thread_cache_) { for (DLRecord* pmem_record : thread_cache.unlinked_records) { if (!checkRecordLinkage(pmem_record)) { pmem_record->Destroy(); to_free.emplace_back( kv_engine_->pmem_allocator_->addr2offset_checked(pmem_record), pmem_record->entry.header.record_size); } } kv_engine_->pmem_allocator_->BatchFree(to_free); to_free.clear(); thread_cache.unlinked_records.clear(); } // clean invalid skiplists for (auto& s : invalid_skiplists_) { s.second->Destroy(); } invalid_skiplists_.clear(); } void SortedCollectionRebuilder::addRecoverySegment(SkiplistNode* start_node) { if (segment_based_rebuild_) { std::lock_guard<SpinMutex> lg(lock_); recovery_segments_.insert({start_node->record, {false, start_node}}); } } Status SortedCollectionRebuilder::insertHashIndex(const StringView& key, void* index_ptr, HashIndexType index_type) { uint16_t search_type_mask; RecordType record_type; if (index_type == HashIndexType::DLRecord) { search_type_mask = SortedDataRecord | SortedDeleteRecord; record_type = static_cast<DLRecord*>(index_ptr)->entry.meta.type; } else if (index_type == HashIndexType::SkiplistNode) { search_type_mask = SortedDataRecord | SortedDeleteRecord; record_type = static_cast<SkiplistNode*>(index_ptr)->record->entry.meta.type; } else if (index_type == HashIndexType::Skiplist) { search_type_mask = SortedHeaderRecord; record_type = SortedHeaderRecord; } HashEntry* entry_ptr = nullptr; HashEntry hash_entry; auto hash_hint = kv_engine_->hash_table_->GetHint(key); Status s = kv_engine_->hash_table_->SearchForWrite( hash_hint, key, search_type_mask, &entry_ptr, &hash_entry, nullptr); switch (s) { case Status::NotFound: { kv_engine_->hash_table_->Insert(hash_hint, entry_ptr, record_type, index_ptr, index_type); return Status::Ok; } case Status::Ok: { GlobalLogger.Error( "Rebuild skiplist error, hash entry of sorted records should not be " "inserted before rebuild\n"); return Status::Abort; } case Status::MemoryOverflow: { return s; } default: std::abort(); // never reach } return Status::Ok; } DLRecord* SortedCollectionRebuilder::findValidVersion( DLRecord* pmem_record, std::vector<DLRecord*>* invalid_version_records) { if (!recoverToCheckpoint()) { return pmem_record; } DLRecord* curr = pmem_record; while (curr != nullptr && curr->entry.meta.timestamp > checkpoint_.CheckpointTS()) { curr = kv_engine_->pmem_allocator_->offset2addr<DLRecord>( curr->older_version_offset); kvdk_assert(curr == nullptr || curr->Validate(), "Broken checkpoint: invalid older version sorted record"); kvdk_assert( curr == nullptr || equal_string_view(curr->Key(), pmem_record->Key()), "Broken checkpoint: key of older version sorted data is " "not same as new " "version"); } return curr; } } // namespace KVDK_NAMESPACE
33.152733
165
0.622036
[ "vector" ]
450c4613e87fec89d9be387dec75f2950b7fe3b1
10,403
hxx
C++
include/problem_export.hxx
cxxszz/DD_ILP
1b6e543f949feb3ccd1925f7e34a104b06bbe2f0
[ "BSD-2-Clause" ]
null
null
null
include/problem_export.hxx
cxxszz/DD_ILP
1b6e543f949feb3ccd1925f7e34a104b06bbe2f0
[ "BSD-2-Clause" ]
null
null
null
include/problem_export.hxx
cxxszz/DD_ILP
1b6e543f949feb3ccd1925f7e34a104b06bbe2f0
[ "BSD-2-Clause" ]
4
2017-12-11T08:09:32.000Z
2022-03-25T14:24:46.000Z
#ifndef PROBLEM_EXPORT_HXX #define PROBLEM_EXPORT_HXX #include <iostream> #include <vector> #include <fstream> #include <iterator> namespace DD_ILP { // store problem and print it out to an .lp file class problem_export { public: struct vector_iterator : std::iterator< std::random_access_iterator_tag, std::size_t >{ vector_iterator(std::size_t _l) : l(_l) {} bool operator==(const vector_iterator o) const { return l == o.l; } bool operator!=(const vector_iterator o) const { return !(*this == o); } void operator++() { ++l; } const std::size_t operator*() const { return l; } long operator-(vector_iterator o) const { return l - o.l; } vector_iterator operator+(const int n) const { return vector_iterator(l + n); } vector_iterator operator-(const int n) const { return vector_iterator(l - n); } private: std::size_t l; }; struct vector_iterator_strided : std::iterator< std::random_access_iterator_tag, std::size_t >{ vector_iterator_strided(std::size_t _l, const std::size_t _stride) : l(_l), stride(_stride) {} bool operator==(const vector_iterator_strided o) const { return (l == o.l && stride == o.stride); } bool operator!=(const vector_iterator_strided o) const { return !(*this == o); } void operator++() { l+=stride; } const std::size_t operator*() const { return l; } long operator-(vector_iterator_strided o) const { return (l - o.l)/stride; } vector_iterator_strided operator+(const int n) const { return vector_iterator_strided(l + n*stride, stride); } private: std::size_t l; std::size_t stride; }; struct vector { template<typename VECTOR> vector(const VECTOR& v) : begin_(0), dim_(v.size()) {} vector(const std::size_t dim) : begin_(0), dim_(dim) { assert(dim > 0); } vector(std::size_t f, const std::size_t dim) : begin_(f), dim_(dim) { assert(dim > 0); } void set_begin(std::size_t l) { begin_ = l; } bool operator==(const vector o) const { return begin_ == o.begin_ && size() == o.size(); } std::size_t size() const { return dim_; } const std::size_t operator[](const std::size_t i) const { assert(i < size()); return begin_ + i; } const std::size_t back() const { return begin_ + size()-1; } auto begin() const { return vector_iterator(begin_); } auto end() const { return vector_iterator(begin_ + size()); } private: std::size_t begin_; const std::size_t dim_; }; struct vector_strided { vector_strided(std::size_t f, const std::size_t dim, const std::size_t stride) : begin_(f), dim_(dim), stride_(stride) { assert(dim > 0 && stride_ > 0); } bool operator==(const vector_strided o) const { return begin_ == o.begin_ && size() == o.size() && stride_ == o.stride_; } std::size_t size() const { return dim_; } const std::size_t operator[](const std::size_t i) const { assert(i < size()); return begin_ + i*stride_; } const std::size_t back() const { return (*this)[size()-1]; } auto begin() const { return vector_iterator_strided(begin_, stride_); } auto end() const { return vector_iterator_strided(begin_ + stride_*size(), stride_); } private: std::size_t begin_; const std::size_t dim_; const std::size_t stride_; }; struct matrix { template<typename MATRIX> matrix(const MATRIX& m) : begin_(0), dim_({m.dim1(), m.dim2()}) {} matrix(const std::size_t n, const std::size_t m) : begin_(0), dim_({n,m}) { assert(n > 0 && m > 0); } matrix(std::size_t f, const std::size_t n, const std::size_t m) : begin_(f), dim_({n,m}) { assert(n > 0 && m > 0); } void set_begin(std::size_t l) { begin_ = l; } bool operator==(const matrix& o) const { return begin_ == o.begin_ && dim_ == o.dim_; } std::size_t size() const { return dim_[0]*dim_[1]; } std::size_t dim1() const { return dim_[0]; } std::size_t dim2() const { return dim_[1]; } std::size_t dim(const std::size_t d) const { assert(d<2); return dim_[d]; } const std::size_t operator[](const std::size_t i) const { assert(i < size()); return begin_ + i; } const std::size_t operator()(const std::size_t x1, const std::size_t x2) const { assert(x1 < dim(0) && x2 < dim(1)); return begin_ + x1*dim(1) + x2; } auto begin() const { return vector_iterator(begin_); } auto end() const { return vector_iterator(begin_ + size()); } vector slice_left(const std::size_t x1) const { assert(x1 < dim(0)); return vector(begin_ + x1*dim(1),dim(1)); } auto slice1(const std::size_t x1) const { return slice_left(x1); } vector_strided slice_right(const std::size_t x2) const { assert(x2 < dim(1)); return vector_strided(begin_ + x2, dim(0), dim(1)); } auto slice2(const std::size_t x2) const { return slice_right(x2); } private: std::size_t begin_; const std::array<std::size_t,2> dim_; }; struct tensor { template<typename TENSOR> tensor(const TENSOR& t) : begin_(0), dim_({t.dim1(), t.dim2(), t.dim3()}) {} tensor(const std::size_t n, const std::size_t m, const std::size_t k) : begin_(0), dim_({n,m,k}) { assert(n > 0 && m > 0 && k > 0); } tensor(std::size_t f, const std::size_t n, const std::size_t m, const std::size_t k) : begin_(f), dim_({n,m,k}) { assert(n > 0 && m > 0 && k > 0); } void set_begin(std::size_t l) { assert(l > 0); begin_ = l; } bool operator==(const tensor& o) const { return begin_ == o.begin_ && dim_ == o.dim_; } std::size_t size() const { return dim_[0]*dim_[1]*dim_[2]; } std::size_t dim(const std::size_t d) const { assert(d<3); return dim_[d]; } const std::size_t operator[](const std::size_t i) const { assert(i < size()); return begin_ + i; } const std::size_t operator()(const std::size_t x1, const std::size_t x2, const std::size_t x3) const { assert(x1 < dim(0) && x2 < dim(1) && x3 < dim(2)); return begin_ + x1*dim(1)*dim(2) + x2*dim(2) + x3; } auto begin() const { return vector_iterator(begin_); } auto end() const { return vector_iterator(begin_ + size()); } vector slice12(const std::size_t x1, const std::size_t x2) const { assert(x1 < dim(0) && x2 < dim(1)); return vector(begin_ + x1*dim(2)*dim(1) + x2*dim(2),dim(2)); } vector_strided slice13(const std::size_t x1, const std::size_t x3) const { assert(x1 < dim(0) && x3 < dim(2)); return vector_strided(begin_ + x1*dim(2)*dim(1) + x3, dim(1), dim(2)); } vector_strided slice23(const std::size_t x2, const std::size_t x3) const { assert(x2 < dim(1) && x3 < dim(2)); return vector_strided(begin_ + x2*dim(2) + x3, dim(0), dim(1)*dim(2)); } private: std::size_t begin_; const std::array<std::size_t,3> dim_; }; using variable = std::size_t; variable add_variable() { return variable_counter_++; } vector add_vector(const std::size_t dim) { vector vec(variable_counter_, dim); variable_counter_ += dim; return vec; } matrix add_matrix(const std::size_t n, const std::size_t m) { matrix mat(variable_counter_, n, m); variable_counter_ += n*m; return mat; } tensor add_tensor(const std::size_t n, const std::size_t m, const std::size_t k) { tensor t(variable_counter_, n, m, k); variable_counter_ += n*m*k; return t; } template<typename T> void add_objective(variable x, const T val) { if(objective_.size() <= x) { objective_.resize(x+1, 0.0); } objective_[x] = val; } void add_implication(const variable i, const variable j) { constraints_.push_back(var_name(i) + " <= " + var_name(j)); } template<typename ITERATOR> variable add_at_most_one_constraint(ITERATOR variable_begin, ITERATOR variable_end) { auto sum_var = add_variable(); std::string c = sum(variable_begin, variable_end); c += " - " + var_name(sum_var) + " = 0"; constraints_.push_back(std::move(c)); return sum_var; } template<typename ITERATOR> void add_simplex_constraint(ITERATOR variable_begin, ITERATOR variable_end) { auto c = sum(variable_begin, variable_end) += " = 1"; constraints_.push_back(std::move(c)); } void make_equal(const variable i, const variable j) { constraints_.push_back(var_name(i) + " = " + var_name(j)); } template<typename ITERATOR> variable max(ITERATOR var_begin, ITERATOR var_end) { auto one_active = add_variable(); for(auto it=var_begin; it!=var_end; ++it) { add_implication(*it, one_active); } for(auto it=var_begin; it!=var_end; ++it) { constraints_.push_back("1 - " + var_name(one_active) + " >= " + var_name(*it)); } // add implication one_active => exists active variable constraints_.push_back(var_name(one_active) + " <= "); constraints_.back() += sum(var_begin, var_end); return one_active; } bool solve() const { return false; } bool solution(const variable i) const { assert(false); return false; } void write_to_file(const std::string& filename) const { std::ofstream f(filename); if(!f) { throw std::runtime_error("could not open file" + filename + " for LP-export"); } f << "Minimize\n"; for(variable i=0; i<objective_.size(); ++i) { auto obj = objective_[i]; f << (obj < 0 ? std::to_string(obj) : "+" + std::to_string(obj)) << " " << var_name(i) << "\n"; } f << "Subject To\n"; for(auto& c : constraints_) { f << c << "\n"; } f << "Bounds\nBinaries\n"; for(variable i=0; i<variable_counter_; ++i) { f << var_name(i) << "\n"; } f << "End"; f.close(); } private: static std::string var_name(const variable x) { return "x" + std::to_string(x); } template<typename ITERATOR> static std::string sum(ITERATOR var_begin, ITERATOR var_end) { assert(std::distance(var_begin, var_end) > 0); std::string c = var_name(*var_begin); for(auto it=var_begin+1; it!=var_end; ++it) { c += " + " + var_name(*it); } return c; } std::size_t variable_counter_ = 0; std::vector<double> objective_; std::vector<std::string> constraints_; }; } // namespace DD_ILP #endif // PROBLEM_EXPORT_HXX
29.22191
121
0.615784
[ "vector" ]
450d8e2773596f260c78174a139d25111415ce48
4,006
cpp
C++
aws-cpp-sdk-apigateway/source/model/VpcLink.cpp
crazecdwn/aws-sdk-cpp
e74b9181a56e82ee04cf36a4cb31686047f4be42
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-apigateway/source/model/VpcLink.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-apigateway/source/model/VpcLink.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/apigateway/model/VpcLink.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace APIGateway { namespace Model { VpcLink::VpcLink() : m_idHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_targetArnsHasBeenSet(false), m_status(VpcLinkStatus::NOT_SET), m_statusHasBeenSet(false), m_statusMessageHasBeenSet(false), m_tagsHasBeenSet(false) { } VpcLink::VpcLink(JsonView jsonValue) : m_idHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_targetArnsHasBeenSet(false), m_status(VpcLinkStatus::NOT_SET), m_statusHasBeenSet(false), m_statusMessageHasBeenSet(false), m_tagsHasBeenSet(false) { *this = jsonValue; } VpcLink& VpcLink::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("id")) { m_id = jsonValue.GetString("id"); m_idHasBeenSet = true; } if(jsonValue.ValueExists("name")) { m_name = jsonValue.GetString("name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("description")) { m_description = jsonValue.GetString("description"); m_descriptionHasBeenSet = true; } if(jsonValue.ValueExists("targetArns")) { Array<JsonView> targetArnsJsonList = jsonValue.GetArray("targetArns"); for(unsigned targetArnsIndex = 0; targetArnsIndex < targetArnsJsonList.GetLength(); ++targetArnsIndex) { m_targetArns.push_back(targetArnsJsonList[targetArnsIndex].AsString()); } m_targetArnsHasBeenSet = true; } if(jsonValue.ValueExists("status")) { m_status = VpcLinkStatusMapper::GetVpcLinkStatusForName(jsonValue.GetString("status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("statusMessage")) { m_statusMessage = jsonValue.GetString("statusMessage"); m_statusMessageHasBeenSet = true; } if(jsonValue.ValueExists("tags")) { Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects(); for(auto& tagsItem : tagsJsonMap) { m_tags[tagsItem.first] = tagsItem.second.AsString(); } m_tagsHasBeenSet = true; } return *this; } JsonValue VpcLink::Jsonize() const { JsonValue payload; if(m_idHasBeenSet) { payload.WithString("id", m_id); } if(m_nameHasBeenSet) { payload.WithString("name", m_name); } if(m_descriptionHasBeenSet) { payload.WithString("description", m_description); } if(m_targetArnsHasBeenSet) { Array<JsonValue> targetArnsJsonList(m_targetArns.size()); for(unsigned targetArnsIndex = 0; targetArnsIndex < targetArnsJsonList.GetLength(); ++targetArnsIndex) { targetArnsJsonList[targetArnsIndex].AsString(m_targetArns[targetArnsIndex]); } payload.WithArray("targetArns", std::move(targetArnsJsonList)); } if(m_statusHasBeenSet) { payload.WithString("status", VpcLinkStatusMapper::GetNameForVpcLinkStatus(m_status)); } if(m_statusMessageHasBeenSet) { payload.WithString("statusMessage", m_statusMessage); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("tags", std::move(tagsJsonMap)); } return payload; } } // namespace Model } // namespace APIGateway } // namespace Aws
22.632768
106
0.715427
[ "model" ]
4513ee0595c75c0a4e71d8f63684c4708dae3461
1,624
hpp
C++
Source/Utility/Thread/kThreadPool.hpp
KingKiller100/kLibrary
37971acd3c54f9ea0decdf78b13e47c935d4bbf0
[ "Apache-2.0" ]
null
null
null
Source/Utility/Thread/kThreadPool.hpp
KingKiller100/kLibrary
37971acd3c54f9ea0decdf78b13e47c935d4bbf0
[ "Apache-2.0" ]
null
null
null
Source/Utility/Thread/kThreadPool.hpp
KingKiller100/kLibrary
37971acd3c54f9ea0decdf78b13e47c935d4bbf0
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../../TypeTraits/BooleanTraits.hpp" #include <functional> #include <mutex> #include <queue> namespace klib::kThread { class ThreadPool { public: using Func_t = std::function<void()>; struct Job { Func_t task; std::string desc; Job() noexcept : task(nullptr) {} Job(const Func_t& taskToDo, const std::string& description) : task(taskToDo) , desc(description) {} void operator()() const { task(); } }; public: ThreadPool(size_t count); ThreadPool(const ThreadPool& other) noexcept = delete; ThreadPool& operator=(const ThreadPool& other) noexcept = delete; ThreadPool(ThreadPool&& other) noexcept = delete; ThreadPool& operator=(ThreadPool&& other) noexcept = delete; ~ThreadPool(); void AddThread(size_t count); void Shutdown(size_t index); void ShutdownAll(); bool CanJoin(size_t index) const; bool CanJoinAll() const; void Join(size_t index); void JoinAll(); void JoinAndPopAll(); void Detach(size_t index); void DetachAll(); void PopJob(); void ClearJobs(); size_t GetSize() const; std::thread::id GetID(size_t index) const; std::vector<std::thread::id> GetIDs() const; void QueueJob(const Job& job); std::thread& GetThread(size_t index); const std::thread& GetThread(size_t index) const; protected: void ThreadLoop(const type_trait::BooleanWrapper& sd); protected: std::mutex mutex; std::condition_variable condVar; std::vector<type_trait::BooleanWrapper> shutdowns; std::queue<Job> jobs; std::vector<std::thread> threads; std::string prevJob; }; }
17.462366
67
0.680419
[ "vector" ]
4515037e51324a8ee77e6c71a5fe7cf1cc0a5c4e
1,978
cpp
C++
01 January Leetcode Challenge 2021/09 wordLadder.cpp
FazeelUsmani/Leetcode
aff4c119178f132c28a39506ffaa75606e0a861b
[ "MIT" ]
7
2020-12-01T14:27:57.000Z
2022-02-12T09:17:22.000Z
01 January Leetcode Challenge 2021/09 wordLadder.cpp
FazeelUsmani/Leetcode
aff4c119178f132c28a39506ffaa75606e0a861b
[ "MIT" ]
4
2020-11-12T17:49:22.000Z
2021-09-06T07:46:37.000Z
01 January Leetcode Challenge 2021/09 wordLadder.cpp
FazeelUsmani/Leetcode
aff4c119178f132c28a39506ffaa75606e0a861b
[ "MIT" ]
6
2021-05-21T03:49:22.000Z
2022-01-20T20:36:53.000Z
from collections import defaultdict class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ if endWord not in wordList or not endWord or not beginWord or not wordList: return 0 # Since all words are of same length. L = len(beginWord) # Dictionary to hold combination of words that can be formed, # from any given word. By changing one letter at a time. all_combo_dict = defaultdict(list) for word in wordList: for i in range(L): # Key is the generic word # Value is a list of words which have the same intermediate generic word. all_combo_dict[word[:i] + "*" + word[i+1:]].append(word) # Queue for BFS queue = collections.deque([(beginWord, 1)]) # Visited to make sure we don't repeat processing same word. visited = {beginWord: True} while queue: current_word, level = queue.popleft() for i in range(L): # Intermediate words for current word intermediate_word = current_word[:i] + "*" + current_word[i+1:] # Next states are all the words which share the same intermediate state. for word in all_combo_dict[intermediate_word]: # If at any point if we find what we are looking for # i.e. the end word - we can return with the answer. if word == endWord: return level + 1 # Otherwise, add it to the BFS Queue. Also mark it visited if word not in visited: visited[word] = True queue.append((word, level + 1)) all_combo_dict[intermediate_word] = [] return 0
40.367347
89
0.551062
[ "object" ]
4516519755d64653945fa1ec11071f11198b6bfe
67,770
hpp
C++
ddbtoaster/srccpp/lib/mmap/cmmap.hpp
szarnyasg/dbtoaster-backend
24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73
[ "Apache-2.0" ]
8
2019-02-13T10:56:44.000Z
2021-10-14T03:31:03.000Z
ddbtoaster/srccpp/lib/mmap/cmmap.hpp
szarnyasg/dbtoaster-backend
24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73
[ "Apache-2.0" ]
null
null
null
ddbtoaster/srccpp/lib/mmap/cmmap.hpp
szarnyasg/dbtoaster-backend
24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73
[ "Apache-2.0" ]
3
2021-06-13T12:26:40.000Z
2022-03-29T19:58:35.000Z
#ifndef CMMAP_H #define CMMAP_H #include <iostream> #include <assert.h> #include <functional> #include <string.h> #include <libcuckoo/cuckoohash_map.hh> #include "types.h" #include "Version.h" #include "../serialization.hpp" #include "../hpds/pstring.hpp" #include "../hpds/macro.hpp" #include <vector> #include "Predicate.h" #include <atomic> #include <type_traits> #include "SpinLock.h" std::vector<void*> tempMem; #define DEFAULT_CHUNK_SIZE 32 #ifndef DEFAULT_HEAP_SIZE #define DEFAULT_HEAP_SIZE 16 #endif FORCE_INLINE void clearTempMem() { for (auto ptr : tempMem) free(ptr); tempMem.clear(); } #define FuncType const std::function<TransactionReturnStatus (T*)>& template<typename T> class IndexMV { public: int idxId; //SBJ: Check if it can be removed MBase* mmapmv; // virtual bool hashDiffers(const T& x, const T& y) const = 0; virtual T* get(const T* key, Transaction& xact) const = 0; virtual T* getForUpdate(const T* key, OperationReturnStatus& s, Transaction& xact) = 0; virtual OperationReturnStatus add(Version<T>* v) = 0; virtual void removeEntry(T* obj, EntryMV<T>* emv) = 0; virtual void undo(Version<T>* v) = 0; virtual void del(Version<T>* v) = 0; // virtual void delCopy(const T* obj, Index<T>* primary) = 0; virtual OperationReturnStatus foreach(FuncType f, Transaction& xact) = 0; // virtual void foreachCopy(FuncType f) = 0; // virtual void slice(const T* key, FuncType f) = 0; // virtual void sliceCopy(const T* key, FuncType f) = 0; // virtual void update(T* obj) = 0; // // virtual void updateCopy(T* obj, Index<T, V>* primary) = 0; // // virtual void updateCopyDependent(T* obj, T* elem) = 0; // virtual size_t count() const = 0; // virtual void clear() = 0; virtual void prepareSize(size_t arrayS, size_t poolS) = 0; virtual ~IndexMV() { }; }; template <typename T, typename IDX_FN> struct HE_ { size_t operator()(const T* e) const { size_t h = IDX_FN::hash(*e); return h; } bool operator()(const T* e1, const T* e2) const { return IDX_FN::cmp(*e1, *e2) == 0; } }; template<typename T, typename IDX_FN > struct CuckooIndex : public IndexMV<T> { typedef HE_<T, IDX_FN> HE; cuckoohash_map<T*, EntryMV<T>*, HE, HE, std::allocator<std::pair<T, EntryMV<T>*>>> index; std::atomic<EntryMV<T>*> dataHead; CuckooIndex(int s = 0) : index((1 << 25)) { //Constructor argument is ignored dataHead = nullptr; } CuckooIndex(void* ptr, int s = 0) : index(1 << 25) { //Constructor argument is ignored dataHead = nullptr; } FORCE_INLINE bool operator==(CuckooIndex<T, IDX_FN>& that) { auto t1 = index.lock_table(); bool flag = true; Version<T>* v1, *v2; for (auto e1 = t1.cbegin(); e1 != t1.cend(); ++e1) { EntryMV<T>* e2; v1 = e1->second->versionHead; //SBJ: v1 cannot be nullptr if rollback removes EntryMV if all versions are gone if (!v1 || v1->obj.isInvalid) continue; if (!that.index.find(e1->first, e2)) { std::cerr << v1->obj << "is extra in table" << std::endl; flag = false; } else { v2 = e2->versionHead; if (!(v2->obj == v1->obj)) { std::cerr << "Found " << v1->obj << " where it should have been " << v2->obj << std::endl; flag = false; } } } t1.release(); auto t2 = that.index.lock_table(); for (auto e2 = t2.cbegin(); e2 != t2.cend(); ++e2) { EntryMV<T>* e1; v2 = e2->second->versionHead; if (!index.find(e2->first, e1)) { std::cerr << v2->obj << " is missing from table " << std::endl; flag = false; } else { v1 = e1->versionHead; if (!(v1->obj == v2->obj)) { std::cerr << "Found" << v1->obj << " where it should have been " << v2->obj << std::endl; flag = false; } } } return flag; } FORCE_INLINE void getSizeStats(std::ostream & fout) { fout << "{}"; } //SBJ: Only for data result loading . To be removed later FORCE_INLINE void add(T* obj, Transaction& xact) { Version<T>* v = aligned_malloc(Version<T>); new(v) Version<T>(*obj, xact); EntryMV<T>* e = aligned_malloc(EntryMV<T>); new(e) EntryMV<T>(nullptr, *obj, v); v->e = e; index.insert(obj, e); xact.undoBufferHead = v; } FORCE_INLINE OperationReturnStatus add(Version<T>* newv) override { auto idxId = IndexMV<T>::idxId; T* keyC = &newv->obj; EntryMV<T> *emv = (EntryMV<T>*) newv->e; if (index.insert(keyC, emv)) { if (idxId == 0) { EntryMV<T>* dh = dataHead; emv->nxt = dh; while (!dataHead.compare_exchange_weak(dh, emv)) { emv->nxt = dh; } } return OP_SUCCESS; } else { return WW_VALUE; } } //SBJ: what should a multiversion clear be? // void clear() override { // index.clear(); // if (dataHead) { // EntryMV<T>* tmp; // Version<T>* VH, *tmpV; // while (dataHead != nullptr) { // tmp = dataHead; // dataHead = dataHead->nxt; // VH = tmp->versionHead; // free(tmp); // while (VH != nullptr) { // tmpV = VH; // VH = VH->oldV; // free(tmpV); // } // } // } // } // size_t count() const override { // return -1; // } FORCE_INLINE void removeEntry(T* obj, EntryMV<T>* emv) override { EntryMV<T>* nxt = emv->nxt; while (!emv->nxt.compare_exchange_strong(nxt, mark(nxt))); //removing from foreach list //SBJ: TODO: Mark other fields as well??? index.erase(obj); //SBJ: TODO: free the memory for key store in cuckoo } FORCE_INLINE void undo(Version<T>* v) override { //Do nothign } FORCE_INLINE void del(Version<T>* v) override { //Do nothing for primary hash index } // void del(T* obj) override { // // if (idxId == 0) { // EntryMV< *elemPrv = obj->prv, *elemNxt = obj->nxt; // if (elemPrv) // elemPrv->nxt = elemNxt; // else // dataHead = elemNxt; // // if (elemNxt) elemNxt->prv = elemPrv; // // obj->nxt = nullptr; // obj->prv = nullptr; // } // // if (index.erase(obj)) { // count_--; // } else { // throw std::logic_error("Delete failed"); // } // } // void delCopy(const T* obj, Index<T, V>* primary) override { // T* orig = primary->get(obj); // del(orig); // } FORCE_INLINE OperationReturnStatus foreach(FuncType f, Transaction& xact) override { EntryMV<T>* cur = dataHead; ForEachPred<T>* pred = (ForEachPred<T>*) malloc(sizeof(ForEachPred<T>)); new(pred) ForEachPred<T>(xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; while (cur) { //SBJ: TODO check for tombstoned entries and delete them Version<T>* v = cur->getCorrectVersion(xact); auto st = f(&v->obj); if (st != SUCCESS) return OR(st); cur = cur->nxt; } return OP_SUCCESS; } // void foreachCopy(FuncType f) override { // std::vector<T*> entries; // T* cur = dataHead; // while (cur) { // entries.push_back(cur->copy()); // cur = cur->nxt; // } // for (auto it : entries) { // f(it); // free(it); //Not calling destructor // } // } FORCE_INLINE T* get(const T* key, Transaction& xact) const override { EntryMV<T>* result; if (index.find(key, result)) { Version<T>* v = result->getCorrectVersion(xact); if (v->obj.isInvalid) return nullptr; GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return &v->obj; } else { return nullptr; } } FORCE_INLINE T* getForUpdate(const T* key, OperationReturnStatus& st, Transaction& xact) override { EntryMV<T>* result; if (index.find(key, result)) { Version<T>* resV = result->versionHead; if (!resV->isVisible(&xact)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; return nullptr; } if (resV->obj.isInvalid) { st = NO_KEY; return nullptr; } Version<T> *newv = aligned_malloc(Version<T>); new(newv) Version<T>(resV, xact); if (!result->versionHead.compare_exchange_strong(resV, newv)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; free(newv); return nullptr; } GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; xact.undoBufferHead = newv; st = OP_SUCCESS; return &newv->obj; } else { st = NO_KEY; return nullptr; } } FORCE_INLINE void prepareSize(size_t arrayS, size_t poolS) override { index.reserve(arrayS); } //Assumption : primary key columns don't change. So do nothing FORCE_INLINE OperationReturnStatus update(T* obj) { // Version<T>* v = (Version<T>*) VBase::getVersionFromT((char *) obj); // EntryMV<T>* emv = (EntryMV<T>*) v->e; // EntryMV<T>* res; // if (index.find(obj, res)) { // return res == emv ? OP_SUCCESS : DUPLICATE_KEY; // } else { // if (!index.insert(obj, emv)) // return DUPLICATE_KEY; // } return OP_SUCCESS; } virtual ~CuckooIndex() { } /******************* non-virtual function wrappers ************************/ FORCE_INLINE T* get(const T& key, Transaction& xact) const { return get(&key, xact); } FORCE_INLINE T* getForUpdate(const T& key, OperationReturnStatus& st, Transaction& xact) { return getForUpdate(&key, st, xact); } // FORCE_INLINE T* getCopy(const T* key) const { // T* obj = get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopy(const T& key) const { // T* obj = get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopyDependent(const T* key) const { // T* obj = get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopyDependent(const T& key) const { // T* obj = get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE void slice(const T& key, FuncType f) { // slice(&key, f); // } // FORCE_INLINE void sliceCopy(const T& key, FuncType f) { // sliceCopy(&key, f); // } // // FORCE_INLINE void sliceCopyDependent(const T* key, FuncType f) { // sliceCopy(key, f); // } // // FORCE_INLINE void sliceCopyDependent(const T& key, FuncType f) { // sliceCopy(&key, f); // } // // FORCE_INLINE void delCopyDependent(const T* obj) { // del(obj); // } }; template <typename T, typename IDX_FN, size_t size> struct ConcurrentArrayIndex : public IndexMV<T> { template<typename A> struct ALIGN CacheAtomic { std::atomic<A> elem; }; typedef CacheAtomic<EntryMV<T>*> AlignedEntry; AlignedEntry array[size]; bool operator==(const ConcurrentArrayIndex<T, IDX_FN, size>& that) { for (size_t i = 0; i < size; ++i) { EntryMV<T>* e1 = array[i].elem; EntryMV<T>* e2 = that.array[i].elem; if ((!e1 && e2) || (e1 && !e2)) { cerr << "Array slots don't match" << endl; if (e1) cerr << e1->versionHead.load()->obj << "is extra"; else cerr << e2->versionHead.load()->obj << "is missing"; return false; } if (!e1) continue; T& t1 = e1->versionHead.load()->obj; T& t2 = e2->versionHead.load()->obj; if (!(t1 == t2)) { cerr << "Found " << t1 << " where it should have been " << t2 << endl; return false; } } return true; } ConcurrentArrayIndex(size_t s) {//ignore memset(array, 0, sizeof(AlignedEntry) * size); } ConcurrentArrayIndex(void* ptr, size_t s) {//ignore memset(array, 0, sizeof(AlignedEntry) * size); } //Data Result loading FORCE_INLINE void add(T* obj, Transaction& xact) { Version<T>* v = aligned_malloc(Version<T>); new(v) Version<T>(*obj, xact); EntryMV<T>* e = aligned_malloc(EntryMV<T>); new(e) EntryMV<T>(nullptr, *obj, v); v->e = e; size_t idx = IDX_FN::hash(v->obj); array[idx].elem = e; xact.undoBufferHead = v; } FORCE_INLINE OperationReturnStatus add(Version<T>* v) override { size_t idx = IDX_FN::hash(v->obj); assert(idx >= 0 && idx < size); EntryMV<T>* emv = (EntryMV<T>*)v->e; EntryMV<T>* temp = nullptr; emv->backptrs[IndexMV<T>::idxId] = array + idx; if (array[idx].elem.compare_exchange_strong(temp, emv)) { return OP_SUCCESS; } else return WW_VALUE; } void removeEntry(T* obj, EntryMV<T>* emv) override { } void undo(Version<T>* v) override { } //Assumption: Primary key columns do not change. So, do nothing FORCE_INLINE OperationReturnStatus update(T* obj) { // Version<T>* v = (Version<T>*) VBase::getVersionFromT((char *) obj); // EntryMV<T>* emv = (EntryMV<T>*) v->e; // EntryMV<T>* res = nullptr; // size_t idx = IDX_FN::hash(*obj); // //SBJ: Backpointer?? // if (!array[idx].elem.compare_exchange_strong(res, emv)) { // return res == emv ? OP_SUCCESS : DUPLICATE_KEY; // } return OP_SUCCESS; } FORCE_INLINE void del(Version<T>* v) override { // size_t idx = IDX_FN::hash(*obj); EntryMV<T>* emv = (EntryMV<T>*)v->e; AlignedEntry* ca = (AlignedEntry*) emv->backptrs[IndexMV<T>::idxId]; auto idx = ca - array; assert(idx >= 0 && idx < size); ca->elem.compare_exchange_strong(emv, nullptr); } FORCE_INLINE OperationReturnStatus foreach(FuncType f, Transaction& xact) override { //Do nothing for now return OP_SUCCESS; } FORCE_INLINE T* get(const T* key, Transaction& xact) const override { return get(*key, xact); } FORCE_INLINE T* get(const T& key, Transaction& xact) const { size_t idx = IDX_FN::hash(key); assert(idx >= 0 && idx < size); EntryMV<T>* e = array[idx].elem.load(); if (!e) return nullptr; Version<T>* v = e->getCorrectVersion(xact); if (!v) return nullptr; else { GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return &v->obj; } } T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) override { return getForUpdate(*key, s, xact); } T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { size_t idx = IDX_FN::hash(key); assert(idx >= 0 && idx < size); EntryMV<T>* e = array[idx].elem; if (!e) { s = NO_KEY; return nullptr; } Version<T>* resV = e->versionHead; if (!resV->isVisible(&xact)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } s = WW_VALUE; return nullptr; } Version<T>* newv = aligned_malloc(Version<T>); new (newv) Version<T>(resV, xact); if (!e->versionHead.compare_exchange_strong(resV, newv)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } s = WW_VALUE; free(newv); return nullptr; } GetPred<T, IDX_FN>* pred = (GetPred<T, IDX_FN>*) malloc(sizeof(GetPred<T, IDX_FN>)); new(pred) GetPred<T, IDX_FN>(key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; xact.undoBufferHead = newv; s = OP_SUCCESS; return &newv->obj; return &resV->obj; } void prepareSize(size_t arrayS, size_t poolS) override { //do nothing } }; // //template <typename T> //struct TreeNode { // uint8_t height; // EntryMV<T>* emv; // TreeNode *parent, *left, *right; // // TreeNode(EntryMV<T>* e, TreeNode* p) : height(1), emv(e), parent(p), left(nullptr), right(nullptr) { // // } //}; //template<typename T, typename IDX_FN2> //struct _Tree { // typedef TreeNode<T> Node; // Node* root; // SpinLock lock; // // _Tree(EntryMV<T>* e) { // root = malloc(sizeof(Node)); // new (root) Node(e, nullptr); // } // FORCE_INLINE Node* getNext(Node* p) { // Node* cur = p->right; // if(cur) { // while(cur->left) // cur = cur->left; // return cur; // } // } // FORCE_INLINE int bfactor(Node *p) { // return height(p->right) - height(p->left); // } // // FORCE_INLINE uint8_t height(Node *p) { // return p ? p->height : 0; // } // // FORCE_INLINE void fixHeight(Node *p) { // uint8_t hl = height(p->left); // uint8_t hr = height(p->right); // p->height = (hl > hr ? hl : hr) + 1; // // } // // FORCE_INLINE Node* rotateRight(Node* p) { // Node* q = p->left; // p->left = q->right; // q->right = p; // // q->parent = p->parent; // p->parent = q; // if (p->left) // p->left->parent = p; // fixHeight(p); // fixHeight(q); // return q; // } // // FORCE_INLINE Node* rotateLeft(Node *p) { // Node* q = p->right; // p->right = q->left; // q->left = p; // // q->parent = p->parent; // p->parent = q; // if (p->right) // p->right->parent = p; // fixHeight(p); // fixHeight(q); // return q; // } // // FORCE_INLINE Node* balance(Node *p) { // fixHeight(p); // if (bfactor(p) == 2) { // if (bfactor(p->right) < 0) // p->right = rotateRight(p->right); // return rotateLeft(p); // } // if (bfactor(p) == -2) { // if (bfactor(p->left) > 0) // p->left = rotateLeft(p->left); // return rotateRight(p); // } // return p; // } // // FORCE_INLINE insert_BST(T* obj, EntryMV<T>* emv) { // Node* cur = root; // while (cur != nullptr) { // T& curObj = cur ->emv->versionHead.load()->obj; // //assumes that slice columns as well as the ord column are same across all versions of Entry // if (IDX_FN2::cmp(*obj, curObj) < 0) { // if (cur->left == nullptr) { // Node* newnode = (Node*) malloc(sizeof(Node)); // new(newnode) Node(emv, cur); // cur->left = newnode; // // Node* par; // while (true) { // par = cur->parent; // if (par) { // if (par->right == cur) { // cur = balance(cur); // par->right = cur; // } else { // cur = balance(cur); // par->left = cur; // } // } else { // root = balance(root); // return; // } // cur = par; // } // } // cur = cur->left; // } else { // if (cur->right == nullptr) { // Node* newnode = (Node*) malloc(sizeof(Node)); // new(newnode) Node(emv, cur); // cur->right = newnode; // // Node* par; // while (true) { // par = cur->parent; // if (par) { // if (par->right == cur) { // cur = balance(cur); // par->right = cur; // } else { // cur = balance(cur); // par->left = cur; // } // } else { // root = balance(root); // return; // } // cur = par; // } // } // cur = cur->right; // } // // } // } // // FORCE_INLINE void removeBST(T* obj, EntryMV* emv) { // Node* cur = root; // while (cur != nullptr) { // if (cur->emv == emv) { // found it // Node* temp; // if (cur->left && cur->right) { // 2 children case // temp = cur; // cur = cur->left; // while (cur->right) { // cur = cur->right; // } // temp-> emv = cur->emv; // } // // now cur has 0 or 1 child // temp = (cur->left ? cur->left : cur->right); // Node* par = cur->parent; // if (!par) // root = temp; // else if (cur == par->right) // par->right = temp; // else // par->left = temp; // // if (temp) // temp->parent = par; // free(cur); // // if (par) { // cur = par; // while (true) { // par = cur->parent; // if (par) { // if (par->right == cur) { // cur = balance(cur); // par->right = cur; // } else { // cur = balance(cur); // par->left = cur; // } // } else { // root = balance(cur); // return; // } // cur = par; // } // } // return; // } // T& curObj = cur->emv->versionHead.load()->obj; // if (IDX_FN2::cmp(*obj, curObj) < 0) // cur = cur->left; // else // cur = cur->right; // } // } //}; // //template<typename T, typename IDX_FN1, typename IDX_FN2> //struct CuckooTreeIndex : public IndexMV<T> { // typedef _Tree<T, IDX_FN2> Tree; // struct HE { // size_t operator()(const T* e) const { // size_t h = IDX_FN1::hash(*e); // return h; // } // bool operator()(const T* e1, const T* e2) const { // return IDX_FN1::cmp(*e1, *e2) == 0; // } // }; // cuckoohash_map<T*, Tree*, HE, HE, std::allocator<std::pair<T*, Tree*>>> index; // // CuckooTreeIndex(size_t s) : index(1 << 23) { // } // // OperationReturnStatus add(T* key, EntryMV<T>* obj) override { // Tree* newtr = (Tree*) malloc(sizeof(Tree)); // new Tree(obj); // T* keyc = key->copy(); // auto updatefn = [newtr, keyc](Tree* &oldtr) { // free(newtr); // free(keyc); // oldtr->lock.lock(); // oldtr->insert_BST(key, obj); // oldtr->lock.unlock(); // }; // return OP_SUCCESS; // } // // void del(T* obj, EntryMV<T>* emv) override { // Tree* tr; // if (index.find(obj, tr)) { // tr->lock.lock(); // tr->removeBST(obj, emv); // tr->lock.unlock(); // } // } // // OperationReturnStatus foreach(const std::function<TransactionReturnStatus()(T*)>& f, Transaction& xact) override { // return OP_SUCCESS; // } // // void prepareSize(size_t arrayS, size_t poolS) override { // } //}; // //template <typename T, typename IDX_FN1, typename IDX_FN2> //struct CuckooMinTreeIndex : public CuckooTreeIndex<T, IDX_FN1, IDX_FN2> { // typedef CuckooTreeIndex<T, IDX_FN1, IDX_FN2> Super; // typedef _Tree<T, IDX_FN2> Tree; // typedef TreeNode<T> Node; // CuckooMinTreeIndex(size_t s ): Super(s){ // // } // T* get(const T* key, Transaction& xact) const override { // Tree* tree; // if (index.find(key, tree)) { // tree->lock.lock(); // Node* cur = tree->root; // // tree->lock.unlock(); // } else // return NO_KEY; // // } //}; template <typename T, typename IDX_FN2, bool is_max> struct Heap { EntryMV<T>** array; uint arraySize; uint size; typedef EntryMV<T>* HeapElemType; Heap() { arraySize = DEFAULT_HEAP_SIZE; array = new EntryMV<T>*[arraySize]; size = 0; } // // void print() { // for (uint i = 1; i <= size; ++i) { // if ((i & (i - 1)) == 0) // std::cout << std::endl; // std::cout << array[i]->getString(4) << "\t"; // } // std::cout << std::endl; // } FORCE_INLINE EntryMV<T>* get() const { return array[1]; } FORCE_INLINE bool checkIfExists(EntryMV<T>* emv) { for (uint i = 1; i <= size; ++i) { if (array[i] == emv) return true; } return false; } FORCE_INLINE void checkHeap(int idx) { for (uint i = 1; i <= size; ++i) { uint l = 2 * i; uint r = l + 1; EntryMV<T>* x = array[i]; if (is_max) { if (l <= size) { assert(IDX_FN2::cmp(x->key, array[l]->key) == 1); if (r <= size) assert(IDX_FN2::cmp(x->key, array[r]->key) == 1); } } else { if (l <= size) { assert(IDX_FN2::cmp(x->key, array[l]->key) == -1); if (r <= size) assert(IDX_FN2::cmp(x->key, array[r]->key) == -1); } } // assert(x->backPtrs[idx] == n); } } FORCE_INLINE void double_() { uint newsize = arraySize << 1; EntryMV<T>** temp = new EntryMV<T>*[newsize]; mempcpy(temp, array, arraySize * sizeof(EntryMV<T>*)); arraySize = newsize; delete[] array; array = temp; assert(array); } FORCE_INLINE void percolateDown(uint holeInput) { uint hole = holeInput; uint child = hole << 1; EntryMV<T>* tmp = array[hole]; while (child <= size) { if (child != size && IDX_FN2::cmp(array[child + 1]->key, array[child]->key) == (is_max ? 1 : -1)) child++; if (IDX_FN2::cmp(array[child]->key, tmp->key) == (is_max ? 1 : -1)) array[hole] = array[child]; else { array[hole] = tmp; return; } hole = child; child = hole << 1; } array[hole] = tmp; } FORCE_INLINE void add(EntryMV<T>* e) { if (size == arraySize - 1) double_(); size++; uint hole = size; uint h = size >> 1; while (hole > 1 && IDX_FN2::cmp(e->key, array[h]->key) == (is_max ? 1 : -1)) { array[hole] = array[h]; hole = h; h = hole >> 1; } array[hole] = e; } //SBJ: Should only be called for a newer value that would be closer to root //In a max heap, the newer value must be greater //In a min heap, the newer value must be smaller //TOFIX: Not considering equal values FORCE_INLINE void update(EntryMV<T>* old, EntryMV<T>* nw) { assert(IDX_FN2::cmp(nw->key, old->key) == (is_max ? 1 : -1)); uint p = 1; if (array[p] != old) { p++; while (p <= size) { if (array[p] == old) break; p++; } // if (p == size + 1) // throw std::logic_error("Element not found in heap"); } uint hole = p; uint h = p >> 1; while (hole > 1 && IDX_FN2::cmp(nw->key, array[h]->key) == (is_max ? 1 : -1)) { array[hole] = array[h]; hole = h; h = hole >> 1; } array[hole] = nw; } FORCE_INLINE void remove(EntryMV<T>* e) { uint p = 1; if (array[p] != e) { p++; while (p <= size) { if (array[p] == e) break; p++; } // if (p == size + 1) // throw std::logic_error("Element not found in heap"); } while (p != 1) { uint h = p >> 1; array[p] = array[h]; p = h; } array[p] = array[size]; array[size] = nullptr; size--; if (p < size) percolateDown(p); } }; template <typename T, typename IDX_FN2> struct MedianHeap { Heap<T, IDX_FN2, true> left; Heap<T, IDX_FN2, false> right; //invariant : l.size = r.size OR l.size = r.size + 1 FORCE_INLINE void add(EntryMV<T>* obj) { if (left.size == 0) { left.add(obj); return; } assert(left.size > 0); if (IDX_FN2::cmp(obj->key, left.array[1]->key) == 1) { //obj greater than median if (right.size == left.size) { // right side will be unbalanced on adding if (IDX_FN2::cmp(obj->key, right.array[1]->key) == 1) { //obj greater than min of right EntryMV<T>* obj2 = right.array[1]; //add obj to right. move min of right to left right.array[1] = obj; right.percolateDown(1); left.add(obj2); } else { //object is new median left.add(obj); } } else { right.add(obj); } } else { //obj same or less as median if (left.size > right.size) { //left will be unbalanced on adding EntryMV<T>* obj2 = left.array[1]; left.array[1] = obj; left.percolateDown(1); right.add(obj2); } else { left.add(obj); } } } //SBJ: May not find the right element if it is median and there are duplicates of it spread across left and right FORCE_INLINE bool checkIfExists(EntryMV<T>* emv) { return left.checkIfExists(emv) || right.checkIfExists(emv); } FORCE_INLINE void remove(EntryMV<T> *obj) { if (IDX_FN2::cmp(obj->key, left.array[1]->key) == 1) { //obj in right if (left.size > right.size) { EntryMV<T> * obj2 = left.array[1]; left.remove(obj2); right.update(obj, obj2); //we are decreasing value in min-heap, safe to call update } else { right.remove(obj); } } else { //obj in left if (left.size == right.size) { EntryMV<T>* obj2 = right.array[1]; right.remove(obj2); left.update(obj, obj2); //increasing value in max-heap } else { left.remove(obj); } } } FORCE_INLINE EntryMV<T>* get() const { return left.array[1]; } FORCE_INLINE void check(int idx) { left.checkHeap(idx); right.checkHeap(idx); EntryMV<T>* r = right.array[1]; EntryMV<T>* l = left.array[1]; assert(left.size == 0 || right.size == 0 || IDX_FN2::cmp(l->key, r->key) == -1); //can be 0 too, but we want to know if there is such a case assert(left.size == right.size || left.size == right.size + 1); } }; template<typename T, typename IDX_FN1, typename IDX_FN2, typename ST_IDX> struct VersionedAggregator : public IndexMV<T> { typedef HE_<T, IDX_FN1> HE; typedef ST_IDX typeST; typedef EntryMV<T>* EntryType; struct ALIGN VersionedContainer { EntryMV<T>* aggE; Transaction* xact; volatile VersionedContainer* next; VersionedContainer(EntryMV<T>*e, Transaction* xact, volatile VersionedContainer* n) : aggE(e), xact(xact), next(n) { } }; struct ALIGN VersionedSlice { SpinLock lock; volatile VersionedContainer* head; ST_IDX sliceST; VersionedSlice() : lock(), head(nullptr), sliceST() { } FORCE_INLINE OperationReturnStatus add(Version<T>* newv) { EntryMV<T>* e = (EntryMV<T>*)newv->e; lock.lock(); sliceST.add(e); EntryMV<T>* aggE = sliceST.get(); if (head && head->xact != TStoPTR(newv->xactid) && head->xact->commitTS == initCommitTS) { lock.unlock(); return WW_VALUE; } /* This is not correct for median index. For example, if there was ab(c) de * ab(c) xde * aby(c) xde and now if we undo x, we should have ab(y) cde. However, this would still return c * Each modification should create a version in median index */ if (!head || head->aggE != aggE) { if (!head || head->xact != TStoPTR(newv->xactid)) { VersionedContainer* vc = aligned_malloc(VersionedContainer); new(vc) VersionedContainer(aggE, TStoPTR(newv->xactid), head); head = vc; } else { head->aggE = aggE; } } lock.unlock(); return OP_SUCCESS; } FORCE_INLINE OperationReturnStatus del(Version<T>* v) { EntryMV<T>* e = (EntryMV<T>*) v->e; lock.lock(); sliceST.remove(e); EntryMV<T>* aggE = sliceST.get(); if (head->xact != TStoPTR(v->xactid) && head->xact->commitTS == initCommitTS) { lock.unlock(); return WW_VALUE; } if (head->aggE != aggE) { if (head->xact != TStoPTR(v->xactid)) { VersionedContainer* vc = aligned_malloc(VersionedContainer); new(vc) VersionedContainer(aggE, TStoPTR(v->xactid), head); head = vc; } else { head->aggE = aggE; } } lock.unlock(); return OP_SUCCESS; } FORCE_INLINE void undo(Version<T>* v) { EntryMV<T>*e = (EntryMV<T>*)v->e; lock.lock(); if (v->obj.isInvalid) { //deleted version, to undo it, need to re-insert entry into index sliceST.add(e); } else if (v->oldV == nullptr) { //only version, inserted. Need to remove to undo sliceST.remove(e); } else { //assuming that normal updates are only to non-key fields, no impact here lock.unlock(); return; } // EntryMV<T>* e_new = sliceST.get(); //to be removed in final version if (head->xact == TStoPTR(v->xactid)) { head = head->next; } // assert(e_new == (head ? head->aggE : nullptr)); lock.unlock(); } FORCE_INLINE void removeEntry(EntryMV<T>* e) { //Do nothing? } FORCE_INLINE OperationReturnStatus update(Version<T>* v) { EntryMV<T>* emv = (EntryMV<T>*) v->e; lock.lock(); if (sliceST.checkIfExists(emv)) { lock.unlock(); return OP_SUCCESS; } else { return add(v); } } FORCE_INLINE EntryMV<T>* get(Transaction & xact) { volatile VersionedContainer* cur = head; while (cur && cur->xact->commitTS > xact.startTS) { cur = cur->next; } return cur ? cur->aggE : nullptr; } }; cuckoohash_map<T*, VersionedSlice*, HE, HE, std::allocator<std::pair<T*, VersionedSlice*>>> index; VersionedAggregator(size_t s) : index(1 << 23) { } FORCE_INLINE OperationReturnStatus add(Version<T>* newv) override { VersionedSlice * vsnew = aligned_malloc(VersionedSlice); new (vsnew) VersionedSlice(); VersionedContainer* vc = aligned_malloc(VersionedContainer); EntryMV<T>* e = (EntryMV<T>*)newv->e; new(vc) VersionedContainer(e, TStoPTR(newv->xactid), nullptr); e->backptrs[IndexMV<T>::idxId] = vsnew; vsnew->head = vc; vsnew->sliceST.add(e); T* keyc = newv->obj.copy(); index.upsert(keyc, [&](VersionedSlice * vsold) { free(keyc); free(vsnew); free(vc); e->backptrs[IndexMV<T>::idxId] = vsold; vsold->add(newv); }, vsnew); return OP_SUCCESS; } FORCE_INLINE void del(Version<T>* newv) override { EntryMV<T>* emv = (EntryMV<T>*) newv->e; VersionedSlice* vs = (VersionedSlice*) emv->backptrs[IndexMV<T>::idxId]; vs->del(newv); } FORCE_INLINE void removeEntry(T* obj, EntryMV<T>* emv) override { VersionedSlice* vs = (VersionedSlice*) emv->backptrs[IndexMV<T>::idxId]; vs->removeEntry(emv); } FORCE_INLINE void undo(Version<T>* v) override { EntryMV<T>* emv = (EntryMV<T>*) v->e; VersionedSlice* vs = (VersionedSlice*) emv->backptrs[IndexMV<T>::idxId]; vs->undo(v); } OperationReturnStatus foreach(FuncType f, Transaction& xact) override { return OP_SUCCESS; } FORCE_INLINE T* get_(const T* key, Transaction& xact) const { VersionedSlice * vs; if (index.find(key, vs)) { EntryMV<T>* e = vs->get(xact); Version<T>* v = e->getCorrectVersion(xact); if (!v) return nullptr; return &v->obj; } else { return nullptr; } } FORCE_INLINE T* getForUpdate_(const T* key, OperationReturnStatus& st, Transaction& xact) { VersionedSlice* result; if (index.find(key, result)) { EntryMV<T>* resE = result->get(xact); if (!resE) { st = NO_KEY; return nullptr; } Version<T>* resV = resE->versionHead; if (!resV->isVisible(&xact)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; return nullptr; } if (resV->obj.isInvalid) { st = NO_KEY; return nullptr; } Version<T> *newv = aligned_malloc(Version<T>); new(newv) Version<T>(resV, xact); if (!resE->versionHead.compare_exchange_strong(resV, newv)) { if (resV->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(resV->xactid); xact.failedBecauseOf = otherXact; } st = WW_VALUE; free(newv); return nullptr; } xact.undoBufferHead = newv; st = OP_SUCCESS; return &newv->obj; } else { st = NO_KEY; return nullptr; } } FORCE_INLINE OperationReturnStatus update(T* obj) { VersionedSlice* res; Version<T>* v = (Version<T>*)VBase::getVersionFromT((char*) obj); OperationReturnStatus ret; if (index.find(obj, res)) { ret = res->update(v); } else { ret = add(v); } assert(ret == OP_SUCCESS); return ret; } void prepareSize(size_t arrayS, size_t poolS) override { } virtual ~VersionedAggregator() { } }; template<typename T, typename IDX_FN1, typename IDX_FN2> struct MinHeapIndex : public VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, false >> { typedef VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, false >> Super; MinHeapIndex(size_t s) : Super(s) { } FORCE_INLINE T * get(const T& key, Transaction & xact) const { return get(&key, xact); } FORCE_INLINE T * get(const T* key, Transaction & xact) const override { T* ret = Super::get_(key, xact); if (ret) { // assert(ret->_4.data_); MinSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MinSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MinSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MinSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { return getForUpdate(&key, s, xact); } FORCE_INLINE T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) { T* ret = Super::getForUpdate_(key, s, xact); if (ret) { // assert(ret->_4.data_); MinSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MinSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MinSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MinSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } }; template<typename T, typename IDX_FN1, typename IDX_FN2> struct MaxHeapIndex : public VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, true >> { typedef VersionedAggregator<T, IDX_FN1, IDX_FN2, Heap<T, IDX_FN2, true >> Super; MaxHeapIndex(size_t s) : Super(s) { } FORCE_INLINE T * get(const T& key, Transaction & xact) const { return get(&key, xact); } FORCE_INLINE T * get(const T* key, Transaction & xact) const override { T* ret = Super::get_(key, xact); if (ret) { MaxSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MaxSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MaxSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MaxSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { return getForUpdate(&key, s, xact); } FORCE_INLINE T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) { T* ret = Super::getForUpdate_(key, s, xact); if (ret) { MaxSlicePred<T, IDX_FN1, IDX_FN2>* pred = (MaxSlicePred<T, IDX_FN1, IDX_FN2>*) malloc(sizeof(MaxSlicePred<T, IDX_FN1, IDX_FN2>)); new(pred) MaxSlicePred<T, IDX_FN1, IDX_FN2>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); pred->key = *ret; xact.predicateHead = pred; } return ret; } }; template<typename T, typename IDX_FN1, typename IDX_FN2> struct MedHeapIndex : public VersionedAggregator<T, IDX_FN1, IDX_FN2, MedianHeap<T, IDX_FN2>> { typedef VersionedAggregator<T, IDX_FN1, IDX_FN2, MedianHeap<T, IDX_FN2>> Super; MedHeapIndex(size_t s) : Super(s) { } FORCE_INLINE T * get(const T& key, Transaction & xact) const { return get(&key, xact); } FORCE_INLINE T * get(const T* key, Transaction & xact) const override { T* ret = Super::get_(key, xact); if (ret) { SlicePred<T, IDX_FN1>* pred = (SlicePred<T, IDX_FN1>*) malloc(sizeof(SlicePred<T, IDX_FN1>)); new(pred) SlicePred<T, IDX_FN1>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T* key, OperationReturnStatus& s, Transaction & xact) { T* ret = Super::getForUpdate_(key, s, xact); if (ret) { SlicePred<T, IDX_FN1>* pred = (SlicePred<T, IDX_FN1>*) malloc(sizeof(SlicePred<T, IDX_FN1>)); new(pred) SlicePred<T, IDX_FN1>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; } return ret; } FORCE_INLINE T * getForUpdate(const T& key, OperationReturnStatus& s, Transaction & xact) { return getForUpdate(&key, s, xact); } }; template<typename T, typename IDX_FN> struct ConcurrentCuckooSecondaryIndex : public IndexMV<T> { typedef HE_<T, IDX_FN> HE; struct ALIGN Container { EntryMV<T>* e; std::atomic<Container *> next; Container(EntryMV<T>* e) : e(e), next(nullptr) { } Container(Container *nxt) : e(nullptr), next(nxt) { } }; cuckoohash_map<T*, Container*, HE, HE, std::allocator<std::pair<T*, Container*>>> index; ConcurrentCuckooSecondaryIndex(size_t size = 100000) : index((1 << 25)) { } // Inserts an entry into the secondary index. //Uses cuckoo hashmap as backend //Inserts the entry if it does not exist already in cuckoo index, otherwise if it exists,updates it //Cuckoo points towards a sentinel to protect against concurrent insertions/deletions FORCE_INLINE OperationReturnStatus add(Version<T>* newv) override { Container *newc = aligned_malloc(Container); EntryMV<T>* obj = (EntryMV<T>*)newv->e; new(newc) Container(obj); obj->backptrs[IndexMV<T>::idxId] = newc; Container *sentinel = aligned_malloc(Container); new(sentinel) Container(newc); T* keyc = newv->obj.copy(); auto updatefn = [newc, sentinel, keyc](Container* &c) { free(sentinel); free(keyc); Container *nxt = c->next; do { newc->next = nxt; } while (!c->next.compare_exchange_weak(nxt, newc)); }; index.upsert(keyc, updatefn, sentinel); return OP_SUCCESS; //SBJ: Mem leak if update happens instead of insert for key->copy } //Marks an entry for removal from concurrent list //Will be actually removed only by a later traversal //Removes other nodes marked for removal during its traversal // Loop focus on cur. prev is before cur, curNext is afterCur. prevNext is node after prev (ideally, cur) // ..... prev -> prevNext (....) cur -> curNext ... // a node is said to be marked for removal if its next pointer is marked. //For example, to see if cur is deleted, we check isMarked(curNext) FORCE_INLINE void removeEntry(T* obj, EntryMV<T>* emv) override { Container *cur = (Container*) emv->backptrs[IndexMV<T>::idxId]; Container* nxt = cur->next; while (!cur->next.compare_exchange_weak(nxt, mark(nxt))); } //Assumption: Primary key columns do not change FORCE_INLINE OperationReturnStatus update(T* obj) { Version<T>* v = (Version<T>*) VBase::getVersionFromT((char *) obj); EntryMV<T>* emv = (EntryMV<T>*) v->e; Container* sentinel; if (index.find(obj, sentinel)) { //slice already exists, need to check if entry is already there Container *cur = sentinel->next, *curNext = cur->next, *old = sentinel, *oldNext = cur; while (isMarked(curNext) || cur->e != emv) { if (!isMarked(curNext)) { if (oldNext != cur) { old->next.compare_exchange_strong(oldNext, cur); } old = cur; cur = curNext; oldNext = curNext; } else { cur = unmark(curNext); } if (!cur) break; curNext = cur->next; } if (!cur) { //emv does not exist in slice Container *newc = aligned_malloc(Container); new(newc) Container(emv); Container *nxt = sentinel->next; do { newc->next = nxt; } while (!sentinel->next.compare_exchange_weak(nxt, newc)); } return OP_SUCCESS; } else { //new slice return add(v); } } void undo(Version<T>* v) override { //Do nothing } FORCE_INLINE void del(Version<T>* v) override { //Do nothing for secondary hash index } FORCE_INLINE OperationReturnStatus slice(const T& key, FuncType f, Transaction& xact) { return slice(&key, f, xact); } FORCE_INLINE OperationReturnStatus slice(const T* key, FuncType f, Transaction& xact) { Container *sentinel; if (index.find(key, sentinel)) { Container *prev = sentinel, *prevNext = sentinel->next, *cur = prevNext, *curNext; //SBJ: TODO: Skip all deleted nodes and remove them do { curNext = cur -> next; while (isMarked(curNext)) { cur = unmark(curNext); if (!cur) break; curNext = cur->next; } if (!cur) break; prev->next.compare_exchange_strong(prevNext, cur); Version<T>* v = cur->e->versionHead; if (!v->isVisible(&xact)) { if (v->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(v->xactid); xact.failedBecauseOf = otherXact; } return WW_VALUE; } if (v && !v->obj.isInvalid) { Version<T> * newV = aligned_malloc(Version<T>); new(newV) Version<T>(v, xact); if (!cur->e->versionHead.compare_exchange_strong(v, newV)) { if (v->xactid > initCommitTS) { Transaction* otherXact = TStoPTR(v->xactid); xact.failedBecauseOf = otherXact; } free(newV); return WW_VALUE; } xact.undoBufferHead = newV; auto st = f(&newV->obj); if (st != SUCCESS) return OR(st); } prev = cur; prevNext = curNext; cur = curNext; } while (cur); SlicePred<T, IDX_FN>* pred = (SlicePred<T, IDX_FN>*) malloc(sizeof(SlicePred<T, IDX_FN>)); new(pred) SlicePred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return OP_SUCCESS; } else { return NO_KEY; } } FORCE_INLINE OperationReturnStatus sliceNoUpdate(const T& key, FuncType f, Transaction& xact) { return sliceNoUpdate(&key, f, xact); } FORCE_INLINE OperationReturnStatus sliceNoUpdate(const T* key, FuncType f, Transaction& xact) { Container *sentinel; if (index.find(key, sentinel)) { Container *prev = sentinel, *prevNext = sentinel->next, *cur = prevNext, *curNext; //SBJ: TODO: Skip all deleted nodes and remove them do { curNext = cur -> next; while (isMarked(curNext)) { cur = unmark(curNext); if (!cur) break; curNext = cur->next; } prev->next.compare_exchange_strong(prevNext, cur); if (!cur) break; Version<T>* v = cur->e->getCorrectVersion(xact); if (v && !v->obj.isInvalid) { auto st = f(&v->obj); if (st != SUCCESS) return OR(st); } prev = cur; prevNext = curNext; cur = curNext; } while (cur); SlicePred<T, IDX_FN>* pred = (SlicePred<T, IDX_FN>*) malloc(sizeof(SlicePred<T, IDX_FN>)); new(pred) SlicePred<T, IDX_FN>(*key, xact.predicateHead, IndexMV<T>::mmapmv, col_type(-1)); xact.predicateHead = pred; return OP_SUCCESS; } else { return NO_KEY; } } OperationReturnStatus foreach(FuncType f, Transaction& xact) override { return NO_KEY; } T* get(const T* key, Transaction& xact) const override { return nullptr; } T* getForUpdate(const T* key, OperationReturnStatus& st, Transaction& xact) override { st = NO_KEY; return nullptr; } void prepareSize(size_t arrayS, size_t poolS) override { index.reserve(arrayS); } virtual ~ConcurrentCuckooSecondaryIndex() { } void getSizeStats(std::ostream & fout) { fout << "{}"; } /******************* non-virtual function wrappers ************************/ FORCE_INLINE T* get(const T& key, Transaction& xact) const { return get(&key, xact); } }; struct MBase { virtual void removeEntry(void* o, void* emv) = 0; virtual void undo(VBase* v) = 0; }; template<typename T, typename...INDEXES> class MultiHashMapMV : MBase { private: bool *modified; public: IndexMV<T>** index; MultiHashMapMV() { // by defintion index 0 is always unique if (sizeof...(INDEXES) > MAX_IDXES_PER_TBL) { cerr << "The maximum indexes per table is configured to be " << MAX_IDXES_PER_TBL << " which is less than the required indexes" << endl; } index = new IndexMV<T>*[sizeof...(INDEXES)] { new INDEXES(DEFAULT_CHUNK_SIZE)... }; modified = new bool[sizeof...(INDEXES)]; for (size_t i = 0; i<sizeof...(INDEXES); ++i) { index[i]->mmapmv = this; index[i]->idxId = i; modified[i] = false; } } MultiHashMapMV(const size_t* arrayLengths, const size_t* poolSizes) { // by defintion index 0 is always unique if (sizeof...(INDEXES) > MAX_IDXES_PER_TBL) { cerr << "The maximum indexes per table is configured to be " << MAX_IDXES_PER_TBL << " which is less than the required indexes" << endl; } index = new IndexMV<T>*[sizeof...(INDEXES)] { new INDEXES()... }; modified = new bool[sizeof...(INDEXES)]; for (size_t i = 0; i<sizeof...(INDEXES); ++i) { index[i]->mmapmv = this; index[i]->prepareSize(arrayLengths[i], poolSizes[i + 1]); index[i]->idxId = i; modified[i] = false; } } ~MultiHashMapMV() { for (size_t i = 0; i<sizeof...(INDEXES); ++i) delete index[i]; delete[] index; delete[] modified; } FORCE_INLINE T* get(const T& key, const size_t idx, Transaction& xact) const { return index[idx]->get(&key, xact); } FORCE_INLINE T* get(const T* key, const size_t idx, Transaction& xact) const { return index[idx]->get(key, xact); } // FORCE_INLINE T* getCopy(const T& key, const size_t idx = 0) const { // T* obj = index[idx]->get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE T* getCopy(const T* key, const size_t idx = 0) const { // T* obj = index[idx]->get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE T* getCopyDependent(const T* key, const size_t idx = 0) const { // T* obj = index[idx]->get(key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // // FORCE_INLINE T* getCopyDependent(const T& key, const size_t idx = 0) const { // T* obj = index[idx]->get(&key); // if (obj) { // T* ptr = obj->copy(); // tempMem.push_back(ptr); // return ptr; // } else // return nullptr; // } // FORCE_INLINE T* copyIntoPool(const T* e) { // T* copy = (T*) malloc(sizeof(T)); // new(copy) T(*e); // return copy; // } // // FORCE_INLINE T* copyIntoPool(const T& e) { // T* copy = (T*) malloc(sizeof(T)); // new(copy) T(e); // return copy; // } FORCE_INLINE OperationReturnStatus add(T& obj, Transaction& xact) { return add(&obj, xact); } FORCE_INLINE OperationReturnStatus add(T* elem, Transaction& xact) { T* cur = index[0]->get(elem); if (cur == nullptr) { Version<T>* newV = aligned_malloc(Version<T>); new(newV) Version<T>(*cur, xact); newV->xactid = PTRtoTS(xact); EntryMV<T> * newE = aligned_malloc(EntryMV<T>); new(newE) EntryMV<T>(this, *elem, newV); newV->e = newE; auto primarySt = index[0] -> add(newV); if (primarySt == OP_SUCCESS) { for (size_t i = 1; i<sizeof...(INDEXES); ++i) index[i]->add(newV); return OP_SUCCESS; } else { free(newE); free(newV); return WW_VALUE; } xact.undoBufferHead = newV; } else { return WW_VALUE; // cur->~T(); // *cur=std::move(*elem); // for (size_t i = 0; i<sizeof...(INDEXES); ++i) { // if (index[i]->hashDiffers(*cur, *elem)) { // index[i]->del(cur); // modified[i] = true; // } // } // new(cur) T(*elem); // for (size_t i = 0; i<sizeof...(INDEXES); ++i) { // if (modified[i]) { // index[i]->add(cur); // modified[i] = false; // } // } } } FORCE_INLINE OperationReturnStatus insert_nocheck(const T& elem, Transaction& xact) { return insert_nocheck(&elem, xact); } FORCE_INLINE OperationReturnStatus insert_nocheck(const T* elem, Transaction& xact) { Version<T>* newV = aligned_malloc(Version<T>); new(newV) Version<T>(*elem, xact); EntryMV<T>* newE = aligned_malloc(EntryMV<T>); new(newE) EntryMV<T>(this, *elem, newV); newV->e = newE; // newV->obj.e = newE; auto primarySt = index[0] -> add(newV); if (primarySt == OP_SUCCESS) { xact.undoBufferHead = newV; for (size_t i = 1; i<sizeof...(INDEXES); ++i) index[i]->add(newV); return OP_SUCCESS; } else { free(newE); free(newV); return WW_VALUE; } } FORCE_INLINE void removeEntry(void* o, void* e) override { T* obj = (T*) o; EntryMV<T>* emv = (EntryMV<T>*) e; for (uint i = 0; i < sizeof...(INDEXES); ++i) index[i]->removeEntry(obj, emv); } FORCE_INLINE void undo(VBase *v) override { for (uint i = 0; i < sizeof...(INDEXES); ++i) index[i]->undo((Version<T>*)v); } FORCE_INLINE void del(T* elem) { elem->isInvalid = true; Version<T>* v = (Version<T>*)VBase::getVersionFromT((char*) elem); for (uint i = 0; i < sizeof...(INDEXES); ++i) index[i]->del(v); } // FORCE_INLINE void del(T* elem) { // assume that the element is already in the map // for (size_t i = 0; i<sizeof...(INDEXES); ++i) index[i]->del(elem); // pool.del(elem); // } // // FORCE_INLINE void delCopyDependent(T* obj) { // T* elem = index[0]->get(obj); // for (size_t i = 0; i<sizeof...(INDEXES); ++i) index[i]->del(elem); // pool.del(elem); // } // // FORCE_INLINE void delCopy(T* obj) { // T* elem = index[0]->get(obj); // for (size_t i = sizeof...(INDEXES) - 1; i != 0; --i) // index[i]->delCopy(obj, index[0]); // index[0]->delCopy(obj, index[0]); // pool.del(elem); // } FORCE_INLINE OperationReturnStatus foreach(FuncType f, Transaction& xact) { return index[0]->foreach(f, xact); } // FORCE_INLINE void foreachCopy(FuncType f) { // index[0]->foreachCopy(f); // } // // void slice(int idx, const T* key, FuncType f) { // index[idx]->slice(key, f); // } // // void slice(int idx, const T& key, FuncType f) { // index[idx]->slice(&key, f); // } // void sliceCopy(int idx, const T* key, FuncType f) { // index[idx]->sliceCopy(key, f); // } // // void sliceCopy(int idx, const T& key, FuncType f) { // index[idx]->sliceCopy(&key, f); // } // // void sliceCopyDependent(int idx, const T* key, FuncType f) { // index[idx]->sliceCopy(key, f); // } // // void sliceCopyDependent(int idx, const T& key, FuncType f) { // index[idx]->sliceCopy(&key, f); // } // // FORCE_INLINE void update(T* elem) { // if (elem == nullptr) // return; // for (size_t i = 0; i < sizeof...(INDEXES); ++i) { // index[i]->update(elem); // } // } // // FORCE_INLINE void updateCopyDependent(T* obj2) { // if (obj2 == nullptr) // return; // T* elem = index[0]->get(obj2); // T* obj = copyIntoPool(obj2); // for (size_t i = 0; i < sizeof...(INDEXES); ++i) { // index[i]->updateCopyDependent(obj, elem); // } // } // // FORCE_INLINE void updateCopy(T* obj2) { // if (obj2 == nullptr) // return; // // T* obj = copyIntoPool(obj2); // //i >= 0 cant be used with unsigned type // for (size_t i = sizeof...(INDEXES) - 1; i != 0; --i) { // index[i]->updateCopy(obj, index[0]); // } // index[0]->updateCopy(obj, index[0]); // } // FORCE_INLINE size_t count() const { // return index[0]->count(); // } // // FORCE_INLINE void clear() { // for (size_t i = sizeof...(INDEXES) - 1; i != 0; --i) // index[i]->clear(); // index[0]->clear(); // } // template<class Archive> // void serialize(Archive& ar, const unsigned int version) const { // ar << "\n\t\t"; // dbtoaster::serialize_nvp(ar, "count", count()); // //SBJ: Hack! fix it! Cannot use store.foreach directly , as the last index may not be ListIndex created // auto idx = const_cast<Index<T, V> *> (index[0]); // idx->foreach([&ar] (T * e) { // ar << "\n"; dbtoaster::serialize_nvp_tabbed(ar, "item", *e, "\t\t"); }); // } }; #endif //MMAP_H
33.367799
148
0.482573
[ "object", "vector" ]
932f75744ce2891df51912fa70d5e79ce7a02279
4,044
cpp
C++
libteseo.device/src/AbstractDevice.cpp
STMicroelectronics/STADG_Teseo_Android_HAL
8822808d5a3ddebe4267fa94d62dc099c1173120
[ "Apache-2.0" ]
10
2018-07-14T23:50:07.000Z
2021-08-28T10:41:52.000Z
libteseo.device/src/AbstractDevice.cpp
STMicroelectronics/STADG_Teseo_Android_HAL
8822808d5a3ddebe4267fa94d62dc099c1173120
[ "Apache-2.0" ]
null
null
null
libteseo.device/src/AbstractDevice.cpp
STMicroelectronics/STADG_Teseo_Android_HAL
8822808d5a3ddebe4267fa94d62dc099c1173120
[ "Apache-2.0" ]
7
2019-07-31T13:56:55.000Z
2021-08-12T09:09:34.000Z
/* * This file is part of Teseo Android HAL * * Copyright (c) 2016-2017, STMicroelectronics - All Rights Reserved * Author(s): Baudouin Feildel <baudouin.feildel@st.com> for STMicroelectronics. * * License terms: Apache 2.0. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * @file AbstractDevice.cpp * @author Baudouin Feildel <baudouin.feildel@st.com> * @copyright 2016, STMicroelectronics, All rights reserved. */ #include <teseo/device/AbstractDevice.h> #define LOG_TAG "teseo_hal_AbstractDevice" #include <cutils/log.h> #include <time.h> #include <teseo/utils/Wakelock.h> #include <teseo/model/NmeaMessage.h> #include <teseo/model/Message.h> using namespace stm::model; namespace stm { namespace device { const ByteVector AbstractDevice::nmeaSequenceStart {'G', 'G', 'A'}; AbstractDevice::AbstractDevice() { } void AbstractDevice::init() { statusUpdate(GPS_STATUS_NONE); } void AbstractDevice::setLocation(const Location & loc) { location.set(loc); } void AbstractDevice::addSatellite(const SatInfo & sat) { if(!satellites) satellites.set(std::map<SatIdentifier, SatInfo>()); auto & sats = *satellites; sats[sat.getId()] = sat; } void AbstractDevice::clearSatelliteList() { satellites->clear(); satellites.invalidate(); } Result<GpsUtcTime, ValueStatus> AbstractDevice::getTimestamp() const { if(this->timestamp) return *timestamp; return timestamp.getStatus(); } Result<Location, ValueStatus> AbstractDevice::getLocation() const { if(this->location) return *location; return location.getStatus(); } Result<SatInfo, ValueStatus> AbstractDevice::getSatellite(const SatIdentifier & id) const { if(!satellites) return ValueStatus::NOT_AVAILABLE; auto & sats = *satellites; auto it = sats.find(id); if(it != sats.end()) { return it->second; } else { return ValueStatus::NOT_AVAILABLE; } } void AbstractDevice::update() { // Update location only if it is valid if(location->locationValidity()) locationUpdate(location); // Trigger satellite list update satelliteListUpdate(this->satellites); } void AbstractDevice::updateIfStartSentenceId(const ByteVector & sentenceId) { if(sentenceId == nmeaSequenceStart) { // Trigger updates update(); // Clear data before starting new sequence this->clearSatelliteList(); } } int AbstractDevice::start() { ALOGI("Start navigation"); // Acquire wakelock, request UTC time and update status utils::Wakelock::acquire(); requestUtcTime(); statusUpdate(GPS_STATUS_SESSION_BEGIN); // Start the navigation startNavigation(); return 0; } int AbstractDevice::stop() { ALOGI("Stop navigation"); // Stop the navigation stopNavigation(); // Release wakelock and update status utils::Wakelock::release(); statusUpdate(GPS_STATUS_SESSION_END); return 0; } void AbstractDevice::setTimestamp(GpsUtcTime t) { timestamp = t; location->timestamp(t); } void AbstractDevice::emitNmea(const NmeaMessage & nmea) { onNmea(timestamp, nmea); } Result<Version, ValueStatus> AbstractDevice::getProductVersion(const std::string & productName) const { if(versions->size() == 0) return ValueStatus::NOT_AVAILABLE; if(versions->count(productName) == 0) return ValueStatus::NOT_AVAILABLE; return versions->at(productName); } void AbstractDevice::newVersionNumber(const model::Version & version) { (*versions)[version.getProduct()] = version; onVersionNumber(version); } void AbstractDevice::sendMessageRequest(const model::Message & message) { sendMessage(*this, message); } } // namespace device } // namespace stm
20.953368
89
0.739862
[ "model" ]
9336aec5d12115afb0095ce377dfbe7bcdec134f
13,917
cpp
C++
experiments/PolicyManager_c++_jni/crypto/crypto.cpp
hansmy/Webinos-Platform
43950daebc41cd985adba4efc5670b61336aca7f
[ "Apache-2.0" ]
1
2015-08-06T20:08:14.000Z
2015-08-06T20:08:14.000Z
experiments/PolicyManager_c++_jni/crypto/crypto.cpp
krishnabangalore/Webinos-Platform
2ab4779112483a0213ae440118b1c2a3cf80c7bd
[ "Apache-2.0" ]
null
null
null
experiments/PolicyManager_c++_jni/crypto/crypto.cpp
krishnabangalore/Webinos-Platform
2ab4779112483a0213ae440118b1c2a3cf80c7bd
[ "Apache-2.0" ]
null
null
null
/* ==================================================================== * Copyright (c) 2000 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * This product includes software written by Dr Stephen N Henson * (steve@openssl.org) for the OpenSSLproject 2000. */ /* * If XXXXXlen is <=0 then XXXXX is the file that contains the resource (eg. a certificate), * else XXXXX is directly the resource (eg. the certificate) */ #include "crypto.h" #include "debug.h" string hex2str(unsigned long hexnum) { string hexstr = ""; int index; char conv[] = {'0','1','2','3','4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; while (hexnum) { index = hexnum & 0xF; hexnum = hexnum >> 4; hexstr = conv[index] + hexstr; } return hexstr; } bool compareHashes(const char* paddedhash, int paddedhashlen, const char* hash, int hashlen) { return !memcmp((paddedhash + paddedhashlen - hashlen), hash, hashlen); } int X509_PEM_decorator(const char * cert, int certlen, char* output) { char* tmp = output; memcpy(tmp, "-----BEGIN CERTIFICATE-----\x0d\x0a", 29); tmp+=29; memcpy(tmp, cert, certlen); tmp+=certlen; memcpy(tmp, "\x0d\x0a-----END CERTIFICATE-----",27); return certlen + 56; } string getCertField(string str) { int index; if ( (index = str.find("/CN")) != string::npos ) { int start = index + 4; int findpos = str.find("/", start); int len = findpos != string::npos ? findpos - start: str.length() - start; return str.substr(start, len); } else return ""; } //int X509_info(char *cert, int certlen) vector<string> X509_info(char *cert, int certlen) { vector<string> certInfo; X509 *x; X509_NAME * subjectname; X509_NAME * issuername; BIO *certificate = NULL; if (certlen > 0) { certificate = BIO_new(BIO_s_mem()); BIO_write(certificate, (unsigned char *)cert, certlen); } else { certificate = BIO_new(BIO_s_file()); BIO_read_filename(certificate, cert); } x = PEM_read_bio_X509_AUX(certificate, NULL, NULL, NULL); if(x) { subjectname = X509_get_subject_name(x); issuername = X509_get_issuer_name(x); int index,start,findpos,len; string tmp; tmp = X509_NAME_oneline(subjectname, 0, 0); LOG("Crypto : " << tmp.data()); if ( (index = tmp.find("/CN")) != string::npos ) { start = index + 4; findpos = tmp.find("/", start); len = findpos != string::npos ? findpos - start: tmp.length() - start; certInfo.push_back(tmp.substr(start, len)); } else certInfo.push_back("empty_cn1"); certInfo.push_back(hex2str(X509_subject_name_hash(x))); tmp = X509_NAME_oneline(issuername, 0, 0); if ( (index = tmp.find("/CN")) != string::npos ) { start = index + 4; findpos = tmp.find("/", start); len = findpos != string::npos ? findpos - start: tmp.length() - start; certInfo.push_back(tmp.substr(start, len)); } else certInfo.push_back("empty_cn2"); certInfo.push_back(hex2str(X509_issuer_name_hash(x))); // Issuer fingerprint } return certInfo; } int sha1(const char *in, int len, char *dgst) { static const int sha1_len = 20; unsigned char out[sha1_len]; // static const char *hex_digits = "0123456789abcdef"; // hex value // int i; // hex value SHA_CTX ctx; SHA1_Init(&ctx); if (len <= 0) { len = 0; int fd = open(in,O_RDONLY); char buf[BUFLEN]; while ((len = read(fd,buf,BUFLEN)) > 0) { SHA1_Update(&ctx, (unsigned char*)buf, len); } close(fd); } else SHA1_Update(&ctx, (unsigned char*)in, len); SHA1_Final(&(out[0]),&ctx); //bytes /* hex value for (i = 0; i < sha1_len; i++) { buf[2*i] = hex_digits[(out[i] & 0xf0) >> 4]; buf[2*i+1] = hex_digits[out[i] & 0x0f]; } //*/ memcpy(dgst, out, sha1_len); return sha1_len; } int sha256(const char *in, int len, char *dgst) { static const int sha256_len = 32; unsigned char out[sha256_len]; SHA256_CTX ctx256; SHA256_Init(&ctx256); if (len <= 0) { len = 0; int fd = open(in,O_RDONLY); char buf[BUFLEN]; while ((len = read(fd,buf,BUFLEN)) > 0) { SHA256_Update(&ctx256, (unsigned char*)buf, len); } close(fd); } else SHA256_Update(&ctx256, (unsigned char*)in, len); SHA256_Final(&(out[0]),&ctx256); // bytes // SHA256_End(&ctx256,buf); // hex value memcpy(dgst, out, sha256_len); return sha256_len; } int toBase64 (unsigned char* input, int inputlen, char* output) { static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int i,j=0; for (i=0; i<inputlen; i+=3) { output[j++] = table[ input[i] >> 2 ]; output[j++] = table[((input[i] & 3)<< 4) + (input[i+1] >> 4)]; output[j++] = table[((input[i+1] & 15) << 2) + (input[i+2] >> 6)]; output[j++] = table[ input[i+2] & 63]; } if(inputlen%3 > 0) { output[j-1] = '='; output[j-2] = table[((input[i-2] & 15) << 2)]; } if(inputlen%3 == 1) { output[j-2] = '='; output[j++] = table[((input[i-3] & 3)<< 4)]; } return j; } unsigned char b64conv(char chr) { if (chr == 43) return 62; else if (chr == 47) return 63; else if (chr >= 97) return chr - 71; else if (chr >= 65) return chr - 65; else return chr + 4; } int fromBase64 (unsigned char* input, int inputlen, char* output) { const int outputlen = BUFLEN; unsigned char in0, in1, in2, in3; int i,j=0; for (i=0; i<inputlen; i+=4) { in0 = b64conv(input[i]); in1 = b64conv(input[i+1]); in2 = b64conv(input[i+2]); in3 = b64conv(input[i+3]); output[j++] = (in0 << 2) + (in1 >> 4); output[j++] = ((in1 & 15) << 4) + (in2 >> 2); output[j++] = ((in2 & 3) << 6) + in3; } if (input[i-2] == '=') return j-2; else if (input[i-1] == '=') return j-1; else return j; } EVP_PKEY * load_key(const char* inkey, int keylen, char keytype) { BIO * key; X509 * x509; EVP_PKEY * pkey = NULL; if (keylen > 0) { key = BIO_new(BIO_s_mem()); BIO_write(key, (unsigned char *)inkey, keylen); } else { key = BIO_new(BIO_s_file()); if(BIO_read_filename(key, inkey) <= 0) return NULL; } switch(keytype) { case KEY_PUBKEY: pkey = PEM_read_bio_PUBKEY(key,NULL,NULL, NULL); break; case KEY_PRIVKEY: pkey = PEM_read_bio_PrivateKey(key,NULL,NULL, NULL); break; case KEY_CERT: x509 = PEM_read_bio_X509_AUX(key, NULL, NULL, NULL); if(x509) { pkey = X509_get_pubkey(x509); X509_free(x509); } else return NULL; break; } return pkey; } int dsa_sign(const char* inkey, int keylen, char keytype, const char* data, int datalen, char* signature, const char* signaturefile) { int err; unsigned int sig_len = 0; unsigned char sig_buf [BUFLEN]; int inputdatalen = datalen; char * inputdata[BUFLEN]; const EVP_MD * md = EVP_dss1(); EVP_MD_CTX md_ctx; EVP_PKEY * pkey = load_key(inkey, keylen, keytype); if (!pkey) return -1; EVP_SignInit(&md_ctx, md); if (inputdatalen == 0) { int fd = open(data, O_RDONLY); inputdatalen = read(fd, inputdata, BUFLEN); EVP_SignUpdate (&md_ctx, inputdata, inputdatalen); } else EVP_SignUpdate (&md_ctx, data, datalen); sig_len = sizeof(sig_buf); err = EVP_SignFinal (&md_ctx, sig_buf, &sig_len, pkey); EVP_PKEY_free (pkey); if (err != 1) return -2; if (signaturefile) { BIO *out; if(!(out = BIO_new_file(signaturefile, "wb"))) return -3; BIO_write(out, sig_buf, sig_len); BIO_free_all(out); } if (signature) memcpy(signature, sig_buf, sig_len); return sig_len; } int dsa_verify(const char* inkey, int keylen, char keytype, const char* signature, int signaturelen, const char* data, int datalen) { int err; int inputdatalen = datalen; char * inputdata[BUFLEN]; int signaturedatalen = signaturelen; char * signaturedata[BUFLEN]; const EVP_MD * md = EVP_dss1(); EVP_MD_CTX md_ctx; EVP_PKEY * pkey = load_key(inkey, keylen, keytype); if (!pkey) return -1; EVP_VerifyInit (&md_ctx, md); if (inputdatalen == 0) { int fd = open(data,O_RDONLY); inputdatalen = read(fd, inputdata, BUFLEN); EVP_VerifyUpdate (&md_ctx, inputdata, inputdatalen); } else EVP_VerifyUpdate (&md_ctx, data, datalen); if (signaturedatalen == 0) { int fd = open(signature,O_RDONLY); signaturedatalen = read(fd, signaturedata, BUFLEN); err = EVP_VerifyFinal (&md_ctx, (unsigned char*)signaturedata, signaturedatalen, pkey); } else err = EVP_VerifyFinal (&md_ctx, (unsigned char*)signature, signaturelen, pkey); EVP_PKEY_free (pkey); if (err != 1) return -2; return 0; } int rsa_sign(const char* inkey, int keylen, char keytype, const char* data, int datalen, char* signature, const char* signaturefile) { BIO *in = NULL; BIO *out = NULL; // line requested for the "write to file" feature EVP_PKEY * pkey = load_key(inkey, keylen, keytype); RSA *rsa = NULL; unsigned char *rsa_in = NULL, *rsa_out = NULL, pad = RSA_PKCS1_PADDING;//RSA_NO_PADDING; int rsa_inlen, rsa_outlen = 0; int keysize; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); if (!pkey) return -1; rsa = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); if(!rsa) return -2; if (datalen > 0) { in = BIO_new(BIO_s_mem()); BIO_write(in, (unsigned char *)data, datalen); } else { if(!(in = BIO_new_file(data, "rb"))) return -3; } //* // line requested for the "write to file" feature if (signaturefile) if(!(out = BIO_new_file(signaturefile, "wb"))) return -4; //*/ keysize = RSA_size(rsa); rsa_in = (unsigned char*)OPENSSL_malloc(keysize * 2); rsa_out = (unsigned char*)OPENSSL_malloc(keysize); rsa_inlen = BIO_read(in, rsa_in, keysize * 2); if(rsa_inlen <= 0) return -5; rsa_outlen = RSA_private_encrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad); if(rsa_outlen <= 0) return -6; if (signaturefile) BIO_write(out, rsa_out, rsa_outlen); // line requested for the "write to file" feature if (signature) memcpy(signature, rsa_out, rsa_outlen); RSA_free(rsa); BIO_free(in); BIO_free_all(out); // line requested for the "write to file" feature if(rsa_in) OPENSSL_free(rsa_in); if(rsa_out) OPENSSL_free(rsa_out); return rsa_outlen; } int rsa_verify(const char* inkey, int keylen, char keytype, const char* signature, int signaturelen, const char* data, int datalen) { BIO *in = NULL; EVP_PKEY * pkey = load_key(inkey, keylen, keytype); RSA *rsa = NULL; unsigned char *rsa_in = NULL, *rsa_out = NULL, pad = RSA_PKCS1_PADDING;//RSA_NO_PADDING; int rsa_inlen, rsa_outlen = 0; int keysize; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); if (!pkey) return -1; rsa = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); if(!rsa) return -2; if (signaturelen > 0) { in = BIO_new(BIO_s_mem()); BIO_write(in, (unsigned char *)signature, signaturelen); } else { if(!(in = BIO_new_file(signature, "rb"))) return -3; } keysize = RSA_size(rsa); rsa_in = (unsigned char*)OPENSSL_malloc(keysize * 2); rsa_out = (unsigned char*)OPENSSL_malloc(keysize); rsa_inlen = BIO_read(in, rsa_in, keysize * 2); if(rsa_inlen <= 0) return -5; rsa_outlen = RSA_public_decrypt(rsa_inlen, rsa_in, rsa_out, rsa, pad); if(rsa_outlen <= 0) return -6; RSA_free(rsa); BIO_free(in); if(rsa_in) OPENSSL_free(rsa_in); if (rsa_outlen > 0) return (compareHashes((char *)rsa_out, rsa_outlen, data, datalen) ? 0 :-7); return -8; }
25.030576
132
0.649781
[ "vector" ]
934024f6f4aa52f58e3f198dc55171ca03e418f5
61,808
cc
C++
GraphLib/treealgs/tree_dynamics.cc
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
1
2020-09-03T07:23:11.000Z
2020-09-03T07:23:11.000Z
GraphLib/treealgs/tree_dynamics.cc
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
null
null
null
GraphLib/treealgs/tree_dynamics.cc
intact-software-systems/cpp-software-patterns
e463fc7eeba4946b365b5f0b2eecf3da0f4c895b
[ "MIT" ]
null
null
null
/*************************************************************************** tree_dynamics.cc - description ------------------- begin : Wed Apr 26 2006 copyright : (C) 2005 by Knut-Helge Vik email : knuthelv@ifi.uio.no ***************************************************************************/ #include <fstream> #include "tree_dynamics.h" #include "prim_mst.h" #include "../simdefs.h" #include "../graphalgs/coreh.h" #include "../graphalgs/complete_graph.h" #include "../graphalgs/graphalgs.h" #include "../simtime.h" #include <cstdlib> #include <math.h> #include <cmath> using namespace std; using namespace boost; using namespace TreeAlgorithms; using namespace GraphAlgorithms; /*----------------------------------------------------------------------- class TreeDynamics(): addVertex -> class InsertDynamics removeVertex -> class RemoveDynamics ------------------------------------------------------------------------- */ //void TreeDynamics::insertVertex() { abort(); } //void TreeDynamics::removeVertex() { abort(); } /*----------------------------------------------------------------------- class TreeDynamics(): help functions for class insertDynamics(), and class removeDynamics() ------------------------------------------------------------------------- */ clock_t TreeDynamics::subTree(TreeStructure &groupT, TreeStructure &subT, VertexSet& steinerSet) { int core = GraphAlgorithms::findBestLocatedMemberNode(subT); ASSERTING(core > -1); TreeStructure new_subT; clock_t exec_time = TreeAlgorithms::buildTree(subT, new_subT, GlobalSimArgs::getSimTreeAlgo(), core); groupT.mergeTrees(new_subT); // merge trees groupT.removeUnusedVertices(); // remove unused steiner points // -- debug -- //cerr << WRITE_FUNCTION << endl; //dumpTreeStructure(new_subT); // -- debug end -- return exec_time; } /*----------------------------------------------------------------------- connectNeighbors: ------------------------------------------------------------------------- */ void TreeDynamics::connectMCE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV) { int degInc = 0, avInc = 2; int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeWeight = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= (getDegreeConstraint(globalG_, *vit) + degInc)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); edge_descriptorN e = ep.first; double tempMinWeight = globalG_[ep.first].weight; int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) - avInc; if(minEdgeWeight > tempMinWeight && od > 0) { minEdgeWeight = tempMinWeight; connE = e; connV = targ; mitV = mit; } } } // -- fail safe -- if(connV < 0) { // connectdV filled up out-degree (shouldn't happen), available out degree < 0 if(getAvOutDegree(globalG_, groupT, connectedV) < 0 || avInc < 0) degInc++; avInc--; if(degInc >= (numeric_limits<double>::max)()) break; cerr << "fail safe -> connV < 0, avInc " << avInc << " degInc " << degInc << endl; //char c = getchar(); } // -- end fail safe -- else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); // calculate available out degree avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); // cerr << "Available out degree " << avOutDegConnected << endl; } } } void TreeDynamics::connectSearchMCE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV) { int degInc = 0, avInc = 2; int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeWeight = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit) + degInc) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) - avInc; if(od > 0) { edge_descriptorN e = ep.first; double tempMinWeight = globalG_[ep.first].weight; findMCEdge(*vit, targ, targ, groupT.g, e, tempMinWeight); if(minEdgeWeight > tempMinWeight) { minEdgeWeight = tempMinWeight; connE = e; connV = targ; mitV = mit; } } } } // -- fail safe -- if(connV < 0) { // connectdV filled up out-degree (shouldn't happen), available out degree < 0 if(getAvOutDegree(globalG_, groupT, connectedV) < 0 || avInc < 0) degInc++; avInc--; if(degInc >= (numeric_limits<double>::max)()) break; cerr << "fail safe -> connV < 0, avInc " << avInc << " degInc " << degInc << endl; //char c = getchar(); } // -- end fail safe -- else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); // calculate available out degree avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); // cerr << "Available out degree " << avOutDegConnected << endl; } } } // NEW CONNECT: void TreeDynamics::connectMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV) { int degInc = 0; while(adjacentMap.size() > 1) { int src_conn = -1, targ_conn = -1; edge_descriptorN connE; double min_current_diameter = (numeric_limits<double>::max)(); double min_src_eccentricity = (numeric_limits<double>::max)(), min_targ_eccentricity = (numeric_limits<double>::max)(); OutDegreeMap::iterator mit_src, mit_targ; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { int src = mit->second; if(getOutDegree(src, groupT.g) >= (getDegreeConstraint(globalG_, src) + degInc)) continue; double src_eccentricity = 0; if(getOutDegree(src, groupT.g) > 0) worstCaseDist(src, src, src, groupT, src_eccentricity); for(OutDegreeMap::iterator mit_in = adjacentMap.begin(), mit_in_end = adjacentMap.end(); mit_in != mit_in_end; ++mit_in) { int targ = mit_in->second; if(src == targ) continue; if(getOutDegree(targ, groupT.g) >= (getDegreeConstraint(globalG_, targ) + degInc)) continue; double target_eccentricity = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseDist(targ, targ, targ, groupT, target_eccentricity); pair<edge_descriptorN, bool> ep = edge(src, targ, globalG_); ASSERTING(ep.second); double new_src_eccentricity = max(src_eccentricity, globalG_[ep.first].weight + target_eccentricity); double new_target_eccentricity = max(target_eccentricity, globalG_[ep.first].weight + src_eccentricity); edge_descriptorN e = ep.first; //findMDEdge(src, src_eccentricity, targ, targ, groupT.g, e, new_src_eccentricity); if(min_current_diameter > new_src_eccentricity) { min_current_diameter = new_src_eccentricity; targ_conn = targ; src_conn = src; mit_targ = mit_in; mit_src = mit; min_src_eccentricity = new_src_eccentricity; min_targ_eccentricity = new_target_eccentricity; // -- debug -- //int targ = target(connE, globalG_), src = source(connE,globalG_); //if(targ != src) targ = src; //cerr << WRITE_FUNCTION << " found edge : " << connE << " current diameter " << new_src_eccentricity << endl; //char c = getchar(); // -- end debug -- } } } // -- fail safe -- if(targ_conn < 0) { degInc++; if(degInc >= (numeric_limits<double>::max)()) break; //cerr << "fail safe -> targ_conn < 0, degInc " << degInc << endl; } // -- end fail safe -- else { groupT.insertEdge(src_conn, targ_conn, globalG_); adjacentMap.erase(mit_targ); //cerr << WRITE_FUNCTION << " CONNECTED: (" << src_conn << "," << targ_conn << ")" << " current diameter " << min_current_diameter << endl; } } } // NEW CONNECT: void TreeDynamics::connectSearchMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV) { int degInc = 0; while(adjacentMap.size() > 1) { int src_conn = -1, targ_conn = -1; edge_descriptorN connE; double min_current_diameter = (numeric_limits<double>::max)(); double min_src_eccentricity = (numeric_limits<double>::max)(), min_targ_eccentricity = (numeric_limits<double>::max)(); OutDegreeMap::iterator mit_src, mit_targ; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { int src = mit->second; if(getOutDegree(src, groupT.g) >= (getDegreeConstraint(globalG_, src) + degInc)) continue; double src_eccentricity = 0; if(getOutDegree(src, groupT.g) > 0) worstCaseDist(src, src, src, groupT, src_eccentricity); for(OutDegreeMap::iterator mit_in = adjacentMap.begin(), mit_in_end = adjacentMap.end(); mit_in != mit_in_end; ++mit_in) { int targ = mit_in->second; if(src == targ) continue; if(getOutDegree(targ, groupT.g) >= (getDegreeConstraint(globalG_, targ) + degInc)) continue; double target_eccentricity = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseDist(targ, targ, targ, groupT, target_eccentricity); pair<edge_descriptorN, bool> ep = edge(src, targ, globalG_); ASSERTING(ep.second); double new_src_eccentricity = max(src_eccentricity, globalG_[ep.first].weight + target_eccentricity); double new_target_eccentricity = max(target_eccentricity, globalG_[ep.first].weight + src_eccentricity); edge_descriptorN e = ep.first; findMDEdge(src, src_eccentricity, targ, targ, groupT.g, e, new_src_eccentricity); if(min_current_diameter > new_src_eccentricity) { min_current_diameter = new_src_eccentricity; targ_conn = targ; src_conn = src; mit_targ = mit_in; mit_src = mit; min_src_eccentricity = new_src_eccentricity; min_targ_eccentricity = new_target_eccentricity; // -- debug -- //int targ = target(connE, globalG_), src = source(connE,globalG_); //if(targ != src) targ = src; //cerr << WRITE_FUNCTION << " found edge : " << connE << " current diameter " << new_src_eccentricity << endl; //char c = getchar(); // -- end debug -- } } } // -- fail safe -- if(targ_conn < 0) { degInc++; if(degInc >= (numeric_limits<double>::max)()) break; //cerr << "fail safe -> targ_conn < 0, degInc " << degInc << endl; } // -- end fail safe -- else { groupT.insertEdge(src_conn, targ_conn, globalG_); adjacentMap.erase(mit_targ); //cerr << WRITE_FUNCTION << " CONNECTED: (" << src_conn << "," << targ_conn << ")" << " current diameter " << min_current_diameter << endl; } } } /*----------------------------------------------------------------------- Connect vertices using delay constrained MCEs ------------------------------------------------------------------------- */ void TreeDynamics::connectDCMCE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= (getDegreeConstraint(globalG_, *vit))) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); edge_descriptorN e = ep.first; double tempMinWeight = distance[*vit] + globalG_[ep.first].weight; double tempMinCost = globalG_[ep.first].cost; int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; if(minEdgeCost > tempMinCost && tempMinWeight <= GlobalSimArgs::getDelayConstraint() && od > 0) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; } } } if(connV < 0) { //cerr << " trying connectMCE " << endl; connectMCE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } void TreeDynamics::connectDCMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; double tempMinWeight = distance[*vit] + globalG_[ep.first].weight; if(od <= 0 || tempMinWeight > GlobalSimArgs::getDelayConstraint()) continue; double worstcase_cost = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseCost(targ, targ, targ, groupT.g, worstcase_cost); edge_descriptorN e = ep.first; double tempMinCost = globalG_[ep.first].cost + worstcase_cost; if(minEdgeCost > tempMinCost) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; } } } if(connV < 0) { connectMDE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } void TreeDynamics::connectDCSearchMCE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; if(od <= 0) continue; edge_descriptorN e; double tempMinCost = (numeric_limits<double>::max)(); double tempMinWeight = distance[*vit] + globalG_[ep.first].weight; if(tempMinWeight <= GlobalSimArgs::getDelayConstraint()) { tempMinCost = globalG_[ep.first].cost; e = ep.first; } findMCEdgeC(*vit, targ, targ, groupT.g, e, tempMinCost, distance); if(minEdgeCost > tempMinCost) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; } } } if(connV < 0) { connectSearchMCE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } void TreeDynamics::connectDCSearchMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; if(od <= 0) continue; double tempMinCost = (numeric_limits<double>::max)(); edge_descriptorN e = ep.first; double tempMinWeight = distance[*vit] + globalG_[ep.first].weight; if(tempMinWeight <= GlobalSimArgs::getDelayConstraint()) { double worstcase_dist = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseCost(targ, targ, targ, groupT.g, worstcase_dist); tempMinCost = globalG_[ep.first].cost + worstcase_dist; e = ep.first; } findMDEdgeC(*vit, targ, targ, groupT.g, e, tempMinCost, distance); if(minEdgeCost > tempMinCost) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; } } } if(connV < 0) { connectSearchMDE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } /*----------------------------------------------------------------------- Connect vertices using diameter bounded MCEs ------------------------------------------------------------------------- */ void TreeDynamics::connectBDMCE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance, const double &diameterBound) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= (getDegreeConstraint(globalG_, *vit))) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); edge_descriptorN e = ep.first; double diameter = distance[*vit] + globalG_[ep.first].weight; double tempMinCost = globalG_[ep.first].weight; int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; if(minEdgeCost > tempMinCost && diameter <= diameterBound && od > 0) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; // -- debug -- //int targ = target(connE, globalG_), src = source(connE,globalG_); //if(targ != *vit) targ = src; //double diameter = distance[targ] + globalG_[e].weight; //cerr << WRITE_FUNCTION << " found edge : " << connE << " diameter : " << diameter << endl; //char c = getchar(); //ASSERTING(diameter <= diameterBound); // -- end debug -- } } } if(connV < 0) { //cerr << " trying connectMCE " << endl; connectMDE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } void TreeDynamics::connectBDMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance, const double &diameterBound) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; double diameter = distance[*vit] + globalG_[ep.first].weight; // tempMinWeight if(od <= 0 || diameter > diameterBound) continue; double worstcase_cost = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseDist(targ, targ, targ, groupT, worstcase_cost); edge_descriptorN e = ep.first; double tempMinCost = globalG_[ep.first].weight + worstcase_cost; if(minEdgeCost > tempMinCost) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; } } } if(connV < 0) { connectMDE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } void TreeDynamics::connectBDSearchMCE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance, const double &diameterBound) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; if(od <= 0) continue; edge_descriptorN e; double tempMinCost = (numeric_limits<double>::max)(); double diameter = distance[*vit] + globalG_[ep.first].weight; if(diameter <= diameterBound) { tempMinCost = globalG_[ep.first].weight; e = ep.first; } findMCEdgeBD(*vit, targ, targ, groupT.g, e, tempMinCost, distance, diameterBound); if(minEdgeCost > tempMinCost) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; // -- debug -- //int targ = target(connE, globalG_), src = source(connE,globalG_); //if(targ != *vit) targ = src; //double diameter = distance[targ] + globalG_[e].weight; //cerr << WRITE_FUNCTION << " found edge : " << connE << " diameter : " << diameter << endl; //char c = getchar(); //ASSERTING(diameter <= diameterBound); // -- end debug -- } } } if(connV < 0) { //cerr << " Couldn't connect! Connectingin connectSearchMDE " << endl; connectSearchMDE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } void TreeDynamics::connectBDSearchMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV, const DistanceVector &distance, const double &diameterBound) { int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double minEdgeCost = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT.g) >= getDegreeConstraint(globalG_, *vit)) continue; for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(*vit, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) ; if(od <= 0) continue; double tempMinCost = (numeric_limits<double>::max)(); edge_descriptorN e = ep.first; double diameter = distance[*vit] + globalG_[ep.first].weight; if(diameter <= diameterBound) { double worstcase_dist = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseDist(targ, targ, targ, groupT, worstcase_dist); tempMinCost = globalG_[ep.first].weight + worstcase_dist; e = ep.first; } findMDEdgeBD(*vit, targ, targ, groupT.g, e, tempMinCost, distance, diameterBound); if(minEdgeCost > tempMinCost) { minEdgeCost = tempMinCost; connE = e; connV = targ; mitV = mit; } } } if(connV < 0) { connectSearchMDE(groupT, adjacentMap, connectedV); break; } else { ASSERTING(connV > -1); groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } /*----------------------------------------------------------------------- various functions ------------------------------------------------------------------------- */ void TreeDynamics::getNeighborsOptimizeSP(const TreeStructure &groupT, vertex_descriptorN src, vertex_descriptorN prev, VertexSet &adjacentSet, VertexSet &adjacentSetSP, EdgeList &remEdges) { //if(adjacentSet.contains(src) || adjacentSetSP.contains(src)) return; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(src, groupT.g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, groupT.g); if(adjacentSet.contains(targ) || adjacentSetSP.contains(targ)) continue; if(targ != prev) { remEdges.push_back(*oit); //cerr << *oit << ", "; if(groupT.g[targ].vertexState == GROUP_MEMBER) adjacentSet.insert(targ); if(groupT.g[targ].vertexState == STEINER_POINT) { adjacentSetSP.insert(targ); getNeighborsOptimizeSP(groupT, targ, src, adjacentSet, adjacentSetSP, remEdges); } } } } void TreeDynamics::getNeighbors(const TreeStructure &groupT, vertex_descriptorN src, VertexSet &adjacentSet) { //cerr << WRITE_FUNCTION << " " << src << " neighbors " ; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(src, groupT.g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, groupT.g); adjacentSet.insert(targ); //cerr << targ << " " ; } //cerr << endl; } void TreeDynamics::getNeighbors(const TreeStructure &groupT, vertex_descriptorN src, VertexSet &adjacentSet, OutDegreeMap &adjacentMap) { //cerr << WRITE_FUNCTION << " " << src << " neighbors " ; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(src, groupT.g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, groupT.g); int avOD = getAvOutDegree(globalG_, groupT, targ) + 1; adjacentMap.insert(pair<int, vertex_descriptorN>(avOD,targ)); adjacentSet.insert(targ); //cerr << targ << " " ; } //cerr << endl; } /* void TreeDynamics::subGraphRingSP(SimVertexMap& subVertices, VertexSet& steinerSet, vertex_descriptorN actVert, vertex_descriptorN src, vertex_descriptorN prev, EdgeList& remEdges, int k) { //cerr << WRITE_FUNCTION << endl; out_edge_iteratorN oit, oit_end; for(tie(oit, oit_end) = out_edges(src, groupT_.g); oit != oit_end && k > 0; ++oit) { vertex_descriptorN targ = target(*oit, groupT_.g); ASSERTING(targ != src ); //cerr << "ActVert " << actVert << ": " << *oit << " targ " << targ << " == " << prev << " ? " ; if(targ != actVert && targ != prev) { remEdges.push_back(*oit); int k_out = k; if(groupT_.g[targ].vertexState == GROUP_MEMBER) { subVertices.insertVertex(groupT_.g[targ]); k_out--; //cerr << " Inserted Group Member: " << targ << endl; } else if(groupT_.g[targ].vertexState == STEINER_POINT) { steinerSet.insert(targ); //cerr << " Inserted SP: " << targ << endl; } else ASSERTING(0); subGraphRingSP(subVertices, steinerSet, actVert, targ, src, remEdges, k_out); } } } */ void TreeDynamics::subGraphRingSP(VertexSet& subVertices, VertexSet& steinerSet, vertex_descriptorN actVert, vertex_descriptorN src, vertex_descriptorN prev, EdgeList& remEdges, int k) { //cerr << WRITE_FUNCTION << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(src, groupT_.g); oit != oit_end && k > 0; ++oit) { vertex_descriptorN targ = target(*oit, groupT_.g); ASSERTING(targ != src ); //cerr << "ActVert " << actVert << ": " << *oit << " targ " << targ << " == " << prev << " ? " ; if(targ != actVert && targ != prev) { remEdges.push_back(*oit); int k_out = k; if(groupT_.g[targ].vertexState == GROUP_MEMBER) { subVertices.insert(targ); k_out--; //cerr << " Inserted Group Member: " << targ << endl; } else if(groupT_.g[targ].vertexState == STEINER_POINT) { steinerSet.insert(targ); //cerr << " Inserted SP: " << targ << endl; } else ASSERTING(0); subGraphRingSP(subVertices, steinerSet, actVert, targ, src, remEdges, k_out); } } } void TreeDynamics::findMCEdge(vertex_descriptorN src, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &w) { //cerr << WRITE_FUNCTION << "src " << src << " prev_v " << prev_v << " start_v " << start_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; //cerr << *oit << " targ " << targ << " src " << src << endl; pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); if((globalG_[e.first].weight) < w && getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { w = globalG_[e.first].weight; new_e = e.first; } findMCEdge(src, start_v, targ, tree_g, new_e, w); } } void TreeDynamics::findMDEdge(vertex_descriptorN src, const double &src_eccentricity, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &current_src_eccentricity) { out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; if(getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { double target_eccentricity = 0; worstCaseDist(targ, targ, targ, tree_g, target_eccentricity); pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); double new_src_eccentricity = max(src_eccentricity, globalG_[e.first].weight + target_eccentricity); if(new_src_eccentricity < current_src_eccentricity) { current_src_eccentricity = new_src_eccentricity; new_e = e.first; } } findMDEdge(src, src_eccentricity, start_v, targ, tree_g, new_e, current_src_eccentricity); } } /* void TreeDynamics::findMDEdge(vertex_descriptorN src, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &w) { //cerr << WRITE_FUNCTION << "src " << src << " prev_v " << prev_v << " start_v " << start_v << endl; out_edge_iteratorN oit, oit_end; for(tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; //cerr << *oit << " targ " << targ << " src " << src << " prev_v " << prev_v << endl; if(getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { double worstcase_dist = 0; worstCaseDist(targ, targ, targ, tree_g, worstcase_dist); pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); if((globalG_[e.first].weight + worstcase_dist) < w) { w = globalG_[e.first].weight + worstcase_dist; new_e = e.first; } } findMDEdge(src, start_v, targ, tree_g, new_e, w); } } */ void TreeDynamics::findMCEdgeC(vertex_descriptorN src, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &w, const DistanceVector &distance) { //cerr << WRITE_FUNCTION << "src " << src << " prev_v " << prev_v << " start_v " << start_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; //cerr << *oit << " targ " << targ << " src " << src << endl; pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); // TODO: check for delay constraints double tempMinWeight = distance[targ] + globalG_[e.first].weight; if(tempMinWeight <= GlobalSimArgs::getDelayConstraint()) //continue; { if((globalG_[e.first].cost) < w && getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { w = globalG_[e.first].cost; new_e = e.first; } } findMCEdgeC(src, start_v, targ, tree_g, new_e, w, distance); } } void TreeDynamics::findMDEdgeC(vertex_descriptorN src, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &w, const DistanceVector &distance) { //cerr << WRITE_FUNCTION << "src " << src << " prev_v " << prev_v << " start_v " << start_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; //cerr << *oit << " targ " << targ << " src " << src << " prev_v " << prev_v << endl; if(getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); // TODO: check for delay constraints double tempMinWeight = distance[targ] + globalG_[e.first].weight; if(tempMinWeight <= GlobalSimArgs::getDelayConstraint()) //continue; { double worstcase_dist = 0; worstCaseCost(targ, targ, targ, tree_g, worstcase_dist); if((globalG_[e.first].cost + worstcase_dist) < w) { w = globalG_[e.first].cost+ worstcase_dist; new_e = e.first; } } } findMDEdgeC(src, start_v, targ, tree_g, new_e, w, distance); } } void TreeDynamics::findMCEdgeBD(vertex_descriptorN src, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &w, const DistanceVector &distance, const double &diameterBound) { //cerr << WRITE_FUNCTION << "src " << src << " prev_v " << prev_v << " start_v " << start_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; //cerr << *oit << " targ " << targ << " src " << src << endl; pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); // TODO: check for delay constraints double diameter = distance[targ] + globalG_[e.first].weight; if(diameter <= diameterBound) //continue; { //cerr << WRITE_FUNCTION << " edge : " << e.first << " diameter " << diameter << " bound " << diameterBound << endl; if((globalG_[e.first].weight) < w && getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { w = globalG_[e.first].weight; new_e = e.first; } } findMCEdgeBD(src, start_v, targ, tree_g, new_e, w, distance, diameterBound); } } void TreeDynamics::findMDEdgeBD(vertex_descriptorN src, vertex_descriptorN prev_v, vertex_descriptorN start_v, const GraphN &tree_g, edge_descriptorN& new_e, double &w, const DistanceVector &distance, const double &diameterBound) { //cerr << WRITE_FUNCTION << "src " << src << " prev_v " << prev_v << " start_v " << start_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(start_v, tree_g); oit != oit_end; ++oit) { vertex_descriptorN targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; //cerr << *oit << " targ " << targ << " src " << src << " prev_v " << prev_v << endl; if(getOutDegree(targ, tree_g) < getDegreeConstraint(globalG_, targ)) { pair<edge_descriptorN, bool> e = edge(src, targ, globalG_); ASSERTING(e.second); // TODO: check for delay constraints double diameter = distance[targ] + globalG_[e.first].weight; if(diameter <= diameterBound) //continue; { double worstcase_dist = 0; worstCaseDist(targ, targ, targ, tree_g, worstcase_dist); if((globalG_[e.first].weight + worstcase_dist) < w) { w = globalG_[e.first].weight + worstcase_dist; new_e = e.first; } } } findMDEdgeBD(src, start_v, targ, tree_g, new_e, w, distance, diameterBound); } } void TreeDynamics::checkRemove(vertex_descriptorN rem_vert) { #ifndef NDEBUG if(groupT_.V.contains(rem_vert)) { if(groupT_.g[rem_vert].vertexState != STEINER_POINT) { dumpTreeStructure(groupT_); cerr << rem_vert << " Props: " << groupT_.g[rem_vert] << endl; cerr << "Tree Algo " << treeAlgo_ << " action Vert " << actionVert_ << endl; cerr << "Num vertices " << groupT_.V.size() << " num edges " << num_edges(groupT_.g) << endl; } ASSERTING(groupT_.g[rem_vert].vertexState == STEINER_POINT); } if(groupT_.V.size() > 1) { for(VertexSet::iterator vit = groupT_.V.begin(), vit_end = groupT_.V.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT_.g) <= 0) { dumpTreeStructure(groupT_); //dumpGraph(groupT_.g); cerr << " Vertex " << *vit << " out-degree == 0 " << endl; cerr << " Props: " << groupT_.g[*vit] << endl; cerr << "Tree Algo " << treeAlgo_ << " action Vert " << actionVert_ << endl; cerr << "Num vertices " << groupT_.V.size() << " num edges " << num_edges(groupT_.g) << endl; } ASSERTING(getOutDegree(*vit, groupT_.g) > 0); } if(groupT_.E.size() > 1) GraphAlgorithms::checkGraph(groupT_.g); } VertexSet edgeVerts; EdgePair::iterator pit = groupT_.Ep.begin(), pit_end = groupT_.Ep.end(); for( ; pit != pit_end; ++pit) { if(pit->first == rem_vert || pit->second == rem_vert) ASSERTING(groupT_.g[rem_vert].vertexState == STEINER_POINT); ASSERTING(getOutDegree(pit->first, groupT_.g) > 0); ASSERTING(getOutDegree(pit->second, groupT_.g) > 0); vertex_descriptorN src = pit->first; vertex_descriptorN targ = pit->second; ASSERTING(src != targ); ASSERTING(groupT_.V.contains(src)); ASSERTING(groupT_.V.contains(targ)); edgeVerts.insert(src); edgeVerts.insert(targ); } VertexSet edgeVerts2; edge_iteratorN eit, eit_end; for(boost::tuples::tie(eit, eit_end) = edges(groupT_.g); eit != eit_end; ++eit) { vertex_descriptorN src = source(*eit, groupT_.g), targ = target(*eit, groupT_.g); ASSERTING(src != targ); ASSERTING(groupT_.V.contains(src)); ASSERTING(groupT_.V.contains(targ)); if(!edgeVerts.contains(src) || !edgeVerts.contains(targ)) { //dumpTreeStructure(groupT_); //dumpGraph(groupT_.g); cerr << "Missing from T.Ep : (" << src << ", " << targ << ") " << endl; cerr << " tree verts " << groupT_.V << endl; cerr << " edge verts " << edgeVerts << endl; cerr << "Tree Algo " << treeAlgo_ << " action Vert " << actionVert_ << endl; cerr << "Num vertices " << groupT_.V.size() << " num edges " << num_edges(groupT_.g) << endl; } ASSERTING(edgeVerts.contains(src)); ASSERTING(edgeVerts.contains(targ)); edgeVerts2.insert(src); edgeVerts2.insert(targ); } if(GlobalSimArgs::removeMeshAlgo() == NO_DYNAMIC_MESH_ALGO) { if(groupT_.E.size() != num_edges(groupT_.g) || ((groupT_.V.size() && groupT_.V.size() != num_edges(groupT_.g) + 1)) || groupInfo_.getMembers().size() != (groupT_.V.size() - groupT_.S.size())) { //dumpTreeStructure(groupT_); //dumpGraph(groupT_.g); cerr << " tree verts " << groupT_.V << endl; cerr << " Ep verts " << edgeVerts << endl; cerr << " edge verts " << edgeVerts2 << endl; cerr << " remaining " << edgeVerts - edgeVerts2 << " OR: " << edgeVerts2 - edgeVerts << " OR: " << edgeVerts - groupT_.V << " OR: " << groupT_.V - edgeVerts << " OR: " << edgeVerts2 - groupT_.V << " OR: " << groupT_.V - edgeVerts2 << endl;; cerr << "Tree Algo " << treeAlgo_ << " action Vert " << actionVert_ << endl; cerr << "Num vertices " << groupT_.V.size() << " num edges " << num_edges(groupT_.g) << endl; cerr << "Num edge verts " << edgeVerts.size() << " " << edgeVerts2.size() << endl; cerr << " members : " << groupInfo_.getMembers() << " steiner points : " << groupT_.S << endl; cerr << " members - steiner points: " << groupT_.V - groupT_.S << endl; } if(groupT_.V.size()) { ASSERTING(groupT_.V.size() == num_edges(groupT_.g) + 1); ASSERTING(groupT_.V.size() == groupT_.E.size() + 1); } } else { if(groupT_.E.size() != num_edges(groupT_.g) || // || ((groupT_.V.size() && groupT_.V.size() != num_edges(groupT_.g) + 1))) groupInfo_.getMembers().size() != (groupT_.V.size() - groupT_.S.size())) { //dumpTreeStructure(groupT_); //dumpGraph(groupT_.g); cerr << " tree verts " << groupT_.V << endl; cerr << " Ep verts " << edgeVerts << endl; cerr << " edge verts " << edgeVerts2 << endl; cerr << " remaining " << edgeVerts - edgeVerts2 << " OR: " << edgeVerts2 - edgeVerts << " OR: " << edgeVerts - groupT_.V << " OR: " << groupT_.V - edgeVerts << " OR: " << edgeVerts2 - groupT_.V << " OR: " << groupT_.V - edgeVerts2 << endl;; cerr << "Tree Algo " << treeAlgo_ << " action Vert " << actionVert_ << endl; cerr << "Num vertices " << groupT_.V.size() << " num edges " << num_edges(groupT_.g) << endl; cerr << "Num edge verts " << edgeVerts.size() << " " << edgeVerts2.size() << endl; cerr << " members : " << groupInfo_.getMembers() << " steiner points : " << groupT_.S << endl; cerr << " members - steiner points: " << groupT_.V - groupT_.S << endl; } } ASSERTING(groupT_.E.size() == groupT_.Ep.size()); ASSERTING(groupT_.E.size() == num_edges(groupT_.g)); ASSERTING(groupInfo_.getMembers().size() == (groupT_.V.size() - groupT_.S.size())); #endif // NDEBUG } void TreeDynamics::checkInsert(vertex_descriptorN ins_vert) { #ifndef NDEBUG ASSERTING(groupT_.V.contains(ins_vert)); if(groupT_.V.size() > 1) { for(VertexSet::iterator vit = groupT_.V.begin(), vit_end = groupT_.V.end(); vit != vit_end; ++vit) { if(getOutDegree(*vit, groupT_.g) <= 0) { dumpTreeStructure(groupT_); //dumpGraph(groupT_.g); cerr << " Vertex " << *vit << " out-degree == 0 " << endl; cerr << " Props: " << groupT_.g[*vit] << endl; cerr << "Tree Algo " << treeAlgo_ << " action Vert " << actionVert_ << endl; cerr << "Num vertices " << groupT_.V.size() << " num edges " << num_edges(groupT_.g) << endl; } ASSERTING(getOutDegree(*vit, groupT_.g) > 0); } if(groupT_.E.size() > 1) GraphAlgorithms::checkGraph(groupT_.g); } if(groupT_.E.size() != num_edges(groupT_.g)) { dumpTreeStructure(groupT_); dumpGraph(groupT_.g); } if(num_edges(groupT_.g)) { bool found_ins_vert = false; edge_iteratorN eit, eit_end; for(boost::tuples::tie(eit, eit_end) = edges(groupT_.g); eit != eit_end; ++eit) { vertex_descriptorN src = source(*eit, groupT_.g), targ = target(*eit, groupT_.g); if(ins_vert == src || ins_vert == targ) found_ins_vert = true; } if(!found_ins_vert) { dumpTreeStructure(groupT_); dumpGraph(groupT_.g); } ASSERTING(found_ins_vert); } if(groupT_.V.size()) { ASSERTING(groupT_.V.size() == num_edges(groupT_.g) + 1); ASSERTING(groupT_.V.size() == groupT_.E.size() + 1); } ASSERTING(groupT_.E.size() == groupT_.Ep.size()); ASSERTING(groupT_.E.size() == num_edges(groupT_.g)); ASSERTING(groupInfo_.getMembers().size() == (groupT_.V.size() - groupT_.S.size())); #endif // NDEBUG } /* ----------------------------------------------------------------------------- unused -------------------------------------------------------------------------------*/ /*----------------------------------------------------------------------- connectComponents: compOne and compTwo must be either the same, or disjoint. ------------------------------------------------------------------------- */ void TreeDynamics::connectComponentsDisjoint(TreeStructure &groupT, const VertexSet &compOne, const VertexSet &compTwo) { VertexSet::const_iterator vit, vit_end, vit_in, vit_in_end; for(vit = compOne.begin(), vit_end = compOne.end(); vit != vit_end ; ++vit) { multimap<double, int> mapRankV; for(vit_in = compTwo.begin(), vit_in_end = compTwo.end(); vit_in != vit_in_end; ++vit_in) { if(*vit_in == *vit) continue; pair<edge_descriptorN, bool> ep = edge(*vit_in, *vit, groupT.g); if((num_vertices(groupT.g) > max(*vit_in, *vit)) && ep.second) continue; ep = edge(*vit_in, *vit, globalG_); ASSERTING(ep.second); //cerr << "(" << *vit_in << "," << *vit << ") " ; mapRankV.insert(pair<double, int>(globalG_[ep.first].weight, *vit_in)); } if(mapRankV.size()) { vertex_descriptorN best_v; multimap<double, int>::iterator mmit = mapRankV.begin(), mmit_end = mapRankV.end(); for( ; mmit != mmit_end; ++mmit) { if(getDegreeConstraint(globalG_, mmit->second) > (getOutDegree(groupT.g, mmit->second))) { best_v = mmit->second; break; } } if(mmit == mmit_end) continue; groupT.insertEdge(best_v, *vit, globalG_); } } } void TreeDynamics::connectComponentsEqual(TreeStructure &groupT, const VertexSet &compOne, const VertexSet &compTwo) { std::vector<VertexSet> connectedVerts(num_vertices(groupT.g) + 1); VertexSet::const_iterator vit, vit_end, vit_in, vit_in_end; for(vit = compOne.begin(), vit_end = compOne.end(); vit != vit_end ; ++vit) connectedVerts[*vit].insert(*vit); for(vit = compOne.begin(), vit_end = compOne.end(); vit != vit_end ; ++vit) { multimap<double, int> mapRankV; for(vit_in = compTwo.begin(), vit_in_end = compTwo.end(); vit_in != vit_in_end; ++vit_in) { if(connectedVerts[*vit].contains(*vit_in)) continue; pair<edge_descriptorN, bool> ep = edge(*vit_in, *vit, groupT.g); if((num_vertices(groupT.g) > max(*vit_in, *vit)) && ep.second) continue; ep = edge(*vit_in, *vit, globalG_); ASSERTING(ep.second); // cerr << "(" << *vit_in << "," << *vit << ") " ; mapRankV.insert(pair<double, int>(globalG_[ep.first].weight, *vit_in)); } if(mapRankV.size()) { int best_v = -1; multimap<double, int>::iterator mmit = mapRankV.begin(), mmit_end = mapRankV.end(); for( ; mmit != mmit_end; ++mmit) { if(getDegreeConstraint(globalG_, mmit->second) > getOutDegree(groupT.g, mmit->second)) { best_v = mmit->second; break; } } if(best_v < 0) continue; groupT.insertEdge(best_v, *vit, globalG_); //cerr << "Inserting ( " << best_v << ", " << *vit << ") " << endl; connectedVerts[*vit] += connectedVerts[best_v]; // update for all for(VertexSet::iterator cit = connectedVerts[*vit].begin(), cit_end = connectedVerts[*vit].end(); cit != cit_end; ++cit) connectedVerts[*cit] = connectedVerts[*vit]; } } } void TreeDynamics::calcNeighborHood(vertex_descriptorN actionVert, vertex_descriptorN src, vertex_descriptorN prev, double& w, int& n, int k) { out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(src, groupT_.g); oit != oit_end && k >= 0; ++oit) { vertex_descriptorN targ = target(*oit, groupT_.g); ASSERTING(targ != src ); //cerr << " (targ " << targ << " == " << prev << " prev) ? " << " actionVert "<< actionVert << " src " << src << endl; if(targ == prev) continue; if(targ != actionVert) { w = w + groupT_.g[*oit].weight; n = n + 1; //cerr << "updated w and n " << endl; //cerr << *oit << " w: " << w << " n: " << n << endl; } calcNeighborHood(actionVert, targ, src, w, n, (k - 1)); } } void TreeDynamics::findBNP(const GraphN &tree_g, vertex_descriptorN actVert, vertex_descriptorN start_v, vertex_descriptorN prev_v, double &bcNeighborHood, int &numNeighbors, edge_descriptorN &new_e) { vertex_descriptorN src, targ; vertex_descriptorN curr_v = start_v; bool done = false; double neighborhoodWeight = 0; int neighbors = 0; //cerr << WRITE_FUNCTION << " actVert " << actVert << " curr_v " << curr_v << " prev_v " << prev_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(curr_v, tree_g); oit != oit_end; ++oit) { targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; findBNP(tree_g, actVert, targ, curr_v, bcNeighborHood, numNeighbors, new_e); if(getOutDegree(targ, tree_g) >= getDegreeConstraint(globalG_, targ)) continue; calcNeighborHood(targ, targ, targ, neighborhoodWeight, neighbors, 2); // connecting edge pair<edge_descriptorN, bool> e = edge(actVert, targ, globalG_); ASSERTING(e.second); double tempRank = (neighborhoodWeight + globalG_[e.first].weight)/neighbors; if((bcNeighborHood > tempRank) || (bcNeighborHood == tempRank && numNeighbors < neighbors)) { bcNeighborHood = tempRank; numNeighbors = neighbors; ASSERTING(bcNeighborHood > 0); new_e = e.first; } //cerr << "for(): tempRank " << tempRank << " neighborhoodWeight " << neighborhoodWeight << " neighbors " << neighbors << " edge " << e.first << endl; //cerr << "for(): bcNeighborhood " << bcNeighborHood << " numNeighbors " << numNeighbors << " new_e " << new_e << endl; neighborhoodWeight = 0; neighbors = 0; } } void TreeDynamics::findMDBNP(const GraphN &tree_g, vertex_descriptorN actVert, vertex_descriptorN start_v, vertex_descriptorN prev_v, double &bcNeighborHood, int &numNeighbors, edge_descriptorN &new_e) { vertex_descriptorN src, targ; vertex_descriptorN curr_v = start_v; bool done = false; double neighborhoodWeight = 0; int neighbors = 0; //cerr << WRITE_FUNCTION << " actVert " << actVert << " curr_v " << curr_v << " prev_v " << prev_v << endl; out_edge_iteratorN oit, oit_end; for(boost::tuples::tie(oit, oit_end) = out_edges(curr_v, tree_g); oit != oit_end; ++oit) { targ = target(*oit, tree_g); ASSERTING(targ != start_v); if(targ == prev_v) continue; findBNP(tree_g, actVert, targ, curr_v, bcNeighborHood, numNeighbors, new_e); if(getOutDegree(targ, tree_g) >= getDegreeConstraint(globalG_, targ)) continue; calcNeighborHood(targ, targ, targ, neighborhoodWeight, neighbors, 2); double worstcase_dist = 0; if(getOutDegree(targ, groupT_.g) > 0) { worstCaseDist(targ, targ, targ, tree_g, worstcase_dist); //cerr << WRITE_FUNCTION << "worst case distance " << worstcase_dist << endl; } // connecting edge pair<edge_descriptorN, bool> e = edge(actVert, targ, globalG_); ASSERTING(e.second); double tempRank = (neighborhoodWeight + globalG_[e.first].weight + worstcase_dist)/neighbors; if((bcNeighborHood > tempRank) || (bcNeighborHood == tempRank && numNeighbors < neighbors)) { bcNeighborHood = tempRank; numNeighbors = neighbors; ASSERTING(bcNeighborHood > 0); new_e = e.first; } //cerr << "for(): neighborhoodWeight " << neighborhoodWeight + worstcase_dist << " neighbors " << neighbors << " edge " << e.first << endl; //cerr << "for(): bcNeighborhood " << bcNeighborHood << " numNeighbors " << numNeighbors << " new_e " << new_e << endl; neighborhoodWeight = 0; neighbors = 0; } } /* void TreeDynamics::subGraphRingk(SimVertexMap& subVertices, VertexSet& steinerSet, vertex_descriptorN actVert, vertex_descriptorN src, EdgeList& remEdges, int k) { k--; out_edge_iteratorN oit, oit_end; for(tie(oit, oit_end) = out_edges(src, groupT_.g); oit != oit_end && k >= 0; ++oit) { vertex_descriptorN targ = target(*oit, groupT_.g); ASSERTING(targ != src ); cerr << *oit << endl; remEdges.push_back(*oit); if(targ != actVert) { // because other vertices are connected to it, it is marked as a group member even though it is steiner point subVertices.insertVertex(targ, groupT_.g[targ], GROUP_MEMBER); if(groupT_.g[targ].vertexState == STEINER_POINT) steinerSet.insert(targ); } subGraphRingk(subVertices, steinerSet, actVert, targ, remEdges, k); } } */ /* void TreeDynamics::connectSearchMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV) { int degInc = 0, avInc = 2; int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double min_current_diameter = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { int src = *vit; if(getOutDegree(src, groupT.g) >= getDegreeConstraint(globalG_, src) + degInc) continue; double src_eccentricity = 0; if(getOutDegree(src, groupT.g) > 0) worstCaseDist(src, src, src, groupT, src_eccentricity); // if source is a leaf node then its eccentricity is alwasy zero -> for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(src, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) - avInc; if(od > 0) { double target_eccentricity = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseDist(targ, targ, targ, groupT, target_eccentricity); edge_descriptorN e = ep.first; //double new_diameter = src_eccentricity + globalG_[ep.first].weight + target_eccentricity; double new_src_eccentricity = max(src_eccentricity, globalG_[ep.first].weight + target_eccentricity); double new_target_eccentricity = max(target_eccentricity, globalG_[ep.first].weight + src_eccentricity); //cerr << src << " src eccentricity " << src_eccentricity << " new src eccentricity " << new_src_eccentricity << " " << targ << " target eccentricity " << target_eccentricity << " new target eccentricity " << new_target_eccentricity << endl; //double eccentricity_difference = abs(new_target_eccentricity - target_eccentricity) + abs(new_src_eccentricity - src_eccentricity); //cerr << "Eccentricity difference : " << eccentricity_difference << endl; //findMDEdge(src, src_eccentricity, targ, targ, groupT.g, e, this_diameter); if(min_current_diameter > new_src_eccentricity) { min_current_diameter = new_src_eccentricity; connE = e; connV = targ; mitV = mit; // -- debug -- //int targ = target(connE, globalG_), src = source(connE,globalG_); //if(targ != src) targ = src; //cerr << WRITE_FUNCTION << " found edge : " << connE << " current diameter " << min_current_diameter << endl; //char c = getchar(); // -- end debug -- } } } } // -- fail safe -- if(connV < 0) { // connectdV filled up out-degree (shouldn't happen), available out degree < 0 if(getAvOutDegree(globalG_, groupT, connectedV) < 0 || avInc < 0) degInc++; avInc--; if(degInc >= (numeric_limits<double>::max)()) break; cerr << "fail safe -> connV < 0, avInc " << avInc << " degInc " << degInc << endl; //char c = getchar(); } // -- end fail safe -- else { groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); // calculate available out degree avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); //cerr << WRITE_FUNCTION << " CONNECTED: " << connE << " current diameter " << min_current_diameter << endl; } } } */ /* void TreeDynamics::connectMDE(TreeStructure &groupT, OutDegreeMap &adjacentMap, VertexSet &connectedV) { int degInc = 0, avInc = 2; int neighborSz = adjacentMap.size() + connectedV.size(); int avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); VertexSet::iterator vit, vit_end; while(connectedV.size() < neighborSz) { int connV = -1; edge_descriptorN connE; double min_current_eccentricity = (numeric_limits<double>::max)(); OutDegreeMap::iterator mitV; for(vit = connectedV.begin(), vit_end = connectedV.end(); vit != vit_end; ++vit) { int src = *vit; if(getOutDegree(src, groupT.g) >= getDegreeConstraint(globalG_, src) + degInc) continue; double src_eccentricity = 0; if(getOutDegree(src, groupT.g) > 0) worstCaseDist(src, src, src, groupT, src_eccentricity); for(OutDegreeMap::iterator mit = adjacentMap.begin(), mit_end = adjacentMap.end(); mit != mit_end; ++mit) { vertex_descriptorN targ = mit->second; pair<edge_descriptorN, bool> ep = edge(src, targ, globalG_); ASSERTING(ep.second); int od = avOutDegConnected + getAvOutDegree(globalG_, groupT, targ) - avInc; if(od > 0) { double target_eccentricity = 0; if(getOutDegree(targ, groupT.g) > 0) worstCaseDist(targ, targ, targ, groupT, target_eccentricity); edge_descriptorN e = ep.first; //double this_diameter = src_eccentricity + globalG_[ep.first].weight + target_eccentricity; double this_eccentricity = max(src_eccentricity, globalG_[ep.first].weight + target_eccentricity); if(min_current_eccentricity > this_eccentricity) { min_current_eccentricity = this_eccentricity; connE = e; connV = targ; mitV = mit; // -- debug -- //int targ = target(connE, globalG_), src = source(connE,globalG_); //if(targ != src) targ = src; cerr << WRITE_FUNCTION << " found edge : " << connE << " current diameter " << min_current_eccentricity << endl; //char c = getchar(); // -- end debug -- } } } } // -- fail safe -- if(connV < 0) { // connectdV filled up out-degree (shouldn't happen), available out degree < 0 if(getAvOutDegree(globalG_, groupT, connectedV) < 0 || avInc < 0) degInc++; avInc--; if(degInc >= (numeric_limits<double>::max)()) break; cerr << "fail safe -> connV < 0, avInc " << avInc << " degInc " << degInc << endl; //char c = getchar(); } // -- end fail safe -- else { groupT.insertEdge(connE, globalG_); connectedV.insert(connV); adjacentMap.erase(mitV); // calculate available out degree avOutDegConnected = getAvOutDegree(globalG_, groupT, connectedV); } } } */
33.756417
246
0.64469
[ "vector" ]
9343f6561833c024666e1da1862984280b042729
4,242
cpp
C++
Simple++/Debug.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Debug.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Debug.cpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
#include "Debug.h" std::vector<MemoryAllocation> Debug::_debugMemoryAllocations; Debug::Debug( void ) { } Debug::~Debug( void ) { } void Debug::_debugNew( const char * fileName, int lineNumber, unsigned long memoryAddress, unsigned long memorySize ) { MemoryAllocation * memoryAllocation = Debug::getMemoryAllocationByAddress( memoryAddress ); for ( unsigned int i = 0; i < _debugMemoryAllocations.size(); i++ ) { if ( _debugMemoryAllocations[i].getMemoryAddress() == memoryAddress ) { if ( _debugMemoryAllocations[i].isAllocated() ) { Log::displayError( StringASCII( "System allocated a memory already set ?!?!?\n Allocation at " ) + fileName + "@" + lineNumber + " and previously at " + _debugMemoryAllocations[i].getAllocationFileName() + "@" + _debugMemoryAllocations[i].getAllocationLineNumber() ); } _debugMemoryAllocations.erase( _debugMemoryAllocations.begin() + i ); } } _debugMemoryAllocations.push_back( MemoryAllocation( memoryAddress, memorySize, std::string( fileName ), lineNumber ) ); } void Debug::_debugNew( unsigned long memoryAddress, unsigned long memorySize ) { _debugNew( "", 0, memoryAddress, memorySize ); } void Debug::_debugDelete( const char * fileName, int lineNumber, unsigned long memoryAddress ) { //A delete null is useless if ( memoryAddress == NULL ) return; MemoryAllocation * memoryAllocation = Debug::getMemoryAllocationByAddress( memoryAddress ); if ( memoryAllocation == NULL ) { Log::displayError( StringASCII( "Memory delete at " ) + fileName + "@" + lineNumber + " was unable to detect his allocation !" ); return; } if ( !memoryAllocation -> isAllocated() ) { Log::displayError( StringASCII( "Memory delete at " ) + fileName + "@" + lineNumber + " is deleting a ALREADY deleted space. Previously deleted at " + memoryAllocation -> getDeleteFileName() + "@" + memoryAllocation -> getDeleteLineNumber() ); return; } memoryAllocation -> setDeleteFileName( fileName ); memoryAllocation -> setDeleteLineNumber( lineNumber ); memoryAllocation -> setAllocated( false ); for ( unsigned int i = 0; i < _debugMemoryAllocations.size(); i++ ) { //if the memory allocation is himself, bypass and do nothing if ( &_debugMemoryAllocations[i] == memoryAllocation ) continue; //if the space is already allocated, bypass if ( _debugMemoryAllocations[i].isAllocated() ) continue; continue; //checking for double delete if ( _debugMemoryAllocations[i].getMemoryAddress() < memoryAllocation -> getMemoryAddress() && _debugMemoryAllocations[i].getMemoryAddress() + _debugMemoryAllocations[i].getMemorySize() >= memoryAllocation -> getMemoryAddress() ) { Log::displayError( StringASCII( "Memory delete at " ) + fileName + "@" + lineNumber + " is deleting a ALREADY deleted space. Previously deleted at " + _debugMemoryAllocations[i].getDeleteFileName() + "@" + _debugMemoryAllocations[i].getDeleteLineNumber() ); continue; } else if ( _debugMemoryAllocations[i].getMemoryAddress() < memoryAllocation -> getMemoryAddress() + memoryAllocation -> getMemorySize() && _debugMemoryAllocations[i].getMemoryAddress() > memoryAllocation -> getMemoryAddress() ) { Log::displayError( StringASCII( "Memory delete at " ) + fileName + "@" + lineNumber + " is deleting a ALREADY deleted space. Previously deleted at " + _debugMemoryAllocations[i].getDeleteFileName() + "@" + _debugMemoryAllocations[i].getDeleteLineNumber() ); continue; } } //delete his value _debugMemoryAllocations.erase( _debugMemoryAllocations.begin() + getMemoryAllocationIndexByAddress( memoryAddress ) ); } void Debug::_debugDelete( unsigned long address ) { _debugDelete( "", 0, address ); } MemoryAllocation * Debug::getMemoryAllocationByAddress( unsigned long memoryAddress ) { for ( unsigned int i = 0; i < _debugMemoryAllocations.size(); i++ ) { if ( _debugMemoryAllocations[i].getMemoryAddress() == memoryAddress ) return &( _debugMemoryAllocations[i] ); } return NULL; } unsigned int Debug::getMemoryAllocationIndexByAddress( unsigned long memoryAddress ) { for ( unsigned int i = 0; i < _debugMemoryAllocations.size(); i++ ) { if ( _debugMemoryAllocations[i].getMemoryAddress() == memoryAddress ) return i; } return 0; }
41.588235
271
0.727959
[ "vector" ]
934e00842d8f1bdd790bbe223e84b89269242f88
3,110
cpp
C++
PortableGraphicsToolkit/src/pgt/graphics/plattform/opengl/voxel/models/VoxelModelManager.cpp
chris-b-h/PortableGraphicsToolkit
85862a6c5444cf9689821ff23952b56a01ff5835
[ "Zlib" ]
3
2017-07-12T20:18:51.000Z
2017-07-20T15:02:58.000Z
PortableGraphicsToolkit/src/pgt/graphics/plattform/opengl/voxel/models/VoxelModelManager.cpp
chris-b-h/PortableGraphicsToolkit
85862a6c5444cf9689821ff23952b56a01ff5835
[ "Zlib" ]
null
null
null
PortableGraphicsToolkit/src/pgt/graphics/plattform/opengl/voxel/models/VoxelModelManager.cpp
chris-b-h/PortableGraphicsToolkit
85862a6c5444cf9689821ff23952b56a01ff5835
[ "Zlib" ]
1
2019-04-03T01:19:42.000Z
2019-04-03T01:19:42.000Z
#include "VoxelModelManager.h" #include <pgt/graphics/plattform/opengl/voxel/renderers/batched/VoxelBatchRenderer.h> #include <pgt/graphics/plattform/opengl/voxel/renderers/static/StaticVoxelMeshRenderer.h> #include <pgt/graphics/plattform/opengl/voxel/model_updaters/AsyncVoxelModelUpdater.h> #include <pgt/graphics/plattform/opengl/voxel/models/VoxelMeshUpdaterStorage.h> namespace pgt { VoxelModelManager::VoxelModelManager() { _index_buffer = plattform::GlIndexBuffer(); const int required_index_count = VoxelBatchRenderer::REQUIRED_INDEX_BUFFER_SIZE; _index_buffer.initForRectangles(required_index_count); _batch_renderer = new VoxelBatchRenderer(_index_buffer.getID()); _static_renderer = new StaticVoxelMeshRenderer(_index_buffer.getID()); int vmu_tc = VoxelModelUpdater::getThreadCountSuggestion(); int vml_tc = VoxelModelLoader::getThreadCountSuggestion(); // +1 for synchronuous (t0) _voxel_mesh_updater_storage = new VoxelMeshUpdaterStorage(vmu_tc + 1); _model_updater = new VoxelModelUpdater(vmu_tc); _model_loader = new VoxelModelLoader(vml_tc); } VoxelModelManager::~VoxelModelManager() { if (_use_queued_updaters) enableQueuedUpdaters(false); delete _model_loader; delete _model_updater; delete _batch_renderer; delete _voxel_mesh_updater_storage; } VoxelMeshBatched* VoxelModelManager::createVoxelMeshBatched( BATCH_VARIANT variant) { return _batch_renderer->createMesh(variant); } pgt::VoxelMeshStatic* VoxelModelManager::createVoxelMeshStatic() { auto m = _static_renderer->generateVoxelMesh(); _static_meshes.push_back(m); return m; } void VoxelModelManager::enableQueuedUpdaters(bool enable) { if (_use_queued_updaters == enable) return; _use_queued_updaters = enable; if (enable) { _model_loader->start(); _model_updater->start(); } else { _model_updater->stop(); _model_loader->stop(); } } void VoxelModelManager::setProjectionMatrix(const mat4& proj_matrix) { _batch_renderer->setProjectionMatrix(proj_matrix); _static_renderer->setProjectionMatrix(proj_matrix); } void VoxelModelManager::setViewMatrix(const mat4& view_matrix) { _batch_renderer->setViewMatrix(view_matrix); _static_renderer->setViewMatrix(view_matrix); } void VoxelModelManager::render() { auto& win = engine::getApp().getRenderingContext().getWindow(); // if (win.getWidth() > 640) _framebuffer.bind(); _batch_renderer->update(); _batch_renderer->render(); // _static_renderer->render(); // if (win.getWidth() > 640) // _framebuffer.unbind(win.getWidth(), win.getHeight()); } void VoxelModelManager::setWireframeMode(bool val) { _batch_renderer->setWireframeMode(val); _static_renderer->setWireframeMode(val); } }
34.94382
89
0.681994
[ "render" ]
93503ebe5b3634ebe902aaf15d8784fe990c1960
3,351
cpp
C++
compiler-rt/test/cfi/cross-dso/simple-fail.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
compiler-rt/test/cfi/cross-dso/simple-fail.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
compiler-rt/test/cfi/cross-dso/simple-fail.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clangxx_cfi_dso -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx_cfi_dso %s -o %t %ld_flags_rpath_exe // RUN: %expect_crash %t 2>&1 | FileCheck --check-prefix=CFI %s // RUN: %expect_crash %t x 2>&1 | FileCheck --check-prefix=CFI-CAST %s // RUN: %clangxx_cfi_dso -DB32 -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx_cfi_dso -DB32 %s -o %t %ld_flags_rpath_exe // RUN: %expect_crash %t 2>&1 | FileCheck --check-prefix=CFI %s // RUN: %expect_crash %t x 2>&1 | FileCheck --check-prefix=CFI-CAST %s // RUN: %clangxx_cfi_dso -DB64 -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx_cfi_dso -DB64 %s -o %t %ld_flags_rpath_exe // RUN: %expect_crash %t 2>&1 | FileCheck --check-prefix=CFI %s // RUN: %expect_crash %t x 2>&1 | FileCheck --check-prefix=CFI-CAST %s // RUN: %clangxx_cfi_dso -DBM -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx_cfi_dso -DBM %s -o %t %ld_flags_rpath_exe // RUN: %expect_crash %t 2>&1 | FileCheck --check-prefix=CFI %s // RUN: %expect_crash %t x 2>&1 | FileCheck --check-prefix=CFI-CAST %s // RUN: %clangxx -DBM -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx -DBM %s -o %t %ld_flags_rpath_exe // RUN: %t 2>&1 | FileCheck --check-prefix=NCFI %s // RUN: %t x 2>&1 | FileCheck --check-prefix=NCFI %s // RUN: %clangxx -DBM -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx_cfi_dso -DBM %s -o %t %ld_flags_rpath_exe // RUN: %t 2>&1 | FileCheck --check-prefix=NCFI %s // RUN: %t x 2>&1 | FileCheck --check-prefix=NCFI %s // RUN: %clangxx_cfi_dso_diag -DSHARED_LIB %s -fPIC -shared -o %dynamiclib %ld_flags_rpath_so // RUN: %clangxx_cfi_dso_diag %s -o %t %ld_flags_rpath_exe // RUN: %t 2>&1 | FileCheck --check-prefix=CFI-DIAG-CALL %s // RUN: %t x 2>&1 | FileCheck --check-prefix=CFI-DIAG-CALL --check-prefix=CFI-DIAG-CAST %s // Tests that the CFI mechanism crashes the program when making a virtual call // to an object of the wrong class but with a compatible vtable, by casting a // pointer to such an object and attempting to make a call through it. // REQUIRES: cxxabi #include <stdio.h> #include <string.h> struct A { virtual void f(); }; void *create_B(); #ifdef SHARED_LIB #include "../utils.h" struct B { virtual void f(); }; void B::f() {} void *create_B() { create_derivers<B>(); return (void *)(new B()); } #else void A::f() {} int main(int argc, char *argv[]) { void *p = create_B(); A *a; // CFI: =0= // CFI-CAST: =0= // NCFI: =0= fprintf(stderr, "=0=\n"); if (argc > 1 && argv[1][0] == 'x') { // Test cast. BOOM. // CFI-DIAG-CAST: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type // CFI-DIAG-CAST-NEXT: note: vtable is of type '{{(struct )?}}B' a = (A*)p; } else { // Invisible to CFI. Test virtual call later. memcpy(&a, &p, sizeof(a)); } // CFI: =1= // CFI-CAST-NOT: =1= // NCFI: =1= fprintf(stderr, "=1=\n"); // CFI-DIAG-CALL: runtime error: control flow integrity check for type 'A' failed during virtual call // CFI-DIAG-CALL-NEXT: note: vtable is of type '{{(struct )?}}B' a->f(); // UB here // CFI-NOT: =2= // CFI-CAST-NOT: =2= // NCFI: =2= fprintf(stderr, "=2=\n"); } #endif
32.852941
115
0.652343
[ "object" ]
935f4bc15bacd4e78fe272ece5968b4ddcb3e827
11,833
hpp
C++
lib/include/ckpttncpp/bpqueue.hpp
luk036/ckpttncpp
25898e331c5b114e5886b828fc68ec5512d409ee
[ "MIT" ]
null
null
null
lib/include/ckpttncpp/bpqueue.hpp
luk036/ckpttncpp
25898e331c5b114e5886b828fc68ec5512d409ee
[ "MIT" ]
2
2019-07-23T14:21:48.000Z
2020-01-20T10:48:07.000Z
lib/include/ckpttncpp/bpqueue.hpp
luk036/ckpttncpp
25898e331c5b114e5886b828fc68ec5512d409ee
[ "MIT" ]
1
2018-11-17T02:40:02.000Z
2018-11-17T02:40:02.000Z
#pragma once #include "dllist.hpp" // import dllink #include <cassert> #include <gsl/span> // #include <type_traits> #include <vector> // Forward declaration for begin() end() template <typename _Tp, typename Int> class bpq_iterator; /*! * @brief bounded priority queue * * Bounded Priority Queue with integer keys in [a..b]. * Implemented by array (bucket) of doubly-linked lists. * Efficient if key is bounded by a small integer value. * * Note that this class does not own the PQ nodes. This feature * makes the nodes sharable between doubly linked list class and * this class. In the FM algorithm, the node either attached to * the gain buckets (PQ) or in the waitinglist (doubly linked list), * but not in both of them in the same time. * * Another improvement is to make the array size one element bigger * i.e. (b - a + 2). The extra dummy array element (which is called * sentinel) is used to reduce the boundary checking during updating. * * All the member functions assume that the keys are within the bound. * * @TODO: support std::pmr */ template <typename _Tp, typename Int = int32_t, typename _Sequence = std::vector<dllink<std::pair<_Tp, std::make_unsigned_t<Int>>>>> // class Allocator = typename std::allocator<dllink<std::pair<_Tp, // Int>> > > class bpqueue { using UInt = std::make_unsigned_t<Int>; friend bpq_iterator<_Tp, Int>; using Item = dllink<std::pair<_Tp, UInt>>; static_assert(std::is_same_v<Item, typename _Sequence::value_type>, "value_type must be the same as the underlying container"); public: using value_type = typename _Sequence::value_type; using reference = typename _Sequence::reference; using const_reference = typename _Sequence::const_reference; using size_type = typename _Sequence::size_type; using container_type = _Sequence; private: Item sentinel {}; //!< sentinel */ _Sequence bucket; //!< bucket, array of lists UInt max {}; //!< max value Int offset; //!< a - 1 UInt high; //!< b - a + 1 // using alloc_t = decltype(bucket.get_allocator()); public: /*! * @brief Construct a new bpqueue object * * @param[in] a lower bound * @param[in] b upper bound */ constexpr bpqueue(Int a, Int b) : bucket(static_cast<UInt>(b - a) + 2U) , offset(a - 1) , high(static_cast<UInt>(b - offset)) { assert(a <= b); static_assert( std::is_integral<Int>::value, "bucket's key must be an integer"); bucket[0].append(this->sentinel); // sentinel } bpqueue(const bpqueue&) = delete; // don't copy ~bpqueue() = default; constexpr auto operator=(const bpqueue&) -> bpqueue& = delete; // don't assign constexpr bpqueue(bpqueue&&) noexcept = default; constexpr auto operator=(bpqueue&&) noexcept -> bpqueue& = default; // don't assign /*! * @brief whether the %bpqueue is empty. * * @return true * @return false */ [[nodiscard]] constexpr auto is_empty() const noexcept -> bool { return this->max == 0U; } /*! * @brief Set the key object * * @param[out] it the item * @param[in] gain the key of it */ constexpr auto set_key(Item& it, Int gain) noexcept -> void { it.data.second = static_cast<UInt>(gain - this->offset); } /*! * @brief Get the max value * * @return T maximum value */ [[nodiscard]] constexpr auto get_max() const noexcept -> Int { return this->offset + Int(this->max); } /*! * @brief clear reset the PQ */ constexpr auto clear() noexcept -> void { while (this->max > 0) { this->bucket[this->max].clear(); this->max -= 1; } } /*! * @brief append item with internal key * * @param[in,out] it the item */ constexpr auto append_direct(Item& it) noexcept -> void { assert(static_cast<Int>(it.data.second) > this->offset); this->append(it, Int(it.data.second)); } /*! * @brief append item with external key * * @param[in,out] it the item * @param[in] k the key */ constexpr auto append(Item& it, Int k) noexcept -> void { assert(k > this->offset); it.data.second = UInt(k - this->offset); if (this->max < it.data.second) { this->max = it.data.second; } this->bucket[it.data.second].append(it); } /*! * @brief append from list * * @param[in,out] nodes */ // constexpr auto appendfrom(gsl::span<Item> nodes) noexcept -> void // { // for (auto& it : nodes) // { // it.data.second -= this->offset; // assert(it.data.second > 0); // this->bucket[it.data.second].append(it); // } // this->max = this->high; // while (this->bucket[this->max].is_empty()) // { // this->max -= 1; // } // } /*! * @brief pop node with the highest key * * @return dllink& */ constexpr auto popleft() noexcept -> Item& { auto& res = this->bucket[this->max].popleft(); while (this->bucket[this->max].is_empty()) { this->max -= 1; } return res; } /*! * @brief decrease key by delta * * @param[in,out] it the item * @param[in] delta the change of the key * * Note that the order of items with same key will not be preserved. * For FM algorithm, this is a prefered behavior. */ constexpr auto decrease_key(Item& it, UInt delta) noexcept -> void { // this->bucket[it.data.second].detach(it) it.detach(); it.data.second -= delta; assert(it.data.second > 0); assert(it.data.second <= this->high); this->bucket[it.data.second].append(it); // FIFO if (this->max < it.data.second) { this->max = it.data.second; return; } while (this->bucket[this->max].is_empty()) { this->max -= 1; } } /*! * @brief increase key by delta * * @param[in,out] it the item * @param[in] delta the change of the key * * Note that the order of items with same key will not be preserved. * For FM algorithm, this is a prefered behavior. */ constexpr auto increase_key(Item& it, UInt delta) noexcept -> void { // this->bucket[it.data.second].detach(it) it.detach(); it.data.second += delta; assert(it.data.second > 0); assert(it.data.second <= this->high); this->bucket[it.data.second].appendleft(it); // LIFO if (this->max < it.data.second) { this->max = it.data.second; } } /*! * @brief modify key by delta * * @param[in,out] it the item * @param[in] delta the change of the key * * Note that the order of items with same key will not be preserved. * For FM algorithm, this is a prefered behavior. */ constexpr auto modify_key(Item& it, Int delta) noexcept -> void { if (it.is_locked()) { return; } if (delta > 0) { this->increase_key(it, UInt(delta)); } else if (delta < 0) { this->decrease_key(it, UInt(-delta)); } } /*! * @brief detach the item from bpqueue * * @param[in,out] it the item */ constexpr auto detach(Item& it) noexcept -> void { // this->bucket[it.data.second].detach(it) it.detach(); while (this->bucket[this->max].is_empty()) { this->max -= 1; } } /*! * @brief iterator point to begin * * @return bpq_iterator */ constexpr auto begin() -> bpq_iterator<_Tp, Int>; /*! * @brief iterator point to end * * @return bpq_iterator */ constexpr auto end() -> bpq_iterator<_Tp, Int>; // constexpr auto& items() // { // return *this; // } // constexpr const auto& items() const // { // return *this; // } // using coro_t = boost::coroutines2::coroutine<dllink<T>&>; // using pull_t = typename coro_t::pull_type; // /** // * @brief item generator // * // * @return pull_t // */ // auto items() -> pull_t // { // auto func = [&](typename coro_t::push_type& yield) { // auto curkey = this->max; // while (curkey > 0) // { // for (const auto& item : this->bucket[curkey].items()) // { // yield(item); // } // curkey -= 1; // } // }; // return pull_t(func); // } }; /*! * @brief Bounded Priority Queue Iterator * * Bounded Priority Queue Iterator. Traverse the queue in descending * order. Detaching queue items may invalidate the iterator because * the iterator makes a copy of current key. */ template <typename _Tp, typename Int = int32_t> class bpq_iterator { using UInt = std::make_unsigned_t<Int>; // using value_type = _Tp; // using key_type = Int; using Item = dllink<std::pair<_Tp, UInt>>; private: bpqueue<_Tp, Int>& bpq; /*!< the priority queue */ UInt curkey; /*!< the current key value */ dll_iterator<std::pair<_Tp, UInt>> curitem; /*!< list iterator pointed to the current item. */ /*! * @brief get the reference of the current list * * @return dllink& */ constexpr auto curlist() -> Item& { return this->bpq.bucket[this->curkey]; } public: /*! * @brief Construct a new bpq iterator object * * @param[in] bpq * @param[in] curkey */ constexpr bpq_iterator(bpqueue<_Tp, Int>& bpq, UInt curkey) : bpq {bpq} , curkey {curkey} , curitem {bpq.bucket[curkey].begin()} { } /*! * @brief move to the next item * * @return bpq_iterator& */ constexpr auto operator++() -> bpq_iterator& { ++this->curitem; while (this->curitem == this->curlist().end()) { do { this->curkey -= 1; } while (this->curlist().is_empty()); this->curitem = this->curlist().begin(); } return *this; } /*! * @brief get the reference of the current item * * @return bpq_iterator& */ constexpr auto operator*() -> Item& { return *this->curitem; } /*! * @brief eq operator * * @param[in] rhs * @return true * @return false */ friend constexpr auto operator==( const bpq_iterator& lhs, const bpq_iterator& rhs) -> bool { return lhs.curitem == rhs.curitem; } /*! * @brief neq operator * * @param[in] rhs * @return true * @return false */ friend constexpr auto operator!=( const bpq_iterator& lhs, const bpq_iterator& rhs) -> bool { return !(lhs == rhs); } }; /*! * @brief * * @return bpq_iterator */ template <typename _Tp, typename Int, class _Sequence> inline constexpr auto bpqueue<_Tp, Int, _Sequence>::begin() -> bpq_iterator<_Tp, Int> { return {*this, this->max}; } /*! * @brief * * @return bpq_iterator */ template <typename _Tp, typename Int, class _Sequence> inline constexpr auto bpqueue<_Tp, Int, _Sequence>::end() -> bpq_iterator<_Tp, Int> { return {*this, 0}; }
25.502155
88
0.545846
[ "object", "vector" ]
9361e19020322dec137799b2496149d446840375
5,929
cc
C++
SimTracker/VertexAssociation/plugins/VertexAssociatorByTracksProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
SimTracker/VertexAssociation/plugins/VertexAssociatorByTracksProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
SimTracker/VertexAssociation/plugins/VertexAssociatorByTracksProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-03-19T13:44:54.000Z
2019-03-19T13:44:54.000Z
#include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/Utilities/interface/EDGetToken.h" #include "DataFormats/Common/interface/Handle.h" #include "SimTracker/Common/interface/TrackingParticleSelector.h" #include "SimTracker/VertexAssociation/interface/VertexAssociatorByTracks.h" #include "SimDataFormats/Associations/interface/VertexToTrackingVertexAssociator.h" class VertexAssociatorByTracksProducer: public edm::global::EDProducer<> { public: explicit VertexAssociatorByTracksProducer(const edm::ParameterSet&); ~VertexAssociatorByTracksProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; // ----------member data --------------------------- const double R2SMatchedSimRatio_; const double R2SMatchedRecoRatio_; const double S2RMatchedSimRatio_; const double S2RMatchedRecoRatio_; const TrackingParticleSelector selector_; const reco::TrackBase::TrackQuality trackQuality_; edm::EDGetTokenT<reco::RecoToSimCollection> trackRecoToSimAssociationToken_; edm::EDGetTokenT<reco::SimToRecoCollection> trackSimToRecoAssociationToken_; }; namespace { TrackingParticleSelector makeSelector(const edm::ParameterSet& param) { return TrackingParticleSelector( param.getParameter<double>("ptMinTP"), param.getParameter<double>("ptMaxTP"), param.getParameter<double>("minRapidityTP"), param.getParameter<double>("maxRapidityTP"), param.getParameter<double>("tipTP"), param.getParameter<double>("lipTP"), param.getParameter<int>("minHitTP"), param.getParameter<bool>("signalOnlyTP"), param.getParameter<bool>("intimeOnlyTP"), param.getParameter<bool>("chargedOnlyTP"), param.getParameter<bool>("stableOnlyTP"), param.getParameter<std::vector<int> >("pdgIdTP") ); } } VertexAssociatorByTracksProducer::VertexAssociatorByTracksProducer(const edm::ParameterSet& config): R2SMatchedSimRatio_(config.getParameter<double>("R2SMatchedSimRatio")), R2SMatchedRecoRatio_(config.getParameter<double>("R2SMatchedRecoRatio")), S2RMatchedSimRatio_(config.getParameter<double>("S2RMatchedSimRatio")), S2RMatchedRecoRatio_(config.getParameter<double>("S2RMatchedRecoRatio")), selector_(makeSelector(config.getParameter<edm::ParameterSet>("trackingParticleSelector"))), trackQuality_(reco::TrackBase::qualityByName(config.getParameter<std::string>("trackQuality"))), trackRecoToSimAssociationToken_(consumes<reco::RecoToSimCollection>(config.getParameter<edm::InputTag>("trackAssociation"))), trackSimToRecoAssociationToken_(consumes<reco::SimToRecoCollection>(config.getParameter<edm::InputTag>("trackAssociation"))) { produces<reco::VertexToTrackingVertexAssociator>(); } VertexAssociatorByTracksProducer::~VertexAssociatorByTracksProducer() {} void VertexAssociatorByTracksProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; // Matching conditions desc.add<double>("R2SMatchedSimRatio", 0.3); desc.add<double>("R2SMatchedRecoRatio", 0.0); desc.add<double>("S2RMatchedSimRatio", 0.0); desc.add<double>("S2RMatchedRecoRatio", 0.3); //RecoTrack selection desc.add<std::string>("trackQuality", "highPurity"); // TrackingParticle selection edm::ParameterSetDescription descTp; descTp.add<double>("lipTP", 30.0); descTp.add<bool>("chargedOnlyTP", true); descTp.add<std::vector<int>>("pdgIdTP", std::vector<int>()); descTp.add<bool>("signalOnlyTP", true); descTp.add<double>("minRapidityTP", -2.4); descTp.add<int>("minHitTP", 0); descTp.add<double>("ptMinTP", 0.9); descTp.add<double>("ptMaxTP", 1e100); descTp.add<double>("maxRapidityTP", 2.4); descTp.add<double>("tipTP", 3.5); desc.add<edm::ParameterSetDescription>("trackingParticleSelector", descTp); // Track-TrackingParticle association desc.add<edm::InputTag>("trackAssociation", edm::InputTag("trackingParticleRecoTrackAsssociation")); descriptions.add("VertexAssociatorByTracks", desc); } void VertexAssociatorByTracksProducer::produce(edm::StreamID, edm::Event& iEvent, const edm::EventSetup&) const { edm::Handle<reco::RecoToSimCollection > recotosimCollectionH; iEvent.getByToken(trackRecoToSimAssociationToken_, recotosimCollectionH); edm::Handle<reco::SimToRecoCollection > simtorecoCollectionH; iEvent.getByToken(trackSimToRecoAssociationToken_, simtorecoCollectionH); auto impl = std::make_unique<VertexAssociatorByTracks>(&(iEvent.productGetter()), R2SMatchedSimRatio_, R2SMatchedRecoRatio_, S2RMatchedSimRatio_, S2RMatchedRecoRatio_, &selector_, trackQuality_, recotosimCollectionH.product(), simtorecoCollectionH.product()); auto toPut = std::make_unique<reco::VertexToTrackingVertexAssociator>(std::move(impl)); iEvent.put(std::move(toPut)); } DEFINE_FWK_MODULE(VertexAssociatorByTracksProducer);
46.320313
127
0.6986
[ "vector" ]
936f4a339fff2401c2cddc2edf1fef4c8a4d1e5f
1,008
cpp
C++
cpp/graphs/matchings/stable_matching.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
1,727
2015-01-01T18:32:37.000Z
2022-03-28T05:56:03.000Z
cpp/graphs/matchings/stable_matching.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
110
2015-05-03T10:23:18.000Z
2021-07-31T22:44:39.000Z
cpp/graphs/matchings/stable_matching.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
570
2015-01-01T10:17:11.000Z
2022-03-31T22:23:46.000Z
#include <bits/stdc++.h> using namespace std; vector<int> stable_matching(vector<vector<int>> prefer_m, vector<vector<int>> prefer_w) { int n = prefer_m.size(); vector<int> pair_m(n, -1); vector<int> pair_w(n, -1); vector<int> p(n); for (int i = 0; i < n; i++) { while (pair_m[i] < 0) { int w = prefer_m[i][p[i]++]; int m = pair_w[w]; if (m == -1) { pair_m[i] = w; pair_w[w] = i; } else if (prefer_w[w][i] < prefer_w[w][m]) { pair_m[m] = -1; pair_m[i] = w; pair_w[w] = i; i = m; } } } return pair_m; } // usage example int main() { vector<vector<int>> prefer_m{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}}; vector<vector<int>> prefer_w{{0, 1, 2}, {2, 0, 1}, {2, 1, 0}}; vector<int> matching = stable_matching(prefer_m, prefer_w); for (int x : matching) cout << x << " "; cout << endl; }
25.846154
89
0.453373
[ "vector" ]
9376332661d521119f99481cdcea5572a686eb06
1,662
hh
C++
CosmicReco/inc/MinuitDriftFitter.hh
singhvivek84/Offline
17dc9d690b74418a5f8aad99309f1591a8904934
[ "Apache-2.0" ]
null
null
null
CosmicReco/inc/MinuitDriftFitter.hh
singhvivek84/Offline
17dc9d690b74418a5f8aad99309f1591a8904934
[ "Apache-2.0" ]
null
null
null
CosmicReco/inc/MinuitDriftFitter.hh
singhvivek84/Offline
17dc9d690b74418a5f8aad99309f1591a8904934
[ "Apache-2.0" ]
1
2020-05-27T22:33:52.000Z
2020-05-27T22:33:52.000Z
#ifndef _COSMIC_RECO_MINUITDRIFTFITTER_HH #define _COSMIC_RECO_MINUITDDRIFTFITTER_HH #include "TrackerConditions/inc/StrawDrift.hh" #include "RecoDataProducts/inc/ComboHit.hh" #include "DataProducts/inc/XYZVec.hh" #include "TrackerGeom/inc/Tracker.hh" #include "RecoDataProducts/inc/CosmicTrackSeed.hh" //For Drift: #include "BTrk/BaBar/BaBar.hh" #include "BTrk/BbrGeom/Trajectory.hh" #include "BTrk/KalmanTrack/KalRep.hh" #include "BTrk/BbrGeom/HepPoint.h" #include "BTrk/TrkBase/TrkPoca.hh" #include "BTrkData/inc/TrkStrawHit.hh" #include "BTrk/BbrGeom/BbrVectorErr.hh" #include "BTrk/TrkBase/TrkPoca.hh" #include "BTrk/ProbTools/ChisqConsistency.hh" #include "BTrk/TrkBase/TrkMomCalculator.hh" //ROOT #include "TMath.h" #include "TF1.h" #include "TH1F.h" //Minuit #include <Minuit2/FCNBase.h> using namespace mu2e; struct FitResult{ public: std::vector<std::string> names; std::vector<double> bestfit; std::vector<double> bestfiterrors; std::vector<double> bestfitcov; std::vector<double> StartDOCAs; std::vector<double> StartTimeResiduals; std::vector<double> GaussianEndDOCAs; std::vector<double> GaussianEndTimeResiduals; std::vector<double> FullFitEndDOCAs; std::vector<double> FullFitEndTimeResiduals; std::vector<double> RecoAmbigs; double NLL; }; namespace MinuitDriftFitter { FitResult DoFit(int diag, CosmicTrackSeed& tseed, StrawResponse const& srep, const Tracker* tracker, double doca_cut, unsigned int MinNCh_cut, int LogLcut, double _gaussTres, double _maxTres); void DoDriftTimeFit(int diag, CosmicTrackSeed& tseed, StrawResponse const& srep, const Tracker* tracker ); } #endif
26.380952
193
0.767148
[ "vector" ]
937a5bec3f416f24d2d760055c4ceb72ff136bcb
524
cpp
C++
tests/src/MpDBConnectorMock.cpp
lgrigoriu/end-to-end-smkex
ffe4582247dd6435e5ac01166022ded6d26babac
[ "BSD-3-Clause" ]
null
null
null
tests/src/MpDBConnectorMock.cpp
lgrigoriu/end-to-end-smkex
ffe4582247dd6435e5ac01166022ded6d26babac
[ "BSD-3-Clause" ]
null
null
null
tests/src/MpDBConnectorMock.cpp
lgrigoriu/end-to-end-smkex
ffe4582247dd6435e5ac01166022ded6d26babac
[ "BSD-3-Clause" ]
null
null
null
#include "MpDBConnectorMock.h" #include "MpBaseService.h" const std::vector<MpMsgPayload>& MpDBConnectorMock::getMessages() { MP_LOG1("Get messages"); return messages_; } void MpDBConnectorMock::pushMessage(MpString const& userSerial, MpMsgPayload const& message) { MP_LOG1("Push message into message queue"); messages_.push_back(message); } void MpDBConnectorMock::messageStatus(const MpMsgPayload& message, mp_status_t status) { } mp_msg_type_t MpDBConnectorMock::getMessageType() { return MP_TYPE_MESSAGE; }
23.818182
67
0.784351
[ "vector" ]
937bf2ff3d440a98221fa85869a1b196be354b11
738
hpp
C++
app/include/driver_for_customer_query_state.hpp
terisikk/TravelAgency
194b6546b7e5ededc7aaa9e7693ddb4f126e8c06
[ "MIT" ]
null
null
null
app/include/driver_for_customer_query_state.hpp
terisikk/TravelAgency
194b6546b7e5ededc7aaa9e7693ddb4f126e8c06
[ "MIT" ]
null
null
null
app/include/driver_for_customer_query_state.hpp
terisikk/TravelAgency
194b6546b7e5ededc7aaa9e7693ddb4f126e8c06
[ "MIT" ]
null
null
null
#ifndef DRIVER_FOR_CUSTOMER_QUERY_STATE_HPP #define DRIVER_FOR_CUSTOMER_QUERY_STATE_HPP #include <ctime> #include <sstream> #include "drivermapper.hpp" #include "travelmapper.hpp" #include "tsv/query.hpp" #include "tsv/table.hpp" #include "ui/context.hpp" class DriverForCustomerQueryState : public ui::State { private: tsv::Table* drivers = nullptr; tsv::Table* travels = nullptr; public: explicit DriverForCustomerQueryState(tsv::Table* drivers, tsv::Table* travels); auto getOutput() -> std::string override; auto getOutput(const std::string& input) -> std::string override; auto executeQuery(const std::string& input) -> std::vector<std::vector<std::string>>; }; #endif
26.357143
93
0.704607
[ "vector" ]
937f0916b7f3797b759586d17ef1ce6de76dfbfd
1,860
cpp
C++
March 2014/MIKE3.cpp
michaelarakel/codechef-solutions
8040aadfe9e1c7311910881c74cc9d2f9de39fcc
[ "Unlicense" ]
null
null
null
March 2014/MIKE3.cpp
michaelarakel/codechef-solutions
8040aadfe9e1c7311910881c74cc9d2f9de39fcc
[ "Unlicense" ]
null
null
null
March 2014/MIKE3.cpp
michaelarakel/codechef-solutions
8040aadfe9e1c7311910881c74cc9d2f9de39fcc
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_set> using namespace std; inline bool next_combination(vector <int>& v, int n) { int k = v.size(); for (int i = k - 1; i >= 0; --i) { if (v[i] < n - k + i + 1) { ++v[i]; for (int j = i + 1; j < k; ++j) v[j] = v[j - 1] + 1; return true; } } return false; } inline bool is_clique(const vector <unordered_set <int> >& g, const vector <int>& combination) { for (int i = 1; i < combination.size(); ++i) { for (int j = 0; j < i; ++j) { if (g[combination[i] - 1].find(combination[j] - 1) == g[combination[i] - 1].end()) return false; } } return true; } inline void find_biggest_clique(const vector <unordered_set <int> >& graph) { int ans = 1; for (int i = 2; i <= graph.size(); ++i) { vector <int> combination(i); for (int j = 0; j < i; ++j) combination[j] = j + 1; bool got_clique = false; do { if (is_clique(graph, combination)) { got_clique = true; break; } } while (next_combination(combination, graph.size())); if (!got_clique) break; else ans = i; } cout << ans; } int main() { int n, m; scanf("%d", &n); scanf("%d", &m); vector <unordered_set <int> > v(m); for (int i = 0; i < m; ++i) { int k; cin >> k; for (int j = 0; j < k; ++j) { int num; scanf("%d", &num); v[i].insert(num); } } vector <unordered_set <int> > g(m); for (int i = 1; i < m; ++i) { for (int j = 0; j < i; ++j) { bool intersect = false; for (auto it = v[j].begin(); !intersect && it != v[j].end(); ++it) { if (v[i].find(*it) != v[i].end()) { intersect = true; break; } } if (!intersect) { g[i].insert(j); g[j].insert(i); } } } find_biggest_clique(g); }
18.415842
95
0.49086
[ "vector" ]
93844739b2c980ab5e52be80ca9bf6da7a6afdc8
63,248
cpp
C++
data/cpp/1186f05c8157e71e6459bf739025fb14_GameState.cpp
maxim5/code-inspector
14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1
[ "Apache-2.0" ]
5
2018-01-03T06:43:07.000Z
2020-07-30T13:15:29.000Z
data/cpp/1186f05c8157e71e6459bf739025fb14_GameState.cpp
maxim5/code-inspector
14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1
[ "Apache-2.0" ]
null
null
null
data/cpp/1186f05c8157e71e6459bf739025fb14_GameState.cpp
maxim5/code-inspector
14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1
[ "Apache-2.0" ]
2
2019-11-04T02:54:49.000Z
2020-04-24T17:50:46.000Z
/* STARFLIGHT - THE LOST COLONY GameState.cpp - ? Author: ? Date: ? */ #include <math.h> #include <sstream> #include <fstream> #include <exception> #include "env.h" #include "Util.h" #include "GameState.h" #include "Archive.h" #include "sfitems.h" #include "Point2D.h" #include "Game.h" #include "DataMgr.h" #include "QuestMgr.h" #include "ModeMgr.h" #include "Events.h" using namespace std; //OFFICER CLASS Officer::Officer() { Reset(); } Officer::Officer(OfficerType type) { Reset(); officerType = type; } Officer::~Officer() { Reset(); } /** This function increases a crew member's skill in a specific area as a result of performing a task. The name of the skill is passed as a string to avoid our already prodigious use of enums. vcap: otoh, enum are nice because compilers know about them, also you can use the switch construct with them, so i did one anyway. **/ bool Officer::SkillUp(string skill, int amount) { //because of the way we use attributes.extra_variable, all sort of bad things will happen if we allow captain //skills to increase thru this function and the captain is filling several roles. if (this->officerType == OFFICER_CAPTAIN) return false; //level up a specific skill if (skill == "science") { if (this->attributes.science >= 255) return false; if (this->attributes.science + amount >= 255) this->attributes.science = 255; else this->attributes.science += amount; } else if (skill == "engineering") { if (this->attributes.engineering >= 255) return false; if (this->attributes.engineering + amount >= 255) this->attributes.engineering = 255; else this->attributes.engineering += amount; } else if (skill == "navigation") { if (this->attributes.navigation >= 255) return false; if (this->attributes.navigation + amount >= 255) this->attributes.navigation = 255; else this->attributes.navigation += amount; } else if (skill == "communication") { if (this->attributes.communication >= 255) return false; if (this->attributes.communication + amount >= 255) this->attributes.communication = 255; else this->attributes.communication += amount; } else if (skill == "medical") { if (this->attributes.medical >= 255) return false; if (this->attributes.medical + amount >= 255) this->attributes.medical = 255; else this->attributes.medical += amount; } else if (skill == "tactical") { if (this->attributes.tactics >= 255) return false; if (this->attributes.tactics + amount >= 255) this->attributes.tactics = 255; else this->attributes.tactics += amount; } else ASSERT(0); return true; } //same as above but with the Skill enum bool Officer::SkillUp(Skill skill, int amount) { //because of the way we use attributes.extra_variable, all sort of bad things will happen if we allow captain //skills to increase thru this function and the captain is filling several roles. if (this->officerType == OFFICER_CAPTAIN) return false; //level up a specific skill switch (skill){ case SKILL_SCIENCE: if (this->attributes.science >= 255) return false; if (this->attributes.science + amount >= 255) this->attributes.science = 255; else this->attributes.science += amount; break; case SKILL_ENGINEERING: if (this->attributes.engineering >= 255) return false; if (this->attributes.engineering + amount >= 255) this->attributes.engineering = 255; else this->attributes.engineering += amount; break; case SKILL_NAVIGATION: if (this->attributes.navigation >= 255) return false; if (this->attributes.navigation + amount >= 255) this->attributes.navigation = 255; else this->attributes.navigation += amount; break; case SKILL_COMMUNICATION: if (this->attributes.communication >= 255) return false; if (this->attributes.communication + amount >= 255) this->attributes.communication = 255; else this->attributes.communication += amount; break; case SKILL_MEDICAL: if (this->attributes.medical >= 255) return false; if (this->attributes.medical + amount >= 255) this->attributes.medical = 255; else this->attributes.medical += amount; break; case SKILL_TACTICAL: if (this->attributes.tactics >= 255) return false; if (this->attributes.tactics + amount >= 255) this->attributes.tactics = 255; else this->attributes.tactics += amount; break; default: ASSERT(0); } return true; } Officer & Officer::operator =(const Officer &rhs) { name = rhs.name; attributes = rhs.attributes; officerType = rhs.officerType; return *this; } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ OfficerType Officer::GetOfficerType() const { return officerType; } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ string Officer::GetTitle() { string result = ""; switch (officerType) { case OFFICER_CAPTAIN: result = "Captain"; break; case OFFICER_SCIENCE: result = "Sciences"; break; case OFFICER_NAVIGATION: result = "Navigation"; break; case OFFICER_ENGINEER: result = "Engineering"; break; case OFFICER_COMMUNICATION: result = "Communications"; break; case OFFICER_MEDICAL: result = "Medical"; break; case OFFICER_TACTICAL: result = "Tactical"; break; case OFFICER_NONE: default: result = "None"; break; }; return result; } string Officer::GetTitle(OfficerType officerType) { string result = ""; switch (officerType) { case OFFICER_CAPTAIN: result = "Captain"; break; case OFFICER_SCIENCE: result = "Sciences"; break; case OFFICER_NAVIGATION: result = "Navigation"; break; case OFFICER_ENGINEER: result = "Engineering"; break; case OFFICER_COMMUNICATION: result = "Communications"; break; case OFFICER_MEDICAL: result = "Medical"; break; case OFFICER_TACTICAL: result = "Tactical"; break; case OFFICER_NONE: default: result = "None"; break; }; return result; } std::string Officer::GetPreferredProfession() { OfficerType prefferredType = OFFICER_NONE; int highestValue = 0; for (int i=0; i < 7; ++i) { if (attributes[i] > highestValue) { highestValue = attributes[i]; prefferredType = (OfficerType)(i + 2); } } return GetTitle(prefferredType); } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ void Officer::SetOfficerType(int type) { switch(type) { case 0: officerType = OFFICER_NONE; break; case 1: officerType = OFFICER_CAPTAIN; break; case 2: officerType = OFFICER_SCIENCE; break; case 3: officerType = OFFICER_NAVIGATION; break; case 4: officerType = OFFICER_ENGINEER; break; case 5: officerType = OFFICER_COMMUNICATION; break; case 6: officerType = OFFICER_MEDICAL; break; case 7: officerType = OFFICER_TACTICAL; break; } } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ void Officer::SetOfficerType(OfficerType type) { officerType = type; } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ void Officer::Reset() { name = ""; attributes.Reset(); officerType = OFFICER_NONE; isHealing = false; this->lastSkillCheck.SetYear(0); } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ bool Officer::Serialize(Archive &ar) { string ClassName = "Officer"; int Schema = 0; if (ar.IsStoring()) { ar << ClassName; ar << Schema; ar << name; if (!attributes.Serialize(ar)) return false; ar << (int)officerType; } else { Reset(); string LoadClassName; ar >> LoadClassName; if (LoadClassName != ClassName) return false; int LoadSchema; ar >> LoadSchema; if (LoadSchema > Schema) return false; ar >> name; if (!attributes.Serialize(ar)) return false; int tmpi; ar >> tmpi; officerType = (OfficerType)tmpi; } return true; } bool Officer::SkillCheck() { int skill_value = 0; int chance = 0; lastSkillCheck = g_game->gameState->stardate; switch(this->GetOfficerType()){ case OFFICER_SCIENCE: skill_value = this->attributes.getScience(); break; case OFFICER_ENGINEER: skill_value = this->attributes.getEngineering(); break; case OFFICER_MEDICAL: skill_value = this->attributes.getMedical(); break; case OFFICER_NAVIGATION: skill_value = this->attributes.getNavigation(); break; case OFFICER_TACTICAL: skill_value = this->attributes.getTactics(); break; case OFFICER_COMMUNICATION: skill_value = this->attributes.getCommunication(); break; default: return false; } //250+ is guaranteed pass if (skill_value > 250) { return true; } //any below 200 is % chance to pass skill check else if(skill_value > 200) { chance = 90; } else if(skill_value > 150) { chance = 80; } else if(skill_value > 100) { chance = 70; } else if(skill_value > 75) { chance = 60; } else if(skill_value > 50) { chance = 50; } else chance = 25; int roll = rand()%100; return (roll < chance); } bool Officer::CanSkillCheck(){ return ( this->lastSkillCheck < g_game->gameState->stardate ); } void Officer::FakeSkillCheck(){ lastSkillCheck = g_game->gameState->stardate; } std::string Officer::getFirstName() { string::size_type loc = name.find(" ",0); if( loc != string::npos ) //found space, return first name return name.substr(0,loc); else //not found, return whole name return name; } std::string Officer::getLastName() { string::size_type loc = name.find(" ",0); if( loc != string::npos ) //found space, return last name return name.substr(loc+1); else //not found, return whole name return name; } /* * THIS IS KNOWN AS A CODE COMMENT. IT EXPLAINS STUFF. IT HELPS OTHER PROGRAMMERS. */ std::string convertClassTypeToString(int num) { // EDIT: Steven Wirsz - 12/20/10 // Modify missile and laser class from 6 to 9 for Mission #52 switch(num) { case 0: return "None"; case 1: return "Class 1"; case 2: return "Class 2"; case 3: return "Class 3"; case 4: return "Class 4"; case 5: return "Class 5"; case 6: return "Class 6"; case 7: return "Class 7"; case 8: return "Class 8"; case 9: return "Class 9"; } return "Error in convertClassTypeToString()"; } Ship::Ship(): maxEngineClass(0),maxArmorClass(0),maxShieldClass(0),maxLaserClass(0),maxMissileLauncherClass(0) { Reset(); } Ship::~Ship() {} void Ship::initializeRepair() { TRACE("Calling Ship::initializeRepair()\n"); //roll the minerals that will be used for repair for ( int i=0; i < NUM_REPAIR_PARTS; i++){ switch (rand()%5){ case 0: repairMinerals[i] = ITEM_COBALT; break; case 1: repairMinerals[i] = ITEM_MOLYBDENUM; break; case 2: repairMinerals[i] = ITEM_ALUMINUM; break; case 3: repairMinerals[i] = ITEM_TITANIUM; break; case 4: repairMinerals[i] = ITEM_SILICA; break; default: ASSERT(0); } } //set the repair counters so that the player will need to pay the next time he start repairs for ( int i=0; i < NUM_REPAIR_PARTS; i++){ repairCounters[i] = MAX_REPAIR_COUNT; } //stop all repair, if needed partInRepair = PART_NONE; } //accessors std::string Ship::getName() const { return name; } int Ship::getCargoPodCount() const { return cargoPodCount; } int Ship::getEngineClass() const { return engineClass; } int Ship::getShieldClass() const { return shieldClass; } int Ship::getArmorClass() const { return armorClass; } int Ship::getMissileLauncherClass() const { return missileLauncherClass; } int Ship::getTotalSpace() { return cargoPodCount * POD_CAPACITY; } int Ship::getOccupiedSpace() { Item item; int numItems, occupiedSpace = 0; //loop over the inventory to get items count int numstacks = g_game->gameState->m_items.GetNumStacks(); for (int i = 0; i < numstacks; i++){ g_game->gameState->m_items.GetStack(i, item, numItems); //artifacts do not take any space if (!item.IsArtifact()) occupiedSpace+=numItems; } return occupiedSpace; } int Ship::getAvailableSpace() { int freeSpace = getTotalSpace() - getOccupiedSpace(); if (freeSpace < 0) g_game->ShowMessageBoxWindow("Your cargo hold contains more stuff than it's actual capacity!"); return freeSpace; } // EDIT: Steven Wirsz - 12/20/10 // Modify missile and laser class from 6 to 9 for Mission #52 int Ship::getMissileLauncherDamage() { //return missile damage based on class switch(missileLauncherClass) { case 1: return g_game->getGlobalNumber("MISSILE1_DAMAGE"); break; case 2: return g_game->getGlobalNumber("MISSILE2_DAMAGE"); break; case 3: return g_game->getGlobalNumber("MISSILE3_DAMAGE"); break; case 4: return g_game->getGlobalNumber("MISSILE4_DAMAGE"); break; case 5: return g_game->getGlobalNumber("MISSILE5_DAMAGE"); break; case 6: return g_game->getGlobalNumber("MISSILE6_DAMAGE"); break; case 7: return g_game->getGlobalNumber("MISSILE7_DAMAGE"); break; case 8: return g_game->getGlobalNumber("MISSILE8_DAMAGE"); break; case 9: return g_game->getGlobalNumber("MISSILE9_DAMAGE"); break; default: return 0; } } int Ship::getMissileLauncherFiringRate() { //return missile firing rate based on class switch(missileLauncherClass) { case 1: return g_game->getGlobalNumber("MISSILE1_FIRERATE"); break; case 2: return g_game->getGlobalNumber("MISSILE2_FIRERATE"); break; case 3: return g_game->getGlobalNumber("MISSILE3_FIRERATE"); break; case 4: return g_game->getGlobalNumber("MISSILE4_FIRERATE"); break; case 5: return g_game->getGlobalNumber("MISSILE5_FIRERATE"); break; case 6: return g_game->getGlobalNumber("MISSILE6_FIRERATE"); break; case 7: return g_game->getGlobalNumber("MISSILE7_FIRERATE"); break; case 8: return g_game->getGlobalNumber("MISSILE8_FIRERATE"); break; case 9: return g_game->getGlobalNumber("MISSILE9_FIRERATE"); break; default: return 0; } } int Ship::getLaserClass() const { return laserClass; } int Ship::getLaserDamage() { //return laser damage based on class switch(laserClass) { case 1: return g_game->getGlobalNumber("LASER1_DAMAGE"); break; case 2: return g_game->getGlobalNumber("LASER2_DAMAGE"); break; case 3: return g_game->getGlobalNumber("LASER3_DAMAGE"); break; case 4: return g_game->getGlobalNumber("LASER4_DAMAGE"); break; case 5: return g_game->getGlobalNumber("LASER5_DAMAGE"); break; case 6: return g_game->getGlobalNumber("LASER6_DAMAGE"); break; case 7: return g_game->getGlobalNumber("LASER7_DAMAGE"); break; case 8: return g_game->getGlobalNumber("LASER8_DAMAGE"); break; case 9: return g_game->getGlobalNumber("LASER9_DAMAGE"); break; default: return 0; } } int Ship::getLaserFiringRate() { //return laser firing rate based on class switch(laserClass) { case 1: return g_game->getGlobalNumber("LASER1_FIRERATE"); break; case 2: return g_game->getGlobalNumber("LASER2_FIRERATE"); break; case 3: return g_game->getGlobalNumber("LASER3_FIRERATE"); break; case 4: return g_game->getGlobalNumber("LASER4_FIRERATE"); break; case 5: return g_game->getGlobalNumber("LASER5_FIRERATE"); break; case 6: return g_game->getGlobalNumber("LASER6_FIRERATE"); break; case 7: return g_game->getGlobalNumber("LASER7_FIRERATE"); break; case 8: return g_game->getGlobalNumber("LASER8_FIRERATE"); break; case 9: return g_game->getGlobalNumber("LASER9_FIRERATE"); break; default: return 0; } } float Ship::getMaxArmorIntegrity() { switch(armorClass) { case 1: return g_game->getGlobalNumber("ARMOR1_STRENGTH"); break; case 2: return g_game->getGlobalNumber("ARMOR2_STRENGTH"); break; case 3: return g_game->getGlobalNumber("ARMOR3_STRENGTH"); break; case 4: return g_game->getGlobalNumber("ARMOR4_STRENGTH"); break; case 5: return g_game->getGlobalNumber("ARMOR5_STRENGTH"); break; case 6: return g_game->getGlobalNumber("ARMOR6_STRENGTH"); break; default: return 0; } } // ADDED: Robert Caldwell - 10/15/10 // return the percent amount of armor strength remaining // Example: ARMOR1_STRENGTH=120, armorIntegrity=120 // armorIntegrity * 100 = 12000, 12000 / ARMOR1_STRENGTH = 100(%) float Ship::getArmorDisplayPercentage() { return (armorIntegrity * 100.0f) / getMaxArmorIntegrity(); } //shield capacity is the absorbing capacity of the shield, it is different from the //shield generator integrity itself. it will slowly regenerate itself up to a maximum //determined by the shield generator class and current integrity and only decrease as //a result of taking damage during combat. // EDIT: Steven Wirsz - 12/20/10 // Modify Shield class from 6 to 8 for Nyssian special case float Ship::getMaxShieldCapacity() { switch(shieldClass) { case 1: return g_game->getGlobalNumber("SHIELD1_STRENGTH") * shieldIntegrity/100.0f; break; case 2: return g_game->getGlobalNumber("SHIELD2_STRENGTH") * shieldIntegrity/100.0f; break; case 3: return g_game->getGlobalNumber("SHIELD3_STRENGTH") * shieldIntegrity/100.0f; break; case 4: return g_game->getGlobalNumber("SHIELD4_STRENGTH") * shieldIntegrity/100.0f; break; case 5: return g_game->getGlobalNumber("SHIELD5_STRENGTH") * shieldIntegrity/100.0f; break; case 6: return g_game->getGlobalNumber("SHIELD6_STRENGTH") * shieldIntegrity/100.0f; break; case 7: return g_game->getGlobalNumber("SHIELD7_STRENGTH") * shieldIntegrity/100.0f; break; case 8: return g_game->getGlobalNumber("SHIELD8_STRENGTH") * shieldIntegrity/100.0f; break; default: return 0; } } float Ship::getMaxShieldCapacityAtFullIntegrity() { switch(shieldClass) { case 1: return g_game->getGlobalNumber("SHIELD1_STRENGTH"); break; case 2: return g_game->getGlobalNumber("SHIELD2_STRENGTH"); break; case 3: return g_game->getGlobalNumber("SHIELD3_STRENGTH"); break; case 4: return g_game->getGlobalNumber("SHIELD4_STRENGTH"); break; case 5: return g_game->getGlobalNumber("SHIELD5_STRENGTH"); break; case 6: return g_game->getGlobalNumber("SHIELD6_STRENGTH"); break; case 7: return g_game->getGlobalNumber("SHIELD7_STRENGTH"); break; case 8: return g_game->getGlobalNumber("SHIELD8_STRENGTH"); break; default: return 0; } } float Ship::getHullIntegrity() const { return hullIntegrity; } float Ship::getArmorIntegrity() const { return armorIntegrity; } float Ship::getShieldIntegrity() const { return shieldIntegrity; } float Ship::getShieldCapacity() const { return shieldCapacity; } float Ship::getEngineIntegrity() const { return engineIntegrity; } float Ship::getMissileLauncherIntegrity() const { return missileLauncherIntegrity; } float Ship::getLaserIntegrity() const { return laserIntegrity; } //std::string Ship::getCargoPodCountString() const { return convertClassTypeToString(cargoPodCount); } std::string Ship::getEngineClassString() const { return convertClassTypeToString(engineClass); } std::string Ship::getShieldClassString() const { return convertClassTypeToString(shieldClass); } std::string Ship::getArmorClassString() const { return convertClassTypeToString(armorClass); } std::string Ship::getMissileLauncherClassString() const { return convertClassTypeToString(missileLauncherClass); } std::string Ship::getLaserClassString() const { return convertClassTypeToString(laserClass); } bool Ship::HaveEngines() const { return engineClass != NotInstalledType; } #pragma region FUEL_SYSTEM float Ship::getFuel() { return fuelPercentage;} /** Standard consumption occurs in interplanetary space (iterations=1). Interstellar should consume 4x this amount. Planet landing/takeoff should each consume 10x. Remember, 1 cu-m Endurium will fill the fuel tank. **/ void Ship::ConsumeFuel(int iterations) { for (int n=0; n<iterations; n++) { // EDIT: Robert Caldwell - 10/09/2010 //consume fuel 0.1% / engine_class (higher class uses less fuel) // grab the current engine class int engine_class = g_game->gameState->m_ship.getEngineClass(); // calc fuel consumption, if engine class is less than 2, add 1 to increase fuel // efficiency a bit, otherwise add nothing float percent_amount = 0.001f / ((engine_class < 2) ? (engine_class + 1) : (engine_class)); g_game->gameState->m_ship.augFuel(-percent_amount); float fuel = g_game->gameState->m_ship.getFuel(); if (fuel < 0.0f) fuel = 0.0f; } } void Ship::setFuel(float percentage) { fuelPercentage = percentage; capFuel(); } void Ship::augFuel(float percentage) { fuelPercentage += percentage; capFuel(); } void Ship::capFuel() { if (fuelPercentage > 1.0f) fuelPercentage = 1.0f; else if (fuelPercentage < 0.0f) fuelPercentage = 0.0f; } int Ship::getEnduriumOnBoard() { //get amount of endurium in cargo Item endurium; const int ITEM_ENDURIUM = 54; int amount = 0; g_game->gameState->m_items.Get_Item_By_ID(ITEM_ENDURIUM, endurium, amount); return amount; } void Ship::injectEndurium() { if (g_game->g_scrollbox == NULL) { g_game->fatalerror("Ship::injectEndurium: g_scrollbox is null"); return; } //check endurium amount int number_of_endurium = getEnduriumOnBoard(); if(number_of_endurium >= 1) { //reduce endurium number_of_endurium--; g_game->gameState->m_items.RemoveItems(54, 1); g_game->printout(g_game->g_scrollbox, "Consuming Endurium crystal... We have " + Util::ToString(number_of_endurium) + " left.", ORANGE,5000); //use it to fill the fuel tank g_game->gameState->m_ship.augFuel(1.0f); //notify CargoHold to update itself Event e(CARGO_EVENT_UPDATE); g_game->modeMgr->BroadcastEvent(&e); } else g_game->printout(g_game->g_scrollbox, "We have no Endurium!", ORANGE,5000); } #pragma endregion //mutators void Ship::setName(std::string initName) { name = initName; } void Ship::setCargoPodCount(int initCargoPodCount) { cargoPodCount = initCargoPodCount; } void Ship::cargoPodPlusPlus() { cargoPodCount++; } void Ship::cargoPodMinusMinus() { cargoPodCount--; } void Ship::setEngineClass(int initEngineClass) { engineClass = initEngineClass; } void Ship::setShieldClass(int initShieldClass) { shieldClass = initShieldClass; } void Ship::setArmorClass(int initArmorClass) { armorClass = initArmorClass; } void Ship::setMissileLauncherClass(int initMissileLauncherClass) { missileLauncherClass = initMissileLauncherClass; } void Ship::setLaserClass(int initLaserClass) { laserClass = initLaserClass; } void Ship::setHullIntegrity(float value) { if (value < 0.0f) value = 0.0f; if (value > 100.0f) value = 100.0f; hullIntegrity = value; } void Ship::augHullIntegrity(float amount) { if (hullIntegrity + amount < 100) setHullIntegrity(hullIntegrity+amount); else setHullIntegrity(100); } void Ship::setArmorIntegrity(float value) { if (value < 0.0f) value = 0.0f; if (value > getMaxArmorIntegrity()) value = getMaxArmorIntegrity(); armorIntegrity = value; } void Ship::augArmorIntegrity(float amount) { if (armorIntegrity + amount < 100) setArmorIntegrity(armorIntegrity+amount); else setArmorIntegrity(100); } void Ship::setShieldIntegrity(float value) { if (value < 0.0f) value = 0.0f; if (value > 100.0f) value = 100.0f; shieldIntegrity = value; } void Ship::augShieldIntegrity(float amount) { if (shieldIntegrity + amount < 100) setShieldIntegrity(shieldIntegrity+amount); else setShieldIntegrity(100); } void Ship::setShieldCapacity(float value) { if (value < 0.0f) value = 0.0f; if (value > getMaxShieldCapacity()) value = getMaxShieldCapacity(); shieldCapacity = value; } void Ship::augShieldCapacity(float amount) { if (shieldCapacity + amount < 100) setShieldCapacity(shieldCapacity+amount); else setShieldCapacity(100); } void Ship::setEngineIntegrity(float value) { if (value < 0.0f) value = 0.0f; if (value > 100.0f) value = 100.0f; engineIntegrity = value; } void Ship::augEngineIntegrity(float amount) { if (engineIntegrity + amount < 100) setEngineIntegrity(engineIntegrity+amount); else setEngineIntegrity(100); } void Ship::setMissileLauncherIntegrity(float value) { if (value < 0.0f) value = 0.0f; if (value > 100.0f) value = 100.0f; missileLauncherIntegrity = value; } void Ship::augMissileLauncherIntegrity(float amount) { if (missileLauncherIntegrity + amount < 100) setMissileLauncherIntegrity(missileLauncherIntegrity+amount); else setMissileLauncherIntegrity(100); } void Ship::setLaserIntegrity(float value) { if (value < 0.0f) value = 0.0f; if (value > 100.0f) value = 100.0f; laserIntegrity = value; } void Ship::augLaserIntegrity(float amount) { if (laserIntegrity + amount < 100) setLaserIntegrity(laserIntegrity+amount); else setLaserIntegrity(100); } void Ship::setMaxEngineClass(int engineClass) { ASSERT(engineClass >= 1 && engineClass <= 6); maxEngineClass = engineClass; } void Ship::setMaxArmorClass(int armorClass) { ASSERT(armorClass >= 1 && armorClass <= 6); maxArmorClass = armorClass; } // EDIT: Steven Wirsz - 12/20/10 // Modify Shield class from 6 to 8 for Nyssian special case void Ship::setMaxShieldClass(int shieldClass) { ASSERT(shieldClass >= 1 && shieldClass <= 8); maxShieldClass = shieldClass; } // EDIT: Steven Wirsz - 12/20/10 // Modify missile and laser class from 6 to 9 for Mission #52 void Ship::setMaxLaserClass(int laserClass) { ASSERT(laserClass >= 1 && laserClass <= 9); maxLaserClass = laserClass; } void Ship::setMaxMissileLauncherClass(int missileLauncherClass) { ASSERT(missileLauncherClass >= 1 && missileLauncherClass <= 9); maxMissileLauncherClass = missileLauncherClass; } void Ship::SendDistressSignal() { //calculate cost of rescue Point2D starport_pos(15553,13244); double distance = Point2D::Distance( g_game->gameState->player->posHyperspace, starport_pos ); double cost = ( 5000 + (distance * 10.0) ); string com = g_game->gameState->officerCom->getFirstName() + "-> "; string message = "Myrrdan Port Authority has dispatched a tow ship to bring us in. "; message += "The cost of the rescue is " + Util::ToString( cost ) + " MU."; g_game->ShowMessageBoxWindow(message, 500, 300, BLUE, 1024/2, 768/2, true, false); //charge player's account for the tow g_game->gameState->m_credits -= cost; //return to starport g_game->setVibration(0); g_game->modeMgr->LoadModule(MODULE_PORT); } //specials void Ship::Reset() { /* These properties are set in ModuleCaptainCreation based on profession NOTE: Actually ModuleCaptainCreation will call this function at the end of the creation process so the values set here are the definitive ones. Presumably this was not the original purpose of this function but it was thereafter hijacked to override ModuleCaptainCreation. */ //name = "Hyperion"; cargoPodCount = 0; engineClass = 0; //this will be upgraded with a tutorial mission shieldClass = 0; armorClass = 0; missileLauncherClass = 0; laserClass = 0; hullIntegrity = 100; armorIntegrity = 0; shieldIntegrity = 0; engineIntegrity = 100; missileLauncherIntegrity = 0; laserIntegrity = 0; hasTV =true; fuelPercentage =1.0f; /* These properties are not stored on disk; they must be recalculated at captain creation and at savegame load NOTE: we can't actually reset them here or they will override the one set in captain creation. */ //maxEngineClass = 0; //maxArmorClass = 0; //maxShieldClass = 0; //maxLaserClass = 0; //maxMissileLauncherClass = 0; } void Ship::RunDiagnostic() { //verify that all ship components are valid? } bool Ship::Serialize(Archive& ar) { string ClassName = "Ship"; int Schema = 0; if (ar.IsStoring()) { ar << ClassName; ar << Schema; ar << name; ar << cargoPodCount; ar << engineClass; ar << shieldClass; ar << armorClass; ar << missileLauncherClass; ar << laserClass; ar << hullIntegrity; ar << armorIntegrity; ar << shieldIntegrity; ar << engineIntegrity; ar << missileLauncherIntegrity; ar << laserIntegrity; ar << hasTV; ar << fuelPercentage; } else { Reset(); string LoadClassName; ar >> LoadClassName; if (LoadClassName != ClassName) return false; int LoadSchema; ar >> LoadSchema; if (LoadSchema > Schema) return false; ar >> name; ar >> cargoPodCount; ar >> engineClass; ar >> shieldClass; ar >> armorClass; ar >> missileLauncherClass; ar >> laserClass; ar >> hullIntegrity; ar >> armorIntegrity; ar >> shieldIntegrity; ar >> engineIntegrity; ar >> missileLauncherIntegrity; ar >> laserIntegrity; ar >> hasTV; ar >> fuelPercentage; } //we used to allow shieldIntegrity > 100.0f, but now that we distinguish between shield integrity and capacity, //integrity can't be greater than 100 anymore. if (shieldIntegrity > 100.0f) shieldIntegrity = 100.0f; return true; } Ship & Ship::operator =(const Ship &rhs) { if (this == &rhs) return *this; name = rhs.name; cargoPodCount = rhs.cargoPodCount; engineClass = rhs.engineClass; shieldClass = rhs.shieldClass; armorClass = rhs.armorClass; laserClass = rhs.laserClass; missileLauncherClass = rhs.missileLauncherClass; maxEngineClass = rhs.maxEngineClass; maxShieldClass = rhs.maxShieldClass; maxArmorClass = rhs.maxArmorClass; maxLaserClass = rhs.maxLaserClass; maxMissileLauncherClass = rhs.maxMissileLauncherClass; hullIntegrity = rhs.hullIntegrity; engineIntegrity = rhs.engineIntegrity; shieldIntegrity = rhs.shieldIntegrity; shieldCapacity = rhs.shieldCapacity; armorIntegrity = rhs.armorIntegrity; laserIntegrity = rhs.laserIntegrity; missileLauncherIntegrity = rhs.missileLauncherIntegrity; hasTV = rhs.hasTV; fuelPercentage = rhs.fuelPercentage; partInRepair = rhs.partInRepair; for (int i=0; i<NUM_REPAIR_PARTS; i++){ repairMinerals[i] = rhs.repairMinerals[i]; repairCounters[i] = rhs.repairCounters[i]; } return *this; } void Ship::damageRandomSystemOrCrew(int odds, int mindamage, int maxdamage) { if (Util::Random(1,100) > odds) return; float amount; // int health; int damage = Util::Random(mindamage,maxdamage); int system = Util::Random(0,4); //0=hull,1=laser,2=missile,3=shield,4=engine,5=crew switch(system) { case 0: //damage the hull amount = getHullIntegrity(); if (amount > 0) { amount -= damage; if (amount < 0) { amount = 0; g_game->printout(g_game->g_scrollbox,"Ship's Hull has been destroyed.",RED,1000); } } else g_game->printout(g_game->g_scrollbox, "Ship's Hull has been breached!",YELLOW,1000); setHullIntegrity(amount); break; case 1: //damage the laser amount = getLaserIntegrity(); if (amount > 1) { amount -= damage; if (amount < 1) { amount = 1; //setLaserClass(0); //this is too harsh! g_game->printout(g_game->g_scrollbox, "Your laser has been heavily damaged!",RED,1000); } else g_game->printout(g_game->g_scrollbox, "Laser is sustaining damage.",YELLOW,1000); setLaserIntegrity(amount); } break; case 2: //damage missile launcher amount = getMissileLauncherIntegrity(); if (amount > 1) { amount -= damage; if (amount < 1) { amount = 1; //setMissileLauncherClass(0); g_game->printout(g_game->g_scrollbox, "The missile launcher has been heavily damaged!",RED,1000); } else g_game->printout(g_game->g_scrollbox,"Missile launcher is sustaining damage.",YELLOW,1000); setMissileLauncherIntegrity(amount); } break; case 3: //damage shield generator amount = getShieldIntegrity(); if (amount > 1) { amount -= damage; if (amount < 1) { amount = 1; //setShieldClass(0); g_game->printout(g_game->g_scrollbox,"The shield generator has been heavily damaged!",RED,1000); } else g_game->printout(g_game->g_scrollbox,"Shield generator is sustaining damage.",YELLOW,1000); setShieldIntegrity(amount); } break; case 4: //damage engine amount = getEngineIntegrity(); if (amount > 1) { amount -= damage; if (amount < 1) { amount = 1; //setEngineClass(0); g_game->printout(g_game->g_scrollbox,"The engine has been heavily damaged!",RED,1000); } else g_game->printout(g_game->g_scrollbox,"Engine is sustaining damage.",YELLOW,1000); setEngineIntegrity(amount); } break; } } //ATTRIBUTES CLASS Attributes::Attributes() { Reset(); } Attributes::~Attributes() { Reset(); } int& Attributes::operator [] (int i) { static int Err = -1; switch (i) { case 0: return science; break; case 1: return navigation; break; case 2: return engineering; break; case 3: return communication; break; case 4: return medical; break; case 5: return tactics; break; /* 6 & 7 were reversed in the artwork so I'm just reversing them here if this introduces any weird bugs in the game we'll deal with it */ case 7: //6: return durability; break; case 6: //7: return learnRate; break; default: return Err; break; } } Attributes & Attributes::operator =(const Attributes &rhs) { durability = rhs.durability; learnRate = rhs.learnRate; science = rhs.science; navigation = rhs.navigation; tactics = rhs.tactics; engineering = rhs.engineering; communication = rhs.communication; medical = rhs.medical; vitality = rhs.vitality; extra_variable = rhs.extra_variable; return *this; } //accessors int Attributes::getDurability() const { return durability; } int Attributes::getLearnRate() const { return learnRate; } int Attributes::getScience() const { return science; } int Attributes::getNavigation() const { return navigation; } int Attributes::getTactics() const { return tactics; } int Attributes::getEngineering() const { return engineering; } int Attributes::getCommunication() const { return communication; } int Attributes::getMedical() const { return medical; } float Attributes::getVitality() const { return vitality; } //mutators void Attributes::setDurability(int initDurability) { durability = initDurability; } void Attributes::setLearnRate(int initLearnRate) { learnRate = initLearnRate; } void Attributes::setScience(int initScience) { science = initScience; } void Attributes::setNavigation(int initNavigation) { navigation = initNavigation; } void Attributes::setTactics(int initTactics) { tactics = initTactics; } void Attributes::setEngineering(int initEngineering) { engineering = initEngineering; } void Attributes::setCommunication(int initCommunication) { communication = initCommunication; } void Attributes::setMedical(int initMedical) { medical = initMedical;} void Attributes::setVitality(float initVital) { vitality = initVital; capVitality();} void Attributes::augVitality(float value) { vitality += value; capVitality();} void Attributes::capVitality() { if(vitality > 100){vitality = 100;} if(vitality < 0){vitality = 0;} } void Attributes::Reset() { durability = 0; learnRate = 0; science = 0; navigation = 0; tactics = 0; engineering = 0; communication = 0; medical = 0; vitality = 100; extra_variable = 0; } bool Attributes::Serialize(Archive& ar) { string ClassName = "Attributes"; int Schema = 0; if (ar.IsStoring()) { ar << ClassName; ar << Schema; ar << durability; ar << learnRate; ar << science; ar << navigation; ar << tactics; ar << engineering; ar << communication; ar << medical; ar << vitality; ar << extra_variable; } else { Reset(); string LoadClassName; ar >> LoadClassName; if (LoadClassName != ClassName) return false; int LoadSchema; ar >> LoadSchema; if (LoadSchema > Schema) return false; ar >> durability; ar >> learnRate; ar >> science; ar >> navigation; ar >> tactics; ar >> engineering; ar >> communication; ar >> medical; ar >> vitality; ar >> extra_variable; } return true; } //GAMESTATE CLASS GameState::GameState(): m_items(*new Items), player(NULL), officerCap(NULL), officerSci(NULL), officerNav(NULL), officerTac(NULL), officerEng(NULL), officerCom(NULL), officerDoc(NULL) {} GameState::~GameState() { delete &m_items; delete player; player = NULL; delete officerCap; officerCap = NULL; delete officerSci; officerSci = NULL; delete officerNav; officerNav = NULL; delete officerTac; officerTac = NULL; delete officerEng; officerEng = NULL; delete officerCom; officerCom = NULL; delete officerDoc; officerDoc = NULL; for (int i=0; i < (int)m_unemployedOfficers.size(); ++i) { delete m_unemployedOfficers[i]; m_unemployedOfficers[i] = NULL; } m_unemployedOfficers.clear(); } GameState & GameState::operator=(const GameState &rhs) { for (int i = 0; i < NUM_ALIEN_RACES; i++) alienAttitudes[i] = rhs.alienAttitudes[i]; playerPosture = rhs.playerPosture; m_gameTimeSecs = rhs.m_gameTimeSecs; stardate = rhs.stardate; m_captainSelected = rhs.m_captainSelected; m_profession = rhs.m_profession; m_credits = rhs.m_credits; m_items = rhs.m_items; delete player; player = new PlayerInfo; *player = *rhs.player; m_ship = rhs.m_ship; fluxSeed = rhs.fluxSeed; m_currentSelectedOfficer = rhs.m_currentSelectedOfficer; for (int i=0; i < (int)m_unemployedOfficers.size(); ++i) { delete m_unemployedOfficers[i]; m_unemployedOfficers[i] = NULL; } m_unemployedOfficers.clear(); for (int i = 0; i < (int)rhs.m_unemployedOfficers.size(); i++) { Officer * newOfficer = new Officer; *newOfficer = *rhs.m_unemployedOfficers[i]; m_unemployedOfficers.push_back(newOfficer); } delete officerCap; officerCap = new Officer(); *officerCap = *rhs.officerCap; delete officerSci; officerSci = new Officer(); *officerSci = *rhs.officerSci; delete officerNav; officerNav = new Officer(); *officerNav = *rhs.officerNav; delete officerTac; officerTac = new Officer(); *officerTac = *rhs.officerTac; delete officerEng; officerEng = new Officer(); *officerEng = *rhs.officerEng; delete officerCom; officerCom = new Officer(); *officerCom = *rhs.officerCom; delete officerDoc; officerDoc = new Officer(); *officerDoc = *rhs.officerDoc; TotalCargoStacks = rhs.TotalCargoStacks; defaultShipCargoSize = rhs.defaultShipCargoSize; m_baseGameTimeSecs = rhs.m_baseGameTimeSecs; m_gameTimeSecs = rhs.m_gameTimeSecs; activeQuest = rhs.activeQuest; storedValue = rhs.storedValue; currentModeWhenGameSaved= rhs.currentModeWhenGameSaved; dirty= false; return *this; } void PlayerInfo::Reset() { m_scanner = false; m_previous_scanner_state = false; m_bHasHyperspacePermit = true; m_bHasOverdueLoan = false; currentStar = 2; currentPlanet = 450; controlPanelMode = 0; // ????? NOT SURE WHAT TO SET THIS TO posHyperspace.x = g_game->getGlobalNumber("PLAYER_HYPERSPACE_START_X"); posHyperspace.y = g_game->getGlobalNumber("PLAYER_HYPERSPACE_START_Y"); posSystem.x = g_game->getGlobalNumber("PLAYER_SYSTEM_START_X"); posSystem.y = g_game->getGlobalNumber("PLAYER_SYSTEM_START_Y"); posPlanet.x = 0; //randomized in PlanetSurface module posPlanet.y = 0; posStarport.x = g_game->getGlobalNumber("PLAYER_STARPORT_START_X"); posStarport.y = g_game->getGlobalNumber("PLAYER_STARPORT_START_Y"); posCombat.x = 0; posCombat.y = 0; m_is_lost = false; alive = true; } std::string PlayerInfo::getAlienRaceName(int race) { switch(race) { case 1: return "Pirate"; break; case 2: return "Elowan"; break; case 3: return "Spemin"; break; case 4: return "Thrynn"; break; case 5: return "Barzhon"; break; case 6: return "Nyssian"; break; case 7: return "Tafel"; break; case 8: return "Minex"; break; case 9: return "Coalition"; break; default: return "None"; break; } return ""; } std::string PlayerInfo::getAlienRaceName(AlienRaces race) { return getAlienRaceName( (int) race ); } std::string PlayerInfo::getAlienRaceNamePlural(AlienRaces race) { switch(race) { case ALIEN_ELOWAN: return "Elowan"; break; case ALIEN_SPEMIN: return "Spemin"; break; case ALIEN_THRYNN: return "Thrynn"; break; case ALIEN_BARZHON: return "Barzhon"; break; case ALIEN_NYSSIAN: return "Nyssian"; break; case ALIEN_TAFEL: return "Tafel"; break; case ALIEN_MINEX: return "Minex"; break; case ALIEN_COALITION: return "Coalition"; break; case ALIEN_PIRATE: return "Pirates"; break; default: return "None"; break; } return ""; } bool PlayerInfo::Serialize(Archive& ar) { string ClassName = "PlayerInfo"; int Schema = 0; if (ar.IsStoring()) { ar << ClassName; ar << Schema; ar << m_scanner; ar << m_previous_scanner_state; ar << m_bHasHyperspacePermit; ar << m_bHasOverdueLoan; ar << currentStar; ar << currentPlanet; ar << controlPanelMode; if (!posHyperspace.Serialize(ar)) return false; if (!posSystem.Serialize(ar)) return false; if (!posPlanet.Serialize(ar)) return false; if (!posStarport.Serialize(ar)) return false; if (!posCombat.Serialize(ar)) return false; } else { string LoadedClassName; ar >> LoadedClassName; if (LoadedClassName != ClassName) return false; int LoadedSchema; ar >> LoadedSchema; if (LoadedSchema > Schema) return false; ar >> m_scanner; ar >> m_previous_scanner_state; ar >> m_bHasHyperspacePermit; ar >> m_bHasOverdueLoan; ar >> currentStar; ar >> currentPlanet; ar >> controlPanelMode; if (!posHyperspace.Serialize(ar)) return false; if (!posSystem.Serialize(ar)) return false; if (!posPlanet.Serialize(ar)) return false; if (!posStarport.Serialize(ar)) return false; if (!posCombat.Serialize(ar)) return false; } return true; } PlayerInfo& PlayerInfo::operator=(const PlayerInfo& rhs) { if (this == &rhs) return *this; m_scanner = rhs.m_scanner; m_previous_scanner_state = rhs.m_previous_scanner_state; m_bHasHyperspacePermit = rhs.m_bHasHyperspacePermit; m_bHasOverdueLoan = rhs.m_bHasOverdueLoan; currentStar = rhs.currentStar; currentPlanet = rhs.currentPlanet; controlPanelMode = rhs.controlPanelMode; posHyperspace = rhs.posHyperspace; posSystem = rhs.posSystem; posPlanet = rhs.posPlanet; posStarport = rhs.posStarport; posCombat = rhs.posCombat; return *this; } /* * This resets the GameState to the default values */ void GameState::Reset() { // EDIT: Steven Wirsz - 12/20/10 // Tweak initial attitudes to better represent the initial communication postures //initialize alien race attitudes alienAttitudes[ALIEN_ELOWAN] = 40; alienAttitudes[ALIEN_SPEMIN] = 70; alienAttitudes[ALIEN_THRYNN] = 50; alienAttitudes[ALIEN_BARZHON] = 40; alienAttitudes[ALIEN_NYSSIAN] = 60; alienAttitudes[ALIEN_TAFEL] = 10; alienAttitudes[ALIEN_MINEX] = 50; alienAttitudes[ALIEN_COALITION] = 40; alienAttitudes[ALIEN_PIRATE] = 10; //start alien attitude update time alienAttitudeUpdate = g_game->globalTimer.getTimer(); //initialize player's posture playerPosture = "friendly"; m_gameTimeSecs = 0; m_baseGameTimeSecs = 0; stardate.Reset(); //altered to use current object. //Stardate sdNew; //g_game->gameState->stardate = sdNew; setCaptainSelected(false); setProfession(PROFESSION_MILITARY); //player starts with nothing and given things via missions setCredits(0); m_items.Reset(); //initialize player data if (player != NULL) { delete player; player = NULL; } player = new PlayerInfo; player->Reset(); //This returns the ship's values to the defaults m_ship.Reset(); //Those values are not used anywhere anymore but must be conserved to preserve savegame compatibility defaultShipCargoSize = 0; TotalCargoStacks = 0; init_fluxSeed(); m_currentSelectedOfficer = OFFICER_CAPTAIN; for (int i=0; i < (int)m_unemployedOfficers.size(); ++i) { delete m_unemployedOfficers[i]; m_unemployedOfficers[i] = NULL; } m_unemployedOfficers.clear(); if (officerCap != NULL) { delete officerCap; officerCap = NULL; } officerCap = new Officer(OFFICER_CAPTAIN); if (officerSci != NULL) { delete officerSci; officerSci = NULL; } officerSci = new Officer(OFFICER_SCIENCE); if (officerNav != NULL) { delete officerNav; officerNav = NULL; } officerNav = new Officer(OFFICER_NAVIGATION); if (officerTac != NULL) { delete officerTac; officerTac = NULL; } officerTac = new Officer(OFFICER_TACTICAL); if (officerEng != NULL) { delete officerEng; officerEng = NULL; } officerEng = new Officer(OFFICER_ENGINEER); if (officerCom != NULL) { delete officerCom; officerCom = NULL; } officerCom = new Officer(OFFICER_COMMUNICATION); if (officerDoc != NULL) { delete officerDoc; officerDoc = NULL; } officerDoc = new Officer(OFFICER_MEDICAL); //////////////////////////////////////////////////////////////////////////// // RANDOM OFFICER POPULATION - BEGIN // * These data should be overwritten when the crew is loaded from a savegame file // * or replaced. This should eventually be removed. //////////////////////////////////////////////////////////////////////////// /* setCaptainSelected(true); //initialize profession (should be needed only during testing) this->m_profession = PROFESSION_MILITARY; if (officerCap != NULL) { delete officerCap; officerCap = NULL; } //create the captain officerCap = new Officer(OFFICER_CAPTAIN); officerCap->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerCap->attributes[i] = Util::Random(10,200); officerCap->attributes[6] = Util::Random(1,25); officerCap->attributes[7] = Util::Random(1,25); if (officerSci != NULL) { delete officerSci; officerSci = NULL; } //create the science officer officerSci = new Officer(OFFICER_SCIENCE); officerSci->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerSci->attributes[i] = Util::Random(10,200); officerSci->attributes[6] = Util::Random(1,25); officerSci->attributes[7] = Util::Random(1,25); if (officerNav != NULL) { delete officerNav; officerNav = NULL; } //create the navigation officer officerNav = new Officer(OFFICER_NAVIGATION); officerNav->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerNav->attributes[i] = Util::Random(10,200); officerNav->attributes[6] = Util::Random(1,25); officerNav->attributes[7] = Util::Random(1,25); if (officerEng != NULL) { delete officerEng; officerEng = NULL; } //create the engineering officer officerEng = new Officer(OFFICER_ENGINEER); officerEng->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerEng->attributes[i] = Util::Random(10,200); officerEng->attributes[6] = Util::Random(1,25); officerEng->attributes[7] = Util::Random(1,25); if (officerCom != NULL) { delete officerCom; officerCom = NULL; } //create the communications officer officerCom = new Officer(OFFICER_COMMUNICATION); officerCom->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerCom->attributes[i] = Util::Random(10,200); officerCom->attributes[6] = Util::Random(1,25); officerCom->attributes[7] = Util::Random(1,25); if (officerDoc != NULL) { delete officerDoc; officerDoc = NULL; } //create the medical officer officerDoc = new Officer(OFFICER_MEDICAL); officerDoc->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerDoc->attributes[i] = Util::Random(10,200); officerDoc->attributes[6] = Util::Random(1,25); officerDoc->attributes[7] = Util::Random(1,25); if (officerTac != NULL) { delete officerTac; officerTac = NULL; } //create the tactical officer officerTac = new Officer(OFFICER_TACTICAL); officerTac->name = g_game->dataMgr->GetRandMixedName(); for (int i=0; i < 6; i++) officerTac->attributes[i] = Util::Random(10,200); officerTac->attributes[6] = Util::Random(1,25); officerTac->attributes[7] = Util::Random(1,25); */ //////////////////////////////////////////////////////////////////////////// // // RANDOM OFFICER POPULATION - END // //////////////////////////////////////////////////////////////////////////// //initial tactical properties shieldStatus = false; weaponStatus = false; currentModeWhenGameSaved = ""; //current stage of the game, INITIAL=1,VIRUS=2,WAR=3,ANCIENTS=4 plotStage = 1; //quest related state variables activeQuest = 1; // -1; bug fix storedValue= -1; questCompleted = false; firstTimeVisitor = true; } /* * This function will either serialize the current game into the Archive or pull from it depending on whether * the archive is flagged for storing. */ bool GameState::Serialize(Archive& ar) { string ClassName = "GameState"; int Schema = 0; Schema = 1; // dsc - added currentModeWhenGameSaved if (ar.IsStoring()) { ar << ClassName; ar << Schema; ar << (int)NUM_ALIEN_RACES; for (int i = 0; i < NUM_ALIEN_RACES; i++) ar << alienAttitudes[i]; ar << playerPosture; //the base game time is added to the current ms timer to get an accurate //date (from gameTimeSecs), so we save gameTimeSecs, but read back into //baseGameTimeSecs: //ar << (double)(m_baseGameTimeSecs + m_gameTimeSecs); //m_gameTimeSecs already includes base. ar << (double) m_gameTimeSecs; if (!stardate.Serialize(ar)) return false; ar << m_captainSelected; ar << (int)m_profession; ar << m_credits; if (!m_items.Serialize(ar)) return false; if (!player->Serialize(ar)) return false; if (!m_ship.Serialize(ar)) return false; ar << fluxSeed; ar << (int)m_currentSelectedOfficer; ar << (int)m_unemployedOfficers.size(); for (vector<Officer*>::iterator i = m_unemployedOfficers.begin(); i != m_unemployedOfficers.end(); ++i) { if (!(*i)->Serialize(ar)) return false; } //serialize the officers/crew int numOfficers = 7; ar << numOfficers; if (!officerCap->Serialize(ar)) return false; if (!officerSci->Serialize(ar)) return false; if (!officerNav->Serialize(ar)) return false; if (!officerEng->Serialize(ar)) return false; if (!officerCom->Serialize(ar)) return false; if (!officerTac->Serialize(ar)) return false; if (!officerDoc->Serialize(ar)) return false; ar << TotalCargoStacks; ar << defaultShipCargoSize; currentModeWhenGameSaved = g_game->modeMgr->GetCurrentModuleName(); ar << currentModeWhenGameSaved; //save quest data ar << activeQuest; //storedValue keeps track of current quest objective //ar << g_game->questMgr->storedValue; ar << storedValue; } // READING ARCHIVE INSTEAD OF STORING else { Reset(); string LoadClassName; ar >> LoadClassName; if (LoadClassName != ClassName) return false; int LoadSchema; ar >> LoadSchema; if (LoadSchema > Schema) return false; int LoadedNumAlienRaces; ar >> LoadedNumAlienRaces; for (int i = 0; (i < LoadedNumAlienRaces) && (i < NUM_ALIEN_RACES); i++) ar >> alienAttitudes[i]; ar >> playerPosture; //the base game time is added to the current ms timer to get an accurate //date (from gameTimeSecs), so we save gameTimeSecs, but read back into //baseGameTimeSecs: ar >> m_baseGameTimeSecs; if (!stardate.Serialize(ar)) return false; ar >> m_captainSelected; int tmpi; ar >> tmpi; m_profession = (ProfessionType)tmpi; ar >> m_credits; if (!m_items.Serialize(ar)) return false; if (!player->Serialize(ar)) return false; if (!m_ship.Serialize(ar)) return false; ar >> fluxSeed; int LoadedCurrentlySelectedOfficer; ar >> LoadedCurrentlySelectedOfficer; m_currentSelectedOfficer = (OfficerType)LoadedCurrentlySelectedOfficer; int LoadedNumUnemployedOfficers; ar >> LoadedNumUnemployedOfficers; for (int i = 0; i < LoadedNumUnemployedOfficers; i++) { Officer * newOfficer = new Officer; if (!newOfficer->Serialize(ar)) { delete newOfficer; return false; } m_unemployedOfficers.push_back(newOfficer); } //Load Officers int LoadedNumOfficers; ar >> LoadedNumOfficers; if (!officerCap->Serialize(ar)) return false; if (!officerSci->Serialize(ar)) return false; if (!officerNav->Serialize(ar)) return false; if (!officerEng->Serialize(ar)) return false; if (!officerCom->Serialize(ar)) return false; if (!officerTac->Serialize(ar)) return false; if (!officerDoc->Serialize(ar)) return false; ar >> TotalCargoStacks; ar >> defaultShipCargoSize; if (LoadSchema >= 1) ar >> currentModeWhenGameSaved; //load quest data ar >> activeQuest; ar >> storedValue; //ar >> g_game->questMgr->storedValue; } return true; } std::string GameState::currentSaveGameFile; #define GAME_MAGIC 0xAAFFAAFF #define GAME_STRING "StarflightTLC-SaveGame" #define GAME_SCHEMA 0 bool GameState::SaveGame(std::string fileName) { currentSaveGameFile = fileName; Archive ar; if (!ar.Open(fileName,Archive::AM_STORE)) return false; int GameMagic = GAME_MAGIC; ar << GameMagic; string GameString = GAME_STRING; ar << GameString; int GameSchema = GAME_SCHEMA; ar << GameSchema; if (!Serialize(ar)) { ar.Close(); return false; } ar << GameMagic; ar.Close(); return true; } GameState* GameState::ReadGame(std::string fileName) { currentSaveGameFile = fileName; Archive ar; if (!ar.Open(fileName,Archive::AM_LOAD)) { TRACE("*** GameState: Cannot open save game file"); return NULL; } //numeric code uniquely identifying this game's file int LoadedGameMagic; ar >> LoadedGameMagic; if ( (unsigned int) LoadedGameMagic != GAME_MAGIC ) { g_game->message("Invalid save game file"); TRACE("*** GameState: Invalid save game file"); return NULL; } //unique string for this savegame file string LoadedGameString; ar >> LoadedGameString; if (LoadedGameString != GAME_STRING) { g_game->message("Invalid save game file"); TRACE("*** GameState: Invalid save game file"); return NULL; } //schema number--not really needed int LoadedGameSchema = 0; ar >> LoadedGameSchema; if (LoadedGameSchema > GAME_SCHEMA) { TRACE("*** GameState: Incorrect schema in save game file"); return NULL; } GameState * g = new GameState; g->Reset(); if (!g->Serialize(ar)) { TRACE("*** GameState: Error reading save game file"); delete g; ar.Close(); return NULL; } LoadedGameMagic = 0; ar >> LoadedGameMagic; if ( (unsigned int) LoadedGameMagic != GAME_MAGIC ) { TRACE("*** GameState: Error loading save game file"); delete g; ar.Close(); return NULL; } ar.Close(); return g; } GameState * GameState::LoadGame(std::string fileName) { TRACE("\n"); GameState* gs= ReadGame(fileName); if (gs == NULL) {TRACE(" in GameState::LoadGame\n"); return gs; } //message picks up where ReadGame left off. gs->m_captainSelected= true; *g_game->gameState= *gs; //assign to game state. delete gs; //return reference pointer only (to game state). g_game->globalTimer.reset(); //reset the global timer (logic from CaptainsLounge module) //restart the quest mgr if (!g_game->questMgr->Initialize()) g_game->fatalerror("GameState::LoadGame(): Error initializing quest manager"); /* Copy baseGameTimeSecs into the gameTimeSecs (note this could be done on assignment; in order to keep code functions compartmentalized, it is done here along with all other manipulations related to GameState initialization). This assignment is done to avoid issues related to reloading a saved game starting in a time-paused module such as the Captain's Lounge, from another module with unpaused time. (=> baseGameTimeSecs is set using gameTimeSecs, which is assumed to have been previously updated itself from baseGameTimeSecs and the timer ) */ g_game->gameState->setGameTimeSecs(g_game->gameState->getBaseGameTimeSecs()); //Update the quest completion status: g_game->questMgr->getActiveQuest(); int reqCode = g_game->questMgr->questReqCode; int reqType = g_game->questMgr->questReqType; int reqAmt = g_game->questMgr->questReqAmt; g_game->questMgr->VerifyRequirements( reqCode, reqType, reqAmt ); //Set the corresponding plot stage //switch ( g_game->gameState->getActiveQuest() ) { //case 36: g_game->gameState->setPlotStage(2); break; //case 37: g_game->gameState->setPlotStage(3); break; //case 38: case 39: g_game->gameState->setPlotStage(4); break; //default: g_game->gameState->setPlotStage(1); break; //} //Set maximum ship upgrades available given captain profession int maxEngineClass=0, maxShieldClass=0, maxArmorClass=0, maxMissileLauncherClass=0, maxLaserClass=0; switch(g_game->gameState->getProfession()) { case PROFESSION_FREELANCE: maxEngineClass = g_game->getGlobalNumber("PROF_FREELANCE_ENGINE_MAX"); maxShieldClass = g_game->getGlobalNumber("PROF_FREELANCE_SHIELD_MAX"); maxArmorClass = g_game->getGlobalNumber("PROF_FREELANCE_ARMOR_MAX"); maxMissileLauncherClass = g_game->getGlobalNumber("PROF_FREELANCE_MISSILE_MAX"); maxLaserClass = g_game->getGlobalNumber("PROF_FREELANCE_LASER_MAX"); break; case PROFESSION_MILITARY: maxEngineClass = g_game->getGlobalNumber("PROF_MILITARY_ENGINE_MAX"); maxShieldClass = g_game->getGlobalNumber("PROF_MILITARY_SHIELD_MAX"); maxArmorClass = g_game->getGlobalNumber("PROF_MILITARY_ARMOR_MAX"); maxMissileLauncherClass = g_game->getGlobalNumber("PROF_MILITARY_MISSILE_MAX"); maxLaserClass = g_game->getGlobalNumber("PROF_MILITARY_LASER_MAX"); break; case PROFESSION_SCIENTIFIC: maxEngineClass = g_game->getGlobalNumber("PROF_SCIENCE_ENGINE_MAX"); maxShieldClass = g_game->getGlobalNumber("PROF_SCIENCE_SHIELD_MAX"); maxArmorClass = g_game->getGlobalNumber("PROF_SCIENCE_ARMOR_MAX"); maxMissileLauncherClass = g_game->getGlobalNumber("PROF_SCIENCE_MISSILE_MAX"); maxLaserClass = g_game->getGlobalNumber("PROF_SCIENCE_LASER_MAX"); break; default: //cant happen ASSERT(0); } g_game->gameState->m_ship.setMaxEngineClass(maxEngineClass); g_game->gameState->m_ship.setMaxShieldClass(maxShieldClass); g_game->gameState->m_ship.setMaxArmorClass(maxArmorClass); g_game->gameState->m_ship.setMaxMissileLauncherClass(maxMissileLauncherClass); g_game->gameState->m_ship.setMaxLaserClass(maxLaserClass); g_game->gameState->m_ship.setShieldCapacity(g_game->gameState->m_ship.getMaxShieldCapacity()); //Roll random repair minerals and set the repair counters g_game->gameState->m_ship.initializeRepair(); #ifdef DEBUG DumpStats(g_game->gameState); //dump statistics to file. #endif TRACE("Game state loaded successfully\n"); return g_game->gameState; //return gs & leave deletion to caller? } void GameState::AutoSave() { if (currentSaveGameFile.size() == 0) { g_game->ShowMessageBoxWindow("There is no active player savegame file!"); return; } SaveGame(currentSaveGameFile); g_game->ShowMessageBoxWindow("Game state has been saved", 400, 200, GREEN); } void GameState::AutoLoad() { if (currentSaveGameFile.size() == 0) { g_game->ShowMessageBoxWindow("There is no active player savegame file to load!"); return; } GameState* lgs = LoadGame(currentSaveGameFile); //if (lgs != NULL) //logic now handled in LoadGame //{ // lgs->m_captainSelected = true; // *this = *lgs; // delete lgs; //} if (lgs != NULL) g_game->ShowMessageBoxWindow("Game has been restored to last save point", 400, 200, GREEN); else g_game->ShowMessageBoxWindow("Game save file could not be found/opened!", 400, 200, GREEN); if (currentModeWhenGameSaved.size() > 0) { g_game->modeMgr->LoadModule(currentModeWhenGameSaved); return; } } //accessors //Stardate GameState::getStardate() const { return m_stardate; } bool GameState::isCaptainSelected() const { return m_captainSelected; } ProfessionType GameState::getProfession() const { return m_profession; } int GameState::getCredits() const { return m_credits; } string GameState::getProfessionString() { switch (getProfession()) { case PROFESSION_NONE: return "none"; break; case PROFESSION_FREELANCE: return "freelance"; break; case PROFESSION_MILITARY: return "military"; break; case PROFESSION_SCIENTIFIC: return "scientific"; break; case PROFESSION_OTHER: return "other"; break; } return ""; } // Helper function in case some module doesn't like to work directly with explicit officer objects Officer *GameState::getOfficer(int officerType) { switch(officerType) { case OFFICER_CAPTAIN: return officerCap; break; case OFFICER_SCIENCE: return officerSci; break; case OFFICER_NAVIGATION: return officerNav; break; case OFFICER_ENGINEER: return officerEng; break; case OFFICER_COMMUNICATION: return officerCom; break; case OFFICER_MEDICAL: return officerDoc; break; case OFFICER_TACTICAL: return officerTac; break; default: ASSERT(0); } //UNREACHABLE //to keep the compiler happy return NULL; } // Helper function in case some module doesn't like to work directly with explicit officer objects Officer *GameState::getOfficer(std::string officerName) { if (officerName == "CAPTAIN") return officerCap; else if (officerName == "SCIENCE" || officerName == "SCIENCE OFFICER") return officerSci; else if (officerName == "NAVIGATION" || officerName == "NAVIGATOR") return officerNav; else if (officerName == "ENGINEER" || officerName == "ENGINEERING" || officerName == "ENGINEERING OFFICER") return officerEng; else if (officerName == "COMMUNICATION" || officerName == "COMMUNICATIONS") return officerCom; else if (officerName == "MEDICAL" || officerName == "MEDICAL OFFICER" || officerName == "DOCTOR") return officerDoc; else if (officerName == "TACTICAL" || officerName == "TACTICAL
27.643357
143
0.688417
[ "object", "vector" ]
938e4b2d9847c35586b42fd358dfadeafc594d84
3,348
cpp
C++
test/FakeVideoCapturer.cpp
gaoyingie/libmediasoupclient
806a0385f76e953c6e5e12e1a761e3c54c01dc9e
[ "ISC" ]
1
2020-09-21T02:42:47.000Z
2020-09-21T02:42:47.000Z
mediasoup-client/deps/libmediasoupclient/test/FakeVideoCapturer.cpp
ethand91/mediasoup-client-android
9e95fbf90de3037f625cf56ac0fe3605644187d3
[ "MIT" ]
null
null
null
mediasoup-client/deps/libmediasoupclient/test/FakeVideoCapturer.cpp
ethand91/mediasoup-client-android
9e95fbf90de3037f625cf56ac0fe3605644187d3
[ "MIT" ]
1
2022-02-14T07:45:49.000Z
2022-02-14T07:45:49.000Z
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "media/base/fakevideocapturer.h" #include "rtc_base/arraysize.h" namespace cricket { FakeVideoCapturer::FakeVideoCapturer(bool isScreencast) : running_(false), is_screencast_(isScreencast), rotation_(webrtc::kVideoRotation_0) { // Default supported formats. Use ResetSupportedFormats to over write. using cricket::VideoFormat; /* static const VideoFormat formats[] = { {1280, 720, VideoFormat::FpsToInterval(30), cricket::FOURCC_I420}, {640, 480, VideoFormat::FpsToInterval(30), cricket::FOURCC_I420}, {320, 240, VideoFormat::FpsToInterval(30), cricket::FOURCC_I420}, {160, 120, VideoFormat::FpsToInterval(30), cricket::FOURCC_I420}, {1280, 720, VideoFormat::FpsToInterval(60), cricket::FOURCC_I420}, }; */ static const VideoFormat formats[] = { { 1920, 1080, cricket::VideoFormat::FpsToInterval(60), cricket::FOURCC_I420 }, { 1920, 1080, cricket::VideoFormat::FpsToInterval(30), cricket::FOURCC_I420 }, { 1280, 720, cricket::VideoFormat::FpsToInterval(60), cricket::FOURCC_I420 }, { 1280, 720, cricket::VideoFormat::FpsToInterval(30), cricket::FOURCC_I420 }, { 960, 540, cricket::VideoFormat::FpsToInterval(60), cricket::FOURCC_I420 }, { 960, 540, cricket::VideoFormat::FpsToInterval(30), cricket::FOURCC_I420 }, { 640, 480, cricket::VideoFormat::FpsToInterval(60), cricket::FOURCC_I420 }, { 640, 480, cricket::VideoFormat::FpsToInterval(30), cricket::FOURCC_I420 } }; ResetSupportedFormats({ formats, &formats[arraysize(formats)] }); } FakeVideoCapturer::FakeVideoCapturer() : FakeVideoCapturer(false) {} FakeVideoCapturer::~FakeVideoCapturer() { SignalDestroyed(this); } void FakeVideoCapturer::ResetSupportedFormats( const std::vector<cricket::VideoFormat>& formats) { SetSupportedFormats(formats); } bool FakeVideoCapturer::CaptureFrame() { return GetCaptureFormat() != nullptr; } bool FakeVideoCapturer::CaptureCustomFrame(int /*width*/, int /*height*/) { return true; } bool FakeVideoCapturer::CaptureFrame(const webrtc::VideoFrame& /*frame*/) { return running_; } cricket::CaptureState FakeVideoCapturer::Start( const cricket::VideoFormat& format) { running_ = true; SetCaptureFormat(&format); SetCaptureState(cricket::CS_RUNNING); return cricket::CS_RUNNING; } void FakeVideoCapturer::Stop() { running_ = false; SetCaptureFormat(nullptr); SetCaptureState(cricket::CS_STOPPED); } bool FakeVideoCapturer::IsRunning() { return running_; } bool FakeVideoCapturer::IsScreencast() const { return is_screencast_; } bool FakeVideoCapturer::GetPreferredFourccs(std::vector<uint32_t>* fourccs) { fourccs->push_back(cricket::FOURCC_I420); fourccs->push_back(cricket::FOURCC_MJPG); return true; } void FakeVideoCapturer::SetRotation(webrtc::VideoRotation rotation) { rotation_ = rotation; } webrtc::VideoRotation FakeVideoCapturer::GetRotation() { return rotation_; } } // namespace cricket
31.28972
87
0.737455
[ "vector" ]
9397cdcd8c5c00b1c410bde0e12a286a52b90363
575
cpp
C++
src/engine/dictionary.cpp
bec-ca/botle
dc85470c71c725bdb1ee7d36d03d10341070f73d
[ "Unlicense" ]
2
2022-03-01T04:16:51.000Z
2022-03-01T23:28:38.000Z
src/engine/dictionary.cpp
bec-ca/botle
dc85470c71c725bdb1ee7d36d03d10341070f73d
[ "Unlicense" ]
null
null
null
src/engine/dictionary.cpp
bec-ca/botle
dc85470c71c725bdb1ee7d36d03d10341070f73d
[ "Unlicense" ]
null
null
null
#include "dictionary.hpp" #include <fstream> #include "match.hpp" using namespace std; OrError<vector<InternalString>> Dictionary::load_words(const string& filename) { vector<InternalString> words; ifstream word_file(filename); if (word_file.bad()) { return Error::format("Failed to open file $", filename); } string word; while (word_file >> word) { if (word.size() != 5) { return Error::format("All word must have 5 words, got $", word); } words.push_back(InternalString(word)); } Match::init_result_cache(); return words; }
19.166667
78
0.671304
[ "vector" ]
939c288ce4358ab6f21ac6066cf5b4b8d5d7fff8
1,188
cpp
C++
diff/weak_ptr.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
7
2017-11-10T05:18:30.000Z
2021-04-29T15:38:25.000Z
diff/weak_ptr.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
null
null
null
diff/weak_ptr.cpp
IgorHersht/proxygen_ih
616a8eb899196d2a130e14c0fabcae1944e34b7d
[ "MIT" ]
null
null
null
#include <boost/thread/thread.hpp> #include <boost/thread/once.hpp> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <iostream> #include <iostream> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <string> #include <algorithm> #include <iterator> #include <functional> #include <numeric> #include <iostream> #include <vector> #include <list> #include <deque> #include <algorithm> #include <iostream> #include <typeinfo> #include <algorithm> #include <iterator> #include <memory> #include <string> #include <vector> #include <queue> #include <iostream> using namespace std; #include <string.h> int main() { boost::shared_ptr<int> spw1(new int(5)); boost::weak_ptr<int> wpw(spw1); { { boost::shared_ptr<int> pw2(wpw.lock());// #1 spw1.reset(); bool ex0 = !spw1; int c1= spw1.use_count() ; // 0 true bool ex = !pw2; int c2= pw2.use_count(); // 1 false line # 1 makes it NOT expired bool ex1 = wpw.expired(); int c3= wpw.use_count(); // 1 false line # 1 makes it NOT expired int i = 0; } } bool ex2 = wpw.expired(); return 0; }
20.842105
96
0.641414
[ "vector" ]
4d337632c0e34b451b7f0abc0a7a5b0a6f8fc7d7
8,245
cpp
C++
vtkMAF/Testing/vtkMAFTextOrientatorTest.cpp
FusionBox2/MAF2
b576955f4f6b954467021f12baedfebcaf79a382
[ "Apache-2.0" ]
1
2018-01-23T09:13:40.000Z
2018-01-23T09:13:40.000Z
vtkMAF/Testing/vtkMAFTextOrientatorTest.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
vtkMAF/Testing/vtkMAFTextOrientatorTest.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
3
2020-09-24T16:04:53.000Z
2020-09-24T16:50:30.000Z
/*========================================================================= Program: MAF2 Module: vtkMAFTextOrientatorTest Authors: Daniele Giunchi Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMAFTextOrientator.h" #include "vtkMAFTextOrientatorTest.h" #include <cppunit/config/SourcePrefix.h> #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkMAFSmartPointer.h" #include "vtkActor2D.h" #include "vtkWindowToImageFilter.h" #include "vtkImageMathematics.h" #include "vtkImageData.h" #include "vtkJPEGWriter.h" #include "vtkJPEGReader.h" #include "vtkPointData.h" void vtkMAFTextOrientatorTest::setUp() { } void vtkMAFTextOrientatorTest::tearDown() { } void vtkMAFTextOrientatorTest::TestFixture() { } //------------------------------------------------------------ void vtkMAFTextOrientatorTest::RenderData(vtkActor2D *actor) //------------------------------------------------------------ { vtkMAFSmartPointer<vtkRenderer> renderer; renderer->SetBackground(1.0, 1.0, 1.0); vtkMAFSmartPointer<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); renderWindow->SetSize(640, 480); renderWindow->SetPosition(100,0); vtkMAFSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor2D(actor); renderWindow->Render(); //renderWindowInteractor->Start(); CompareImages(renderWindow); #ifdef WIN32 Sleep(2000); #else usleep(2000*1000); #endif } //------------------------------------------------------------------ void vtkMAFTextOrientatorTest::SetText(vtkMAFTextOrientator *actor) //------------------------------------------------------------------ { if(actor) { actor->SetVisibility(true); actor->SetTextLeft("L"); actor->SetTextDown("D"); actor->SetTextRight("R"); actor->SetTextUp("U"); } } //------------------------------------------------------------ void vtkMAFTextOrientatorTest::TestDynamicAllocation() //------------------------------------------------------------ { vtkMAFTextOrientator *to = vtkMAFTextOrientator::New(); to->Delete(); } //-------------------------------------------- void vtkMAFTextOrientatorTest::TestText() //-------------------------------------------- { m_TestNumber = ID_TEXT_TEST; vtkMAFTextOrientator *actor; actor = vtkMAFTextOrientator::New(); SetText(actor); //test GetText CPPUNIT_ASSERT(strcmp(actor->GetTextLeft(),"L")==0); CPPUNIT_ASSERT(strcmp(actor->GetTextDown(),"D")==0); CPPUNIT_ASSERT(strcmp(actor->GetTextRight(),"R")==0); CPPUNIT_ASSERT(strcmp(actor->GetTextUp(),"U")==0); RenderData(actor); actor->Delete(); } //-------------------------------------------- void vtkMAFTextOrientatorTest::TestSingleActorVisibility() //-------------------------------------------- { m_TestNumber = ID_SINGLE_VISIBILITY_TEST; vtkMAFTextOrientator *actor; actor = vtkMAFTextOrientator::New(); SetText(actor); actor->SetSingleActorVisibility(vtkMAFTextOrientator::ID_ACTOR_LEFT, false); //left label is not visible RenderData(actor); actor->Delete(); } //-------------------------------------------- void vtkMAFTextOrientatorTest::TestTextColor() //-------------------------------------------- { m_TestNumber = ID_TEXT_COLOR_TEST; vtkMAFTextOrientator *actor; actor = vtkMAFTextOrientator::New(); SetText(actor); actor->SetTextColor(1.0, 0.0, 0.0); RenderData(actor); actor->Delete(); } //-------------------------------------------- void vtkMAFTextOrientatorTest::TestBackgroundColor() //-------------------------------------------- { m_TestNumber = ID_BACKGROUND_COLOR_TEST; vtkMAFTextOrientator *actor; actor = vtkMAFTextOrientator::New(); SetText(actor); actor->SetBackgroundColor(1.0, 0.0, 0.0); RenderData(actor); actor->Delete(); } //-------------------------------------------- void vtkMAFTextOrientatorTest::TestBackgroundVisibility() //-------------------------------------------- { m_TestNumber = ID_BACKGROUND_VISIBILITY_TEST; vtkMAFTextOrientator *actor; actor = vtkMAFTextOrientator::New(); SetText(actor); actor->SetTextColor(0.0,0.0,0.0); actor->SetBackgroundVisibility(false); RenderData(actor); actor->Delete(); } //-------------------------------------------- void vtkMAFTextOrientatorTest::TestScale() //-------------------------------------------- { m_TestNumber = ID_SCALE_TEST; vtkMAFTextOrientator *actor; actor = vtkMAFTextOrientator::New(); SetText(actor); actor->SetScale(2); RenderData(actor); actor->Delete(); } //---------------------------------------------------------------------------- void vtkMAFTextOrientatorTest::CompareImages(vtkRenderWindow * renwin) //---------------------------------------------------------------------------- { char *file = __FILE__; std::string name(file); std::string path(file); int slashIndex = name.find_last_of('\\'); name = name.substr(slashIndex+1); path = path.substr(0,slashIndex); int pointIndex = name.find_last_of('.'); name = name.substr(0, pointIndex); std::string controlOriginFile; controlOriginFile+=(path.c_str()); controlOriginFile+=("\\"); controlOriginFile+=(name.c_str()); controlOriginFile+=("_"); controlOriginFile+=("image"); controlOriginFile+=vtkMAFTextOrientatorTest::ConvertInt(m_TestNumber).c_str(); controlOriginFile+=(".jpg"); fstream controlStream; controlStream.open(controlOriginFile.c_str()); // visualization control renwin->OffScreenRenderingOn(); vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New(); w2i->SetInput(renwin); //w2i->SetMagnification(magnification); w2i->Update(); renwin->OffScreenRenderingOff(); //write comparing image vtkJPEGWriter *w = vtkJPEGWriter::New(); w->SetInput(w2i->GetOutput()); std::string imageFile=""; if(!controlStream) { imageFile+=(path.c_str()); imageFile+=("\\"); imageFile+=(name.c_str()); imageFile+=("_"); imageFile+=("image"); } else { imageFile+=(path.c_str()); imageFile+=("\\"); imageFile+=(name.c_str()); imageFile+=("_"); imageFile+=("comp"); } imageFile+=vtkMAFTextOrientatorTest::ConvertInt(m_TestNumber).c_str(); imageFile+=(".jpg"); w->SetFileName(imageFile.c_str()); w->Write(); if(!controlStream) { controlStream.close(); w->Delete(); w2i->Delete(); return; } controlStream.close(); //read original Image vtkJPEGReader *rO = vtkJPEGReader::New(); std::string imageFileOrig=""; imageFileOrig+=(path.c_str()); imageFileOrig+=("\\"); imageFileOrig+=(name.c_str()); imageFileOrig+=("_"); imageFileOrig+=("image"); imageFileOrig+=vtkMAFTextOrientatorTest::ConvertInt(m_TestNumber).c_str(); imageFileOrig+=(".jpg"); rO->SetFileName(imageFileOrig.c_str()); rO->Update(); vtkImageData *imDataOrig = rO->GetOutput(); //read compared image vtkJPEGReader *rC = vtkJPEGReader::New(); rC->SetFileName(imageFile.c_str()); rC->Update(); vtkImageData *imDataComp = rC->GetOutput(); vtkImageMathematics *imageMath = vtkImageMathematics::New(); imageMath->SetInput1(imDataOrig); imageMath->SetInput2(imDataComp); imageMath->SetOperationToSubtract(); imageMath->Update(); double srR[2] = {-1,1}; imageMath->GetOutput()->GetPointData()->GetScalars()->GetRange(srR); CPPUNIT_ASSERT(srR[0] == 0.0 && srR[1] == 0.0); // end visualization control rO->Delete(); rC->Delete(); imageMath->Delete(); w->Delete(); w2i->Delete(); } //-------------------------------------------------- std::string vtkMAFTextOrientatorTest::ConvertInt(int number) //-------------------------------------------------- { std::stringstream stringStream; stringStream << number;//add number to the stream return stringStream.str();//return a string with the contents of the stream }
26.511254
106
0.599636
[ "render" ]
4d381a8db65e24af43ed0e1f7b978986d883de47
7,563
hpp
C++
src/ncp/ncp_spi.hpp
CAJ2/openthread
120aa72ff2268cce60f773219ebe9162d20f0b90
[ "BSD-3-Clause" ]
1
2019-03-09T07:54:10.000Z
2019-03-09T07:54:10.000Z
src/ncp/ncp_spi.hpp
54markov/openthread
749421641513cc71bfc9bb899c5b683d6ce060c9
[ "BSD-3-Clause" ]
null
null
null
src/ncp/ncp_spi.hpp
54markov/openthread
749421641513cc71bfc9bb899c5b683d6ce060c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file contains definitions for a SPI interface to the OpenThread stack. */ #ifndef NCP_SPI_HPP_ #define NCP_SPI_HPP_ #include "openthread-core-config.h" #include "ncp/ncp_base.hpp" namespace ot { namespace Ncp { /** * This class defines a SPI frame. * */ class SpiFrame { public: enum { kHeaderSize = 5, ///< SPI header size (in bytes). }; /** * This constructor initializes an `SpiFrame` instance. * * @param[in] aBuffer Pointer to buffer containing the frame. * */ SpiFrame(uint8_t *aBuffer) : mBuffer(aBuffer) { } /** * This method gets a pointer to data portion in the SPI frame skipping the header. * * @returns A pointer to data in the SPI frame. * */ uint8_t *GetData(void) { return mBuffer + kHeaderSize; } /** * This method indicates whether or not the frame is valid. * * In a valid frame the flag byte should contain the pattern bits. * * @returns TRUE if the frame is valid, FALSE otherwise. * */ bool IsValid(void) const { return ((mBuffer[kIndexFlagByte] & kFlagPatternMask) == kFlagPattern); } /** * This method sets the "flag byte" field in the SPI frame header. * * @param[in] aResetFlag The status of reset flag (TRUE to set the flag, FALSE to clear flag). * */ void SetHeaderFlagByte(bool aResetFlag) { mBuffer[kIndexFlagByte] = kFlagPattern | (aResetFlag ? kFlagReset : 0); } /** * This method sets the "accept len" field in the SPI frame header. * * "accept len" specifies number of bytes the sender of the SPI frame can receive. * * @param[in] aAcceptLen The accept length in bytes. * */ void SetHeaderAcceptLen(uint16_t aAcceptLen) { Encoding::LittleEndian::WriteUint16(aAcceptLen, mBuffer + kIndexAcceptLen); } /** * This method gets the "accept len" field in the SPI frame header. * * @returns The accept length in bytes. * */ uint16_t GetHeaderAcceptLen(void) const { return Encoding::LittleEndian::ReadUint16(mBuffer + kIndexAcceptLen); } /** * This method sets the "data len" field in the SPI frame header. * * "Data len" specifies number of data bytes in the transmitted SPI frame. * * @param[in] aDataLen The data length in bytes. * */ void SetHeaderDataLen(uint16_t aDataLen) { Encoding::LittleEndian::WriteUint16(aDataLen, mBuffer + kIndexDataLen); } /** * This method gets the "data len" field in the SPI frame header. * * @returns The data length in bytes. * */ uint16_t GetHeaderDataLen(void) const { return Encoding::LittleEndian::ReadUint16(mBuffer + kIndexDataLen); } private: enum { kIndexFlagByte = 0, // flag byte (uint8_t). kIndexAcceptLen = 1, // accept len (uint16_t little-endian encoding). kIndexDataLen = 3, // data len (uint16_t little-endian encoding). kFlagReset = (1 << 7), // Flag byte RESET bit. kFlagPattern = 0x02, // Flag byte PATTERN bits. kFlagPatternMask = 0x03, // Flag byte PATTERN mask. }; uint8_t *mBuffer; }; class NcpSpi : public NcpBase { public: /** * This constructor initializes the object. * * @param[in] aInstance A pointer to the OpenThread instance structure. * */ NcpSpi(Instance *aInstance); private: enum { /** * SPI tx and rx buffer size (should fit a max length frame + SPI header). * */ kSpiBufferSize = OPENTHREAD_CONFIG_NCP_SPI_BUFFER_SIZE, /** * Size of the SPI header (in bytes). * */ kSpiHeaderSize = SpiFrame::kHeaderSize, }; enum TxState { kTxStateIdle, // No frame to send. kTxStateSending, // A frame is ready to be sent. kTxStateHandlingSendDone // The frame was sent successfully, waiting to prepare the next one (if any). }; typedef uint8_t LargeFrameBuffer[kSpiBufferSize]; typedef uint8_t EmptyFrameBuffer[kSpiHeaderSize]; static bool SpiTransactionComplete(void * aContext, uint8_t *aOutputBuf, uint16_t aOutputLen, uint8_t *aInputBuf, uint16_t aInputLen, uint16_t aTransLen); bool SpiTransactionComplete(uint8_t *aOutputBuf, uint16_t aOutputLen, uint8_t *aInputBuf, uint16_t aInputLen, uint16_t aTransLen); static void SpiTransactionProcess(void *aContext); void SpiTransactionProcess(void); static void HandleFrameAddedToTxBuffer(void * aContext, NcpFrameBuffer::FrameTag aFrameTag, NcpFrameBuffer::Priority aPriority, NcpFrameBuffer * aNcpFrameBuffer); static void PrepareTxFrame(Tasklet &aTasklet); void PrepareTxFrame(void); void HandleRxFrame(void); void PrepareNextSpiSendFrame(void); volatile TxState mTxState; volatile bool mHandlingRxFrame; volatile bool mResetFlag; Tasklet mPrepareTxFrameTask; uint16_t mSendFrameLength; LargeFrameBuffer mSendFrame; EmptyFrameBuffer mEmptySendFrameFullAccept; EmptyFrameBuffer mEmptySendFrameZeroAccept; LargeFrameBuffer mReceiveFrame; EmptyFrameBuffer mEmptyReceiveFrame; }; } // namespace Ncp } // namespace ot #endif // NCP_SPI_HPP_
33.317181
120
0.622372
[ "object" ]
4d4041b227c5194ed1a18f2599cddab291e313d8
5,323
cc
C++
third_party/blink/renderer/modules/webcodecs/video_frame_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/webcodecs/video_frame_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/webcodecs/video_frame_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/base/video_frame.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/modules/webcodecs/video_frame.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace blink { namespace { class VideoFrameTest : public testing::Test { public: VideoFrame* CreateBlinkVideoFrame( scoped_refptr<media::VideoFrame> media_frame) { return MakeGarbageCollected<VideoFrame>(std::move(media_frame)); } VideoFrame* CreateBlinkVideoFrameFromHandle( scoped_refptr<VideoFrame::Handle> handle) { return MakeGarbageCollected<VideoFrame>(std::move(handle)); } scoped_refptr<media::VideoFrame> CreateDefaultBlackMediaVideoFrame() { return CreateBlackMediaVideoFrame(base::TimeDelta::FromMicroseconds(1000), media::PIXEL_FORMAT_I420, gfx::Size(112, 208) /* coded_size */, gfx::Size(100, 200) /* visible_size */); } scoped_refptr<media::VideoFrame> CreateBlackMediaVideoFrame( base::TimeDelta timestamp, media::VideoPixelFormat format, const gfx::Size& coded_size, const gfx::Size& visible_size) { scoped_refptr<media::VideoFrame> media_frame = media::VideoFrame::WrapVideoFrame( media::VideoFrame::CreateBlackFrame(coded_size), format, gfx::Rect(visible_size) /* visible_rect */, visible_size /* natural_size */); media_frame->set_timestamp(timestamp); return media_frame; } }; TEST_F(VideoFrameTest, ConstructorAndAttributes) { scoped_refptr<media::VideoFrame> media_frame = CreateBlackMediaVideoFrame( base::TimeDelta::FromMicroseconds(1000), media::PIXEL_FORMAT_I420, gfx::Size(112, 208) /* coded_size */, gfx::Size(100, 200) /* visible_size */); VideoFrame* blink_frame = CreateBlinkVideoFrame(media_frame); EXPECT_EQ(1000u, blink_frame->timestamp().value()); EXPECT_EQ(112u, blink_frame->codedWidth()); EXPECT_EQ(208u, blink_frame->codedHeight()); EXPECT_EQ(100u, blink_frame->cropWidth()); EXPECT_EQ(200u, blink_frame->cropHeight()); EXPECT_EQ(media_frame, blink_frame->frame()); blink_frame->destroy(); EXPECT_FALSE(blink_frame->timestamp().has_value()); EXPECT_EQ(0u, blink_frame->codedWidth()); EXPECT_EQ(0u, blink_frame->codedHeight()); EXPECT_EQ(0u, blink_frame->cropWidth()); EXPECT_EQ(0u, blink_frame->cropHeight()); EXPECT_EQ(nullptr, blink_frame->frame()); } TEST_F(VideoFrameTest, FramesSharingHandleDestruction) { scoped_refptr<media::VideoFrame> media_frame = CreateDefaultBlackMediaVideoFrame(); VideoFrame* blink_frame = CreateBlinkVideoFrame(media_frame); VideoFrame* frame_with_shared_handle = CreateBlinkVideoFrameFromHandle(blink_frame->handle()); // A blink::VideoFrame created from a handle should share the same // media::VideoFrame reference. EXPECT_EQ(media_frame, frame_with_shared_handle->frame()); // Destroying a frame should invalidate all frames sharing the same handle. blink_frame->destroy(); EXPECT_EQ(nullptr, frame_with_shared_handle->frame()); } TEST_F(VideoFrameTest, FramesNotSharingHandleDestruction) { scoped_refptr<media::VideoFrame> media_frame = CreateDefaultBlackMediaVideoFrame(); VideoFrame* blink_frame = CreateBlinkVideoFrame(media_frame); auto new_handle = base::MakeRefCounted<VideoFrame::Handle>(blink_frame->frame()); VideoFrame* frame_with_new_handle = CreateBlinkVideoFrameFromHandle(std::move(new_handle)); EXPECT_EQ(media_frame, frame_with_new_handle->frame()); // If a frame was created a new handle reference the same media::VideoFrame, // one frame's destruction should not affect the other. blink_frame->destroy(); EXPECT_EQ(media_frame, frame_with_new_handle->frame()); } TEST_F(VideoFrameTest, ClonedFrame) { V8TestingScope scope; scoped_refptr<media::VideoFrame> media_frame = CreateDefaultBlackMediaVideoFrame(); VideoFrame* blink_frame = CreateBlinkVideoFrame(media_frame); VideoFrame* cloned_frame = blink_frame->clone(scope.GetExceptionState()); // The cloned frame should be referencing the same media::VideoFrame. EXPECT_EQ(blink_frame->frame(), cloned_frame->frame()); EXPECT_EQ(media_frame, cloned_frame->frame()); EXPECT_FALSE(scope.GetExceptionState().HadException()); blink_frame->destroy(); // Destroying the original frame should not affect the cloned frame. EXPECT_EQ(media_frame, cloned_frame->frame()); } TEST_F(VideoFrameTest, CloningDestroyedFrame) { V8TestingScope scope; scoped_refptr<media::VideoFrame> media_frame = CreateDefaultBlackMediaVideoFrame(); VideoFrame* blink_frame = CreateBlinkVideoFrame(media_frame); blink_frame->destroy(); VideoFrame* cloned_frame = blink_frame->clone(scope.GetExceptionState()); // No frame should have been created, and there should be an exception. EXPECT_EQ(nullptr, cloned_frame); EXPECT_TRUE(scope.GetExceptionState().HadException()); } } // namespace } // namespace blink
36.210884
79
0.736239
[ "geometry" ]
4d408892a1935bfe1a493c02de5c024cbcc60f9c
967
cpp
C++
CF/1187E.cpp
langonginc/cfile
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
[ "MIT" ]
1
2020-09-13T02:51:25.000Z
2020-09-13T02:51:25.000Z
CF/1187E.cpp
langonginc/cfile
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
[ "MIT" ]
null
null
null
CF/1187E.cpp
langonginc/cfile
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
[ "MIT" ]
1
2021-06-05T03:37:57.000Z
2021-06-05T03:37:57.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <climits> #include <vector> #include <cmath> using namespace std; typedef long long ll; const int inf = 200005; ll n, vis[inf], size[inf], dep[inf], dp[inf], ans = 0; vector <ll> adj[inf]; void dfs (int u, int f) { size[u] = 1; dp[1] ++; for (int i = 0; i < adj[u].size(); i ++) { int v = adj[u][i]; if (f != v) { dfs (v, u); size[u] += size[v]; dp[1] += size[v]; } } } void dfs2 (int u, int f) { for (int i = 0; i < adj[u].size(); i ++) { int v = adj[u][i]; if (v != f) { dp[v] = dp[u] + size[1] - size[v] * 2; ans = max (ans, dp[v]); dfs2 (v, u); } } } int main () { scanf ("%lld", &n); for (int i = 1; i < n; i ++) { ll u, v; scanf ("%lld%lld", &u, &v); adj[u].push_back(v); adj[v].push_back(u); } dfs (1, 0); dfs2 (1, 0); printf ("%lld\n", ans); return 0; }
16.116667
54
0.469493
[ "vector" ]
4d4d92be4d5ea2daa7d28dae3e0eca3ea75e59d5
66,845
cpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_ENHANCED_MEMPOOL_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_ENHANCED_MEMPOOL_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_ENHANCED_MEMPOOL_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "CISCO_ENHANCED_MEMPOOL_MIB.hpp" using namespace ydk; namespace cisco_ios_xe { namespace CISCO_ENHANCED_MEMPOOL_MIB { CISCOENHANCEDMEMPOOLMIB::CISCOENHANCEDMEMPOOLMIB() : cempnotificationconfig(std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig>()) , cempmempooltable(std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable>()) , cempmembufferpooltable(std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable>()) , cempmembuffercachepooltable(std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable>()) { cempnotificationconfig->parent = this; cempmempooltable->parent = this; cempmembufferpooltable->parent = this; cempmembuffercachepooltable->parent = this; yang_name = "CISCO-ENHANCED-MEMPOOL-MIB"; yang_parent_name = "CISCO-ENHANCED-MEMPOOL-MIB"; is_top_level_class = true; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::~CISCOENHANCEDMEMPOOLMIB() { } bool CISCOENHANCEDMEMPOOLMIB::has_data() const { if (is_presence_container) return true; return (cempnotificationconfig != nullptr && cempnotificationconfig->has_data()) || (cempmempooltable != nullptr && cempmempooltable->has_data()) || (cempmembufferpooltable != nullptr && cempmembufferpooltable->has_data()) || (cempmembuffercachepooltable != nullptr && cempmembuffercachepooltable->has_data()); } bool CISCOENHANCEDMEMPOOLMIB::has_operation() const { return is_set(yfilter) || (cempnotificationconfig != nullptr && cempnotificationconfig->has_operation()) || (cempmempooltable != nullptr && cempmempooltable->has_operation()) || (cempmembufferpooltable != nullptr && cempmembufferpooltable->has_operation()) || (cempmembuffercachepooltable != nullptr && cempmembuffercachepooltable->has_operation()); } std::string CISCOENHANCEDMEMPOOLMIB::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cempNotificationConfig") { if(cempnotificationconfig == nullptr) { cempnotificationconfig = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig>(); } return cempnotificationconfig; } if(child_yang_name == "cempMemPoolTable") { if(cempmempooltable == nullptr) { cempmempooltable = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable>(); } return cempmempooltable; } if(child_yang_name == "cempMemBufferPoolTable") { if(cempmembufferpooltable == nullptr) { cempmembufferpooltable = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable>(); } return cempmembufferpooltable; } if(child_yang_name == "cempMemBufferCachePoolTable") { if(cempmembuffercachepooltable == nullptr) { cempmembuffercachepooltable = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable>(); } return cempmembuffercachepooltable; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(cempnotificationconfig != nullptr) { _children["cempNotificationConfig"] = cempnotificationconfig; } if(cempmempooltable != nullptr) { _children["cempMemPoolTable"] = cempmempooltable; } if(cempmembufferpooltable != nullptr) { _children["cempMemBufferPoolTable"] = cempmembufferpooltable; } if(cempmembuffercachepooltable != nullptr) { _children["cempMemBufferCachePoolTable"] = cempmembuffercachepooltable; } return _children; } void CISCOENHANCEDMEMPOOLMIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOENHANCEDMEMPOOLMIB::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::clone_ptr() const { return std::make_shared<CISCOENHANCEDMEMPOOLMIB>(); } std::string CISCOENHANCEDMEMPOOLMIB::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string CISCOENHANCEDMEMPOOLMIB::get_bundle_name() const { return "cisco_ios_xe"; } augment_capabilities_function CISCOENHANCEDMEMPOOLMIB::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> CISCOENHANCEDMEMPOOLMIB::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool CISCOENHANCEDMEMPOOLMIB::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cempNotificationConfig" || name == "cempMemPoolTable" || name == "cempMemBufferPoolTable" || name == "cempMemBufferCachePoolTable") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::CempNotificationConfig() : cempmembuffernotifyenabled{YType::boolean, "cempMemBufferNotifyEnabled"} { yang_name = "cempNotificationConfig"; yang_parent_name = "CISCO-ENHANCED-MEMPOOL-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::~CempNotificationConfig() { } bool CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::has_data() const { if (is_presence_container) return true; return cempmembuffernotifyenabled.is_set; } bool CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::has_operation() const { return is_set(yfilter) || ydk::is_set(cempmembuffernotifyenabled.yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempNotificationConfig"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (cempmembuffernotifyenabled.is_set || is_set(cempmembuffernotifyenabled.yfilter)) leaf_name_data.push_back(cempmembuffernotifyenabled.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "cempMemBufferNotifyEnabled") { cempmembuffernotifyenabled = value; cempmembuffernotifyenabled.value_namespace = name_space; cempmembuffernotifyenabled.value_namespace_prefix = name_space_prefix; } } void CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "cempMemBufferNotifyEnabled") { cempmembuffernotifyenabled.yfilter = yfilter; } } bool CISCOENHANCEDMEMPOOLMIB::CempNotificationConfig::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cempMemBufferNotifyEnabled") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolTable() : cempmempoolentry(this, {"entphysicalindex", "cempmempoolindex"}) { yang_name = "cempMemPoolTable"; yang_parent_name = "CISCO-ENHANCED-MEMPOOL-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::~CempMemPoolTable() { } bool CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cempmempoolentry.len(); index++) { if(cempmempoolentry[index]->has_data()) return true; } return false; } bool CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::has_operation() const { for (std::size_t index=0; index<cempmempoolentry.len(); index++) { if(cempmempoolentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempMemPoolTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cempMemPoolEntry") { auto ent_ = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry>(); ent_->parent = this; cempmempoolentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cempmempoolentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cempMemPoolEntry") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::CempMemPoolEntry() : entphysicalindex{YType::str, "entPhysicalIndex"}, cempmempoolindex{YType::int32, "cempMemPoolIndex"}, cempmempooltype{YType::enumeration, "cempMemPoolType"}, cempmempoolname{YType::str, "cempMemPoolName"}, cempmempoolplatformmemory{YType::str, "cempMemPoolPlatformMemory"}, cempmempoolalternate{YType::int32, "cempMemPoolAlternate"}, cempmempoolvalid{YType::boolean, "cempMemPoolValid"}, cempmempoolused{YType::uint32, "cempMemPoolUsed"}, cempmempoolfree{YType::uint32, "cempMemPoolFree"}, cempmempoollargestfree{YType::uint32, "cempMemPoolLargestFree"}, cempmempoollowestfree{YType::uint32, "cempMemPoolLowestFree"}, cempmempoolusedlowwatermark{YType::uint32, "cempMemPoolUsedLowWaterMark"}, cempmempoolallochit{YType::uint32, "cempMemPoolAllocHit"}, cempmempoolallocmiss{YType::uint32, "cempMemPoolAllocMiss"}, cempmempoolfreehit{YType::uint32, "cempMemPoolFreeHit"}, cempmempoolfreemiss{YType::uint32, "cempMemPoolFreeMiss"}, cempmempoolshared{YType::uint32, "cempMemPoolShared"}, cempmempoolusedovrflw{YType::uint32, "cempMemPoolUsedOvrflw"}, cempmempoolhcused{YType::uint64, "cempMemPoolHCUsed"}, cempmempoolfreeovrflw{YType::uint32, "cempMemPoolFreeOvrflw"}, cempmempoolhcfree{YType::uint64, "cempMemPoolHCFree"}, cempmempoollargestfreeovrflw{YType::uint32, "cempMemPoolLargestFreeOvrflw"}, cempmempoolhclargestfree{YType::uint64, "cempMemPoolHCLargestFree"}, cempmempoollowestfreeovrflw{YType::uint32, "cempMemPoolLowestFreeOvrflw"}, cempmempoolhclowestfree{YType::uint64, "cempMemPoolHCLowestFree"}, cempmempoolusedlowwatermarkovrflw{YType::uint32, "cempMemPoolUsedLowWaterMarkOvrflw"}, cempmempoolhcusedlowwatermark{YType::uint64, "cempMemPoolHCUsedLowWaterMark"}, cempmempoolsharedovrflw{YType::uint32, "cempMemPoolSharedOvrflw"}, cempmempoolhcshared{YType::uint64, "cempMemPoolHCShared"} { yang_name = "cempMemPoolEntry"; yang_parent_name = "cempMemPoolTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::~CempMemPoolEntry() { } bool CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::has_data() const { if (is_presence_container) return true; return entphysicalindex.is_set || cempmempoolindex.is_set || cempmempooltype.is_set || cempmempoolname.is_set || cempmempoolplatformmemory.is_set || cempmempoolalternate.is_set || cempmempoolvalid.is_set || cempmempoolused.is_set || cempmempoolfree.is_set || cempmempoollargestfree.is_set || cempmempoollowestfree.is_set || cempmempoolusedlowwatermark.is_set || cempmempoolallochit.is_set || cempmempoolallocmiss.is_set || cempmempoolfreehit.is_set || cempmempoolfreemiss.is_set || cempmempoolshared.is_set || cempmempoolusedovrflw.is_set || cempmempoolhcused.is_set || cempmempoolfreeovrflw.is_set || cempmempoolhcfree.is_set || cempmempoollargestfreeovrflw.is_set || cempmempoolhclargestfree.is_set || cempmempoollowestfreeovrflw.is_set || cempmempoolhclowestfree.is_set || cempmempoolusedlowwatermarkovrflw.is_set || cempmempoolhcusedlowwatermark.is_set || cempmempoolsharedovrflw.is_set || cempmempoolhcshared.is_set; } bool CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(entphysicalindex.yfilter) || ydk::is_set(cempmempoolindex.yfilter) || ydk::is_set(cempmempooltype.yfilter) || ydk::is_set(cempmempoolname.yfilter) || ydk::is_set(cempmempoolplatformmemory.yfilter) || ydk::is_set(cempmempoolalternate.yfilter) || ydk::is_set(cempmempoolvalid.yfilter) || ydk::is_set(cempmempoolused.yfilter) || ydk::is_set(cempmempoolfree.yfilter) || ydk::is_set(cempmempoollargestfree.yfilter) || ydk::is_set(cempmempoollowestfree.yfilter) || ydk::is_set(cempmempoolusedlowwatermark.yfilter) || ydk::is_set(cempmempoolallochit.yfilter) || ydk::is_set(cempmempoolallocmiss.yfilter) || ydk::is_set(cempmempoolfreehit.yfilter) || ydk::is_set(cempmempoolfreemiss.yfilter) || ydk::is_set(cempmempoolshared.yfilter) || ydk::is_set(cempmempoolusedovrflw.yfilter) || ydk::is_set(cempmempoolhcused.yfilter) || ydk::is_set(cempmempoolfreeovrflw.yfilter) || ydk::is_set(cempmempoolhcfree.yfilter) || ydk::is_set(cempmempoollargestfreeovrflw.yfilter) || ydk::is_set(cempmempoolhclargestfree.yfilter) || ydk::is_set(cempmempoollowestfreeovrflw.yfilter) || ydk::is_set(cempmempoolhclowestfree.yfilter) || ydk::is_set(cempmempoolusedlowwatermarkovrflw.yfilter) || ydk::is_set(cempmempoolhcusedlowwatermark.yfilter) || ydk::is_set(cempmempoolsharedovrflw.yfilter) || ydk::is_set(cempmempoolhcshared.yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/cempMemPoolTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempMemPoolEntry"; ADD_KEY_TOKEN(entphysicalindex, "entPhysicalIndex"); ADD_KEY_TOKEN(cempmempoolindex, "cempMemPoolIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entphysicalindex.is_set || is_set(entphysicalindex.yfilter)) leaf_name_data.push_back(entphysicalindex.get_name_leafdata()); if (cempmempoolindex.is_set || is_set(cempmempoolindex.yfilter)) leaf_name_data.push_back(cempmempoolindex.get_name_leafdata()); if (cempmempooltype.is_set || is_set(cempmempooltype.yfilter)) leaf_name_data.push_back(cempmempooltype.get_name_leafdata()); if (cempmempoolname.is_set || is_set(cempmempoolname.yfilter)) leaf_name_data.push_back(cempmempoolname.get_name_leafdata()); if (cempmempoolplatformmemory.is_set || is_set(cempmempoolplatformmemory.yfilter)) leaf_name_data.push_back(cempmempoolplatformmemory.get_name_leafdata()); if (cempmempoolalternate.is_set || is_set(cempmempoolalternate.yfilter)) leaf_name_data.push_back(cempmempoolalternate.get_name_leafdata()); if (cempmempoolvalid.is_set || is_set(cempmempoolvalid.yfilter)) leaf_name_data.push_back(cempmempoolvalid.get_name_leafdata()); if (cempmempoolused.is_set || is_set(cempmempoolused.yfilter)) leaf_name_data.push_back(cempmempoolused.get_name_leafdata()); if (cempmempoolfree.is_set || is_set(cempmempoolfree.yfilter)) leaf_name_data.push_back(cempmempoolfree.get_name_leafdata()); if (cempmempoollargestfree.is_set || is_set(cempmempoollargestfree.yfilter)) leaf_name_data.push_back(cempmempoollargestfree.get_name_leafdata()); if (cempmempoollowestfree.is_set || is_set(cempmempoollowestfree.yfilter)) leaf_name_data.push_back(cempmempoollowestfree.get_name_leafdata()); if (cempmempoolusedlowwatermark.is_set || is_set(cempmempoolusedlowwatermark.yfilter)) leaf_name_data.push_back(cempmempoolusedlowwatermark.get_name_leafdata()); if (cempmempoolallochit.is_set || is_set(cempmempoolallochit.yfilter)) leaf_name_data.push_back(cempmempoolallochit.get_name_leafdata()); if (cempmempoolallocmiss.is_set || is_set(cempmempoolallocmiss.yfilter)) leaf_name_data.push_back(cempmempoolallocmiss.get_name_leafdata()); if (cempmempoolfreehit.is_set || is_set(cempmempoolfreehit.yfilter)) leaf_name_data.push_back(cempmempoolfreehit.get_name_leafdata()); if (cempmempoolfreemiss.is_set || is_set(cempmempoolfreemiss.yfilter)) leaf_name_data.push_back(cempmempoolfreemiss.get_name_leafdata()); if (cempmempoolshared.is_set || is_set(cempmempoolshared.yfilter)) leaf_name_data.push_back(cempmempoolshared.get_name_leafdata()); if (cempmempoolusedovrflw.is_set || is_set(cempmempoolusedovrflw.yfilter)) leaf_name_data.push_back(cempmempoolusedovrflw.get_name_leafdata()); if (cempmempoolhcused.is_set || is_set(cempmempoolhcused.yfilter)) leaf_name_data.push_back(cempmempoolhcused.get_name_leafdata()); if (cempmempoolfreeovrflw.is_set || is_set(cempmempoolfreeovrflw.yfilter)) leaf_name_data.push_back(cempmempoolfreeovrflw.get_name_leafdata()); if (cempmempoolhcfree.is_set || is_set(cempmempoolhcfree.yfilter)) leaf_name_data.push_back(cempmempoolhcfree.get_name_leafdata()); if (cempmempoollargestfreeovrflw.is_set || is_set(cempmempoollargestfreeovrflw.yfilter)) leaf_name_data.push_back(cempmempoollargestfreeovrflw.get_name_leafdata()); if (cempmempoolhclargestfree.is_set || is_set(cempmempoolhclargestfree.yfilter)) leaf_name_data.push_back(cempmempoolhclargestfree.get_name_leafdata()); if (cempmempoollowestfreeovrflw.is_set || is_set(cempmempoollowestfreeovrflw.yfilter)) leaf_name_data.push_back(cempmempoollowestfreeovrflw.get_name_leafdata()); if (cempmempoolhclowestfree.is_set || is_set(cempmempoolhclowestfree.yfilter)) leaf_name_data.push_back(cempmempoolhclowestfree.get_name_leafdata()); if (cempmempoolusedlowwatermarkovrflw.is_set || is_set(cempmempoolusedlowwatermarkovrflw.yfilter)) leaf_name_data.push_back(cempmempoolusedlowwatermarkovrflw.get_name_leafdata()); if (cempmempoolhcusedlowwatermark.is_set || is_set(cempmempoolhcusedlowwatermark.yfilter)) leaf_name_data.push_back(cempmempoolhcusedlowwatermark.get_name_leafdata()); if (cempmempoolsharedovrflw.is_set || is_set(cempmempoolsharedovrflw.yfilter)) leaf_name_data.push_back(cempmempoolsharedovrflw.get_name_leafdata()); if (cempmempoolhcshared.is_set || is_set(cempmempoolhcshared.yfilter)) leaf_name_data.push_back(cempmempoolhcshared.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entPhysicalIndex") { entphysicalindex = value; entphysicalindex.value_namespace = name_space; entphysicalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolIndex") { cempmempoolindex = value; cempmempoolindex.value_namespace = name_space; cempmempoolindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolType") { cempmempooltype = value; cempmempooltype.value_namespace = name_space; cempmempooltype.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolName") { cempmempoolname = value; cempmempoolname.value_namespace = name_space; cempmempoolname.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolPlatformMemory") { cempmempoolplatformmemory = value; cempmempoolplatformmemory.value_namespace = name_space; cempmempoolplatformmemory.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolAlternate") { cempmempoolalternate = value; cempmempoolalternate.value_namespace = name_space; cempmempoolalternate.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolValid") { cempmempoolvalid = value; cempmempoolvalid.value_namespace = name_space; cempmempoolvalid.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolUsed") { cempmempoolused = value; cempmempoolused.value_namespace = name_space; cempmempoolused.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolFree") { cempmempoolfree = value; cempmempoolfree.value_namespace = name_space; cempmempoolfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolLargestFree") { cempmempoollargestfree = value; cempmempoollargestfree.value_namespace = name_space; cempmempoollargestfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolLowestFree") { cempmempoollowestfree = value; cempmempoollowestfree.value_namespace = name_space; cempmempoollowestfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolUsedLowWaterMark") { cempmempoolusedlowwatermark = value; cempmempoolusedlowwatermark.value_namespace = name_space; cempmempoolusedlowwatermark.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolAllocHit") { cempmempoolallochit = value; cempmempoolallochit.value_namespace = name_space; cempmempoolallochit.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolAllocMiss") { cempmempoolallocmiss = value; cempmempoolallocmiss.value_namespace = name_space; cempmempoolallocmiss.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolFreeHit") { cempmempoolfreehit = value; cempmempoolfreehit.value_namespace = name_space; cempmempoolfreehit.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolFreeMiss") { cempmempoolfreemiss = value; cempmempoolfreemiss.value_namespace = name_space; cempmempoolfreemiss.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolShared") { cempmempoolshared = value; cempmempoolshared.value_namespace = name_space; cempmempoolshared.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolUsedOvrflw") { cempmempoolusedovrflw = value; cempmempoolusedovrflw.value_namespace = name_space; cempmempoolusedovrflw.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolHCUsed") { cempmempoolhcused = value; cempmempoolhcused.value_namespace = name_space; cempmempoolhcused.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolFreeOvrflw") { cempmempoolfreeovrflw = value; cempmempoolfreeovrflw.value_namespace = name_space; cempmempoolfreeovrflw.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolHCFree") { cempmempoolhcfree = value; cempmempoolhcfree.value_namespace = name_space; cempmempoolhcfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolLargestFreeOvrflw") { cempmempoollargestfreeovrflw = value; cempmempoollargestfreeovrflw.value_namespace = name_space; cempmempoollargestfreeovrflw.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolHCLargestFree") { cempmempoolhclargestfree = value; cempmempoolhclargestfree.value_namespace = name_space; cempmempoolhclargestfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolLowestFreeOvrflw") { cempmempoollowestfreeovrflw = value; cempmempoollowestfreeovrflw.value_namespace = name_space; cempmempoollowestfreeovrflw.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolHCLowestFree") { cempmempoolhclowestfree = value; cempmempoolhclowestfree.value_namespace = name_space; cempmempoolhclowestfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolUsedLowWaterMarkOvrflw") { cempmempoolusedlowwatermarkovrflw = value; cempmempoolusedlowwatermarkovrflw.value_namespace = name_space; cempmempoolusedlowwatermarkovrflw.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolHCUsedLowWaterMark") { cempmempoolhcusedlowwatermark = value; cempmempoolhcusedlowwatermark.value_namespace = name_space; cempmempoolhcusedlowwatermark.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolSharedOvrflw") { cempmempoolsharedovrflw = value; cempmempoolsharedovrflw.value_namespace = name_space; cempmempoolsharedovrflw.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemPoolHCShared") { cempmempoolhcshared = value; cempmempoolhcshared.value_namespace = name_space; cempmempoolhcshared.value_namespace_prefix = name_space_prefix; } } void CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entPhysicalIndex") { entphysicalindex.yfilter = yfilter; } if(value_path == "cempMemPoolIndex") { cempmempoolindex.yfilter = yfilter; } if(value_path == "cempMemPoolType") { cempmempooltype.yfilter = yfilter; } if(value_path == "cempMemPoolName") { cempmempoolname.yfilter = yfilter; } if(value_path == "cempMemPoolPlatformMemory") { cempmempoolplatformmemory.yfilter = yfilter; } if(value_path == "cempMemPoolAlternate") { cempmempoolalternate.yfilter = yfilter; } if(value_path == "cempMemPoolValid") { cempmempoolvalid.yfilter = yfilter; } if(value_path == "cempMemPoolUsed") { cempmempoolused.yfilter = yfilter; } if(value_path == "cempMemPoolFree") { cempmempoolfree.yfilter = yfilter; } if(value_path == "cempMemPoolLargestFree") { cempmempoollargestfree.yfilter = yfilter; } if(value_path == "cempMemPoolLowestFree") { cempmempoollowestfree.yfilter = yfilter; } if(value_path == "cempMemPoolUsedLowWaterMark") { cempmempoolusedlowwatermark.yfilter = yfilter; } if(value_path == "cempMemPoolAllocHit") { cempmempoolallochit.yfilter = yfilter; } if(value_path == "cempMemPoolAllocMiss") { cempmempoolallocmiss.yfilter = yfilter; } if(value_path == "cempMemPoolFreeHit") { cempmempoolfreehit.yfilter = yfilter; } if(value_path == "cempMemPoolFreeMiss") { cempmempoolfreemiss.yfilter = yfilter; } if(value_path == "cempMemPoolShared") { cempmempoolshared.yfilter = yfilter; } if(value_path == "cempMemPoolUsedOvrflw") { cempmempoolusedovrflw.yfilter = yfilter; } if(value_path == "cempMemPoolHCUsed") { cempmempoolhcused.yfilter = yfilter; } if(value_path == "cempMemPoolFreeOvrflw") { cempmempoolfreeovrflw.yfilter = yfilter; } if(value_path == "cempMemPoolHCFree") { cempmempoolhcfree.yfilter = yfilter; } if(value_path == "cempMemPoolLargestFreeOvrflw") { cempmempoollargestfreeovrflw.yfilter = yfilter; } if(value_path == "cempMemPoolHCLargestFree") { cempmempoolhclargestfree.yfilter = yfilter; } if(value_path == "cempMemPoolLowestFreeOvrflw") { cempmempoollowestfreeovrflw.yfilter = yfilter; } if(value_path == "cempMemPoolHCLowestFree") { cempmempoolhclowestfree.yfilter = yfilter; } if(value_path == "cempMemPoolUsedLowWaterMarkOvrflw") { cempmempoolusedlowwatermarkovrflw.yfilter = yfilter; } if(value_path == "cempMemPoolHCUsedLowWaterMark") { cempmempoolhcusedlowwatermark.yfilter = yfilter; } if(value_path == "cempMemPoolSharedOvrflw") { cempmempoolsharedovrflw.yfilter = yfilter; } if(value_path == "cempMemPoolHCShared") { cempmempoolhcshared.yfilter = yfilter; } } bool CISCOENHANCEDMEMPOOLMIB::CempMemPoolTable::CempMemPoolEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "entPhysicalIndex" || name == "cempMemPoolIndex" || name == "cempMemPoolType" || name == "cempMemPoolName" || name == "cempMemPoolPlatformMemory" || name == "cempMemPoolAlternate" || name == "cempMemPoolValid" || name == "cempMemPoolUsed" || name == "cempMemPoolFree" || name == "cempMemPoolLargestFree" || name == "cempMemPoolLowestFree" || name == "cempMemPoolUsedLowWaterMark" || name == "cempMemPoolAllocHit" || name == "cempMemPoolAllocMiss" || name == "cempMemPoolFreeHit" || name == "cempMemPoolFreeMiss" || name == "cempMemPoolShared" || name == "cempMemPoolUsedOvrflw" || name == "cempMemPoolHCUsed" || name == "cempMemPoolFreeOvrflw" || name == "cempMemPoolHCFree" || name == "cempMemPoolLargestFreeOvrflw" || name == "cempMemPoolHCLargestFree" || name == "cempMemPoolLowestFreeOvrflw" || name == "cempMemPoolHCLowestFree" || name == "cempMemPoolUsedLowWaterMarkOvrflw" || name == "cempMemPoolHCUsedLowWaterMark" || name == "cempMemPoolSharedOvrflw" || name == "cempMemPoolHCShared") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolTable() : cempmembufferpoolentry(this, {"entphysicalindex", "cempmembufferpoolindex"}) { yang_name = "cempMemBufferPoolTable"; yang_parent_name = "CISCO-ENHANCED-MEMPOOL-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::~CempMemBufferPoolTable() { } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cempmembufferpoolentry.len(); index++) { if(cempmembufferpoolentry[index]->has_data()) return true; } return false; } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::has_operation() const { for (std::size_t index=0; index<cempmembufferpoolentry.len(); index++) { if(cempmembufferpoolentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempMemBufferPoolTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cempMemBufferPoolEntry") { auto ent_ = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry>(); ent_->parent = this; cempmembufferpoolentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cempmembufferpoolentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cempMemBufferPoolEntry") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::CempMemBufferPoolEntry() : entphysicalindex{YType::str, "entPhysicalIndex"}, cempmembufferpoolindex{YType::uint32, "cempMemBufferPoolIndex"}, cempmembuffermempoolindex{YType::int32, "cempMemBufferMemPoolIndex"}, cempmembuffername{YType::str, "cempMemBufferName"}, cempmembufferdynamic{YType::boolean, "cempMemBufferDynamic"}, cempmembuffersize{YType::uint32, "cempMemBufferSize"}, cempmembuffermin{YType::uint32, "cempMemBufferMin"}, cempmembuffermax{YType::uint32, "cempMemBufferMax"}, cempmembufferpermanent{YType::uint32, "cempMemBufferPermanent"}, cempmembuffertransient{YType::uint32, "cempMemBufferTransient"}, cempmembuffertotal{YType::uint32, "cempMemBufferTotal"}, cempmembufferfree{YType::uint32, "cempMemBufferFree"}, cempmembufferhit{YType::uint32, "cempMemBufferHit"}, cempmembuffermiss{YType::uint32, "cempMemBufferMiss"}, cempmembufferfreehit{YType::uint32, "cempMemBufferFreeHit"}, cempmembufferfreemiss{YType::uint32, "cempMemBufferFreeMiss"}, cempmembufferpermchange{YType::int32, "cempMemBufferPermChange"}, cempmembufferpeak{YType::uint32, "cempMemBufferPeak"}, cempmembufferpeaktime{YType::uint32, "cempMemBufferPeakTime"}, cempmembuffertrim{YType::uint32, "cempMemBufferTrim"}, cempmembuffergrow{YType::uint32, "cempMemBufferGrow"}, cempmembufferfailures{YType::uint32, "cempMemBufferFailures"}, cempmembuffernostorage{YType::uint32, "cempMemBufferNoStorage"} { yang_name = "cempMemBufferPoolEntry"; yang_parent_name = "cempMemBufferPoolTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::~CempMemBufferPoolEntry() { } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::has_data() const { if (is_presence_container) return true; return entphysicalindex.is_set || cempmembufferpoolindex.is_set || cempmembuffermempoolindex.is_set || cempmembuffername.is_set || cempmembufferdynamic.is_set || cempmembuffersize.is_set || cempmembuffermin.is_set || cempmembuffermax.is_set || cempmembufferpermanent.is_set || cempmembuffertransient.is_set || cempmembuffertotal.is_set || cempmembufferfree.is_set || cempmembufferhit.is_set || cempmembuffermiss.is_set || cempmembufferfreehit.is_set || cempmembufferfreemiss.is_set || cempmembufferpermchange.is_set || cempmembufferpeak.is_set || cempmembufferpeaktime.is_set || cempmembuffertrim.is_set || cempmembuffergrow.is_set || cempmembufferfailures.is_set || cempmembuffernostorage.is_set; } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(entphysicalindex.yfilter) || ydk::is_set(cempmembufferpoolindex.yfilter) || ydk::is_set(cempmembuffermempoolindex.yfilter) || ydk::is_set(cempmembuffername.yfilter) || ydk::is_set(cempmembufferdynamic.yfilter) || ydk::is_set(cempmembuffersize.yfilter) || ydk::is_set(cempmembuffermin.yfilter) || ydk::is_set(cempmembuffermax.yfilter) || ydk::is_set(cempmembufferpermanent.yfilter) || ydk::is_set(cempmembuffertransient.yfilter) || ydk::is_set(cempmembuffertotal.yfilter) || ydk::is_set(cempmembufferfree.yfilter) || ydk::is_set(cempmembufferhit.yfilter) || ydk::is_set(cempmembuffermiss.yfilter) || ydk::is_set(cempmembufferfreehit.yfilter) || ydk::is_set(cempmembufferfreemiss.yfilter) || ydk::is_set(cempmembufferpermchange.yfilter) || ydk::is_set(cempmembufferpeak.yfilter) || ydk::is_set(cempmembufferpeaktime.yfilter) || ydk::is_set(cempmembuffertrim.yfilter) || ydk::is_set(cempmembuffergrow.yfilter) || ydk::is_set(cempmembufferfailures.yfilter) || ydk::is_set(cempmembuffernostorage.yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/cempMemBufferPoolTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempMemBufferPoolEntry"; ADD_KEY_TOKEN(entphysicalindex, "entPhysicalIndex"); ADD_KEY_TOKEN(cempmembufferpoolindex, "cempMemBufferPoolIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entphysicalindex.is_set || is_set(entphysicalindex.yfilter)) leaf_name_data.push_back(entphysicalindex.get_name_leafdata()); if (cempmembufferpoolindex.is_set || is_set(cempmembufferpoolindex.yfilter)) leaf_name_data.push_back(cempmembufferpoolindex.get_name_leafdata()); if (cempmembuffermempoolindex.is_set || is_set(cempmembuffermempoolindex.yfilter)) leaf_name_data.push_back(cempmembuffermempoolindex.get_name_leafdata()); if (cempmembuffername.is_set || is_set(cempmembuffername.yfilter)) leaf_name_data.push_back(cempmembuffername.get_name_leafdata()); if (cempmembufferdynamic.is_set || is_set(cempmembufferdynamic.yfilter)) leaf_name_data.push_back(cempmembufferdynamic.get_name_leafdata()); if (cempmembuffersize.is_set || is_set(cempmembuffersize.yfilter)) leaf_name_data.push_back(cempmembuffersize.get_name_leafdata()); if (cempmembuffermin.is_set || is_set(cempmembuffermin.yfilter)) leaf_name_data.push_back(cempmembuffermin.get_name_leafdata()); if (cempmembuffermax.is_set || is_set(cempmembuffermax.yfilter)) leaf_name_data.push_back(cempmembuffermax.get_name_leafdata()); if (cempmembufferpermanent.is_set || is_set(cempmembufferpermanent.yfilter)) leaf_name_data.push_back(cempmembufferpermanent.get_name_leafdata()); if (cempmembuffertransient.is_set || is_set(cempmembuffertransient.yfilter)) leaf_name_data.push_back(cempmembuffertransient.get_name_leafdata()); if (cempmembuffertotal.is_set || is_set(cempmembuffertotal.yfilter)) leaf_name_data.push_back(cempmembuffertotal.get_name_leafdata()); if (cempmembufferfree.is_set || is_set(cempmembufferfree.yfilter)) leaf_name_data.push_back(cempmembufferfree.get_name_leafdata()); if (cempmembufferhit.is_set || is_set(cempmembufferhit.yfilter)) leaf_name_data.push_back(cempmembufferhit.get_name_leafdata()); if (cempmembuffermiss.is_set || is_set(cempmembuffermiss.yfilter)) leaf_name_data.push_back(cempmembuffermiss.get_name_leafdata()); if (cempmembufferfreehit.is_set || is_set(cempmembufferfreehit.yfilter)) leaf_name_data.push_back(cempmembufferfreehit.get_name_leafdata()); if (cempmembufferfreemiss.is_set || is_set(cempmembufferfreemiss.yfilter)) leaf_name_data.push_back(cempmembufferfreemiss.get_name_leafdata()); if (cempmembufferpermchange.is_set || is_set(cempmembufferpermchange.yfilter)) leaf_name_data.push_back(cempmembufferpermchange.get_name_leafdata()); if (cempmembufferpeak.is_set || is_set(cempmembufferpeak.yfilter)) leaf_name_data.push_back(cempmembufferpeak.get_name_leafdata()); if (cempmembufferpeaktime.is_set || is_set(cempmembufferpeaktime.yfilter)) leaf_name_data.push_back(cempmembufferpeaktime.get_name_leafdata()); if (cempmembuffertrim.is_set || is_set(cempmembuffertrim.yfilter)) leaf_name_data.push_back(cempmembuffertrim.get_name_leafdata()); if (cempmembuffergrow.is_set || is_set(cempmembuffergrow.yfilter)) leaf_name_data.push_back(cempmembuffergrow.get_name_leafdata()); if (cempmembufferfailures.is_set || is_set(cempmembufferfailures.yfilter)) leaf_name_data.push_back(cempmembufferfailures.get_name_leafdata()); if (cempmembuffernostorage.is_set || is_set(cempmembuffernostorage.yfilter)) leaf_name_data.push_back(cempmembuffernostorage.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entPhysicalIndex") { entphysicalindex = value; entphysicalindex.value_namespace = name_space; entphysicalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferPoolIndex") { cempmembufferpoolindex = value; cempmembufferpoolindex.value_namespace = name_space; cempmembufferpoolindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferMemPoolIndex") { cempmembuffermempoolindex = value; cempmembuffermempoolindex.value_namespace = name_space; cempmembuffermempoolindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferName") { cempmembuffername = value; cempmembuffername.value_namespace = name_space; cempmembuffername.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferDynamic") { cempmembufferdynamic = value; cempmembufferdynamic.value_namespace = name_space; cempmembufferdynamic.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferSize") { cempmembuffersize = value; cempmembuffersize.value_namespace = name_space; cempmembuffersize.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferMin") { cempmembuffermin = value; cempmembuffermin.value_namespace = name_space; cempmembuffermin.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferMax") { cempmembuffermax = value; cempmembuffermax.value_namespace = name_space; cempmembuffermax.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferPermanent") { cempmembufferpermanent = value; cempmembufferpermanent.value_namespace = name_space; cempmembufferpermanent.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferTransient") { cempmembuffertransient = value; cempmembuffertransient.value_namespace = name_space; cempmembuffertransient.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferTotal") { cempmembuffertotal = value; cempmembuffertotal.value_namespace = name_space; cempmembuffertotal.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferFree") { cempmembufferfree = value; cempmembufferfree.value_namespace = name_space; cempmembufferfree.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferHit") { cempmembufferhit = value; cempmembufferhit.value_namespace = name_space; cempmembufferhit.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferMiss") { cempmembuffermiss = value; cempmembuffermiss.value_namespace = name_space; cempmembuffermiss.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferFreeHit") { cempmembufferfreehit = value; cempmembufferfreehit.value_namespace = name_space; cempmembufferfreehit.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferFreeMiss") { cempmembufferfreemiss = value; cempmembufferfreemiss.value_namespace = name_space; cempmembufferfreemiss.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferPermChange") { cempmembufferpermchange = value; cempmembufferpermchange.value_namespace = name_space; cempmembufferpermchange.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferPeak") { cempmembufferpeak = value; cempmembufferpeak.value_namespace = name_space; cempmembufferpeak.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferPeakTime") { cempmembufferpeaktime = value; cempmembufferpeaktime.value_namespace = name_space; cempmembufferpeaktime.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferTrim") { cempmembuffertrim = value; cempmembuffertrim.value_namespace = name_space; cempmembuffertrim.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferGrow") { cempmembuffergrow = value; cempmembuffergrow.value_namespace = name_space; cempmembuffergrow.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferFailures") { cempmembufferfailures = value; cempmembufferfailures.value_namespace = name_space; cempmembufferfailures.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferNoStorage") { cempmembuffernostorage = value; cempmembuffernostorage.value_namespace = name_space; cempmembuffernostorage.value_namespace_prefix = name_space_prefix; } } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entPhysicalIndex") { entphysicalindex.yfilter = yfilter; } if(value_path == "cempMemBufferPoolIndex") { cempmembufferpoolindex.yfilter = yfilter; } if(value_path == "cempMemBufferMemPoolIndex") { cempmembuffermempoolindex.yfilter = yfilter; } if(value_path == "cempMemBufferName") { cempmembuffername.yfilter = yfilter; } if(value_path == "cempMemBufferDynamic") { cempmembufferdynamic.yfilter = yfilter; } if(value_path == "cempMemBufferSize") { cempmembuffersize.yfilter = yfilter; } if(value_path == "cempMemBufferMin") { cempmembuffermin.yfilter = yfilter; } if(value_path == "cempMemBufferMax") { cempmembuffermax.yfilter = yfilter; } if(value_path == "cempMemBufferPermanent") { cempmembufferpermanent.yfilter = yfilter; } if(value_path == "cempMemBufferTransient") { cempmembuffertransient.yfilter = yfilter; } if(value_path == "cempMemBufferTotal") { cempmembuffertotal.yfilter = yfilter; } if(value_path == "cempMemBufferFree") { cempmembufferfree.yfilter = yfilter; } if(value_path == "cempMemBufferHit") { cempmembufferhit.yfilter = yfilter; } if(value_path == "cempMemBufferMiss") { cempmembuffermiss.yfilter = yfilter; } if(value_path == "cempMemBufferFreeHit") { cempmembufferfreehit.yfilter = yfilter; } if(value_path == "cempMemBufferFreeMiss") { cempmembufferfreemiss.yfilter = yfilter; } if(value_path == "cempMemBufferPermChange") { cempmembufferpermchange.yfilter = yfilter; } if(value_path == "cempMemBufferPeak") { cempmembufferpeak.yfilter = yfilter; } if(value_path == "cempMemBufferPeakTime") { cempmembufferpeaktime.yfilter = yfilter; } if(value_path == "cempMemBufferTrim") { cempmembuffertrim.yfilter = yfilter; } if(value_path == "cempMemBufferGrow") { cempmembuffergrow.yfilter = yfilter; } if(value_path == "cempMemBufferFailures") { cempmembufferfailures.yfilter = yfilter; } if(value_path == "cempMemBufferNoStorage") { cempmembuffernostorage.yfilter = yfilter; } } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferPoolTable::CempMemBufferPoolEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "entPhysicalIndex" || name == "cempMemBufferPoolIndex" || name == "cempMemBufferMemPoolIndex" || name == "cempMemBufferName" || name == "cempMemBufferDynamic" || name == "cempMemBufferSize" || name == "cempMemBufferMin" || name == "cempMemBufferMax" || name == "cempMemBufferPermanent" || name == "cempMemBufferTransient" || name == "cempMemBufferTotal" || name == "cempMemBufferFree" || name == "cempMemBufferHit" || name == "cempMemBufferMiss" || name == "cempMemBufferFreeHit" || name == "cempMemBufferFreeMiss" || name == "cempMemBufferPermChange" || name == "cempMemBufferPeak" || name == "cempMemBufferPeakTime" || name == "cempMemBufferTrim" || name == "cempMemBufferGrow" || name == "cempMemBufferFailures" || name == "cempMemBufferNoStorage") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolTable() : cempmembuffercachepoolentry(this, {"entphysicalindex", "cempmembufferpoolindex"}) { yang_name = "cempMemBufferCachePoolTable"; yang_parent_name = "CISCO-ENHANCED-MEMPOOL-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::~CempMemBufferCachePoolTable() { } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cempmembuffercachepoolentry.len(); index++) { if(cempmembuffercachepoolentry[index]->has_data()) return true; } return false; } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::has_operation() const { for (std::size_t index=0; index<cempmembuffercachepoolentry.len(); index++) { if(cempmembuffercachepoolentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempMemBufferCachePoolTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cempMemBufferCachePoolEntry") { auto ent_ = std::make_shared<CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry>(); ent_->parent = this; cempmembuffercachepoolentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cempmembuffercachepoolentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cempMemBufferCachePoolEntry") return true; return false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::CempMemBufferCachePoolEntry() : entphysicalindex{YType::str, "entPhysicalIndex"}, cempmembufferpoolindex{YType::str, "cempMemBufferPoolIndex"}, cempmembuffercachesize{YType::uint32, "cempMemBufferCacheSize"}, cempmembuffercachetotal{YType::uint32, "cempMemBufferCacheTotal"}, cempmembuffercacheused{YType::uint32, "cempMemBufferCacheUsed"}, cempmembuffercachehit{YType::uint32, "cempMemBufferCacheHit"}, cempmembuffercachemiss{YType::uint32, "cempMemBufferCacheMiss"}, cempmembuffercachethreshold{YType::uint32, "cempMemBufferCacheThreshold"}, cempmembuffercachethresholdcount{YType::uint32, "cempMemBufferCacheThresholdCount"} { yang_name = "cempMemBufferCachePoolEntry"; yang_parent_name = "cempMemBufferCachePoolTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::~CempMemBufferCachePoolEntry() { } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::has_data() const { if (is_presence_container) return true; return entphysicalindex.is_set || cempmembufferpoolindex.is_set || cempmembuffercachesize.is_set || cempmembuffercachetotal.is_set || cempmembuffercacheused.is_set || cempmembuffercachehit.is_set || cempmembuffercachemiss.is_set || cempmembuffercachethreshold.is_set || cempmembuffercachethresholdcount.is_set; } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(entphysicalindex.yfilter) || ydk::is_set(cempmembufferpoolindex.yfilter) || ydk::is_set(cempmembuffercachesize.yfilter) || ydk::is_set(cempmembuffercachetotal.yfilter) || ydk::is_set(cempmembuffercacheused.yfilter) || ydk::is_set(cempmembuffercachehit.yfilter) || ydk::is_set(cempmembuffercachemiss.yfilter) || ydk::is_set(cempmembuffercachethreshold.yfilter) || ydk::is_set(cempmembuffercachethresholdcount.yfilter); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-ENHANCED-MEMPOOL-MIB:CISCO-ENHANCED-MEMPOOL-MIB/cempMemBufferCachePoolTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cempMemBufferCachePoolEntry"; ADD_KEY_TOKEN(entphysicalindex, "entPhysicalIndex"); ADD_KEY_TOKEN(cempmembufferpoolindex, "cempMemBufferPoolIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entphysicalindex.is_set || is_set(entphysicalindex.yfilter)) leaf_name_data.push_back(entphysicalindex.get_name_leafdata()); if (cempmembufferpoolindex.is_set || is_set(cempmembufferpoolindex.yfilter)) leaf_name_data.push_back(cempmembufferpoolindex.get_name_leafdata()); if (cempmembuffercachesize.is_set || is_set(cempmembuffercachesize.yfilter)) leaf_name_data.push_back(cempmembuffercachesize.get_name_leafdata()); if (cempmembuffercachetotal.is_set || is_set(cempmembuffercachetotal.yfilter)) leaf_name_data.push_back(cempmembuffercachetotal.get_name_leafdata()); if (cempmembuffercacheused.is_set || is_set(cempmembuffercacheused.yfilter)) leaf_name_data.push_back(cempmembuffercacheused.get_name_leafdata()); if (cempmembuffercachehit.is_set || is_set(cempmembuffercachehit.yfilter)) leaf_name_data.push_back(cempmembuffercachehit.get_name_leafdata()); if (cempmembuffercachemiss.is_set || is_set(cempmembuffercachemiss.yfilter)) leaf_name_data.push_back(cempmembuffercachemiss.get_name_leafdata()); if (cempmembuffercachethreshold.is_set || is_set(cempmembuffercachethreshold.yfilter)) leaf_name_data.push_back(cempmembuffercachethreshold.get_name_leafdata()); if (cempmembuffercachethresholdcount.is_set || is_set(cempmembuffercachethresholdcount.yfilter)) leaf_name_data.push_back(cempmembuffercachethresholdcount.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entPhysicalIndex") { entphysicalindex = value; entphysicalindex.value_namespace = name_space; entphysicalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferPoolIndex") { cempmembufferpoolindex = value; cempmembufferpoolindex.value_namespace = name_space; cempmembufferpoolindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheSize") { cempmembuffercachesize = value; cempmembuffercachesize.value_namespace = name_space; cempmembuffercachesize.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheTotal") { cempmembuffercachetotal = value; cempmembuffercachetotal.value_namespace = name_space; cempmembuffercachetotal.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheUsed") { cempmembuffercacheused = value; cempmembuffercacheused.value_namespace = name_space; cempmembuffercacheused.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheHit") { cempmembuffercachehit = value; cempmembuffercachehit.value_namespace = name_space; cempmembuffercachehit.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheMiss") { cempmembuffercachemiss = value; cempmembuffercachemiss.value_namespace = name_space; cempmembuffercachemiss.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheThreshold") { cempmembuffercachethreshold = value; cempmembuffercachethreshold.value_namespace = name_space; cempmembuffercachethreshold.value_namespace_prefix = name_space_prefix; } if(value_path == "cempMemBufferCacheThresholdCount") { cempmembuffercachethresholdcount = value; cempmembuffercachethresholdcount.value_namespace = name_space; cempmembuffercachethresholdcount.value_namespace_prefix = name_space_prefix; } } void CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entPhysicalIndex") { entphysicalindex.yfilter = yfilter; } if(value_path == "cempMemBufferPoolIndex") { cempmembufferpoolindex.yfilter = yfilter; } if(value_path == "cempMemBufferCacheSize") { cempmembuffercachesize.yfilter = yfilter; } if(value_path == "cempMemBufferCacheTotal") { cempmembuffercachetotal.yfilter = yfilter; } if(value_path == "cempMemBufferCacheUsed") { cempmembuffercacheused.yfilter = yfilter; } if(value_path == "cempMemBufferCacheHit") { cempmembuffercachehit.yfilter = yfilter; } if(value_path == "cempMemBufferCacheMiss") { cempmembuffercachemiss.yfilter = yfilter; } if(value_path == "cempMemBufferCacheThreshold") { cempmembuffercachethreshold.yfilter = yfilter; } if(value_path == "cempMemBufferCacheThresholdCount") { cempmembuffercachethresholdcount.yfilter = yfilter; } } bool CISCOENHANCEDMEMPOOLMIB::CempMemBufferCachePoolTable::CempMemBufferCachePoolEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "entPhysicalIndex" || name == "cempMemBufferPoolIndex" || name == "cempMemBufferCacheSize" || name == "cempMemBufferCacheTotal" || name == "cempMemBufferCacheUsed" || name == "cempMemBufferCacheHit" || name == "cempMemBufferCacheMiss" || name == "cempMemBufferCacheThreshold" || name == "cempMemBufferCacheThresholdCount") return true; return false; } const Enum::YLeaf CempMemPoolTypes::other {1, "other"}; const Enum::YLeaf CempMemPoolTypes::processorMemory {2, "processorMemory"}; const Enum::YLeaf CempMemPoolTypes::ioMemory {3, "ioMemory"}; const Enum::YLeaf CempMemPoolTypes::pciMemory {4, "pciMemory"}; const Enum::YLeaf CempMemPoolTypes::fastMemory {5, "fastMemory"}; const Enum::YLeaf CempMemPoolTypes::multibusMemory {6, "multibusMemory"}; const Enum::YLeaf CempMemPoolTypes::interruptStackMemory {7, "interruptStackMemory"}; const Enum::YLeaf CempMemPoolTypes::processStackMemory {8, "processStackMemory"}; const Enum::YLeaf CempMemPoolTypes::localExceptionMemory {9, "localExceptionMemory"}; const Enum::YLeaf CempMemPoolTypes::virtualMemory {10, "virtualMemory"}; const Enum::YLeaf CempMemPoolTypes::reservedMemory {11, "reservedMemory"}; const Enum::YLeaf CempMemPoolTypes::imageMemory {12, "imageMemory"}; const Enum::YLeaf CempMemPoolTypes::asicMemory {13, "asicMemory"}; const Enum::YLeaf CempMemPoolTypes::posixMemory {14, "posixMemory"}; } }
40.463075
1,008
0.74761
[ "vector" ]
4d501dd1e043b9a42b94e6f8a15226df0c4627f5
1,107
cpp
C++
treeintro.cpp
preetifeb13/Hackto21
b026e526771053eb32aace35ee76ee7862b082fb
[ "MIT" ]
7
2021-12-03T14:28:52.000Z
2022-02-04T09:06:09.000Z
treeintro.cpp
riti2409/Hackto21
ce7ae587a5dce631c01549afe6455fb58859538b
[ "MIT" ]
null
null
null
treeintro.cpp
riti2409/Hackto21
ce7ae587a5dce631c01549afe6455fb58859538b
[ "MIT" ]
2
2021-10-04T12:36:44.000Z
2021-10-05T02:54:35.000Z
#include<bits/stdc++.h> using namespace std; struct treenode{ int val; struct treenode *left; struct treenode *right; treenode(int data){ val=data; left=right=NULL; } }; void preorder(treenode*root){ if(!root) return; vector<int>v; cout<<root->val<<" "; preorder(root->left); preorder(root->right); } void innorder(treenode*root){ if(!root) return; vector<int>v; innorder(root->left); cout<<root->val<<" "; innorder(root->right); } void postorder(treenode*root){ if(!root) return; vector<int>v; postorder(root->left); postorder(root->right); cout<<root->val<<" "; } int main(){ treenode * root=new treenode(12); root->left=new treenode(20); root->right=new treenode(10); root->left->left=new treenode(11); root->left->right=new treenode(17); root->right->left=new treenode(15); root->right->right=new treenode(18); cout<<"preorder:"; preorder(root); cout<<" inorder :"; innorder(root); cout<<"postorder :"; postorder(root); return 0; }
20.127273
37
0.593496
[ "vector" ]
4d55b0608f981c7cf696ef3ce94c596e135920fa
2,720
cpp
C++
CUILib/Histogram.cpp
EMinsight/FEBioStudio
d3e6485610d19217550fb94cb22180bc4bda45f9
[ "MIT" ]
null
null
null
CUILib/Histogram.cpp
EMinsight/FEBioStudio
d3e6485610d19217550fb94cb22180bc4bda45f9
[ "MIT" ]
null
null
null
CUILib/Histogram.cpp
EMinsight/FEBioStudio
d3e6485610d19217550fb94cb22180bc4bda45f9
[ "MIT" ]
null
null
null
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2021 University of Utah, The Trustees of Columbia University in the City of New York, and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "stdafx.h" #include "HistogramViewer.h" #include <PostLib/ImageModel.h> #include <ImageLib/3DImage.h> #include <QBoxLayout> #include <QCheckBox> #include <FEBioStudio/PlotWidget.h> using namespace Post; CHistogramViewer::CHistogramViewer(QWidget* parent) : QWidget(parent) { m_logMode = false; m_img = nullptr; m_chart = new CPlotWidget; m_chart->showLegend(false); QCheckBox* cb = new QCheckBox("Logarithmic"); QVBoxLayout* v = new QVBoxLayout; v->addWidget(cb); v->addWidget(m_chart); setLayout(v); QObject::connect(cb, SIGNAL(clicked(bool)), this, SLOT(SetLogMode(bool))); } void CHistogramViewer::SetLogMode(bool b) { if (b != m_logMode) { m_logMode = b; Update(); } } void CHistogramViewer::SetImageModel(CImageModel* img) { m_img = img; Update(); } void CHistogramViewer::Update() { if (m_img == nullptr) return; C3DImage* im = m_img->GetImageSource()->Get3DImage(); vector<double> h(256, 0.0); for (int k = 0; k < im->Depth(); ++k) { for (int j = 0; j < im->Height(); ++j) for (int i = 0; i < im->Width(); ++i) { int n = im->value(i, j, k); h[n]++; } } if (m_logMode) { for (int i = 0; i < 256; ++i) h[i] = log(h[i] + 1.0); } double N = im->Depth()*im->Width()*im->Height(); m_chart->clear(); CPlotData* data = new CPlotData; for (int i = 0; i<256; ++i) data->addPoint(i, h[i] / N); m_chart->addPlotData(data); m_chart->fitHeightToData(); }
26.153846
89
0.715074
[ "vector" ]
4d56a3f535b81ca2f66554275697e3219b9631b9
96,576
cpp
C++
libs/libarchfpga/src/read_fpga_interchange_arch.cpp
amin1377/vtr-verilog-to-routing
700be36e479442fa41d8cb3ceb86e967f4dc078a
[ "MIT" ]
null
null
null
libs/libarchfpga/src/read_fpga_interchange_arch.cpp
amin1377/vtr-verilog-to-routing
700be36e479442fa41d8cb3ceb86e967f4dc078a
[ "MIT" ]
1
2022-03-09T09:36:24.000Z
2022-03-09T09:36:24.000Z
libs/libarchfpga/src/read_fpga_interchange_arch.cpp
amin1377/vtr-verilog-to-routing
700be36e479442fa41d8cb3ceb86e967f4dc078a
[ "MIT" ]
null
null
null
#include <algorithm> #include <kj/std/iostream.h> #include <limits> #include <map> #include <regex> #include <set> #include <stdlib.h> #include <string> #include <string.h> #include <zlib.h> #include "vtr_assert.h" #include "vtr_digest.h" #include "vtr_log.h" #include "vtr_memory.h" #include "vtr_util.h" #include "arch_check.h" #include "arch_error.h" #include "arch_util.h" #include "arch_types.h" #include "read_fpga_interchange_arch.h" /* * FPGA Interchange Device frontend * * This file contains functions to read and parse a Cap'n'proto FPGA interchange device description * and populate the various VTR architecture's internal data structures. * * The Device data is, by default, GZipped, hence the requirement of the ZLIB library to allow * for in-memory decompression of the input file. */ using namespace DeviceResources; using namespace LogicalNetlist; using namespace capnp; // Necessary to reduce code verbosity when getting the pin directions static const auto INPUT = LogicalNetlist::Netlist::Direction::INPUT; static const auto OUTPUT = LogicalNetlist::Netlist::Direction::OUTPUT; static const auto INOUT = LogicalNetlist::Netlist::Direction::INOUT; static const auto LOGIC = Device::BELCategory::LOGIC; static const auto ROUTING = Device::BELCategory::ROUTING; static const auto SITE_PORT = Device::BELCategory::SITE_PORT; // Enum for pack pattern expansion direction enum e_pp_dir { FORWARD = 0, BACKWARD = 1 }; struct t_package_pin { std::string name; std::string site_name; std::string bel_name; }; struct t_bel_cell_mapping { size_t cell; size_t site; std::vector<std::pair<size_t, size_t>> pins; bool operator<(const t_bel_cell_mapping& other) const { return cell < other.cell || (cell == other.cell && site < other.site); } }; // Intermediate data type to store information on interconnects to be created struct t_ic_data { std::string input; std::set<std::string> outputs; bool requires_pack_pattern; }; /****************** Utility functions ******************/ /** * @brief The FPGA interchange timing model includes three different corners (min, typ and max) for each of the two * speed_models (slow and fast). * * Timing data can be found on PIPs, nodes, site pins and bel pins. * This function retrieves the timing value based on the wanted speed model and the wanted corner. * * More information on the FPGA Interchange timing model can be found here: * - https://github.com/chipsalliance/fpga-interchange-schema/blob/main/interchange/DeviceResources.capnp */ static float get_corner_value(Device::CornerModel::Reader model, const char* speed_model, const char* value) { bool slow_model = std::string(speed_model) == std::string("slow"); bool fast_model = std::string(speed_model) == std::string("fast"); bool min_corner = std::string(value) == std::string("min"); bool typ_corner = std::string(value) == std::string("typ"); bool max_corner = std::string(value) == std::string("max"); if (!slow_model && !fast_model) { archfpga_throw("", __LINE__, "Wrong speed model `%s`. Expected `slow` or `fast`\n", speed_model); } if (!min_corner && !typ_corner && !max_corner) { archfpga_throw("", __LINE__, "Wrong corner model `%s`. Expected `min`, `typ` or `max`\n", value); } bool has_fast = model.getFast().hasFast(); bool has_slow = model.getSlow().hasSlow(); if (slow_model && has_slow) { auto half = model.getSlow().getSlow(); if (min_corner && half.getMin().isMin()) { return half.getMin().getMin(); } else if (typ_corner && half.getTyp().isTyp()) { return half.getTyp().getTyp(); } else if (max_corner && half.getMax().isMax()) { return half.getMax().getMax(); } else { if (half.getMin().isMin()) { return half.getMin().getMin(); } else if (half.getTyp().isTyp()) { return half.getTyp().getTyp(); } else if (half.getMax().isMax()) { return half.getMax().getMax(); } else { archfpga_throw("", __LINE__, "Invalid speed model %s. No value found!\n", speed_model); } } } else if (fast_model && has_fast) { auto half = model.getFast().getFast(); if (min_corner && half.getMin().isMin()) { return half.getMin().getMin(); } else if (typ_corner && half.getTyp().isTyp()) { return half.getTyp().getTyp(); } else if (max_corner && half.getMax().isMax()) { return half.getMax().getMax(); } else { if (half.getMin().isMin()) { return half.getMin().getMin(); } else if (half.getTyp().isTyp()) { return half.getTyp().getTyp(); } else if (half.getMax().isMax()) { return half.getMax().getMax(); } else { archfpga_throw("", __LINE__, "Invalid speed model %s. No value found!\n", speed_model); } } } return 0.; } /** @brief Returns the port corresponding to the given model in the architecture */ static t_model_ports* get_model_port(t_arch* arch, std::string model, std::string port, bool fail = true) { for (t_model* m : {arch->models, arch->model_library}) { for (; m != nullptr; m = m->next) { if (std::string(m->name) != model) continue; for (t_model_ports* p : {m->inputs, m->outputs}) for (; p != nullptr; p = p->next) if (std::string(p->name) == port) return p; } } if (fail) archfpga_throw(__FILE__, __LINE__, "Could not find model port: %s (%s)\n", port.c_str(), model.c_str()); return nullptr; } /** @brief Returns the specified architecture model */ static t_model* get_model(t_arch* arch, std::string model) { for (t_model* m : {arch->models, arch->model_library}) for (; m != nullptr; m = m->next) if (std::string(m->name) == model) return m; archfpga_throw(__FILE__, __LINE__, "Could not find model: %s\n", model.c_str()); } /** @brief Returns the physical or logical type by its name */ template<typename T> static T* get_type_by_name(const char* type_name, std::vector<T>& types) { for (auto& type : types) { if (0 == strcmp(type.name, type_name)) { return &type; } } archfpga_throw(__FILE__, __LINE__, "Could not find type: %s\n", type_name); } /** @brief Returns a generic port instantiation for a complex block */ static t_port get_generic_port(t_arch* arch, t_pb_type* pb_type, PORTS dir, std::string name, std::string model = "", int num_pins = 1) { t_port port; port.parent_pb_type = pb_type; port.name = vtr::strdup(name.c_str()); port.num_pins = num_pins; port.index = 0; port.absolute_first_pin_index = 0; port.port_index_by_type = 0; port.equivalent = PortEquivalence::NONE; port.type = dir; port.is_clock = false; port.is_non_clock_global = false; port.model_port = nullptr; port.port_class = vtr::strdup(nullptr); port.port_power = (t_port_power*)vtr::calloc(1, sizeof(t_port_power)); if (!model.empty()) port.model_port = get_model_port(arch, model, name); return port; } /** @brief Returns true if a given port name exists in the given complex block */ static bool block_port_exists(t_pb_type* pb_type, std::string port_name) { for (int iport = 0; iport < pb_type->num_ports; iport++) { const t_port port = pb_type->ports[iport]; if (std::string(port.name) == port_name) return true; } return false; } /** @brief Returns a pack pattern given it's name, input and output strings */ static t_pin_to_pin_annotation get_pack_pattern(std::string pp_name, std::string input, std::string output) { t_pin_to_pin_annotation pp; pp.prop = (int*)vtr::calloc(1, sizeof(int)); pp.value = (char**)vtr::calloc(1, sizeof(char*)); pp.type = E_ANNOT_PIN_TO_PIN_PACK_PATTERN; pp.format = E_ANNOT_PIN_TO_PIN_CONSTANT; pp.prop[0] = (int)E_ANNOT_PIN_TO_PIN_PACK_PATTERN_NAME; pp.value[0] = vtr::strdup(pp_name.c_str()); pp.input_pins = vtr::strdup(input.c_str()); pp.output_pins = vtr::strdup(output.c_str()); pp.num_value_prop_pairs = 1; pp.clock = nullptr; return pp; } /****************** End Utility functions ******************/ struct ArchReader { public: ArchReader(t_arch* arch, Device::Reader& arch_reader, const char* arch_file, std::vector<t_physical_tile_type>& phys_types, std::vector<t_logical_block_type>& logical_types) : arch_(arch) , arch_file_(arch_file) , ar_(arch_reader) , ptypes_(phys_types) , ltypes_(logical_types) { set_arch_file_name(arch_file); for (std::string str : ar_.getStrList()) { auto interned_string = arch_->strings.intern_string(vtr::string_view(str.c_str())); arch_->interned_strings.push_back(interned_string); } } void read_arch() { // Preprocess arch information process_luts(); process_package_pins(); process_cell_bel_mappings(); process_constants(); process_bels_and_sites(); process_models(); process_constant_model(); process_device(); process_layout(); process_switches(); process_segments(); process_sites(); process_constant_block(); process_tiles(); process_constant_tile(); link_physical_logical_types(ptypes_, ltypes_); SyncModelsPbTypes(arch_, ltypes_); check_models(arch_); } private: t_arch* arch_; const char* arch_file_; Device::Reader& ar_; std::vector<t_physical_tile_type>& ptypes_; std::vector<t_logical_block_type>& ltypes_; t_default_fc_spec default_fc_; std::string bel_dedup_suffix_ = "_bel"; std::string const_block_ = "constant_block"; std::unordered_set<int> take_bels_; std::unordered_set<int> take_sites_; // Package pins // TODO: add possibility to have multiple packages std::vector<t_package_pin> package_pins_; std::unordered_set<std::string> pad_bels_; std::string out_suffix_ = "_out"; std::string in_suffix_ = "_in"; // Bel Cell mappings std::unordered_map<uint32_t, std::set<t_bel_cell_mapping>> bel_cell_mappings_; std::unordered_map<std::string, int> segment_name_to_segment_idx; // Utils /** @brief Returns the string corresponding to the given index */ std::string str(size_t idx) { return arch_->interned_strings[idx].get(&arch_->strings); } /** @brief Get the BEL count of a site depending on its category (e.g. logic or routing BELs) */ int get_bel_type_count(Device::SiteType::Reader& site, Device::BELCategory category, bool skip_lut = false) { int count = 0; for (auto bel : site.getBels()) { auto bel_name = str(bel.getName()); bool is_logic = category == LOGIC; if (skip_lut && is_lut(bel_name, str(site.getName()))) continue; bool skip_bel = is_logic && take_bels_.count(bel.getName()) == 0; if (bel.getCategory() == category && !skip_bel) count++; } return count; } /** @brief Get the BEL reader given its name and site */ Device::BEL::Reader get_bel_reader(Device::SiteType::Reader& site, std::string bel_name) { for (auto bel : site.getBels()) if (str(bel.getName()) == bel_name) return bel; VTR_ASSERT_MSG(0, "Could not find the BEL reader!\n"); } /** @brief Get the BEL pin reader given its name, site and corresponding BEL */ Device::BELPin::Reader get_bel_pin_reader(Device::SiteType::Reader& site, Device::BEL::Reader& bel, std::string pin_name) { auto bel_pins = site.getBelPins(); for (auto bel_pin : bel.getPins()) { auto pin_reader = bel_pins[bel_pin]; if (str(pin_reader.getName()) == pin_name) return pin_reader; } VTR_ASSERT_MSG(0, "Could not find the BEL pin reader!\n"); } /** @brief Get the BEL name, with an optional deduplication suffix in case its name collides with the site name */ std::string get_bel_name(Device::SiteType::Reader& site, Device::BEL::Reader& bel) { if (bel.getCategory() == SITE_PORT) return str(site.getName()); auto site_name = str(site.getName()); auto bel_name = str(bel.getName()); return site_name == bel_name ? bel_name + bel_dedup_suffix_ : bel_name; } /** @brief Returns the name of the input argument BEL with optionally the de-duplication suffix removed */ std::string remove_bel_suffix(std::string bel) { std::smatch regex_matches; std::string regex = std::string("(.*)") + bel_dedup_suffix_; const std::regex bel_regex(regex.c_str()); if (std::regex_match(bel, regex_matches, bel_regex)) return regex_matches[1].str(); return bel; } /** @brief Returns true in case the input argument corresponds to the name of a LUT */ bool is_lut(std::string name, const std::string site = std::string()) { for (auto cell : arch_->lut_cells) if (cell.name == name) return true; for (const auto& it : arch_->lut_elements) { if (!site.empty() && site != it.first) { continue; } for (const auto& lut_element : it.second) { for (const auto& lut_bel : lut_element.lut_bels) { if (lut_bel.name == name) { return true; } } } } return false; } t_lut_element* get_lut_element_for_bel(const std::string& site_type, const std::string& bel_name) { if (!arch_->lut_elements.count(site_type)) { return nullptr; } for (auto& lut_element : arch_->lut_elements.at(site_type)) { for (auto& lut_bel : lut_element.lut_bels) { if (lut_bel.name == bel_name) { return &lut_element; } } } return nullptr; } /** @brief Returns true in case the input argument corresponds to a PAD BEL */ bool is_pad(std::string name) { return pad_bels_.count(name) != 0; } /** @brief Utility function to fill in all the necessary information for the sub_tile * * Given a physical tile type and a corresponding sub tile with additional information on the IO pin count * this function populates all the data structures corresponding to the sub tile, and modifies also the parent * physical tile type, updating the pin numberings as well as the directs pin mapping for the equivalent sites * * Affected data structures: * - pinloc * - fc_specs * - equivalent_sites * - tile_block_pin_directs_map **/ void fill_sub_tile(t_physical_tile_type& type, t_sub_tile& sub_tile, int num_pins, int input_count, int output_count) { sub_tile.num_phy_pins += num_pins; type.num_pins += num_pins; type.num_inst_pins += num_pins; type.num_input_pins += input_count; type.num_output_pins += output_count; type.num_receivers += input_count; type.num_drivers += output_count; type.pin_width_offset.resize(type.num_pins, 0); type.pin_height_offset.resize(type.num_pins, 0); type.pinloc.resize({1, 1, 4}, std::vector<bool>(type.num_pins, false)); for (e_side side : {TOP, RIGHT, BOTTOM, LEFT}) { for (int pin = 0; pin < type.num_pins; pin++) { type.pinloc[0][0][side][pin] = true; type.pin_width_offset[pin] = 0; type.pin_height_offset[pin] = 0; } } vtr::bimap<t_logical_pin, t_physical_pin> directs_map; for (int npin = 0; npin < type.num_pins; npin++) { t_physical_pin physical_pin(npin); t_logical_pin logical_pin(npin); directs_map.insert(logical_pin, physical_pin); } auto ltype = get_type_by_name<t_logical_block_type>(sub_tile.name, ltypes_); sub_tile.equivalent_sites.push_back(ltype); type.tile_block_pin_directs_map[ltype->index][sub_tile.index] = directs_map; // Assign FC specs int iblk_pin = 0; for (const auto& port : sub_tile.ports) { t_fc_specification fc_spec; // FIXME: Use always one segment for the time being. // Can use the right segment for this IOPIN as soon // as the RR graph reading from the interchange is complete. fc_spec.seg_index = 0; //Apply type and defaults if (port.type == IN_PORT) { fc_spec.fc_type = e_fc_type::IN; fc_spec.fc_value_type = default_fc_.in_value_type; fc_spec.fc_value = default_fc_.in_value; } else { VTR_ASSERT(port.type == OUT_PORT); fc_spec.fc_type = e_fc_type::OUT; fc_spec.fc_value_type = default_fc_.out_value_type; fc_spec.fc_value = default_fc_.out_value; } //Add all the pins from this port for (int iport_pin = 0; iport_pin < port.num_pins; ++iport_pin) { int true_physical_blk_pin = sub_tile.sub_tile_to_tile_pin_indices[iblk_pin++]; fc_spec.pins.push_back(true_physical_blk_pin); } type.fc_specs.push_back(fc_spec); } } /** @brief Returns an intermediate map representing all the interconnects to be added in a site */ std::unordered_map<std::string, t_ic_data> get_interconnects(Device::SiteType::Reader& site) { // dictionary: // - key: interconnect name // - value: interconnect data std::unordered_map<std::string, t_ic_data> ics; const std::string site_type = str(site.getName()); for (auto wire : site.getSiteWires()) { std::string wire_name = str(wire.getName()); // pin name, bel name int pin_id = OPEN; bool pad_exists = false; bool all_inout_pins = true; std::string pad_bel_name; std::string pad_bel_pin_name; for (auto pin : wire.getPins()) { auto bel_pin = site.getBelPins()[pin]; auto dir = bel_pin.getDir(); std::string bel_pin_name = str(bel_pin.getName()); auto bel = get_bel_reader(site, str(bel_pin.getBel())); auto bel_name = get_bel_name(site, bel); auto bel_is_pad = is_pad(bel_name); pad_exists |= bel_is_pad; all_inout_pins &= dir == INOUT; if (bel_is_pad) { pad_bel_name = bel_name; pad_bel_pin_name = bel_pin_name; } if (dir == OUTPUT) pin_id = pin; } if (pin_id == OPEN) { // If no driver pin has been found, the assumption is that // there must be a PAD with inout pin connected to other inout pins for (auto pin : wire.getPins()) { auto bel_pin = site.getBelPins()[pin]; std::string bel_pin_name = str(bel_pin.getName()); auto bel = get_bel_reader(site, str(bel_pin.getBel())); auto bel_name = get_bel_name(site, bel); if (!is_pad(bel_name)) continue; pin_id = pin; } } VTR_ASSERT(pin_id != OPEN); auto out_pin = site.getBelPins()[pin_id]; auto out_pin_bel = get_bel_reader(site, str(out_pin.getBel())); auto out_pin_name = str(out_pin.getName()); for (auto pin : wire.getPins()) { if ((int)pin == pin_id) continue; auto bel_pin = site.getBelPins()[pin]; std::string out_bel_pin_name = str(bel_pin.getName()); auto out_bel = get_bel_reader(site, str(bel_pin.getBel())); auto out_bel_name = get_bel_name(site, out_bel); auto in_bel = out_pin_bel; auto in_bel_name = get_bel_name(site, in_bel); auto in_bel_pin_name = out_pin_name; bool skip_in_bel = in_bel.getCategory() == LOGIC && take_bels_.count(in_bel.getName()) == 0; bool skip_out_bel = out_bel.getCategory() == LOGIC && take_bels_.count(out_bel.getName()) == 0; if (skip_in_bel || skip_out_bel) continue; // LUT bels are nested under pb_types which represent LUT // elements. Check if a BEL belongs to a LUT element and // adjust pb_type name in the interconnect accordingly. auto get_lut_element_index = [&](const std::string& bel_name) { auto lut_element = get_lut_element_for_bel(site_type, bel_name); if (lut_element == nullptr) return -1; const auto& lut_elements = arch_->lut_elements.at(site_type); auto it = std::find(lut_elements.begin(), lut_elements.end(), *lut_element); VTR_ASSERT(it != lut_elements.end()); return (int)std::distance(lut_elements.begin(), it); }; // TODO: This avoids having LUTs that can be used in other ways than LUTs, e.g. as DRAMs. // Once support is added for macro expansion, all the connections currently marked as // invalid will be re-enabled. auto is_lut_connection_valid = [&](const std::string& bel_name, const std::string& pin_name) { auto lut_element = get_lut_element_for_bel(site_type, bel_name); if (lut_element == nullptr) return false; bool pin_found = false; for (auto lut_bel : lut_element->lut_bels) { for (auto lut_bel_pin : lut_bel.input_pins) pin_found |= lut_bel_pin == pin_name; pin_found |= lut_bel.output_pin == pin_name; } if (!pin_found) return false; return true; }; int index = get_lut_element_index(out_bel_name); bool valid_lut = is_lut_connection_valid(out_bel_name, out_bel_pin_name); if (index >= 0) { out_bel_name = "LUT" + std::to_string(index); if (!valid_lut) continue; } index = get_lut_element_index(in_bel_name); valid_lut = is_lut_connection_valid(in_bel_name, in_bel_pin_name); if (index >= 0) { in_bel_name = "LUT" + std::to_string(index); if (!valid_lut) continue; } std::string ostr = out_bel_name + "." + out_bel_pin_name; std::string istr = in_bel_name + "." + in_bel_pin_name; // TODO: If the bel pin is INOUT (e.g. PULLDOWN/PULLUP in Series7) // for now treat as input only and assign the in suffix if (bel_pin.getDir() == INOUT && !all_inout_pins && !is_pad(out_bel_name)) ostr += in_suffix_; auto ic_name = wire_name + "_" + out_bel_pin_name; bool requires_pack_pattern = pad_exists; std::vector<std::pair<std::string, t_ic_data>> ics_data; if (all_inout_pins) { std::string extra_istr = out_bel_name + "." + out_bel_pin_name + out_suffix_; std::string extra_ostr = in_bel_name + "." + in_bel_pin_name + in_suffix_; std::string extra_ic_name = ic_name + "_extra"; std::set<std::string> extra_ostrs{extra_ostr}; t_ic_data extra_ic_data = { extra_istr, // ic input extra_ostrs, // ic outputs requires_pack_pattern // pack pattern required }; ics_data.push_back(std::make_pair(extra_ic_name, extra_ic_data)); istr += out_suffix_; ostr += in_suffix_; } else if (pad_exists) { if (out_bel_name == pad_bel_name) ostr += in_suffix_; else { // Create new wire to connect PAD output to the BELs input ic_name = wire_name + "_" + pad_bel_pin_name + out_suffix_; istr = pad_bel_name + "." + pad_bel_pin_name + out_suffix_; } } std::set<std::string> ostrs{ostr}; t_ic_data ic_data = { istr, ostrs, requires_pack_pattern}; ics_data.push_back(std::make_pair(ic_name, ic_data)); for (auto entry : ics_data) { auto name = entry.first; auto data = entry.second; auto res = ics.emplace(name, data); if (!res.second) { auto old_data = res.first->second; VTR_ASSERT(old_data.input == data.input); VTR_ASSERT(data.outputs.size() == 1); for (auto out : data.outputs) res.first->second.outputs.insert(out); res.first->second.requires_pack_pattern |= data.requires_pack_pattern; } } } } return ics; } /** * Preprocessors: * - process_bels_and_sites: information on whether sites and bels need to be expanded in pb types * - process_luts: processes information on which cells and bels are LUTs * - process_package_pins: processes information on the device's pinout and which sites and bels * contain IO pads * - process_cell_bel_mapping: processes mappings between a cell and the possible BELs location for that cell * - process_constants: processes constants cell and net names */ void process_bels_and_sites() { auto tiles = ar_.getTileList(); auto tile_types = ar_.getTileTypeList(); auto site_types = ar_.getSiteTypeList(); for (auto tile : tiles) { auto tile_type = tile_types[tile.getType()]; for (auto site : tile.getSites()) { auto site_type_in_tile = tile_type.getSiteTypes()[site.getType()]; auto site_type = site_types[site_type_in_tile.getPrimaryType()]; bool found = false; for (auto bel : site_type.getBels()) { auto bel_name = bel.getName(); bool res = bel_cell_mappings_.find(bel_name) != bel_cell_mappings_.end(); found |= res; if (res || is_pad(str(bel_name))) take_bels_.insert(bel_name); } if (found) take_sites_.insert(site_type.getName()); // TODO: Enable also alternative site types handling } } } void process_luts() { // Add LUT Cell definitions // This is helpful to understand which cells are LUTs auto lut_def = ar_.getLutDefinitions(); for (auto lut_cell : lut_def.getLutCells()) { t_lut_cell cell; cell.name = lut_cell.getCell().cStr(); for (auto input : lut_cell.getInputPins()) cell.inputs.push_back(input.cStr()); auto equation = lut_cell.getEquation(); if (equation.isInitParam()) cell.init_param = equation.getInitParam().cStr(); arch_->lut_cells.push_back(cell); } for (auto lut_elem : lut_def.getLutElements()) { for (auto lut : lut_elem.getLuts()) { t_lut_element element; element.site_type = lut_elem.getSite().cStr(); element.width = lut.getWidth(); for (auto bel : lut.getBels()) { t_lut_bel lut_bel; lut_bel.name = bel.getName().cStr(); std::vector<std::string> ipins; for (auto pin : bel.getInputPins()) ipins.push_back(pin.cStr()); lut_bel.input_pins = ipins; lut_bel.output_pin = bel.getOutputPin().cStr(); element.lut_bels.push_back(lut_bel); } arch_->lut_elements[element.site_type].push_back(element); } } } void process_package_pins() { for (auto package : ar_.getPackages()) { for (auto pin : package.getPackagePins()) { t_package_pin pckg_pin; pckg_pin.name = str(pin.getPackagePin()); if (pin.getBel().isBel()) { pckg_pin.bel_name = str(pin.getBel().getBel()); pad_bels_.insert(pckg_pin.bel_name); } if (pin.getSite().isSite()) pckg_pin.site_name = str(pin.getSite().getSite()); package_pins_.push_back(pckg_pin); } } } void process_cell_bel_mappings() { auto primLib = ar_.getPrimLibs(); auto portList = primLib.getPortList(); for (auto cell_mapping : ar_.getCellBelMap()) { size_t cell_name = cell_mapping.getCell(); int found_valid_prim = false; for (auto primitive : primLib.getCellDecls()) { bool is_prim = str(primitive.getLib()) == std::string("primitives"); bool is_cell = cell_name == primitive.getName(); bool has_inout = false; for (auto port_idx : primitive.getPorts()) { auto port = portList[port_idx]; if (port.getDir() == INOUT) { has_inout = true; break; } } if (is_prim && is_cell && !has_inout) { found_valid_prim = true; break; } } if (!found_valid_prim) continue; for (auto common_pins : cell_mapping.getCommonPins()) { std::vector<std::pair<size_t, size_t>> pins; for (auto pin_map : common_pins.getPins()) pins.emplace_back(pin_map.getCellPin(), pin_map.getBelPin()); for (auto site_type_entry : common_pins.getSiteTypes()) { size_t site_type = site_type_entry.getSiteType(); for (auto bel : site_type_entry.getBels()) { t_bel_cell_mapping mapping; mapping.cell = cell_name; mapping.site = site_type; mapping.pins = pins; std::set<t_bel_cell_mapping> maps{mapping}; auto res = bel_cell_mappings_.emplace(bel, maps); if (!res.second) { res.first->second.insert(mapping); } } } } } } void process_constants() { auto consts = ar_.getConstants(); arch_->gnd_cell = std::make_pair(str(consts.getGndCellType()), str(consts.getGndCellPin())); arch_->vcc_cell = std::make_pair(str(consts.getVccCellType()), str(consts.getVccCellPin())); arch_->gnd_net = consts.getGndNetName().isName() ? str(consts.getGndNetName().getName()) : "$__gnd_net"; arch_->vcc_net = consts.getVccNetName().isName() ? str(consts.getVccNetName().getName()) : "$__vcc_net"; } /* end preprocessors */ // Model processing void process_models() { // Populate the common library, namely .inputs, .outputs, .names, .latches CreateModelLibrary(arch_); t_model* temp = nullptr; std::map<std::string, int> model_name_map; std::pair<std::map<std::string, int>::iterator, bool> ret_map_name; int model_index = NUM_MODELS_IN_LIBRARY; arch_->models = nullptr; auto primLib = ar_.getPrimLibs(); for (auto primitive : primLib.getCellDecls()) { if (str(primitive.getLib()) == std::string("primitives")) { std::string prim_name = str(primitive.getName()); if (is_lut(prim_name)) continue; // Check whether the model can be placed in at least one // BEL that was marked as valid (e.g. added to the take_bels_ data structure) bool has_bel = false; for (auto bel_cell_map : bel_cell_mappings_) { auto bel_name = bel_cell_map.first; bool take_bel = take_bels_.count(bel_name) != 0; if (!take_bel || is_lut(str(bel_name))) continue; for (auto map : bel_cell_map.second) has_bel |= primitive.getName() == map.cell; } if (!has_bel) continue; try { temp = new t_model; temp->index = model_index++; temp->never_prune = true; temp->name = vtr::strdup(prim_name.c_str()); ret_map_name = model_name_map.insert(std::pair<std::string, int>(temp->name, 0)); if (!ret_map_name.second) { archfpga_throw(arch_file_, __LINE__, "Duplicate model name: '%s'.\n", temp->name); } if (!process_model_ports(temp, primitive)) { free_arch_model(temp); continue; } check_model_clocks(temp, arch_file_, __LINE__); check_model_combinational_sinks(temp, arch_file_, __LINE__); warn_model_missing_timing(temp, arch_file_, __LINE__); } catch (ArchFpgaError& e) { free_arch_model(temp); throw; } temp->next = arch_->models; arch_->models = temp; } } } bool process_model_ports(t_model* model, Netlist::CellDeclaration::Reader primitive) { auto primLib = ar_.getPrimLibs(); auto portList = primLib.getPortList(); std::set<std::pair<std::string, enum PORTS>> port_names; for (auto port_idx : primitive.getPorts()) { auto port = portList[port_idx]; enum PORTS dir = ERR_PORT; switch (port.getDir()) { case INPUT: dir = IN_PORT; break; case OUTPUT: dir = OUT_PORT; break; case INOUT: return false; break; default: break; } t_model_ports* model_port = new t_model_ports; model_port->dir = dir; model_port->name = vtr::strdup(str(port.getName()).c_str()); // TODO: add parsing of clock port types when the interchange schema allows for it: // https://github.com/chipsalliance/fpga-interchange-schema/issues/66 //Sanity checks if (model_port->is_clock == true && model_port->is_non_clock_global == true) { archfpga_throw(arch_file_, __LINE__, "Model port '%s' cannot be both a clock and a non-clock signal simultaneously", model_port->name); } if (model_port->name == nullptr) { archfpga_throw(arch_file_, __LINE__, "Model port is missing a name"); } if (port_names.count(std::pair<std::string, enum PORTS>(model_port->name, dir)) && dir != INOUT_PORT) { archfpga_throw(arch_file_, __LINE__, "Duplicate model port named '%s'", model_port->name); } if (dir == OUT_PORT && !model_port->combinational_sink_ports.empty()) { archfpga_throw(arch_file_, __LINE__, "Model output ports can not have combinational sink ports"); } model_port->min_size = 1; model_port->size = 1; if (port.isBus()) { int s = port.getBus().getBusStart(); int e = port.getBus().getBusEnd(); model_port->size = std::abs(e - s) + 1; } port_names.insert(std::pair<std::string, enum PORTS>(model_port->name, dir)); //Add the port if (dir == IN_PORT) { model_port->next = model->inputs; model->inputs = model_port; } else if (dir == OUT_PORT) { model_port->next = model->outputs; model->outputs = model_port; } } return true; } // Complex Blocks void process_sites() { auto siteTypeList = ar_.getSiteTypeList(); int index = 0; // TODO: Make this dynamic depending on data from the interchange auto EMPTY = get_empty_logical_type(); EMPTY.index = index; ltypes_.push_back(EMPTY); for (auto site : siteTypeList) { auto bels = site.getBels(); if (bels.size() == 0) continue; t_logical_block_type ltype; std::string name = str(site.getName()); if (take_sites_.count(site.getName()) == 0) continue; // Check for duplicates auto is_duplicate = [name](t_logical_block_type l) { return std::string(l.name) == name; }; VTR_ASSERT(std::find_if(ltypes_.begin(), ltypes_.end(), is_duplicate) == ltypes_.end()); ltype.name = vtr::strdup(name.c_str()); ltype.index = ++index; auto pb_type = new t_pb_type; ltype.pb_type = pb_type; pb_type->name = vtr::strdup(name.c_str()); pb_type->num_pb = 1; process_block_ports(pb_type, site); // Process modes (for simplicity, only the default mode is allowed for the time being) pb_type->num_modes = 1; pb_type->modes = new t_mode[pb_type->num_modes]; auto mode = &pb_type->modes[0]; mode->parent_pb_type = pb_type; mode->index = 0; mode->name = vtr::strdup("default"); mode->disable_packing = false; // Get LUT elements for this site std::vector<t_lut_element> lut_elements; if (arch_->lut_elements.count(name)) lut_elements = arch_->lut_elements.at(name); // Count non-LUT BELs plus LUT elements int block_count = get_bel_type_count(site, LOGIC, true) + get_bel_type_count(site, ROUTING, true) + lut_elements.size(); mode->num_pb_type_children = block_count; mode->pb_type_children = new t_pb_type[mode->num_pb_type_children]; // Add regular BELs int count = 0; for (auto bel : bels) { auto category = bel.getCategory(); if (bel.getCategory() == SITE_PORT) continue; bool is_logic = category == LOGIC; if (take_bels_.count(bel.getName()) == 0 && is_logic) continue; if (is_lut(str(bel.getName()), name)) continue; auto bel_name = str(bel.getName()); std::pair<std::string, std::string> key(name, bel_name); auto mid_pb_type = &mode->pb_type_children[count++]; std::string mid_pb_type_name = bel_name == name ? bel_name + bel_dedup_suffix_ : bel_name; mid_pb_type->name = vtr::strdup(mid_pb_type_name.c_str()); mid_pb_type->num_pb = 1; mid_pb_type->parent_mode = mode; mid_pb_type->blif_model = nullptr; if (!is_pad(bel_name)) process_block_ports(mid_pb_type, site, bel.getName()); if (is_pad(bel_name)) process_pad_block(mid_pb_type, bel, site); else if (is_logic) process_generic_block(mid_pb_type, bel, site); else { VTR_ASSERT(category == ROUTING); process_routing_block(mid_pb_type); } } // Add LUT elements for (size_t i = 0; i < lut_elements.size(); ++i) { const auto& lut_element = lut_elements[i]; auto mid_pb_type = &mode->pb_type_children[count++]; std::string lut_name = "LUT" + std::to_string(i); mid_pb_type->name = vtr::strdup(lut_name.c_str()); mid_pb_type->num_pb = 1; mid_pb_type->parent_mode = mode; mid_pb_type->blif_model = nullptr; process_lut_element(mid_pb_type, lut_element); } process_interconnects(mode, site); ltypes_.push_back(ltype); } } /** @brief Processes a LUT element starting from the intermediate pb type */ void process_lut_element(t_pb_type* parent, const t_lut_element& lut_element) { // Collect ports for the parent pb_type representing the whole LUT // element std::set<std::tuple<std::string, PORTS, int>> parent_ports; for (const auto& lut_bel : lut_element.lut_bels) { for (const auto& name : lut_bel.input_pins) { parent_ports.emplace(name, IN_PORT, 1); } parent_ports.emplace(lut_bel.output_pin, OUT_PORT, 1); } // Create the ports create_ports(parent, parent_ports); // Make a single mode for each member LUT of the LUT element parent->num_modes = (int)lut_element.lut_bels.size(); parent->modes = new t_mode[parent->num_modes]; for (size_t i = 0; i < lut_element.lut_bels.size(); ++i) { const t_lut_bel& lut_bel = lut_element.lut_bels[i]; auto mode = &parent->modes[i]; mode->name = vtr::strdup(lut_bel.name.c_str()); mode->parent_pb_type = parent; mode->index = i; // Leaf pb_type block for the LUT mode->num_pb_type_children = 1; mode->pb_type_children = new t_pb_type[mode->num_pb_type_children]; auto pb_type = &mode->pb_type_children[0]; pb_type->name = vtr::strdup(lut_bel.name.c_str()); pb_type->num_pb = 1; pb_type->parent_mode = mode; pb_type->blif_model = nullptr; process_lut_block(pb_type, lut_bel); // Mode interconnect mode->num_interconnect = lut_bel.input_pins.size() + 1; mode->interconnect = new t_interconnect[mode->num_interconnect]; std::string istr, ostr, name; // Inputs for (size_t j = 0; j < lut_bel.input_pins.size(); ++j) { auto* ic = &mode->interconnect[j]; ic->type = DIRECT_INTERC; ic->parent_mode = mode; ic->parent_mode_index = mode->index; istr = std::string(parent->name) + "." + lut_bel.input_pins[j]; ostr = std::string(pb_type->name) + ".in[" + std::to_string(j) + "]"; name = istr + "_to_" + ostr; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); ic->name = vtr::strdup(name.c_str()); } // Output auto* ic = &mode->interconnect[mode->num_interconnect - 1]; ic->type = DIRECT_INTERC; ic->parent_mode = mode; ic->parent_mode_index = mode->index; istr = std::string(pb_type->name) + ".out"; ostr = std::string(parent->name) + "." + lut_bel.output_pin; name = istr + "_to_" + ostr; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); ic->name = vtr::strdup(name.c_str()); } } /** @brief Processes a LUT primitive starting from the intermediate pb type */ void process_lut_block(t_pb_type* pb_type, const t_lut_bel& lut_bel) { // Create port list size_t width = lut_bel.input_pins.size(); std::set<std::tuple<std::string, PORTS, int>> ports; ports.emplace("in", IN_PORT, width); ports.emplace("out", OUT_PORT, 1); create_ports(pb_type, ports); // Make two modes. One for LUT-thru and another for the actual LUT bel pb_type->num_modes = 2; pb_type->modes = new t_mode[pb_type->num_modes]; // ................................................ // LUT-thru t_mode* mode = &pb_type->modes[0]; // Mode mode->name = vtr::strdup("wire"); mode->parent_pb_type = pb_type; mode->index = 0; mode->num_pb_type_children = 0; // Mode interconnect mode->num_interconnect = 1; mode->interconnect = new t_interconnect[mode->num_interconnect]; t_interconnect* ic = &mode->interconnect[0]; std::string istr, ostr, name; istr = std::string(pb_type->name) + ".in"; ostr = std::string(pb_type->name) + ".out"; name = "passthrough"; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); ic->name = vtr::strdup(name.c_str()); ic->type = COMPLETE_INTERC; ic->parent_mode = mode; ic->parent_mode_index = mode->index; // ................................................ // LUT BEL mode = &pb_type->modes[1]; // Mode mode->name = vtr::strdup("lut"); mode->parent_pb_type = pb_type; mode->index = 1; // Leaf pb_type mode->num_pb_type_children = 1; mode->pb_type_children = new t_pb_type[mode->num_pb_type_children]; auto lut = &mode->pb_type_children[0]; lut->name = vtr::strdup("lut"); lut->num_pb = 1; lut->parent_mode = mode; lut->blif_model = vtr::strdup(MODEL_NAMES); lut->model = get_model(arch_, std::string(MODEL_NAMES)); lut->num_ports = 2; lut->ports = (t_port*)vtr::calloc(lut->num_ports, sizeof(t_port)); lut->ports[0] = get_generic_port(arch_, lut, IN_PORT, "in", MODEL_NAMES, width); lut->ports[1] = get_generic_port(arch_, lut, OUT_PORT, "out", MODEL_NAMES); lut->ports[0].equivalent = PortEquivalence::FULL; // Set classes pb_type->class_type = LUT_CLASS; lut->class_type = LUT_CLASS; lut->ports[0].port_class = vtr::strdup("lut_in"); lut->ports[1].port_class = vtr::strdup("lut_out"); // Mode interconnect mode->num_interconnect = 2; mode->interconnect = new t_interconnect[mode->num_interconnect]; // Input ic = &mode->interconnect[0]; ic->type = DIRECT_INTERC; ic->parent_mode = mode; ic->parent_mode_index = mode->index; istr = std::string(pb_type->name) + ".in"; ostr = std::string(lut->name) + ".in"; name = istr + "_to_" + ostr; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); ic->name = vtr::strdup(name.c_str()); // Output ic = &mode->interconnect[1]; ic->type = DIRECT_INTERC; ic->parent_mode = mode; ic->parent_mode_index = mode->index; istr = std::string(lut->name) + ".out"; ostr = std::string(pb_type->name) + ".out"; name = istr + "_to_" + ostr; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); ic->name = vtr::strdup(name.c_str()); } /** @brief Generates the leaf pb types for the PAD type */ void process_pad_block(t_pb_type* pad, Device::BEL::Reader& bel, Device::SiteType::Reader& site) { // For now, hard-code two modes for pads, so that PADs can either be IPADs or OPADs pad->num_modes = 2; pad->modes = new t_mode[2]; // Add PAD pb_type ports VTR_ASSERT(bel.getPins().size() == 1); std::string pin = str(site.getBelPins()[bel.getPins()[0]].getName()); std::string ipin = pin + in_suffix_; std::string opin = pin + out_suffix_; auto num_ports = 2; auto ports = new t_port[num_ports]; pad->ports = ports; pad->num_ports = pad->num_pins = num_ports; pad->num_input_pins = 1; pad->num_output_pins = 1; int pin_abs = 0; int pin_count = 0; for (auto dir : {IN_PORT, OUT_PORT}) { int pins_dir_count = 0; t_port* port = &ports[pin_count]; port->parent_pb_type = pad; port->index = pin_count++; port->port_index_by_type = pins_dir_count++; port->absolute_first_pin_index = pin_abs++; port->equivalent = PortEquivalence::NONE; port->num_pins = 1; port->type = dir; port->is_clock = false; bool is_input = dir == IN_PORT; port->name = is_input ? vtr::strdup(ipin.c_str()) : vtr::strdup(opin.c_str()); port->model_port = nullptr; port->port_class = vtr::strdup(nullptr); port->port_power = (t_port_power*)vtr::calloc(1, sizeof(t_port_power)); } // OPAD mode auto omode = &pad->modes[0]; omode->name = vtr::strdup("opad"); omode->parent_pb_type = pad; omode->index = 0; omode->num_pb_type_children = 1; omode->pb_type_children = new t_pb_type[1]; auto opad = new t_pb_type; opad->name = vtr::strdup("opad"); opad->num_pb = 1; opad->parent_mode = omode; num_ports = 1; opad->num_ports = num_ports; opad->ports = (t_port*)vtr::calloc(num_ports, sizeof(t_port)); opad->blif_model = vtr::strdup(MODEL_OUTPUT); opad->model = get_model(arch_, std::string(MODEL_OUTPUT)); opad->ports[0] = get_generic_port(arch_, opad, IN_PORT, "outpad", MODEL_OUTPUT); omode->pb_type_children[0] = *opad; // IPAD mode auto imode = &pad->modes[1]; imode->name = vtr::strdup("ipad"); imode->parent_pb_type = pad; imode->index = 1; imode->num_pb_type_children = 1; imode->pb_type_children = new t_pb_type[1]; auto ipad = new t_pb_type; ipad->name = vtr::strdup("ipad"); ipad->num_pb = 1; ipad->parent_mode = imode; num_ports = 1; ipad->num_ports = num_ports; ipad->ports = (t_port*)vtr::calloc(num_ports, sizeof(t_port)); ipad->blif_model = vtr::strdup(MODEL_INPUT); ipad->model = get_model(arch_, std::string(MODEL_INPUT)); ipad->ports[0] = get_generic_port(arch_, ipad, OUT_PORT, "inpad", MODEL_INPUT); imode->pb_type_children[0] = *ipad; // Handle interconnects int num_pins = 1; omode->num_interconnect = num_pins; omode->interconnect = new t_interconnect[num_pins]; imode->num_interconnect = num_pins; imode->interconnect = new t_interconnect[num_pins]; std::string opad_istr = std::string(pad->name) + std::string(".") + ipin; std::string opad_ostr = std::string(opad->name) + std::string(".outpad"); std::string o_ic_name = std::string(pad->name) + std::string("_") + std::string(opad->name); std::string ipad_istr = std::string(ipad->name) + std::string(".inpad"); std::string ipad_ostr = std::string(pad->name) + std::string(".") + opin; std::string i_ic_name = std::string(ipad->name) + std::string("_") + std::string(pad->name); auto o_ic = new t_interconnect[num_pins]; auto i_ic = new t_interconnect[num_pins]; o_ic->name = vtr::strdup(o_ic_name.c_str()); o_ic->type = DIRECT_INTERC; o_ic->parent_mode_index = 0; o_ic->parent_mode = omode; o_ic->input_string = vtr::strdup(opad_istr.c_str()); o_ic->output_string = vtr::strdup(opad_ostr.c_str()); i_ic->name = vtr::strdup(i_ic_name.c_str()); i_ic->type = DIRECT_INTERC; i_ic->parent_mode_index = 0; i_ic->parent_mode = imode; i_ic->input_string = vtr::strdup(ipad_istr.c_str()); i_ic->output_string = vtr::strdup(ipad_ostr.c_str()); omode->interconnect[0] = *o_ic; imode->interconnect[0] = *i_ic; } /** @brief Generates the leaf pb types for a generic intermediate block, with as many modes * as the number of models that can be used in this complex block. */ void process_generic_block(t_pb_type* pb_type, Device::BEL::Reader& bel, Device::SiteType::Reader& site) { std::string pb_name = std::string(pb_type->name); std::set<t_bel_cell_mapping> maps(bel_cell_mappings_[bel.getName()]); std::vector<t_bel_cell_mapping> map_to_erase; for (auto map : maps) { auto name = str(map.cell); bool is_compatible = map.site == site.getName(); for (auto pin_map : map.pins) { if (is_compatible == false) break; auto cell_pin = str(pin_map.first); auto bel_pin = str(pin_map.second); if (cell_pin == arch_->vcc_cell.first || cell_pin == arch_->gnd_cell.first) continue; // Assign suffix to bel pin as it is a inout pin which was split in out and in ports auto pin_reader = get_bel_pin_reader(site, bel, bel_pin); bool is_inout = pin_reader.getDir() == INOUT; auto model_port = get_model_port(arch_, name, cell_pin, false); if (is_inout && model_port != nullptr) bel_pin = model_port->dir == IN_PORT ? bel_pin + in_suffix_ : bel_pin + out_suffix_; is_compatible &= block_port_exists(pb_type, bel_pin); } if (!is_compatible) map_to_erase.push_back(map); } for (auto map : map_to_erase) VTR_ASSERT(maps.erase(map) == 1); int num_modes = maps.size(); VTR_ASSERT(num_modes > 0); pb_type->num_modes = num_modes; pb_type->modes = new t_mode[num_modes]; int count = 0; for (auto map : maps) { if (map.site != site.getName()) continue; int idx = count++; t_mode* mode = &pb_type->modes[idx]; auto name = str(map.cell); mode->name = vtr::strdup(name.c_str()); mode->parent_pb_type = pb_type; mode->index = idx; mode->num_pb_type_children = 1; mode->pb_type_children = new t_pb_type[1]; auto leaf = &mode->pb_type_children[0]; std::string leaf_name = name == std::string(pb_type->name) ? name + std::string("_leaf") : name; leaf->name = vtr::strdup(leaf_name.c_str()); leaf->num_pb = 1; leaf->parent_mode = mode; // Pre-count pins int ic_count = 0; for (auto pin_map : map.pins) { auto cell_pin = str(pin_map.first); if (cell_pin == arch_->vcc_cell.first || cell_pin == arch_->gnd_cell.first) continue; ic_count++; } int num_ports = ic_count; leaf->num_ports = num_ports; leaf->ports = (t_port*)vtr::calloc(num_ports, sizeof(t_port)); leaf->blif_model = vtr::strdup((std::string(".subckt ") + name).c_str()); leaf->model = get_model(arch_, name); mode->num_interconnect = num_ports; mode->interconnect = new t_interconnect[num_ports]; std::set<std::tuple<std::string, PORTS, int>> pins; ic_count = 0; for (auto pin_map : map.pins) { auto cell_pin = str(pin_map.first); auto bel_pin = str(pin_map.second); if (cell_pin == arch_->vcc_cell.first || cell_pin == arch_->gnd_cell.first) continue; std::smatch regex_matches; std::string pin_suffix; const std::regex port_regex("([0-9A-Za-z-]+)\\[([0-9]+)\\]"); if (std::regex_match(cell_pin, regex_matches, port_regex)) { cell_pin = regex_matches[1].str(); pin_suffix = std::string("[") + regex_matches[2].str() + std::string("]"); } auto model_port = get_model_port(arch_, name, cell_pin); auto size = model_port->size; auto dir = model_port->dir; // Assign suffix to bel pin as it is a inout pin which was split in out and in ports auto pin_reader = get_bel_pin_reader(site, bel, bel_pin); bool is_inout = pin_reader.getDir() == INOUT; pins.emplace(cell_pin, dir, size); std::string istr, ostr, ic_name; switch (dir) { case IN_PORT: bel_pin = is_inout ? bel_pin + in_suffix_ : bel_pin; istr = pb_name + std::string(".") + bel_pin; ostr = leaf_name + std::string(".") + cell_pin + pin_suffix; break; case OUT_PORT: bel_pin = is_inout ? bel_pin + out_suffix_ : bel_pin; istr = leaf_name + std::string(".") + cell_pin + pin_suffix; ostr = pb_name + std::string(".") + bel_pin; break; default: VTR_ASSERT(0); } ic_name = istr + std::string("_") + ostr; auto ic = &mode->interconnect[ic_count++]; ic->name = vtr::strdup(ic_name.c_str()); ic->type = DIRECT_INTERC; ic->parent_mode_index = idx; ic->parent_mode = mode; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); } create_ports(leaf, pins, name); } } /** @brief Generates a routing block to allow for cascading routing blocks to be * placed in the same complex block type. */ void process_routing_block(t_pb_type* pb_type) { pb_type->num_modes = 1; pb_type->modes = new t_mode[1]; int idx = 0; auto mode = &pb_type->modes[idx]; std::string name = std::string(pb_type->name); mode->name = vtr::strdup(name.c_str()); mode->parent_pb_type = pb_type; mode->index = idx; mode->num_pb_type_children = 0; std::string istr, ostr, ic_name; // The MUX interconnections can only have a single output VTR_ASSERT(pb_type->num_output_pins == 1); for (int iport = 0; iport < pb_type->num_ports; iport++) { const t_port port = pb_type->ports[iport]; auto port_name = name + "." + std::string(port.name); switch (port.type) { case IN_PORT: istr += istr.empty() ? port_name : " " + port_name; break; case OUT_PORT: ostr = port_name; break; default: VTR_ASSERT(0); } } ic_name = std::string(pb_type->name); mode->num_interconnect = 1; mode->interconnect = new t_interconnect[1]; e_interconnect ic_type = pb_type->num_input_pins == 1 ? DIRECT_INTERC : MUX_INTERC; auto ic = &mode->interconnect[idx]; ic->name = vtr::strdup(ic_name.c_str()); ic->type = ic_type; ic->parent_mode_index = idx; ic->parent_mode = mode; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); } /** @brief Processes all the ports of a given complex block. * If a bel name index is specified, the bel pins are processed, otherwise the site ports * are processed instead. */ void process_block_ports(t_pb_type* pb_type, Device::SiteType::Reader& site, size_t bel_name = OPEN) { // Prepare data based on pb_type level std::set<std::tuple<std::string, PORTS, int>> pins; if (bel_name == (size_t)OPEN) { for (auto pin : site.getPins()) { auto dir = pin.getDir() == INPUT ? IN_PORT : OUT_PORT; pins.emplace(str(pin.getName()), dir, 1); } } else { auto bel = get_bel_reader(site, str(bel_name)); for (auto bel_pin : bel.getPins()) { auto pin = site.getBelPins()[bel_pin]; auto dir = pin.getDir(); switch (dir) { case INPUT: pins.emplace(str(pin.getName()), IN_PORT, 1); break; case OUTPUT: pins.emplace(str(pin.getName()), OUT_PORT, 1); break; case INOUT: pins.emplace(str(pin.getName()) + in_suffix_, IN_PORT, 1); pins.emplace(str(pin.getName()) + out_suffix_, OUT_PORT, 1); break; default: VTR_ASSERT(0); } } } create_ports(pb_type, pins); } /** @brief Generates all the port for a complex block, given its pointer and a map of ports (key) and their direction and width */ void create_ports(t_pb_type* pb_type, std::set<std::tuple<std::string, PORTS, int>>& pins, std::string model = "") { std::unordered_set<std::string> names; auto num_ports = pins.size(); auto ports = new t_port[num_ports]; pb_type->ports = ports; pb_type->num_ports = pb_type->num_pins = num_ports; pb_type->num_input_pins = 0; pb_type->num_output_pins = 0; int pin_abs = 0; int pin_count = 0; for (auto dir : {IN_PORT, OUT_PORT}) { int pins_dir_count = 0; for (auto pin_tuple : pins) { std::string pin_name; PORTS pin_dir; int num_pins; std::tie(pin_name, pin_dir, num_pins) = pin_tuple; if (pin_dir != dir) continue; bool is_input = dir == IN_PORT; pb_type->num_input_pins += is_input ? 1 : 0; pb_type->num_output_pins += is_input ? 0 : 1; auto port = get_generic_port(arch_, pb_type, dir, pin_name, /*string_model=*/"", num_pins); ports[pin_count] = port; port.index = pin_count++; port.port_index_by_type = pins_dir_count++; port.absolute_first_pin_index = pin_abs++; if (!model.empty()) port.model_port = get_model_port(arch_, model, pin_name); } } } /** @brief Processes and creates the interconnects corresponding to a given mode */ void process_interconnects(t_mode* mode, Device::SiteType::Reader& site) { auto ics = get_interconnects(site); auto num_ic = ics.size(); mode->num_interconnect = num_ic; mode->interconnect = new t_interconnect[num_ic]; int curr_ic = 0; std::unordered_set<std::string> names; // Handle site wires, namely direct interconnects for (auto ic_pair : ics) { auto ic_name = ic_pair.first; auto ic_data = ic_pair.second; auto input = ic_data.input; auto outputs = ic_data.outputs; auto merge_string = [](std::string ss, std::string s) { return ss.empty() ? s : ss + " " + s; }; std::string outputs_str = std::accumulate(outputs.begin(), outputs.end(), std::string(), merge_string); t_interconnect* ic = &mode->interconnect[curr_ic++]; // No line num for interconnects, as line num is XML specific // TODO: probably line_num should be deprecated as it is dependent // on the input architecture format. ic->line_num = 0; ic->type = DIRECT_INTERC; ic->parent_mode_index = mode->index; ic->parent_mode = mode; VTR_ASSERT(names.insert(ic_name).second); ic->name = vtr::strdup(ic_name.c_str()); ic->input_string = vtr::strdup(input.c_str()); ic->output_string = vtr::strdup(outputs_str.c_str()); } // Checks and, in case, adds all the necessary pack patterns to the marked interconnects for (size_t iic = 0; iic < num_ic; iic++) { t_interconnect* ic = &mode->interconnect[iic]; auto ic_data = ics.at(std::string(ic->name)); if (ic_data.requires_pack_pattern) { auto backward_pps_map = propagate_pack_patterns(ic, site, BACKWARD); auto forward_pps_map = propagate_pack_patterns(ic, site, FORWARD); std::unordered_map<t_interconnect*, std::set<std::string>> pps_map; for (auto pp : backward_pps_map) pps_map.emplace(pp.first, std::set<std::string>{}); for (auto pp : forward_pps_map) pps_map.emplace(pp.first, std::set<std::string>{}); // Cross-product of all pack-patterns added both when exploring backwards and forward. // E.g.: // Generated pack patterns // - backward: OBUFDS, OBUF // - forward: OPAD // Final pack patterns: // - OBUFDS_OPAD, OBUF_OPAD for (auto for_pp_pair : forward_pps_map) for (auto back_pp_pair : backward_pps_map) for (auto for_pp : for_pp_pair.second) for (auto back_pp : back_pp_pair.second) { std::string pp_name = for_pp + "_" + back_pp; pps_map.at(for_pp_pair.first).insert(pp_name); pps_map.at(back_pp_pair.first).insert(pp_name); } for (auto pair : pps_map) { t_interconnect* pp_ic = pair.first; auto num_pp = pair.second.size(); pp_ic->num_annotations = num_pp; pp_ic->annotations = new t_pin_to_pin_annotation[num_pp]; int idx = 0; for (auto pp_name : pair.second) pp_ic->annotations[idx++] = get_pack_pattern(pp_name, pp_ic->input_string, pp_ic->output_string); } } } } /** @brief Propagates and generates all pack_patterns required for the given ic. * This is necessary to find all root blocks that generate the pack pattern. */ std::unordered_map<t_interconnect*, std::set<std::string>> propagate_pack_patterns(t_interconnect* ic, Device::SiteType::Reader& site, e_pp_dir direction) { auto site_pins = site.getBelPins(); std::string endpoint = direction == BACKWARD ? ic->input_string : ic->output_string; auto ic_endpoints = vtr::split(endpoint, " "); std::unordered_map<t_interconnect*, std::set<std::string>> pps_map; bool is_backward = direction == BACKWARD; for (auto ep : ic_endpoints) { auto parts = vtr::split(ep, "."); auto bel = parts[0]; auto pin = parts[1]; if (bel == str(site.getName())) return pps_map; // Assign mode and pb_type t_mode* parent_mode = ic->parent_mode; t_pb_type* pb_type = nullptr; for (int ipb = 0; ipb < parent_mode->num_pb_type_children; ipb++) if (std::string(parent_mode->pb_type_children[ipb].name) == bel) pb_type = &parent_mode->pb_type_children[ipb]; VTR_ASSERT(pb_type != nullptr); auto bel_reader = get_bel_reader(site, remove_bel_suffix(bel)); // Passing through routing mux. Check at the muxes input pins interconnects if (bel_reader.getCategory() == ROUTING) { for (auto bel_pin : bel_reader.getPins()) { auto pin_reader = site_pins[bel_pin]; auto pin_name = str(pin_reader.getName()); if (pin_reader.getDir() != (is_backward ? INPUT : OUTPUT)) continue; for (int iic = 0; iic < parent_mode->num_interconnect; iic++) { t_interconnect* other_ic = &parent_mode->interconnect[iic]; if (std::string(ic->name) == std::string(other_ic->name)) continue; std::string ic_to_find = bel + "." + pin_name; bool found = false; for (auto out : vtr::split(is_backward ? other_ic->output_string : other_ic->input_string, " ")) found |= out == ic_to_find; if (found) { // An output interconnect to propagate was found, continue searching auto res = propagate_pack_patterns(other_ic, site, direction); for (auto pp_map : res) pps_map.emplace(pp_map.first, pp_map.second); } } } } else { VTR_ASSERT(bel_reader.getCategory() == LOGIC); for (int imode = 0; imode < pb_type->num_modes; imode++) { t_mode* mode = &pb_type->modes[imode]; for (int iic = 0; iic < mode->num_interconnect; iic++) { t_interconnect* other_ic = &mode->interconnect[iic]; bool found = false; for (auto other_ep : vtr::split(is_backward ? other_ic->output_string : other_ic->input_string, " ")) { found |= other_ep == ep; } if (found) { std::string pp_name = std::string(pb_type->name) + "." + std::string(mode->name); std::set<std::string> pp{pp_name}; auto res = pps_map.emplace(other_ic, pp); if (!res.second) res.first->second.insert(pp_name); } } } } } return pps_map; } // Physical Tiles void process_tiles() { auto EMPTY = get_empty_physical_type(); int index = 0; EMPTY.index = index; ptypes_.push_back(EMPTY); auto tileTypeList = ar_.getTileTypeList(); auto siteTypeList = ar_.getSiteTypeList(); for (auto tile : tileTypeList) { t_physical_tile_type ptype; auto name = str(tile.getName()); if (name == EMPTY.name) continue; bool has_valid_sites = false; for (auto site_type : tile.getSiteTypes()) has_valid_sites |= take_sites_.count(siteTypeList[site_type.getPrimaryType()].getName()) != 0; if (!has_valid_sites) continue; ptype.name = vtr::strdup(name.c_str()); ptype.index = ++index; ptype.width = ptype.height = ptype.area = 1; ptype.capacity = 0; process_sub_tiles(ptype, tile); setup_pin_classes(&ptype); bool is_io = false; for (auto site : tile.getSiteTypes()) { auto site_type = ar_.getSiteTypeList()[site.getPrimaryType()]; for (auto bel : site_type.getBels()) is_io |= is_pad(str(bel.getName())); } ptype.is_input_type = ptype.is_output_type = is_io; // TODO: remove the following once the RR graph generation is fully enabled from the device database ptype.switchblock_locations = vtr::Matrix<e_sb_type>({{1, 1}}, e_sb_type::FULL); ptype.switchblock_switch_overrides = vtr::Matrix<int>({{1, 1}}, DEFAULT_SWITCH); ptypes_.push_back(ptype); } } void process_sub_tiles(t_physical_tile_type& type, Device::TileType::Reader& tile) { // TODO: only one subtile at the moment auto siteTypeList = ar_.getSiteTypeList(); for (auto site_in_tile : tile.getSiteTypes()) { t_sub_tile sub_tile; auto site = siteTypeList[site_in_tile.getPrimaryType()]; if (take_sites_.count(site.getName()) == 0) continue; auto pins_to_wires = site_in_tile.getPrimaryPinsToTileWires(); sub_tile.index = type.capacity; sub_tile.name = vtr::strdup(str(site.getName()).c_str()); sub_tile.capacity.set(type.capacity, type.capacity); type.capacity++; int port_idx = 0; int abs_first_pin_idx = 0; int icount = 0; int ocount = 0; std::unordered_map<std::string, std::string> port_name_to_wire_name; int idx = 0; for (auto dir : {INPUT, OUTPUT}) { int port_idx_by_type = 0; for (auto pin : site.getPins()) { if (pin.getDir() != dir) continue; t_physical_tile_port port; port.name = vtr::strdup(str(pin.getName()).c_str()); port_name_to_wire_name[std::string(port.name)] = str(pins_to_wires[idx++]); sub_tile.sub_tile_to_tile_pin_indices.push_back(type.num_pins + port_idx); port.index = port_idx++; port.absolute_first_pin_index = abs_first_pin_idx++; port.port_index_by_type = port_idx_by_type++; if (dir == INPUT) { port.type = IN_PORT; icount++; } else { port.type = OUT_PORT; ocount++; } sub_tile.ports.push_back(port); } } auto pins_size = site.getPins().size(); fill_sub_tile(type, sub_tile, pins_size, icount, ocount); type.sub_tiles.push_back(sub_tile); } } /** @brief The constant block is a synthetic tile which is used to assign a virtual * location in the grid to the constant signals which are than driven to * all the real constant wires. * * The block's diagram can be seen below. The port names are specified in * the interchange device database, therefore GND and VCC are mainly * examples in this case. * * +---------------+ * | | * | +-------+ | * | | | | * | | GND +----+--> RR Graph node * | | | | * | +-------+ | * | | * | | * | +-------+ | * | | | | * | | VCC +----+--> RR Graph node * | | | | * | +-------+ | * | | * +---------------+ */ void process_constant_block() { std::vector<std::pair<std::string, std::string>> const_cells{arch_->gnd_cell, arch_->vcc_cell}; // Create constant complex block t_logical_block_type block; block.name = vtr::strdup(const_block_.c_str()); block.index = ltypes_.size(); auto pb_type = new t_pb_type; block.pb_type = pb_type; pb_type->name = vtr::strdup(const_block_.c_str()); pb_type->num_pb = 1; pb_type->num_modes = 1; pb_type->modes = new t_mode[pb_type->num_modes]; pb_type->num_ports = 2; pb_type->ports = (t_port*)vtr::calloc(pb_type->num_ports, sizeof(t_port)); pb_type->num_output_pins = 2; pb_type->num_input_pins = 0; pb_type->num_clock_pins = 0; pb_type->num_pins = 2; auto mode = &pb_type->modes[0]; mode->parent_pb_type = pb_type; mode->index = 0; mode->name = vtr::strdup("default"); mode->disable_packing = false; mode->num_interconnect = 2; mode->interconnect = new t_interconnect[mode->num_interconnect]; mode->num_pb_type_children = 2; mode->pb_type_children = new t_pb_type[mode->num_pb_type_children]; int count = 0; for (auto const_cell : const_cells) { auto leaf_pb_type = &mode->pb_type_children[count]; std::string leaf_name = const_cell.first; leaf_pb_type->name = vtr::strdup(leaf_name.c_str()); leaf_pb_type->num_pb = 1; leaf_pb_type->parent_mode = mode; leaf_pb_type->blif_model = nullptr; leaf_pb_type->num_output_pins = 1; leaf_pb_type->num_input_pins = 0; leaf_pb_type->num_clock_pins = 0; leaf_pb_type->num_pins = 1; int num_ports = 1; leaf_pb_type->num_ports = num_ports; leaf_pb_type->ports = (t_port*)vtr::calloc(num_ports, sizeof(t_port)); leaf_pb_type->blif_model = vtr::strdup(const_cell.first.c_str()); leaf_pb_type->model = get_model(arch_, const_cell.first); leaf_pb_type->ports[0] = get_generic_port(arch_, leaf_pb_type, OUT_PORT, const_cell.second, const_cell.first); pb_type->ports[count] = get_generic_port(arch_, leaf_pb_type, OUT_PORT, const_cell.first + "_" + const_cell.second); std::string istr = leaf_name + "." + const_cell.second; std::string ostr = const_block_ + "." + const_cell.first + "_" + const_cell.second; std::string ic_name = const_cell.first; auto ic = &mode->interconnect[count]; ic->name = vtr::strdup(ic_name.c_str()); ic->type = DIRECT_INTERC; ic->parent_mode_index = 0; ic->parent_mode = mode; ic->input_string = vtr::strdup(istr.c_str()); ic->output_string = vtr::strdup(ostr.c_str()); count++; } ltypes_.push_back(block); } /** @brief Creates the models corresponding to the constant cells that are used in a given interchange device */ void process_constant_model() { std::vector<std::pair<std::string, std::string>> const_cells{arch_->gnd_cell, arch_->vcc_cell}; // Create constant models for (auto const_cell : const_cells) { t_model* model = new t_model; model->index = arch_->models->index + 1; model->never_prune = true; model->name = vtr::strdup(const_cell.first.c_str()); t_model_ports* model_port = new t_model_ports; model_port->dir = OUT_PORT; model_port->name = vtr::strdup(const_cell.second.c_str()); model_port->min_size = 1; model_port->size = 1; model_port->next = model->outputs; model->outputs = model_port; model->next = arch_->models; arch_->models = model; } } /** @brief Creates a synthetic constant tile that will be located in the external layer of the device. * * The constant tile has two output ports, one for GND and the other for VCC. The constant tile hosts * the constant pb type that is generated as well. See process_constant_model and process_constant_block. */ void process_constant_tile() { std::vector<std::pair<std::string, std::string>> const_cells{arch_->gnd_cell, arch_->vcc_cell}; // Create constant tile t_physical_tile_type constant; constant.name = vtr::strdup(const_block_.c_str()); constant.index = ptypes_.size(); constant.width = constant.height = constant.area = 1; constant.capacity = 1; constant.is_input_type = constant.is_output_type = false; constant.switchblock_locations = vtr::Matrix<e_sb_type>({{1, 1}}, e_sb_type::FULL); constant.switchblock_switch_overrides = vtr::Matrix<int>({{1, 1}}, DEFAULT_SWITCH); t_sub_tile sub_tile; sub_tile.index = 0; sub_tile.name = vtr::strdup(const_block_.c_str()); int count = 0; for (auto const_cell : const_cells) { sub_tile.sub_tile_to_tile_pin_indices.push_back(count); t_physical_tile_port port; port.type = OUT_PORT; port.num_pins = 1; port.name = vtr::strdup((const_cell.first + "_" + const_cell.second).c_str()); port.index = port.absolute_first_pin_index = port.port_index_by_type = 0; sub_tile.ports.push_back(port); count++; } fill_sub_tile(constant, sub_tile, 2, 0, 2); constant.sub_tiles.push_back(sub_tile); setup_pin_classes(&constant); ptypes_.push_back(constant); } // Layout Processing void process_layout() { auto tiles = ar_.getTileList(); auto tile_types = ar_.getTileTypeList(); auto site_types = ar_.getSiteTypeList(); std::vector<std::string> packages; for (auto package : ar_.getPackages()) packages.push_back(str(package.getName())); for (auto name : packages) { t_grid_def grid_def; grid_def.width = grid_def.height = 0; for (auto tile : tiles) { grid_def.width = std::max(grid_def.width, tile.getCol() + 1); grid_def.height = std::max(grid_def.height, tile.getRow() + 1); } grid_def.width += 2; grid_def.height += 2; grid_def.grid_type = GridDefType::FIXED; if (name == "auto") { // At the moment, the interchange specifies fixed-layout only architectures, // and allowing for auto-sizing could potentially be implemented later on // to allow for experimentation on new architectures. // For the time being the layout is restricted to be only fixed. archfpga_throw(arch_file_, __LINE__, "The name auto is reserved for auto-size layouts; please choose another name"); } grid_def.name = name; for (auto tile : tiles) { auto tile_type = tile_types[tile.getType()]; bool found = false; for (auto site : tile.getSites()) { auto site_type_in_tile = tile_type.getSiteTypes()[site.getType()]; auto site_type = site_types[site_type_in_tile.getPrimaryType()]; found |= take_sites_.count(site_type.getName()) != 0; } if (!found) continue; t_metadata_dict data; std::string tile_prefix = str(tile.getName()); std::string tile_type_name = str(tile_type.getName()); size_t pos = tile_prefix.find(tile_type_name); if (pos != std::string::npos && pos == 0) tile_prefix.erase(pos, tile_type_name.length() + 1); t_grid_loc_def single(tile_type_name, 1); single.x.start_expr = std::to_string(tile.getCol() + 1); single.y.start_expr = std::to_string(tile.getRow() + 1); single.x.end_expr = single.x.start_expr + " + w - 1"; single.y.end_expr = single.y.start_expr + " + h - 1"; single.owned_meta = std::make_unique<t_metadata_dict>(data); single.meta = single.owned_meta.get(); grid_def.loc_defs.emplace_back(std::move(single)); } // The constant source tile will be placed at (0, 0) t_grid_loc_def constant(const_block_, 1); constant.x.start_expr = std::to_string(1); constant.y.start_expr = std::to_string(1); constant.x.end_expr = constant.x.start_expr + " + w - 1"; constant.y.end_expr = constant.y.start_expr + " + h - 1"; grid_def.loc_defs.emplace_back(std::move(constant)); arch_->grid_layouts.emplace_back(std::move(grid_def)); } } void process_device() { /* * The generic architecture data is not currently available in the interchange format * therefore, for a very initial implementation, the values are taken from the ones * used primarly in the Xilinx series7 devices, generated using SymbiFlow. * * As the interchange format develops further, with possibly more details, this function can * become dynamic, allowing for different parameters for the different architectures. * * FIXME: This will require to be dynamically assigned, and a suitable representation added * to the FPGA interchange device schema. */ arch_->R_minW_nmos = 6065.520020; arch_->R_minW_pmos = 18138.500000; arch_->grid_logic_tile_area = 14813.392; arch_->Chans.chan_x_dist.type = UNIFORM; arch_->Chans.chan_x_dist.peak = 1; arch_->Chans.chan_x_dist.width = 0; arch_->Chans.chan_x_dist.xpeak = 0; arch_->Chans.chan_x_dist.dc = 0; arch_->Chans.chan_y_dist.type = UNIFORM; arch_->Chans.chan_y_dist.peak = 1; arch_->Chans.chan_y_dist.width = 0; arch_->Chans.chan_y_dist.xpeak = 0; arch_->Chans.chan_y_dist.dc = 0; arch_->ipin_cblock_switch_name = std::string("generic"); arch_->SBType = WILTON; arch_->Fs = 3; default_fc_.specified = true; default_fc_.in_value_type = e_fc_value_type::FRACTIONAL; default_fc_.in_value = 1.0; default_fc_.out_value_type = e_fc_value_type::FRACTIONAL; default_fc_.out_value = 1.0; } void process_switches() { std::set<std::pair<bool, uint32_t>> pip_timing_models; for (auto tile_type : ar_.getTileTypeList()) { for (auto pip : tile_type.getPips()) { pip_timing_models.insert(std::pair<bool, uint32_t>(pip.getBuffered21(), pip.getTiming())); if (!pip.getDirectional()) pip_timing_models.insert(std::pair<bool, uint32_t>(pip.getBuffered20(), pip.getTiming())); } } auto timing_data = ar_.getPipTimings(); std::vector<std::pair<bool, uint32_t>> pip_timing_models_list; pip_timing_models_list.reserve(pip_timing_models.size()); for (auto entry : pip_timing_models) { pip_timing_models_list.push_back(entry); } size_t num_switches = pip_timing_models.size() + 2; std::string switch_name; arch_->num_switches = num_switches; if (num_switches > 0) { arch_->Switches = new t_arch_switch_inf[num_switches]; } float R, Cin, Cint, Cout, Tdel; for (size_t i = 0; i < num_switches; ++i) { t_arch_switch_inf* as = &arch_->Switches[i]; R = Cin = Cint = Cout = Tdel = 0.0; SwitchType type; if (i == 0) { switch_name = "short"; type = SwitchType::SHORT; R = 0.0; } else if (i == 1) { switch_name = "generic"; type = SwitchType::MUX; R = 0.0; } else { auto entry = pip_timing_models_list[i - 2]; auto model = timing_data[entry.second]; std::stringstream name; std::string mux_type_string = entry.first ? "mux_" : "passGate_"; name << mux_type_string; // FIXME: allow to dynamically choose different speed models and corners R = get_corner_value(model.getOutputResistance(), "slow", "min"); name << "R" << std::scientific << R; Cin = get_corner_value(model.getInputCapacitance(), "slow", "min"); name << "Cin" << std::scientific << Cin; Cout = get_corner_value(model.getOutputCapacitance(), "slow", "min"); name << "Cout" << std::scientific << Cout; if (entry.first) { Cint = get_corner_value(model.getInternalCapacitance(), "slow", "min"); name << "Cinternal" << std::scientific << Cint; } Tdel = get_corner_value(model.getInternalDelay(), "slow", "min"); name << "Tdel" << std::scientific << Tdel; switch_name = name.str() + std::to_string(i); type = entry.first ? SwitchType::MUX : SwitchType::PASS_GATE; } /* Should never happen */ if (switch_name == std::string(VPR_DELAYLESS_SWITCH_NAME)) { archfpga_throw(arch_file_, __LINE__, "Switch name '%s' is a reserved name for VPR internal usage!", switch_name.c_str()); } as->name = vtr::strdup(switch_name.c_str()); as->set_type(type); as->mux_trans_size = as->type() == SwitchType::MUX ? 1 : 0; as->R = R; as->Cin = Cin; as->Cout = Cout; as->Cinternal = Cint; as->set_Tdel(t_arch_switch_inf::UNDEFINED_FANIN, Tdel); if (as->type() == SwitchType::SHORT || as->type() == SwitchType::PASS_GATE) { as->buf_size_type = BufferSize::ABSOLUTE; as->buf_size = 0; as->power_buffer_type = POWER_BUFFER_TYPE_ABSOLUTE_SIZE; as->power_buffer_size = 0.; } else { as->buf_size_type = BufferSize::AUTO; as->buf_size = 0.; as->power_buffer_type = POWER_BUFFER_TYPE_AUTO; } } } void process_segments() { // Segment names will be taken from wires connected to pips // They are good representation for nodes std::set<uint32_t> wire_names; for (auto tile_type : ar_.getTileTypeList()) { auto wires = tile_type.getWires(); for (auto pip : tile_type.getPips()) { wire_names.insert(wires[pip.getWire0()]); wire_names.insert(wires[pip.getWire1()]); } } // FIXME: have only one segment type for the time being, so that // the RR graph generation is correct. // This can be removed once the RR graph reader from the interchange // device is ready and functional. size_t num_seg = 1; //wire_names.size(); arch_->Segments.resize(num_seg); size_t index = 0; for (auto i : wire_names) { if (index >= num_seg) break; // Use default values as we will populate rr_graph with correct values // This segments are just declaration of future use arch_->Segments[index].name = str(i); arch_->Segments[index].length = 1; arch_->Segments[index].frequency = 1; arch_->Segments[index].Rmetal = 1e-12; arch_->Segments[index].Cmetal = 1e-12; arch_->Segments[index].parallel_axis = BOTH_AXIS; // TODO: Only bi-directional segments are created, but it the interchange format // has directionality information on PIPs, which may be used to infer the // segments' directonality. arch_->Segments[index].directionality = BI_DIRECTIONAL; arch_->Segments[index].arch_wire_switch = 1; arch_->Segments[index].arch_opin_switch = 1; arch_->Segments[index].cb.resize(1); arch_->Segments[index].cb[0] = true; arch_->Segments[index].sb.resize(2); arch_->Segments[index].sb[0] = true; arch_->Segments[index].sb[1] = true; segment_name_to_segment_idx[str(i)] = index; ++index; } } }; void FPGAInterchangeReadArch(const char* FPGAInterchangeDeviceFile, const bool /*timing_enabled*/, t_arch* arch, std::vector<t_physical_tile_type>& PhysicalTileTypes, std::vector<t_logical_block_type>& LogicalBlockTypes) { // Decompress GZipped capnproto device file gzFile file = gzopen(FPGAInterchangeDeviceFile, "r"); VTR_ASSERT(file != Z_NULL); std::vector<uint8_t> output_data; output_data.resize(4096); std::stringstream sstream(std::ios_base::in | std::ios_base::out | std::ios_base::binary); while (true) { int ret = gzread(file, output_data.data(), output_data.size()); VTR_ASSERT(ret >= 0); if (ret > 0) { sstream.write((const char*)output_data.data(), ret); VTR_ASSERT(sstream); } else { VTR_ASSERT(ret == 0); int error; gzerror(file, &error); VTR_ASSERT(error == Z_OK); break; } } VTR_ASSERT(gzclose(file) == Z_OK); sstream.seekg(0); kj::std::StdInputStream istream(sstream); // Reader options capnp::ReaderOptions reader_options; reader_options.nestingLimit = std::numeric_limits<int>::max(); reader_options.traversalLimitInWords = std::numeric_limits<uint64_t>::max(); capnp::InputStreamMessageReader message_reader(istream, reader_options); auto device_reader = message_reader.getRoot<DeviceResources::Device>(); arch->architecture_id = vtr::strdup(vtr::secure_digest_file(FPGAInterchangeDeviceFile).c_str()); ArchReader reader(arch, device_reader, FPGAInterchangeDeviceFile, PhysicalTileTypes, LogicalBlockTypes); reader.read_arch(); }
37.977192
160
0.547424
[ "vector", "model" ]
4d587463a2320dcf88dfb1349b5205dcc0525cb1
44,452
cpp
C++
src/utils.cpp
yuki-inaho/vsac
4fb7b5e8c18fa05ef89ae092d7738da5522b8fd0
[ "BSD-3-Clause" ]
7
2021-10-22T04:45:34.000Z
2022-03-31T13:08:13.000Z
src/utils.cpp
yuki-inaho/vsac
4fb7b5e8c18fa05ef89ae092d7738da5522b8fd0
[ "BSD-3-Clause" ]
2
2022-01-23T12:08:31.000Z
2022-01-25T15:42:47.000Z
src/utils.cpp
yuki-inaho/vsac
4fb7b5e8c18fa05ef89ae092d7738da5522b8fd0
[ "BSD-3-Clause" ]
4
2021-11-15T06:36:28.000Z
2022-03-27T11:17:35.000Z
#include "precomp.hpp" #include <opencv2/flann/miniflann.hpp> namespace cv { namespace vsac { int mergePoints (InputArray pts1_, InputArray pts2_, Mat &pts, bool ispnp) { Mat pts1 = pts1_.getMat(), pts2 = pts2_.getMat(); auto convertPoints = [] (Mat &points, int pt_dim) { points.convertTo(points, CV_32F); // convert points to have float precision if (points.channels() > 1) points = points.reshape(1, (int)points.total()); // convert point to have 1 channel if (points.rows < points.cols) transpose(points, points); // transpose so points will be in rows CV_CheckGE(points.cols, pt_dim, "Invalid dimension of point"); if (points.cols != pt_dim) // in case when image points are 3D convert them to 2D points = points.colRange(0, pt_dim); }; convertPoints(pts1, 2); // pts1 are always image points convertPoints(pts2, ispnp ? 3 : 2); // for PnP points are 3D // points are of size [Nx2 Nx2] = Nx4 for H, F, E // points are of size [Nx2 Nx3] = Nx5 for PnP hconcat(pts1, pts2, pts); return pts.rows; } double Utils::getCalibratedThreshold (double threshold, const Mat &K1, const Mat &K2) { const auto * const k1 = (double *) K1.data, * const k2 = (double *) K2.data; return threshold / ((k1[0] + k1[4] + k2[0] + k2[4]) / 4.0); } /* * K1, K2 are 3x3 intrinsics matrices * points is matrix of size |N| x 4 * Assume K = [k11 k12 k13 * 0 k22 k23 * 0 0 1] */ void Utils::calibratePoints (const Mat &K1, const Mat &K2, const Mat &points, Mat &calib_points) { const auto * const points_ = (float *) points.data; const auto * const k1 = (double *) K1.data; const auto inv1_k11 = float(1 / k1[0]); // 1 / k11 const auto inv1_k12 = float(-k1[1] / (k1[0]*k1[4])); // -k12 / (k11*k22) // (-k13*k22 + k12*k23) / (k11*k22) const auto inv1_k13 = float((-k1[2]*k1[4] + k1[1]*k1[5]) / (k1[0]*k1[4])); const auto inv1_k22 = float(1 / k1[4]); // 1 / k22 const auto inv1_k23 = float(-k1[5] / k1[4]); // -k23 / k22 const auto * const k2 = (double *) K2.data; const auto inv2_k11 = float(1 / k2[0]); const auto inv2_k12 = float(-k2[1] / (k2[0]*k2[4])); const auto inv2_k13 = float((-k2[2]*k2[4] + k2[1]*k2[5]) / (k2[0]*k2[4])); const auto inv2_k22 = float(1 / k2[4]); const auto inv2_k23 = float(-k2[5] / k2[4]); calib_points = Mat ( points.rows, 4, points.type()); auto * calib_points_ = (float *) calib_points.data; for (int i = 0; i < points.rows; i++) { const int idx = 4*i; (*calib_points_++) = inv1_k11 * points_[idx ] + inv1_k12 * points_[idx+1] + inv1_k13; (*calib_points_++) = inv1_k22 * points_[idx+1] + inv1_k23; (*calib_points_++) = inv2_k11 * points_[idx+2] + inv2_k12 * points_[idx+3] + inv2_k13; (*calib_points_++) = inv2_k22 * points_[idx+3] + inv2_k23; } } /* * K is 3x3 intrinsic matrix * points is matrix of size |N| x 5, first two columns are image points [u_i, v_i] * calib_norm_pts are K^-1 [u v 1]^T / ||K^-1 [u v 1]^T|| */ void Utils::calibrateAndNormalizePointsPnP (const Mat &K, const Mat &pts, Mat &calib_norm_pts) { const auto * const points = (float *) pts.data; const auto * const k = (double *) K.data; const auto inv_k11 = float(1 / k[0]); const auto inv_k12 = float(-k[1] / (k[0]*k[4])); const auto inv_k13 = float((-k[2]*k[4] + k[1]*k[5]) / (k[0]*k[4])); const auto inv_k22 = float(1 / k[4]); const auto inv_k23 = float(-k[5] / k[4]); calib_norm_pts = Mat (pts.rows, 3, pts.type()); auto * calib_norm_pts_ = (float *) calib_norm_pts.data; for (int i = 0; i < pts.rows; i++) { const int idx = 5 * i; const float k_inv_u = inv_k11 * points[idx] + inv_k12 * points[idx+1] + inv_k13; const float k_inv_v = inv_k22 * points[idx+1] + inv_k23; const float norm = 1.f / sqrtf(k_inv_u*k_inv_u + k_inv_v*k_inv_v + 1); (*calib_norm_pts_++) = k_inv_u * norm; (*calib_norm_pts_++) = k_inv_v * norm; (*calib_norm_pts_++) = norm; } } void Utils::normalizeAndDecalibPointsPnP (const Mat &K_, Mat &pts, Mat &calib_norm_pts) { const auto * const K = (double *) K_.data; const auto k11 = (float)K[0], k12 = (float)K[1], k13 = (float)K[2], k22 = (float)K[4], k23 = (float)K[5]; calib_norm_pts = Mat (pts.rows, 3, pts.type()); auto * points = (float *) pts.data; auto * calib_norm_pts_ = (float *) calib_norm_pts.data; for (int i = 0; i < pts.rows; i++) { const int idx = 5 * i; const float k_inv_u = points[idx ]; const float k_inv_v = points[idx+1]; const float norm = 1.f / sqrtf(k_inv_u*k_inv_u + k_inv_v*k_inv_v + 1); (*calib_norm_pts_++) = k_inv_u * norm; (*calib_norm_pts_++) = k_inv_v * norm; (*calib_norm_pts_++) = norm; points[idx ] = k11 * k_inv_u + k12 * k_inv_v + k13; points[idx+1] = k22 * k_inv_v + k23; } } /* * decompose Projection Matrix to calibration, rotation and translation * Assume K = [fx 0 tx * 0 fy ty * 0 0 1] */ void Utils::decomposeProjection (const Mat &P, Mat &K_, Mat &R, Mat &t, bool same_focal) { const Mat M = P.colRange(0,3); double scale = norm(M.row(2)); scale *= scale; Matx33d K = Matx33d::eye(); K(1,2) = M.row(1).dot(M.row(2)) / scale; K(0,2) = M.row(0).dot(M.row(2)) / scale; K(1,1) = sqrt(M.row(1).dot(M.row(1)) / scale - K(1,2)*K(1,2)); K(0,0) = sqrt(M.row(0).dot(M.row(0)) / scale - K(0,2)*K(0,2)); if (same_focal) K(0,0) = K(1,1) = (K(0,0) + K(1,1)) / 2; R = K.inv() * M / sqrt(scale); if (determinant(M) < 0) R *= -1; t = R * M.inv() * P.col(3); K_ = Mat(K); } // since F(E) has rank 2 we use cross product to compute epipole, // since the third column / row is linearly dependent on two first // this is faster than SVD Vec3d Utils::getLeftEpipole (const Mat &F/*E*/) { Vec3d _e = F.col(0).cross(F.col(2)); // F^T e' = 0; e'^T F = 0 const auto * const e = _e.val; if (e[0] <= DBL_EPSILON && e[0] > -DBL_EPSILON && e[1] <= DBL_EPSILON && e[1] > -DBL_EPSILON && e[2] <= DBL_EPSILON && e[2] > -DBL_EPSILON) _e = Vec3d(Mat(F.col(1))).cross(F.col(2)); // if e' is zero return _e; // e' } Vec3d Utils::getRightEpipole (const Mat &F/*E*/) { Vec3d _e = F.row(0).cross(F.row(2)); // Fe = 0 const auto * const e = _e.val; if (e[0] <= DBL_EPSILON && e[0] > -DBL_EPSILON && e[1] <= DBL_EPSILON && e[1] > -DBL_EPSILON && e[2] <= DBL_EPSILON && e[2] > -DBL_EPSILON) _e = F.row(1).cross(F.row(2)); // if e is zero return _e; } void Utils::densitySort (const Mat &points, int knn, Mat &sorted_points, std::vector<int> &sorted_mask) { // mask of sorted points (array of indexes) const int points_size = points.rows, dim = points.cols; sorted_mask = std::vector<int >(points_size); for (int i = 0; i < points_size; i++) sorted_mask[i] = i; // get neighbors FlannNeighborhoodGraph &graph = *FlannNeighborhoodGraph::create(points, points_size, knn, true /*get distances */, 6, 1); std::vector<double> sum_knn_distances (points_size, 0); for (int p = 0; p < points_size; p++) { const std::vector<double> &dists = graph.getNeighborsDistances(p); for (int k = 0; k < knn; k++) sum_knn_distances[p] += dists[k]; } // compare by sum of distances to k nearest neighbors. std::sort(sorted_mask.begin(), sorted_mask.end(), [&](int a, int b) { return sum_knn_distances[a] < sum_knn_distances[b]; }); // copy array of points to array with sorted points // using @sorted_idx mask of sorted points indexes sorted_points = Mat(points_size, dim, points.type()); const auto * const points_ptr = (float *) points.data; auto * spoints_ptr = (float *) sorted_points.data; for (int i = 0; i < points_size; i++) { const int pt2 = sorted_mask[i] * dim; for (int j = 0; j < dim; j++) (*spoints_ptr++) = points_ptr[pt2+j]; } } Matx33d Math::getSkewSymmetric(const Vec3d &v) { return {0, -v[2], v[1], v[2], 0, -v[0], -v[1], v[0], 0}; } Matx33d Math::rotVec2RotMat (const Vec3d &v) { const double phi = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); const double x = v[0] / phi, y = v[1] / phi, z = v[2] / phi; const double a = sin(phi), b = cos(phi); // R = I + sin(phi) * skew(v) + (1 - cos(phi) * skew(v)^2 return {(b - 1)*y*y + (b - 1)*z*z + 1, -a*z - x*y*(b - 1), a*y - x*z*(b - 1), a*z - x*y*(b - 1), (b - 1)*x*x + (b - 1)*z*z + 1, -a*x - y*z*(b - 1), -a*y - x*z*(b - 1), a*x - y*z*(b - 1), (b - 1)*x*x + (b - 1)*y*y + 1}; } Vec3d Math::rotMat2RotVec (const Matx33d &R) { // https://math.stackexchange.com/questions/83874/efficient-and-accurate-numerical-implementation-of-the-inverse-rodrigues-rotatio?rq=1 Vec3d rot_vec; const double trace = R(0,0)+R(1,1)+R(2,2); if (trace >= 3 - FLT_EPSILON) { rot_vec = (0.5 * (trace-3)/12)*Vec3d(R(2,1)-R(1,2), R(0,2)-R(2,0), R(1,0)-R(0,1)); } else if (3 - FLT_EPSILON > trace && trace > -1 + FLT_EPSILON) { double theta = acos((trace - 1) / 2); rot_vec = (theta / (2 * sin(theta))) * Vec3d(R(2,1)-R(1,2), R(0,2)-R(2,0), R(1,0)-R(0,1)); } else { int a; if (R(0,0) > R(1,1)) a = R(0,0) > R(2,2) ? 0 : 2; else a = R(1,1) > R(2,2) ? 1 : 2; Vec3d v; int b = (a + 1) % 3, c = (a + 2) % 3; double s = sqrt(R(a,a) - R(b,b) - R(c,c) + 1); v[a] = s / 2; v[b] = (R(b,a) + R(a,b)) / (2 * s); v[c] = (R(c,a) + R(a,c)) / (2 * s); rot_vec = M_PI * v / norm(v); } return rot_vec; } /* * Eliminate matrix of m rows and n columns to be upper triangular. */ bool Math::eliminateUpperTriangular (std::vector<double> &a, int m, int n) { for (int r = 0; r < m; r++){ double pivot = a[r*n+r]; int row_with_pivot = r; // find the maximum pivot value among r-th column for (int k = r+1; k < m; k++) if (fabs(pivot) < fabs(a[k*n+r])) { pivot = a[k*n+r]; row_with_pivot = k; } // if pivot value is 0 continue if (fabs(pivot) < DBL_EPSILON) continue; // swap row with maximum pivot value with current row for (int c = r; c < n; c++) std::swap(a[row_with_pivot*n+c], a[r*n+c]); // eliminate other rows for (int j = r+1; j < m; j++){ const int row_idx1 = j*n, row_idx2 = r*n; const auto fac = a[row_idx1+r] / pivot; a[row_idx1+r] = 0; // zero eliminated element for (int c = r+1; c < n; c++) a[row_idx1+c] -= fac * a[row_idx2+c]; } } return true; } double Utils::intersectionOverUnion (const std::vector<bool> &a, const std::vector<bool> &b) { int intersects = 0, unions = 0; for (int i = 0; i < (int)a.size(); i++) if (a[i] || b[i]) { unions++; // one value is true if (a[i] && b[i]) intersects++; // a[i] == b[i] and if they both true } return (double) intersects / unions; } double Utils::getPoissonCDF (double lambda, int inliers) { double exp_lamda = exp(-lambda), cdf = exp_lamda, lambda_i_div_fact_i = 1; for (int i = 1; i <= inliers; i++) { lambda_i_div_fact_i *= (lambda / i); cdf += exp_lamda * lambda_i_div_fact_i; if (fabs(cdf - 1) < DBL_EPSILON) // cdf is almost 1 break; } return cdf; } int Utils::triangulatePointsRt (const Mat &points, Mat &points3D, const Mat &K1_, const Mat &K2_, const cv::Mat &R, const cv::Mat &t_vec, std::vector<bool> &good_mask, std::vector<double> &depths1, std::vector<double> &depths2) { cv::Matx33d K1 = Matx33d(K1_), K2 = Matx33d(K2_); cv::Matx34d P2; cv::hconcat(K2 * R, K2 * t_vec, P2); cv::Matx66d A = cv::Matx66d::zeros(); A(2,0) = A(5,1) = 1; for (int r = 0; r < 3; r++) { for (int c = 0; c < 4; c++) { A( r,2+c) = -K1 (r,c); A(3+r,2+c) = -P2(r,c); } } good_mask = std::vector<bool> (points.rows, false); depths1 = std::vector<double>(points.rows,0); depths2 = std::vector<double>(points.rows,0); points3D = Mat_<float>::zeros(points.rows, 3); const auto * const pts = (float *) points.data; auto * pts3D_ptr = (float *) points3D.data; int num_valid_pts = 0; for (int i = 0; i < points.rows; i++) { A(0,0) = pts[4*i ]; A(1,0) = pts[4*i+1]; A(3,1) = pts[4*i+2]; A(4,1) = pts[4*i+3]; // https://cw.fel.cvut.cz/wiki/_media/courses/gvg/pajdla-gvg-lecture-2021.pdf cv::Matx66d U, Vt; cv::Vec6d D; cv::SVDecomp(A, D, U, Vt); const double scale1 = Vt(5,0) / Vt(5,5), scale2 = Vt(5,1) / Vt(5,5); // since P1 = K [I | 0] it imples that if scale1 < 0 then z < 0 if (scale1 > 0 && scale2 > 0) { good_mask[i] = true; pts3D_ptr[i*3 ] = Vt(5,2) / Vt(5,5); pts3D_ptr[i*3+1] = Vt(5,3) / Vt(5,5); pts3D_ptr[i*3+2] = Vt(5,4) / Vt(5,5); depths1[i] = scale1; depths2[i] = scale2; num_valid_pts++; } } return num_valid_pts; } void Utils::triangulatePoints (const Mat &points, const Mat &E, const Mat &K1_, const Mat &K2_, Mat &points3D, cv::Mat &R, cv::Mat &t_vec, std::vector<bool> &good_mask, std::vector<double> &depths2, std::vector<double> &depths1) { cv::Mat R1, R2, t; cv::decomposeEssentialMat(E, R1, R2, t); std::vector<Mat> pts3D(4); std::vector<std::vector<bool>> good_masks(4); std::vector<std::vector<double>> depths2_(4), depths1_(4); int pts_in_front[4] = { Utils::triangulatePointsRt(points, pts3D[0], K1_, K2_, R1, t, good_masks[0], depths1_[0], depths2_[0]), Utils::triangulatePointsRt(points, pts3D[1], K1_, K2_, R1, -t, good_masks[1], depths1_[1], depths2_[1]), Utils::triangulatePointsRt(points, pts3D[2], K1_, K2_, R2, t, good_masks[2], depths1_[2], depths2_[2]), Utils::triangulatePointsRt(points, pts3D[3], K1_, K2_, R2, -t, good_masks[3], depths1_[3], depths2_[3]) }; int max_points_in_front = 0, correct_idx = 0; for (int p = 0; p < 4; p++) if (max_points_in_front < pts_in_front[p]) { max_points_in_front = pts_in_front[p]; correct_idx = p; } R = correct_idx <= 1 ? Mat(R1) : Mat(R2); // 0 and 2 index corresponds to +t, 1 and 3 to -t t_vec = correct_idx % 2 ? Mat(-t) : Mat(t); pts3D[correct_idx].copyTo(points3D); good_mask = good_masks[correct_idx]; depths1 = depths1_[correct_idx]; depths2 = depths2_[correct_idx]; } // https://www.researchgate.net/publication/221362655_Triangulation_Made_Easy void Utils::triangulatePoints (const Mat &F_, const Mat &points1, const Mat &points2, Mat &corr_points1, Mat &corr_points2, const Mat &K1_, const Mat &K2_, Mat &points3D, Mat &R, Mat &t_out, const std::vector<bool> &good_point_mask) { cv::Mat pts1_ = points1, pts2_ = points2; pts1_.convertTo(pts1_, CV_32F); pts2_.convertTo(pts2_, CV_32F); corr_points1 = Mat_<float>::zeros(points1.rows, 2); corr_points2 = Mat_<float>::zeros(points1.rows, 2); int correct_pose_pair = -1, num_pts_processed = 0; int num_pts_positive_depth[4] = {0}; cv::Mat points3D_R1, points3D_R2; Vec3d t_, t_corr; Matx33d R1, R2, F (F_), K1, K2, R_corr, K1_inv, K2_inv, E; const bool has_calibration = !K1_.empty() && !K2_.empty(); if (has_calibration) { K1 = Matx33d(K1_); K2 = Matx33d(K2_); K2_inv = K2.inv(); K1_inv = K1.inv(); E = K2.t() * F * K1; points3D_R1 = Mat_<float>::zeros(points1.rows, 3); points3D_R2 = Mat_<float>::zeros(points1.rows, 3); decomposeEssentialMat(E, R1, R2, t_); } F = F.t(); auto * pts3D_R1 = (float *) points3D_R1.data, * pts3D_R2 = (float *) points3D_R2.data; const auto * const pts1 = (float *) pts1_.data, * const pts2 = (float *) pts2_.data; auto * cpts1 = (float *) corr_points1.data, * cpts2 = (float *) corr_points2.data; const Matx23d S (1, 0, 0, 0, 1, 0); const Matx32d St = S.t(); const Matx23d SF = S * F, SFt = S * F.t(); const Matx22d SFSt = S * F * St; for (int pt = 0; pt < points1.rows; pt++) { if (!good_point_mask[pt]) continue; const int idx = 2*pt; Vec3d x (pts1[idx], pts1[idx+1], 1); Vec3d xp (pts2[idx], pts2[idx+1], 1); Vec2d n = SF * xp, np = SFt * x; // n^T SES^T n' const auto a = (n[0] * SFSt(0,0) + n[1] * SFSt(1,0)) * np[0] + (n[0] * SFSt(0,1) + n[1] * SFSt(1,1)) * np[1]; const auto b = 0.5 * (n.dot(n) + np.dot(np)); const auto c = (x[0] * F(0,0) + x[1] * F(1,0) + F(2,0)) * xp[0] + (x[0] * F(0,1) + x[1] * F(1,1) + F(2,1)) * xp[1] + (x[0] * F(0,2) + x[1] * F(1,2) + F(2,2)); // xT E x auto lambda = c / (b + sqrt(b*b - a * c)); auto dx = lambda * n; auto dxp = lambda * np; n -= SFSt * dxp; np -= SFSt.t() * dx; // niter1 dx = dx.dot(n) * n / n.dot(n); dxp = dxp.dot(np) * np / np.dot(np); // niter2 // lambda = lambda * 2 * d /(n.dot(n) + np.dot(np)); // dx = lambda * n; // dxp = lambda * np; x -= St * dx; xp -= St * dxp; cpts1[idx ] = x[0]; cpts1[idx+1] = x[1]; cpts2[idx ] = xp[0]; cpts2[idx+1] = xp[1]; if (has_calibration) { num_pts_processed++; x[2] = 1; xp[2] = 1; // get normalized points by K^-1 x cv::Vec3d norm_x1 = K1_inv * x, norm_x2 = K2_inv * xp; cv::Vec3d norm_x1_unit = norm_x1 / norm(norm_x1), norm_x2_unit = norm_x2 / norm(norm_x2); if (correct_pose_pair != -1) { // we found correct pose const Vec3d z = norm_x1.cross(R_corr * norm_x2); const Vec3d X = z.dot(E * norm_x2) * x / (z.dot(z)); pts3D_R1[3*pt ] = X[0]; pts3D_R1[3*pt+1] = X[1]; pts3D_R1[3*pt+2] = X[2]; } else { const bool R1_t_good = Utils::satisfyCheirality(R1, t_, norm_x1_unit, norm_x2_unit); const bool R1_min_t_good = Utils::satisfyCheirality(R1,-t_, norm_x1_unit, norm_x2_unit); const bool R2_t_good = Utils::satisfyCheirality(R2, t_, norm_x1_unit, norm_x2_unit); const bool R2_min_t_good = Utils::satisfyCheirality(R2,-t_, norm_x1_unit, norm_x2_unit); if (R1_t_good) num_pts_positive_depth[0]++; if (R1_min_t_good) num_pts_positive_depth[1]++; if (R2_t_good) num_pts_positive_depth[2]++; if (R2_min_t_good) num_pts_positive_depth[3]++; if (R1_t_good || R1_min_t_good) { const Vec3d z = norm_x1.cross(R1 * norm_x2); const Vec3d X = z.dot(E * norm_x2) * x / (z.dot(z)); pts3D_R1[3*pt ] = X[0]; pts3D_R1[3*pt+1] = X[1]; pts3D_R1[3*pt+2] = X[2]; } else { const Vec3d z = norm_x1.cross(R2 * norm_x2); const Vec3d X = z.dot(E * norm_x2) * x / (z.dot(z)); pts3D_R2[3*pt ] = X[0]; pts3D_R2[3*pt+1] = X[1]; pts3D_R2[3*pt+2] = X[2]; } } if (num_pts_processed == 100 || num_pts_processed == points1.rows) { // 100 points is enough to find out good pose pair int max_points_in_front = 0; for (int cam = 0; cam < 4; cam++) { if (max_points_in_front < num_pts_positive_depth[cam]) { max_points_in_front = num_pts_positive_depth[cam]; correct_pose_pair = cam; } } t_corr = correct_pose_pair % 2 ? -t_ : t_; if (correct_pose_pair >= 2) { R_corr = R2; // we store correct points in points3D_R1 array, so // copy all elements of points3D_R2. std::copy((float *)points3D_R2.data, (float *)points3D_R2.data+3*pt, (float *)points3D_R1.data); } else R_corr = R1; } } } R = Mat(R_corr); t_out = Mat(t_corr); points3D_R1.copyTo(points3D); points3D.convertTo(points3D, points1.type()); corr_points1.convertTo(corr_points1, points1.type()); corr_points2.convertTo(corr_points2, points2.type()); } //////////////////////////////////////// RANDOM GENERATOR ///////////////////////////// class UniformRandomGeneratorImpl : public UniformRandomGenerator { private: int subset_size = 0, max_range = 0; std::vector<int> subset; RNG rng; public: explicit UniformRandomGeneratorImpl (int state) : rng(state) {} // interval is <0; max_range); UniformRandomGeneratorImpl (int state, int max_range_, int subset_size_) : rng(state) { subset_size = subset_size_; max_range = max_range_; subset = std::vector<int>(subset_size_); } int getRandomNumber () override { return rng.uniform(0, max_range); } int getRandomNumber (int max_rng) override { return rng.uniform(0, max_rng); } // closed range void resetGenerator (int max_range_) override { CV_CheckGE(0, max_range_, "max range must be greater than 0"); max_range = max_range_; } void generateUniqueRandomSet (std::vector<int>& sample) override { CV_CheckLE(subset_size, max_range, "RandomGenerator. Subset size must be LE than range!"); int j, num; sample[0] = rng.uniform(0, max_range); for (int i = 1; i < subset_size;) { num = rng.uniform(0, max_range); // check if value is in array for (j = i - 1; j >= 0; j--) if (num == sample[j]) // if so, generate again break; // success, value is not in array, so it is unique, add to sample. if (j == -1) sample[i++] = num; } } // interval is <0; max_range) void generateUniqueRandomSet (std::vector<int>& sample, int max_range_) override { /* * if subset size is bigger than range then array cannot be unique, * so function has infinite loop. */ CV_CheckLE(subset_size, max_range_, "RandomGenerator. Subset size must be LE than range!"); int num, j; sample[0] = rng.uniform(0, max_range_); for (int i = 1; i < subset_size;) { num = rng.uniform(0, max_range_); for (j = i - 1; j >= 0; j--) if (num == sample[j]) break; if (j == -1) sample[i++] = num; } } // interval is <0, max_range) void generateUniqueRandomSet (std::vector<int>& sample, int subset_size_, int max_range_) override { CV_CheckLE(subset_size_, max_range_, "RandomGenerator. Subset size must be LE than range!"); int num, j; sample[0] = rng.uniform(0, max_range_); for (int i = 1; i < subset_size_;) { num = rng.uniform(0, max_range_); for (j = i - 1; j >= 0; j--) if (num == sample[j]) break; if (j == -1) sample[i++] = num; } } const std::vector<int> &generateUniqueRandomSubset (std::vector<int> &array1, int size1) override { CV_CheckLE(subset_size, size1, "RandomGenerator. Subset size must be LE than range!"); int temp_size1 = size1; for (int i = 0; i < subset_size; i++) { const int idx1 = rng.uniform(0, temp_size1); subset[i] = array1[idx1]; std::swap(array1[idx1], array1[--temp_size1]); } return subset; } void setSubsetSize (int subset_size_) override { if (subset_size < subset_size_) subset.resize(subset_size_); subset_size = subset_size_; } int getSubsetSize () const override { return subset_size; } }; Ptr<UniformRandomGenerator> UniformRandomGenerator::create (int state) { return makePtr<UniformRandomGeneratorImpl>(state); } Ptr<UniformRandomGenerator> UniformRandomGenerator::create (int state, int max_range, int subset_size_) { return makePtr<UniformRandomGeneratorImpl>(state, max_range, subset_size_); } // @k_minth - desired k-th minimal element. For median is half of array // closed working interval of array <@left; @right> float quicksort_median (std::vector<float> &array, int k_minth, int left, int right); float quicksort_median (std::vector<float> &array, int k_minth, int left, int right) { // length is 0, return single value if (right - left == 0) return array[left]; // get pivot, the rightest value in array const auto pivot = array[right]; int right_ = right - 1; // -1, not including pivot // counter of values smaller equal than pivot int j = left, values_less_eq_pivot = 1; // 1, inludes pivot already for (; j <= right_;) { if (array[j] <= pivot) { j++; values_less_eq_pivot++; } else // value is bigger than pivot, swap with right_ value // swap values in array and decrease interval std::swap(array[j], array[right_--]); } if (values_less_eq_pivot == k_minth) return pivot; if (k_minth > values_less_eq_pivot) return quicksort_median(array, k_minth - values_less_eq_pivot, j, right-1); else return quicksort_median(array, k_minth, left, j-1); } // find median using quicksort with complexity O(log n) // Note, function changes order of values in array float Utils::findMedian (std::vector<float> &array) { const int length = static_cast<int>(array.size()); if (length % 2) { // odd number of values return quicksort_median (array, length/2+1, 0, length-1); } else { // even: return average return (quicksort_median(array, length/2 , 0, length-1) + quicksort_median(array, length/2+1, 0, length-1))*.5f; } } ///////////////////////////////// Radius Search Graph ///////////////////////////////////////////// class RadiusSearchNeighborhoodGraphImpl : public RadiusSearchNeighborhoodGraph { private: std::vector<std::vector<int>> graph; public: RadiusSearchNeighborhoodGraphImpl (const Mat &container_, int points_size, double radius, int flann_search_params, int num_kd_trees) { // Radius search OpenCV works only with float data CV_Assert(container_.type() == CV_32F); FlannBasedMatcher flann(makePtr<flann::KDTreeIndexParams>(num_kd_trees), makePtr<flann::SearchParams>(flann_search_params)); std::vector<std::vector<DMatch>> neighbours; flann.radiusMatch(container_, container_, neighbours, (float)radius); // allocate graph graph = std::vector<std::vector<int>> (points_size); int pt = 0; for (const auto &n : neighbours) { if (n.size() <= 1) continue; auto &graph_row = graph[pt]; graph_row = std::vector<int>(n.size()-1); int j = 0; for (const auto &idx : n) // skip neighbor which has the same index as requested point if (idx.trainIdx != pt) graph_row[j++] = idx.trainIdx; pt++; } } inline const std::vector<int> &getNeighbors(int point_idx) const override { return graph[point_idx]; } }; Ptr<RadiusSearchNeighborhoodGraph> RadiusSearchNeighborhoodGraph::create (const Mat &points, int points_size, double radius_, int flann_search_params, int num_kd_trees) { return makePtr<RadiusSearchNeighborhoodGraphImpl> (points, points_size, radius_, flann_search_params, num_kd_trees); } ///////////////////////////////// FLANN Graph ///////////////////////////////////////////// class FlannNeighborhoodGraphImpl : public FlannNeighborhoodGraph { private: std::vector<std::vector<int>> graph; std::vector<std::vector<double>> distances; public: FlannNeighborhoodGraphImpl (const Mat &container_, int points_size, int k_nearest_neighbors, bool get_distances, int flann_search_params_, int num_kd_trees) { CV_Assert(k_nearest_neighbors <= points_size); // FLANN works only with float data CV_Assert(container_.type() == CV_32F); flann::Index flannIndex (container_.reshape(1), flann::KDTreeIndexParams(num_kd_trees)); Mat dists, nearest_neighbors; flannIndex.knnSearch(container_, nearest_neighbors, dists, k_nearest_neighbors+1, flann::SearchParams(flann_search_params_)); // first nearest neighbor of point is this point itself. // remove this first column nearest_neighbors.colRange(1, k_nearest_neighbors+1).copyTo (nearest_neighbors); graph = std::vector<std::vector<int>>(points_size, std::vector<int>(k_nearest_neighbors)); const auto * const nn = (int *) nearest_neighbors.data; const auto * const dists_ptr = (float *) dists.data; if (get_distances) distances = std::vector<std::vector<double>>(points_size, std::vector<double>(k_nearest_neighbors)); for (int pt = 0; pt < points_size; pt++) { std::copy(nn + k_nearest_neighbors*pt, nn + k_nearest_neighbors*pt + k_nearest_neighbors, &graph[pt][0]); if (get_distances) std::copy(dists_ptr + k_nearest_neighbors*pt, dists_ptr + k_nearest_neighbors*pt + k_nearest_neighbors, &distances[pt][0]); } } const std::vector<double>& getNeighborsDistances (int idx) const override { return distances[idx]; } inline const std::vector<int> &getNeighbors(int point_idx) const override { // CV_Assert(point_idx_ < num_vertices); return graph[point_idx]; } }; Ptr<FlannNeighborhoodGraph> FlannNeighborhoodGraph::create(const Mat &points, int points_size, int k_nearest_neighbors_, bool get_distances, int flann_search_params_, int num_kd_trees) { return makePtr<FlannNeighborhoodGraphImpl>(points, points_size, k_nearest_neighbors_, get_distances, flann_search_params_, num_kd_trees); } ///////////////////////////////// Grid Neighborhood Graph ///////////////////////////////////////// class GridNeighborhoodGraphImpl : public GridNeighborhoodGraph { private: // This struct is used for the nearest neighbors search by griding two images. struct CellCoord { int c1x, c1y, c2x, c2y; CellCoord (int c1x_, int c1y_, int c2x_, int c2y_) { c1x = c1x_; c1y = c1y_; c2x = c2x_; c2y = c2y_; } bool operator==(const CellCoord &o) const { return c1x == o.c1x && c1y == o.c1y && c2x == o.c2x && c2y == o.c2y; } bool operator<(const CellCoord &o) const { if (c1x < o.c1x) return true; if (c1x == o.c1x && c1y < o.c1y) return true; if (c1x == o.c1x && c1y == o.c1y && c2x < o.c2x) return true; return c1x == o.c1x && c1y == o.c1y && c2x == o.c2x && c2y < o.c2y; } }; std::map<CellCoord, std::vector<int >> neighbors_map; std::vector<std::vector<int>> graph; public: GridNeighborhoodGraphImpl (const Mat &container_, int points_size, int cell_size_x_img1, int cell_size_y_img1, int cell_size_x_img2, int cell_size_y_img2, int max_neighbors) { const auto * const container = (float *) container_.data; // <int, int, int, int> -> {neighbors set} // Key is cell position. The value is indexes of neighbors. const float cell_sz_x1 = 1.f / (float) cell_size_x_img1, cell_sz_y1 = 1.f / (float) cell_size_y_img1, cell_sz_x2 = 1.f / (float) cell_size_x_img2, cell_sz_y2 = 1.f / (float) cell_size_y_img2; const int dimension = container_.cols; for (int i = 0; i < points_size; i++) { const int idx = dimension * i; neighbors_map[CellCoord((int)(container[idx ] * cell_sz_x1), (int)(container[idx+1] * cell_sz_y1), (int)(container[idx+2] * cell_sz_x2), (int)(container[idx+3] * cell_sz_y2))].emplace_back(i); } //--------- create a graph ---------- graph = std::vector<std::vector<int>>(points_size); // store neighbors cells into graph (2D vector) for (const auto &cell : neighbors_map) { const int neighbors_in_cell = static_cast<int>(cell.second.size()); // only one point in cell -> no neighbors if (neighbors_in_cell < 2) continue; const std::vector<int> &neighbors = cell.second; // ---------- fill graph ----- for (int v_in_cell : neighbors) { // there is always at least one neighbor auto &graph_row = graph[v_in_cell]; graph_row = std::vector<int>(std::min(max_neighbors, neighbors_in_cell-1)); int j = 0; for (int n : neighbors) if (n != v_in_cell){ graph_row[j++] = n; if (j >= max_neighbors) break; } } } } const std::vector<std::vector<int>> &getGraph () const override { return graph; } inline const std::vector<int> &getNeighbors(int point_idx) const override { // Note, neighbors vector also includes point_idx! // return neighbors_map[vertices_to_cells[point_idx]]; return graph[point_idx]; } }; Ptr<GridNeighborhoodGraph> GridNeighborhoodGraph::create(const Mat &points, int points_size, int cell_size_x_img1_, int cell_size_y_img1_, int cell_size_x_img2_, int cell_size_y_img2_, int max_neighbors) { return makePtr<GridNeighborhoodGraphImpl>(points, points_size, cell_size_x_img1_, cell_size_y_img1_, cell_size_x_img2_, cell_size_y_img2_, max_neighbors); } class GridNeighborhoodGraph2Impl : public GridNeighborhoodGraph2 { private: // This struct is used for the nearest neighbors search by griding two images. struct CellCoord { int c1x, c1y; CellCoord (int c1x_, int c1y_) { c1x = c1x_; c1y = c1y_; } bool operator==(const CellCoord &o) const { return c1x == o.c1x && c1y == o.c1y; } bool operator<(const CellCoord &o) const { if (c1x < o.c1x) return true; return c1x == o.c1x && c1y < o.c1y; } }; std::map<CellCoord, std::vector<int >> neighbors_map1, neighbors_map2; std::vector<std::vector<int>> graph; public: GridNeighborhoodGraph2Impl (const Mat &container_, int points_size, int cell_size_x_img1, int cell_size_y_img1, int cell_size_x_img2, int cell_size_y_img2) { const auto * const container = (float *) container_.data; // <int, int, int, int> -> {neighbors set} // Key is cell position. The value is indexes of neighbors. const auto cell_sz_x1 = 1.f / (float) cell_size_x_img1, cell_sz_y1 = 1.f / (float) cell_size_y_img1, cell_sz_x2 = 1.f / (float) cell_size_x_img2, cell_sz_y2 = 1.f / (float) cell_size_y_img2; const int dimension = container_.cols; for (int i = 0; i < points_size; i++) { const int idx = dimension * i; neighbors_map1[CellCoord((int)(container[idx ] * cell_sz_x1), (int)(container[idx+1] * cell_sz_y1))].emplace_back(i); neighbors_map2[CellCoord((int)(container[idx+2] * cell_sz_x2), (int)(container[idx+3] * cell_sz_y2))].emplace_back(i); } //--------- create a graph ---------- graph = std::vector<std::vector<int>>(points_size); // store neighbors cells into graph (2D vector) for (const auto &cell : neighbors_map1) { const int neighbors_in_cell = static_cast<int>(cell.second.size()); // only one point in cell -> no neighbors if (neighbors_in_cell < 2) continue; const std::vector<int> &neighbors = cell.second; // ---------- fill graph ----- // for (int v_in_cell : neighbors) { const int v_in_cell = neighbors[0]; // there is always at least one neighbor auto &graph_row = graph[v_in_cell]; graph_row.reserve(neighbors_in_cell); for (int n : neighbors) if (n != v_in_cell) graph_row.emplace_back(n); // } } // store neighbors cells into graph (2D vector) for (const auto &cell : neighbors_map2) { if (cell.second.size() < 2) continue; const std::vector<int> &neighbors = cell.second; // ---------- fill graph ----- // for (const int &v_in_cell : neighbors) { const int v_in_cell = neighbors[0]; // there is always at least one neighbor auto &graph_row = graph[v_in_cell]; for (const int &n : neighbors) if (n != v_in_cell) { bool has = false; for (const int &nn : graph_row) if (n == nn) { has = true; break; } if (!has) graph_row.emplace_back(n); } // } } } const std::vector<std::vector<int>> &getGraph () const override { return graph; } inline const std::vector<int> &getNeighbors(int point_idx) const override { // Note, neighbors vector also includes point_idx! // return neighbors_map[vertices_to_cells[point_idx]]; return graph[point_idx]; } }; Ptr<GridNeighborhoodGraph2> GridNeighborhoodGraph2::create(const Mat &points, int points_size, int cell_size_x_img1_, int cell_size_y_img1_, int cell_size_x_img2_, int cell_size_y_img2_) { return makePtr<GridNeighborhoodGraph2Impl>(points, points_size, cell_size_x_img1_, cell_size_y_img1_, cell_size_x_img2_, cell_size_y_img2_); } }} namespace vsac { void triangulatePointsLindstrom (const cv::Mat &F, const cv::Mat &points1, const cv::Mat &points2, cv::Mat &points1_corr, cv::Mat &points2_corr, const std::vector<bool> &good_point_mask) { cv::Mat temp; cv::vsac::Utils::triangulatePoints(F, points1, points2, points1_corr, points2_corr, temp, temp, temp, temp, temp, good_point_mask); } void triangulatePointsLindstrom (const cv::Mat &E, const cv::Mat &points1, const cv::Mat &points2, cv::Mat &points1_corr, cv::Mat &points2_corr, const cv::Mat &K1, const cv::Mat &K2, cv::Mat &points3D, cv::Mat &R, cv::Mat &t, const std::vector<bool> &good_point_mask) { cv::vsac::Utils::triangulatePoints(E, points1, points2, points1_corr, points2_corr, K1, K2, points3D, R, t, good_point_mask); } bool getCorrectedPointsHomography(const cv::Mat &points1, const cv::Mat &points2, cv::Mat &corr_points1, cv::Mat &corr_points2, const cv::Mat &H, const std::vector<bool> &mask) { cv::Mat pts1 = points1, pts2 = points2; pts1.convertTo(pts1, CV_32F); pts2.convertTo(pts2, CV_32F); const auto * const p1 = (float *) pts1.data; const auto * const p2 = (float *) pts2.data; corr_points1 = cv::Mat_<float>::zeros(points1.rows, 2); corr_points2 = cv::Mat_<float>::zeros(points2.rows, 2); auto * cp1 = (float *) corr_points1.data; auto * cp2 = (float *) corr_points2.data; cv::Mat H_inv = H.inv(); const auto * const h = (double *) H.data; const auto * const h_inv = (double *) H_inv.data; // https://cmp.felk.cvut.cz/~chum/papers/chum-icpr12.pdf double s2_sqr = 1, EPS = 1; for (int i = 0; i < points1.rows; i++) { if (! mask[i]) continue; const int idx = 2*i; const auto x1 = p1[idx], y1 = p1[idx+1], x2 = p2[idx], y2 = p2[idx+1]; // Jacobian of homography matrix cv::Matx33d A (h[0] - x2*h[6], h[1] - x2*h[7], h[2] + x2 * (x1 * h[6] + y1 * h[7]), h[3] - y2*h[6], h[4] - y2*h[7], h[5] + y2 * (x1 * h[6] + y1 * h[7]), 0, 0, h[8] + h[6] * x1 + h[7] * y1); const double s1_sqr = pow(1/cv::determinant(A / A(2,2)), 2); // H^-1 (x2 y2 1) const auto z1_proj = h_inv[6] * x2 + h_inv[7] * y2 + h_inv[8]; const auto x1_proj = (h_inv[0] * x2 + h_inv[1] * y2 + h_inv[2]) / z1_proj; const auto y1_proj = (h_inv[3] * x2 + h_inv[4] * y2 + h_inv[5]) / z1_proj; const auto x1_corr = (s1_sqr * x1 + s2_sqr * x1_proj) / (s1_sqr + s2_sqr); const auto y1_corr = (s1_sqr * y1 + s2_sqr * y1_proj) / (s1_sqr + s2_sqr); const auto z2_corr = h[6] * x1_corr + h[7] * y1_corr + h[8]; const auto x2_corr = (h[0] * x1_corr + h[1] * y1_corr + h[2]) / z2_corr; const auto y2_corr = (h[3] * x1_corr + h[4] * y1_corr + h[5]) / z2_corr; cp1[idx ] = x1_corr; cp1[idx+1] = y1_corr; cp2[idx ] = x2_corr; cp2[idx+1] = y2_corr; } corr_points1.convertTo(corr_points1, points1.type()); corr_points2.convertTo(corr_points2, points2.type()); return true; } /* // // Older version for correcting points using half homography // bool getCorrectedPointsHomography(const cv::Mat &points, cv::Mat &corr_points, const cv::Mat &H, const std::vector<bool> &mask) { Eigen::Matrix<double, 3, 3, Eigen::RowMajor> h((double *)H.data); h /= h(2,2); // must be normaized to avoid internal sqrt error Eigen::Matrix<double, 3, 3> sqrtH; try { sqrtH = h.sqrt(); } catch (const std::exception &e) { std::cerr << e.what() << "\n"; std::cerr << "Cannot find matrix square root!\n"; return false; } cv::Mat_<double > H_half (3,3,(double*)sqrtH.data()); cv::transpose(H_half, H_half); cv::Mat pts1, pts2, mid_pts, corr_pts1, corr_pts2; cv::vconcat(points.colRange(0,2).t(), cv::Mat_<float>::ones(1, points.rows), pts1); cv::vconcat(points.colRange(2,4).t(), cv::Mat_<float>::ones(1, points.rows), pts2); pts1.convertTo(pts1, CV_64F); pts2.convertTo(pts2, CV_64F); corr_pts1 = H_half * pts1; corr_pts2 = H_half.inv() * pts2; cv::divide(corr_pts1.row(0), corr_pts1.row(2), corr_pts1.row(0)); cv::divide(corr_pts1.row(1), corr_pts1.row(2), corr_pts1.row(1)); cv::divide(corr_pts2.row(0), corr_pts2.row(2), corr_pts2.row(0)); cv::divide(corr_pts2.row(1), corr_pts2.row(2), corr_pts2.row(1)); // mid_pts = (H_half * pts1 + H_half.inv() * pts2) * 0.5; mid_pts = (corr_pts1 + corr_pts2) * 0.5; corr_pts1 = H_half.inv() * mid_pts; corr_pts2 = H_half * mid_pts; cv::divide(corr_pts1.row(0), corr_pts1.row(2), corr_pts1.row(0)); cv::divide(corr_pts1.row(1), corr_pts1.row(2), corr_pts1.row(1)); cv::divide(corr_pts2.row(0), corr_pts2.row(2), corr_pts2.row(0)); cv::divide(corr_pts2.row(1), corr_pts2.row(2), corr_pts2.row(1)); cv::hconcat(corr_pts1.rowRange(0,2).t(), corr_pts2.rowRange(0,2).t(), corr_points); corr_points.convertTo(corr_points, CV_32F); return true; }*/ }
43.367805
178
0.561977
[ "vector", "3d" ]
4d5eef6afbb0bbe4e18ef1baa126d6eacd376f7a
1,629
cpp
C++
competitive programming/leetcode/15. 3Sum.cpp
kashyap99saksham/Code
96658d0920eb79c007701d2a3cc9dbf453d78f96
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/leetcode/15. 3Sum.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/leetcode/15. 3Sum.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int> > res; int n=nums.size(); if(n<3) return res; sort(nums.begin(), nums.end()); for(int i=0;i<n-2;i++){ if(i==0 || (i>0 && nums[i]!=nums[i-1])){ // not taking duplicates int sum=0-nums[i]; int low=i+1, high=n-1; while(low<high){ if(nums[low]+nums[high]==sum){ res.push_back({nums[i], nums[low], nums[high]}); while(low<high && nums[low]==nums[low+1]) low++; while(low<high && nums[high]==nums[high-1]) high--; low++; high--; } else if(nums[low]+nums[high]>sum) high--; else low++; } } } return res; } }; /* while(low<high && nums[low]==nums[low+1]) low++; while(low<high && nums[high]==nums[high-1]) high--; here, we are doing low++ in the while loop because, for a given sum, we might get result as A[i], A[low]=x, A[high]=y ie: (A[i), x, y) Now if we din't check A[low]==A[low+1] we might get duplicate results, as if A[low+1]=x, then our solution again will be (A[i], x, y) */
24.313433
161
0.505832
[ "vector" ]
4d64b106879594bc2111e20d8ac703419103c2e3
2,816
cc
C++
src/CCA/Components/Models/SolidReactionModel/DiffusionModel.cc
damu1000/Uintah
0c768664c1fe0a80eff2bbbd9b837e27f281f0a5
[ "MIT" ]
2
2021-12-17T05:50:44.000Z
2021-12-22T21:37:32.000Z
src/CCA/Components/Models/SolidReactionModel/DiffusionModel.cc
damu1000/Uintah
0c768664c1fe0a80eff2bbbd9b837e27f281f0a5
[ "MIT" ]
null
null
null
src/CCA/Components/Models/SolidReactionModel/DiffusionModel.cc
damu1000/Uintah
0c768664c1fe0a80eff2bbbd9b837e27f281f0a5
[ "MIT" ]
1
2020-11-30T04:46:05.000Z
2020-11-30T04:46:05.000Z
/* * The MIT License * * Copyright (c) 1997-2020 The University of Utah * * 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 <CCA/Components/Models/SolidReactionModel/DiffusionModel.h> #include <Core/Exceptions/ProblemSetupException.h> #include <Core/ProblemSpec/ProblemSpec.h> #include <cmath> using namespace Uintah; using namespace std; DiffusionModel::DiffusionModel(ProblemSpecP &params) { params->require("dimension", d_dimension); if(d_dimension > 4 || d_dimension < 1) throw new ProblemSetupException("ERROR: Diffusion reaction model must be 1, 2, 3 or 4 dimensional.", __FILE__, __LINE__); } void DiffusionModel::outputProblemSpec(ProblemSpecP& ps) { ProblemSpecP model_ps = ps->appendChild("RateModel"); model_ps->setAttribute("type","Diffusion"); model_ps->appendElement("dimension", d_dimension); } /// @brief Get the contribution to the rate from the fraction reacted /// @param fractionReactant The fraction in the volume that is reactant, i.e. m_r/(m_r+m_p) /// @return a scalar for the extent of reaction double DiffusionModel::getDifferentialFractionChange(double fractionReactant) { double oneMinus = 1.0-fractionReactant; switch(d_dimension) { case 1: // 1-Dimensional return 0.5*fractionReactant; break; case 2: // 2-Dimensional return 1.0/(-log(oneMinus)); break; case 3: // Jander Equation return 3.0*pow(oneMinus, 2.0/3.0)/(2.0*(1.0-pow(oneMinus, 1.0/3.0))); break; case 4: // Ginstling-Brounshtein break; default: throw new ProblemSetupException("ERROR: Diffusion reaction model must be 1, 2 or 3 dimensional.", __FILE__, __LINE__); } return -999.0; }
37.546667
130
0.709162
[ "model" ]
4d66a1b02bcd20b772b38eb9ba845ec900c62db9
1,236
cpp
C++
boboleetcode/Play-Leetcode-master/0253-Meeting-Rooms-II/cpp-0253/main4.cpp
yaominzh/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2021-03-25T05:26:55.000Z
2021-04-20T03:33:24.000Z
boboleetcode/Play-Leetcode-master/0253-Meeting-Rooms-II/cpp-0253/main4.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0253-Meeting-Rooms-II/cpp-0253/main4.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/meeting-rooms-ii/description/ /// Author : liuyubobobo /// Time : 2018-09-10 #include <iostream> #include <vector> using namespace std; /// Dealing with start time and end time seperately /// make start time and end time in a pair structure /// and deal with them in one single vector:) /// /// Time Complexity: O(nlogn) /// Space Complexity: O(n) /// Definition for an interval. struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { vector<pair<int, char>> timepoints; for(const Interval& interval: intervals){ timepoints.push_back(make_pair(interval.start, 's')); timepoints.push_back(make_pair(interval.end, 'e')); } sort(timepoints.begin(), timepoints.end()); int res = 0; int cur = 0; for(const pair<int, char>& p: timepoints) if(p.second == 's'){ cur ++; res = max(res, cur); } else cur --; return res; } }; int main() { return 0; }
22.472727
72
0.570388
[ "vector" ]
4d66ff9d37458602d7d83226cf00d12f491f1275
4,362
hpp
C++
sfml-porting/Shader.hpp
osom8979/example
f3cbe2c345707596edc1ec2763f9318c4676a92f
[ "Zlib" ]
1
2020-02-11T05:37:54.000Z
2020-02-11T05:37:54.000Z
sfml-porting/Shader.hpp
osom8979/example
f3cbe2c345707596edc1ec2763f9318c4676a92f
[ "Zlib" ]
null
null
null
sfml-porting/Shader.hpp
osom8979/example
f3cbe2c345707596edc1ec2763f9318c4676a92f
[ "Zlib" ]
1
2022-03-01T00:47:19.000Z
2022-03-01T00:47:19.000Z
/** * @file Shader.hpp * @brief Shader class prototype. * @author zer0 * @date 2019-02-19 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_GUI_SHADER_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_GUI_SHADER_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/geometry/Point3.hpp> #include <libtbag/geometry/Point4.hpp> #include <libtbag/math/Matrix.hpp> #include <libtbag/gui/SfNative.hpp> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace gui { // Forward declaration. class Texture; /** * Shader class prototype. * * @author zer0 * @date 2019-02-19 */ class TBAG_API Shader : public SfNative { public: enum class Type { T_VERTEX, T_GEOMETRY, T_FRAGMENT }; using Vec2 = libtbag::geometry::Point2f; using Ivec2 = libtbag::geometry::Point2i; using Bvec2 = libtbag::geometry::Point2b; using Vec3 = libtbag::geometry::Point3f; using Ivec3 = libtbag::geometry::Point3i; using Bvec3 = libtbag::geometry::Point3b; using Vec4 = libtbag::geometry::Point4f; using Ivec4 = libtbag::geometry::Point4i; using Bvec4 = libtbag::geometry::Point4b; using Mat3 = libtbag::math::Matrix3x3f; using Mat4 = libtbag::math::Matrix4x4f; public: struct current_texture_t {}; public: TBAG_CONSTEXPR static current_texture_t current_texture = current_texture_t{}; public: Shader(); Shader(void * handle, no_init_no_ref_t); Shader(Shader && obj) TBAG_NOEXCEPT; virtual ~Shader(); public: Shader & operator =(Shader && obj) TBAG_NOEXCEPT; public: void swap(Shader & obj) TBAG_NOEXCEPT; public: inline friend void swap(Shader & lh, Shader & rh) TBAG_NOEXCEPT { lh.swap(rh); } public: bool loadFromFile(std::string const & filename, Type type); bool loadFromFile(std::string const & vertex, std::string const & fragment); bool loadFromFile(std::string const & vertex, std::string const & geometry, std::string const & fragment); bool loadFromMemory(std::string const & shader, Type type); bool loadFromMemory(std::string const & vertex, std::string const & fragment); bool loadFromMemory(std::string const & vertex, std::string const & geometry, std::string const & fragment); public: void setUniform(std::string const & name, float x); void setUniform(std::string const & name, Vec2 const & vector); void setUniform(std::string const & name, Vec3 const & vector); void setUniform(std::string const & name, Vec4 const & vector); void setUniform(std::string const & name, int x); void setUniform(std::string const & name, Ivec2 const & vector); void setUniform(std::string const & name, Ivec3 const & vector); void setUniform(std::string const & name, Ivec4 const & vector); void setUniform(std::string const & name, bool x); void setUniform(std::string const & name, Bvec2 const & vector); void setUniform(std::string const & name, Bvec3 const & vector); void setUniform(std::string const & name, Bvec4 const & vector); void setUniform(std::string const & name, Mat3 const & matrix); void setUniform(std::string const & name, Mat4 const & matrix); void setUniform(std::string const & name, Texture const & texture); void setUniform(std::string const & name, current_texture_t); void setUniformArray(std::string const & name, float const * scalar_arr, std::size_t length); void setUniformArray(std::string const & name, Vec2 const * vector_arr, std::size_t length); void setUniformArray(std::string const & name, Vec3 const * vector_arr, std::size_t length); void setUniformArray(std::string const & name, Vec4 const * vector_arr, std::size_t length); void setUniformArray(std::string const & name, Mat3 const * matrix_arr, std::size_t length); void setUniformArray(std::string const & name, Mat4 const * matrix_arr, std::size_t length); unsigned int getNativeHandle() const; public: static void bind(Shader const & shader); static bool isAvailable(); static bool isGeometryAvailable(); }; } // namespace gui // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_GUI_SHADER_HPP__
31.381295
112
0.689592
[ "geometry", "vector" ]
4d6848e8d7c3a080a6f88a5612d0b5a1ae5afffa
9,555
hpp
C++
src/libs/optframe/src/OptFrame/MultiEvaluator.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
1
2021-08-19T13:31:29.000Z
2021-08-19T13:31:29.000Z
src/libs/optframe/src/OptFrame/MultiEvaluator.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
null
null
null
src/libs/optframe/src/OptFrame/MultiEvaluator.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
null
null
null
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 Lesser General Public License v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_MULTI_EVALUATOR_HPP_ #define OPTFRAME_MULTI_EVALUATOR_HPP_ #include <iostream> #include "Solution.hpp" #include "Evaluator.hpp" #include "MultiEvaluation.hpp" #include "MultiDirection.hpp" #include "Action.hpp" using namespace std; using namespace scannerpp; namespace optframe { // MultiEvaluator is not a REAL evaluator... a bunch/pack of evaluators... TODO: unify template<XSolution S, XEvaluation XEv, XEvaluation XMEv = MultiEvaluation<>, XESolution XMES = pair<S, XMEv>, XSearch<XMES> XSH = XMES> //, XSearch<XES> XSH = MultiESolution<XES> > class MultiEvaluator: public MultiDirection, public GeneralEvaluator<XMES, XMEv, XSH> { //XESolution XES = pair<S, XMEv>, using XES = pair<S, XEv>; protected: vector<Evaluator<S, XEv, XES>*> sngEvaluators; // single evaluators bool allowCosts; // move.cost() is enabled or disabled for this Evaluator public: MultiEvaluator(vector<Evaluator<S, XEv, XES>*> _veval) : sngEvaluators(_veval), allowCosts(false) { for (unsigned i = 0; i < _veval.size(); i++) if (_veval[i]) vDir.push_back(_veval[i]); nObjectives = vDir.size(); } MultiEvaluator(bool _allowCosts = false) : allowCosts(_allowCosts) { } virtual void addEvaluator(Evaluator<S, XEv, XES>& ev) { sngEvaluators.push_back(&ev); } // MultiEvaluator(MultiDirection& mDir, bool _allowCosts = false) : // MultiDirection(mDir), allowCosts(_allowCosts) // { // } // // MultiEvaluator(vector<Direction*>& vDir, bool _allowCosts = false) : // MultiDirection(vDir), allowCosts(_allowCosts) // { // } // MultiEvaluator(MultiEvaluator<S, XEv>& _mev) : // sngEvaluators(*_mev.getEvaluators2()), allowCosts(false) // { // cout<<"sngEvaluators.size():"<<sngEvaluators.size()<<endl; // for (unsigned i = 0; i < sngEvaluators.size(); i++) // if (sngEvaluators[i]) // vDir.push_back(sngEvaluators[i]); // nObjectives = vDir.size(); // } virtual ~MultiEvaluator() { } unsigned size() { return sngEvaluators.size(); } unsigned size() const { return sngEvaluators.size(); } virtual bool betterThan(const Evaluation<>& ev1, const Evaluation<>& ev2, int index) { return sngEvaluators[index]->betterThan(ev1, ev2); } virtual bool equals(const Evaluation<>& ev1, const Evaluation<>& ev2, int index) { return sngEvaluators[index]->equals(ev1, ev2); } //changed to Meval without point TODO virtual XMEv evaluate(const S& s) { cout << "inside mother class" << endl; getchar(); MultiEvaluation<> nev; for (unsigned i = 0; i < sngEvaluators.size(); i++) { Evaluation<> ev {sngEvaluators[i]->evaluate(s)}; nev.addEvaluation(ev); } return nev; } void clear() { for (int e = 0; e < int(sngEvaluators.size()); e++) delete sngEvaluators[e]; } //virtual void reevaluateMEV(MultiEvaluation<>& mev, const XES& se) // //virtual void reevaluate(pair<S, MultiEvaluation<>>& se) override //virtual void reevaluate(pair<S, XMEv>& se) override virtual void reevaluate(XMES& se) override { MultiEvaluation<>& mev = se.second; // for (unsigned i = 0; i < sngEvaluators.size(); i++) { //Evaluation<> e { std::move(mev[i]) }; // TODO (IGOR): why move???? //sngEvaluators[i]->reevaluate(e, s); //mev[i] = std::move(e); // Evaluation<>& e = mev[i]; // TODO: embed MEV in 'se' pair<decltype(se.first), XEv> pse(se.first, e); // TODO: we should AVOID this 's' and 'e' copy... by keeping s,e together. sngEvaluators[i]->reevaluate(pse); e = std::move(pse.second); // TODO: verify if this works //mev[i] = std::move(e); } } // bool getAllowCosts() // { // return allowCosts; // } // vector<Evaluator<XES, XEv>*> getEvaluators2() // { // return sngEvaluators; // } // // TODO: check // const vector<const Evaluator<XES, XEv>*>* getEvaluatorsConstTest() const // { // if (sngEvaluators.size() > 0) // return new vector<const Evaluator<XES, XEv>*>(sngEvaluators); // else // return nullptr; // } // Evaluator<XES, XEv>& at(unsigned index) // { // return *sngEvaluators.at(index); // } // // const Evaluator<XES, XEv>& at(unsigned index) const // { // return *sngEvaluators.at(index); // } // // Evaluator<XES, XEv>& operator[](unsigned index) // { // return *sngEvaluators[index]; // } // // const Evaluator<XES, XEv>& operator[](unsigned index) const // { // return *sngEvaluators[index]; // } // void addEvaluator(const Evaluator<XES, XEv>& ev) // { // sngEvaluators.push_back(&ev.clone()); // } // ======================= // this strictly better than parameter 'e' (for mini, 'this' < 'e') virtual bool betterStrict(const XMEv& e1, const XMEv& e2) { assert(false); return false; } // returns 'true' if this 'cost' (represented by this Evaluation) is improvement virtual bool isStrictImprovement(const XMEv& e) { assert(false); return false; } // returns 'true' if this 'cost' (represented by this Evaluation) is improvement virtual bool isNonStrictImprovement(const XMEv& e) { assert(false); return false; } virtual bool equals(const XMEv& e1, const XMEv& e2) { assert(false); return false; } // ================================================ protected: // ============= Component =============== virtual bool compatible(string s) { return (s == idComponent()) || (MultiDirection::compatible(s)); } static string idComponent() { stringstream ss; ss << MultiDirection::idComponent() << ":MultiEvaluator"; return ss.str(); } virtual string id() const { return idComponent(); } }; template<XSolution S, XEvaluation XEv = Evaluation<>, XESolution XES = pair<S, XEv>, X2ESolution<XES> X2ES = MultiESolution<XES>> class MultiEvaluatorAction: public Action<S, XEv, X2ES> { public: virtual ~MultiEvaluatorAction() { } virtual string usage() { return ":MultiEvaluator idx evaluate :Solution idx [output_variable] => OptFrame:Evaluation"; } virtual bool handleComponent(string type) { return ComponentHelper::compareBase(MultiEvaluator<S, XEv>::idComponent(), type); } virtual bool handleComponent(Component& component) { return component.compatible(MultiEvaluator<S, XEv>::idComponent()); } virtual bool handleAction(string action) { return (action == "evaluate"); //|| (action == "betterThan") || (action == "betterOrEquals"); } virtual bool doCast(string component, int id, string type, string variable, HeuristicFactory<S, XEv, XES, X2ES>& hf, map<string, string>& d) { cout << "MultiEvaluator::doCast: NOT IMPLEMENTED!" << endl; return false; if (!handleComponent(type)) { cout << "EvaluatorAction::doCast error: can't handle component type '" << type << " " << id << "'" << endl; return false; } Component* comp = hf.components[component].at(id); if (!comp) { cout << "EvaluatorAction::doCast error: nullptr component '" << component << " " << id << "'" << endl; return false; } if (!ComponentHelper::compareBase(comp->id(), type)) { cout << "EvaluatorAction::doCast error: component '" << comp->id() << " is not base of " << type << "'" << endl; return false; } // remove old component from factory hf.components[component].at(id) = nullptr; // cast object to lower type Component* final = nullptr; if (type == Evaluator<XES, XEv>::idComponent()) { final = (Evaluator<XES, XEv>*) comp; } else { cout << "EvaluatorAction::doCast error: no cast for type '" << type << "'" << endl; return false; } // add new component Scanner scanner(variable); return ComponentAction<S, XEv>::addAndRegister(scanner, *final, hf, d); } virtual bool doAction(string content, HeuristicFactory<S, XEv, XES, X2ES>& hf, map<string, string>& dictionary, map<string, vector<string> >& ldictionary) { cout << "MultiEvaluator::doAction: NOT IMPLEMENTED!" << endl; return false; //cout << "Evaluator::doAction '" << content << "'" << endl; Scanner scanner(content); if (!scanner.hasNext()) return false; Evaluator<XES, XEv>* ev; hf.assign(ev, *scanner.nextInt(), scanner.next()); if (!ev) return false; if (!scanner.hasNext()) return false; string action = scanner.next(); if (!handleAction(action)) return false; if (action == "evaluate") { if (!scanner.hasNext()) return false; S* s; hf.assign(s, *scanner.nextInt(), scanner.next()); if (!s) return false; Evaluation<>& e = ev->evaluate(*s); return Action<S, XEv, X2ES>::addAndRegister(scanner, e, hf, dictionary); } // no action found! return false; } }; } // namespace optframe #endif /*OPTFRAME_MULTI_EVALUATOR_HPP_*/
24.43734
181
0.654108
[ "object", "vector" ]
4d69b22433bbdd9ef3094c19326685fdcb56e264
3,008
hxx
C++
OCC/inc/Approx_SameParameter.hxx
cy15196/FastCAE
0870752ec2e590f3ea6479e909ebf6c345ac2523
[ "BSD-3-Clause" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Approx_SameParameter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
33
2019-11-13T18:09:51.000Z
2021-11-26T17:24:12.000Z
opencascade/Approx_SameParameter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1995-06-02 // Created by: Xavier BENVENISTE // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Approx_SameParameter_HeaderFile #define _Approx_SameParameter_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <Standard_Real.hxx> class Geom2d_BSplineCurve; class Adaptor2d_HCurve2d; class Adaptor3d_HCurve; class Adaptor3d_HSurface; class Standard_OutOfRange; class Standard_ConstructionError; class Geom_Curve; class Geom2d_Curve; class Geom_Surface; //! Approximation of a PCurve on a surface to make its //! parameter be the same that the parameter of a given 3d //! reference curve. class Approx_SameParameter { public: DEFINE_STANDARD_ALLOC //! Warning: the C3D and C2D must have the same parametric domain. Standard_EXPORT Approx_SameParameter(const Handle(Geom_Curve)& C3D, const Handle(Geom2d_Curve)& C2D, const Handle(Geom_Surface)& S, const Standard_Real Tol); Standard_EXPORT Approx_SameParameter(const Handle(Adaptor3d_HCurve)& C3D, const Handle(Geom2d_Curve)& C2D, const Handle(Adaptor3d_HSurface)& S, const Standard_Real Tol); //! Warning: the C3D and C2D must have the same parametric domain. Standard_EXPORT Approx_SameParameter(const Handle(Adaptor3d_HCurve)& C3D, const Handle(Adaptor2d_HCurve2d)& C2D, const Handle(Adaptor3d_HSurface)& S, const Standard_Real Tol); Standard_Boolean IsDone() const; Standard_Real TolReached() const; //! Tells whether the original data had already the same //! parameter up to the tolerance : in that case nothing //! is done. Standard_Boolean IsSameParameter() const; //! Returns the 2D curve that has the same parameter as //! the 3D curve once evaluated on the surface up to the //! specified tolerance Handle(Geom2d_BSplineCurve) Curve2d() const; protected: private: //! Compute the Pcurve (internal use only). Standard_EXPORT void Build (const Standard_Real Tol); Standard_Boolean mySameParameter; Standard_Boolean myDone; Standard_Real myTolReached; Handle(Geom2d_BSplineCurve) myCurve2d; Handle(Adaptor2d_HCurve2d) myHCurve2d; Handle(Adaptor3d_HCurve) myC3d; Handle(Adaptor3d_HSurface) mySurf; }; #include <Approx_SameParameter.lxx> #endif // _Approx_SameParameter_HeaderFile
28.377358
177
0.772274
[ "3d" ]
4d75f5cf9e2dea707400cef1cde155189db0d841
16,533
cpp
C++
xsbench-sycl/Simulation.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
58
2020-08-06T18:53:44.000Z
2021-10-01T07:59:46.000Z
xsbench-sycl/Simulation.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
2
2020-12-04T12:35:02.000Z
2021-03-04T22:49:25.000Z
xsbench-sycl/Simulation.cpp
BeauJoh/HeCBench
594b845171d686dc951971ce36ed59cf114dd2b4
[ "BSD-3-Clause" ]
13
2020-08-19T13:44:18.000Z
2021-09-08T04:25:34.000Z
#include "XSbench_header.h" //////////////////////////////////////////////////////////////////////////////////// // BASELINE FUNCTIONS //////////////////////////////////////////////////////////////////////////////////// // All "baseline" code is at the top of this file. The baseline code is a simple // implementation of the algorithm, with only minor CPU optimizations in place. // Following these functions are a number of optimized variants, // which each deploy a different combination of optimizations strategies. By // default, XSBench will only run the baseline implementation. Optimized variants // are not yet implemented in this SYCL port. //////////////////////////////////////////////////////////////////////////////////// // use SYCL namespace to reduce symbol names using namespace cl::sycl; unsigned long long run_event_based_simulation(Inputs in, SimulationData SD, int mype, double * kernel_init_time) { //////////////////////////////////////////////////////////////////////////////// // SUMMARY: Simulation Data Structure Manifest for "SD" Object // Here we list all heap arrays (and lengths) in SD that would need to be // offloaded manually if using an accelerator with a seperate memory space //////////////////////////////////////////////////////////////////////////////// // int * num_nucs; // Length = length_num_nucs; // double * concs; // Length = length_concs // int * mats; // Length = length_mats // double * unionized_energy_array; // Length = length_unionized_energy_array // int * index_grid; // Length = length_index_grid // NuclideGridPoint * nuclide_grid; // Length = length_nuclide_grid // // Note: "unionized_energy_array" and "index_grid" can be of zero length // depending on lookup method. // // Note: "Lengths" are given as the number of objects in the array, not the // number of bytes. //////////////////////////////////////////////////////////////////////////////// // Let's create an extra verification array to reduce manually later on if( mype == 0 ) printf("Allocating an additional %.1lf MB of memory for verification arrays...\n", in.lookups * sizeof(int) /1024.0/1024.0); int * verification_host = (int *) malloc(in.lookups * sizeof(int)); // Timers double start = get_time(); double stop; // Scope here is important, as when we exit this blocl we will automatically sync with device // to ensure all work is done and that we can read from verification_host array. { // create a queue using the default device for the platform (cpu, gpu) queue sycl_q{default_selector()}; //queue sycl_q{gpu_selector()}; //queue sycl_q{cpu_selector()}; if(mype == 0 ) printf("Running on: %s\n", sycl_q.get_device().get_info<cl::sycl::info::device::name>().c_str()); if(mype == 0 ) printf("Initializing device buffers and JIT compiling kernel...\n"); //////////////////////////////////////////////////////////////////////////////// // Create Device Buffers //////////////////////////////////////////////////////////////////////////////// printf(" assign SYCL buffer to existing memory\n"); buffer<int, 1> num_nucs_d(SD.num_nucs,SD.length_num_nucs); buffer<double, 1> concs_d(SD.concs, SD.length_concs); buffer<int, 1> mats_d(SD.mats, SD.length_mats); buffer<NuclideGridPoint, 1> nuclide_grid_d(SD.nuclide_grid, SD.length_nuclide_grid); buffer<int, 1> verification_d(verification_host, in.lookups); // These two are a bit of a hack. Sometimes they are empty buffers (if using hash or nuclide // grid methods). OpenCL will throw an example when we try to create an empty buffer. So, we // will just allocate some memory for them and move them as normal. The rest of our code // won't actually use them if they aren't needed, so this is safe. Probably a cleaner way // of doing this. if( SD.length_unionized_energy_array == 0 ) { SD.length_unionized_energy_array = 1; SD.unionized_energy_array = (double *) malloc(sizeof(double)); } buffer<double,1> unionized_energy_array_d(SD.unionized_energy_array, SD.length_unionized_energy_array); if( SD.length_index_grid == 0 ) { SD.length_index_grid = 1; SD.index_grid = (int *) malloc(sizeof(int)); } // For the unionized grid, this is a large array. Enforce that it is able to be allocated on the // OpenCL device (as some OpenCL devices have fairly low limts here for some reason...) size_t index_grid_allocation_sz = ceil((SD.length_index_grid * sizeof(int))); assert( index_grid_allocation_sz <= sycl_q.get_device().get_info<cl::sycl::info::device::max_mem_alloc_size>() ); buffer<int, 1> index_grid_d(SD.index_grid, (unsigned long long ) SD.length_index_grid); //////////////////////////////////////////////////////////////////////////////// // Define Device Kernel //////////////////////////////////////////////////////////////////////////////// // queue a kernel to be run, as a lambda sycl_q.submit([&](handler &cgh) { //////////////////////////////////////////////////////////////////////////////// // Create Device Accessors for Device Buffers //////////////////////////////////////////////////////////////////////////////// auto num_nucs = num_nucs_d.get_access<access::mode::read>(cgh); auto concs = concs_d.get_access<access::mode::read>(cgh); auto mats = mats_d.get_access<access::mode::read>(cgh); auto nuclide_grid = nuclide_grid_d.get_access<access::mode::read>(cgh); auto verification = verification_d.get_access<access::mode::write>(cgh); auto unionized_energy_array = unionized_energy_array_d.get_access<access::mode::read>(cgh); auto index_grid = index_grid_d.get_access<access::mode::read>(cgh); //////////////////////////////////////////////////////////////////////////////// // XS Lookup Simulation Loop //////////////////////////////////////////////////////////////////////////////// cgh.parallel_for<kernel>(range<1>(in.lookups), [=](id<1> idx) { // get the index to operate on, first dimemsion size_t i = idx[0]; // Set the initial seed value uint64_t seed = STARTING_SEED; // Forward seed to lookup index (we need 2 samples per lookup) seed = fast_forward_LCG(seed, 2*i); // Randomly pick an energy and material for the particle double p_energy = LCG_random_double(&seed); int mat = pick_mat(&seed); // debugging //printf("E = %lf mat = %d\n", p_energy, mat); double macro_xs_vector[5] = {0}; // Perform macroscopic Cross Section Lookup calculate_macro_xs( p_energy, // Sampled neutron energy (in lethargy) mat, // Sampled material type index neutron is in in.n_isotopes, // Total number of isotopes in simulation in.n_gridpoints, // Number of gridpoints per isotope in simulation num_nucs, // 1-D array with number of nuclides per material concs, // Flattened 2-D array with concentration of each nuclide in each material unionized_energy_array, // 1-D Unionized energy array index_grid, // Flattened 2-D grid holding indices into nuclide grid for each unionized energy level nuclide_grid, // Flattened 2-D grid holding energy levels and XS_data for all nuclides in simulation mats, // Flattened 2-D array with nuclide indices defining composition of each type of material macro_xs_vector, // 1-D array with result of the macroscopic cross section (5 different reaction channels) in.grid_type, // Lookup type (nuclide, hash, or unionized) in.hash_bins, // Number of hash bins used (if using hash lookup type) SD.max_num_nucs // Maximum number of nuclides present in any material ); // For verification, and to prevent the compiler from optimizing // all work out, we interrogate the returned macro_xs_vector array // to find its maximum value index, then increment the verification // value by that index. In this implementation, we store to a global // array that will get tranferred back and reduced on the host. double max = -1.0; int max_idx = 0; for(int j = 0; j < 5; j++ ) { if( macro_xs_vector[j] > max ) { max = macro_xs_vector[j]; max_idx = j; } } verification[i] = max_idx+1; }); }); stop = get_time(); if(mype==0) printf("Kernel initialization, compilation, and launch took %.2lf seconds.\n", stop-start); if(mype==0) printf("Beginning event based simulation...\n"); } // Host reduces the verification array unsigned long long verification_scalar = 0; for( int i = 0; i < in.lookups; i++ ) verification_scalar += verification_host[i]; return verification_scalar; } // binary search for energy on unionized energy grid // returns lower index template <class T> long grid_search( long n, double quarry, T A) { long lowerLimit = 0; long upperLimit = n-1; long examinationPoint; long length = upperLimit - lowerLimit; while( length > 1 ) { examinationPoint = lowerLimit + ( length / 2 ); if( A[examinationPoint] > quarry ) upperLimit = examinationPoint; else lowerLimit = examinationPoint; length = upperLimit - lowerLimit; } return lowerLimit; } // Calculates the microscopic cross section for a given nuclide & energy template <class Double_Type, class Int_Type, class NGP_Type> void calculate_micro_xs( double p_energy, int nuc, long n_isotopes, long n_gridpoints, Double_Type egrid, Int_Type index_data, NGP_Type nuclide_grids, long idx, double * xs_vector, int grid_type, int hash_bins ){ // Variables double f; NuclideGridPoint low, high; long low_idx, high_idx; // If using only the nuclide grid, we must perform a binary search // to find the energy location in this particular nuclide's grid. if( grid_type == NUCLIDE ) { // Perform binary search on the Nuclide Grid to find the index long offset = nuc * n_gridpoints; idx = grid_search_nuclide( n_gridpoints, p_energy, nuclide_grids, offset, offset + n_gridpoints-1); // pull ptr from nuclide grid and check to ensure that // we're not reading off the end of the nuclide's grid if( idx == n_gridpoints - 1 ) low_idx = idx - 1; else low_idx = idx; } else if( grid_type == UNIONIZED) // Unionized Energy Grid - we already know the index, no binary search needed. { // pull ptr from energy grid and check to ensure that // we're not reading off the end of the nuclide's grid if( index_data[idx * n_isotopes + nuc] == n_gridpoints - 1 ) low_idx = nuc*n_gridpoints + index_data[idx * n_isotopes + nuc] - 1; else { low_idx = nuc*n_gridpoints + index_data[idx * n_isotopes + nuc]; } } else // Hash grid { // load lower bounding index int u_low = index_data[idx * n_isotopes + nuc]; // Determine higher bounding index int u_high; if( idx == hash_bins - 1 ) u_high = n_gridpoints - 1; else u_high = index_data[(idx+1)*n_isotopes + nuc] + 1; // Check edge cases to make sure energy is actually between these // Then, if things look good, search for gridpoint in the nuclide grid // within the lower and higher limits we've calculated. double e_low = nuclide_grids[nuc*n_gridpoints + u_low].energy; double e_high = nuclide_grids[nuc*n_gridpoints + u_high].energy; long lower; if( p_energy <= e_low ) lower = nuc*n_gridpoints; else if( p_energy >= e_high ) lower = nuc*n_gridpoints + n_gridpoints - 1; else { long offset = nuc*n_gridpoints; lower = grid_search_nuclide( n_gridpoints, p_energy, nuclide_grids, offset+u_low, offset+u_high); } if( (lower % n_gridpoints) == n_gridpoints - 1 ) low_idx = lower - 1; else low_idx = lower; } high_idx = low_idx + 1; low = nuclide_grids[low_idx]; high = nuclide_grids[high_idx]; // calculate the re-useable interpolation factor f = (high.energy - p_energy) / (high.energy - low.energy); // Total XS xs_vector[0] = high.total_xs - f * (high.total_xs - low.total_xs); // Elastic XS xs_vector[1] = high.elastic_xs - f * (high.elastic_xs - low.elastic_xs); // Absorbtion XS xs_vector[2] = high.absorbtion_xs - f * (high.absorbtion_xs - low.absorbtion_xs); // Fission XS xs_vector[3] = high.fission_xs - f * (high.fission_xs - low.fission_xs); // Nu Fission XS xs_vector[4] = high.nu_fission_xs - f * (high.nu_fission_xs - low.nu_fission_xs); } // Calculates macroscopic cross section based on a given material & energy template <class Double_Type, class Int_Type, class NGP_Type, class E_GRID_TYPE, class INDEX_TYPE> void calculate_macro_xs( double p_energy, int mat, long n_isotopes, long n_gridpoints, Int_Type num_nucs, Double_Type concs, E_GRID_TYPE egrid, INDEX_TYPE index_data, NGP_Type nuclide_grids, Int_Type mats, double * macro_xs_vector, int grid_type, int hash_bins, int max_num_nucs ){ int p_nuc; // the nuclide we are looking up long idx = -1; double conc; // the concentration of the nuclide in the material // cleans out macro_xs_vector for( int k = 0; k < 5; k++ ) macro_xs_vector[k] = 0; // If we are using the unionized energy grid (UEG), we only // need to perform 1 binary search per macroscopic lookup. // If we are using the nuclide grid search, it will have to be // done inside of the "calculate_micro_xs" function for each different // nuclide in the material. if( grid_type == UNIONIZED ) idx = grid_search( n_isotopes * n_gridpoints, p_energy, egrid); else if( grid_type == HASH ) { double du = 1.0 / hash_bins; idx = p_energy / du; } // Once we find the pointer array on the UEG, we can pull the data // from the respective nuclide grids, as well as the nuclide // concentration data for the material // Each nuclide from the material needs to have its micro-XS array // looked up & interpolatied (via calculate_micro_xs). Then, the // micro XS is multiplied by the concentration of that nuclide // in the material, and added to the total macro XS array. // (Independent -- though if parallelizing, must use atomic operations // or otherwise control access to the xs_vector and macro_xs_vector to // avoid simulataneous writing to the same data structure) for( int j = 0; j < num_nucs[mat]; j++ ) { double xs_vector[5]; p_nuc = mats[mat*max_num_nucs + j]; conc = concs[mat*max_num_nucs + j]; calculate_micro_xs( p_energy, p_nuc, n_isotopes, n_gridpoints, egrid, index_data, nuclide_grids, idx, xs_vector, grid_type, hash_bins ); for( int k = 0; k < 5; k++ ) macro_xs_vector[k] += xs_vector[k] * conc; } } // picks a material based on a probabilistic distribution int pick_mat( unsigned long * seed ) { // I have a nice spreadsheet supporting these numbers. They are // the fractions (by volume) of material in the core. Not a // *perfect* approximation of where XS lookups are going to occur, // but this will do a good job of biasing the system nonetheless. // Also could be argued that doing fractions by weight would be // a better approximation, but volume does a good enough job for now. double dist[12]; dist[0] = 0.140; // fuel dist[1] = 0.052; // cladding dist[2] = 0.275; // cold, borated water dist[3] = 0.134; // hot, borated water dist[4] = 0.154; // RPV dist[5] = 0.064; // Lower, radial reflector dist[6] = 0.066; // Upper reflector / top plate dist[7] = 0.055; // bottom plate dist[8] = 0.008; // bottom nozzle dist[9] = 0.015; // top nozzle dist[10] = 0.025; // top of fuel assemblies dist[11] = 0.013; // bottom of fuel assemblies double roll = LCG_random_double(seed); // makes a pick based on the distro for( int i = 0; i < 12; i++ ) { double running = 0; for( int j = i; j > 0; j-- ) running += dist[j]; if( roll < running ) return i; } return 0; } double LCG_random_double(uint64_t * seed) { // LCG parameters const uint64_t m = 9223372036854775808ULL; // 2^63 const uint64_t a = 2806196910506780709ULL; const uint64_t c = 1ULL; *seed = (a * (*seed) + c) % m; return (double) (*seed) / (double) m; } uint64_t fast_forward_LCG(uint64_t seed, uint64_t n) { // LCG parameters const uint64_t m = 9223372036854775808ULL; // 2^63 uint64_t a = 2806196910506780709ULL; uint64_t c = 1ULL; n = n % m; uint64_t a_new = 1; uint64_t c_new = 0; while(n > 0) { if(n & 1) { a_new *= a; c_new = c_new * a + c; } c *= (a + 1); a *= a; n >>= 1; } return (a_new * seed + c_new) % m; }
38.09447
141
0.642654
[ "object" ]
4d7ae5852206bb1730fbf6dde0ea426ea44b8269
8,161
cpp
C++
lib/har/src/world/world.cpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
2
2020-09-11T18:11:10.000Z
2020-10-20T17:25:38.000Z
lib/har/src/world/world.cpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
null
null
null
lib/har/src/world/world.cpp
Ocead/HAR
341738dd6d513573635f4d6c51b9c7bd8abfcc2b
[ "BSD-2-Clause" ]
null
null
null
// // Created by Johannes on 26.05.2020. // #include <iomanip> #include "world/world.hpp" using namespace har; world::world() : _model({ MODEL_GRID, dcoords_t() }, part::invalid()), _bank({ BANK_GRID, dcoords_t() }, part::invalid()), _cargo() { } world::world(const dcoords_t & model_size, const part & model_blank, const dcoords_t & bank_size, const part & bank_blank) : _model({ MODEL_GRID, model_size }, model_blank), _bank({ BANK_GRID, bank_size }, bank_blank), _cargo() { } world::world(dcoords_t && model_size, const part & model_blank, dcoords_t && bank_size, const part & bank_blank) : _model({ MODEL_GRID, model_size }, model_blank), _bank({ BANK_GRID, bank_size }, bank_blank), _cargo() { } world::world(const world & ref) : _model({ ref._model.cat(), ref._model.dim() }, part::invalid()), _bank({ ref._bank.cat(), ref._bank.dim() }, part::invalid()), _cargo() { for (uint_t i = 0; i < 2; ++i) { auto & grid = (i == 0) ? _model : _bank; for (auto &[pos, oclb] : ref._model) { auto & clb = grid.at(pos); clb = static_cast<const cell_base &>(oclb); for (auto &[use, to] : oclb.connected()) { clb.add_connection(use, at(to.get().position())); } } } } world::world(world && fref) noexcept: _model(std::move(fref._model)), _bank(std::move(fref._bank)), _cargo(std::move(fref._cargo)) { } grid & world::get_model() { return _model; } const grid & world::get_model() const { return _model; } grid & world::get_bank() { return _bank; } const grid & world::get_bank() const { return _bank; } decltype(world::_cargo) & world::cargo() { return _cargo; } const decltype(world::_cargo) & world::cargo() const { return _cargo; } grid_cell_base & world::at(const gcoords_t & pos) { switch (pos.cat) { case MODEL_GRID: { return _model.at(pos.pos); } case BANK_GRID: { return _bank.at(pos.pos); } case INVALID_GRID: default: { return grid_cell_base::invalid(); } } } cargo_cell_base & world::at(cargo_h num) { return _cargo.at(num); } cell_base & world::at(const cell_h & hnd) { switch (cell_cat(hnd.index())) { case cell_cat::INVALID_CELL: { return cell_base::invalid(); } case cell_cat::GRID_CELL: { return at(std::get<uint_t(cell_cat::GRID_CELL)>(hnd)); } case cell_cat::CARGO_CELL: { return at(std::get<uint_t(cell_cat::CARGO_CELL)>(hnd)); } default: { return cell_base::invalid(); } } } void world::resize(grid_t grid, const part & pt, const dcoords_t & to) { switch (grid) { case MODEL_GRID: _model.resize_to(pt, to); return; case BANK_GRID: _bank.resize_to(pt, to); return; case INVALID_GRID: return; } } void world::resize(grid_t grid, const part & pt, dcoords_t && to) { switch (grid) { case MODEL_GRID: _model.resize_to(pt, to); return; case BANK_GRID: _bank.resize_to(pt, to); return; case INVALID_GRID: return; } } void world::minimize(grid_t grid) { if (grid != grid_t::INVALID_GRID) { ((grid == grid_t::MODEL_GRID) ? _model : _bank).minimize(); } } void world::purge_part(const part & pt, const part & with) { _model.purge_part(pt, with); _bank.purge_part(pt, with); for (auto & c : _cargo) { if (c.second.logic().id() == pt.id()) { c.second.set_type(with); } } } world & world::operator=(const world & ref) { if (this != &ref) { this->~world(); new(this) world(ref); } return *this; } world & world::operator=(world && fref) noexcept = default; world::~world() = default; ostream & har::operator<<(ostream & os, const world & world) { os << text('\n'); os << string_t(text("model\n")) + text("name ") << std::quoted(world._model.title()) << text("\n") << text("size ") << world._model.dim() << text("\n"); os << string_t(text("bank\n")) + text("name ") << std::quoted(world._bank.title()) << text("\n") << text("size ") << world._bank.dim() << text("\n"); for (auto & c : world._model) { if (!(c.second.logic().traits() & traits::EMPTY_PART)) { os << '\n' << c.second; } } for (auto & c : world._bank) { if (!(c.second.logic().traits() & traits::EMPTY_PART)) { os << '\n' << c.second; } } for (auto & c : world._cargo) { os << '\n' << c.second; } return os; } std::tuple<istream &, const std::map<part_h, part> &> har::operator>>(std::tuple<istream &, const std::map<part_h, part> &> is_inv, std::tuple<world &, bool_t &> world_ok) { string_t line; auto &[is, inv] = is_inv; auto &[world, ok] = world_ok; std::queue<unresolved_connection> conns; bool_t done = false; std::getline(is, line, text('\n')); remove_r(line); if (line.substr(0, 5) == text("model")) { std::getline(is, line, text(' ')); remove_r(line); if (line.substr(0, 4) == text("name")) { is >> std::quoted(world._model.title()); } else { ok = false; return is_inv; } std::getline(is >> std::ws, line, text('\n')); remove_r(line); if (line.substr(0, 5) == text("size ")) { stringstream ss{ line.substr(5) }; dcoords_t dim; ss >> dim; world._model.resize_to(inv.at(PART[0]), dim); } else { ok = false; return is_inv; } } else { ok = false; return is_inv; } std::getline(is, line, text('\n')); remove_r(line); if (line.substr(0, 4) == text("bank")) { std::getline(is, line, text(' ')); remove_r(line); if (line.substr(0, 4) == text("name")) { is >> std::quoted(world._bank.title()); } else { ok = false; return is_inv; } std::getline(is >> std::ws, line, text('\n')); remove_r(line); if (line.substr(0, 5) == text("size ")) { stringstream ss{ line.substr(5) }; dcoords_t dim; ss >> dim; world._bank.resize_to(inv.at(PART[0]), dim); } else { ok = false; return is_inv; } } else { ok = false; return is_inv; } std::getline(is, line, text('\n')); remove_r(line); while (!is.eof() && !done) { char c = is.peek(); switch (c) { case 'c': { cargo_cell_base cclb{ CARGO[0], part::invalid() }; is_inv >> cclb; cclb.transit(); world.cargo().try_emplace(cclb.id(), std::forward<cargo_cell_base>(cclb)); break; } case 'g': { grid_cell_base gclb{ part::invalid() }; is_inv >> std::tie(gclb, conns); gclb.transit(); while (!conns.empty()) { unresolved_connection uconn = conns.front(); uconn.base.get().add_connection(uconn.use, world.at(uconn.pos)); conns.pop(); } world.at(gclb.position()).adopt(std::move(gclb)); break; } default: { done = true; break; } } } return is_inv; }
28.635088
119
0.483152
[ "model" ]
4d7ae858f91f62b7c2bb8292976402d8f15572a8
4,324
cpp
C++
Session_11/FFT_00_visualize/src/ofApp.cpp
bakercp/ExperimentalMedia2015
bb596b20ebd7ffd5d85e4987e0d2d3e8f3e57e24
[ "MIT" ]
3
2015-09-01T23:34:44.000Z
2015-09-18T04:25:18.000Z
Session_11/FFT_00_visualize/src/ofApp.cpp
bakercp/ExperimentalMedia2015
bb596b20ebd7ffd5d85e4987e0d2d3e8f3e57e24
[ "MIT" ]
null
null
null
Session_11/FFT_00_visualize/src/ofApp.cpp
bakercp/ExperimentalMedia2015
bb596b20ebd7ffd5d85e4987e0d2d3e8f3e57e24
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ windowWidth = ofGetWidth(); binSize = 512; //512 divisions form 0 - sampling rate (44100) // to get the freq of the bin -> (samplingrate/binSize) * index of the bin //this also means our frequency resolution is samplingrate/binSize. //setup the fft using 512 bins fft.setup(binSize); polys.resize(binSize/2 + 1); //although we are using 512 bins, only the first half of the bins are going to be meaningful to us here. //the reasons are bit technical (but have to do with the Nyquist frequency). // think of the second half of our fft as the dark mirror image of out first half, as 'bizzaro world' fft. //in any case, the second half of out fft is thrown out (bins 257- 512) //& the results or our fft will only deal with the first half (bins 0-256, 257 values). fftMagnitudeScale = 256; } //-------------------------------------------------------------- void ofApp::update(){ fft.update(); fftBufferV = fft.getBins(); // plot the results of our fft. by calling .getBins() returns an array of the magnitudes of each bin. // so, the first value in fft.getBins() is the magnitude of the first bin // every value will be float betwwen 0 - 1. // what we usually want to do is put the reults of .getBins() into a std::vector int n = MIN(1024, fftBufferV.size()); for(std::size_t i = 0; i < n; i++) { //iterate through our fftBuffer float phase =0.0; //I'm going to use a sine wave to create verticies for out polylines float phaseAddr; polys[i].clear(); //clear all the polylines verticies for(std::size_t j = 0; j < windowWidth; j++) { //time to create the verticies. we will add a vertex from 0-windowWidth and set our x-value phaseAddr = (TWO_PI * (44100/binSize) * i)/(float)44100; //we need to get the freq that the bin corresponds to //to get the freq of the bin -> samplingrate/binsize * nbin // 44100/512 * i polys[i].addVertex(j, sin(phase) * (fftBufferV[i] * fftMagnitudeScale)); // here is where we stuff out polyline array // We will make a ploy line for each bin, that will hold the points // of sine wave that is the frequency of that bin. // the large we draw the sine wave (its y-value) will be determined // by the bins magnitude // sice the magnitude will be between 0-1, we scale it (here by 256) phase += phaseAddr; } //find the loudest frequency //cycle though all the bins and figure out which one has the highest magnitude, store that index int binTest =fftBufferV[i]; int highBin = 0; if (binTest > highBin) { highBin = binTest; loudestBin = i; } //this will actuallt find only the loudest bin closest to bin 0. } loudest = (44100/binSize) * loudestBin; //what the frequency of the loudest bin. } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofPushMatrix(); ofTranslate(0,ofGetHeight()/2); for (std::size_t i = 0; i < polys.size(); i++) { //iterate through our polyline array and draw it to the screen if( i == loudestBin) { //i want to draw that loudest bin blue ofSetColor(50, 100, 255, 200); polys[i].draw(); } else if ( i >= 1 ){ //i want to draw other polylines as purple ofSetColor(255, 100, 255, 100); polys[i].draw(); } else { //the only thing that is left is the polyline for bin 0, which is for frequency 0, which will most likely just remain at 0 magnitude //so it will be a straight line... forever. a nice grid line ofSetColor(255, 255, 255, 200); polys[i].draw(); } } ofPopMatrix(); //Still, there are going to be 256 polylines drawn on top of eachother, so its going to look like a beautiful mess. //try changing the binSize variable to see what happens //use a power of two though!! ie 128, 256, 512, 1024 //print that loudest frequency ofSetColor(255); std::string loudStr = "my Fantastic Frequency= ~" + ofToString(loudest); ofDrawBitmapString(loudStr, 200, 700); } void ofApp::keyPressed(int key){ }
38.265487
141
0.61679
[ "vector" ]
4d8008eaf1ff3580527f0f478ae86be147a760b1
9,226
cpp
C++
Examples/exOperations/exOperationApp.cpp
breseight/MAF2
77b517b5450cc7fe82cb99c5bb23db89980e30e8
[ "Apache-2.0" ]
null
null
null
Examples/exOperations/exOperationApp.cpp
breseight/MAF2
77b517b5450cc7fe82cb99c5bb23db89980e30e8
[ "Apache-2.0" ]
null
null
null
Examples/exOperations/exOperationApp.cpp
breseight/MAF2
77b517b5450cc7fe82cb99c5bb23db89980e30e8
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Program: MAF2 Module: exOperationApp Authors: Paolo Quadrani Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "exOperationApp.h" #include "mafDecl.h" #include "mafVMEFactory.h" #include "mafPics.h" #include "mafGUIMDIFrame.h" #include "mafNodeGeneric.h" #include "mafNodeRoot.h" #include "mafVMERoot.h" #include "mafVMESurface.h" #include "mafPipeFactoryVME.h" #include "mafInteractionFactory.h" #include "mafOp2DMeasure.h" #include "mafOpAddLandmark.h" #include "mafOpClipSurface.h" #include "mafOpCreateGroup.h" #include "mafOpCreateMeter.h" #include "mafOpCreateProber.h" #include "mafOpCreateRefSys.h" #include "mafOpCreateSlicer.h" #include "mafOpCreateVolume.h" #include "mafOpCrop.h" #include "mafOpEditMetadata.h" #include "mafOpExplodeCollapse.h" #include "mafOpExtractIsosurface.h" #include "mafOpFilterSurface.h" #include "mafOpFilterVolume.h" #include "mafOpImporterImage.h" #include "mafOpMAFTransform.h" #include "mafOpExporterMSF.h" #include "mafOpImporterMSF.h" #include "mafOpImporterMSF1x.h" #include "mafOpImporterRAWVolume.h" #include "mafOpReparentTo.h" #include "mafOpExporterSTL.h" #include "mafOpImporterSTL.h" #include "mafOpVolumeResample.h" #include "mafOpImporterVRML.h" #include "mafOpExporterVTK.h" #include "mafOpImporterVTK.h" #include "mafOpValidateTree.h" #include "mafOpRemoveCells.h" #include "mafOpEditNormals.h" #include "mafOpVOIDensityEditor.h" #include "mafOpExporterRaw.h" #include "mafOpBooleanSurface.h" #ifdef MAF_USE_ITK #include "mafOpImporterASCII.h" #endif #include "mafViewVTK.h" #include "mafViewCompound.h" #include "mafOpCreateSurfaceParametric.h" //#include "mafUser.h" //#include "mafCrypt.h" //#include "mmoSRBUpload.h" //#include "mafViewPlot.h" //-------------------------------------------------------------------------------- // Create the Application //-------------------------------------------------------------------------------- IMPLEMENT_APP(exOperationApp) //-------------------------------------------------------------------------------- bool exOperationApp::OnInit() //-------------------------------------------------------------------------------- { mafPictureFactory::GetPictureFactory()->Initialize(); #include "Examples/exOperations/MAFIcons/FRAME_ICON16x16.xpm" mafADDPIC(FRAME_ICON16x16); #include "Examples/exOperations/MAFIcons/FRAME_ICON32x32.xpm" mafADDPIC(FRAME_ICON32x32); #include "Examples/exOperations/MAFIcons/MDICHILD_ICON.xpm" mafADDPIC(MDICHILD_ICON); int result = mafVMEFactory::Initialize(); assert(result==MAF_OK); // Initialize and Fill of PipeFactory -- could be a SideEffect of the node plug result = mafPipeFactoryVME::Initialize(); assert(result==MAF_OK); result = mafInteractionFactory::Initialize(); assert(result==MAF_OK); m_Logic = new mafLogicWithManagers(); m_Logic->GetTopWin()->SetTitle("Operations example"); //m_Logic->PlugTimebar(false); //m_Logic->PlugMenu(false); //m_Logic->PlugToolbar(false); //m_Logic->PlugLogbar(false); //m_Logic->PlugSidebar(true, mafSideBar::SINGLE_NOTEBOOK); //m_Logic->PlugOpManager(false); //m_Logic->PlugViewManager(false); //m_Logic->PlugVMEManager(false); // the VmeManager at the moment cause 4 leaks of 200+32+24+56 bytes //SIL. 20-4-2005: m_Logic->Configure(); SetTopWindow(mafGetFrame()); //------------------------------------------------------------ // Importer Menu': //------------------------------------------------------------ m_Logic->Plug(new mafOpImporterImage("Images")); m_Logic->Plug(new mafOpImporterRAWVolume("RAW Volume")); m_Logic->Plug(new mafOpImporterSTL("STL")); m_Logic->Plug(new mafOpImporterVRML("VRML")); m_Logic->Plug(new mafOpImporterVTK("VTK")); m_Logic->Plug(new mafOpImporterMSF("MSF")); m_Logic->Plug(new mafOpImporterMSF1x("MSF 1.x")); #ifdef MAF_USE_ITK m_Logic->Plug(new mafOpImporterASCII("ASCII")); #endif //------------------------------------------------------------ //------------------------------------------------------------ // Exporter Menu': //------------------------------------------------------------ m_Logic->Plug(new mafOpExporterMSF("MSF")); m_Logic->Plug(new mafOpExporterSTL("STL")); m_Logic->Plug(new mafOpExporterVTK("VTK")); m_Logic->Plug(new mafOpExporterRAW("RAW")); //------------------------------------------------------------ //------------------------------------------------------------ // Operation Menu': //------------------------------------------------------------ //m_Logic->Plug(new mmoSRBUpload()); m_Logic->Plug(new mafOpValidateTree()); m_Logic->Plug(new mafOpRemoveCells()); m_Logic->Plug(new mafOpEditNormals()); m_Logic->Plug(new mafOp2DMeasure("2D Measure")); m_Logic->Plug(new mafOpAddLandmark("Add Landmark")); m_Logic->Plug(new mafOpClipSurface("Clip Surface")); m_Logic->Plug(new mafOpBooleanSurface("BooleanSurface")); m_Logic->Plug(new mafOpCreateSurfaceParametric("Surface Parametric"),"Create"); m_Logic->Plug(new mafOpCreateGroup("Group"),"Create"); m_Logic->Plug(new mafOpCreateMeter("Meter"),"Create"); m_Logic->Plug(new mafOpCreateRefSys("RefSys"),"Create"); m_Logic->Plug(new mafOpCreateProber("Prober"),"Create"); m_Logic->Plug(new mafOpCreateSlicer("Slicer"),"Create"); m_Logic->Plug(new mafOpCreateVolume("Constant Volume"),"Create"); m_Logic->Plug(new mafOpEditMetadata("Metadata Editor")); m_Logic->Plug(new mafOpExplodeCollapse("Explode/Collapse cloud")); m_Logic->Plug(new mafOpExtractIsosurface("Extract Isosurface")); m_Logic->Plug(new mafOpFilterSurface("Surface"),"Filter"); m_Logic->Plug(new mafOpFilterVolume("Volume"),"Filter/Volume"); m_Logic->Plug(new mafOpVOIDensityEditor(), "Filter"); m_Logic->Plug(new mafOpMAFTransform("Transform \tCtrl+T")); m_Logic->Plug(new mafOpReparentTo("Reparent to... \tCtrl+R")); m_Logic->Plug(new mafOpVolumeResample("Resample Volume")); m_Logic->Plug(new mafOpCrop("Crop Volume")); //------------------------------------------------------------ //------------------------------------------------------------ // View Menu': //------------------------------------------------------------ m_Logic->Plug(new mafViewVTK("VTK view")); m_Logic->Plug(new mafViewVTK("VTK stereo view",CAMERA_PERSPECTIVE,true,false,1)); mafViewVTK *v = new mafViewVTK("Slice view", CAMERA_CT); v->PlugVisualPipe("mafVMEVolumeGray", "mafPipeVolumeSlice",MUTEX); m_Logic->Plug(v); mafViewVTK *rxv = new mafViewVTK("RX view", CAMERA_RX_FRONT); rxv->PlugVisualPipe("mafVMEVolumeGray", "mafPipeVolumeProjected",MUTEX); m_Logic->Plug(rxv); mafViewVTK *viso = new mafViewVTK("Isosurface view"); viso->PlugVisualPipe("mafVMEVolumeGray", "mafPipeIsosurface",MUTEX); m_Logic->Plug(viso); mafViewVTK *visoGPU = new mafViewVTK("Isosurface View (GPU)"); visoGPU->PlugVisualPipe("mafVMEVolumeGray", "mafPipeIsosurfaceGPU",MUTEX); m_Logic->Plug(visoGPU); //m_Logic->Plug(new mafViewPlot("Plot view")); mafViewCompound *vc = new mafViewCompound("view compound",3); mafViewVTK *v2 = new mafViewVTK("Slice view", CAMERA_CT); v2->PlugVisualPipe("mafVMEVolumeGray", "mafPipeVolumeSlice", MUTEX); vc->PlugChildView(v2); m_Logic->Plug(vc); //------------------------------------------------------------ //wxHandleFatalExceptions(); //m_Logic->ShowSplashScreen(); m_Logic->Show(); mafString app_stamp; app_stamp = "OPEN_ALL_DATA"; m_Logic->SetApplicationStamp(app_stamp); //mafUser *user = m_Logic->GetUser(); //user->ShowLoginDialog(); m_Logic->Init(argc,argv); // calls FileNew - which create the root return TRUE; } //-------------------------------------------------------------------------------- int exOperationApp::OnExit() //-------------------------------------------------------------------------------- { cppDEL(m_Logic); return 0; } //-------------------------------------------------------------------------------- void exOperationApp::OnFatalException() //-------------------------------------------------------------------------------- { m_Logic->HandleException(); }
38.441667
125
0.586928
[ "transform" ]
4d87030c48dcc7483da4b753873c31ee55c39d93
11,887
cc
C++
performance/src/android/http_metric.cc
oliwilkinsonio/firebase-cpp-sdk
1a2790030e92f77ad2aaa87000a1222d12dcabfc
[ "Apache-2.0" ]
193
2019-03-18T16:30:43.000Z
2022-03-30T17:39:32.000Z
performance/src/android/http_metric.cc
oliwilkinsonio/firebase-cpp-sdk
1a2790030e92f77ad2aaa87000a1222d12dcabfc
[ "Apache-2.0" ]
647
2019-03-18T20:50:41.000Z
2022-03-31T18:32:33.000Z
performance/src/android/http_metric.cc
oliwilkinsonio/firebase-cpp-sdk
1a2790030e92f77ad2aaa87000a1222d12dcabfc
[ "Apache-2.0" ]
86
2019-04-21T09:40:38.000Z
2022-03-26T20:48:37.000Z
// Copyright 2021 Google LLC #import "performance/src/include/firebase/performance/http_metric.h" #include <jni.h> #include <string> #include "app/src/assert.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/log.h" #include "app/src/util_android.h" #include "performance/src/android/performance_android_internal.h" #include "performance/src/include/firebase/performance.h" #include "performance/src/performance_common.h" namespace firebase { namespace performance { namespace internal { // The order in the array has to be exactly the same as the order in which // they're declared in http_metric.h. static const char* kHttpMethodToString[] = {"GET", "PUT", "POST", "DELETE", "HEAD", "PATCH", "OPTIONS", "TRACE", "CONNECT"}; // Maps the firebase::performance::HttpMethod enum to its string counterpart. const char* GetFIRHttpMethodString(HttpMethod method) { FIREBASE_ASSERT(method >= 0 && method < FIREBASE_ARRAYSIZE(kHttpMethodToString)); return kHttpMethodToString[method]; } // The Internal implementation of HttpMetric as recommended by the pImpl design // pattern. This class is thread safe as long as we can assume that raw ponter // access is atomic on any of the platforms this will be used on. class HttpMetricInternal { public: explicit HttpMetricInternal() {} ~HttpMetricInternal() { if (active_http_metric_) { if (stop_on_destroy_) { StopHttpMetric(); } else { CancelHttpMetric(); } } } // Creates an underlying Java HttpMetric. If a previous one exists, // it is cancelled. void CreateHttpMetric(const char* url, HttpMethod http_method, bool stop_on_destroy) { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); stop_on_destroy_ = stop_on_destroy; if (WarnIf(url == nullptr, "URL cannot be nullptr. Unable to create HttpMetric.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); if (active_http_metric_ != nullptr) { CancelHttpMetric(); } jstring url_jstring = url ? env->NewStringUTF(url) : nullptr; jstring http_method_jstring = env->NewStringUTF(GetFIRHttpMethodString(http_method)); jobject local_active_http_metric = env->CallObjectMethod( GetFirebasePerformanceClassInstance(), performance_jni::GetMethodId(performance_jni::kNewHttpMetric), url_jstring, http_method_jstring); util::CheckAndClearJniExceptions(env); active_http_metric_ = env->NewGlobalRef(local_active_http_metric); env->DeleteLocalRef(local_active_http_metric); if (url_jstring) env->DeleteLocalRef(url_jstring); env->DeleteLocalRef(http_method_jstring); } // Starts an already created Java HttpMetric. void StartCreatedHttpMetric() { JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); if (active_http_metric_) { env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kStartHttpMetric)); util::CheckAndClearJniExceptions(env); } } // Creates and starts an underlying Java HttpMetric. If a previous one // exists, it is cancelled. void CreateAndStartHttpMetric(const char* url, HttpMethod http_method) { CreateHttpMetric(url, http_method, true); StartCreatedHttpMetric(); } // Gets whether the underlying HttpMetric associated with this object is // created. bool IsHttpMetricCreated() { return active_http_metric_ != nullptr; } // Cancels the http metric, and makes sure it isn't logged to the backend. void CancelHttpMetric() { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIfNotCreated("Cannot cancel HttpMetric.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); env->DeleteGlobalRef(active_http_metric_); active_http_metric_ = nullptr; } // Stops the network trace if it hasn't already been stopped, and logs it to // the backend. void StopHttpMetric() { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIfNotCreated("Cannot stop HttpMetric.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kStopHttpMetric)); util::CheckAndClearJniExceptions(env); env->DeleteGlobalRef(active_http_metric_); active_http_metric_ = nullptr; } // Creates a custom attribute for the given network trace with the // given name and value. void SetAttribute(const char* attribute_name, const char* attribute_value) { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIf(attribute_name == nullptr, "Cannot set value for null attribute.")) return; if (WarnIfNotCreated("Cannot SetAttribute.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); jstring attribute_name_jstring = env->NewStringUTF(attribute_name); if (attribute_value == nullptr) { env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kRemoveAttribute), attribute_name_jstring); } else { jstring attribute_value_jstring = env->NewStringUTF(attribute_value); env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kSetAttribute), attribute_name_jstring, attribute_value_jstring); env->DeleteLocalRef(attribute_value_jstring); } util::CheckAndClearJniExceptions(env); env->DeleteLocalRef(attribute_name_jstring); } // Gets the value of the custom attribute identified by the given // name or an empty string if it hasn't been set. std::string GetAttribute(const char* attribute_name) const { FIREBASE_ASSERT_RETURN("", IsInitialized()); if (WarnIf(attribute_name == nullptr, "attribute_name cannot be null.")) return ""; if (WarnIfNotCreated("Cannot GetAttribute.")) return ""; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); jstring attribute_name_jstring = attribute_name ? env->NewStringUTF(attribute_name) : nullptr; jobject attribute_value_jstring = env->CallObjectMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kGetAttribute), attribute_name_jstring); util::CheckAndClearJniExceptions(env); env->DeleteLocalRef(attribute_name_jstring); if (attribute_value_jstring == nullptr) { return ""; } else { return util::JniStringToString(env, attribute_value_jstring); } } // Sets the HTTP Response Code (for eg. 404 or 200) of the network // trace. void set_http_response_code(int http_response_code) { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIfNotCreated("Cannot set_http_response_code.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kSetHttpResponseCode), http_response_code); util::CheckAndClearJniExceptions(env); } // Sets the Request Payload size in bytes for the network trace. void set_request_payload_size(int64_t bytes) { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIfNotCreated("Cannot set_request_payload_size.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kSetRequestPayloadSize), bytes); util::CheckAndClearJniExceptions(env); } // Sets the Response Content Type of the network trace. void set_response_content_type(const char* content_type) { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIf(content_type == nullptr, "Cannot set null ResponseContentType.")) return; if (WarnIfNotCreated("Cannot set_response_content_type.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); jstring content_type_jstring = env->NewStringUTF(content_type); env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kSetResponseContentType), content_type_jstring); util::CheckAndClearJniExceptions(env); env->DeleteLocalRef(content_type_jstring); } // Sets the Response Payload Size in bytes for the network trace. void set_response_payload_size(int64_t bytes) { FIREBASE_ASSERT_RETURN_VOID(IsInitialized()); if (WarnIfNotCreated("Cannot set_response_payload_size.")) return; JNIEnv* env = GetFirebaseApp()->GetJNIEnv(); env->CallVoidMethod( active_http_metric_, http_metric_jni::GetMethodId(http_metric_jni::kSetResponsePayloadSize), bytes); util::CheckAndClearJniExceptions(env); } private: jobject active_http_metric_ = nullptr; // The unity implementation doesn't stop the underlying Java trace, whereas // the C++ implementation does. This flag is set when a Java trace is created // to track whether it should be stopped before deallocating the object. bool stop_on_destroy_ = false; bool WarnIfNotCreated(const char* warning_message_details) const { if (!active_http_metric_) { LogWarning( "%s HttpMetric is not active. Please create a " "new HttpMetric.", warning_message_details); return true; } return false; } bool WarnIf(bool condition, const char* warning_message) const { if (condition) LogWarning(warning_message); return condition; } }; } // namespace internal HttpMetric::HttpMetric() { FIREBASE_ASSERT(internal::IsInitialized()); internal_ = new internal::HttpMetricInternal(); } HttpMetric::HttpMetric(const char* url, HttpMethod http_method) { FIREBASE_ASSERT(internal::IsInitialized()); internal_ = new internal::HttpMetricInternal(); internal_->CreateAndStartHttpMetric(url, http_method); } HttpMetric::~HttpMetric() { delete internal_; } HttpMetric::HttpMetric(HttpMetric&& other) { internal_ = other.internal_; other.internal_ = nullptr; } HttpMetric& HttpMetric::operator=(HttpMetric&& other) { if (this != &other) { delete internal_; internal_ = other.internal_; other.internal_ = nullptr; } return *this; } bool HttpMetric::is_started() { // In the C++ API we never allow a situation where an underlying HttpMetric // is created, but not started, which is why this check is sufficient. // This isn't used in the Unity implementation. return internal_->IsHttpMetricCreated(); } void HttpMetric::Cancel() { internal_->CancelHttpMetric(); } void HttpMetric::Stop() { internal_->StopHttpMetric(); } void HttpMetric::Start(const char* url, HttpMethod http_method) { internal_->StopHttpMetric(); internal_->CreateAndStartHttpMetric(url, http_method); } void HttpMetric::SetAttribute(const char* attribute_name, const char* attribute_value) { internal_->SetAttribute(attribute_name, attribute_value); } std::string HttpMetric::GetAttribute(const char* attribute_name) const { return internal_->GetAttribute(attribute_name); } void HttpMetric::set_http_response_code(int http_response_code) { internal_->set_http_response_code(http_response_code); } void HttpMetric::set_request_payload_size(int64_t bytes) { internal_->set_request_payload_size(bytes); } void HttpMetric::set_response_content_type(const char* content_type) { internal_->set_response_content_type(content_type); } void HttpMetric::set_response_payload_size(int64_t bytes) { internal_->set_response_payload_size(bytes); } void HttpMetric::Create(const char* url, HttpMethod http_method) { internal_->CreateHttpMetric(url, http_method, false); } void HttpMetric::StartCreatedHttpMetric() { internal_->StartCreatedHttpMetric(); } } // namespace performance } // namespace firebase
33.866097
80
0.719273
[ "object" ]
4d8c8b2789391b50e60b25d5c585b3e593e3e16a
4,112
cpp
C++
src/CostAdaptiveStateManager.cpp
wilseypa/warped
8842cf88b11213b6b69e53de5e969c4e3c2c8bd5
[ "MIT" ]
12
2015-03-13T09:58:25.000Z
2021-09-23T11:48:42.000Z
src/CostAdaptiveStateManager.cpp
wilseypa/warped
8842cf88b11213b6b69e53de5e969c4e3c2c8bd5
[ "MIT" ]
1
2015-12-09T05:21:44.000Z
2015-12-17T19:37:12.000Z
src/CostAdaptiveStateManager.cpp
wilseypa/warped
8842cf88b11213b6b69e53de5e969c4e3c2c8bd5
[ "MIT" ]
null
null
null
#include <ostream> // for operator<<, basic_ostream, etc #include <string> // for char_traits, operator<< #include "CostAdaptiveStateManager.h" #include "DefaultObjectID.h" // for OBJECT_ID #include "ObjectID.h" // for ObjectID #include "SimulationObject.h" // for SimulationObject #include "TimeWarpSimulationManager.h" // for TimeWarpSimulationManager #include "WarpedDebug.h" // for debugout class VTime; // These are the default values. const unsigned int defaultRecalculationPeriod = 100; const unsigned int defaultAdaptionValue = 1; CostAdaptiveStateManager::CostAdaptiveStateManager(TimeWarpSimulationManager* simMgr): AdaptiveStateManagerBase(simMgr) { int numSimObjs = simMgr->getNumberOfSimulationObjects(); eventsBetweenRecalculation.resize(numSimObjs, defaultRecalculationPeriod); forwardExecutionLength.resize(numSimObjs, 0); adaptionValue.resize(numSimObjs, defaultAdaptionValue); oldCostIndex.resize(numSimObjs, 0); filteredCostIndex.resize(numSimObjs, 0); forwardExecutionLength.resize(numSimObjs, 0); } void CostAdaptiveStateManager::setAdaptiveParameters(unsigned int id, long eventsBeforeRecalcuate) { eventsBetweenRecalculation[id] = eventsBeforeRecalcuate; } void CostAdaptiveStateManager::calculatePeriod(SimulationObject* object) { OBJECT_ID* currentObjectID = object->getObjectID(); unsigned int objId = currentObjectID->getSimulationObjectID(); // The current period for this object. int period = objectStatePeriod[objId]; // Calculate the raw current cost function. double stateTime = StateSaveTimeWeighted[objId].getData(); double coastTime = CoastForwardTimeWeighted[objId].getData(); double costIndex = stateTime + coastTime; // To prevent oscillations, calculate the filtered cost index. filteredCostIndex[objId] = 0.4 * filteredCostIndex[objId] + 0.6 * costIndex; // When the cost index is 0, continue to increase the period. Otherwise, // change the value as specified. if (oldCostIndex[objId] > 0) { if (oldCostIndex[objId] > 1.2 * filteredCostIndex[objId]) { period += adaptionValue[objId]; oldCostIndex[objId] = filteredCostIndex[objId]; } else if (oldCostIndex[objId] < 0.8 * filteredCostIndex[objId]) { adaptionValue[objId] = -adaptionValue[objId]; period += adaptionValue[objId]; oldCostIndex[objId] = filteredCostIndex[objId]; } if (coastTime == 0) { adaptionValue[objId] = 1; period++; oldCostIndex[objId] = filteredCostIndex[objId]; } } else { period++; oldCostIndex[objId] = filteredCostIndex[objId]; } // Make sure that the period stays in the range: 0 <= period <= 30. if (period < 0) { period = 0; } else if (period > maxDefaultInterval) { period = maxDefaultInterval; } debug::debugout << object->getName() << " period: " << period << "\n"; // Reset values. forwardExecutionLength[objId] = 1; StateSaveTimeWeighted[objId].reset(); CoastForwardTimeWeighted[objId].reset(); objectStatePeriod[objId] = period; } void CostAdaptiveStateManager::coastForwardTiming(unsigned int id, double coastforwardtime) { CoastForwardTimeWeighted[id].update(coastforwardtime); } double CostAdaptiveStateManager::getCoastForwardTime(unsigned int id) { return (CoastForwardTimeWeighted[id].getData()); } void CostAdaptiveStateManager::saveState(const VTime& currentTime, SimulationObject* object) { ObjectID* currentObjectID = object->getObjectID(); unsigned int simObjectID = currentObjectID->getSimulationObjectID(); // The period is only recalculated after the specified number of events. if (forwardExecutionLength[simObjectID] < eventsBetweenRecalculation[simObjectID]) { forwardExecutionLength[simObjectID]++; } else { calculatePeriod(object); } AdaptiveStateManagerBase::saveState(currentTime, object); }
38.074074
100
0.698444
[ "object" ]
4da9e3467dd9aeee932bb80a70fb46b69834a925
1,474
cpp
C++
Spoj/LongestPathInATree/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
Spoj/LongestPathInATree/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
Spoj/LongestPathInATree/main.cpp
jeevanpuchakay/a2oj
f867e9b2ced6619be3ca6b1a1a1838107322782d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long double ld; typedef long long int ll; vector<vector<ll> > adjlist; ll max(ll x,ll y) {return (x>y)?x:y;} #define min(x,y) (x>y)?y:x #define sfor(a,n,i) for(ll i=a;i<n;i++) #define rfor(n,a,i) for(ll i=n;i>=a;i--) #define mod 1000000007 #define pb push_back #define in insert #define mp make_pair #define inf mod #define bg begin() #define ed end() #define sz size() #define vi vector<ll> #define imap map<ll,ll> #define cmap map<char,ll> #define smap map<string,ll> #define iset set<ll> #define bit(x,i) (x&(1<<i)) vi dis; ll n; ll bfs(ll x){ vi a(n+1,0); queue<ll> q; a[x]=1; dis[x]=0; q.push(x); while(!q.empty()){ ll t=q.front(); q.pop(); for(auto w=adjlist[t].bg;w!=adjlist[t].ed;w++){ if(!a[*w]){ a[*w]=1; q.push(*w); dis[*w]=max(dis[*w],dis[t]+1); } } } return 0; } int main() { ll x,y,ans=0; cin>>n; adjlist=vector<vi>(n+1); sfor(0,n-1,i){ cin>>x>>y; adjlist[x].pb(y); adjlist[y].pb(x); } dis=vi(n+1); bfs(1); x=0; sfor(0,n+1,i) { if(dis[i]>ans) { ans=dis[i]; x=i; } } //dis.clear(); sfor(0,n+1,i) dis[i]=0; ans=0; bfs(x); sfor(0,n+1,i) { if(dis[i]>ans) { ans=dis[i]; x=i; } } cout<<ans<<endl; //zdis.bg; return 0; }
16.75
55
0.485075
[ "vector" ]
4dab2958ae79d0dca4f726d1949f1bb54800ce46
1,975
cpp
C++
Phase 1 Placement Specific/Graph Problems/Planets and Kingdoms.cpp
aashitachouhan/CPP-DSA
582cb72d6d5f2a6208cca7be57d50a2dc76e3e70
[ "Apache-2.0" ]
null
null
null
Phase 1 Placement Specific/Graph Problems/Planets and Kingdoms.cpp
aashitachouhan/CPP-DSA
582cb72d6d5f2a6208cca7be57d50a2dc76e3e70
[ "Apache-2.0" ]
null
null
null
Phase 1 Placement Specific/Graph Problems/Planets and Kingdoms.cpp
aashitachouhan/CPP-DSA
582cb72d6d5f2a6208cca7be57d50a2dc76e3e70
[ "Apache-2.0" ]
null
null
null
/*Problem Statement: A game has n planets, connected by m teleporters. Two planets a and b belong to the same kingdom exactly when there is a route both from a to b and from b to a. Your task is to determine for each planet its kingdom. Constraints 1≤n≤105 1≤m≤2⋅105 1≤a,b≤n Example Input: 5 6 1 2 2 3 3 1 3 4 4 5 5 4 Output: 2 1 1 1 2 2 */ //Code(C++): #include <bits/stdc++.h> using namespace std; #define ll long long #define f(i,a,n) for (int i = a; i < n; i++) #define fr(i,a,n) for (int i = n; i >=a; i--) #define m9 1000000009 #define m7 1000000007 #define vi vector<int> #define setbits(x) __builtin_popcountll(x) #define zerobits(x) __builtin_ctzll(x) #define ff first #define ss second #define pii pair<int, int> #define mii map<int, int> #define mkp make_pair #define pb push_back #define fastio std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL) int n,m; vector<int> ar[200005]; vector<int> tr[200005]; vector<int> Time; vector<int> Scc; vector<int> ans(200001); int vis[200001]; //Kosaraju's algorithm void dfs(int node) { vis[node]=1; for(auto it: ar[node]) { if(vis[it]==0) dfs(it); } Time.pb(node); } void dfs1(int node) { vis[node]=1; for(auto it: tr[node]) { if(vis[it]==0) dfs1(it); } Scc.pb(node); } int main() { cin>>n>>m; int a,b; while(m--) { cin>>a>>b; ar[a].pb(b); tr[b].pb(a); } memset(vis,0,sizeof(vis)); f(i,1,n+1) { if(vis[i]==0) dfs(i); } memset(vis,0,sizeof(vis)); reverse(Time.begin(),Time.end()); int cnt=0; f(i,0,Time.size()) { if(vis[Time[i]]==0) { Scc.clear(); dfs1(Time[i]); cnt++; for(int i=0;i<Scc.size();i++) { ans[Scc[i]]=cnt; //cout<<cnt<<" "; } } } cout<<cnt<<"\n"; for(int i=1;i<n+1;i++) cout<<ans[i]<<" "; return 0; }
17.954545
77
0.551392
[ "vector" ]
4dbc78df570b826e2d82bba5020e8cfe7524af8d
2,314
cpp
C++
raytracer/sphere.cpp
bdolinar/ray_tracer_challenge_cpp
96e746b58ca4a173583ecbccfcde714a22b12935
[ "BSD-2-Clause" ]
null
null
null
raytracer/sphere.cpp
bdolinar/ray_tracer_challenge_cpp
96e746b58ca4a173583ecbccfcde714a22b12935
[ "BSD-2-Clause" ]
null
null
null
raytracer/sphere.cpp
bdolinar/ray_tracer_challenge_cpp
96e746b58ca4a173583ecbccfcde714a22b12935
[ "BSD-2-Clause" ]
null
null
null
#include <memory> #include <raytracer/sphere.h> #include <algorithm> #include <raytracer/intersection.h> //------------------------------------------------------------------------------ std::unique_ptr<Sphere> Sphere::new_ptr() { return std::make_unique<Sphere>(); } //------------------------------------------------------------------------------ Sphere::Sphere() : transform_(Matrix::identity_matrix(4)) { } //------------------------------------------------------------------------------ Matrix Sphere::transform() const { return transform_; } //------------------------------------------------------------------------------ void Sphere::set_transform(const Matrix& a_transform) { transform_ = a_transform; } //------------------------------------------------------------------------------ Material Sphere::material() const { return material_; } //------------------------------------------------------------------------------ void Sphere::set_material(const class Material& a_material) { material_ = a_material; } //------------------------------------------------------------------------------ Intersections Sphere::intersect(const Ray& a_ray) const { // use a ray translated to sphere coordinates to intersect Ray ray_sphere = a_ray.transform(transform().inverse()); std::vector<Intersection> intersections; Tuple sphere_to_ray = ray_sphere.origin() - point(0, 0, 0); double a = dot(ray_sphere.direction(), ray_sphere.direction()); double b = 2 * dot(ray_sphere.direction(), sphere_to_ray); double c = dot(sphere_to_ray, sphere_to_ray) - 1; double discriminant = b * b - 4 * a * c; if (discriminant < 0) return intersections; double t_1 = (-b - sqrt(discriminant)) / (2 * a); double t_2 = (-b + sqrt(discriminant)) / (2 * a); if (t_1 > t_2) std::swap(t_1, t_2); intersections = {{t_1, *this}, {t_2, *this}}; return intersections; } //------------------------------------------------------------------------------ Tuple Sphere::normal_at(Tuple a_world_point) const { Tuple object_point = transform().inverse() * a_world_point; Tuple object_normal = object_point - point(0, 0, 0); Tuple world_normal = transform().inverse().transpose() * object_normal; world_normal.set_w(0); return world_normal.normalize(); }
27.223529
80
0.496543
[ "vector", "transform" ]
4dca1284cf8c355bdc061958b01501b2456524ba
1,105
cxx
C++
src/Ray.cxx
fermi-lat/geometry
71a08bdb0caf952566fed8d8aeb62bd264a4bab7
[ "BSD-3-Clause" ]
null
null
null
src/Ray.cxx
fermi-lat/geometry
71a08bdb0caf952566fed8d8aeb62bd264a4bab7
[ "BSD-3-Clause" ]
null
null
null
src/Ray.cxx
fermi-lat/geometry
71a08bdb0caf952566fed8d8aeb62bd264a4bab7
[ "BSD-3-Clause" ]
null
null
null
// $Id: Ray.cxx,v 1.2 2001/09/21 18:37:19 atwood Exp $ #include "geometry/Ray.h" Ray::Ray( const Point& p, const Vector& d ) : pos( p ), dir(d.unit()) , arclength(0), flag(0) { } Ray::Ray( const Ray& r ) :pos(r.pos),GeomObject(), dir(r.dir), arclength(r.arclength) { // copy constructor } Point Ray::position(double s) const { // return pos + (s * dir); Point p = pos; return p + s*dir; } //should define operators to do this void Ray::printOn( std::ostream& os ) const { // printing function using C++ ostream class os << "Ray: origin = " << pos << ", direction = " << dir << "\n"; } GeomObject& Ray::transform( const CoordTransform & T) { pos.transform(T); dir.transform(T); return *this; } double Ray::distanceOfClosestApproach( const Ray& r ) const { Vector perp = direction(0.).cross(r.direction(0.)); double d = (perp*(r.position(0.)-pos)) / perp.mag(); return d; } Vector Ray::vectorOfClosestApproach( const Ray& r ) const { Vector perp = direction(0.).cross(r.direction(0.)); double d = (perp*(r.position(0.)-pos)) / perp.mag(); return d*perp; }
18.728814
60
0.622624
[ "geometry", "vector", "transform" ]
4dcd4b8141c23f07c1349fd41a25ee3bbf5f5b41
9,889
cpp
C++
VR360VideoIos/src/VR360VideoIosApp.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
[ "Apache-2.0" ]
null
null
null
VR360VideoIos/src/VR360VideoIosApp.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
[ "Apache-2.0" ]
null
null
null
VR360VideoIos/src/VR360VideoIosApp.cpp
eighteight/CinderEigh
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
[ "Apache-2.0" ]
null
null
null
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/qtime/QuickTimeGl.h" #include "cinder/MotionManager.h" #include "cinder/Utilities.h" #include "cinder/Log.h" #include "cinder/Timeline.h" #include "cinder/audio/MonitorNode.h" #include "cinder/audio/Device.h" using namespace ci; using namespace ci::app; using namespace std; static const float kTargetSize = 2.0f; static const float kTargetDistance = 4.0f; static const float kHorizontalSize = kTargetSize * 4.0f; class VR360VideoIosApp : public App { public: void setup ( ) override; void update ( ) override; void draw ( ) override; void resize ( ) override; private: void createGeometry(); void loadGeomSource( const geom::Source &source ); void createShaders(); void nextShape(); void straightenViewAnimated(); void turnViewForCylinderAnimated(); void renderToServerFbo(); CameraPersp _camera; gl::TextureRef _texture; gl::BatchRef _sphere; qtime::MovieGlRef _video; const std::vector<std::string> mShapeNames = {"plane", "cylinder", "sphere"}; enum Shapes {Plane, Cylinder, Sphere}; enum Transition {PlaneCylinder, CylinderPlane}; vector<gl::GlslProgRef> mShapeShaders; int mCurrntShape; int mNextShape; int mTransition; int mTransitionTime; AxisAlignedBox mBbox; vec3 mCameraCOI; gl::BatchRef mPrimitive; Anim<float> mMix; Anim<quat> mQuatAnim, mRotateQuatAnim; audio::InputDeviceNodeRef mInputDeviceNode; audio::MonitorSpectralNodeRef mMonitorSpectralNode; // number of frequency bands of our spectrum const int kBands = 1024; const int kHistory = 128; const int kWidth = 256; const int kHeight = 256; Channel32f mChannelLeft; Channel32f mChannelRight; gl::TextureRef mTextureLeft; gl::TextureRef mTextureRight; gl::Texture::Format mTextureFormat; uint32_t mOffset; vector<float> mMagSpectrum; float mVolume; }; void VR360VideoIosApp::createGeometry() { auto plane = geom::Plane().subdivisions( ivec2( 100, 100 ) ); loadGeomSource( geom::Plane( plane ) ); } void VR360VideoIosApp::loadGeomSource( const geom::Source &source ) { // The purpose of the TriMesh is to capture a bounding box; without that need we could just instantiate the Batch directly using primitive TriMesh::Format fmt = TriMesh::Format().positions().normals().texCoords(); TriMesh mesh( source, fmt ); mBbox = mesh.calcBoundingBox(); mCameraCOI = mesh.calcBoundingBox().getCenter(); mPrimitive = gl::Batch::create( mesh, mShapeShaders[mTransition] ); } void VR360VideoIosApp::createShaders() { try { mShapeShaders.push_back( gl::GlslProg::create( loadAsset( "shaders/plane-cylinder_es2.vert" ), loadAsset( "shaders/spectrum_es2.frag" ) )); mShapeShaders.push_back(gl::GlslProg::create( loadAsset( "shaders/cylinder-sphere_es2.vert" ), loadAsset( "shaders/spectrum_es2.frag" ) )); mShapeShaders.push_back(gl::GlslProg::create( loadAsset( "shaders/sphere-plane_es2.vert" ), loadAsset( "shaders/spectrum_es2.frag" ) )); } catch( Exception &exc ) { CI_LOG_E( "error loading phong shader: " << exc.what() ); } } void VR360VideoIosApp::nextShape(){ float nextMix = mMix == 1.0f ? 0.0f : 1.0f; if (mCurrntShape == Plane && mNextShape == Cylinder) { mTransition = 0; } else if ( mCurrntShape == Cylinder && mNextShape == Plane) { mMix = 0.0f; nextMix = 1.0f; cout<< mMix << " " <<nextMix<<endl; mTransition = 0; } else if (mCurrntShape == Cylinder && mNextShape == Sphere){ mTransition = 1; mMix = 1.0f; nextMix = 0.0f; } else if (mCurrntShape == Sphere && mNextShape == Cylinder) { mTransition = 1; } else if (mCurrntShape == Plane && mNextShape == Sphere) { mTransition = 2; } else if (mCurrntShape == Sphere && mNextShape == Plane) { mTransition = 2; } mPrimitive->replaceGlslProg(mShapeShaders[mTransition]); if (mNextShape == Plane) { straightenViewAnimated(); } if (mNextShape == Cylinder) { turnViewForCylinderAnimated(); } timeline().appendTo( &mMix, nextMix, mTransitionTime, EaseInOutQuad() ).finishFn([this] { mCurrntShape = mNextShape; }); } void VR360VideoIosApp::straightenViewAnimated() { timeline().appendTo( &mQuatAnim, quat(), 5, EaseInOutQuad() ); } void VR360VideoIosApp::turnViewForCylinderAnimated() { vec3 normal = vec3( 0, 0, 1 ); quat cylinderQuat = angleAxis((float) M_PI_2, normalize( normal ) ); timeline().appendTo( &mQuatAnim, cylinderQuat, 5, EaseInOutQuad() ); } void VR360VideoIosApp::setup() { getSignalSupportedOrientations().connect( [] { return InterfaceOrientation::All; } ); MotionManager::enable( 60.0f, cinder::MotionManager::SensorMode::Gyroscope ); gl::enableDepth(); _sphere = gl::Batch::create ( geom::Sphere().subdivisions(64).radius(32), gl::getStockShader( gl::ShaderDef().texture() ) ); _video = qtime::MovieGl::create( getAssetPath( "Image_2.mov"/* "BVGG6623.mp4" */) ); _video->setLoop(); _video->play(); _camera.setEyePoint( vec3( 0 ) ); _texture = gl::Texture::create(loadImage(loadAsset("test_shot0161.png"))); // Load and compile the shaders. createShaders(); // start from current position mMix = 0.f; mCurrntShape = Sphere; mNextShape = Cylinder; mTransition = 1; createGeometry(); nextShape(); // Enable the depth buffer. gl::enableDepthRead(); gl::enableDepthWrite(); auto ctx = audio::Context::master(); mInputDeviceNode = ctx->createInputDeviceNode(); cout<< "Using " << mInputDeviceNode->getDevice() -> getName() << " audio input" <<endl; // By providing an FFT size double that of the window size, we 'zero-pad' the analysis data, which gives // an increase in resolution of the resulting spectrum data. auto monitorFormat = audio::MonitorSpectralNode::Format().fftSize( kBands ).windowSize( kBands / 2 ); mMonitorSpectralNode = ctx->makeNode( new audio::MonitorSpectralNode( monitorFormat ) ); mInputDeviceNode >> mMonitorSpectralNode; mInputDeviceNode->enable(); //ctx->enable(); // mChannelLeft = Channel32f(kBands, kHistory); // mChannelRight = Channel32f(kBands, kHistory); // memset( mChannelLeft.getData(), 0, mChannelLeft.getRowBytes() * kHistory ); // memset( mChannelRight.getData(), 0, mChannelRight.getRowBytes() * kHistory ); //#if !defined( CINDER_COCOA_TOUCH ) // mTextureFormat.setWrapS( GL_CLAMP_TO_BORDER ); //#endif // mTextureFormat.setWrapT( GL_REPEAT ); // mTextureFormat.setMinFilter( GL_LINEAR ); // mTextureFormat.setMagFilter( GL_LINEAR ); } void VR360VideoIosApp::resize() { bool isPortrait = getWindowHeight() > getWindowWidth(); float adjustedViewWidth = ( isPortrait ? kHorizontalSize : (kHorizontalSize / kTargetSize) * getWindowAspectRatio() ); float theta = 2.0f * math<float>::atan2( adjustedViewWidth / 2.0f, kTargetDistance ); _camera.setPerspective( toDegrees( theta ) , getWindowAspectRatio(), 1, 1000 ); } void VR360VideoIosApp::update ( ) { if ( _video->checkNewFrame() ) _texture = _video->getTexture();//.loadTopDown(); _camera.setOrientation( MotionManager::getRotation( getOrientation() ) ); return; mMagSpectrum = mMonitorSpectralNode->getMagSpectrum(); // get spectrum for left and right channels and copy it into our channels float* pDataLeft = mChannelLeft.getData() + kBands * mOffset; float* pDataRight = mChannelRight.getData() + kBands * mOffset; std::reverse_copy(mMagSpectrum.begin(), mMagSpectrum.end(), pDataLeft); std::copy(mMagSpectrum.begin(), mMagSpectrum.end(), pDataRight); // increment texture offset mOffset = (mOffset+1) % kHistory; mTextureLeft = gl::Texture::create(mChannelLeft, mTextureFormat); mTextureRight = gl::Texture::create(mChannelRight, mTextureFormat); } void VR360VideoIosApp::renderToServerFbo() { if (!mTextureLeft || !mTextureRight || !_texture) return; gl::clear( Color::black() ); gl::enableAlphaBlending(); gl::setMatrices( _camera ); gl::setDefaultShaderVars(); gl::ScopedTextureBind scopedTextureBind( _texture ); gl::rotate( mQuatAnim ); gl::rotate(mRotateQuatAnim); // Draw the primitive. gl::ScopedColor colorScope( Color( 0.7f, 0.5f, 0.3f ) ); float off = (mOffset / float(kHistory) - 0.5) * 2.0f; gl::GlslProgRef shader = mPrimitive->getGlslProg(); shader->uniform("uTexOffset", off); shader->uniform("uMix", mMix); shader->uniform("resolution", 0.25f*(float)kWidth); shader->uniform("uTex0",0); shader->uniform("uLeftTex", 1); shader->uniform("uRightTex", 2); shader->uniform("uVolume", (1.0f + mVolume * mMonitorSpectralNode->getVolume())); gl::ScopedTextureBind texLeft( mTextureLeft, 1 ); gl::ScopedTextureBind texRight( mTextureRight, 2 ); gl::ScopedBlendAdditive blend; mPrimitive->draw(); } void VR360VideoIosApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::setMatrices(_camera); if ( _texture ) { gl::ScopedTextureBind tex0 ( _texture ); _sphere->draw(); } renderToServerFbo(); } CINDER_APP( VR360VideoIosApp, RendererGl );
33.408784
147
0.643948
[ "mesh", "vector" ]
4dcd9d32ca73b1e340cc34a835cbae39897efe25
7,867
hpp
C++
include/questui_components/context.hpp
raineio/QuestUI-Playground
f4276bc287666d0956776642e6a46d98dfc3d280
[ "MIT" ]
null
null
null
include/questui_components/context.hpp
raineio/QuestUI-Playground
f4276bc287666d0956776642e6a46d98dfc3d280
[ "MIT" ]
null
null
null
include/questui_components/context.hpp
raineio/QuestUI-Playground
f4276bc287666d0956776642e6a46d98dfc3d280
[ "MIT" ]
null
null
null
#pragma once #include "key.hpp" #include <concepts> #include <tuple> #include <any> #include "UnityEngine/GameObject.hpp" #include "UnityEngine/Transform.hpp" namespace QUC { template <typename T> struct PtrWrapper { T ptr; }; struct UnsafeAny { UnsafeAny() = default; UnsafeAny(UnsafeAny const&) = delete; // TODO: Copy constructor copies the data with a new ptr? template<typename T, typename... TArgs> T& make_any(TArgs&&... args) { if (dtor != nullptr) dtor(data); data = new T(std::forward<TArgs>(args)...); dtor = &destroy_data<T>; return *static_cast<T*>(data); } template<typename T> T& get_any() { return *static_cast<T*>(data); } bool has_value() { return data != nullptr; } ~UnsafeAny() { if (dtor != nullptr) dtor(data); free(data); } private: template<typename T> static void destroy_data(void* ptr) { delete reinterpret_cast<T*>(ptr); } void* data = nullptr; void(*dtor)(void*) = nullptr; }; struct RenderContextChildData { UnsafeAny childData; template<typename T> T& getData() { if (!childData.has_value()) { childData.make_any<T>(); } return childData.get_any<T>(); } }; struct RenderContext { using ChildContextKey = Key; // 64 bit number using ChildData = Il2CppObject*; /// @brief The parent transform to render on to. UnityEngine::Transform& parentTransform; // For now, if we ever need to trigger a rebuild we simply say that we need to on the component side. // Alternatively, any time we show a component, we call render, which will generate what we need and set everything accordingly. // For now, we will do this, though there are quite a few optimizations we may be able to make in the future. RenderContext(UnityEngine::Transform* ptr) : parentTransform(*ptr) {} RenderContext(UnityEngine::Transform& ref) : parentTransform(ref) {} auto& getChildData(ChildContextKey index) { return dataContext[index]; } #pragma region child Context Clutter // TODO: Figure this out better // maybe not needed template<typename T, typename F = std::function<UnityEngine::Transform*()>> RenderContext& getChildContext(ChildContextKey id, F transform) { auto it = childrenContexts.find(id); std::hash<void*> hash; auto klassHash = hash(classof(T*)); if (it == childrenContexts.end()) { return childrenContexts.try_emplace(id, klassHash, transform()).first->second.second; } else { auto& [klassHashObject, data] = it->second; if (klassHash == klassHashObject) { return data; } if (data.parentTransform.m_CachedPtr) { // Destroy old context tree UnityEngine::Object::Destroy(data.parentTransform.get_gameObject()); } return childrenContexts.try_emplace(id, klassHash, transform()).first->second.second; } } void destroyChildContext(ChildContextKey id) { auto contextIt = childrenContexts.find(id); if (contextIt != childrenContexts.end()) { auto& context = contextIt->second; auto const& data = context.second; if (data.parentTransform.m_CachedPtr) { // Destroy old context tree UnityEngine::Object::Destroy(data.parentTransform.get_gameObject()); } childrenContexts.erase(contextIt); } } #pragma endregion template<bool includeParent = false> void destroyTree() { if (parentTransform.m_CachedPtr) { if constexpr (includeParent) { UnityEngine::Object::Destroy(parentTransform.get_gameObject()); } else { int childCount = parentTransform.GetChildCount(); std::vector<UnityEngine::Transform*> transforms; for (int i = 0; i < childCount; i++) { auto transform = parentTransform.GetChild(i); transforms.emplace_back(transform); } for (auto transform :transforms) { UnityEngine::Object::Destroy(transform->get_gameObject()); } } } } private: // template<typename InnerData> // struct RenderContextData { // // https://stackoverflow.com/a/994368/9816000 // const size_t klassHash; // InnerData data; // // template<typename T> // requires (std::is_convertible_v<T, Il2CppObject*>) // RenderContextData(InnerData const& data) : data(data) { // static auto klass = klassHash = std::hash<T>()(classof(T)); // } // }; // TODO: Figure out cleaning unusued keys std::unordered_map<ChildContextKey, RenderContextChildData> dataContext; std::unordered_map<ChildContextKey, std::pair<size_t, RenderContext>> childrenContexts; }; template<typename T> concept keyed = std::is_convertible_v<T, const QUC::Key>; // Allows both copies and references template<class T> /// @brief A concept for renderable components. /// @tparam T The type to check. concept renderable = requires (T t, RenderContext c, RenderContextChildData& data) { t.render(c, data); } && requires(T const t) { {t.key} -> keyed; }; template<class T, class U> concept pointer_type_match = std::is_pointer_v<T> && std::is_convertible_v<T, U>; template<class T, class U> concept renderable_return = requires (T t, RenderContext c, RenderContextChildData& data) { {t.render(c, data)} -> pointer_type_match<U>; }; template<class T> /// @brief A concept for updatable components. /// @tparam T The type to check. concept updatable = requires (T t, RenderContext c) { t; // {t.update()}; }; template<class T> /// @brief A concept for cloneable components. /// @tparam T The type to check. concept cloneable = requires (T t, RenderContext c) { t; // {t.clone()} -> std::same_as<T>; }; namespace detail { template<class T> requires (renderable<T>) static constexpr auto renderSingle(T& child, RenderContext& ctx) { auto& childData = ctx.getChildData(child.key); return child.render(ctx, childData); } template<size_t idx = 0, class... TArgs> requires ((renderable<TArgs> && ...)) static constexpr void renderTuple(std::tuple<TArgs...>& args, RenderContext& ctx) { if constexpr (idx < sizeof...(TArgs)) { auto& child = std::get<idx>(args); renderSingle(child, ctx); // render child renderTuple<idx + 1>(args, ctx); } } template<size_t idx = 0, class... TArgs> requires ((cloneable<TArgs> && ...)) std::tuple<TArgs...> cloneTuple(std::tuple<TArgs...> const& args) { if constexpr (idx < sizeof...(TArgs)) { auto clone = std::get<idx>(args).clone(); auto newTuple = cloneTuple<idx + 1>(args); return std::make_tuple<TArgs...>(clone, newTuple); } } } }
32.916318
136
0.557265
[ "render", "object", "vector", "transform" ]
4dcf853ffed26713c292330721637a4b4585deba
5,739
cpp
C++
src/source/Image.cpp
Matistjati/Mandelbuld-renderer
0330eb6a1c8dee822ae2f8b8f7c82a89a6303f94
[ "MIT" ]
3
2019-06-21T21:34:12.000Z
2022-01-26T10:45:29.000Z
src/source/Image.cpp
Matistjati/Mandelbuld-renderer
0330eb6a1c8dee822ae2f8b8f7c82a89a6303f94
[ "MIT" ]
1
2019-05-25T17:39:40.000Z
2019-06-02T11:05:54.000Z
src/source/Image.cpp
Matistjati/Mandelbuld-renderer
0330eb6a1c8dee822ae2f8b8f7c82a89a6303f94
[ "MIT" ]
null
null
null
#include "headers/Image.h" #include "headers/Debug.h" #include <stdexcept> #include <iostream> Image::Image(int width, int height, std::vector<Pixel> *pixels) : width(width), height(height), pixels(pixels), pixelsInitialized(false), hasAlpha(false) {} Image::Image(int width, int height, std::vector<glm::ivec4> pixels) : width(width), height(height), pixelsInitialized(true), hasAlpha(true) { std::vector<Pixel> *data = new std::vector<Pixel>(width * height); size_t pixelCount = width * height; for (size_t i = 0; i < pixelCount; i++) { (*data)[i] = Pixel(pixels[i]); } this->pixels = data; } Image::Image(std::string filePath) : pixelsInitialized(true) { png_bytep* row_pointers = NULL; FILE* fp = fopen(filePath.c_str(), "rb"); png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png) abort(); png_infop info = png_create_info_struct(png); if (!info) abort(); if (setjmp(png_jmpbuf(png))) abort(); png_init_io(png, fp); png_read_info(png, info); width = png_get_image_width(png, info); height = png_get_image_height(png, info); png_byte color_type = png_get_color_type(png, info); png_byte bit_depth = png_get_bit_depth(png, info); hasAlpha = (color_type & PNG_COLOR_MASK_ALPHA); // Read any color_type into 8bit depth, RGBA format. // See http://www.libpng.org/pub/png/libpng-manual.txt if (bit_depth == 16) png_set_strip_16(png); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png); // PNG_COLOR_TYPE_GRAY_ALPHA is always 8 or 16bit depth. if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png); if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png); // These color_type don't have an alpha channel then fill it with 0xff. if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png, 0xFF, PNG_FILLER_AFTER); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png); png_read_update_info(png, info); if (row_pointers) abort(); row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height); for (int y = 0; y < height; y++) { row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info)); } png_read_image(png, row_pointers); fclose(fp); png_destroy_read_struct(&png, &info, NULL); if (!hasAlpha) { //DebugPrint("There is currently no support for an alpha channel"); //BreakIfDebug(); } std::vector<Pixel>* data = new std::vector<Pixel>(width * height); for (int y = 0; y < height; y++) { png_bytep row = row_pointers[y]; for (int x = 0; x < width; x++) { png_bytep px = &(row[x * 4]); (*data)[y * width + x] = Pixel(px[0], px[1], px[2], 255); } } this->pixels = data; } Image::~Image() { if (pixelsInitialized) { delete pixels; } } // You know i "borrowed" the code when there are comments in it :) void Image::Save(const std::string path) { FILE * fp; png_structp png_ptr = nullptr; png_infop info_ptr = nullptr; png_byte ** row_pointers = nullptr; // Trial and error (By someone else) const int pixel_size = 4; const int depth = 8; fp = fopen(path.c_str(), "wb"); if (!fp) { std::cout << "Error saving image : bad file path : " << path << std::endl; throw std::invalid_argument("Error saving image: bad file path: " + path); } png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); if (png_ptr == nullptr) { fclose(fp); throw std::invalid_argument("Could not create png pointer"); } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == nullptr) { fclose(fp); throw std::invalid_argument("Could not create info pointer"); } // Set up error handling if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); throw std::invalid_argument("Could not set up error handling"); } // Set image attributes png_set_IHDR(png_ptr, info_ptr, width, height, depth, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); // Initialize rows of PNG. row_pointers = (png_byte**)png_malloc(png_ptr, height * sizeof(png_byte *)); for (int y = 0; y < height; ++y) { png_byte *row = (png_byte*)png_malloc(png_ptr, sizeof(uint8_t) * width * pixel_size); row_pointers[y] = row; for (int x = 0; x < width; ++x) { Pixel* pixel = PixelAt(x, y); *row++ = pixel->r; *row++ = pixel->g; *row++ = pixel->b; *row++ = pixel->a; } } // Write image data to the file png_init_io(png_ptr, fp); png_set_rows(png_ptr, info_ptr, row_pointers); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); // Free the allocated memory for (int y = 0; y < height; y++) { png_free(png_ptr, row_pointers[y]); } png_free(png_ptr, row_pointers); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); } void Image::FlipVertically() { try { for (int j = 0; j < width; j++) { for (int i = 0; i < height / 2; i++) { Swap(&(*pixels)[j + width * i], &(*pixels)[j + width * (height - i - 1)]); } } } catch (std::exception& e) { std::cout << e.what(); } } void Image::FlipAndSave(const std::string path) { this->FlipVertically(); this->Save(path); } void Image::Invert() { for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { Pixel* pixel = PixelAt(x, y); pixel->r = 255 - pixel->r; pixel->g = 255 - pixel->g; pixel->b = 255 - pixel->b; } } } inline Pixel* Image::PixelAt(int x, int y) { return &(*pixels)[width * y + x]; } inline void Image::Swap(Pixel * a, Pixel * b) { Pixel temp = *a; *a = *b; *b = temp; }
22.417969
153
0.666492
[ "vector" ]
4dd796ab41726fecf7cbfbfcdd84ea439d93ca3f
12,807
cpp
C++
muller-brown/muller_brown.cpp
muhammadhasyim/tps-torch
21201458d037649fa66794b993ccfba7d7414028
[ "BSD-3-Clause" ]
3
2021-05-05T12:09:45.000Z
2021-05-17T18:39:54.000Z
muller-brown/muller_brown.cpp
muhammadhasyim/tps-torch
21201458d037649fa66794b993ccfba7d7414028
[ "BSD-3-Clause" ]
null
null
null
muller-brown/muller_brown.cpp
muhammadhasyim/tps-torch
21201458d037649fa66794b993ccfba7d7414028
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <fstream> #include <random> #include <algorithm> #include <math.h> #include <ctime> #include <string> #include <vector> #include <chrono> #include "saruprng.hpp" #include "muller_brown.h" using namespace std; MullerBrown::MullerBrown() { // Constructor, currently does nothing state.x = 0; state.y = 0; } MullerBrown::~MullerBrown() { // Delete the pointers delete[] a_const; delete[] a_param; delete[] b_param; delete[] c_param; delete[] x_param; delete[] y_param; delete[] phi_storage; delete[] state_storage; } void MullerBrown::GetParams(string name, int rank_in) { ifstream input; input.open(name); if(input.fail()) { cout << "No input file" << endl; } else { char buffer; string line; //cout << "Param file detected. Changing values." << endl; input >> line >> temp; //cout << "temp is now " << temp << endl; getline(input, line); input >> line >> count; //cout << "Count is now " << count << endl; a_const = new double[count]; a_param = new double[count]; b_param = new double[count]; c_param = new double[count]; x_param = new double[count]; y_param = new double[count]; for(int i=0; i<count; i++) { input >> line >> a_const[i] >> a_param[i] >> b_param[i] >> c_param[i] >> x_param[i] >> y_param[i]; //cout << i << " A_ " << a_const[i] << " a_ " << a_param[i] << " b_ " << b_param[i] << " c_ " << c_param[i] << " x_ " << x_param[i] << " y_ " << y_param[i] << endl; getline(input, line); } input >> line >> lambda; //cout << "lambda is now " << lambda << endl; getline(input, line); input >> line >> cycles >> storage_time; //cout << "Cycles " << cycles << " storage_time " << storage_time << endl; getline(input, line); phi_storage = new double[cycles/storage_time]; state_storage = new double2[cycles/storage_time]; input >> line >> seed_base >> count_step >> frame_time >> check_time; //cout << "seed_base " << seed_base << " count_step " << count_step << " frame_time " << frame_time << " check_time " << check_time << endl; getline(input, line); generator = Saru(seed_base, count_step); } // also modify config path config_file.open("string_"+to_string(rank_in)+"_config.xyz", std::ios_base::app); } double MullerBrown::Energy(double2 state_) { double phi_ = 0.0; for(int i=0; i<count; i++) { double x_term = state_.x-x_param[i]; double y_term = state_.y-y_param[i]; phi_ += a_const[i]*exp(a_param[i]*x_term*x_term+b_param[i]*x_term*y_term+c_param[i]*y_term*y_term); } return phi_; } double MullerBrown::VoronoiDist(double2 state_test, float * vor_cell) { double dist_x = pow(state_test.x-vor_cell[0],2); double dist_y = pow(state_test.y-vor_cell[1],2); return sqrt(dist_x+dist_y); } int MullerBrown::VoronoiCheck(double2 state_) { int min_index = 0; double min_distance = VoronoiDist(state_, voronoi_cells); for(int i=1; i<vor_sizes[0]; i++) { double distance = VoronoiDist(state_, voronoi_cells+i*vor_sizes[2]); if(distance < min_distance) { min_distance = distance; min_index = i; } } return min_index; } void MullerBrown::VoronoiSet() { state.x = voronoi_cells[rank*vor_sizes[2]]; state.y = voronoi_cells[rank*vor_sizes[2]+1]; phi = Energy(state); } void MullerBrown::MCStep() { double2 state_trial; state_trial.x = state.x + lambda*generator.d(-1.0,1.0); state_trial.y = state.y + lambda*generator.d(-1.0,1.0); double phi_ = Energy(state_trial); double phi_diff = phi_-phi; if(phi_diff < 0) { // accept state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else if(generator.d() < exp(-phi_diff/temp)) { // still accept, just a little more work state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else { // reject steps_rejected++; } steps_tested++; } void MullerBrown::MCStepSelf() { phi = Energy(state); double2 state_trial; state_trial.x = state.x + lambda*generator.d(-1.0,1.0); state_trial.y = state.y + lambda*generator.d(-1.0,1.0); double phi_ = Energy(state_trial); double phi_diff = phi_-phi; if(phi_diff < 0) { // accept state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else if(generator.d() < exp(-phi_diff/temp)) { // still accept, just a little more work state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else { // reject steps_rejected++; } steps_tested++; } void MullerBrown::MCStepBias() { double2 state_trial; state_trial.x = state.x + lambda*generator.d(-1.0,1.0); state_trial.y = state.y + lambda*generator.d(-1.0,1.0); double phi_ = Energy(state_trial); double phi_diff = phi_-phi; // Check to see if it satisfies constraints double lcheck = lweight[0]*state_trial.x+lweight[1]*state_trial.y+lbias[0]; double rcheck = rweight[0]*state_trial.x+rweight[1]*state_trial.y+rbias[0]; bool check = (lcheck >= 0) && (rcheck <= 0); if((phi_diff < 0) && check) { // accept state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else if((generator.d() < exp(-phi_diff/temp)) && check) { // still accept, just a little more work state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else { // reject steps_rejected++; } steps_tested++; } void MullerBrown::MCStepVor() { ofstream config_dump; config_dump.precision(10); config_dump.open("out_"+to_string(rank), std::ios_base::app); double2 state_trial; state_trial.x = state.x + lambda*generator.d(-1.0,1.0); state_trial.y = state.y + lambda*generator.d(-1.0,1.0); double phi_ = Energy(state_trial); double phi_diff = phi_-phi; int check = VoronoiCheck(state_trial); if(check == rank) { if(phi_diff < 0) { // accept state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else if(generator.d() < exp(-phi_diff/temp)) { // still accept, just a little more work state.x = state_trial.x; state.y = state_trial.y; phi = phi_; } else { // reject steps_rejected++; } } else { // reject steps_rejected++; } if(count_step%50==0) { config_dump << "States " << state.x << " " << state.y << " " << state_trial.x << " " << state_trial.y << " phi_diff " << phi_diff << " check " << check << " " << rank << "\n"; } steps_tested++; if((count_step%500==0) && (count_step>0)) { // Adjust lambda for optimal acceptance/rejectance double ratio = double(steps_rejected)/double(steps_tested); if(ratio < 0.5) { lambda *= 1.2; } else if(ratio > 0.7) { lambda *= 0.9; } steps_rejected = 0; steps_tested = 0; } } void MullerBrown::Simulate(int steps) { steps_tested = 0; steps_rejected = 0; ofstream config_file_2; config_file_2.precision(10); config_file_2.open(config, std::ios_base::app); phi = Energy(state); for(int i=0; i<steps; i++) { generator = Saru(seed_base, count_step++); MCStep(); if(i%check_time==0) { cout << "Cycle " << i << " phi " << phi << " A/R " << double(steps_rejected)/double(steps_tested) << endl; } if(i%storage_time==0) { phi_storage[i/storage_time] = phi; state_storage[i/storage_time].x = state.x; state_storage[i/storage_time].y = state.y; } if(i%frame_time==0) { DumpXYZ(config_file_2); } } } void MullerBrown::SimulateBias(int steps) { steps_tested = 0; steps_rejected = 0; phi = Energy(state); for(int i=0; i<steps; i++) { generator = Saru(seed_base, count_step++); MCStepBias(); if(dump_sim==1){ if(i%check_time==0) { cout << "Cycle " << i << " phi " << phi << " A/R " << double(steps_rejected)/double(steps_tested) << endl; } if(i%storage_time==0) { phi_storage[i/storage_time] = phi; state_storage[i/storage_time].x = state.x; state_storage[i/storage_time].y = state.y; } } } } void MullerBrown::SimulateVor(int steps) { steps_tested = 0; steps_rejected = 0; phi = Energy(state); // Check to see if initial config is within Voronoi cell is it supposed to be in // If not, change config to Voronoi cell // If outside (false), set int check = VoronoiCheck(state); if(check != rank) { VoronoiSet(); } for(int i=0; i<steps; i++) { generator = Saru(seed_base, count_step++); MCStepVor(); if(dump_sim==1){ if(i%check_time==0) { cout << "Cycle " << i << " phi " << phi << " A/R " << double(steps_rejected)/double(steps_tested) << endl; } if(i%storage_time==0) { phi_storage[i/storage_time] = phi; state_storage[i/storage_time].x = state.x; state_storage[i/storage_time].y = state.y; } } } } void MullerBrown::DumpXYZ(ofstream& myfile) { // turns off synchronization of C++ streams ios_base::sync_with_stdio(false); // Turns off flushing of out before in cin.tie(NULL); myfile << 1 << endl; myfile << "# step " << count_step << endl; myfile << "0 " << std::scientific << state.x << " " << std::scientific << state.y << " 0\n"; } void MullerBrown::DumpXYZBias(int dump=0) { // turns off synchronization of C++ streams ios_base::sync_with_stdio(false); // Turns off flushing of out before in cin.tie(NULL); config_file << 1 << endl; config_file << "# step " << count_step << " "; if(dump==1) { // Dump weights and biases config_file << "lweight " << lweight[0] << " " << lweight[1] << " lbias " << lbias[0] << " "; config_file << "rweight " << rweight[0] << " " << rweight[1] << " rbias " << rbias[0]; } config_file << "\n"; config_file << "0 " << std::scientific << state.x << " " << std::scientific << state.y << " 0\n"; } void MullerBrown::DumpXYZVor() { // turns off synchronization of C++ streams ios_base::sync_with_stdio(false); // Turns off flushing of out before in cin.tie(NULL); config_file << 2 << endl; config_file << "# step " << count_step << "\n"; config_file << "0 " << std::scientific << state.x << " " << std::scientific << state.y << " 0\n"; config_file << "1 " << std::scientific << voronoi_cells[rank*vor_sizes[2]] << " " << voronoi_cells[rank*vor_sizes[2]+1] << " 0\n"; } void MullerBrown::DumpPhi() { // Evaluate same stats stuff and dump all stored values double phi_ave = 0.0; int storage = cycles/storage_time; for(int i=0; i<storage; i++) { phi_ave += phi_storage[i]; } phi_ave /= storage; // Standard deviation with Bessel's correction double phi_std = 0.0; for(int i=0; i<storage; i++) { double phi_std_ = phi_ave-phi_storage[i]; phi_std += phi_std_*phi_std_; } phi_std = sqrt(phi_std/(storage-1)); ofstream myfile; myfile.precision(10); myfile.open("phi.txt"); myfile << "phi from simulation run" << endl; myfile << "Average " << std::scientific << phi_ave << " Standard_Deviation " << std::scientific << phi_std << endl; myfile.close(); myfile.open("phi_storage.txt"); myfile << "Energy from run" << endl; for(int i=0; i<storage; i++) { myfile << std::scientific << phi_storage[i] << "\n"; } } void MullerBrown::DumpStates() { int storage = cycles/storage_time; ofstream myfile; myfile.precision(10); myfile.open("state_storage.txt"); myfile << "States from run" << endl; for(int i=0; i<storage; i++) { myfile << std::scientific << state_storage[i].x << " " << std::scientific << state_storage[i].y << "\n"; } } int main(int argc, char* argv[]) { MullerBrown system; system.GetParams("param", 0); system.Simulate(system.cycles); system.DumpPhi(); system.DumpStates(); }
32.178392
183
0.563754
[ "vector" ]
4dd8ee7becc632494273186324f4afc5d7c0263b
4,223
cpp
C++
src/NetService.cpp
Lw-Cui/Compression-server
3501d746f14145d3764700d40d3672a0da0b2eae
[ "MIT" ]
3
2016-12-10T16:06:20.000Z
2017-06-25T12:47:06.000Z
src/NetService.cpp
Lw-Cui/Compression-server
3501d746f14145d3764700d40d3672a0da0b2eae
[ "MIT" ]
2
2017-05-15T15:22:36.000Z
2017-05-20T15:01:25.000Z
src/NetService.cpp
Lw-Cui/Tiny-server
3501d746f14145d3764700d40d3672a0da0b2eae
[ "MIT" ]
null
null
null
#include <NetService.hpp> using namespace std; int Client::connectServer(const std::string &hostname, int port, SocketType type) { if ((connfd = socket(AF_INET, type, 0)) < 0) err_sys("Open socket error"); struct hostent *hostInfo = nullptr; if ((hostInfo = gethostbyname(hostname.c_str())) == nullptr) err_sys("Get hostname error"); struct sockaddr_in serverSocket; memset(reinterpret_cast<char *>(&serverSocket), 0, sizeof(serverSocket)); serverSocket.sin_family = AF_INET; bcopy(hostInfo->h_addr_list[0], reinterpret_cast<char *>(&serverSocket.sin_addr.s_addr), static_cast<size_t>(hostInfo->h_length)); serverSocket.sin_port = htons(port); if (connect(connfd, reinterpret_cast<struct sockaddr *>(&serverSocket), sizeof(serverSocket)) < 0) err_sys("connect error"); return connfd; } size_t NetReadWrite::rioRead(int fd, std::string &usrbuf) { usrbuf.clear(); while (true) { char c; long int rc{read(fd, &c, 1)}; // IMPORTANT! if (rc == 1 && c != '\0') usrbuf.push_back(c); if (rc == 0 || c == '\0') return usrbuf.size(); // EOF if (rc < 0) err_sys("Read failed"); } } void NetReadWrite::rioWrite(int fd, const string &usrbuf) { size_t nleft{usrbuf.length()}; ssize_t nwritten; const char *bufp{usrbuf.c_str()}; while (nleft > 0) { if ((nwritten = write(fd, bufp, nleft)) <= 0) { if (errno == EINTR) nwritten = 0; else err_sys("Write failed"); } nleft -= nwritten; bufp += nwritten; } write(fd, "\0", 1); // write EOF } int Server::Listening(int port, SocketType type) { listenfd = port; if ((listenfd = socket(AF_INET, type, 0)) < 0) err_sys("Socket open failed"); int optval = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const void *>(&optval), sizeof(int)) < 0) err_sys("Setsockopt failed"); struct sockaddr_in clientSocket; memset(&clientSocket, 0, sizeof(clientSocket)); clientSocket.sin_family = AF_INET; clientSocket.sin_addr.s_addr = htons(INADDR_ANY); clientSocket.sin_port = htons(port); if (::bind(listenfd, reinterpret_cast<sockaddr *>(&clientSocket), sizeof(clientSocket)) < 0) err_sys("Bind socket failed"); if (type == TCP && listen(listenfd, LISTENQ) < 0) err_sys("Listen port failed"); return listenfd; } int Server::waitConnection() { struct sockaddr_in clientSocket; unsigned int clientlen = sizeof(clientSocket); int connfd = -1; if ((connfd = accept(listenfd, reinterpret_cast<sockaddr *>(&clientSocket), &clientlen)) < 0) err_sys("Accept failed"); return connfd; } void err_sys(const char *fmt, ...) { constexpr int MAXLINE = 500; char buf[MAXLINE]; va_list ap; va_start(ap, fmt); vsnprintf(buf, MAXLINE, fmt, ap); va_end(ap); snprintf(buf + strlen(buf), MAXLINE - strlen(buf), ": %s", strerror(errno)); strcat(buf, "\n"); fflush(stdout); fputs(buf, stderr); fflush(NULL); exit(1); } void CstyleNetServer::send(const std::string &hostname, int port, std::string info) { auto fd = c.connectServer(hostname, port); NetReadWrite::rioWrite(fd, info); close(fd); } CstyleNetServer::CstyleNetServer(int port) { io.addFd(server.Listening(port), [this](int)mutable -> void { int fd = server.waitConnection(); NetReadWrite::rioRead(fd, buffer); close(fd); }); } std::string CstyleNetServer::receive() { io.processOneRequest(); return buffer; } void IOMultiplexingUtility::processOneRequest() { auto readySet = socketSet; select(maxfd + 1, &readySet, NULL, NULL, NULL); for (auto &pair: fdVec) if (FD_ISSET(pair.first, &readySet)) { if (pair.second != nullptr) pair.second(pair.first); else if (defaultAction) defaultAction(pair.first); break; } } std::vector<int> IOMultiplexingUtility::getUnspecifedFd() { std::vector<int> vec; for (auto &pair: fdVec) if (pair.second == nullptr) vec.push_back(pair.first); return vec; }
30.164286
102
0.624438
[ "vector" ]
4dd9e513125dc8b32e07d89fea4f4ddb6e09b220
707
cpp
C++
Cplus/TheSkylineProblem.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/TheSkylineProblem.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/TheSkylineProblem.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <set> #include <vector> using namespace std; /* range check */ class Solution { public: vector<vector<int>> getSkyline(vector<vector<int>> &buildings) { vector<vector<int>> res; int maxheight = 0; multiset<pair<int, int>> criticalpoint; //{range bounder,height} for (auto &b : buildings) { criticalpoint.insert({b[0], -b[2]}); criticalpoint.insert({b[1], b[2]}); } multiset<int> height({0}); for (auto p : criticalpoint) { if (p.second < 0) height.insert(-p.second); else height.erase(height.find(p.second)); if (*height.rbegin() != maxheight) { maxheight = *height.rbegin(); res.push_back({p.first, maxheight}); } } return res; } };
18.605263
66
0.623762
[ "vector" ]
4ddaaa6b508061d3fcf9c50ba8db9a8959559b38
19,293
cc
C++
connectivity/shill/test-rpc-proxy/proxy_rpc_server.cc
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
connectivity/shill/test-rpc-proxy/proxy_rpc_server.cc
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
connectivity/shill/test-rpc-proxy/proxy_rpc_server.cc
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
// // Copyright (C) 2015 The Android 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 <base/bind.h> #include "proxy_rpc_in_data_types.h" #include "proxy_rpc_out_data_types.h" #include "proxy_rpc_server.h" #include "proxy_util.h" namespace { // XmlRpc library verbosity level. static const int kDefaultXmlRpcVerbosity = 5; // Profile name to be used for all the tests. static const char kTestProfileName[] = "test"; bool ValidateNumOfElements(const XmlRpc::XmlRpcValue& value, int expected_num) { if (expected_num != 0) { return (value.valid() && value.size() == expected_num); } else { // |value| will be marked invalid when there are no elements. return !value.valid(); } } }// namespace /*************** RPC Method implementations **********/ XmlRpc::XmlRpcValue CreateProfile( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& profile_name(params_in[0]); return shill_wifi_client->CreateProfile(profile_name); } XmlRpc::XmlRpcValue RemoveProfile( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& profile_name(params_in[0]); return shill_wifi_client->RemoveProfile(profile_name); } XmlRpc::XmlRpcValue PushProfile( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& profile_name(params_in[0]); return shill_wifi_client->PushProfile(profile_name); } XmlRpc::XmlRpcValue PopProfile( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& profile_name(params_in[0]); return shill_wifi_client->PopProfile(profile_name); } XmlRpc::XmlRpcValue CleanProfiles( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 0)) { return false; } return shill_wifi_client->CleanProfiles(); } XmlRpc::XmlRpcValue ConfigureServiceByGuid( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } ConfigureServiceParameters config_params(&params_in[0]); return shill_wifi_client->ConfigureServiceByGuid( config_params.guid_, config_params.autoconnect_type_, config_params.passphrase_); } XmlRpc::XmlRpcValue ConfigureWifiService( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } AssociationParameters assoc_params(&params_in[0]); brillo::VariantDictionary security_params; assoc_params.security_config_->GetServiceProperties(&security_params); return shill_wifi_client->ConfigureWifiService( assoc_params.ssid_, assoc_params.security_config_->security_, security_params, assoc_params.save_credentials_, assoc_params.station_type_, assoc_params.is_hidden_, assoc_params.guid_, assoc_params.autoconnect_type_); } XmlRpc::XmlRpcValue ConnectWifi( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } AssociationParameters assoc_params(&params_in[0]); std::string wifi_interface = assoc_params.bgscan_config_->interface_; if (wifi_interface.empty()) { std::vector<std::string> interfaces; if (!shill_wifi_client->ListControlledWifiInterfaces(&interfaces) || interfaces.empty()) { return false; } wifi_interface = interfaces[0]; } shill_wifi_client->ConfigureBgScan( wifi_interface, assoc_params.bgscan_config_->method_, assoc_params.bgscan_config_->short_interval_, assoc_params.bgscan_config_->long_interval_, assoc_params.bgscan_config_->signal_threshold_); brillo::VariantDictionary security_params; assoc_params.security_config_->GetServiceProperties(&security_params); long discovery_time, association_time, configuration_time; std::string failure_reason; bool is_success = shill_wifi_client->ConnectToWifiNetwork( assoc_params.ssid_, assoc_params.security_config_->security_, security_params, assoc_params.save_credentials_, assoc_params.station_type_, assoc_params.is_hidden_, assoc_params.guid_, assoc_params.autoconnect_type_, GetMillisecondsFromSeconds(assoc_params.discovery_timeout_seconds_), GetMillisecondsFromSeconds(assoc_params.association_timeout_seconds_), GetMillisecondsFromSeconds(assoc_params.configuration_timeout_seconds_), &discovery_time, &association_time, &configuration_time, &failure_reason); AssociationResult association_result( is_success, GetSecondsFromMilliseconds(discovery_time), GetSecondsFromMilliseconds(association_time), GetSecondsFromMilliseconds(configuration_time), failure_reason); return association_result.ConvertToXmlRpcValue(); } XmlRpc::XmlRpcValue DeleteEntriesForSsid( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& ssid(params_in[0]); return shill_wifi_client->DeleteEntriesForSsid(ssid); } XmlRpc::XmlRpcValue InitTestNetworkState( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 0)) { return false; } shill_wifi_client->SetLogging(); shill_wifi_client->CleanProfiles(); shill_wifi_client->RemoveAllWifiEntries(); shill_wifi_client->RemoveProfile(kTestProfileName); bool is_success = shill_wifi_client->CreateProfile(kTestProfileName); if (is_success) { shill_wifi_client->PushProfile(kTestProfileName); } return is_success; } XmlRpc::XmlRpcValue ListControlledWifiInterfaces( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 0)) { return false; } std::vector<std::string> interfaces; if (!shill_wifi_client->ListControlledWifiInterfaces(&interfaces)) { return false; } XmlRpc::XmlRpcValue result; int array_pos = 0; for (const auto& interface : interfaces) { result[array_pos++] = interface; } return result; } XmlRpc::XmlRpcValue Disconnect( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& ssid = params_in[0]; return shill_wifi_client->Disconnect(ssid); } XmlRpc::XmlRpcValue WaitForServiceStates( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 3)) { return false; } const std::string& ssid(params_in[0]); XmlRpc::XmlRpcValue states_as_xmlrpcvalue(params_in[1]); int timeout(params_in[2]); int num_states = states_as_xmlrpcvalue.size(); std::vector<std::string> states; for (int array_pos = 0; array_pos < num_states; array_pos++) { states.emplace_back(std::string(states_as_xmlrpcvalue[array_pos])); } std::string final_state; long wait_time; bool is_success = shill_wifi_client->WaitForServiceStates( ssid, states, GetMillisecondsFromSeconds(timeout), &final_state, &wait_time); XmlRpc::XmlRpcValue result; result[0] = is_success; result[1] = final_state; result[2] = GetSecondsFromMilliseconds(wait_time); return result; } XmlRpc::XmlRpcValue GetServiceOrder( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 0)) { return false; } std::string order; if (!shill_wifi_client->GetServiceOrder(&order)) { return false; } return order; } XmlRpc::XmlRpcValue SetServiceOrder( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& order(params_in[0]); return shill_wifi_client->SetServiceOrder(order); } XmlRpc::XmlRpcValue GetServiceProperties( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& ssid(params_in[0]); brillo::VariantDictionary properties; if (!shill_wifi_client->GetServiceProperties(ssid, &properties)) { return false; } XmlRpc::XmlRpcValue result; GetXmlRpcValueFromBrilloAnyValue(properties, &result); return result; } XmlRpc::XmlRpcValue GetActiveWifiSsids( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 0)) { return false; } std::vector<std::string> ssids; if (!shill_wifi_client->GetActiveWifiSsids(&ssids)) { return false; } XmlRpc::XmlRpcValue result; int array_pos = 0; for (const auto& ssid : ssids) { result[array_pos++] = ssid; } return result; } XmlRpc::XmlRpcValue SetSchedScan( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } bool enable(params_in[0]); return shill_wifi_client->SetSchedScan(enable); } XmlRpc::XmlRpcValue GetDbusPropertyOnDevice( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); const std::string& property_name(params_in[1]); brillo::Any property_value; if (!shill_wifi_client->GetPropertyOnDevice( interface_name, property_name, &property_value)) { return false; } XmlRpc::XmlRpcValue result; GetXmlRpcValueFromBrilloAnyValue(property_value, &result); return result; } XmlRpc::XmlRpcValue SetDbusPropertyOnDevice( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 3)) { return false; } const std::string& interface_name(params_in[0]); const std::string& property_name(params_in[1]); brillo::Any property_value; GetBrilloAnyValueFromXmlRpcValue(&params_in[2], &property_value); return shill_wifi_client->SetPropertyOnDevice( interface_name, property_name, property_value); } XmlRpc::XmlRpcValue RequestRoamDbus( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& bssid(params_in[0]); const std::string& interface_name(params_in[1]); // |interface_name| is the first argument in ProxyShillWifiClient method // to keep it symmetric with other methods defined in the interface even // though it is reversed in the RPC call. return shill_wifi_client->RequestRoam(interface_name, bssid); } XmlRpc::XmlRpcValue SetDeviceEnabled( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); bool enable(params_in[1]); return shill_wifi_client->SetDeviceEnabled(interface_name, enable); } XmlRpc::XmlRpcValue DiscoverTdlsLink( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); const std::string& peer_mac_address(params_in[1]); return shill_wifi_client->DiscoverTdlsLink(interface_name, peer_mac_address); } XmlRpc::XmlRpcValue EstablishTdlsLink( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); const std::string& peer_mac_address(params_in[1]); return shill_wifi_client->EstablishTdlsLink(interface_name, peer_mac_address); } XmlRpc::XmlRpcValue QueryTdlsLink( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); const std::string& peer_mac_address(params_in[1]); std::string status; if (!shill_wifi_client->QueryTdlsLink( interface_name, peer_mac_address, &status)) { return false; } return status; } XmlRpc::XmlRpcValue AddWakePacketSource( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); const std::string& source_ip(params_in[1]); return shill_wifi_client->AddWakePacketSource(interface_name, source_ip); } XmlRpc::XmlRpcValue RemoveWakePacketSource( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 2)) { return false; } const std::string& interface_name(params_in[0]); const std::string& source_ip(params_in[1]); return shill_wifi_client->RemoveWakePacketSource(interface_name, source_ip); } XmlRpc::XmlRpcValue RemoveAllWakePacketSources( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } const std::string& interface_name(params_in[0]); return shill_wifi_client->RemoveAllWakePacketSources(interface_name); } XmlRpc::XmlRpcValue SyncTimeTo( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { if (!ValidateNumOfElements(params_in, 1)) { return false; } double epoch_seconds(params_in[0]); double seconds; double microseconds = modf(epoch_seconds, &seconds) * 1000000; struct timeval tv; tv.tv_sec = seconds; tv.tv_usec = microseconds; return settimeofday(&tv, nullptr); } // Dummy method to be used for rpc methods not implemented yet. XmlRpc::XmlRpcValue NotImplementedRpcMethod( XmlRpc::XmlRpcValue params_in, ProxyShillWifiClient* shill_wifi_client) { LOG(ERROR) << "RPC Method not implemented."; return true; } ProxyRpcServerMethod::ProxyRpcServerMethod( const std::string& method_name, const RpcServerMethodHandler& handler, ProxyShillWifiClient* shill_wifi_client, ProxyRpcServer* server) : XmlRpcServerMethod(method_name, server), handler_(handler), shill_wifi_client_(shill_wifi_client) { } void ProxyRpcServerMethod::execute( XmlRpc::XmlRpcValue& params_in, XmlRpc::XmlRpcValue& value_out) { value_out = handler_.Run(params_in, shill_wifi_client_); } std::string ProxyRpcServerMethod::help(void) { // TODO: Lookup the method help using the |method_name| from // a text file. return "Shill Test Proxy RPC methods help."; } ProxyRpcServer::ProxyRpcServer( int server_port, std::unique_ptr<ProxyShillWifiClient> shill_wifi_client) : XmlRpcServer(), server_port_(server_port), shill_wifi_client_(std::move(shill_wifi_client)) { } void ProxyRpcServer::RegisterRpcMethod( const std::string& method_name, const RpcServerMethodHandler& handler) { methods_.emplace_back( new ProxyRpcServerMethod( method_name, handler, shill_wifi_client_.get(), this)); } void ProxyRpcServer::Run() { XmlRpc::setVerbosity(kDefaultXmlRpcVerbosity); if (!XmlRpc::XmlRpcServer::bindAndListen(server_port_)) { LOG(ERROR) << "Failed to bind to port " << server_port_ << "."; return; } XmlRpc::XmlRpcServer::enableIntrospection(true); RegisterRpcMethod("create_profile", base::Bind(&CreateProfile)); RegisterRpcMethod("remove_profile", base::Bind(&RemoveProfile)); RegisterRpcMethod("push_profile", base::Bind(&PushProfile)); RegisterRpcMethod("pop_profile", base::Bind(&PopProfile)); RegisterRpcMethod("clean_profiles", base::Bind(&CleanProfiles)); RegisterRpcMethod("configure_service_by_guid", base::Bind(&ConfigureServiceByGuid)); RegisterRpcMethod("configure_wifi_service", base::Bind(&ConfigureWifiService)); RegisterRpcMethod("connect_wifi", base::Bind(&ConnectWifi)); RegisterRpcMethod("delete_entries_for_ssid", base::Bind(&DeleteEntriesForSsid)); RegisterRpcMethod("init_test_network_state", base::Bind(&InitTestNetworkState)); RegisterRpcMethod("list_controlled_wifi_interfaces", base::Bind(&ListControlledWifiInterfaces)); RegisterRpcMethod("disconnect", base::Bind(&Disconnect)); RegisterRpcMethod("wait_for_service_states", base::Bind(&WaitForServiceStates)); RegisterRpcMethod("get_service_order", base::Bind(&GetServiceOrder)); RegisterRpcMethod("set_service_order", base::Bind(&SetServiceOrder)); RegisterRpcMethod("get_service_properties", base::Bind(&GetServiceProperties)); RegisterRpcMethod("get_active_wifi_SSIDs", base::Bind(&GetActiveWifiSsids)); RegisterRpcMethod("set_sched_scan", base::Bind(&SetSchedScan)); RegisterRpcMethod("get_dbus_property_on_device", base::Bind(&GetDbusPropertyOnDevice)); RegisterRpcMethod("set_dbus_property_on_device", base::Bind(&SetDbusPropertyOnDevice)); RegisterRpcMethod("request_roam_dbus", base::Bind(&RequestRoamDbus)); RegisterRpcMethod("set_device_enabled", base::Bind(&SetDeviceEnabled)); RegisterRpcMethod("discover_tdls_link", base::Bind(&DiscoverTdlsLink)); RegisterRpcMethod("establish_tdls_link", base::Bind(&EstablishTdlsLink)); RegisterRpcMethod("query_tdls_link", base::Bind(&QueryTdlsLink)); RegisterRpcMethod("add_wake_packet_source", base::Bind(&AddWakePacketSource)); RegisterRpcMethod("remove_wake_packet_source", base::Bind(&RemoveWakePacketSource)); RegisterRpcMethod("remove_all_wake_packet_sources", base::Bind(&RemoveAllWakePacketSources)); RegisterRpcMethod("sync_time_to", base::Bind(&SyncTimeTo)); RegisterRpcMethod("request_roam", base::Bind(&NotImplementedRpcMethod)); RegisterRpcMethod("enable_ui", base::Bind(&NotImplementedRpcMethod)); RegisterRpcMethod("do_suspend", base::Bind(&NotImplementedRpcMethod)); RegisterRpcMethod("do_suspend_bg", base::Bind(&NotImplementedRpcMethod)); RegisterRpcMethod("clear_supplicant_blacklist", base::Bind(&NotImplementedRpcMethod)); RegisterRpcMethod("ready", base::Bind(&NotImplementedRpcMethod)); XmlRpc::XmlRpcServer::work(-1.0); }
33.611498
82
0.742445
[ "vector" ]
4ddd609801e13f73db298ef1b5b5ed82916f74ae
25,226
cc
C++
chrome/browser/chromeos/policy/handlers/minimum_version_policy_handler.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/browser/chromeos/policy/handlers/minimum_version_policy_handler.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/browser/chromeos/policy/handlers/minimum_version_policy_handler.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/policy/handlers/minimum_version_policy_handler.h" #include <algorithm> #include <string> #include <utility> #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" #include "ash/public/cpp/system_tray.h" #include "base/bind.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/numerics/safe_conversions.h" #include "base/time/default_clock.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/ash/notifications/update_required_notification.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/policy/core/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/handlers/minimum_version_policy_handler_delegate_impl.h" #include "chrome/browser/ui/ash/system_tray_client_impl.h" #include "chrome/browser/upgrade_detector/build_state.h" #include "chrome/browser/upgrade_detector/upgrade_detector.h" #include "chrome/common/pref_names.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/settings/cros_settings_provider.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "ui/chromeos/devicetype_utils.h" using MinimumVersionRequirement = policy::MinimumVersionPolicyHandler::MinimumVersionRequirement; namespace policy { namespace { const int kOneWeekEolNotificationInDays = 7; PrefService* local_state() { return g_browser_process->local_state(); } MinimumVersionPolicyHandler::NetworkStatus GetCurrentNetworkStatus() { chromeos::NetworkStateHandler* network_state_handler = chromeos::NetworkHandler::Get()->network_state_handler(); const chromeos::NetworkState* current_network = network_state_handler->DefaultNetwork(); if (!current_network || !current_network->IsConnectedState()) return MinimumVersionPolicyHandler::NetworkStatus::kOffline; if (network_state_handler->default_network_is_metered()) return MinimumVersionPolicyHandler::NetworkStatus::kMetered; return MinimumVersionPolicyHandler::NetworkStatus::kAllowed; } void OpenNetworkSettings() { ash::SystemTray::Get()->ShowNetworkDetailedViewBubble(); } void OpenEnterpriseInfoPage() { SystemTrayClientImpl::Get()->ShowEnterpriseInfo(); } std::string GetEnterpriseManager() { return g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetEnterpriseDomainManager(); } BuildState* GetBuildState() { return g_browser_process->GetBuildState(); } int GetDaysRounded(base::TimeDelta time) { return base::ClampRound(time / base::TimeDelta::FromDays(1)); } chromeos::UpdateEngineClient* GetUpdateEngineClient() { return chromeos::DBusThreadManager::Get()->GetUpdateEngineClient(); } // Overrides the relaunch notification style to required and configures the // relaunch deadline according to the deadline. void OverrideRelaunchNotification(base::Time deadline) { UpgradeDetector* upgrade_detector = UpgradeDetector::GetInstance(); upgrade_detector->OverrideRelaunchNotificationToRequired(true); upgrade_detector->OverrideHighAnnoyanceDeadline(deadline); } // Resets the overridden relaunch notification style and deadline. void ResetRelaunchNotification() { UpgradeDetector* upgrade_detector = UpgradeDetector::GetInstance(); upgrade_detector->ResetOverriddenDeadline(); upgrade_detector->OverrideRelaunchNotificationToRequired(false); } } // namespace const char MinimumVersionPolicyHandler::kRequirements[] = "requirements"; const char MinimumVersionPolicyHandler::kChromeOsVersion[] = "chromeos_version"; const char MinimumVersionPolicyHandler::kWarningPeriod[] = "warning_period"; const char MinimumVersionPolicyHandler::kEolWarningPeriod[] = "aue_warning_period"; const char MinimumVersionPolicyHandler::kUnmanagedUserRestricted[] = "unmanaged_user_restricted"; MinimumVersionRequirement::MinimumVersionRequirement( const base::Version version, const base::TimeDelta warning, const base::TimeDelta eol_warning) : minimum_version_(version), warning_time_(warning), eol_warning_time_(eol_warning) {} std::unique_ptr<MinimumVersionRequirement> MinimumVersionRequirement::CreateInstanceIfValid( const base::DictionaryValue* dict) { const std::string* version = dict->FindStringKey(kChromeOsVersion); if (!version) return nullptr; base::Version minimum_version(*version); if (!minimum_version.IsValid()) return nullptr; auto warning = dict->FindIntKey(kWarningPeriod); base::TimeDelta warning_time = base::TimeDelta::FromDays(warning.has_value() ? warning.value() : 0); auto eol_warning = dict->FindIntKey(kEolWarningPeriod); base::TimeDelta eol_warning_time = base::TimeDelta::FromDays( eol_warning.has_value() ? eol_warning.value() : 0); return std::make_unique<MinimumVersionRequirement>( minimum_version, warning_time, eol_warning_time); } int MinimumVersionRequirement::Compare( const MinimumVersionRequirement* other) const { const int version_compare = version().CompareTo(other->version()); if (version_compare != 0) return version_compare; if (warning() != other->warning()) return (warning() > other->warning() ? 1 : -1); if (eol_warning() != other->eol_warning()) return (eol_warning() > other->eol_warning() ? 1 : -1); return 0; } MinimumVersionPolicyHandler::MinimumVersionPolicyHandler( Delegate* delegate, ash::CrosSettings* cros_settings) : delegate_(delegate), cros_settings_(cros_settings), clock_(base::DefaultClock::GetInstance()) { policy_subscription_ = cros_settings_->AddSettingsObserver( chromeos::kDeviceMinimumVersion, base::BindRepeating(&MinimumVersionPolicyHandler::OnPolicyChanged, weak_factory_.GetWeakPtr())); // Fire it once so we're sure we get an invocation on startup. OnPolicyChanged(); } MinimumVersionPolicyHandler::~MinimumVersionPolicyHandler() { GetBuildState()->RemoveObserver(this); StopObservingNetwork(); GetUpdateEngineClient()->RemoveObserver(this); } void MinimumVersionPolicyHandler::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void MinimumVersionPolicyHandler::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } bool MinimumVersionPolicyHandler::CurrentVersionSatisfies( const MinimumVersionRequirement& requirement) const { base::Version platform_version(delegate_->GetCurrentVersion()); if (platform_version.IsValid()) return delegate_->GetCurrentVersion().CompareTo(requirement.version()) >= 0; return true; } bool MinimumVersionPolicyHandler::IsPolicyRestrictionAppliedForUser() const { return delegate_->IsUserEnterpriseManaged() || unmanaged_user_restricted_; } // static void MinimumVersionPolicyHandler::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterTimePref(prefs::kUpdateRequiredTimerStartTime, base::Time()); registry->RegisterTimeDeltaPref(prefs::kUpdateRequiredWarningPeriod, base::TimeDelta()); } bool MinimumVersionPolicyHandler::ShouldShowUpdateRequiredEolBanner() const { return !RequirementsAreSatisfied() && IsPolicyRestrictionAppliedForUser() && eol_reached_; } bool MinimumVersionPolicyHandler::IsDeadlineTimerRunningForTesting() const { return update_required_deadline_timer_.IsRunning(); } bool MinimumVersionPolicyHandler::IsPolicyApplicable() { bool device_managed = delegate_->IsDeviceEnterpriseManaged(); bool is_kiosk = delegate_->IsKioskMode(); return device_managed && !is_kiosk; } void MinimumVersionPolicyHandler::OnPolicyChanged() { chromeos::CrosSettingsProvider::TrustedStatus status = cros_settings_->PrepareTrustedValues( base::BindOnce(&MinimumVersionPolicyHandler::OnPolicyChanged, weak_factory_.GetWeakPtr())); if (status != chromeos::CrosSettingsProvider::TRUSTED || !IsPolicyApplicable() || !chromeos::features::IsMinimumChromeVersionEnabled()) { VLOG(1) << "Ignore policy change - policy is not applicable or settings " "are not trusted."; return; } const base::DictionaryValue* policy_value; if (!cros_settings_->GetDictionary(chromeos::kDeviceMinimumVersion, &policy_value)) { VLOG(1) << "Revoke policy - policy is unset or value is incorrect."; HandleUpdateNotRequired(); return; } const base::Value* entries = policy_value->FindListKey(kRequirements); if (!entries || entries->GetList().empty()) { VLOG(1) << "Revoke policy - empty policy requirements."; HandleUpdateNotRequired(); return; } auto restricted = policy_value->FindBoolKey(kUnmanagedUserRestricted); unmanaged_user_restricted_ = restricted.value_or(false); std::vector<std::unique_ptr<MinimumVersionRequirement>> configs; for (const auto& item : entries->GetList()) { const base::DictionaryValue* dict; if (item.GetAsDictionary(&dict)) { std::unique_ptr<MinimumVersionRequirement> instance = MinimumVersionRequirement::CreateInstanceIfValid(dict); if (instance) configs.push_back(std::move(instance)); } } // Select the strongest config whose requirements are not satisfied by the // current version. The strongest config is chosen as the one whose minimum // required version is greater and closest to the current version. In case of // conflict. preference is given to the one with lesser warning time or eol // warning time. int strongest_config_idx = -1; std::vector<std::unique_ptr<MinimumVersionRequirement>> update_required_configs; for (unsigned int i = 0; i < configs.size(); i++) { MinimumVersionRequirement* item = configs[i].get(); if (!CurrentVersionSatisfies(*item) && (strongest_config_idx == -1 || item->Compare(configs[strongest_config_idx].get()) < 0)) strongest_config_idx = i; } if (strongest_config_idx != -1) { // Update is required if at least one config exists whose requirements are // not satisfied by the current version. std::unique_ptr<MinimumVersionRequirement> strongest_config = std::move(configs[strongest_config_idx]); if (!state_ || state_->Compare(strongest_config.get()) != 0) { state_ = std::move(strongest_config); FetchEolInfo(); } } else { // Update is not required as the requirements of all of the configs in the // policy are satisfied by the current Chrome OS version. We could also // reach here at the time of login if the device was rebooted to apply the // downloaded update, in which case it is needed to reset the local state. HandleUpdateNotRequired(); } } void MinimumVersionPolicyHandler::HandleUpdateNotRequired() { VLOG(2) << "Update is not required."; // Reset the state including any running timers. Reset(); // Hide update required screen if it is visible and switch back to the login // screen. if (delegate_->IsLoginSessionState()) delegate_->HideUpdateRequiredScreenIfShown(); ResetRelaunchNotification(); } void MinimumVersionPolicyHandler::Reset() { deadline_reached_ = false; eol_reached_ = false; update_required_deadline_ = base::Time(); update_required_time_ = base::Time(); update_required_deadline_timer_.Stop(); notification_timer_.Stop(); GetBuildState()->RemoveObserver(this); state_.reset(); HideNotification(); notification_handler_.reset(); ResetLocalState(); StopObservingNetwork(); } void MinimumVersionPolicyHandler::ResetOnUpdateCompleted() { update_required_deadline_timer_.Stop(); notification_timer_.Stop(); GetBuildState()->RemoveObserver(this); HideNotification(); notification_handler_.reset(); } void MinimumVersionPolicyHandler::FetchEolInfo() { // Return if update required state is null meaning all requirements are // satisfied. if (!state_) return; update_required_time_ = clock_->Now(); // Request the End of Life (Auto Update Expiration) status. GetUpdateEngineClient()->GetEolInfo( base::BindOnce(&MinimumVersionPolicyHandler::OnFetchEolInfo, weak_factory_.GetWeakPtr())); } void MinimumVersionPolicyHandler::OnFetchEolInfo( const chromeos::UpdateEngineClient::EolInfo info) { if (!chromeos::switches::IsAueReachedForUpdateRequiredForTest() && (info.eol_date.is_null() || info.eol_date > update_required_time_)) { // End of life is not reached. Start update with |warning_time_|. eol_reached_ = false; HandleUpdateRequired(state_->warning()); } else { // End of life is reached. Start update with |eol_warning_time_|. eol_reached_ = true; HandleUpdateRequired(state_->eol_warning()); } if (!fetch_eol_callback_.is_null()) std::move(fetch_eol_callback_).Run(); } void MinimumVersionPolicyHandler::HandleUpdateRequired( base::TimeDelta warning_time) { const base::Time stored_timer_start_time = local_state()->GetTime(prefs::kUpdateRequiredTimerStartTime); const base::TimeDelta stored_warning_time = local_state()->GetTimeDelta(prefs::kUpdateRequiredWarningPeriod); base::Time previous_deadline = stored_timer_start_time + stored_warning_time; // If update is already required, use the existing timer start time to // calculate the new deadline. Else use |update_required_time_|. Do not reduce // the warning time if policy is already applied. if (stored_timer_start_time.is_null()) { update_required_deadline_ = update_required_time_ + warning_time; } else { update_required_deadline_ = stored_timer_start_time + std::max(stored_warning_time, warning_time); } VLOG(1) << "Update is required with " << "update required time " << update_required_time_ << " warning time " << warning_time << " and update required deadline " << update_required_deadline_; const bool deadline_reached = update_required_deadline_ <= update_required_time_; if (deadline_reached) { // As per the policy, the deadline for the user cannot reduce. // This case can be encountered when :- // a) Update was not required before and now critical update is required. // b) Update was required and warning time has expired when device is // rebooted. OnDeadlineReached(); return; } // Need to start the timer even if the deadline is same as the previous one to // handle the case of Chrome reboot. if (update_required_deadline_timer_.IsRunning() && update_required_deadline_timer_.desired_run_time() == update_required_deadline_) { DLOG(WARNING) << "Deadline is same as previous and timer is running."; return; } // This case can be encountered when :- // a) Update was not required before and now update is required with a // warning time. b) Policy has been updated with new values and update is // still required. // Hide update required screen if it is shown on the login screen. if (delegate_->IsLoginSessionState()) delegate_->HideUpdateRequiredScreenIfShown(); // The |deadline| can only be equal to or greater than the // |previous_deadline|. No need to update the local state if the deadline has // not been extended. if (update_required_deadline_ > previous_deadline) UpdateLocalState(warning_time); // The device has already downloaded the update in-session and waiting for // reboot to apply it. if (GetBuildState()->update_type() == BuildState::UpdateType::kNormalUpdate) { OverrideRelaunchNotification(update_required_deadline_); DLOG(WARNING) << "Update is already installed."; return; } StartDeadlineTimer(update_required_deadline_); if (!eol_reached_) StartObservingUpdate(); ShowAndScheduleNotification(update_required_deadline_); } void MinimumVersionPolicyHandler::ResetLocalState() { local_state()->ClearPref(prefs::kUpdateRequiredTimerStartTime); local_state()->ClearPref(prefs::kUpdateRequiredWarningPeriod); } void MinimumVersionPolicyHandler::UpdateLocalState( base::TimeDelta warning_time) { base::Time timer_start_time = local_state()->GetTime(prefs::kUpdateRequiredTimerStartTime); if (timer_start_time.is_null()) { local_state()->SetTime(prefs::kUpdateRequiredTimerStartTime, update_required_time_); } local_state()->SetTimeDelta(prefs::kUpdateRequiredWarningPeriod, warning_time); local_state()->CommitPendingWrite(); } void MinimumVersionPolicyHandler::StartDeadlineTimer(base::Time deadline) { // Start the timer to expire when deadline is reached and the device is not // updated to meet the policy requirements. update_required_deadline_timer_.Start( FROM_HERE, deadline, base::BindOnce(&MinimumVersionPolicyHandler::OnDeadlineReached, weak_factory_.GetWeakPtr())); } void MinimumVersionPolicyHandler::StartObservingUpdate() { auto* build_state = GetBuildState(); if (!build_state->HasObserver(this)) build_state->AddObserver(this); } absl::optional<int> MinimumVersionPolicyHandler::GetTimeRemainingInDays() { const base::Time now = clock_->Now(); if (!state_ || update_required_deadline_ <= now) return absl::nullopt; base::TimeDelta time_remaining = update_required_deadline_ - now; return GetDaysRounded(time_remaining); } void MinimumVersionPolicyHandler::MaybeShowNotificationOnLogin() { // |days| could be null if |update_required_deadline_timer_| expired while // login was in progress, else we would have shown the update required screen // at startup. absl::optional<int> days = GetTimeRemainingInDays(); if (days && days.value() <= 1) MaybeShowNotification(base::TimeDelta::FromDays(days.value())); } void MinimumVersionPolicyHandler::MaybeShowNotification( base::TimeDelta warning) { const NetworkStatus status = GetCurrentNetworkStatus(); if ((!eol_reached_ && status == NetworkStatus::kAllowed) || !delegate_->IsUserLoggedIn() || !IsPolicyRestrictionAppliedForUser()) { return; } if (!notification_handler_) { notification_handler_ = std::make_unique<ash::UpdateRequiredNotification>(); } NotificationType type = NotificationType::kNoConnection; base::OnceClosure button_click_callback; std::string manager = GetEnterpriseManager(); std::u16string device_type = ui::GetChromeOSDeviceName(); auto close_callback = base::BindOnce(&MinimumVersionPolicyHandler::StopObservingNetwork, weak_factory_.GetWeakPtr()); if (eol_reached_) { VLOG(2) << "Showing end of life notification."; type = NotificationType::kEolReached; button_click_callback = base::BindOnce(&OpenEnterpriseInfoPage); } else if (status == NetworkStatus::kMetered) { VLOG(2) << "Showing metered network notification."; type = NotificationType::kMeteredConnection; button_click_callback = base::BindOnce( &MinimumVersionPolicyHandler::UpdateOverMeteredPermssionGranted, weak_factory_.GetWeakPtr()); } else if (status == NetworkStatus::kOffline) { VLOG(2) << "Showing no network notification."; button_click_callback = base::BindOnce(&OpenNetworkSettings); } else { NOTREACHED(); return; } notification_handler_->Show(type, warning, manager, device_type, std::move(button_click_callback), std::move(close_callback)); if (!eol_reached_) { chromeos::NetworkStateHandler* network_state_handler = chromeos::NetworkHandler::Get()->network_state_handler(); if (!network_state_handler->HasObserver(this)) network_state_handler->AddObserver(this, FROM_HERE); } } void MinimumVersionPolicyHandler::ShowAndScheduleNotification( base::Time deadline) { const base::Time now = clock_->Now(); if (deadline <= now) return; base::Time expiry; base::TimeDelta time_remaining = deadline - now; int days_remaining = GetDaysRounded(time_remaining); // Network limitation notifications are shown when policy is received and on // the last day. End of life notifications are shown when policy is received, // one week before EOL and on the last day. No need to schedule a notification // if it is already the last day. if (eol_reached_ && days_remaining > kOneWeekEolNotificationInDays) { expiry = deadline - base::TimeDelta::FromDays(kOneWeekEolNotificationInDays); } else if (days_remaining > 1) { expiry = deadline - base::TimeDelta::FromDays(1); } VLOG(2) << "Next notification scheduled for " << expiry; MaybeShowNotification(base::TimeDelta::FromDays(days_remaining)); if (!expiry.is_null()) { notification_timer_.Start( FROM_HERE, expiry, base::BindOnce( &MinimumVersionPolicyHandler::ShowAndScheduleNotification, weak_factory_.GetWeakPtr(), deadline)); } } void MinimumVersionPolicyHandler::OnUpdate(const BuildState* build_state) { // If the device has been successfully updated, the relaunch notifications // will reboot it for applying the updates. VLOG(1) << "Update installed successfully at " << clock_->Now() << " with deadline " << update_required_deadline_; GetUpdateEngineClient()->RemoveObserver(this); if (build_state->update_type() == BuildState::UpdateType::kNormalUpdate) { ResetOnUpdateCompleted(); OverrideRelaunchNotification(update_required_deadline_); } } void MinimumVersionPolicyHandler::HideNotification() const { if (notification_handler_) notification_handler_->Hide(); } void MinimumVersionPolicyHandler::DefaultNetworkChanged( const chromeos::NetworkState* network) { // Close notification if network has switched to one that allows updates. const NetworkStatus status = GetCurrentNetworkStatus(); if (status == NetworkStatus::kAllowed && notification_handler_) { HideNotification(); } } void MinimumVersionPolicyHandler::StopObservingNetwork() { if (!chromeos::NetworkHandler::IsInitialized()) return; chromeos::NetworkStateHandler* network_state_handler = chromeos::NetworkHandler::Get()->network_state_handler(); network_state_handler->RemoveObserver(this, FROM_HERE); } void MinimumVersionPolicyHandler::UpdateOverMeteredPermssionGranted() { VLOG(1) << "Permission for update over metered network granted."; chromeos::UpdateEngineClient* const update_engine_client = GetUpdateEngineClient(); if (!update_engine_client->HasObserver(this)) update_engine_client->AddObserver(this); update_engine_client->RequestUpdateCheck( base::BindOnce(&MinimumVersionPolicyHandler::OnUpdateCheckStarted, weak_factory_.GetWeakPtr())); } void MinimumVersionPolicyHandler::OnUpdateCheckStarted( chromeos::UpdateEngineClient::UpdateCheckResult result) { VLOG(1) << "Update check started."; if (result != chromeos::UpdateEngineClient::UPDATE_RESULT_SUCCESS) GetUpdateEngineClient()->RemoveObserver(this); } void MinimumVersionPolicyHandler::UpdateStatusChanged( const update_engine::StatusResult& status) { if (status.current_operation() == update_engine::Operation::NEED_PERMISSION_TO_UPDATE) { GetUpdateEngineClient()->SetUpdateOverCellularOneTimePermission( status.new_version(), status.new_size(), base::BindOnce(&MinimumVersionPolicyHandler:: OnSetUpdateOverCellularOneTimePermission, weak_factory_.GetWeakPtr())); } } void MinimumVersionPolicyHandler::OnSetUpdateOverCellularOneTimePermission( bool success) { if (success) UpdateOverMeteredPermssionGranted(); else GetUpdateEngineClient()->RemoveObserver(this); } void MinimumVersionPolicyHandler::OnDeadlineReached() { deadline_reached_ = true; if (delegate_->IsLoginSessionState() && !delegate_->IsLoginInProgress()) { // Show update required screen over the login screen. delegate_->ShowUpdateRequiredScreen(); } else if (delegate_->IsUserLoggedIn() && IsPolicyRestrictionAppliedForUser()) { // Terminate the current user session to show update required // screen on the login screen if the user is managed or // |unmanaged_user_restricted_| is set to true. delegate_->RestartToLoginScreen(); } // No action is required if - // 1) The user signed in is not managed. Once the un-managed user signs out or // the device is rebooted, the policy handler will be called again to show the // update required screen if required. // 2) Login is in progress. This would be handled in-session once user logs // in, the user would be logged out and update required screen is shown. // 3) Device has just been enrolled. The login screen would check and show the // update required screen. } } // namespace policy
38.690184
97
0.741378
[ "vector" ]
4e2878293cacab9613385ca7cf2377c9387784c7
4,097
cpp
C++
experimental/benchmarks/benchmarks/cache/benchmark_structure_and_array.cpp
Dllieu/experimental
05a32a786d541b5560f713e2cf87e147142999cb
[ "MIT" ]
null
null
null
experimental/benchmarks/benchmarks/cache/benchmark_structure_and_array.cpp
Dllieu/experimental
05a32a786d541b5560f713e2cf87e147142999cb
[ "MIT" ]
26
2017-10-10T18:02:16.000Z
2019-08-12T03:06:39.000Z
experimental/benchmarks/benchmarks/cache/benchmark_structure_and_array.cpp
Dllieu/experimental
05a32a786d541b5560f713e2cf87e147142999cb
[ "MIT" ]
null
null
null
#include <algorithm> #include <benchmark/benchmark.h> #include <limits> #include <random> #include <utils/cache_information.h> namespace { template <typename F> void RunBenchmark(benchmark::State& iState, F&& iFunctor) { std::size_t size = iState.range(0); for ([[maybe_unused]] auto handler : iState) { std::size_t n = 0; for (std::size_t i = 0; i < size; ++i) { benchmark::DoNotOptimize(n += iFunctor(i)); } } } void CacheStructureAndArray_ArrayOfStructure(benchmark::State& iState) { struct Structure { Structure() : m_X(0) , m_Y(0) , m_Z(0) { } std::int64_t m_X; std::int64_t m_Y; std::int64_t m_Z; }; std::vector<Structure> arrayOfStructure(iState.range(0)); RunBenchmark(iState, [&](std::size_t i) { return arrayOfStructure[i].m_X + arrayOfStructure[i].m_Y + arrayOfStructure[i].m_Z; }); } // Half ot the fetched data is wasted due to the unused members void CacheStructureAndArray_ArrayOfStructureWithUnusedMembers(benchmark::State& iState) { struct StructureWithUnusedMembers { StructureWithUnusedMembers() : m_X(0) , m_Y(0) , m_Z(0) , m_DX(0) , m_DY(0) , m_DZ(0) { } std::int64_t m_X; std::int64_t m_Y; std::int64_t m_Z; std::int64_t m_DX; std::int64_t m_DY; std::int64_t m_DZ; }; std::vector<StructureWithUnusedMembers> arrayOfStructure(iState.range(0)); RunBenchmark(iState, [&](std::size_t i) { return arrayOfStructure[i].m_X + arrayOfStructure[i].m_Y + arrayOfStructure[i].m_Z; }); } void CacheStructureAndArray_StructureOfArrays(benchmark::State& iState) { struct StructureOfArrays { explicit StructureOfArrays(std::size_t n) : m_X(n) , m_Y(n) , m_Z(n) { } std::vector<std::int64_t> m_X; std::vector<std::int64_t> m_Y; std::vector<std::int64_t> m_Z; } structureOfArrays(iState.range(0)); RunBenchmark(iState, [&](std::size_t i) { return structureOfArrays.m_X[i] + structureOfArrays.m_Y[i] + structureOfArrays.m_Z[i]; }); } // Unused member do not affect the fetching void CacheStructureAndArray_StructureOfArraysWithUnusedMembers(benchmark::State& iState) { struct StructureOfArraysWithUnusedMembers { explicit StructureOfArraysWithUnusedMembers(std::size_t n) : m_X(n) , m_Y(n) , m_Z(n) , m_DX(n) , m_DY(n) , m_DZ(n) { } std::vector<std::int64_t> m_X; std::vector<std::int64_t> m_Y; std::vector<std::int64_t> m_Z; std::vector<std::int64_t> m_DX; std::vector<std::int64_t> m_DY; std::vector<std::int64_t> m_DZ; } structureOfArrays(iState.range(0)); RunBenchmark(iState, [&](std::size_t i) { return structureOfArrays.m_X[i] + structureOfArrays.m_Y[i] + structureOfArrays.m_Z[i]; }); } void BenchmarkArguments(benchmark::internal::Benchmark* iBenchmark) { for (std::size_t i = 2_KB; i <= 40_KB; i += 2_KB) { iBenchmark->Arg(i); } } } BENCHMARK(CacheStructureAndArray_ArrayOfStructure)->Apply(BenchmarkArguments); // NOLINT BENCHMARK(CacheStructureAndArray_ArrayOfStructureWithUnusedMembers)->Apply(BenchmarkArguments); // NOLINT BENCHMARK(CacheStructureAndArray_StructureOfArrays)->Apply(BenchmarkArguments); // NOLINT BENCHMARK(CacheStructureAndArray_StructureOfArraysWithUnusedMembers)->Apply(BenchmarkArguments); // NOLINT
32.007813
140
0.557481
[ "vector" ]
4e2a73384060fe2a5c33acfc5d57639c35f58272
818
hpp
C++
lib/include/Room.hpp
glbwsk/oop
7856a909bfdd197dc13c0f6945ef9c6e00aaa889
[ "MIT" ]
1
2020-07-02T17:16:29.000Z
2020-07-02T17:16:29.000Z
lib/include/Room.hpp
glbwsk/oop
7856a909bfdd197dc13c0f6945ef9c6e00aaa889
[ "MIT" ]
null
null
null
lib/include/Room.hpp
glbwsk/oop
7856a909bfdd197dc13c0f6945ef9c6e00aaa889
[ "MIT" ]
1
2021-05-28T13:13:19.000Z
2021-05-28T13:13:19.000Z
#ifndef ROOM_HPP #define ROOM_HPP #include "Date.hpp" #include "Equipment.hpp" #include <vector> #include <memory> class Room { public: Room( int number = 0, int floorNumber = 0, int pricePerDay = 100 ); virtual ~Room() = default; // getters & setters int getNumber(); void setNumber( int val ); int getPricePerDay(); void setPricePerDay( int val ); Date getDateCleaned(); void setDateCleaned( Date val ); std::vector<std::shared_ptr<Equipment>>& getEquipment(); void setFloorNumber( int floorNumber ); int getFloorNumber(); protected: private: int number; int pricePerDay; Date dateCleaned; std::vector<std::shared_ptr<Equipment>> equipment; int floorNumber; }; #endif // ROOM_HPP
19.95122
61
0.621027
[ "vector" ]
4e2e1292358d6294ff8cced244d640c8d1ae5ce4
77,131
cpp
C++
Source/Services/Social/Manager/social_graph.cpp
KevinAsgari/xbox-live-api
ffd23ba0a9f93790afd67de222011be0c2147a29
[ "MIT" ]
null
null
null
Source/Services/Social/Manager/social_graph.cpp
KevinAsgari/xbox-live-api
ffd23ba0a9f93790afd67de222011be0c2147a29
[ "MIT" ]
null
null
null
Source/Services/Social/Manager/social_graph.cpp
KevinAsgari/xbox-live-api
ffd23ba0a9f93790afd67de222011be0c2147a29
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "social_manager_internal.h" #include "xsapi/services.h" #include "xsapi/system.h" #include "xsapi/presence.h" #include "xbox_live_context_impl.h" #include "system_internal.h" #include "xbox_system_factory.h" #include "social_internal.h" #include "xbox_live_app_config_internal.h" #include "presence_internal.h" using namespace xbox::services; using namespace xbox::services::system; using namespace xbox::services::presence; using namespace xbox::services::social; using namespace xbox::services::real_time_activity; using namespace Concurrency::extras; NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_MANAGER_CPP_BEGIN const std::chrono::seconds social_graph::TIME_PER_CALL_SEC = #if UNIT_TEST_SERVICES std::chrono::seconds::zero(); #else std::chrono::seconds(30); #endif const std::chrono::minutes social_graph::REFRESH_TIME_MIN = std::chrono::minutes(20); const uint32_t social_graph::NUM_EVENTS_PER_FRAME = 5; social_graph::social_graph( _In_ xbox_live_user_t user, _In_ social_manager_extra_detail_level socialManagerExtraDetailLevel, _In_ xbox_live_callback<void> graphDestructionCompleteCallback, _In_ async_queue_handle_t backgroundAsyncQueue ) : m_detailLevel(socialManagerExtraDetailLevel), m_xboxLiveContextImpl(new xbox_live_context_impl(m_user)), m_user(std::move(user)), m_graphDestructionCompleteCallback(std::move(graphDestructionCompleteCallback)), m_isInitialized(false), m_socialGraphState(social_graph_state::normal), m_stateRTAFunction(nullptr), m_perfTester("social_graph"), m_wasDisconnected(false), m_numEventsThisFrame(0), m_userAddedContext(0), m_shouldCancel(false), m_isPollingRichPresence(false), m_backgroundAsyncQueue(backgroundAsyncQueue) { m_xboxLiveContextImpl->user_context()->set_caller_context_type(caller_context_type::social_manager); m_xboxLiveContextImpl->init(); m_peoplehubService = peoplehub_service( m_xboxLiveContextImpl->user_context(), m_xboxLiveContextImpl->settings(), xbox_live_app_config_internal::get_app_config_singleton() ); LOG_DEBUG_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose, "social_graph created" ); } social_graph::~social_graph() { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_xboxLiveContextImpl->real_time_activity_service()->deactivate(); m_perfTester.start_timer("~social_graph"); try { if (m_graphDestructionCompleteCallback != nullptr) { m_graphDestructionCompleteCallback(); } } catch (...) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "Exception happened during graph destruction complete callback" ); } LOG_DEBUG_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose, "social_graph destroyed" ); m_perfTester.stop_timer("~social_graph"); } void social_graph::initialize(xbox_live_callback<xbox_live_result<void>> callback) { std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); setup_rta(); m_presenceRefreshTimer = xsapi_allocate_shared<call_buffer_timer>( [thisWeakPtr](const xsapi_internal_vector<xsapi_internal_string>& eventArgs, std::shared_ptr<call_buffer_timer_completion_context>) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->presence_timer_callback( eventArgs ); } }, TIME_PER_CALL_SEC, m_backgroundAsyncQueue ); m_presencePollingTimer = xsapi_allocate_shared<call_buffer_timer>( [thisWeakPtr](const xsapi_internal_vector<xsapi_internal_string> eventArgs, std::shared_ptr<call_buffer_timer_completion_context>) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->presence_timer_callback( eventArgs ); } }, TIME_PER_CALL_SEC, m_backgroundAsyncQueue ); m_socialGraphRefreshTimer = xsapi_allocate_shared<call_buffer_timer>( [thisWeakPtr](const xsapi_internal_vector<xsapi_internal_string> eventArgs, std::shared_ptr<call_buffer_timer_completion_context> completionContext) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->social_graph_timer_callback( eventArgs, completionContext ); } }, TIME_PER_CALL_SEC, m_backgroundAsyncQueue ); m_resyncRefreshTimer = xsapi_allocate_shared<call_buffer_timer>( [thisWeakPtr](xsapi_internal_vector<xsapi_internal_string>, std::shared_ptr<call_buffer_timer_completion_context>) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->refresh_graph(); } }, TIME_PER_CALL_SEC, m_backgroundAsyncQueue ); #if UWP_API || TV_API || UNIT_TEST_SERVICES schedule_social_graph_refresh(); #endif schedule_event_work(); m_peoplehubService.get_social_graph( #if TV_API || UNIT_TEST_SERVICES || !XSAPI_CPP utils::internal_string_from_string_t(m_xboxLiveContextImpl->user()->XboxUserId->Data()), #else utils::internal_string_from_string_t(m_xboxLiveContextImpl->user()->xbox_user_id()), #endif m_detailLevel, m_backgroundAsyncQueue, [thisWeakPtr, callback](xbox_live_result<xsapi_internal_vector<xbox_social_user>> socialUsersResult) { try { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { if (socialUsersResult.err()) { callback(xbox_live_result<void>(socialUsersResult.err(), socialUsersResult.err_message())); return; } pThis->initialize_social_buffers(socialUsersResult.payload()); auto& inactiveBufferSocialGraph = pThis->m_userBuffer.inactive_buffer()->socialUserGraph; for (auto& user : inactiveBufferSocialGraph) { if (user.second.socialUser == nullptr) continue; auto devicePresenceSubResult = pThis->m_xboxLiveContextImpl->presence_service()->subscribe_to_device_presence_change(utils::internal_string_from_string_t(user.second.socialUser->xbox_user_id())); auto titlePresenceSubResult = pThis->m_xboxLiveContextImpl->presence_service()->subscribe_to_title_presence_change( utils::internal_string_from_char_t(user.second.socialUser->xbox_user_id()), pThis->m_xboxLiveContextImpl->application_config()->title_id() ); if (devicePresenceSubResult.err() || titlePresenceSubResult.err()) { callback(xbox_live_result<void>(xbox_live_error_code::runtime_error, "subscription initialization failed")); return; } std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("sub"); pThis->m_socialUserSubscriptions[user.first].devicePresenceChangeSubscription = devicePresenceSubResult.payload(); pThis->m_socialUserSubscriptions[user.first].titlePresenceChangeSubscription = titlePresenceSubResult.payload(); pThis->m_perfTester.stop_timer("sub"); } std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("m_isInitialized"); pThis->m_isInitialized = true; pThis->m_perfTester.stop_timer("m_isInitialized"); } else { callback(xbox_live_result<void>(xbox_live_error_code::runtime_error)); return; } } catch (const std::exception& e) { LOGS_DEBUG_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose) << "Exception in get_social_graph " << e.what(); } catch (...) { LOG_DEBUG_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose, "Unknown std::exception in initialization" ); } callback(xbox_live_result<void>()); }); } const xsapi_internal_unordered_map<uint64_t, xbox_social_user_context>* social_graph::active_buffer_social_graph() { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); return &m_userBuffer.active_buffer()->socialUserGraph; } void social_graph::set_background_async_queue(async_queue_handle_t queue) { m_backgroundAsyncQueue = queue; } void social_graph::schedule_event_work() { std::weak_ptr<social_graph> thisWeak = shared_from_this(); AsyncBlock* async = new (xsapi_memory::mem_alloc(sizeof(AsyncBlock))) AsyncBlock{}; async->context = utils::store_weak_ptr(thisWeak); async->queue = m_backgroundAsyncQueue; async->callback = [](AsyncBlock* async) { auto pThis = utils::get_shared_ptr<social_graph>(async->context); if (pThis) { pThis->schedule_event_work(); } xsapi_memory::mem_free(async); }; BeginAsync(async, utils::store_weak_ptr(thisWeak), nullptr, __FUNCTION__, [](AsyncOp op, const AsyncProviderData* data) { if (op == AsyncOp_DoWork) { auto pThis = utils::get_shared_ptr<social_graph>(data->context); if (pThis) { bool hasRemainingEvent = false; do { hasRemainingEvent = pThis->do_event_work(); } while (hasRemainingEvent); } CompleteAsync(data->async, S_OK, 0); } return S_OK; }); ScheduleAsync(async, 30); } bool social_graph::do_event_work() { bool hasRemainingEvent = false; bool hasCachedEvents = false; { std::lock_guard<std::recursive_mutex> socialGraphStateLock(m_socialGraphStateMutex); { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); set_state(social_graph_state::event_processing); m_perfTester.start_timer("do_event_work: event_processing"); m_perfTester.start_timer("do_event_work: has_cached_events"); hasCachedEvents = m_isInitialized && m_userBuffer.inactive_buffer() && !m_userBuffer.inactive_buffer()->socialUserEventQueue.empty(true); m_perfTester.stop_timer("do_event_work: has_cached_events"); if (hasCachedEvents) { m_perfTester.start_timer("do_event_work: set_state"); LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "set state: event_processing" ); m_perfTester.stop_timer("do_event_work: set_state"); } m_perfTester.stop_timer("do_event_work: event_processing"); } if (hasCachedEvents) { process_cached_events(); hasRemainingEvent = true; } else if (m_isInitialized) { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("do_event_work: process_events"); set_state(social_graph_state::normal); hasRemainingEvent = process_events(); //effectively a coroutine here so that each event yields when it is done processing m_perfTester.stop_timer("do_event_work: process_events"); } else { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("set_state: normal"); set_state(social_graph_state::normal); m_perfTester.stop_timer("set_state: normal"); } } return hasRemainingEvent; } void social_graph::initialize_social_buffers( _In_ const xsapi_internal_vector<xbox_social_user>& socialUsers ) { m_userBuffer.initialize(socialUsers); } bool social_graph::is_initialized() { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); return m_isInitialized; } void social_graph::process_cached_events() { if (m_userBuffer.inactive_buffer() != nullptr) { auto inactiveBuffer = m_userBuffer.inactive_buffer(); auto& eventQueue = inactiveBuffer->socialUserEventQueue; while (!eventQueue.empty()) { auto evt = eventQueue.pop(); apply_event(evt, false); } std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); set_state(social_graph_state::normal); } } bool social_graph::process_events() { bool shouldApplyEvent = !m_unprocessedEventQueue.empty() && m_numEventsThisFrame < NUM_EVENTS_PER_FRAME; if(shouldApplyEvent) { ++m_numEventsThisFrame; auto evt = m_unprocessedEventQueue.pop(); apply_event(evt, true); m_userBuffer.add_event(evt); } return shouldApplyEvent; } void social_graph::apply_event( _In_ const unprocessed_social_event& evt, _In_ bool isFreshEvent ) { const auto& inactiveBuffer = m_userBuffer.inactive_buffer(); if (inactiveBuffer == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "In active buffer null in event processing" ); return; } social_event_type eventType = social_event_type::unknown; switch (evt.event_type()) { case unprocessed_social_event_type::users_added: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: users_added" ); apply_users_added_event(evt, inactiveBuffer, isFreshEvent); break; } case unprocessed_social_event_type::users_changed: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: users_changed" ); apply_users_change_event(evt, inactiveBuffer, isFreshEvent); break; } case unprocessed_social_event_type::users_removed: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: users_removed" ); apply_users_removed_event(evt, inactiveBuffer, eventType, isFreshEvent); break; } case unprocessed_social_event_type::device_presence_changed: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: device_presence_changed" ); apply_device_presence_changed_event(evt, inactiveBuffer, isFreshEvent, eventType); break; } case unprocessed_social_event_type::title_presence_changed: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: title_presence_changed" ); auto titlePresenceChanged = evt.title_presence_args(); auto xuid = utils::internal_string_to_uint64(titlePresenceChanged->xbox_user_id()); auto xuidIter = inactiveBuffer->socialUserGraph.find(xuid); if (xuidIter == inactiveBuffer->socialUserGraph.end() || (xuidIter != inactiveBuffer->socialUserGraph.end() && xuidIter->second.socialUser == nullptr)) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social graph: social user not found in title presence change" ); break; } auto& userPresenceRecord = inactiveBuffer->socialUserGraph.at(xuid).socialUser->m_presenceRecord; if (titlePresenceChanged->title_state() == xbox::services::presence::title_presence_state::ended) { userPresenceRecord._Remove_title( titlePresenceChanged->title_id() ); } eventType = social_event_type::presence_changed; break; } case unprocessed_social_event_type::presence_changed: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: presence_changed" ); apply_presence_changed_event(evt, inactiveBuffer, isFreshEvent); break; } case unprocessed_social_event_type::social_relationships_changed: case unprocessed_social_event_type::profiles_changed: { LOG_INFO_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::info, "Applying internal events: social_relationships_changed or profiles_changed" ); m_perfTester.start_timer("profiles_changed"); for (auto& user : evt.users_affected()) { auto userIterator = inactiveBuffer->socialUserGraph.find(user._Xbox_user_id_as_integer()); if (userIterator != inactiveBuffer->socialUserGraph.end() && userIterator->second.socialUser != nullptr) { *(userIterator->second.socialUser) = user; } } eventType = social_event_type::profiles_changed; m_perfTester.stop_timer("profiles_changed"); break; } case unprocessed_social_event_type::unknown: default: { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "unknown event in process_events" ); } } if (isFreshEvent) { m_socialEventQueue.push(evt, m_user, eventType); } } void social_graph::apply_users_added_event( _In_ const unprocessed_social_event& evt, _In_ user_buffer* inactiveBuffer, _In_ bool isFreshEvent ) { m_perfTester.start_timer("apply_users_added_event"); xsapi_internal_vector<xsapi_internal_string> usersToAdd; for (auto& user : evt.users_affected_as_string_vec()) { auto userIter = inactiveBuffer->socialUserGraph.find(utils::internal_string_to_uint64(user)); if (userIter != inactiveBuffer->socialUserGraph.end()) { ++userIter->second.refCount; } else { usersToAdd.push_back(user); } } if (usersToAdd.empty()) { invoke_callback(evt.callback, xbox_live_result<void>()); } else { auto usersAddedStruct = xsapi_allocate_shared<call_buffer_timer_completion_context>( ++m_userAddedContext, usersToAdd.size(), evt.callback ); if (isFreshEvent) { m_socialGraphRefreshTimer->fire(usersToAdd, usersAddedStruct); } for (auto& user : usersToAdd) { auto userAsInt = utils::internal_string_to_uint64(user); inactiveBuffer->socialUserGraph[userAsInt].socialUser = nullptr; inactiveBuffer->socialUserGraph[userAsInt].refCount = 1; } } m_perfTester.stop_timer("apply_users_added_event"); } void social_graph::apply_users_removed_event( _In_ const unprocessed_social_event& evt, _In_ user_buffer* inactiveBuffer, _Inout_ social_event_type& eventType, _In_ bool isFreshEvent ) { m_perfTester.start_timer("removing_users"); auto usersAffected = evt.users_to_remove(); xsapi_internal_vector<uint64_t> removeUsers; for (auto& user : usersAffected) { --inactiveBuffer->socialUserGraph[user].refCount; if (inactiveBuffer->socialUserGraph[user].refCount == 0) { if (inactiveBuffer->socialUserGraph[user].socialUser != nullptr) { removeUsers.push_back(user); } else { inactiveBuffer->socialUserGraph.erase(user); } eventType = social_event_type::users_removed_from_social_graph; } } m_userBuffer.remove_users_from_buffer(removeUsers, *inactiveBuffer); if (isFreshEvent) { unsubscribe_users(removeUsers); } m_perfTester.stop_timer("removing_users"); } void social_graph::apply_users_change_event( _In_ const unprocessed_social_event& evt, _In_ user_buffer* inactiveBuffer, _In_ bool isFreshEvent ) { m_perfTester.start_timer("apply_users_change_event"); xsapi_internal_vector<xbox_social_user> usersToAdd; xsapi_internal_vector<xbox_social_user> usersChanged; if (evt.completion_context() != nullptr) { // delay callback invocation to avoid deadlock invoke_callback(evt.completion_context()->callback, evt.error()); } auto result = evt.error(); if (result.err() != xbox_live_error_code::no_error) { m_socialEventQueue.push(evt, m_user, social_event_type::users_added_to_social_graph, evt.error()); return; } for (auto user : evt.users_affected()) { auto userIter = inactiveBuffer->socialUserGraph.find(user._Xbox_user_id_as_integer()); if (userIter != inactiveBuffer->socialUserGraph.end()) // if not found then it was deleted while the lookup was happening { if (userIter->second.socialUser == nullptr) { usersToAdd.push_back(user); } else { *userIter->second.socialUser = user; usersChanged.push_back(user); } } } if (!usersToAdd.empty()) { auto numObjects = evt.completion_context() != nullptr ? evt.completion_context()->numObjects : 0; m_userBuffer.add_users_to_buffer(usersToAdd, *inactiveBuffer, numObjects); xsapi_internal_vector<uint64_t> usersList; for (auto& user : usersToAdd) { usersList.push_back(user._Xbox_user_id_as_integer()); } if (isFreshEvent) { setup_device_and_presence_subscriptions(usersList); unprocessed_social_event internalSocialUsersAddedEvent(unprocessed_social_event_type::users_added, usersToAdd); m_socialEventQueue.push(internalSocialUsersAddedEvent, m_user, social_event_type::users_added_to_social_graph); } } if (!usersChanged.empty() && isFreshEvent) { unprocessed_social_event internalSocialProfileChangedEvent(unprocessed_social_event_type::profiles_changed, usersChanged); m_socialEventQueue.push(internalSocialProfileChangedEvent, m_user, social_event_type::profiles_changed); } m_perfTester.stop_timer("apply_users_change_event"); } void social_graph::apply_device_presence_changed_event( _In_ const unprocessed_social_event& evt, _In_ user_buffer* inactiveBuffer, _In_ bool isFreshEvent, _Inout_ social_event_type& eventType ) { m_perfTester.start_timer("apply_device_presence_changed_event"); auto devicePresenceChangedArgs = evt.device_presence_args(); auto xuid = utils::internal_string_to_uint64(devicePresenceChangedArgs->xbox_user_id()); bool fireCallbackTimer = false; auto mapIter = m_userBuffer.inactive_buffer()->socialUserGraph.find(xuid); if (mapIter != m_userBuffer.inactive_buffer()->socialUserGraph.end()) { if (mapIter->second.socialUser == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social graph: social user null in apply_device_presence_changed_event" ); return; } auto& userPresenceRecord = mapIter->second.socialUser->presence_record(); auto deviceRecordSize = userPresenceRecord.presence_title_records().size(); fireCallbackTimer = deviceRecordSize > 1 || devicePresenceChangedArgs->is_user_logged_on_device(); } else { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "device presence record received for user not in graph" ); return; } if (fireCallbackTimer && isFreshEvent) { xsapi_internal_vector<xsapi_internal_string> entryVec(1, devicePresenceChangedArgs->xbox_user_id()); m_presenceRefreshTimer->fire(entryVec); } else if (!fireCallbackTimer) { auto xuidIter = inactiveBuffer->socialUserGraph.find(xuid); if (xuidIter == inactiveBuffer->socialUserGraph.end() || (xuidIter != inactiveBuffer->socialUserGraph.end() && xuidIter->second.socialUser == nullptr)) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social graph: social user null in inactiveBuffer" ); return; } auto& userPresenceRecord = xuidIter->second.socialUser->m_presenceRecord; userPresenceRecord._Update_device( devicePresenceChangedArgs->device_type(), devicePresenceChangedArgs->is_user_logged_on_device() ); eventType = social_event_type::presence_changed; } m_perfTester.stop_timer("apply_device_presence_changed_event"); } void social_graph::apply_presence_changed_event( _In_ const unprocessed_social_event& evt, _In_ user_buffer* inactiveBuffer, _In_ bool isFreshEvent ) { m_perfTester.start_timer("apply_presence_changed_event"); xsapi_internal_vector<uint64_t> userAddedVec; auto& presenceRecords = evt.presence_records(); for (auto& presenceRecord : presenceRecords) { uint64_t index = presenceRecord._Xbox_user_id(); if (index == 0) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social_graph: Invalid user in apply_presence_changed_event" ); continue; } auto userPresenceRecordIter = inactiveBuffer->socialUserGraph.find(index); if (userPresenceRecordIter != inactiveBuffer->socialUserGraph.end()) { auto socialUser = userPresenceRecordIter->second.socialUser; if (socialUser == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social_graph: User not found in updating presence" ); continue; } auto userPresenceRecord = socialUser->presence_record(); if (userPresenceRecord._Compare(presenceRecord)) // TODO: potential optimization, limits the number of compares that can happen in a single event (i.e. if presence result has 100 record split it up into 10 events) { auto socialUserGraphUser = inactiveBuffer->socialUserGraph.at(presenceRecord._Xbox_user_id()).socialUser; if (socialUserGraphUser == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social_graph: User not found in social user graph" ); continue; } socialUserGraphUser->_Set_presence_record(presenceRecord); userAddedVec.push_back(presenceRecord._Xbox_user_id()); } } } if (isFreshEvent && !userAddedVec.empty()) { unprocessed_social_event internalPresenceChangedEvent(unprocessed_social_event_type::presence_changed, userAddedVec); m_socialEventQueue.push(internalPresenceChangedEvent, m_user, social_event_type::presence_changed); } m_perfTester.stop_timer("apply_presence_changed_event"); } void social_graph::set_state( _In_ social_graph_state socialGraphState ) { m_socialGraphState = socialGraphState; } void social_graph::setup_rta() { std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); setup_rta_subscriptions(); m_devicePresenceContext = m_xboxLiveContextImpl->presence_service()->add_device_presence_changed_handler( [thisWeakPtr](std::shared_ptr<device_presence_change_event_args_internal> eventArgs) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->handle_device_presence_change( eventArgs ); } }); m_titlePresenceContext = m_xboxLiveContextImpl->presence_service()->add_title_presence_changed_handler( [thisWeakPtr](std::shared_ptr<title_presence_change_event_args_internal> eventArgs) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->handle_title_presence_change( eventArgs ); } }); m_socialRelationshipContext = m_xboxLiveContextImpl->social_service_impl()->add_social_relationship_changed_handler( [thisWeakPtr](std::shared_ptr<social_relationship_change_event_args_internal> eventArgs) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->handle_social_relationship_change( eventArgs ); } }); } void social_graph::setup_rta_subscriptions( _In_ bool shouldReinitialize ) { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("setup_rta_subscriptions"); m_xboxLiveContextImpl->real_time_activity_service()->activate(); auto socialRelationshipChangeResult = m_xboxLiveContextImpl->social_service_impl()->subscribe_to_social_relationship_change( m_xboxLiveContextImpl->xbox_live_user_id() ); if (socialRelationshipChangeResult.err()) { LOGS_ERROR_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error) << "Social relationship change error " << socialRelationshipChangeResult.err().message() << " message: " << socialRelationshipChangeResult.err_message(); } else { m_socialRelationshipChangeSubscription = socialRelationshipChangeResult.payload(); } if (shouldReinitialize) { if (m_userBuffer.inactive_buffer() == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "Failed to reinitialize rta subs" ); return; } xsapi_internal_vector<uint64_t> users; for (auto& userPair : m_userBuffer.inactive_buffer()->socialUserGraph) { auto user = userPair.second.socialUser; if (user == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social_graph: setup_rta_subscriptions get users" ); continue; } users.push_back(user->_Xbox_user_id_as_integer()); } setup_device_and_presence_subscriptions(users); } std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); m_resyncContext = m_xboxLiveContextImpl->real_time_activity_service()->add_resync_handler( [thisWeakPtr]() { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->m_resyncRefreshTimer->fire(); } }); m_subscriptionErrorContext = m_xboxLiveContextImpl->real_time_activity_service()->add_subscription_error_handler( [thisWeakPtr](real_time_activity_subscription_error_event_args args) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->handle_rta_subscription_error(args); } }); m_rtaStateChangeContext = m_xboxLiveContextImpl->real_time_activity_service()->add_connection_state_change_handler( [thisWeakPtr](real_time_activity_connection_state args) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { pThis->handle_rta_connection_state_change(args); } }); m_perfTester.stop_timer("setup_rta_subscriptions"); } void social_graph::setup_device_and_presence_subscriptions_helper( _In_ const xsapi_internal_vector<uint64_t>& users ) { for (auto xuid : users) { xsapi_internal_stringstream str; str << xuid; auto xuidStr = str.str(); auto devicePresenceSubResult = m_xboxLiveContextImpl->presence_service()->subscribe_to_device_presence_change(xuidStr); auto titlePresenceSubResult = m_xboxLiveContextImpl->presence_service()->subscribe_to_title_presence_change( xuidStr, m_xboxLiveContextImpl->application_config()->title_id() ); if (devicePresenceSubResult.err() || titlePresenceSubResult.err()) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "presence subscription failed in social manager" ); } std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("setup_device_and_presence_subscriptions"); m_socialUserSubscriptions[xuid].devicePresenceChangeSubscription = devicePresenceSubResult.payload(); m_socialUserSubscriptions[xuid].titlePresenceChangeSubscription = titlePresenceSubResult.payload(); m_perfTester.stop_timer("setup_device_and_presence_subscriptions"); } } struct social_graph_context { social_graph_context(xsapi_internal_vector<uint64_t> _users, std::weak_ptr<social_graph> _pThis) : users(std::move(_users)), pThis(std::move(_pThis)) { } xsapi_internal_vector<uint64_t> users; std::weak_ptr<social_graph> pThis; }; void social_graph::setup_device_and_presence_subscriptions( _In_ const xsapi_internal_vector<uint64_t>& users ) { AsyncBlock* async = new (xsapi_memory::mem_alloc(sizeof(AsyncBlock))) AsyncBlock{}; async->queue = m_backgroundAsyncQueue; async->callback = [](AsyncBlock* asyncBlock) { xsapi_memory::mem_free(asyncBlock); }; auto context = utils::store_shared_ptr(xsapi_allocate_shared<social_graph_context>(users, shared_from_this())); BeginAsync(async, context, nullptr, __FUNCTION__, [](AsyncOp op, const AsyncProviderData* data) { if (op == AsyncOp_DoWork) { auto context = utils::get_shared_ptr<social_graph_context>(data->context); std::shared_ptr<social_graph> pThis(context->pThis.lock()); if (pThis != nullptr) { pThis->setup_device_and_presence_subscriptions_helper(context->users); } } return S_OK; }); ScheduleAsync(async, 0); } void social_graph::unsubscribe_users( _In_ const xsapi_internal_vector<uint64_t>& users ) { AsyncBlock* async = new (xsapi_memory::mem_alloc(sizeof(AsyncBlock))) AsyncBlock{}; async->queue = m_backgroundAsyncQueue; async->callback = [](AsyncBlock* asyncBlock) { xsapi_memory::mem_free(asyncBlock); }; auto context = utils::store_shared_ptr(xsapi_allocate_shared<social_graph_context>(users, shared_from_this())); BeginAsync(async, context, nullptr, __FUNCTION__, [](AsyncOp op, const AsyncProviderData* data) { if (op == AsyncOp_DoWork) { auto context = utils::get_shared_ptr<social_graph_context>(data->context); std::shared_ptr<social_graph> pThis(context->pThis.lock()); if (pThis != nullptr) { for (auto& user : context->users) { std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("unsubscribe_users"); auto subscriptions = pThis->m_socialUserSubscriptions[user]; pThis->m_xboxLiveContextImpl->presence_service()->unsubscribe_from_device_presence_change(subscriptions.devicePresenceChangeSubscription); pThis->m_xboxLiveContextImpl->presence_service()->unsubscribe_from_title_presence_change(subscriptions.titlePresenceChangeSubscription); pThis->m_socialUserSubscriptions.erase(user); pThis->m_perfTester.stop_timer("unsubscribe_users"); } } CompleteAsync(data->async, S_OK, 0); // Have to return E_PENDING from AsyncOp_DoWork return E_PENDING; } return S_OK; }); ScheduleAsync(async, 0); } void social_graph::refresh_graph_helper(xsapi_internal_vector<uint64_t>& userRefreshList) { auto inactiveBuffer = m_userBuffer.inactive_buffer(); if (inactiveBuffer == nullptr) { return; } for (auto& user : inactiveBuffer->socialUserGraph) { auto socialUser = user.second.socialUser; if (socialUser == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social graph: no user found in refresh_graph_helper" ); continue; } if (!socialUser->is_followed_by_caller()) { userRefreshList.push_back(user.first); } } } void social_graph::refresh_graph() { xsapi_internal_vector<uint64_t> userRefreshList; { std::lock_guard<std::recursive_mutex> socialGraphStateLock(m_socialGraphStateMutex); { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("refresh_graph"); set_state(social_graph_state::refresh); m_perfTester.stop_timer("refresh_graph"); } refresh_graph_helper(userRefreshList); { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("refresh_graph stop"); set_state(social_graph_state::normal); m_perfTester.stop_timer("rrefresh_graph stop"); } } xsapi_internal_vector<xsapi_internal_string> userRefreshListStr; for (auto& user : userRefreshList) { xsapi_internal_stringstream str; str << user; userRefreshListStr.push_back(str.str()); } m_socialGraphRefreshTimer->fire(userRefreshListStr); std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); m_peoplehubService.get_social_graph( #if TV_API || UNIT_TEST_SERVICES || !XSAPI_CPP utils::internal_string_from_string_t(m_xboxLiveContextImpl->user()->XboxUserId->Data()), #else utils::internal_string_from_string_t(m_xboxLiveContextImpl->user()->xbox_user_id()), #endif m_detailLevel, m_backgroundAsyncQueue, [thisWeakPtr](xbox_live_result<xsapi_internal_vector<xbox_social_user>> socialListResult) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { if (!socialListResult.err()) { auto& socialList = socialListResult.payload(); xsapi_internal_unordered_map<uint64_t, xbox_social_user> socialMap; for (auto& user : socialList) { socialMap[user._Xbox_user_id_as_integer()] = user; } pThis->perform_diff(socialMap); } else { LOGS_ERROR_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error) << "social_graph: refresh_graph call failed with error: " << socialListResult.err() << " " << socialListResult.err_message(); } } }); } void social_graph::perform_diff( _In_ const xsapi_internal_unordered_map<uint64_t, xbox_social_user>& xboxSocialUsers ) { std::lock_guard<std::recursive_mutex> socialGraphStateLock(m_socialGraphStateMutex); { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("set_state"); if (m_userBuffer.inactive_buffer() == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "Diff cannot happening with null buffer" ); return; } set_state(social_graph_state::diff); m_perfTester.stop_timer("set_state"); } xsapi_internal_vector<xbox_social_user> usersAddedList; xsapi_internal_vector<uint64_t> usersRemovedList; xsapi_internal_vector<social_manager_presence_record> presenceChangeList; xsapi_internal_vector<xbox_social_user> socialRelationshipChangeList; xsapi_internal_vector<xbox_social_user> profileChangeList; for (auto& currentUserPair : xboxSocialUsers) { m_perfTester.start_timer("perform_diff: start"); auto inactiveBufferUserGraph = m_userBuffer.inactive_buffer()->socialUserGraph; if (inactiveBufferUserGraph.find(currentUserPair.first) == inactiveBufferUserGraph.end()) { usersAddedList.push_back(currentUserPair.second); continue; } auto previousUser = inactiveBufferUserGraph.at(currentUserPair.first).socialUser; change_list_enum didChange = previousUser ? xbox_social_user::_Compare(*previousUser, currentUserPair.second) : (change_list_enum::presence_change | change_list_enum::profile_change | change_list_enum::social_relationship_change); if ((didChange & change_list_enum::presence_change) == change_list_enum::presence_change) { presenceChangeList.push_back(currentUserPair.second.presence_record()); } if ((didChange & change_list_enum::profile_change) == change_list_enum::profile_change) { profileChangeList.push_back(currentUserPair.second); } if ((didChange & change_list_enum::social_relationship_change) == change_list_enum::social_relationship_change) { socialRelationshipChangeList.push_back(currentUserPair.second); } } auto inactiveBufferUserGraph = m_userBuffer.inactive_buffer()->socialUserGraph; for (auto& previousUserPair : inactiveBufferUserGraph) { if (xboxSocialUsers.find(previousUserPair.first) == xboxSocialUsers.end() && (previousUserPair.second.socialUser != nullptr && previousUserPair.second.socialUser->is_following_user())) { usersRemovedList.push_back(previousUserPair.first); } } if (usersAddedList.size() > 0) { m_unprocessedEventQueue.push(unprocessed_social_event_type::users_changed, usersAddedList); } if (usersRemovedList.size() > 0) { m_unprocessedEventQueue.push(unprocessed_social_event_type::users_removed, usersRemovedList); } if (presenceChangeList.size() > 0) { m_unprocessedEventQueue.push(unprocessed_social_event_type::presence_changed, presenceChangeList); } if (profileChangeList.size() > 0) { m_unprocessedEventQueue.push(unprocessed_social_event_type::profiles_changed, profileChangeList); } if (socialRelationshipChangeList.size() > 0) { m_unprocessedEventQueue.push(unprocessed_social_event_type::social_relationships_changed, socialRelationshipChangeList); } { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("set_state normal"); set_state(social_graph_state::normal); m_perfTester.stop_timer("set_state normal"); } } uint32_t social_graph::title_id() { return m_xboxLiveContextImpl->application_config()->title_id(); } change_struct social_graph::do_work( _Inout_ xsapi_internal_vector<std::shared_ptr<social_event_internal>>& socialEvents ) { m_perfTester.start_timer("do_work"); m_perfTester.start_timer("do_work locktime"); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.stop_timer("do_work locktime"); m_numEventsThisFrame = 0; change_struct changeStruct; changeStruct.socialUsers = nullptr; m_perfTester.start_timer("social_graph_state_check"); if (m_socialGraphState == social_graph_state::normal && m_userBuffer.inactive_buffer() != nullptr && m_userBuffer.inactive_buffer()->socialUserEventQueue.empty()) { m_perfTester.start_timer("user buffer swap"); m_userBuffer.swap(); m_perfTester.stop_timer("user buffer swap"); } m_perfTester.stop_timer("social_graph_state_check"); m_perfTester.start_timer("assign active buffer"); if (m_userBuffer.active_buffer() != nullptr) { changeStruct.socialUsers = &m_userBuffer.active_buffer()->socialUserGraph; } m_perfTester.stop_timer("assign active buffer"); m_perfTester.start_timer("!m_socialEventQueue.empty()"); if (!m_socialEventQueue.empty() && m_socialGraphState == social_graph_state::normal) { m_perfTester.start_timer("do_work: social event push_back"); socialEvents.reserve(socialEvents.size() + m_socialEventQueue.social_event_list().size()); for (auto& evt : m_socialEventQueue.social_event_list()) { socialEvents.push_back(evt); } m_socialEventQueue.clear(); m_perfTester.stop_timer("do_work: social event push_back"); } m_perfTester.stop_timer("!m_socialEventQueue.empty()"); m_perfTester.stop_timer("do_work"); m_perfTester.clear(); return changeStruct; } void social_graph::social_graph_timer_callback( _In_ const xsapi_internal_vector<xsapi_internal_string>& users, _In_ std::shared_ptr<call_buffer_timer_completion_context> completionContext ) { auto stdUsers = utils::std_string_vector_from_internal_string_vector(users); std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); m_peoplehubService.get_social_graph( m_xboxLiveContextImpl->xbox_live_user_id(), m_detailLevel, users, m_backgroundAsyncQueue, [thisWeakPtr, users, completionContext](xbox_live_result<xsapi_internal_vector<xbox_social_user>> socialListResult) { try { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis) { if (!socialListResult.err()) { pThis->m_unprocessedEventQueue.push(unprocessed_social_event_type::users_changed, socialListResult.payload(), completionContext); } else { xsapi_internal_vector<xsapi_internal_string> xsapiStrVec; for (auto user : users) { xsapiStrVec.push_back(user.c_str()); } unprocessed_social_event evt(unprocessed_social_event_type::users_changed, xbox_live_result<void>(socialListResult.err(), socialListResult.err_message()), xsapiStrVec); evt.set_completion_context(completionContext); pThis->m_unprocessedEventQueue.push(evt); } } } catch (const std::exception& e) { LOGS_DEBUG_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose) << "Exception in social_graph_timer_callback " << e.what(); } catch (...) { LOG_DEBUG_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose, "Unknown std::exception in initialization"); } }); } void social_graph::schedule_social_graph_refresh() { #if UWP_API || TV_API || UNIT_TEST_SERVICES std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); AsyncBlock* async = new (xsapi_memory::mem_alloc(sizeof(AsyncBlock))) AsyncBlock{}; async->queue = m_backgroundAsyncQueue; async->context = utils::store_weak_ptr(thisWeakPtr); async->callback = [](AsyncBlock* async) { auto pThis = utils::get_shared_ptr<social_graph>(async->context); if (pThis) { pThis->schedule_social_graph_refresh(); } xsapi_memory::mem_free(async); }; BeginAsync(async, utils::store_weak_ptr(thisWeakPtr), nullptr, __FUNCTION__, [](AsyncOp op, const AsyncProviderData* data) { if (op == AsyncOp_DoWork) { try { auto pThis = utils::get_shared_ptr<social_graph>(data->context); if (pThis) { pThis->refresh_graph(); } } catch (const std::exception& e) { LOGS_DEBUG_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose) << "Exception in social_graph_refresh_callback " << e.what(); } catch (...) { LOG_DEBUG_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose, "Unknown std::exception in initialization" ); } CompleteAsync(data->async, S_OK, 0); return E_PENDING; } return S_OK; }); ScheduleAsync(async, (uint32_t)std::chrono::duration_cast<std::chrono::milliseconds>(REFRESH_TIME_MIN).count()); #endif } void social_graph::handle_device_presence_change( _In_ std::shared_ptr<device_presence_change_event_args_internal> devicePresenceChanged ) { uint64_t id = utils::internal_string_to_uint64(devicePresenceChanged->xbox_user_id()); if (id == 0) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "Invalid user" ); return; } m_unprocessedEventQueue.push(unprocessed_social_event(unprocessed_social_event_type::device_presence_changed, devicePresenceChanged)); } void social_graph::handle_title_presence_change( _In_ std::shared_ptr<xbox::services::presence::title_presence_change_event_args_internal> titlePresenceChanged ) { if (titlePresenceChanged->title_state() == title_presence_state::started) { xsapi_internal_vector<xsapi_internal_string> presenceVec(1, titlePresenceChanged->xbox_user_id()); m_presenceRefreshTimer->fire(presenceVec); } else { unprocessed_social_event titlePresenceChangeEvent(unprocessed_social_event_type::title_presence_changed, titlePresenceChanged); m_unprocessedEventQueue.push(titlePresenceChangeEvent); } } void social_graph::handle_social_relationship_change( _In_ std::shared_ptr<xbox::services::social::social_relationship_change_event_args_internal> socialRelationshipChanged ) { auto socialNotification = socialRelationshipChanged->social_notification(); if (socialNotification == social_notification_type::added) { m_unprocessedEventQueue.push(unprocessed_social_event_type::users_added, socialRelationshipChanged->xbox_user_ids()); } else if (socialNotification == social_notification_type::changed) { m_socialGraphRefreshTimer->fire(socialRelationshipChanged->xbox_user_ids()); } else if (socialNotification == social_notification_type::removed) { xsapi_internal_vector<uint64_t> xboxUserIdsAsInt; xboxUserIdsAsInt.reserve(socialRelationshipChanged->xbox_user_ids().size()); for (auto& xuid : socialRelationshipChanged->xbox_user_ids()) { uint64_t id = utils::internal_string_to_uint64(xuid); if (id == 0) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "Invalid user" ); continue; } xboxUserIdsAsInt.push_back(id); } remove_users(xboxUserIdsAsInt); } } void social_graph::handle_rta_subscription_error( _In_ xbox::services::real_time_activity::real_time_activity_subscription_error_event_args& rtaErrorEventArgs ) { LOGS_ERROR_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error) << "RTA subscription error occurred in social manager: " << rtaErrorEventArgs.err().message() << " " << rtaErrorEventArgs.err_message(); } void social_graph::handle_rta_connection_state_change( _In_ real_time_activity_connection_state rtaState ) { bool wasDisconnected = false; { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("handle_rta_connection_state_change:disconnected_check"); wasDisconnected = m_wasDisconnected; m_perfTester.stop_timer("handle_rta_connection_state_change:disconnected_check"); } if(rtaState == real_time_activity_connection_state::disconnected) { { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("handle_rta_connection_state_change: disconnected received"); m_wasDisconnected = true; m_perfTester.stop_timer("handle_rta_connection_state_change: disconnected received"); } } else if (wasDisconnected) { { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("handle_rta_connection_state_change: disconnected check false"); m_wasDisconnected = false; m_perfTester.stop_timer("handle_rta_connection_state_change: disconnected check false"); } setup_rta_subscriptions(true); } _Trigger_rta_connection_state_change_event(rtaState); } void social_graph::_Trigger_rta_connection_state_change_event( _In_ xbox::services::real_time_activity::real_time_activity_connection_state state ) { if (m_stateRTAFunction != nullptr) { m_stateRTAFunction(state); } } void social_graph::presence_timer_callback( _In_ const xsapi_internal_vector<xsapi_internal_string>& users ) { if (users.empty()) { return; } std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); m_xboxLiveContextImpl->presence_service()->get_presence_for_multiple_users( users, xsapi_internal_vector<presence_device_type>(), xsapi_internal_vector<uint32_t>(), presence_detail_level::all, false, false, m_backgroundAsyncQueue, [thisWeakPtr](xbox_live_result<xsapi_internal_vector<std::shared_ptr<presence_record_internal>>> presenceRecordsResult) { std::shared_ptr<social_graph> pThis(thisWeakPtr.lock()); if (pThis != nullptr) { if (!presenceRecordsResult.err()) { std::lock_guard<std::recursive_mutex> socialGraphStateLock(pThis->m_socialGraphStateMutex); { std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("social graph refresh state set"); if (pThis->m_userBuffer.inactive_buffer() == nullptr) { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "Cannot update presence when user buffer is null" ); return; } pThis->set_state(social_graph_state::refresh); pThis->m_perfTester.start_timer("social graph refresh state set"); } auto presenceRecordReturnVec = presenceRecordsResult.payload(); xsapi_internal_vector<social_manager_presence_record> socialManagerPresenceVec; socialManagerPresenceVec.reserve(presenceRecordReturnVec.size()); for (auto& presenceRecord : presenceRecordReturnVec) { socialManagerPresenceVec.push_back(social_manager_presence_record(presenceRecord)); } std::vector<social_manager_presence_record> presenceRecordChanges; for (auto& record : socialManagerPresenceVec) { auto previousRecordIter = pThis->m_userBuffer.inactive_buffer()->socialUserGraph.find(record._Xbox_user_id()); if (previousRecordIter == pThis->m_userBuffer.inactive_buffer()->socialUserGraph.end()) { continue; } if (previousRecordIter->second.socialUser == nullptr) { continue; } auto& previousRecord = previousRecordIter->second.socialUser->presence_record(); if (previousRecord._Compare(record)) { presenceRecordChanges.push_back(record); } } pThis->m_unprocessedEventQueue.push( unprocessed_social_event_type::presence_changed, socialManagerPresenceVec ); { std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("social graph refresh state set normal"); pThis->set_state(social_graph_state::normal); pThis->m_perfTester.stop_timer("social graph refresh state set normal"); } } else { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "social_graph: presence record update failed" ); } } }); } bool social_graph::are_events_empty() { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); m_perfTester.start_timer("are_events_empty"); auto result = m_userBuffer.user_buffer_a().socialUserEventQueue.empty() && m_userBuffer.user_buffer_b().socialUserEventQueue.empty(); m_perfTester.stop_timer("are_events_empty"); return result; } void social_graph::add_users( _In_ const xsapi_internal_vector<xsapi_internal_string>& users, _In_ xbox_live_callback<xbox_live_result<void>> callback ) { m_unprocessedEventQueue.push(unprocessed_social_event(unprocessed_social_event_type::users_added, users, callback)); // this is fine to be n-sized because it will generate 0 events } void social_graph::remove_users( _In_ const xsapi_internal_vector<uint64_t>& users ) { m_unprocessedEventQueue.push(unprocessed_social_event_type::users_removed, users); } void social_graph::schedule_presence_refresh() { #if UWP_API || TV_API || UNIT_TEST_SERVICES std::weak_ptr<social_graph> thisWeakPtr = shared_from_this(); AsyncBlock* async = new (xsapi_memory::mem_alloc(sizeof(AsyncBlock))) AsyncBlock{}; async->queue = m_backgroundAsyncQueue; async->context = utils::store_weak_ptr(thisWeakPtr); async->callback = [](AsyncBlock* async) { auto pThis = utils::get_shared_ptr<social_graph>(async->context); if (pThis && !pThis->m_shouldCancel) { pThis->schedule_presence_refresh(); } xsapi_memory::mem_free(async); }; BeginAsync(async, utils::store_weak_ptr(thisWeakPtr), nullptr, __FUNCTION__, [](AsyncOp op, const AsyncProviderData* data) { if (op == AsyncOp_DoWork) { auto pThis = utils::get_shared_ptr<social_graph>(data->context); if (pThis && !pThis->m_shouldCancel) { xsapi_internal_vector<xsapi_internal_string> userList; { std::lock_guard<std::recursive_mutex> socialGraphStateLock(pThis->m_socialGraphStateMutex); if (pThis->m_userBuffer.inactive_buffer() != nullptr) { { std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("presence refresh state set"); pThis->set_state(social_graph_state::refresh); pThis->m_perfTester.stop_timer("presence refresh state set"); } userList.reserve(pThis->m_userBuffer.inactive_buffer()->socialUserGraph.size()); for (auto& user : pThis->m_userBuffer.inactive_buffer()->socialUserGraph) { if (user.second.socialUser != nullptr) { userList.push_back(utils::internal_string_from_string_t(user.second.socialUser->xbox_user_id())); } } pThis->m_presencePollingTimer->fire(userList); { std::lock_guard<std::recursive_mutex> lock(pThis->m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(pThis->m_socialGraphPriorityMutex); pThis->m_perfTester.start_timer("presence refresh fire"); pThis->set_state(social_graph_state::normal); pThis->m_perfTester.stop_timer("presence refresh fire"); } } } } CompleteAsync(data->async, S_OK, 0); } return S_OK; }); ScheduleAsync(async, (uint32_t)std::chrono::duration_cast<std::chrono::milliseconds>(TIME_PER_CALL_SEC).count()); #endif } void social_graph::enable_rich_presence_polling( _In_ bool shouldEnablePolling ) { bool isPollingRichPresence; { std::lock_guard<std::recursive_mutex> lock(m_socialGraphMutex); std::lock_guard<std::recursive_mutex> priorityLock(m_socialGraphPriorityMutex); isPollingRichPresence = m_isPollingRichPresence; m_isPollingRichPresence = shouldEnablePolling; } if (shouldEnablePolling && !isPollingRichPresence) { { std::lock_guard<std::recursive_mutex> socialGraphStateLock(m_socialGraphStateMutex); m_shouldCancel = false; } schedule_presence_refresh(); } else if(!shouldEnablePolling) { std::lock_guard<std::recursive_mutex> socialGraphStateLock(m_socialGraphStateMutex); m_shouldCancel = true; } } void social_graph::clear_debug_counters() { } void social_graph::print_debug_info() { } const uint32_t user_buffers_holder::EXTRA_USER_FREE_SPACE = 5; user_buffers_holder::user_buffers_holder() : m_activeBuffer(nullptr), m_inactiveBuffer(nullptr) { } user_buffers_holder::~user_buffers_holder() { LOG_DEBUG_IF(social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::verbose, "destroying user buffer holder"); if (m_userBufferA.buffer != nullptr) { xsapi_memory::mem_free(m_userBufferA.buffer); } if (m_userBufferB.buffer != nullptr) { xsapi_memory::mem_free(m_userBufferB.buffer); } } void user_buffers_holder::initialize( _In_ const xsapi_internal_vector<xbox_social_user>& users ) { initialize_buffer(m_userBufferA, users); initialize_buffer(m_userBufferB, users); m_activeBuffer = &m_userBufferA; m_inactiveBuffer = &m_userBufferB; } user_buffer& user_buffers_holder::user_buffer_a() { return m_userBufferA; } user_buffer& user_buffers_holder::user_buffer_b() { return m_userBufferB; } void user_buffers_holder::initialize_buffer( _Inout_ user_buffer& userBuffer, _In_ const xsapi_internal_vector<xbox_social_user>& users, _In_ size_t freeSpaceRequired ) { auto usersSize = users.size(); buffer_init(userBuffer, users, freeSpaceRequired); initialize_users_in_map(userBuffer, usersSize, 0); } void user_buffers_holder::buffer_init( _Inout_ user_buffer& userBuffer, _In_ const xsapi_internal_vector<xbox_social_user>& users, _In_ size_t freeSpaceRequired ) { userBuffer.freeData = xsapi_internal_queue<byte*>(); size_t allocatedSize = 0; auto buffer = buffer_alloc(users.size(), allocatedSize, freeSpaceRequired); if (buffer == nullptr) { return; // return with error } userBuffer.buffer = buffer; auto usersSize = users.size(); auto socialUserSize = sizeof(xbox_social_user); for (uint32_t i = 0; i < usersSize; ++i) { auto xboxSocialUser = reinterpret_cast<xbox_social_user*>(userBuffer.buffer + (i * socialUserSize)); new (xboxSocialUser) xbox_social_user(); *xboxSocialUser = users[i]; } auto totalFreeSpace = EXTRA_USER_FREE_SPACE + freeSpaceRequired; auto startOffset = userBuffer.buffer + users.size() * socialUserSize; for (uint32_t i = 0; i < totalFreeSpace; ++i) { userBuffer.freeData.push(startOffset + i * socialUserSize); } } byte* user_buffers_holder::buffer_alloc( _In_ size_t numUsers, _Out_ size_t& allocatedSize, _In_ size_t freeSpaceRequired ) { if (numUsers == 0 && freeSpaceRequired == 0) { allocatedSize = 0; return nullptr; } auto totalFreeSpace = EXTRA_USER_FREE_SPACE + freeSpaceRequired; // gives some wiggle room with the alloc, 5 extra users can be added to graph before realloc size_t size = (numUsers + totalFreeSpace) * sizeof(xbox_social_user); auto buffer = static_cast<byte*>(xsapi_memory::mem_alloc(size)); allocatedSize = size; return buffer; } void user_buffers_holder::initialize_users_in_map( _Inout_ user_buffer& userBuffer, _In_ size_t numUsers, _In_ size_t bufferOffset ) { xsapi_internal_unordered_map<uint64_t, xbox_social_user_context>& socialUserGraph = userBuffer.socialUserGraph; auto buffer = userBuffer.buffer + bufferOffset; for (uint32_t i = 0; i < numUsers; ++i) { auto userPtr = (buffer + i * sizeof(xbox_social_user)); xbox_social_user* socialUser = reinterpret_cast<xbox_social_user*>(userPtr); auto userIter = socialUserGraph.find(socialUser->_Xbox_user_id_as_integer()); if (userIter == socialUserGraph.end()) { xbox_social_user_context userContext; userContext.refCount = 1; userContext.socialUser = socialUser; socialUserGraph[socialUser->_Xbox_user_id_as_integer()] = userContext; } else { userIter->second.socialUser = socialUser; } } } void user_buffers_holder::add_users_to_buffer( _In_ const xsapi_internal_vector<xbox_social_user>& users, _Inout_ user_buffer& userBufferInactive, _In_ size_t finalSize ) { auto totalSizeNeeded = __max(finalSize, users.size()); if (totalSizeNeeded > userBufferInactive.freeData.size()) { uint32_t size = 0; for (auto& user : userBufferInactive.socialUserGraph) { if (user.second.socialUser != nullptr) { ++size; } } xsapi_internal_vector<xbox_social_user> socialVec(size); if (size > 0) { #if _WIN32 memcpy_s(&socialVec[0], socialVec.size() * sizeof(xbox_social_user), &userBufferInactive.buffer[0], size * sizeof(xbox_social_user)); #else memcpy(&socialVec[0], &userBufferInactive.buffer[0], size * sizeof(xbox_social_user)); #endif } xsapi_memory::mem_free(userBufferInactive.buffer); initialize_buffer(userBufferInactive, socialVec, totalSizeNeeded); } for (auto& user : users) { auto freeData = userBufferInactive.freeData.front(); xbox_social_user* xboxSocialUser = reinterpret_cast<xbox_social_user*>(freeData); userBufferInactive.freeData.pop(); new (freeData) xbox_social_user(); *xboxSocialUser = user; initialize_users_in_map(userBufferInactive, 1, freeData - userBufferInactive.buffer); } } void user_buffers_holder::remove_users_from_buffer( _In_ const xsapi_internal_vector<uint64_t>& users, _Inout_ user_buffer& userBufferInactive ) { for (auto user : users) { auto xboxSocialUserContextIter = userBufferInactive.socialUserGraph.find(user); if (xboxSocialUserContextIter != userBufferInactive.socialUserGraph.end()) { auto userPtr = userBufferInactive.socialUserGraph[user].socialUser; userBufferInactive.freeData.push(reinterpret_cast<byte*>(userPtr)); userBufferInactive.socialUserGraph.erase(xboxSocialUserContextIter); } else { LOG_ERROR_IF( social_manager_internal::get_singleton_instance()->diagnostics_trace_level() >= xbox_services_diagnostics_trace_level::error, "user_buffers_holder: user not found in buffer" ); } } } void user_buffers_holder::swap() { if (m_activeBuffer == &m_userBufferA) { m_activeBuffer = &m_userBufferB; m_inactiveBuffer = &m_userBufferA; } else { m_activeBuffer = &m_userBufferA; m_inactiveBuffer = &m_userBufferB; } } user_buffer* user_buffers_holder::active_buffer() { return m_activeBuffer; } user_buffer* user_buffers_holder::inactive_buffer() { return m_inactiveBuffer; } void user_buffers_holder::add_event( _In_ const unprocessed_social_event& internalSocialEvent ) { m_activeBuffer->socialUserEventQueue.push(internalSocialEvent); } event_queue::event_queue() : m_lastKnownSize(0), m_eventState(event_state::clear) { } event_queue::event_queue( _In_ const xbox_live_user_t& user_t ) : m_user(std::move(user_t)), m_lastKnownSize(0), m_eventState(event_state::clear) { } const xsapi_internal_vector<std::shared_ptr<social_event_internal>>& event_queue::social_event_list() { std::lock_guard<std::mutex> lock(m_eventGraphMutex.get()); m_eventState = event_state::read; return m_socialEventList; } void event_queue::push( _In_ const unprocessed_social_event& socialEvent, _In_ xbox_live_user_t user, _In_ social_event_type socialEventType, _In_ xbox_live_result<void> error ) { if (socialEventType == social_event_type::unknown) { return; } xsapi_internal_vector<xbox_user_id_container> usersAffected; usersAffected.reserve(socialEvent.users_affected_as_string_vec().size()); for (auto& affectedUser : socialEvent.users_affected_as_string_vec()) { usersAffected.push_back(utils::string_t_from_internal_string(affectedUser).data()); } std::lock_guard<std::mutex> lock(m_eventGraphMutex.get()); m_socialEventList.push_back(xsapi_allocate_shared<social_event_internal>( user, socialEventType, usersAffected, nullptr, error.err(), error.err_message().data() )); m_eventState = event_state::ready_to_read; } void event_queue::clear() { std::lock_guard<std::mutex> lock(m_eventGraphMutex.get()); m_socialEventList.clear(); m_eventState = event_state::clear; } bool event_queue::empty() { std::lock_guard<std::mutex> lock(m_eventGraphMutex.get()); return m_socialEventList.empty(); } NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_MANAGER_CPP_END
37.082212
228
0.663909
[ "vector" ]
4e3025c6b94b5d1d2ee43ba605d718bdcf0b6d66
1,539
cpp
C++
980.cpp
ducthienbui97/Random-leetcode
209cbf537319875735b5dea876103f13eecef6d1
[ "MIT" ]
null
null
null
980.cpp
ducthienbui97/Random-leetcode
209cbf537319875735b5dea876103f13eecef6d1
[ "MIT" ]
null
null
null
980.cpp
ducthienbui97/Random-leetcode
209cbf537319875735b5dea876103f13eecef6d1
[ "MIT" ]
null
null
null
// Leetcode 980. Unique Paths III class Solution { public: constexpr const static int xDir[4] = {0,0,1,-1}; constexpr const static int yDir[4] = {1,-1,0,0}; int visit(int x, int y, int finishX, int finishY, int rows, int cols, int visited, int mark) { int current = 1 << (x*cols) + y; if(current & visited || !(current & mark)) { return 0; } if(x == finishX && y == finishY) { return (visited | current) == mark; } int rep = 0; for(int i = 0; i < 4; i++) { int nX = x + xDir[i]; int nY = y + yDir[i]; if(nX < 0 || nX >= rows || nY < 0 || nY >= cols) continue; rep += visit(nX, nY, finishX, finishY, rows, cols, visited | current, mark); } return rep; } int uniquePathsIII(vector<vector<int>>& grid) { int rows = grid.size(); int cols = grid[0].size(); int x,y, finishX, finishY; int mark = (1 << (rows*cols)) - 1; for(int i = 0; i< rows;i ++) { for(int j = 0; j < cols; j++) { if(grid[i][j] == 1) { x = i; y = j; } else if(grid[i][j] == 2) { finishX = i; finishY = j; } else if(grid[i][j] < 0) { mark -= (1<<(i*cols + j)); } } } return visit(x,y, finishX, finishY, rows, cols, 0, mark); } };
32.0625
98
0.411956
[ "vector" ]
4e30ee81ced49ed184e38b049e6801a116936e54
13,923
cpp
C++
Trash/sandbox/qt_webkit/qt-qtwebkit-examples/examples/webkitwidgets/embedded/anomaly/src/flickcharm.cpp
ruslankuzmin/julia
2ad5bfb9c9684b1c800e96732a9e2f1e844b856f
[ "BSD-3-Clause" ]
null
null
null
Trash/sandbox/qt_webkit/qt-qtwebkit-examples/examples/webkitwidgets/embedded/anomaly/src/flickcharm.cpp
ruslankuzmin/julia
2ad5bfb9c9684b1c800e96732a9e2f1e844b856f
[ "BSD-3-Clause" ]
null
null
null
Trash/sandbox/qt_webkit/qt-qtwebkit-examples/examples/webkitwidgets/embedded/anomaly/src/flickcharm.cpp
ruslankuzmin/julia
2ad5bfb9c9684b1c800e96732a9e2f1e844b856f
[ "BSD-3-Clause" ]
1
2020-08-30T20:40:25.000Z
2020-08-30T20:40:25.000Z
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "flickcharm.h" #include <QAbstractScrollArea> #include <QApplication> #include <QBasicTimer> #include <QEvent> #include <QHash> #include <QList> #include <QMouseEvent> #include <QScrollBar> #include <QTime> #include <QWebFrame> #include <QWebView> #include <QDebug> const int fingerAccuracyThreshold = 3; struct FlickData { typedef enum { Steady, // Interaction without scrolling ManualScroll, // Scrolling manually with the finger on the screen AutoScroll, // Scrolling automatically AutoScrollAcceleration // Scrolling automatically but a finger is on the screen } State; State state; QWidget *widget; QPoint pressPos; QPoint lastPos; QPoint speed; QTime speedTimer; QList<QEvent*> ignored; QTime accelerationTimer; bool lastPosValid:1; bool waitingAcceleration:1; FlickData() : lastPosValid(false) , waitingAcceleration(false) {} void resetSpeed() { speed = QPoint(); lastPosValid = false; } void updateSpeed(const QPoint &newPosition) { if (lastPosValid) { const int timeElapsed = speedTimer.elapsed(); if (timeElapsed) { const QPoint newPixelDiff = (newPosition - lastPos); const QPoint pixelsPerSecond = newPixelDiff * (1000 / timeElapsed); // fingers are inacurates, we ignore small changes to avoid stopping the autoscroll because // of a small horizontal offset when scrolling vertically const int newSpeedY = (qAbs(pixelsPerSecond.y()) > fingerAccuracyThreshold) ? pixelsPerSecond.y() : 0; const int newSpeedX = (qAbs(pixelsPerSecond.x()) > fingerAccuracyThreshold) ? pixelsPerSecond.x() : 0; if (state == AutoScrollAcceleration) { const int max = 4000; // px by seconds const int oldSpeedY = speed.y(); const int oldSpeedX = speed.x(); if ((oldSpeedY <= 0 && newSpeedY <= 0) || (oldSpeedY >= 0 && newSpeedY >= 0) && (oldSpeedX <= 0 && newSpeedX <= 0) || (oldSpeedX >= 0 && newSpeedX >= 0)) { speed.setY(qBound(-max, (oldSpeedY + (newSpeedY / 4)), max)); speed.setX(qBound(-max, (oldSpeedX + (newSpeedX / 4)), max)); } else { speed = QPoint(); } } else { const int max = 2500; // px by seconds // we average the speed to avoid strange effects with the last delta if (!speed.isNull()) { speed.setX(qBound(-max, (speed.x() / 4) + (newSpeedX * 3 / 4), max)); speed.setY(qBound(-max, (speed.y() / 4) + (newSpeedY * 3 / 4), max)); } else { speed = QPoint(newSpeedX, newSpeedY); } } } } else { lastPosValid = true; } speedTimer.start(); lastPos = newPosition; } // scroll by dx, dy // return true if the widget was scrolled bool scrollWidget(const int dx, const int dy) { QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea*>(widget); if (scrollArea) { const int x = scrollArea->horizontalScrollBar()->value(); const int y = scrollArea->verticalScrollBar()->value(); scrollArea->horizontalScrollBar()->setValue(x - dx); scrollArea->verticalScrollBar()->setValue(y - dy); return (scrollArea->horizontalScrollBar()->value() != x || scrollArea->verticalScrollBar()->value() != y); } QWebView *webView = qobject_cast<QWebView*>(widget); if (webView) { QWebFrame *frame = webView->page()->mainFrame(); const QPoint position = frame->scrollPosition(); frame->setScrollPosition(position - QPoint(dx, dy)); return frame->scrollPosition() != position; } return false; } bool scrollTo(const QPoint &newPosition) { const QPoint delta = newPosition - lastPos; updateSpeed(newPosition); return scrollWidget(delta.x(), delta.y()); } }; class FlickCharmPrivate { public: QHash<QWidget*, FlickData*> flickData; QBasicTimer ticker; QTime timeCounter; void startTicker(QObject *object) { if (!ticker.isActive()) ticker.start(15, object); timeCounter.start(); } }; FlickCharm::FlickCharm(QObject *parent): QObject(parent) { d = new FlickCharmPrivate; } FlickCharm::~FlickCharm() { delete d; } void FlickCharm::activateOn(QWidget *widget) { QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea*>(widget); if (scrollArea) { scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); QWidget *viewport = scrollArea->viewport(); viewport->installEventFilter(this); scrollArea->installEventFilter(this); d->flickData.remove(viewport); d->flickData[viewport] = new FlickData; d->flickData[viewport]->widget = widget; d->flickData[viewport]->state = FlickData::Steady; return; } QWebView *webView = qobject_cast<QWebView*>(widget); if (webView) { QWebFrame *frame = webView->page()->mainFrame(); frame->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); frame->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff); webView->installEventFilter(this); d->flickData.remove(webView); d->flickData[webView] = new FlickData; d->flickData[webView]->widget = webView; d->flickData[webView]->state = FlickData::Steady; return; } qWarning() << "FlickCharm only works on QAbstractScrollArea (and derived classes)"; qWarning() << "or QWebView (and derived classes)"; } void FlickCharm::deactivateFrom(QWidget *widget) { QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea*>(widget); if (scrollArea) { QWidget *viewport = scrollArea->viewport(); viewport->removeEventFilter(this); scrollArea->removeEventFilter(this); delete d->flickData[viewport]; d->flickData.remove(viewport); return; } QWebView *webView = qobject_cast<QWebView*>(widget); if (webView) { webView->removeEventFilter(this); delete d->flickData[webView]; d->flickData.remove(webView); return; } } static QPoint deaccelerate(const QPoint &speed, const int deltatime) { const int deltaSpeed = deltatime; int x = speed.x(); int y = speed.y(); x = (x == 0) ? x : (x > 0) ? qMax(0, x - deltaSpeed) : qMin(0, x + deltaSpeed); y = (y == 0) ? y : (y > 0) ? qMax(0, y - deltaSpeed) : qMin(0, y + deltaSpeed); return QPoint(x, y); } bool FlickCharm::eventFilter(QObject *object, QEvent *event) { if (!object->isWidgetType()) return false; const QEvent::Type type = event->type(); switch (type) { case QEvent::MouseButtonPress: case QEvent::MouseMove: case QEvent::MouseButtonRelease: break; case QEvent::MouseButtonDblClick: // skip double click return true; default: return false; } QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); if (type == QEvent::MouseMove && mouseEvent->buttons() != Qt::LeftButton) return false; if (mouseEvent->modifiers() != Qt::NoModifier) return false; QWidget *viewport = qobject_cast<QWidget*>(object); FlickData *data = d->flickData.value(viewport); if (!viewport || !data || data->ignored.removeAll(event)) return false; const QPoint mousePos = mouseEvent->pos(); bool consumed = false; switch (data->state) { case FlickData::Steady: if (type == QEvent::MouseButtonPress) { consumed = true; data->pressPos = mousePos; } else if (type == QEvent::MouseButtonRelease) { consumed = true; QMouseEvent *event1 = new QMouseEvent(QEvent::MouseButtonPress, data->pressPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QMouseEvent *event2 = new QMouseEvent(QEvent::MouseButtonRelease, data->pressPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); data->ignored << event1; data->ignored << event2; QApplication::postEvent(object, event1); QApplication::postEvent(object, event2); } else if (type == QEvent::MouseMove) { consumed = true; data->scrollTo(mousePos); const QPoint delta = mousePos - data->pressPos; if (delta.x() > fingerAccuracyThreshold || delta.y() > fingerAccuracyThreshold) data->state = FlickData::ManualScroll; } break; case FlickData::ManualScroll: if (type == QEvent::MouseMove) { consumed = true; data->scrollTo(mousePos); } else if (type == QEvent::MouseButtonRelease) { consumed = true; data->state = FlickData::AutoScroll; data->lastPosValid = false; d->startTicker(this); } break; case FlickData::AutoScroll: if (type == QEvent::MouseButtonPress) { consumed = true; data->state = FlickData::AutoScrollAcceleration; data->waitingAcceleration = true; data->accelerationTimer.start(); data->updateSpeed(mousePos); data->pressPos = mousePos; } else if (type == QEvent::MouseButtonRelease) { consumed = true; data->state = FlickData::Steady; data->resetSpeed(); } break; case FlickData::AutoScrollAcceleration: if (type == QEvent::MouseMove) { consumed = true; data->updateSpeed(mousePos); data->accelerationTimer.start(); if (data->speed.isNull()) data->state = FlickData::ManualScroll; } else if (type == QEvent::MouseButtonRelease) { consumed = true; data->state = FlickData::AutoScroll; data->waitingAcceleration = false; data->lastPosValid = false; } break; default: break; } data->lastPos = mousePos; return true; } void FlickCharm::timerEvent(QTimerEvent *event) { int count = 0; QHashIterator<QWidget*, FlickData*> item(d->flickData); while (item.hasNext()) { item.next(); FlickData *data = item.value(); if (data->state == FlickData::AutoScrollAcceleration && data->waitingAcceleration && data->accelerationTimer.elapsed() > 40) { data->state = FlickData::ManualScroll; data->resetSpeed(); } if (data->state == FlickData::AutoScroll || data->state == FlickData::AutoScrollAcceleration) { const int timeElapsed = d->timeCounter.elapsed(); const QPoint delta = (data->speed) * timeElapsed / 1000; bool hasScrolled = data->scrollWidget(delta.x(), delta.y()); if (data->speed.isNull() || !hasScrolled) data->state = FlickData::Steady; else count++; data->speed = deaccelerate(data->speed, timeElapsed); } } if (!count) d->ticker.stop(); else d->timeCounter.start(); QObject::timerEvent(event); }
34.548387
118
0.591324
[ "object" ]
4e33e11e16b604df70f95902fdb92dc34f658b4f
26,069
cxx
C++
vtkview/vtkview.cxx
sferanchuk/tbev
71e62ae093719aa0e0de4708e87e589129b44f96
[ "MIT" ]
null
null
null
vtkview/vtkview.cxx
sferanchuk/tbev
71e62ae093719aa0e0de4708e87e589129b44f96
[ "MIT" ]
null
null
null
vtkview/vtkview.cxx
sferanchuk/tbev
71e62ae093719aa0e0de4708e87e589129b44f96
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <map> #include <string> #include <set> using namespace std; #include <vtkSmartPointer.h> #include <vtkVersion.h> #include <vtkParametricFunctionSource.h> #include <vtkTupleInterpolator.h> #include <vtkTubeFilter.h> #include <vtkParametricSpline.h> #include <vtkDoubleArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkSphereSource.h> #include <vtkPolyDataMapper.h> #include <vtkObjectFactory.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRendererCollection.h> #include <vtkRenderWindowInteractor.h> #include <vtkWindowToImageFilter.h> #include <vtkPNGWriter.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkProperty.h> #include <vtkCamera.h> static double resolutionScale = 3.; // Define interaction style class KeyPressInteractorStyle : public vtkInteractorStyleTrackballCamera { public: static KeyPressInteractorStyle* New(); vtkTypeMacro(KeyPressInteractorStyle, vtkInteractorStyleTrackballCamera); virtual void OnKeyPress() { // Get the keypress vtkRenderWindowInteractor *rwi = this->Interactor; std::string key = rwi->GetKeySym(); // Output the key that was pressed std::cout << "Pressed " << key << std::endl; // Handle an arrow key if(key == "Up") { std::cout << "The up arrow was pressed." << std::endl; } // Handle a "normal" key if(key == "a") { vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter = vtkSmartPointer<vtkWindowToImageFilter>::New(); windowToImageFilter->SetInput( rwi->GetRenderWindow() ); windowToImageFilter->SetMagnification( resolutionScale ); //set the resolution of the output image (3 times the current resolution of vtk render window) windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel //windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer windowToImageFilter->Update(); printf( "enter file name to save image [.png]\n" ); char fname[256]; fgets( fname, 256, stdin ); if ( strlen( fname ) > 1 ) { strtok( fname, "\n" ); if ( strlen( fname ) < 4 || strcmp( fname + strlen( fname ) - 4, ".png" ) != 0 ) strcat( fname, ".png" ); vtkSmartPointer<vtkPNGWriter> writer = vtkSmartPointer<vtkPNGWriter>::New(); writer->SetFileName( fname ); writer->SetInputConnection(windowToImageFilter->GetOutputPort()); writer->Write(); printf( "image saved to %s\n", fname ); } rwi->Render(); rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->Clear(); rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->ResetCamera(); rwi->Render(); //std::cout << "The a key was pressed." << std::endl; } if(key == "c") { printf( "enter file name to save camera [.cam]\n" ); char fname[256]; fgets( fname, 256, stdin ); if ( strlen( fname ) > 1 ) { strtok( fname, "\n" ); if ( strlen( fname ) < 4 || strcmp( fname + strlen( fname ) - 4, ".cam" ) != 0 ) strcat( fname, ".cam" ); vtkCamera *cam = rwi->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera(); FILE *ofile = fopen( fname, "wt" ); double position[3]; double focalpoint[3]; double viewup[3]; cam->GetPosition( position ); cam->GetFocalPoint( focalpoint ); cam->GetViewUp( viewup ); fprintf( ofile, "%g %g %g\n", position[0], position[1], position[2] ); fprintf( ofile, "%g %g %g\n", focalpoint[0], focalpoint[1], focalpoint[2] ); fprintf( ofile, "%g %g %g\n", viewup[0], viewup[1], viewup[2] ); fclose( ofile ); printf( "camera attributes saved to %s\n", fname ); } } if ( key.size() == 1 && key != "a" && key != "c" && key[0] > 'a' && key[0] <= 'z' ) { printf( "a - save image; c - save camera; you pressed %s\n", key.data() ); } // Forward events vtkInteractorStyleTrackballCamera::OnKeyPress(); } }; vtkStandardNewMacro(KeyPressInteractorStyle); int main(int argc, char *argv[]) { if ( argc == 1 ) { fprintf( stderr, "arguments: pdb corr [cam] [-nomark] [-noscale] [-fragm beg end] [-offset num] [-ignore num] [-title text] [-magnification num=3]\n" ); return 1; } bool domark = true; bool doscale = true; bool camf = false; double camattr[3][3]; char buf[1024]; int markbeg = 297; int markend = 304; int moffset = 0; int ignorenum = 0; string wtitle = argv[1]; for ( int ac = 1; ac < argc; ac++ ) { if ( strcmp( argv[ac], "-nomark" ) == 0 ) domark = false; if ( strcmp( argv[ac], "-noscale" ) == 0 ) doscale = false; if ( strcmp( argv[ac], "-fragm" ) == 0 ) { ac++; markbeg = atoi( argv[ac] ); ac++; markend = atoi( argv[ac] ); } if ( strcmp( argv[ac], "-offset" ) == 0 ) { ac++; moffset = atoi( argv[ac] ); } if ( strcmp( argv[ac], "-ignore" ) == 0 ) { ac++; ignorenum = atoi( argv[ac] ); } if ( strcmp( argv[ac], "-magnification" ) == 0 ) { ac++; resolutionScale = atof( argv[ac] ); } if ( strcmp( argv[ac], "-title" ) == 0 ) { ac++; wtitle = argv[ac]; } } if ( argc > 3 && strcmp( argv[ 3 ], "-nomark" ) != 0 && strcmp( argv[3], "-noscale" ) != 0 ) { FILE *camfile = fopen( argv[3], "rt" ); if ( !camfile ) { fprintf( stderr, "can't open camera file %s\n", argv[3] ); return 1; } int ac = 0; while ( fgets( buf, 1024, camfile ) ) { int cc = 0; for ( char *p = strtok( buf, " \n" ); p && cc < 3; p = strtok( 0, " \n" ), cc++ ) camattr[ ac ][ cc ] = atof( p ); ac++; } fclose( camfile ); camf = true; } FILE *cfile = fopen( argv[2], "rt" ); const int nmut = 7; int mutpos[ nmut ] = { 518, 633, 676, 691, 723, 802, 831 }; int mutflags[ nmut ] = { 2, 1, 1, 1, 1, 2, 2 }; const int nzn = 2; int zncoord[ nzn ][ 3 ] = { { 0 } }; map<int,int> smutpos; for ( int i = 0; i < nmut; i++ ) smutpos[ mutpos[i] ] = i; double mutcoord[ nmut ][ 3 ] = { { 0 } }; const int nseg = 35; double bestsdist[ nseg ]; int bestsnum[ nseg ]; const char *romand[] = { "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii", "xiii", "xiv", "xv", "xvi", " xvii", "xviii", "xix", "xx", "xxi", "xxii", "xxiii", "xxiv", "xxv" }; multimap<double,int> segments; if ( !fgets( buf, 1024, cfile ) ) return 1; while ( fgets( buf, 1024, cfile ) ) { string s1( strtok( buf, "\t" ) ); double v = atof( strtok( 0, "\t\n" ) ); int n = atoi( s1.substr( 2, strcspn( s1.data() + 2, "_" ) ).data() ) / 10; segments.insert( pair<double,int>( v, n ) ); } fclose( cfile ); map<int,double> seln; map<int,int> p2rindex0; double mincv = segments.begin()->first; double maxcv = segments.rbegin()->first; if ( doscale ) { mincv = 4e-13; maxcv = 9e-12; } int oc = 0; for ( multimap<double,int>::iterator it = segments.begin(); it != segments.end() && oc < nseg; it++, oc++ ) { if ( it->second * 10 <= ignorenum ) continue; bestsdist[ seln.size() ] = 1000; p2rindex0[ it->second ] = seln.size(); seln[ it->second ] = it->first; maxcv = it->first; printf( "%d %g\n", it->second, it->first ); } vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkPoints> points2 = vtkSmartPointer<vtkPoints>::New(); FILE *ifile = fopen( argv[1], "rt" ); int pc = moffset; int pc2 = 0; int pcc = 0; map<int,int> p2index; map<int,int> p2rindex; map<int,double> p2dist; double p2dmax = 0; double p2dmin = 1000; double prev2coord[3] = { 0 }; int znpos = 0; while ( fgets( buf, 1024, ifile ) ) { if ( strncmp( buf, "ATOM", 4 ) == 0 && strncmp( buf + 13, "CA", 2 ) == 0 && !( strncmp( buf + 17, "GTP", 3 ) == 0 || strncmp( buf + 17, "SAH", 3 ) == 0 ) ) { double coord[3]; coord[0] = atof( buf + 31 ); coord[1] = atof( buf + 39 ); coord[2] = atof( buf + 47 ); int resnum = atoi( buf + 23 ); if ( resnum < ignorenum ) { markbeg--; markend--; pc++; continue; } points->InsertPoint( pcc, coord[0], coord[1], coord[2] ); if ( smutpos.find( pc ) != smutpos.end() ) { mutcoord[ smutpos[pc] ][ 0 ] = coord[0]; mutcoord[ smutpos[pc] ][ 1 ] = coord[1]; mutcoord[ smutpos[pc] ][ 2 ] = coord[2]; } pc++; pcc++; if ( resnum % 10 == 4 ) { if ( seln.find( resnum / 10 ) != seln.end() ) { points2->InsertPoint( pc2, coord[0], coord[1], coord[2] ); if ( pc2 > 0 ) { double dist = sqrt( pow( coord[0] - prev2coord[0], 2 ) + pow( coord[1] - prev2coord[1], 2 ) + pow( coord[2] - prev2coord[2], 2 ) ); p2dmax = fmax( dist, p2dmax ); p2dmin = fmin( dist, p2dmin ); p2dist[ pc2 ] = dist; printf( "%d %g\n", pc2, dist ); } p2index[ pc2 ] = resnum / 10; p2rindex[ p2rindex0[ resnum / 10 ] ] = pc2; //printf( "%d %g\n", pc2, seln[ resnum/10] ); memcpy( prev2coord, coord, 3 * sizeof( double ) ); pc2++; } } } if ( strncmp( buf, "ATOM", 4 ) == 0 && ( strncmp( buf + 12, "ZN", 2 ) == 0 || strncmp( buf + 13, "ZN", 2 ) == 0 ) ) { double coord[3]; coord[0] = atof( buf + 31 ); coord[1] = atof( buf + 39 ); coord[2] = atof( buf + 47 ); zncoord[ znpos ][ 0 ] = coord[0]; zncoord[ znpos ][ 1 ] = coord[1]; zncoord[ znpos ][ 2 ] = coord[2]; znpos++; } } fclose( ifile ); // Fit a spline to the points vtkSmartPointer<vtkParametricSpline> spline = vtkSmartPointer<vtkParametricSpline>::New(); spline->SetPoints(points); vtkSmartPointer<vtkParametricFunctionSource> functionSource = vtkSmartPointer<vtkParametricFunctionSource>::New(); functionSource->SetParametricFunction(spline); functionSource->SetUResolution(10 * points->GetNumberOfPoints()); functionSource->Update(); vtkSmartPointer<vtkParametricSpline> spline2 = vtkSmartPointer<vtkParametricSpline>::New(); spline2->SetPoints(points2); vtkSmartPointer<vtkParametricFunctionSource> functionSource2 = vtkSmartPointer<vtkParametricFunctionSource>::New(); functionSource2->SetParametricFunction(spline2); functionSource2->SetUResolution(10 * points2->GetNumberOfPoints()); functionSource2->SetScalarModeToU(); functionSource2->Update(); /* vtkSmartPointer<vtkParametricFunctionSource> functionSourceI2 = vtkSmartPointer<vtkParametricFunctionSource>::New(); functionSourceI2->SetParametricFunction(spline2); functionSourceI2->SetUResolution(10 * points2->GetNumberOfPoints()); functionSourceI2->Update();*/ // Interpolate the scalars double rad; vtkSmartPointer<vtkTupleInterpolator> interpolatedRadius = vtkSmartPointer<vtkTupleInterpolator> ::New(); interpolatedRadius->SetInterpolationTypeToLinear(); interpolatedRadius->SetNumberOfComponents(1); for ( int i = 0; i < points->GetNumberOfPoints(); i++ ) { rad = .1; if ( i >= markbeg && i <= markend ) rad = .4; interpolatedRadius->AddTuple(i,&rad); } vtkSmartPointer<vtkTupleInterpolator> interpolatedRadius2 = vtkSmartPointer<vtkTupleInterpolator> ::New(); interpolatedRadius2->SetInterpolationTypeToLinear(); interpolatedRadius2->SetNumberOfComponents(1); for ( int i = 0; i < points2->GetNumberOfPoints(); i++ ) { rad = 1.2; interpolatedRadius2->AddTuple(i,&rad); } /* vtkSmartPointer<vtkTupleInterpolator> interpolatedIndex2 = vtkSmartPointer<vtkTupleInterpolator> ::New(); interpolatedIndex2->SetInterpolationTypeToLinear(); interpolatedIndex2->SetNumberOfComponents(1); for ( int i = 0; i < points2->GetNumberOfPoints(); i++ ) { rad = i; interpolatedIndex2->AddTuple(i,&rad); } */ /* vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertPoint(0,1,0,0); points->InsertPoint(1,2,0,0); points->InsertPoint(2,3,1,0); points->InsertPoint(3,4,1,0); points->InsertPoint(4,5,0,0); points->InsertPoint(5,6,0,0); // Fit a spline to the points vtkSmartPointer<vtkParametricSpline> spline = vtkSmartPointer<vtkParametricSpline>::New(); spline->SetPoints(points); vtkSmartPointer<vtkParametricFunctionSource> functionSource = vtkSmartPointer<vtkParametricFunctionSource>::New(); functionSource->SetParametricFunction(spline); functionSource->SetUResolution(10 * points->GetNumberOfPoints()); functionSource->Update(); // Interpolate the scalars double rad; vtkSmartPointer<vtkTupleInterpolator> interpolatedRadius = vtkSmartPointer<vtkTupleInterpolator> ::New(); interpolatedRadius->SetInterpolationTypeToLinear(); interpolatedRadius->SetNumberOfComponents(1); rad = .2; interpolatedRadius->AddTuple(0,&rad); rad = .2; interpolatedRadius->AddTuple(1,&rad); rad = .2; interpolatedRadius->AddTuple(2,&rad); rad = .1; interpolatedRadius->AddTuple(3,&rad); rad = .1; interpolatedRadius->AddTuple(4,&rad); rad = .1; interpolatedRadius->AddTuple(5,&rad); */ // Generate the radius scalars vtkSmartPointer<vtkDoubleArray> tubeRadius = vtkSmartPointer<vtkDoubleArray>::New(); unsigned int n = functionSource->GetOutput()->GetNumberOfPoints(); unsigned int n1p = points->GetNumberOfPoints(); unsigned int n2p = points2->GetNumberOfPoints(); tubeRadius->SetNumberOfTuples(n); tubeRadius->SetName("TubeRadius"); double tMin = interpolatedRadius->GetMinimumT(); double tMax = interpolatedRadius->GetMaximumT(); double r; for (unsigned int i = 0; i < n; ++i) { int res = ( double( i ) * ( n1p - 1 ) ) / n; int rf = 255, gf = 255, bf = 255; int flag = ( res >= markbeg && res <= markend ); if ( flag ) r = 0.3; else r = 0.2; tubeRadius->SetTuple1(i, r); } vtkSmartPointer<vtkDoubleArray> tubeRadius2 = vtkSmartPointer<vtkDoubleArray>::New(); unsigned int n2 = functionSource2->GetOutput()->GetNumberOfPoints(); printf( "n2 = %u, n = %u, n1p = %u, n2p = %u markbeg = %d markend = %d\n", n2, n, n1p, n2p, markbeg, markend ); tubeRadius2->SetNumberOfTuples(n2); tubeRadius2->SetName("TubeRadius2"); double tMin2 = interpolatedRadius2->GetMinimumT(); double tMax2 = interpolatedRadius2->GetMaximumT(); for (unsigned int i = 0; i < n2; ++i) { //double t = (tMax2 - tMin2) / (n2 - 1) * i + tMin2; //interpolatedRadius2->InterpolateTuple(t, &r); double u2 = double( i ) / n2; double su[3]; double sp[3]; double sd[9]; su[0] = u2; spline2->Evaluate( su, sp, sd ); for ( int k = 0; k < nseg; k++ ) { const double *coord = points2->GetPoint( k ); double d = 0; for ( int j = 0; j < 3; j++ ) d += ( coord[j] - sp[j] ) * ( coord[j] - sp[j] ); d = sqrt( d ); if ( bestsdist[k] > d ) { bestsdist[k] = d; bestsnum[k] = i; } } } for (unsigned int i = 0; i < n2; ++i) { int cj = 0; for ( int j = 0; j < n2p - 1; j++ ) { if ( bestsnum[j] <= i && bestsnum[ j + 1 ] >= i ) { cj = j; break; } } double r0 = 1.2; double dist = p2dist[ cj + 1 ]; double ir1 = 5 * double( i - bestsnum[cj] ) / ( bestsnum[ cj + 1 ] - bestsnum[cj] ); double ir2 = 5 * double( bestsnum[ cj + 1 ] - i ) / ( bestsnum[ cj + 1 ] - bestsnum[cj] ); double rc = fmax( exp( - ir1 * ir1 ), exp( -ir2 * ir2 ) ); double r = r0 * ( 1. - ( 1. - rc ) * dist / p2dmax ); printf( "%d %d %g %g %g %g\n", i, cj, dist, ir1, ir2, r ); if ( r < 0.3 ) r = 0.3; //r = 1.2; tubeRadius2->SetTuple1(i, r); } /* vtkSmartPointer<vtkDoubleArray> tubeIndex2 = vtkSmartPointer<vtkDoubleArray>::New(); unsigned int nI2 = functionSourceI2->GetOutput()->GetNumberOfPoints(); tubeIndex2->SetNumberOfTuples(nI2); tubeIndex2->SetName("TubeIndex2"); double tIMin2 = interpolatedIndex2->GetMinimumT(); double tIMax2 = interpolatedIndex2->GetMaximumT(); for (unsigned int i = 0; i < nI2; ++i) { double t = (tIMax2 - tIMin2) / (nI2 - 1) * i + tIMin2; interpolatedIndex2->InterpolateTuple(t, &r); tubeIndex2->SetTuple1(i, r); } */ // Add the scalars to the polydata vtkSmartPointer<vtkPolyData> tubePolyData = vtkSmartPointer<vtkPolyData>::New(); tubePolyData = functionSource->GetOutput(); tubePolyData->GetPointData()->AddArray(tubeRadius); tubePolyData->GetPointData()->SetActiveScalars("TubeRadius"); vtkSmartPointer<vtkUnsignedCharArray> rcolors = vtkSmartPointer<vtkUnsignedCharArray>::New(); rcolors->SetName("RColors"); rcolors->SetNumberOfComponents(3); rcolors->SetNumberOfTuples(n); for (int i = 0; i < n ;i++) { //double pr = ( seln[ p2index[ i / 10 ] ] - mincv ) / maxcv - mincv; //printf( "%g\n", seln[ p2index[ i / 10 ] ] ); //double pr = ( log( seln[ p2index[ i / 10 ] ] ) - log( mincv ) ) / ( log( maxcv ) - log( mincv ) ); //double pr = ( log( seln[ p2index[ i / 10 ] ] ) ) / ( log( maxcv ) ); int res = ( double( i ) * ( n1p - 1 ) ) / n; int rf = 255, gf = 255, bf = 255; int flag = ( res >= markbeg && res <= markend ); if ( flag ) { rf = 255; gf = 10; bf = 10; } if ( seln.find( res / 10 ) != seln.end() && flag == 255 && domark && false ) { rf = 200; gf = 10; bf = 10; } rcolors->InsertTuple3(i, rf, gf, bf ); } tubePolyData->GetPointData()->AddArray(rcolors); // Create the tubes vtkSmartPointer<vtkPolyData> tubePolyData2 = vtkSmartPointer<vtkPolyData>::New(); tubePolyData2 = functionSource2->GetOutput(); tubePolyData2->GetPointData()->AddArray(tubeRadius2); tubePolyData2->GetPointData()->SetActiveScalars("TubeRadius2"); vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New(); colors->SetName("Colors"); colors->SetNumberOfComponents(3); colors->SetNumberOfTuples(n2); for (int i = 0; i < n2 ;i++) { //double pr = ( seln[ p2index[ i / 10 ] ] - mincv ) / maxcv - mincv; //printf( "%g\n", seln[ p2index[ i / 10 ] ] ); int cj = 0; for ( int j = 0; j < n2p - 1; j++ ) { if ( bestsnum[j] <= i && bestsnum[ j + 1 ] >= i ) { cj = j; break; } } double ir1 = double( i - bestsnum[cj] ) / ( bestsnum[ cj + 1 ] - bestsnum[cj] ); double ir2 = double( bestsnum[ cj + 1 ] - i ) / ( bestsnum[ cj + 1 ] - bestsnum[cj] ); if ( ir1 < ir2 ) { ir1 = 0; ir2 = 1; } else { ir1 = 1; ir2 = 0; } double cval = ( 1 - ir1 ) * seln[ p2index[ cj ] ] + ( 1 - ir2 ) * seln[ p2index[ cj + 1 ] ]; double pr = ( log( cval ) - log( mincv ) ) / ( log( maxcv ) - log( mincv ) ); //double pr = ( log( seln[ p2index[ i / 10 ] ] ) ) / ( log( maxcv ) ); colors->InsertTuple3(i, 0, int(255. * pr ), int(255. * (1 - pr) ) ); } tubePolyData2->GetPointData()->AddArray(colors); /* vtkSmartPointer<vtkPolyData> tubePolyDataI2 = vtkSmartPointer<vtkPolyData>::New(); tubePolyDataI2 = functionSourceI2->GetOutput(); tubePolyDataI2->GetPointData()->AddArray(tubeIndex2); tubePolyDataI2->GetPointData()->SetActiveScalars("TubeIndex2"); */ vtkSmartPointer<vtkTubeFilter> tuber = vtkSmartPointer<vtkTubeFilter>::New(); #if VTK_MAJOR_VERSION <= 5 tuber->SetInput(tubePolyData); #else tuber->SetInputData(tubePolyData); #endif tuber->SetNumberOfSides(20); tuber->SetVaryRadiusToVaryRadiusByAbsoluteScalar(); vtkSmartPointer<vtkTubeFilter> tuber2 = vtkSmartPointer<vtkTubeFilter>::New(); #if VTK_MAJOR_VERSION <= 5 tuber2->SetInput(tubePolyData2); #else tuber2->SetInputData(tubePolyData2); #endif tuber2->SetNumberOfSides(20); tuber2->SetVaryRadiusToVaryRadiusByAbsoluteScalar(); /* //tubePolyData2->GetPointData()->SetActiveScalars("TubeIndex2"); //-------------- // Setup actors and mappers vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); #if VTK_MAJOR_VERSION <= 5 lineMapper->SetInput(tubePolyData); #else lineMapper->SetInputData(tubePolyData); #endif lineMapper->SetScalarRange(tubePolyData->GetScalarRange()); vtkSmartPointer<vtkPolyDataMapper> lineMapper2 = vtkSmartPointer<vtkPolyDataMapper>::New(); #if VTK_MAJOR_VERSION <= 5 lineMapper2->SetInput(tubePolyDataI2); #else lineMapper2->SetInputData(tubePolyDataI2); #endif lineMapper2->SetScalarRange(tubePolyDataI2->GetScalarRange()); */ vtkSmartPointer<vtkPolyDataMapper> tubeMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); tubeMapper->SetInputConnection(tuber->GetOutputPort()); tubeMapper->SetScalarRange(tubePolyData->GetScalarRange()); tubeMapper->ScalarVisibilityOn(); tubeMapper->SetScalarModeToUsePointFieldData(); tubeMapper->SelectColorArray("RColors"); vtkSmartPointer<vtkPolyDataMapper> tubeMapper2 = vtkSmartPointer<vtkPolyDataMapper>::New(); tubeMapper2->SetInputConnection(tuber2->GetOutputPort()); tubeMapper2->SetScalarRange(tubePolyData2->GetScalarRange()); tubeMapper2->ScalarVisibilityOn(); tubeMapper2->SetScalarModeToUsePointFieldData(); tubeMapper2->SelectColorArray("Colors"); //vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); //lineActor->SetMapper(lineMapper); vtkSmartPointer<vtkActor> tubeActor = vtkSmartPointer<vtkActor>::New(); tubeActor->SetMapper(tubeMapper); //vtkSmartPointer<vtkActor> lineActor2 = vtkSmartPointer<vtkActor>::New(); //lineActor2->SetMapper(lineMapper2); vtkSmartPointer<vtkActor> tubeActor2 = vtkSmartPointer<vtkActor>::New(); tubeActor2->SetMapper(tubeMapper2); // Setup render window, renderer, and interactor vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->SetWindowName( wtitle.data() ); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); vtkSmartPointer<KeyPressInteractorStyle> style = vtkSmartPointer<KeyPressInteractorStyle>::New(); renderWindowInteractor->SetInteractorStyle(style); style->SetCurrentRenderer(renderer); //renderer->AddActor(lineActor); renderer->AddActor(tubeActor); //renderer->AddActor(lineActor2); renderer->AddActor(tubeActor2); for (int mc = 0; mc < nmut; mc++ ) { /* vtkSmartPointer<vtkUnsignedCharArray> scolors = vtkSmartPointer<vtkUnsignedCharArray>::New(); scolors->SetName("SColors"); scolors->SetNumberOfComponents(3); scolors->SetNumberOfTuples(1); scolors.InsertNextTuple3(255,0,0); */ vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->SetCenter( mutcoord[mc][0], mutcoord[mc][1], mutcoord[mc][2] ); sphereSource->SetRadius(1.7); /* sp = sphereSource->GetOutput(); sphereSource->Update(); sp->GetCellData()->SetScalars( scolors ); appendData.AddInputData(sp ) */ vtkSmartPointer<vtkPolyDataMapper> smapper = vtkSmartPointer<vtkPolyDataMapper>::New(); smapper->SetInputConnection(sphereSource->GetOutputPort()); //smapper->SetColorModeToDirectScalars(); //smapper->SelectColorArray("SColors"); vtkSmartPointer<vtkActor> sactor = vtkSmartPointer<vtkActor>::New(); sactor->SetMapper(smapper); if ( mutflags[ mc ] == 1 ) { sactor->GetProperty()->SetColor(0.1, 0.1, 0.1); } else { sactor->GetProperty()->SetColor(0.1, 0.1, 0.1); } renderer->AddActor(sactor); } for (int zc = 0; zc < nzn; zc++ ) { /* vtkSmartPointer<vtkUnsignedCharArray> scolors = vtkSmartPointer<vtkUnsignedCharArray>::New(); scolors->SetName("SColors"); scolors->SetNumberOfComponents(3); scolors->SetNumberOfTuples(1); scolors.InsertNextTuple3(255,0,0); */ vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->SetCenter( zncoord[zc][0], zncoord[zc][1], zncoord[zc][2] ); sphereSource->SetRadius(2.7); /* sp = sphereSource->GetOutput(); sphereSource->Update(); sp->GetCellData()->SetScalars( scolors ); appendData.AddInputData(sp ) */ vtkSmartPointer<vtkPolyDataMapper> smapper = vtkSmartPointer<vtkPolyDataMapper>::New(); smapper->SetInputConnection(sphereSource->GetOutputPort()); //smapper->SetColorModeToDirectScalars(); //smapper->SelectColorArray("SColors"); vtkSmartPointer<vtkActor> sactor = vtkSmartPointer<vtkActor>::New(); sactor->SetMapper(smapper); sactor->GetProperty()->SetColor(0.57, 0, 0.82); renderer->AddActor(sactor); } if ( domark ) for (int sc = 0; sc < points2->GetNumberOfPoints(); sc++ ) { const double *coord = points2->GetPoint( p2rindex[ sc ] ); double ccoord[3]; ccoord[0] = coord[0]; ccoord[1] = coord[1]; ccoord[2] = coord[2]; const char *crdigit = romand[ sc ]; ccoord[0] += 1.6; for ( int sc1 = 0; sc1 < strlen( crdigit ); sc1++ ) { char cd = crdigit[ sc1 ]; vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->SetCenter( ccoord[0], ccoord[1], ccoord[2] ); sphereSource->SetRadius( cd == 'x' ? 1.2 : ( ( cd == 'v' ) ? 0.9 : 0.6 ) ); vtkSmartPointer<vtkPolyDataMapper> smapper = vtkSmartPointer<vtkPolyDataMapper>::New(); smapper->SetInputConnection(sphereSource->GetOutputPort()); vtkSmartPointer<vtkActor> sactor = vtkSmartPointer<vtkActor>::New(); sactor->SetMapper(smapper); sactor->GetProperty()->SetColor( 0.1, 0.1, (cd == 'v' ) ? 0.8: 0.1 ); renderer->AddActor(sactor); ccoord[0] += 1.6; } } //renderer->SetBackground(0.78, 0.78, 0.78); renderer->SetBackground(1., 1., 1.); if ( camf ) { vtkSmartPointer<vtkCamera> camera = vtkSmartPointer<vtkCamera>::New(); for ( int i = 0; i < 3; i++ ) for( int k = 0; k < 3; k++ ) printf( "%g ", camattr[i][k] ); camera->SetPosition( camattr[0] ); camera->SetFocalPoint( camattr[1] ); camera->SetViewUp( camattr[2] ); printf( "\ncamera configured\n" ); renderer->SetActiveCamera(camera); } renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
32.708908
199
0.640761
[ "render" ]
4e36e985334777ea682b37b8084bf9f157157d0e
1,928
hpp
C++
3rdParty/boost/1.71.0/libs/hana/test/_include/auto/for_each.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/hana/test/_include/auto/for_each.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/hana/test/_include/auto/for_each.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Copyright Louis Dionne 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #ifndef BOOST_HANA_TEST_AUTO_FOR_EACH_HPP #define BOOST_HANA_TEST_AUTO_FOR_EACH_HPP #include <boost/hana/assert.hpp> #include <boost/hana/for_each.hpp> #include "test_case.hpp" #include <laws/base.hpp> #include <vector> TestCase test_for_each{[]{ namespace hana = boost::hana; using hana::test::ct_eq; // Make sure the function is applied in left-to-right order. { auto check = [](auto ...xs) { std::vector<int> seen{}; hana::for_each(MAKE_TUPLE(xs...), [&](int x) { seen.push_back(x); }); BOOST_HANA_RUNTIME_CHECK(seen == std::vector<int>{xs...}); }; check(); check(0); check(0, 1); check(0, 1, 2); check(0, 1, 2, 3); check(0, 1, 2, 3, 4); } // Make sure the function is never called when the sequence is empty. { struct undefined { }; hana::for_each(MAKE_TUPLE(), undefined{}); } // Make sure it works with heterogeneous sequences. { hana::for_each(MAKE_TUPLE(ct_eq<0>{}), [](auto) { }); hana::for_each(MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}), [](auto) { }); hana::for_each(MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}), [](auto) { }); hana::for_each(MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}), [](auto) { }); } // Make sure for_each is constexpr when used with a constexpr function // and constexpr arguments. This used not to be the case. #ifndef MAKE_TUPLE_NO_CONSTEXPR { struct f { constexpr void operator()(int) const { } }; constexpr int i = (hana::for_each(MAKE_TUPLE(1, 2, 3), f{}), 0); (void)i; } #endif }}; #endif // !BOOST_HANA_TEST_AUTO_FOR_EACH_HPP
29.661538
97
0.592842
[ "vector" ]
4e38a15b9a1af2cd5a31c483e27970f5a4c45250
1,719
cc
C++
2021/Vjudge/2017 Multi-University Training Contest - Team 6/H.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2021/Vjudge/2017 Multi-University Training Contest - Team 6/H.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2021/Vjudge/2017 Multi-University Training Contest - Team 6/H.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using LL = long long; using Pii = pair<int, int>; using Pll = pair<LL, LL>; using VI = vector<int>; using VP = vector<pair<int, int>>; #define rep(i, a, b) for (auto i = (a); i < (b); ++i) #define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i) #define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i]) #define mem(x, v) memset(x, v, sizeof(x)) #define cpy(x, y) memcpy(x, y, sizeof(x)) #define SZ(V) static_cast<int>(V.size()) #define pb push_back #define mp make_pair constexpr int maxn = 2e5 + 7; char str[maxn]; int f[maxn]; int main() { int T; scanf("%d", &T); while (T--) { int m; scanf("%d %s", &m, str); int len = strlen(str), ans = 0; f[0] = 0; //! Odd rep(i, 1, len) { int l = i + 1, r = i + 1, cur = 0; f[i] = 0; while (l < len) { while (r < len && 2 * i - r >= 0) { if (cur + abs(str[r] - str[2 * i - r]) <= m) { cur += abs(str[r] - str[2 * i - r]); ++r; } else { break; } } f[i] = max(f[i], r - l); if (f[i] > ans) ans = f[i]; cur -= abs(str[l] - str[2 * i - l]); ++l; } } //! Even rep(i, 1, len) { int l = i, r = i, cur = 0; while (l < len) { while (r < len && 2 * i - 1 - r >= 0) { if (cur + abs(str[r] - str[2 * i - 1 - r]) <= m) { cur += abs(str[r] - str[2 * i - 1 - r]); ++r; } else { break; } } f[i] = max(f[i], r - l); if (f[i] > ans) ans = f[i]; cur -= abs(str[l] - str[2 * i - 1 - l]); ++l; } } printf("%d\n", ans); } }
24.211268
60
0.400233
[ "vector" ]
4e3960cc7fada00072bf6181fe08aa5efda85657
1,059
cc
C++
racional/racional_main.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97
d1dbcfb1ea8e478b869c10ae718cada45155a8ae
[ "MIT" ]
null
null
null
racional/racional_main.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97
d1dbcfb1ea8e478b869c10ae718cada45155a8ae
[ "MIT" ]
null
null
null
racional/racional_main.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97
d1dbcfb1ea8e478b869c10ae718cada45155a8ae
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <sstream> #include <cstring> #include <algorithm> #include "racional.h" // #include "tools.h" int main(){ // Usage(argc, argv); std::string fichero_entrada{}; std::cin>>fichero_entrada; // std::string fichero_salida{argv[2]}; racional result(1,1); std::vector<std::string> vec{}; std::vector<int> vec2{}; vec = result.extraer_rac(fichero_entrada); for (unsigned int i=0;i<vec.size();i++){ vec2 = SepararCifra(vec[i]); } int num1={vec2[0]}; int den1={vec2[1]}; int num2={vec2[2]}; int den2={vec2[3]}; racional rac1(num1,den1); racional rac2(num2,den2); rac1.print(); rac2.print(); result.suma_racionales(rac1, rac2); result.resta_racionales(rac1,rac2); result.multiplicacion_racionales(rac1, rac2); result.division_racionales(rac1, rac2); result.mayor(rac1, rac2); // result.mayor_igual(rac1, rac2); result.menor(rac1, rac2); // result.menor_igual(rac1, rac2); result.igual_igual(rac1, rac2); result.distinto(rac1, rac2); }
23.533333
47
0.672332
[ "vector" ]
4e3cfc936024373c472448eb4fdd65993f0f132b
821
cpp
C++
src/processor.cpp
sk-banerjee/system-monitor
17f4b3c2f57497f1e4c1cae5b49670d4538c78fa
[ "MIT" ]
null
null
null
src/processor.cpp
sk-banerjee/system-monitor
17f4b3c2f57497f1e4c1cae5b49670d4538c78fa
[ "MIT" ]
null
null
null
src/processor.cpp
sk-banerjee/system-monitor
17f4b3c2f57497f1e4c1cae5b49670d4538c78fa
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <numeric> #include <unistd.h> #include "processor.h" #include "linux_parser.h" using namespace std; // Return the aggregate CPU utilization float Processor::Utilization() { float utilization = 0; long active = LinuxParser::ActiveJiffies(); long idle = LinuxParser::IdleJiffies(); long total = active + idle; long prev_active = sample_prev_.at(0); long prev_idle = sample_prev_.at(1); long prev_total = prev_active + prev_idle; if(total > prev_total) { long delta_total_time = (total - prev_total); long delta_idle_time = (idle - prev_idle); utilization = (delta_total_time - delta_idle_time) / static_cast<float>(delta_total_time); } sample_prev_.at(0) = active; sample_prev_.at(1) = idle; return utilization; }
23.457143
57
0.696711
[ "vector" ]
4e3e7cca7a99a4e8ca52697183c64a6378768ebd
59
cpp
C++
src/core/Vector.cpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
11
2018-11-22T03:07:10.000Z
2022-03-31T15:51:29.000Z
src/core/Vector.cpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
2
2019-02-14T15:05:42.000Z
2019-07-26T06:07:13.000Z
src/core/Vector.cpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
4
2018-12-18T12:40:07.000Z
2022-03-31T15:51:31.000Z
#include <core\Vector.hpp> NAMESPACE_BEGIN NAMESPACE_END
9.833333
26
0.813559
[ "vector" ]
4e411119bde9487bd96f675bddba0d3f5e8b3e39
9,274
cc
C++
content/browser/indexed_db/indexed_db_factory.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/indexed_db_factory.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/indexed_db_factory.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_factory.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "content/browser/indexed_db/indexed_db_backing_store.h" #include "content/browser/indexed_db/indexed_db_tracing.h" #include "content/browser/indexed_db/indexed_db_transaction_coordinator.h" #include "third_party/WebKit/public/platform/WebIDBDatabaseException.h" namespace content { const int64 kBackingStoreGracePeriodMs = 2000; static std::string ComputeFileIdentifier(const std::string& origin_identifier) { return origin_identifier + "@1"; } IndexedDBFactory::IndexedDBFactory() {} IndexedDBFactory::~IndexedDBFactory() {} void IndexedDBFactory::ReleaseDatabase( const IndexedDBDatabase::Identifier& identifier, bool forcedClose) { DCHECK(database_map_.find(identifier) != database_map_.end()); std::string backing_store_identifier = database_map_[identifier]->backing_store()->identifier(); database_map_.erase(identifier); // No grace period on a forced-close, as the initiator is // assuming the backing store will be released once all // connections are closed. ReleaseBackingStore(backing_store_identifier, forcedClose); } void IndexedDBFactory::ReleaseBackingStore(const std::string& identifier, bool immediate) { // Only close if this is the last reference. if (!HasLastBackingStoreReference(identifier)) return; if (immediate) { CloseBackingStore(identifier); return; } DCHECK(!backing_store_map_[identifier]->close_timer()->IsRunning()); backing_store_map_[identifier]->close_timer()->Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kBackingStoreGracePeriodMs), base::Bind(&IndexedDBFactory::MaybeCloseBackingStore, this, identifier)); } void IndexedDBFactory::MaybeCloseBackingStore(const std::string& identifier) { // Another reference may have opened since the maybe-close was posted, // so it is necessary to check again. if (HasLastBackingStoreReference(identifier)) CloseBackingStore(identifier); } void IndexedDBFactory::CloseBackingStore(const std::string& identifier) { backing_store_map_.erase(identifier); } bool IndexedDBFactory::HasLastBackingStoreReference( const std::string& identifier) const { IndexedDBBackingStore* ptr; { // Scope so that the implicit scoped_refptr<> is freed. IndexedDBBackingStoreMap::const_iterator it = backing_store_map_.find(identifier); DCHECK(it != backing_store_map_.end()); ptr = it->second.get(); } return ptr->HasOneRef(); } void IndexedDBFactory::GetDatabaseNames( scoped_refptr<IndexedDBCallbacks> callbacks, const std::string& origin_identifier, const base::FilePath& data_directory) { IDB_TRACE("IndexedDBFactory::GetDatabaseNames"); // TODO(dgrogan): Plumb data_loss back to script eventually? WebKit::WebIDBCallbacks::DataLoss data_loss; bool disk_full; scoped_refptr<IndexedDBBackingStore> backing_store = OpenBackingStore( origin_identifier, data_directory, &data_loss, &disk_full); if (!backing_store) { callbacks->OnError( IndexedDBDatabaseError(WebKit::WebIDBDatabaseExceptionUnknownError, "Internal error opening backing store for " "indexedDB.webkitGetDatabaseNames.")); return; } callbacks->OnSuccess(backing_store->GetDatabaseNames()); } void IndexedDBFactory::DeleteDatabase( const string16& name, scoped_refptr<IndexedDBCallbacks> callbacks, const std::string& origin_identifier, const base::FilePath& data_directory) { IDB_TRACE("IndexedDBFactory::DeleteDatabase"); IndexedDBDatabase::Identifier unique_identifier(origin_identifier, name); IndexedDBDatabaseMap::iterator it = database_map_.find(unique_identifier); if (it != database_map_.end()) { // If there are any connections to the database, directly delete the // database. it->second->DeleteDatabase(callbacks); return; } // TODO(dgrogan): Plumb data_loss back to script eventually? WebKit::WebIDBCallbacks::DataLoss data_loss; bool disk_full = false; scoped_refptr<IndexedDBBackingStore> backing_store = OpenBackingStore( origin_identifier, data_directory, &data_loss, &disk_full); if (!backing_store) { callbacks->OnError( IndexedDBDatabaseError(WebKit::WebIDBDatabaseExceptionUnknownError, ASCIIToUTF16( "Internal error opening backing store " "for indexedDB.deleteDatabase."))); return; } scoped_refptr<IndexedDBDatabase> database = IndexedDBDatabase::Create(name, backing_store, this, unique_identifier); if (!database) { callbacks->OnError(IndexedDBDatabaseError( WebKit::WebIDBDatabaseExceptionUnknownError, ASCIIToUTF16( "Internal error creating database backend for " "indexedDB.deleteDatabase."))); return; } database_map_[unique_identifier] = database; database->DeleteDatabase(callbacks); database_map_.erase(unique_identifier); } scoped_refptr<IndexedDBBackingStore> IndexedDBFactory::OpenBackingStore( const std::string& origin_identifier, const base::FilePath& data_directory, WebKit::WebIDBCallbacks::DataLoss* data_loss, bool* disk_full) { const std::string file_identifier = ComputeFileIdentifier(origin_identifier); const bool open_in_memory = data_directory.empty(); IndexedDBBackingStoreMap::iterator it2 = backing_store_map_.find(file_identifier); if (it2 != backing_store_map_.end()) { it2->second->close_timer()->Stop(); return it2->second; } scoped_refptr<IndexedDBBackingStore> backing_store; if (open_in_memory) { backing_store = IndexedDBBackingStore::OpenInMemory(file_identifier); } else { backing_store = IndexedDBBackingStore::Open(origin_identifier, data_directory, file_identifier, data_loss, disk_full); } if (backing_store.get()) { backing_store_map_[file_identifier] = backing_store; // If an in-memory database, bind lifetime to this factory instance. if (open_in_memory) session_only_backing_stores_.insert(backing_store); // All backing stores associated with this factory should be of the same // type. DCHECK(session_only_backing_stores_.empty() || open_in_memory); return backing_store; } return 0; } void IndexedDBFactory::Open( const string16& name, int64 version, int64 transaction_id, scoped_refptr<IndexedDBCallbacks> callbacks, scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks, const std::string& origin_identifier, const base::FilePath& data_directory) { IDB_TRACE("IndexedDBFactory::Open"); scoped_refptr<IndexedDBDatabase> database; IndexedDBDatabase::Identifier unique_identifier(origin_identifier, name); IndexedDBDatabaseMap::iterator it = database_map_.find(unique_identifier); WebKit::WebIDBCallbacks::DataLoss data_loss = WebKit::WebIDBCallbacks::DataLossNone; bool disk_full = false; if (it == database_map_.end()) { scoped_refptr<IndexedDBBackingStore> backing_store = OpenBackingStore( origin_identifier, data_directory, &data_loss, &disk_full); if (!backing_store) { if (disk_full) { callbacks->OnError( IndexedDBDatabaseError(WebKit::WebIDBDatabaseExceptionQuotaError, ASCIIToUTF16( "Encountered full disk while opening " "backing store for indexedDB.open."))); return; } callbacks->OnError(IndexedDBDatabaseError( WebKit::WebIDBDatabaseExceptionUnknownError, ASCIIToUTF16( "Internal error opening backing store for indexedDB.open."))); return; } database = IndexedDBDatabase::Create(name, backing_store, this, unique_identifier); if (!database) { callbacks->OnError(IndexedDBDatabaseError( WebKit::WebIDBDatabaseExceptionUnknownError, ASCIIToUTF16( "Internal error creating database backend for indexedDB.open."))); return; } database_map_[unique_identifier] = database; } else { database = it->second; } database->OpenConnection( callbacks, database_callbacks, transaction_id, version, data_loss); } std::vector<IndexedDBDatabase*> IndexedDBFactory::GetOpenDatabasesForOrigin( const std::string& origin_identifier) const { std::vector<IndexedDBDatabase*> result; for (IndexedDBDatabaseMap::const_iterator it = database_map_.begin(); it != database_map_.end(); ++it) { if (it->first.first == origin_identifier) result.push_back(it->second.get()); } return result; } } // namespace content
36.085603
80
0.703796
[ "vector" ]
4e48d6f69e9b97268a57de65927816128c149943
2,301
cpp
C++
binding/matlab/S2M_ContactGamma.cpp
fmoissenet/biorbd
3b3352bf06b9e8fbbdf4f77c852b6a115522becf
[ "MIT" ]
null
null
null
binding/matlab/S2M_ContactGamma.cpp
fmoissenet/biorbd
3b3352bf06b9e8fbbdf4f77c852b6a115522becf
[ "MIT" ]
null
null
null
binding/matlab/S2M_ContactGamma.cpp
fmoissenet/biorbd
3b3352bf06b9e8fbbdf4f77c852b6a115522becf
[ "MIT" ]
null
null
null
void S2M_ContactGamma( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ){ // Verifier les arguments d'entrée checkNombreInputParametres(nrhs, 4, 4, "4 arguments are required where the 2nd is the handler on the model, 3rd is the Q and 4th is the Qdot"); // Recevoir le model s2mMusculoSkeletalModel * model = convertMat2Ptr<s2mMusculoSkeletalModel>(prhs[1]); unsigned int nQ = model->nbQ(); /* Get the number of DoF */ /**** ATTENTION, NQ A REMPLACÉ NDDL, SEGFAULT? ****/ unsigned int nQdot = model->nbQdot(); /* Get the number of DoF */ /**** ATTENTION, NQ A REMPLACÉ NDDL, SEGFAULT? ****/ // Recevoir Q s2mGenCoord Q = *getParameterQ(prhs, 2, nQ).begin(); s2mGenCoord QDot = *getParameterQdot(prhs, 3, nQdot).begin(); unsigned int nContacts = model->nContacts(); // // Compute gamma // RigidBodyDynamics::ConstraintSet CS = model->getConstraints(*model); // unsigned int prev_body_id = 0; // Eigen::Vector3d prev_body_point = Eigen::Vector3d::Zero(); // Eigen::Vector3d gamma_i = Eigen::Vector3d::Zero(); // CS.QDDot_0.setZero(); // UpdateKinematicsCustom (*model, NULL, NULL, &CS.QDDot_0); // for (unsigned int i = 0; i < CS.size(); i++) { // // only compute point accelerations when necessary // if (prev_body_id != CS.body[i] || prev_body_point != CS.point[i]) { // gamma_i = CalcPointAcceleration (*model, Q, QDot, CS.QDDot_0, CS.body[i], CS.point[i], false); // prev_body_id = CS.body[i]; // prev_body_point = CS.point[i]; // } // // we also substract ContactData[i].acceleration such that the contact // // point will have the desired acceleration // CS.gamma[i] = CS.acceleration[i] - CS.normal[i].dot(gamma_i); // } Eigen::MatrixXd G_tp(Eigen::MatrixXd::Zero(nContacts,model->nbQ())); RigidBodyDynamics::CalcConstraintsJacobian(*model, Q, model->getConstraints(*model), G_tp, true); RigidBodyDynamics::Math::VectorNd Gamma = model->getConstraints(*model).gamma; /* Create a matrix for the return argument */ plhs[0] = mxCreateDoubleMatrix( nContacts, 1, mxREAL); double *gamma = mxGetPr(plhs[0]); for (unsigned int j=0; j<nContacts; ++j){ gamma[j] = Gamma[j]; } return; }
43.415094
147
0.64146
[ "model" ]
4e4a645f073d90caa4098bc60b77f209f10bcb42
1,633
cpp
C++
CppSTL/Chapter1/vectors/vec2.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
CppSTL/Chapter1/vectors/vec2.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
CppSTL/Chapter1/vectors/vec2.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; template<class T> class Vector { template<class U> friend istream& operator>>( istream&, Vector<U>&); template<class U> friend ostream& operator<<( ostream&, Vector<U>&); private: T size; vector<T> vect; public: template<class U> Vector(U Size) : size(Size) { for( size_t i=0; i<size; i++) vect.push_back(0); } ~Vector() { cout << "\nPoping back elements ...\n"; typename std::vector<T>::iterator itr=vect.begin(); while( !vect.empty() ) { vect.pop_back(); cout << "Poping back element #" << *itr << "\n"; itr++; } //this->print(); } template<class U> void print() { typename std::vector<U>::iterator itr = vect.begin(); size_t i=0; while( itr != vect.end() ) { cout << "Vec[" << i++ << "] = " << *itr << " "; itr++; } cout << endl; } }; template<class U> istream& operator>>( istream& is, Vector<U>& vect ) { cout << "Enter vector length: "; is >> vect.size; U val; for( size_t i=0; i<vect.size; i++) { cout << "Enter element #" << i+1 << " : "; is >> val; vect.vect[i] = val; } return is; } template<class U> ostream& operator<<( ostream& os, Vector<U>& vect ) { for( size_t i=0 ; i<vect.vect.size() ; i++ ) os << "Vect[" << i << "] = " << vect.vect[i] << "\n"; return os; } main() { const int N = 5; Vector<int> vec(N); cin >> vec; cout << vec; }
21.486842
61
0.490508
[ "vector" ]
4e4d002265ba8cf24345a764275bc4aade21988f
11,395
hpp
C++
SRC/Maps/MapUtils.hpp
poli0048/Recon
d3836b3ea569f389c238469b17390ed6e9c34b65
[ "BSD-3-Clause" ]
1
2021-12-26T12:53:35.000Z
2021-12-26T12:53:35.000Z
SRC/Maps/MapUtils.hpp
poli0048/Recon
d3836b3ea569f389c238469b17390ed6e9c34b65
[ "BSD-3-Clause" ]
null
null
null
SRC/Maps/MapUtils.hpp
poli0048/Recon
d3836b3ea569f389c238469b17390ed6e9c34b65
[ "BSD-3-Clause" ]
2
2021-06-12T18:34:18.000Z
2021-12-26T12:53:44.000Z
//This module provides utility functions for coordinate conversions, tile lookup, and related things //Author: Bryan Poling //Copyright (c) 2020 Sentek Systems, LLC. All rights reserved.
 #pragma once //System Includes #include <cstdint> #include <tuple> #include <cmath> //Eigen Includes #include "../../../eigen/Eigen/Core" //We have two map coordinate systems. The first is Widget coordinates. This is the position of a pixel relative to the upper-left corner of the //map widget, in pixels. X goes right and y goes down. The second coordinate system is Normalized Mercator, which is used to reference //locations on the Earth. We have utilities to map back and forth between NM and widget coordinates. We also sometimes need to go back and //forth to Lat/Lon, but normalized mercator should be used internally whenever possible for consistency. inline Eigen::Vector2d NMToLatLon(Eigen::Vector2d const & NMCoords) { const double PI = 3.14159265358979; double x = NMCoords(0); double y = NMCoords(1); double lon = PI*x; double lat = 2.0*(atan(exp(y*PI)) - PI/4.0); return Eigen::Vector2d(lat,lon); } inline Eigen::Vector2d LatLonToNM(Eigen::Vector2d const & LatLon) { const double PI = 3.14159265358979; double lat = LatLon(0); double lon = LatLon(1); double x = lon / PI; double y = log(tan(lat/2.0 + PI/4.0)) / PI; return Eigen::Vector2d(x,y); } //Compute ECEF position (in meters) from WGS84 latitude, longitude, and altitude. //Input vector is: [Lat (radians), Lon (radians), Alt (m)] inline Eigen::Vector3d LLA2ECEF(Eigen::Vector3d const & Position_LLA) { double lat = Position_LLA(0); double lon = Position_LLA(1); double alt = Position_LLA(2); double a = 6378137.0; //Semi-major axis of reference ellipsoid double ecc = 0.081819190842621; //First eccentricity of the reference ellipsoid double eccSquared = ecc*ecc; double N = a/sqrt(1.0 - eccSquared*sin(lat)*sin(lat)); double X = (N + alt)*cos(lat)*cos(lon); double Y = (N + alt)*cos(lat)*sin(lon); double Z = (N*(1 - eccSquared) + alt)*sin(lat); return Eigen::Vector3d(X, Y, Z); } //Compute latitude (radians), longitude (radians), and altitude (height above WGS84 ref. elipsoid, in meters) from ECEF position (in meters) //Latitude and longitude are also both given with respect to the WGS84 reference elipsoid. //Output is the vector [Lat (radians), Lon (radians), Alt (m)] inline Eigen::Vector3d ECEF2LLA(Eigen::Vector3d const & Position_ECEF) { double x = Position_ECEF(0); double y = Position_ECEF(1); double z = Position_ECEF(2); //Set constants double R_0 = 6378137.0; double R_P = 6356752.314; double ecc = 0.081819190842621; //Calculate longitude (radians) double lon = atan2(y, x); //Compute intermediate values needed for lat and alt double eccSquared = ecc*ecc; double p = sqrt(x*x + y*y); double E = sqrt(R_0*R_0 - R_P*R_P); double F = 54.0*(R_P*z)*(R_P*z); double G = p*p + (1.0 - eccSquared)*z*z - eccSquared*E*E; double c = pow(ecc,4.0)*F*p*p/pow(G,3.0); double s = pow(1.0 + c + sqrt(c*c + 2.0*c),1.0/3.0); double P = (F/(3.0*G*G))/((s + (1.0/s) + 1.0)*(s + (1.0/s) + 1.0)); double Q = sqrt(1.0 + 2.0*pow(ecc,4.0)*P); double k_1 = -1.0*P*eccSquared*p/(1.0 + Q); double k_2 = 0.5*R_0*R_0*(1.0 + 1.0/Q); double k_3 = -1.0*P*(1.0 - eccSquared)*z*z/(Q*(1.0 + Q)); double k_4 = -0.5*P*p*p; double r_0 = k_1 + sqrt(k_2 + k_3 + k_4); double k_5 = (p - eccSquared*r_0); double U = sqrt(k_5*k_5 + z*z); double V = sqrt(k_5*k_5 + (1.0 - eccSquared)*z*z); double z_0 = (R_P*R_P*z)/(R_0*V); double e_p = (R_0/R_P)*ecc; //Calculate latitude (radians) double lat = atan((z + z_0*e_p*e_p)/p); //Calculate Altitude (m) double alt = U*(1.0 - (R_P*R_P/(R_0*V))); return Eigen::Vector3d(lat, lon, alt); } //Get the rotation between ECEF and ENU at a given latitude and longitude inline Eigen::Matrix3d latLon_2_C_ECEF_ENU(double lat, double lon) { //Populate C_ECEF_NED Eigen::Matrix3d C_ECEF_NED; C_ECEF_NED << -sin(lat)*cos(lon), -sin(lat)*sin(lon), cos(lat), -sin(lon), cos(lon), 0.0, -cos(lat)*cos(lon), -cos(lat)*sin(lon), -sin(lat); //Compute C_ECEF_ENU from C_ECEF_NED Eigen::Matrix3d C_NED_ENU; C_NED_ENU << 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0; Eigen::Matrix3d C_ECEF_ENU = C_NED_ENU * C_ECEF_NED; return C_ECEF_ENU; } inline Eigen::Vector2d WidgetCoordsToNormalizedMercator(Eigen::Vector2d const & WidgetCords, Eigen::Vector2d const & ULCorner_NM, double Zoom, int32_t tileWidth) { double screenPixelLengthNM = 2.0 / (pow(2.0, Zoom) * ((double) tileWidth)); return (ULCorner_NM + Eigen::Vector2d(WidgetCords(0)*screenPixelLengthNM, -1.0*WidgetCords(1)*screenPixelLengthNM)); } inline Eigen::Vector2d NormalizedMercatorToWidgetCoords(Eigen::Vector2d const & NMCoords, Eigen::Vector2d const & ULCorner_NM, double Zoom, int32_t tileWidth) { double screenPixelLengthNM = 2.0 / (pow(2.0, Zoom) * ((double) tileWidth)); return Eigen::Vector2d(NMCoords(0) - ULCorner_NM(0), ULCorner_NM(1) - NMCoords(1))/screenPixelLengthNM; } //Convert a distance in meters to normalized mercator units at the given point on Earth (only the y-coord matters). //Be careful with this - it is not perfect and gets especially bad over long distances. inline double MetersToNMUnits(double Meters, double yPos_NM) { const double PI = 3.14159265358979; const double C = 40075017.0; //meters (Wikipedia) double lat = 2.0*(atan(exp(yPos_NM*PI)) - PI/4.0); double NMUnitsPerMeter = 2.0/(C*cos(lat)); return Meters*NMUnitsPerMeter; } //Convert a distance in normalized mercator units to meters at a given point on Earth (only the y-coord matters). //This is not exact and should certainly never be used over large distances. inline double NMUnitsToMeters(double Dist_NM, double yPos_NM) { const double PI = 3.14159265358979; const double C = 40075017.0; //meters (Wikipedia) double lat = 2.0*(atan(exp(yPos_NM*PI)) - PI/4.0); double MetersPerNMUnit = C*cos(lat)/2.0; return Dist_NM*MetersPerNMUnit; } //Convert a distance in meters to pixels at the given zoom level and point on Earth (only the y-coord matters). //Be careful with this - it is not perfect and gets especially bad over long distances. inline double MetersToPixels(double Meters, double yPos_NM, double MapZoom) { const double PI = 3.14159265358979; const double C = 40075017.0; //meters (Wikipedia) double lat = 2.0*(atan(exp(yPos_NM*PI)) - PI/4.0); double PixelsPerMeter = pow(2.0, MapZoom + 8.0)/(C*cos(lat)); return Meters*PixelsPerMeter; } //Convert a distance in pixels at a given zoom level to NM units at the given point on Earth (only the y-coord matters). //Be careful with this - it is not perfect and gets especially bad over long distances. inline double PixelsToNMUnits(double Pixels, double yPos_NM, double MapZoom) { const double PI = 3.14159265358979; const double C = 40075017.0; //meters (Wikipedia) double lat = 2.0*(atan(exp(yPos_NM*PI)) - PI/4.0); double NMUnitsPerMeter = 2.0/(C*cos(lat)); double PixelsPerMeter = pow(2.0, MapZoom + 8.0)/(C*cos(lat)); double NMUnitsPerPixel = NMUnitsPerMeter / PixelsPerMeter; return Pixels*NMUnitsPerPixel; } //Take the Upper-Left corner location of a map in Normalized Mercator coordinates and the zoom level and map dimensions (Width x Height in piexls) and get //the X and Y limits of the viewable area in Normalized Mercator coordinates. Returned in form (XMin, XMax, YMin, YMax) inline Eigen::Vector4d GetViewableArea_NormalizedMercator(Eigen::Vector2d const & ULCorner_NM, Eigen::Vector2d const & WindowDims, double Zoom, int32_t tileWidth) { Eigen::Vector2d LRCorner_NM = WidgetCoordsToNormalizedMercator(WindowDims, ULCorner_NM, Zoom, tileWidth); return Eigen::Vector4d(ULCorner_NM(0), LRCorner_NM(0), LRCorner_NM(1), ULCorner_NM(1)); } //Get the Normalized-Mercator coordinates of the center of pixel (row, col) in the given tile inline Eigen::Vector2d TilePixelToNM(int32_t TileX, int32_t TileY, int32_t PyramidLevel, int Row, int Col, int32_t tileWidth) { int32_t tilesOnThisLevel = (int32_t) (1U << PyramidLevel); //In each dimension double xNM = (double(TileX) + (double(Col) + 0.5)/double(tileWidth))*2.0 / (double(tilesOnThisLevel)) - 1.0; double yNM = 1.0 - (double(TileY) + (double(Row) + 0.5)/double(tileWidth))*2.0 / double(tilesOnThisLevel); return Eigen::Vector2d(xNM, yNM); } //Get the pixel coordinates of the given Normalized-Mercator position in the given tile. Returned in form <col, row>. //This is the inverse of TilePixelToNM() inline Eigen::Vector2d NMToTilePixel(int32_t TileX, int32_t TileY, int32_t PyramidLevel, Eigen::Vector2d const & Position_NM, int32_t tileWidth) { int32_t tilesOnThisLevel = (int32_t) (1U << PyramidLevel); //In each dimension double Col = ((1.0 + Position_NM(0))*double(tilesOnThisLevel)/2.0 - double(TileX))*double(tileWidth) - 0.5; double Row = ((1.0 - Position_NM(1))*double(tilesOnThisLevel)/2.0 - double(TileY))*double(tileWidth) - 0.5; return Eigen::Vector2d(Col, Row); } //Get the pixel containing the given Normalized-Mercator position in the given tile. Returned in form <col, row>. This version //saturates each coordinate to [0, tileWidth-1] inline std::tuple<int, int> NMToTilePixel_int(int32_t TileX, int32_t TileY, int32_t PyramidLevel, Eigen::Vector2d const & Position_NM, int32_t tileWidth) { int32_t tilesOnThisLevel = (int32_t) (1U << PyramidLevel); //In each dimension double Col = ((1.0 + Position_NM(0))*double(tilesOnThisLevel)/2.0 - double(TileX))*double(tileWidth) - 0.5; double Row = ((1.0 - Position_NM(1))*double(tilesOnThisLevel)/2.0 - double(TileY))*double(tileWidth) - 0.5; Col = floor(std::min(std::max(Col, 0.0), double(tileWidth - 1))); Row = floor(std::min(std::max(Row, 0.0), double(tileWidth - 1))); return std::make_tuple(int(Col), int(Row)); } //Get <tileCol, tileRow> for the tile on the given pyramid level containing the given point in Normalized Mercator coordinates inline std::tuple<int32_t, int32_t> getCoordsOfTileContainingPoint(Eigen::Vector2d const & PointNM, int32_t PyramidLevel) { int32_t tilesOnThisLevel = (int32_t) (1U << PyramidLevel); //In each dimension int32_t tileX = floor((PointNM(0) + 1.0)*tilesOnThisLevel/2.0); int32_t tileY = floor((1.0 - PointNM(1))*tilesOnThisLevel/2.0); tileX = std::max((int32_t) 0, std::min(tilesOnThisLevel - 1, tileX)); tileY = std::max((int32_t) 0, std::min(tilesOnThisLevel - 1, tileY)); return std::make_tuple(tileX, tileY); } //Get NM coords of upper-left corner of upper-left pixel of a given tile inline Eigen::Vector2d GetNMCoordsOfULCornerOfTile(int32_t TileX, int32_t TileY, int32_t PyramidLevel) { int32_t tilesOnThisLevel = (int32_t) (1U << PyramidLevel); //In each dimension double xNM = ((double) TileX)*2.0 / ((double) tilesOnThisLevel) - 1.0; double yNM = 1.0 - ((double) TileY)*2.0 / ((double) tilesOnThisLevel); return Eigen::Vector2d(xNM, yNM); } //Get NM coords of lower-right corner of lower-right pixel of a given tile inline Eigen::Vector2d GetNMCoordsOfLRCornerOfTile(int32_t TileX, int32_t TileY, int32_t PyramidLevel) { int32_t tilesOnThisLevel = (int32_t) (1U << PyramidLevel); //In each dimension double xNM = ((double) (TileX+1))*2.0 / ((double) tilesOnThisLevel) - 1.0; double yNM = 1.0 - ((double) (TileY+1))*2.0 / ((double) tilesOnThisLevel); return Eigen::Vector2d(xNM, yNM); }
47.677824
164
0.714173
[ "vector" ]
4e4e0e2b7c2108e31d9c36948adbfedab430c638
6,849
cpp
C++
Old Files/Car3D_Intersection/Car3D_Intersection/fourway_intersection_1.cpp
karenl7/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
6
2019-01-30T00:11:55.000Z
2022-03-09T02:44:51.000Z
Old Files/Car3D_Intersection/Car3D_Intersection/fourway_intersection_1.cpp
StanfordASL/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
null
null
null
Old Files/Car3D_Intersection/Car3D_Intersection/fourway_intersection_1.cpp
StanfordASL/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
4
2018-09-08T00:16:55.000Z
2022-03-09T02:44:54.000Z
#include "add_lane.cpp" #include "add_sq.cpp" #include "get_subvector.cpp" #include "update_lane.cpp" void fourway_intersection( beacls::FloatVec& lane, levelset::HJI_Grid* g, beacls::FloatVec gmin, beacls::FloatVec gmax, int Command) { FLOAT_TYPE vehicle_width = 1.; FLOAT_TYPE lane_width = 4.; const size_t numel = g->get_numel(); const size_t num_dim = g->get_num_of_dimensions(); const std::vector<size_t> shape = g->get_shape(); beacls::FloatVec lane_temp; beacls::FloatVec lane_temp_calc; lane.assign(numel, -12.); //lane_temp.assign(numel, -20.); //lane_temp_calc.assign(numel,0.); beacls::FloatVec xs_temp; beacls::FloatVec range; FLOAT_TYPE theta_offset; FLOAT_TYPE lane_offset; int enhance; enhance = 0; //1-enhance value function for (size_t dim = 0; dim < num_dim; ++dim) { if (dim == 0 || dim == 2){ const beacls::FloatVec &xs = g->get_xs(dim); if (Command == 0){ //0-Go straight; 1-Turn left theta_offset = M_PI/2; range = {0.,4.,-12.,12.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[1]+range[0])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); theta_offset = 3.*M_PI/2.; range = {-4.,0.,-12.,12.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[1]+range[0])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); } if (Command == 1){ //0-Go straight; 1-Turn left theta_offset = M_PI/2; range = {0.,4.,-12.,-4.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[1]+range[0])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); range = {0.,4.,4.,12.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[1]+range[0])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); theta_offset = 3.*M_PI/2.; range = {-4.,0.,-12.,-4.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[1]+range[0])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); range = {-4.,0.,4.,12.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[1]+range[0])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); } } if (dim == 1 || dim == 2){ const beacls::FloatVec &xs = g->get_xs(dim); if (Command == 0){ theta_offset = M_PI; range = {-12.,-4.,0.,4.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); range = {4.,12.,0.,4.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); theta_offset = 0.; range = {-12.,-4.,-4.,0.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); range = {4.,12.,-4.,0.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); } if (Command == 1){ enhance = 1; theta_offset = M_PI; range = {-12.,-4.,0.,4.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); enhance = 0; range = {-4.,12.,0.,4.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); theta_offset = 0.; range = {-12.,12.,-4.,0.}; //{xmin,xmax,ymin,ymax} lane_offset = (range[3]+range[2])/2.; get_subvector(lane_temp,lane,shape,range,gmin,gmax,dim); get_subvector(xs_temp,xs,shape,range,gmin,gmax,dim); add_lane(lane_temp,xs_temp,lane_offset,lane_width,theta_offset,vehicle_width,dim,enhance); update_lane(lane_temp,lane,shape,range,gmin,gmax,dim); } } } }
43.624204
100
0.634691
[ "shape", "vector" ]
4e521fe8ac2bb5baedd8977b7395b2f800e4becb
3,464
hpp
C++
dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/surface/include/pcl/surface/impl/marching_cubes_hoppe.hpp
hddxds/scripts_from_gi
afb8977c001b860335f9062464e600d9115ea56e
[ "Apache-2.0" ]
2
2019-04-10T14:04:52.000Z
2019-05-29T03:41:58.000Z
software/SLAM/ygz_slam_ros/Thirdparty/PCL/surface/include/pcl/surface/impl/marching_cubes_hoppe.hpp
glider54321/GAAS
5c3b8c684e72fdf7f62c5731a260021e741069e7
[ "BSD-3-Clause" ]
null
null
null
software/SLAM/ygz_slam_ros/Thirdparty/PCL/surface/include/pcl/surface/impl/marching_cubes_hoppe.hpp
glider54321/GAAS
5c3b8c684e72fdf7f62c5731a260021e741069e7
[ "BSD-3-Clause" ]
1
2021-12-20T06:54:41.000Z
2021-12-20T06:54:41.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef PCL_SURFACE_IMPL_MARCHING_CUBES_HOPPE_H_ #define PCL_SURFACE_IMPL_MARCHING_CUBES_HOPPE_H_ #include <pcl/surface/marching_cubes_hoppe.h> #include <pcl/common/common.h> #include <pcl/common/vector_average.h> #include <pcl/Vertices.h> #include <pcl/kdtree/kdtree_flann.h> ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::MarchingCubesHoppe<PointNT>::~MarchingCubesHoppe () { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::MarchingCubesHoppe<PointNT>::voxelizeData () { const bool is_far_ignored = dist_ignore_ > 0.0f; for (int x = 0; x < res_x_; ++x) { const int y_start = x * res_y_ * res_z_; for (int y = 0; y < res_y_; ++y) { const int z_start = y_start + y * res_z_; for (int z = 0; z < res_z_; ++z) { std::vector<int> nn_indices (1, 0); std::vector<float> nn_sqr_dists (1, 0.0f); const Eigen::Vector3f point = (lower_boundary_ + size_voxel_ * Eigen::Array3f (x, y, z)).matrix (); PointNT p; p.getVector3fMap () = point; tree_->nearestKSearch (p, 1, nn_indices, nn_sqr_dists); if (!is_far_ignored || nn_sqr_dists[0] < dist_ignore_) { const Eigen::Vector3f normal = input_->points[nn_indices[0]].getNormalVector3fMap (); if (!std::isnan (normal (0)) && normal.norm () > 0.5f) grid_[z_start + z] = normal.dot ( point - input_->points[nn_indices[0]].getVector3fMap ()); } } } } } #define PCL_INSTANTIATE_MarchingCubesHoppe(T) template class PCL_EXPORTS pcl::MarchingCubesHoppe<T>; #endif // PCL_SURFACE_IMPL_MARCHING_CUBES_HOPPE_H_
36.083333
107
0.659065
[ "vector" ]
4e5da5d2dfdf7a8f5676a36966d24a9e00cc9370
16,565
cpp
C++
src/shape.cpp
jondgoodwin/pegasus3d
b30cf4bcc707b4aca9c32c3fbd5aafc3798d7ec5
[ "MIT-0", "MIT" ]
4
2018-01-01T08:57:08.000Z
2021-12-01T14:36:58.000Z
src/shape.cpp
jondgoodwin/pegasus3d
b30cf4bcc707b4aca9c32c3fbd5aafc3798d7ec5
[ "MIT-0", "MIT" ]
null
null
null
src/shape.cpp
jondgoodwin/pegasus3d
b30cf4bcc707b4aca9c32c3fbd5aafc3798d7ec5
[ "MIT-0", "MIT" ]
null
null
null
/** Shape type - Handles a 3-D geometric mesh * @file * * This source file is part of the Pegasus3d browser. * See Copyright Notice in pegasus3d.h */ #include "pegasus3d.h" #include "xyzmath.h" #include <math.h> /** Generate a sphere shape centered at (0,0,0), passing radius and nsegments. The geometry is via longitude and latitude divisions. Normals extend outwards. The top point's uv is (0,1) with u wrapping horizontally around the latitudes. */ int shape_sphere(Value th) { // Obtain and validate parameters float radius = getTop(th)>=2 && isFloat(getLocal(th, 1))? toAfloat(getLocal(th,1)) : 1.0f; int nsegments = getTop(th)>=3 && isInt(getLocal(th, 2))? toAint(getLocal(th,2)) : 15; int nverts = (nsegments+1) * (nsegments-2) + 2; int nindices = 6*nsegments*nsegments; if (nsegments<=2 || nverts>=65536) { pushValue(th, aNull); return 1; } // Push a new Shape on the stack and give it buffer properties int sphereidx = getTop(th); pushSym(th, "New"); pushGloVar(th, "Shape"); getCall(th, 1, 1); pushSym(th, "New"); pushGloVar(th, "Xyzs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value posval = getFromTop(th, 0); popProperty(th, sphereidx, "positions"); pushSym(th, "New"); pushGloVar(th, "Xyzs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value normval = getFromTop(th, 0); popProperty(th, sphereidx, "normals"); pushSym(th, "New"); pushGloVar(th, "Uvs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value uvval = getFromTop(th, 0); popProperty(th, sphereidx, "uvs"); pushSym(th, "New"); pushGloVar(th, "Integers"); pushValue(th, anInt(nindices)); getCall(th, 2, 1); Value indxval = getFromTop(th, 0); popProperty(th, sphereidx, "indices"); // Top pole vertex GLfloat zero = 0.f; GLfloat one = 1.f; strAppend(th, posval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&radius), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&one), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, uvval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, uvval, (const char*)(&one), sizeof(GLfloat)); // each vertex, vertically and then around the circle int v0, v1, v2, v3; for (int i=1; i<nsegments; i++) { GLfloat mang = (GLfloat)M_PI * ((GLfloat)i) / ((GLfloat)(nsegments)); for (int j=0; j<nsegments; j++) { GLfloat nang = 2.0f * (GLfloat)M_PI * ((GLfloat)j) / ((GLfloat)nsegments); GLfloat x = -cos(nang)*sin(mang); GLfloat y = cos(mang); GLfloat z = sin(nang)*sin(mang); strAppend(th, normval, (const char*)(&x), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&y), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&z), sizeof(GLfloat)); x *= radius; y *= radius; z *= radius; strAppend(th, posval, (const char*)(&x), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&y), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&z), sizeof(GLfloat)); GLfloat uv1 = (GLfloat)j/(GLfloat)nsegments; GLfloat uv2 = (GLfloat)(nsegments-i)/(GLfloat)nsegments; strAppend(th, uvval, (const char*)(&uv1), sizeof(GLfloat)); strAppend(th, uvval, (const char*)(&uv2), sizeof(GLfloat)); // Generate two triangles per segment if (i==1) { v0 = 0; v1 = j+2; v2 = j+1; strAppend(th, indxval, (const char*)(&v0), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v1), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v2), sizeof(unsigned short)); } else { v0 = ((i-2)*nsegments)+j+1; v1 = ((i-2)*nsegments)+(j+2); v2 = ((i-1)*nsegments)+(j+2); v3 = ((i-1)*nsegments)+j+1; strAppend(th, indxval, (const char*)(&v0), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v2), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v3), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v0), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v1), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v2), sizeof(unsigned short)); } } GLfloat x = -sin(mang); GLfloat y = cos(mang); GLfloat z = 0.0f; strAppend(th, normval, (const char*)(&x), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&y), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&z), sizeof(GLfloat)); x *= radius; y *= radius; z *= radius; strAppend(th, posval, (const char*)(&x), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&y), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&z), sizeof(GLfloat)); GLfloat uv1 = 1.0f; GLfloat uv2 = (GLfloat)(nsegments-i)/(GLfloat)nsegments; strAppend(th, uvval, (const char*)(&uv1), sizeof(GLfloat)); strAppend(th, uvval, (const char*)(&uv2), sizeof(GLfloat)); } // Bottom pole vertex strAppend(th, uvval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, uvval, (const char*)(&zero), sizeof(GLfloat)); radius = -radius; one = -one; strAppend(th, posval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&radius), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&one), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&zero), sizeof(GLfloat)); for (int j=0; j<nsegments; j++) { v0 = ((nsegments-2)*nsegments)+j+1; v1 = (j==nsegments-1)? ((nsegments-2)*nsegments)+1 : ((nsegments-2)*nsegments)+j+2; v2 = ((nsegments-1)*nsegments)+1; strAppend(th, indxval, (const char*)(&v0), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v1), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v2), sizeof(unsigned short)); } return 1; } /** Generate a plane surface shape centered on (0,0,0), passing nsegments. The plane is flat to y, and extends between -1 and 1 in x and z. The plane normal is positive y. The uv coordinate of 0,0 is the corner at (-1, 0, 1) */ int shape_plane(Value th) { // Obtain and validate parameters int nsegments = getTop(th)>=2 && isInt(getLocal(th, 1))? toAint(getLocal(th,1)) : 1; GLfloat uvrepeat = getTop(th)>=3 && isFloat(getLocal(th, 2))? toAfloat(getLocal(th,2)) : 1.0f; int nverts = (nsegments+1) * (nsegments+1); int nindices = 6*nsegments*nsegments; if (nsegments<1 || nverts>=65536) { pushValue(th, aNull); return 1; } // Push a new Shape on the stack and give it buffer properties int planeidx = getTop(th); pushSym(th, "New"); pushGloVar(th, "Shape"); getCall(th, 1, 1); pushSym(th, "New"); pushGloVar(th, "Xyzs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value posval = getFromTop(th, 0); popProperty(th, planeidx, "positions"); pushSym(th, "New"); pushGloVar(th, "Xyzs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value normval = getFromTop(th, 0); popProperty(th, planeidx, "normals"); pushSym(th, "New"); pushGloVar(th, "Uvs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value uvval = getFromTop(th, 0); popProperty(th, planeidx, "uvs"); pushSym(th, "New"); pushGloVar(th, "Integers"); pushValue(th, anInt(nindices)); getCall(th, 2, 1); Value indxval = getFromTop(th, 0); popProperty(th, planeidx, "indices"); // each vertex, vertically and then horizontally int v0, v1, v2, v3; GLfloat zero = 0.0f; GLfloat one = 1.0f; for (int segz=0; segz<=nsegments; segz++) { for (int segx=0; segx<=nsegments; segx++) { GLfloat x = 2.0f * (GLfloat)segx/(GLfloat)nsegments - 1.0f; GLfloat z = 2.0f * (GLfloat)segz/(GLfloat)nsegments - 1.0f; strAppend(th, posval, (const char*)(&x), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, posval, (const char*)(&z), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&zero), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&one), sizeof(GLfloat)); strAppend(th, normval, (const char*)(&zero), sizeof(GLfloat)); GLfloat uv1 = uvrepeat * (GLfloat)segx/(GLfloat)nsegments; GLfloat uv2 = uvrepeat * (1.0f - (GLfloat)segz/(GLfloat)nsegments); strAppend(th, uvval, (const char*)(&uv1), sizeof(GLfloat)); strAppend(th, uvval, (const char*)(&uv2), sizeof(GLfloat)); // Generate two triangles per segment if (segx>0 && segz>0) { v0 = ((segz-1)*(nsegments+1))+segx-1; v1 = ((segz-1)*(nsegments+1))+segx; v2 = (segz*(nsegments+1))+segx; v3 = (segz*(nsegments+1))+segx-1; strAppend(th, indxval, (const char*)(&v0), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v2), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v3), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v0), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v1), sizeof(unsigned short)); strAppend(th, indxval, (const char*)(&v2), sizeof(unsigned short)); } } } return 1; } const GLfloat cube_positions[] = { -1., 1., -1., 1., 1., -1., 1., 1., 1., -1., 1., 1., -1., -1., -1., 1., -1., -1., 1., -1., 1., -1., -1., 1., -1., 1., -1., 1., 1., -1., 1., -1., -1., -1., -1., -1., -1., 1., 1., 1., 1., 1., 1., -1., 1., -1., -1., 1., -1., -1., -1., -1., 1., -1., -1., 1., 1., -1., -1., 1., 1., -1., -1., 1., 1., -1., 1., 1., 1., 1., -1., 1. }; const char cube_indices[] = "0,1,2, 0,2,3, 4,5,6, 4,6,7, 8,9,10, 8,10,11, 12,13,14, 12,14,15, 16,17,18, 16,18,19, 20,21,22, 20,22,23"; /** Generate a cube centered at 0.0.0. Parameter specifies its size. It has no uvs or normals. */ int shape_cube(Value th) { // Obtain and validate parameters GLfloat cubesize = getTop(th)>=2 && isFloat(getLocal(th, 1))? toAfloat(getLocal(th,1)) : 1.0f; int nverts = 72; // Push a new Shape on the stack and give it buffer properties int cubeidx = getTop(th); pushSym(th, "New"); pushGloVar(th, "Shape"); getCall(th, 1, 1); pushSym(th, "New"); pushGloVar(th, "Xyzs"); pushValue(th, anInt(nverts)); getCall(th, 2, 1); Value posval = getFromTop(th, 0); popProperty(th, cubeidx, "positions"); pushSym(th, "New"); pushGloVar(th, "Integers"); pushString(th, aNull, cube_indices); getCall(th, 2, 1); popProperty(th, cubeidx, "indices"); for (int v = 0; v<nverts; v++) { GLfloat pos = cubesize * cube_positions[v]; strAppend(th, posval, (const char*)(&pos), sizeof(GLfloat)); } return 1; } /** Get the draw property (symbol) */ int shape_getDraw(Value th) { pushProperty(th, 0, "_drawsym"); return 1; } /** Set the draw property's closure value using symbols */ int shape_setDraw(Value th) { GLint draw = GL_TRIANGLES; Value drawsym = getLocal(th, 1); if (isSym(drawsym)) { const char *drawstr = toStr(drawsym); if (strcmp("Triangles", drawstr)==0) draw=GL_TRIANGLES; else if (strcmp("TriangleStrip", drawstr)==0) draw=GL_TRIANGLE_STRIP; else if (strcmp("TriangleFan", drawstr)==0) draw=GL_TRIANGLE_FAN; else if (strcmp("TrianglesAdjacency", drawstr)==0) draw=GL_TRIANGLES_ADJACENCY; else if (strcmp("TriangleStripAdjacency", drawstr)==0) draw=GL_TRIANGLE_STRIP_ADJACENCY; else if (strcmp("Patches", drawstr)==0) draw=GL_PATCHES; else if (strcmp("Lines", drawstr)==0) draw=GL_LINES; else if (strcmp("LineStrip", drawstr)==0) draw=GL_LINE_STRIP; else if (strcmp("LineLoop", drawstr)==0) draw=GL_LINE_LOOP; else if (strcmp("LinesAdjacency", drawstr)==0) draw=GL_LINES_ADJACENCY; else if (strcmp("LineStripAdjacency", drawstr)==0) draw=GL_LINE_STRIP_ADJACENCY; else if (strcmp("Points", drawstr)==0) draw=GL_POINTS; else if (strcmp("Polygon", drawstr)==0) draw=GL_POLYGON; // TriangleFan } pushValue(th, anInt(draw)); popProperty(th, 0, "_draw"); pushValue(th, drawsym); popProperty(th, 0, "_drawsym"); return 0; } /** Create a new shape */ int shape_new(Value th) { pushType(th, getLocal(th, 0), 16); return 1; } /** Prepare a shape for rendering */ int shape_renderprep(Value th) { int selfidx = 0; int cameraidx = 1; return 0; } /** Render the shape */ int shape_render(Value th) { int selfidx = 0; int contextidx = 1; // Render the shader, loading it and its uniforms pushSym(th, "_Render"); Value shader = pushProperty(th, selfidx, "shader"); if (shader == aNull) { popValue(th); shader = pushProperty(th, contextidx, "shader"); } pushLocal(th, contextidx); pushLocal(th, selfidx); getCall(th, 3, 0); // Turn on blending for shapes that use translucent colors Value transparent = pushProperty(th, selfidx, "transparent"); popValue(th); if (!isFalse(transparent)) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } // Draw the vertexes using the vertex attribute buffers GLuint vao; GLuint vbo[100]; unsigned int nverts = -1; // Get the list of vertex attributes Value vertattsym = pushSym(th, "attributes"); Value vertattrlistv = getProperty(th, shader, vertattsym); popValue(th); // symbol int nattrs = getSize(vertattrlistv); // Set up Vertex Array Object glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Allocate and assign as many Vertex Buffer Objects to our handle as we have attributes // then load and activate each one. glGenBuffers(nattrs, vbo); Value attrsource = getLocal(th, selfidx); for (int i=0; i<nattrs; i++) { Value buffer = getProperty(th, attrsource, arrGet(th, vertattrlistv, i)); if (!isCData(buffer)) continue; ArrayHeader *buffhdr = toArrayHeader(buffer); // Bind as active, copy, define and enable the OpenGL buffer glBindBuffer(GL_ARRAY_BUFFER, vbo[i]); glBufferData(GL_ARRAY_BUFFER, getSize(buffer), toCData(buffer), GL_STATIC_DRAW); /* Copy data */ AuintIdx n = getSize(buffer); float *f = (float *)toCData(buffer); switch (buffhdr->mbrType) { case Uint8Nbr: glVertexAttribPointer(i, buffhdr->structSz, GL_UNSIGNED_BYTE, GL_FALSE, 0, 0); break; case Uint16Nbr: glVertexAttribPointer(i, buffhdr->structSz, GL_UNSIGNED_SHORT, GL_FALSE, 0, 0); break; case Uint32Nbr: glVertexAttribPointer(i, buffhdr->structSz, GL_INT, GL_FALSE, 0, 0); break; case FloatNbr: case Vec2Value: case XyzValue: case ColorValue: case QuatValue: glVertexAttribPointer(i, buffhdr->structSz, GL_FLOAT, GL_FALSE, 0, 0); break; default: ; } glEnableVertexAttribArray(i); // Remember the smallest number of vertices we found in the buffers nverts = (nverts < 0 || nverts>buffhdr->nStructs)? buffhdr->nStructs : nverts; } // How shall we draw the primitives? Value drawprop = pushGetActProp(th, selfidx, "_draw"); int drawmode = isInt(drawprop)? toAint(drawprop) : GL_TRIANGLES; popValue(th); /* Do we have a "indices" property with vertex indices? Use it */ Value indicesym = pushSym(th, "indices"); Value vertices = getProperty(th, attrsource, indicesym); popValue(th); if (isCData(vertices)) { ArrayHeader *verthdr = toArrayHeader(vertices); // Generate a buffer for the indices GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, getSize(vertices), toCData(vertices), GL_STATIC_DRAW); // Draw the vertices using the indices as a guide glDrawElements(drawmode, verthdr->nStructs, GL_UNSIGNED_SHORT, (void*)0); glDeleteBuffers(1, &elementbuffer); } /* Otherwise, draw specified primitives using vertices defined by attribute buffers */ else glDrawArrays(drawmode, 0, nverts); popValue(th); // vertices /* Clean up allocated array and buffers */ for (int i=0; i<nattrs; i++) { glDisableVertexAttribArray(i); } glDeleteBuffers(nattrs, vbo); glDeleteVertexArrays(1, &vao); if (!isFalse(transparent)) glDisable(GL_BLEND); return 1; } /** Initialize shape type */ void shape_init(Value th) { Value Shape = pushType(th, aNull, 16); Value Placement = pushGloVar(th, "Placement"); popValue(th); addMixin(th, Shape, Placement); pushSym(th, "Shape"); popProperty(th, 0, "_name"); pushCMethod(th, shape_new); popProperty(th, 0, "New"); pushCMethod(th, shape_render); popProperty(th, 0, "_Render"); pushCMethod(th, shape_renderprep); popProperty(th, 0, "_RenderPrep"); pushCMethod(th, shape_sphere); popProperty(th, 0, "NewSphere"); pushCMethod(th, shape_plane); popProperty(th, 0, "NewPlane"); pushCMethod(th, shape_cube); popProperty(th, 0, "NewCube"); pushCMethod(th, shape_getDraw); pushCMethod(th, shape_setDraw); pushClosure(th, 2); popProperty(th, 0, "draw"); popGloVar(th, "Shape"); }
36.168122
107
0.666948
[ "mesh", "geometry", "render", "object", "shape" ]
4e6373be0d8032f03a28171c37907ce21b0655e2
8,030
cc
C++
Code/Components/Services/icewrapper/current/tosmetadata/TypedValueMapConstMapper.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/icewrapper/current/tosmetadata/TypedValueMapConstMapper.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/icewrapper/current/tosmetadata/TypedValueMapConstMapper.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file TypedValueMapConstMapper.cc /// /// @copyright (c) 2010 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Ben Humphreys <ben.humphreys@csiro.au> // Include own header file first #include "TypedValueMapConstMapper.h" // ASKAPsoft includes #include "askap/AskapError.h" #include "casacore/casa/aips.h" #include "casacore/measures/Measures/MDirection.h" // CP Ice interfaces #include "TypedValues.h" // Using using namespace askap; using namespace askap::cp::icewrapper; using namespace askap::interfaces; TypedValueMapConstMapper::TypedValueMapConstMapper(const TypedValueMap& map) : itsConstMap(map) { } int TypedValueMapConstMapper::getInt(const std::string& key) const { return get<int, TypeInt, TypedValueIntPtr>(key); } long TypedValueMapConstMapper::getLong(const std::string& key) const { // ::Ice::Long is 64-bit (even on 32-bit x86) whereas casa::Long will be // 32-bit. Using this mapper on such a system will likely lead to grief. #ifndef __LP64__ ASKAPTHROW(AskapError, "This platform does not support 64-bit long"); #else return get<long, TypeLong, TypedValueLongPtr>(key); #endif } casa::String TypedValueMapConstMapper::getString(const std::string& key) const { return get<casa::String, TypeString, TypedValueStringPtr>(key); } casa::Bool TypedValueMapConstMapper::getBool(const std::string& key) const { return get<casa::Bool, TypeBool, TypedValueBoolPtr>(key); } casa::Float TypedValueMapConstMapper::getFloat(const std::string& key) const { return get<casa::Float, TypeFloat, TypedValueFloatPtr>(key); } casa::Double TypedValueMapConstMapper::getDouble(const std::string& key) const { return get<casa::Double, TypeDouble, TypedValueDoublePtr>(key); } casa::Complex TypedValueMapConstMapper::getFloatComplex(const std::string& key) const { askap::interfaces::FloatComplex val = get<askap::interfaces::FloatComplex, TypeFloatComplex, TypedValueFloatComplexPtr>(key); return casa::Complex(val.real, val.imag); } casa::DComplex TypedValueMapConstMapper::getDoubleComplex(const std::string& key) const { askap::interfaces::FloatComplex val = get<askap::interfaces::FloatComplex, TypeFloatComplex, TypedValueFloatComplexPtr>(key); return casa::DComplex(val.real, val.imag); } casa::MDirection TypedValueMapConstMapper::getDirection(const std::string& key) const { askap::interfaces::Direction val = get<askap::interfaces::Direction, TypeDirection, TypedValueDirectionPtr>(key); return convertDirection(val); } std::vector<casa::Int> TypedValueMapConstMapper::getIntSeq(const std::string& key) const { return get<std::vector<casa::Int>, TypeIntSeq, TypedValueIntSeqPtr>(key); } std::vector<casa::Long> TypedValueMapConstMapper::getLongSeq(const std::string& key) const { // ::Ice::Long is 64-bit (even on 32-bit x86) whereas casa::Long will be // 32-bit. Using this mapper on such a system will likely lead to grief. #ifndef __LP64__ ASKAPTHROW(AskapError, "This platform does not support 64-bit long"); #else //return get<std::vector<casa::Long>, TypeLongSeq, TypedValueLongSeqPtr>(key); LongSeq seq = get<LongSeq, TypeLongSeq, TypedValueLongSeqPtr>(key); return std::vector<casa::Long>(seq.begin(), seq.end()); #endif } std::vector<casa::String> TypedValueMapConstMapper::getStringSeq(const std::string& key) const { askap::interfaces::StringSeq val = get<askap::interfaces::StringSeq, TypeStringSeq, TypedValueStringSeqPtr>(key); return std::vector<casa::String>(val.begin(), val.end()); } std::vector<casa::Bool> TypedValueMapConstMapper::getBoolSeq(const std::string& key) const { return get<std::vector<casa::Bool>, TypeBoolSeq, TypedValueBoolSeqPtr>(key); } std::vector<casa::Float> TypedValueMapConstMapper::getFloatSeq(const std::string& key) const { return get<std::vector<casa::Float>, TypeFloatSeq, TypedValueFloatSeqPtr>(key); } std::vector<casa::Double> TypedValueMapConstMapper::getDoubleSeq(const std::string& key) const { return get<std::vector<casa::Double>, TypeDoubleSeq, TypedValueDoubleSeqPtr>(key); } std::vector<casa::Complex> TypedValueMapConstMapper::getFloatComplexSeq(const std::string& key) const { askap::interfaces::FloatComplexSeq val = get<askap::interfaces::FloatComplexSeq, TypeFloatComplexSeq, TypedValueFloatComplexSeqPtr>(key); // Populate this vector before returning it std::vector<casa::Complex> container; askap::interfaces::FloatComplexSeq::const_iterator it = val.begin(); for (it = val.begin(); it != val.end(); ++it) { container.push_back(casa::Complex(it->real, it->imag)); } return container; } std::vector<casa::DComplex> TypedValueMapConstMapper::getDoubleComplexSeq(const std::string& key) const { askap::interfaces::DoubleComplexSeq val = get<askap::interfaces::DoubleComplexSeq, TypeDoubleComplexSeq, TypedValueDoubleComplexSeqPtr>(key); // Populate this vector before returning it std::vector<casa::DComplex> container; askap::interfaces::DoubleComplexSeq::const_iterator it = val.begin(); for (it = val.begin(); it != val.end(); ++it) { container.push_back(casa::DComplex(it->real, it->imag)); } return container; } std::vector<casa::MDirection> TypedValueMapConstMapper::getDirectionSeq(const std::string& key) const { askap::interfaces::DirectionSeq val = get<askap::interfaces::DirectionSeq, TypeDirectionSeq, TypedValueDirectionSeqPtr>(key); // Populate this vector before returning it std::vector<casa::MDirection> container; askap::interfaces::DirectionSeq::const_iterator it = val.begin(); for (it = val.begin(); it != val.end(); ++it) { container.push_back(convertDirection(*it)); } return container; } template <class T, askap::interfaces::TypedValueType TVType, class TVPtr> T TypedValueMapConstMapper::get(const std::string& key) const { if (itsConstMap.count(key) == 0) { ASKAPTHROW(AskapError, "Specified key (" << key << ") does not exist"); } const TypedValuePtr tv = itsConstMap.find(key)->second; if (tv->type != TVType) { ASKAPTHROW(AskapError, "Specified key (" << key << ") not of the requested type"); } return TVPtr::dynamicCast(tv)->value; } casa::MDirection TypedValueMapConstMapper::convertDirection(const askap::interfaces::Direction& dir) const { switch (dir.sys) { case J2000 : return casa::MDirection(casa::Quantity(dir.coord1, "deg"), casa::Quantity(dir.coord2, "deg"), casa::MDirection::Ref(casa::MDirection::J2000)); break; case AZEL : return casa::MDirection(casa::Quantity(dir.coord1, "deg"), casa::Quantity(dir.coord2, "deg"), casa::MDirection::Ref(casa::MDirection::AZEL)); break; } // This is the default case ASKAPTHROW(AskapError, "Coordinate system not supported"); }
33.881857
106
0.708219
[ "vector" ]
4e6a90623a723d02db3048d593b2904c6200bf91
5,141
cpp
C++
src/xrGame/CarLights.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/xrGame/CarLights.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/xrGame/CarLights.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#include "StdAfx.h" #include "CarLights.h" #ifdef DEBUG #include "PHDebug.h" #endif #include "alife_space.h" #include "Hit.h" #include "PHDestroyable.h" #include "Car.h" #include "Include/xrRender/Kinematics.h" // extern CPHWorld* ph_world; #include "xrPhysics/IPHWorld.h" SCarLight::SCarLight() { light_render = nullptr; glow_render = nullptr; bone_id = BI_NONE; m_holder = nullptr; } SCarLight::~SCarLight() { light_render.destroy(); glow_render.destroy(); bone_id = BI_NONE; } void SCarLight::Init(CCarLights* holder) { m_holder = holder; } void SCarLight::ParseDefinitions(LPCSTR section) { light_render = GEnv.Render->light_create(); light_render->set_type(IRender_Light::SPOT); light_render->set_shadow(true); glow_render = GEnv.Render->glow_create(); // lanim = 0; // time2hide = 0; // set bone id IKinematics* pKinematics = smart_cast<IKinematics*>(m_holder->PCar()->Visual()); CInifile* ini = pKinematics->LL_UserData(); Fcolor clr; clr.set(ini->r_fcolor(section, "color")); // clr.mul_rgb (torch->spot_brightness); // fBrightness = torch->spot_brightness; light_render->set_range(ini->r_float(section, "range")); light_render->set_color(clr); light_render->set_cone(deg2rad(ini->r_float(section, "cone_angle"))); light_render->set_texture(ini->r_string(section, "spot_texture")); glow_render->set_texture(ini->r_string(section, "glow_texture")); glow_render->set_color(clr); glow_render->set_radius(ini->r_float(section, "glow_radius")); bone_id = pKinematics->LL_BoneID(ini->r_string(section, "bone")); glow_render->set_active(false); light_render->set_active(false); pKinematics->LL_SetBoneVisible(bone_id, FALSE, TRUE); // lanim = LALib.FindItem(ini->r_string(section,"animator")); } void SCarLight::Switch() { VERIFY(!physics_world()->Processing()); if (isOn()) TurnOff(); else TurnOn(); } void SCarLight::TurnOn() { VERIFY(!physics_world()->Processing()); if (isOn()) return; IKinematics* K = smart_cast<IKinematics*>(m_holder->PCar()->Visual()); K->LL_SetBoneVisible(bone_id, TRUE, TRUE); K->CalculateBones_Invalidate(); K->CalculateBones(TRUE); glow_render->set_active(true); light_render->set_active(true); Update(); } void SCarLight::TurnOff() { VERIFY(!physics_world()->Processing()); if (!isOn()) return; glow_render->set_active(false); light_render->set_active(false); smart_cast<IKinematics*>(m_holder->PCar()->Visual())->LL_SetBoneVisible(bone_id, FALSE, TRUE); } bool SCarLight::isOn() { VERIFY(!physics_world()->Processing()); VERIFY(light_render->get_active() == glow_render->get_active()); return light_render->get_active(); } void SCarLight::Update() { VERIFY(!physics_world()->Processing()); if (!isOn()) return; CCar* pcar = m_holder->PCar(); CBoneInstance& BI = smart_cast<IKinematics*>(pcar->Visual())->LL_GetBoneInstance(bone_id); Fmatrix M; M.mul(pcar->XFORM(), BI.mTransform); light_render->set_rotation(M.k, M.i); glow_render->set_direction(M.k); glow_render->set_position(M.c); light_render->set_position(M.c); } CCarLights::CCarLights() { m_pcar = NULL; } void CCarLights::Init(CCar* pcar) { m_pcar = pcar; m_lights.clear(); } void CCarLights::ParseDefinitions() { CInifile* ini = smart_cast<IKinematics*>(m_pcar->Visual())->LL_UserData(); if (!ini->section_exist("lights")) return; LPCSTR S = ini->r_string("lights", "headlights"); string64 S1; int count = _GetItemCount(S); for (int i = 0; i < count; ++i) { _GetItem(S, i, S1); m_lights.push_back(xr_new<SCarLight>()); m_lights.back()->Init(this); m_lights.back()->ParseDefinitions(S1); } } void CCarLights::Update() { VERIFY(!physics_world()->Processing()); auto i = m_lights.begin(), e = m_lights.end(); for (; i != e; ++i) (*i)->Update(); } void CCarLights::SwitchHeadLights() { VERIFY(!physics_world()->Processing()); auto i = m_lights.begin(), e = m_lights.end(); for (; i != e; ++i) (*i)->Switch(); } void CCarLights::TurnOnHeadLights() { VERIFY(!physics_world()->Processing()); auto i = m_lights.begin(), e = m_lights.end(); for (; i != e; ++i) (*i)->TurnOn(); } void CCarLights::TurnOffHeadLights() { VERIFY(!physics_world()->Processing()); auto i = m_lights.begin(), e = m_lights.end(); for (; i != e; ++i) (*i)->TurnOff(); } bool CCarLights::IsLight(u16 bone_id) { SCarLight* light = nullptr; return findLight(bone_id, light); } bool CCarLights::findLight(u16 bone_id, SCarLight*& light) { auto e = m_lights.end(); SCarLight find_light; find_light.bone_id = bone_id; auto i = std::find_if(m_lights.begin(), e, SFindLightPredicate(&find_light)); light = *i; return i != e; } CCarLights::~CCarLights() { auto i = m_lights.begin(), e = m_lights.end(); for (; i != e; ++i) xr_delete(*i); m_lights.clear(); }
26.364103
98
0.641898
[ "render" ]
4e7517470b1dc29140cbdfecb8cf68d30b22e70d
2,389
hpp
C++
plugin/lua/src/minko/component/LuaSurface.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
null
null
null
plugin/lua/src/minko/component/LuaSurface.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
null
null
null
plugin/lua/src/minko/component/LuaSurface.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2014 Aerys 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 "minko/Common.hpp" #include "minko/component/Surface.hpp" #include "minko/math/Vector2.hpp" #include "minko/math/Vector3.hpp" #include "minko/math/Vector4.hpp" #include "minko/math/Matrix4x4.hpp" #include "minko/render/Texture.hpp" #include "minko/geometry/Geometry.hpp" #include "minko/render/Effect.hpp" #include "minko/data/Provider.hpp" #include "minko/LuaWrapper.hpp" namespace minko { namespace component { class LuaSurface : public LuaWrapper { public: static void bind(LuaGlue& state) { state.Class<Surface>("Surface") .method("create", static_cast<Surface::Ptr(*)(geometry::Geometry::Ptr, material::Material::Ptr, render::Effect::Ptr)>(&Surface::create)) .property("material", &Surface::material) .method("setEffect", static_cast<void(Surface::*)(std::shared_ptr<render::Effect>, const std::string&)>(&Surface::effect)) .method("setVisible", static_cast<void(Surface::*)(bool)>(&Surface::visible)); } private: static std::string getNameWrapper(Surface::Ptr s) { return s->name(); } }; } }
37.328125
142
0.670992
[ "geometry", "render" ]
4e7a2ed6f3ef7d58a2ca7f1627315fbb2b41bbb9
5,216
hpp
C++
pixy/src/host/libpixyusb/src/pixyinterpreter.hpp
GambuzX/Pixy-SIW
8d76b0c41402756533f444e1f99b332f74123618
[ "MIT" ]
1
2019-05-30T00:52:06.000Z
2019-05-30T00:52:06.000Z
pixy/src/host/libpixyusb/src/pixyinterpreter.hpp
GambuzX/Pixy-SIW
8d76b0c41402756533f444e1f99b332f74123618
[ "MIT" ]
1
2015-05-11T19:51:54.000Z
2015-05-11T19:51:54.000Z
pixy/src/host/libpixyusb/src/pixyinterpreter.hpp
GambuzX/Pixy-SIW
8d76b0c41402756533f444e1f99b332f74123618
[ "MIT" ]
null
null
null
// // begin license header // // This file is part of Pixy CMUcam5 or "Pixy" for short // // All Pixy source code is provided under the terms of the // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html). // Those wishing to use Pixy source code, software and/or // technologies under different licensing terms should contact us at // cmucam@cs.cmu.edu. Such licensing terms are available for // all portions of the Pixy codebase presented here. // // end license header // #ifndef __PIXYINTERPRETER_HPP__ #define __PIXYINTERPRETER_HPP__ #include <vector> #include <boost/thread.hpp> #include <boost/thread/mutex.hpp> #include "pixytypes.h" #include "pixy.h" #include "usblink.h" #include "interpreter.hpp" #include "chirpreceiver.hpp" #define PIXY_BLOCK_CAPACITY 250 class PixyInterpreter : public Interpreter { public: PixyInterpreter(); ~PixyInterpreter(); /** @brief Spawns an 'interpreter' thread which attempts to connect to Pixy using the USB interface. On successful connection, this thread will capture and store Pixy 'block' object data which can be retreived using the getBlocks() method. @return 0 Success @return -1 Error: Unable to open pixy USB device */ int init(); /** @brief Terminates the USB connection to Pixy and the 'iterpreter' thread. */ void close(); /** @brief Get status of the block data received from Pixy. @return 0 Stale Data: Block data has previously been retrieved using 'pixy_get_blocks()'. @return 1 New Data: Pixy sent new data that has not been retrieve yet. */ int blocks_are_new(); /** @brief Copies up to 'max_blocks' number of Blocks to the address pointed to by 'blocks'. @param[in] max_blocks Maximum number of Blocks to copy to the address pointed to by 'blocks'. @param[out] blocks Address of an array in which to copy the blocks to. The array must be large enough to write 'max_blocks' number of Blocks to. @return Non-negative Success: Number of blocks copied @return PIXY_ERROR_USB_IO USB Error: I/O @return PIXY_ERROR_NOT_FOUND USB Error: Pixy not found @return PIXY_ERROR_USB_BUSY USB Error: Busy @return PIXY_ERROR_USB_NO_DEVICE USB Error: No device @return PIXY_ERROR_INVALID_PARAMETER Invalid pararmeter specified */ int get_blocks(int max_blocks, Block * blocks); /** @brief Sends a command to Pixy. @param[in] name Remote procedure call identifier string. @param[in,out] arguments Argument list to function call. @return -1 Error */ int send_command(const char * name, va_list arguments); /** @brief Sends a command to Pixy. @param[in] name Remote procedure call identifier string. @return -1 Error */ int send_command(const char * name, ...); private: ChirpReceiver * receiver_; USBLink link_; boost::thread thread_; bool thread_die_; bool thread_dead_; std::vector<Block> blocks_; boost::mutex blocks_access_mutex_; boost::mutex chirp_access_mutex_; bool blocks_are_new_; /** @brief Interpreter thread entry point. Performs the following operations: 1. Connect to Pixy. 2. Interpretes Pixy messages and saves pixy 'block' objects. */ void interpreter_thread(); /** @brief Interprets data sent from Pixy over the Chirp protocol. @param[in] data Incoming Chirp protocol data from Pixy. */ void interpret_data(const void * chrip_data[]); /** @brief Interprets CCB1 messages sent from Pixy. @param[in] data Incoming Chirp protocol data from Pixy. */ void interpret_CCB1(const void * data[]); /** @brief Interprets CCB2 messages sent from Pixy. @param[in] data Incoming Chirp protocol data from Pixy. */ void interpret_CCB2(const void * data[]); /** @brief Adds blocks with normal signatures to the PixyInterpreter 'blocks_' buffer. @param[in] blocks An array of normal signature blocks to add to buffer. @param[in] count Size of the 'blocks' array. */ void add_normal_blocks(const BlobA * blocks, uint32_t count); /** @brief Adds blocks with color code signatures to the PixyInterpreter 'blocks_' buffer. @param[in] blocks An array of color code signature blocks to add to buffer. @param[in] count Size of the 'blocks' array. */ void add_color_code_blocks(const BlobB * blocks, uint32_t count); }; #endif
32.397516
97
0.60046
[ "object", "vector" ]
4e81633d6bb30fecd26c3a9c8f57e087b44e4628
1,170
cpp
C++
cpp/lib/dp/knapsack/01_knapsack_v.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/dp/knapsack/01_knapsack_v.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/dp/knapsack/01_knapsack_v.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; // -------------------------------------------------------- template<class T> bool chmax(T& a, const T b) { if (a < b) { a = b; return 1; } return 0; } #define FOR(i,l,r) for (ll i = (l); i < (r); ++i) #define REP(i,n) FOR(i,0,n) #define ALL(c) (c).begin(), (c).end() #define MAX(c) *max_element(ALL(c)) using VLL = vector<ll>; using VVLL = vector<VLL>; static const ll INF = (1LL << 62) - 1; // 4611686018427387904 - 1 // -------------------------------------------------------- int main() { ios::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(15); ll N, W; cin >> N >> W; VLL w(N+1),v(N+1); FOR(i,1,N+1) cin >> w[i] >> v[i]; ll V = N * MAX(v); VVLL dp(N+1, VLL(V+1, INF)); dp[0][0] = 0; FOR(i,1,N+1) FOR(j,0,V+1) { if (0 <= j - v[i]) { dp[i][j] = min(dp[i-1][j], dp[i-1][j - v[i]] + w[i]); } else { dp[i][j] = dp[i-1][j]; } } ll ans = 0; FOR(i,0,V+1) if (dp[N][i] <= W) chmax(ans, i); cout << ans << '\n'; return 0; } // Verify: https://atcoder.jp/contests/dp/tasks/dp_e
28.536585
91
0.442735
[ "vector" ]
4e83976a3575a1ec34c5cb9b07bd74165032fd8d
7,196
cpp
C++
dali/array/op/spatial_utils.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
dali/array/op/spatial_utils.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
dali/array/op/spatial_utils.cpp
bzcheeseman/Dali
a77c7ce60b20ce150a5927747e128688657907eb
[ "MIT" ]
null
null
null
#include "spatial_utils.h" #include "dali/utils/make_message.h" #include "dali/utils/assert2.h" #include "dali/utils/print_utils.h" namespace { int int_ceil(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } struct DataFormatDimMapping { int n_dim; int c_dim; int h_dim; int w_dim; DataFormatDimMapping(const std::string& data_format); }; DataFormatDimMapping::DataFormatDimMapping(const std::string& data_format) { n_dim = data_format.find('N'); c_dim = data_format.find('C'); h_dim = data_format.find('H'); w_dim = data_format.find('W'); const auto MISS = std::string::npos; ASSERT2(n_dim != MISS && c_dim != MISS && h_dim != MISS && w_dim != MISS && data_format.size() == 4, utils::make_message( "data_format must be a permutation of letters N,C,H,W (got ", data_format, ").")); } } namespace op { void check_data_format(const std::string& data_format, int* n_dim, int* c_dim, int* h_dim, int* w_dim) { ASSERT2(data_format.size() == 4, utils::make_message("data_format" " should be 4 character string containing letters N, C, H and W (" "got ", data_format, ").")); *n_dim = data_format.find('N'); ASSERT2(*n_dim != -1, utils::make_message("data_format" " should contain character 'N' (got ", data_format, ").")); *c_dim = data_format.find('C'); ASSERT2(*c_dim != -1, utils::make_message("data_format" " should contain character 'C' (got ", data_format, ").")); *h_dim = data_format.find('H'); ASSERT2(*h_dim != -1, utils::make_message("data_format" " should contain character 'H' (got ", data_format, ").")); *w_dim = data_format.find('W'); ASSERT2(*w_dim != -1, utils::make_message("data_format" " should contain character 'W' (got ", data_format, ").")); } template<typename Container> Container function_info_helper( const std::vector<int>& input_shape, const int& window_h, const int& window_w, const int& stride_h, const int& stride_w, const PADDING_T& padding, const DataFormatDimMapping& mapping) { Container info; info.batch_size = input_shape[mapping.n_dim]; info.in_channels = input_shape[mapping.c_dim]; info.in_h = input_shape[mapping.h_dim]; info.in_w = input_shape[mapping.w_dim]; if (padding == PADDING_T_SAME) { info.out_h = int_ceil(info.in_h, stride_h); info.out_w = int_ceil(info.in_w, stride_w); } else if (padding == PADDING_T_VALID) { info.out_h = int_ceil(info.in_h - window_h + 1, stride_h); info.out_w = int_ceil(info.in_w - window_w + 1, stride_w); } else { ASSERT2(false, utils::make_message( "expected padding to be SAME or VALID (got ", padding, ").")); } if (padding == PADDING_T_SAME) { info.padding_h = std::max(0, (info.out_h - 1) * stride_h + window_h - info.in_h); info.padding_w = std::max(0, (info.out_w - 1) * stride_w + window_w - info.in_w); } else if (padding == PADDING_T_VALID) { info.padding_h = 0; info.padding_w = 0; } info.odd_padding_h = info.padding_h % 2; info.odd_padding_w = info.padding_w % 2; info.padding_h /= 2; info.padding_w /= 2; info.stride_h = stride_h; info.stride_w = stride_w; return info; } PoolFunctionInfo compute_pool_info( const std::vector<int>& input_shape, const int& window_h, const int& window_w, const int& stride_h, const int& stride_w, const PADDING_T& padding, const std::string& data_format) { DataFormatDimMapping mapping(data_format); auto ret = function_info_helper<PoolFunctionInfo>( input_shape, window_h, window_w, stride_h, stride_w, padding, mapping); ret.window_h = window_h; ret.window_w = window_w; return ret; } ConvFunctionInfo compute_conv2d_info( const std::vector<int>& input_shape, const std::vector<int>& filters_shape, const int& stride_h, const int& stride_w, const PADDING_T& padding, const std::string& data_format) { DataFormatDimMapping mapping(data_format); int filter_h = filters_shape[mapping.h_dim]; int filter_w = filters_shape[mapping.w_dim]; ConvFunctionInfo ret = function_info_helper<ConvFunctionInfo>( input_shape, filter_h, filter_w, stride_h, stride_w, padding, mapping); ASSERT2_EQ(ret.in_channels, filters_shape[mapping.c_dim], utils::make_message("conv2d input and filters need to have " "the same number of input channels (got filters input channels " "= ", filters_shape[mapping.c_dim], ", and image input channels = ", ret.in_channels, ").")); ret.filter_h = filter_h; ret.filter_w = filter_w; ret.out_channels = filters_shape[mapping.n_dim]; return ret; } std::ostream& operator<<(std::ostream& os, const PoolFunctionInfo& info) { os << utils::make_message("Pooling(" "batch_size = ", info.batch_size, "\n" "in_channels = ", info.in_channels, "\n" "in_h = ", info.in_h, "\n" "in_w = ", info.in_w, "\n" "out_h = ", info.out_h, "\n" "out_w = ", info.out_w, "\n" "padding_h = ", info.padding_h, "\n" "padding_w = ", info.padding_w, "\n" "odd_padding_h = ", info.odd_padding_h, "\n" "odd_padding_w = ", info.odd_padding_w, "\n" "stride_h = ", info.stride_h, "\n" "stride_w = ", info.stride_w, "\n" "window_h = ", info.window_h, "\n" "window_w = ", info.window_w, ")"); return os; } std::ostream& operator<<(std::ostream& os, const ConvFunctionInfo& info) { os << utils::make_message("Convolution(" "batch_size=", info.batch_size, ",\n" "in_channels=", info.in_channels, ",\n" "in_h=", info.in_h, ",\n" "in_w=", info.in_w, ",\n" "out_h=", info.out_h, ",\n" "out_w=", info.out_w, ",\n" "padding_h=", info.padding_h, ",\n" "padding_w=", info.padding_w, ",\n" "odd_padding_h=", info.odd_padding_h, ",\n" "odd_padding_w=", info.odd_padding_w, ",\n" "stride_h=", info.stride_h, ",\n" "stride_w=", info.stride_w, ",\n" "filter_h=", info.filter_h, ",\n" "filter_w=", info.filter_w, ",\n" "out_channels=", info.out_channels, ")"); return os; } }
42.579882
93
0.555447
[ "vector" ]
4e846852f80a8b9b3c7d2522f94a985bff2f191c
44,464
cpp
C++
Viewer/ecflowUI/src/VModelData.cpp
ecmwf/ecflow
2498d0401d3d1133613d600d5c0e0a8a30b7b8eb
[ "Apache-2.0" ]
11
2020-08-07T14:42:45.000Z
2021-10-21T01:59:59.000Z
Viewer/ecflowUI/src/VModelData.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
10
2020-08-07T14:36:27.000Z
2022-02-22T06:51:24.000Z
Viewer/ecflowUI/src/VModelData.cpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
6
2020-08-07T14:34:38.000Z
2022-01-10T12:06:27.000Z
//============================================================================ // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. //============================================================================ #include "VModelData.hpp" #include "AbstractNodeModel.hpp" #include "ExpandState.hpp" #include "NodeQuery.hpp" #include "VFilter.hpp" #include "ServerHandler.hpp" #include "VAttribute.hpp" #include "VAttributeType.hpp" #include "VNode.hpp" #include "VTree.hpp" #include "UiLogS.hpp" #include "UIDebug.hpp" #include <QDebug> #include <QMetaMethod> #define _UI_VMODELDATA_DEBUG void VTreeChangeInfo::addStateChange(const VNode* n) { VNode* s=n->suite(); Q_ASSERT(s->isTopLevel()); Q_ASSERT(s); if(std::find(stateSuites_.begin(),stateSuites_.end(),s) == stateSuites_.end()) stateSuites_.push_back(s); } //========================================== // // VModelServer // //========================================== //It takes ownership of the filter VModelServer::VModelServer(ServerHandler *server) : server_(server), inScan_(false) { //We has to observe the nodes of the server. server_->addNodeObserver(this); //We has to observe the server. server_->addServerObserver(this); } VModelServer::~VModelServer() { server_->removeNodeObserver(this); server_->removeServerObserver(this); } int VModelServer::totalNodeNum() const { return server_->vRoot()->totalNum(); } //========================================== // // VTreeServer // //========================================== //It takes ownership of the filter VTreeServer::VTreeServer(ServerHandler *server,NodeFilterDef* filterDef,AttributeFilter* attrFilter) : VModelServer(server), changeInfo_(new VTreeChangeInfo()), attrFilter_(attrFilter), firstScan_(true), firstScanTryNo_(0), maxFirstScanTry_(10), expandState_(nullptr) { tree_=new VTree(this); filter_=new TreeNodeFilter(filterDef,server_,tree_); //We has to observe the nodes of the server. //server_->addNodeObserver(this); } VTreeServer::~VTreeServer() { delete tree_; delete changeInfo_; delete filter_; if(expandState_) delete expandState_; } NodeFilter* VTreeServer::filter() const { return const_cast<TreeNodeFilter*>(filter_); } int VTreeServer::nodeNum() const { return tree_->totalNum(); } void VTreeServer::adjustFirstScan() { if(firstScan_) { if(nodeNum() > 0) { firstScan_=false; } else { firstScanTryNo_++; if(firstScanTryNo_ == maxFirstScanTry_) { firstScan_=false; } } } } //-------------------------------------------------- // ServerObserver methods //-------------------------------------------------- void VTreeServer::notifyDefsChanged(ServerHandler* server, const std::vector<ecf::Aspect::Type>& a) { //When the defs changed we need to update the server node in the model/view Q_EMIT dataChanged(this); //TODO: what about node or attr num changes! } void VTreeServer::notifyServerDelete(ServerHandler* s) { UI_ASSERT(false, "server: " << s->longName()); Q_ASSERT(0); } void VTreeServer::notifyBeginServerScan(ServerHandler* server,const VServerChange& change) { //When the server scan begins we must be in inScan mode so that the model should think that //this server tree is empty. inScan_=true; UI_ASSERT(tree_->numOfChildren() == 0, "num: " << tree_->numOfChildren()); changeInfo_->clear(); } void VTreeServer::notifyEndServerScan(ServerHandler* /*server*/) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif UI_ASSERT(tree_->numOfChildren() == 0, "num: " << tree_->numOfChildren()); //We still must be in inScan mode so that the model should think //that this server tree is empty. inScan_=true; filter_->clearForceShowNode(); attrFilter_->clearForceShowAttr(); //When the server scan ends we need to rebuild the tree. if(filter_->isComplete()) { tree_->build(); } else { filter_->update(); tree_->build(filter_->match_); } int num=tree_->attrNum(attrFilter_)+tree_->numOfChildren(); //Notifies the model of the number of children nodes to be added to the server node. Q_EMIT beginServerScan(this, num); //We leave the inScan mode. From this moment on the model can see the whole tree in the server. inScan_=false; //Notifies the model that the scan finished. The model can now relayout its new contents. Q_EMIT endServerScan(this, num); adjustFirstScan(); } void VTreeServer::notifyBeginServerClear(ServerHandler* server) { Q_EMIT beginServerClear(this,-1); changeInfo_->clear(); tree_->clear(); filter_->clear(); attrFilter_->clearForceShowAttr(); inScan_=true; } void VTreeServer::notifyEndServerClear(ServerHandler* server) { Q_EMIT endServerClear(this,-1); } void VTreeServer::notifyServerConnectState(ServerHandler* server) { Q_EMIT rerender(); } void VTreeServer::notifyServerActivityChanged(ServerHandler* server) { Q_EMIT dataChanged(this); } //This is called when a normal sync (neither reset nor rescan) is finished. We have delayed the update of the //filter to this point but now we need to do it. void VTreeServer::notifyEndServerSync(ServerHandler* server) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) UiLogS(server_).dbg() << " number of state changes=" << changeInfo_->stateChangeSuites().size(); #endif updateFilter(changeInfo_->stateChangeSuites()); changeInfo_->clear(); } //-------------------------------------------------- // NodeObserver methods //-------------------------------------------------- void VTreeServer::notifyBeginNodeChange(const VNode* vnode, const std::vector<ecf::Aspect::Type>& aspect, const VNodeChange& change) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif if(vnode==nullptr) return; VTreeNode* node=tree_->find(vnode); bool attrNumCh=(std::find(aspect.begin(),aspect.end(),ecf::Aspect::ADD_REMOVE_ATTR) != aspect.end()); bool nodeNumCh=(std::find(aspect.begin(),aspect.end(),ecf::Aspect::ADD_REMOVE_NODE) != aspect.end()); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " node=" << vnode->strName(); #endif //----------------------------------------------------------------------- // The number of attributes changed but the number of nodes is the same! //----------------------------------------------------------------------- if(node && attrNumCh && !nodeNumCh) { //We do not deal with the attributes if they were never used for the given node. //The first access to the attributes makes them initialised in the tree node. if(node->isAttrInitialised()) { //Update the forceshow attribute in the filter because //it might have been deleted/reallocated attrFilter_->updateForceShowAttr(); //This is the already updated attribute num int currentNum=vnode->attrNum(attrFilter_); //That is the attribute num we store in the tree node. int cachedNum=node->attrNum(attrFilter_); Q_ASSERT(cachedNum >= 0); int diff=currentNum-cachedNum; if(diff != 0) { Q_EMIT beginAddRemoveAttributes(this,node,currentNum,cachedNum); //We update the attribute num in the tree node node->updateAttrNum(attrFilter_); Q_EMIT endAddRemoveAttributes(this,node,currentNum,cachedNum); } //This can happen. When we change a trigger expression the change aspect we receive is ADD_REMOVE_ATTR. //In this case we just update all the attributes of the node! else { if(node) { Q_EMIT attributesChanged(this,node); } } } } //---------------------------------------------------------------------- // The number of nodes changed but number of attributes is the same! //---------------------------------------------------------------------- else if(!attrNumCh && nodeNumCh) { //This can never happen assert(0); } //--------------------------------------------------------------------- // Both the number of nodes and the number of attributes changed! //--------------------------------------------------------------------- else if(attrNumCh && nodeNumCh) { //This can never happen assert(0); } //--------------------------------------------------------------------- // The number of attributes and nodes did not change //--------------------------------------------------------------------- else { //Check the aspects for(auto it : aspect) { //Changes in the nodes if(it == ecf::Aspect::STATE || it == ecf::Aspect::DEFSTATUS || it == ecf::Aspect::SUSPENDED) { if(node && node->isAttrInitialised()) { Q_EMIT nodeChanged(this,node); } if(!vnode->isServer()) changeInfo_->addStateChange(vnode); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " node status changed"; #endif } //Changes might affect the icons else if (it == ecf::Aspect::FLAG || it == ecf::Aspect::SUBMITTABLE || it == ecf::Aspect::TODAY || it == ecf::Aspect::TIME || it == ecf::Aspect::DAY || it == ecf::Aspect::CRON || it == ecf::Aspect::DATE) { if(node && node->isAttrInitialised()) { Q_EMIT nodeChanged(this,node); } } //Changes in the attributes if(it == ecf::Aspect::METER || it == ecf::Aspect::EVENT || it == ecf::Aspect::LABEL || it == ecf::Aspect::LIMIT || it == ecf::Aspect::EXPR_TRIGGER || it == ecf::Aspect::EXPR_COMPLETE || it == ecf::Aspect::REPEAT || it == ecf::Aspect::REPEAT_INDEX || it == ecf::Aspect::NODE_VARIABLE || it == ecf::Aspect::LATE || it == ecf::Aspect::TODAY || it == ecf::Aspect::TIME || it == ecf::Aspect::DAY || it == ecf::Aspect::CRON || it == ecf::Aspect::DATE ) { if(node && node->isAttrInitialised()) { Q_EMIT attributesChanged(this,node); } } } } } void VTreeServer::notifyEndNodeChange(const VNode* vnode, const std::vector<ecf::Aspect::Type>& aspect, const VNodeChange& change) { } void VTreeServer::reload() { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG #endif changeInfo_->clear(); Q_EMIT beginServerClear(this,-1); tree_->clear(); inScan_=true; Q_EMIT endServerClear(this,-1); Q_ASSERT(filter_); filter_->clearForceShowNode(); if(filter_->isComplete()) { tree_->build(); } else { filter_->update(); tree_->build(filter_->match_); } Q_EMIT beginServerScan(this, tree_->attrNum(attrFilter_)+tree_->numOfChildren()); inScan_=false; Q_EMIT endServerScan(this, tree_->attrNum(attrFilter_)+tree_->numOfChildren()); adjustFirstScan(); } void VTreeServer::attrFilterChanged() { //In the tree root the attrNum must be cached/initialised Q_ASSERT(tree_->isAttrInitialised()); int oriNum=tree_->attrNum(attrFilter_)+tree_->numOfChildren(); Q_EMIT beginServerClear(this,oriNum); inScan_=true; Q_EMIT endServerClear(this,oriNum); //We reset the attrNum to the uninitailsed value in the whole tree tree_->resetAttrNum(); //Get the current num of attr and children int num=tree_->attrNum(attrFilter_)+tree_->numOfChildren(); Q_EMIT beginServerScan(this,num); inScan_=false; Q_EMIT endServerScan(this,num); } //This is called when a normal sync (neither reset nor rescan) is finished. We have delayed the update of the //filter to this point but now we need to do it. //It is also called when a forceShowNode is set. // //The vector suitesChanged contains all the suites in which a change happened. The filter //will only be updated for the branches of these nodes. void VTreeServer::updateFilter(const std::vector<VNode*>& suitesChanged) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif //if there was a state change during the sync if(suitesChanged.size() > 0 && !filter_->isNull() && !filter_->isComplete()) { #ifdef _UI_VMODELDATA_DEBUG if(suitesChanged.size() < 0) UiLogS(server_).dbg() << " suites changed:"; for(auto i : suitesChanged) UiLogS(server_).dbg() << " " << i->strName(); #endif //Update the filter for the suites with a status change. topFilterChange //will contain the branches where the filter changed. A branch is //defined by the top level node with a filter status change in a given //suite. A branch cannot be a server (root) but at most a suite. std::vector<VNode*> topFilterChange; filter_->update(suitesChanged,topFilterChange); #ifdef _UI_VMODELDATA_DEBUG if(topFilterChange.size() > 0) UiLogS(server_).dbg() << " top level nodes that changed in filter:"; for(auto & i : topFilterChange) UiLogS(server_).dbg() << " " << i->strName(); #endif //A topFilterChange branch cannot be the root (server) for(auto & i : topFilterChange) { Q_ASSERT(!i->isServer()); } #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " apply changes to branches"; #endif //If something changed in the list of filtered nodes for(auto & i : topFilterChange) { #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " branch: " << i->absNodePath(); #endif //If the filter status of a SUITE has changed if(i->isSuite()) { VNode *suite=i; Q_ASSERT(suite); //This is the branch where there is a change in the filter VTreeNode* tn=tree_->find(i); //Remove the suite if it is in the tree if(tn) { Q_ASSERT(!tn->isRoot()); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " remove suite: " << suite->absNodePath(); #endif int index=tree_->indexOfTopLevel(tn); Q_ASSERT(index >=0); Q_EMIT beginFilterUpdateRemoveTop(this,index); tree_->remove(tn); Q_EMIT endFilterUpdateRemoveTop(this,index); } //Add the suite if it is NOT in the tree else { #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " add suite: " << suite->absNodePath(); #endif VTreeNode *branch=tree_->makeTopLevelBranch(filter_->match_,suite); int index=tree_->indexOfTopLevelToInsert(suite); Q_ASSERT(index >=0); Q_EMIT beginFilterUpdateInsertTop(this,index); tree_->insertTopLevelBranch(branch,index); Q_EMIT endFilterUpdateInsertTop(this,index); } } //If the top level node that changed is not a suite else { //We need to find the nearest existing parent in the tree VTreeNode* tn=tree_->findAncestor(i); //This must be at most a suite. It cannot be the root! Q_ASSERT(tn); Q_ASSERT(!tn->isRoot()); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " tree node to update: " << tn->vnode()->absNodePath(); #endif //First, we remove the branch contents if(tn->numOfChildren() >0) { int totalRows=tn->attrNum(attrFilter_) + tn->numOfChildren(); Q_EMIT beginFilterUpdateRemove(this,tn,totalRows); tree_->removeChildren(tn); Q_EMIT endFilterUpdateRemove(this,tn,totalRows); } //Second, we add the new contents VTreeNode *branch=tree_->makeBranch(filter_->match_,tn); int chNum=branch->numOfChildren(); Q_EMIT beginFilterUpdateAdd(this,tn,chNum); if(chNum > 0) { tree_->replaceWithBranch(tn,branch); } Q_EMIT endFilterUpdateAdd(this,tn,chNum); //branch must be empty now Q_ASSERT(branch->numOfChildren() == 0); delete branch; } } } } //Set the forceShowNode and rerun the filter. The forceShowNode is a node that //has to be visible even if it does not match the status filter. There can be at most one //forceShowNode at any time. void VTreeServer::setForceShowNode(const VNode* node) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif Q_ASSERT(node); if(node == filter_->forceShowNode()) return; //There is no status filter if(filter_->isNull()) { filter_->setForceShowNode(const_cast<VNode*>(node)); return; } //We have a status filter. We need to rerun it for the //branch of the forceShow node else { //find the suite of the node VNode* s=node->suite(); Q_ASSERT(s); Q_ASSERT(s->isTopLevel()); std::vector<VNode*> sv; sv.push_back(s); //modify the filter definition filter_->setForceShowNode(const_cast<VNode*>(node)); //run the filter updateFilter(sv); } } void VTreeServer::setForceShowAttribute(const VAttribute* a) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif Q_ASSERT(a); VNode* vnode=a->parent(); Q_ASSERT(vnode); VTreeNode* node=tree_->find(vnode); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " node=" << node << " Attr=" << a->name() << " type=" << a->typeName(); #endif //Clear clearForceShow(a); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " node after clear=" << node; #endif //clearForce might have removed the node, so we need to find it again! node=tree_->find(vnode); //Tell the attribute filter that this attribute must always be visible //attrFilter_->setForceShowAttr(const_cast<VAttribute*>(a)); //Tell the tree that this node must always be visible filter_->setForceShowNode(const_cast<VNode*>(vnode)); //The node is not visible at the moment e.i. not in the tree. We rerun //updatefilter in the nodes's branch. This will add the node to the tree //and will result in displaying the right attributes as well. if(!node) { #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " node does not exist -->" << node; #endif //find the suite VNode* s=vnode->suite(); Q_ASSERT(s->isTopLevel()); Q_ASSERT(s); std::vector<VNode*> sv; sv.push_back(s); //Tell the attribute filter that this attribute must always be visible attrFilter_->setForceShowAttr(const_cast<VAttribute*>(a)); updateFilter(sv); } //The attribute is not visible (its type is not filtered) else if(!attrFilter_->isSet(a->type())) { #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " attribute type is not filtered -->"; #endif //We only need to handle this case. When the attributes are not yet initialised //the selection in the view will trigger the attribute initialisation. This //will use the filter that we already set to use the attribute (as forceShowAttr). if(node->isAttrInitialised()) { //This is the attribute num we store in the tree node //(and display in the tree). int cachedNum=node->attrNum(attrFilter_); //Tell the attribute filter that this attribute must always be visible attrFilter_->setForceShowAttr(const_cast<VAttribute*>(a)); //This is the current attribute num using the modified attribute filter int currentNum=vnode->attrNum(attrFilter_); //This is the attribute num we store in the tree node //(and display in the tree). //int cachedNum=node->attrNum(attrFilter_); Q_ASSERT(cachedNum >= 0); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " currentNum=" << currentNum << " cachedNum=" << cachedNum; #endif if(currentNum != cachedNum) { Q_EMIT beginAddRemoveAttributes(this,node,currentNum,cachedNum); //We update the attribute num in the tree node node->updateAttrNum(attrFilter_); //This will trigger rerendering the attributes Q_EMIT endAddRemoveAttributes(this,node,currentNum,cachedNum); } //This will trigger rerendering the attributes of the given node when //currentNum and cachedNum are the same. else { Q_EMIT attributesChanged(this,node); } } else { //Tell the attribute filter that this attribute must always be visible attrFilter_->setForceShowAttr(const_cast<VAttribute*>(a)); } } } void VTreeServer::setForceShow(const VItem* item) { if(!item) return; //Get the server if(item->server() == server_) { if(VNode *n=item->isNode()) { setForceShowNode(n); } else if(VAttribute* a=item->isAttribute()) { setForceShowAttribute(a); } } } //Clear the forceShow if it does not match itemNext, which is the the next item //to be set as forceShow void VTreeServer::clearForceShow(const VItem* itemNext) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif if(!itemNext) return; //The stateFilter is unique for each VTreeServer while the AttrFilter is //shared by the servers! VNode* vnPrev=filter_->forceShowNode(); VAttribute* aPrev=attrFilter_->forceShowAttr(); //If there is a forceShowAttribute if(aPrev) { Q_ASSERT(aPrev->parent()->server()); //The stored attribute belongs to this server if(aPrev->parent()->server()== server_) { Q_ASSERT(vnPrev); Q_ASSERT(aPrev->parent() == vnPrev); } //Otherwise we pretend it is 0 else aPrev=nullptr; } //No forceShowNode or forceShow attribute is set. There is nothing to clear! if(!vnPrev && !aPrev) return; //We need to figure out if itemNext is the same foreceShow that we //currently store because in this case there is nothing to do. //Get the server ServerHandler *sh=itemNext->server(); //The server matches if(sh == server_) { //itemNext is a node and it is the same that we store if(VNode *itn=itemNext->isNode()) { //The current forceShow is a node if(!aPrev) { //it is the same that we store or no state filter is defined if(itn == vnPrev || filter_->isNull()) return; } } //itemNext is an attribute if(VAttribute *ita=itemNext->isAttribute()) { if(aPrev) { //The attribute is in the current branch and both the current and next //attribute type is filtered if(ita->parent() == aPrev->parent() && attrFilter_->isSet(aPrev->type()) && attrFilter_->isSet(ita->type())) { return; } //the attribute is the same as before if(aPrev->sameContents(ita)) { return; } } //The item is an attribute (child) of the current showForceNode else if(vnPrev && vnPrev == ita->parent()) return; } } //Need to remove the current showForce attribute if(aPrev) { //Remove the current showForce attribute from the attribute filter attrFilter_->clearForceShowAttr(); //Rebuild the branch of the current showForce node with the //current attribute filter VTreeNode *node=tree_->find(vnPrev); if(node) { Q_ASSERT(node->isAttrInitialised()); //This is the actual num with the current filter int currentNum=vnPrev->attrNum(attrFilter_); //This is the attribute num we store in the tree node //(and display in the tree). int cachedNum=node->attrNum(attrFilter_); Q_ASSERT(cachedNum >= 0); Q_ASSERT(currentNum <= cachedNum); Q_EMIT beginAddRemoveAttributes(this,node,currentNum,cachedNum); //Update the attribute num in the tree node node->updateAttrNum(attrFilter_); //This will trigger rerendering the attributes of the given node //even if currentNum and cachedNum are the same. Q_EMIT endAddRemoveAttributes(this,node,currentNum,cachedNum); } } //Remove the current showForce node from the node status filter filter_->clearForceShowNode(); //Reload the node status filter VNode* s=vnPrev->suite(); Q_ASSERT(s->isTopLevel()); Q_ASSERT(s); std::vector<VNode*> sv; sv.push_back(s); updateFilter(sv); } void VTreeServer::deleteExpandState() { if(expandState_) delete expandState_; expandState_=nullptr; } void VTreeServer::setExpandState(ExpandState* es) { if(expandState_) delete expandState_; expandState_=es; } //========================================== // // VTableServer // //========================================== //It takes ownership of the filter VTableServer::VTableServer(ServerHandler *server,NodeFilterDef* filterDef) : VModelServer(server) { filter_=new TableNodeFilter(filterDef,server); //We have to observe the nodes of the server. //server_->addNodeObserver(this); } VTableServer::~VTableServer() { delete filter_; } NodeFilter* VTableServer::filter() const { return const_cast<TableNodeFilter*>(filter_); } int VTableServer::nodeNum() const { return filter_->matchCount(); } //Node at the position in the list of filtered nodes VNode* VTableServer::nodeAt(int index) const { return filter_->nodeAt(index); } //Position in the list of filtered nodes int VTableServer::indexOf(const VNode* node) const { return filter_->indexOf(node); } //-------------------------------------------------- // ServerObserver methods //-------------------------------------------------- void VTableServer::notifyServerDelete(ServerHandler* s) { UI_ASSERT(false,"server: " << s->longName()); } void VTableServer::notifyBeginServerScan(ServerHandler* server,const VServerChange& change) { inScan_=true; Q_ASSERT(nodeNum() == 0); //At this point we do not know how many nodes we will have in the filter! } void VTableServer::notifyEndServerScan(ServerHandler* server) { Q_ASSERT(inScan_); filter_->update(); Q_EMIT beginServerScan(this,nodeNum()); inScan_=false; Q_EMIT endServerScan(this,nodeNum()); } void VTableServer::notifyBeginServerClear(ServerHandler* server) { Q_EMIT beginServerClear(this,nodeNum()); } void VTableServer::notifyEndServerClear(ServerHandler* server) { int oriNodeNum=nodeNum(); filter_->clear(); //filter_->clearForceShowNode(); Q_EMIT endServerClear(this,oriNodeNum); } void VTableServer::notifyServerConnectState(ServerHandler* server) { Q_EMIT rerender(); } void VTableServer::notifyServerActivityChanged(ServerHandler* server) { Q_EMIT dataChanged(this); } //This is called when a normal sync (no reset or rescan) is finished. We have delayed the update of the //filter to this point but now we need to do it. void VTableServer::notifyEndServerSync(ServerHandler*) { Q_EMIT updateBegin(); reload(); Q_EMIT updateEnd(); } void VTableServer::notifyBeginNodeChange(const VNode* node, const std::vector<ecf::Aspect::Type>& types,const VNodeChange&) { Q_EMIT nodeChanged(this,node); } void VTableServer::notifyEndNodeChange(const VNode* node, const std::vector<ecf::Aspect::Type>& types,const VNodeChange&) { } void VTableServer::reload() { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG_S(server_) #endif int oriNodeNum=nodeNum(); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " oriNodeNum=" << oriNodeNum; #endif Q_EMIT beginServerClear(this,oriNodeNum); VNode *fsn=filter_->forceShowNode(); filter_->clear(); filter_->setForceShowNode(fsn); inScan_=true; Q_EMIT endServerClear(this,oriNodeNum); filter_->update(); Q_EMIT beginServerScan(this, nodeNum()); inScan_=false; Q_EMIT endServerScan(this, nodeNum()); #ifdef _UI_VMODELDATA_DEBUG UiLogS(server_).dbg() << " nodeNum: " << oriNodeNum; #endif } //Set the forceShowNode and rerun the filter. The forceShowNode is a node that //has to be visible even if it does not match the filter. void VTableServer::setForceShowNode(const VNode* node) { if(inScan_) return; if(filter_->indexOf(node) != -1) { clearForceShow(node); return; } Q_ASSERT(node); filter_->setForceShowNode(const_cast<VNode*>(node)); reload(); } void VTableServer::setForceShowAttribute(const VAttribute*) { } void VTableServer::clearForceShow(const VItem* item) { if(!item) return; VNode* vnPrev=filter_->forceShowNode(); if(!vnPrev) return; if(item->parent()->server() == server_) { if(VNode *itn=item->isNode()) { if(itn == vnPrev) return; } if(VAttribute *ita=item->isAttribute()) { if(ita->parent() == vnPrev) { return; } } } filter_->clearForceShowNode(); reload(); } //========================================== // // VModelData // //========================================== VModelData::VModelData(NodeFilterDef *filterDef,AbstractNodeModel* model) : QObject(model), serverNum_(0), serverFilter_(nullptr), filterDef_(filterDef), model_(model), active_(false) { connect(filterDef_,SIGNAL(changed()), this,SLOT(slotFilterDefChanged())); connect(this,SIGNAL(filterDeleteBegin()), model_,SLOT(slotFilterDeleteBegin())); connect(this,SIGNAL(filterDeleteEnd()), model_,SLOT(slotFilterDeleteEnd())); connect(this,SIGNAL(serverAddBegin(int)), model_,SLOT(slotServerAddBegin(int))); connect(this,SIGNAL(serverAddEnd()), model_,SLOT(slotServerAddEnd())); connect(this,SIGNAL(serverRemoveBegin(VModelServer*,int)), model_,SLOT(slotServerRemoveBegin(VModelServer*,int))); connect(this,SIGNAL(serverRemoveEnd(int)), model_,SLOT(slotServerRemoveEnd(int))); #if 0 connect(this,SIGNAL(filterChangeBegun()), model_,SIGNAL(filterChangeBegun())); connect(this,SIGNAL(filterChangeEnded()), model_,SIGNAL(filterChangeEnded())); #endif } VModelData::~VModelData() { clear(); } void VModelData::connectToModel(VModelServer* d) { connect(d,SIGNAL(dataChanged(VModelServer*)), model_,SLOT(slotDataChanged(VModelServer*))); connect(d,SIGNAL(beginServerScan(VModelServer*,int)), model_,SLOT(slotBeginServerScan(VModelServer*,int))); connect(d,SIGNAL(endServerScan(VModelServer*,int)), model_,SLOT(slotEndServerScan(VModelServer*,int))); connect(d,SIGNAL(beginServerClear(VModelServer*,int)), model_,SLOT(slotBeginServerClear(VModelServer*,int))); connect(d,SIGNAL(endServerClear(VModelServer*,int)), model_,SLOT(slotEndServerClear(VModelServer*,int))); //The model relays this signal connect(d,SIGNAL(rerender()), model_,SIGNAL(rerender())); } //Completely clear the data and rebuild everything with a new //ServerFilter. void VModelData::reset(ServerFilter* serverFilter) { clear(); serverFilter_=serverFilter; init(); } void VModelData::init() { serverFilter_->addObserver(this); for(auto i : serverFilter_->items()) { if(ServerHandler *server=i->serverHandler()) { UI_ASSERT(indexOfServer(server) == -1,"server=" << server->name()); add(server); } } } void VModelData::addToServers(VModelServer* s) { servers_.push_back(s); serverNum_=servers_.size(); } void VModelData::clear() { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG #endif if(serverFilter_) serverFilter_->removeObserver(this); serverFilter_=nullptr; for(auto & server : servers_) { delete server; } servers_.clear(); serverNum_=0; } VModelServer* VModelData::server(int n) const { return (n >=0 && n < static_cast<int>(servers_.size()))?servers_[n]:nullptr; } ServerHandler* VModelData::serverHandler(int n) const { return (n >=0 && n < static_cast<int>(servers_.size()))?servers_[n]->server_:nullptr; } int VModelData::indexOfServer(void* idPointer) const { for(std::size_t i=0; i < servers_.size(); i++) { if(servers_[i] == idPointer) return i; } return -1; } ServerHandler* VModelData::serverHandler(void* idPointer) const { for(int i=0; i < serverNum_; i++) { if(servers_[i] == idPointer) return servers_[i]->server_; } return nullptr; } VModelServer* VModelData::server(const void* idPointer) const { for(int i=0; i < serverNum_; i++) { if(servers_[i] == idPointer) return servers_[i]; } return nullptr; } VModelServer* VModelData::server(const std::string& name) const { for(int i=0; i < serverNum_; i++) if(servers_[i]->server_->name() == name) return servers_[i]; return nullptr; } VModelServer* VModelData::server(ServerHandler* s) const { for(int i=0; i < serverNum_; i++) if(servers_[i]->server_ == s) return servers_[i]; return nullptr; } int VModelData::indexOfServer(ServerHandler* s) const { for(int i=0; i < serverNum_; i++) { if(servers_[i]->server_ == s) return i; } return -1; } int VModelData::numOfNodes(int index) const { if(VModelServer *d=server(index)) { return d->nodeNum(); } return 0; } //ServerFilter observer methods void VModelData::notifyServerFilterAdded(ServerItem* item) { if(!item) return; if(ServerHandler *server=item->serverHandler()) { //A server can already be added!! It can happen when we add a server to a tab where no view exists. //In this case a tree view is created automatically and can lead to muliple calls //to this routine with the same server!!! if(indexOfServer(server) != -1) return; //Notifies the model that a change will happen Q_EMIT serverAddBegin(count()); add(server); //Notifies the model that the change has finished Q_EMIT serverAddEnd(); return; } } void VModelData::notifyServerFilterRemoved(ServerItem* item) { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG #endif if(!item) return; #ifdef _UI_VMODELDATA_DEBUG UiLog().dbg() << " server=" << item->longName(); #endif int i=0; for(auto it=servers_.begin(); it!= servers_.end(); ++it) { if((*it)->server_ == item->serverHandler()) { int nodeNum=(*it)->nodeNum(); #ifdef _UI_VMODELDATA_DEBUG UiLog().dbg() << " emit serverRemoveBegin()"; #endif //Notifies the model that a change will happen Q_EMIT serverRemoveBegin(*it,nodeNum); delete *it; servers_.erase(it); serverNum_=servers_.size(); #ifdef _UI_VMODELDATA_DEBUG UiLog().dbg() << " emit serverRemoveEnd()"; #endif //Notifies the model that the change has finished Q_EMIT serverRemoveEnd(nodeNum); return; } i++; } } void VModelData::notifyServerFilterChanged(ServerItem* item) { //Q_EMIT dataChanged(); } void VModelData::notifyServerFilterDelete() { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG #endif #ifdef _UI_VMODELDATA_DEBUG UiLog().dbg() << " emits filterDeleteBegin()"; #endif Q_EMIT filterDeleteBegin(); clear(); #ifdef _UI_VMODELDATA_DEBUG UiLog().dbg() << " emits filterDeleteEnd()"; #endif Q_EMIT filterDeleteEnd(); } //Should only be called once at the beginning void VModelData::setActive(bool active) { if(active != active_) { active_=active; if(active_) reload(); else clear(); } } void VModelData::reload() { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG #endif Q_ASSERT(active_); Q_EMIT updateBegin(); for(int i=0; i < serverNum_; i++) { servers_[i]->reload(); } Q_EMIT updateEnd(); } void VModelData::slotFilterDefChanged() { #ifdef _UI_VMODELDATA_DEBUG UI_FUNCTION_LOG #endif if(active_) reload(); } bool VModelData::isFilterComplete() const { for(int i=0; i < serverNum_; i++) { return servers_[i]->filter()->isComplete(); } return true; } bool VModelData::isFilterNull() const { for(int i=0; i < serverNum_; i++) { return servers_[i]->filter()->isNull(); } return true; } //============================================================== // // VTreeModelData // //============================================================== VTreeModelData::VTreeModelData(NodeFilterDef* filterDef,AttributeFilter* attrFilter,AbstractNodeModel* model) : VModelData(filterDef,model), attrFilter_(attrFilter) { //Attribute filter changes connect(attrFilter_,SIGNAL(changed()), this,SLOT(slotAttrFilterChanged())); } void VTreeModelData::connectToModel(VModelServer* s) { VModelData::connectToModel(s); VTreeServer* ts=s->treeServer(); Q_ASSERT(ts); connect(ts,SIGNAL(beginAddRemoveAttributes(VTreeServer*,const VTreeNode*,int,int)), model_,SLOT(slotBeginAddRemoveAttributes(VTreeServer*,const VTreeNode*,int,int))); connect(ts,SIGNAL(endAddRemoveAttributes(VTreeServer*,const VTreeNode*,int,int)), model_,SLOT(slotEndAddRemoveAttributes(VTreeServer*,const VTreeNode*,int,int))); connect(ts,SIGNAL(nodeChanged(VTreeServer*,const VTreeNode*)), model_,SLOT(slotNodeChanged(VTreeServer*,const VTreeNode*))); connect(ts,SIGNAL(attributesChanged(VTreeServer*,const VTreeNode*)), model_,SLOT(slotAttributesChanged(VTreeServer*,const VTreeNode*))); connect(ts,SIGNAL(beginFilterUpdateRemove(VTreeServer*,const VTreeNode*,int)), model_,SLOT(slotBeginFilterUpdateRemove(VTreeServer*,const VTreeNode*,int))); connect(ts,SIGNAL(endFilterUpdateRemove(VTreeServer*,const VTreeNode*,int)), model_,SLOT(slotEndFilterUpdateRemove(VTreeServer*,const VTreeNode*,int))); connect(ts,SIGNAL(beginFilterUpdateAdd(VTreeServer*,const VTreeNode*,int)), model_,SLOT(slotBeginFilterUpdateAdd(VTreeServer*,const VTreeNode*,int))); connect(ts,SIGNAL(endFilterUpdateAdd(VTreeServer*,const VTreeNode*,int)), model_,SLOT(slotEndFilterUpdateAdd(VTreeServer*,const VTreeNode*,int))); connect(ts,SIGNAL(beginFilterUpdateRemoveTop(VTreeServer*,int)), model_,SLOT(slotBeginFilterUpdateRemoveTop(VTreeServer*,int))); connect(ts,SIGNAL(endFilterUpdateRemoveTop(VTreeServer*,int)), model_,SLOT(slotEndFilterUpdateRemoveTop(VTreeServer*,int))); connect(ts,SIGNAL(beginFilterUpdateInsertTop(VTreeServer*,int)), model_,SLOT(slotBeginFilterUpdateInsertTop(VTreeServer*,int))); connect(ts,SIGNAL(endFilterUpdateInsertTop(VTreeServer*,int)), model_,SLOT(slotEndFilterUpdateInsertTop(VTreeServer*,int))); } void VTreeModelData::add(ServerHandler *server) { //We need to check it. See the comment in VModelData::notifyServerFilterAdded UI_ASSERT(indexOfServer(server) == -1,"server=" << server->name()); VModelServer* d=nullptr; d=new VTreeServer(server,filterDef_,attrFilter_); connectToModel(d); VModelData::addToServers(d); //?????? if(active_) reload(); } void VTreeModelData::slotAttrFilterChanged() { for(int i=0; i < serverNum_; i++) { servers_[i]->treeServer()->attrFilterChanged(); } } void VTreeModelData::deleteExpandState() { for(int i=0; i < serverNum_; i++) { servers_[i]->treeServer()->deleteExpandState(); } } //============================================================== // // VTableModelData // //============================================================== VTableModelData::VTableModelData(NodeFilterDef* filterDef,AbstractNodeModel* model) : VModelData(filterDef,model) { } void VTableModelData::connectToModel(VModelServer* s) { VModelData::connectToModel(s); VTableServer* ts=s->tableServer(); Q_ASSERT(ts); connect(ts,SIGNAL(nodeChanged(VTableServer*,const VNode*)), model_,SLOT(slotNodeChanged(VTableServer*,const VNode*))); } void VTableModelData::add(ServerHandler *server) { //We need to check it. See the comment in VModelData::notifyServerFilterAdded UI_ASSERT(indexOfServer(server) == -1,"server=" << server->name()); VModelServer* d=nullptr; d=new VTableServer(server,filterDef_); connectToModel(d); VModelData::addToServers(d); connect(d,SIGNAL(updateBegin()), this,SIGNAL(updateBegin())); connect(d,SIGNAL(updateEnd()), this,SIGNAL(updateEnd())); if(active_) reload(); } //Gives the position of this server in the full list of filtered nodes. int VTableModelData::position(VTableServer* server) { int start=-1; if(server) { start=0; for(int i=0; i < serverNum_; i++) { if(servers_[i] == server) { return start; } start+=servers_[i]->nodeNum(); } } return start; } //Identifies the range of nodes belonging to this server in the full list of filtered nodes. bool VTableModelData::position(VTableServer* server,int& start,int& count) { start=-1; count=-1; if(server) { if(server->nodeNum() > 0) { count=server->nodeNum(); start=0; for(int i=0; i < serverNum_; i++) { if(servers_[i] == server) { return true; } start+=servers_[i]->nodeNum(); } } } return false; } //Gets the position of the given node in the full list of filtered nodes. //This has to be very fast!!! int VTableModelData::position(VTableServer* server,const VNode *node) const { if(server) { int totalRow=0; for(int i=0; i < serverNum_; i++) { if(servers_[i] == server) { int pos=server->tableServer()->indexOf(node); if(pos != -1) { totalRow+=pos; return totalRow; } else return -1; } else { totalRow+=servers_[i]->nodeNum(); } } } return -1; } //This has to be very fast!!! int VTableModelData::position(const VNode *node) const { int serverIdx=indexOfServer(node->server()); if(serverIdx != -1) { return position(servers_[serverIdx]->tableServer(),node); } return -1; } VNode* VTableModelData::nodeAt(int totalRow) { int cnt=0; if(totalRow < 0) return nullptr; for(int i=0; i < serverNum_; i++) { int pos=totalRow-cnt; if(pos < servers_[i]->nodeNum()) { return servers_[i]->tableServer()->nodeAt(pos); } cnt+= servers_[i]->nodeNum(); } return nullptr; }
26.866465
132
0.610044
[ "vector", "model" ]
4e8a7c07e84ffdb088bee9586e2f2ebf935016f4
938
hpp
C++
src/engine/components/HitboxComponent.hpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
src/engine/components/HitboxComponent.hpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
src/engine/components/HitboxComponent.hpp
arthurchaloin/indie
84fa7f0864c54e4b35620235ca4e852d7b85fffd
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** Thomas Arbona ** File description: ** engine */ #pragma once #include <irrlicht/irrlicht.h> #include <vector> #include <functional> #include "engine/utils/ComponentConstraint.hpp" #include "../helpers/GeometryHelper.hpp" namespace engine { class Entity; struct HitboxComponent { using Constraint = ComponentConstraint<HitboxComponent, false>; using OnCollideFunction = std::function<void(Entity const&)>; HitboxComponent(); HitboxComponent(std::string const& polygon); std::vector<Segment3D> segments3D; float rebound = 0.3; Vec2D patch; Vec2D size; Vec2D WSize; Vec2D AABBPosition; Vec2D AABBWPosition; Polygon hitbox2D; Polygon hitboxW2D; bool hasDebugMode = false; bool isAABBOnly = false; bool isStatic = false; bool isComputed = false; OnCollideFunction onCollide; }; }
22.333333
69
0.666311
[ "vector" ]
4e97c8862d7f4e85ce1d600cb13a7c39931b1e28
25,781
cpp
C++
android/android_42/base/libs/hwui/FontRenderer.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_42/base/libs/hwui/FontRenderer.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_42/base/libs/hwui/FontRenderer.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2010 The Android 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. */ #define LOG_TAG "OpenGLRenderer" #include <SkUtils.h> #include <cutils/properties.h> #include <utils/Log.h> #include "Caches.h" #include "Debug.h" #include "FontRenderer.h" #include "Rect.h" namespace android { namespace uirenderer { /////////////////////////////////////////////////////////////////////////////// // FontRenderer /////////////////////////////////////////////////////////////////////////////// static bool sLogFontRendererCreate = true; FontRenderer::FontRenderer() { if (sLogFontRendererCreate) { INIT_LOGD("Creating FontRenderer"); } mGammaTable = NULL; mInitialized = false; mMaxNumberOfQuads = 1024; mCurrentQuadIndex = 0; mTextMesh = NULL; mCurrentCacheTexture = NULL; mLastCacheTexture = NULL; mLinearFiltering = false; mIndexBufferID = 0; mSmallCacheWidth = DEFAULT_TEXT_SMALL_CACHE_WIDTH; mSmallCacheHeight = DEFAULT_TEXT_SMALL_CACHE_HEIGHT; mLargeCacheWidth = DEFAULT_TEXT_LARGE_CACHE_WIDTH; mLargeCacheHeight = DEFAULT_TEXT_LARGE_CACHE_HEIGHT; char property[PROPERTY_VALUE_MAX]; if (property_get(PROPERTY_TEXT_SMALL_CACHE_WIDTH, property, NULL) > 0) { mSmallCacheWidth = atoi(property); } if (property_get(PROPERTY_TEXT_SMALL_CACHE_HEIGHT, property, NULL) > 0) { mSmallCacheHeight = atoi(property); } if (property_get(PROPERTY_TEXT_LARGE_CACHE_WIDTH, property, NULL) > 0) { mLargeCacheWidth = atoi(property); } if (property_get(PROPERTY_TEXT_LARGE_CACHE_HEIGHT, property, NULL) > 0) { mLargeCacheHeight = atoi(property); } uint32_t maxTextureSize = (uint32_t) Caches::getInstance().maxTextureSize; mSmallCacheWidth = mSmallCacheWidth > maxTextureSize ? maxTextureSize : mSmallCacheWidth; mSmallCacheHeight = mSmallCacheHeight > maxTextureSize ? maxTextureSize : mSmallCacheHeight; mLargeCacheWidth = mLargeCacheWidth > maxTextureSize ? maxTextureSize : mLargeCacheWidth; mLargeCacheHeight = mLargeCacheHeight > maxTextureSize ? maxTextureSize : mLargeCacheHeight; if (sLogFontRendererCreate) { INIT_LOGD(" Text cache sizes, in pixels: %i x %i, %i x %i, %i x %i, %i x %i", mSmallCacheWidth, mSmallCacheHeight, mLargeCacheWidth, mLargeCacheHeight >> 1, mLargeCacheWidth, mLargeCacheHeight >> 1, mLargeCacheWidth, mLargeCacheHeight); } sLogFontRendererCreate = false; } FontRenderer::~FontRenderer() { for (uint32_t i = 0; i < mCacheTextures.size(); i++) { delete mCacheTextures[i]; } mCacheTextures.clear(); if (mInitialized) { // Unbinding the buffer shouldn't be necessary but it crashes with some drivers Caches::getInstance().unbindIndicesBuffer(); glDeleteBuffers(1, &mIndexBufferID); delete[] mTextMesh; } Vector<Font*> fontsToDereference = mActiveFonts; for (uint32_t i = 0; i < fontsToDereference.size(); i++) { delete fontsToDereference[i]; } } void FontRenderer::flushAllAndInvalidate() { if (mCurrentQuadIndex != 0) { issueDrawCommand(); mCurrentQuadIndex = 0; } for (uint32_t i = 0; i < mActiveFonts.size(); i++) { mActiveFonts[i]->invalidateTextureCache(); } for (uint32_t i = 0; i < mCacheTextures.size(); i++) { mCacheTextures[i]->init(); } #if DEBUG_FONT_RENDERER uint16_t totalGlyphs = 0; for (uint32_t i = 0; i < mCacheTextures.size(); i++) { totalGlyphs += mCacheTextures[i]->getGlyphCount(); // Erase caches, just as a debugging facility if (mCacheTextures[i]->getTexture()) { memset(mCacheTextures[i]->getTexture(), 0, mCacheTextures[i]->getWidth() * mCacheTextures[i]->getHeight()); } } ALOGD("Flushing caches: glyphs cached = %d", totalGlyphs); #endif } void FontRenderer::flushLargeCaches() { // Start from 1; don't deallocate smallest/default texture for (uint32_t i = 1; i < mCacheTextures.size(); i++) { CacheTexture* cacheTexture = mCacheTextures[i]; if (cacheTexture->getTexture()) { cacheTexture->init(); for (uint32_t j = 0; j < mActiveFonts.size(); j++) { mActiveFonts[j]->invalidateTextureCache(cacheTexture); } cacheTexture->releaseTexture(); } } } CacheTexture* FontRenderer::cacheBitmapInTexture(const SkGlyph& glyph, uint32_t* startX, uint32_t* startY) { for (uint32_t i = 0; i < mCacheTextures.size(); i++) { if (mCacheTextures[i]->fitBitmap(glyph, startX, startY)) { return mCacheTextures[i]; } } // Could not fit glyph into current cache textures return NULL; } void FontRenderer::cacheBitmap(const SkGlyph& glyph, CachedGlyphInfo* cachedGlyph, uint32_t* retOriginX, uint32_t* retOriginY, bool precaching) { checkInit(); cachedGlyph->mIsValid = false; // If the glyph is too tall, don't cache it if (glyph.fHeight + TEXTURE_BORDER_SIZE * 2 > mCacheTextures[mCacheTextures.size() - 1]->getHeight()) { ALOGE("Font size too large to fit in cache. width, height = %i, %i", (int) glyph.fWidth, (int) glyph.fHeight); return; } // Now copy the bitmap into the cache texture uint32_t startX = 0; uint32_t startY = 0; CacheTexture* cacheTexture = cacheBitmapInTexture(glyph, &startX, &startY); if (!cacheTexture) { if (!precaching) { // If the new glyph didn't fit and we are not just trying to precache it, // clear out the cache and try again flushAllAndInvalidate(); cacheTexture = cacheBitmapInTexture(glyph, &startX, &startY); } if (!cacheTexture) { // either the glyph didn't fit or we're precaching and will cache it when we draw return; } } cachedGlyph->mCacheTexture = cacheTexture; *retOriginX = startX; *retOriginY = startY; uint32_t endX = startX + glyph.fWidth; uint32_t endY = startY + glyph.fHeight; uint32_t cacheWidth = cacheTexture->getWidth(); if (!cacheTexture->getTexture()) { Caches::getInstance().activeTexture(0); // Large-glyph texture memory is allocated only as needed cacheTexture->allocateTexture(); } uint8_t* cacheBuffer = cacheTexture->getTexture(); uint8_t* bitmapBuffer = (uint8_t*) glyph.fImage; unsigned int stride = glyph.rowBytes(); uint32_t cacheX = 0, bX = 0, cacheY = 0, bY = 0; for (cacheX = startX - TEXTURE_BORDER_SIZE; cacheX < endX + TEXTURE_BORDER_SIZE; cacheX++) { cacheBuffer[(startY - TEXTURE_BORDER_SIZE) * cacheWidth + cacheX] = 0; cacheBuffer[(endY + TEXTURE_BORDER_SIZE - 1) * cacheWidth + cacheX] = 0; } for (cacheY = startY - TEXTURE_BORDER_SIZE + 1; cacheY < endY + TEXTURE_BORDER_SIZE - 1; cacheY++) { cacheBuffer[cacheY * cacheWidth + startX - TEXTURE_BORDER_SIZE] = 0; cacheBuffer[cacheY * cacheWidth + endX + TEXTURE_BORDER_SIZE - 1] = 0; } if (mGammaTable) { for (cacheX = startX, bX = 0; cacheX < endX; cacheX++, bX++) { for (cacheY = startY, bY = 0; cacheY < endY; cacheY++, bY++) { uint8_t tempCol = bitmapBuffer[bY * stride + bX]; cacheBuffer[cacheY * cacheWidth + cacheX] = mGammaTable[tempCol]; } } } else { for (cacheX = startX, bX = 0; cacheX < endX; cacheX++, bX++) { for (cacheY = startY, bY = 0; cacheY < endY; cacheY++, bY++) { uint8_t tempCol = bitmapBuffer[bY * stride + bX]; cacheBuffer[cacheY * cacheWidth + cacheX] = tempCol; } } } cachedGlyph->mIsValid = true; } CacheTexture* FontRenderer::createCacheTexture(int width, int height, bool allocate) { CacheTexture* cacheTexture = new CacheTexture(width, height); if (allocate) { Caches::getInstance().activeTexture(0); cacheTexture->allocateTexture(); } return cacheTexture; } void FontRenderer::initTextTexture() { for (uint32_t i = 0; i < mCacheTextures.size(); i++) { delete mCacheTextures[i]; } mCacheTextures.clear(); mUploadTexture = false; mCacheTextures.push(createCacheTexture(mSmallCacheWidth, mSmallCacheHeight, true)); mCacheTextures.push(createCacheTexture(mLargeCacheWidth, mLargeCacheHeight >> 1, false)); mCacheTextures.push(createCacheTexture(mLargeCacheWidth, mLargeCacheHeight >> 1, false)); mCacheTextures.push(createCacheTexture(mLargeCacheWidth, mLargeCacheHeight, false)); mCurrentCacheTexture = mCacheTextures[0]; } // Avoid having to reallocate memory and render quad by quad void FontRenderer::initVertexArrayBuffers() { uint32_t numIndices = mMaxNumberOfQuads * 6; uint32_t indexBufferSizeBytes = numIndices * sizeof(uint16_t); uint16_t* indexBufferData = (uint16_t*) malloc(indexBufferSizeBytes); // Four verts, two triangles , six indices per quad for (uint32_t i = 0; i < mMaxNumberOfQuads; i++) { int i6 = i * 6; int i4 = i * 4; indexBufferData[i6 + 0] = i4 + 0; indexBufferData[i6 + 1] = i4 + 1; indexBufferData[i6 + 2] = i4 + 2; indexBufferData[i6 + 3] = i4 + 0; indexBufferData[i6 + 4] = i4 + 2; indexBufferData[i6 + 5] = i4 + 3; } glGenBuffers(1, &mIndexBufferID); Caches::getInstance().bindIndicesBuffer(mIndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSizeBytes, indexBufferData, GL_STATIC_DRAW); free(indexBufferData); uint32_t coordSize = 2; uint32_t uvSize = 2; uint32_t vertsPerQuad = 4; uint32_t vertexBufferSize = mMaxNumberOfQuads * vertsPerQuad * coordSize * uvSize; mTextMesh = new float[vertexBufferSize]; } // We don't want to allocate anything unless we actually draw text void FontRenderer::checkInit() { if (mInitialized) { return; } initTextTexture(); initVertexArrayBuffers(); mInitialized = true; } void FontRenderer::checkTextureUpdate() { if (!mUploadTexture && mLastCacheTexture == mCurrentCacheTexture) { return; } Caches& caches = Caches::getInstance(); GLuint lastTextureId = 0; // Iterate over all the cache textures and see which ones need to be updated for (uint32_t i = 0; i < mCacheTextures.size(); i++) { CacheTexture* cacheTexture = mCacheTextures[i]; if (cacheTexture->isDirty() && cacheTexture->getTexture()) { // Can't copy inner rect; glTexSubimage expects pointer to deal with entire buffer // of data. So expand the dirty rect to the encompassing horizontal stripe. const Rect* dirtyRect = cacheTexture->getDirtyRect(); uint32_t x = 0; uint32_t y = dirtyRect->top; uint32_t width = cacheTexture->getWidth(); uint32_t height = dirtyRect->getHeight(); void* textureData = cacheTexture->getTexture() + y * width; if (cacheTexture->getTextureId() != lastTextureId) { lastTextureId = cacheTexture->getTextureId(); caches.activeTexture(0); glBindTexture(GL_TEXTURE_2D, lastTextureId); } #if DEBUG_FONT_RENDERER ALOGD("glTexSubimage for cacheTexture %d: x, y, width height = %d, %d, %d, %d", i, x, y, width, height); #endif glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_ALPHA, GL_UNSIGNED_BYTE, textureData); cacheTexture->setDirty(false); } } caches.activeTexture(0); glBindTexture(GL_TEXTURE_2D, mCurrentCacheTexture->getTextureId()); mCurrentCacheTexture->setLinearFiltering(mLinearFiltering, false); mLastCacheTexture = mCurrentCacheTexture; mUploadTexture = false; } void FontRenderer::issueDrawCommand() { checkTextureUpdate(); Caches& caches = Caches::getInstance(); caches.bindIndicesBuffer(mIndexBufferID); if (!mDrawn) { float* buffer = mTextMesh; int offset = 2; bool force = caches.unbindMeshBuffer(); caches.bindPositionVertexPointer(force, buffer); caches.bindTexCoordsVertexPointer(force, buffer + offset); } glDrawElements(GL_TRIANGLES, mCurrentQuadIndex * 6, GL_UNSIGNED_SHORT, NULL); mDrawn = true; } void FontRenderer::appendMeshQuadNoClip(float x1, float y1, float u1, float v1, float x2, float y2, float u2, float v2, float x3, float y3, float u3, float v3, float x4, float y4, float u4, float v4, CacheTexture* texture) { if (texture != mCurrentCacheTexture) { if (mCurrentQuadIndex != 0) { // First, draw everything stored already which uses the previous texture issueDrawCommand(); mCurrentQuadIndex = 0; } // Now use the new texture id mCurrentCacheTexture = texture; } const uint32_t vertsPerQuad = 4; const uint32_t floatsPerVert = 4; float* currentPos = mTextMesh + mCurrentQuadIndex * vertsPerQuad * floatsPerVert; (*currentPos++) = x1; (*currentPos++) = y1; (*currentPos++) = u1; (*currentPos++) = v1; (*currentPos++) = x2; (*currentPos++) = y2; (*currentPos++) = u2; (*currentPos++) = v2; (*currentPos++) = x3; (*currentPos++) = y3; (*currentPos++) = u3; (*currentPos++) = v3; (*currentPos++) = x4; (*currentPos++) = y4; (*currentPos++) = u4; (*currentPos++) = v4; mCurrentQuadIndex++; } void FontRenderer::appendMeshQuad(float x1, float y1, float u1, float v1, float x2, float y2, float u2, float v2, float x3, float y3, float u3, float v3, float x4, float y4, float u4, float v4, CacheTexture* texture) { if (mClip && (x1 > mClip->right || y1 < mClip->top || x2 < mClip->left || y4 > mClip->bottom)) { return; } appendMeshQuadNoClip(x1, y1, u1, v1, x2, y2, u2, v2, x3, y3, u3, v3, x4, y4, u4, v4, texture); if (mBounds) { mBounds->left = fmin(mBounds->left, x1); mBounds->top = fmin(mBounds->top, y3); mBounds->right = fmax(mBounds->right, x3); mBounds->bottom = fmax(mBounds->bottom, y1); } if (mCurrentQuadIndex == mMaxNumberOfQuads) { issueDrawCommand(); mCurrentQuadIndex = 0; } } void FontRenderer::appendRotatedMeshQuad(float x1, float y1, float u1, float v1, float x2, float y2, float u2, float v2, float x3, float y3, float u3, float v3, float x4, float y4, float u4, float v4, CacheTexture* texture) { appendMeshQuadNoClip(x1, y1, u1, v1, x2, y2, u2, v2, x3, y3, u3, v3, x4, y4, u4, v4, texture); if (mBounds) { mBounds->left = fmin(mBounds->left, fmin(x1, fmin(x2, fmin(x3, x4)))); mBounds->top = fmin(mBounds->top, fmin(y1, fmin(y2, fmin(y3, y4)))); mBounds->right = fmax(mBounds->right, fmax(x1, fmax(x2, fmax(x3, x4)))); mBounds->bottom = fmax(mBounds->bottom, fmax(y1, fmax(y2, fmax(y3, y4)))); } if (mCurrentQuadIndex == mMaxNumberOfQuads) { issueDrawCommand(); mCurrentQuadIndex = 0; } } void FontRenderer::setFont(SkPaint* paint, uint32_t fontId, float fontSize) { int flags = 0; if (paint->isFakeBoldText()) { flags |= Font::kFakeBold; } const float skewX = paint->getTextSkewX(); uint32_t italicStyle = *(uint32_t*) &skewX; const float scaleXFloat = paint->getTextScaleX(); uint32_t scaleX = *(uint32_t*) &scaleXFloat; SkPaint::Style style = paint->getStyle(); const float strokeWidthFloat = paint->getStrokeWidth(); uint32_t strokeWidth = *(uint32_t*) &strokeWidthFloat; mCurrentFont = Font::create(this, fontId, fontSize, flags, italicStyle, scaleX, style, strokeWidth); } FontRenderer::DropShadow FontRenderer::renderDropShadow(SkPaint* paint, const char *text, uint32_t startIndex, uint32_t len, int numGlyphs, uint32_t radius, const float* positions) { checkInit(); if (!mCurrentFont) { DropShadow image; image.width = 0; image.height = 0; image.image = NULL; image.penX = 0; image.penY = 0; return image; } mDrawn = false; mClip = NULL; mBounds = NULL; Rect bounds; mCurrentFont->measure(paint, text, startIndex, len, numGlyphs, &bounds, positions); uint32_t paddedWidth = (uint32_t) (bounds.right - bounds.left) + 2 * radius; uint32_t paddedHeight = (uint32_t) (bounds.top - bounds.bottom) + 2 * radius; uint8_t* dataBuffer = new uint8_t[paddedWidth * paddedHeight]; for (uint32_t i = 0; i < paddedWidth * paddedHeight; i++) { dataBuffer[i] = 0; } int penX = radius - bounds.left; int penY = radius - bounds.bottom; mCurrentFont->render(paint, text, startIndex, len, numGlyphs, penX, penY, Font::BITMAP, dataBuffer, paddedWidth, paddedHeight, NULL, positions); blurImage(dataBuffer, paddedWidth, paddedHeight, radius); DropShadow image; image.width = paddedWidth; image.height = paddedHeight; image.image = dataBuffer; image.penX = penX; image.penY = penY; return image; } void FontRenderer::initRender(const Rect* clip, Rect* bounds) { checkInit(); mDrawn = false; mBounds = bounds; mClip = clip; } void FontRenderer::finishRender() { mBounds = NULL; mClip = NULL; if (mCurrentQuadIndex != 0) { issueDrawCommand(); mCurrentQuadIndex = 0; } } void FontRenderer::precache(SkPaint* paint, const char* text, int numGlyphs) { int flags = 0; if (paint->isFakeBoldText()) { flags |= Font::kFakeBold; } const float skewX = paint->getTextSkewX(); uint32_t italicStyle = *(uint32_t*) &skewX; const float scaleXFloat = paint->getTextScaleX(); uint32_t scaleX = *(uint32_t*) &scaleXFloat; SkPaint::Style style = paint->getStyle(); const float strokeWidthFloat = paint->getStrokeWidth(); uint32_t strokeWidth = *(uint32_t*) &strokeWidthFloat; float fontSize = paint->getTextSize(); Font* font = Font::create(this, SkTypeface::UniqueID(paint->getTypeface()), fontSize, flags, italicStyle, scaleX, style, strokeWidth); font->precache(paint, text, numGlyphs); } bool FontRenderer::renderText(SkPaint* paint, const Rect* clip, const char *text, uint32_t startIndex, uint32_t len, int numGlyphs, int x, int y, Rect* bounds) { if (!mCurrentFont) { ALOGE("No font set"); return false; } initRender(clip, bounds); mCurrentFont->render(paint, text, startIndex, len, numGlyphs, x, y); finishRender(); return mDrawn; } bool FontRenderer::renderPosText(SkPaint* paint, const Rect* clip, const char *text, uint32_t startIndex, uint32_t len, int numGlyphs, int x, int y, const float* positions, Rect* bounds) { if (!mCurrentFont) { ALOGE("No font set"); return false; } initRender(clip, bounds); mCurrentFont->render(paint, text, startIndex, len, numGlyphs, x, y, positions); finishRender(); return mDrawn; } bool FontRenderer::renderTextOnPath(SkPaint* paint, const Rect* clip, const char *text, uint32_t startIndex, uint32_t len, int numGlyphs, SkPath* path, float hOffset, float vOffset, Rect* bounds) { if (!mCurrentFont) { ALOGE("No font set"); return false; } initRender(clip, bounds); mCurrentFont->render(paint, text, startIndex, len, numGlyphs, path, hOffset, vOffset); finishRender(); return mDrawn; } void FontRenderer::removeFont(const Font* font) { for (uint32_t ct = 0; ct < mActiveFonts.size(); ct++) { if (mActiveFonts[ct] == font) { mActiveFonts.removeAt(ct); break; } } if (mCurrentFont == font) { mCurrentFont = NULL; } } void FontRenderer::computeGaussianWeights(float* weights, int32_t radius) { // Compute gaussian weights for the blur // e is the euler's number float e = 2.718281828459045f; float pi = 3.1415926535897932f; // g(x) = ( 1 / sqrt( 2 * pi ) * sigma) * e ^ ( -x^2 / 2 * sigma^2 ) // x is of the form [-radius .. 0 .. radius] // and sigma varies with radius. // Based on some experimental radius values and sigma's // we approximately fit sigma = f(radius) as // sigma = radius * 0.3 + 0.6 // The larger the radius gets, the more our gaussian blur // will resemble a box blur since with large sigma // the gaussian curve begins to lose its shape float sigma = 0.3f * (float) radius + 0.6f; // Now compute the coefficints // We will store some redundant values to save some math during // the blur calculations // precompute some values float coeff1 = 1.0f / (sqrt( 2.0f * pi ) * sigma); float coeff2 = - 1.0f / (2.0f * sigma * sigma); float normalizeFactor = 0.0f; for (int32_t r = -radius; r <= radius; r ++) { float floatR = (float) r; weights[r + radius] = coeff1 * pow(e, floatR * floatR * coeff2); normalizeFactor += weights[r + radius]; } //Now we need to normalize the weights because all our coefficients need to add up to one normalizeFactor = 1.0f / normalizeFactor; for (int32_t r = -radius; r <= radius; r ++) { weights[r + radius] *= normalizeFactor; } } void FontRenderer::horizontalBlur(float* weights, int32_t radius, const uint8_t* source, uint8_t* dest, int32_t width, int32_t height) { float blurredPixel = 0.0f; float currentPixel = 0.0f; for (int32_t y = 0; y < height; y ++) { const uint8_t* input = source + y * width; uint8_t* output = dest + y * width; for (int32_t x = 0; x < width; x ++) { blurredPixel = 0.0f; const float* gPtr = weights; // Optimization for non-border pixels if (x > radius && x < (width - radius)) { const uint8_t *i = input + (x - radius); for (int r = -radius; r <= radius; r ++) { currentPixel = (float) (*i); blurredPixel += currentPixel * gPtr[0]; gPtr++; i++; } } else { for (int32_t r = -radius; r <= radius; r ++) { // Stepping left and right away from the pixel int validW = x + r; if (validW < 0) { validW = 0; } if (validW > width - 1) { validW = width - 1; } currentPixel = (float) input[validW]; blurredPixel += currentPixel * gPtr[0]; gPtr++; } } *output = (uint8_t)blurredPixel; output ++; } } } void FontRenderer::verticalBlur(float* weights, int32_t radius, const uint8_t* source, uint8_t* dest, int32_t width, int32_t height) { float blurredPixel = 0.0f; float currentPixel = 0.0f; for (int32_t y = 0; y < height; y ++) { uint8_t* output = dest + y * width; for (int32_t x = 0; x < width; x ++) { blurredPixel = 0.0f; const float* gPtr = weights; const uint8_t* input = source + x; // Optimization for non-border pixels if (y > radius && y < (height - radius)) { const uint8_t *i = input + ((y - radius) * width); for (int32_t r = -radius; r <= radius; r ++) { currentPixel = (float)(*i); blurredPixel += currentPixel * gPtr[0]; gPtr++; i += width; } } else { for (int32_t r = -radius; r <= radius; r ++) { int validH = y + r; // Clamp to zero and width if (validH < 0) { validH = 0; } if (validH > height - 1) { validH = height - 1; } const uint8_t *i = input + validH * width; currentPixel = (float) (*i); blurredPixel += currentPixel * gPtr[0]; gPtr++; } } *output = (uint8_t) blurredPixel; output++; } } } void FontRenderer::blurImage(uint8_t *image, int32_t width, int32_t height, int32_t radius) { float *gaussian = new float[2 * radius + 1]; computeGaussianWeights(gaussian, radius); uint8_t* scratch = new uint8_t[width * height]; horizontalBlur(gaussian, radius, image, scratch, width, height); verticalBlur(gaussian, radius, scratch, image, width, height); delete[] gaussian; delete[] scratch; } }; // namespace uirenderer }; // namespace android
33.56901
100
0.608355
[ "render", "shape", "vector" ]
4e9b93af7bff97a38d234a130a9fa32b89d18b3d
2,912
cpp
C++
Google CodeJam/CJ191Ba.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
null
null
null
Google CodeJam/CJ191Ba.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
null
null
null
Google CodeJam/CJ191Ba.cpp
anubhawbhalotia/Competitive-Programming
32d7003abf9af4999b3dfa78fe1df9022ebbf50b
[ "MIT" ]
1
2020-05-20T18:36:31.000Z
2020-05-20T18:36:31.000Z
#include<bits/stdc++.h> using namespace std; #define ll long long #define mp make_pair #define pb push_back #define lb lower_bound #define ub upper_bound #define all(v) v.begin(),v.end() #define allr(v) v.rbegin(),v.rend() #define fi first #define se second #define f(i,s,n) for(long i=s;i<n;i++) #define fe(i,s,n) for(long i=s;i<=n;i++) #define fr(i,s,n) for(long i=s;i>n;i--) #define fre(i,s,n) for(long i=s;i>=n;i--) #define mod 998244353 #define all(v) v.begin(),v.end() //Anubhaw Bhalotia https://github.com/anubhawbhalotia typedef vector<int> vi; typedef vector<long> vl; typedef vector<ll> vll; typedef pair<int,int> pii; typedef pair<long,long> pll; typedef pair<ll,ll> pllll; typedef set<int> si; typedef set<long> sl; typedef set<ll> sll; typedef multiset<int> msi; typedef multiset<long> msl; typedef multiset<ll> msll; long lwr_bnd(vl a, long val, long start, long end) { if(val > a[end]) return end + 1; if(val <= a[start]) return start; long mid = (start + end) / 2; if(a[mid] < val) return lwr_bnd(a, val, mid+1, end); else return lwr_bnd(a, val, start, mid); } long upr_bnd(vl a, long val, long start, long end) { if(val >= a[end]) return end + 1; if(val < a[start]) return start; long mid = (start + end) / 2; if(a[mid] <= val) return upr_bnd(a, val, mid+1, end); else return upr_bnd(a, val, start, mid); } int main() { int t; cin>>t; f(z,1,t+1) { long np,q; cin>>np>>q; long x, y, rowMap[1001] = {}, colMap[1001] = {}; char d; sl one, two; vl n,s,e,w; f(i,0,np) { cin>>x>>y>>d; two.insert(x); //Column one.insert(y); //Rows switch(d) { case 'N': n.pb(y); break; case 'S': s.pb(y); break; case 'E': e.pb(x); break; case 'W': w.pb(x); } } sort(all(n)); sort(all(s)); sort(all(e)); sort(all(w)); one.insert(0); //Rows two.insert(0); //Cols one.insert(q); two.insert(q); int p = 0, pp = 0; long last = -1; for(sl :: iterator it = one.begin(); it !=one.end(); it++) //row { if(*it != last + 1) rowMap[p++] = last + 1; rowMap[p++] = *it; last = *it; } last = -1; for(sl :: iterator it = two.begin(); it !=two.end(); it++) //col { if(*it != last + 1) colMap[pp++] = last + 1; colMap[pp++] = *it; last = *it; } int my = 0, mx = 0, ans, maxAns = 0; f(j,0,p) { ans = 0; if(!n.empty()) ans += lwr_bnd(n, rowMap[j], 0, n.size() - 1); if(!s.empty()) ans += s.size() - upr_bnd(s, rowMap[j], 0, s.size() - 1); if(ans > maxAns) { maxAns = ans; my = j; } } maxAns = 0; f(j,0,pp) { ans = 0; if(!e.empty()) ans += lwr_bnd(e, colMap[j], 0, e.size() - 1); if(!w.empty()) ans += w.size() - upr_bnd(w, colMap[j], 0, w.size() - 1); if(ans > maxAns) { maxAns = ans; mx = j; } } cout<<"Case #"<<z<<": "<<colMap[mx]<<" "<<rowMap[my]<<endl; } }
20.507042
68
0.545673
[ "vector" ]
4e9cc8f3700530aeb9e2cc7ba48bc891b9e404d5
1,962
cpp
C++
src/compute/ComputeModule.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
4
2019-07-24T03:24:08.000Z
2022-03-04T07:41:08.000Z
src/compute/ComputeModule.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
3
2019-07-30T22:10:39.000Z
2020-06-15T15:57:08.000Z
src/compute/ComputeModule.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
6
2019-07-30T21:33:07.000Z
2022-03-21T20:53:11.000Z
#include "ComputeModule.h" #include <src/common/OpenCL.h> #include <src/common/Optional.h> #include <src/util/Logging.h> #include <src/common/Assert.h> #include <src/compute/opencl/CLProgramLoader.h> #include <src/config/Config.h> namespace riner { ComputeModule::ComputeModule(const Config &config) : allDevices(gatherAllDeviceIds()) { VLOG(5) << "compute ctor scope..."; auto kernelDir = config.global_settings().opencl_kernel_dir(); auto precompiledDir = kernelDir + "precompiled/"; VLOG(5) << "CLProgramLoader make_unique..."; clProgramLoader = std::make_unique<CLProgramLoader>(kernelDir, precompiledDir); VLOG(5) << "CLProgramLoader make_unique...done"; VLOG(5) << "compute ctor scope...done"; } ComputeModule::~ComputeModule() { //this empty destructor enables forward declaration of types contained in member unique_ptrs } const std::vector<DeviceId> &ComputeModule::getAllDeviceIds() const { return allDevices; } optional<cl::Device> ComputeModule::getDeviceOpenCL(const DeviceId &requestId) { std::vector<cl::Platform> clPlatforms; cl::Platform::get(&clPlatforms); for (auto &clPlatform : clPlatforms) { std::vector<cl::Device> clDevices; clPlatform.getDevices(CL_DEVICE_TYPE_ALL, &clDevices); for (auto &clDevice : clDevices) { if (auto deviceId = obtainDeviceIdFromOpenCLDevice(clDevice)) { if (deviceId == requestId) return clDevice; } } } LOG(INFO) << "ComputeModule: in 'getDeviceOpenCL' the device '" << requestId.getName() << "' does not have a corresponding opencl device"; return nullopt; } CLProgramLoader &ComputeModule::getProgramLoaderOpenCL() { RNR_ENSURES(clProgramLoader); return *clProgramLoader; } }
33.254237
100
0.634047
[ "vector" ]
4e9eaa0a1f3cbd4479105e570054505c483a0066
15,235
cpp
C++
tools/driver/driver.cpp
ralic/gnu_comma
f66c6ad0fca1679aaf25fccfd598af4456ee219a
[ "MIT" ]
null
null
null
tools/driver/driver.cpp
ralic/gnu_comma
f66c6ad0fca1679aaf25fccfd598af4456ee219a
[ "MIT" ]
null
null
null
tools/driver/driver.cpp
ralic/gnu_comma
f66c6ad0fca1679aaf25fccfd598af4456ee219a
[ "MIT" ]
null
null
null
// This tool is temporary. It drives the lexer, parser, and type checker over // the contents of a single file. #include "config.h" #include "SourceManager.h" #include "comma/ast/Ast.h" #include "comma/ast/AstResource.h" #include "comma/basic/TextManager.h" #include "comma/basic/IdentifierPool.h" #include "comma/codegen/Generator.h" #include "comma/parser/Parser.h" #include "comma/typecheck/Checker.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/SystemUtils.h" #include "llvm/System/Host.h" #include "llvm/System/Path.h" #include "llvm/System/Process.h" #include "llvm/System/Program.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegistry.h" #include "llvm/Target/TargetSelect.h" #include <algorithm> #include <fstream> #include <iostream> #include <memory> using namespace comma::driver; using llvm::dyn_cast; // The input file name as a positional argument. llvm::cl::opt<std::string> InputFile(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("")); // A switch that asks the driver to perform syntatic and semantic processing // only. llvm::cl::opt<bool> SyntaxOnly("fsyntax-only", llvm::cl::desc("Only perform syntatic and semantic analysis.")); // The entry switch defining the main function to call. llvm::cl::opt<std::string> EntryPoint("e", llvm::cl::desc("Comma procedure to use as an entry point.")); // Emit llvm IR in assembly form. llvm::cl::opt<bool> EmitLLVM("emit-llvm", llvm::cl::desc("Emit llvm assembly.")); // Emit llvm IR in bitcode form. llvm::cl::opt<bool> EmitLLVMBitcode("emit-llvm-bc", llvm::cl::desc("Emit llvm bitcode.")); // Output file. llvm::cl::opt<std::string> OutputFile("o", llvm::cl::desc("Defines the output file."), llvm::cl::init("")); // Destination directory. Default to pwd. llvm::cl::opt<std::string> DestDir("d", llvm::cl::desc("Destination directory."), llvm::cl::init("")); // Disable optimizations. llvm::cl::opt<bool> DisableOpt("disable-opt", llvm::cl::desc("Disable all optimizations.")); // Dump the AST. llvm::cl::opt<bool> DumpAST("dump-ast", llvm::cl::desc("Dump ast to stderr.")); namespace { // Selects a procedure to use as an entry point and generates the corresponding // main function. bool emitEntryPoint(Generator *Gen, const CompilationUnit &cu) { // We must have a well formed entry point string of the form "D.P", where D // is the context domain and P is the procedure to call. typedef std::string::size_type Index; Index dotPos = EntryPoint.find('.'); if (dotPos == std::string::npos) { llvm::errs() << "Malformed entry designator `" << EntryPoint << "'\n"; return false; } std::string capsuleName = EntryPoint.substr(0, dotPos); std::string procName = EntryPoint.substr(dotPos + 1); // Bring the capsule and procedure name into canonical lower case form. std::transform(capsuleName.begin(), capsuleName.end(), capsuleName.begin(), static_cast<int(*)(int)>(std::tolower)); std::transform(procName.begin(), procName.end(), procName.begin(), static_cast<int(*)(int)>(std::tolower)); // Find a declaration in the given compilation unit which matches the needed // capsule. DeclRegion *region = 0; typedef CompilationUnit::decl_iterator ctx_iterator; for (ctx_iterator I = cu.begin_declarations(); I != cu.end_declarations(); ++I) { if (PackageDecl *package = dyn_cast<PackageDecl>(*I)) { if (capsuleName == package->getString()) { region = package->getInstance(); break; } } } if (!region) { llvm::errs() << "Entry capsule `" << capsuleName << "' not found.\n"; return false; } // Find a nullary procedure declaration with the given name. ProcedureDecl *proc = 0; typedef DeclRegion::DeclIter decl_iterator; for (decl_iterator I = region->beginDecls(); I != region->endDecls(); ++I) { ProcedureDecl *candidate = dyn_cast<ProcedureDecl>(*I); if (!candidate) continue; if (procName != candidate->getString()) continue; if (candidate->getArity() == 0) { proc = candidate; break; } } if (!proc) { llvm::errs() << "Entry procedure `" << procName << "' not found.\n"; return false; } Gen->emitEntry(proc); return true; } // Emits llvm IR in either assembly or bitcode format to the given file. If // emitBitcode is true llvm bitcode is generated, otherwise assembly. Returns // zero on sucess and one otherwise. bool outputIR(llvm::Module *M, llvm::sys::Path &outputPath, bool emitBitcode) { // Ensure that the output path is not "-". We never output to stdout. assert(outputPath.str() != "-" && "Cannout output to stdout!"); // Determine the output file mode. If we are emitting bitcode use a binary // stream. unsigned mode = emitBitcode ? llvm::raw_fd_ostream::F_Binary : 0; // Open a stream to the output. std::string message; std::auto_ptr<llvm::raw_ostream> output( new llvm::raw_fd_ostream(outputPath.c_str(), message, mode)); if (!message.empty()) { llvm::errs() << message << '\n'; return false; } if (emitBitcode) llvm::WriteBitcodeToFile(M, *output); else M->print(*output, 0); return true; } bool outputExec(std::vector<SourceItem*> &Items) { // Determine the output file. If no name was explicity given on the command // line derive the output file from the input file name. llvm::sys::Path outputPath; if (OutputFile.empty()) { llvm::sys::Path inputPath(InputFile); outputPath = DestDir; outputPath.appendComponent(inputPath.getBasename()); } else outputPath = OutputFile; // Locate llvm-ld. llvm::sys::Path llvm_ld = llvm::sys::Program::FindProgramByName("llvm-ld"); if (llvm_ld.isEmpty()) { llvm::errs() << "Cannot locate `llvm-ld'.\n"; return false; } // Generate the library path which contains the runtime library. std::string libflag = "-L" COMMA_BUILD_ROOT "/lib"; // Build the argument vector for llvm-ld and execute. llvm::SmallVector<const char*, 16> args; args.push_back(llvm_ld.c_str()); args.push_back("-native"); args.push_back("-o"); args.push_back(outputPath.c_str()); args.push_back(libflag.c_str()); args.push_back("-lruntime"); // Disable optimizations if requested. if (DisableOpt) args.push_back("-disable-opt"); // Append all of the bitcode file names. for (unsigned i = 0; i < Items.size(); ++i) args.push_back(Items[i]->getBitcodePath().c_str()); // Terminate the argument list. args.push_back(0); std::string message; if (llvm::sys::Program::ExecuteAndWait( llvm_ld, &args[0], 0, 0, 0, 0, &message)) { llvm::errs() << "Could not generate executable: " << message << '\n'; return false; } return true; } bool generateSourceItem(SourceItem *Item, TextManager &Manager, AstResource &Resource, Diagnostic &Diag, bool EmitEntry = false) { llvm::InitializeAllTargets(); // FIXME: CodeGen should handle all of this. llvm::LLVMContext context; std::string message; const llvm::Target *target; const llvm::TargetMachine *machine; const llvm::TargetData *data; std::auto_ptr<llvm::Module> M( new llvm::Module(Item->getSourcePath().str(), context)); std::string triple = llvm::sys::getHostTriple(); M->setTargetTriple(triple); target = llvm::TargetRegistry::lookupTarget(triple, message); if (!target) { std::cerr << "Could not auto-select target architecture for " << triple << ".\n : " << message << std::endl; return false; } machine = target->createTargetMachine(triple, ""); data = machine->getTargetData(); M->setDataLayout(data->getStringRepresentation()); std::auto_ptr<Generator> Gen( Generator::create(M.get(), *data, Manager, Resource)); CompilationUnit *CU = Item->getCompilation(); Gen->emitCompilationUnit(CU); // Generate an entry point and native executable if requested. if (EmitEntry && !EntryPoint.empty()) { if (!emitEntryPoint(Gen.get(), *CU)) return false; } // Emit llvm IR if requested. if (EmitLLVM) { llvm::sys::Path output(DestDir); if (!output.exists()) { std::string message; if (output.createDirectoryOnDisk(true, &message)) { llvm::errs() << "Could not create output directory: " << message << '\n'; return false; } } output.appendComponent(Item->getSourcePath().getBasename()); output.appendSuffix("ll"); if (!outputIR(M.get(), output, false)) return false; Item->setIRPath(output); } // Emit llvm bitcode if requested. if (EmitLLVMBitcode) { llvm::sys::Path output(DestDir); if (!output.exists()) { std::string message; if (output.createDirectoryOnDisk(true, &message)) { llvm::errs() << "Could not create output directory: " << message << '\n'; return false; } } output.appendComponent(Item->getSourcePath().getBasename()); output.appendSuffix("bc"); if (!outputIR(M.get(), output, true)) return false; Item->setBitcodePath(output); } return true; } Decl *findPrincipleDeclaration(Diagnostic &Diag, SourceItem *Item) { CompilationUnit *CU = Item->getCompilation(); assert(CU && "Dependency not resolved!"); std::string target = Item->getSourcePath().getBasename(); std::transform(target.begin(), target.end(), target.begin(), tolower); typedef CompilationUnit::decl_iterator iterator; iterator I = CU->begin_declarations(); iterator E = CU->end_declarations(); for ( ; I != E; ++I) { Decl *decl = *I; std::string candidate = decl->getIdInfo()->getString(); std::transform(candidate.begin(), candidate.end(), candidate.begin(), tolower); if (candidate == target) return decl; } Diag.getStream() << "File `" << Item->getSourcePath().str() << "' does not define a unit named `" << target << "'\n"; return 0; } bool compileSourceItem(SourceItem *RootItem, AstResource &Resource, Diagnostic &Diag) { typedef std::vector<SourceItem*>::reverse_iterator source_iterator; std::vector<SourceItem*> Items; RootItem->extractDependencies(Items); // If an entry point was defined we must generate an executable. Ensure // bitcode is generated in this case. if (!EntryPoint.empty()) EmitLLVMBitcode = true; // Process the dependencies in reverse order. TextManager TM; for (source_iterator I = Items.rbegin(), E = Items.rend(); I != E; ++I) { SourceItem *Item = *I; TextProvider &TP = TM.create(Item->getSourcePath()); std::auto_ptr<CompilationUnit> CU( new CompilationUnit(Item->getSourcePath())); std::auto_ptr<Checker> TC( Checker::create(TM, Diag, Resource, CU.get())); Parser P(TP, Resource.getIdentifierPool(), *TC, Diag); // Initialize the compilation unit with any needed dependencies. for (SourceItem::iterator D = Item->begin(); D != Item->end(); ++D) { // FIXME: We allow multiple declarations in compilation units for // now (so that the test suite does not break). In the future we // will probably insist that a source item provides only one unit // with the required name. For now, ensure that at least one unit // exists with the required name (all other declarations are // effectively private within the source item). Decl *principle; if (!(principle = findPrincipleDeclaration(Diag, *D))) return false; CU->addDependency(principle); } // Drive the parser and type checker. P.parseCompilationUnit(); // We are finished with the source code. Close the TextProvider and // release the associated resources. TP.close(); // Dump the ast if we were asked. if (DumpAST) { typedef CompilationUnit::decl_iterator iterator; iterator I = CU->begin_declarations(); iterator E = CU->end_declarations(); for ( ; I != E; ++I) { Decl *decl = *I; decl->dump(); llvm::errs() << '\n'; } } // Stop processing if the SourceItem did not parse/typecheck cleanly. if (Diag.numErrors() != 0) return false; // Add the compilation unit to the SourceItem. Item->setCompilation(CU.release()); // Codegen if needed. if (!SyntaxOnly) { bool emitEntry = Item == RootItem; if (!generateSourceItem(Item, TM, Resource, Diag, emitEntry)) return false; } } // FIXME: We might want to insist that the root source item declares a unit // with a matching name. However, such a constraint would break the test // suite ATM since the current convention is to use an entry point named // Test.Run regardless of the file name (or perhaps we should not care, // since the dependency graph is cycle free nothing can refer to the root // item anyway). // If an entry point was defined, generate a native executable. if (!EntryPoint.empty()) return outputExec(Items); return true; } } // end anonymous namespace using namespace comma::driver; int main(int argc, char **argv) { llvm::cl::ParseCommandLineOptions(argc, argv); if (InputFile.empty()) { llvm::errs() << "Missing input file.\n"; return 1; } llvm::sys::Path path(InputFile); if (!path.canRead()) { llvm::errs() << "Cannot open `" << path.str() <<"' for reading.\n"; return 1; } if (path.getSuffix() != "cms") { llvm::errs() << "Input files must have a `.cms' extension.\n"; return 1; } if (DestDir.empty()) DestDir = llvm::sys::Path::GetCurrentDirectory().str(); Diagnostic diag; IdentifierPool idPool; AstResource resource(idPool); SourceManager SM(idPool, diag); SourceItem *Item = SM.getSourceItem(path); if (Item) return compileSourceItem(Item, resource, diag) ? 0 : 1; else return 1; }
32.209302
80
0.608139
[ "vector", "transform" ]
4ea447d0972df390ee9daeb42ff4720cd90111bd
1,339
hpp
C++
ligador/include/linker.hpp
bandreghetti/SB_2018-2
bcfba7a05a7cc609420306e0823b2cdbeeefe97d
[ "MIT" ]
null
null
null
ligador/include/linker.hpp
bandreghetti/SB_2018-2
bcfba7a05a7cc609420306e0823b2cdbeeefe97d
[ "MIT" ]
null
null
null
ligador/include/linker.hpp
bandreghetti/SB_2018-2
bcfba7a05a7cc609420306e0823b2cdbeeefe97d
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <list> #include <map> #include <vector> #include <set> #include <utils.hpp> class Linker { private: std::regex intRegEx = std::regex("(\\+|-)?[0-9]+"); std::regex hexRegEx = std::regex("0(x|X)[0-9a-f]{1,4}"); std::regex natRegEx = std::regex("[0-9]+"); int error = 0; std::string errMsg; std::string genErrMsg(std::string, std::string); std::string outputName; std::map<std::string, std::list<std::vector<std::string>>> srcFiles; std::list<std::string> srcFileNames; std::map<std::string, std::map<std::string, std::list<unsigned int>>> useTables; std::set<std::string> definedSymbols; std::map<std::string, std::map<std::string, unsigned int>> defTables; std::map<std::string, std::list<unsigned int>> relativeListMap; std::map<std::string, std::vector<int>> machineCode; std::map<std::string, unsigned int> sizeMap; std::map<std::string, unsigned int> byteOffsetMap; std::vector<int> linkedCode; public: Linker(std::list<std::string>); int printOutput(); int getError(); std::string getErrorMessage(); int parseTables(); int printTables(); int link(); int writeOutput(); };
29.755556
88
0.587752
[ "vector" ]
4ea581c8630ab5dda1ae954a92529a5c33fd8fcb
1,536
hh
C++
include/vcf2multialign/variant_processor.hh
tsnorri/vcf2multialign
ee987f55b376a5db9c260e6a38201a09d940fd7e
[ "MIT" ]
2
2019-06-13T16:16:16.000Z
2020-10-17T00:40:58.000Z
include/vcf2multialign/variant_processor.hh
tsnorri/vcf2multialign
ee987f55b376a5db9c260e6a38201a09d940fd7e
[ "MIT" ]
1
2020-01-05T10:48:08.000Z
2020-01-05T13:19:28.000Z
include/vcf2multialign/variant_processor.hh
tsnorri/vcf2multialign
ee987f55b376a5db9c260e6a38201a09d940fd7e
[ "MIT" ]
1
2018-05-18T08:46:52.000Z
2018-05-18T08:46:52.000Z
/* * Copyright (c) 2019 Tuukka Norri * This code is licensed under MIT license (see LICENSE for details). */ #ifndef VCF2MULTIALIGN_VARIANT_PROCESSOR_HH #define VCF2MULTIALIGN_VARIANT_PROCESSOR_HH #include <libbio/vcf/subfield.hh> #include <vcf2multialign/types.hh> #include <vcf2multialign/variant_processor_delegate.hh> namespace vcf2multialign { class variant_processor { public: enum class variant_check_status : std::uint8_t { PASS, ERROR, FATAL_ERROR }; typedef std::vector <libbio::vcf::info_field_base *> vcf_info_field_vector; protected: libbio::vcf::reader *m_reader{}; vector_type const *m_reference{}; std::string const *m_chromosome_name{}; public: variant_processor() = default; variant_processor( libbio::vcf::reader &reader, vector_type const &reference, std::string const &chromosome_name ): m_reader(&reader), m_reference(&reference), m_chromosome_name(&chromosome_name) { } virtual ~variant_processor() {} libbio::vcf::reader &reader() { return *m_reader; } vector_type const &reference() { return *m_reference; } void fill_filter_by_assigned( std::vector <std::string> const &field_names_for_filter_by_assigned, vcf_info_field_vector &filter_by_assigned, variant_processor_delegate &delegate ); variant_check_status check_variant( libbio::vcf::transient_variant const &var, vcf_info_field_vector const &filter_by_assigned, variant_processor_delegate &delegate ); }; } #endif
23.272727
77
0.729167
[ "vector" ]
4ea70f65a520720b61f55b156dad64492a426987
385
cpp
C++
1877/P1877/P1877/main.cpp
swy20190/Leetcode-Cracker
3b80eacfa63983d5fcc50442f0813296d5c1af94
[ "MIT" ]
null
null
null
1877/P1877/P1877/main.cpp
swy20190/Leetcode-Cracker
3b80eacfa63983d5fcc50442f0813296d5c1af94
[ "MIT" ]
null
null
null
1877/P1877/P1877/main.cpp
swy20190/Leetcode-Cracker
3b80eacfa63983d5fcc50442f0813296d5c1af94
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include <algorithm> using namespace std; class Solution { public: int minPairSum(vector<int>& nums) { sort(nums.begin(), nums.end()); int answer = INT_MIN; for (int i = 0; i < nums.size() / 2; i++) { int pair_sum = nums[i] + nums[nums.size() - 1 - i]; if (pair_sum > answer) { answer = pair_sum; } } return answer; } };
19.25
54
0.605195
[ "vector" ]
4eb501b3c30e4c9666d8e04b229a91f6c79c1878
2,555
cpp
C++
src/objparser.cpp
ccoverstreet/Tarcza
8cb49b8fac7026201b0a6d25a351ec70542ac431
[ "MIT" ]
null
null
null
src/objparser.cpp
ccoverstreet/Tarcza
8cb49b8fac7026201b0a6d25a351ec70542ac431
[ "MIT" ]
4
2021-10-18T03:52:13.000Z
2022-01-26T22:50:45.000Z
src/objparser.cpp
ccoverstreet/Tarcza
8cb49b8fac7026201b0a6d25a351ec70542ac431
[ "MIT" ]
null
null
null
#include "./objparser.h" #include <string> #include <iostream> #include <cstdint> #include <cmath> #include <map> Geometry parseObjFile(const char *filename, YAML::Node partname_map, YAML::Node material_map) { std::fstream input_file(filename); std::vector<Eigen::Vector3f> vertices; std::vector<Triangle> triangles; std::map<std::string, Part> part_map; std::string cur_part = ""; std::string cur_mat = ""; size_t cur_tri_index = 0; size_t start_tri_index = 0; size_t skipped_triangles = 0; while (!input_file.fail()) { std::string desc; input_file >> desc; if (desc == "o") { continue; } else if (desc == "g") { while (input_file.peek() == ' ') { input_file.ignore(1); } if (cur_mat != "VOID" && cur_part != "") { part_map.insert(std::pair<std::string, Part>(cur_part, Part(cur_part, start_tri_index, cur_tri_index, material_map[cur_mat.c_str()]))); } start_tri_index = cur_tri_index; std::string part; std::getline(input_file, part); std::cout << "\nReading part \"" << part << "\"...\n"; cur_part = part; cur_mat = partname_map[cur_part].as<std::string>(); continue; } if (cur_mat == "VOID") { input_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (desc == "v") { skipped_triangles++; } continue; } if (desc == "v") { float x, y, z; input_file >> x; input_file >> y; input_file >> z; vertices.push_back(Eigen::Vector3f(x, y, z) * 100); } else if (desc == "f") { std::string v1; std::string v2; std::string v3; input_file >> v1 >> v2 >> v3; uint32_t i_v1 = std::stoi(v1.substr(0, v1.find("/"))) - 1 - skipped_triangles; uint32_t i_v2 = std::stoi(v2.substr(0, v2.find("/"))) - 1 - skipped_triangles; uint32_t i_v3 = std::stoi(v3.substr(0, v3.find("/"))) - 1 - skipped_triangles; auto vect1 = vertices[i_v1]; auto vect2 = vertices[i_v2]; auto vect3 = vertices[i_v3]; auto raw_norm = (vect2 - vect1).cross(vect3 - vect1); auto norm = raw_norm / sqrt(raw_norm.dot(raw_norm)); //+ 1E-10f); //std::cout << norm << "\n\n"; triangles.push_back(Triangle{vect1, vect2, vect3, norm}); cur_tri_index += 1; } } if (cur_part != "" && cur_mat != "VOID") { part_map.insert(std::pair<std::string, Part>(cur_part, Part(cur_part, start_tri_index, cur_tri_index, material_map[cur_mat.c_str()]))); start_tri_index = cur_tri_index; } printf("# of vertices: %d\n", vertices.size()); printf("# of triangles: %d\n", triangles.size()); return Geometry{triangles, part_map}; }
26.071429
139
0.629746
[ "geometry", "vector" ]
4eba3b4b11c035f53921fb2a55798433b670ef60
16,872
cpp
C++
src/astro/gravitation/gravityFieldVariations.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
src/astro/gravitation/gravityFieldVariations.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
src/astro/gravitation/gravityFieldVariations.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #include "tudat/basics/utilities.h" #include "tudat/astro/gravitation/gravityFieldVariations.h" #include "tudat/astro/gravitation/basicSolidBodyTideGravityFieldVariations.h" #include "tudat/math/interpolators/linearInterpolator.h" namespace tudat { namespace gravitation { //! Function to add sine and cosine corrections at given time to coefficient matrices. void PairInterpolationInterface::getCosineSinePair( const double time, Eigen::MatrixXd& sineCoefficients, Eigen::MatrixXd& cosineCoefficients ) { // Interpolate corrections Eigen::MatrixXd cosineSinePair = cosineSineInterpolator_->interpolate( time ); // Split combined interpolated cosine/sine correction block and add to existing values cosineCoefficients.block( startDegree_, startOrder_, numberOfDegrees_, numberOfOrders_ ) += cosineSinePair.block( 0, 0, cosineSinePair.rows( ), cosineSinePair.cols( ) / 2 ); sineCoefficients.block( startDegree_, startOrder_, numberOfDegrees_, numberOfOrders_ ) += cosineSinePair.block( 0, cosineSinePair.cols( ) / 2, cosineSinePair.rows( ), cosineSinePair.cols( ) / 2 ); } //! Function to add sine and cosine corrections at given time to coefficient matrices. void GravityFieldVariations::addSphericalHarmonicsCorrections( const double time, Eigen::MatrixXd& sineCoefficients, Eigen::MatrixXd& cosineCoefficients ) { // Calculate corrections. std::pair< Eigen::MatrixXd, Eigen::MatrixXd > correctionPair = calculateSphericalHarmonicsCorrections( time ); // Add corrections to existing values sineCoefficients.block( minimumDegree_, minimumOrder_, numberOfDegrees_, numberOfOrders_ ) += correctionPair.second; lastSineCorrection_.block( minimumDegree_, minimumOrder_, numberOfDegrees_, numberOfOrders_ ) = correctionPair.second; cosineCoefficients.block( minimumDegree_, minimumOrder_, numberOfDegrees_, numberOfOrders_ ) += correctionPair.first; lastCosineCorrection_.block( minimumDegree_, minimumOrder_, numberOfDegrees_, numberOfOrders_ ) = correctionPair.first; } //! Function to retrieve a variation object of given type (and name if necessary). std::pair< bool, std::shared_ptr< gravitation::GravityFieldVariations > > GravityFieldVariationsSet::getGravityFieldVariation( const BodyDeformationTypes deformationType, const std::string identifier ) { // Declare return pointer. std::shared_ptr< gravitation::GravityFieldVariations > gravityFieldVariation; // Check how many variation objects of request type are in list. int numberOfEntries = std::count( variationType_.begin( ), variationType_.end( ), deformationType ); // Check if number of variation objects of requested type is not zero. bool isEntryFound = 1; if( numberOfEntries == 0 ) { isEntryFound = 0; } // If number of objects of requested type is 1, no further search is required else if( numberOfEntries == 1 ) { // Retrieve index of object and set as return pointer. std::vector< BodyDeformationTypes >::iterator findIterator = std::find( variationType_.begin( ), variationType_.end( ), deformationType ); int vectorIndex = std::distance( variationType_.begin( ), findIterator ); gravityFieldVariation = variationObjects_[ vectorIndex ]; } // If number of objects of requested type is > 1, search for object with required identifier else { bool isCorrectIdentifierFound = 0; // Loop over all entries for( unsigned int i = 0; i < variationType_.size( ); i++ ) { // Check if type and identifer match if( ( variationType_[ i ] == deformationType ) && ( ( variationIdentifier_[ i ] == identifier ) || ( identifierPerType_.at( variationType_[ i ] ).size( ) == 1 ) ) ) { // Set return pointer and exit loop. gravityFieldVariation = variationObjects_[ i ]; isCorrectIdentifierFound = 1; break; } } // Provide warning if no matches are found if( isCorrectIdentifierFound == 0 ) { std::string errorMessage = "Error when retrieving gravity field variation of type " + std::to_string( deformationType ) + ", none of " + std::to_string( numberOfEntries ) + " potential entries match identifier."; throw std::runtime_error( errorMessage ); } } return std::make_pair( isEntryFound, gravityFieldVariation ); } //! Function to create a function linearly interpolating the sine and cosine correction coefficients //! produced by an object of GravityFieldVariations type. std::function< void( const double, Eigen::MatrixXd&, Eigen::MatrixXd& ) > createInterpolatedSphericalHarmonicCorrectionFunctions( std::shared_ptr< GravityFieldVariations > variationObject, const double initialTime, const double finalTime, const double timeStep, const std::shared_ptr< interpolators::InterpolatorSettings > interpolatorSettings ) { // Declare map of combined cosine and since corrections, to be filled and passed to interpolator std::map< double, Eigen::MatrixXd > cosineSineCorrectionsMap; // Perform once for matrices size determination. double currentTime = initialTime; std::pair< Eigen::MatrixXd, Eigen::MatrixXd > singleCorrections; singleCorrections = variationObject->calculateSphericalHarmonicsCorrections( currentTime ); int correctionDegrees = singleCorrections.first.rows( ); int correctionOrders = singleCorrections.first.cols( ); // Loop over all times at which corrections are to be calculated. Eigen::MatrixXd cosineSineCorrections; while( currentTime < finalTime ) { // Calculate current corrections. singleCorrections = variationObject->calculateSphericalHarmonicsCorrections( currentTime ); // Set current corrections in single block. cosineSineCorrections = Eigen::MatrixXd::Zero( correctionDegrees, 2 * correctionOrders ); cosineSineCorrections.block( 0, 0, correctionDegrees, correctionOrders ) += singleCorrections.first; cosineSineCorrections.block( 0, correctionOrders, correctionDegrees, correctionOrders ) += singleCorrections.second; cosineSineCorrectionsMap[ currentTime ] = cosineSineCorrections; // Increment time. currentTime += timeStep; } // Create interpolator std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > > cosineSineCorrectionInterpolator = interpolators::createOneDimensionalInterpolator< double, Eigen::MatrixXd >( cosineSineCorrectionsMap, interpolatorSettings ); // Create pair interpolation interface for TimeDependentSphericalHarmonicsGravityField std::shared_ptr< PairInterpolationInterface > interpolationInterface = std::make_shared< PairInterpolationInterface >( cosineSineCorrectionInterpolator, variationObject->getMinimumDegree( ), variationObject->getMinimumOrder( ), variationObject->getNumberOfDegrees( ), variationObject->getNumberOfOrders( ) ); // Create update function. return std::bind( &PairInterpolationInterface::getCosineSinePair, interpolationInterface, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ); } //! Class constructor. GravityFieldVariationsSet::GravityFieldVariationsSet( const std::vector< std::shared_ptr< GravityFieldVariations > > variationObjects, const std::vector< BodyDeformationTypes > variationType, const std::vector< std::string > variationIdentifier, const std::map< int, std::shared_ptr< interpolators::InterpolatorSettings > > createInterpolator, const std::map< int, double > initialTimes, const std::map< int, double > finalTimes, const std::map< int, double > timeSteps ): variationObjects_( variationObjects ), variationType_( variationType ), variationIdentifier_( variationIdentifier ), createInterpolator_( createInterpolator ), initialTimes_( initialTimes ), finalTimes_( finalTimes ), timeSteps_( timeSteps ) { // Check consistency of input data vector sizes. if( variationObjects_.size( ) != variationType_.size( ) ) { throw std::runtime_error( "Error when making GravityFieldVariationsSet, inconsistent input, type 1" ); } if( variationObjects_.size( ) != variationIdentifier_.size( ) ) { throw std::runtime_error( "Error when making GravityFieldVariationsSet, inconsistent input, type 2" ); } for( unsigned int i = 0; i < variationType_.size( ); i++ ) { identifierPerType_[ variationType_.at( i ) ].push_back( variationIdentifier_.at( i ) ); } // Check if interpolation information is provided where required. for( std::map< int, std::shared_ptr< interpolators::InterpolatorSettings > >::iterator interpolatorSettingsIterator = createInterpolator_.begin( ); interpolatorSettingsIterator != createInterpolator_.end( ); interpolatorSettingsIterator++ ) { if( initialTimes_.count( interpolatorSettingsIterator->first ) == 0 ) { std::string errorMessage = "Error when making GravityFieldVariationsSet, inconsistent input, type 4, " + std::to_string( interpolatorSettingsIterator->first ); throw std::runtime_error( errorMessage ); } if( finalTimes_.count( interpolatorSettingsIterator->first ) == 0 ) { std::string errorMessage = "Error when making GravityFieldVariationsSet, inconsistent input, type 5, " + std::to_string( interpolatorSettingsIterator->first ); throw std::runtime_error( errorMessage ); } if( timeSteps_.count( interpolatorSettingsIterator->first ) == 0 ) { std::string errorMessage = "Error when making GravityFieldVariationsSet, inconsistent input, type 6, " + std::to_string( interpolatorSettingsIterator->first ); throw std::runtime_error( errorMessage ); } } } //! Function to retrieve list of variation functions. std::vector< std::function< void( const double, Eigen::MatrixXd&, Eigen::MatrixXd& ) > > GravityFieldVariationsSet::getVariationFunctions( ) { // Declare list std::vector< std::function< void( const double, Eigen::MatrixXd&, Eigen::MatrixXd& ) > > variationFunctions; // Iterate over all corrections and add correction function. for( unsigned int i = 0; i < variationObjects_.size( ); i++ ) { // If current variation is to be interpolated, create interpolation function and add to list if( createInterpolator_.count( i ) > 0 ) { variationFunctions.push_back( createInterpolatedSphericalHarmonicCorrectionFunctions( variationObjects_[ i ], initialTimes_[ i ], finalTimes_[ i ], timeSteps_[ i ], createInterpolator_[ i ] ) ); } // If current variation is to not be interpolated, create function directly by function // pointer by to current GravityFieldVariations object. else { variationFunctions.push_back( std::bind( &GravityFieldVariations::addSphericalHarmonicsCorrections, variationObjects_[ i ], std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ) ); } } // Return list. return variationFunctions; } //! Function to retrieve the tidal gravity field variation with the specified bodies causing deformation std::shared_ptr< GravityFieldVariations > GravityFieldVariationsSet::getDirectTidalGravityFieldVariation( const std::vector< std::string >& namesOfBodiesCausingDeformation ) { std::shared_ptr< GravityFieldVariations > gravityFieldVariation; // Check number of variation objects of correct type int numberOfBasicModels = std::count( variationType_.begin( ), variationType_.end( ), basic_solid_body ); // If one model of correct type is found, check if it is consistent with input if( ( numberOfBasicModels ) == 1 ) { // Retrieve variation object. It is the return object if no namesOfBodiesCausingDeformation are given gravityFieldVariation = variationObjects_.at( ( std::distance( variationType_.begin( ), std::find( variationType_.begin( ), variationType_.end( ), basic_solid_body ) ) ) ); std::shared_ptr< BasicSolidBodyTideGravityFieldVariations > tidalGravityFieldVariation = std::dynamic_pointer_cast< BasicSolidBodyTideGravityFieldVariations >( gravityFieldVariation ); // Check consistency if( tidalGravityFieldVariation == nullptr ) { throw std::runtime_error( "Error when getting direct tidal gravity field variation, one model found, but type does not match" ); } // Check if consistency with input needs to be determined else if( namesOfBodiesCausingDeformation.size( ) != 0 ) { bool doBodiesMatch = utilities::doStlVectorContentsMatch( tidalGravityFieldVariation->getDeformingBodies( ), namesOfBodiesCausingDeformation ); if( !doBodiesMatch ) { throw std::runtime_error( "Error when getting direct tidal gravity field variation, one model found, but deforming bodies do not match" ); } } } // If no models found, throw exception else if( numberOfBasicModels == 0 ) { throw std::runtime_error( "Error when getting direct tidal gravity field variation, no such model found" ); } else { // If no input bodies are given, no object can be returned: no information is available to choose from list if( namesOfBodiesCausingDeformation.size( ) == 0 ) { throw std::runtime_error( "Error when getting direct tidal gravity field variation, found multiple models, but not id is provided" ); } bool isVariationFound = 0; // Iterate over all objects and check consistency with input for( unsigned int i = 0; i < variationType_.size( ); i++ ) { if( std::dynamic_pointer_cast< gravitation::BasicSolidBodyTideGravityFieldVariations >( variationObjects_.at( i ) ) != nullptr ) { bool doBodiesMatch = utilities::doStlVectorContentsMatch( std::dynamic_pointer_cast< gravitation::BasicSolidBodyTideGravityFieldVariations >( variationObjects_.at( i ) )->getDeformingBodies( ), namesOfBodiesCausingDeformation ); if( doBodiesMatch ) { gravityFieldVariation = variationObjects_.at( i ); isVariationFound = 1; } } } if( isVariationFound == 0 ) { throw std::runtime_error( "Error when getting direct tidal gravity field variation, found multiple models of correct type, but none coincide with ids in list" ); } } return gravityFieldVariation; } //! Function to retrieve the tidal gravity field variations std::vector< std::shared_ptr< GravityFieldVariations > > GravityFieldVariationsSet::getDirectTidalGravityFieldVariations( ) { std::vector< std::shared_ptr< GravityFieldVariations > > directTidalVariations; // Iterate over variation objects and check type for( unsigned int i = 0; i < variationType_.size( ); i++ ) { if( variationType_[ i ] == basic_solid_body ) { directTidalVariations.push_back( variationObjects_[ i ] ); } } return directTidalVariations; } } // namespace gravitation } // namespace tudat
45.477089
159
0.665481
[ "object", "vector", "model" ]
4ebc1806733b69e5f12bdb33371f0bf574babc75
4,060
cpp
C++
cpp/structures/wavelet_matrix.cpp
indy256/codelibrary-sandbox
fd49b2de1cf578084f222a087a472f0760a4fa4d
[ "Unlicense" ]
6
2018-04-20T22:58:22.000Z
2021-03-25T13:09:57.000Z
cpp/structures/wavelet_matrix.cpp
indy256/codelibrary-sandbox
fd49b2de1cf578084f222a087a472f0760a4fa4d
[ "Unlicense" ]
null
null
null
cpp/structures/wavelet_matrix.cpp
indy256/codelibrary-sandbox
fd49b2de1cf578084f222a087a472f0760a4fa4d
[ "Unlicense" ]
2
2018-06-05T18:30:17.000Z
2018-11-14T16:56:19.000Z
#include <bits/stdc++.h> using namespace std; struct BitVector { using uint = uint32_t; vector<uint> blocks, ranktable; int len, blocks_len, count; BitVector(int n = 0) { init(n); } void set(int i) { blocks[i >> 5] |= 1 << (i & 31); } bool get(int i) const { return blocks[i >> 5] >> (i & 31) & 1; } void init(int n) { len = n; blocks_len = (len + 31) / 32 + 1; blocks.assign(blocks_len, 0); } void build() { count = 0; if (len == 0) return; ranktable.assign(blocks_len + 1, 0); for (int i = 0; i < blocks_len; ++i) { ranktable[i] = count; count += popcount(blocks[i]); } ranktable[blocks_len] = count; } int rank(int p) const {// number of 1s in [0, p) int idx = p >> 5; return ranktable[idx] + popcount(blocks[idx] & (1u << (p & 31)) - 1); } int rank(bool b, int p) const { return b ? rank(p) : p - rank(p); } int rank(bool b, int l, int r) const { return rank(b, r) - rank(b, l); } private: static inline int popcount(uint x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); return ((x + (x >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } }; struct WaveletMatrix { using value_t = unsigned int; int height, len; value_t maxval; vector<BitVector> B; vector<int> mids; WaveletMatrix() { init({}); } void init(const vector<value_t> &data) { len = data.size(); maxval = len ? *max_element(data.begin(), data.end()) : 0; for (height = 1; maxval >> 1 >> (height - 1); ++height); B.assign(height, BitVector(len)); mids.resize(height); vector<value_t> now(data), next(len); for (int i = 0; i < height; ++i) { for (int j = 0; j < len; ++j) { mids[i] += (now[j] >> (height - 1 - i) & 1) == 0; } BitVector &bv = B[i]; int zero = 0, one = mids[i]; for (int j = 0; j < len; ++j) { bool b = now[j] >> (height - 1 - i) & 1; if (b) next[one++] = now[j], bv.set(j); else next[zero++] = now[j]; } bv.build(); next.swap(now); } } value_t get(int p) const { value_t ret = 0; for (int i = 0; i < height; ++i) { const BitVector &bv = B[i]; bool dir = bv.get(p); ret = ret << 1 | dir; p = bv.rank(dir, p); if (dir) p += mids[i]; } return ret; } // k-th element in position [left, right) value_t quantile(int left, int right, int k) const { if (k < 0 || right - left <= k) { return -1; } value_t val = 0; for (int i = 0; i < height; i++) { const BitVector &bv = B[i]; int count = bv.rank(true, left, right); bool dir = k < count; val = val << 1 | (dir ? 1 : 0); if (!dir) k -= count; left = bv.rank(dir, left), right = bv.rank(dir, right); if (dir) left += mids[i], right += mids[i]; } return val; } // number of element less/greater than val in position [left, right), return the rank? int rank_all(value_t val, int left, int right, int &res_lt, int &res_gt) const { if (val > maxval) { res_lt = right - left; res_gt = 0; return 0; } res_lt = res_gt = 0; for (int i = 0; i < height; ++i) { const BitVector &bv = B[i]; bool dir = val >> (height - i - 1) & 1; int leftcount = bv.rank(dir, left), rightcount = bv.rank(dir, right); (dir ? res_lt : res_gt) += (right - left) - (rightcount - leftcount); left = leftcount, right = rightcount; if (dir) left += mids[i], right += mids[i]; } return right - left; } }; // usage example int main() { WaveletMatrix waveletMatrix(); }
30.298507
90
0.470197
[ "vector" ]
4ebc83bbc2279f99aea0995be4dc4c3d7dfb70b8
509
hpp
C++
include/vsim/env/physics_scene.hpp
malasiot/vsim
2a69e27364bab29194328af3d050e34f907e226b
[ "MIT" ]
null
null
null
include/vsim/env/physics_scene.hpp
malasiot/vsim
2a69e27364bab29194328af3d050e34f907e226b
[ "MIT" ]
null
null
null
include/vsim/env/physics_scene.hpp
malasiot/vsim
2a69e27364bab29194328af3d050e34f907e226b
[ "MIT" ]
null
null
null
#ifndef __VSIM_PHYSICS_SCENE_HPP__ #define __VSIM_PHYSICS_SCENE_HPP__ #include <string> #include <vector> #include <memory> #include <map> #include <Eigen/Core> #include <vsim/env/scene_fwd.hpp> #include <vsim/env/base_element.hpp> namespace vsim { // a physics scene contains all bodies and models comprising the simulation struct PhysicsScene: public BaseElement { public: PhysicsScene() = default ; std::vector<RigidBodyPtr> bodies_ ; std::vector<PhysicsModelPtr> models_ ; }; } #endif
18.178571
75
0.752456
[ "vector" ]
4ebdb4e94285dd4067856e3b58f85a2044a68da7
2,843
hpp
C++
openstudiocore/src/model/ZoneAirHeatBalanceAlgorithm.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
4
2015-05-02T21:04:15.000Z
2015-10-28T09:47:22.000Z
openstudiocore/src/model/ZoneAirHeatBalanceAlgorithm.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
null
null
null
openstudiocore/src/model/ZoneAirHeatBalanceAlgorithm.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
1
2020-11-12T21:52:36.000Z
2020-11-12T21:52:36.000Z
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_ZONEAIRHEATBALANCEALGORITHM_HPP #define MODEL_ZONEAIRHEATBALANCEALGORITHM_HPP #include "ModelAPI.hpp" #include "ModelObject.hpp" namespace openstudio { namespace model { namespace detail { class ZoneAirHeatBalanceAlgorithm_Impl; } // detail /** ZoneAirHeatBalanceAlgorithm is a ModelObject that wraps the OpenStudio IDD object 'OS:ZoneAirHeatBalanceAlgorithm'. */ class MODEL_API ZoneAirHeatBalanceAlgorithm : public ModelObject { public: /** @name Constructors and Destructors */ //@{ virtual ~ZoneAirHeatBalanceAlgorithm() {} //@} static IddObjectType iddObjectType(); static std::vector<std::string> validAlgorithmValues(); /** @name Getters */ //@{ std::string algorithm() const; bool isAlgorithmDefaulted() const; //@} /** @name Setters */ //@{ bool setAlgorithm(std::string algorithm); void resetAlgorithm(); //@} /** @name Other */ //@{ //@} protected: /// @cond typedef detail::ZoneAirHeatBalanceAlgorithm_Impl ImplType; explicit ZoneAirHeatBalanceAlgorithm(std::shared_ptr<detail::ZoneAirHeatBalanceAlgorithm_Impl> impl); friend class detail::ZoneAirHeatBalanceAlgorithm_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; explicit ZoneAirHeatBalanceAlgorithm(Model& model); /// @endcond private: REGISTER_LOGGER("openstudio.model.ZoneAirHeatBalanceAlgorithm"); }; /** \relates ZoneAirHeatBalanceAlgorithm*/ typedef boost::optional<ZoneAirHeatBalanceAlgorithm> OptionalZoneAirHeatBalanceAlgorithm; /** \relates ZoneAirHeatBalanceAlgorithm*/ typedef std::vector<ZoneAirHeatBalanceAlgorithm> ZoneAirHeatBalanceAlgorithmVector; } // model } // openstudio #endif // MODEL_ZONEAIRHEATBALANCEALGORITHM_HPP
29.309278
123
0.690116
[ "object", "vector", "model" ]
4ec8eea73e359ff18aaef606cbc94fd79f953537
515
hpp
C++
include/Entity/Sphere.hpp
xubury/OpenGLApp
60d199351ec0406b372dd0aeaaea0a5b1664a327
[ "BSD-3-Clause" ]
2
2021-06-27T12:52:57.000Z
2021-08-24T21:25:57.000Z
include/Entity/Sphere.hpp
xubury/OpenGLApp
60d199351ec0406b372dd0aeaaea0a5b1664a327
[ "BSD-3-Clause" ]
null
null
null
include/Entity/Sphere.hpp
xubury/OpenGLApp
60d199351ec0406b372dd0aeaaea0a5b1664a327
[ "BSD-3-Clause" ]
null
null
null
#ifndef SPHERE_HPP #define SPHERE_HPP #include "Entity/EntityBase.hpp" #include "Graphic/VertexArray.hpp" #include "Graphic/Material.hpp" namespace te { class Sphere : public EntityBase { public: Sphere(EntityManager<EntityBase> *manager, uint32_t id, float radius, Ref<Material> material); void draw(const Shader &shader, const glm::mat4 &transform) const override; private: Ref<VertexArray> m_sphere; Ref<Material> m_material; }; } // namespace te #endif /* SPHERE_HPP */
20.6
79
0.71068
[ "transform" ]