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
20b2e2750169e84330b84729a781491480dded6e
10,041
hpp
C++
include/triton_helpers.hpp
miguelusque/hugectr_backend
277fb1acd78a8268f642437dd3cc49e485a8d20b
[ "BSD-3-Clause" ]
null
null
null
include/triton_helpers.hpp
miguelusque/hugectr_backend
277fb1acd78a8268f642437dd3cc49e485a8d20b
[ "BSD-3-Clause" ]
null
null
null
include/triton_helpers.hpp
miguelusque/hugectr_backend
277fb1acd78a8268f642437dd3cc49e485a8d20b
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2021, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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. #pragma once #include <boost/algorithm/string.hpp> #include <functional> #include <inference/inference_utils.hpp> #include <triton_common.hpp> #include "triton/backend/backend_common.h" namespace triton { namespace backend { namespace hugectr { class TritonJsonHelper { public: // --- BASIC TYPES --- /** * Maps JSON values as follows: * false, "false", "0" => false * true, "true", <non-zero number> => true * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( bool& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON double values or strings that represent doubles. * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( double& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON float values or strings that represent floats. * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( float& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON integer values or strings that represent integers. * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( int32_t& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON long integer values or strings that represent long integers. * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( int64_t& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON size_t values or strings that represent a size_t. * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( size_t& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON string values. * * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( std::string& value, const common::TritonJson::Value& json, const char* key, bool required); // --- ENUM TYPES --- /** * Maps JSON string values that represent a \p DatabaseType_t . * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( HugeCTR::DatabaseType_t& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON string values that represent a \p DatabaseHashMapAlgorithm_t . * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( HugeCTR::DatabaseHashMapAlgorithm_t& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON string values that represent a \p DatabaseOverflowPolicy_t . * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( HugeCTR::DatabaseOverflowPolicy_t& value, const common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON string values that represent a \p UpdateSourceType_t . * @param value The place where the value should be stored. * @param json JSON object. * @param key Name of the member. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( HugeCTR::UpdateSourceType_t& value, const common::TritonJson::Value& json, const char* key, bool required); // --- COLLECTION TYPES --- /** * Maps JSON array containing float values or strings that represent float * values. * * @param json JSON object. * @param key Name of the member. * @param value The place where the value should be stored. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( std::vector<float>& value, common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON array containing integer values or strings that represent integer * values. * * @param json JSON object. * @param key Name of the member. * @param value The place where the value should be stored. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( std::vector<int32_t>& value, common::TritonJson::Value& json, const char* key, bool required); /** * Maps JSON array containing strings. * * @param json JSON object. * @param key Name of the member. * @param value The place where the value should be stored. * @param required If true, will emit a \p TRITONSERVER_Error and return an * error that can be caught with \p RETURN_IF_ERROR if the key does not exist. * @return \p nullptr or error value if error occurred. */ static TRITONSERVER_Error* parse( std::vector<std::string>& value, common::TritonJson::Value& json, const char* key, bool required); }; }}} // namespace triton::backend::hugectr
41.320988
80
0.704711
[ "object", "vector" ]
20b6fe9e5f3d962dd6c14558d0c134854b9c91f5
5,048
cpp
C++
src/cli/transfer/fts3-transfer-status.cpp
cern-fts/fts3
cf9eb5c9f52728929965edf58a86381eec0c4e88
[ "Apache-2.0" ]
9
2018-06-27T09:53:51.000Z
2021-01-19T09:54:37.000Z
src/cli/transfer/fts3-transfer-status.cpp
cern-fts/fts3
cf9eb5c9f52728929965edf58a86381eec0c4e88
[ "Apache-2.0" ]
null
null
null
src/cli/transfer/fts3-transfer-status.cpp
cern-fts/fts3
cf9eb5c9f52728929965edf58a86381eec0c4e88
[ "Apache-2.0" ]
3
2018-07-13T06:17:44.000Z
2021-07-08T04:57:04.000Z
/* * Copyright (c) CERN 2013-2015 * * Copyright (c) Members of the EMI Collaboration. 2010-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * 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 "RestContextAdapter.h" #include "JobStatus.h" #include "ui/TransferStatusCli.h" #include "rest/ResponseParser.h" #include "rest/HttpRequest.h" #include "exception/bad_option.h" #include "exception/cli_exception.h" #include "JsonOutput.h" #include <algorithm> #include <vector> #include <string> #include <iterator> #include <boost/assign.hpp> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> using namespace fts3::cli; static bool isTransferFailed(const std::string& state) { return state == "CANCELED" || state == "FAILED"; } /** * This is the entry point for the fts3-transfer-status command line tool. */ int main(int ac, char* av[]) { static const size_t DEFAULT_LIMIT = 10000; try { TransferStatusCli cli; // create and initialise the command line utility cli.parse(ac, av); if (cli.printHelp()) return 0; cli.validate(); RestContextAdapter ctx(cli.getService(), cli.capath(), cli.getCertAndKeyPair(), cli.isInsecure()); cli.printApiDetails(ctx); // archived content? bool archive = cli.queryArchived(); // get job IDs that have to be check std::vector<std::string> jobIds = cli.getJobIds(); // iterate over job IDs std::vector<std::string>::iterator it; for (it = jobIds.begin(); it < jobIds.end(); it++) { std::string jobId = *it; std::ofstream failedFiles; if (cli.dumpFailed()) { failedFiles.open(jobId.c_str(), std::ios_base::out); if (failedFiles.fail()) throw bad_option("dump-failed", strerror(errno)); } JobStatus status = cli.isVerbose() ? ctx.getTransferJobSummary(jobId, archive) : ctx.getTransferJobStatus(jobId, archive) ; // If a list is requested, or dumping the failed transfers, // get the transfers if (cli.list() || cli.dumpFailed()) { size_t offset = 0; size_t cnt = 0; do { // do the request std::vector<FileInfo> const vect = ctx.getFileStatus(jobId, archive, (int)offset, (int)DEFAULT_LIMIT, cli.detailed()); cnt = vect.size(); std::vector<FileInfo>::const_iterator it; for (it = vect.begin(); it < vect.end(); it++) { if (cli.list()) { status.addFile(*it); } else if (cli.dumpFailed() && isTransferFailed(it->getState())) { failedFiles << it->getSource() << " " << it->getDestination() << std::endl; } } offset += vect.size(); } while(cnt == DEFAULT_LIMIT); } MsgPrinter::instance().print(status); } } catch(cli_exception const & ex) { MsgPrinter::instance().print(ex); return 1; } catch(std::exception& ex) { MsgPrinter::instance().print(ex); return 1; } catch(...) { MsgPrinter::instance().print("error", "exception of unknown type!"); return 1; } return 0; }
33.879195
127
0.461767
[ "vector" ]
20b884fb8b5f1b688d77b2b2a8e2c03bfa1cbd8e
262
cpp
C++
library/Methods/Maths/number-theory/common-divisors-two-nums.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
4
2021-01-05T09:25:59.000Z
2021-09-27T03:57:28.000Z
library/Methods/Maths/number-theory/common-divisors-two-nums.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
null
null
null
library/Methods/Maths/number-theory/common-divisors-two-nums.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
null
null
null
// calculate the gcd of given two numbers, and then count divisors of that gcd vector<long long> v; template<typename T> void common_div(T a ,T b){ T g = __gcd(a,b); for (T i = 1; i*i <= g; i++) { if (g%i==0) { v.push_back(i); v.push_back(g/i); } } }
23.818182
78
0.603053
[ "vector" ]
20b885961396a1b6f36a040f1fc3fbc464d6e3e3
4,288
cpp
C++
MEX/src/cpp/vision/features/multi_bow_extractor.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
47
2016-07-25T00:48:59.000Z
2021-02-17T09:19:03.000Z
MEX/src/cpp/vision/features/multi_bow_extractor.cpp
umariqb/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
5
2016-09-17T19:40:46.000Z
2018-11-07T06:49:02.000Z
MEX/src/cpp/vision/features/multi_bow_extractor.cpp
iqbalu/3D_Pose_Estimation_CVPR2016
83f6bf36aa68366ea8fa078eea6d91427e28503b
[ "BSD-3-Clause" ]
35
2016-07-21T09:13:15.000Z
2019-05-13T14:11:37.000Z
/* * multi_bow_extractor.cpp * * Created on: Nov 10, 2011 * Author: lbossard */ #include "multi_bow_extractor.hpp" #include <vector> #include <tr1/unordered_map> #include <algorithm> #include <boost/foreach.hpp> #include <boost/filesystem/path.hpp> namespace fs = boost::filesystem; #include <glog/logging.h> #include "cpp/utils/file_utils.hpp" #include "cpp/utils/serialization/opencv_serialization.hpp" #include "cpp/utils/serialization/serialization.hpp" namespace vision { namespace features { MultiBowExtractor::MultiBowExtractor() { // TODO Auto-generated constructor stub } MultiBowExtractor::~MultiBowExtractor() { } bool MultiBowExtractor::loadBows(const std::vector<fs::path>& vocs) { // make sure, that the same collection stays the same std::vector<fs::path> vocabulary_files(vocs); std::sort(vocabulary_files.begin(), vocabulary_files.end()); // vocabulary_files.resize(std::min(200UL, vocabulary_files.size())); cv::Mat_<float> all_vocs; int voc_size = -1; BOOST_FOREACH(const fs::path& vocabulary_file, vocabulary_files) { // read vocabulary cv::Mat_<float> voc; if (!utils::serialization::read_binary_archive(vocabulary_file.string(), voc) || voc.data == NULL) { LOG(ERROR) << "Could not load vocabulary '" << vocabulary_file.string() << "'" << std::endl; return false; } if (voc_size == -1) { voc_size = voc.rows; } else if (voc.rows != voc_size) { LOG(ERROR) << "Vocabularies don't have the same size. ("<< voc_size << "!= " << voc.rows << std::endl; return false; } all_vocs.push_back(voc); } bow_extractor_.reset(new BowExtractor(all_vocs, cvflann::FLANN_INDEX_KDTREE)); words_per_voc_ = voc_size; /* * For non equal sized vocs: record start_id of the particular vocabulary. * the voc_id for a given word id can then be found via * int voc_id = std::upper_bound(voc_indexes.begin(), voc_indexes.end(), words[idx]) - voc_indexes.begin() - 1; */ return true; } /** * Matches the features to all known words. * @param low_level_features * @param visual_words */ void MultiBowExtractor::match(const cv::Mat_<float>& low_level_features, std::vector<BowExtractor::WordId>& visual_words) { bow_extractor_->match(low_level_features, visual_words); } /** * Matches each feature to the vocabulary * Returns not the word id, but the id of the particular vocabulary * @param low_level_features * @param visual_words */ void MultiBowExtractor::matchVocabulary(const cv::Mat_<float>& low_level_features, std::vector<BowExtractor::WordId>& visual_words) { bow_extractor_->match(low_level_features, visual_words); for (unsigned int i = 0; i < visual_words.size(); ++i) { visual_words[i] = wordToVocabularyId(visual_words[i]); } } /** * Matches the features to its k nearest visual words and returns the dominant * class. * @param low_level_features * @param visual_words * @param k */ void MultiBowExtractor::matchVocabularyKnn( const cv::Mat_<float>& low_level_features, std::vector<BowExtractor::WordId>& visual_words, unsigned int k) { static cv::Mat_<BowExtractor::WordId> indices; static cv::Mat_<float> dists; typedef std::tr1::unordered_map<VocabularyId, unsigned int> VoteMap; VoteMap vote_map; bow_extractor_->match(low_level_features, indices, dists, k); visual_words.resize(indices.rows); for (unsigned int r = 0; r < indices.rows; ++r) { // cast vote for classes vote_map.clear(); for (unsigned int c = 0; c < indices.cols; ++c) { ++vote_map[wordToVocabularyId(indices(r,c))]; } // find max VocabularyId max_id = 0; unsigned int max_count = 0; BOOST_FOREACH(const VoteMap::value_type& item, vote_map) { if (item.second > max_count) { max_id = item.first; max_count = item.second; } } visual_words[r] = max_id; } } } /* namespace features */ } /* namespace vision */
27.844156
131
0.639226
[ "vector" ]
20b9e9e83cc484a3b02f94dce661f548d10fce12
14,631
cpp
C++
src/QMCWaveFunctions/SPOSet.cpp
prckent/qmcpack
127caf219ee99c2449b803821fcc8b1304b66ee1
[ "NCSA" ]
null
null
null
src/QMCWaveFunctions/SPOSet.cpp
prckent/qmcpack
127caf219ee99c2449b803821fcc8b1304b66ee1
[ "NCSA" ]
null
null
null
src/QMCWaveFunctions/SPOSet.cpp
prckent/qmcpack
127caf219ee99c2449b803821fcc8b1304b66ee1
[ "NCSA" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign // Miguel Morales, moralessilva2@llnl.gov, Lawrence Livermore National Laboratory // Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign // Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory // Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory // // File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign ////////////////////////////////////////////////////////////////////////////////////// #include "QMCWaveFunctions/SPOSet.h" #include "Message/Communicate.h" #include "Numerics/MatrixOperators.h" #include "OhmmsData/AttributeSet.h" #include <simd/simd.hpp> #include "Utilities/ProgressReportEngine.h" #include <io/hdf_archive.h> #include <limits> namespace qmcplusplus { SPOSet::SPOSet(bool ion_deriv, bool optimizable) : ionDerivs(ion_deriv), Optimizable(optimizable), OrbitalSetSize(0) #if !defined(ENABLE_SOA) , Identity(false), BasisSetSize(0), C(nullptr) #endif { className = "invalid"; #if !defined(ENABLE_SOA) IsCloned = false; //default is false: LCOrbitalSet.h needs to set this true and recompute needs to check myComm = nullptr; #endif } void SPOSet::evaluate(const ParticleSet& P, PosType& r, ValueVector_t& psi) { APP_ABORT("Need specialization for SPOSet::evaluate(const ParticleSet& P, PosType &r)\n"); } void SPOSet::evaluateDetRatios(const VirtualParticleSet& VP, ValueVector_t& psi, const ValueVector_t& psiinv, std::vector<ValueType>& ratios) { assert(psi.size() == psiinv.size()); for (int iat = 0; iat < VP.getTotalNum(); ++iat) { evaluate(VP, iat, psi); ratios[iat] = simd::dot(psi.data(), psiinv.data(), psi.size()); } } void SPOSet::evaluateThirdDeriv(const ParticleSet& P, int first, int last, GGGMatrix_t& grad_grad_grad_logdet) { APP_ABORT("Need specialization of SPOSet::evaluateThirdDeriv(). \n"); } void SPOSet::evaluate_notranspose(const ParticleSet& P, int first, int last, ValueMatrix_t& logdet, GradMatrix_t& dlogdet, HessMatrix_t& grad_grad_logdet) { APP_ABORT("Need specialization of SPOSet::evaluate_notranspose() for grad_grad_logdet. \n"); } void SPOSet::evaluate_notranspose(const ParticleSet& P, int first, int last, ValueMatrix_t& logdet, GradMatrix_t& dlogdet, HessMatrix_t& grad_grad_logdet, GGGMatrix_t& grad_grad_grad_logdet) { APP_ABORT("Need specialization of SPOSet::evaluate_notranspose() for grad_grad_grad_logdet. \n"); } SPOSet* SPOSet::makeClone() const { APP_ABORT("Missing SPOSet::makeClone for " + className); return 0; } #if !defined(ENABLE_SOA) bool SPOSet::setIdentity(bool useIdentity) { Identity = useIdentity; if (Identity) return true; if (C == nullptr && (OrbitalSetSize > 0) && (BasisSetSize > 0)) { C = new ValueMatrix_t(OrbitalSetSize, BasisSetSize); } else { app_error() << "either OrbitalSetSize or BasisSetSize has an invalid value !!\n"; app_error() << "OrbitalSetSize = " << OrbitalSetSize << std::endl; app_error() << "BasisSetSize = " << BasisSetSize << std::endl; APP_ABORT("SPOSet::setIdentiy "); } return true; } /** Parse the xml file for information on the Dirac determinants. *@param cur the current xmlNode */ bool SPOSet::put(xmlNodePtr cur) { #undef FunctionName #define FunctionName \ printf("Calling FunctionName from %s\n", __FUNCTION__); \ FunctionNameReal //Check if HDF5 present ReportEngine PRE("SPOSet", "put(xmlNodePtr)"); //Special case for sposet hierarchy: go up only once. OhmmsAttributeSet locAttrib; std::string cur_name; locAttrib.add(cur_name, "name"); locAttrib.put(cur); xmlNodePtr curtemp; if (cur_name == "spo-up" || cur_name == "spo-dn") curtemp = cur->parent; else curtemp = cur->parent->parent; std::string MOtype, MOhref; bool H5file = false; OhmmsAttributeSet H5checkAttrib; H5checkAttrib.add(MOtype, "type"); H5checkAttrib.add(MOhref, "href"); H5checkAttrib.put(curtemp); std::string MOhref2; if (MOtype == "MolecularOrbital" && MOhref != "") { MOhref2 = XMLAttrString(curtemp, "href"); H5file = true; PRE.echo(curtemp); } //initialize the number of orbital by the basis set size int norb = BasisSetSize; std::string debugc("no"); bool PBC = false; OhmmsAttributeSet aAttrib; aAttrib.add(norb, "orbitals"); aAttrib.add(norb, "size"); aAttrib.add(debugc, "debug"); aAttrib.put(cur); setOrbitalSetSize(norb); xmlNodePtr occ_ptr = NULL; xmlNodePtr coeff_ptr = NULL; cur = cur->xmlChildrenNode; while (cur != NULL) { std::string cname((const char*)(cur->name)); if (cname == "occupation") { occ_ptr = cur; } else if (cname.find("coeff") < cname.size() || cname == "parameter" || cname == "Var") { coeff_ptr = cur; } cur = cur->next; } if (coeff_ptr == NULL) { app_log() << " Using Identity for the LCOrbitalSet " << std::endl; return setIdentity(true); } bool success = putOccupation(occ_ptr); if (H5file == false) success = putFromXML(coeff_ptr); else { hdf_archive hin(myComm); if (myComm->rank() == 0) { if (!hin.open(MOhref2, H5F_ACC_RDONLY)) APP_ABORT("SPOSet::putFromH5 missing or incorrect path to H5 file."); //TO REVIEWERS:: IDEAL BEHAVIOUR SHOULD BE: /* if(!hin.push("PBC") PBC=false; else if (!hin.read(PBC,"PBC")) APP_ABORT("Could not read PBC dataset in H5 file. Probably corrupt file!!!."); // However, it always succeeds to enter the if condition even if the group does not exists... */ hin.push("PBC"); PBC = false; hin.read(PBC, "PBC"); hin.close(); if (PBC) APP_ABORT("SPOSet::putFromH5 PBC is not supported by AoS builds"); } myComm->bcast(PBC); success = putFromH5(MOhref2, coeff_ptr); } bool success2 = transformSPOSet(); if (debugc == "yes") { app_log() << " Single-particle orbital coefficients dims=" << C->rows() << " x " << C->cols() << std::endl; app_log() << C << std::endl; } return success && success2; } void SPOSet::checkObject() { if (!(OrbitalSetSize == C->rows() && BasisSetSize == C->cols())) { app_error() << " SPOSet::checkObject Linear coeffient for SPOSet is not consistent with the input." << std::endl; OHMMS::Controller->abort(); } } bool SPOSet::putFromXML(xmlNodePtr coeff_ptr) { Identity = true; int norbs = 0; OhmmsAttributeSet aAttrib; aAttrib.add(norbs, "size"); aAttrib.add(norbs, "orbitals"); aAttrib.put(coeff_ptr); if (norbs < OrbitalSetSize) { return false; APP_ABORT("SPOSet::putFromXML missing or incorrect size"); } if (norbs) { Identity = false; std::vector<ValueType> Ctemp; Ctemp.resize(norbs * BasisSetSize); setIdentity(Identity); putContent(Ctemp, coeff_ptr); int n = 0, i = 0; std::vector<ValueType>::iterator cit(Ctemp.begin()); while (i < OrbitalSetSize) { if (Occ[n] > std::numeric_limits<RealType>::epsilon()) { std::copy(cit, cit + BasisSetSize, (*C)[i]); i++; } n++; cit += BasisSetSize; } } return true; } /** read data from a hdf5 file * @param norb number of orbitals to be initialized * @param fname hdf5 file name * @param coeff_ptr xmlnode for coefficients */ bool SPOSet::putFromH5(const std::string& fname, xmlNodePtr coeff_ptr) { #if defined(HAVE_LIBHDF5) int norbs = OrbitalSetSize; int neigs = BasisSetSize; int setVal = -1; std::string setname; OhmmsAttributeSet aAttrib; aAttrib.add(setVal, "spindataset"); aAttrib.add(neigs, "size"); aAttrib.add(neigs, "orbitals"); aAttrib.put(coeff_ptr); setIdentity(false); hdf_archive hin(myComm); if (myComm->rank() == 0) { if (!hin.open(fname, H5F_ACC_RDONLY)) APP_ABORT("SPOSet::putFromH5 missing or incorrect path to H5 file."); Matrix<RealType> Ctemp(neigs, BasisSetSize); char name[72]; sprintf(name, "%s%d", "/KPTS_0/eigenset_", setVal); setname = name; if (!hin.readEntry(Ctemp, setname)) { setname = "SPOSet::putFromH5 Missing " + setname + " from HDF5 File."; APP_ABORT(setname.c_str()); } hin.close(); int n = 0, i = 0; while (i < norbs) { if (Occ[n] > 0.0) { std::copy(Ctemp[n], Ctemp[n + 1], (*C)[i]); i++; } n++; } } myComm->bcast(C->data(), C->size()); #else APP_ABORT("SPOSet::putFromH5 HDF5 is disabled.") #endif return true; } bool SPOSet::putOccupation(xmlNodePtr occ_ptr) { //die?? if (BasisSetSize == 0) { APP_ABORT("SPOSet::putOccupation detected ZERO BasisSetSize"); return false; } Occ.resize(std::max(BasisSetSize, OrbitalSetSize)); Occ = 0.0; for (int i = 0; i < OrbitalSetSize; i++) Occ[i] = 1.0; std::vector<int> occ_in; std::string occ_mode("table"); if (occ_ptr == NULL) { occ_mode = "ground"; } else { const XMLAttrString o(occ_ptr, "mode"); if (!o.empty()) occ_mode = o; } //Do nothing if mode == ground if (occ_mode == "excited") { putContent(occ_in, occ_ptr); for (int k = 0; k < occ_in.size(); k++) { if (occ_in[k] < 0) //remove this, -1 is to adjust the base Occ[-occ_in[k] - 1] = 0.0; else Occ[occ_in[k] - 1] = 1.0; } } else if (occ_mode == "table") { putContent(Occ, occ_ptr); } return true; } #endif void SPOSet::basic_report(const std::string& pad) { app_log() << pad << "size = " << size() << std::endl; app_log() << pad << "state info:" << std::endl; //states.report(pad+" "); app_log().flush(); } void SPOSet::evaluate(const ParticleSet& P, int iat, ValueVector_t& psi, GradVector_t& dpsi, HessVector_t& grad_grad_psi) { APP_ABORT("Need specialization of " + className + "::evaluate(P,iat,psi,dpsi,dhpsi) (vector quantities)\n"); } void SPOSet::evaluate(const ParticleSet& P, int iat, ValueVector_t& psi, GradVector_t& dpsi, HessVector_t& grad_grad_psi, GGGVector_t& grad_grad_grad_psi) { APP_ABORT("Need specialization of " + className + "::evaluate(P,iat,psi,dpsi,dhpsi,dghpsi) (vector quantities)\n"); } void SPOSet::evaluateGradSource(const ParticleSet& P, int first, int last, const ParticleSet& source, int iat_src, GradMatrix_t& gradphi) { APP_ABORT("SPOSetBase::evalGradSource is not implemented"); } void SPOSet::evaluateGradSource(const ParticleSet& P, int first, int last, const ParticleSet& source, int iat_src, GradMatrix_t& grad_phi, HessMatrix_t& grad_grad_phi, GradMatrix_t& grad_lapl_phi) { APP_ABORT("SPOSetBase::evalGradSource is not implemented"); } #ifdef QMC_CUDA void SPOSet::evaluate(std::vector<Walker_t*>& walkers, int iat, gpu::device_vector<CTS::ValueType*>& phi) { app_error() << "Need specialization of vectorized evaluate in SPOSet.\n"; app_error() << "Required CUDA functionality not implemented. Contact developers.\n"; abort(); } void SPOSet::evaluate(std::vector<Walker_t*>& walkers, std::vector<PosType>& new_pos, gpu::device_vector<CTS::ValueType*>& phi) { app_error() << "Need specialization of vectorized evaluate in SPOSet.\n"; app_error() << "Required CUDA functionality not implemented. Contact developers.\n"; abort(); } void SPOSet::evaluate(std::vector<Walker_t*>& walkers, std::vector<PosType>& new_pos, gpu::device_vector<CTS::ValueType*>& phi, gpu::device_vector<CTS::ValueType*>& grad_lapl_list, int row_stride) { app_error() << "Need specialization of vectorized eval_grad_lapl in SPOSet.\n"; app_error() << "Required CUDA functionality not implemented. Contact developers.\n"; abort(); } void SPOSet::evaluate(std::vector<Walker_t*>& walkers, std::vector<PosType>& new_pos, gpu::device_vector<CTS::ValueType*>& phi, gpu::device_vector<CTS::ValueType*>& grad_lapl_list, int row_stride, int k, bool klinear) { app_error() << "Need specialization of vectorized eval_grad_lapl in SPOSet.\n"; app_error() << "Required CUDA functionality not implemented. Contact developers.\n"; abort(); } void SPOSet::evaluate(std::vector<PosType>& pos, gpu::device_vector<CTS::RealType*>& phi) { app_error() << "Need specialization of vectorized evaluate " << "in SPOSet.\n"; app_error() << "Required CUDA functionality not implemented. Contact developers.\n"; abort(); } void SPOSet::evaluate(std::vector<PosType>& pos, gpu::device_vector<CTS::ComplexType*>& phi) { app_error() << "Need specialization of vectorized evaluate " << "in SPOSet.\n"; app_error() << "Required CUDA functionality not implemented. Contact developers.\n"; abort(); } #endif } // namespace qmcplusplus
30.354772
119
0.594765
[ "vector" ]
20ce133d82170dddb024b514fbec2124bb220d6e
4,556
cpp
C++
cpp/main.cpp
serghov/OpencvFaceDetectWasm
6e2a0b24b6b633a34353add6f6eee49ba75e25d1
[ "MIT" ]
8
2018-07-16T18:59:24.000Z
2020-12-04T01:42:17.000Z
cpp/main.cpp
serghov/OpencvFaceDetectWasm
6e2a0b24b6b633a34353add6f6eee49ba75e25d1
[ "MIT" ]
1
2019-04-09T11:41:15.000Z
2019-04-09T11:41:15.000Z
cpp/main.cpp
serghov/OpencvFaceDetectWasm
6e2a0b24b6b633a34353add6f6eee49ba75e25d1
[ "MIT" ]
1
2018-07-16T20:13:44.000Z
2018-07-16T20:13:44.000Z
#include "opencv2/imgcodecs.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/objdetect/objdetect.hpp" #include <iostream> #include <fstream> #include <chrono> #include <emscripten.h> #include <stdio.h> #include <SDL/SDL.h> #include <SDL/SDL_image.h> using namespace std; using namespace cv; using namespace chrono; /** * Gets current time in milliseconds * @return */ long long getMillis() { chrono::milliseconds ms = duration_cast<chrono::milliseconds>(high_resolution_clock::now().time_since_epoch()); return ms.count(); } SDL_Surface *screen = nullptr; SDL_Surface *sdlImage = nullptr; /** * Displays an image using sdl * apparently not all functionality is implemented in emscripten * so only rgba images are currently supported * @param img */ void sdlShowImage(Mat &img) { int width = img.cols, height = img.rows; SDL_Rect rect = {0, 0, width, height}; if (sdlImage) { SDL_FreeSurface(sdlImage); } sdlImage = SDL_CreateRGBSurfaceFrom(img.data, width, height, 32, width * 4, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000); // SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format, 0, 0, 0)); SDL_BlitSurface(sdlImage, &rect, screen, &rect); SDL_UpdateRect(screen, 0, 0, width, height); } String face_cascade_name = "haarcascade_frontalface_default.xml"; CascadeClassifier face_cascade; RNG rng(12345); /** * Finds faces in an image, draws circles around them * and displays the image using sdl * http://docs.opencv.org/2.4/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html * @param frame */ void detectAndDisplay(Mat frame) { std::vector<Rect> faces; Mat frame_gray; cvtColor(frame, frame_gray, CV_RGBA2GRAY); equalizeHist(frame_gray, frame_gray); face_cascade.detectMultiScale(frame_gray, faces, 2, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(50, 50), Size(frame.rows * 0.9, frame.cols * 0.9)); for (size_t i = 0; i < faces.size(); i++) { Point center(faces[i].x + faces[i].width * 0.5, faces[i].y + faces[i].height * 0.5); ellipse(frame, center, Size(faces[i].width * 0.5, faces[i].height * 0.5), 0, 0, 360, Scalar(0, 0, 255, 255), 1, 8, 0); } sdlShowImage(frame); } /** * This function is called from js, when a new video frame is ready * it takes the frame, puts it into a an opencv Mat * finds faces, and draws the output using sdl */ extern "C" void onNewImage(uchar *data, int width, int height) { long long startTime = getMillis(); Mat image(height, width, CV_8UC4); image.data = data; detectAndDisplay(image); delete data; long long endTime = getMillis(); // cout << "Took " << endTime - startTime << "ms, " << (int) (1000.0 / (endTime - startTime)) << "fps;" << endl; // we show this on the upper part of the webpage string res = "updateData('Took " + std::to_string(endTime - startTime) + "ms, " + std::to_string((int) (1000.0 / (endTime - startTime))) + "fps;');"; emscripten_run_script(res.c_str()); } void update() { // nothing here, just an empty update loop } int main(int, char **) { // initialize sdl SDL_Init(SDL_INIT_VIDEO); screen = SDL_SetVideoMode(640, 360, 32, SDL_HWSURFACE); // load opencv haar cascade file, which needs to be in // in emscripten memory if (!face_cascade.load(face_cascade_name)) { printf("--(!)Error loading\n"); cout << "Error loading face haar cascade file " << face_cascade_name << endl; return -1; } cout << "Ready" << endl; // tell js that we are ready emscripten_run_script("isReady = true"); // run an empty loop to our program doesnt end with return 0 emscripten_set_main_loop(update, 0, 1); return 0; } //emcc ../main.cpp -I /home/serg/build/opencv/build/install/include -l/home/serg/build/opencv/build/install/lib/libopencv_core -l/home/serg/build/opencv/build/install/lib/libopencv_imgproc -l/home/serg/build/opencv/build/install/lib/libopencv_imgcodecs -l/home/serg/build/opencv/build/install/lib/libopencv_highgui -l/home/serg/build/opencv/build/install/lib/libopencv_photo -l/home/serg/build/opencv/build/install/lib/libopencv_video -l/home/serg/build/opencv/build/install/lib/libopencv_videoio -O3 --preload-file test.bmp -s WASM=1 -o main.js
30.993197
545
0.652985
[ "vector" ]
20dd2ece3d718df8572323d9ac99d7702b25741f
2,600
hh
C++
include/LHEParticle.hh
omar-moreno/simulation-formerly-known-as-slic
331d0452d05762e2f4554f0ace6fe46922a7333c
[ "BSD-3-Clause-LBNL" ]
null
null
null
include/LHEParticle.hh
omar-moreno/simulation-formerly-known-as-slic
331d0452d05762e2f4554f0ace6fe46922a7333c
[ "BSD-3-Clause-LBNL" ]
null
null
null
include/LHEParticle.hh
omar-moreno/simulation-formerly-known-as-slic
331d0452d05762e2f4554f0ace6fe46922a7333c
[ "BSD-3-Clause-LBNL" ]
null
null
null
/** * @file LHEParticle.h * @brief Class defining a single particle record in an LHE event * @author Jeremy McCormick, SLAC National Accelerator Laboratory */ #ifndef SLIC_LHEPARTICLE_HH_ #define SLIC_LHEPARTICLE_HH_ // STL #include <string> #include <vector> namespace slic { /** * @class LHEParticle * @brief Single particle record in an LHE event */ class LHEParticle { public: /** * Class constructor. * @param data The particle record as a space-delimited string. */ LHEParticle(std::string& data); /** * Get the PDG code (IDUP). * @return The PDG code. */ int getIDUP() const; /** * Get the status code (ISTUP). * @return The status code. */ int getISTUP() const; /** * Get a mother particle index (MOTHUP) by index. * @return The mother particle by index. */ int getMOTHUP(int) const; /** * Get the particle color (ICOLUP) by index. * @return The particle color by index. */ int getICOLUP(int) const; /** * Get a momentum component (PUP) by index. * Defined in order: E/C, Px, Py, Pz, mass * @return The momentum component by index. */ double getPUP(int) const; /** * Get the proper lifetime (VTIMUP). * @return The particle's proper lifetime. */ double getVTIMUP() const; /** * Get the particle's spin (SPINUP). * @return The particle's spin. */ double getSPINUP() const; /** * Set a mother particle by index. * @param i The mother index. * @param particle The mother particle. */ void setMother(int i, LHEParticle* particle); /** * Get a mother particle by index. * @return The mother particle at the index. */ LHEParticle* getMother(int) const; /** * Print particle information to an output stream. * @param stream The output stream. */ void print(std::ostream& stream) const; /** * Overloaded stream operator. * @param stream The output stream. * @param particle The particle to print. */ friend std::ostream& operator<<(std::ostream& stream, const LHEParticle& particle); private: /** * The mother particles. */ LHEParticle* mothers_[2]; /** * The PDG code. */ int idup_; /** * The status code. */ int istup_; /** * The mother particle indices. */ int mothup_[2]; /** * The particle color. */ int icolup_[2]; /** * The momentum components. */ double pup_[5]; /** * The proper time. */ double vtimup_; /** * The particle's spin. */ int spinup_; }; } // namespace slic #endif
18.181818
65
0.612308
[ "vector" ]
22161a96e690645120bfc52acc410c3a468b6b26
6,565
cc
C++
ui/display/manager/json_converter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ui/display/manager/json_converter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ui/display/manager/json_converter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/display/manager/json_converter.h" #include <memory> #include <string> #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "ui/display/display_layout.h" namespace display { namespace { // Persistent key names const char kDefaultUnifiedKey[] = "default_unified"; const char kPrimaryIdKey[] = "primary-id"; const char kDisplayPlacementKey[] = "display_placement"; // DisplayPlacement key names const char kPositionKey[] = "position"; const char kOffsetKey[] = "offset"; const char kDisplayPlacementDisplayIdKey[] = "display_id"; const char kDisplayPlacementParentDisplayIdKey[] = "parent_display_id"; bool AddLegacyValuesFromValue(const base::Value& value, DisplayLayout* layout) { if (!value.is_dict()) return false; absl::optional<int> optional_offset = value.FindIntKey(kOffsetKey); if (optional_offset) { DisplayPlacement::Position position; const std::string* position_str = value.FindStringKey(kPositionKey); if (!position_str) return false; DisplayPlacement::StringToPosition(*position_str, &position); layout->placement_list.emplace_back(position, *optional_offset); } return true; } // Returns true if // The key is missing - output is left unchanged // The key matches the type - output is updated to the value. bool UpdateFromDict(const base::Value& value, const std::string& field_name, bool* output) { const base::Value* field = value.FindKey(field_name); if (!field) { LOG(WARNING) << "Missing field: " << field_name; return true; } absl::optional<bool> field_value = field->GetIfBool(); if (!field_value) return false; *output = *field_value; return true; } // Returns true if // The key is missing - output is left unchanged // The key matches the type - output is updated to the value. bool UpdateFromDict(const base::Value& value, const std::string& field_name, int* output) { const base::Value* field = value.FindKey(field_name); if (!field) { LOG(WARNING) << "Missing field: " << field_name; return true; } absl::optional<int> field_value = field->GetIfInt(); if (!field_value) return false; *output = *field_value; return true; } // Returns true if // The key is missing - output is left unchanged // The key matches the type - output is updated to the value. bool UpdateFromDict(const base::Value& value, const std::string& field_name, DisplayPlacement::Position* output) { const base::Value* field = value.FindKey(field_name); if (!field) { LOG(WARNING) << "Missing field: " << field_name; return true; } const std::string* field_value = field->GetIfString(); if (!field_value) return false; return field_value->empty() ? true : DisplayPlacement::StringToPosition(*field_value, output); } // Returns true if // The key is missing - output is left unchanged // The key matches the type - output is updated to the value. bool UpdateFromDict(const base::Value& value, const std::string& field_name, int64_t* output) { const base::Value* field = value.FindKey(field_name); if (!field) { LOG(WARNING) << "Missing field: " << field_name; return true; } const std::string* field_value = field->GetIfString(); if (!field_value) return false; return field_value->empty() ? true : base::StringToInt64(*field_value, output); } // Returns true if // The key is missing - output is left unchanged // The key matches the type - output is updated to the value. bool UpdateFromDict(const base::Value& value, const std::string& field_name, std::vector<DisplayPlacement>* output) { const base::Value* field = value.FindKey(field_name); if (!field) { LOG(WARNING) << "Missing field: " << field_name; return true; } if (!field->is_list()) return false; const base::Value::ConstListView list = field->GetList(); output->reserve(list.size()); for (const base::Value& list_item : list) { if (!list_item.is_dict()) return false; DisplayPlacement item; if (!UpdateFromDict(list_item, kOffsetKey, &item.offset) || !UpdateFromDict(list_item, kPositionKey, &item.position) || !UpdateFromDict(list_item, kDisplayPlacementDisplayIdKey, &item.display_id) || !UpdateFromDict(list_item, kDisplayPlacementParentDisplayIdKey, &item.parent_display_id)) { return false; } output->push_back(item); } return true; } } // namespace bool JsonToDisplayLayout(const base::Value& value, DisplayLayout* layout) { layout->placement_list.clear(); if (!value.is_dict()) return false; if (!UpdateFromDict(value, kDefaultUnifiedKey, &layout->default_unified) || !UpdateFromDict(value, kPrimaryIdKey, &layout->primary_id)) { return false; } UpdateFromDict(value, kDisplayPlacementKey, &layout->placement_list); if (layout->placement_list.size() != 0u) return true; // For compatibility with old format. return AddLegacyValuesFromValue(value, layout); } bool DisplayLayoutToJson(const DisplayLayout& layout, base::Value* value) { if (!value->is_dict()) return false; value->SetBoolKey(kDefaultUnifiedKey, layout.default_unified); value->SetStringKey(kPrimaryIdKey, base::NumberToString(layout.primary_id)); base::Value::ListStorage placement_list; for (const auto& placement : layout.placement_list) { base::Value placement_value(base::Value::Type::DICTIONARY); placement_value.SetStringKey( kPositionKey, DisplayPlacement::PositionToString(placement.position)); placement_value.SetIntKey(kOffsetKey, placement.offset); placement_value.SetStringKey(kDisplayPlacementDisplayIdKey, base::NumberToString(placement.display_id)); placement_value.SetStringKey( kDisplayPlacementParentDisplayIdKey, base::NumberToString(placement.parent_display_id)); placement_list.push_back(std::move(placement_value)); } value->SetKey(kDisplayPlacementKey, base::Value(std::move(placement_list))); return true; } } // namespace display
31.261905
80
0.678294
[ "vector" ]
221fb4bf15cfdcc2ccbe1538fa9ce88fd3d23a94
59,296
cpp
C++
src/guimanager.cpp
PleXone2019/cmftStudio
46f006f22a8c6683da23cee015c6898eb5ab6d3f
[ "BSD-2-Clause" ]
1,087
2015-01-02T10:34:26.000Z
2022-03-30T07:41:43.000Z
src/guimanager.cpp
PleXone2019/cmftStudio
46f006f22a8c6683da23cee015c6898eb5ab6d3f
[ "BSD-2-Clause" ]
25
2015-03-06T11:14:02.000Z
2020-04-19T09:00:11.000Z
src/guimanager.cpp
PleXone2019/cmftStudio
46f006f22a8c6683da23cee015c6898eb5ab6d3f
[ "BSD-2-Clause" ]
127
2015-02-26T11:57:06.000Z
2022-03-23T02:22:44.000Z
/* * Copyright 2014-2015 Dario Manesku. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include "common/common.h" #include "guimanager.h" #include "common/utils.h" // WidgetAnimator #include <bx/string.h> // bx::snprintf #include <cmft/callbacks.h> // cmft::setCallback #include <bx/string.h> #include <bx/thread.h> // bx::MutexScope #include <bx/macros.h> // BX_STATIC_ASSERT #include <bx/os.h> // Imgui status. //----- struct StatusManager { StatusManager() { m_deltaTime = 0.0f; m_time = 0.0f; m_eventIdx = 0; } void update(float _deltaTime) { m_deltaTime = _deltaTime; m_time += _deltaTime; } void draw() { for (int16_t last = m_messageList.count()-1, ii = last; ii >= 0; --ii) { const uint16_t idx = last - ii; const uint16_t handle = m_messageList.getHandleAt(idx); const Message* msg = m_messageList.getFromHandle(handle); if (0.0f != msg->m_endTime && msg->m_endTime < m_time) { m_animators[handle].fadeOut(); } if (!m_animators[handle].m_visible) { m_messageList.removeAt(idx); last--; } else { const bool hasButton = ('\0' != msg->m_button[0]); const int32_t statusHeight = 34; const int32_t statusWidth = int32_t(msg->m_width)+11; const int32_t buttonWidth = 86; const float startY = 0.0f; const float endY = 10.0f; m_animators[handle].update(m_deltaTime, 0.1f); m_animators[handle].setKeyPoints(msg->m_posX, startY, msg->m_posX, endY + float(idx*(statusHeight+5))); imguiBeginArea(NULL , int32_t(m_animators[handle].m_x) - int32_t(hasButton)*buttonWidth/2 , int32_t(m_animators[handle].m_y) , statusWidth, statusHeight, true, 5 ); imguiSeparator(2); { // Font scope. ImguiFontScope fontScope(Fonts::StatusFont); imguiLabel(msg->m_warning?imguiRGBA(255, 128, 128, 255):imguiRGBA(255,255,255,230), msg->m_str); } imguiEndArea(); if (hasButton) { imguiBeginArea(NULL , int32_t(m_animators[handle].m_x) + statusWidth - buttonWidth/2 + 4 , int32_t(m_animators[handle].m_y) , buttonWidth, statusHeight, true, 5 ); if (imguiButton(msg->m_button)) { m_animators[handle].fadeOut(); if (m_eventIdx < MaxEvents) { m_eventQueue[m_eventIdx++] = msg->m_buttonEvent; } } imguiEndArea(); } } } } void add(const char* _msg, float _durationSec, bool _isWarning, const char* _button, uint16_t _buttonEvent, StatusWindowId::Enum _id) { if (m_messageList.count() >= MaxMessages) { return; } if (StatusWindowId::None != _id) { for (uint16_t ii = m_messageList.count(); ii--; ) { const Message* msg = m_messageList.getAt(ii); if (msg->m_id == _id) { return; } } } const float msgLength = imguiGetTextLength(_msg, Fonts::StatusFont); const float msgPosX = (float(g_width)-msgLength)*0.5f; Message* msg = m_messageList.addNew(); msg->m_endTime = 0.0f == _durationSec ? 0.0f : m_time+_durationSec; msg->m_posX = msgPosX; msg->m_width = msgLength; msg->m_buttonEvent = _buttonEvent; msg->m_warning = _isWarning; msg->m_id = _id; dm::strscpy(msg->m_str, _msg, 128); dm::strscpy(msg->m_button, _button, 32); const uint16_t handle = m_messageList.getHandleOf(msg); m_animators[handle].reset(true, msgPosX, 0.0f); m_animators[handle].fadeIn(); } uint16_t getNextEvent() { return m_eventIdx > 0 ? m_eventQueue[--m_eventIdx] : 0; } void remove(StatusWindowId::Enum _id) { for (uint16_t ii = m_messageList.count(); ii--; ) { const Message* msg = m_messageList.getAt(ii); if (msg->m_id == _id) { const uint16_t handle = m_messageList.getHandleOf(msg); m_animators[handle].fadeOut(); } } } struct Message { float m_endTime; float m_posX; float m_width; uint16_t m_buttonEvent; bool m_warning; StatusWindowId::Enum m_id; char m_str[128]; char m_button[32]; }; enum { MaxMessages = 8, MaxEvents = 16, }; float m_deltaTime; float m_time; int16_t m_eventIdx; uint16_t m_eventQueue[MaxEvents]; dm::OpListT<Message, MaxMessages> m_messageList; WidgetAnimator m_animators[MaxMessages]; }; static StatusManager s_statusManager; void imguiStatusMessage(const char* _msg , float _durationSec , bool _isWarning , const char* _button , uint16_t _buttonEvent , StatusWindowId::Enum _id ) { s_statusManager.add(_msg, _durationSec, _isWarning, _button, _buttonEvent, _id); } void imguiRemoveStatusMessage(StatusWindowId::Enum _id) { s_statusManager.remove(_id); } uint16_t imguiGetStatusEvent() { return s_statusManager.getNextEvent(); } // Circular string array //----- struct CircularStringArray { CircularStringArray() { clear(); } void clear() { bx::MutexScope lock(m_mutex); m_last = UINT16_MAX; m_lastListed = UINT16_MAX; m_count = 0; m_unlisted = 0; } void add(const char* _str, uint32_t _len = OutputWindowState::LineLength) { // Copy _str contents into the next line. dm::strscpy(getLine(++m_last), _str, _len); ++m_unlisted; } void addSplitNewLine(const char _str[OutputWindowState::LineLength]) { char temp[2048]; dm::strscpy(temp, _str, 2048); bx::MutexScope lock(m_mutex); const char* ptr = strtok(temp, "\n"); do { enum { LineLength = 105 }; // Split and add line by line of specified length. while (strlen(ptr) > LineLength) { add(ptr, LineLength); ptr += (LineLength-1); } // Add the rest. add(ptr); } while ((ptr = strtok(NULL, "\n")) != NULL); } char* getLine(uint16_t _idx) { return m_lines[wrapAround(_idx)]; } uint16_t getLines(char** _ptrs) { bx::MutexScope lock(m_mutex); for (uint16_t ii = 0; ii < m_count; ++ii) { _ptrs[ii] = getLine(m_lastListed-ii); } return m_count; } void submitNext() { if (0 == m_unlisted) { return; } bx::MutexScope lock(m_mutex); --m_unlisted; ++m_lastListed; m_count = (++m_count > OutputWindowState::MaxLines) ? uint16_t(OutputWindowState::MaxLines) : m_count; } private: static inline uint16_t wrapAround(uint16_t _idx) { return _idx&(OutputWindowState::MaxLines-1); } public: uint16_t m_last; uint16_t m_lastListed; uint16_t m_count; uint16_t m_unlisted; char m_lines[OutputWindowState::MaxLines][OutputWindowState::LineLength]; bx::Mutex m_mutex; }; static CircularStringArray s_csa; static const char* printfVargs(const char* _format, va_list _argList) { static char s_buffer[8192]; char* out = s_buffer; int32_t len = bx::vsnprintf(out, sizeof(s_buffer), _format, _argList); if ((int32_t)sizeof(s_buffer) < len) { out = (char*)alloca(len+1); len = bx::vsnprintf(out, len, _format, _argList); } out[len] = '\0'; return out; } // Output window. //----- static OutputWindowState* s_outputWindowState; struct PrintCallback: public cmft::PrintCallbackI { virtual ~PrintCallback() { } virtual void printWarning(const char* _msg) const { outputWindowPrint(_msg); } virtual void printInfo(const char* _msg) const { outputWindowPrint(_msg); } }; static PrintCallback s_printCallback; void outputWindowInit(OutputWindowState* _state) { s_outputWindowState = _state; // Redirect cmft output to output window. cmft::setCallback(&s_printCallback); } void outputWindowPrint(const char* _format, ...) { va_list argList; va_start(argList, _format); const char* str = printfVargs(_format, argList); va_end(argList); s_csa.addSplitNewLine(str); } void outputWindowUpdate(float _deltaTime/*sec*/, float _updateFreq = 0.014f/*sec*/) { static float timeNow = 0.0f; timeNow += _deltaTime; if (timeNow > _updateFreq) { s_csa.submitNext(); timeNow = 0.0f; } const uint16_t before = s_outputWindowState->m_linesCount; const uint16_t now = s_csa.getLines(s_outputWindowState->m_lines); s_outputWindowState->m_linesCount = now; if (before != now) { s_outputWindowState->scrollDown(); } } void outputWindowClear() { s_outputWindowState->m_scroll = 0; s_csa.clear(); } void outputWindowShow() { widgetShow(Widget::OutputWindow); } // Animators. //----- static inline Widget::Enum texPickerFor(cs::Material::Texture _matTexture) { static const Widget::Enum sc_materialToWidget[cs::Material::TextureCount] = { Widget::TexPickerAlbedo, // Material::Albedo Widget::TexPickerNormal, // Material::Normal Widget::TexPickerSurface, // Material::Surface Widget::TexPickerReflectivity, // Material::Reflectivity Widget::TexPickerOcclusion, // Material::Occlusion Widget::TexPickerEmissive, // Material::Emissive }; return sc_materialToWidget[_matTexture]; } // Widgets. //----- static uint64_t s_widgets = Widget::Right | Widget::Left; void widgetShow(Widget::Enum _widget) { s_widgets |= _widget; } void widgetHide(Widget::Enum _widget) { s_widgets &= ~_widget; } void widgetHide(uint64_t _mask) { s_widgets &= ~_mask; } void widgetToggle(Widget::Enum _widget) { s_widgets ^= _widget; } void widgetSetOrClear(Widget::Enum _widget, uint64_t _mask) { s_widgets ^= _widget; s_widgets &= ~(_widget^_mask); } bool widgetIsVisible(Widget::Enum _widget) { return (0 != (s_widgets & _widget)); } struct Animators { enum Enum { LeftScrollArea, RightScrollArea, MeshSaveWidget, MeshBrowser, TexPickerAlbedo, TexPickerNormal, TexPickerSurface, TexPickerReflectivity, TexPickerOcclusion, TexPickerEmissive, LeftTextureBrowser, EnvMapWidget, SkyboxBrowser, PmremBrowser, IemBrowser, TonemapWidget, CmftTransform, CmftIem, CmftPmrem, CmftSaveSkybox, CmftSavePmrem, CmftSaveIem, CmftInfoSkybox, CmftInfoPmrem, CmftInfoIem, OutputWindow, AboutWindow, MagnifyWindow, ProjectWindow, Count }; static inline Animators::Enum texPickerFor(cs::Material::Texture _matTexture) { static const Animators::Enum sc_materialToAnimator[cs::Material::TextureCount] = { TexPickerAlbedo, //Material::Albedo TexPickerNormal, //Material::Normal TexPickerSurface, //Material::Surface TexPickerReflectivity, //Material::Reflectivity TexPickerOcclusion, //Material::Occlusion TexPickerEmissive, //Material::Emissive }; return sc_materialToAnimator[_matTexture]; } void init(float _width, float _height , float _lx, float _ly, float _lw , float _rx, float _ry ) { const float width = _width - 10.0f; m_animators[LeftScrollArea ].reset(false, _lx, _ly); m_animators[RightScrollArea ].reset(false, _rx, _ry); m_animators[MeshSaveWidget ].reset(false, _lx-_lw, _ly); m_animators[MeshBrowser ].reset(false, _lx-_lw, _ly); m_animators[TexPickerAlbedo ].reset(false, _lx-_lw, _ly); m_animators[TexPickerNormal ].reset(false, _lx-_lw, _ly); m_animators[TexPickerSurface ].reset(false, _lx-_lw, _ly); m_animators[TexPickerReflectivity].reset(false, _lx-_lw, _ly); m_animators[TexPickerOcclusion ].reset(false, _lx-_lw, _ly); m_animators[TexPickerEmissive ].reset(false, _lx-_lw, _ly); m_animators[LeftTextureBrowser ].reset(false, _lx-_lw, _ly); m_animators[EnvMapWidget ].reset(false, width, 0.0f); m_animators[SkyboxBrowser ].reset(false, width, 0.0f); m_animators[PmremBrowser ].reset(false, width, 0.0f); m_animators[IemBrowser ].reset(false, width, 0.0f); m_animators[TonemapWidget ].reset(false, width, 0.0f); m_animators[CmftTransform ].reset(false, width, 0.0f); m_animators[CmftIem ].reset(false, width, 0.0f); m_animators[CmftPmrem ].reset(false, width, 0.0f); m_animators[CmftSaveSkybox ].reset(false, width, 0.0f); m_animators[CmftSavePmrem ].reset(false, width, 0.0f); m_animators[CmftSaveIem ].reset(false, width, 0.0f); m_animators[CmftInfoSkybox ].reset(false, width, 0.0f); m_animators[CmftInfoPmrem ].reset(false, width, 0.0f); m_animators[CmftInfoIem ].reset(false, width, 0.0f); m_animators[OutputWindow ].reset(false, (width-800.0f)*0.5f, _height); m_animators[AboutWindow ].reset(false, (width-800.0f)*0.5f, -400.0f); m_animators[MagnifyWindow ].reset(false, (width-800.0f)*0.5f, -400.0f); m_animators[ProjectWindow ].reset(false, _lx-_lw, (_height-600.0f)*0.5f); } void setKeyPoints(float _width, float _height, float _lw, float _rw , float _l0x, float _l0y , float _l1x, float _l1y , float _l2x, float _l2y , float _r0x, float _r0y , float _r1x, float _r1y , float _r2x, float _r2y ) { // This input happens on Windows when window is minimized. if (0.0f == _width || 0.0f == _height) { return; } const float width = _width - 10.0f; m_animators[LeftScrollArea ].setKeyPoints(_l0x - _rw, _l0y, _l0x, _l0y); m_animators[RightScrollArea ].setKeyPoints(_r0x + _rw, _r0y, _r0x, _r0y); m_animators[MeshSaveWidget ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[MeshBrowser ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[TexPickerAlbedo ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[TexPickerNormal ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[TexPickerSurface ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[TexPickerReflectivity].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[TexPickerOcclusion ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[TexPickerEmissive ].setKeyPoints(_l0x - _lw, _l0y, _l1x, _l1y); m_animators[LeftTextureBrowser ].setKeyPoints(_l0x - _lw, _l0y, _l2x, _l2y); m_animators[EnvMapWidget ].setKeyPoints(width, _r0y, _r1x, _r1y); m_animators[SkyboxBrowser ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[PmremBrowser ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[IemBrowser ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[TonemapWidget ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[CmftTransform ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[CmftIem ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[CmftPmrem ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[CmftSaveSkybox ].setKeyPoints(width, _r0y, _r2x-Gui::PaneWidth, _r2y); m_animators[CmftSavePmrem ].setKeyPoints(width, _r0y, _r2x-Gui::PaneWidth, _r2y); m_animators[CmftSaveIem ].setKeyPoints(width, _r0y, _r2x-Gui::PaneWidth, _r2y); m_animators[CmftInfoSkybox ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[CmftInfoPmrem ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[CmftInfoIem ].setKeyPoints(width, _r0y, _r2x, _r2y); m_animators[OutputWindow ].setKeyPoints((_width -800.0f)*0.5f , _height , (_width -800.0f)*0.5f , (_height-400.0f)*0.5f ); m_animators[AboutWindow ].setKeyPoints((_width -800.0f)*0.5f , -400.0f , (_width -800.0f)*0.5f , (_height-400.0f)*0.5f ); m_animators[MagnifyWindow ].setKeyPoints(_width*0.06f , -_height-10.0f , _width*0.06f , _height*0.07f ); m_animators[ProjectWindow ].setKeyPoints(_l0x-_lw , (_height-800.0f)*0.5f , (_width -350.0f)*0.5f , (_height-800.0f)*0.5f , width , (_height-800.0f)*0.5f ); } void tick(float _deltaTime, float _widgetAnimDuration = 0.1f, float _modalWindowAnimDuration = 0.06f) { m_animators[LeftScrollArea ].update(_deltaTime, _widgetAnimDuration); m_animators[RightScrollArea ].update(_deltaTime, _widgetAnimDuration); m_animators[MeshSaveWidget ].update(_deltaTime, _widgetAnimDuration); m_animators[MeshBrowser ].update(_deltaTime, _widgetAnimDuration); m_animators[TexPickerAlbedo ].update(_deltaTime, _widgetAnimDuration); m_animators[TexPickerNormal ].update(_deltaTime, _widgetAnimDuration); m_animators[TexPickerSurface ].update(_deltaTime, _widgetAnimDuration); m_animators[TexPickerReflectivity].update(_deltaTime, _widgetAnimDuration); m_animators[TexPickerOcclusion ].update(_deltaTime, _widgetAnimDuration); m_animators[TexPickerEmissive ].update(_deltaTime, _widgetAnimDuration); m_animators[LeftTextureBrowser ].update(_deltaTime, _widgetAnimDuration); m_animators[EnvMapWidget ].update(_deltaTime, _widgetAnimDuration); m_animators[SkyboxBrowser ].update(_deltaTime, _widgetAnimDuration); m_animators[PmremBrowser ].update(_deltaTime, _widgetAnimDuration); m_animators[IemBrowser ].update(_deltaTime, _widgetAnimDuration); m_animators[TonemapWidget ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftTransform ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftIem ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftPmrem ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftSaveSkybox ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftSavePmrem ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftSaveIem ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftInfoSkybox ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftInfoPmrem ].update(_deltaTime, _widgetAnimDuration); m_animators[CmftInfoIem ].update(_deltaTime, _widgetAnimDuration); m_animators[OutputWindow ].update(_deltaTime, _modalWindowAnimDuration); m_animators[AboutWindow ].update(_deltaTime, _modalWindowAnimDuration); m_animators[MagnifyWindow ].update(_deltaTime, _modalWindowAnimDuration); m_animators[ProjectWindow ].update(_deltaTime, _modalWindowAnimDuration); } void updateVisibility() { #define CS_HANDLE_ANIMATION(_widget, _animator) \ if (widgetIsVisible(_widget)) \ { \ m_animators[_animator].fadeIn(); \ } \ else \ { \ m_animators[_animator].fadeOut(); \ } // Left side. if (widgetIsVisible(Widget::Left)) { // Scroll area. m_animators[Animators::LeftScrollArea].fadeIn(); CS_HANDLE_ANIMATION(Widget::MeshSaveWidget, Animators::MeshSaveWidget) CS_HANDLE_ANIMATION(Widget::MeshBrowser, Animators::MeshBrowser) CS_HANDLE_ANIMATION(Widget::TexPickerAlbedo, Animators::TexPickerAlbedo) CS_HANDLE_ANIMATION(Widget::TexPickerNormal, Animators::TexPickerNormal) CS_HANDLE_ANIMATION(Widget::TexPickerSurface, Animators::TexPickerSurface) CS_HANDLE_ANIMATION(Widget::TexPickerReflectivity, Animators::TexPickerReflectivity) CS_HANDLE_ANIMATION(Widget::TexPickerOcclusion, Animators::TexPickerOcclusion) CS_HANDLE_ANIMATION(Widget::TexPickerEmissive, Animators::TexPickerEmissive) if (widgetIsVisible(Widget::TextureFileBrowser) && widgetIsVisible(Widget::TexPickerMask)) { m_animators[Animators::LeftTextureBrowser].fadeIn(); } else { m_animators[Animators::LeftTextureBrowser].fadeOut(); } } else { m_animators[Animators::LeftScrollArea ].fadeOut(); m_animators[Animators::MeshSaveWidget ].fadeOut(); m_animators[Animators::MeshBrowser ].fadeOut(); m_animators[Animators::TexPickerAlbedo ].fadeOut(); m_animators[Animators::TexPickerNormal ].fadeOut(); m_animators[Animators::TexPickerSurface ].fadeOut(); m_animators[Animators::TexPickerReflectivity].fadeOut(); m_animators[Animators::TexPickerOcclusion ].fadeOut(); m_animators[Animators::TexPickerEmissive ].fadeOut(); m_animators[Animators::LeftTextureBrowser ].fadeOut(); } // Right side. if (widgetIsVisible(Widget::Right)) { // Scroll area. m_animators[Animators::RightScrollArea].fadeIn(); // Env widget. if (widgetIsVisible(Widget::EnvWidget)) { m_animators[Animators::EnvMapWidget].fadeIn(); CS_HANDLE_ANIMATION(Widget::CmftInfoSkyboxWidget, Animators::CmftInfoSkybox) CS_HANDLE_ANIMATION(Widget::CmftInfoPmremWidget, Animators::CmftInfoPmrem) CS_HANDLE_ANIMATION(Widget::CmftInfoIemWidget, Animators::CmftInfoIem) CS_HANDLE_ANIMATION(Widget::CmftSaveSkyboxWidget, Animators::CmftSaveSkybox) CS_HANDLE_ANIMATION(Widget::CmftSavePmremWidget, Animators::CmftSavePmrem) CS_HANDLE_ANIMATION(Widget::CmftSaveIemWidget, Animators::CmftSaveIem) CS_HANDLE_ANIMATION(Widget::TonemapWidget, Animators::TonemapWidget) CS_HANDLE_ANIMATION(Widget::CmftTransformWidget, Animators::CmftTransform) CS_HANDLE_ANIMATION(Widget::CmftIemWidget, Animators::CmftIem) CS_HANDLE_ANIMATION(Widget::CmftPmremWidget, Animators::CmftPmrem) CS_HANDLE_ANIMATION(Widget::SkyboxBrowser, Animators::SkyboxBrowser) CS_HANDLE_ANIMATION(Widget::PmremBrowser, Animators::PmremBrowser) CS_HANDLE_ANIMATION(Widget::IemBrowser, Animators::IemBrowser) } else { widgetHide(Widget::RightSideSubwidgetMask); m_animators[Animators::EnvMapWidget ].fadeOut(); m_animators[Animators::CmftInfoSkybox].fadeOut(); m_animators[Animators::CmftInfoPmrem ].fadeOut(); m_animators[Animators::CmftInfoIem ].fadeOut(); m_animators[Animators::CmftSaveSkybox].fadeOut(); m_animators[Animators::CmftSavePmrem ].fadeOut(); m_animators[Animators::CmftSaveIem ].fadeOut(); m_animators[Animators::CmftPmrem ].fadeOut(); m_animators[Animators::CmftIem ].fadeOut(); m_animators[Animators::CmftTransform ].fadeOut(); m_animators[Animators::TonemapWidget ].fadeOut(); m_animators[Animators::SkyboxBrowser ].fadeOut(); m_animators[Animators::PmremBrowser ].fadeOut(); m_animators[Animators::IemBrowser ].fadeOut(); } } else { m_animators[Animators::RightScrollArea].fadeOut(); m_animators[Animators::EnvMapWidget ].fadeOut(); m_animators[Animators::CmftInfoSkybox ].fadeOut(); m_animators[Animators::CmftInfoPmrem ].fadeOut(); m_animators[Animators::CmftInfoIem ].fadeOut(); m_animators[Animators::CmftSaveSkybox ].fadeOut(); m_animators[Animators::CmftSavePmrem ].fadeOut(); m_animators[Animators::CmftSaveIem ].fadeOut(); m_animators[Animators::CmftPmrem ].fadeOut(); m_animators[Animators::CmftIem ].fadeOut(); m_animators[Animators::CmftTransform ].fadeOut(); m_animators[Animators::TonemapWidget ].fadeOut(); m_animators[Animators::SkyboxBrowser ].fadeOut(); m_animators[Animators::PmremBrowser ].fadeOut(); m_animators[Animators::IemBrowser ].fadeOut(); } // Modal. CS_HANDLE_ANIMATION(Widget::OutputWindow, Animators::OutputWindow) CS_HANDLE_ANIMATION(Widget::AboutWindow, Animators::AboutWindow) CS_HANDLE_ANIMATION(Widget::MagnifyWindow, Animators::MagnifyWindow) CS_HANDLE_ANIMATION(Widget::ProjectWindow, Animators::ProjectWindow) #undef CS_HANDLE_ANIMATION } inline WidgetAnimator& operator[](uint32_t _index) { return m_animators[_index]; } private: WidgetAnimator m_animators[Animators::Count]; }; static Animators s_animators; static inline void setOrClear(uint8_t& _field, uint8_t _flag) { _field = (_field == _flag) ? 0 : _flag; } // Draw entire GUI. bool guiDraw(ImguiState& _guiState , Settings& _settings , GuiWidgetState& _widgetState , const Mouse& _mouse , char _ascii , float _deltaTime // lists , cs::MeshInstanceList& _meshInstList , const cs::TextureList& _textureList , const cs::MaterialList& _materialList , const cs::EnvList& _envList // imguiLeftScrollArea , float _widgetAnimDuration , float _modalWindowAnimDuration , uint8_t _viewId ) { g_guiHeight = DM_MAX(1022, g_height); const float aspect = g_widthf/g_heightf; g_guiWidth = dm::ftou(float(g_guiHeight)*aspect); const float columnLeft0X = float(Gui::BorderButtonWidth) - g_texelHalf; const float columnLeft1X = float(columnLeft0X + Gui::PaneWidth + Gui::HorizontalSpacing); const float columnLeft2X = float(columnLeft1X + Gui::PaneWidth + Gui::HorizontalSpacing); const float columnRight0X = float(g_guiWidth - Gui::PaneWidth - Gui::BorderButtonWidth + 1); const float columnRight1X = float(columnRight0X - Gui::PaneWidth - Gui::HorizontalSpacing); const float columnRight2X = float(columnRight1X - Gui::PaneWidth - Gui::HorizontalSpacing); // Setup animators. static bool s_once = false; if (!s_once) { s_animators.init(float(g_guiWidth), float(g_guiHeight) , columnLeft0X, Gui::FirstPaneY, Gui::PaneWidth , columnRight0X, Gui::FirstPaneY ); s_once = true; } s_animators.setKeyPoints(float(g_guiWidth), float(g_guiHeight), Gui::PaneWidth, Gui::PaneWidth , columnLeft0X, Gui::FirstPaneY , columnLeft1X, Gui::SecondPaneY , columnLeft2X, Gui::SecondPaneY , columnRight0X, Gui::FirstPaneY , columnRight1X, Gui::SecondPaneY , columnRight2X, Gui::SecondPaneY ); s_animators.updateVisibility(); s_animators.tick(_deltaTime, _widgetAnimDuration, _modalWindowAnimDuration); // Update output window. outputWindowUpdate(_deltaTime); // Dismiss modal window when escape is pressed. if (27 == _ascii) { widgetHide(Widget::ModalWindowMask); } // Begin imgui. imguiSetFont(Fonts::Default); const uint8_t mbuttons = (Mouse::Hold == _mouse.m_left ? IMGUI_MBUT_LEFT : 0) | (Mouse::Hold == _mouse.m_right ? IMGUI_MBUT_RIGHT : 0) ; imguiBeginFrame(_mouse.m_curr.m_mx , _mouse.m_curr.m_my , mbuttons , _mouse.m_scroll , g_width , g_height , g_guiWidth , g_guiHeight , _ascii , _viewId ); const bool enabled = !widgetIsVisible(Widget::ModalWindowMask); // Border buttons logic. if (imguiBorderButton(ImguiBorder::Right, widgetIsVisible(Widget::Right), enabled)) { widgetToggle(Widget::Right); } if (imguiBorderButton(ImguiBorder::Left, widgetIsVisible(Widget::Left), enabled)) { widgetToggle(Widget::Left); } // Adjust mouse input according to gui scale. Mouse mouse; memcpy(&mouse, &_mouse, sizeof(Mouse)); const float xScale = float(g_guiWidth)/g_widthf; const float yScale = float(g_guiHeight)/g_heightf; mouse.m_curr.m_mx = int32_t(float(mouse.m_curr.m_mx)*xScale); mouse.m_curr.m_my = int32_t(float(mouse.m_curr.m_my)*yScale); mouse.m_prev.m_mx = int32_t(float(mouse.m_prev.m_mx)*xScale); mouse.m_prev.m_my = int32_t(float(mouse.m_prev.m_my)*yScale); // Right scroll area. if (s_animators[Animators::RightScrollArea].isVisible()) { imguiRightScrollArea(int32_t(s_animators[Animators::RightScrollArea].m_x) , int32_t(s_animators[Animators::RightScrollArea].m_y) , Gui::PaneWidth , g_guiHeight , _guiState , _settings , mouse , _envList , _widgetState.m_rightScrollArea , enabled , _viewId ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_rightScrollArea.m_events)) { if (RightScrollAreaState::ShowOutputWindow == _widgetState.m_rightScrollArea.m_action) { widgetShow(Widget::OutputWindow); } else if (RightScrollAreaState::ShowAboutWindow == _widgetState.m_rightScrollArea.m_action) { widgetShow(Widget::AboutWindow); } else if (RightScrollAreaState::ShowProjectWindow == _widgetState.m_rightScrollArea.m_action) { //Reset project window state. imguiRemoveStatusMessage(StatusWindowId::LoadWarning); imguiRemoveStatusMessage(StatusWindowId::LoadError); _widgetState.m_projectWindow.m_tabs = 0; _widgetState.m_projectWindow.m_confirmButton = false; widgetShow(Widget::ProjectWindow); } else if (RightScrollAreaState::ToggleEnvWidget == _widgetState.m_rightScrollArea.m_action) { widgetSetOrClear(Widget::EnvWidget, Widget::RightSideWidgetMask); } else if (RightScrollAreaState::HideEnvWidget == _widgetState.m_rightScrollArea.m_action) { widgetHide(Widget::RightSideWidgetMask); } } } // Left scroll area. if (s_animators[Animators::LeftScrollArea].isVisible()) { imguiLeftScrollArea(int32_t(s_animators[Animators::LeftScrollArea].m_x) , int32_t(s_animators[Animators::LeftScrollArea].m_y) , Gui::PaneWidth , g_guiHeight , _guiState , _settings , mouse , _envList[_settings.m_selectedEnvMap] , _meshInstList , _meshInstList[_settings.m_selectedMeshIdx] , _materialList , _widgetState.m_leftScrollArea , enabled ); // Hide texture pickers for hidden texture previews. for (uint8_t ii = 0; ii < cs::Material::TextureCount; ++ii) { if (_widgetState.m_leftScrollArea.m_inactiveTexPreviews&(1<<ii)) { const cs::Material::Texture matTex = (cs::Material::Texture)ii; const Widget::Enum widget = texPickerFor(matTex); if (widgetIsVisible(widget)) { widgetHide(Widget::LeftSideWidgetMask); } } } if (_widgetState.m_leftScrollArea.m_events & GuiEvent::HandleAction) { if (LeftScrollAreaState::MeshSelectionChange == _widgetState.m_leftScrollArea.m_action) { // Get mesh name. const cs::MeshHandle mesh = { _widgetState.m_leftScrollArea.m_data }; const char* meshName = cs::getName(mesh); // Update selected mesh name. dm::strscpya(_widgetState.m_meshSave.m_outputName, meshName); } else if (LeftScrollAreaState::TabSelectionChange == _widgetState.m_leftScrollArea.m_action) { widgetHide(Widget::LeftSideWidgetMask); } } if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_leftScrollArea.m_events)) { if (LeftScrollAreaState::SaveMesh == _widgetState.m_leftScrollArea.m_action) { // Get mesh name. const cs::MeshHandle mesh = { _widgetState.m_leftScrollArea.m_data }; const char* meshName = cs::getName(mesh); // Pass parameters to MeshSaveWidget. _widgetState.m_meshSave.m_mesh = mesh; dm::strscpya(_widgetState.m_meshSave.m_outputName, meshName); // Show MeshSaveWidget. widgetSetOrClear(Widget::MeshSaveWidget, Widget::LeftSideWidgetMask); } else if (LeftScrollAreaState::ToggleMeshBrowser == _widgetState.m_leftScrollArea.m_action) { widgetSetOrClear(Widget::MeshBrowser, Widget::LeftSideWidgetMask); } else if (LeftScrollAreaState::ToggleTexPicker == _widgetState.m_leftScrollArea.m_action) { const cs::Material::Texture matTex = (cs::Material::Texture)_widgetState.m_leftScrollArea.m_data; const Widget::Enum widget = texPickerFor(matTex); widgetSetOrClear(widget, Widget::LeftSideWidgetMask); } else if (LeftScrollAreaState::HideLeftSideWidget == _widgetState.m_leftScrollArea.m_action) { widgetHide(Widget::LeftSideWidgetMask); } } } // Left side. if (s_animators[Animators::MeshSaveWidget].isVisible()) { imguiMeshSaveWidget(int32_t(s_animators[Animators::MeshSaveWidget].m_x) , int32_t(s_animators[Animators::MeshSaveWidget].m_y) , Gui::PaneWidth , _widgetState.m_meshSave ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_meshSave.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_meshSave.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_meshSave.m_events)) { widgetSetOrClear(Widget::MeshSaveWidget, Widget::LeftSideWidgetMask); } } if (s_animators[Animators::MeshBrowser].isVisible()) { const bool objSelected = (0 == strcmp("obj", _widgetState.m_meshBrowser.m_fileExt)); _widgetState.m_meshBrowser.m_objSelected = objSelected; imguiMeshBrowserWidget(int32_t(s_animators[Animators::MeshBrowser].m_x) , int32_t(s_animators[Animators::MeshBrowser].m_y) , Gui::PaneWidth , _widgetState.m_meshBrowser ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_meshBrowser.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_meshBrowser.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_meshBrowser.m_events)) { widgetSetOrClear(Widget::MeshBrowser, Widget::LeftSideWidgetMask); } } // Handle all texture pickers. for (uint8_t ii = 0; ii < cs::Material::TextureCount; ++ii) { const cs::Material::Texture matTex = (cs::Material::Texture)ii; if (s_animators[Animators::texPickerFor(matTex)].isVisible()) { imguiTexPickerWidget(int32_t(s_animators[Animators::texPickerFor(matTex)].m_x) , int32_t(s_animators[Animators::texPickerFor(matTex)].m_y) , Gui::PaneWidth , _textureList , _widgetState.m_texPicker[matTex] ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_texPicker[matTex].m_events)) { widgetHide(Widget::LeftSideWidgetMask); widgetHide(Widget::LeftSideSubWidgetMask); } if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_texPicker[matTex].m_events)) { _widgetState.m_textureBrowser.m_texPickerFor = matTex; widgetShow(Widget::TextureFileBrowser); } } } if (s_animators[Animators::LeftTextureBrowser].isVisible()) { imguiTextureBrowserWidget(int32_t(s_animators[Animators::LeftTextureBrowser].m_x) , int32_t(s_animators[Animators::LeftTextureBrowser].m_y) , Gui::PaneWidth , _widgetState.m_textureBrowser , enabled ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_textureBrowser.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_textureBrowser.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_textureBrowser.m_events)) { widgetHide(Widget::LeftSideSubWidgetMask); } } // Right side. if (s_animators[Animators::EnvMapWidget].isVisible()) { const cs::EnvHandle envHandle = _envList[_settings.m_selectedEnvMap]; imguiEnvMapWidget(envHandle , int32_t(s_animators[Animators::EnvMapWidget].m_x) , int32_t(s_animators[Animators::EnvMapWidget].m_y) , Gui::PaneWidth , _widgetState.m_envMap , enabled ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_envMap.m_events)) { widgetHide(Widget::RightSideWidgetMask); } if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_envMap.m_events)) { if (EnvMapWidgetState::Save == _widgetState.m_envMap.m_action) { static const uint32_t s_selectionToWidget[cs::Environment::Count] = { Widget::CmftSaveSkyboxWidget, Widget::CmftSavePmremWidget, Widget::CmftSaveIemWidget, }; const Widget::Enum widget = (Widget::Enum)s_selectionToWidget[_widgetState.m_envMap.m_selection]; widgetSetOrClear(widget, Widget::RightSideSubwidgetMask); } else if (EnvMapWidgetState::Info == _widgetState.m_envMap.m_action) { static const uint32_t s_selectionToWidget[cs::Environment::Count] = { Widget::CmftInfoSkyboxWidget, Widget::CmftInfoPmremWidget, Widget::CmftInfoIemWidget, }; const Widget::Enum widget = (Widget::Enum)s_selectionToWidget[_widgetState.m_envMap.m_selection]; widgetSetOrClear(widget, Widget::RightSideSubwidgetMask); } else if (EnvMapWidgetState::Transform == _widgetState.m_envMap.m_action) { widgetSetOrClear(Widget::CmftTransformWidget, Widget::RightSideSubwidgetMask); } else if (EnvMapWidgetState::Browse == _widgetState.m_envMap.m_action) { static const uint32_t s_selectionToWidget[cs::Environment::Count] = { Widget::SkyboxBrowser, Widget::PmremBrowser, Widget::IemBrowser, }; const Widget::Enum widget = (Widget::Enum)s_selectionToWidget[_widgetState.m_envMap.m_selection]; widgetSetOrClear(widget, Widget::RightSideSubwidgetMask); } else if (EnvMapWidgetState::Process == _widgetState.m_envMap.m_action) { static const uint32_t s_selectionToWidget[cs::Environment::Count] = { Widget::TonemapWidget, Widget::CmftPmremWidget, Widget::CmftIemWidget, }; const Widget::Enum widget = (Widget::Enum)s_selectionToWidget[_widgetState.m_envMap.m_selection]; widgetSetOrClear(widget, Widget::RightSideSubwidgetMask); } } // Env browsers. if (s_animators[Animators::SkyboxBrowser].isVisible()) { imguiEnvMapBrowserWidget(getCubemapTypeStr(_widgetState.m_envMap.m_selection) , int32_t(s_animators[Animators::SkyboxBrowser].m_x) , int32_t(s_animators[Animators::SkyboxBrowser].m_y) , Gui::PaneWidth , _widgetState.m_skyboxBrowser ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_skyboxBrowser.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_skyboxBrowser.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_skyboxBrowser.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } if (s_animators[Animators::PmremBrowser].isVisible()) { imguiEnvMapBrowserWidget(getCubemapTypeStr(_widgetState.m_envMap.m_selection) , int32_t(s_animators[Animators::PmremBrowser].m_x) , int32_t(s_animators[Animators::PmremBrowser].m_y) , Gui::PaneWidth , _widgetState.m_pmremBrowser ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_pmremBrowser.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_pmremBrowser.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_pmremBrowser.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } if (s_animators[Animators::IemBrowser].isVisible()) { imguiEnvMapBrowserWidget(getCubemapTypeStr(_widgetState.m_envMap.m_selection) , int32_t(s_animators[Animators::IemBrowser].m_x) , int32_t(s_animators[Animators::IemBrowser].m_y) , Gui::PaneWidth , _widgetState.m_iemBrowser ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_iemBrowser.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_iemBrowser.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_iemBrowser.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } // Cmft info widgets. if (s_animators[Animators::CmftInfoSkybox].isVisible()) { imguiCmftInfoWidget(envHandle , int32_t(s_animators[Animators::CmftInfoSkybox].m_x) , int32_t(s_animators[Animators::CmftInfoSkybox].m_y) , Gui::PaneWidth , _widgetState.m_cmftInfoSkybox ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftInfoSkybox.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } else if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_cmftInfoSkybox.m_events)) { _widgetState.m_magnifyWindow.m_env = _widgetState.m_cmftInfoSkybox.m_env; _widgetState.m_magnifyWindow.m_envType = cs::Environment::Skybox; _widgetState.m_magnifyWindow.m_lod = 0.0f; widgetShow(Widget::MagnifyWindow); } } if (s_animators[Animators::CmftInfoPmrem].isVisible()) { imguiCmftInfoWidget(envHandle , int32_t(s_animators[Animators::CmftInfoPmrem].m_x) , int32_t(s_animators[Animators::CmftInfoPmrem].m_y) , Gui::PaneWidth , _widgetState.m_cmftInfoPmrem ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftInfoPmrem.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } else if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_cmftInfoPmrem.m_events)) { _widgetState.m_magnifyWindow.m_env = _widgetState.m_cmftInfoPmrem.m_env; _widgetState.m_magnifyWindow.m_envType = cs::Environment::Pmrem; _widgetState.m_magnifyWindow.m_lod = _widgetState.m_cmftInfoPmrem.m_lod; widgetShow(Widget::MagnifyWindow); } } if (s_animators[Animators::CmftInfoIem].isVisible()) { imguiCmftInfoWidget(envHandle , int32_t(s_animators[Animators::CmftInfoIem].m_x) , int32_t(s_animators[Animators::CmftInfoIem].m_y) , Gui::PaneWidth , _widgetState.m_cmftInfoIem ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftInfoIem.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } else if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_cmftInfoIem.m_events)) { _widgetState.m_magnifyWindow.m_env = _widgetState.m_cmftInfoIem.m_env; _widgetState.m_magnifyWindow.m_envType = cs::Environment::Iem; _widgetState.m_magnifyWindow.m_lod = 0.0f; widgetShow(Widget::MagnifyWindow); } } // Cmft save widgets. if (s_animators[Animators::CmftSaveSkybox].isVisible()) { imguiCmftSaveWidget(int32_t(s_animators[Animators::CmftSaveSkybox].m_x) , int32_t(s_animators[Animators::CmftSaveSkybox].m_y) , Gui::PaneWidth , _widgetState.m_cmftSaveSkybox ); if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_cmftSaveSkybox.m_events)) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_cmftSaveSkybox.m_directory); imguiStatusMessage(msg, 4.0f); } if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftSaveSkybox.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } if (s_animators[Animators::CmftSavePmrem].isVisible()) { imguiCmftSaveWidget(int32_t(s_animators[Animators::CmftSavePmrem].m_x) , int32_t(s_animators[Animators::CmftSavePmrem].m_y) , Gui::PaneWidth , _widgetState.m_cmftSavePmrem ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftSavePmrem.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } if (s_animators[Animators::CmftSaveIem].isVisible()) { imguiCmftSaveWidget(int32_t(s_animators[Animators::CmftSaveIem].m_x) , int32_t(s_animators[Animators::CmftSaveIem].m_y) , Gui::PaneWidth , _widgetState.m_cmftSaveIem ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftSaveIem.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } // Cmft filter widgets. if (s_animators[Animators::CmftPmrem].isVisible()) { imguiCmftPmremWidget(envHandle , int32_t(s_animators[Animators::CmftPmrem].m_x) , int32_t(s_animators[Animators::CmftPmrem].m_y) , Gui::PaneWidth , _widgetState.m_cmftPmrem ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftPmrem.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } else if (_widgetState.m_cmftPmrem.m_events & GuiEvent::GuiUpdate) { imguiStatusMessage("Edge fixup is required for DX9 and OGL without ARB_seamless_cube_map!" , 8.0f, false, "Close", 0, StatusWindowId::WarpFilterInfo0); imguiStatusMessage("Whan used, it should be also handled at runtime. 'Warp filtered cubemap' option will be enabled." , 8.0f, false, "Close", 0, StatusWindowId::WarpFilterInfo1); } } if (s_animators[Animators::CmftIem].isVisible()) { imguiCmftIemWidget(envHandle , int32_t(s_animators[Animators::CmftIem].m_x) , int32_t(s_animators[Animators::CmftIem].m_y) , Gui::PaneWidth , _widgetState.m_cmftIem ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftIem.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } // Cmft transform widget. if (s_animators[Animators::CmftTransform].isVisible()) { imguiCmftTransformWidget(envHandle , int32_t(s_animators[Animators::CmftTransform].m_x) , int32_t(s_animators[Animators::CmftTransform].m_y) , Gui::PaneWidth , _widgetState.m_cmftTransform , mouse ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_cmftTransform.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } // Tonemap widget. if (s_animators[Animators::TonemapWidget].isVisible()) { imguiTonemapWidget(envHandle , int32_t(s_animators[Animators::TonemapWidget].m_x) , int32_t(s_animators[Animators::TonemapWidget].m_y) , Gui::PaneWidth , _widgetState.m_tonemapWidget ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_tonemapWidget.m_events)) { widgetHide(Widget::RightSideSubwidgetMask); } } } // Modal windows. if (s_animators[Animators::OutputWindow].isVisible()) { imguiModalOutputWindow(int32_t(s_animators[Animators::OutputWindow].m_x) , int32_t(s_animators[Animators::OutputWindow].m_y) , *s_outputWindowState ); if (guiEvent(GuiEvent::DismissWindow, s_outputWindowState->m_events)) { widgetHide(Widget::ModalWindowMask); } } if (s_animators[Animators::AboutWindow].isVisible()) { imguiModalAboutWindow(int32_t(s_animators[Animators::AboutWindow].m_x) , int32_t(s_animators[Animators::AboutWindow].m_y) , _widgetState.m_aboutWindow ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_aboutWindow.m_events)) { widgetHide(Widget::ModalWindowMask); } } if (s_animators[Animators::MagnifyWindow].isVisible()) { imguiModalMagnifyWindow(int32_t(s_animators[Animators::MagnifyWindow].m_x) , int32_t(s_animators[Animators::MagnifyWindow].m_y) , _widgetState.m_magnifyWindow ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_magnifyWindow.m_events)) { widgetHide(Widget::ModalWindowMask); } } if (s_animators[Animators::ProjectWindow].isVisible()) { imguiModalProjectWindow(int32_t(s_animators[Animators::ProjectWindow].m_x) , int32_t(s_animators[Animators::ProjectWindow].m_y) , _widgetState.m_projectWindow ); if (guiEvent(GuiEvent::DismissWindow, _widgetState.m_projectWindow.m_events)) { widgetHide(Widget::ModalWindowMask); imguiRemoveStatusMessage(StatusWindowId::LoadWarning); } if (guiEvent(GuiEvent::GuiUpdate, _widgetState.m_projectWindow.m_events)) { if (ProjectWindowState::Warning == _widgetState.m_projectWindow.m_action) { const char* msg = "Warning: you will lose all your unsaved changes if you proceed!"; imguiStatusMessage(msg, 6.0f, true, NULL, 0, StatusWindowId::LoadWarning); } else if (ProjectWindowState::ShowLoadDir == _widgetState.m_projectWindow.m_action) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_projectWindow.m_load.m_directory); imguiStatusMessage(msg, 4.0f); } else if (ProjectWindowState::ShowSaveDir == _widgetState.m_projectWindow.m_action) { char msg[128]; bx::snprintf(msg, sizeof(msg), "Directory: %s", _widgetState.m_projectWindow.m_load.m_directory); imguiStatusMessage(msg, 4.0f); } } } // Status bars. s_statusManager.update(_deltaTime); s_statusManager.draw(); // End imgui. imguiEndFrame(); return imguiMouseOverArea(); } /* vim: set sw=4 ts=4 expandtab: */
39.061924
137
0.559329
[ "mesh", "transform" ]
2223a48def266652499173ced5fd701077289b2c
612
cpp
C++
src/Evaluater/compare.cpp
atom9393/CUBE
b398a1c7b317047b89a7eeddf67aed1a78d20f36
[ "MIT" ]
7
2021-12-27T05:43:40.000Z
2022-01-12T09:35:52.000Z
src/Evaluater/compare.cpp
atom9393/CUBE
b398a1c7b317047b89a7eeddf67aed1a78d20f36
[ "MIT" ]
6
2021-12-24T11:29:05.000Z
2022-01-11T12:23:19.000Z
src/Evaluater/compare.cpp
atom9393/CUBE
b398a1c7b317047b89a7eeddf67aed1a78d20f36
[ "MIT" ]
1
2021-12-22T02:41:33.000Z
2021-12-22T02:41:33.000Z
#include <algorithm> #include "error.h" #include "debug.h" #include "Token.h" #include "Object.h" #include "Node.h" #include "Evaluater.h" ObjectType Evaluater::compare(Node* node) { auto& ret = node->objtype; ret = evaluate(node->expr_list[0].item); if( !ret.equals(OBJ_INT) && !ret.equals(OBJ_FLOAT) ) { error(ERR_TYPE, node->token, "invalid operator"); exit(1); } for( auto it = node->expr_list.begin() + 1; it != node->expr_list.end(); it++ ) { if( !ret.equals(evaluate(it->item)) ) { error(ERR_TYPE, it->token, "type mismatch"); exit(1); } } return OBJ_BOOL; }
22.666667
83
0.622549
[ "object" ]
223a30b74f74e4caa9eead9cc0ab5b5c3b90db30
174,996
cpp
C++
bench/ml2cpp-demo/SVR_rbf/RandomReg_100/ml2cpp-demo_SVR_rbf_RandomReg_100.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
null
null
null
bench/ml2cpp-demo/SVR_rbf/RandomReg_100/ml2cpp-demo_SVR_rbf_RandomReg_100.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
33
2020-09-13T09:55:01.000Z
2022-01-06T11:53:55.000Z
bench/ml2cpp-demo/SVR_rbf/RandomReg_100/ml2cpp-demo_SVR_rbf_RandomReg_100.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
1
2021-01-26T14:41:58.000Z
2021-01-26T14:41:58.000Z
// ******************************************************** // This C++ code was automatically generated by ml2cpp (development version). // Copyright 2020 // https://github.com/antoinecarme/ml2cpp // Model : SVR_rbf // Dataset : RandomReg_100 // This CPP code can be compiled using any C++-17 compiler. // g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_SVR_rbf_RandomReg_100.exe ml2cpp-demo_SVR_rbf_RandomReg_100.cpp // Model deployment code // ******************************************************** #include "../../Generic.i" namespace { std::vector<std::any> lProblem_data_dual = { 0.1 , -0.1 , 0.1 , 0.1 , 0.1 , -0.1 , 0.1 , -0.1 , -0.1 , 0.1 , -0.1 , -0.1 , 0.1 , -0.1 , 0.1 , -0.1 , -0.1 , -0.1 , 0.1 , 0.1 , 0.1 , -0.1 , -0.1 , 0.1 , -0.1 , -0.1 , -0.1 , -0.1 , 0.1 , -0.1 , 0.1 , -0.1 , 0.1 , 0.1 , -0.1 , 0.1 , 0.1 , -0.1 , -0.1 , -0.1 , 0.1 , 0.1 , -0.1 , 0.1 , 0.1 , -0.1 , 0.1 , 0.1 , 0.1 , 0.1 , 0.1 , -0.1 , -0.1 , 0.1 , -0.1 , -0.1 , -0.1 , 0.1 , -0.1 , 0.1 , 0.1 , -0.1 , -0.1 , 0.1 , 0.1 , -0.1 , 0.1 , -0.1 , 0.1 , -0.1 , 0.1 , 0.1 , 0.1 , -0.1 , -0.1 , -0.1 , -0.1 , 0.1 , -0.1 , 0.1 ,}; std::vector<std::vector<std::any> > lProblem_data_sv = { { 0.9975868835302524, -1.0185164819252965, -0.4907095935832193, -0.1175964601895572, 1.6618758964364468, -0.40286853045436744, -0.9074016847202964, 0.4159519024571559, -0.16461818088766905, 0.14740634346962928, 1.7854547384883273, 0.618817017939555, -0.25780460687449214, -0.6770895759269412, -0.36477608245908644, -0.37782152830727483, -1.856253002739237, 1.7960290020904512, -0.30254920218381587, -0.5559621973797875, 0.7991038438840854, 0.13078436686290298, -0.5217573225473036, -1.5220599955356129, -0.5253535247722844, 0.3385140293914567, -0.6950787279168026, 1.4002706710996493, -1.2570409012649058, -0.9178020538746622, -2.2713599016681725, 0.5129063900513596, 0.5121727475123873, -0.2912274847884899, -0.6427228986099494, -0.3131129503855756, 1.721446415941349, -0.17201217073495145, 0.9488904105360995, 2.2424795386949707, -1.1595419832220037, 0.7934215718317604, 0.9356393202354978, 0.5204610216972285, -1.6205963714569014, 1.229049310791119, -0.09992785854738331, 0.41852148239198356, -0.7182733876113051, -0.9856325121353287, -0.1535070762467532, -0.37454700236594907, -0.29127459055683874, 0.682763890836373, 1.2641569795367864, 0.7098812147007791, 1.5771135501927906, 0.14351653832831143, 0.9843377189523411, 2.2242886492238942, -0.8205401689735666, 1.1955089641562817, 0.11167422566881283, -0.8177928819332131, 0.28744514967522755, -0.5134105077236958, -0.3225191851796998, 0.1912940593917663, -1.080963694044816, 0.18197529367808726, -2.2886284398323293, 0.161275838764888, 0.8706783713613224, -1.3191981518292886, -0.830969625127735, -1.3928344082676603, 0.5464825298673197, -0.20909367812384821, 1.491459026765595, 0.7493356599277641, 1.1466886648707697, 0.7876799523508591, 0.2959905067172231, -0.6972996896518504, 0.23450676000724083, 0.011364624847997808, -0.13208217690352722, 1.9468272421201875, 0.4135619376396626, 0.7733056054179359, 1.0128048153995814, 0.9411422608847925, 1.2489033652160668, -0.13209290768365922, -0.4883683896034081, 0.16524838725655086, -1.1488996959744968, 1.3493331232197965, 0.2489083404352714, -0.7620785776327283 }, { -1.0941228121000135, 0.26903307191420417, -1.539447205535099, 0.11611905254181326, 0.059720875350302544, 0.22525967204239097, 0.06873296628221594, 0.2186300522158838, 0.01734883909357232, -2.0807434366065274, 0.197319544692469, 0.09548179512526811, -1.7071503084430795, 2.0197075382161973, -0.21302784187080862, 0.700108335023235, -0.2690801545497016, 1.4777948839167314, 0.37147117070110064, 1.8999242249159969, 0.18277554352874176, 0.29516926909051866, -1.200588300491612, -1.0526075033440259, 0.4540609666262245, 0.22956100049753425, 0.8688713137691321, -0.8564014685404552, 0.4806247755082118, 0.7555560753022003, 0.25642306018972494, 2.3197003724864405, 0.005776445690250085, 0.9939125193518435, 0.5429754970389625, -0.5213806932686862, 2.3607398202908456, -0.45161871045280855, -0.94573867878224, 0.6231872755523417, -0.2577199536318905, -0.8066313121815939, -0.24658132838041721, 0.3893492601241742, 0.23032946912583396, 0.7987201146135731, -0.843626994433454, -0.7663698075173571, -0.4657740816266557, -1.6626699167852952, 0.9044629641934606, 0.8811381937870795, 1.045707370001454, 0.9216080128673165, 0.15296794423012733, -2.045086351640408, 0.12505410550811816, -1.5979223566251546, -1.0223563065585863, -0.3411777852018967, 1.2851772071802452, 0.2883460412331891, 0.8578682015098723, -1.966529924556001, 0.8824090912831056, -2.676012769033237, 1.2848698888277887, -0.2637109958674293, -1.0964347843416533, 0.5666115350404656, -1.1938216052345876, -0.3491154200828086, -0.1785962508390721, -0.1243309808707174, 0.2424887066377945, 1.086449903197894, 0.3349872925775053, 0.19616414704117394, -0.0831589256767515, -0.9054390119820906, -1.0811046088210599, -0.38232143661331514, 0.8779667626192937, 0.9711365118738093, 1.2126467551721245, 0.7425669134136468, -0.29435682245124273, 0.3908935807166696, 0.20336034477363013, 1.1336879755799698, -1.0055380770174316, 0.380802426428408, -1.0408842446962512, -0.013470916881029048, -0.2848001645251152, 0.16029645021972425, 0.2039112843885945, 1.531470666375417, 1.3867217084073522, -0.43145378468816875 }, { -0.6038415048551125, -0.5500445634098673, 1.1987407295974568, 1.0808888040073836, -0.8326992223188531, -0.10980458243257392, 1.3839078891899046, 0.15797297071605337, -1.9352919679634237, -0.13407626572907905, 1.885772361269078, 0.2796008140283078, 0.015753812755006907, -0.5810401230650515, -1.0552803062310707, -0.27199552384021314, 0.49123592676716743, -1.3409235307343772, 0.9930519828754866, -0.9721005261157247, -0.3491743621738599, -0.5840914507853797, 0.4548726514534548, -1.1858790167232, 2.1530127692880088, 0.31019109620968505, -1.1684726172741504, -0.8320790022395909, 0.5555744663752504, -0.19093991296277119, -0.4931607192822323, -0.30092184281142215, -1.0824197503189952, -0.29345241845195624, 0.09760196253837831, -0.18456462794712944, 1.1421122335703084, 1.7168023082382906, -0.46325375980963035, 0.1717656079566421, -2.170365952646124, -0.007565149922078345, 1.3957852252647645, 0.4966330833310774, 0.6438397869377434, 0.13709555490599074, -0.5309976462222049, 0.23873785304934028, 0.46235765919974514, -0.06507469676654463, -0.0660006217871807, 1.1506028239303168, 0.9511301038315328, -0.21006979388293318, 1.1650525764041093, -0.5598594458869008, -0.5620678942514361, -1.9915668447242423, 0.3680832393511564, -1.6760339422173018, -0.6319723648137022, 0.7467360124831843, -0.3121490298354688, -0.9285284294689728, 1.7325160567759645, -0.625002117575258, 1.4180348225968646, 0.3675616569481875, -0.40127619051743346, -0.9841573460665335, -0.8127228223550851, -0.6761587758754272, -0.27935115699567614, 0.9445466357528333, -1.7631693027466862, 0.2448776230078828, 0.4958958995442235, -1.342240466295085, -1.2534770416212726, 1.023707973326149, 0.8122587815237609, 1.7262079536131392, -1.8148095645157531, -1.440068172277151, -0.3409716567521859, -0.6367649857832111, -0.3951217446440815, 0.43178634165410146, 1.1350914789682731, -0.28990312664795453, 0.12468681606563736, 0.16233874689032918, -0.7501273902001805, 0.08581502548639967, 0.5223429655591334, -0.43949746969466935, 0.7742996607029197, 0.7787162158067873, 0.9613959727333456, -1.5386554000200503 }, { -1.2845665573436023, -1.2358172795805038, -1.0035871813708714, 0.505778165322547, -0.9516149391452087, -1.2382061998974805, -1.1562465476980834, 1.1683595864774254, 1.2780698055750692, -0.32719679929761397, 0.5737159253616118, -0.3927402150079893, 0.6019230358769425, -0.25284855216233365, -0.975171866312725, 0.21077319931609845, 0.37294958190691846, 0.6731684358114798, -0.21485889624091203, 1.547167334324274, -0.7661477643069091, -0.5281813448045657, 0.9839338698365118, -0.045728902075928474, -0.5140339525818278, 1.3930809796189392, 1.7196699412287848, -1.2325021017174356, 0.5874418670365338, 0.037311441317267074, -0.6096457503599236, -0.15597197373965818, -0.41564693189695573, 0.728065902936228, -0.34844631863951114, -2.1873042874678688, -1.4941282953522228, 1.3401239841043064, 0.5264340921992666, 0.24915567274604444, 0.3477615630836113, 0.2296040700909747, -1.8869324431180343, 0.3218366962899042, -0.08960750981985693, 0.9275558456792803, -1.1521243963828545, -1.0490657824280945, -0.7766288847671153, -0.5033613242384567, -0.09875161723161692, 0.41359649592199804, 1.0418355683627163, -0.12056260431824695, -0.6222824334141263, 0.49208113979504614, -0.021982795695214163, 0.8588962077282837, -0.2067674743833677, -0.9012615755426259, -0.35046964259922275, 0.5870541694322574, -2.16701532588275, -0.015136373059819245, 0.6414564376658192, 0.5431907790156175, 0.7869523573965067, 1.2162740191280312, -0.7299877774104621, 1.2495928478776275, 0.7477551613291447, -0.15867583023858642, -0.7680547234380762, 1.3114372988926326, -0.8860138062064501, 2.437529485261286, 0.25508020468670817, 0.958018010739779, -0.05353121179525126, 0.7370702471714684, 1.608695307321087, -0.7968240838443422, -0.3856097851182563, -0.3261791133748659, -0.9979727593666947, 1.6510226694425665, 1.788260436160657, -0.5767303683963166, -0.3227444037884647, 0.9213283770320988, 0.44807258771271824, -0.20667770907646468, 0.42795216908556305, -0.666441265856412, 0.6586029014628093, 0.1505204106038074, 0.7273863789381249, 0.16446386005868274, -0.45990513075108486, 2.0494550418773194 }, { -1.0129709485035108, 0.1758529598594738, -2.124017697020008, 1.5918934839299015, -0.4965908385468796, 0.5747079488646184, -0.8125894344701877, 0.8901912774957191, 1.3955083532278496, 0.05005660378635286, -0.3422754726525957, -1.0681013872437675, 1.404591697347607, -0.46123660182969617, -0.7689635955027699, -1.423751308368867, -0.0649779661059019, -0.3108926350163469, 1.0850633664610485, -0.5123744390615866, 0.23393099711981735, 0.10712220930068758, 0.30993547412311195, 0.3616943206052126, -0.9578464625366726, -0.28644000055479085, 0.7924424901248528, 1.3698651802049584, -0.7273353868032125, -0.22873921494136007, 1.665084547537538, -0.16800439240917622, -1.0101430144349874, -0.323596015434112, -1.3195652280706762, -0.4728260225553187, 1.292379523190115, 0.9219480499509473, -0.8670636063559841, -0.4600368110556441, -1.2826632366617503, 0.7157208520586755, -1.567329591837615, 0.9650888403767531, 0.5826294780823734, 0.6030826172173702, 0.5997872351093034, -1.8446658847999522, -0.5749599821077215, 1.103780077181924, 1.1825308150446205, -0.21500103200187376, 0.6552430971627566, 0.21547383024526368, 0.18452146550329931, -1.0171569789157369, 0.0865112941209962, 0.49403762255015354, -0.918238003291653, -0.7579269170525086, -0.036336076488534715, 2.2053533528503895, -0.35712726235177694, 1.8621164983678586, -0.19487025688779008, 0.5436025033388283, 0.12292826302270285, 0.2729501157654951, 1.1922006908057363, 1.7287021602832124, 1.6686815058350344, 0.47499447720415827, 0.22088447943860617, -0.5466385581363211, -0.1464480339431949, -1.2011815419734744, 0.17163935790654755, 0.31534242280700536, -0.16803149993756028, 0.9843108394055231, -0.04372784795194554, 0.1154793949168143, 0.829398311906618, 0.7537858121706568, 0.5529430025218375, 0.4513692668829509, -1.405846366991037, 1.1837513531470258, 1.028769790079673, 0.5309261951169724, -0.13711901586401823, 0.6800583500631447, -1.5598473770425523, -0.6486506901716966, -2.101134919828781, -0.6748741379360986, -0.546063870435756, -1.3884670600153215, 2.3296807010311498, -0.9118910514472455 }, { 0.9105231769233195, -0.3955576818362122, 0.7297304045978491, 0.05421690682506059, 0.0015054387104832332, 0.25360983489131994, 0.4949162516439646, -1.3070730409615443, 0.9527733280821856, 0.19554134248301583, 1.4537226733491924, -1.3226984787927474, -0.37605867641074014, -0.6947828356973941, -0.17424242604374757, -2.2724159845307237, 0.9819645661925364, -0.3566277079871807, -0.11890667940220898, 0.3246777802681322, 0.8851896523725042, -1.984841805739109, 1.1105425582895145, 2.002419889656071, -0.9916120707286292, -0.0640047513703269, 1.2614971183989245, 0.674494399226458, 0.39002837370407417, -0.28448464110138644, -0.7722212215401404, 1.1725987515928256, 0.44288899262266535, 0.2723098839475687, 0.47206522558489566, 0.4482761292475762, 1.2153452298634448, -1.6830229177997325, -0.6773465471277739, 0.2779114808909512, 1.0081334158185864, -1.355034428776207, -0.161801653752509, -0.5652778763105981, 0.41335980222137936, 0.42238305869124765, 0.7112337984776995, 1.7744279188169088, -1.4259508158528043, -0.6537467633077745, 0.999012494801386, -0.03096518504988527, 1.2666575686592898, -0.913288640685386, 0.20211195454166467, 0.05900729153788349, 0.3208065709069315, 0.18522872660908676, -0.12520454612192722, -1.2640455987181434, 1.320595775301568, 0.5993564505961142, 1.3198190481440728, -0.7514590064927159, 1.8006105181473373, -0.40879214799108193, 0.6216950790059019, -1.3651828973014568, -0.18777591649520586, 1.3306958148508041, 0.9799824213252673, -0.08058710689730604, 0.7785157686173833, 0.10336666450572725, -1.032386278660329, 1.0123041609371397, -0.15619700089011793, 0.23212621989057727, 0.4634530915081752, 0.2860464833805073, -1.0621822597900308, -0.5192720546629351, -1.4540177950915505, 0.2367572151246406, -1.1448666726113645, -0.6460840340167464, -0.6595773495940102, 0.0940904102670373, -0.33993486325251376, -0.25832489782461504, 0.06661085123260317, 0.8550632715410826, 1.536752431463167, -0.01707126722672022, -1.2139031001215053, -1.6477480044411406, 1.0053130127005914, -0.6653922101531952, -1.058252307657798, -1.6510428638289125 }, { 0.7776282218269234, -0.24379989258930954, 0.752924380191013, -0.977321689783187, 0.9520742701157866, 0.8590822798899417, -0.11682016815733795, 1.8070782568590917, 0.8627659152827322, 0.6156544307222147, -0.5867952644936384, -0.3264108678952418, 0.6550136792740332, -0.26085594832317993, -0.2940530127506063, -0.005586154896213053, -0.366538036929481, 0.9529308131356813, 0.061780701862683744, 0.18260993893193986, 0.497715535121489, -0.7668597615910899, 0.6397110387433214, -0.9605477122885152, 0.4245429152242627, -0.11022711792187163, 0.9958876123178917, -0.8873813506551436, 0.1281922841997881, 2.42247622271464, -1.2778710757513634, 1.2360995542822817, -0.7197677899107197, 0.7062547862724639, -0.521861488528336, -0.34630750878301625, -1.5255212754952614, -0.3541269750181948, 0.6470161680589449, 1.5061426829349598, 0.9152366943029557, 0.7334662501880774, -0.6298223101036279, -0.4928700865499721, 0.1449959436771628, 0.628883510145767, 0.24443963213113018, 0.7508371228384951, -1.558283573899076, 1.716142997327132, -0.7608407698819836, 0.5720014223445904, -0.9319510950421263, 0.6620344378202925, -1.8392499953836126, 0.09462850583490037, 0.6002371534341546, -0.0994191601386941, -0.4340542751759801, -0.24223073698988998, 1.721614588783887, 0.4577416885625386, -0.08107535975335757, -1.112205091328532, -2.303816498707583, -0.6198176332018573, 1.9491730910516283, -0.6168757981930597, 0.18794722564168084, 1.1216512229519413, 0.09286241395221292, -0.8078421352778917, -0.40725270591101514, -1.8326025339049876, 0.18797939961701263, 1.2424690862524188, 1.5570617620773537, 0.3178357660335945, 1.177120497954702, -1.1147611489746436, 0.9837190961593756, 0.5890337546389524, 0.8876763970882487, -1.4341542479321494, -0.600142579833799, 1.2060328664572244, -0.6245037845698839, 1.6652528958218347, 0.41911675731125125, -0.7045212696185703, 0.7274187888572882, 0.7429386111395339, -0.2918666947028037, 0.37307151903369595, -1.5799163405471108, -0.6229783978776244, -0.7459202912236828, 0.8765680877994171, 0.6526286023457208, 0.3368386356142362 }, { -0.5947312471390133, -0.14855701667470037, 0.9972243916339923, -0.659807599616025, -1.2194989423910927, -0.22885242107312934, -0.3407562343302471, 1.9014603919756865, 0.49672677649497265, -0.8183320547434164, 2.2685872258770905, 0.6818628664528035, 2.317840129971608, 0.34812887568753526, 0.9284705507206129, 0.08377370948811456, -1.9420133003619735, 0.9934886010441593, 1.591417918480605, -0.6555957450068655, -0.09520191074001921, 2.648163670079692, 0.17070433220548542, -0.45664441884308327, -0.6165639971833476, 0.5921367946972346, -1.7121764966971844, -0.2524775468785099, 2.1677749702748446, 2.256697904789873, 1.4765029429200935, -0.7893931092551081, 0.739332654554414, 0.11027959010054796, 0.5190214675906757, -1.345551979790628, -0.5307045322224024, 0.6602292850712695, -0.18576378527052065, -0.16547391902202888, 0.9613047392498556, -0.5533292299123506, 0.08957237279348364, 1.1269338505796052, 0.018891335176157147, -0.5039047582119509, -0.19005169714227246, 0.12404207242383153, -2.1480505684327142, 0.5835540700251768, -0.7582041020072973, -2.0478193176659087, 1.336227230258171, 0.42158125344786807, 0.11191854813332354, 1.4288736838288938, 0.9582240417748618, -0.07770331578540216, -1.295336622959194, 0.16843010970207475, -0.13109785882058722, 0.1823868712016277, -2.282352717394551, -1.9413043911008907, -0.37942207730647354, -0.7108515624267276, 2.0163852520087913, 0.3469154224334339, 0.07738590051954632, -0.052511464668111504, -0.9646025597580585, -0.4332335375980467, 1.3608998283081601, -1.1786045060890393, 0.9628034817169104, -0.8398841617944885, 0.3973088960435351, 2.0907239226021073, 1.4246529613071528, 0.0650881344193953, -2.250236231772434, 0.3866323637246483, 0.7236378757831969, -0.5877553905268816, 2.036830823346565, -0.7948485517954336, 0.6194974161532137, -2.008725096794061, -1.1504844470300848, -0.5789272546275236, -0.8446609367343986, -0.41461001950474163, 0.5052563678518943, 0.5293825938811465, 1.0630087975286668, -0.30632041667865256, 1.599067054953987, 0.05112609624003823, -0.5404918080065868, 0.7148739927425414 }, { 0.33291056374103883, -0.16372009255828124, 0.6711947190599098, 1.3419906953654295, -0.4233378333961578, 1.7226040722993716, 1.7327983780353353, -0.919723457692772, 0.5225386626750229, -1.4113130571285446, 0.6392020587185764, -2.3647574020068047, 1.0901295605582688, -0.5758290809477716, 0.32341826959648295, 0.6433592121809218, -0.5303271526476072, -1.1371915662299197, -0.32708625268269326, -0.5058003865138625, 1.3739520090723474, -1.7885360709318514, -0.3463541301131144, 0.21308828842752156, 1.0793443975291446, 0.46238060129166486, 0.6623298870476911, -0.24873961548043694, -0.23929647235393137, 0.41071007855143443, 0.15853523281812312, 0.22418695911281536, 0.6430072393302189, 0.9380136904955607, 0.008195345837626634, 0.32142977152454844, -1.2495795813027977, 0.26152125787538144, -0.2900040524105142, 1.43629280498466, 0.10715851196782991, -1.277994412610604, 1.421875453224298, -1.0495224376120962, -0.9615662898307464, -0.22534264711586277, 0.9444309886480903, -0.6614220432878031, 0.27881375828154403, -0.5303212005433303, 1.662672460930335, -0.21472348589688536, -1.2710077669151731, -0.29157358796271793, -0.7706707136524124, -0.08042811833495835, 0.7379869754948905, -1.635627281588523, 1.061984565910281, 0.03846674558083296, 0.4913350109051379, 0.22885481609230923, -0.03277253020320722, -0.5362164085336691, -0.6450938560071097, -0.62021156059666, 1.3310869796087246, 1.2505521474548902, -0.4595236871795928, 0.6575038895002946, -0.548574995285362, -0.08032563816377523, 0.4715198809820012, -0.9541511016410574, 0.999564916000194, -0.3653894159197561, -0.4957144018056562, 0.4365104476539064, 0.31951315402216107, 0.6134728139942742, -1.8130818762045466, 0.5686299031785073, 0.7668437757754999, 0.01663158436200757, -0.50121130930097, 0.11846602683614461, -2.040113803171429, 0.45828793876616447, 0.5522043442253135, -0.26852046676993463, -0.5583924823639528, -0.18440779099069243, -0.11352248037217438, -0.07117113335021549, -0.14466184364459408, -0.8100387031157575, 0.7359394469163053, -0.2227444485320821, -0.34219217399760216, -0.032340697730724274 }, { -0.03952658557316196, -1.5703451918982143, -0.6921519604442642, 0.8305297993852947, 1.5264579268468426, 0.9070950390564853, -1.93869079545603, -0.5244383543738317, -0.9686555633330414, -0.032826783337179886, 0.8368529362198859, 0.0799232666041485, 0.32363523946490275, -0.9598852679092784, 0.2419754184202342, -0.5679381033414751, -1.1152026531410597, -1.5967032945702595, 0.3929679590774747, 1.122884079539261, -0.9027762264793969, 1.23012363518232, -0.003867240589349672, 0.371755682675117, -1.502895047451602, -0.6949206973081019, -0.4548924221554887, -0.36101707880458855, -1.6750068416055923, -1.0679456019942863, 0.6865384484494096, 0.7391862592491135, -0.6800471204436256, 0.3850992572108831, -1.2825146469141433, -0.9189047280942176, -0.23902716868204135, 0.6915938719982303, 0.26364613571074824, 1.3847639501026054, -0.0750537851217341, 0.26157684399692804, -0.1944269810158187, 0.620915555616041, -1.350163787357163, -1.6744383713120186, -0.5666067468034486, -2.031048577702042, -0.9916279066014636, -0.8144640017516379, -0.3617670044067983, 1.2542810863606966, 0.5340396052561488, -0.37901185397582493, -1.7537864969013697, -0.4433783115027706, -0.5434738627426289, 0.49481459231140307, -1.0819030886115917, -0.95308420759752, 0.4301156983479469, -1.987845251423184, -0.5685640726247965, -1.6254313021666404, 1.020827464289526, 0.6194665990268481, 0.03011015784914913, -0.37507160746228224, 0.10525716103775908, -1.5508626534469214, -1.5673268757828764, 0.2178232684497715, 0.08145614337373172, -0.5884895266977762, -0.03174504385460746, -0.37602223883119723, -0.9833173355754584, 1.0397287009694685, 1.0671410769529253, -0.7574798215711888, 1.8174897430279287, 1.4158181775754703, 1.6058237194269285, 2.785199980487858, 1.147206568382731, 0.8286561237765696, 0.04450156581425728, -0.03566527878895629, -1.1967851934768055, -0.17810061015708223, -1.3410459970717008, 0.51068167474964, -0.15208586936522825, -0.7473915447418805, 1.0090990711807322, 0.36833748980135433, -0.822443328554055, 0.13821976272366712, 0.1694385211769322, 2.8635788027581994 }, { -1.3972730704749228, 0.6863791088567063, -0.14910764370107588, -0.8469924795989027, 0.30676498278866865, 1.217880095229888, -0.6808716255154688, 0.6653751952735278, 1.126511830403137, 0.34527283247497775, -1.1264551907289397, 1.0928449170385495, -1.619727393034093, 0.7778850493052814, -1.3894135849923503, -0.2619337051067455, 0.06100047219319655, -0.9316296335612599, -1.3797204232516866, -0.5279281236716252, -1.0430282633403334, 0.09315367351534695, -0.18557431358150414, -0.16038586965929355, 1.4710591444507641, -0.5171034674316312, -0.3926442633073219, 0.40759276106969017, -0.8396332755628751, 1.0328665570369036, -0.13417726126593654, 0.0424532071914051, -0.7323133528167771, -2.8848894314818914, 1.3352521582992876, 0.6599742237413181, 0.5694280757863868, -0.2922259070116752, -1.1243934691027448, -0.5466790728769666, 0.7589110790016569, -0.3249694575015152, 0.15854521672390867, -0.7454950135632554, -1.1524586314613603, 1.854581168899049, 0.5536689394082407, 0.031273712409758465, -1.6641409688948057, -0.9836755376106112, 0.857390467996648, 0.1576454363367638, -0.7507934487670709, 0.48174308006640976, -0.8303723222155923, 0.2681358152314392, 1.1721918759343581, 0.6488000660348413, -0.010402614709676709, 0.04973433253049581, -0.1244913307996997, -0.04606999745151482, 2.08793068549344, 0.017922186169432225, 1.6810008737734947, 0.369008618648244, 1.1098255908670482, 0.4008556092301585, -0.07505324455592051, -0.1072753864939762, -1.6580321110762395, 2.2046891521854675, 0.5774932190014629, -0.772242366601433, 0.5173681413203864, -0.9940810914565409, 1.4217904379903907, -2.3270096991780385, 1.206420135227378, -2.27487538810346, 0.5635383410864324, 1.455191487578734, 0.5377998158757598, -0.9716058609533806, 1.2514544282602138, -0.27046777918220216, -0.6619315381607885, 1.3267253368720948, -0.5942319858236069, 0.9707868611268088, -0.8558056453982146, -1.706234181003013, -1.397327932189668, -0.38229578755628013, -0.4811845639215385, -0.006375533761750635, 0.10329859071447435, -1.0525763830060462, -0.20167866028996354, 0.3514497783244194 }, { -0.08690978306197038, 0.7260545123437954, 0.2717946860850315, 1.718561978569764, 0.7320580635677166, 0.4162039895467424, 2.0830286044594035, 1.988976920686586, 0.41864035078570133, 0.4014263105289899, -0.50803809653635, -1.8643995936474218, -1.1423525688464795, -1.260894060688721, -1.1556858222173405, -0.05195967943954113, 1.2270131689911181, 0.6715738673839912, 0.15335974112513717, -0.08547766482955906, -0.161035898030632, 0.5478162552734464, 2.153084879202437, -0.18806216314284416, 1.1368003686542203, 0.6447230744502875, 0.5309559740922958, -1.0178317303315616, 0.17815169924446114, 0.749948147305792, 0.763947903506552, 1.0498208059757421, 0.14266302284649846, -0.11638196666523518, -0.13793261728909617, -0.01482252367721145, -0.6035770372730629, 1.6116294602103485, 0.6651549231330268, 0.5483374948115611, 0.08099936818397095, -0.06565698651262593, -1.0443410078173883, 0.09683329811512516, -0.47589126569796164, 1.4890870194625914, 0.24058130874091932, 0.281863059760365, -2.015823890084818, -2.019075703173198, 2.4682981850399845, 0.5383749375019986, -0.28341786210057146, 0.3008137551173893, -0.11005991037950565, -0.29205288503151927, 1.8593325812269772, -1.381316893359802, -1.2928353086594067, -0.23173544602187363, 0.27108529502972284, -0.23172914832429878, 0.7077058956948523, -0.826457032229246, -0.10852287373331655, -0.641308202070225, 0.5993690862612395, -0.3419451110301778, 0.6578815732756145, 0.5453396281022503, 0.16006283470135788, 0.2626468888111379, 1.8147067709002562, -1.8578814466630083, -0.11187833014223748, -1.185192290333742, -0.2743634920107099, 0.4437962878087906, -0.03278999398728394, -0.06225904167854967, -1.013768345180017, -0.039441616833135525, 0.30359479397105116, 0.14291816801836205, -1.113765615562838, -1.2053649707741243, -1.515590572322359, -2.1543250912774288, 1.5344341153891825, 0.42092320557149143, -0.7098917462237448, -0.7422043574304762, 0.2495298012881626, -1.1949210307104428, -0.5885620850397905, -0.5989298788340073, -0.7483311622940687, 0.12688799184367516, 1.8473674158220879, -1.428919043025157 }, { -0.98693649184592, 1.1003034548615616, -1.1702103636784984, -0.09332916238488831, -0.4327088852674899, -0.8848955050642627, -0.8085106573755173, -0.17296732067126483, -0.8268917183652948, 0.7386142678389742, -1.8538064310652083, -1.0410577503631961, -0.6053288537018707, 0.2229771482926343, -0.06888630341919498, -0.5380317769839932, 1.6620227477330687, -0.04412724472229267, 1.1845814087791051, 0.04784414140000045, -1.0804025655384235, -1.5372604756739112, 0.05741866092190154, -0.006013033307559362, 0.7168817949552, 0.6073370836202142, 0.8433044627908811, 2.2075250316034145, 0.23870929448409425, -1.37132874892401, 0.403411040634529, 1.1637281269434583, 1.0384034097008856, -0.1462295418252087, -0.5404949868741813, -0.27873958784203245, 0.6950225656309289, -1.4855341278836849, 0.5317384899403423, -0.29982850274870737, 2.172846382580873, 0.875038612129393, -1.3065713537127475, -0.07337230638204141, 0.7793998929193858, 0.775518108146664, 0.35158713011723, -1.002795413717236, -0.23755863410129502, 0.468080482045854, -0.8319544631442446, 1.293040641999056, -0.7200858118733392, 1.0530973862870714, -0.22855063781202187, 1.604014579779061, -0.49383150358316646, 0.6411046102964769, -0.5222774234733065, 0.3581090782395454, 1.1128608077165325, 0.1180355948128962, -0.14839250798561443, 0.9628377175453581, -1.936582378510229, -0.37381493078931, 0.2347198683128469, -0.9379584582125078, -0.5268295742785101, 0.3098235604676291, -0.47489279354122943, 1.010753980239362, 1.2924065116425525, 1.1221168744374106, 0.1963576101831779, -0.2701499141139821, 0.9085718028399721, -2.0699749284335627, 0.056921583162931666, 1.6139408469755823, -1.1226569203109782, 1.1662269797226006, 0.7039453318310216, -2.229181403925957, -0.984523695246308, 0.17699105749581198, -0.9775679223971109, 0.42003723122545095, -0.9500833592351923, -0.14481447294149044, -0.21092004212678328, -0.7689112141414661, -0.07775010549382703, -0.6650468386804915, -0.7551090598342964, 1.2868921231735904, -1.0142904478330204, 0.6223662660462851, 0.031412046120930855, 0.27579511020102754 }, { 0.3702505410944805, 0.8284306774946497, -0.7766226862528746, 0.018151702277787538, -0.4887139804461066, -0.02161186873248639, -1.4679775399754245, -0.019969718017409446, -0.5856664633791127, 1.415826651466769, -1.2559929026152352, -1.884962214862873, -1.0570561784216586, -1.5061240538049725, 1.2874790332135608, 0.3771608488736561, -1.0536020030619555, -0.284100964087227, -0.13467637081776826, 1.02893532998294, 0.6086504974223589, -0.8402524742208763, -0.3528617268558269, 0.446028413125773, -1.536223089028803, -1.6612078224582647, 0.3477541399516683, 1.628264261413477, 1.3931857058623973, 1.3480824840915737, -0.6052009622934934, 0.08570712738299263, -0.25032349075250115, -0.12267980326169775, 1.0982385393875604, 0.8210286795976579, 0.007771030678422243, 0.04226679226339141, 0.5468133807409573, -0.8113114929484562, 0.3169373951906087, -1.5091117715254316, 0.9373557961016804, -0.240480574134581, -0.1010347815266436, 0.2643051836514046, 0.5645175812515462, -0.4387717531266958, -0.3722112838821014, -1.243055569323862, 1.6462950695982654, 0.6727585000325176, -0.8554896321102844, -0.06654742384153825, 0.4639886251121335, -0.23418486604729027, 2.065748166099198, 0.7973982150530132, -0.45863519482192705, -0.3945045848199923, 0.4484288720907343, 0.46011648323764814, 1.3746619171298042, 0.6273308951547046, -1.4287278193736928, -1.2247394017941498, 0.23404976813667597, -1.3440866313071487, 1.0436860697750232, 2.3022450833553143, -0.14091881054853841, -0.08183390691709466, -1.471812859964554, 0.7175849056881419, 1.37737474910241, -1.679035048595325, -0.26042933316533984, -0.7431906710757226, -0.06579358741649732, -0.27903651915184974, -0.8089640402909711, 0.2808431222187296, -0.3505989675637277, 1.2240525548745516, -1.3757220143162818, 0.5196951166511814, 0.5276741702653153, -0.06249100293784565, 1.4816692574490422, -0.5993467148821967, -0.15447503141553207, 1.1722408198776013, 0.37425889007856306, -0.8058223346425675, 0.6412274839095561, 0.6756921094910426, -0.31090732217909384, 0.7048162016458319, 0.1072471480067689, 0.2914599787532277 }, { -0.7003888431996858, 0.41154256025074676, 1.292806296401084, -0.06897205508934094, -2.438942842105244, -1.338934373537281, 1.041680296683158, 1.4066849877239231, -0.46005270140230853, 1.0010497509429792, 0.1729158484675054, 0.5702647301423693, 0.32929720451875094, 1.5777751298372342, 0.467576573356032, 0.34571977434413254, -0.6944486745763742, 2.2514328539341477, 1.232642318716628, -0.1900524982249717, 0.9785176702819524, -0.2547404573190124, 0.6420079704392442, -0.36287829273424, -0.5732216531739246, 1.3337029962034943, -0.5467998705122511, 0.7072826641973712, 0.6527370944831964, -0.23032682292384687, -0.23349838759969752, 1.1112415055613214, -1.1826365498055673, 2.3074156972803395, 0.362413215391425, -0.301964905175538, 1.0880139036771574, -0.2478227826958914, -0.1844230552021386, 0.45627423822052166, -0.14399442942957605, 1.3414511849993838, -1.4125988336873063, -0.0018412074432535483, -0.30649817800407114, -0.23134578117427373, -1.1866440794884126, -0.706455687311838, -1.1015903774870965, 0.4869308550273929, 0.3817556877687567, -1.21470602981773, -0.5030956287896002, -0.9342209856694352, 0.79043958423003, 0.09030320002135481, -0.44062064013479463, -0.07312170333010978, -1.0843286092220217, -1.7176271786517316, 0.14365438821595217, -0.9083607705227542, -0.780322217641987, -0.2814533772357238, -0.5413620905808516, -0.2748118109825542, -0.693259230937527, 0.4918269285611587, -0.2462596944321865, -1.084092229830414, 0.38379407650614444, 0.3717675364945683, 0.3443629130462136, -0.5475571881418724, 1.3910096987610754, -0.20160496711019635, 1.012459294901585, 1.080623042884234, 1.9986629554933093, 0.6070234375683149, 1.555930500665415, 0.8587170453753297, -0.18655344814390212, -2.354729159903822, -1.5283542457206636, -0.22392109773828028, -1.2367654583942513, 0.0198982877035271, 0.24893891668322016, 0.4496539436281081, 1.077269028243528, 0.4625724782839708, 0.7536968207857005, 1.3147927533758246, -1.1810958710711217, 0.6102179879494551, -0.9396837384214894, 0.16070401298639178, 0.46327685669667895, 0.6031722649955746 }, { -0.22139927546056845, 0.5714031173356633, 0.8098614124809865, 2.256301961917925, -0.34690225598408053, 0.22337686130942347, 0.9331206522194625, 1.0030898368093824, 0.07483272624587753, 0.20676485648979964, 0.4244216296897666, -0.5868924185098222, -1.297697292347013, 2.0005634158251278, -1.333840395361331, -0.5163351094919342, -0.41885388843977606, 0.7998668645053387, 1.585198395540513, -0.22669998237752373, 1.8022711700445704, -0.7947862956379745, 0.9286288474355266, -0.178583552499455, 1.2429680253652773, -0.7935692200609352, 0.03700967271260039, 1.314975027072653, -0.9060366090180468, 0.3563278278222486, 1.0618944886445998, 0.143358938571268, -0.6099629717677647, 0.3216958098364426, -0.7002458734742882, 0.8823043501688784, 0.6029813607804352, -1.243729422437221, -0.055320887608967605, -1.3877156966038404, 0.6023246725425109, -0.17430263471919263, -0.7965098955709412, -0.21660713583930927, 2.6152071321860784, -1.3487263600079173, 0.36318992485991275, 2.127673799808464, 0.1985462708850758, -0.3460572317198982, 0.5581078376681246, -0.4581223359819836, -0.30143322806125683, 0.4545300115356162, -1.9434117250125704, 1.0975860143533673, 0.11137693573281555, -0.5920478573914889, 0.010947310759300928, 2.409401915195078, 1.8572197458356485, -1.7958764158325908, 0.2789066415323579, -1.2392647157785315, -0.9563994386659851, 0.5037286297402777, -1.0626182628021874, -1.238541107329956, -1.581106270264064, 1.067056707232822, 1.0119750839303052, -0.033750772701053755, -0.5409768010241458, 0.8283810689813178, 0.3239184350541288, -0.36325385521399955, -0.5006099795560649, 0.6000748129552127, -0.32608844708492196, -2.048750454750933, -1.2648140223508368, -0.634012152196603, 0.669181718206968, -0.7517513885245742, 0.7455031279957828, 0.8310474339221648, 0.7224735636943518, -1.2092784736776658, -1.349655055048815, 0.9875512232075188, 0.30886860783430703, -1.213680197561748, -1.3500488793778287, -0.7396618129117561, 1.0909958241864044, 1.2611300207605518, -0.485774874778836, 0.596694470525451, 0.6119926412996275, 0.8042428405680427 }, { -0.13632378284024155, 1.2152534863759479, -1.3678678373930075, -0.5165280232435927, 0.6824509412133823, -0.6262774957928293, -0.6671762124490688, -2.0208413142130066, -0.0833564841835222, 0.2085294044685653, 0.043039454111794315, -1.3355162633489484, 0.8258891895515599, -1.5415663037413365, -0.26281382485368454, 0.43456978077114833, -0.9258643993117348, 0.2703862035654465, -0.7632560164916736, 1.3533874966348145, 0.31827228005184777, 0.7594534226489745, 0.22570696108522578, -0.5523743553524609, -0.12364945820272977, 0.30977341110103634, 0.31185635282854945, 1.9017120015609177, 0.5420178181726996, 0.8786800358284746, -0.3038045105991931, -1.7169514524442147, -2.1646328178267606, 0.5399893174478579, 1.09454184485926, -0.38534153757147543, 1.2113993167941488, 0.8838432767071851, -1.1962672429648122, -1.0302439223724664, -1.1253508314660343, 1.2352498037600959, -0.6051143990859468, 0.9599054213537032, 0.13259031012630484, 0.30980123930228526, 1.3548961455618693, 0.08251202973687757, -0.5438838097882499, 0.13348986436681037, -1.5102900997114403, -1.0204007954297452, 0.022246247525958072, 1.6587816500355252, -0.18394767683074523, -0.3897701663525113, -0.5794853106563015, 0.5981065630889727, 0.010009493974437787, -0.6525392818281912, 0.3654265937549856, -0.47233140466099655, -0.2096841938104726, 0.30759767813903804, -1.050112885914809, -0.7228195792190966, 0.8361209290020025, -0.4568327626044805, 1.170281885547052, -1.0274106352840298, 1.2328897955995988, -0.7398335065411328, 1.0554419537631132, -0.5888832940269327, 1.9700469007520691, -1.653072346911288, 0.1659731586695937, 0.2383235902087662, 0.6116067322591254, -1.6481374784001142, -0.16465221732652252, -1.1168005867174555, 0.6937742387233252, 2.0212171683404834, -1.7314477363071765, 1.1823297408569777, -1.9106028686223662, -0.9857556862820056, 0.18888607092982104, -0.13474372848774657, -0.4687689777396894, 1.0059133300360188, -2.917889466719743, -0.14548873032072998, -0.6889555303444136, -0.2881357574032014, -0.21354307472765038, 0.3179899949066597, 0.7416053168114382, -0.2151273470998047 }, { 0.383662752303337, 0.599492751241967, -0.2667727107444298, 0.8340682965604244, 0.7798169085755695, 0.850394559638177, -0.29585223044981024, 1.7512113579510886, 0.007349393660930282, -0.9283253948662588, -0.38516847286988404, -0.6997148226859411, -0.7241244948431479, 0.6060583742954327, -0.6508549765517309, -0.6268825692007995, 2.3734267245137084, 0.1732428201342394, 0.07502210901775273, 1.9587029179784332, 0.23108483050541428, 0.1464604989028643, 0.7376923024994149, -0.18606366292464604, -1.7435560670257144, -2.0070481329634533, 0.9729250524967098, -1.7486835408055794, -0.8043445375618473, 0.15751619745294035, 2.1161694988350668, -0.997137790295992, -0.21090862254606219, -0.23354556732561846, 0.045573794790903684, 0.3033550271058119, -2.0519181548453753, -1.2006064797470026, -0.033824134879483124, -0.6984918032373812, -1.6606420368945007, 1.2141181587900938, -1.1248871808400778, 2.4183512535355756, 0.6843801868028495, 0.48103333094708, -0.022558049086434794, 0.6038638960214402, 0.8714283022897665, 0.27459308955114464, -0.11940692383472072, 1.7124188383295873, -1.568500778139071, 0.21729932386181927, -1.2428662773075683, -0.6223547043720487, 0.27230373013148873, -0.2970905311300741, -0.012434628103643933, 1.5439710354202336, 0.477291583877924, -2.6930339350438466, 1.2034175292158387, 0.19788961253904996, -1.696574586755614, 0.4465216676401544, -1.3024424385253213, 0.2238444117064559, 1.089555886010767, -0.6281538376577588, -0.23698151932808167, -0.506304059594967, 0.8694875937951905, -1.5192849610345298, 0.5998868552035189, -0.19092608029074828, 0.7010422222955548, 0.6437211442529228, -0.008088963133553116, -0.47977071084619655, -0.7662113851944702, -0.3145847231819713, -0.4356622320281033, 0.6968516233810611, -1.290944794081264, 1.4857621450120069, -0.595924073326016, -0.48528822059062976, 0.5636302652808222, -1.0287960957987252, 0.5361873524369329, -0.5778503738818427, -0.28113923590740003, 1.3268747767106244, -1.5875502203835912, -1.4334268297626658, 0.42167544965698733, 0.801154158847177, 1.2638491512254972, 1.205407035785646 }, { 1.044124827481621, 0.6516009895591945, -0.2969257530794755, 0.37163330448457177, 0.30452650765436773, 0.6251179641981, 0.10035223944693157, -1.3346276081429205, -0.7939063383019999, -0.005248968293008887, 2.2465711006015354, -1.2279828931925818, 1.6601630697742045, -1.3972734285509325, 1.479402245700579, 1.1900124659524722, 1.0724260851900882, 0.9811437306800027, -0.29331220799138447, 0.6969214733920075, 0.20568740431107632, 0.7811461883515146, 0.00034197782094747383, 0.1764714829113371, -0.09210676238916095, -1.2860347170971833, -0.2989395826176677, 1.0167299204515756, -0.9994107402479164, -1.5881839845391224, 0.00805398983168259, 1.7221242086291038, 0.25587200002127997, -0.21853076873831948, -1.2772491291084875, -0.20619632131507679, 0.04628000805258999, -2.77137309104911, 0.042222888827086684, 0.5501272299359659, -1.351880036849211, 0.07363937379028708, 0.5861286152087923, 0.32860849837932377, 0.6492306648300178, -0.6286313717426678, -0.18141314870979064, -1.0855971885593652, 0.2847085474047056, 1.1158359022639828, 0.8229768459341839, -1.2179864376020313, 1.0471535662667568, -1.0726309645127379, 1.2092735460138309, 1.7188066059335225, 0.11548094593330971, -0.41077149271089275, -0.031768835200006396, -0.27215209932830153, -0.6811313810878464, -0.3281690127521437, 0.5434708923738543, 1.0728684732622407, -0.6239553939583973, 0.16510300088075855, -3.3216235420990627, -0.10448724127868438, 0.07890613191008501, 1.228016194347917, -0.6603154189610244, -0.713030187393645, -0.08184854574726218, -0.8694104918010929, -0.05429368365235902, 0.4134645030890917, -0.1366277705154083, -0.8146704937706711, 0.2214504167314693, 1.277183442589581, -1.2434943326403465, 0.19530285360626876, 0.369610067513583, -0.2556088157688678, -0.8699788550148038, 0.05440543779612954, -0.7820254828749014, -1.2477495833125631, 0.6068914795696249, 0.2743032539854942, -1.016583678473653, 1.1654255167555958, 1.2737291846238634, -0.49340815450390335, 0.9305723115073938, -0.1597204022834737, 0.7440038531678899, 0.1871414304689708, 0.6764071341887264, -0.9117532912607734 }, { -1.3761365133573247, 0.10161769716667013, 0.4819016982479505, 1.8636761750259285, 0.002998848059648558, 2.0149809079688232, -0.17251606597801197, -0.23111004883362812, 1.2358618100348313, 1.1134216045715493, -0.26449594518306935, -0.3682608515712467, -1.1231996307354715, 0.17795449907024966, -0.018332062237922126, 0.6503160285234533, 0.6148192031386226, -0.04091713642687653, -0.6739510116255246, 0.3995718640784574, -0.39551448819000345, 0.19473779715512832, 0.5209113098846627, 2.417054861808752, -0.36463056234762287, -0.23629810031052442, 0.8714357904821504, -0.28362982470682985, -0.004574209946186514, 0.9000332733498076, -0.429705348594708, -0.02809822172998146, -0.017392128360770965, 0.09371217429928591, -0.3852812419254049, -0.6701611709337768, -0.009201751383153824, -0.11574641412942402, 0.5065073523177843, 0.7547880546950534, -0.3664167099339168, 0.5739897858919526, 0.2438331868187321, 0.16646354334782837, -0.11383599465882831, -1.6956197084274678, -1.895440193129297, -0.7620964488052713, -0.31659588254769644, 1.732838127345506, -0.22197356540081373, -0.21565482732191849, 0.8123156159768736, -0.37136311510859676, -0.36631781914596634, -1.1777280662354839, -0.21028200180043236, 0.5812720165196269, -1.5566541812469044, -0.657315453188274, -1.8209711468470275, -0.6704873462630017, -0.11328201176834943, -0.724220376948176, 0.020207113434797724, -1.571167140442656, 0.0988498877234608, -1.4163631793609812, 1.5789574325673585, -0.8708483805553044, 0.6240984778240488, -0.5727268155861474, -0.2565277840476353, 0.287314374793906, 0.18317718789237777, 0.25165619136885564, -0.9060379148082284, -1.0175895230213272, 0.06320334160197565, 1.226313996907214, -0.059931208934743956, 0.9024076103802063, -0.13472360225882665, 0.0026139794026256145, 0.0664204557189136, -0.22308608836814553, 0.2273672950511646, 0.9402461539176794, -1.073399946885656, 1.7657847651197505, -1.4985955480241298, 0.2881150726401531, 1.6337401595876992, -0.6315191858450451, 0.028771370562105436, 1.217788569833026, -2.019586382061707, 0.6592941348515517, 0.52620404482088, 0.29370702742225135 }, { -2.6504348078772666, -0.28334391607449494, 0.2969946498558182, 0.07617336099517048, 0.8418759587614627, -0.4810506318721992, -0.4251497690198057, -0.3730218255300593, -0.07158079137427009, 0.6777703512300358, 0.559883772656571, 1.6174725068918034, -0.8122104669373016, 0.18376726928792192, -0.20264782944002338, 0.6578905110082953, 1.9048968112034605, 1.2093596431060374, 1.3394541901201602, 0.7931110068515232, 0.8048065913470068, 0.32481966689754466, 0.7492941650005034, -0.6219775856788415, 0.1798401571198408, -0.011096455452549066, -0.27710610995910573, 1.8922719905980423, -0.1648432505778448, 0.1285486444381695, -0.4039889236312651, 0.44060160930812425, 1.5448738735848198, 0.10477567546151301, 0.8155312969289258, 0.07634987343553191, -1.412843646332525, 0.05934698255193573, -1.4027543137746823, -1.3143870737800836, -1.1050845959954028, 0.025123124359675737, -0.8003637530947717, 1.4909194437183195, 0.7939394135047745, 0.32231600917934444, -0.13913358041066382, -0.5575756217344349, -0.33685715596600385, 1.0402493250202867, 1.0254270919757824, -0.14731619631935533, 0.8642991859054625, -1.3342320628586, 0.8694658553563811, 1.3836821873064789, -0.437992766776364, 0.7569329319183769, -0.5101817887266062, 1.3718580990261264, -2.066940958729536, 0.19732089993804675, 0.3315447565439609, 1.4956347318288359, -0.24880730730543055, -0.36428592099963547, 0.8243327192443618, -0.8323998527814014, 0.40120861131295915, -0.031156963502157804, 1.9361974989562825, -0.5696318782570726, -0.8471113585352369, -0.9525626479423205, -0.01281511578613812, -1.429673956113182, 1.7606775540319757, -1.3037213791976396, 0.7970231121864289, -0.9508264565581138, 1.3984516222766565, -0.13443087191076483, 0.3804535114147103, 0.01757527731681911, 1.3154285230387475, -0.8960524512724193, -1.2782061542607623, -0.0060346296139561755, 0.8165643472198515, -0.3515519888636757, 1.036835286330158, -0.7906605853093821, -0.22984797680336783, -0.09948630772462574, -1.3323675799679833, -0.3679721028796168, -0.7253957871116793, -1.3842675161773497, -1.079364555162556, 1.864733751994399 }, { 1.9974957854682451, 0.6154709257625192, 0.9565457228126262, -0.09531830540803374, -0.607236430967155, -1.207876717090178, -0.22992594864367555, 0.5837024639062935, -1.1127408964568832, 0.32259823752531014, 2.1075370996268363, -0.4538183654192955, -0.28327577511605856, 0.9267379217412168, -1.125198474372646, 0.32122322166620293, -0.8804236166679313, -1.0163753635909154, 0.6057647425591918, -0.19108456381327035, 1.7756344194673364, 0.5643440883394347, 1.6116528168867261, -1.5566066631314366, 1.339574267563195, 1.0447328815741237, 0.6236129415493975, -0.6989840587032564, -0.24328515332388947, -1.0104561157240683, -1.4777684658023829, -1.140939118205586, 0.6189991470373059, -0.015856987341836423, -1.3178727445021077, 1.4669383699558076, -0.4160456157639572, -0.5301828290426382, 1.1874660409064541, -0.7687280919651254, -1.0609620708434353, 0.07907349012617786, 0.9223860370754371, 0.7896125491009928, 1.102172156944756, 0.5740128352018578, -0.4009682624561043, -0.3052453423654851, -1.7256498764497343, -1.6640231228467963, 0.5346163306733653, -1.3774339694935103, -0.32668807945158196, 0.09837247417661953, -0.08816994434880157, 0.1490116254763958, -2.468230739698945, 1.7450191779914188, -0.6242932046264565, 0.5971798518771105, 2.9668799962078927, 0.7547977200245436, 0.19722743259903036, 0.41366164916259185, -0.5067958125610813, 0.24155844393607054, -0.06359239438385034, 0.39538952175711417, -0.47981395808460175, 1.6889503579844596, 0.7198136600784613, 0.7414040660902838, 0.8556012542864424, 0.8581429348826691, 0.255580372030913, -0.20970858516978674, 0.4379207507742336, -1.6253589385246885, -1.0758969085344567, -0.06872427636562302, 0.8457806756901033, -1.3590634940804462, 0.6010199230496943, -1.5033574796759017, -0.9232834176468133, -1.4363995528267068, 1.041871701767818, -0.38010645623319833, -0.1833115810963406, -0.7021358771839084, 0.40649859597526317, 0.7815476827392451, -1.3480938192171945, -0.1327751091181984, 0.15225279537428232, -0.1096574934875198, 0.9337826396358704, -0.05101867476097302, 1.3966663898469833, -1.0741142648349236 }, { -0.17855945468397613, -0.6228487254135945, -1.7284425918875408, 0.334853404591496, 0.7187408239867127, 0.9840677678714723, -0.8719066352829101, -0.2854366953492674, 0.7377151451454363, -0.08713190528706027, -0.9319187897273441, -1.1165803813586723, -1.5214674525039726, 0.20513463348321362, 0.20183273537588117, -2.069967083521728, 0.2819002019195001, 0.2359746099106653, 0.027846853346256348, 0.3022306313431248, 0.912910417594001, 0.21462371217773862, -1.0818228016852813, 0.2572826422776033, 0.015680992837290804, 1.1969194747364584, -0.4618281361584025, 0.7065144439417109, 1.6750788402710486, -1.931708541389024, -0.22880286381013604, 1.011869580473402, -0.7470562920281442, -1.0023269623082287, -0.3325256663768716, 1.167296382639764, -0.6023687781309492, 1.1885618209342328, -1.7870937209670765, -1.6925964789619288, 1.4538656752429717, -0.8752991103413905, -0.10901154780063542, -0.5904326222369385, 1.379223123598584, -0.48072505895211093, -1.578252131066906, -0.6787365543409554, 1.785872309017749, 0.2916889651876067, 0.68481480220752, -0.7275645446548676, -0.5154219064660369, 0.3807868644653168, 1.320733659456181, -0.63434258814282, -0.1574070564129218, -1.8269187690221786, -1.4417262205579258, 0.38375880240144716, -1.327973879328081, 0.8884394941391724, 0.6542048082863688, 0.18692444733346839, 1.5068534674159346, 0.9708894648967081, -0.5616810388265795, 1.4953205739570938, 0.32509950330225623, 0.5898218407658757, -1.4564963703936544, -1.4069600131337687, -0.5619212042974564, -1.1515451425398897, 0.3626037665296422, 0.8683217213336255, -0.21403686554326648, 1.4442567348618272, 1.1570255625684165, -0.06593849829195415, -1.6729945576900727, 0.17713361481554643, -1.0069953851419153, -0.6720031757229359, -0.4971336667011418, -1.190812423481692, -0.9388793934705852, 0.9209925611655292, 1.2975881759342094, -0.13904939433053817, 0.6242779270376473, 0.11404902308302416, 1.1348812299632505, 1.6868396198671713, -0.19754265080065375, 0.46674285829502626, -1.3406856057117935, -0.015617466422715272, -0.6411859443893935, -0.0834154217674384 }, { -0.10022086660425418, -0.6722119090328699, -0.7542065734923298, -0.6816462488818024, -0.5526742302079868, 2.09731873838805, 1.1387004191313173, -0.8838245627204, 2.482052217125993, -0.740395240274356, -0.19631023831548394, 1.1998093070069982, -1.1608434158200922, -0.651007441840205, 0.8493454854372654, 1.3928075128174293, -1.0990808638765965, -0.5204003704769516, -0.7666087197869033, 0.6338026305037282, 1.5311983550005106, 1.2627915968336225, 1.006413638482614, 0.32130164584645937, -0.9880232245485409, -0.20956758938746994, -0.2503360739970576, 1.288531808640965, 0.5913960864194006, 0.2641604651550488, 0.14765066509007296, 0.029604428418017262, 0.945210088403176, -0.5235070581898156, 1.0524315374430993, -0.3799803450621543, -2.0530713672306127, 0.49000785249614837, 0.977374483058694, -0.1384674924819679, 0.7263145401240255, 1.0975420757208134, 0.6451729301526186, -0.2457388716838968, 0.0515037282893027, 0.277410646264741, 3.0756833417407328, -0.08474822765109583, 0.8478417156149001, -0.9480785560174604, 0.4411374940247676, -0.9448246018050871, 0.41256248665060424, -0.08492506031743015, -1.5783466395669434, 1.7492354586231653, 0.0009724560965995704, 0.1474380721154339, 0.29193330007125595, 2.0892035868601218, 0.8398096936716949, 0.8595569938843669, -0.7898930825433955, 1.7386182003003554, 2.0207035385665573, -0.704527640023053, -0.6843096743598479, 1.2040513861891045, 0.1395052637770818, 0.6409903937495018, -0.1486665328745829, 0.7500152818611872, -0.6745426151070969, -0.906778536234766, 1.2025363425144684, -0.7866786727104034, 0.34946586628417137, -0.14507548339289142, 0.19059965361591358, -0.8880427866473928, -1.6373264935392542, 0.4187700754381529, 0.6471773427784323, 1.4245455255661097, -0.5266161338573613, 1.7697051109265938, -0.27614006665931984, 0.977362854630293, -0.41621620324636927, -1.0742227965728, 0.7633602793291528, 0.4060414601734859, 0.8620956777894639, 0.11991680006476509, -0.3382437359815563, 0.7877385844744279, 0.4822056509748021, -2.612742376012952, -0.015011728510092989, -0.4040636300879279 }, { 0.06557940837440991, 0.5656448643100187, 0.41708916055265305, -0.9704596596215672, -0.7156873642488237, 0.1072764915148025, 0.021502559178437155, 0.5002900384697986, 0.8436259018525353, -1.3105829077638824, -1.4013119528630187, 0.38686220200632837, 0.4589166829846703, -1.253747339494215, -1.0246224826766965, 0.7951259601154973, -0.45645750382342726, -0.6395529200341387, -1.1862580040448318, 1.206128952446889, 0.09828956746008508, -1.387464254141337, 1.0714766434931284, 0.9288911488134304, -1.2045956146143366, 0.4769353380471021, -0.42845371630479484, -0.8817747008080867, 0.04546251629490132, 1.2284446294269584, 0.15485842145302023, -0.5163806863696991, 0.30293341670872687, 0.05982575530170821, 0.8439436947811081, -1.3709579422304121, -0.5748403034721529, -0.8882464676099763, 1.466355783283758, -0.5291411245147772, 0.9156578951390623, -1.7922334689482633, -0.48223581789974207, -0.03842599576617681, -0.9618891526391441, -1.9992248242524269, 3.1562342467530686, -0.33131192974856033, -1.8807470909342812, 0.8946630669850542, -0.7539384089550744, -0.5316402615625622, 0.939061077688266, 0.2899203297580468, 0.4297766676786277, 0.5710945685674074, -0.5171428667234192, 0.14238892940858705, 0.4126392484183401, 1.8205967400304808, -2.8157836791395248, 0.18850020147452717, 0.4776600277362922, -1.404122741681666, -0.01609820812295413, -1.0137351422013003, 0.0533209657758236, 1.0695732542463599, 0.5813396291628292, 2.2212309941161545, -0.8992866757636583, 0.43322197652138883, -0.2864969545106686, 1.5424596095693293, -1.3580126739622276, -0.13390323710850777, -0.4815249669669482, 0.5149178330633134, -2.766818949148389, 0.7787584268532184, 2.0038886141452537, -0.5598772506979708, -0.4509073121933944, 0.1976998909955636, 0.5412233114438146, -0.19381011678594676, -1.3279785613078376, -1.026458329339968, 0.5446768027957327, 0.3410345452514555, 0.9144042810292695, -1.3598164358951192, 1.894130564007337, -0.01826704439433703, -0.5861139517633616, 0.26819528381253566, 0.7623716932122655, 1.3119481126078678, -0.6877168421441043, -0.12538990885979015 }, { 1.4059022291112546, -1.44609981447776, 1.8707990203444556, -0.6705951851773736, -0.1172047450963123, -0.8882511674743028, 0.22845687816871496, -0.4353497617111027, -0.7084232552991563, 0.08834405076689975, 1.3405786405019882, -1.0563233179555274, 0.1716159495322378, 1.0618957007509529, 1.528500196158185, 0.5655873091251542, 1.0724621994076917, -1.3131888484745238, -1.0753348558648812, -1.0225617182447297, -0.7705689871915238, 1.7256297111193701, -0.41833171940147035, 0.21700707025870167, 1.068473481203861, 1.147435986759093, 0.5658963271312024, 0.5680231796271783, -0.3765228917584655, 1.6133369671078026, -0.6743711508922287, -1.1523519367273491, 0.5993617319259009, 0.5987986492055537, -1.477916120797085, -0.22855648908746537, -1.007244911953894, 1.158889560184995, 0.45152868131554497, -1.2153251480629355, 0.7754332489451086, -1.0645543980910208, 0.6090791416103596, -1.9541774714779745, 1.828073756766709, 0.5799440574963358, -1.0291241911938687, -0.8251520000141187, 0.668831293276836, -0.12591011488052545, -1.0071898282886314, -0.567638225656197, 0.5992305169425107, 2.0328560837963914, -1.1297156380324742, 0.0827827699202437, -1.548175125784293, 1.2321184747709981, -0.6156916654116572, -0.010620158102156003, -1.1065716650874518, -0.6547737013991098, 1.2592322388377213, 0.9182489220689356, -1.1265414423822402, 0.04897210243577909, 1.7853743347332958, -0.43621289772292937, -1.095813791626073, -2.0754115453764594, -0.035907302688261526, 0.017735354487675593, 0.04001553077508151, 1.3113006022211964, 0.5400965272596173, 0.8897644897277356, -0.5170305617560162, 0.21322409963485095, -0.8636095237248967, -0.6933579194040345, -0.9609332409885871, 1.1982092114178884, 1.9331856144753456, 1.6024553652557723, 0.43692144269997113, 0.4737966274159915, -0.058679104463655846, -1.2109418471585336, -0.150996900133143, -0.7624992592799055, -0.054967117595312455, 0.3077383014955197, -0.17980996125412801, -0.43902030328151176, -0.4966174196397363, 0.03726576029547339, -0.43493241834170365, -0.5860874797224124, -0.6982897443885591, 1.0862061614346725 }, { -0.9783101718237738, 0.09200849473625443, -1.1265523427454618, -0.3797056452824107, -0.05792023330592202, 1.4673980262816295, 0.5167888470889453, -1.2993733749986591, -0.15142472907125964, 0.4082268345768936, -0.10423194147023028, -1.2356187320216947, 1.5580757859657746, -0.3522345421411251, -1.5510620760237592, 1.82254427778669, 0.08035903641354274, -0.5480666590678563, -0.28517587983883586, -0.4677728456372002, -0.10445723695006577, 0.5580708792355052, 1.8335016068442187, 0.1810684148312123, -0.790136834127381, 1.5912809043610705, 1.0881079290552305, -0.4436108863646244, -0.30140645838448377, -0.3350001012438779, -0.7040217735018001, -1.6150577047170969, -0.7937393811158475, -0.6332407184217448, 1.9228315260639584, 1.3632172077260685, -0.4851618784702026, 0.8381192177571422, -0.05543379041014717, -1.7380014414805853, -2.1750047903879675, 0.1871136528585137, -0.090846185098471, -1.5484865912506751, -1.2904434116430674, 0.0853052563642307, 0.48800012572297097, -0.5959537402918761, 0.43682078766313637, -0.3215844821768764, 0.7002664936764431, 1.7356100601024593, 0.3980601494042509, -0.6582635215139973, -1.9145674213105675, 0.6746504712602902, -0.45249406010621274, -0.9815658412606427, -0.6867895675553979, 0.9515651566387969, 0.9387868005670988, 2.7733666930033767, 0.9718713810813835, 1.0530619022862004, -0.06500523929324094, -0.1836161565127523, -1.8507550465890894, 0.22568339693863218, -0.8065084544444748, 1.0337269455910414, 1.1084833230717808, 0.11425460286743816, 0.039105160187911624, 0.22997836180248976, -0.2783788646043621, -0.03976059544460938, 2.012472835651435, -0.9768496980142567, -1.0395667034640583, 0.5538458626584544, 0.09279864498427388, 0.1235898342470035, -0.7828235653859934, 0.23331230753416635, 0.601588065471581, -1.1474686183135505, 0.15017779650103733, -0.8001347600857062, 0.5828533578426487, -1.738964048703083, 0.08907661988215022, 0.2946412176778375, -1.1741036306455366, -0.6975023886023849, 0.5453780249776145, -0.8374500151933785, 0.32865603444480046, 0.22624387216255432, -0.006738440530756834, -1.4656398750752206 }, { -1.6029675507078027, -1.2452021755158476, 0.3849118230609253, -2.3193533343491337, -0.2695269233326, -0.808850961070232, -0.43004364732443184, -1.7805361717013237, 0.2279153143318026, 0.38430996300023934, -0.544635753890886, 0.6009894653186875, -0.5053880807341884, 1.1011827454866228, 0.9419087163812009, 0.7247252243296863, -0.3600757521358404, 0.5039544410639959, -2.1134532715534857, -0.953162730606443, -0.8983614540149265, -0.6251220103043027, 0.5530388298155836, 0.7890619342925153, 0.6105549601913836, -1.8627893680098915, 0.9448178618579324, -0.3280007719010029, -0.4520372760617799, -0.2926019245576951, -1.6688008079191368, -0.4080791976448021, 0.1523388543715378, 0.3552781233314094, -0.1831270155013664, 0.6923577494633475, 0.7319629704555579, 1.7818504590089663, 0.36533241692664975, -0.8401682079226183, -2.9964106116136384, -0.9972646762898463, -0.48051060029886783, 0.19383875052706556, -0.275781871480906, -0.9903188367371569, -0.37505049089675097, 0.12695114295215842, 0.6447988761743444, -0.4243435076184424, -0.20641216784712554, 1.134975796350472, -0.36416320897922405, -0.5486843619750286, -2.635395377935171, -0.30788869573807465, -0.15611173117830232, -0.4393264706447139, -0.611516937913227, -1.2035443549825156, -0.27205692144231397, -1.391533911510309, 0.38962231315593315, -0.3527102434153756, 0.001205275020150757, -1.4555165861166115, 0.44163939960439563, 0.3415494708446594, 1.7173692171362192, 0.25346309492480956, 0.17902781741110155, -0.03153911506782015, -2.20563490293138, -0.12456029579893677, 1.097742171557778, -0.9499193379500878, 0.4430939996472298, 1.5901460474018652, -1.0426156417214079, 0.5723912973152899, -0.8568103845058032, 1.692307935862085, -0.9410204988283747, 2.666509199344988, -0.9578777787509632, 0.1989426082009662, 1.5543569165827167, -0.4907338277340231, 0.2938455161624249, 1.018067173765173, 0.47383371924011236, -0.031512375909575716, -0.40415382503937813, -0.7161604343204366, 0.706702749649105, -0.5681753245287866, -0.4163755953987177, 1.355154299601464, 1.0910945270412904, 1.8483138381644135 }, { 0.6255009272216094, 2.1508402265832336, -0.49316128227111905, -1.600234250088839, 1.7167494862446706, 0.4493930913595165, 0.7839731826906043, 0.8765542579301453, 0.44700521075823474, 0.46056816457678257, -1.2137058689659654, -0.4844542407650819, -1.1073259851513775, -0.08729817678991153, -0.5721877444859774, -1.6659804064031547, -0.03899492591155594, 0.7137513410829677, -0.001566164987189828, -1.0807402721286223, -0.11412659533995685, 2.0924383731879224, 1.5324277072365777, -2.887888694551708, -0.2625826878227349, 0.8859026548300941, 0.44598034682280746, -1.0206830240460643, -0.18969641056276565, -0.41444134745666206, 1.8491212777211226, -0.5327090732098937, 0.704356586154322, 0.8957919548980996, 1.5396969412442543, 0.026809646646239395, -0.05286638276222712, -0.9379827751153026, 0.2590478088042501, 0.8608650328028572, 0.7086175713534938, -0.4509281332805825, -1.0204592051581713, 0.9269302891181439, -0.27414710274172566, 0.46637014519519654, -2.037110417361588, 1.133952284760116, 1.3765057027877814, 0.8329539105256729, -1.6235851132742039, -0.5155753238981462, 0.6573244165640606, 0.9013860177576881, 1.4331250119548786, 0.2163423805135389, -0.6154506829724836, -0.34415497699481845, -1.2889882346679884, -1.6498961826676108, -0.32613307833205585, -0.17120407328281476, -0.3549420060787057, 1.988895675849579, 1.2661153439280655, 0.6039785482054233, -0.6859949993338167, -0.353443745822563, -0.5103336822692579, -0.10535180327900172, 1.0691975784096521, -1.4644674305288994, -1.1832550572689857, -1.0340170756673177, -0.7753208860398105, -0.9257799811288497, -0.21356195136018533, -0.043709172898115746, 0.6812681132382418, 0.9521405813957425, -0.627058156441872, -0.9988130364796763, -1.0291105541040937, -1.3901266457526407, -1.567159122863642, 0.07729135474638434, 0.5944760957667391, 0.016361003402824086, -0.49990973818127793, -1.338738421450741, 1.0902251179851108, 0.8406638591300707, 1.1979665198916165, -0.7103958626219633, 1.1656660450286789, -0.1475151646292369, -0.026013783573345425, -1.6280360524861965, 0.6292647629879022, -0.7765558795558188 }, { 0.5810927563761852, 1.6376109899441542, -0.6179514487628903, 0.5544974439798215, 0.6925780067614139, -0.13162096946897037, -1.259087121545147, -0.9252291304902153, -0.7024861230801519, 1.0017888294868609, -0.925873455324248, -0.43566192978975193, 1.3179446897189413, 3.0897194018674305, -0.5582069909239272, -1.0633430267897959, -1.220661222885187, 0.367810189465281, -0.3406953109632349, -1.1034138644440055, 0.339720023915946, 0.01360021911108557, 1.182467724023535, 0.8023417930750578, -0.3555737428098137, 0.25891898294654336, -0.05960195332471677, -0.5038999680059266, 0.033067709707918266, -1.3875425553990854, 1.5009144842528042, -0.6781979843700254, -1.0992610752189118, 0.6452763803961805, -0.4546543364645116, -0.022771156144872285, -0.7918645807851455, -0.2765691393759998, -0.6765568100568714, 0.9910044469048895, -0.37023015207973875, -0.3145794626638006, -1.231189211918245, -0.8946974592343956, 0.16934116394530974, -0.8774321131154464, -0.20351528451266887, -1.0098775189511153, -0.9894557652219436, -2.4453100337136973, 0.1553582961969257, -0.4853201739878981, -0.20253218741305376, -0.3477346455143974, -0.2917007488606336, 0.8555412498080189, 1.0548446019084499, 2.472259135298025, 0.8686780722035481, 1.0458982105943468, -0.791649936484885, 1.8549377384198311, -1.1723759431280754, -0.4117912136199903, 1.4693916019473083, 0.15575177136442153, -0.164853478245716, 0.37003340324014394, -1.3478590700188853, -0.5722727309951104, 0.46746570777587815, 0.2498508111005477, 0.38944489315826936, 0.8852148155488029, 0.825946145711074, -0.37274409292028227, -0.5304086894048464, -0.18505804238751353, 1.8419023352951567, 0.4218220364495436, -0.002916123713120403, -0.31565407510982535, -0.35187243189063955, 0.7041591448877691, -0.6916321479928236, -0.12088942146926639, -0.18394646994468516, 1.8614832394895624, 0.668198213094329, -0.1980050980874572, 0.704741391098966, -0.4097990003968652, 1.4786892224112378, -0.4254040053058919, 0.6152157348408102, 0.4086611914359168, 0.07158837646470421, 1.7179811643268996, 0.8931680600571674, 0.16179152226352178 }, { -1.0907741038606205, -1.542287751357401, -0.1544761418032801, -0.19681480859435635, 0.2538331204331133, -0.283151431068253, -0.8964873360369523, -0.7267050412763977, -0.009614935207818752, -0.5578950073427882, 0.43837338287697236, -0.77870628518035, -0.1328103563668507, -0.4182149420269807, -0.1845449293364036, -0.07276392716817857, 0.4468032545632936, 0.65251310553707, -1.6969766401343638, 0.6931003150397271, -0.229956009622284, 0.4129315993698696, -0.4111272739539324, 0.7237688337413529, 0.3683280917442405, -0.6334256892343394, -1.1249490407859841, -0.9323459538919395, -0.4781579799783016, -0.462487823451104, 0.9733017655314985, -0.6533100692759523, 1.3507177709063487, 1.1374304844189729, -0.15986498416891942, 0.1601264498165174, -1.0700643334407074, 0.7570312621125994, -0.9237497034057537, 0.7367573269321587, -2.347307442706693, 0.008965038511363883, 0.7495225246401558, -1.1087823305662274, 0.597975626722247, -0.9093671070080933, -0.038542623803839174, 0.20477331964533826, 0.7913691603567619, -0.042499579177659015, 2.4078330355338275, 0.13591074937467573, -1.6871084617770258, -0.41310136994862373, 0.4026619594653187, 1.6651090272220965, -0.1602931337185752, -2.02409611418877, -0.788588446871872, -0.5885539124000144, 0.45421467387640974, -0.6520655423597109, 1.3807526667309216, 0.3248488636048916, 1.246190623556535, 0.006136138434022347, 1.5826337082225417, -1.4131223820433771, -0.6452852841971116, -0.439979755927037, 1.1286243137119634, -1.3600227997523813, 0.25184058625686695, 0.12972290556387542, -0.6771070758289621, 0.3119270847821037, -0.25006563701851736, 0.21984235839346433, 0.0749967352171838, 0.942932919469549, 2.41284469805768, -0.7059617546233503, -0.7693624819396376, 0.08678323006270934, -1.1030236195585204, 1.8177245610108121, 0.7386346530591905, 1.9577521816773507, -0.6143802580184726, -0.33860078522687825, 2.5023171996628357, -0.43621200736197113, 1.345261224892582, -0.7859837273599437, 0.7352640845615632, -0.9273485381249156, -0.21882616498906898, 1.4369555857862433, 1.5374394381295717, -0.45634746731932097 }, { -1.3561124154938262, -0.0015789186703085898, 0.49672246159944444, 2.270427589527539, 1.5497488913840711, -0.25504489446066697, 0.02836928754971846, 0.3344069607922437, 0.22854668956124885, 1.3599823140600036, -1.2235574225696195, -0.18827579243127363, -0.8924757097696946, 0.028560815013715185, 0.16230204056825231, 0.19469545490354656, 0.6663440514882734, 0.01455103349718811, -0.13838476439003514, 1.3835807839382153, -1.8594673388511802, -0.6081638955783788, -0.21126014651968075, 0.5195299238396527, 0.12189474284465616, 0.5568016174000188, -0.3677090796427124, 0.8935381309565336, -0.20124030502951126, 0.252706409068763, 1.348723529547942, 0.20980585441660593, -1.374988278232347, 0.1459092217677983, -1.6063012192370645, -2.2031716800800893, 0.4681699098093207, 2.4285605627033737, 0.8079260789700295, 0.4945799105524901, 0.7643309821825955, -1.1784368283418802, -0.9016179737689242, -0.7062483366052165, 0.27170771873580696, 1.5756376365435563, -1.0296866102096485, 0.7897831553079575, -0.7541036657763066, -2.157202940503384, -0.022451191817114923, 0.9490597110684509, -0.46010676538288925, 0.4967026951744504, 0.42491362977770764, -1.184084555050825, 0.11709383771908405, -0.23704455476189762, -0.5620748747661446, 0.6341556261842508, -0.34317194575025256, 1.2708434111089666, 0.5330936866601457, 0.45145957878755527, -1.130477923555915, -0.6448443740977763, -1.7192791710919115, -0.11916666763530592, 1.622220499876002, -2.8084590036745234, 0.3919018819785948, -0.6291554222878477, -0.36774107112573506, -0.23466763827204706, -0.5571753734134236, -0.3714605513493901, 1.796809718272194, -0.2593902881453731, 1.551393520222226, -0.04827146626244696, -1.0551436064707271, -0.18835432146532413, 0.17429962826544634, 0.2817612553117911, -0.2504761692220707, -0.3055057287261066, -1.3544875337303193, -0.9019866681279065, -0.18818482499196837, -0.5919038285892679, 0.9054462438300439, -1.8613585974260207, 1.222342770312901, -1.0788350106156344, 1.685999065093465, -1.244627571674987, 0.08926500806958192, -0.4528922746474418, -0.19307639146194658, -0.17180680841560506 }, { -0.1445599705773918, -1.4936163570457806, 0.5279273719412688, 0.7266853172862444, 0.24512637423515318, -0.3900047575338882, -2.2754880925553764, -0.18025593833449047, 0.2488741978594048, -1.0539617025370573, 0.2725348162818081, -0.13826844028933677, -1.3621667589758781, 1.6884266967312438, 0.2940921394662121, 1.0043174491507734, 0.9886963855751573, 0.1566421908100412, 0.31979396380280967, 0.18349507942942808, 1.1526947392500682, -0.773260467478887, 1.1601278118376455, 1.8497508336118649, 0.7313480017166913, -0.23190900622214275, -0.29802353748373633, 0.458285414222116, 0.7294929865988632, -0.25867635045018705, 0.41027963209089385, 0.12531643825163674, 0.4716651856734489, 0.3248596444666294, 0.03654774911034719, 1.0649035237523727, -0.5253948036977352, 0.9705770353905205, 0.9157628699637899, 0.19152554315852524, 1.4662842464117785, -0.8818202911380859, 1.5659657428490898, 1.4050832385139034, -0.9473523444248783, 0.504102979760375, 0.08458857976585446, -1.254839766122515, -0.09095425967484289, -0.8294983492706064, -1.1407482961684963, 0.1320008761939007, -0.9190500494490377, -1.088928414428482, -0.8773807308896898, -1.5143607191145412, -0.03027528069282466, -0.9809776884103529, -0.16044099178502713, -0.3256559367847493, 0.3009191605564667, 0.39653158664382926, 0.3804308145478951, 1.8739947031647546, 2.7710368955384235, 0.010055206131212406, 0.23663581487037103, 0.648379990643556, 0.169599702037568, -0.06492096976078905, -1.2208941580799626, -0.2438377223319336, 0.02864948894735873, 1.1632577739723082, 0.5997947007943435, 0.4617311954721077, 0.4424603811109182, 2.492716428249163, 0.47985599993034866, 0.9056718797813089, 0.4762230379462544, 1.5924110965545255, -1.808311046758298, 1.3225494132825735, 0.42316647171829197, 2.2009044618507003, 0.6594947311675449, -0.12740483951699785, 0.8886428486778387, 0.540992147873893, -0.17137945651596775, 0.5360997233376372, -1.7756917107822765, -0.41313643494361907, 1.1001286802846104, -0.6793558152425799, 0.4305179467619908, 1.835741482296728, 0.3497953780614013, 0.002094317493645155 }, { -2.0970207924123065, 0.03925985978843474, 0.30698695131991577, -0.5185255388647046, 0.9597344964915981, -1.960037622302445, 1.7482379249314102, 0.45964496739514576, -0.28615768994752194, 1.0758434160925507, 0.7840140428955209, 0.2590083197810578, 2.1593780500686166, 0.4706273324967197, 0.29013680262027125, -1.1704933710220167, 0.16396651162957998, 1.3074562460495363, -0.6500190111170133, -1.4801130716990472, -0.25050082755552167, -0.08780272610885605, 1.009239003503671, 0.39893426286726297, 1.7599572402235426, 1.2197167159635984, 0.98307648811214, 1.267838209524453, -0.6848477663869544, 1.4784372415245663, -1.2890266919941633, -0.700199817061501, 0.5244298379497727, -0.13664482186664384, 1.337191460469648, -0.677865353466164, -2.591919665125854, -0.001458472834529965, 0.6327678342761557, 0.5504227734683368, 0.6506608894940055, 0.10620673432488974, -1.0857247460881567, -0.20176676335730875, 0.05692430828052312, -0.10031939992148166, -0.07438421926042132, 0.620666029843087, -0.929093473715672, 0.45682964801742687, -0.3609474833218181, -1.1283384367002827, -0.9141542818623707, -0.19628087922503357, 0.38518112438533525, 1.2449184247685419, 0.27176212290973917, 0.5128648259710329, 0.46220272417668606, 1.7042002693808167, 1.0944022892971503, 0.6513300678935843, 0.7296049214166109, 0.7126914180806484, 1.4128251920316264, -1.6337847198404774, -0.7717627153791798, 1.0100888191386137, 0.2171672857146571, -1.2375897182915083, -1.1051553434665085, -0.8875531942226557, 0.8907231971804103, -0.5428876459854941, -0.7035891820662726, -0.36335727994247025, 0.40761238202287053, -1.1178149160350748, -1.4675902054458705, -0.75633742046972, -0.5754102935608729, 0.2689579909411566, 1.6130197734323561, -0.1002546636818907, -0.34561412566923905, -0.649386173025745, -0.15520284481165747, -0.12635515685033286, -0.32617355811675836, -1.4464869661642423, -0.4471972312742787, -0.5040891578752278, -0.32272524401673275, -0.8684966216165448, -0.01165879148686541, 0.7111792161203389, -1.3602326079768101, 0.7221611770105988, -0.023084342286595286, -0.9128341181386119 }, { 0.7423710625796153, 0.7123390519552104, -0.19117861881610373, 0.8334354702627103, -1.0891220109533541, -0.40537009963386655, 0.2044656406721552, 0.869910008579568, -1.9251652771316121, -0.558199946725487, -0.3067954095018961, 0.9895116702153739, -0.4295443054846807, -1.0084434437899652, -0.6329654352307923, 1.6683050923755676, -1.1057614779490772, -0.20000064559893602, -0.5596062996179485, 1.2829470873782685, -3.1696142272024894, 0.4102831602109937, -0.47942777427790206, -1.548593957643747, -0.6700068874318357, -0.824685617170717, 1.6786249095489691, -1.579185901584857, -0.4889659804777, -1.545248015116031, 0.6211015783561841, -1.2851984515022954, 0.24574304767985183, 0.09437805347117681, -0.9746547362497546, -1.210948521406792, -1.490689333408942, -1.2428311261926355, -1.6125232364735274, -0.38090561720367905, 1.5749781344216711, -0.7299859279798765, -0.4469213895440181, -1.2898838882090038, 1.2675731281638314, -1.4596507644228884, 0.6329267458318439, 0.4183206787739375, -0.818966975048439, -0.4602899902024293, 2.4567227486800003, -1.3865989824751281, 0.1276272033630895, -1.47182843481266, 0.21875733727384525, 1.0524002726544588, 2.042280816548413, 1.042450211629437, 1.762482437943609, -1.310204929365227, 0.23519185740484655, -0.19659399568986932, -0.3043213444392766, -0.9532260881045761, -1.6576820791622162, -0.28595180897706696, 0.4008023774251802, 0.19332667663206562, -0.6123285600680045, -0.06662683861896368, -0.8378088849059321, 0.9140341759831195, -0.5054454037515027, 0.8605625136537127, -0.15759024368941546, -0.42302679079601635, 1.3602459254310815, 2.4982666098638786, -0.6735496081165018, 0.4127975337815304, -0.5613799834209606, -0.5601317366287375, -0.49325854149053344, -0.49685636517228776, -1.4497250561226767, -0.5266986667737219, 0.8415128986542306, 0.37474517403903845, -0.24175861684352323, 0.4681005747880394, 0.9836098587278835, 0.3306691567189461, -1.052088522725825, -0.14834386068807412, -0.0978957231015179, -1.2213803900564149, -1.414061847407403, 0.24590007051725868, 0.06566438555116566, -0.6128815902420947 }, { -1.4824378705608687, -0.2195981237256954, -1.260388611459921, 0.9244034939055477, -0.13145099662596565, -0.1562161359832897, -0.8530810939552238, -0.6949151177079994, 0.09753998051137429, -1.1906951335949656, 0.45347427331625734, -1.0618002530947594, 0.14983273328641608, 0.04955709631823871, 1.0861096278675435, 2.0316414452525615, -1.5196677338284785, -0.029689751794591553, 0.557149650126264, 0.46832184004636934, 0.5488334956093064, -0.1659073373372995, 0.5614915351810286, 0.3970344108034619, 0.27847492582080813, 1.4858350395201183, -0.3873858342275803, 0.45433636269494804, -1.146279264023587, 0.7379574685217809, -0.5337415633591912, 1.0828127473030345, 1.742034545164525, 0.4157371021282, -1.4591869099753134, 0.5487605827582843, 1.3659435164010456, 0.41691903187539114, 0.17816366835852765, 0.4601352136609123, -1.6696344123144053, 1.1093497635189957, 1.0318279134934734, 0.4133720598558558, -3.287109005831095, 2.414511176129195, -0.1413375806208861, 0.13206251383375076, -0.4687900182852733, -0.8119686575998775, -2.163997885828794, 1.016027913617149, -0.8976471886714045, -0.45386990335101396, 0.9754796397961486, 2.1075190846693124, 0.5301238478975979, 0.13425403890911422, -0.5499418652410724, 0.30532612573837503, -0.35802900775472857, -1.536200395977166, -1.685794061025429, -1.352785412069021, -1.7469812916372771, 0.41305238028373564, -1.4984048487464958, -0.8856909043080359, 1.069832332259602, 0.8587447085568625, -0.4339835563273529, -0.1655587948971325, 0.4446478556954591, 0.2623696737897327, -0.6271390867243407, 1.788645603118602, -0.4988159047857718, -0.4722553894300078, 1.3026835304390707, 0.36195605585727303, 0.1925901614886144, 1.0568301592593368, -0.8233208696770469, 0.25960623126768057, -0.9878650730199997, 0.00915853786332437, 1.8876654880023864, -0.452716726237623, 0.48657188663481926, 0.04484825838387398, 0.7855618886009731, 0.4911292227172369, -0.10864420314523378, -1.3644038996542505, -1.3181679475993184, 2.193461844126569, -1.1325188957087162, -0.19655748187273353, 0.9341023052872538, 0.9162911002751908 }, { -0.6691884578144682, -0.12957865983420624, -0.912642489395746, 0.7897930490912431, 0.431658855449415, 0.1881494340868233, -0.12430744868551509, 2.5225605605531323, -1.5166041053190509, -0.45113757666335036, 1.7948364560286947, 0.41872886839291534, 1.1880366484491138, 0.5228889293837047, -0.22556063949551705, -1.8503890172435273, -0.15666655038892777, 0.4656874164763012, -0.4812586524558606, 0.36218565691105825, -0.8090741117828932, 0.801070432083699, -0.6980433904329304, 0.8098489495869586, 1.6795757626060934, 0.4065855383139613, -0.9766664042500565, 0.7314611671545065, -0.1763874979678821, 0.06448156856785105, -0.26840530910019694, 1.1272271277867774, 0.8116967504480518, 0.6116070963608933, 0.6991368404409637, 1.0928723053759317, 0.7644700754117622, 1.0410910526650485, 0.5034959900304022, -0.10193328733917946, -1.1897217017578599, 1.0307043418176058, -0.08045077728386318, -0.25119217645923403, -1.726528444453791, -0.42883478716366624, 0.7529107145955704, 0.32190414193490563, -0.016825042981646547, -0.7174287709504331, 0.07181355327899108, 0.7287620812421035, 0.6981154419874249, -0.85019542027068, 0.774293140763859, 0.4646297704345669, -0.6218397212663667, -0.47995924747908775, 2.125129979639995, 0.7886801292016953, -0.25037375871039397, -2.015689688396726, -1.0503679648380937, 1.9227765350345105, -0.30980342743702627, 0.7377606701157123, -0.8605453796991411, 1.2998574395588953, 0.805704526160043, -0.8286777773856103, 1.2023385506539528, -0.029918753730135576, 0.2255077068168869, -1.6795682826030272, -0.17863692225361183, 0.5433983708092225, -0.9228451965155212, 0.5904086196517729, -0.7948424945794131, -1.6925972068951673, -0.1014809494727687, -0.7098148964421276, -1.0410012791193115, -0.7817480765090087, 0.5591113740195014, 0.16898762416711743, -1.9233572293375274, -1.0059862981414454, -0.240954655410966, 0.8817074047368034, 0.35541723146710735, 1.0359059621070514, 0.5158019720743743, -0.9775502716104231, -1.7458224701678409, -1.6005741758222447, 1.4618429615435986, -0.6656176617030676, 1.2540931354288336, 1.6517368231263982 }, { 0.9077773202976954, 1.3091959748264632, -0.6531046322712478, 0.0700895190505033, 1.3578631593599308, -0.6063081759100694, 1.1763201408541397, 0.6390090971221555, -1.5528492186315366, 0.39673036742647777, 0.07289826782959258, 0.4429451254248995, 0.9163159312908554, -0.10935148458695346, 0.7660618705588176, -1.350263826412948, 0.5118666259247007, -0.30184596578734263, -0.8427312261944231, 1.2017639348686213, -0.7410559999483923, 0.7242357615152795, -0.8018690535540091, -1.1433648800585257, -0.31990173419339757, 0.2222490173513799, -0.934171585903133, 0.5690268024300056, 0.4462069130548913, -0.24994041358415106, -0.3849610308601142, 0.28061572994824374, 0.0795238106571166, 1.2659608206770592, -0.641323443313481, 0.8008060005543081, 1.0875786172713011, 0.10194313155859999, -0.26795646299429854, 0.15814989877011007, -1.0519171808669634, -0.1345688181450329, 1.48326309157716, -1.304894971328293, -0.3713516139277758, 0.3625078128434109, -1.2040694754459622, -0.4683064577666047, -0.2708658142159807, -2.107785444028803, -0.15589823390619165, -0.7607079380925357, 1.9112056746961639, 1.6107909787320578, 1.0793275485521696, 0.8983678156957325, -0.8979343773228285, -0.3516871610468938, 0.09277943720376404, -0.9627763613520943, -0.967362439503107, 0.26935926460800974, 0.6369201176068588, -1.2057970118953532, -0.9126487569299693, -0.39850545106012664, -0.27744935154570594, 1.6803263848778627, -1.3950092299003622, -0.9162844120369635, 0.06092410825175316, 1.5508739149605042, 0.4293478445932007, 2.2715361251416417, 0.720828443413314, -1.2380684835915359, 1.6754068543201028, 1.2932942727563472, 0.2167898044684144, 0.6341942808613908, -0.9429407718786104, 1.0251032482292912, -0.1127831462618303, -1.2989360745432708, 0.6308784508740043, -0.013612855422774678, 1.7092283052598438, 0.816662288212276, 1.0175757139937605, -1.4962534246585684, -1.099456569975433, 0.9820633652723506, -0.5489867873255534, -1.1270577801687418, 0.2393235320553732, 1.8431275397765952, -0.8931628521412164, -1.343403612028842, -0.3106436618983198, -0.19025323694621463 }, { -0.9571061103786428, 0.36551627628353806, -0.11277253037360371, 1.125614314655949, -0.2677102081670475, 1.5432954456675945, 0.11742619830434155, -0.565584890561844, 0.7953693797969654, -0.0383647508779886, -0.044719761747669, 0.3107075164132313, 1.1858967430109484, 0.6823726774989353, 0.8144639415505126, -1.2239106605909769, -0.9581224468329635, -0.6090212453969837, -0.38466214876440546, -0.7396814840086928, 0.06182859825640229, 0.7364756996799262, 1.4144930329833942, -0.7688191967955612, 0.9576955706910079, 1.2822472748879843, 1.2838741042696213, 0.4957713804763092, 1.25174602390459, -0.6476188611581833, 0.7144708667963553, -1.544442249968037, -1.122955461252027, -0.30017469709221256, -1.2712748588388945, -0.925128802552641, 1.764551457693241, 0.29817420894461794, -0.9835488728527352, -1.1961844973510685, 0.45265829126257445, -0.7699712907880301, 0.39714075238696783, -0.10618167801335134, 0.06421942131397819, 0.9268945895198647, -0.7952865619099267, -1.819411001155519, 0.3797349664557138, 0.7367428462013813, -1.2139218197965687, 0.38851852125286146, -0.8790684554983479, 0.8893051547735248, 0.43833201435347685, 0.027279407182167523, 0.8165147570652562, 0.40880721407731774, -0.6881779145074398, 1.6750705474993672, 1.388220860533827, -1.5460887026123749, -0.9075733260280786, -1.0611964010334098, 0.702078894942259, -0.9199174743502724, 0.7522264380592368, 0.044831926148258594, -0.4570691076563303, 0.2207471211918942, 0.5343921487399698, 0.5544034932782911, 0.7468955436759172, 0.8115826075937111, 1.0978095379452595, -0.5183577061940321, -0.23611659157001066, -0.36049611511864166, -0.4850030506659452, -2.1255587767153816, -1.1548788353141275, -1.9007258316613689, 1.9481632861059295, 0.5797805023970461, 0.34008074084164636, -0.9548087971813503, 0.3294187479755894, -0.3918641857026478, 0.4556925522348462, 0.003336713574020795, -0.3590243715231741, 0.832624409864077, -0.2916636126147598, 1.7085435542323963, -0.23368691587344095, 1.4172962714373025, -0.4567059824023781, -0.8320005540481972, 0.8802212853077537, 0.8341101949096081 }, { 0.5525454265339375, 0.5956588925200148, -0.5436415665651615, 1.450558714816838, -0.44446770535641705, -0.9020446137291568, 0.8054358030541144, -0.4484521271758498, 0.7691640303743639, -0.5003960755132368, -0.1320089532154323, -1.0842236436237935, 0.32102928859993557, -1.0581224269761023, 0.8118518637007615, 1.2508692085312674, -0.7089451764781542, 0.5478300170328623, -1.5862844084168233, 0.06423565242119421, 0.8984343624405936, 0.2981861383751191, 0.8028101463468529, -0.3099657973438254, -1.8810003568718077, -0.1628127792616174, -0.5418712928351967, -0.9890230917429439, -0.7969497883839457, -2.5073793979302, -0.32242507729262027, -0.9096883312261039, -2.7650440841954635, -0.2921497061866458, 0.26046687768611276, -0.49977772543310606, -3.089610835938123, 0.9696279419342645, -1.1541976005177779, -1.5427436360361764, -0.06332551024019477, -0.6982943940335923, -1.1387987815727247, -1.5144525906895077, -0.44054572552424115, -0.8245169169806522, 0.22538752706183512, 0.1561740365755788, 0.5247046690282647, 0.1429049431817078, 0.13245383874304076, -0.9753506006576156, -0.4173800329961826, 0.19795601540774754, -0.6414576262086366, -1.1340032769813841, -2.3734708553288963, -1.2312362418431317, -0.5544101687564588, 0.12537772361801008, -1.5836590937967203, 0.6221282649958255, -0.37966008671382007, -0.09485030443617087, -0.9755230046165743, -0.17652928554006597, -0.2461146910776825, -0.30195324627631, -2.413217265140388, -1.0480844008340622, -0.2437516775870525, -1.0395252337606076, 0.6708119579735411, -0.32379682142290106, -0.932392490579041, -0.04780391870903994, -0.6055229818707674, 1.8177178864376013, 0.3645040654026263, -0.30162031879144124, -0.723670072365476, 0.6826258497005147, 0.33439491535571825, -0.32629541365508025, 1.2872263255501357, 0.4655923267550111, -0.2585210494731121, -1.039974937329654, 0.2676780817309403, -2.2011214219754796, 0.1378719639101381, -2.1548873722288997, -0.8259817078519377, -0.01618607857975504, -1.826500113250474, -0.3181872957526478, 1.097639239414702, 1.1430531616576431, 1.1718605518835452, 0.02672261276218199 }, { -1.5267452105596802, 0.7773313280305143, -0.8618997020571054, -0.33046471473968697, 0.2994439827420094, 1.9078447863610666, 0.2874757674794942, 0.6463949139277622, -0.9629716456008092, -0.991965486931157, -0.2426846054907883, -0.8621009105454076, 1.7167111186704995, 0.49200199373172776, 0.15330997581111538, -0.355400298947847, 0.7969144018118319, 0.2703762867588683, 0.18639521349020208, 0.03796794731381623, 0.3554239017882369, -0.43322443492213436, 0.6556119845612695, -0.16797773982277925, 0.44838065256683857, -0.6872280210722164, 1.078591818084275, 0.07098523979813981, 0.8665542996298878, -0.8096179557236116, 0.16685047108965026, -0.680854529542143, -0.8254358145708851, -0.39944202771827986, -2.0777823952446637, 0.6288278300871021, -1.4940304864689773, -0.27619010745981765, -0.46962280033178255, 0.8998588746034407, 0.4497511999334253, -0.03543061410593532, 1.0974564541645413, -1.4752301476405936, 0.6134766780648474, -1.2483943939629274, -0.9299036606944553, -0.11916566106199243, -0.1094373418313095, -0.8961723373627033, -0.14101555442514185, -0.3344295774455488, 1.1655528924555303, -0.48045942253441404, -0.03034929453118245, -0.08571836249804406, -1.12467670068506, -1.1107184339140432, 1.2471073627194775, 1.0746865920694835, 2.286659647414255, -0.25584532485703226, -1.1505369181650706, 1.135840621863299, -2.0082979823512077, -0.028785976341655244, 2.79317762567717, 1.3183650987571542, -1.5106834743459334, -1.6245302503590326, -0.4236178103774399, 2.0919591715815744, -1.257371874812074, 0.3956660803610171, 0.3159152300672564, -2.0243953318495533, -1.025924511178159, 2.4870539801243194, -0.8422809966284758, -1.1007617449046605, 1.0231991429875475, -0.32349323542128317, -0.04800528810625516, -0.4020204001173392, 0.04076597106457897, -0.5417216119135527, 0.8437758322220759, 0.19234025472129176, -0.6934149910078912, 0.5504413875204174, -0.4338317480884896, 0.8748363433037567, -0.2259478242267026, -0.8705709780011982, -1.2793579719887787, -0.3920654663534845, -0.24821476929390338, 0.8024272203678369, -1.058463128061013, 1.1837133158997275 }, { -1.2444938101353153, -0.27030700192334484, -1.2860070928199014, 0.7215285831579862, 0.8521023044711545, -1.9354841669016463, 2.0547776256168016, 0.335743649477269, 1.020877006004173, 0.6928904974216306, -0.14935580270055646, 1.9109221713997868, -0.05827983826811595, 0.13162002752358837, 2.5822965053949627, 2.213497246312328, 1.513357610801169, 0.2252022871873388, 0.0821293970425042, -0.09575483677203418, 0.9425649556963045, -0.660205944297436, -0.021848822189423127, -1.3339817911094425, -1.0792614421335545, -1.1733025106341013, 0.7207434805232708, -0.3722360383098267, 0.880396082226695, 0.8924097886466407, -0.7206099718864133, 0.30454828318016514, -0.3451113495181165, 0.0874790000968836, -0.3530060283512357, 0.43132295377634144, 0.6412358113134358, -1.0372614162030416, -1.4385249726675196, 1.2235079094786776, -0.7820435125213892, -0.4900862391215434, 0.4923514241654075, -1.1943291028079168, -1.5839777613026764, 0.1911901025641164, 2.30765261598852, 0.7246942979421225, 1.2772247764156375, -0.7059141496103871, 0.4315339647892429, -0.09583483398938329, 1.4754074240114428, -0.17499329998002902, -2.1192849138225545, 2.0924777520762396, 0.129660586712414, 0.1265970704029502, 0.23402647105877872, 1.3913380845927334, -0.6578209964747518, 1.5367205253393996, 0.8056169324909463, 0.4852832425313453, -0.5898499199451304, -0.36334342253003127, 1.3194088108687985, -0.9001239223252033, -0.4851403319027945, -1.0651206640762976, -1.2312818823788312, 0.7175856775928523, 0.15912970363075035, -1.9309920976465242, 1.7468431650200693, 0.07828609605630278, -0.7502485230377764, -0.01123007667220182, -0.38581645600445613, 0.6791694046829135, -1.0120027086729175, 0.77340475729799, 0.5426876392506307, 0.4887074042836445, 1.103754927687276, -1.2976533715230039, -0.5656561992886575, -0.8049394236211724, 0.8431816617964767, 0.7590717564135474, 0.6557739250205056, 0.9083563189036603, 1.6999128761908946, -0.15412602169561954, -0.3168290130421339, 2.722665213313896, 0.06422070707802642, 0.8760530020316523, -1.4273240849002529, -1.100052375184437 }, { 0.5332362278538161, -0.7316055257282454, -0.7547578392719083, 0.7170982147745377, -0.3595416802956811, 0.9025576236112316, -0.8675307263358101, -1.0086055365452034, 0.004201245140549573, -0.9755988948905111, 0.5848769600737401, -0.30316752387338225, -1.338223765343062, 0.493342449775057, 1.9540526877783968, 1.7865800687697118, -0.4942500513642472, -0.3081837563994298, 1.448672761194118, -1.280243594631716, -1.6705502607963145, 0.3157891806128535, -0.7053962723529572, -0.5921020260956296, 1.9237983276629056, -0.8699956558858843, 1.075454824498838, -0.7622195986952931, 1.6291196836536666, -0.5170011076885922, -0.7166672594865237, -0.3429427928315064, 0.41114180902221253, 0.3489793502480238, 0.06830175982883509, -0.47415727917841755, -1.542888700063745, 0.08104746800905385, -2.285336460695868, 0.34642199165862175, -1.1198274320381068, -2.2794899979439207, -0.9473038873347146, -1.4019265891681467, -1.2046223916010679, -1.0294885983063269, 0.7374966711458555, -0.3868492073770521, 0.5956716004128759, -0.28716589332060605, -0.1729768491882046, 0.16107086607654694, 0.334121733328859, -0.08314447917590859, -2.25172596607797, -0.335888052180236, -2.3902436875506616, 0.7112308158791331, -0.5014978785411157, -1.135799169010799, 0.22129611809550373, -1.6051248685408466, -0.29142228251948976, 0.6296270048824404, -0.4714510622029676, -0.8668579977431166, 0.18719794757612454, -0.33025921200548725, -0.026144652974399385, 0.2972543692644539, -1.4566441271360548, 1.5291603692319757, 0.3181667012834959, 1.799171236656339, -1.7003586981028127, -0.30530440485731475, 0.5615278010509654, -0.6184859930770144, -0.11690690871763049, 1.4755916663451145, 0.06737149007711642, -0.44067174919370344, 0.9788342985821908, 0.7903220549605323, 0.7130176584465836, -0.3651471237792341, -0.6604808839577364, 1.697551420401744, 0.09152548646861867, -1.1481931777963525, -0.9374170658387335, -0.8690826802285403, -0.09168595272553377, 1.4708211807437417, 0.7600384554800391, 0.6146785067751667, -1.0279939159784055, -0.152214316951217, 0.7794510160838216, 0.8262139875761331 }, { -0.464254706032466, -0.5197813398230935, -0.4890788081469726, -0.0408993447127761, 0.44052616598884464, 0.09658018665556761, 0.4823561866601587, 0.45937527608647377, -0.27087304851827493, -0.2820610528847364, 0.4510400917048256, -0.6335263036856167, -1.8496312430620698, 0.32412645292925046, -1.3177930821811472, 1.3859752613689444, -0.1279862102222538, -0.2928395509328819, -0.7652211614201562, -0.6306813897496198, 1.479736305420959, 1.2972005563638596, -0.24587813969894348, -2.3872331104147952, 0.29882401103561246, 1.5020991528186403, -0.7306769271543673, 0.2843158423243132, 0.4077795099634447, 0.17694851913636817, 0.06776588596397357, -0.13969353459406367, -0.8147836454165648, -0.06662394235369169, 1.1630120802780826, 1.9097507399940987, -0.9488285855139893, -0.15764681405781933, -0.16039894424350754, -0.1968673453397322, -2.405157093871082, -0.8601248878212027, 0.2499155148305244, -0.5319670334824499, -0.6364523500817749, -0.07294647921164348, 1.2632101043318926, 0.4231853507672746, 0.8634329363425775, -0.3595936926494856, 0.7622538085877659, -0.677487503105155, -1.0766937345468124, -0.9629907633488812, 1.3090595096714164, 0.15289018149647987, 0.5039996578730331, 1.1414769100501043, 0.08808862560532926, -0.18585464085328673, -0.272373525136746, 1.053044350243403, -1.0170336945677485, 2.533801579517288, -1.7126259079599218, 0.6928308002350323, 0.32709241573756465, -0.7801591863458546, 1.0998537512887436, -1.4125998391902972, 1.2986179100680018, 0.9722465125810441, 0.1868932886665019, 0.4103690123502744, -0.2642669408838468, -0.13324274461378927, 0.5153530190604998, 0.12914864965968098, -0.6453721268239471, 1.60323681164677, 2.6335222478297915, 0.20112431419989524, 1.4906181093199948, -0.5032386330050175, -0.8168143819903771, -0.4447081615124609, -1.9127818143024837, 0.12974593112489022, 2.291602567849576, 1.6453178031855227, 0.6802317361309215, -0.03339148763383366, 0.3250857659395095, 0.6430557749950224, -1.1417839749447836, 0.1308070063745191, 0.2607762759771436, 0.9580876522818198, 0.12619959516699006, -1.1193691021804713 }, { 0.22712992118617067, -0.2910250922952861, -0.902524354365507, -0.1635519640408705, 0.2781046409511623, -0.25734886057657475, 0.6153790097513575, -2.010975404556045, -1.191350008994739, -0.490409355348407, 0.8397084163901372, -0.1195908814057428, -0.05044761115498077, 0.24989015769315734, -0.646765369290697, 0.7715318849351436, 1.4283396703803821, -0.45216300048043895, -1.1108347542678259, -0.7016358635580302, 0.4573549328395563, -0.7171155881116582, 0.01422635902243672, -0.7346845452118295, -0.041599816783310886, 1.2719113111830331, 0.27090499267036866, -1.3910581822704684, -0.08297164006726594, 0.05199032230941295, -1.3478029666059517, -0.3398866417095335, -0.925749000075465, -0.5268785998120931, 1.2345865822670457, -0.3532115809382646, -0.07897029274790046, -0.7759519877446006, -0.5656609914422823, 0.05455839292785645, -2.3335952470209267, 0.19482453081449688, -1.8257685332958602, -0.9984847898903751, 0.13778246239818034, 0.27127052324008327, -0.9930780773205736, -0.7668968172870431, 1.287118503534582, 1.4687152058389148, 1.3218027850689913, 0.6743675136538267, 1.4603764100828562, -1.938701090888766, -0.6621399678477305, -0.45392600956859724, 1.2439784836776424, 1.099835254976953, -1.3178041423509814, 0.07930076706006788, -0.4248355544068813, -1.697327365249931, 0.43574220556187054, 0.11541675110041805, -0.33678601527897584, -1.1416555514867486, 0.14097441827081159, -1.3552852588304418, 0.9949807327031945, -1.0423276041335574, -0.23369524932236002, 0.9811479198612779, 1.413987495732526, 0.5974372365261409, -0.3245367306349593, 0.5833675890866477, 0.6224014605540726, 0.3685560730017994, -2.2207347799423736, -1.2746643195360716, -1.2205412879954782, 2.235106406621907, -0.8911637751535689, -0.28464597534737834, -0.6403567985327366, -1.2288864396244858, -0.5028648975440856, 2.4682449403426205, 1.0953814223822986, 1.169382285845246, -0.2934238425705862, -0.10326925949601579, -0.4476981631389615, -0.7719156945686176, 0.8890198006009729, 0.26844364065052884, -0.6346496879284288, -1.4461951770157968, 1.0762449261358806, -0.9237215050926489 }, { -0.6336243885616766, 0.5016238690403942, 0.5435411843679763, -1.773339935924119, 0.8469927720451665, -0.6694501036389904, 1.4899602795850702, 1.3664343116819744, -0.03729916662173145, 0.2477078555483897, -0.7535153343733162, 0.8744913402172434, -1.285319614323115, -0.8304779667876765, -0.621695621873184, 0.04641940210771781, 0.7998200121900043, -0.5158576448510103, 1.3931159420398498, 0.38763424520621365, -0.45554958187170874, -1.330453525447341, -2.2893613320520667, -0.05921435405629275, -0.2564935784976147, -0.28303254906539976, -1.1730820750498756, -0.3447379576317808, 0.7317030797092215, 1.6204637173855818, -2.131770112366544, 0.9253637595010583, -0.17087891231717106, 2.144073613470472, 0.7661885682802827, -0.6176602772457068, -1.1290068451821798, -2.110642488124157, -0.4166774450277118, -0.7862027516351073, -0.299986851088213, -0.9905455388140557, -0.6690357441424056, -0.6640789574602977, -1.031346732954803, 1.9365330870226702, 0.29430426094675455, -0.8597946187938953, -0.8724979258321856, -0.6554937694836958, -0.6215031638486787, 0.9041334680112227, 0.5500741683926771, 0.7859497379870748, -1.396829581099286, -1.6679707538950481, -1.593773766655197, 0.31964742414328157, -2.3898482947288007, 0.6647675785646695, -0.6295837446213427, 0.8425243742715756, -1.1794274136346123, 0.14865908143026257, -2.00487553560662, -0.14911471563473935, -0.11334210298782126, -0.3919321510565424, 0.5485962755645618, -1.3446136978517564, 2.0083049137592637, 1.1397547707224598, -1.158092284726835, -0.017636367684785707, -0.5253207669280485, -1.2396640447834093, -0.1569936720843588, -0.2787251809811541, 1.1686862260296453, 0.6350547337733549, 0.5781195057014056, 0.4456619207199029, 0.7269479495058303, -0.2730315419421489, 0.26712170502804367, -2.015971108777896, -1.568443141238731, -2.0457802288091194, -0.25832876766120705, -1.2241338291287005, 0.4085778035792607, -0.30202409485098636, -0.9074741574790783, -0.658797519565921, -0.045407276610231445, 0.23044042221413205, -0.11044684904415007, 1.5505894960461644, 0.43435727061102364, -1.726150554440203 }, { -0.3982502266011002, -0.40285502366981213, 0.4544580702441042, 0.8445690968252847, 0.35657649062586005, -0.2393698939053771, 0.22791227276399767, 0.014572029092152715, 2.9693841284073783, 0.27527464946434327, 0.21613312278706975, -0.9513505110092062, 1.4104143412232766, -0.056226576066870364, 0.08280170989871005, 0.6497095291203544, 0.1990384239746642, -0.5102829386645948, 0.11723846433122774, -1.0895569165105152, -1.8104600009835023, -0.19519397196418958, -0.05138752195548597, -1.4632684894847103, -0.07535298890285384, 0.8949058614466554, -0.0971972153483106, 1.3088576815030213, 1.3029076254572782, -0.42638367996919596, -1.2782855115254377, 0.967052741688248, 0.447552523244729, -0.42579809322312545, 1.1211352705681215, -0.37636484744990467, -0.8226555345862778, -0.701235823486658, 0.6298350782399438, -0.14675659943303274, -1.1372796055439, 0.764592173504894, -1.405062171393429, -0.1228743666796199, 0.8987077680510518, -0.08022485631716736, -0.01937076324183403, 0.03853345865715804, 0.3662268342315187, 0.11115676054827911, 0.06688749998235222, -0.3073455627199309, -0.21022581616481117, -0.12079091973187382, -0.04567213176204704, 2.0444361151110955, 0.9366721396845383, -0.8452572438885065, 0.4791944966749785, 0.47535287010209604, -0.9866008830124189, 2.8565060918670557, 0.9457962846935869, 0.7553624459889428, -1.09368531597005, 0.5781653469612414, 0.46333785417471, 0.018700340477745495, 0.04811698281576616, -0.6240554630261066, -0.7821116440014605, -0.5886427628227279, -0.6864567724253312, -1.1952902959156477, 0.9075100609673984, 1.3278454601866436, 0.41431644747567137, -0.6558603790627878, 0.3239030376932511, 0.8616476559045195, -0.07807749626128803, 0.8147572599767009, 0.17396381802713248, 0.12293977810118402, 0.6273233739185194, -0.44143158481198075, 1.2078291289541723, -1.937198422217055, 0.35217922818227987, -1.5033516601815726, -1.0223158033300939, -0.26885581576968537, 0.3049993154961562, 1.2256219409309945, -0.9203406117755046, -0.24568360029884975, -1.0519591249114026, -0.2054277779441778, -0.9209860650220704, 0.6370720279355122 }, { 0.6934962017714466, -1.2708742875498553, -0.2747787384117187, 0.08772020245110565, 1.223189002990752, 0.4357952670103954, -0.7140576274183421, 0.6274220635002802, 1.2053403520305512, -0.9201019100133823, 0.775708018390299, -0.412981244546771, 0.7385507091677951, -0.48952066598801885, -0.1166365394931037, 0.0058614865495363305, -0.954165654985342, -0.6289683911107703, -0.4540756478910529, 0.40659678606093036, -2.060359069247964, -0.18237057659364636, 0.41404416348927886, -0.7548010094371674, -0.22698384350686704, -0.0789449116833583, -0.3873363584981163, -1.4581236757582776, 0.3137272750690443, -0.05784113283642071, -1.7939341660060957, -0.638559000744845, 0.5858829655209081, 0.8723382641413405, 0.12820951063826086, -2.7975908218713146, 1.3755998839964025, 1.6315693897179826, -0.5807879446819597, 0.41698825803908857, 1.1516083362715595, -0.13894204693405945, 1.5777765734241946, -0.3685030324162928, 0.23192293235266906, -0.276395163487372, 0.7890413267107167, 0.8284548488821913, -0.4032487058954558, 0.9073028843050248, -1.617538021198701, -1.6850158831968773, 1.131830933069869, 1.484828483428315, 0.14882078625207695, -0.9988279220948385, -0.8007339630036906, -0.2666077248994875, -0.20424889290634776, 1.8363139093116259, -1.123918503691437, 0.5349920637405039, -1.3625060839329601, 0.02071147324440332, 0.5450869085741313, 0.9090420662569002, -2.205142261859099, 0.07811612392760449, 0.4640517150433348, -1.6662918770777428, -1.1317013577974062, 0.3505763409669054, 0.3860657655580885, 0.1237608394994164, -0.056296984429000226, -2.6144710383581935, 1.5169889167017494, -1.1482283994645026, -1.0937552513923419, -0.9154375270221837, 0.568556881521231, 1.7332769188300625, 1.3775826733785614, -0.609279510420502, -1.471313890769128, -1.3357922948024175, 0.7282142106400513, 1.2286762283915416, -0.14830837894660653, -1.000208653647885, 0.8951206443459568, 0.489006563836124, -1.2514253601642689, -1.9273064385511294, -1.649022038755338, 0.06483853027523015, 2.4757792981564615, 1.6304883495261664, -0.277456411494561, -0.6084855457527203 }, { -0.2969255935667437, -1.3501159801679619, -1.3563483157998104, 0.38223747146123493, 0.6635298189266661, 0.6069251466869219, -0.6763130915031872, -1.1968980788952286, -1.8286407264562279, 0.24594990629716912, 0.36458131758527834, -0.39503053455188475, 0.1428234375544994, -2.2621486387295566, 1.10029713039155, -0.09700332282502283, -2.199743786421981, -0.5336312908433302, -1.118434513766733, -1.1547561740886876, -1.6565102786456245, 1.2109787600649815, -0.7830410802834251, 1.6194344903687652, -0.09595174515519661, -1.8972489128697798, 0.03841579954222735, 0.11816448421992835, -2.739855194205992, 0.7867553861791049, -0.387893863234298, 0.2885256287525637, -2.5843929186548933, -0.7556900866570333, 0.23205386101078684, 0.40160082936950897, -0.23935928580898716, -1.0774168163779443, -0.6074489802408838, 0.44800912362444234, 1.1521313128676907, 0.20856145222461037, -0.9211506221136606, -1.2258282194591732, 0.29504140222013553, 1.343474402139517, 1.1325570637326305, 1.0483485856748747, 0.4207483878965611, 0.398000944613371, 0.94213843478248, -0.6627390212031201, 0.14170018501642553, 0.39078497074084717, 0.05082224025280411, -2.0832276526580147, 1.1862464913767061, -0.36121572947948266, 0.6309802578468462, 1.1879259133126627, 0.4670780234884911, -0.3772931228289678, -1.2436146969691546, -0.918191245064267, 0.7685123075625041, -1.115219434341902, -1.8001429546096888, -0.1799005852915881, 1.9116583486725016, -1.164212817699058, -1.3000349756396508, -1.1268099477298654, 1.4681397351703331, 0.2656371665218786, 1.9905315781888306, 0.8271203687685157, 0.022887095709767578, -1.095359900156557, 0.6159655272526229, -0.49217204825697336, 1.217484890053481, 1.127868101755768, 0.48689622731431514, 1.589409294320567, 0.08721451909626922, -1.7173876090846873, 1.9027715712909363, -1.3237146661924357, 0.17610268006022542, 0.27130689959861487, 1.6940467719765528, 0.839976257563523, 0.5736628569610096, -0.6990499225311589, -1.92055033045521, 0.20448033407081023, 0.6671623942486472, 0.29277870485086904, 0.2553689069790637, 0.7443039312093164 }, { -1.1365837894564879, 0.5954037927510325, -0.9111624985412842, 0.3781652794765844, 1.8895093291402365, 0.16570774892010567, -0.676235377285506, 0.4046572347831502, -0.1081631402803485, 1.2345206323242353, -0.9983391915296311, 0.6973258980550217, 0.22955532510863014, 0.6087353189398461, -0.4336314213224637, -0.015371877600012943, -0.2644411406035447, -2.442578102995452, -0.33105850433048223, -0.22941513385000936, -0.2824054255710601, 0.8848030095348101, -0.7818036529040304, 0.34772597045665365, -0.3823549435870604, 0.08020196531728359, 0.45189854662796913, 1.7547365463413482, 0.8946545738807921, -0.9920261699605332, -1.5684186727117593, -1.97702512361777, -0.531455034202097, -0.9387674363882164, -0.09273966406486917, -0.10860463591180596, -0.6027011210831197, -1.1509067082623887, 0.11307470800320615, 0.23039739257878258, -0.3171572240500192, -1.1064300003596221, 0.06868650472315178, -0.4929461115424358, 2.043792043279568, -0.6701716712078918, 0.4103222689501792, -0.40985286260528325, 1.568858009621059, -1.1121432737824786, 0.686202537505947, -1.0085145526212849, -0.08616453826617713, -1.6135636509864733, -0.39189988442844326, -0.29900676838974083, -0.7670282462742279, -0.8515695691905028, -1.5304437167197753, -0.9737584973907895, 1.6712963758483788, 0.682507636080473, -0.1816617479787651, -0.6440536302502254, 1.3878025109505776, 1.603085268317239, 0.034209246094872234, -0.797043754464036, 0.7586245728379858, 0.4566811678651874, -1.3836589214944692, 0.6030055807128301, -1.183886912751562, 0.5485104933261994, 0.6647704898016108, -0.5200328367593617, 0.90995650265103, 1.2549458280877144, 2.1632753102210254, -0.4779298111510119, 1.4471995211291517, 1.6657290821182051, -0.7154687792882347, 0.7786974440195222, 0.8088096071605914, -0.7416393681570426, -0.8544370614871207, -0.58917576839409, -0.3828900625692363, 1.0265911894907813, -0.8248537078826857, 0.029682066567994294, 0.011150131383921557, -0.0859725104706794, -2.1424970859722263, 0.09705968136816892, -2.1570037653956406, 0.0263571541334393, 1.0025816838698343, -0.5059675384773165 }, { 0.6181828355867455, -2.0380997713438007, 0.3046585722264628, -0.014980996492931432, -0.5290618831927314, 0.7534535995653877, 1.9966011707973088, 0.19972613787025162, -0.16467186566030662, -0.1521026655376468, -0.9624026138193565, 0.13520582022086736, -0.6341929930213883, 0.002809569219270865, -0.7402709529379303, 2.4700338835817313, 0.6098850048713202, 0.9741194261580279, -0.15575405296659442, -1.1214027916147937, -0.6314193013700002, -0.15060743742917457, -0.07593007910264404, -0.16263678202300752, 0.6107310496604722, -0.15206514397570287, -1.0447998742641398, 0.4517222860649883, -0.33288479448975566, 0.5745901873736575, -1.4697913688875572, -0.11125683859707515, -0.8116451610289523, 0.22916036970459389, 0.6138413720482201, -0.33760275685003066, -1.1087580100802648, -0.4837068427590092, 0.9172937856716435, 0.6044433177877142, 0.39318564387781163, -0.16838677020388274, -2.0235313223919364, 0.6197347986319731, 0.9519093576303396, -0.6087374876863917, 1.8936063378793577, 0.556768733025668, 1.4670208699267915, 2.158241115300078, -0.8462732575021674, 1.4704670843488727, 0.680639781253891, 0.6800389448678937, 0.4443892983426857, -0.12009890074340625, -1.7368938491583985, 0.44597598519855775, -0.9405029222707214, 0.021022926526784357, -0.338919141995621, 0.7629042454446997, 0.5040578163877221, -0.01805437836471338, 0.27988285098167726, 2.300788317276629, -0.01685524773979206, -0.08936038423557587, 1.2566586429636435, 0.5558891171695225, 1.2408346836340327, 1.235580504196008, 0.15007426791522938, -0.7534053731189334, 1.0415788701799007, 0.2676507811668582, 1.182789744087736, 0.6779919322360048, 2.0157523076551636, -0.5243777808662209, 1.970456348555097, -0.8608076793809787, 1.3163150783217819, 0.6882659841162968, 0.09867578068167436, 0.970141400173321, 0.19019454677242392, -0.5062877939242316, 1.9737574262819368, -0.7909057983300439, 0.5711322440763456, 1.7692639439055955, 0.3358890911364689, -0.24829220161063323, 1.1193750188066534, -1.2494742219861754, -0.3609251947482264, -1.5232512983910809, 0.02323201628587036, -1.2861876748861645 }, { 0.0856117097484301, 1.7891411311761507, -0.5779309445174989, -0.9477135917935934, -0.3284393370393129, -0.3424842969173367, -1.2133597867162809, 1.781901338675662, -1.1328892921895806, 0.3926546687773441, -0.7838331143458954, -0.2645319846675511, -0.20581929426265352, 0.3934904493475551, -0.04300901712921723, -0.16643180145198783, -0.606967521126245, -0.41286146583892586, -1.291640924094838, 0.1892121513162941, 1.4464199491127139, 0.015527652977428771, 0.18231367422801134, -0.18463775564951004, 0.23692240761932087, -0.6863594811853401, -0.08685417076196686, -0.7376107806844802, -1.1604821467390474, 0.4012165110500722, -1.8634259287801365, 0.43522048858913664, 0.7182554344756484, 0.720436322209309, -0.7621895082924326, -0.431797734781552, -0.3516002499123709, -0.8422734809743888, -0.8738520580911261, 0.9946180601645901, -0.6244390030280417, -0.40456836700849846, -0.7625013360785882, -1.637067148918226, 0.47061506642329315, 1.1918123455727472, -0.2305709096572516, 0.632747681089182, -0.635690029979972, -0.7281920692595044, -1.7559254888848528, 0.16723627206717942, 0.14712293147761835, 0.14827649197127948, -0.3020786097179257, 1.8752422682453516, -0.0005021685611438591, -1.9055055973471406, -1.2281992343014236, 0.3719842482504176, -0.5076896822709527, 1.0745547638467607, 1.1045416731415307, -0.6893412294569584, 1.1883838127922213, 0.5480613592949402, 0.10440103565217573, -0.5815145919857758, 0.9314847250956625, -0.4425649375843885, -0.276033871221501, 0.3991473038139888, 0.7862802429846997, -0.9432389950153416, -1.2541461525343507, -1.6000545034250846, 0.2872755866574618, 0.334943087884672, -0.3140730833305353, -0.17030757407725908, 0.8640360861416734, 1.1587286363321414, 0.9885814592582236, -0.3200804420096442, 1.5520043825987448, -1.1625979392804486, -1.3242806534736256, 1.8369132052030337, 1.082594675177034, 1.8259118242213628, 0.5874259113514994, 0.5747195299915093, -0.619109827928565, 0.3806566625610409, 1.4278133994261744, -1.9229705603423615, -0.1616583588395748, 1.4162108935290167, -0.415484922854095, -0.8140132952625552 }, { 1.2676270611506806, -0.09052358673811935, -0.00023057916884053096, -0.28000705937005227, -0.7567953751806218, 0.35121216851630055, 0.4883408459886232, -0.5720632502487718, -1.8771823079087109, -0.1733409487457324, -0.7106724116602606, 1.3557003562239318, 0.7624861301795683, 0.8162032277200669, -0.6883632192427706, 0.5755701798721801, 0.47622869613740776, -0.6865796844997276, 0.7995920237054235, -0.6802522807355122, -2.01538868069262, -0.6971863531078512, -0.3493809597037354, 0.3860543324061075, -0.7340214154121387, -0.10951067753582554, 0.2814326967037637, -0.5652249002132552, -0.07311599195678786, -0.21859653494556755, -0.6791275640062873, -0.6230619698730728, -0.8503852126922034, -2.4578274483007845, -1.0570335333704277, 1.1740298048606888, 0.5045350892710652, -0.12339469433432487, 1.000489225229767, -0.19392660807454937, -1.3250605014946772, 0.6001072219498214, 1.9667921746538215, 1.1710609682726607, -1.6290872271605714, 0.05876257922376973, -2.3997616253217897, 0.5480053727374883, 1.0771080931605943, -0.9126257995616591, 1.57026922940029, 0.10980297606440384, -0.14924030197732863, 0.9435459758615723, -0.675305088902776, -1.8946789716117465, 0.3360417399417849, -1.5970622957601468, 0.3610311462726052, -0.04616457654974757, -2.189974132171463, -0.46751785044987576, -1.3911498499592279, -0.47354146902076905, 0.19374357157618485, -1.6919505513002089, 0.5780877860156984, 2.537351234111302, -0.6476618258327104, -0.871968514349978, 1.2933778984246012, 0.14171060511662675, -0.3015729460972642, 0.286805062145173, -0.7650006900341245, 0.48041266361849044, 0.33754023906153224, 0.8878693809746785, -2.250023503513127, 0.1657440468502889, -1.7789415673005766, -0.7554214296352272, -0.739272897760803, 1.1527373351581298, 1.904398811798897, -0.0651294873147382, -0.2664794805128094, 0.12259625358387607, -0.005736220725460483, 0.8519404578452733, -0.6598265884773525, 2.218901780068254, -0.2726439244691154, -0.5467697348722917, -1.4825084903202208, 1.3492279858420204, -0.7823927044485124, -0.8821471377616996, -0.32096183400363915, 0.005283645842354981 }, { 0.6726975035705334, -1.7508235058494586, -0.7799267643532388, -1.1047959260248388, -2.167187869981266, 0.9571175791132981, -0.32390369876238295, -1.1869470430155042, 0.3127715158172786, -0.037800000104788754, -0.28136997893757565, 1.2608249912451461, -0.4891020309204746, -0.15665987469943665, 0.8193286448470624, 0.43017286514411934, 0.13126809703472483, 0.6239383889663912, 1.068447924700476, -0.4258991633343039, 0.299817950575783, 1.8668896787163218, -0.1353995759088942, 0.4438703833801332, 1.4537475288670103, -0.5063341316848499, 0.08111428213257582, 0.13721838031819997, -0.22072889099702173, 0.8382278283191865, -0.41891275102182174, 0.10349549883226493, 0.31499188836806313, 0.4867966624470344, 0.15096733691392855, -2.0667737465108575, 0.6448122775907826, -1.00565942048849, 0.9882623931320879, -0.5261027803862764, 0.14422411498937415, 0.7195926107503471, -0.15314215390503494, 1.2508963726286983, 1.253987911208878, -0.6779632701164942, -1.5436941382188871, 1.9131848749841924, 0.03850054838633259, -0.7021475896915673, 1.454434368765574, -1.697175854120697, 0.11419808105236828, 0.7418908437074255, 0.18397711493222269, 0.35779625402122706, -1.4846938730448909, -2.0926705026057166, -0.10243450299888099, -0.4216528372503178, 0.10115699471165063, -0.34606034824628995, -0.945508332048161, 0.39717310957848884, -1.1258299656007202, 0.9292121322049107, -0.37529634171919524, 1.262357297789643, 0.22053117404998115, 0.3689607571364458, 0.10309296140791814, 1.6715475233552755, -0.12757127833522322, -0.3888787143393962, 0.795079479681488, -2.4590593576582704, -0.12340951798125396, 0.8511469342628039, -1.6374718490642715, 0.015263966226908144, 0.7814501979636447, 0.32341552260209006, 0.5789589402844029, 1.0427263427746971, -0.022146517811675967, -0.5976189693559287, -1.7785903052878322, -0.9488547650604059, 0.42108104302935817, 0.19486165180493412, 1.2556062453785795, 0.5631894766774882, -0.17057857809091334, 0.322077533946446, -1.7905247621039362, 0.4614041028471036, 0.9503027236921624, -1.0857290932317156, -1.3410162614448395, -0.6439149603344907 }, { -0.19896902971129113, 0.6092918905932327, -0.1777274238119207, 0.4848685698533823, 1.38771837590671, 1.171063910783152, -0.8547063340469194, 1.6415619023752994, -1.1234204429320007, 0.47725259230451605, 0.881659832048358, 0.7176195986946633, -0.6783197429147366, 0.11667942674264384, -0.8203927462180832, 0.5419782209804288, -0.3681250473636452, 1.115900793420022, -0.27555411575443367, 0.9254696950896681, -0.8796752051040351, 0.6839877690723207, 0.39187713326385537, -0.3416916931859367, 0.691556104943225, 0.7455155023900201, 0.024845861691727786, 1.844842165596687, -1.517123088367237, 0.5222317747224877, 0.5888751896812718, -2.303711346779209, 0.5338625166970453, 0.5149650465708248, -0.5316052532252377, 0.5618641800568575, 0.1000615978856139, -0.8137641651267039, 1.566373183976681, 0.45520171670995774, -1.260489926881573, -0.11375485483184287, -1.5192584210408289, -0.5515900417452402, 0.7975704026991762, -0.574038642807157, 2.786666039907419, -0.24314617436822233, 0.7421051994033782, -1.708250754951745, 0.929109034765779, -0.24310303362174623, -0.18299719098984596, 0.03664665939186954, -0.41140674699842056, 0.9360304980308632, 0.9739963658368882, 0.44459862953872886, -2.56008208245992, -1.7531132797074727, -0.6554914868670046, 1.027655581422479, -1.6901362441330445, -1.0986952061796802, -0.9142738624306846, -0.914441974220657, 0.9136070853349696, 0.6862263219753683, 1.844971720121501, 0.5870882672631664, 0.9930477464680129, 0.333439930833815, -0.6004106807672194, 0.39481017099768867, -0.6955758043539098, -0.23334198234808626, -0.37234639815929227, -0.42044229341615924, 0.34469460560843546, -0.7579251888146887, -0.13317766041591197, 2.002985394929973, 0.6299633912831115, -0.6649033591649571, 0.7846591885976968, 0.9804729374638099, -0.41516515870373616, -0.4933802219168811, 0.9808769040577084, 0.94860901336376, -0.1573573761958354, -0.5701826925155763, -2.322005254043188, -0.4218254897931664, -1.0894878716225131, 0.3837470241621572, 0.6257215979840863, -0.004766488742011826, 0.23717506199313787, -0.5705873030693851 }, { 0.592320677754238, -0.3831060365791185, 0.38841350184762674, 0.5270328426013722, -0.059189282281476824, -0.5253315952168892, 0.2428673627937566, 1.5106788126619253, -0.7605544425920906, 0.8957058527905379, 0.897915350776134, -0.25498681234927045, -0.686281149939981, -0.09043738101982302, -0.058889610203018763, -0.16445060164807965, -0.9388496796076679, 0.14679599426120907, -0.40890920393593183, 0.22683049285599155, 0.31697074068391023, -0.2350023316752592, 0.38777275700974684, 0.7959346234880742, -0.030585714665006272, -1.0814890708130305, -0.2158551321137205, -2.09880887292451, -0.47324295973428415, 0.5435431463842321, -0.4404992834734593, 0.2262133821332148, -0.1994490101956016, 1.0002775614822719, 1.149032317686806, -0.8772791464696974, -0.22172931387812184, 0.18407914076502693, -0.10063623023226706, -1.2527003007232056, 0.3443074983108928, -0.9410741640253305, 0.061977914554795774, 0.24127661539029793, -1.2532574714005915, 0.23923325479366292, 0.32081151229944055, -0.06206811913518845, -0.34985323483909436, 1.2139683659775669, -0.36969488190287425, 0.032725865090010596, 0.7166910126800817, -0.7400201843232491, -1.1174246843998936, 0.9730245447933525, -0.9401754695589996, -0.8933992092688836, -0.5408837708470463, -1.8466131767504812, 0.138945348352955, 0.4387243840268747, 1.1630084621132026, -0.6578396791890873, 1.425964709996351, -0.47874191845130565, -2.3695251191878657, 0.7110209605847021, -0.43565801903455115, 1.4335490316530952, 1.672162859173469, -0.4349404857520415, 0.49295828286945365, -0.9812505444446684, 0.35636138931837724, -0.7521493355980489, 1.6682308763185152, 1.82060438217612, -0.6111340017686427, 1.763091190329479, -1.3808282491800317, 0.04380280996909565, 2.071290254907259, -2.5615081345583657, -1.467923202508643, 0.3346009353845349, -0.42052554248306667, -0.39042179980684194, 0.9827646432457453, 1.2502174517597118, -0.33430243551914995, -0.826691402447693, 0.08283922337958557, 0.5772408321845801, 1.5407644483880758, -1.0224410466789313, 1.4048345740478676, -0.9714958393442844, -0.6403802865199788, -0.01526600206223496 }, { 2.3245258298689517, 0.590073142106568, 1.2348832422851728, 0.4628091863090723, -1.976413157629242, -0.9930152997916878, 0.6676552382937967, 1.4826125135660713, 0.7213956818380016, -1.4106996648261814, -0.411049443729862, -1.2075516899718026, -0.2623191341071186, -0.7525523307912171, 0.641133565813935, -0.8139846098761571, 1.4748990671509223, 0.37749674298401403, 1.3370129132288529, 0.27092043412700983, -0.7989883731849405, 0.6482359457974429, -0.2927990594406174, -0.9576848597133814, -1.0356217381671817, -0.2526691976213626, -0.5404209609759824, 0.6706403936652142, -1.0710791320127768, 2.3282022256811254, 0.5759438978338732, -0.656236120443038, 1.6723305341433419, -0.1892225779948198, -0.9680196264767379, 1.2690182788570517, -0.6185873204412594, 0.3393775312876351, -1.938178188963139, 1.185258671675495, 1.1059647931846888, 0.3946384614277951, -1.4288118579981, 0.11183692586903747, 0.5974141876773217, 1.2347974673485365, -0.4281419226911731, 0.9813851126201767, 0.013022565482962625, -1.2747548723494717, -0.6118282557494995, -0.5235055969573618, 1.758333615390419, -2.1210491611392026, 0.5724923866820542, -0.3984272155352602, 0.5265983016381951, 0.45749341942586963, 0.22061171142919073, -1.5827795324078966, -0.09844784198520089, 0.353529998808534, 0.22489357488207268, -2.0594145104768975, -3.999487300865249, -2.2058371015794878, -0.18330056669109823, 1.5600245411486457, 0.44653905675821576, -0.20712318790448764, -1.054373369947023, -0.4429800656582239, -0.20048338514441633, 0.3109496648844218, -2.06119171918792, -0.5551292201295385, 0.9546282498977118, 0.7813736534398419, -1.1048120798574066, -0.44903912924898487, -1.2825524208692767, -0.2610015656585808, -1.4391477984009402, 0.9649837164202721, 1.7223703579129608, 1.1990936955445848, -0.7676012692429768, 1.1813294219852932, 0.47349109327894934, 1.4406007700853627, -1.139122189840085, -0.7768134245831424, -1.271400775143453, -0.9928630646029379, -0.7277315283602517, -0.9293895784669353, -0.05594977282421982, 1.497640787810823, -0.05075659906679469, 0.21827857239804518 }, { 0.5808785897881003, -0.7144466977965421, 0.27565128056072435, -0.03112898646612017, -0.4048796896961861, -0.11284909476706406, 1.5934992819851874, -0.015887156847311925, -0.2033339852168571, 0.4635522739835376, -0.7602609828812461, 0.1624585003006626, -0.38133407178771733, -1.3554113913258523, 0.8992535619215368, -0.22991780618561922, -1.3062226651862714, 0.24305276432229345, -0.6152009119004808, -0.4705101821172524, -2.6777262381741047, -0.10247720252442781, -0.34077148916401007, 0.4115055366128111, -2.131386668015201, -1.3294233640668782, -0.7564392151070537, 0.6978971245167451, 0.899924130400587, 1.305983211699767, 1.8645848281401756, -1.0021255152470883, -0.6293514135958789, 1.6463823808635114, -1.1724041601071047, 0.08315603141731011, -0.9080364634558798, -1.571760337623021, 1.5089916423206782, -1.1318134373308184, 1.0744726513297502, -0.2286103223603902, 0.7254470434294349, -0.16401642530080338, 0.02625185270919059, -1.2547475485028143, -0.05787448957628966, -0.09787280529369119, -1.1328987002032684, -0.029789324119040308, 0.438445096385647, 2.11284313064625, 1.1972791257083464, -0.4260164617152593, -1.5190538796257085, 0.6364114468368925, 0.6987983745543145, 0.5538101805198388, -0.16838479504277373, 2.0770491954319485, 0.12350184876759351, -0.9333996029359934, -0.7226106849337951, 1.6739873209929503, -0.10787105566725193, 1.5511816687776292, -0.7316771471229085, 0.659143097150394, 0.0270240379696014, -0.3545037282928397, 0.9072591797682991, -1.316468728006145, -1.51484439704644, 0.9711216352175784, 0.790781244392539, 0.8943488866248186, 1.4308755031534817, -0.03651858273624319, -0.1177175584485747, 1.130213661583191, 1.0379327931300484, -1.712740061639858, -0.485367530063448, 1.0174063070902462, -0.3186115623300638, 0.14761454401970273, -0.605325651559082, -1.3720934007304015, 0.6245740679256717, 0.006087665539117245, -1.2600497769977326, 0.08802706380001292, -1.1805608949384836, -0.5157838751403616, -1.2792067861498762, -0.1548491096480704, 0.33398020738840734, -0.17267647572835454, -0.28936213946633066, -1.2774632528150838 }, { -1.1735736966489194, -1.2679060107868183, 0.36020269704900265, 0.28381826441777724, -0.3295110267765279, 0.5970678461373305, 0.03461500889626973, -0.2014308184713412, -1.6396640097900248, -0.31172801691168095, -0.28170994103372377, 0.36128898476648685, -1.1354525938388917, 1.146152542069523, -0.0720080757408644, -0.8652709130766908, -0.9230735063733629, 1.1345669763557775, 0.8111677826519179, 0.4036424175948364, -1.901960994127573, -0.05913390995862523, 0.8460253589207, 0.9171142076772031, -1.9128764086596943, -0.275532662092817, 0.3749802043461396, -0.29217336906132846, -0.44296670633908924, -0.31653307060563424, -1.28769249383717, 0.09590626818884648, -0.5893446079519488, 1.3529109958557364, 0.43323193923523384, -0.5718951469569499, 1.0206980897103375, -1.5275769161802106, -0.4595746429904063, -1.0125009859641754, -1.0035168442536155, 0.9966584109091859, 0.12351677313949856, 0.3604140807082112, -1.7714595788973113, -0.8187520576948073, -0.19039355616389778, 0.58878835401447, 0.8155060843561148, -1.1439355216536318, 0.7267485766000887, -0.2627987466950506, -1.5812405130184897, -0.4622798828737177, -1.42228280165164, 0.011784483827049937, 0.6846357428683117, -2.749299956276001, 1.331678306180111, 1.6969119274044162, 0.2729894366374213, -1.1907079189326013, 0.2540801928081956, -0.009804520388070111, 0.3385752776764636, 1.5395588792322834, -0.8676729237227017, 0.3974492994019938, -1.1279187429781343, 0.3676957162287964, -0.8969851208014983, 0.6105794556782123, 0.9558976011889302, 0.15781341731417284, -0.32100747715725464, 0.6977193908928562, 0.44506841512220163, -0.6630357907757148, 0.6374016653757639, 0.2565301833411379, -0.24967124693926807, -1.2350999494646717, 0.8947745424601817, 0.06614467245509996, -1.5779164782619681, -1.089683563004246, -0.29832680877954854, -0.6561481466859135, 1.7661989435406067, -0.04231369710159985, -0.26017242541559127, 0.7187043279907096, 1.9484002000569196, -0.06943227694421239, 0.25691023974057264, 0.9539915500957037, 1.4539457167546879, 1.7856133484630068, 0.231193212921571, -0.6093654374509209 }, { -0.8436953692161203, 1.1403687146545711, 1.1627379959741544, -2.325593730374806, 0.2508321203882224, -0.26876616817780496, 0.9118751708274545, 0.5593417757218335, 0.7484171724699786, 0.4343988686793317, 0.24233116899355356, 1.9139705127928572, -0.9185652984653185, 0.40802891543195796, 1.893562365820764, -1.7961343737638875, 1.590450599980861, -0.44590020858856405, 1.2054363019404444, 1.278200589011554, 0.7331819722942867, 0.2816858531862019, 0.7743587442654286, 0.8502095019134059, 1.4750503806358966, 0.40454142845308166, 1.316431438566773, 0.15697640260937867, 0.9866645476844838, -1.6235160299861386, -0.27681954148561966, -0.12428288688114128, -0.002765753229974107, -0.6934756385783727, -0.9145220873371239, 0.9296084218844393, -0.3810033123337653, 1.0689424654848447, 0.503543798281007, -0.14177382003135722, -0.9021122846554515, -0.6632278165134872, 0.5685134447011606, 0.11944007532846003, -1.0359088552056592, 1.5099495879542313, -1.7412985055954375, -0.25136966830526714, -1.071718993866301, 0.7912937578534497, -0.8917059628142566, 1.0642187321957457, 0.8019565819032007, -0.023674975134683116, 0.70437710402104, 0.20008050347457573, -0.3622756884391842, 1.2381134812853323, -0.6880841751153751, 0.43847647541864854, 0.04195528827267062, -0.1977161128707227, -1.8397838944507896, 0.4689646513535646, -1.4685070207920081, -0.24750274610440257, 0.644081535440215, -1.3132671134222667, 1.1839070070757338, 0.09583656787703049, -0.6736553031866847, 0.3948404045477603, 2.6961086714397733, 1.206535369914174, -0.41692224102824205, 0.2986252625863738, -1.9627937743649688, 0.36240577396983314, -0.05671970192324229, 0.14847117069752788, 0.23790121836449404, 1.1566231845587134, -0.41536480757569677, -0.16919643228479828, -1.9211594800832146, -0.35800738256721126, 2.0594349815016812, -0.3154762243047322, 2.1205212767905053, 0.21661875321153015, 1.2007764412811985, 0.6041437123783666, -0.2734707846275726, 0.09287221714743027, 0.951777886431126, 0.5723875779545984, 0.41391473344189467, 0.2866710589444781, -2.493192057810182, 0.4662699709696029 }, { 0.5777134508584179, -0.5191126417670997, -0.39307737100295187, 0.32352647874126544, 0.5726776539427924, 0.18854613223706282, -1.6609626153461512, 1.2858848379083372, 0.9469237926708421, -1.6126566483217692, 0.9753014755739655, -0.3342564176970907, 0.25549888551199024, 0.1781713865349134, 0.12653779009790744, -0.04549433685186687, -0.593732153514301, -1.8698111842792704, -0.6505380713993673, -1.6885098099151221, 0.37603929050721885, -0.8345899783244505, 1.3116777830399515, -0.1315509296756318, 2.0084547376009967, 0.6059183944431722, -0.7006133738973869, 0.2215217368642739, 0.20808863823842969, 0.006726377172991974, -0.16754029410411758, 0.28790664952921147, -0.14137935807646834, -0.2331524458143434, 0.5720665692949388, 0.9512903264082805, 0.8925066051464107, -1.5729461903742477, 0.6611902236370111, -1.1133360828655823, -1.1558523406940737, -1.464300560062819, 0.6486990466627172, 0.8869018415236215, -0.5048183564068304, -0.5308815979945182, -0.3759502375043379, 0.20165761762829837, -0.7718390608935541, -0.5535475104056661, -0.5404072404353932, -0.0564963118442956, 0.5227439529909028, 0.6765968814461931, 0.6428203801487145, -0.08449315378612543, 0.5686368497274472, 1.269097462609644, 1.891596226329703, -0.24113633866225953, 1.51252455047804, -1.1544938498559487, 0.6209443772933548, 0.6243585548374928, 0.2441684305880272, 1.9197388600414955, 1.5101310042133032, -0.32855633074891877, 0.8426464431093431, -0.5310367121365047, 1.7031488327402398, 0.6803759125033781, -1.4497696311192405, 1.4022850466412842, -0.1534165052796025, 0.2396216288564148, -1.7048127622616176, 0.7237993086181729, 0.5818750348652246, 0.3272846063594416, 2.5729699533283337, 1.092394657105337, 0.4865993106668523, 0.35770162681448975, 0.839148431149735, -0.21716181522581632, -0.9470294199285149, -0.4842955103112627, 2.1211125679375935, 1.2743450104002358, -0.9018266327237118, -0.6742662171185382, 0.04984065318113498, -0.47703874151618086, 0.4090528354818052, 2.128833463132692, -1.104399499530119, -0.5759303131887764, -0.6090244768146145, 1.2802585911952058 }, { -0.8603824903967677, 0.24341756422362942, -0.7207110119914911, 0.688784976660913, -0.746714714003956, -0.5694877346620838, 0.9240758326024664, 0.42746055969398317, -0.4529978537207179, 0.8151238210536257, -0.9930525661442867, 0.8210139367077368, 0.06843585488290525, 0.12628169460974029, 2.114946312307044, -0.7108078827772315, -0.335425214261384, 0.5724694408791396, -1.403533057014992, 1.1960353794208398, -0.37643670345727764, -2.225152235431099, 1.4991682163963964, -2.3785683917877862, 1.0370478778070071, 1.1160162790452162, 0.5265901355073898, -0.6347614323774023, 1.2014092915779466, 0.6901656765268035, 1.9135438594858556, 0.9390601295284825, -1.3666577661148436, 0.5743687574735632, 2.1384334310502386, -0.8947693097346873, 0.09105665670267307, 0.32041930360915893, 0.9519363731854388, -0.248649989585878, -1.1990605472332412, -0.7861078661911578, -0.1431926390281472, -1.0978411100657763, -0.0796279241819503, -0.20877417990161257, -0.002713464286530254, 1.5641339821633637, -1.4098579535398672, -0.27477386802935677, 0.9920380683143198, 1.9166845764561806, -0.9058771415634985, 0.9998038479389679, -0.38406308321209837, 0.678857689038219, 1.2816486998922447, 1.4744429770404668, 0.1898951242845705, -0.778904841889569, 0.947070982832206, 0.0735440455331129, 1.3043637328094897, 0.364470212212307, 0.2204757626748826, -1.6954634964443107, -0.14720176084601921, -0.23535958180997357, 0.9809718053351589, 0.33096695019245326, -0.6644098559090763, 0.6945067437375674, 1.5003943923978444, -1.0068462621961132, 0.5478670653533124, 1.1676659069437627, -1.6967136186966825, 0.5949623941169124, -0.051611279917776844, -0.19911889199335459, -1.3259374673796567, -1.2349295467993733, -1.0376495311937552, -0.848279033549494, -1.184505972541764, -0.05751735139191513, -0.4153367757505721, -0.6601593586553272, 1.589503038405418, -0.16627803410264055, -1.6194490359969465, -0.13429896991523257, 0.11891971849658374, -0.2025023741185703, 0.23809991482248796, -1.0556308228806424, -1.5778680606878603, 0.8048238474519366, -1.1706398402452143, 0.9057350317599364 }, { -0.32052642588330943, 0.014015630427259368, -0.7872814595584858, -1.0320494674590612, 0.6079391278687112, 0.06711919596690699, -1.1195736988895069, 0.5987228115722101, 1.946627410670744, -1.2309040542120573, -1.6016760503430227, -0.6400707494366356, -0.3769200830783895, -1.881147435097396, -0.364833660311179, 1.2394901472382438, -2.5822219767120433, 0.9385558335263279, -1.2444731794993122, -0.17029222973279046, 0.6269921808670073, 0.6237119678458634, 0.9860364205242188, 0.19780360205007655, -0.47219344766626015, -0.5606962447700163, -1.5673180767596235, -0.7954995048564861, -0.48300091225165315, 0.8140569727264538, 0.419278807098495, 1.013702648641696, -1.1516773597530263, 0.6245763606452769, 0.8114695051394201, 0.2539319859081602, -1.1136260062380825, 0.08723896130888954, -0.4252352985588666, -0.7703780295843813, -0.8005908645215533, 0.6558271476216921, 1.164000190361407, 0.37584520409402516, -2.3139061498864613, 0.008090430401473402, -1.5214934517222904, 1.085099318697313, -1.2995288560489866, -0.975602640246757, -1.1352020315059954, 0.6311708639757797, 0.18443456600419098, 0.9830832752397359, 0.11458988800970488, 0.5639982450853085, 0.4757408144779104, -0.7787333827124212, 0.1415604377078685, 0.5075617043278976, -0.9669891266702795, 0.055729374626876535, 0.8156917819749367, -1.6686325929640657, 0.10022014824476716, -0.03284362804759225, -0.9540563375783152, 0.4663961029082525, 0.8165676985695072, -1.6655876524606814, -0.5193742565666934, 0.021185171614799433, 0.5248182629993667, -0.8393886752515646, -1.029176044602788, -0.02057102573855834, 0.12461819137922958, 0.821547765022235, -0.8722329539031995, -0.30575335562301564, 0.18882595444532638, 1.0994485587681015, -0.9426260644614204, 0.16760528831621838, -0.3239578740002622, 0.2100363619788315, -0.2439890782759525, -1.0817274778821013, -0.736031642050373, 0.19600873499351631, 1.3187850933782534, 2.200433359276774, -0.800718980222107, -0.15595046215690442, -0.21274418386403118, 1.0550414813033842, 0.7048692123677627, -1.5633936611777302, -0.24097702634710816, 0.5544074767696807 }, { -0.4963821225633215, 0.25273823590779587, -0.5662611699355061, -1.4351076301626604, 1.5727543369521997, -0.7506181799438272, 0.13311377770499075, -0.16127737985308307, -0.6481408566108926, -0.8929040237718665, -0.28178865040767564, -1.8320546125322572, 0.5334606167410998, 1.0074027483815893, 0.9309738981628217, -0.9773055618428319, -0.7260115874357913, 1.048541605941504, -0.1404220734465099, -1.5916936297783382, 0.3945813760489362, -0.008092575630246896, -0.09421672249011982, -0.16326356176940165, 1.6803714050238034, 1.7578932956001991, 0.4043527991246496, -0.35352099457869224, 1.029430205600887, 0.30851758315283234, -0.7282070187946046, 0.3301863923758512, 2.625769014638022, -1.5593298867936973, -9.617149215920775e-05, 1.6210770708935722, -0.9683101899830961, -1.5778325384498009, -0.7147936716508372, 1.4746098318690724, -1.8284277610636617, -0.08798278697012904, -0.14203846294725717, -0.18191751180117813, 1.3928489477376786, 0.4102158211004136, -0.4338126575601065, 0.913876855606588, -2.099147669338375, -1.1955601829328215, -1.4031583677536585, 1.110791677109241, 1.24001560892114, -1.7827096318579896, 0.16236293759589615, -1.2428254887599448, -0.16963933508179477, -1.3572720613204745, 0.5599017905399861, -0.735232683578599, 0.4825405498748673, -0.6892640771787257, -0.8751805171556316, -0.09904085910169363, -0.3530817633578635, 0.038458128118578315, 0.8192724944956098, -0.29791387497881033, -0.2982856641323979, -1.0568757321691962, -1.702744325643868, -0.7240629456303459, -1.4384357380521113, -1.6764109618678866, -1.0395478021448894, -0.5438633888600009, 0.35277317071054987, 1.0897810277953779, 0.0384435666740488, 0.5580745537466728, 0.29725908131785506, -0.1773195593611974, -0.9085204716516203, 2.314056471083925, -0.4339036561674381, 1.1302135009452585, -1.013319697958156, 1.0501978491512216, 0.1771057854239862, -1.1387911534776063, 1.4884859009409979, 2.1829513638464273, 0.5301726912233747, -1.374675619349566, -1.6436380581233299, 1.7981919360309893, 1.0572822091985636, 0.055110257451533966, -1.7621345635739472, 1.1316188042775364 }, { 1.2096808909547216, 0.3865841106904163, -2.1149059951041447, 2.6172616385816783, -0.19542549849159022, -0.43842520021606246, 0.22763895409692256, -2.8216911804365634, 1.1282302957577677, -0.3503736184395924, 2.0067703482344403, -0.9007553457275508, -0.9984245946097869, 1.4358406867783902, 0.4561029516974969, 0.5682113860486041, 0.6285891087387011, -0.19906714528279124, 0.597897581790449, -0.22155784758738667, 0.834719474055897, -0.6797088278612645, 0.3891891919664451, -0.04516093680407816, -0.13744132082455965, 1.8600279199448644, 1.0886696196542898, 0.22462473796220153, 0.665164390086072, -0.9808805214666916, -2.378301585702668, 0.6322865086253191, -0.4495520026581664, -0.18991129391507175, -1.6337935083640451, 0.7350203765457541, -0.043617437067114344, 0.07197340611630768, -1.3599927149951372, 2.3060839174894183, 0.9072514621536818, -0.32255613517553494, 0.39230663515238623, -0.4190651175862964, -1.268906139098932, 2.912380450002187, -0.33867648300981956, -0.4911965112067554, -1.562469478191058, 0.6524456582599437, 1.7621077796149867, -0.6762877782588641, 0.0451566750028403, 0.766502303151452, -0.7042407123439298, 1.2044747262473807, -1.6231588260731458, 0.11978289974596712, -0.1415819375498652, -0.16775593915786222, 1.1693616340243, 0.4729462787586433, -0.30443890493375075, 1.6648881130552695, 1.2664698994174757, -1.1862993453339454, -0.46572914721932196, -0.6558630101183833, 1.0557258655518, -0.7844042240269484, -0.1576222954504636, 0.3923639185895749, 2.3343146873629217, -1.083459369052837, 0.6293878772395719, 2.41590268185876, 0.9813116941308822, -0.07931237792905528, 0.6790964104657448, 0.344452511474381, 0.08599323207504223, -0.15734605237993396, -1.6849022720346896, -0.8782666944529253, -0.15387233889994986, -0.8205920046019116, 1.4796888156331849, -0.5730577945037407, -0.9398722629312064, -0.6652759807788118, -0.6899714915712183, 0.34067933650012744, -0.8267034724642239, -0.21601377643225325, -1.2524676510635009, -0.09093227236879678, 0.5637245282992578, 0.5923512434443049, -0.5706265696373104, 0.03985480035689831 }, { -1.0213643150564344, -0.7077093375341552, 1.2677448282091763, -1.9690316200271885, -0.1684869270788572, -0.8937999420120641, 0.45710602944658, 1.0277869428808146, -2.197031824714255, 1.4259302830125873, 0.6671471553333966, 1.7784327461792242, -0.3315669021932324, -1.5269425246684214, -0.11284674178864307, 0.200392330917138, -0.23392479528395121, 0.000847845504163174, 0.3315419928466354, 0.5690928671850705, 0.40771150680965784, 0.5499489736749087, -1.4096415510122975, -0.9246041038555484, 0.6408561816145748, 0.3984310182699265, -2.6101755411483256, -1.64767093886752, -1.5099164113810044, 1.7919700566977819, -1.0589265913858656, 0.01189294497731182, -0.09892403595128649, -0.8098186892859396, 0.04920369687480899, 1.1523840041462714, 2.254844929531299, 0.8506488915769724, 1.2324111587446178, 0.0770542430008042, -0.6039418257642315, 0.6600163216958292, 0.9817198975625917, 0.26828911575611797, -0.3333413138733305, -0.07456073891528521, 0.5799525780582467, -0.6988532503328256, 0.14743170638405145, 0.41779273989784965, 0.12117584903359796, 1.9533499960604683, 1.2288467268280974, 0.07534262280015797, 0.12075111588683088, 0.8920463795031756, 1.1695097017421923, 1.1338556134473663, -0.7905571011154054, 1.1801952335121655, 0.6743963082317352, 2.049242328424867, 0.22203892869367856, -1.4795555763837018, 0.7733055767171565, -0.7207374678094026, -0.9766176166035073, -1.1331118597338665, -0.17701826747227253, 0.09902315873383925, -0.9695032635759974, 0.8110209612153687, 2.150094397467189, 0.43211557741513706, 1.7878315284482282, 0.3549479136066054, -0.923146558146134, 0.49434366868063107, -1.601674290705607, 0.9465075750101926, -0.4414044125407976, -0.7155940899299555, 0.8059056643414938, -0.6689655222332462, -0.31298242202142607, -1.2666647185051971, 2.9223187019061934, 0.23537680744023048, -0.7237562085303576, 0.9218384457865493, 1.3334151596433177, 2.5557072502459595, -1.1433045781666662, -0.029921406165362496, -2.0174308126533207, -0.8728415885096061, 0.8077031270750686, 0.8325680306824264, 0.7804081025452676, 1.4497967305822839 }, { 1.6790817474825157, -0.8476118372145044, -0.013972862322232738, 0.0022477541703211797, -1.769226761024657, -0.9528306994416562, 0.6867820873586565, -1.2858168391518259, 0.29202910366822943, -0.7528124034211668, -1.9341777236157487, -1.4980536013517791, 1.3219650161837138, 0.22419559605360795, -1.7251596432017071, -0.6402334523743592, -0.06890439211111006, -0.5340836479963117, -0.5506453661209813, -0.775941502647083, 0.22212572582170587, -1.6660212648512045, 0.1622499945115102, -0.14080086900721978, -0.254626605481279, 0.023704602100948026, 0.056235256748707614, 0.20442446588261218, -0.1218631735254164, 0.2572835495923687, 0.0965731298775608, -0.6771958633652719, -0.32481011109586194, 1.43510780923581, -0.41049588322704006, 0.24604062690196513, -1.4874594308169145, 0.21044668511115883, -0.9769034820751823, 1.1855441941619398, 0.2210404919112486, 0.48424423091528973, -1.713709414959977, 0.5831174721957082, 0.06141116737235621, -0.13575652071959188, -0.9128192705929258, -1.5655186802439274, 1.0275955840264062, -1.1001001181897776, 1.432787794319652, 0.026095995124150367, 0.6412197846277495, -0.16751737624753474, -0.5929347440928783, 1.1788233901753848, 0.3224671631145088, 0.7081912803889806, -0.512937770550562, -0.2541534285619086, 0.264243214035167, -0.6818785271788628, -2.7522268080449, 0.667234626739064, -0.35973095394460053, -0.7175497214843048, -0.7957909386824983, -1.036369857665617, -1.0189046525526813, 1.1300302618515137, 0.15748302574357786, -0.5393369892610423, 2.0785359909795944, -0.2736730223867336, 0.06130106078541003, -0.47831350350842905, 0.2813765493533417, 0.5210355105777529, -0.016181727364438545, 2.518669970149674, 0.5880258129342234, -1.340215214414744, -0.7529508536397467, -1.0873590267493258, -1.3026293402892424, -1.2453277751343117, -1.0798917056581026, -1.5807474313041496, 1.518923975143502, 0.905263125722708, 1.3460484805275705, 1.194458753495682, -0.9475372951077169, -0.032462696134654356, -1.2683798986405008, 0.18607533518488406, 0.9788981026252043, -0.03423803185817576, 1.2602417304020563, -0.06207629096421556 }, { 1.2621190656210834, -0.3474333598007753, -0.060347655827979255, 0.738275982301284, -1.074653972221543, 0.2588801619086689, 2.0958556488784024, 0.6311035489040773, -0.07463878241592434, 0.7000473867801554, 0.6307891862477114, 0.7316261211346499, -0.9937390191746367, -1.1221448073812108, 1.3023514874165105, 0.21351935978155798, -1.51125172675285, -0.4299666693658347, -0.020740240980986667, 1.124026130806446, -1.0262469401396512, 1.87537250288579, 1.4321952389465753, 0.29555831849829717, -0.1947252034560796, -0.3093235091111961, 1.738741177599107, 0.14498787583333014, -2.408589671078978, -1.2817421055315223, -1.481913963837002, -0.7857194492739092, -0.0037948497623813615, -0.12875022488078935, 1.0733430351073072, -0.566243175109869, 0.5413315485891246, -2.8951397669851433, -0.01178577032390541, -0.11036957287712479, 1.139213943498887, -0.3580895049481383, -1.8316894690704832, 0.391610882673137, 0.9005493064829846, 0.12853183489140385, -0.46089293180940766, -1.770495386387641, -1.4151234456298987, -0.8389344049233628, -0.17237723790595258, 0.5340592256715511, 0.12433609021302627, 1.9281234723864962, 0.033602057890890415, -1.012696716665257, -0.8806903984842515, -0.20550758304272917, -0.5240372776217319, 2.989596347044145, -0.13694221346809365, 0.21616985546375272, 0.4259197084380305, -0.10323300759337241, 0.7018565551129017, 2.265435222000944, -0.24046266634057512, 0.26604319157707085, -0.847744174576057, -2.8012908337953695, -0.8044509059315914, -0.1821711947159624, 0.5386834807895613, 0.5234378276312774, -1.235391494814571, -0.6028563864258912, 0.23688793275339634, 0.6836049309057372, 1.1813381968736358, 0.9128267937845747, -0.8094992179351388, 0.38748490651690554, 0.30964558622762334, -0.4980035136027024, -0.4025380964924924, -0.15161271838505047, 0.49557191205319456, 0.731188936783624, 1.4050432480605073, 1.4684153292982585, 1.5235357221633312, -0.04690948394036747, -1.738666070442788, 1.271598798688941, 0.2405781237046412, -1.320396310421733, -0.46884983781022405, -1.4731268041595753, -1.2066366796746637, 0.40298773311385333 }, { -0.08450696698206925, -0.7936447915881308, 0.20748430088201789, -0.00933133231559023, 0.21370622903484965, 0.2248313230836138, -0.20570204275137494, -0.01045123581916971, 0.8700042055479552, -0.17567676593068624, 1.4725043064635035, -1.4903927254568767, -0.23278543716825484, 0.9258298278593506, -1.0138261419444248, -0.7985707836574795, 0.45541345645922804, 0.07977373911783138, -1.1882825664102716, -0.1603908580769207, -0.14951052782287613, 0.5989102030769105, 0.0062537850754962356, 1.7644177709181612, -0.7467524381197183, 0.6416617208775423, 0.502671609600154, -2.166833388305844, 0.5180883321872263, -0.5353614872776982, -0.4512366248586104, -0.2587007935243621, -1.7233131137738058, 0.894448653587834, -0.32534818845709185, -0.9395963053615763, 0.5207786274303489, -0.08744567066224412, 0.7257281891182893, 0.6702564010043021, -0.984328582751476, 0.5603501525806283, 0.5834632748315884, -0.32209764399822294, 0.23852235439234742, -1.0554266466293196, -1.6221407903160001, -0.37130621882365633, 0.6528346689763799, 1.1148484036212902, -0.9404024527328233, -1.6495605162363896, 0.309034037724279, 1.3853411484536555, -0.7292387804574364, -1.5620444193874008, -0.9155230954710623, -0.6025566842279466, 1.8718868736154533, -0.9843902204265503, 0.053086537217756864, 1.4614642005893579, 1.078633664569656, 0.02936508082130974, 1.5328892717376408, -1.339329321200922, -0.1409018256075982, -1.7436753268940095, 0.630720434202698, 0.7021661307711144, 0.3672238355175033, -0.9598106636836263, -1.466060385773434, 0.5202886837439229, 0.020030777977788447, -0.9697235208702738, 0.3548798489504771, 0.7545522266349011, 0.2609633614461009, 1.2944800536737409, -0.7650423450283456, 0.08802982437975501, -1.6062497967824172, -0.9132687647044126, -0.027096921891841246, 0.9175835493212345, 0.4580198500938179, -1.147659738972888, 0.9315912133534038, 0.14007687423581497, 0.07464340799957858, 0.044992917869031764, 0.052215927140739624, -0.2077344262574845, -0.07745596310831362, 0.30998973008135167, 0.49922807426646293, -0.3083762395667019, -0.11673057112234253, 0.581387525454937 }, { 2.056659153155958, -0.897542103118255, 0.26892751628269174, 0.5626346722252391, -0.11971919602461677, -0.6625901578189521, 1.096346758731619, 0.07541068152742729, 0.8539045960204441, 0.26556655657165096, 1.3425603509145725, 0.5014017531135045, -1.438068528174004, -0.13833627845838795, 0.7736004396461722, -0.22098252013399305, 0.9082533896389186, -0.3590104221166061, -0.7583061158309711, -0.30739087713614155, 0.8884751716323638, 0.6217903707245287, 0.5880590383606051, 1.315719022822222, -0.22311141433684528, -1.857174758351857, -2.083747892731013, 1.2870876582870259, 1.1180013181999116, 1.733306674360591, -1.9615400865520563, 0.061511064367099064, -1.1046104248903197, 0.4542675536766193, 0.010196916097805014, -0.784485125225216, 0.5211453232076437, 2.6793684908534945, 1.4707352192216345, 0.5446990376280106, -0.6076170556198841, -0.8842483463757149, -0.4711693555453962, 1.664676299590766, -0.9665825195070681, -0.25515067476471387, -0.03154079357054912, -0.6672723515040168, 0.5915594863181303, -0.6250483429847133, -2.074365304550842, -1.6023855135061766, -0.4318653868475927, 0.17188077551491762, 0.39220152427553423, -0.6740601815868219, 0.06739871471600488, -0.5827545679923805, -0.5366279055083962, -0.08850649555001236, 0.7241115631696492, 0.3581334560054164, 1.6510181037268314, -1.5738740836623555, -0.01478283911188792, 0.7243169828153123, -0.542395090454386, 1.60392291253458, 0.12793554653835645, 0.527049891578202, -0.43532062112193076, -1.7149965756047405, 0.6943404379991043, -0.6741938166600668, -0.3344179957838603, -1.4357579756137606, -2.2702496956511333, 0.5539669058190562, 0.4180615525902767, 0.054758407373292746, -0.7512346614965767, -1.1216530223181285, -0.47329354549285385, 0.5878264886190551, 0.6710794014601988, 1.5787563639338869, 0.18017943179795534, -1.2327187976881535, 0.4764187871348821, 0.4174405430760545, 1.0850907617187955, -0.3932997285423594, -1.2129376369650964, -0.14377183373093294, -0.013691959690023247, -0.9521456642803452, -0.2691205380514488, -0.8663522045069018, -1.7959841664290255, 0.9219781947988865 }, { -0.3578381195054871, 0.3411156106303855, -0.42631246651197174, -0.11728174157618361, -1.1390675819584843, 0.6257934977643377, -0.07311487427687871, 2.0641658940154417, -0.9700703142304766, 1.8851923591788315, -1.576493922961707, -0.17192509328806393, 1.554094515554756, -0.702099634603212, -0.5358338340960276, 0.9901996201422381, 0.42274197870752167, -0.7719005055118565, -0.5290055653654653, -0.15032583319947546, -1.0257575525416762, 2.536872158269446, 1.39612614116553, -0.5077393986792766, 1.5134153826452292, 0.9172750779145623, -0.6830388943553033, -1.1396719987954953, 1.2620623821886832, 0.49076493686941586, -0.3598900028337642, 1.6143691204240178, 1.1442363057263225, 1.6358181429210554, 0.04161107631195436, 0.8768598800409682, -0.010556609508770874, -1.375290176010564, 1.0924055799221717, 1.6534798561148698, 0.2815823149679292, 0.06042395542377661, -1.1675759544902458, -0.23722190917825464, -0.8860129823388654, -0.959787207698042, 0.3351617002585376, -1.0124729651948594, 0.5274924367860602, 0.22390340933397432, 0.5373334186672339, 0.14014694264283872, -0.2667267987006351, -1.4154817383546598, -0.2505741676573826, -0.12561596629342692, -1.2306593233465757, 0.5289719465894865, -1.4295969251958514, -0.12163348066388933, 0.04179536625780968, -1.079118997522687, 0.8704477304858711, 1.5486852304614012, -0.23850440982281604, -0.6204985999209679, -0.6605478281957555, 1.3904410231608881, -0.1698545247276394, -0.5267109759537659, -0.28396851312169324, -0.3597745501743664, -1.6875432358533327, 0.6797149623205381, 1.316567675804255, 0.3958560652519254, -0.33214229627966046, -1.4611046077991, -0.06916621312191336, 0.010590906790424227, -0.07166164372372062, 0.16576568896358934, -1.056764567188837, -0.30306309111296825, -0.5705960371038334, -1.6124586328402692, -1.340196562483487, 1.7868856091430403, -0.050296874768032705, 0.8969222570100541, 1.5392724011614582, 0.1509533596095972, -0.2498144786942369, -1.5234284642112759, -0.7625660795816913, 0.7013200440182342, -0.013785675180243406, -0.1003326705170898, -0.23255996696378534, -0.44819563213104874 }, { -0.8600001039810757, -0.2217541098618083, 0.8182134106513242, 1.275324231769488, 0.18718816182465295, 2.366210981933168, 1.2225491356595994, -0.4015132606151716, 1.0922637008008165, -0.8247386765672512, -0.8513859597677959, -0.43612443192901007, -0.7009147346925401, -0.7999918493911853, -0.49359338144971304, 1.0778368507131793, 0.8101652577887264, 0.04850285199708388, 0.3309851877727071, -2.7334920427719305, 2.3453536978609395, -0.7736968616611716, 0.7895918067562282, 0.931493322851242, -0.9796081095389828, 0.3881745492052495, 3.302423385661058, -0.6304686833564966, -1.665659298286175, 1.255410400644897, 0.856747522882864, 2.1673459552972862, 0.3184676012129015, -1.6095846590402796, 0.7051765777597817, 1.4245923795129203, -2.66919053313733, 0.5224798300089807, -0.7165024020678531, 0.6325751808043198, -1.0101292909202784, 0.3710323364145385, 0.7653022495581538, -0.15266011413148942, 0.3745093873498504, -0.537568998431861, -1.6687540286545108, 0.11980571541974624, 1.2340141780153357, 1.202913769623372, 0.6111375049123404, 0.4094726522324029, 0.5340801468876006, 2.118161303293482, 0.8610998952800141, -0.2905872747226866, 1.3388089124306457, 0.9373779595628063, -0.8741102693058417, 0.13165203370196366, -0.7496819374470186, 0.6253521576574672, 0.07754228358934802, 0.024359234625515758, 2.11402754543284, 0.5171264864748337, 1.475823287076824, -0.3483663499208492, 0.6840689176766821, -0.03446905234498018, 1.0351623373578995, 1.1448839667949813, 0.35271749918100365, 0.1918317076303942, 1.2410314654615393, -1.0718223450585043, -0.571049797760258, -0.21328787838453325, -0.21465673128869814, 0.0785398911404803, 0.3323122590451256, -1.4400516935003635, -0.7550456917856824, 1.2924031649538417, 2.1987983829318276, 0.6903238960709172, -0.37319176580448193, 0.9344222111956373, 0.20160697772444763, 0.31804461485988017, 0.13009267717345713, 1.2182022670707904, 0.9756026792823378, -0.8111128517419887, 0.0985874483206428, 0.7271781258553296, -0.7299385998554432, -1.0775691827532745, 1.078813726801673, 0.3509869572122436 }, { 0.1835186463845854, -2.304579465727078, 0.0854563955714447, -0.9592328268034378, 0.45776861236436783, 0.4344720049661924, 0.5485049111325756, 0.6594088240218963, 1.0597774221088758, 0.7024601634400496, -1.045608822526576, 0.23587535234668064, -0.6110319040746274, -0.8300214134281432, 0.877453233191471, 0.5946771946702072, 1.4639499794023008, 0.31429933236347446, 0.5957530556545604, -1.085697803504388, 0.5223126891662067, -0.4144582662993713, -1.3292435730646213, -0.45933373732420313, 0.3038362285511924, -0.03830316399091625, -1.1182778334078747, -0.2662260018709619, 1.379437953273724, 1.873681027604768, 1.5547544560226256, 0.0942146697818402, 1.173904485168846, 1.6687535011141577, 0.1206207624047862, 0.5616515631128071, -1.819962407026388, -0.23083301281521054, -0.6473424533291884, -1.3637383386684128, -0.7932309459422675, 1.9009645965187745, 0.9959381235678008, 0.9982712581526261, 0.1888688624711014, -0.9630387748738439, 0.48828125906256004, 0.36130330235485497, 1.2677590217581047, 1.0225965404741875, 0.3001204991813368, 1.5454270693209808, -1.0080192103774277, -0.0030773090682687846, 0.4434717408763967, -1.518667497757524, 0.03698694704325669, 1.1330277779829447, -0.6120665005682058, 1.1349097915558093, 0.4982022211777723, 0.39411425825101476, -0.92259520661707, -0.7573078864848414, -0.8100836790794957, -2.3121256842155526, -2.7844237984466416, 0.4329310829188612, 1.9378098213560637, 1.0503797085149378, 0.3304737044689873, -0.11851970432064364, -2.0693302021355904, -1.117434817605979, -0.35992947582286433, 0.1109836453347228, 0.6916038439055038, 2.1349324856704786, 0.993953501299861, 0.7491792114879661, 1.0177323969292706, 0.029100875461091216, 0.5363879326031334, -0.5047314478596443, -2.594699659221376, -0.3792582630656641, 0.14029315922137522, -1.7654497366924988, 0.7554488928463763, -0.3495703224537293, -0.49432436559262044, 0.7383661741607511, -1.11848880136501, -1.6702920432003687, 0.8644006299002615, 1.2533880835073579, 1.2259126830124203, -1.6415017006911274, -0.8234440790714608, -0.01685310360797014 }, { -0.43402179215766995, -1.2022626805345373, 1.1813800695435097, -0.8482238103808111, 1.1652559200196702, -0.9547491162474954, 0.8522322064785327, 1.8601544575390998, -0.8056523931979609, 0.621569591136764, 1.3342619736798964, -0.6877058581257056, -0.09806838526877916, -1.358205573674985, 0.8611203251707968, -0.8026886039393627, -0.043001569823097455, 0.9698316053510007, 0.060456888535888355, 0.37560290417828696, -1.3184631546633627, -0.9513062512384739, -0.9742287960857795, 0.7267023769932568, -0.7311373551871643, 1.6144338981026864, 0.1615366499199391, 1.523420881803621, -0.09517800460654884, -0.16440872180846086, 0.5091425400330967, 1.3552181700785124, 0.7137685307816142, 0.8926508070441075, 0.516486844908131, -0.09557118051875993, -0.12190340128340385, -0.8271878908539927, -1.1115830647925953, -0.7437584320630177, 0.14578393904296535, 0.874817326977578, 0.12669342085379465, 1.9934900123119332, -1.9254362616353777, -1.5201606542700428, -0.533081768479679, -0.9505802681342531, -0.9149312513145348, -0.8970369266524275, 0.5138913313245205, -0.31159686239507617, 0.4320682985514547, 0.4931997887760304, 0.5475856127067232, 2.09873190438419, -0.5639536700801293, 0.5100098645766866, -0.02297950596767749, -0.10511607484214058, -2.8027999493862987, 2.914452285436796, -0.6021411311512282, -0.27601867480520664, 0.047730348573047254, 0.0632333098501988, 1.2215782493454315, -1.24699370671143, 0.42634418520555944, 0.31557172229948033, 3.9764229577794183, -0.6095588650477142, -0.21994380041290493, -1.7886116273087656, 0.981200468702635, -0.8611529869274795, -1.3836426691788093, 0.3868025286861422, 0.1743330417498122, -2.154409686992778, -0.8503654970214636, -2.2853240739874954, 0.24759336406347135, 0.7182398254665738, -0.7431351329899025, 0.036293664756191724, 0.13307728946208236, 0.7050449130481905, -0.6335974527059692, -1.5448933897877701, 1.6218279963575055, 0.64478264064944, -2.834653214787353, 1.7571486088531003, 1.0996215218753465, -0.44535004147286456, 0.23745882000328752, -0.2764827261772311, 0.4214242328345763, 0.27169947769575054 }, { 0.0723143856990206, -0.02069267069932383, -0.5051294606689419, 0.6376469031190886, -0.10229743100799707, -0.5172636994420001, -2.156142788805475, 0.8926364266809378, 1.0704216794816013, -1.182900826833835, 0.6922367627835768, 0.14982368413028058, -0.9789833660632571, -0.18223222648661958, 0.5262179726722146, 0.9358877578556513, 0.5550927004712566, -0.4310570137408539, -0.05905353589784172, -3.128052551852183, 1.3985279817021397, -0.5046633073904174, -0.17987749069401462, -0.8250020335138498, -0.11715016849098538, -1.5009715933743029, 1.3961164944812807, -2.25968011107512, -0.926950501451529, 1.657163459739028, 0.3689111720053029, -1.3060808905225858, -2.1608087418587103, -1.3600838083216642, -0.09042391709831117, 0.9509396041322911, -1.1222065338671467, -0.5474531747429262, -1.9465490034148487, 0.3165296982630501, 0.29380280969875866, 0.05683189814209038, 0.9435123697934017, -0.32764717232116247, 0.5403186658468895, -0.28788847779777116, -0.41599376230845037, -1.0481439634845175, -1.6751397924433453, -0.3589934233330177, 0.2558855340046302, -0.9750303921779984, -0.42349325079652106, 0.38248964972385663, 1.567229268931477, 1.9851379894107173, -0.049646239547708255, -0.4548039382881989, 0.5342641763783902, 2.2712581927099014, -1.3204211592305497, 0.16491905418643066, 1.252611683179527, 0.02203517822314502, 0.4843270202120351, -0.19782484935688951, 0.7814458725064569, 1.9893288090218062, -0.7134934243796238, 0.20762885649820953, 0.4236011123737128, 0.3720312865538448, 1.1322592858496117, -0.5852259675957106, -0.7168106579618828, -0.8841785334407415, -0.60771614997114, 0.21548070624671156, 0.7547247721423913, -0.32772439090965566, -0.8345317375509023, -1.029592625504747, -1.2986447228488094, -1.6051918674841095, -0.7158517840787266, 0.13168467345570203, 1.3648442273574952, 0.24953817027766637, 1.3330811475585767, -0.2322060067736688, -0.11227875762954875, -0.9694303674444206, 1.9120075474059623, -0.22863004885316196, -1.211962136894731, 0.004308948358311879, 0.9303988505331233, 0.8538549084288432, -0.6509487146417271, 0.05127659959363924 }, { 0.7228998304034141, -0.5260570668155637, -0.20326233960659823, 0.001719037157521093, 0.27002190364357354, 0.4360233718517596, -0.8848315285504244, 0.23814818729004725, -0.539302485019225, 0.08714369129198542, 0.9639614740312772, -1.4140885633757012, -0.9271211687212061, -0.8045799829326755, 1.5534421557849714, 0.3090534183070598, -0.0029612153397468696, -1.5436401312000307, 0.780256352318789, 0.43544699084132327, -0.6472500590292026, -0.9482388186243279, -1.1082507283907583, 0.38010794615312576, -0.060617173973973336, 0.08315393965619164, 0.1681073361671535, 1.0147896426825267, 1.0222423409716397, -0.29289931732292546, -0.6183145709636859, 0.4901177593583503, -0.8260062407675888, -0.9927341986706184, -0.6836361414163139, 0.9175704526469516, 0.5406708660627032, -0.3328282292457956, -0.9911372902873472, -0.19378146675149294, 1.6669856622783608, -0.5405962142392532, -0.2122234655315312, 0.29349580918492907, 0.8917370173841276, 0.5159696144833439, 1.2583566820972496, -0.8009615349408227, 1.5826898169772574, 0.9755509765875247, 0.9153872840822571, -1.2479415399441545, 2.617014671923157, -0.5205502784880056, 0.48666024360543847, 0.1214618257592761, -0.21103050139975743, 0.4423187475294355, -1.9443515527816235, 0.21112511923351365, 1.8278570189145837, -0.5165875593551311, 0.7219430043674174, -1.7514323874048998, -0.23822972844241505, -0.31956635983562726, -0.6306429240066235, -0.5469459760213657, -0.34965868515051246, -0.5874075219088194, -0.5163186851314968, -2.2448734423329717, -1.2642796880407265, -0.703530178057231, 1.0603674041541769, 0.41674286306762726, -0.137813660948031, -0.9023148194356945, 0.43052620765616273, 0.7528884123320732, 1.056583893445835, -0.06718980656788584, -1.664229826163415, 0.41162707922936004, -0.046243201756082895, -0.6257666950630579, 0.9792024182480213, 0.2636014562517827, 1.303808053717355, -0.470671472089499, 0.041262374065768256, 0.7288145380640063, 1.6983374332198768, -0.4684203759835061, 0.5829877545090271, -1.7708190941499808, 0.5081355282502482, 0.09791523741654545, 0.864696608376361, 1.220254139715563 }, { 0.44011111326112634, -0.671056357601337, 1.4285246682208486, -0.975812190259969, -1.3772180163804053, 0.8082406882505451, 0.8244841092005082, -1.104188264698124, 1.3538171212424261, 0.733213730236543, -0.3229242385162422, 0.05585617527127051, 0.6850332998704365, -0.04638228174219358, 0.006929541855696499, 0.9465242775190894, -0.726556484661113, 1.1006632049302374, -0.8907070942025165, 0.011234783007924062, -1.1363886335878592, -2.0141302040853226, 1.625287509446744, -0.9989944575321646, -1.2182352651863348, -0.7533378726378422, -1.400491313078739, 0.03791289315313609, 0.8414898858796809, 1.6651773003587378, 0.2411147947466978, 0.6633771146612322, -0.5397507425555766, -1.7680997914308425, -0.4927529681719123, 1.3751899143690551, 0.4231028800480095, 0.7125862011845311, -1.1436958140589355, -0.24430521036022312, -1.4349567295694268, -1.9265952814456877, -0.5410346419996819, 0.7891945795189854, 2.5284398382949673, -0.46735246675499825, -0.3574933508851164, -0.4162162876061722, 0.6362061220697144, 0.3721842635105366, 1.11776220151122, -1.4011217555090467, 0.13885399442094767, 0.9390465134224008, -1.3670859251955358, 0.9234559251323446, 1.5329439505824023, -1.1793379066135334, -0.3651686974408722, -0.34823476356569266, 0.008892113598604829, 1.3245317034396096, -1.935530146663683, -1.3040170336969015, -0.7282615292209176, 1.1312377879671325, 0.39965755441799067, 1.2231550005190703, 0.3791148651250689, 1.4059833416367757, 0.8147299259516954, -0.6081621382311619, -1.7841438731130486, 0.8071078936626502, -0.32677132412184023, -0.37978276806701233, 0.6843759636913519, -0.991394909235565, 1.7581740397609251, -1.1990154890397682, -1.2498832607309216, -1.3188493192550859, -0.7740163122240292, 0.31813783124876577, -0.23844978265485656, 0.2248986521362337, -1.2904216006791396, -1.2418612522296315, -0.8312181190201454, 1.4130131530785608, -1.5093494420546982, -1.141292749554278, -1.7421943535696425, -0.6452455170992683, -0.7171617664983058, -1.4422860526960608, -0.35783904836780284, -0.23214175978462545, -0.7930045871038665, 0.07876181242753888 }, { 1.4571999251243943, 0.21676605787807776, -0.838589015414262, -0.7473784012583318, 1.1667979346125072, 1.992395413454694, -1.5808567490522076, -0.8876003970083411, -0.3836463999316619, 2.4086983285231485, -1.1093831706533943, -0.38616846234702973, -1.0611592291685525, 1.0149475994246853, 0.39854152563269746, -0.20690660642588762, 0.7647334852071475, 2.4784354136408373, -0.3540969991453984, -0.4048607672269444, 0.2469979029485283, -0.16605075556412136, -0.2828939092349784, 0.4616591137578472, 1.2880270079364793, -0.5086521580938796, -1.0159491337530115, 1.5925889073470478, -0.8046494327691066, 0.08948193306627472, 0.7993633180188738, -0.35396609245825805, -0.2023289849707361, 0.3363367634031988, 0.05727995495607487, 0.5814778573839984, 0.32641893044821796, 0.19774792541786465, -0.6866289710518995, 0.7064023024606123, -0.257253490755629, -0.9749024964798427, -1.081935002550611, 2.00981876791672, -0.6572579309456213, -0.5604320034473044, 0.7030496697084702, -0.4146698263765147, -0.34759953823670936, -2.375662244656454, 0.5606985951020999, -0.7767402867453991, 1.068668318048301, -0.41045378390114734, -0.4880611420192788, 0.4276742412528555, -0.8203776766217897, -1.1300262705484643, 1.6473763479499919, -0.3108339396883555, 0.8710956729026854, 0.5766617673758224, -0.20862325960939537, 1.4640077020708853, 0.2225463176807338, 0.3129992764096173, -0.2904803006908261, 1.1069259267256204, -0.04030596569218826, 0.11068783307433734, 0.7197742673142024, -0.9546562656252064, 0.11063276048779566, 1.0710852521274465, -0.2711998876188699, 0.3845611693793841, -1.0112901028656165, -0.534070223945409, 0.11431519520838536, -0.595801330668271, 0.5768243195588467, 2.4191041523474195, 1.12946096283399, -0.9131788157689282, 0.4150470765405016, -1.4143683008451737, -0.9555553695792222, 0.014566080923397147, 0.2616123764644281, 0.31764830851623777, 0.9228974112157644, -0.06250144461987162, -1.7917736991715292, -1.0358748927301749, 0.47350987897162383, 0.5164461547628265, 0.011922659197635906, 1.1082168514144142, -0.30310338243370677, -1.3704798065802524 }, { -1.2678712209867766, 0.44671924126641055, 1.319052590932086, -1.0777922104069178, -1.497891915040608, 0.5118708661590234, 1.0553461822407526, -0.9130895589146282, 0.8165814814001561, 0.9069980968563993, 0.8951020023546248, -0.09469473155308554, 0.7330279375354769, 0.8767452156794496, 0.6144505387686183, 0.0967449624074513, 1.5815413107192335, -0.672439948892021, -0.17439557186145035, -1.0258064931524689, -0.7862372504227012, 0.8997610152806942, -1.144773020380193, 0.6999678434164447, 0.14520623877090036, -1.9489407887167591, -1.4708328029766353, -1.4243507798543118, 0.4269765523739046, 2.1485926319508337, 1.709739984655543, 0.532209465069058, -0.219349331060029, 0.7014162865195237, 1.3267475825434885, 0.8225402692956437, -1.1218167353824682, 0.10201666991001211, 0.6705050706368214, 0.41196674683921974, -1.7123027042151333, -1.5740357600872281, 0.23799064979014117, 0.03871268203341901, 0.28152903534190477, -0.18733608325895434, 0.5049850775155297, 0.8241242926333195, -0.5701151597105298, -0.1875314250765816, 0.6887768222299981, 0.5046892278312088, 1.1490425037792134, 0.0015816041204044422, 0.2439555930898157, 0.00784353550046139, 0.4490543675498789, 0.24979353661152362, 0.18326124834926713, -0.9820825654556917, -1.148404136037371, -0.6771405762749413, -1.284578693829332, -0.7611441570995022, 0.32719933533759565, 0.777358113614427, -0.7345395163334633, -1.5833204420707574, -1.5695215267423552, -0.6884958561806588, 0.0984094338266941, 0.06859821913415322, -0.6932978668884219, 0.28912839064085527, 1.742824037045857, 0.2360145054383539, 0.11831498277565781, 0.3815212022343498, 0.6882839866082388, 1.7539056934946298, 0.09178886699607128, -1.292634964857941, -0.14840122723859764, -0.9644122015295955, 0.09453847140571678, -0.29816534724154986, -0.5504717791418197, -1.356569845779204, -0.10826327780064719, -0.5401272873035792, -1.2808061745255601, -0.4903811339228011, 0.6167296208003669, 0.0978637168212704, -0.572115540545848, 0.480830595001396, -0.7882415102218178, -0.06452571783516405, -0.33473964628988523, 0.3429989921140878 }, { 1.008404476310951, -0.9508935672402672, 0.291993613104117, 1.670927089552435, 0.3928388355825836, -0.18722261489927725, -0.7051913326628592, 0.9345774254716126, 0.8037679440680124, 0.6008116937038641, 0.9567405573635612, 0.4216882973170257, 0.2966329388539434, -1.9079776035767597, -0.40306224069204966, 0.11724716882794144, 0.6761804068245167, 1.0978825983775917, 1.0387824703914883, -0.12704048004071272, 0.7267781109547563, -0.991391707983483, -0.8564097200157075, -0.6550736725587594, -0.7025036800087415, -1.2495409208803328, 0.3494158747839881, 0.2367724290863154, -0.14490823792584728, 1.3057492643430275, -0.9675784633481913, 1.1271871590114204, -1.7206740883924276, 0.9908381150754164, -0.16104490427296092, 1.070088205789964, 1.1352549387252504, -0.4013417111980933, 0.9311081946187121, 0.7323942062420845, -1.9215804094971576, 1.4964566535823185, 0.1875901783233878, 0.8174124373228862, 0.36596290608041254, 0.8436828957649024, -1.9489722219040737, 0.36860794553175896, -0.5427918958620014, -1.3157115383923255, -1.3156332352170856, 1.058171013210782, -0.0867360316949045, -0.7157387078725475, 1.8207530511515095, -1.7516253433919915, 0.6030337587390456, -0.5048346440293533, -0.7528135009116936, -0.050316833668158624, -0.5213253200352531, -0.45810323508021167, 1.6998893753270106, 0.6429642863228179, 1.0831079837281372, 0.8222812037947991, -2.5665062657480977, -1.4285817946055637, 0.06129702661697322, -0.5387631944075266, -0.4786555924059382, 1.2320930534930068, 0.9905487636276048, -1.9001775986599596, -1.0950674272441343, -0.2543842002580888, -0.8148060664558938, -0.985104768416336, 1.2871465673488465, 1.9172560396556215, 1.8302433276613608, 0.17933865710548139, 0.4931714251821265, 0.5622815503608488, -0.24894790224859287, 0.7169830756754006, -0.20795738980991837, 0.5014356702225439, -1.1082675388202876, -0.43136727436332717, -2.9539110781648725, 1.1899325389869864, -0.3095495631506292, 1.6359734751574904, -1.1850456651959491, 0.6610814484957174, -1.0404259064095096, 1.6484754725778463, 0.6232385849324242, 0.6635392845773066 }, }; std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Estimator" }; return lOutputs; } tTable compute_regression(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { std::vector<std::any> inputs = { Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99 }; std::any lDotProduct = rbf_kernel( lProblem_data_dual, lProblem_data_sv, inputs, 0.010248801918082818 ) + -4.37816536353874; tTable lTable; std::any lEstimator = lDotProduct; lTable[ "Estimator" ] = { lEstimator }; return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_regression(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace int main() { score_csv_file("outputs/ml2cpp-demo/datasets/RandomReg_100.csv"); return 0; }
1,182.405405
2,827
0.820579
[ "vector", "model" ]
2240ee96a4d5ce98448488690c3e7824791ccfc6
16,285
cpp
C++
gazeboSimulation/gazebo_rsv_balance_original.cpp
corno93/self-balancing-robot-using-RL
24a52e141f20aee0279a4c0a47a4ca738612cc08
[ "MIT" ]
1
2020-11-07T09:14:08.000Z
2020-11-07T09:14:08.000Z
gazeboSimulation/gazebo_rsv_balance_original.cpp
Avinashshah099/self-balancing-robot-using-RL
24a52e141f20aee0279a4c0a47a4ca738612cc08
[ "MIT" ]
null
null
null
gazeboSimulation/gazebo_rsv_balance_original.cpp
Avinashshah099/self-balancing-robot-using-RL
24a52e141f20aee0279a4c0a47a4ca738612cc08
[ "MIT" ]
1
2021-03-06T04:49:52.000Z
2021-03-06T04:49:52.000Z
/********************************************************************* * Copyright (c) 2015 Robosavvy Ltd. * Author: Vitor Matos * * Based on diff_drive_plugin *********************************************************************/ #include "gazebo_rsv_balance/gazebo_rsv_balance.h" #include <string> #include <map> #include <ros/ros.h> #include <sdf/sdf.hh> namespace gazebo { GazeboRsvBalance::GazeboRsvBalance() {} GazeboRsvBalance::~GazeboRsvBalance() {} void GazeboRsvBalance::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { this->parent_ = _parent; this->sdf_ = _sdf; this->gazebo_ros_ = GazeboRosPtr(new GazeboRos(_parent, _sdf, "RsvBalancePlugin")); this->gazebo_ros_->isInitialized(); // Obtain parameters from rosparam this->gazebo_ros_->getParameter<bool>(this->publish_odom_tf_, "publishOdomTF", true); this->gazebo_ros_->getParameter<bool>(this->publish_wheel_joint_, "publishWheelJointState", true); this->gazebo_ros_->getParameter<std::string>(this->command_topic_, "commandTopic", "cmd_vel"); this->gazebo_ros_->getParameter<std::string>(this->odom_topic_, "odomTopic", "odom"); this->gazebo_ros_->getParameter<std::string>(this->base_frame_id_, "baseFrameId", "base_link"); this->gazebo_ros_->getParameter<std::string>(this->odom_frame_id_, "odomFrameId", "odom"); this->gazebo_ros_->getParameter<bool>(this->publish_state_, "publishState", true); this->gazebo_ros_->getParameter<double>(this->update_rate_, "updateRate", 50.0); this->gazebo_ros_->getParameter<double>(this->publish_state_rate_, "publishStateRate", 50); this->gazebo_ros_->getParameter<double>(this->publish_diagnostics_rate_, "publishDiagnosticsRate", 1); std::map<std::string, OdomSource> odom_options; odom_options["encoder"] = ENCODER; odom_options["world"] = WORLD; this->gazebo_ros_->getParameter<OdomSource>(this->odom_source_, "odomSource", odom_options, WORLD); this->mode_map_["park"] = PARK; this->mode_map_["tractor"] = TRACTOR; this->mode_map_["balance"] = BALANCE; this->gazebo_ros_->getParameter<Mode>(this->current_mode_, "startMode", this->mode_map_, BALANCE); if (!this->sdf_->HasElement("wheelSeparation") || !this->sdf_->HasElement("wheelRadius") ) { ROS_ERROR("RsvBalancePlugin - Missing <wheelSeparation> or <wheelDiameter>, Aborting"); return; } else { this->gazebo_ros_->getParameter<double>(this->wheel_separation_, "wheelSeparation"); this->gazebo_ros_->getParameter<double>(this->wheel_radius_, "wheelRadius"); } this->joints_.resize(2); this->joints_[LEFT] = this->gazebo_ros_->getJoint(this->parent_, "leftJoint", "left_joint"); this->joints_[RIGHT] = this->gazebo_ros_->getJoint(this->parent_, "rightJoint", "right_joint"); // Control loop timing if (this->update_rate_ > 0.0) { this->update_period_ = 1.0 / this->update_rate_; } else { ROS_WARN("RsvBalancePlugin - Update rate < 0. Update period set to: 0.1. "); this->update_period_ = 0.1; } this->last_update_time_ = this->parent_->GetWorld()->GetSimTime(); // Command velocity subscriber ros::SubscribeOptions so = ros::SubscribeOptions::create<geometry_msgs::Twist>(this->command_topic_, 5, boost::bind(&GazeboRsvBalance::cmdVelCallback, this, _1), ros::VoidPtr(), &this->queue_); this->cmd_vel_subscriber_ = this->gazebo_ros_->node()->subscribe(so); ROS_INFO("%s: Subscribed to %s!", this->gazebo_ros_->info(), this->command_topic_.c_str()); // Tilt equilibrium subscriber so = ros::SubscribeOptions::create<std_msgs::Float64>("tilt_equilibrium", 5, boost::bind(&GazeboRsvBalance::cmdTiltCallback, this, _1), ros::VoidPtr(), &this->queue_); this->cmd_tilt_subscriber_ = this->gazebo_ros_->node()->subscribe(so); ROS_INFO("%s: Subscribed to %s!", this->gazebo_ros_->info(), "tilt_equilibrium"); // Odometry publisher this->odometry_publisher_ = this->gazebo_ros_->node()->advertise<nav_msgs::Odometry>(this->odom_topic_, 10); ROS_INFO("%s: Advertise odom on %s !", this->gazebo_ros_->info(), this->odom_topic_.c_str()); // State publisher this->state_publisher_ = this->gazebo_ros_->node()->advertise<rsv_balance_msgs::State>("state", 10); ROS_INFO("%s: Advertise system state on %s !", this->gazebo_ros_->info(), "state"); // Joint state publisher this->joint_state_publisher_ = this->gazebo_ros_->node()->advertise<sensor_msgs::JointState>("joint_states", 10); ROS_INFO("%s: Advertise joint_states!", gazebo_ros_->info()); // Service for changing operating mode ros::AdvertiseServiceOptions ao = ros::AdvertiseServiceOptions::create<rsv_balance_msgs::SetMode>("set_mode", boost::bind(&GazeboRsvBalance::setMode, this, _1), ros::VoidPtr(), &this->queue_); this->set_mode_server_ = this->gazebo_ros_->node()->advertiseService(ao); // Service for chaning input source ao = ros::AdvertiseServiceOptions::create<rsv_balance_msgs::SetInput>("set_input", boost::bind(&GazeboRsvBalance::setInput, this, _1), ros::VoidPtr(), &this->queue_); this->set_input_server_ = this->gazebo_ros_->node()->advertiseService(ao); // Reset override service ao = ros::AdvertiseServiceOptions::create<std_srvs::Empty>("reset_override", boost::bind(&GazeboRsvBalance::resetOverride, this, _1), ros::VoidPtr(), &this->queue_); this->reset_override_server_ = this->gazebo_ros_->node()->advertiseService(ao); // Reset odom service ao = ros::AdvertiseServiceOptions::create<std_srvs::Empty>("reset_odom", boost::bind(&GazeboRsvBalance::resetOdom, this, _1), ros::VoidPtr(), &this->queue_); this->reset_odom_server_ = this->gazebo_ros_->node()->advertiseService(ao); // Broadcaster for TF this->transform_broadcaster_ = boost::shared_ptr<tf::TransformBroadcaster>(new tf::TransformBroadcaster()); this->resetVariables(); this->state_control_.resetControl(); this->x_desired_ = 0; this->rot_desired_ = 0; this->tilt_desired_ = 0; this->u_control_ = this->state_control_.getControl(); this->alive_ = true; // start custom queue this->callback_queue_thread_ = boost::thread(boost::bind(&GazeboRsvBalance::QueueThread, this)); // listen to the update event (broadcast every simulation iteration) this->update_connection_ = event::Events::ConnectWorldUpdateBegin(boost::bind(&GazeboRsvBalance::UpdateChild, this)); } /*! * \brief Resets simulation variables. * * Used when starting and when gazebo reset world or model */ void GazeboRsvBalance::resetVariables() { this->x_desired_ = 0; this->rot_desired_ = 0; this->odom_offset_pos_ = math::Vector3(0, 0, 0); this->odom_offset_rot_ = math::Vector3(0, 0, 0); } /*! * \brief Sets platform operating mode. */ bool GazeboRsvBalance::setMode(rsv_balance_msgs::SetMode::Request &req) { // Ugly implementation means bad concept switch (req.mode) { case rsv_balance_msgs::SetModeRequest::PARK: ROS_INFO("%s: Mode: park", this->gazebo_ros_->info()); this->current_mode_ = PARK; break; case rsv_balance_msgs::SetModeRequest::TRACTOR: ROS_INFO("%s: Mode: tractor", this->gazebo_ros_->info()); this->current_mode_ = TRACTOR; break; case rsv_balance_msgs::SetModeRequest::BALANCE: ROS_INFO("%s: Mode: balance", this->gazebo_ros_->info()); this->current_mode_ = BALANCE; break; default: return false; }; return true; } /*! * \brief Just exposes service. Not used in simulation */ bool GazeboRsvBalance::setInput(rsv_balance_msgs::SetInput::Request &req) { // In simulation input should always be serial communication. ROS_INFO("%s: Input: %d", this->gazebo_ros_->info(), req.input); return true; } /*! * \brief Just exposes service. Not used in simulation */ bool GazeboRsvBalance::resetOverride(std_srvs::Empty::Request &req) { // In simulation we don't have RC override, nothing to reset ROS_INFO("%s: Reset Override", this->gazebo_ros_->info()); return true; } /*! * \brief Service to reset odometry. */ bool GazeboRsvBalance::resetOdom(std_srvs::Empty::Request &req) { ROS_INFO("%s: Reset Odom", this->gazebo_ros_->info()); this->resetOdometry(); return true; } /*! * \brief Callback to cmd_vel */ void GazeboRsvBalance::cmdVelCallback(const geometry_msgs::Twist::ConstPtr& cmd_msg) { this->x_desired_ = cmd_msg->linear.x; this->rot_desired_ = cmd_msg->angular.z; } /*! * \brief Callback to cmd_tilt */ void GazeboRsvBalance::cmdTiltCallback(const std_msgs::Float64::ConstPtr& cmd_tilt) { this->tilt_desired_ = cmd_tilt->data; } /*! * \brief Gets pitch angle values directly from Gazebo world */ void GazeboRsvBalance::updateIMU() { // Store pitch and dpitch math::Pose pose = this->parent_->GetWorldPose(); math::Vector3 veul = this->parent_->GetRelativeAngularVel(); this->imu_pitch_ = pose.rot.GetPitch(); this->imu_dpitch_ = veul.y; } /*! * \brief Resets odometry by adding offset to WORLD odometry, and resetting odometry values. */ /** @todo Actually implement it */ void GazeboRsvBalance::resetOdometry() { math::Pose pose = this->parent_->GetWorldPose(); this->odom_offset_pos_ = pose.pos; this->odom_offset_rot_.z = pose.rot.GetYaw(); } /*! * \brief Updates odometry, from Gazebo world or from encoders. */ /** @todo Implement encoder odometry */ void GazeboRsvBalance::updateOdometry() { double ang_velocity_left = -this->joints_[LEFT]->GetVelocity(0); double ang_velocity_right = this->joints_[RIGHT]->GetVelocity(0); this->feedback_v_ = this->wheel_radius_/2.0 * (ang_velocity_right + ang_velocity_left); this->feedback_w_ = this->wheel_radius_/this->wheel_separation_ * (ang_velocity_right - ang_velocity_left); if (odom_source_ == WORLD) { math::Pose pose = this->parent_->GetWorldPose(); math::Vector3 velocity_linear = this->parent_->GetRelativeLinearVel(); math::Vector3 velocity_angular = this->parent_->GetRelativeAngularVel(); // TODO(vmatos): reset odometry by setting an offset in world // this->odom_.pose.pose.position.x = pose.pos[0] - this->odom_offset_pos_[0]; // this->odom_.pose.pose.position.y = pose.pos[1] - this->odom_offset_pos_[1]; // this->odom_.pose.pose.position.z = pose.pos[2] - this->odom_offset_pos_[2]; this->odom_.pose.pose.position.x = pose.pos[0]; this->odom_.pose.pose.position.y = pose.pos[1]; this->odom_.pose.pose.position.z = pose.pos[2]; // tf::Quaternion qt; // qt.setRPY(pose.rot.GetRoll(), pose.rot.GetPitch(), pose.rot.GetYaw() - this->odom_offset_rot_[2]); // qt.setRPY(pose.rot.GetRoll(), pose.rot.GetPitch(), pose.rot.GetYaw()); this->odom_.pose.pose.orientation.x = pose.rot.x; this->odom_.pose.pose.orientation.y = pose.rot.y; this->odom_.pose.pose.orientation.z = pose.rot.z; this->odom_.pose.pose.orientation.w = pose.rot.w; this->odom_.twist.twist.linear.x = velocity_linear[0]; this->odom_.twist.twist.linear.y = velocity_linear[1]; this->odom_.twist.twist.angular.z = velocity_angular.z; } else { ROS_WARN("%s - Odometry from other sources not yet supported.", this->gazebo_ros_->info()); } } /*! * \brief Publishes odometry and desired tfs */ /** @todo User configurable covariance */ void GazeboRsvBalance::publishOdometry() { ros::Time current_time = ros::Time::now(); std::string odom_frame = this->gazebo_ros_->resolveTF(this->odom_frame_id_); std::string base_frame = this->gazebo_ros_->resolveTF(this->base_frame_id_); // set odometry covariance this->odom_.pose.covariance[0] = 0.00001; this->odom_.pose.covariance[7] = 0.00001; this->odom_.pose.covariance[14] = 1000000000000.0; this->odom_.pose.covariance[21] = 1000000000000.0; this->odom_.pose.covariance[28] = 1000000000000.0; this->odom_.pose.covariance[35] = 0.001; // set header this->odom_.header.stamp = current_time; this->odom_.header.frame_id = odom_frame; this->odom_.child_frame_id = base_frame; // Publish odometry this->odometry_publisher_.publish(this->odom_); if (this->publish_odom_tf_) { tf::Vector3 vt; tf::Quaternion qt; vt = tf::Vector3(this->odom_.pose.pose.position.x, this->odom_.pose.pose.position.y, this->odom_.pose.pose.position.z); qt = tf::Quaternion(this->odom_.pose.pose.orientation.x, this->odom_.pose.pose.orientation.y, this->odom_.pose.pose.orientation.z, this->odom_.pose.pose.orientation.w); tf::Transform base_to_odom(qt, vt); this->transform_broadcaster_->sendTransform( tf::StampedTransform(base_to_odom, current_time, odom_frame, base_frame)); } } /*! * \brief Publishes wheel joint_states */ void GazeboRsvBalance::publishWheelJointState() { ros::Time current_time = ros::Time::now(); sensor_msgs::JointState joint_state; joint_state.header.stamp = current_time; joint_state.name.resize(joints_.size()); joint_state.position.resize(joints_.size()); for (int i = 0; i < 2; i++) { physics::JointPtr joint = this->joints_[i]; math::Angle angle = joint->GetAngle(0); joint_state.name[i] = joint->GetName(); joint_state.position[i] = angle.Radian(); } this->joint_state_publisher_.publish(joint_state); } /*! * \brief Called when Gazebo resets world */ void GazeboRsvBalance::Reset() { this->resetVariables(); this->state_control_.resetControl(); // Reset control this->last_update_time_ = this->parent_->GetWorld()->GetSimTime(); this->current_mode_ = BALANCE; this->imu_pitch_ = 0; this->imu_dpitch_ = 0; this->feedback_v_ = 0; this->feedback_w_ = 0; } /*! * \brief Gazebo step update */ void GazeboRsvBalance::UpdateChild() { common::Time current_time = this->parent_->GetWorld()->GetSimTime(); double seconds_since_last_update = (current_time - this->last_update_time_).Double(); // Only execute control loop on specified rate if (seconds_since_last_update >= this->update_period_) { if (fabs(this->imu_pitch_) > .9 && this->current_mode_ == BALANCE) { this->current_mode_ = TRACTOR; } this->updateIMU(); this->updateOdometry(); this->publishOdometry(); this->publishWheelJointState(); double x_desired[4]; x_desired[balance_control::theta] = tilt_desired_; x_desired[balance_control::dx] = x_desired_; x_desired[balance_control::dphi] = rot_desired_; x_desired[balance_control::dtheta] = 0; double y_fbk[4]; y_fbk[balance_control::theta] = this->imu_pitch_; y_fbk[balance_control::dx] = this->feedback_v_; y_fbk[balance_control::dphi] = this->feedback_w_; y_fbk[balance_control::dtheta] = this->imu_dpitch_; this->state_control_.stepControl(seconds_since_last_update, x_desired, y_fbk); this->last_update_time_ += common::Time(this->update_period_); } switch (this->current_mode_) { case BALANCE: this->joints_[LEFT]->SetForce(0, -this->u_control_[balance_control::tauL]); this->joints_[RIGHT]->SetForce(0, this->u_control_[balance_control::tauR]); break; case TRACTOR: this->joints_[LEFT]->SetVelocity(0, -( (2.0*this->x_desired_ - this->rot_desired_*this->wheel_separation_) / (this->wheel_radius_*2.0))); this->joints_[RIGHT]->SetVelocity(0, ( (2.0*this->x_desired_ + this->rot_desired_*this->wheel_separation_) / (this->wheel_radius_*2.0))); break; case PARK: this->joints_[LEFT]->SetVelocity(0, 0); this->joints_[RIGHT]->SetVelocity(0, 0); this->joints_[LEFT]->SetForce(0, 0); this->joints_[RIGHT]->SetForce(0, 0); break; }; } /*! * \brief Called by gazebo upon exiting */ void GazeboRsvBalance::FiniChild() { this->alive_ = false; this->queue_.clear(); this->queue_.disable(); this->gazebo_ros_->node()->shutdown(); this->callback_queue_thread_.join(); } void GazeboRsvBalance::QueueThread() { static const double timeout = 0.01; while (this->alive_ && this->gazebo_ros_->node()->ok()) { this->queue_.callAvailable(ros::WallDuration(timeout)); } } GZ_REGISTER_MODEL_PLUGIN(GazeboRsvBalance) } // namespace gazebo
35.634573
119
0.686583
[ "model", "transform" ]
224e2dd4bfefc2d03d1d35205b1ca404b0b67878
7,558
cpp
C++
BackInTime/Motor2D/j1FlyingEnemy.cpp
Bernat-Pablo/Platformer-game
6d1c597a06798b0fa657ea73b1aa03e2baa86a14
[ "MIT" ]
null
null
null
BackInTime/Motor2D/j1FlyingEnemy.cpp
Bernat-Pablo/Platformer-game
6d1c597a06798b0fa657ea73b1aa03e2baa86a14
[ "MIT" ]
null
null
null
BackInTime/Motor2D/j1FlyingEnemy.cpp
Bernat-Pablo/Platformer-game
6d1c597a06798b0fa657ea73b1aa03e2baa86a14
[ "MIT" ]
null
null
null
#include "j1App.h" #include "j1Player.h" #include "j1Render.h" #include "j1RectSprites.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Input.h" #include "j1Animation.h" #include "p2Log.h" #include "j1Collision.h" #include "j1Map.h" #include "j1Scene.h" #include "j1Fade.h" #include "Brofiler/Brofiler.h" #include "j1FlyingEnemy.h" #include "j1PathFinding.h" j1FlyingEnemy::j1FlyingEnemy() : j1Entity(entityTypes::FLYING_ENEMY) { name.create("flyingEnemy"); type = entityTypes::FLYING_ENEMY; debug_tex = nullptr; falling = false; set_path = true; set_timer = false; starting_flying = false; path_num = 0; tick1 = 0, tick2 = 0; float speed = 0.55f; //FLY fly.PushBack({ 24,0,35,39 },speed); fly.PushBack({ 63,0,35,39 }, speed); fly.PushBack({ 103,0,35,45 }, speed); fly.PushBack({ 143,0,35,45 }, speed); fly.PushBack({ 183,0,35,39 }, speed); fly.PushBack({ 223,0,35,39 }, speed); fly.PushBack({ 263,0,35,39 }, speed); fly.PushBack({ 303,0,35,39 }, speed); //GROUND speed = 0.2f; ground.PushBack({ 24,45,37,36 }, speed); ground.PushBack({ 64,45,37,36 }, speed); ground.PushBack({ 104,45,37,36 }, speed); ground.PushBack({ 144,45,37,36 }, speed); //HIT speed = 0.3f; hit.PushBack({ 23,126,39,39 }, speed); hit.PushBack({ 64,126,39,39 }, speed); hit.PushBack({ 104,126,39,39 }, speed); hit.PushBack({ 143,126,39,39 }, speed); hit.PushBack({ 184,126,39,39 }, speed); hit.loop = false; //FALL speed = 0.3f; fall.PushBack({ 24,81,35,45 }, speed); fall.PushBack({ 64,81,35,45 }, speed); fall.PushBack({ 104,81,35,45 }, speed); fall.PushBack({ 144,81,35,45 }, speed); } bool j1FlyingEnemy::Awake(pugi::xml_node& config) { bool ret = true; config = App->GetConfig(); config = config.child("entityManager").child("flyingEnemy"); velocity = config.child("velocity").attribute("value").as_float(); fall_velocity = config.child("fall_velocity").attribute("value").as_float(); return ret; } bool j1FlyingEnemy::Start() { spritesheet_entity = App->tex->Load("character/enemies_spritesheet.png"); debug_tex = App->tex->Load("maps/pathRect.png"); state = entityStates::FLY; current_animation = &fly; collider_entity = App->collision->AddCollider(current_animation->GetCurrentFrame(), COLLIDER_FLYING_ENEMY, "bird", (j1Module*)this); //a collider to start isgrounded = false; return true; } bool j1FlyingEnemy::PreUpdate() { //STATE MACHINE switch (state) { case entityStates::FLY: if (moving_right)state = entityStates::FLY_FORWARD; else if (moving_left)state = entityStates::FLY_BACKWARD; else if (falling)state = entityStates::FALL; break; case entityStates::FLY_FORWARD: if (moving_right == false)state = entityStates::FLY; break; case entityStates::FLY_BACKWARD: if (moving_left == false)state = entityStates::FLY; break; case entityStates::FALL: if (falling == false)state = entityStates::IN_GROUND; break; case entityStates::IN_GROUND: if (starting_flying == true)state = entityStates::FLY_UP; break; case entityStates::HIT: if (!being_hit)state = entityStates::FLY; break; } //PATH TO PLAYER (LOGIC) calculate_path(); BROFILER_CATEGORY("Bird_PreUpdate", Profiler::Color::DarkGray); return true; } bool j1FlyingEnemy::Update(float dt) { //STATE MACHINE APPLYING MOVEMENT switch (state) { case entityStates::FLY: current_animation = &fly; starting_flying = false; set_path = true; break; case entityStates::FLY_FORWARD: current_animation = &fly; starting_flying = false; position.x += (int)ceil(velocity*dt); moving_right = true; moving_left = false; break; case entityStates::FLY_BACKWARD: current_animation = &fly; position.x -= (int)ceil(velocity * dt); moving_right = false; starting_flying = false; moving_left = true; break; case entityStates::FALL: current_animation = &fall; position.y += (int)ceil(fall_velocity * dt); falling = true; set_path = false; moving_right = false; moving_left = false; break; case entityStates::IN_GROUND: if (!set_timer) { set_timer = true; tick2 = SDL_GetTicks(); } current_animation = &ground; falling = false; isgrounded = true; set_path = false; tick1 = SDL_GetTicks(); if (tick1 - tick2 >= 2500) { tick1 = tick2 = 0; isgrounded = false; position.y -= 7; //i have to put this to avoid collide to ground and set allways state to IN_GROUND set_timer = false; starting_flying = true; } break; case entityStates::FLY_UP: if (!set_timer) { set_timer = true; tick2 = SDL_GetTicks(); } set_path = false; isgrounded = false; current_animation = &fly; tick1 = SDL_GetTicks(); if (tick1 - tick2 >= 2000) { tick1 = tick2 = 0; state = entityStates::FLY; set_timer = false; } position.y -= (int)ceil(velocity * dt); break; case entityStates::HIT: current_animation = &hit; hit.Reset(); isDead = true; App->entityManager->DestroyEntity(this); break; default: break; } BlitEverything(); BROFILER_CATEGORY("Bird_Update", Profiler::Color::Fuchsia); return true; } bool j1FlyingEnemy::CleanUp() { LOG("Unloading Bird\n"); current_animation = nullptr; //Unload textures App->tex->UnLoad(spritesheet_entity); App->tex->UnLoad(debug_tex); //Unload spritesheets spritesheet_entity = nullptr; //Unload colliders collider_entity->to_delete = true; collider_entity = nullptr; return true; } void j1FlyingEnemy::calculate_path() { iPoint origin = App->map->WorldToMap(App->player->position.x, App->player->position.y); iPoint p = App->render->ScreenToWorld(position.x, position.y); p = App->map->WorldToMap(position.x, position.y); if (App->player->position.x - position.x >= -160 && position.x - App->player->position.x >= -160) { App->pathfinding->CreatePath(origin, p); if (set_path == true)check_path_toMove(); } } void j1FlyingEnemy::blit_path() { const p2DynArray<iPoint>* path = App->pathfinding->GetLastPath(); for (uint i = 0; i < path->Count(); ++i) { iPoint pos = App->map->MapToWorld(path->At(i)->x, path->At(i)->y); if(debug_tex != nullptr)App->render->Blit(debug_tex, pos.x, pos.y); } } void j1FlyingEnemy::check_path_toMove() { const p2DynArray<iPoint>* path = App->pathfinding->GetLastPath(); iPoint pos = App->map->MapToWorld(path->At(1)->x, path->At(1)->y); if (pos.x < position.x)state = entityStates::FLY_BACKWARD; if (pos.x > position.x)state = entityStates::FLY_FORWARD; if (pos.x >= position.x-5 && pos.x <= position.x + 5)state = entityStates::FALL; } void j1FlyingEnemy::OnCollision(Collider* c1, Collider* c2) { if(c1->type == COLLIDER_FLYING_ENEMY) { switch (c2->type) { case COLLIDER_WALL: if (position.y < c2->rect.y) { if(collider_entity != nullptr) if (position.x + collider_entity->rect.w > c2->rect.x) { if (position.x < c2->rect.x + c2->rect.w - 0.2 * collider_entity->rect.w) { state = entityStates::IN_GROUND; if (!starting_flying) isgrounded = true; } } } break; case COLLIDER_ROCK: state = entityStates::HIT; break; case COLLIDER_DIE: state = entityStates::HIT; default: break; } } } void j1FlyingEnemy::BlitEverything() { //BLIT if (spritesheet_entity != nullptr && current_animation != nullptr) App->render->Blit(spritesheet_entity, position.x, position.y, &current_animation->GetCurrentFrame()); if (collider_entity != nullptr) collider_entity->SetPos(position.x, position.y); //PATH TO PLAYER (BLIT) if (App->collision->debug) blit_path(); }
23.545171
155
0.677825
[ "render" ]
224eac7f604fc771b007d217c0604dffc8d79efd
2,168
cpp
C++
Source/Framework/Core/Components/TeCCamera.cpp
fabsgc/TweedeFrameworkRedux
2c61e6f31c43db36a20d3288e45047586a503725
[ "Zlib" ]
57
2019-09-02T01:10:37.000Z
2022-01-11T06:28:10.000Z
Source/Framework/Core/Components/TeCCamera.cpp
fabsgc/TweedeFrameworkRedux
2c61e6f31c43db36a20d3288e45047586a503725
[ "Zlib" ]
null
null
null
Source/Framework/Core/Components/TeCCamera.cpp
fabsgc/TweedeFrameworkRedux
2c61e6f31c43db36a20d3288e45047586a503725
[ "Zlib" ]
6
2020-02-29T17:19:30.000Z
2021-10-30T04:29:22.000Z
#include "Components/TeCCamera.h" #include "Scene/TeSceneManager.h" namespace te { CCamera::CCamera() : Component(HSceneObject(), (UINT32)TID_CCamera) { SetName("Camera"); SetFlag(Component::AlwaysRun, true); } CCamera::CCamera(const HSceneObject& parent) : Component(parent, (UINT32)TID_CCamera) { SetName("Camera"); SetFlag(Component::AlwaysRun, true); } CCamera::~CCamera() { if (!_internal->IsDestroyed()) _internal->Destroy(); } void CCamera::Initialize() { Component::Initialize(); } ConvexVolume CCamera::GetWorldFrustum() const { const Vector<Plane>& frustumPlanes = GetFrustum().GetPlanes(); Matrix4 worldMatrix = SO()->GetWorldMatrix(); Vector<Plane> worldPlanes(frustumPlanes.size()); UINT32 i = 0; for (auto& plane : frustumPlanes) { worldPlanes[i] = worldMatrix.MultiplyAffine(plane); i++; } return ConvexVolume(worldPlanes); } void CCamera::UpdateView() const { _internal->_updateState(*SO()); } void CCamera::SetMain(bool main) { _internal->SetMain(main); } void CCamera::_instantiate() { _internal = Camera::Create(); } void CCamera::OnInitialized() { gSceneManager()._bindActor(_internal, SO()); gSceneManager()._notifyMainCameraStateChanged(_internal); Component::OnInitialized(); } void CCamera::OnTransformChanged(TransformChangedFlags flags) { _internal->_updateState(*SO()); } void CCamera::OnDestroyed() { gSceneManager()._unbindActor(_internal); Component::OnDestroyed(); _internal->Destroy(); } void CCamera::Clone(const HComponent& c) { Clone(static_object_cast<CCamera>(c)); } void CCamera::Clone(const HCamera& c) { Component::Clone(c.GetInternalPtr()); SPtr<Camera> camera = c->_getCamera(); _internal->_transform = camera->_transform; _internal->_mobility = camera->_mobility; } }
22.583333
70
0.59179
[ "vector" ]
2255bb2e5c669c28159db1e8de1e9bca65adda72
2,768
hh
C++
src/physics/Gripper.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2016-01-17T20:41:39.000Z
2018-05-01T12:02:58.000Z
src/physics/Gripper.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/physics/Gripper.hh
nherment/gazebo
fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a
[ "ECL-2.0", "Apache-2.0" ]
5
2015-09-29T02:30:16.000Z
2022-03-30T12:11:22.000Z
/* * Copyright 2011 Nate Koenig & Andrew Howard * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __GRIPPER_HH__ #define __GRIPPER_HH__ #include <map> #include <vector> #include <string> #include "physics/PhysicsTypes.hh" namespace gazebo { namespace physics { /// \addtogroup gazebo_physics /// \{ /// \brief A gripper abstraction /* * A gripper is a collection of links that act as a gripper. This class * will intelligently generate fixed joints between the gripper and an * object within the gripper. This allows the object to be manipulated * without falling or behaving poorly. */ class Gripper { /// \brief Constructor public: Gripper(ModelPtr _model); /// \brief Destructor public: virtual ~Gripper(); /// \brief Load /// \param _sdf Shared point to an sdf element that contains the list /// of links in the gripper. public: virtual void Load(sdf::ElementPtr _sdf); /// \brief Initialize public: virtual void Init(); /// \brief Update the gripper private: void OnUpdate(); /// \brief Callback used when the gripper contacts an object private: void OnContact(const std::string &_collisionName, const physics::Contact &_contact); /// \brief Attach an object to the gripper private: void HandleAttach(); /// \brief Detach an object from the gripper private: void HandleDetach(); /// \brief A reset function private: void ResetDiffs(); private: physics::ModelPtr model; private: physics::PhysicsEnginePtr physics; private: physics::JointPtr fixedJoint; private: std::vector<physics::JointPtr> joints; private: std::vector<physics::LinkPtr> links; private: std::vector<event::ConnectionPtr> connections; private: std::map<std::string, physics::CollisionPtr> collisions; private: std::vector<physics::Contact> contacts; private: bool attached; private: math::Pose prevDiff; private: std::vector<double> diffs; private: int diffIndex; private: common::Time updateRate, prevUpdateTime; private: int posCount, zeroCount; }; } } #endif
29.136842
75
0.669075
[ "object", "vector", "model" ]
225b6bb4a5c000121dedbe9fa90df6d1c45d8ade
1,208
cpp
C++
camera-cmd/fnames.cpp
idrilsilverfoot/windows-camera-tools
eef4b1df25b9b91f2170bc20c35a957be768990e
[ "MIT" ]
20
2016-09-07T10:32:05.000Z
2021-06-04T17:12:17.000Z
camera-cmd/fnames.cpp
idrilsilverfoot/windows-camera-tools
eef4b1df25b9b91f2170bc20c35a957be768990e
[ "MIT" ]
1
2020-01-16T02:51:21.000Z
2020-02-19T02:34:29.000Z
camera-cmd/fnames.cpp
idrilsilverfoot/windows-camera-tools
eef4b1df25b9b91f2170bc20c35a957be768990e
[ "MIT" ]
5
2019-04-03T14:27:55.000Z
2021-01-18T13:24:52.000Z
/* * Copyright(c) 2016 Chew Esmero * All rights reserved. */ #include "stdafx.h" #include "fnames.h" #include "..\include\libcamera.h" #include "common.h" #include "appcontext.h" int DispatchFriendlyNames(wchar_t *pszParam, wchar_t *pszSubParam, PVOID pContext) { CContext *pCt = (CContext*)pContext; ICameraMf *pCamMf = NULL; HRESULT hr = E_FAIL; int retcode = DEFAULT_ERROR; hr = CreateCameraMfInstance(&pCamMf); if (SUCCEEDED(hr) && pCamMf) { wchar_t *pszNames = NULL; LONG cbSize = 0; hr = pCamMf->GetFriendlyNames(&pszNames, &cbSize); if (pszNames) { vector<std::wstring> names; wstring wstrnames(pszNames); split(wstrnames, L';', names); if (names.size() > 0) { _tprintf(L"Available camera(s):\n"); for (int i = 0; i < names.size(); i++) { _tprintf(L"%d. %s\n", i + 1, names.at(i).c_str()); } retcode = names.size(); } free(pszNames); } pCamMf->Release(); } *pCt->m_pCmdSupported = TRUE; return retcode; }
21.571429
82
0.522351
[ "vector" ]
225e14a1be08abd550ad63c45eb51a1c462e1c20
3,379
cpp
C++
Source/JavaScriptCore/jit/JITArithmetic32_64.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/JavaScriptCore/jit/JITArithmetic32_64.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/JavaScriptCore/jit/JITArithmetic32_64.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2008-2019 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(JIT) #if USE(JSVALUE32_64) #include "JIT.h" #include "CodeBlock.h" #include "JITInlines.h" #include "JSArray.h" #include "JSFunction.h" #include "Interpreter.h" #include "JSCInlines.h" #include "ResultType.h" #include "SlowPathCall.h" namespace JSC { void JIT::emit_op_unsigned(const Instruction* currentInstruction) { auto bytecode = currentInstruction->as<OpUnsigned>(); VirtualRegister result = bytecode.m_dst; VirtualRegister op1 = bytecode.m_operand; emitLoad(op1, regT1, regT0); addSlowCase(branchIfNotInt32(regT1)); addSlowCase(branch32(LessThan, regT0, TrustedImm32(0))); emitStoreInt32(result, regT0, result == op1); } void JIT::emit_op_inc(const Instruction* currentInstruction) { auto bytecode = currentInstruction->as<OpInc>(); VirtualRegister srcDst = bytecode.m_srcDst; emitLoad(srcDst, regT1, regT0); addSlowCase(branchIfNotInt32(regT1)); addSlowCase(branchAdd32(Overflow, TrustedImm32(1), regT0)); emitStoreInt32(srcDst, regT0, true); } void JIT::emit_op_dec(const Instruction* currentInstruction) { auto bytecode = currentInstruction->as<OpDec>(); VirtualRegister srcDst = bytecode.m_srcDst; emitLoad(srcDst, regT1, regT0); addSlowCase(branchIfNotInt32(regT1)); addSlowCase(branchSub32(Overflow, TrustedImm32(1), regT0)); emitStoreInt32(srcDst, regT0, true); } // Mod (%) /* ------------------------------ BEGIN: OP_MOD ------------------------------ */ void JIT::emit_op_mod(const Instruction* currentInstruction) { JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_mod); slowPathCall.call(); } void JIT::emitSlow_op_mod(const Instruction*, Vector<SlowCaseEntry>::iterator&) { // We would have really useful assertions here if it wasn't for the compiler's // insistence on attribute noreturn. // RELEASE_ASSERT_NOT_REACHED(); } /* ------------------------------ END: OP_MOD ------------------------------ */ } // namespace JSC #endif // USE(JSVALUE32_64) #endif // ENABLE(JIT)
32.490385
82
0.717668
[ "vector" ]
2260caa2159a0570b15d8bce6240f0c8450426be
7,164
cpp
C++
day15/day15.cpp
CheezeCake/AoC-2018
add9b20f0708069e58317b31c7447534792a6d40
[ "MIT" ]
null
null
null
day15/day15.cpp
CheezeCake/AoC-2018
add9b20f0708069e58317b31c7447534792a6d40
[ "MIT" ]
null
null
null
day15/day15.cpp
CheezeCake/AoC-2018
add9b20f0708069e58317b31c7447534792a6d40
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <functional> #include <iostream> #include <limits> #include <numeric> #include <optional> #include <queue> #include <stdexcept> #include <tuple> #include <vector> struct Point { int x; int y; }; std::ostream& operator<<(std::ostream& os, const Point& p) { os << '(' << p.x << ", " << p.y << ')'; return os; } bool operator<(const Point& lhs, const Point& rhs) { return (lhs.y < rhs.y || (lhs.y == rhs.y && lhs.x < rhs.x)); } bool operator==(const Point& lhs, const Point& rhs) { return (lhs.x == rhs.x && lhs.y == rhs.y); } struct Unit { enum class Type : char { Goblin = 'G', Elf = 'E' }; Type type; Point position; int attack{3}; int hp{200}; void hit(int attackValue) { hp -= attackValue; } bool isAlive() const { return (hp > 0); } Type getEnemyType() const { return (type == Type::Goblin) ? Type::Elf : Type::Goblin; } }; class Battle { std::vector<std::vector<bool>> mMap; std::vector<Unit> mUnits; bool isValid(const Point& p) const { return (p.y >= 0 && p.y < mMap.size() && p.x >= 0 && p.x < mMap[p.y].size()); } std::vector<Point> adjacentPoints(const Point& from) const { static const std::array<const Point, 4> directions = {{ {0, -1}, {-1, 0}, {1, 0}, {0, 1} }}; std::vector<Point> adj; adj.reserve(4); for (const auto& dir : directions) { Point p{from.x + dir.x, from.y + dir.y}; if (isValid(p)) adj.push_back(p); } return adj; } std::optional<Point> getEnemyInRange(const Point& from, Unit::Type enemyType) const { std::optional<Point> e; int eHp{std::numeric_limits<int>::max()}; for (const auto& p : adjacentPoints(from)) { if (unitAt(p)) { const auto& unit{getUnitAt(p)}; if (unit.type == enemyType && unit.hp < eHp) { e = p; eHp = unit.hp; } } } return e; } Unit& getUnitAt(const Point& p) { return *std::find_if(std::begin(mUnits), std::end(mUnits), [&p](const auto& u) { return (u.isAlive() && u.position == p); }); } const Unit& getUnitAt(const Point& p) const { return *std::find_if(std::begin(mUnits), std::end(mUnits), [&p](const auto& u) { return (u.isAlive() && u.position == p); }); } bool unitAt(const Point& p) const { return (std::find_if(std::begin(mUnits), std::end(mUnits), [&p](const auto& u) { return (u.isAlive() && u.position == p); }) != std::end(mUnits)); } bool hitUnitAt(const Point& p, int attackValue) { auto& unit{getUnitAt(p)}; unit.hit(attackValue); return unit.isAlive(); } std::vector<Point> pointsInRange(Unit::Type enemyType) const { std::vector<Point> results; results.reserve((mUnits.size() - 1) * 4); for (const auto& unit : mUnits) { if (unit.type != enemyType || !unit.isAlive()) continue; const auto& adj{adjacentPoints(unit.position)}; for (const auto& p : adj) { auto [x, y] = p; if (!mMap[y][x] && !unitAt({x, y})) results.push_back(p); } } return results; } std::optional<std::pair<Point, unsigned>> findPath(const Point& from, const Point& to) const { std::vector<std::vector<bool>> visited{mMap.size(), std::vector<bool>(mMap[0].size(), false)}; std::queue<std::pair<Point, unsigned>> q; q.push({from, 0}); visited[from.y][from.x] = true; while (!q.empty()) { const auto [p, dist] = q.front(); q.pop(); for (const auto& adj : adjacentPoints(p)) { if (adj == to) return {{p, dist}}; if (!visited[adj.y][adj.x] && !mMap[adj.y][adj.x] && !unitAt(adj)) { q.push({adj, dist + 1}); visited[adj.y][adj.x] = true; } } } return {}; } std::optional<Point> determineMove(const Point& from, Unit::Type enemyType) const { std::optional<Point> ret; unsigned retDist{std::numeric_limits<unsigned>::max()}; auto points{pointsInRange(enemyType)}; std::sort(std::begin(points), std::end(points)); for (const auto& p : points) { const auto dist{findPath(p, from)}; if (dist) { if (dist->second < retDist) { ret = dist->first; retDist = dist->second; } } } return ret; } void moveUnit(const Point& from, const Point& to) { auto& unit{getUnitAt(from)}; unit.position = to; } void update() { std::sort(std::begin(mUnits), std::end(mUnits), [](const auto& lhs, const auto& rhs) { return (lhs.position < rhs.position); }); } bool enemiesLeft() const { int goblins{0}; int elves{0}; for (const auto& unit : mUnits) { if (!unit.isAlive()) continue; if (unit.type == Unit::Type::Goblin) ++goblins; else ++elves; } return (goblins > 0 && elves > 0); } public: Battle(const std::vector<std::string>& map, int elftAttack = 3) { mMap.resize(map.size()); for (int y{0}; y < map.size(); ++y) { mMap[y].resize(map[y].size()); for (int x{0}; x < map[y].size(); ++x) { mMap[y][x] = (map[y][x] == '#'); if (map[y][x] == 'G') mUnits.push_back({Unit::Type::Goblin, {x, y}}); else if (map[y][x] == 'E') mUnits.push_back({Unit::Type::Elf, {x, y}, elftAttack}); } } } using ElfDead = int; bool round(bool stopOnElfDeath = false) { for (const auto& unit : mUnits) { if (!unit.isAlive()) continue; if (!enemiesLeft()) return false; const auto eType{unit.getEnemyType()}; auto enemyPos{getEnemyInRange(unit.position, eType)}; if (!enemyPos) { const auto to{determineMove(unit.position, eType)}; if (to) { moveUnit(unit.position, *to); enemyPos = getEnemyInRange(*to, eType); } } if (enemyPos) { if (hitUnitAt(*enemyPos, unit.attack) && eType == Unit::Type::Elf && stopOnElfDeath) throw ElfDead{}; } } update(); return enemiesLeft(); } int play() { int rounds{0}; while (round()) ++rounds; return rounds; } bool playUntilElfDeath() { while (true) { try { if (!round(true)) return true; } catch (ElfDead) { return false; } } } void printHpForLine(int y) const { for (int x{0}; x < mMap[y].size(); ++x) { if (unitAt({x, y})) { const auto& unit{getUnitAt({x, y})}; std::cout << ' ' << static_cast<char>(unit.type) << '(' << unit.hp << ')'; } } } void print() const { for (int y{0}; y < mMap.size(); ++y) { for (int x{0}; x < mMap[y].size(); ++x) { if (unitAt({x, y})) { std::cout << static_cast<char>(getUnitAt({x, y}).type); } else { if (mMap[y][x]) std::cout << '#'; else std::cout << '.'; } } printHpForLine(y); std::cout << '\n'; } } int hpSum() const { int sum{0}; for (const auto& u : mUnits) { if (u.isAlive()) sum += u.hp; } return sum; } }; int main(int argc, char** argv) { std::vector<std::string> input; std::string line; while (std::getline(std::cin, line)) input.push_back(line); { Battle b{input}; int rounds{b.play()}; int sum{b.hpSum()}; std::cout << "part 1: " << rounds << " * " << sum << " = " << rounds * sum << '\n'; } for (int attack{4}; ; ++attack) { Battle b{input, attack}; if (b.playUntilElfDeath()) { std::cout << "part 2: " << attack << '\n'; return 0; } } }
19.681319
96
0.5677
[ "vector" ]
22612d5f6f60115ffb799ac613b360072cb7e63d
1,812
cpp
C++
tourist-spots/cpp/test.cpp
XUranus/shit
695a1c33c65357fb5bb170483e84fecb4368d224
[ "Unlicense" ]
1
2020-11-12T17:20:29.000Z
2020-11-12T17:20:29.000Z
tourist-spots/cpp/test.cpp
XUranus/shit
695a1c33c65357fb5bb170483e84fecb4368d224
[ "Unlicense" ]
null
null
null
tourist-spots/cpp/test.cpp
XUranus/shit
695a1c33c65357fb5bb170483e84fecb4368d224
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; #include <iostream> #include <string> #include <map> #include <vector> #include <set> #include <algorithm> #include <fstream> #include <list> #include <cstdio> #include <set> #include "Graph.h" #include "util.h" /* HamiltonPath Graph::Hamilton() { } set<int> erase_verice(set<int> ss) { //delete iter->first from ss set<int>::iterator it; for (it=ss.begin(); it!=ss.end(); it++) { if(it->first==iter->first) { ss.erase(it++); return ss; } else it++; } } HamiltonPath Graph::Hamilton(int v,set<int> s) { set<int>::iterator iter; vector<HamiltonPath> ans_vec; for(iter=s.begin();iter!=s.end();iter++) { if(distance_between(v,*iter)>=INF) { s = erase_verice(*iter); iter = s.begin(); }// Hamilton(*iter,ss)+distance_between(v,iter->first) } }*/ int tot_node; int m_size[50]; int mmap[50][50]; int vis[50]; int ans[50]; int cas = 1; int n,m; Graph *graph = load_graph(); void dfs(int m,int len,int c) { int i,j; vis[m] = 1; ans[len] = m; for(i = 0; i<m_size[i]; i++) { int t = mmap[m][i]; if(t == c && len == tot_node) { printf("%d: ",cas++); for(j = 0; j<tot_node; j++) printf("%d ",ans[j]); printf("%d\n",c); } if(!vis[t]) dfs(t,len+1,c); } vis[m] = 0; } int main(int argc, char *argv[]) { tot_node = graph->vertices.size(); for(int i=0;i<graph->vertices.size();i++) { list<Edge> &e = graph->vertices[i].edges; list<Edge>::iterator it; int k=0; for(it=e.begin();it!=e.end();it++) mmap[i][k++]=it->to; m_size[i] = k; } // for(int i=0;i<graph->vertices.size();i++) { cout << i << ": "; for(int j=0;j<m_size[i];j++) { cout << mmap[i][j] << " "; } cout << endl; } // for(int i=0;i<graph->vertices.size();i++) { memset(vis,0,sizeof(vis)); dfs(i,0,i); } }
17.09434
57
0.570088
[ "vector" ]
22619b913956ca5ac3d8ef9914b41c8a5f9e05c1
37,059
cc
C++
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/theme_customization.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/theme_customization.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/actions/sdk/v2/theme_customization.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/actions/sdk/v2/theme_customization.proto #include "google/actions/sdk/v2/theme_customization.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> namespace google { namespace actions { namespace sdk { namespace v2 { class ThemeCustomizationDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<ThemeCustomization> _instance; } _ThemeCustomization_default_instance_; } // namespace v2 } // namespace sdk } // namespace actions } // namespace google static void InitDefaultsThemeCustomization_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::actions::sdk::v2::_ThemeCustomization_default_instance_; new (ptr) ::google::actions::sdk::v2::ThemeCustomization(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::actions::sdk::v2::ThemeCustomization::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_ThemeCustomization_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsThemeCustomization_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto}, {}}; void InitDefaults_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto() { ::google::protobuf::internal::InitSCC(&scc_info_ThemeCustomization_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto.base); } ::google::protobuf::Metadata file_level_metadata_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto[1]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto[1]; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto = nullptr; const ::google::protobuf::uint32 TableStruct_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, background_color_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, primary_color_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, font_family_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, image_corner_style_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, landscape_background_image_), PROTOBUF_FIELD_OFFSET(::google::actions::sdk::v2::ThemeCustomization, portrait_background_image_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::actions::sdk::v2::ThemeCustomization)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::actions::sdk::v2::_ThemeCustomization_default_instance_), }; ::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto = { {}, AddDescriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, "google/actions/sdk/v2/theme_customization.proto", schemas, file_default_instances, TableStruct_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto::offsets, file_level_metadata_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, 1, file_level_enum_descriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, file_level_service_descriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, }; const char descriptor_table_protodef_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto[] = "\n/google/actions/sdk/v2/theme_customizat" "ion.proto\022\025google.actions.sdk.v2\"\311\002\n\022The" "meCustomization\022\030\n\020background_color\030\001 \001(" "\t\022\025\n\rprimary_color\030\002 \001(\t\022\023\n\013font_family\030" "\003 \001(\t\022V\n\022image_corner_style\030\004 \001(\0162:.goog" "le.actions.sdk.v2.ThemeCustomization.Ima" "geCornerStyle\022\"\n\032landscape_background_im" "age\030\005 \001(\t\022!\n\031portrait_background_image\030\006" " \001(\t\"N\n\020ImageCornerStyle\022\"\n\036IMAGE_CORNER" "_STYLE_UNSPECIFIED\020\000\022\n\n\006CURVED\020\001\022\n\n\006ANGL" "ED\020\002Bp\n\031com.google.actions.sdk.v2B\027Theme" "CustomizationProtoP\001Z8google.golang.org/" "genproto/googleapis/actions/sdk/v2;sdkb\006" "proto3" ; ::google::protobuf::internal::DescriptorTable descriptor_table_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto = { false, InitDefaults_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, descriptor_table_protodef_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, "google/actions/sdk/v2/theme_customization.proto", &assign_descriptors_table_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, 526, }; void AddDescriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto() { static constexpr ::google::protobuf::internal::InitFunc deps[1] = { }; ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto, deps, 0); } // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto = []() { AddDescriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto(); return true; }(); namespace google { namespace actions { namespace sdk { namespace v2 { const ::google::protobuf::EnumDescriptor* ThemeCustomization_ImageCornerStyle_descriptor() { ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto); return file_level_enum_descriptors_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto[0]; } bool ThemeCustomization_ImageCornerStyle_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const ThemeCustomization_ImageCornerStyle ThemeCustomization::IMAGE_CORNER_STYLE_UNSPECIFIED; const ThemeCustomization_ImageCornerStyle ThemeCustomization::CURVED; const ThemeCustomization_ImageCornerStyle ThemeCustomization::ANGLED; const ThemeCustomization_ImageCornerStyle ThemeCustomization::ImageCornerStyle_MIN; const ThemeCustomization_ImageCornerStyle ThemeCustomization::ImageCornerStyle_MAX; const int ThemeCustomization::ImageCornerStyle_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 // =================================================================== void ThemeCustomization::InitAsDefaultInstance() { } class ThemeCustomization::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ThemeCustomization::kBackgroundColorFieldNumber; const int ThemeCustomization::kPrimaryColorFieldNumber; const int ThemeCustomization::kFontFamilyFieldNumber; const int ThemeCustomization::kImageCornerStyleFieldNumber; const int ThemeCustomization::kLandscapeBackgroundImageFieldNumber; const int ThemeCustomization::kPortraitBackgroundImageFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ThemeCustomization::ThemeCustomization() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.actions.sdk.v2.ThemeCustomization) } ThemeCustomization::ThemeCustomization(const ThemeCustomization& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); background_color_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.background_color().size() > 0) { background_color_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.background_color_); } primary_color_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.primary_color().size() > 0) { primary_color_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.primary_color_); } font_family_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.font_family().size() > 0) { font_family_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.font_family_); } landscape_background_image_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.landscape_background_image().size() > 0) { landscape_background_image_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.landscape_background_image_); } portrait_background_image_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.portrait_background_image().size() > 0) { portrait_background_image_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.portrait_background_image_); } image_corner_style_ = from.image_corner_style_; // @@protoc_insertion_point(copy_constructor:google.actions.sdk.v2.ThemeCustomization) } void ThemeCustomization::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_ThemeCustomization_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto.base); background_color_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); primary_color_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); font_family_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); landscape_background_image_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); portrait_background_image_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); image_corner_style_ = 0; } ThemeCustomization::~ThemeCustomization() { // @@protoc_insertion_point(destructor:google.actions.sdk.v2.ThemeCustomization) SharedDtor(); } void ThemeCustomization::SharedDtor() { background_color_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); primary_color_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); font_family_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); landscape_background_image_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); portrait_background_image_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void ThemeCustomization::SetCachedSize(int size) const { _cached_size_.Set(size); } const ThemeCustomization& ThemeCustomization::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_ThemeCustomization_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto.base); return *internal_default_instance(); } void ThemeCustomization::Clear() { // @@protoc_insertion_point(message_clear_start:google.actions.sdk.v2.ThemeCustomization) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; background_color_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); primary_color_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); font_family_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); landscape_background_image_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); portrait_background_image_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); image_corner_style_ = 0; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* ThemeCustomization::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<ThemeCustomization*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string background_color = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.ThemeCustomization.background_color"); object = msg->mutable_background_color(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string primary_color = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.ThemeCustomization.primary_color"); object = msg->mutable_primary_color(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string font_family = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.ThemeCustomization.font_family"); object = msg->mutable_font_family(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // .google.actions.sdk.v2.ThemeCustomization.ImageCornerStyle image_corner_style = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->set_image_corner_style(static_cast<::google::actions::sdk::v2::ThemeCustomization_ImageCornerStyle>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // string landscape_background_image = 5; case 5: { if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.ThemeCustomization.landscape_background_image"); object = msg->mutable_landscape_background_image(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string portrait_background_image = 6; case 6: { if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.actions.sdk.v2.ThemeCustomization.portrait_background_image"); object = msg->mutable_portrait_background_image(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool ThemeCustomization::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.actions.sdk.v2.ThemeCustomization) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string background_color = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_background_color())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->background_color().data(), static_cast<int>(this->background_color().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.ThemeCustomization.background_color")); } else { goto handle_unusual; } break; } // string primary_color = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_primary_color())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->primary_color().data(), static_cast<int>(this->primary_color().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.ThemeCustomization.primary_color")); } else { goto handle_unusual; } break; } // string font_family = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_font_family())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->font_family().data(), static_cast<int>(this->font_family().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.ThemeCustomization.font_family")); } else { goto handle_unusual; } break; } // .google.actions.sdk.v2.ThemeCustomization.ImageCornerStyle image_corner_style = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_image_corner_style(static_cast< ::google::actions::sdk::v2::ThemeCustomization_ImageCornerStyle >(value)); } else { goto handle_unusual; } break; } // string landscape_background_image = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_landscape_background_image())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->landscape_background_image().data(), static_cast<int>(this->landscape_background_image().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.ThemeCustomization.landscape_background_image")); } else { goto handle_unusual; } break; } // string portrait_background_image = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_portrait_background_image())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->portrait_background_image().data(), static_cast<int>(this->portrait_background_image().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.actions.sdk.v2.ThemeCustomization.portrait_background_image")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:google.actions.sdk.v2.ThemeCustomization) return true; failure: // @@protoc_insertion_point(parse_failure:google.actions.sdk.v2.ThemeCustomization) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void ThemeCustomization::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.actions.sdk.v2.ThemeCustomization) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string background_color = 1; if (this->background_color().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->background_color().data(), static_cast<int>(this->background_color().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.background_color"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->background_color(), output); } // string primary_color = 2; if (this->primary_color().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->primary_color().data(), static_cast<int>(this->primary_color().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.primary_color"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->primary_color(), output); } // string font_family = 3; if (this->font_family().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->font_family().data(), static_cast<int>(this->font_family().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.font_family"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->font_family(), output); } // .google.actions.sdk.v2.ThemeCustomization.ImageCornerStyle image_corner_style = 4; if (this->image_corner_style() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 4, this->image_corner_style(), output); } // string landscape_background_image = 5; if (this->landscape_background_image().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->landscape_background_image().data(), static_cast<int>(this->landscape_background_image().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.landscape_background_image"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 5, this->landscape_background_image(), output); } // string portrait_background_image = 6; if (this->portrait_background_image().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->portrait_background_image().data(), static_cast<int>(this->portrait_background_image().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.portrait_background_image"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 6, this->portrait_background_image(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.actions.sdk.v2.ThemeCustomization) } ::google::protobuf::uint8* ThemeCustomization::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.actions.sdk.v2.ThemeCustomization) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string background_color = 1; if (this->background_color().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->background_color().data(), static_cast<int>(this->background_color().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.background_color"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->background_color(), target); } // string primary_color = 2; if (this->primary_color().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->primary_color().data(), static_cast<int>(this->primary_color().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.primary_color"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->primary_color(), target); } // string font_family = 3; if (this->font_family().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->font_family().data(), static_cast<int>(this->font_family().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.font_family"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->font_family(), target); } // .google.actions.sdk.v2.ThemeCustomization.ImageCornerStyle image_corner_style = 4; if (this->image_corner_style() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 4, this->image_corner_style(), target); } // string landscape_background_image = 5; if (this->landscape_background_image().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->landscape_background_image().data(), static_cast<int>(this->landscape_background_image().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.landscape_background_image"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 5, this->landscape_background_image(), target); } // string portrait_background_image = 6; if (this->portrait_background_image().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->portrait_background_image().data(), static_cast<int>(this->portrait_background_image().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.actions.sdk.v2.ThemeCustomization.portrait_background_image"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 6, this->portrait_background_image(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.actions.sdk.v2.ThemeCustomization) return target; } size_t ThemeCustomization::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.actions.sdk.v2.ThemeCustomization) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string background_color = 1; if (this->background_color().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->background_color()); } // string primary_color = 2; if (this->primary_color().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->primary_color()); } // string font_family = 3; if (this->font_family().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->font_family()); } // string landscape_background_image = 5; if (this->landscape_background_image().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->landscape_background_image()); } // string portrait_background_image = 6; if (this->portrait_background_image().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->portrait_background_image()); } // .google.actions.sdk.v2.ThemeCustomization.ImageCornerStyle image_corner_style = 4; if (this->image_corner_style() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->image_corner_style()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ThemeCustomization::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.actions.sdk.v2.ThemeCustomization) GOOGLE_DCHECK_NE(&from, this); const ThemeCustomization* source = ::google::protobuf::DynamicCastToGenerated<ThemeCustomization>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.actions.sdk.v2.ThemeCustomization) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.actions.sdk.v2.ThemeCustomization) MergeFrom(*source); } } void ThemeCustomization::MergeFrom(const ThemeCustomization& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.actions.sdk.v2.ThemeCustomization) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.background_color().size() > 0) { background_color_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.background_color_); } if (from.primary_color().size() > 0) { primary_color_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.primary_color_); } if (from.font_family().size() > 0) { font_family_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.font_family_); } if (from.landscape_background_image().size() > 0) { landscape_background_image_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.landscape_background_image_); } if (from.portrait_background_image().size() > 0) { portrait_background_image_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.portrait_background_image_); } if (from.image_corner_style() != 0) { set_image_corner_style(from.image_corner_style()); } } void ThemeCustomization::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.actions.sdk.v2.ThemeCustomization) if (&from == this) return; Clear(); MergeFrom(from); } void ThemeCustomization::CopyFrom(const ThemeCustomization& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.actions.sdk.v2.ThemeCustomization) if (&from == this) return; Clear(); MergeFrom(from); } bool ThemeCustomization::IsInitialized() const { return true; } void ThemeCustomization::Swap(ThemeCustomization* other) { if (other == this) return; InternalSwap(other); } void ThemeCustomization::InternalSwap(ThemeCustomization* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); background_color_.Swap(&other->background_color_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); primary_color_.Swap(&other->primary_color_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); font_family_.Swap(&other->font_family_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); landscape_background_image_.Swap(&other->landscape_background_image_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); portrait_background_image_.Swap(&other->portrait_background_image_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(image_corner_style_, other->image_corner_style_); } ::google::protobuf::Metadata ThemeCustomization::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto); return ::file_level_metadata_google_2factions_2fsdk_2fv2_2ftheme_5fcustomization_2eproto[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace v2 } // namespace sdk } // namespace actions } // namespace google namespace google { namespace protobuf { template<> PROTOBUF_NOINLINE ::google::actions::sdk::v2::ThemeCustomization* Arena::CreateMaybeMessage< ::google::actions::sdk::v2::ThemeCustomization >(Arena* arena) { return Arena::CreateInternal< ::google::actions::sdk::v2::ThemeCustomization >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
46.850822
266
0.730565
[ "object" ]
2262c76e64f979ffcd57865a7577a1f81b5e138a
141,236
cpp
C++
cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
164
2015-01-05T16:49:11.000Z
2022-03-29T20:40:27.000Z
cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
127
2015-01-12T12:02:32.000Z
2021-11-28T08:46:25.000Z
cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
1,141
2015-01-01T22:54:40.000Z
2022-02-09T22:08:26.000Z
// Copyright (C) 2017 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 "src/matchers/SimpleLogMatchingTracker.h" #include "src/metrics/ValueMetricProducer.h" #include "src/stats_log_util.h" #include "metrics_test_helper.h" #include "tests/statsd_test_util.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <math.h> #include <stdio.h> #include <vector> using namespace testing; using android::sp; using android::util::ProtoReader; using std::make_shared; using std::set; using std::shared_ptr; using std::unordered_map; using std::vector; #ifdef __ANDROID__ namespace android { namespace os { namespace statsd { const ConfigKey kConfigKey(0, 12345); const int tagId = 1; const int64_t metricId = 123; const int64_t atomMatcherId = 678; const int logEventMatcherIndex = 0; const int64_t bucketStartTimeNs = 10000000000; const int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(ONE_MINUTE) * 1000000LL; const int64_t bucket2StartTimeNs = bucketStartTimeNs + bucketSizeNs; const int64_t bucket3StartTimeNs = bucketStartTimeNs + 2 * bucketSizeNs; const int64_t bucket4StartTimeNs = bucketStartTimeNs + 3 * bucketSizeNs; const int64_t bucket5StartTimeNs = bucketStartTimeNs + 4 * bucketSizeNs; const int64_t bucket6StartTimeNs = bucketStartTimeNs + 5 * bucketSizeNs; double epsilon = 0.001; static void assertPastBucketValuesSingleKey( const std::unordered_map<MetricDimensionKey, std::vector<ValueBucket>>& mPastBuckets, const std::initializer_list<int>& expectedValuesList, const std::initializer_list<int64_t>& expectedDurationNsList) { std::vector<int> expectedValues(expectedValuesList); std::vector<int64_t> expectedDurationNs(expectedDurationNsList); ASSERT_EQ(expectedValues.size(), expectedDurationNs.size()); if (expectedValues.size() == 0) { ASSERT_EQ(0, mPastBuckets.size()); return; } ASSERT_EQ(1, mPastBuckets.size()); ASSERT_EQ(expectedValues.size(), mPastBuckets.begin()->second.size()); auto buckets = mPastBuckets.begin()->second; for (int i = 0; i < expectedValues.size(); i++) { EXPECT_EQ(expectedValues[i], buckets[i].values[0].long_value) << "Values differ at index " << i; EXPECT_EQ(expectedDurationNs[i], buckets[i].mConditionTrueNs) << "Condition duration value differ at index " << i; } } class ValueMetricProducerTestHelper { public: static shared_ptr<LogEvent> createEvent(int64_t eventTimeNs, int64_t value) { shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, eventTimeNs); event->write(tagId); event->write(value); event->write(value); event->init(); return event; } static sp<ValueMetricProducer> createValueProducerNoConditions( sp<MockStatsPullerManager>& pullerManager, ValueMetric& metric) { UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return()); sp<ValueMetricProducer> valueProducer = new ValueMetricProducer( kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer->prepareFirstBucket(); return valueProducer; } static sp<ValueMetricProducer> createValueProducerWithCondition( sp<MockStatsPullerManager>& pullerManager, ValueMetric& metric) { UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return()); sp<ValueMetricProducer> valueProducer = new ValueMetricProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer->prepareFirstBucket(); valueProducer->mCondition = ConditionState::kFalse; return valueProducer; } static ValueMetric createMetric() { ValueMetric metric; metric.set_id(metricId); metric.set_bucket(ONE_MINUTE); metric.mutable_value_field()->set_field(tagId); metric.mutable_value_field()->add_child()->set_field(2); metric.set_max_pull_delay_sec(INT_MAX); return metric; } static ValueMetric createMetricWithCondition() { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_condition(StringToId("SCREEN_ON")); return metric; } }; /* * Tests that the first bucket works correctly */ TEST(ValueMetricProducerTest, TestCalcPreviousBucketEndTime) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); int64_t startTimeBase = 11; UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); // statsd started long ago. // The metric starts in the middle of the bucket ValueMetricProducer valueProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, logEventMatcherIndex, eventMatcherWizard, -1, startTimeBase, 22, pullerManager); valueProducer.prepareFirstBucket(); EXPECT_EQ(startTimeBase, valueProducer.calcPreviousBucketEndTime(60 * NS_PER_SEC + 10)); EXPECT_EQ(startTimeBase, valueProducer.calcPreviousBucketEndTime(60 * NS_PER_SEC + 10)); EXPECT_EQ(60 * NS_PER_SEC + startTimeBase, valueProducer.calcPreviousBucketEndTime(2 * 60 * NS_PER_SEC)); EXPECT_EQ(2 * 60 * NS_PER_SEC + startTimeBase, valueProducer.calcPreviousBucketEndTime(3 * 60 * NS_PER_SEC)); } /* * Tests that the first bucket works correctly */ TEST(ValueMetricProducerTest, TestFirstBucket) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); // statsd started long ago. // The metric starts in the middle of the bucket ValueMetricProducer valueProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, logEventMatcherIndex, eventMatcherWizard, -1, 5, 600 * NS_PER_SEC + NS_PER_SEC / 2, pullerManager); valueProducer.prepareFirstBucket(); EXPECT_EQ(600500000000, valueProducer.mCurrentBucketStartTimeNs); EXPECT_EQ(10, valueProducer.mCurrentBucketNum); EXPECT_EQ(660000000005, valueProducer.getCurrentBucketEndTimeNs()); } /* * Tests pulled atoms with no conditions */ TEST(ValueMetricProducerTest, TestPulledEventsNoCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(3); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(11); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(11, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(8, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(8, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); allData.clear(); event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(tagId); event->write(23); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(23, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(12, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(2UL, valueProducer->mPastBuckets.begin()->second.size()); EXPECT_EQ(8, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); EXPECT_EQ(12, valueProducer->mPastBuckets.begin()->second.back().values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second.back().mConditionTrueNs); allData.clear(); event = make_shared<LogEvent>(tagId, bucket4StartTimeNs + 1); event->write(tagId); event->write(36); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket4StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(36, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(13, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(3UL, valueProducer->mPastBuckets.begin()->second.size()); EXPECT_EQ(8, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); EXPECT_EQ(12, valueProducer->mPastBuckets.begin()->second[1].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[1].mConditionTrueNs); EXPECT_EQ(13, valueProducer->mPastBuckets.begin()->second[2].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[2].mConditionTrueNs); } TEST(ValueMetricProducerTest, TestPartialBucketCreated) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initialize bucket. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(tagId); event->write(1); event->init(); data->push_back(event); return true; })) // Partial bucket. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 10); event->write(tagId); event->write(5); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); // First bucket ends. vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 10); event->write(tagId); event->write(2); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** success */ true, bucket2StartTimeNs); // Partial buckets created in 2nd bucket. valueProducer->notifyAppUpgrade(bucket2StartTimeNs + 2, "com.foo", 10000, 1); // One full bucket and one partial bucket. EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); vector<ValueBucket> buckets = valueProducer->mPastBuckets.begin()->second; EXPECT_EQ(2UL, buckets.size()); // Full bucket (2 - 1) EXPECT_EQ(1, buckets[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, buckets[0].mConditionTrueNs); // Full bucket (5 - 3) EXPECT_EQ(3, buckets[1].values[0].long_value); // partial bucket [bucket2StartTimeNs, bucket2StartTimeNs + 2] EXPECT_EQ(2, buckets[1].mConditionTrueNs); } /* * Tests pulled atoms with filtering */ TEST(ValueMetricProducerTest, TestPulledEventsWithFiltering) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); auto keyValue = atomMatcher.add_field_value_matcher(); keyValue->set_field(1); keyValue->set_eq_int(3); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(3); event->write(3); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = new ValueMetricProducer( kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer->prepareFirstBucket(); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(3); event->write(11); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(11, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(8, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(8, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); allData.clear(); event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(4); event->write(23); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); // No new data seen, so data has been cleared. EXPECT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(11, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(8, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(8, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); allData.clear(); event = make_shared<LogEvent>(tagId, bucket4StartTimeNs + 1); event->write(3); event->write(36); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket4StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // the base was reset EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(36, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(1UL, valueProducer->mPastBuckets.begin()->second.size()); EXPECT_EQ(8, valueProducer->mPastBuckets.begin()->second.back().values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second.back().mConditionTrueNs); } /* * Tests pulled atoms with no conditions and take absolute value after reset */ TEST(ValueMetricProducerTest, TestPulledEventsTakeAbsoluteValueOnReset) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_use_absolute_value_on_reset(true); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)).WillOnce(Return(true)); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(11); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(11, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); allData.clear(); event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(tagId); event->write(10); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(10, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(10, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(10, valueProducer->mPastBuckets.begin()->second.back().values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second.back().mConditionTrueNs); allData.clear(); event = make_shared<LogEvent>(tagId, bucket4StartTimeNs + 1); event->write(tagId); event->write(36); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket4StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(36, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(26, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(2UL, valueProducer->mPastBuckets.begin()->second.size()); EXPECT_EQ(10, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); EXPECT_EQ(26, valueProducer->mPastBuckets.begin()->second[1].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[1].mConditionTrueNs); } /* * Tests pulled atoms with no conditions and take zero value after reset */ TEST(ValueMetricProducerTest, TestPulledEventsTakeZeroOnReset) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)).WillOnce(Return(false)); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(11); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(11, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); allData.clear(); event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(tagId); event->write(10); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(10, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); allData.clear(); event = make_shared<LogEvent>(tagId, bucket4StartTimeNs + 1); event->write(tagId); event->write(36); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket4StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(36, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(26, curInterval.value.long_value); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); EXPECT_EQ(26, valueProducer->mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, valueProducer->mPastBuckets.begin()->second[0].mConditionTrueNs); } /* * Test pulled event with non sliced condition. */ TEST(ValueMetricProducerTest, TestEventsWithNonSlicedCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(130); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(tagId); event->write(180); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // startUpdated:false sum:0 start:100 EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(100, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(1); event->write(110); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {10}, {bucketSizeNs - 8}); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(110, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(10, curInterval.value.long_value); valueProducer->onConditionChanged(false, bucket2StartTimeNs + 1); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {10}, {bucketSizeNs - 8}); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(20, curInterval.value.long_value); EXPECT_EQ(false, curInterval.hasBase); valueProducer->onConditionChanged(true, bucket3StartTimeNs + 1); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {10, 20}, {bucketSizeNs - 8, 1}); } TEST(ValueMetricProducerTest, TestPushedEventsWithUpgrade) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); valueProducer.notifyAppUpgrade(bucketStartTimeNs + 150, "ANY.APP", 1, 1); EXPECT_EQ(1UL, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucketStartTimeNs + 150, valueProducer.mCurrentBucketStartTimeNs); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 59 * NS_PER_SEC); event2->write(1); event2->write(10); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); EXPECT_EQ(1UL, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucketStartTimeNs + 150, valueProducer.mCurrentBucketStartTimeNs); // Next value should create a new bucket. shared_ptr<LogEvent> event3 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 65 * NS_PER_SEC); event3->write(1); event3->write(10); event3->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event3); EXPECT_EQ(2UL, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, valueProducer.mCurrentBucketStartTimeNs); } TEST(ValueMetricProducerTest, TestPulledValueWithUpgrade) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Return(true)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 149); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(100); event->init(); allData.push_back(event); valueProducer.onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); valueProducer.notifyAppUpgrade(bucket2StartTimeNs + 150, "ANY.APP", 1, 1); EXPECT_EQ(1UL, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucket2StartTimeNs + 150, valueProducer.mCurrentBucketStartTimeNs); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {20}, {150}); allData.clear(); event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(tagId); event->write(150); event->init(); allData.push_back(event); valueProducer.onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); EXPECT_EQ(2UL, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucket3StartTimeNs, valueProducer.mCurrentBucketStartTimeNs); EXPECT_EQ(20L, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].values[0].long_value); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {20, 30}, {150, bucketSizeNs - 150}); } TEST(ValueMetricProducerTest, TestPulledWithAppUpgradeDisabled) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_split_bucket_for_app_upgrade(false); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, Pull(tagId, _)).WillOnce(Return(true)); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(100); event->init(); allData.push_back(event); valueProducer.onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); valueProducer.notifyAppUpgrade(bucket2StartTimeNs + 150, "ANY.APP", 1, 1); EXPECT_EQ(0UL, valueProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucket2StartTimeNs, valueProducer.mCurrentBucketStartTimeNs); } TEST(ValueMetricProducerTest, TestPulledValueWithUpgradeWhileConditionFalse) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs - 100); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 1); valueProducer->onConditionChanged(false, bucket2StartTimeNs-100); EXPECT_FALSE(valueProducer->mCondition); valueProducer->notifyAppUpgrade(bucket2StartTimeNs-50, "ANY.APP", 1, 1); // Expect one full buckets already done and starting a partial bucket. EXPECT_EQ(bucket2StartTimeNs-50, valueProducer->mCurrentBucketStartTimeNs); EXPECT_EQ(1UL, valueProducer->mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size()); EXPECT_EQ(bucketStartTimeNs, valueProducer->mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][0].mBucketStartNs); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {(bucket2StartTimeNs - 100) - (bucketStartTimeNs + 1)}); EXPECT_FALSE(valueProducer->mCondition); } TEST(ValueMetricProducerTest, TestPushedEventsWithoutCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 20); event2->write(1); event2->write(20); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(10, curInterval.value.long_value); EXPECT_EQ(true, curInterval.hasValue); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(30, curInterval.value.long_value); valueProducer.flushIfNeededLocked(bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {30}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestPushedEventsWithCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); valueProducer.mCondition = ConditionState::kFalse; shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has 1 slice EXPECT_EQ(0UL, valueProducer.mCurrentSlicedBucket.size()); valueProducer.onConditionChangedLocked(true, bucketStartTimeNs + 15); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 20); event2->write(1); event2->write(20); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(20, curInterval.value.long_value); shared_ptr<LogEvent> event3 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 30); event3->write(1); event3->write(30); event3->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event3); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(50, curInterval.value.long_value); valueProducer.onConditionChangedLocked(false, bucketStartTimeNs + 35); shared_ptr<LogEvent> event4 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 40); event4->write(1); event4->write(40); event4->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event4); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(50, curInterval.value.long_value); valueProducer.flushIfNeededLocked(bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {50}, {20}); } TEST(ValueMetricProducerTest, TestAnomalyDetection) { sp<AlarmMonitor> alarmMonitor; Alert alert; alert.set_id(101); alert.set_metric_id(metricId); alert.set_trigger_if_sum_gt(130); alert.set_num_buckets(2); const int32_t refPeriodSec = 3; alert.set_refractory_period_secs(refPeriodSec); ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1 /*-1 meaning no condition*/, wizard, logEventMatcherIndex, eventMatcherWizard, -1 /*not pulled*/, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); sp<AnomalyTracker> anomalyTracker = valueProducer.addAnomalyTracker(alert, alarmMonitor); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1 * NS_PER_SEC); event1->write(161); event1->write(10); // value of interest event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 2 + NS_PER_SEC); event2->write(162); event2->write(20); // value of interest event2->init(); shared_ptr<LogEvent> event3 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 2 * bucketSizeNs + 1 * NS_PER_SEC); event3->write(163); event3->write(130); // value of interest event3->init(); shared_ptr<LogEvent> event4 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 1 * NS_PER_SEC); event4->write(35); event4->write(1); // value of interest event4->init(); shared_ptr<LogEvent> event5 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 2 * NS_PER_SEC); event5->write(45); event5->write(150); // value of interest event5->init(); shared_ptr<LogEvent> event6 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 3 * bucketSizeNs + 10 * NS_PER_SEC); event6->write(25); event6->write(160); // value of interest event6->init(); // Two events in bucket #0. valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // Value sum == 30 <= 130. EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U); // One event in bucket #2. No alarm as bucket #0 is trashed out. valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event3); // Value sum == 130 <= 130. EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U); // Three events in bucket #3. valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event4); // Anomaly at event 4 since Value sum == 131 > 130! EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), std::ceil(1.0 * event4->GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec)); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event5); // Event 5 is within 3 sec refractory period. Thus last alarm timestamp is still event4. EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), std::ceil(1.0 * event4->GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec)); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event6); // Anomaly at event 6 since Value sum == 160 > 130 and after refractory period. EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), std::ceil(1.0 * event6->GetElapsedTimestampNs() / NS_PER_SEC + refPeriodSec)); } // Test value metric no condition, the pull on bucket boundary come in time and too late TEST(ValueMetricProducerTest, TestBucketBoundaryNoCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)).WillOnce(Return(true)); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; // pull 1 allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(11); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // startUpdated:true sum:0 start:11 EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(11, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); // pull 2 at correct time allData.clear(); event = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event->write(tagId); event->write(23); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // tartUpdated:false sum:12 EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(23, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {12}, {bucketSizeNs}); // pull 3 come late. // The previous bucket gets closed with error. (Has start value 23, no ending) // Another bucket gets closed with error. (No start, but ending with 36) // The new bucket is back to normal. allData.clear(); event = make_shared<LogEvent>(tagId, bucket6StartTimeNs + 1); event->write(tagId); event->write(36); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket6StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // startUpdated:false sum:12 EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(36, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {12}, {bucketSizeNs}); } /* * Test pulled event with non sliced condition. The pull on boundary come late because the alarm * was delivered late. */ TEST(ValueMetricProducerTest, TestBucketBoundaryWithCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // condition becomes true .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })) // condition becomes false .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(100, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); // pull on bucket boundary come late, condition change happens before it valueProducer->onConditionChanged(false, bucket2StartTimeNs + 1); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {bucketSizeNs - 8}); EXPECT_EQ(false, curInterval.hasBase); // Now the alarm is delivered. // since the condition turned to off before this pull finish, it has no effect vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 30, 110)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {bucketSizeNs - 8}); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); } /* * Test pulled event with non sliced condition. The pull on boundary come late, after the condition * change to false, and then true again. This is due to alarm delivered late. */ TEST(ValueMetricProducerTest, TestBucketBoundaryWithCondition2) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // condition becomes true .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })) // condition becomes false .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })) // condition becomes true again .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 25); event->write(tagId); event->write(130); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // startUpdated:false sum:0 start:100 EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(100, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); // pull on bucket boundary come late, condition change happens before it valueProducer->onConditionChanged(false, bucket2StartTimeNs + 1); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {bucketSizeNs - 8}); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); // condition changed to true again, before the pull alarm is delivered valueProducer->onConditionChanged(true, bucket2StartTimeNs + 25); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {bucketSizeNs - 8}); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(130, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); // Now the alarm is delivered, but it is considered late, the data will be used // for the new bucket since it was just pulled. vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 50, 140)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs + 50); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(140, curInterval.base.long_value); EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(10, curInterval.value.long_value); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {bucketSizeNs - 8}); allData.clear(); allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket3StartTimeNs, 160)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20, 30}, {bucketSizeNs - 8, bucketSizeNs - 24}); } TEST(ValueMetricProducerTest, TestPushedAggregateMin) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_aggregation_type(ValueMetric::MIN); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 20); event2->write(1); event2->write(20); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(10, curInterval.value.long_value); EXPECT_EQ(true, curInterval.hasValue); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(10, curInterval.value.long_value); valueProducer.flushIfNeededLocked(bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {10}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestPushedAggregateMax) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_aggregation_type(ValueMetric::MAX); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 20); event2->write(1); event2->write(20); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(10, curInterval.value.long_value); EXPECT_EQ(true, curInterval.hasValue); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(20, curInterval.value.long_value); valueProducer.flushIfNeededLocked(bucket3StartTimeNs); /* EXPECT_EQ(1UL, valueProducer.mPastBuckets.size()); */ /* EXPECT_EQ(1UL, valueProducer.mPastBuckets.begin()->second.size()); */ /* EXPECT_EQ(20, valueProducer.mPastBuckets.begin()->second.back().values[0].long_value); */ } TEST(ValueMetricProducerTest, TestPushedAggregateAvg) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_aggregation_type(ValueMetric::AVG); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 20); event2->write(1); event2->write(15); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval; curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(10, curInterval.value.long_value); EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(1, curInterval.sampleSize); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(25, curInterval.value.long_value); EXPECT_EQ(2, curInterval.sampleSize); valueProducer.flushIfNeededLocked(bucket2StartTimeNs); EXPECT_EQ(1UL, valueProducer.mPastBuckets.size()); EXPECT_EQ(1UL, valueProducer.mPastBuckets.begin()->second.size()); EXPECT_TRUE(std::abs(valueProducer.mPastBuckets.begin()->second.back().values[0].double_value - 12.5) < epsilon); } TEST(ValueMetricProducerTest, TestPushedAggregateSum) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_aggregation_type(ValueMetric::SUM); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 20); event2->write(1); event2->write(15); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(10, curInterval.value.long_value); EXPECT_EQ(true, curInterval.hasValue); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(25, curInterval.value.long_value); valueProducer.flushIfNeededLocked(bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {25}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestSkipZeroDiffOutput) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_aggregation_type(ValueMetric::MIN); metric.set_use_diff(true); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 15); event2->write(1); event2->write(15); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(10, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(5, curInterval.value.long_value); // no change in data. shared_ptr<LogEvent> event3 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 10); event3->write(1); event3->write(15); event3->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event3); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(15, curInterval.base.long_value); EXPECT_EQ(true, curInterval.hasValue); shared_ptr<LogEvent> event4 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 15); event4->write(1); event4->write(15); event4->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event4); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval = valueProducer.mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(15, curInterval.base.long_value); EXPECT_EQ(true, curInterval.hasValue); valueProducer.flushIfNeededLocked(bucket3StartTimeNs); EXPECT_EQ(1UL, valueProducer.mPastBuckets.size()); EXPECT_EQ(1UL, valueProducer.mPastBuckets.begin()->second.size()); assertPastBucketValuesSingleKey(valueProducer.mPastBuckets, {5}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestSkipZeroDiffOutputMultiValue) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_value_field()->add_child()->set_field(3); metric.set_aggregation_type(ValueMetric::MIN); metric.set_use_diff(true); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, -1, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event1->write(1); event1->write(10); event1->write(20); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucketStartTimeNs + 15); event2->write(1); event2->write(15); event2->write(22); event2->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval0 = valueProducer.mCurrentSlicedBucket.begin()->second[0]; ValueMetricProducer::Interval curInterval1 = valueProducer.mCurrentSlicedBucket.begin()->second[1]; EXPECT_EQ(true, curInterval0.hasBase); EXPECT_EQ(10, curInterval0.base.long_value); EXPECT_EQ(false, curInterval0.hasValue); EXPECT_EQ(true, curInterval1.hasBase); EXPECT_EQ(20, curInterval1.base.long_value); EXPECT_EQ(false, curInterval1.hasValue); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2); // has one slice EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval0 = valueProducer.mCurrentSlicedBucket.begin()->second[0]; curInterval1 = valueProducer.mCurrentSlicedBucket.begin()->second[1]; EXPECT_EQ(true, curInterval0.hasValue); EXPECT_EQ(5, curInterval0.value.long_value); EXPECT_EQ(true, curInterval1.hasValue); EXPECT_EQ(2, curInterval1.value.long_value); // no change in first value field shared_ptr<LogEvent> event3 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 10); event3->write(1); event3->write(15); event3->write(25); event3->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event3); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval0 = valueProducer.mCurrentSlicedBucket.begin()->second[0]; curInterval1 = valueProducer.mCurrentSlicedBucket.begin()->second[1]; EXPECT_EQ(true, curInterval0.hasBase); EXPECT_EQ(15, curInterval0.base.long_value); EXPECT_EQ(true, curInterval0.hasValue); EXPECT_EQ(true, curInterval1.hasBase); EXPECT_EQ(25, curInterval1.base.long_value); EXPECT_EQ(true, curInterval1.hasValue); shared_ptr<LogEvent> event4 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 15); event4->write(1); event4->write(15); event4->write(29); event4->init(); valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event4); EXPECT_EQ(1UL, valueProducer.mCurrentSlicedBucket.size()); curInterval0 = valueProducer.mCurrentSlicedBucket.begin()->second[0]; curInterval1 = valueProducer.mCurrentSlicedBucket.begin()->second[1]; EXPECT_EQ(true, curInterval0.hasBase); EXPECT_EQ(15, curInterval0.base.long_value); EXPECT_EQ(true, curInterval0.hasValue); EXPECT_EQ(true, curInterval1.hasBase); EXPECT_EQ(29, curInterval1.base.long_value); EXPECT_EQ(true, curInterval1.hasValue); valueProducer.flushIfNeededLocked(bucket3StartTimeNs); EXPECT_EQ(1UL, valueProducer.mPastBuckets.size()); EXPECT_EQ(2UL, valueProducer.mPastBuckets.begin()->second.size()); EXPECT_EQ(2UL, valueProducer.mPastBuckets.begin()->second[0].values.size()); EXPECT_EQ(1UL, valueProducer.mPastBuckets.begin()->second[1].values.size()); EXPECT_EQ(bucketSizeNs, valueProducer.mPastBuckets.begin()->second[0].mConditionTrueNs); EXPECT_EQ(5, valueProducer.mPastBuckets.begin()->second[0].values[0].long_value); EXPECT_EQ(0, valueProducer.mPastBuckets.begin()->second[0].valueIndex[0]); EXPECT_EQ(2, valueProducer.mPastBuckets.begin()->second[0].values[1].long_value); EXPECT_EQ(1, valueProducer.mPastBuckets.begin()->second[0].valueIndex[1]); EXPECT_EQ(bucketSizeNs, valueProducer.mPastBuckets.begin()->second[1].mConditionTrueNs); EXPECT_EQ(3, valueProducer.mPastBuckets.begin()->second[1].values[0].long_value); EXPECT_EQ(1, valueProducer.mPastBuckets.begin()->second[1].valueIndex[0]); } /* * Tests zero default base. */ TEST(ValueMetricProducerTest, TestUseZeroDefaultBase) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_dimensions_in_what()->set_field(tagId); metric.mutable_dimensions_in_what()->add_child()->set_field(1); metric.set_use_zero_default_base(true); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(1); event->write(3); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); auto iter = valueProducer->mCurrentSlicedBucket.begin(); auto& interval1 = iter->second[0]; EXPECT_EQ(1, iter->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval1.hasBase); EXPECT_EQ(3, interval1.base.long_value); EXPECT_EQ(false, interval1.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event1->write(2); event1->write(4); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event2->write(1); event2->write(11); event2->init(); allData.push_back(event1); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(2UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(true, interval1.hasBase); EXPECT_EQ(11, interval1.base.long_value); EXPECT_EQ(false, interval1.hasValue); EXPECT_EQ(8, interval1.value.long_value); auto it = valueProducer->mCurrentSlicedBucket.begin(); for (; it != valueProducer->mCurrentSlicedBucket.end(); it++) { if (it != iter) { break; } } EXPECT_TRUE(it != iter); auto& interval2 = it->second[0]; EXPECT_EQ(2, it->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval2.hasBase); EXPECT_EQ(4, interval2.base.long_value); EXPECT_EQ(false, interval2.hasValue); EXPECT_EQ(4, interval2.value.long_value); EXPECT_EQ(2UL, valueProducer->mPastBuckets.size()); auto iterator = valueProducer->mPastBuckets.begin(); EXPECT_EQ(bucketSizeNs, iterator->second[0].mConditionTrueNs); EXPECT_EQ(8, iterator->second[0].values[0].long_value); iterator++; EXPECT_EQ(bucketSizeNs, iterator->second[0].mConditionTrueNs); EXPECT_EQ(4, iterator->second[0].values[0].long_value); } /* * Tests using zero default base with failed pull. */ TEST(ValueMetricProducerTest, TestUseZeroDefaultBaseWithPullFailures) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_dimensions_in_what()->set_field(tagId); metric.mutable_dimensions_in_what()->add_child()->set_field(1); metric.set_use_zero_default_base(true); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(1); event->write(3); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); auto iter = valueProducer->mCurrentSlicedBucket.begin(); auto& interval1 = iter->second[0]; EXPECT_EQ(1, iter->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval1.hasBase); EXPECT_EQ(3, interval1.base.long_value); EXPECT_EQ(false, interval1.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event1->write(2); event1->write(4); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event2->write(1); event2->write(11); event2->init(); allData.push_back(event1); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(2UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(true, interval1.hasBase); EXPECT_EQ(11, interval1.base.long_value); EXPECT_EQ(false, interval1.hasValue); EXPECT_EQ(8, interval1.value.long_value); auto it = valueProducer->mCurrentSlicedBucket.begin(); for (; it != valueProducer->mCurrentSlicedBucket.end(); it++) { if (it != iter) { break; } } EXPECT_TRUE(it != iter); auto& interval2 = it->second[0]; EXPECT_EQ(2, it->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval2.hasBase); EXPECT_EQ(4, interval2.base.long_value); EXPECT_EQ(false, interval2.hasValue); EXPECT_EQ(4, interval2.value.long_value); EXPECT_EQ(2UL, valueProducer->mPastBuckets.size()); // next pull somehow did not happen, skip to end of bucket 3 allData.clear(); event1 = make_shared<LogEvent>(tagId, bucket4StartTimeNs + 1); event1->write(2); event1->write(5); event1->init(); allData.push_back(event1); valueProducer->onDataPulled(allData, /** succeed */ true, bucket4StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(true, interval2.hasBase); EXPECT_EQ(5, interval2.base.long_value); EXPECT_EQ(false, interval2.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); EXPECT_EQ(2UL, valueProducer->mPastBuckets.size()); allData.clear(); event1 = make_shared<LogEvent>(tagId, bucket5StartTimeNs + 1); event1->write(2); event1->write(13); event1->init(); allData.push_back(event1); event2 = make_shared<LogEvent>(tagId, bucket5StartTimeNs + 1); event2->write(1); event2->write(5); event2->init(); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket5StartTimeNs); EXPECT_EQ(2UL, valueProducer->mCurrentSlicedBucket.size()); auto it1 = std::next(valueProducer->mCurrentSlicedBucket.begin())->second[0]; EXPECT_EQ(true, it1.hasBase); EXPECT_EQ(13, it1.base.long_value); EXPECT_EQ(false, it1.hasValue); EXPECT_EQ(8, it1.value.long_value); auto it2 = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, it2.hasBase); EXPECT_EQ(5, it2.base.long_value); EXPECT_EQ(false, it2.hasValue); EXPECT_EQ(5, it2.value.long_value); EXPECT_EQ(true, valueProducer->mHasGlobalBase); EXPECT_EQ(2UL, valueProducer->mPastBuckets.size()); } /* * Tests trim unused dimension key if no new data is seen in an entire bucket. */ TEST(ValueMetricProducerTest, TestTrimUnusedDimensionKey) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_dimensions_in_what()->set_field(tagId); metric.mutable_dimensions_in_what()->add_child()->set_field(1); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(1); event->write(3); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); auto iter = valueProducer->mCurrentSlicedBucket.begin(); auto& interval1 = iter->second[0]; EXPECT_EQ(1, iter->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval1.hasBase); EXPECT_EQ(3, interval1.base.long_value); EXPECT_EQ(false, interval1.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event1 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event1->write(2); event1->write(4); event1->init(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event2->write(1); event2->write(11); event2->init(); allData.push_back(event1); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(2UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(true, interval1.hasBase); EXPECT_EQ(11, interval1.base.long_value); EXPECT_EQ(false, interval1.hasValue); EXPECT_EQ(8, interval1.value.long_value); EXPECT_FALSE(interval1.seenNewData); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {8}, {bucketSizeNs}); auto it = valueProducer->mCurrentSlicedBucket.begin(); for (; it != valueProducer->mCurrentSlicedBucket.end(); it++) { if (it != iter) { break; } } EXPECT_TRUE(it != iter); auto& interval2 = it->second[0]; EXPECT_EQ(2, it->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval2.hasBase); EXPECT_EQ(4, interval2.base.long_value); EXPECT_EQ(false, interval2.hasValue); EXPECT_FALSE(interval2.seenNewData); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {8}, {bucketSizeNs}); // next pull somehow did not happen, skip to end of bucket 3 allData.clear(); event1 = make_shared<LogEvent>(tagId, bucket4StartTimeNs + 1); event1->write(2); event1->write(5); event1->init(); allData.push_back(event1); valueProducer->onDataPulled(allData, /** succeed */ true, bucket4StartTimeNs); // Only one interval left. One was trimmed. EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); interval2 = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(2, it->first.getDimensionKeyInWhat().getValues()[0].mValue.int_value); EXPECT_EQ(true, interval2.hasBase); EXPECT_EQ(5, interval2.base.long_value); EXPECT_EQ(false, interval2.hasValue); EXPECT_FALSE(interval2.seenNewData); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {8}, {bucketSizeNs}); allData.clear(); event1 = make_shared<LogEvent>(tagId, bucket5StartTimeNs + 1); event1->write(2); event1->write(14); event1->init(); allData.push_back(event1); valueProducer->onDataPulled(allData, /** succeed */ true, bucket5StartTimeNs); interval2 = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, interval2.hasBase); EXPECT_EQ(14, interval2.base.long_value); EXPECT_EQ(false, interval2.hasValue); EXPECT_FALSE(interval2.seenNewData); ASSERT_EQ(2UL, valueProducer->mPastBuckets.size()); auto iterator = valueProducer->mPastBuckets.begin(); EXPECT_EQ(9, iterator->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, iterator->second[0].mConditionTrueNs); iterator++; EXPECT_EQ(8, iterator->second[0].values[0].long_value); EXPECT_EQ(bucketSizeNs, iterator->second[0].mConditionTrueNs); } TEST(ValueMetricProducerTest, TestResetBaseOnPullFailAfterConditionChange_EndOfBucket) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); // Used by onConditionChanged. EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(100, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); vector<shared_ptr<LogEvent>> allData; valueProducer->onDataPulled(allData, /** succeed */ false, bucket2StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(false, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestResetBaseOnPullFailAfterConditionChange) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })) .WillOnce(Return(false)); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(100, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); valueProducer->onConditionChanged(false, bucketStartTimeNs + 20); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestResetBaseOnPullFailBeforeConditionChange) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(50); event->init(); data->push_back(event); return false; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); // Don't directly set mCondition; the real code never does that. Go through regular code path // to avoid unexpected behaviors. // valueProducer->mCondition = ConditionState::kTrue; valueProducer->onConditionChanged(true, bucketStartTimeNs); EXPECT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); valueProducer->onConditionChanged(false, bucketStartTimeNs + 1); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(false, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestResetBaseOnPullDelayExceeded) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_condition(StringToId("SCREEN_ON")); metric.set_max_pull_delay_sec(0); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; // Max delay is set to 0 so pull will exceed max delay. valueProducer->onConditionChanged(true, bucketStartTimeNs + 1); EXPECT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); } TEST(ValueMetricProducerTest, TestResetBaseOnPullTooLate) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return()); ValueMetricProducer valueProducer(kConfigKey, metric, 1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucket2StartTimeNs, bucket2StartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); valueProducer.mCondition = ConditionState::kFalse; // Event should be skipped since it is from previous bucket. // Pull should not be called. valueProducer.onConditionChanged(true, bucketStartTimeNs); EXPECT_EQ(0UL, valueProducer.mCurrentSlicedBucket.size()); } TEST(ValueMetricProducerTest, TestBaseSetOnConditionChange) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(tagId); event->write(100); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; valueProducer->mHasGlobalBase = false; valueProducer->onConditionChanged(true, bucketStartTimeNs + 1); valueProducer->mHasGlobalBase = true; EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(100, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestInvalidBucketWhenOneConditionFailed) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Return(false)) // Second onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(130); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kTrue; // Bucket start. vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(1); event->write(110); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucketStartTimeNs); // This will fail and should invalidate the whole bucket since we do not have all the data // needed to compute the metric value when the screen was on. valueProducer->onConditionChanged(false, bucketStartTimeNs + 2); valueProducer->onConditionChanged(true, bucketStartTimeNs + 3); // Bucket end. allData.clear(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event2->write(1); event2->write(140); event2->init(); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); valueProducer->flushIfNeededLocked(bucket2StartTimeNs + 1); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); // Contains base from last pull which was successful. EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(140, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestInvalidBucketWhenGuardRailHit) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_dimensions_in_what()->set_field(tagId); metric.mutable_dimensions_in_what()->add_child()->set_field(1); metric.set_condition(StringToId("SCREEN_ON")); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { for (int i = 0; i < 2000; i++) { shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(i); event->write(i); event->init(); data->push_back(event); } return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; valueProducer->onConditionChanged(true, bucketStartTimeNs + 2); EXPECT_EQ(true, valueProducer->mCurrentBucketIsInvalid); EXPECT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); } TEST(ValueMetricProducerTest, TestInvalidBucketWhenInitialPullFailed) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })) // Second onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(130); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kTrue; // Bucket start. vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(1); event->write(110); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ false, bucketStartTimeNs); valueProducer->onConditionChanged(false, bucketStartTimeNs + 2); valueProducer->onConditionChanged(true, bucketStartTimeNs + 3); // Bucket end. allData.clear(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event2->write(1); event2->write(140); event2->init(); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); valueProducer->flushIfNeededLocked(bucket2StartTimeNs + 1); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); // Contains base from last pull which was successful. EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(140, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestInvalidBucketWhenLastPullFailed) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(120); event->init(); data->push_back(event); return true; })) // Second onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 8); event->write(tagId); event->write(130); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kTrue; // Bucket start. vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 1); event->write(1); event->write(110); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucketStartTimeNs); // This will fail and should invalidate the whole bucket since we do not have all the data // needed to compute the metric value when the screen was on. valueProducer->onConditionChanged(false, bucketStartTimeNs + 2); valueProducer->onConditionChanged(true, bucketStartTimeNs + 3); // Bucket end. allData.clear(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event2->write(1); event2->write(140); event2->init(); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ false, bucket2StartTimeNs); valueProducer->flushIfNeededLocked(bucket2StartTimeNs + 1); EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); // Last pull failed so based has been reset. EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(false, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestEmptyDataResetsBase_onDataPulled) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Start bucket. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(3); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); // Bucket 2 start. vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(110); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); // Bucket 3 empty. allData.clear(); shared_ptr<LogEvent> event2 = make_shared<LogEvent>(tagId, bucket3StartTimeNs + 1); event2->init(); allData.push_back(event2); valueProducer->onDataPulled(allData, /** succeed */ true, bucket3StartTimeNs); // Data has been trimmed. EXPECT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); } TEST(ValueMetricProducerTest, TestEmptyDataResetsBase_onConditionChanged) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(3); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 10); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); // Empty pull. valueProducer->onConditionChanged(false, bucketStartTimeNs + 10); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(false, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestEmptyDataResetsBase_onBucketBoundary) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(1); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(2); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(5); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 10); valueProducer->onConditionChanged(false, bucketStartTimeNs + 11); valueProducer->onConditionChanged(true, bucketStartTimeNs + 12); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval& curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); // End of bucket vector<shared_ptr<LogEvent>> allData; allData.clear(); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; // Data is empty, base should be reset. EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(5, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); EXPECT_EQ(1UL, valueProducer->mPastBuckets.size()); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {1}, {bucketSizeNs - 12 + 1}); } TEST(ValueMetricProducerTest, TestPartialResetOnBucketBoundaries) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_dimensions_in_what()->set_field(tagId); metric.mutable_dimensions_in_what()->add_child()->set_field(1); metric.set_condition(StringToId("SCREEN_ON")); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First onConditionChanged .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(1); event->write(1); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 10); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); // End of bucket vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(2); event->write(2); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // Key 1 should be reset since in not present in the most pull. EXPECT_EQ(2UL, valueProducer->mCurrentSlicedBucket.size()); auto iterator = valueProducer->mCurrentSlicedBucket.begin(); EXPECT_EQ(true, iterator->second[0].hasBase); EXPECT_EQ(2, iterator->second[0].base.long_value); EXPECT_EQ(false, iterator->second[0].hasValue); iterator++; EXPECT_EQ(false, iterator->second[0].hasBase); EXPECT_EQ(1, iterator->second[0].base.long_value); EXPECT_EQ(false, iterator->second[0].hasValue); EXPECT_EQ(true, valueProducer->mHasGlobalBase); } TEST(ValueMetricProducerTest, TestBucketIncludingUnknownConditionIsInvalid) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.mutable_dimensions_in_what()->set_field(tagId); metric.mutable_dimensions_in_what()->add_child()->set_field(1); metric.set_condition(StringToId("SCREEN_ON")); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Second onConditionChanged. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(2); event->write(2); event->init(); data->push_back(event); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kUnknown; valueProducer->onConditionChanged(false, bucketStartTimeNs + 10); valueProducer->onConditionChanged(true, bucketStartTimeNs + 20); // End of bucket vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(4); event->write(4); event->init(); allData.push_back(event); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // Bucket is incomplete so it is mark as invalid, however the base is fine since the last pull // succeeded. EXPECT_EQ(0UL, valueProducer->mPastBuckets.size()); } TEST(ValueMetricProducerTest, TestFullBucketResetWhenLastBucketInvalid) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initialization. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs, 1)); return true; })) // notifyAppUpgrade. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent( bucketStartTimeNs + bucketSizeNs / 2, 10)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); ASSERT_EQ(0UL, valueProducer->mCurrentFullBucket.size()); valueProducer->notifyAppUpgrade(bucketStartTimeNs + bucketSizeNs / 2, "com.foo", 10000, 1); ASSERT_EQ(1UL, valueProducer->mCurrentFullBucket.size()); vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket3StartTimeNs + 1, 4)); valueProducer->onDataPulled(allData, /** fails */ false, bucket3StartTimeNs + 1); ASSERT_EQ(0UL, valueProducer->mCurrentFullBucket.size()); } TEST(ValueMetricProducerTest, TestBucketBoundariesOnConditionChange) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Second onConditionChanged. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back( ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 10, 5)); return true; })) // Third onConditionChanged. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back( ValueMetricProducerTestHelper::createEvent(bucket3StartTimeNs + 10, 7)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kUnknown; valueProducer->onConditionChanged(false, bucketStartTimeNs); ASSERT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); // End of first bucket vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 1, 4)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs + 1); ASSERT_EQ(0UL, valueProducer->mCurrentSlicedBucket.size()); valueProducer->onConditionChanged(true, bucket2StartTimeNs + 10); ASSERT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); auto curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasBase); EXPECT_EQ(5, curInterval.base.long_value); EXPECT_EQ(false, curInterval.hasValue); valueProducer->onConditionChanged(false, bucket3StartTimeNs + 10); // Bucket should have been completed. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {2}, {bucketSizeNs - 10}); } TEST(ValueMetricProducerTest, TestLateOnDataPulledWithoutDiff) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_use_diff(false); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs + 30, 10)); valueProducer->onDataPulled(allData, /** succeed */ true, bucketStartTimeNs + 30); allData.clear(); allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs, 20)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // Bucket should have been completed. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {30}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestLateOnDataPulledWithDiff) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initialization. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs, 1)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs + 30, 10)); valueProducer->onDataPulled(allData, /** succeed */ true, bucketStartTimeNs + 30); allData.clear(); allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs, 20)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // Bucket should have been completed. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {19}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestBucketBoundariesOnAppUpgrade) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initialization. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs, 1)); return true; })) // notifyAppUpgrade. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back( ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 2, 10)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); valueProducer->notifyAppUpgrade(bucket2StartTimeNs + 2, "com.foo", 10000, 1); // Bucket should have been completed. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {9}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestDataIsNotUpdatedWhenNoConditionChanged) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First on condition changed. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs, 1)); return true; })) // Second on condition changed. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs, 3)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); valueProducer->onConditionChanged(false, bucketStartTimeNs + 10); valueProducer->onConditionChanged(false, bucketStartTimeNs + 10); EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); auto curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(2, curInterval.value.long_value); vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 1, 10)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs + 1); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {2}, {2}); } TEST(ValueMetricProducerTest, TestBucketInvalidIfGlobalBaseIsNotSet) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // First condition change. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs, 1)); return true; })) // 2nd condition change. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs, 1)); return true; })) // 3rd condition change. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs, 1)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->onConditionChanged(true, bucket2StartTimeNs + 10); vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucketStartTimeNs + 3, 10)); valueProducer->onDataPulled(allData, /** succeed */ false, bucketStartTimeNs + 3); allData.clear(); allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs, 20)); valueProducer->onDataPulled(allData, /** succeed */ false, bucket2StartTimeNs); valueProducer->onConditionChanged(false, bucket2StartTimeNs + 8); valueProducer->onConditionChanged(true, bucket2StartTimeNs + 10); allData.clear(); allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket3StartTimeNs, 30)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // There was not global base available so all buckets are invalid. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {}, {}); } static StatsLogReport outputStreamToProto(ProtoOutputStream* proto) { vector<uint8_t> bytes; bytes.resize(proto->size()); size_t pos = 0; sp<ProtoReader> reader = proto->data(); while (reader->readBuffer() != NULL) { size_t toRead = reader->currentToRead(); std::memcpy(&((bytes)[pos]), reader->readBuffer(), toRead); pos += toRead; reader->move(toRead); } StatsLogReport report; report.ParseFromArray(bytes.data(), bytes.size()); return report; } TEST(ValueMetricProducerTest, TestPullNeededFastDump) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return()); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initial pull. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(1); event->write(1); event->init(); data->push_back(event); return true; })); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); ProtoOutputStream output; std::set<string> strSet; valueProducer.onDumpReport(bucketStartTimeNs + 10, true /* include recent buckets */, true, FAST, &strSet, &output); StatsLogReport report = outputStreamToProto(&output); // Bucket is invalid since we did not pull when dump report was called. EXPECT_EQ(0, report.value_metrics().data_size()); } TEST(ValueMetricProducerTest, TestFastDumpWithoutCurrentBucket) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return()); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initial pull. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(1); event->write(1); event->init(); data->push_back(event); return true; })); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); vector<shared_ptr<LogEvent>> allData; allData.clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucket2StartTimeNs + 1); event->write(tagId); event->write(2); event->write(2); event->init(); allData.push_back(event); valueProducer.onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); ProtoOutputStream output; std::set<string> strSet; valueProducer.onDumpReport(bucket4StartTimeNs, false /* include recent buckets */, true, FAST, &strSet, &output); StatsLogReport report = outputStreamToProto(&output); // Previous bucket is part of the report. EXPECT_EQ(1, report.value_metrics().data_size()); EXPECT_EQ(0, report.value_metrics().data(0).bucket_info(0).bucket_num()); } TEST(ValueMetricProducerTest, TestPullNeededNoTimeConstraints) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); UidMap uidMap; SimpleAtomMatcher atomMatcher; atomMatcher.set_atom_id(tagId); sp<EventMatcherWizard> eventMatcherWizard = new EventMatcherWizard({new SimpleLogMatchingTracker( atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)}); sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>(); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, RegisterReceiver(tagId, _, _, _)).WillOnce(Return()); EXPECT_CALL(*pullerManager, UnRegisterReceiver(tagId, _)).WillRepeatedly(Return()); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // Initial pull. .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs); event->write(tagId); event->write(1); event->write(1); event->init(); data->push_back(event); return true; })) .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); shared_ptr<LogEvent> event = make_shared<LogEvent>(tagId, bucketStartTimeNs + 10); event->write(tagId); event->write(3); event->write(3); event->init(); data->push_back(event); return true; })); ValueMetricProducer valueProducer(kConfigKey, metric, -1, wizard, logEventMatcherIndex, eventMatcherWizard, tagId, bucketStartTimeNs, bucketStartTimeNs, pullerManager); valueProducer.prepareFirstBucket(); ProtoOutputStream output; std::set<string> strSet; valueProducer.onDumpReport(bucketStartTimeNs + 10, true /* include recent buckets */, true, NO_TIME_CONSTRAINTS, &strSet, &output); StatsLogReport report = outputStreamToProto(&output); EXPECT_EQ(1, report.value_metrics().data_size()); EXPECT_EQ(1, report.value_metrics().data(0).bucket_info_size()); EXPECT_EQ(2, report.value_metrics().data(0).bucket_info(0).values(0).value_long()); } TEST(ValueMetricProducerTest, TestPulledData_noDiff_withoutCondition) { ValueMetric metric = ValueMetricProducerTestHelper::createMetric(); metric.set_use_diff(false); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerNoConditions(pullerManager, metric); vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 30, 10)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs + 30); // Bucket should have been completed. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {10}, {bucketSizeNs}); } TEST(ValueMetricProducerTest, TestPulledData_noDiff_withMultipleConditionChanges) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); metric.set_use_diff(false); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // condition becomes true .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent( bucketStartTimeNs + 30, 10)); return true; })) // condition becomes false .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent( bucketStartTimeNs + 50, 20)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); valueProducer->onConditionChanged(false, bucketStartTimeNs + 50); // has one slice EXPECT_EQ(1UL, valueProducer->mCurrentSlicedBucket.size()); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(true, curInterval.hasValue); EXPECT_EQ(20, curInterval.value.long_value); // Now the alarm is delivered. Condition is off though. vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 30, 110)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {20}, {50 - 8}); curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); } TEST(ValueMetricProducerTest, TestPulledData_noDiff_bucketBoundaryTrue) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); metric.set_use_diff(false); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // condition becomes true .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent( bucketStartTimeNs + 30, 10)); return true; })); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); // Now the alarm is delivered. Condition is off though. vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 30, 30)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {30}, {bucketSizeNs - 8}); ValueMetricProducer::Interval curInterval = valueProducer->mCurrentSlicedBucket.begin()->second[0]; EXPECT_EQ(false, curInterval.hasBase); EXPECT_EQ(false, curInterval.hasValue); } TEST(ValueMetricProducerTest, TestPulledData_noDiff_bucketBoundaryFalse) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); metric.set_use_diff(false); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; // Now the alarm is delivered. Condition is off though. vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 30, 30)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // Condition was always false. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {}, {}); } TEST(ValueMetricProducerTest, TestPulledData_noDiff_withFailure) { ValueMetric metric = ValueMetricProducerTestHelper::createMetricWithCondition(); metric.set_use_diff(false); sp<MockStatsPullerManager> pullerManager = new StrictMock<MockStatsPullerManager>(); EXPECT_CALL(*pullerManager, Pull(tagId, _)) // condition becomes true .WillOnce(Invoke([](int tagId, vector<std::shared_ptr<LogEvent>>* data) { data->clear(); data->push_back(ValueMetricProducerTestHelper::createEvent( bucketStartTimeNs + 30, 10)); return true; })) .WillOnce(Return(false)); sp<ValueMetricProducer> valueProducer = ValueMetricProducerTestHelper::createValueProducerWithCondition(pullerManager, metric); valueProducer->mCondition = ConditionState::kFalse; valueProducer->onConditionChanged(true, bucketStartTimeNs + 8); valueProducer->onConditionChanged(false, bucketStartTimeNs + 50); // Now the alarm is delivered. Condition is off though. vector<shared_ptr<LogEvent>> allData; allData.push_back(ValueMetricProducerTestHelper::createEvent(bucket2StartTimeNs + 30, 30)); valueProducer->onDataPulled(allData, /** succeed */ true, bucket2StartTimeNs); // No buckets, we had a failure. assertPastBucketValuesSingleKey(valueProducer->mPastBuckets, {}, {}); } } // namespace statsd } // namespace os } // namespace android #else GTEST_LOG_(INFO) << "This test does nothing.\n"; #endif
45.080115
103
0.69066
[ "vector" ]
2263ad0b6076abd6b9cbac4d322eadb6bc0893ab
1,824
cpp
C++
webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopFrame.cpp
hhgyu/webrtc-java
572c3814c94a407cfacdee1e2bc898522063731f
[ "Apache-2.0" ]
1
2020-10-18T04:59:44.000Z
2020-10-18T04:59:44.000Z
webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopFrame.cpp
hhgyu/webrtc-java
572c3814c94a407cfacdee1e2bc898522063731f
[ "Apache-2.0" ]
null
null
null
webrtc-jni/src/main/cpp/src/media/video/desktop/DesktopFrame.cpp
hhgyu/webrtc-java
572c3814c94a407cfacdee1e2bc898522063731f
[ "Apache-2.0" ]
1
2021-04-22T12:30:45.000Z
2021-04-22T12:30:45.000Z
/* * Copyright 2019 Alex Andres * * 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 "media/video/desktop/DesktopFrame.h" #include "JavaClasses.h" #include "JavaDimension.h" #include "JavaRectangle.h" #include "JNI_WebRTC.h" namespace jni { namespace DesktopFrame { JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::DesktopFrame * frame) { if (frame == nullptr) { return nullptr; } const webrtc::DesktopRect & rect = frame->rect(); const webrtc::DesktopSize & size = frame->size(); const auto javaClass = JavaClasses::get<JavaDesktopFrameClass>(env); jobject buffer = env->NewDirectByteBuffer(frame->data(), frame->stride() * frame->size().height()); jobject object = env->NewObject(javaClass->cls, javaClass->ctor, JavaRectangle::toJava(env, rect.left(), rect.top(), rect.width(), rect.height()).get(), JavaDimension::toJava(env, size.width(), size.height()).get(), static_cast<jfloat>(frame->scale_factor()), static_cast<jint>(frame->stride()), buffer); return JavaLocalRef<jobject>(env, object); } JavaDesktopFrameClass::JavaDesktopFrameClass(JNIEnv * env) { cls = FindClass(env, PKG_MEDIA"DesktopFrame"); ctor = GetMethod(env, cls, "<init>", "(Ljava/awt/Rectangle;Ljava/awt/Dimension;FI" BYTE_BUFFER_SIG ")V"); } } }
32
108
0.70614
[ "object" ]
226ccf933435c8c2b180b290c26d629ce0c15668
2,160
cpp
C++
15. 3sum.cpp
dipta007/leetcode-solutions-dipta007
0454ad24ce686a37fab8025c75efb7d857985f29
[ "MIT" ]
null
null
null
15. 3sum.cpp
dipta007/leetcode-solutions-dipta007
0454ad24ce686a37fab8025c75efb7d857985f29
[ "MIT" ]
null
null
null
15. 3sum.cpp
dipta007/leetcode-solutions-dipta007
0454ad24ce686a37fab8025c75efb7d857985f29
[ "MIT" ]
null
null
null
#define ff first #define ss second #define pii pair < int, int > class Solution { public: pii find(vector < pii > &vp, int strt, int end, int val) { int low = strt, high = end; while(low <= high) { int mid = (low + high) / 2; if(vp[mid].ff < val) { low = mid + 1; } else if(vp[mid].ff > val) { high = mid - 1; } else return vp[mid]; } return pii(-1, -1); } vector<vector<int>> threeSum(vector<int>& nums) { cout << nums.size() << endl; vector < vector < int > > res; vector < pii > vp; unordered_map <int, int> count; for(int i=0; i<nums.size(); i++) { count[ nums[i] ]++; } unordered_map <int, int> :: iterator it; for(it=count.begin(); it!=count.end(); it++) { vp.push_back( pii(it->ff, it->ss) ); } sort(vp.begin(), vp.end()); int len = vp.size(); for(int i=0; i<len; i++) { if(vp[i].ss > 1) { int now = vp[i].ff + vp[i].ff; pii p = find(vp, i+1, len-1, -now); if(p.ff != -1) { res.push_back({ vp[i].ff, vp[i].ff, -now }); } } if(vp[i].ff==0 && vp[i].ss>2) { res.push_back({0,0,0}); } for(int j=i+1; j<len; j++) { int now = vp[i].ff + vp[j].ff; if(-now == vp[j].ff && vp[j].ss > 1) { res.push_back({vp[i].ff, vp[j].ff, -now}); continue; } pii p = find(vp, j+1, len-1, -now); if(p.ff != -1) { res.push_back({vp[i].ff, vp[j].ff, -now}); } } } return res; } };
24.827586
64
0.327315
[ "vector" ]
226ce176e969f1b55e73263fd485ef9e1aaebaa8
4,525
cpp
C++
Src/Complan/GenerateTrajectory.cpp
Dronacharya-Org/ComplanV2
6ba7516342ae9a826e2752389fb6f268c1d1f582
[ "MIT" ]
1
2015-07-17T20:21:49.000Z
2015-07-17T20:21:49.000Z
Src/Complan/GenerateTrajectory.cpp
Dronacharya-Org/ComplanV2
6ba7516342ae9a826e2752389fb6f268c1d1f582
[ "MIT" ]
4
2015-07-17T19:50:13.000Z
2015-08-04T05:33:19.000Z
Src/Complan/GenerateTrajectory.cpp
Dronacharya-Org/ComplanV2
6ba7516342ae9a826e2752389fb6f268c1d1f582
[ "MIT" ]
null
null
null
/* File: GenerateTrajectory.cpp Authors: Indranil Saha (isaha@cse.iitk.ac.in) Ankush Desai(ankush@eecs.berkeley.edu) This file is used for generating the trajectory, as a sequence of the motion primitives. */ #include <iostream> #include <fstream> #include <string> #include <stdlib.h> #include "MotionPrimitives.h" #include "InputParser.h" #include "GenerateConstraints.h" #include "Z3OutputParser.h" #ifdef PLAT_WINDOWS #include <Windows.h> #endif using namespace std; const unsigned int max_traj_length = 30; void GenerateZ3File(MotionPrimitive_Vector primitives, int length_x, int length_y, RobotPosition_Vector obstacles, RobotPosition pos_start, RobotPosition pos_end, int number_of_points, float total_cost) { ofstream ofp; ofp.open("constraints.smt2"); /* Declare the variables */ GenerateVariableDeclarations(ofp, number_of_points); /* Write the General Constraints */ GenerateInitialLocationConstraints(ofp, pos_start); ofp << endl; GenerateObstacleConstraints(ofp, length_x, length_y, obstacles); ofp << endl; GenerateTransitionConstraints(ofp, primitives, length_x, length_y, obstacles, number_of_points); ofp << endl; GenerateCostConstraint(ofp, number_of_points, total_cost); ofp << endl; /* Write the specification constraints */ GenerateFinalDestinationConstraints(ofp, pos_end, number_of_points); /* Check the satisfiability of the constraints and output the model */ ofp << "(check-sat)" << endl; //ofp << "(get-model)" << endl; GenerateOutputConstraints(ofp, number_of_points); ofp.close(); } bool GenerateTrajectory(MotionPrimitive_Vector primitives, MotionPrimitive_Cost prim_cost, int length_x, int length_y, RobotPosition_Vector obstacles, RobotPosition pos_start, RobotPosition pos_end, int* trajectory_length) { ifstream ifp; string line; unsigned int count; float cost; ofstream ofp; count = 2; while (true) { cost = count * prim_cost.max_cost; GenerateZ3File(primitives, length_x, length_y, obstacles, pos_start, pos_end, count, cost); system("z3 constraints.smt2 > z3_output"); ifp.open("z3_output"); if (ifp.is_open()) { getline(ifp, line); ifp.close(); } if (line == "unsat") { count = count + 1; if (count > max_traj_length) { cout << "Complan Error: Trajectory does not exist.." << endl; return false; } } else if (line == "sat") { system("cp z3_output z3_output_sat"); break; } else { cout << "Complan Error : unknown output from z3.." << endl; count = count + 1; if (count > max_traj_length) { return false; } } if (count > max_traj_length) break; } //system("perl processoutputfile.pl"); //system("mv planner_output plan_noopt"); *trajectory_length = count; return true; } void OptimizeTrajectory(MotionPrimitive_Vector primitives, MotionPrimitive_Cost prim_cost, int length_x, int length_y, RobotPosition_Vector obstacles, RobotPosition pos_start, RobotPosition pos_end, int trajectory_length) { float max_total_cost, min_total_cost, current_cost; ifstream ifp; string line; ofstream ofp; max_total_cost = trajectory_length * prim_cost.max_cost; min_total_cost = trajectory_length * prim_cost.min_cost; current_cost = (max_total_cost + min_total_cost) / 2; system("mv z3_output z3_output_sat"); while (max_total_cost - min_total_cost > prim_cost.min_cost_diff) { GenerateZ3File(primitives, length_x, length_y, obstacles, pos_start, pos_end, trajectory_length, current_cost); system("z3 constraints.smt2 > z3_output"); ifp.open("z3_output"); getline(ifp, line); ifp.close(); if (line == "unsat") { min_total_cost = current_cost; } else if (line == "sat") { //max_total_cost = ExtractTrajectoryCostInformation(); max_total_cost = current_cost; system("mv z3_output z3_output_sat"); } else { cout << "unknown output from z3.." << endl; min_total_cost = current_cost; } current_cost = (max_total_cost + min_total_cost) / 2; //cout << "max cost = " << max_total_cost << endl; //cout << "min cost = " << min_total_cost << endl; //cout << "current cost = " << current_cost << endl; } system("mv z3_output_sat z3_output"); //system("perl processoutputfile.pl"); //system("mv planner_output plan_opt"); //cout << "Cost = " << ExtractTrajectoryCostInformation() << endl << endl; }
26.461988
222
0.691934
[ "model" ]
2270178bc489454b0ef84a5fbd35779a0aa36a27
2,273
cc
C++
tests/stree-test.cc
dendi239/algorithms-data-structures
43db1aa8340f8ef9669bcb26894884f4bc420def
[ "MIT" ]
10
2020-02-02T23:53:04.000Z
2022-02-14T02:55:14.000Z
tests/stree-test.cc
dendi239/algorithms-data-structures
43db1aa8340f8ef9669bcb26894884f4bc420def
[ "MIT" ]
2
2020-09-02T12:27:48.000Z
2021-05-04T00:10:44.000Z
tests/stree-test.cc
dendi239/algorithms-data-structures
43db1aa8340f8ef9669bcb26894884f4bc420def
[ "MIT" ]
1
2020-04-30T23:16:08.000Z
2020-04-30T23:16:08.000Z
#include <catch2/catch_all.hpp> #include "../data-structures/segment-tree/segment-tree.hpp" struct SumData { static auto Pure(int64_t value) { return value; } static auto Merge(int64_t lhs, int64_t rhs) -> int64_t { return lhs + rhs; } }; TEST_CASE("Pure sumtree test") { std::vector<int64_t> xs(10); std::mt19937 rnd(239); for (auto &x : xs) { x = rnd(); } auto stree = segment_tree::build<SumData>(xs); for (int l = 0; l < 10; ++l) { int64_t expected = xs[l]; for (int r = l + 1; r <= 10; ++r) { REQUIRE(expected == stree.Fold(l, r)); if (r < 10) { expected += xs[r]; } } } } TEST_CASE("Iota builder test") { auto stree = segment_tree::build<SumData>(10, [](int index) { return index; }); for (int i = 0; i < 10; ++i) { REQUIRE(stree.Fold(i, i+1) == i); } for (int l = 0; l < 10; ++l) { int64_t expected = l; for (int r = l + 1; r <= 10; expected += r++) { REQUIRE(stree.Fold(l, r) == expected); } } } template <class T> struct AtLeastFinder { T value; template <class Walker> int Find(Walker w) { if (w.Get() < value) { return -1; } if (w.size() == 1) { return w.left; } int left = Find(w.Left()); if (left != -1) { return left; } else { return Find(w.Right()); } } }; template <class T> struct Setter { int index; T value; template <class Walker> void set(Walker walker) { if (walker.size() == 1) { walker.Get() = Walker::Monoid::Pure(value); } else { set(index < walker.mid() ? walker.Left() : walker.Right()); walker.Update(); } } }; struct MaxData { template <class T> static auto Pure(T value) { return value; } template <class T> static auto Merge(T lhs, T rhs) { return std::max(lhs, rhs); } }; TEST_CASE("Pure maxtree test") { auto stree = segment_tree::build<MaxData>(std::vector<int>{1, 3, 2, 4, 6}); auto find = [&](int x) { return AtLeastFinder<int>{x}.Find(stree.Root()); }; auto set = [&](int i, int x) { Setter<int>{i, x}.set(stree.Root()); }; REQUIRE(find(2) == 1); REQUIRE(find(5) == 4); set(2, 5); REQUIRE(find(4) == 2); REQUIRE(find(8) == -1); set(3, 7); REQUIRE(find(6) == 3); }
19.938596
78
0.545095
[ "vector" ]
2273a489e3093b7a81d63c6639a6eeeab80be263
8,190
cpp
C++
iris-cpp/src/iris/gen/GraphGenerator.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/src/iris/gen/GraphGenerator.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/src/iris/gen/GraphGenerator.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
#include "iris/gen/GraphGenerator.hpp" #include <algorithm> #include <iostream> #include <random> #include <stdexcept> #include <utility> #include "iris/Utils.hpp" namespace iris { namespace gen { types::uint32 chooseFamilySize(const types::fnumeric& p, const CDF& cdf) { for(CDF::size_type i = 0; i < cdf.size(); i++) { if(p <= cdf[i]) { return i; } } // This should never happen! throw std::runtime_error("p = " + util::toString(p) + ": The probability for the CDF is out" " of range!"); } std::vector<types::fnumeric> createCDF(const io::CensusData& census) { CDF cdf(census.size()); for(io::CensusData::size_type i = 0; i < census.size(); i++) { if(i == 0) { cdf[0] = census[0]; } else { cdf[i] = cdf[i - 1] + census[i]; } } // Fix the last element. cdf[cdf.size() - 1] = (types::fnumeric)1.0; return cdf; } void wireFamilyUnit(Agent& agent, const FamilyUnit& unit) { const auto id = agent.getUId(); for(auto i = unit.first; i < unit.second; i++) { if(i == id) { continue; } agent.addConnection(i); } } void wireGraph(Agent* const agents, AgentID totalAgents, const io::CensusData census, types::uint32 outConnections, types::fnumeric connectionProb, types::fnumeric recipProb, types::mersenne_twister& random) { using namespace iris; using namespace iris::types; typedef std::uniform_real_distribution<fnumeric> FDist; CDF cdf = createCDF(census); FDist chooser(0.0, 1.0); AgentID counter = 0; FamilyUnit unit; while(counter < totalAgents) { // Choose a new family unit. // // Add 1 to offset base 0. const fnumeric p = chooser(random); const uint32 familySize = chooseFamilySize(p, cdf) + 1; // Create a "new" family unit. unit.first = counter; unit.second = counter + familySize; // Check for overflow. if(unit.second > totalAgents) { unit.second = totalAgents; } for(auto i = unit.first; i < unit.second; i++) { wireFamilyUnit(agents[i], unit); agents[i].setFamilySize(familySize); wireOutGroup(i, agents, totalAgents, outConnections, connectionProb, recipProb, random); } // Finally, update the counter itself. counter += familySize; } } void wireOutGroup(const AgentID& id, Agent* const agents, AgentID totalAgents, types::uint32 outConnections, types::fnumeric connectionProb, types::fnumeric recipProb, types::mersenne_twister& random) { using namespace iris::types; using namespace iris::util; using namespace std; // If the number of out-going connections is zero, // then do not bother. if(outConnections == 0) { return; } typedef uniform_real_distribution<fnumeric> FDist; typedef uniform_int_distribution<AgentID> UintDist; // Obtain the current network. auto network = agents[id].getNetwork(); // The random distributions to use. FDist fdist(0.0, 1.0); UintDist udist(0, totalAgents - 1); // The actual number of maximum connections to make. const auto familySize = agents[id].getFamilyConnections(); // Figure out what the upper bound is, here. const AgentID upperBound = ((outConnections + familySize) > (totalAgents - 1)) ? (totalAgents - 1) : (outConnections + familySize); const AgentID maxConnections = upperBound - network.size(); #ifdef IRIS_VISUAL_DEBUG using namespace iris::util::term; Sequence cyan(Color::Cyan); Sequence def(Color::Default); std::cout << cyan << "*" << def << " ID: " << id << std::endl; std::cout << "Family size: " << familySize << std::endl; std::cout << "Max connections: " << maxConnections << std::endl; #endif // Ensure the current ID is also checked. sortedInsert(network, id); for(AgentID i = 0; i < maxConnections; i++) { // Determine if a new connection should be made. const auto shouldConnect = fdist(random); if(shouldConnect > connectionProb) { continue; } // The new agent to connect to. auto newIndex = udist(random); #ifdef IRIS_WARN_ON_NONUNIQUE_RANDOM try { #endif // Ensure it is uniquely random. newIndex = ensureRandom<AgentID>(newIndex, network, (AgentID)0, totalAgents); #ifdef IRIS_VISUAL_DEBUG if(find(network.begin(), network.end(), newIndex) != network.end()) { std::cout << "Inserting a duplicate! " << " with" << newIndex << std::endl; } if(agents[id].alreadyConnectedTo(newIndex)) { std::cout << "Agent detects a duplicate too! " << newIndex << std::endl; } #endif // Place into the network (again) in sorted order. sortedInsert(network, newIndex); // Connect to the agent. agents[id].addConnection(newIndex); #ifdef IRIS_VISUAL_DEBUG std::cout << "Added: " << id << " " << newIndex << std::endl; #endif // Determine reciprocity. const auto shouldRecip = fdist(random); const auto makeRecip = shouldRecip <= recipProb; const auto isFull = agents[newIndex].isNetworkFull(outConnections, totalAgents); const auto isConnected = agents[newIndex].isConnectedTo(id); if(makeRecip && !isFull && !isConnected) { agents[newIndex].addConnection(id); #ifdef IRIS_VISUAL_DEBUG std::cout << "Recip: " << newIndex << " " << id << std::endl; #endif } #ifdef IRIS_WARN_ON_NONUNIQUE_RANDOM } catch(std::runtime_error& re) { using namespace iris::util::term; Sequence yellow(Color::Yellow); Sequence def(Color::Default); std::cerr << yellow << "*" << def << " Non-unique random" << " number ignored." << std::endl; } #endif } #ifdef IRIS_VISUAL_DEBUG std::cout << std::endl; #endif } } }
32.629482
92
0.450183
[ "vector" ]
22753951abd3bbad6259215fd0749d28ed754c05
1,708
cpp
C++
test/main.cpp
hxmhuang/OpenArray_Dev
863866a6b7accf21fa253567b0e66143c7506cdf
[ "MIT" ]
3
2020-09-08T05:01:56.000Z
2020-11-23T13:11:25.000Z
test/main.cpp
hxmhuang/OpenArray_Dev
863866a6b7accf21fa253567b0e66143c7506cdf
[ "MIT" ]
null
null
null
test/main.cpp
hxmhuang/OpenArray_Dev
863866a6b7accf21fa253567b0e66143c7506cdf
[ "MIT" ]
2
2019-08-16T08:32:30.000Z
2020-02-10T08:44:04.000Z
#include <iostream> #include <cstdio> #include <string> #include <mpi.h> #include "test.hpp" #include "../MPI.hpp" using namespace std; int main(int argc, char** argv) { // MPI_Init(NULL, NULL); oa::MPI::global()->c_init(MPI_COMM_WORLD, 0, NULL); int m = stol(argv[1]); int n = stol(argv[2]); int p = stol(argv[3]); int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); if (world_rank == 0) { // test_Range(); // test_Box(); // test_Partition(); } //test_Pool(); //test_Array(); // mpirun -n 6 for test_transfer //test_transfer(); test_update_ghost(); //test_operator(); //test_io(); //test_operator(); //test_write_graph(); //test_force_eval(); //test_fusion_kernel(); //test_c_interface(); //test_logic_operator(); //test_math_operator(); //test_gen_kernel_JIT(); //test_min_max(); //test_eval(); //test_csum(); //test_sum(); //test_sub(); //test_set(); //test_rep(); //test_l2g(); //test_g2l(); //test_set_l2g(); //test_set_g2l(); //test_set_with_mask(); //test_fusion_operator(); //test_op(); // tic("3d"); // for (int i = 0; i < 10; i++) // test_fusion_op_3d(m, n, p, 1); // toc("3d"); // tic("2d"); // test_fusion_op_2d(m, n, p); // toc("2d"); // show_all(); //test_pseudo_3d(); //test_rand(); //test_bitset(); //test_operator_with_grid(); // tic("cache"); // test_cache(m, n, p); // toc("cache"); // show_all(); //test_gen_kernel_JIT_with_op(m, n, p); if (world_rank == 0) std::cout<<"Finished."<<std::endl; // !clear_cache(); MPI_Finalize(); // clear_cache(); return 0; }
18.365591
57
0.590749
[ "3d" ]
227aa38e575f89c502e3aab88b8637dc5515bca9
808
cpp
C++
src/generate.cpp
ebayboy/cpp_demos
b01df202c0285bf232900662d336505520d5d24d
[ "Apache-2.0" ]
null
null
null
src/generate.cpp
ebayboy/cpp_demos
b01df202c0285bf232900662d336505520d5d24d
[ "Apache-2.0" ]
null
null
null
src/generate.cpp
ebayboy/cpp_demos
b01df202c0285bf232900662d336505520d5d24d
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** @file:generate.cpp @author:ebayboy@163.com @date:2019-10-18 08:54 @version: 1.0 @description: cpp file @Copyright (c) all right reserved **************************************************************************/ #include <iostream> #include <string> #include <numeric> #include <vector> #include <algorithm> using namespace std; #define DEBUG void show(vector<int> v) { cout << endl; std::for_each(v.begin(), v.end(), [](int i) { cout << i << " "; }); cout << endl; } int main(int argc, char **argv) { vector<int> v(10); show(v); std::generate(v.begin(), v.end(), std::rand); show(v); vector<int> v2(10); std::generate_n(std::begin(v2) + 2, 3, std::rand); show(v2); return 0; }
17.191489
77
0.490099
[ "vector" ]
228157ad48f2d7db0a6470c44a6d781b783fcaec
233
hpp
C++
src/cpptinytools/Parser.hpp
kamsykula/CppTinyTools
e18b67f127654249ab4f66627d1d98a3b5a21656
[ "MIT" ]
null
null
null
src/cpptinytools/Parser.hpp
kamsykula/CppTinyTools
e18b67f127654249ab4f66627d1d98a3b5a21656
[ "MIT" ]
null
null
null
src/cpptinytools/Parser.hpp
kamsykula/CppTinyTools
e18b67f127654249ab4f66627d1d98a3b5a21656
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <string> namespace sk { class Parser { public: Parser() = delete; static std::vector<std::string> split(const std::string& source, const std::string& delimiter); }; }
15.533333
101
0.635193
[ "vector" ]
2288e533811029d8b7205b5f24bfbeb6846cafff
21,198
cpp
C++
mcfi/src/Repl.cpp
pkusensei/MinskFork
e9b93ea5af4d2c88a9e61724dd57d2a4a8dd8271
[ "MIT" ]
2
2020-07-12T17:58:09.000Z
2022-03-11T13:16:27.000Z
mcfi/src/Repl.cpp
pkusensei/MinskFork
e9b93ea5af4d2c88a9e61724dd57d2a4a8dd8271
[ "MIT" ]
null
null
null
mcfi/src/Repl.cpp
pkusensei/MinskFork
e9b93ea5af4d2c88a9e61724dd57d2a4a8dd8271
[ "MIT" ]
1
2022-03-11T13:23:54.000Z
2022-03-11T13:23:54.000Z
#include "Repl.h" #include <fstream> #include <iostream> #include "IO.h" #include "Parsing.h" #include "StringHelper.h" #include "Authoring.h" namespace fs = std::filesystem; namespace { constexpr auto NEW_LINE = '\n'; fs::path GetSubmissionDir() { /// %USERPROFILE%/AppData/Local/Temp auto temp = fs::temp_directory_path(); temp.append("mcf").append("Submissions"); return temp; } std::vector<fs::path> GetFilesInDir(const fs::path& dir) { auto files = std::vector<fs::path>(); for (const auto& p : fs::directory_iterator(dir)) files.push_back(p.path()); return files; } std::string ReadTextFromFile(const fs::path& path) { auto text = std::stringstream(); text << std::ifstream(path).rdbuf(); return text.str(); } } //namespace struct Repl::MetaCommand { // HACK a big hack using MethodType = std::variant<std::function<void()>, std::function<void(std::string_view)>>; std::string_view Name; std::string_view Description; size_t Arity; MethodType Method; MetaCommand(std::string_view name, std::string_view description, MethodType method, size_t arity = 0) :Name(name), Description(description), Arity(arity), Method(std::move(method)) { } }; class Repl::SubmissionView final { private: LineRenderHandle _lineRenderer; const Document& _submissionDocument; size_t _cursorTop; int _renderedLineCount{ 0 }; size_t _currentLine{ 0 }; size_t _currentCharacter{ 0 }; void SubmissionDocumentChanged(); void Render(); void UpdateCursorPosition(); public: SubmissionView(LineRenderHandle lineRenderer, Document& document); size_t CurrentLine()const { return _currentLine; } void CurrentLine(const size_t value); size_t CurrentCharacter()const { return _currentCharacter; } void CurrentCharacter(const size_t value); }; Repl::SubmissionView::SubmissionView(LineRenderHandle lineRenderer, Document& document) :_lineRenderer(std::move(lineRenderer)), _submissionDocument(document), _cursorTop(MCF::GetCursorTop()) { document.SetAction([this]() { this->SubmissionDocumentChanged(); }); Render(); //_lineRenderer -- Repl::RenderLine & McfRepl::RenderLine // used in SubmissionView::Render & thus SubmissionView::SubmissionDocumentChanged // //SubmissionView::SubmissionDocumentChanged -- ObservableCollection::_action // the function called when _submissionDocument changed } void Repl::SubmissionView::SubmissionDocumentChanged() { Render(); } void Repl::SubmissionView::Render() { MCF::SetCursorVisibility(false); auto lineCount = 0; bool resetState = true; for (const auto& line : _submissionDocument) { if (_cursorTop + lineCount >= static_cast<size_t>(MCF::GetConsoleHeight())) { MCF::SetCursorPosition(0, MCF::GetConsoleHeight() - 1); std::cout << '\n'; if (_cursorTop > 0) --_cursorTop; } MCF::SetCursorPosition(0, _cursorTop + lineCount); MCF::SetConsoleColor(MCF::ConsoleColor::Green); if (lineCount == 0) std::cout << "> "; else std::cout << "| "; MCF::ResetConsoleColor(); resetState = _lineRenderer(_submissionDocument, lineCount, resetState); std::cout << std::string(MCF::GetConsoleWidth() - line.length() - 2, ' '); ++lineCount; } auto numberOfBlankLines = _renderedLineCount - lineCount; if (numberOfBlankLines > 0) { auto blankLine = std::string(MCF::GetConsoleWidth() - 1, ' '); for (int i = 0; i < numberOfBlankLines; ++i) { MCF::SetCursorPosition(0, _cursorTop + lineCount + i); std::cout << blankLine << '\n'; } } _renderedLineCount = lineCount; MCF::SetCursorVisibility(true); UpdateCursorPosition(); } void Repl::SubmissionView::UpdateCursorPosition() { MCF::SetCursorPosition(2 + _currentCharacter, _cursorTop + _currentLine); } void Repl::SubmissionView::CurrentLine(const size_t value) { if (_currentLine != value) { _currentLine = value; _currentCharacter = _submissionDocument[_currentLine].length() < _currentCharacter ? _submissionDocument[_currentLine].length() : _currentCharacter; UpdateCursorPosition(); } } void Repl::SubmissionView::CurrentCharacter(const size_t value) { if (_currentCharacter != value) { _currentCharacter = value; UpdateCursorPosition(); } } Repl::Repl() { if (!MCF::EnableVTMode()) { std::cerr << "Warning: Unable to enter VT processing mode.\n"; } _metaCommands.emplace_back("help", "Shows help.", [this] { EvaluateHelp(); }); } void Repl::Run() { while (true) { std::cout << '\n'; // HACK prevents last line displayed from being eaten auto text = EditSubmission(); if (text.empty()) continue; auto& lastItem = _submissionHistory.emplace_back(std::move(text)); if (lastItem.find(NEW_LINE) == lastItem.npos && lastItem.starts_with('#')) EvaluateMetaCommand(lastItem); else EvaluateSubmission(lastItem); _submissionHistoryIndex = 0; } } std::string Repl::EditSubmission() { _done = false; auto document = Document(std::string()); auto view = SubmissionView( [this](const Document& lines, size_t index, bool resetState) { return this->RenderLine(lines, index, resetState); }, document); while (!_done) { auto key = MCF::ReadKeyFromConsole(); HandleKey(key, document, view); } view.CurrentLine(document.size() - 1); view.CurrentCharacter(document[view.CurrentLine()].length()); std::cout << '\n'; return MCF::StringJoin(document.cbegin(), document.cend(), NEW_LINE); } void Repl::HandleKey(const MCF::KeyInfo& key, Document& document, SubmissionView& view) { if (key.IsFunctionalKey) { if (key.Kind != MCF::KeyInputKind::Control) { switch (key.Kind) { case MCF::KeyInputKind::Escape: HandleEscape(document, view); break; case MCF::KeyInputKind::Enter: HandleEnter(document, view); break; case MCF::KeyInputKind::LeftArrow: HandleLeftArrow(view); break; case MCF::KeyInputKind::RightArrow: HandleRightArrow(document, view); break; case MCF::KeyInputKind::UpArrow: HandleUpArrow(view); break; case MCF::KeyInputKind::DownArrow: HandleDownArrow(document, view); break; case MCF::KeyInputKind::Backspace: HandleBackspace(document, view); break; case MCF::KeyInputKind::Delete: HandleDelete(document, view); break; case MCF::KeyInputKind::Home: HandleHome(view); break; case MCF::KeyInputKind::End: HandleEnd(document, view); break; case MCF::KeyInputKind::Tab: HandleTab(document, view); break; case MCF::KeyInputKind::PageUp: HandlePageUp(document, view); break; case MCF::KeyInputKind::PageDown: HandlePageDown(document, view); break; default: auto c = key.Key; if (c >= ' ') HandleTyping(document, view, c); break; } } } else { auto c = key.Key; if (c >= ' ') HandleTyping(document, view, c); } } void Repl::HandleEscape(Document& document, SubmissionView& view) { document.Clear(); document.Add(std::string()); view.CurrentLine(0); } void Repl::HandleEnter(Document& document, SubmissionView& view) { auto text = MCF::StringJoin(document.cbegin(), document.cend(), NEW_LINE); if (text.starts_with('#') || IsCompleteSubmission(text)) { _done = true; return; } InsertLine(document, view); } void Repl::HandleControlEnter(Document& document, SubmissionView& view) { InsertLine(document, view); } void Repl::InsertLine(Document& document, SubmissionView& view) { auto remainder = document[view.CurrentLine()].substr(view.CurrentCharacter()); document.SetAt(view.CurrentLine(), document[view.CurrentLine()].substr(0, view.CurrentCharacter())); auto lineIndex = view.CurrentLine() + 1; document.Insert(lineIndex, std::string()); view.CurrentCharacter(0); view.CurrentLine(lineIndex); } void Repl::HandleLeftArrow(SubmissionView& view) { if (view.CurrentCharacter() > 0) view.CurrentCharacter(view.CurrentCharacter() - 1); } void Repl::HandleRightArrow(Document& document, SubmissionView& view) { auto line = document[view.CurrentLine()]; if (view.CurrentCharacter() <= line.length() - 1) view.CurrentCharacter(view.CurrentCharacter() + 1); } void Repl::HandleUpArrow(SubmissionView& view) { if (view.CurrentLine() > 0) view.CurrentLine(view.CurrentLine() - 1); } void Repl::HandleDownArrow(Document& document, SubmissionView& view) { if (view.CurrentLine() < document.size() - 1) view.CurrentLine(view.CurrentLine() + 1); } void Repl::HandleBackspace(Document& document, SubmissionView& view) { auto start = view.CurrentCharacter(); if (start == 0) { if (view.CurrentLine() == 0) return; auto currentLine = document[view.CurrentLine()]; auto previousLine = document[view.CurrentLine() - 1]; document.RemoveAt(view.CurrentLine()); view.CurrentLine(view.CurrentLine() - 1); document.SetAt(view.CurrentLine(), previousLine + currentLine); view.CurrentCharacter(previousLine.length()); } else { auto lineIndex = view.CurrentLine(); auto line = document[lineIndex]; auto before = line.substr(0, start - 1); auto after = line.substr(start); document.SetAt(lineIndex, before + after); view.CurrentCharacter(view.CurrentCharacter() - 1); } } void Repl::HandleDelete(Document& document, SubmissionView& view) { auto lineIndex = view.CurrentLine(); auto line = document[lineIndex]; auto start = view.CurrentCharacter(); if (start >= line.length()) { if (view.CurrentLine() == document.size() - 1) return; auto nextLine = document[view.CurrentLine() + 1]; document.SetAt(view.CurrentLine(), document[view.CurrentLine()] + nextLine); document.RemoveAt(view.CurrentLine() + 1); return; } auto before = line.substr(0, start); auto after = line.substr(start + 1); document.SetAt(lineIndex, before + after); } void Repl::HandleHome(SubmissionView& view) { view.CurrentCharacter(0); } void Repl::HandleEnd(Document& document, SubmissionView& view) { view.CurrentCharacter(document[view.CurrentLine()].length()); } void Repl::HandleTab(Document& document, SubmissionView& view) { constexpr auto tabWidth = 4; auto start = view.CurrentCharacter(); auto remainingSpaces = tabWidth - start % tabWidth; auto line = document[view.CurrentLine()]; document.SetAt(view.CurrentLine(), line.insert(start, std::string(remainingSpaces, ' '))); view.CurrentCharacter(view.CurrentCharacter() + remainingSpaces); } void Repl::HandlePageUp(Document& document, SubmissionView& view) { if (_submissionHistoryIndex == 0) _submissionHistoryIndex = _submissionHistory.size() - 1; else --_submissionHistoryIndex; UpdateDocumentFromHistory(document, view); } void Repl::HandlePageDown(Document& document, SubmissionView& view) { ++_submissionHistoryIndex; if (_submissionHistoryIndex > _submissionHistory.size() - 1) _submissionHistoryIndex = 0; UpdateDocumentFromHistory(document, view); } void Repl::UpdateDocumentFromHistory(Document& document, SubmissionView& view) { if (_submissionHistory.empty()) return; document.Clear(); auto& historyItem = _submissionHistory[_submissionHistoryIndex]; auto lines = MCF::StringSplit(historyItem.begin(), historyItem.end(), NEW_LINE); for (const auto& it : lines) { document.Add(std::string(it)); } view.CurrentLine(document.size() - 1); view.CurrentCharacter(document[view.CurrentLine()].length()); } void Repl::HandleTyping(Document& document, SubmissionView& view, char c) { auto lineIndex = view.CurrentLine(); auto& line = document[lineIndex]; line.push_back(c); document.SetAt(lineIndex, line); view.CurrentCharacter(view.CurrentCharacter() + 1); } bool Repl::RenderLine(const Document& lines, size_t index, bool resetState)const { std::cout << lines[index]; return resetState; } namespace { std::vector<std::string> ParseArgs(std::string_view input) { auto args = std::vector<std::string>(); auto inQuotes = false; size_t position = 1; auto arg = std::string(); auto commitArg = [&args, &arg]() { if (!MCF::StringIsBlank(arg)) args.push_back(std::move(arg)); arg.clear(); }; while (position < input.length()) { auto c = input.at(position); auto l = position + 1 >= input.length() ? '\0' : input.at(position + 1); if (std::isspace(c)) { if (!inQuotes) commitArg(); else arg.push_back(c); } else if (c == '\"') { if (!inQuotes) inQuotes = true; else if (l == '\"') { arg.push_back(c); ++position; } else inQuotes = false; } else { arg.push_back(c); } ++position; } commitArg(); return args; } } //namespace void Repl::EvaluateMetaCommand(std::string_view input) { auto args = ParseArgs(input); const auto& name = args.front(); auto command = std::find_if(_metaCommands.cbegin(), _metaCommands.cend(), [&name](const auto& it) { return name == it.Name; }); if (command == _metaCommands.cend()) { MCF::SetConsoleColor(MCF::ConsoleColor::Red); std::cout << "Invalid command " << input << ".\n"; MCF::ResetConsoleColor(); return; } if (args.size() - 1 != command->Arity) { MCF::SetConsoleColor(MCF::ConsoleColor::Red); std::cout << "ERROR: invalid number of arguments; expecting exactly " << command->Arity << ".\n"; MCF::ResetConsoleColor(); return; } auto& method = command->Method; if (method.index() == 0) std::get_if<0>(&method)->operator()(); else std::get_if<1>(&method)->operator()(args.at(1)); } void Repl::EvaluateHelp() { auto maxNameLength = std::max_element(_metaCommands.cbegin(), _metaCommands.cend(), [](const auto& a, const auto& b) { return a.Name.length() < b.Name.length(); }) ->Name.length(); std::sort(_metaCommands.begin(), _metaCommands.end(), [](const auto& a, const auto& b) { return a.Name < b.Name; }); auto writer = MCF::TextWriter(std::cout); for (const auto& it : _metaCommands) { if (it.Arity == 0) { auto paddedName = std::string(it.Name).append(maxNameLength - it.Name.length(), ' '); writer.WritePunctuation("#"); writer.WriteIdentifier(paddedName); writer.WriteSpace(); writer.WriteSpace(); } else { writer.WritePunctuation("#"); writer.WriteIdentifier(it.Name); writer.WriteSpace(); writer.WritePunctuation("<"); writer.WriteIdentifier("symbol"); writer.WritePunctuation(">"); } writer.WriteSpace(); writer.WritePunctuation(it.Description); writer.WriteLine(); } } const std::unique_ptr<MCF::Compilation> McfRepl::emptyCompilation = std::make_unique<MCF::Compilation>(MCF::Compilation::CreateScript(nullptr, nullptr)); McfRepl::McfRepl() :Repl() { _metaCommands.emplace_back("exit", "Exits the REPL.", [this] { EvaluateExit(); }); _metaCommands.emplace_back("cls", "Clears the screen.", [this] { EvaluateCls(); }); _metaCommands.emplace_back("ls", "Lists all symbols", [this] { EvaluateLs(); }); _metaCommands.emplace_back("showTree", "Shows the parse tree.", [this] { EvaluateShowTree(); }); _metaCommands.emplace_back("showProgram", "Shows the bound tree.", [this] { EvaluateShowProgram(); }); _metaCommands.emplace_back("reset", "Clears all previous submissions.", [this] { EvaluateReset(); }); _metaCommands.emplace_back("dump", "Shows bound tree of a given function.", [this](std::string_view name) { EvaluateDump(name); }, 1); _metaCommands.emplace_back("load", "Loads a script file", [this](std::string_view path) { EvaluateLoad(path); }, 1); LoadSubmissions(); } McfRepl::~McfRepl() = default; bool McfRepl::RenderLine(const Document & lines, size_t index, bool resetState)const { static std::unique_ptr<MCF::SyntaxTree> tree = nullptr; if (resetState) { auto text = MCF::StringJoin(lines.cbegin(), lines.cend(), NEW_LINE); tree = MCF::SyntaxTree::Parse(text); } auto lineSpan = tree->Text().Lines[index].Span(); auto classSpans = Classify(*tree, lineSpan); for (const auto& span : classSpans) { #define MATCH_COLOR(kind, color) \ case Classification::kind: \ MCF::SetConsoleColor(MCF::ConsoleColor::color); break; auto spanText = tree->Text().ToString(span.Span); switch (span.ClassEnum) { MATCH_COLOR(Keyword, Blue); MATCH_COLOR(Identifier, DarkYellow); MATCH_COLOR(Number, Cyan); MATCH_COLOR(String, Magenta); MATCH_COLOR(Comment, Green); case Classification::Text: default: MCF::SetConsoleColor(MCF::ConsoleColor::DarkGray); break; } std::cout << spanText; MCF::ResetConsoleColor(); #undef MATCH_COLOR } return false; } void McfRepl::EvaluateExit()const { std::exit(0); } void McfRepl::EvaluateCls()const { MCF::ClearConsole(); } void McfRepl::EvaluateLs() { auto compilation = _previous ? _previous.get() : emptyCompilation.get(); auto symbols = compilation->GetSymbols(); std::sort(symbols.begin(), symbols.end(), [](const auto& a, const auto& b) { if (a->Kind() == b->Kind()) return a->Name < b->Name; else return a->Kind() < b->Kind(); }); std::for_each(symbols.cbegin(), symbols.cend(), [](const auto& it) { it->WriteTo(std::cout); std::cout << '\n'; }); } void McfRepl::EvaluateReset() { _previous = nullptr; _variables.clear(); ClearSubmissions(); } void McfRepl::EvaluateShowTree() { _showTree = !_showTree; std::cout << (_showTree ? "Showing parse trees." : "Not showing parse trees.") << '\n'; } void McfRepl::EvaluateShowProgram() { _showProgram = !_showProgram; std::cout << (_showProgram ? "Showing bound tree." : "Not showing bound tree.") << '\n'; } void McfRepl::EvaluateDump(std::string_view name)const { auto compilation = _previous ? _previous.get() : emptyCompilation.get(); auto symbols = compilation->GetSymbols(); auto func = std::find_if(symbols.cbegin(), symbols.cend(), [name](const auto& it) { return it->Kind() == MCF::SymbolKind::Function && it->Name == name; }); if (func == symbols.cend()) { MCF::SetConsoleColor(MCF::ConsoleColor::Red); std::cout << "ERROR: function '" << name << "' does not exist." << '\n'; MCF::ResetConsoleColor(); return; } compilation->EmitTree(static_cast<const MCF::FunctionSymbol&>(**func), std::cout); } void McfRepl::EvaluateLoad(std::string_view path) { auto p = fs::absolute(path); if (!fs::exists(p)) { MCF::SetConsoleColor(MCF::ConsoleColor::Red); std::cout << "ERROR: file does not exist '" << p << "'.\n"; MCF::ResetConsoleColor(); return; } auto text = ReadTextFromFile(p); EvaluateSubmission(text); } void McfRepl::ClearSubmissions()const { fs::remove_all(GetSubmissionDir()); } void McfRepl::LoadSubmissions() { auto dir = GetSubmissionDir(); if (!fs::exists(dir)) return; auto files = GetFilesInDir(dir); if (files.empty()) return; MCF::SetConsoleColor(MCF::ConsoleColor::DarkGray); std::cout << "Loaded " << files.size() << " submission(s).\n"; MCF::ResetConsoleColor(); _loadingSubmission = true; for (const auto& file : files) { auto text = ReadTextFromFile(file); EvaluateSubmission(text); } _loadingSubmission = false; } void McfRepl::SaveSubmission(std::string_view text) { if (_loadingSubmission) return; auto dir = GetSubmissionDir(); fs::create_directories(dir); auto count = GetFilesInDir(dir).size(); auto ss = std::stringstream(); ss << "submission" << std::setw(4) << std::setfill('0') << count; auto name = ss.str(); auto path = dir.append(name); auto file = std::ofstream(path); file << text; } bool McfRepl::IsCompleteSubmission(std::string_view text) const { if (text.empty()) return true; auto lastTwoLinesAreBlank = [&text]() { auto v = MCF::StringSplit(text.begin(), text.end(), NEW_LINE); if (v.size() > 1) { auto i = v.crbegin(); return MCF::StringIsBlank(*i) && MCF::StringIsBlank(*++i); } else return false; }; if (lastTwoLinesAreBlank()) return true; auto tree = MCF::SyntaxTree::Parse(text); auto last = tree->Root()->Members.empty() ? nullptr : tree->Root()->Members.back().get(); if (last == nullptr || last->GetLastToken().IsMissing()) return false; return true; } void McfRepl::EvaluateSubmission(std::string_view text) { // creates a string_view referncing to the last item in _submissionHistory // That was the original idea BUT // _submissionHistory as a vector<T> moves/copies its content when resizing // That invalidates string_view in SyntaxTree esp. when SSO kicks in // At the end of the day each syntax tree keeps its own copy of input string auto syntaxTree = MCF::SyntaxTree::Parse(text); auto compilation = MCF::Compilation::CreateScript(std::move(_previous), std::move(syntaxTree)); if (_showTree) compilation.SyntaxTrees().back()->Root()->WriteTo(std::cout); if (_showProgram) compilation.EmitTree(std::cout); auto result = compilation.Evaluate(_variables); auto writer = MCF::IndentedTextWriter(std::cout); writer.WriteDiagnostics(result.Diagnostics()); if (!result.Diagnostics().HasErrors()) { auto value = result.Value(); if (value.HasValue()) { MCF::SetConsoleColor(MCF::ConsoleColor::White); std::cout << value; MCF::ResetConsoleColor(); } _previous = std::make_unique<MCF::Compilation>(std::move(compilation)); SaveSubmission(text); } std::cout << '\n'; }
25.478365
101
0.684357
[ "render", "vector" ]
228a46e7c383249f60eab107c2a5bb892c408898
7,209
cpp
C++
main/src/vtr_vision/src/features/augment/descriptor_augment.cpp
utiasASRL/vtr3
b4edca56a19484666d3cdb25a032c424bdc6f19d
[ "Apache-2.0" ]
32
2021-09-15T03:42:42.000Z
2022-03-26T10:40:01.000Z
main/src/vtr_vision/src/features/augment/descriptor_augment.cpp
shimp-t/vtr3
bdcad784ffe26fabfa737d0e195bcb3bacb930c3
[ "Apache-2.0" ]
7
2021-09-18T19:18:15.000Z
2022-02-02T11:15:40.000Z
main/src/vtr_vision/src/features/augment/descriptor_augment.cpp
shimp-t/vtr3
bdcad784ffe26fabfa737d0e195bcb3bacb930c3
[ "Apache-2.0" ]
7
2021-09-18T01:31:28.000Z
2022-03-14T05:09:37.000Z
// Copyright 2021, Autonomous Space Robotics Lab (ASRL) // // 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 descriptor_augment.cpp * \brief Source file for the ASRL vision package * \details * * \author Kirk MacTavish, Autonomous Space Robotics Lab (ASRL) */ #include <vtr_logging/logging.hpp> #include <vtr_vision/features/augment/descriptor_augment.hpp> namespace vtr { namespace vision { //////////////////////////////////////////////////////////////////// // AugmentorEngine //////////////////////////////////////////////////////////////////// cv::Mat_<DescType> AugmentorEngine::augment(const ChannelFeatures &channel) { // Check the input if (channel.cameras.size() == 0 || channel.cameras[0].descriptors.rows == 0) return cv::Mat_<DescType>(); if (channel.cameras[0].descriptors.type() != CV_32F) throw std::invalid_argument( "The descriptors must be floats or this class needs to be templated"); // Allocate the return std::vector<unsigned> dims(1, 0); dims.reserve(augmentors_.size() + 1); for (const auto &aug : augmentors_) dims.emplace_back(dims.back() + aug->getDim(channel)); cv::Mat_<DescType> augmented(channel.cameras[0].descriptors.rows, dims.back()); // Loop through all the augmentors auto offset = dims.begin(); for (auto it = augmentors_.begin(); it != augmentors_.end(); ++it, ++offset) { // Augment the descriptor (*it)->augment(&augmented, *offset, channel); } return augmented; } //////////////////////////////////////////////////////////////////// // AugmentorDescriptor //////////////////////////////////////////////////////////////////// void AugmentorDescriptor::augment(cv::Mat_<DescType> *augmented, unsigned offset, const ChannelFeatures &channel) const { if (channel.cameras[0].descriptors.type() != CV_32F) throw std::invalid_argument( "The descriptors must be floats or this class needs to be templated"); // Copy the descriptor (shallow copy) const auto &priv_cam = channel.cameras[0]; cv::Range cols(offset, offset + priv_cam.descriptors.cols); (*augmented)(cv::Range::all(), cols) = priv_cam.descriptors.clone() / sigma_d_; } //////////////////////////////////////////////////////////////////// // AugmentorDisparity //////////////////////////////////////////////////////////////////// AugmentorDisparity::AugmentorDisparity(const RigCalibration &calibration, float sigma_d, float sigma_z) : calibration_(calibration), sigma_d_(sigma_d), sigma_z_(sigma_z) { if (sigma_d_ <= 0 || sigma_z_ <= 0) throw std::invalid_argument("Standard deviations must be positive"); } unsigned AugmentorDisparity::getDim(const ChannelFeatures &channel) const { if (calibration_.extrinsics.size() != calibration_.intrinsics.size() || calibration_.extrinsics.size() != channel.cameras.size()) throw std::invalid_argument( "AugmentorDisparity: Calibration and camera sizes don't match."); // Only works for fully matched and rectified right now return channel.fully_matched && calibration_.rectified ? getNumCams(channel) - 1 : 0; } void AugmentorDisparity::augment(cv::Mat_<DescType> *augmented, unsigned column, const ChannelFeatures &channel) const { if (!getDim(channel)) return; // rectified only float focal = calibration_.intrinsics[0](0, 0) / calibration_.intrinsics[0](2, 2); // center of the camera in world coordinates float cx0_w = -calibration_.extrinsics[0].matrix()(0, 3); LOG(DEBUG) << "focal: " << focal << " cx0_w: " << cx0_w << " "; // Loop over each camera (the first is checked and skipped const Features &cam0 = channel.cameras[0]; for (unsigned j = 0; j < channel.cameras.size(); ++j) { const Features &camj = channel.cameras[j]; // Make sure there are the right number of keypoints if (camj.keypoints.size() != (unsigned)augmented->rows) throw std::runtime_error( "Augmented descriptor has different rows than num keypoints."); // Disparity is relative to the privileged camera (for now, fully matched) if (j == 0) continue; float cxj_w = -calibration_.extrinsics[j].matrix()(0, 3); float baseline = cxj_w - cx0_w; // usually positive float baseline_abs = std::abs(baseline); // Scaling parameters float a = sqrt(focal * baseline_abs / (sigma_d_ * sigma_z_)); float c = a * sigma_d_; LOG(DEBUG) << "a: " << a << " c: " << c << " cxj_w: " << cxj_w << " base: " << baseline << " "; // Calculate and populate the disparity for (unsigned i = 0; i < camj.keypoints.size(); ++i) { float disparity = cam0.keypoints[i].pt.x - camj.keypoints[i].pt.x; disparity = std::max(0.001f, std::copysign(disparity, baseline)); // this gives us a gradient that matches the sigmas at either extreme (*augmented)(i, column + j - 1) = a * (1.f - 1.f / (disparity / c + 1.f)); } } } //////////////////////////////////////////////////////////////////// // AugmentorSize //////////////////////////////////////////////////////////////////// void AugmentorSize::augment(cv::Mat_<DescType> *augmented, unsigned offset, const ChannelFeatures &channel) const { // Check input const Keypoints &kps = channel.cameras[0].keypoints; if (int(kps.size()) != augmented->rows) throw std::out_of_range( "The keypoint sizes don't match the number of descriptors."); // Scaling parameter float log_sigma = log(sigma_sz_log_base_); // Populate each entry for (int i = 0; i < augmented->rows; ++i) { // Calculate log of size, and scale (*augmented)(i, offset) = log(kps[i].size) / log_sigma; } } //////////////////////////////////////////////////////////////////// // AugmentorPixelPos //////////////////////////////////////////////////////////////////// void AugmentorPixelPos::augment(cv::Mat_<DescType> *augmented, unsigned int offset, const ChannelFeatures &channel) const { // Check input const Keypoints &kps = channel.cameras[0].keypoints; if (int(kps.size()) != augmented->rows) throw std::out_of_range( "The keypoint sizes don't match the number of descriptors."); // Populate each entry for (int i = 0; i < augmented->rows; ++i) { // Calculate log of size, and scale (*augmented)(i, offset) = kps[i].pt.x / sigma_pixel_d_; (*augmented)(i, offset + 1) = kps[i].pt.y / sigma_pixel_d_; } } } // namespace vision } // namespace vtr
38.345745
80
0.591205
[ "vector" ]
228d9356cfc25b9e5fdc334ac1ab9463a127b582
5,852
cpp
C++
src/core/ArEntity.cpp
ZeusYang/AuroraTracer
af97a88bd577ed1acc0d7b2a34dc2105146aceb2
[ "MIT" ]
36
2019-09-26T13:01:32.000Z
2021-04-13T03:17:50.000Z
src/core/ArEntity.cpp
ZeusYang/AuroraTracer
af97a88bd577ed1acc0d7b2a34dc2105146aceb2
[ "MIT" ]
null
null
null
src/core/ArEntity.cpp
ZeusYang/AuroraTracer
af97a88bd577ed1acc0d7b2a34dc2105146aceb2
[ "MIT" ]
3
2020-06-29T14:26:48.000Z
2021-04-03T06:53:50.000Z
#include "ArEntity.h" #include "ArShape.h" namespace Aurora { //-------------------------------------------AEntity------------------------------------- AURORA_REGISTER_CLASS(AEntity, "Entity") AEntity::AEntity(const APropertyTreeNode &node) { const APropertyList& props = node.getPropertyList(); // Shape const auto &shapeNode = node.getPropertyChild("Shape"); AShape::ptr shape = AShape::ptr(static_cast<AShape*>(AObjectFactory::createInstance( shapeNode.getTypeName(), shapeNode))); shape->setTransform(&m_objectToWorld, &m_worldToObject); // Transform ATransform objectToWrold; const auto &shapeProps = shapeNode.getPropertyList(); if (shapeNode.hasProperty("Transform")) { std::vector<ATransform> transformStack; std::vector<Float> sequence = shapeProps.getVectorNf("Transform"); size_t it = 0; bool undefined = false; while (it < sequence.size() && !undefined) { int token = static_cast<int>(sequence[it]); switch (token) { case 0://translate CHECK_LT(it + 3, sequence.size()); AVector3f _trans = AVector3f(sequence[it + 1], sequence[it + 2], sequence[it + 3]); transformStack.push_back(translate(_trans)); it += 4; break; case 1://scale CHECK_LT(it + 3, sequence.size()); AVector3f _scale = AVector3f(sequence[it + 1], sequence[it + 2], sequence[it + 3]); transformStack.push_back(scale(_scale.x, _scale.y, _scale.z)); it += 4; break; case 2://rotate CHECK_LT(it + 4, sequence.size()); AVector3f axis = AVector3f(sequence[it + 1], sequence[it + 2], sequence[it + 3]); transformStack.push_back(rotate(sequence[it + 4], axis)); it += 5; break; default: undefined = true; LOG(ERROR) << "Undefined transform action"; break; } } //Note: calculate the transform matrix in a first-in-last-out manner if (!undefined) { for (auto it = transformStack.rbegin(); it != transformStack.rend(); ++it) { objectToWrold = objectToWrold * (*it); } } } m_objectToWorld = objectToWrold; m_worldToObject = inverse(m_objectToWorld); // Material const auto &materialNode = node.getPropertyChild("Material"); m_material = AMaterial::ptr(static_cast<AMaterial*>(AObjectFactory::createInstance( materialNode.getTypeName(), materialNode))); //Area light AAreaLight::ptr areaLight = nullptr; if (node.hasPropertyChild("Light")) { const auto &lightNode = node.getPropertyChild("Light"); areaLight = AAreaLight::ptr(static_cast<AAreaLight*>(AObjectFactory::createInstance( lightNode.getTypeName(), lightNode))); } m_hitables.push_back(std::make_shared<AHitableObject>(shape, m_material.get(), areaLight)); } //-------------------------------------------AMeshEntity------------------------------------- AURORA_REGISTER_CLASS(AMeshEntity, "MeshEntity") AMeshEntity::AMeshEntity(const APropertyTreeNode &node) { const APropertyList& props = node.getPropertyList(); const std::string filename = props.getString("Filename"); // Shape const auto &shapeNode = node.getPropertyChild("Shape"); // Transform ATransform objectToWrold; const auto &shapeProps = shapeNode.getPropertyList(); if (shapeNode.hasProperty("Transform")) { std::vector<ATransform> transformStack; std::vector<Float> sequence = shapeProps.getVectorNf("Transform"); size_t it = 0; bool undefined = false; while (it < sequence.size() && !undefined) { int token = static_cast<int>(sequence[it]); switch (token) { case 0://translate CHECK_LT(it + 3, sequence.size()); AVector3f _trans = AVector3f(sequence[it + 1], sequence[it + 2], sequence[it + 3]); transformStack.push_back(translate(_trans)); it += 4; break; case 1://scale CHECK_LT(it + 3, sequence.size()); AVector3f _scale = AVector3f(sequence[it + 1], sequence[it + 2], sequence[it + 3]); transformStack.push_back(scale(_scale.x, _scale.y, _scale.z)); it += 4; break; case 2://rotate CHECK_LT(it + 4, sequence.size()); AVector3f axis = AVector3f(sequence[it + 1], sequence[it + 2], sequence[it + 3]); transformStack.push_back(rotate(sequence[it + 4], axis)); it += 5; break; default: undefined = true; LOG(ERROR) << "Undefined transform action"; break; } } //Note: calculate the transform matrix in a first-in-last-out manner if (!undefined) { for (auto it = transformStack.rbegin(); it != transformStack.rend(); ++it) { objectToWrold = objectToWrold * (*it); } } } m_objectToWorld = objectToWrold; m_worldToObject = inverse(m_objectToWorld); //Material const auto &materialNode = node.getPropertyChild("Material"); m_material = AMaterial::ptr(static_cast<AMaterial*>(AObjectFactory::createInstance( materialNode.getTypeName(), materialNode))); //Load each triangle of the mesh as a HitableEntity m_mesh = ATriangleMesh::unique_ptr(new ATriangleMesh(&m_objectToWorld, APropertyTreeNode::m_directory + filename)); const auto &meshIndices = m_mesh->getIndices(); for (size_t i = 0; i < meshIndices.size(); i += 3) { std::array<int, 3> indices; indices[0] = meshIndices[i + 0]; indices[1] = meshIndices[i + 1]; indices[2] = meshIndices[i + 2]; ATriangleShape::ptr triangle = std::make_shared<ATriangleShape>(&m_objectToWorld, &m_worldToObject, indices, m_mesh.get()); //Area light AAreaLight::ptr areaLight = nullptr; if (node.hasPropertyChild("Light")) { const auto &lightNode = node.getPropertyChild("Light"); areaLight = AAreaLight::ptr(static_cast<AAreaLight*>(AObjectFactory::createInstance( lightNode.getTypeName(), lightNode))); } m_hitables.push_back(std::make_shared<AHitableObject>(triangle, m_material.get(), areaLight)); } } }
32.511111
126
0.655502
[ "mesh", "shape", "vector", "transform" ]
2292164e615363930664f55e4ab63631062235ff
3,002
cpp
C++
1/Code/Source/Engine/Source/Object.cpp
Zakhar-V/Prototypes
413a7ce9fdb2a6f3ba97a041f798c71351efc855
[ "MIT" ]
null
null
null
1/Code/Source/Engine/Source/Object.cpp
Zakhar-V/Prototypes
413a7ce9fdb2a6f3ba97a041f798c71351efc855
[ "MIT" ]
null
null
null
1/Code/Source/Engine/Source/Object.cpp
Zakhar-V/Prototypes
413a7ce9fdb2a6f3ba97a041f798c71351efc855
[ "MIT" ]
null
null
null
#include "Object.hpp" namespace ge { //----------------------------------------------------------------------------// // Object //----------------------------------------------------------------------------// Mutex Object::s_namesMutex; HashMap<uint32, String> Object::s_names; //----------------------------------------------------------------------------// void Object::SetName(const String& _name) { m_name = _name.NameHash(); SCOPE_LOCK(s_namesMutex); s_names[m_name] = _name; } //----------------------------------------------------------------------------// const String& Object::GetName(void) { SCOPE_READ(s_namesMutex); auto _name = s_names.find(m_name); return _name != s_names.end() ? _name->second : String::Empty; } //----------------------------------------------------------------------------// //----------------------------------------------------------------------------// // Event //----------------------------------------------------------------------------// //----------------------------------------------------------------------------// Event::~Event(void) { for (auto i = m_callbacks.begin(); i != m_callbacks.end();) { delete i->second; i = m_callbacks.erase(i); } } //----------------------------------------------------------------------------// void Event::Subscribe(Object* _receiver, EventCallback* _callback) { ASSERT(_receiver != nullptr); ASSERT(_callback != nullptr); m_callbacks[_receiver] = _callback; } //----------------------------------------------------------------------------// void Event::Unsubscribe(Object* _receiver) { auto _it = m_callbacks.find(_receiver); if (_it != m_callbacks.end()) _it->second->SetReceiver(nullptr); } //----------------------------------------------------------------------------// bool Event::IsSubscribed(Object* _receiver) { auto _it = m_callbacks.find(_receiver); if (_it != m_callbacks.end()) return _it->second->GetReceiver() == _receiver; return false; } //----------------------------------------------------------------------------// void Event::Send(Object* _sender) { bool _hasNullCallbacks = false; m_sender = _sender; for (auto i = m_callbacks.begin(), e = m_callbacks.end(); i != e; ++i) { EventCallback* _cb = i->second; if (_cb->GetReceiver()) _cb->Invoke(this); else _hasNullCallbacks = true; } m_sender = nullptr; if (_hasNullCallbacks) { for (auto i = m_callbacks.begin(); i != m_callbacks.end();) { if (i->second->GetReceiver()) ++i; else { delete i->second; i = m_callbacks.erase(i); } } } } //----------------------------------------------------------------------------// //----------------------------------------------------------------------------// // //----------------------------------------------------------------------------// }
30.323232
82
0.358095
[ "object" ]
2292fdbbf79958c2cf929fb2be1bcbf805f4a4c0
21,523
cpp
C++
src_main/engine/r_areaportal.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
25
2018-02-28T15:04:42.000Z
2021-08-16T03:49:00.000Z
src_main/engine/r_areaportal.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
1
2019-09-20T11:06:03.000Z
2019-09-20T11:06:03.000Z
src_main/engine/r_areaportal.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
9
2019-07-31T11:58:20.000Z
2021-08-31T11:18:15.000Z
// Copyright © 1996-2018, Valve Corporation, All rights reserved. #include "render_pch.h" #include "r_areaportal.h" #include "client.h" #include "cmodel_engine.h" #include "con_nprint.h" #include "debug_leafvis.h" #include "tier0/include/fasttimer.h" #include "tier0/include/memdbgon.h" ConVar r_ClipAreaPortals("r_ClipAreaPortals", "1", FCVAR_CHEAT); ConVar r_DrawPortals("r_DrawPortals", "0", FCVAR_CHEAT); CUtlVector<CPortalRect> g_PortalRects; extern bool g_bViewerInSolidSpace = false; // ------------------------------------------------------------------------------------ // // Classes. // ------------------------------------------------------------------------------------ // // #define MAX_PORTAL_VERTS 32 class CAreaCullInfo { public: CAreaCullInfo() { m_GlobalCounter = 0; memset(&m_Frustum, 0, sizeof(m_Frustum)); memset(&m_Rect, 0, sizeof(m_Rect)); } Frustum_t m_Frustum; CPortalRect m_Rect; u16 m_GlobalCounter; // Used to tell if it's been touched yet this frame. }; // ------------------------------------------------------------------------------------ // // Globals. // ------------------------------------------------------------------------------------ // // // Visible areas from the client DLL + occluded areas using area portals. unsigned char g_RenderAreaBits[32]; // Used to prevent it from coming back into portals while flowing through them. static unsigned char g_AreaStack[32]; // Frustums for each area for the current frame. Used to cull out leaves. static CUtlVector<CAreaCullInfo> g_AreaCullInfo; // List of areas marked visible this frame. static u16 g_VisibleAreas[MAX_MAP_AREAS]; static int g_nVisibleAreas; // Tied to CAreaCullInfo::m_GlobalCounter. static u16 g_GlobalCounter = 1; // ------------------------------------------------------------------------------------ // // Functions. // ------------------------------------------------------------------------------------ // // void R_Areaportal_LevelInit() { g_AreaCullInfo.SetCount(host_state.worldbrush->m_nAreas); } void R_Areaportal_LevelShutdown() { g_AreaCullInfo.Purge(); g_PortalRects.Purge(); } static inline void R_SetBit(unsigned char *pBits, int bit) { pBits[bit >> 3] |= (1 << (bit & 7)); } static inline void R_ClearBit(unsigned char *pBits, int bit) { pBits[bit >> 3] &= ~(1 << (bit & 7)); } static inline unsigned char R_TestBit(unsigned char *pBits, int bit) { return pBits[bit >> 3] & (1 << (bit & 7)); } struct portalclip_t { portalclip_t() { lists[0] = v0; lists[1] = v1; } Vector v0[MAX_PORTAL_VERTS]; Vector v1[MAX_PORTAL_VERTS]; Vector *lists[2]; }; // Transforms and clips the portal's verts to the view frustum. Returns false // if the verts lie outside the frustum. static inline bool GetPortalScreenExtents(dareaportal_t *pPortal, portalclip_t *SOURCE_RESTRICT clip, CPortalRect &portalRect, float *pReflectionWaterHeight) { portalRect.left = portalRect.bottom = 1e24f; portalRect.right = portalRect.top = -1e24f; bool bValidExtents = false; worldbrushdata_t *pBrushData = host_state.worldbrush; int nStartVerts = std::min((int)pPortal->m_nClipPortalVerts, MAX_PORTAL_VERTS); // NOTE: We need two passes to deal with reflection. We need to compute // the screen extents for both the reflected + non-reflected area portals // and make bounds that surrounds them both. int nPassCount = (pReflectionWaterHeight != NULL) ? 2 : 1; for (int j = 0; j < nPassCount; ++j) { int i; for (i = 0; i < nStartVerts; i++) { clip->v0[i] = pBrushData->m_pClipPortalVerts[pPortal->m_FirstClipPortalVert + i]; // 2nd pass is to compute the reflected areaportal position if (j == 1) { clip->v0[i].z = 2.0f * (*pReflectionWaterHeight) - clip->v0[i].z; } } int iCurList = 0; bool bAllClipped = false; for (int iPlane = 0; iPlane < 4; iPlane++) { const cplane_t *pPlane = g_Frustum.GetPlane(iPlane); Vector *pIn = clip->lists[iCurList]; Vector *pOut = clip->lists[!iCurList]; int nOutVerts = 0; int iPrev = nStartVerts - 1; float flPrevDot = pPlane->normal.Dot(pIn[iPrev]) - pPlane->dist; for (int iCur = 0; iCur < nStartVerts; iCur++) { float flCurDot = pPlane->normal.Dot(pIn[iCur]) - pPlane->dist; if ((flCurDot > 0) != (flPrevDot > 0)) { if (nOutVerts < MAX_PORTAL_VERTS) { // Add the vert at the intersection. float t = flPrevDot / (flPrevDot - flCurDot); VectorLerp(pIn[iPrev], pIn[iCur], t, pOut[nOutVerts]); ++nOutVerts; } } // Add this vert? if (flCurDot > 0) { if (nOutVerts < MAX_PORTAL_VERTS) { pOut[nOutVerts] = pIn[iCur]; ++nOutVerts; } } flPrevDot = flCurDot; iPrev = iCur; } if (nOutVerts == 0) { // If they're all behind, then this portal is clipped out. bAllClipped = true; break; } nStartVerts = nOutVerts; iCurList = !iCurList; } if (bAllClipped) continue; // Project all the verts and figure out the screen extents. Vector screenPos; Assert(iCurList == 0); for (i = 0; i < nStartVerts; i++) { Vector &point = clip->v0[i]; g_EngineRenderer->ClipTransform(point, &screenPos); portalRect.left = std::min(screenPos.x, portalRect.left); portalRect.bottom = std::min(screenPos.y, portalRect.bottom); portalRect.top = std::max(screenPos.y, portalRect.top); portalRect.right = std::max(screenPos.x, portalRect.right); } bValidExtents = true; } if (!bValidExtents) { portalRect.left = portalRect.bottom = 0; portalRect.right = portalRect.top = 0; } return bValidExtents; } // Fill in the intersection between the two rectangles. inline bool GetRectIntersection(CPortalRect const *pRect1, CPortalRect const *pRect2, CPortalRect *pOut) { pOut->left = std::max(pRect1->left, pRect2->left); pOut->right = std::min(pRect1->right, pRect2->right); if (pOut->left >= pOut->right) return false; pOut->bottom = std::max(pRect1->bottom, pRect2->bottom); pOut->top = std::min(pRect1->top, pRect2->top); if (pOut->bottom >= pOut->top) return false; return true; } static void R_FlowThroughArea(int area, const Vector &vecVisOrigin, const CPortalRect *pClipRect, const VisOverrideData_t *pVisData, float *pReflectionWaterHeight) { #ifndef SWDS // Update this area's frustum. if (g_AreaCullInfo[area].m_GlobalCounter != g_GlobalCounter) { g_VisibleAreas[g_nVisibleAreas] = area; ++g_nVisibleAreas; g_AreaCullInfo[area].m_GlobalCounter = g_GlobalCounter; g_AreaCullInfo[area].m_Rect = *pClipRect; } else { // Expand the areaportal's rectangle to include the new cliprect. CPortalRect *pFrustumRect = &g_AreaCullInfo[area].m_Rect; pFrustumRect->left = std::min(pFrustumRect->left, pClipRect->left); pFrustumRect->bottom = std::min(pFrustumRect->bottom, pClipRect->bottom); pFrustumRect->top = std::max(pFrustumRect->top, pClipRect->top); pFrustumRect->right = std::max(pFrustumRect->right, pClipRect->right); } // Mark this area as visible. R_SetBit(g_RenderAreaBits, area); // Set that we're in this area on the stack. R_SetBit(g_AreaStack, area); worldbrushdata_t *pBrushData = host_state.worldbrush; Assert(area < host_state.worldbrush->m_nAreas); darea_t *pArea = &host_state.worldbrush->m_pAreas[area]; // temp buffer for clipping portalclip_t clipTmp; // Check all areas that connect to this area. for (int iAreaPortal = 0; iAreaPortal < pArea->numareaportals; iAreaPortal++) { Assert(pArea->firstareaportal + iAreaPortal < pBrushData->m_nAreaPortals); dareaportal_t *pAreaPortal = &pBrushData->m_pAreaPortals[pArea->firstareaportal + iAreaPortal]; // Don't flow back into a portal on the stack. if (R_TestBit(g_AreaStack, pAreaPortal->otherarea)) continue; // If this portal is closed, don't go through it. if (!R_TestBit(cl.m_chAreaPortalBits, pAreaPortal->m_PortalKey)) continue; // Make sure the viewer is on the right side of the portal to see through // it. cplane_t *pPlane = &pBrushData->planes[pAreaPortal->planenum]; // Use the specified vis origin to test backface culling, or the main view // if none was specified float flDist = pPlane->normal.Dot(vecVisOrigin) - pPlane->dist; if (flDist < -0.1f) continue; // If the client doesn't want this area visible, don't try to flow into it. if (!R_TestBit(cl.m_chAreaBits, pAreaPortal->otherarea)) continue; CPortalRect portalRect; bool portalVis = true; // don't try to clip portals if the viewer is practically in the plane float fDistTolerance = (pVisData) ? (pVisData->m_fDistToAreaPortalTolerance) : (0.1f); if (flDist > fDistTolerance) { portalVis = GetPortalScreenExtents(pAreaPortal, &clipTmp, portalRect, pReflectionWaterHeight); } else { portalRect.left = -1; portalRect.top = 1; portalRect.right = 1; portalRect.bottom = -1; // note top/bottom reversed! // portalVis=true - not needed, default } if (portalVis) { CPortalRect intersection; if (GetRectIntersection(&portalRect, pClipRect, &intersection)) { if (r_DrawPortals.GetInt()) { g_PortalRects.AddToTail(intersection); } // Ok, we can see into this area. R_FlowThroughArea(pAreaPortal->otherarea, vecVisOrigin, &intersection, pVisData, pReflectionWaterHeight); } } } // Mark that we're leaving this area. R_ClearBit(g_AreaStack, area); #endif } static void IncrementGlobalCounter() { if (g_GlobalCounter == 0xFFFF) { for (int i = 0; i < g_AreaCullInfo.Count(); i++) g_AreaCullInfo[i].m_GlobalCounter = 0; g_GlobalCounter = 1; } else { g_GlobalCounter++; } } ConVar r_snapportal("r_snapportal", "-1"); extern void CSGFrustum(Frustum_t &frustum); static void R_SetupVisibleAreaFrustums() { #ifndef SWDS const CViewSetup &viewSetup = g_EngineRenderer->ViewGetCurrent(); CPortalRect viewWindow; if (viewSetup.m_bOrtho) { viewWindow.right = viewSetup.m_OrthoRight; viewWindow.left = viewSetup.m_OrthoLeft; viewWindow.top = viewSetup.m_OrthoTop; viewWindow.bottom = viewSetup.m_OrthoBottom; } else { // Assuming a view plane distance of 1, figure out the boundaries of a // window the view would project into given the FOV. float xFOV = g_EngineRenderer->GetFov() * 0.5f; float yFOV = g_EngineRenderer->GetFovY() * 0.5f; viewWindow.right = tan(DEG2RAD(xFOV)); viewWindow.left = -viewWindow.right; viewWindow.top = tan(DEG2RAD(yFOV)); viewWindow.bottom = -viewWindow.top; } // Now scale the portals as specified in the normalized view frustum // (-1,-1,1,1) into our view window and generate planes out of that. for (int i = 0; i < g_nVisibleAreas; i++) { CAreaCullInfo *pInfo = &g_AreaCullInfo[g_VisibleAreas[i]]; CPortalRect portalWindow; portalWindow.left = RemapVal(pInfo->m_Rect.left, -1, 1, viewWindow.left, viewWindow.right); portalWindow.right = RemapVal(pInfo->m_Rect.right, -1, 1, viewWindow.left, viewWindow.right); portalWindow.top = RemapVal(pInfo->m_Rect.top, -1, 1, viewWindow.bottom, viewWindow.top); portalWindow.bottom = RemapVal(pInfo->m_Rect.bottom, -1, 1, viewWindow.bottom, viewWindow.top); if (viewSetup.m_bOrtho) { // Left and right planes... float orgOffset = DotProduct(CurrentViewOrigin(), CurrentViewRight()); pInfo->m_Frustum.SetPlane(FRUSTUM_LEFT, PLANE_ANYZ, CurrentViewRight(), portalWindow.left + orgOffset); pInfo->m_Frustum.SetPlane(FRUSTUM_RIGHT, PLANE_ANYZ, -CurrentViewRight(), -portalWindow.right - orgOffset); // Top and bottom planes... orgOffset = DotProduct(CurrentViewOrigin(), CurrentViewUp()); pInfo->m_Frustum.SetPlane(FRUSTUM_TOP, PLANE_ANYZ, CurrentViewUp(), portalWindow.top + orgOffset); pInfo->m_Frustum.SetPlane(FRUSTUM_BOTTOM, PLANE_ANYZ, -CurrentViewUp(), -portalWindow.bottom - orgOffset); } else { Vector normal; const cplane_t *pTest; // right side normal = portalWindow.right * CurrentViewForward() - CurrentViewRight(); VectorNormalize(normal); // OPTIMIZE: This is unnecessary for culling pTest = pInfo->m_Frustum.GetPlane(FRUSTUM_RIGHT); pInfo->m_Frustum.SetPlane(FRUSTUM_RIGHT, PLANE_ANYZ, normal, DotProduct(normal, CurrentViewOrigin())); // left side normal = CurrentViewRight() - portalWindow.left * CurrentViewForward(); VectorNormalize(normal); // OPTIMIZE: This is unnecessary for culling pTest = pInfo->m_Frustum.GetPlane(FRUSTUM_LEFT); pInfo->m_Frustum.SetPlane(FRUSTUM_LEFT, PLANE_ANYZ, normal, DotProduct(normal, CurrentViewOrigin())); // top normal = portalWindow.top * CurrentViewForward() - CurrentViewUp(); VectorNormalize(normal); // OPTIMIZE: This is unnecessary for culling pTest = pInfo->m_Frustum.GetPlane(FRUSTUM_TOP); pInfo->m_Frustum.SetPlane(FRUSTUM_TOP, PLANE_ANYZ, normal, DotProduct(normal, CurrentViewOrigin())); // bottom normal = CurrentViewUp() - portalWindow.bottom * CurrentViewForward(); VectorNormalize(normal); // OPTIMIZE: This is unnecessary for culling pTest = pInfo->m_Frustum.GetPlane(FRUSTUM_BOTTOM); pInfo->m_Frustum.SetPlane(FRUSTUM_BOTTOM, PLANE_ANYZ, normal, DotProduct(normal, CurrentViewOrigin())); // farz pInfo->m_Frustum.SetPlane( FRUSTUM_FARZ, PLANE_ANYZ, -CurrentViewForward(), DotProduct( -CurrentViewForward(), CurrentViewOrigin() + CurrentViewForward() * viewSetup.zFar)); } // DEBUG: Code to visualize the areaportal frustums in 3D // Useful for debugging extern void CSGFrustum(Frustum_t & frustum); if (r_snapportal.GetInt() >= 0) { if (g_VisibleAreas[i] == r_snapportal.GetInt()) { pInfo->m_Frustum.SetPlane( FRUSTUM_NEARZ, PLANE_ANYZ, CurrentViewForward(), DotProduct(CurrentViewForward(), CurrentViewOrigin())); pInfo->m_Frustum.SetPlane( FRUSTUM_FARZ, PLANE_ANYZ, -CurrentViewForward(), DotProduct(-CurrentViewForward(), CurrentViewOrigin() + CurrentViewForward() * 500)); r_snapportal.SetValue(-1); CSGFrustum(pInfo->m_Frustum); } } } #endif } // Intersection of AABB and a frustum. The frustum may contain 0-32 planes // (active planes are defined by inClipMask). Returns boolean value indicating // whether AABB intersects the view frustum or not. // If AABB intersects the frustum, an output clip mask is returned as well // (indicating which planes are crossed by the AABB). This information // can be used to optimize testing of child nodes or objects inside the // nodes (pass value as 'inClipMask'). inline bool R_CullNodeInternal(mnode_t *pNode, int &nClipMask, const Frustum_t &frustum) { int nOutClipMask = nClipMask & FRUSTUM_CLIP_IN_AREA; // init outclip mask float flCenterDotNormal, flHalfDiagDotAbsNormal; if (nClipMask & FRUSTUM_CLIP_RIGHT) { const cplane_t *pPlane = frustum.GetPlane(FRUSTUM_RIGHT); flCenterDotNormal = DotProduct(pNode->m_vecCenter, pPlane->normal) - pPlane->dist; flHalfDiagDotAbsNormal = DotProduct(pNode->m_vecHalfDiagonal, frustum.GetAbsNormal(FRUSTUM_RIGHT)); if (flCenterDotNormal + flHalfDiagDotAbsNormal < 0.0f) return true; if (flCenterDotNormal - flHalfDiagDotAbsNormal < 0.0f) nOutClipMask |= FRUSTUM_CLIP_RIGHT; } if (nClipMask & FRUSTUM_CLIP_LEFT) { const cplane_t *pPlane = frustum.GetPlane(FRUSTUM_LEFT); flCenterDotNormal = DotProduct(pNode->m_vecCenter, pPlane->normal) - pPlane->dist; flHalfDiagDotAbsNormal = DotProduct(pNode->m_vecHalfDiagonal, frustum.GetAbsNormal(FRUSTUM_LEFT)); if (flCenterDotNormal + flHalfDiagDotAbsNormal < 0.0f) return true; if (flCenterDotNormal - flHalfDiagDotAbsNormal < 0.0f) nOutClipMask |= FRUSTUM_CLIP_LEFT; } if (nClipMask & FRUSTUM_CLIP_TOP) { const cplane_t *pPlane = frustum.GetPlane(FRUSTUM_TOP); flCenterDotNormal = DotProduct(pNode->m_vecCenter, pPlane->normal) - pPlane->dist; flHalfDiagDotAbsNormal = DotProduct(pNode->m_vecHalfDiagonal, frustum.GetAbsNormal(FRUSTUM_TOP)); if (flCenterDotNormal + flHalfDiagDotAbsNormal < 0.0f) return true; if (flCenterDotNormal - flHalfDiagDotAbsNormal < 0.0f) nOutClipMask |= FRUSTUM_CLIP_TOP; } if (nClipMask & FRUSTUM_CLIP_BOTTOM) { const cplane_t *pPlane = frustum.GetPlane(FRUSTUM_BOTTOM); flCenterDotNormal = DotProduct(pNode->m_vecCenter, pPlane->normal) - pPlane->dist; flHalfDiagDotAbsNormal = DotProduct(pNode->m_vecHalfDiagonal, frustum.GetAbsNormal(FRUSTUM_BOTTOM)); if (flCenterDotNormal + flHalfDiagDotAbsNormal < 0.0f) return true; if (flCenterDotNormal - flHalfDiagDotAbsNormal < 0.0f) nOutClipMask |= FRUSTUM_CLIP_BOTTOM; } nClipMask = nOutClipMask; return false; // AABB intersects frustum } bool R_CullNode(Frustum_t *pAreaFrustum, mnode_t *pNode, int &nClipMask) { // Now cull to this area's frustum. if ((!g_bViewerInSolidSpace) && (pNode->area > 0)) { // First make sure its whole area is even visible. if (!R_IsAreaVisible(pNode->area)) return true; // This ConVar access causes a huge perf hit in some cases. // If you want to put it back in please cache it's value. //#ifdef USE_CONVARS // if( r_ClipAreaPortals.GetInt() ) //#else if (1) //#endif { if ((nClipMask & FRUSTUM_CLIP_IN_AREA) == 0) { // In this case, we've never hit this area before and // we need to test all planes again because we just changed the frustum nClipMask = FRUSTUM_CLIP_IN_AREA | FRUSTUM_CLIP_ALL; } pAreaFrustum = &g_AreaCullInfo[pNode->area].m_Frustum; } } return R_CullNodeInternal(pNode, nClipMask, *pAreaFrustum); } static ConVar r_portalscloseall("r_portalscloseall", "0"); static ConVar r_portalsopenall("r_portalsopenall", "0", FCVAR_CHEAT, "Open all portals"); static ConVar r_ShowViewerArea("r_ShowViewerArea", "0"); void R_SetupAreaBits(int iForceViewLeaf /* = -1 */, const VisOverrideData_t *pVisData /* = NULL */, float *pWaterReflectionHeight /* = NULL */) { IncrementGlobalCounter(); g_bViewerInSolidSpace = false; // Clear the visible area bits. memset(g_RenderAreaBits, 0, sizeof(g_RenderAreaBits)); memset(g_AreaStack, 0, sizeof(g_AreaStack)); // Our initial clip rect is the whole screen. CPortalRect rect; rect.left = rect.bottom = -1; rect.top = rect.right = 1; // Flow through areas starting at the one we're in. int leaf = iForceViewLeaf; // If view point override wasn't specified, use the current view origin if (iForceViewLeaf == -1) { leaf = CM_PointLeafnum(g_EngineRenderer->ViewOrigin()); } if (r_portalscloseall.GetBool()) { if (cl.m_bAreaBitsValid) { // Clear the visible area bits. memset(g_RenderAreaBits, 0, sizeof(g_RenderAreaBits)); int area = host_state.worldbrush->leafs[leaf].area; R_SetBit(g_RenderAreaBits, area); g_VisibleAreas[0] = area; g_nVisibleAreas = 1; g_AreaCullInfo[area].m_GlobalCounter = g_GlobalCounter; g_AreaCullInfo[area].m_Rect = rect; R_SetupVisibleAreaFrustums(); } else { g_bViewerInSolidSpace = true; } return; } if (host_state.worldbrush->leafs[leaf].contents & CONTENTS_SOLID || cl.ishltv || !cl.m_bAreaBitsValid || r_portalsopenall.GetBool()) { // Draw everything if we're in solid space or if r_portalsopenall is true // (used for building cubemaps) g_bViewerInSolidSpace = true; if (r_ShowViewerArea.GetInt()) Con_NPrintf(3, "Viewer area: (solid space)"); } else { int area = host_state.worldbrush->leafs[leaf].area; if (r_ShowViewerArea.GetInt()) Con_NPrintf(3, "Viewer area: %d", area); g_nVisibleAreas = 0; Vector vecVisOrigin = (pVisData) ? (pVisData->m_vecVisOrigin) : (g_EngineRenderer->ViewOrigin()); R_FlowThroughArea(area, vecVisOrigin, &rect, pVisData, pWaterReflectionHeight); R_SetupVisibleAreaFrustums(); } } const Frustum_t *GetAreaFrustum(int area) { if (g_AreaCullInfo[area].m_GlobalCounter == g_GlobalCounter) return &g_AreaCullInfo[area].m_Frustum; else return &g_Frustum; }
36.29511
87
0.643405
[ "vector", "3d", "solid" ]
229fc9900ea15a9e901e006764df78585cc224a6
1,897
cpp
C++
native/tests/unit-test/src/math_utils_test.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/tests/unit-test/src/math_utils_test.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
native/tests/unit-test/src/math_utils_test.cpp
SteveLau-GameDeveloper/engine
159e5acd0f5115a878d59ed59f924ce7627a5466
[ "Apache-2.0", "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 "gtest/gtest.h" #include "cocos/math/Vec2.h" #include "cocos/math/Math.h" #include "cocos/math/MathUtil.h" #include "utils.h" #include <math.h> #include <vector> TEST(mathUtilsTest, test9) { // smooth logLabel = "test the MathUtil smooth function"; float startP = 3; cc::MathUtil::smooth(&startP, 10, 0.3, 0.7); ExpectEq(IsEqualF(startP, 5.1), true); cc::MathUtil::smooth(&startP, 10, 0.6, 0.4, 0.9); ExpectEq(IsEqualF(startP, 8.039999), true); // lerp logLabel = "test the MathUtil lerp function"; float res = cc::MathUtil::lerp(2, 15, 0.8); ExpectEq(IsEqualF(res, 12.3999996), true); }
43.113636
77
0.684238
[ "vector" ]
22a22e576315547c541db1259565441c2a71f9b9
2,184
hh
C++
core/inc/com/centreon/broker/ceof/ceof_iterator.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
core/inc/com/centreon/broker/ceof/ceof_iterator.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
core/inc/com/centreon/broker/ceof/ceof_iterator.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2009-2013 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CCB_CEOF_CEOF_ITERATOR_HH # define CCB_CEOF_CEOF_ITERATOR_HH # include <vector> # include "com/centreon/broker/ceof/ceof_token.hh" # include "com/centreon/broker/namespace.hh" CCB_BEGIN() namespace ceof { /** * @class ceof_iterator ceof_iterator.hh "com/centreon/broker/ceof/ceof_iterator.hh" * @brief Centreon Engine Object File iterator. * * This iterates over the parsed tokens of a ceof document. */ class ceof_iterator { public: ceof_iterator(); ceof_iterator( std::vector<ceof_token>::const_iterator const& begin, std::vector<ceof_token>::const_iterator const& end); ceof_iterator(ceof_iterator const& other); ceof_iterator& operator=(ceof_iterator const& other); ~ceof_iterator() throw(); bool operator==(ceof_iterator const& other) const throw(); bool operator!=(ceof_iterator const& other) const throw(); ceof_iterator& operator++() throw(); ceof_token::token_type get_type() const throw(); std::string const& get_value() const throw(); bool has_children() const throw(); ceof_iterator enter_children() const throw(); bool end() const throw(); private: std::vector<ceof_token>::const_iterator _token_it; std::vector<ceof_token>::const_iterator _token_end; }; } CCB_END() #endif // !CCB_CEOF_CEOF_ITERATOR_HH
31.2
87
0.654304
[ "object", "vector" ]
22b3a916e7066cfab7f7bdc59ed231e7042b8b8f
19,954
cpp
C++
src/lexer.cpp
alextsao1999/hypermind
f4b33724ae02fa57e4df33daffedc90417ca52c8
[ "MIT" ]
12
2019-03-24T09:10:19.000Z
2021-12-14T10:54:50.000Z
src/lexer.cpp
alextsao1999/hypermind
f4b33724ae02fa57e4df33daffedc90417ca52c8
[ "MIT" ]
null
null
null
src/lexer.cpp
alextsao1999/hypermind
f4b33724ae02fa57e4df33daffedc90417ca52c8
[ "MIT" ]
2
2019-04-10T02:35:30.000Z
2019-04-11T14:38:38.000Z
// // Created by 曹顺 on 2019/2/11. // #include <iostream> #include <cstring> #include "lexer.h" #include "obj/string.h" namespace hypermind { bool IsSpace(HMChar ch){ return ch == _HM_C(' ') || ch == _HM_C('\r'); } bool IsNumber(HMChar ch) { return ch >= _HM_C('0') && ch <= _HM_C('9'); } bool IsAlpha(HMChar ch) { return (ch >= _HM_C('a') && ch <= _HM_C('z')) || (ch >= _HM_C('A') && ch <= _HM_C('Z')); } bool IsCodeChar(HMChar ch) { // 汉字范围 [\u4e00-\u9fa5] #ifdef HMUNICODE return IsAlpha(ch) || ch == _HM_C('_') || (ch >= _HM_C('\u4e00') && ch <= _HM_C('\u9fa5')); #else return IsAlpha(ch) || ch == _HM_C('_'); #endif } void DumpTokenType(Ostream &os, TokenType type) { #define TOKEN_DUMP(v) os << _HM_C(v); switch (type) { case TokenType::End: TOKEN_DUMP("<end>"); break; case TokenType::Delimiter: TOKEN_DUMP("<delimiter>"); break; case TokenType::Add: TOKEN_DUMP("+"); break; case TokenType::Sub: TOKEN_DUMP("-"); break; case TokenType::Mul: TOKEN_DUMP("*"); break; case TokenType::Div: TOKEN_DUMP("/"); break; case TokenType::Identifier: TOKEN_DUMP("<identifier>"); case TokenType::Number: TOKEN_DUMP("<number>"); break; case TokenType::String: TOKEN_DUMP("<string>"); break; case TokenType::Dot: TOKEN_DUMP("."); break; case TokenType::Comma: TOKEN_DUMP(","); break; case TokenType::LeftParen: TOKEN_DUMP("("); break; case TokenType::RightParen: TOKEN_DUMP(")"); break; case TokenType::LeftBracket: TOKEN_DUMP("["); break; case TokenType::RightBracket: TOKEN_DUMP("]"); break; case TokenType::LeftBrace: TOKEN_DUMP("{"); break; case TokenType::RightBrace: TOKEN_DUMP("}"); break; case TokenType::Increase: TOKEN_DUMP("++"); break; case TokenType::Decrease: TOKEN_DUMP("--"); break; case TokenType::Assign: TOKEN_DUMP("="); break; case TokenType::AddAssign: TOKEN_DUMP("+="); break; case TokenType::SubAssign: TOKEN_DUMP("-="); break; case TokenType::MulAssign: TOKEN_DUMP("*="); break; case TokenType::DivAssign: TOKEN_DUMP("/="); break; case TokenType::ModAssign: TOKEN_DUMP("%="); break; case TokenType::AndAssign: TOKEN_DUMP("&="); break; case TokenType::OrAssign: TOKEN_DUMP("|="); break; case TokenType::XorAssign: TOKEN_DUMP("^="); break; case TokenType::Arrow: TOKEN_DUMP("->"); break; case TokenType::Not: TOKEN_DUMP("!"); break; case TokenType::Equal: TOKEN_DUMP("=="); break; case TokenType::NotEqual: TOKEN_DUMP("!="); break; case TokenType::Greater: TOKEN_DUMP(">"); break; case TokenType::Less: TOKEN_DUMP("<"); break; case TokenType::GreaterEqual: TOKEN_DUMP(">="); break; case TokenType::LessEqual: TOKEN_DUMP("<="); break; case TokenType::Or: TOKEN_DUMP("|"); break; case TokenType::LogicOr: TOKEN_DUMP("||"); break; case TokenType::And: TOKEN_DUMP("&"); break; case TokenType::LogicAnd: TOKEN_DUMP("&&"); break; case TokenType::Mod: TOKEN_DUMP("%"); break; case TokenType::At: TOKEN_DUMP("@"); break; case TokenType::Colon: TOKEN_DUMP(":"); break; default: TOKEN_DUMP("<unknown>"); } #undef TOKEN_DUMP } void Token::dump(Ostream &os) const { #define TOKEN_DUMP(v) name = _HM_C(v); String name; switch (type) { case TokenType::End: TOKEN_DUMP("<end>"); break; case TokenType::Delimiter: TOKEN_DUMP("<delimiter>"); break; case TokenType::Add: TOKEN_DUMP("+"); break; case TokenType::Sub: TOKEN_DUMP("-"); break; case TokenType::Mul: TOKEN_DUMP("*"); break; case TokenType::Div: TOKEN_DUMP("/"); break; case TokenType::Identifier: case TokenType::Number: name = String(start, length); break; case TokenType::String: break; case TokenType::Dot: TOKEN_DUMP("."); break; case TokenType::Comma: TOKEN_DUMP(","); break; case TokenType::LeftParen: TOKEN_DUMP("("); break; case TokenType::RightParen: TOKEN_DUMP(")"); break; case TokenType::LeftBracket: TOKEN_DUMP("["); break; case TokenType::RightBracket: TOKEN_DUMP("]"); break; case TokenType::LeftBrace: TOKEN_DUMP("{"); break; case TokenType::RightBrace: TOKEN_DUMP("}"); break; case TokenType::Increase: TOKEN_DUMP("++"); break; case TokenType::Decrease: TOKEN_DUMP("--"); break; case TokenType::Assign: TOKEN_DUMP("="); break; case TokenType::AddAssign: TOKEN_DUMP("+="); break; case TokenType::SubAssign: TOKEN_DUMP("-="); break; case TokenType::MulAssign: TOKEN_DUMP("*="); break; case TokenType::DivAssign: TOKEN_DUMP("/="); break; case TokenType::ModAssign: TOKEN_DUMP("%="); break; case TokenType::AndAssign: TOKEN_DUMP("&="); break; case TokenType::OrAssign: TOKEN_DUMP("|="); break; case TokenType::XorAssign: TOKEN_DUMP("^="); break; case TokenType::Arrow: TOKEN_DUMP("->"); break; case TokenType::Not: TOKEN_DUMP("!"); break; case TokenType::Equal: TOKEN_DUMP("=="); break; case TokenType::NotEqual: TOKEN_DUMP("!="); break; case TokenType::Greater: TOKEN_DUMP(">"); break; case TokenType::Less: TOKEN_DUMP("<"); break; case TokenType::GreaterEqual: TOKEN_DUMP(">="); break; case TokenType::LessEqual: TOKEN_DUMP("<="); break; case TokenType::Or: TOKEN_DUMP("|"); break; case TokenType::LogicOr: TOKEN_DUMP("||"); break; case TokenType::And: TOKEN_DUMP("&"); break; case TokenType::LogicAnd: TOKEN_DUMP("&&"); break; case TokenType::Mod: TOKEN_DUMP("%"); break; case TokenType::At: TOKEN_DUMP("@"); break; case TokenType::Colon: TOKEN_DUMP(":"); break; case TokenType::KeywordNew: TOKEN_DUMP("new"); break; default: TOKEN_DUMP("<unknown>"); } os << name ; #undef TOKEN_DUMP } // 读取一个Token void Lexer::GetNextToken() { if (mEof) return; // 跳过空格 SkipSpace(); switch (CURRENT_CHAR) { case _HM_C('\n'): TOKEN(TokenType::Delimiter, 1); NEXT_LINE(); break; case _HM_C(';'): TOKEN(TokenType::Delimiter, 1); break; case _HM_C('('): TOKEN(TokenType::LeftParen, 1); break; case _HM_C(')'): TOKEN(TokenType::RightParen, 1); break; case _HM_C('['): TOKEN(TokenType::LeftBracket, 1); break; case _HM_C(']'): TOKEN(TokenType::RightBracket, 1); break; case _HM_C('{'): TOKEN(TokenType::LeftBrace, 1); break; case _HM_C('}'): TOKEN(TokenType::RightBrace, 1); break; case _HM_C('.'): TOKEN(TokenType::Dot, 1); break; case _HM_C('@'): TOKEN(TokenType::At, 1); break; case _HM_C(':'): TOKEN(TokenType::Colon, 1); break; case _HM_C('!'): if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::NotEqual, 2); // != not equal 不相等 NEXT(); } else { TOKEN(TokenType::Not, 1); // ! } break; case _HM_C('|'): if (NEXT_CHAR == _HM_C('|')) { TOKEN(TokenType::LogicOr, 2); // || NEXT(); } else { TOKEN(TokenType::Or, 1); // | } break; case _HM_C('&'): if (NEXT_CHAR == _HM_C('&')) { TOKEN(TokenType::LogicAnd, 2); // && NEXT(); } else { TOKEN(TokenType::And, 1); // & } break; case _HM_C('+'): if (NEXT_CHAR == _HM_C('+')) { TOKEN(TokenType::Increase, 2); // ++ NEXT(); } else if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::AddAssign, 2); // += NEXT(); } else { TOKEN(TokenType::Add, 1); // + } break; case _HM_C('>'): if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::GreaterEqual, 2); // >= NEXT(); } else { TOKEN(TokenType::Greater, 1); // + } break; case _HM_C('<'): if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::LessEqual, 2); // >= NEXT(); } else { TOKEN(TokenType::Less, 1); // + } break; case _HM_C('='): if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::Equal, 2); // == NEXT(); } else { TOKEN(TokenType::Assign, 1); // = } break; case _HM_C('%'): if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::ModAssign, 2); // %= NEXT(); } else { TOKEN(TokenType::Mod, 1); // % } break; case _HM_C('-'): if (NEXT_CHAR == _HM_C('-')) { // -- TOKEN(TokenType::Decrease, 2); // 自减 NEXT(); } else if (NEXT_CHAR == _HM_C('=')) { // -= TOKEN(TokenType::SubAssign, 2); NEXT(); } else if (NEXT_CHAR == _HM_C('>')) { // -> Arrow 箭头 TOKEN(TokenType::Arrow, 2); NEXT(); } else { TOKEN(TokenType::Sub, 1); // - } break; case _HM_C('*'): if (NEXT_CHAR == _HM_C('=')) { TOKEN(TokenType::MulAssign, 2); // *= NEXT(); } else { TOKEN(TokenType::Mul, 1); } break; case _HM_C(','): TOKEN(TokenType::Comma, 1); break; // 可能为注释 或者除号 case _HM_C('/'): if (NEXT_CHAR == _HM_C('/') || NEXT_CHAR == _HM_C('*')) { SkipComment(); return GetNextToken(); // 跳过之后继续读取一个token } else if (NEXT_CHAR == _HM_C('=')) { // /= TOKEN(TokenType::DivAssign, 2); NEXT(); } else { TOKEN(TokenType::Div, 1); } break; case _HM_C('\0'): mEof = true; TOKEN(TokenType::End, 0); return; default: if (IsCodeChar(CURRENT_CHAR)) { ParseIdentifier(); } else if (IsNumber(CURRENT_CHAR)) { ParseNumber(); } else if (CURRENT_CHAR == _HM_C('"') || CURRENT_CHAR == _HM_C('\'')) { ParseString(); } else { LEXER_UNKOWNCHAR(CURRENT_CHAR); NEXT(); } return; // 已经到文件尾部了 返回就ok } NEXT(); } void Lexer::SkipComment() { // TODO 仅支持单行 之后添加多行注释 /* */ do { NEXT(); } while (CURRENT_CHAR != _HM_C('\n') || !mEof); NEXT_LINE(); NEXT(); } void Lexer::SkipSpace() { if (IsSpace(CURRENT_CHAR)){ do { NEXT(); } while (IsSpace(CURRENT_CHAR)); } } bool Lexer::Match(TokenType type) { TokenType tok = PeekTokenType(); if (tok == type) { mTokens.pop_front(); return true; } return false; } Token Lexer::Peek(HMInteger i) { while (mTokens.size() < i) { if (mEof) return CURRENT_TOKEN; GetNextToken(); mTokens.push_back(CURRENT_TOKEN); } return mTokens[i - 1]; } void Lexer::ParseNumber() { // TODO 浮点数的支持 TOKEN(TokenType::Number, 0); do { NEXT(); } while (IsNumber(CURRENT_CHAR) || CURRENT_CHAR == _HM_C('.')); TOKEN_LENGTH((HMUINT32)(CURRENT_POS - TOKEN_START)); mCurrentToken.value.type = ValueType::Integer; mCurrentToken.value.intval = (int) hm_strtoi(mCurrentToken.start); } void Lexer::ParseString() { Buffer<HMChar> strbuf; HMChar first = CURRENT_CHAR; NEXT(); // 跳过 ' " 文本符 TOKEN(TokenType::String, 0); #define APPEND_CHAR(c) strbuf.push(&mVM->mGCHeap, c) do { if (CURRENT_CHAR == _HM_C('\\')) { // 跳过转义符 NEXT(); switch (CURRENT_CHAR) { case _HM_C('n'): APPEND_CHAR(_HM_C('\n')); break; case _HM_C('\''): APPEND_CHAR(_HM_C('\'')); break; case _HM_C('\"'): APPEND_CHAR(_HM_C('"')); break; case _HM_C('\\'): APPEND_CHAR(_HM_C('\\')); break; case _HM_C('a'): APPEND_CHAR(_HM_C('\a')); break; case _HM_C('b'): APPEND_CHAR(_HM_C('\b')); break; case _HM_C('f'): APPEND_CHAR(_HM_C('\f')); break; case _HM_C('r'): APPEND_CHAR(_HM_C('\r')); break; default: // 不存在 break; } } else { APPEND_CHAR(CURRENT_CHAR); } NEXT(); } while (CURRENT_CHAR != first); TOKEN_LENGTH((HMUINT32)(CURRENT_POS - TOKEN_START)); // 当前字符为 " ' 跳过 获取下一个字符 NEXT(); auto *objString = mVM->NewObject<HMString>(strbuf.data, strbuf.count); TOKEN_VALUE.type = ValueType::Object; TOKEN_VALUE.objval = objString; strbuf.clear(&mVM->mGCHeap); } void Lexer::ParseIdentifier() { TOKEN(TokenType::Identifier, 0); do { NEXT(); } while (IsCodeChar(CURRENT_CHAR) || IsNumber(CURRENT_CHAR)); TOKEN_LENGTH((HMUINT32)(CURRENT_POS - TOKEN_START)); HMChar identifierBuffer[MAX_IDENTIFIER_LENTH] = {_HM_C('\0')}; hm_memcpy(identifierBuffer, mCurrentToken.start, mCurrentToken.length); TokenType tok = HMKeywords[identifierBuffer]; if (tok != TokenType::End) { TOKEN_TYPE(tok); } } Token Lexer::Read() { if (!mTokens.empty()) { Token token = mTokens.front(); mTokens.pop_front(); return token; } GetNextToken(); return CURRENT_TOKEN; } TokenType Lexer::ReadTokenType() { GetNextToken(); return CURRENT_TOKEN.type; } TokenType Lexer::PeekTokenType() { if (mTokens.empty()) { GetNextToken(); mTokens.push_back(mCurrentToken); } return mTokens[0].type; } void Lexer::Consume() { if (!mTokens.empty()) mTokens.pop_front(); else GetNextToken(); } void Lexer::Consume(TokenType type) { if (PeekTokenType() == type) Consume(); else { hm_cout << _HM_C(" missing token : "); DumpTokenType(hm_cout, type); hm_cout << std::endl; } } Token::Token(TokenType mType, const HMChar *mStart, HMUINT32 mLength, HMUINT32 mLine) : type(mType), start(mStart), length(mLength), line(mLine) { } }
31.374214
108
0.38689
[ "object" ]
42f12576af26df12d13e64a1c5068cbee45cd8cf
2,942
cpp
C++
windows/pw6e.official/CPlusPlus/Chapter18/BubbleLevel/BubbleLevel/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:18:08.000Z
2016-11-23T08:18:08.000Z
windows/pw6e.official/CPlusPlus/Chapter18/BubbleLevel/BubbleLevel/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
null
null
null
windows/pw6e.official/CPlusPlus/Chapter18/BubbleLevel/BubbleLevel/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:17:34.000Z
2016-11-23T08:17:34.000Z
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" using namespace BubbleLevel; using namespace Concurrency; using namespace Platform; using namespace Windows::Devices::Sensors; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::UI::Core; using namespace Windows::UI::Popups; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; MainPage::MainPage() { InitializeComponent(); accelerometer = Accelerometer::GetDefault(); DisplayProperties::AutoRotationPreferences = DisplayProperties::NativeOrientation; Loaded += ref new RoutedEventHandler(this, &MainPage::OnMainPageLoaded); SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::OnMainPageSizeChanged); } void MainPage::OnMainPageLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args) { if (accelerometer != nullptr) { accelerometer->ReportInterval = accelerometer->MinimumReportInterval; SetBubble(accelerometer->GetCurrentReading()); accelerometer->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &MainPage::OnAccelerometerReadingChanged); } else { MessageDialog^ messageDialog = ref new MessageDialog("Accelerometer is not available"); task<IUICommand^> showDialogTask = create_task(messageDialog->ShowAsync()); showDialogTask.then([this] (IUICommand^ command) {}); } } void MainPage::OnMainPageSizeChanged(Object^ sender, SizeChangedEventArgs^ args) { double size = min(args->NewSize.Width, args->NewSize.Height); outerCircle->Width = size; outerCircle->Height = size; halfCircle->Width = size / 2; halfCircle->Height = size / 2; } void MainPage::OnAccelerometerReadingChanged(Accelerometer^ sender, AccelerometerReadingChangedEventArgs^ args) { this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]() { SetBubble(args->Reading); })); } void MainPage::SetBubble(AccelerometerReading^ accelerometerReading) { if (accelerometerReading == nullptr) return; double x = accelerometerReading->AccelerationX; double y = accelerometerReading->AccelerationY; bubbleTranslate->X = -x * centeredGrid->ActualWidth / 2; bubbleTranslate->Y = y * centeredGrid->ActualHeight / 2; }
33.816092
126
0.693406
[ "object" ]
42ff32946b5a11ab17779e0204535e30efba709f
14,045
cpp
C++
src/mir/passes_test.cpp
annacrombie/meson-plus-plus
9b922c1bc76917b8fd197d2dbb1409fd7707affb
[ "Apache-2.0" ]
null
null
null
src/mir/passes_test.cpp
annacrombie/meson-plus-plus
9b922c1bc76917b8fd197d2dbb1409fd7707affb
[ "Apache-2.0" ]
null
null
null
src/mir/passes_test.cpp
annacrombie/meson-plus-plus
9b922c1bc76917b8fd197d2dbb1409fd7707affb
[ "Apache-2.0" ]
null
null
null
// SPDX-license-identifier: Apache-2.0 // Copyright © 2021 Intel Corporation #include <gtest/gtest.h> #include <sstream> #include <variant> #include "arguments.hpp" #include "ast_to_mir.hpp" #include "driver.hpp" #include "exceptions.hpp" #include "lower.hpp" #include "mir.hpp" #include "passes.hpp" #include "state/state.hpp" #include "toolchains/archiver.hpp" #include "toolchains/common.hpp" #include "toolchains/compilers/cpp/cpp.hpp" #include "toolchains/linker.hpp" namespace { static const std::filesystem::path src_root = "/home/test user/src/test project/"; static const std::filesystem::path build_root = "/home/test user/src/test project/builddir/"; std::unique_ptr<Frontend::AST::CodeBlock> parse(const std::string & in) { Frontend::Driver drv{}; std::istringstream stream{in}; auto src = src_root / "meson.build"; drv.name = src; auto block = drv.parse(stream); return block; } MIR::BasicBlock lower(const std::string & in) { auto block = parse(in); const MIR::State::Persistant pstate{src_root, build_root}; auto ir = MIR::lower_ast(block, pstate); return ir; } } // namespace TEST(flatten, basic) { auto irlist = lower("func(['a', ['b', ['c']], 'd'])"); MIR::State::Persistant pstate{src_root, build_root}; bool progress = MIR::Passes::flatten(&irlist, pstate); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::FunctionCall>>(r)); const auto & f = std::get<std::unique_ptr<MIR::FunctionCall>>(r); ASSERT_EQ(f->name, "func"); ASSERT_EQ(f->pos_args.size(), 1); const auto & arg = f->pos_args.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Array>>(arg)); const auto & arr = std::get<std::unique_ptr<MIR::Array>>(arg)->value; ASSERT_EQ(arr.size(), 4); } TEST(flatten, already_flat) { auto irlist = lower("func(['a', 'd'])"); MIR::State::Persistant pstate{src_root, build_root}; bool progress = MIR::Passes::flatten(&irlist, pstate); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::FunctionCall>>(r)); const auto & f = std::get<std::unique_ptr<MIR::FunctionCall>>(r); ASSERT_EQ(f->name, "func"); ASSERT_EQ(f->pos_args.size(), 1); const auto & arg = f->pos_args.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Array>>(arg)); const auto & arr = std::get<std::unique_ptr<MIR::Array>>(arg)->value; ASSERT_EQ(arr.size(), 2); } TEST(flatten, mixed_args) { auto irlist = lower("project('foo', ['a', ['d']])"); MIR::State::Persistant pstate{src_root, build_root}; bool progress = MIR::Passes::flatten(&irlist, pstate); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::FunctionCall>>(r)); const auto & f = std::get<std::unique_ptr<MIR::FunctionCall>>(r); ASSERT_EQ(f->pos_args.size(), 2); const auto & arg = f->pos_args.back(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Array>>(arg)); const auto & arr = std::get<std::unique_ptr<MIR::Array>>(arg)->value; ASSERT_EQ(arr.size(), 2); } TEST(branch_pruning, simple) { auto irlist = lower("x = 7\nif true\n x = 8\nendif\n"); bool progress = MIR::Passes::branch_pruning(&irlist); ASSERT_TRUE(progress); ASSERT_FALSE(irlist.condition.has_value()); ASSERT_EQ(irlist.instructions.size(), 2); } TEST(branch_pruning, next_block) { auto irlist = lower("x = 7\nif true\n x = 8\nendif\ny = x"); bool progress = MIR::Passes::branch_pruning(&irlist); ASSERT_TRUE(progress); ASSERT_FALSE(irlist.condition.has_value()); ASSERT_NE(irlist.next, nullptr); ASSERT_EQ(irlist.next->instructions.size(), 1); } TEST(branch_pruning, if_else) { auto irlist = lower("x = 7\nif true\n x = 8\nelse\n x = 9\nendif\n"); bool progress = MIR::Passes::branch_pruning(&irlist); ASSERT_TRUE(progress); ASSERT_FALSE(irlist.condition.has_value()); ASSERT_EQ(irlist.instructions.size(), 2); } TEST(branch_pruning, if_false) { auto irlist = lower("x = 7\nif false\n x = 8\nelse\n x = 9\n y = 2\nendif\n"); bool progress = MIR::Passes::branch_pruning(&irlist); ASSERT_TRUE(progress); ASSERT_FALSE(irlist.condition.has_value()); // Using 3 here allows us to know that we went down the right path ASSERT_EQ(irlist.instructions.size(), 3); const auto & first = std::get<std::unique_ptr<MIR::Number>>(irlist.instructions.front()); ASSERT_EQ(first->value, 7); ASSERT_EQ(first->var.name, "x"); const auto & last = std::get<std::unique_ptr<MIR::Number>>(irlist.instructions.back()); ASSERT_EQ(last->value, 2); ASSERT_EQ(last->var.name, "y"); } TEST(join_blocks, simple) { auto irlist = lower("x = 7\nif true\n x = 8\nelse\n x = 9\nendif\ny = x"); bool progress = MIR::Passes::branch_pruning(&irlist); ASSERT_TRUE(progress); ASSERT_FALSE(irlist.condition.has_value()); ASSERT_EQ(irlist.instructions.size(), 2); ASSERT_NE(irlist.next, nullptr); ASSERT_EQ(irlist.next->instructions.size(), 1); progress = MIR::Passes::join_blocks(&irlist); ASSERT_TRUE(progress); ASSERT_FALSE(irlist.condition.has_value()); ASSERT_EQ(irlist.instructions.size(), 3); ASSERT_EQ(irlist.next, nullptr); } TEST(machine_lower, simple) { auto irlist = lower("x = 7\ny = host_machine.cpu_family()"); auto info = MIR::Machines::PerMachine<MIR::Machines::Info>( MIR::Machines::Info{MIR::Machines::Machine::BUILD, MIR::Machines::Kernel::LINUX, MIR::Machines::Endian::LITTLE, "x86_64"}); bool progress = MIR::Passes::machine_lower(&irlist, info); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 2); const auto & r = irlist.instructions.back(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::String>>(r)); ASSERT_EQ(std::get<std::unique_ptr<MIR::String>>(r)->value, "x86_64"); } TEST(machine_lower, in_array) { auto irlist = lower("x = [host_machine.cpu_family()]"); auto info = MIR::Machines::PerMachine<MIR::Machines::Info>( MIR::Machines::Info{MIR::Machines::Machine::BUILD, MIR::Machines::Kernel::LINUX, MIR::Machines::Endian::LITTLE, "x86_64"}); bool progress = MIR::Passes::machine_lower(&irlist, info); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Array>>(r)); const auto & a = std::get<std::unique_ptr<MIR::Array>>(r)->value; ASSERT_EQ(a.size(), 1); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::String>>(a[0])); ASSERT_EQ(std::get<std::unique_ptr<MIR::String>>(a[0])->value, "x86_64"); } TEST(machine_lower, in_function_args) { auto irlist = lower("foo(host_machine.endian())"); auto info = MIR::Machines::PerMachine<MIR::Machines::Info>( MIR::Machines::Info{MIR::Machines::Machine::BUILD, MIR::Machines::Kernel::LINUX, MIR::Machines::Endian::LITTLE, "x86_64"}); bool progress = MIR::Passes::machine_lower(&irlist, info); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::FunctionCall>>(r)); const auto & f = std::get<std::unique_ptr<MIR::FunctionCall>>(r); ASSERT_EQ(f->pos_args.size(), 1); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::String>>(f->pos_args[0])); ASSERT_EQ(std::get<std::unique_ptr<MIR::String>>(f->pos_args[0])->value, "little"); } TEST(machine_lower, in_condtion) { auto irlist = lower("if host_machine.cpu_family()\n x = 2\nendif"); auto info = MIR::Machines::PerMachine<MIR::Machines::Info>( MIR::Machines::Info{MIR::Machines::Machine::BUILD, MIR::Machines::Kernel::LINUX, MIR::Machines::Endian::LITTLE, "x86_64"}); bool progress = MIR::Passes::machine_lower(&irlist, info); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 0); const auto & con = irlist.condition; ASSERT_TRUE(con.has_value()); const auto & obj = con.value().condition; ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::String>>(obj)); ASSERT_EQ(std::get<std::unique_ptr<MIR::String>>(obj)->value, "x86_64"); } TEST(insert_compiler, simple) { const std::vector<std::string> init{"null"}; auto comp = std::make_unique<MIR::Toolchain::Compiler::CPP::Clang>(init); auto tc = std::make_shared<MIR::Toolchain::Toolchain>( std::move(comp), std::make_unique<MIR::Toolchain::Linker::Drivers::Gnu>(MIR::Toolchain::Linker::GnuBFD{init}, comp.get()), std::make_unique<MIR::Toolchain::Archiver::Gnu>(init)); std::unordered_map<MIR::Toolchain::Language, MIR::Machines::PerMachine<std::shared_ptr<MIR::Toolchain::Toolchain>>> tc_map{}; tc_map[MIR::Toolchain::Language::CPP] = MIR::Machines::PerMachine<std::shared_ptr<MIR::Toolchain::Toolchain>>{tc}; auto irlist = lower("x = meson.get_compiler('cpp')"); bool progress = MIR::Passes::insert_compilers(&irlist, tc_map); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & e = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Compiler>>(e)); const auto & c = std::get<std::unique_ptr<MIR::Compiler>>(e); ASSERT_EQ(c->toolchain->compiler->id(), "clang"); } TEST(insert_compiler, unknown_language) { std::unordered_map<MIR::Toolchain::Language, MIR::Machines::PerMachine<std::shared_ptr<MIR::Toolchain::Toolchain>>> tc_map{}; auto irlist = lower("x = meson.get_compiler('cpp')"); try { (void)MIR::Passes::insert_compilers(&irlist, tc_map); FAIL(); } catch (Util::Exceptions::MesonException & e) { ASSERT_EQ(e.message, "No compiler for language"); } } TEST(files, simple) { auto irlist = lower("x = files('foo.c')"); const MIR::State::Persistant pstate{src_root, build_root}; bool progress = MIR::Passes::lower_free_functions(&irlist, pstate); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Array>>(r)); const auto & a = std::get<std::unique_ptr<MIR::Array>>(r)->value; ASSERT_EQ(a.size(), 1); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::File>>(a[0])); const auto & f = std::get<std::unique_ptr<MIR::File>>(a[0]); ASSERT_EQ(f->file.get_name(), "foo.c"); } TEST(executable, simple) { auto irlist = lower("x = executable('exe', 'source.c', cpp_args : ['-Dfoo'])"); MIR::State::Persistant pstate{src_root, build_root}; pstate.toolchains[MIR::Toolchain::Language::CPP] = std::make_shared<MIR::Toolchain::Toolchain>(MIR::Toolchain::get_toolchain( MIR::Toolchain::Language::CPP, MIR::Machines::Machine::BUILD)); bool progress = MIR::Passes::lower_free_functions(&irlist, pstate); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::Executable>>(r)); const auto & e = std::get<std::unique_ptr<MIR::Executable>>(r)->value; ASSERT_EQ(e.name, "exe"); ASSERT_TRUE(e.arguments.find(MIR::Toolchain::Language::CPP) != e.arguments.end()); const auto & args = e.arguments.at(MIR::Toolchain::Language::CPP); ASSERT_EQ(args.size(), 1); const auto & a = args.front(); ASSERT_EQ(a.type, MIR::Arguments::Type::DEFINE); ASSERT_EQ(a.value, "foo"); } TEST(static_library, simple) { auto irlist = lower("x = static_library('exe', 'source.c', cpp_args : '-Dfoo')"); MIR::State::Persistant pstate{src_root, build_root}; pstate.toolchains[MIR::Toolchain::Language::CPP] = std::make_shared<MIR::Toolchain::Toolchain>(MIR::Toolchain::get_toolchain( MIR::Toolchain::Language::CPP, MIR::Machines::Machine::BUILD)); bool progress = MIR::Passes::lower_free_functions(&irlist, pstate); ASSERT_TRUE(progress); ASSERT_EQ(irlist.instructions.size(), 1); const auto & r = irlist.instructions.front(); ASSERT_TRUE(std::holds_alternative<std::unique_ptr<MIR::StaticLibrary>>(r)); const auto & e = std::get<std::unique_ptr<MIR::StaticLibrary>>(r)->value; ASSERT_EQ(e.name, "exe"); ASSERT_TRUE(e.arguments.find(MIR::Toolchain::Language::CPP) != e.arguments.end()); const auto & args = e.arguments.at(MIR::Toolchain::Language::CPP); ASSERT_EQ(args.size(), 1); const auto & a = args.front(); ASSERT_EQ(a.type, MIR::Arguments::Type::DEFINE); ASSERT_EQ(a.value, "foo"); } TEST(project, valid) { auto irlist = lower("project('foo')"); MIR::State::Persistant pstate{src_root, build_root}; MIR::Passes::lower_project(&irlist, pstate); ASSERT_EQ(pstate.name, "foo"); } TEST(lower, trivial) { auto irlist = lower("project('foo')"); MIR::State::Persistant pstate{src_root, build_root}; MIR::Passes::lower_project(&irlist, pstate); MIR::lower(&irlist, pstate); } #if false TEST(lower, simple_real) { auto irlist = lower(R"EOF( project('foo', 'c') t_files = files( 'bar.c', ) executable( 'exe', t_files, ) )EOF"); MIR::State::Persistant pstate{src_root, build_root}; MIR::Passes::lower_project(&irlist, pstate); MIR::lower(&irlist, pstate); } #endif
36.863517
100
0.655892
[ "vector" ]
6e08530c98c48c7737e2c1bc5d8d599f9901bb1e
16,528
cc
C++
sample_test.cc
flipk/sqlite3gen
952a5655abfd23a916ea548362337b0c2bd3551c
[ "Unlicense" ]
null
null
null
sample_test.cc
flipk/sqlite3gen
952a5655abfd23a916ea548362337b0c2bd3551c
[ "Unlicense" ]
null
null
null
sample_test.cc
flipk/sqlite3gen
952a5655abfd23a916ea548362337b0c2bd3551c
[ "Unlicense" ]
null
null
null
#define __STDC_FORMAT_MACROS #ifndef DEPENDING #include SAMPLE_H_HDR #endif #include <stdio.h> #include <inttypes.h> #include <unistd.h> #include <stdlib.h> #include <gtest/gtest.h> #include "sample_test.h" int main(int argc, char ** argv) { ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); unlink(TEST_DATABASE); return ret; } //////////////////////////// SQL_TABLE_user_custom //////////////////////////// SQL_TABLE_user_custom :: SQL_TABLE_user_custom(sqlite3 *_pdb /*= NULL*/) : SQL_TABLE_User(_pdb) { pStmt_by_great_balance = NULL; } SQL_TABLE_user_custom :: ~SQL_TABLE_user_custom(void) { sqlite3_finalize(pStmt_by_great_balance); } // note this is intended to demonstrate extended queries // even though it duplicates the get_great_balance CUSTOM-GET // in the base class. bool SQL_TABLE_user_custom :: get_by_great_balance(double threshold) { int r; bool ret = false; if (pStmt_by_great_balance == NULL) { r = sqlite3_prepare_v2( pdb, "SELECT rowid,* FROM user WHERE balance > ?", -1, &pStmt_by_great_balance, NULL); if (r != SQLITE_OK) printf("ERROR building SELECT for balance at line %d\n", __LINE__); } sqlite3_reset(pStmt_by_great_balance); r = sqlite3_bind_double(pStmt_by_great_balance, 1, threshold); if (r != SQLITE_OK) { fprintf(stderr, "SQL_TABLE_user :: get_by_great_balance : " "bind: r = %d\n", r); return false; } if (library::SQL_TABLE_ALL_TABLES::log_get_func) library::SQL_TABLE_ALL_TABLES::log_get_func( library::SQL_TABLE_ALL_TABLES::log_arg, pStmt_by_great_balance); r = sqlite3_step(pStmt_by_great_balance); if (r == SQLITE_ROW) { ret = get_columns(pStmt_by_great_balance); previous_get = pStmt_by_great_balance; } else if (r == SQLITE_DONE) previous_get = NULL; return ret; } void SQL_TABLE_user_custom :: print(void) { // we can print a blob as a string only because // this test program always sets 'blob' objects to // strings. printf("row %" PRId64 " userid %d" " %s %s %s SSN %d %f proto (%d) '%s'\n", (int64_t) rowid, userid, firstname.c_str(), mi.c_str(), lastname.c_str(), SSN, balance, (int) proto.length(), proto.c_str()); printf("%d checkouts:\n", (int) Checkouts.size()); for (size_t ind = 0; ind < Checkouts.size(); ind++) { printf(" row %" PRId64 " userid2 %d" " bookid %d duedate %" PRId64 "\n", (int64_t) Checkouts[ind].rowid, Checkouts[ind].userid2, Checkouts[ind].bookid2, Checkouts[ind].duedate); } printf("TOSTRING: %s\n", toString().c_str()); } ////////////////////////////// SampleTextFixture ////////////////////////////// int SampleTextFixture :: get_all(void) { int count = 0; ucust.init(); if (ucust.get_all() == false) { printf("get failed\n"); return -1; } do { ucust.print(); count++; } while (ucust.get_next()); return count; } void SampleTextFixture :: get_row(int64_t row) { ucust.init(); if (ucust.get_by_rowid(row) == false) { printf("get failed\n"); return; } do { ucust.print(); } while (ucust.get_next()); } int SampleTextFixture :: get_like(const std::string &patt) { int count = 0; ucust.init(); if (ucust.get_by_lastname_like(patt) == false) { printf("get like failed\n"); return -1; } do { ucust.print(); count++; } while (ucust.get_next()); return count; } int SampleTextFixture :: get_custom1(double thresh) { int count = 0; ucust.init(); if (ucust.get_great_balance(thresh) == false) { printf("get by great threshold returned no users\n"); return -1; } do { ucust.print(); count++; } while (ucust.get_next()); return count; } int SampleTextFixture :: get_custom2(const std::string &first, const std::string &last) { int count = 0; ucust.init(); if (ucust.get_firstlast(first, last) == false) { printf("get by firstlast returned no users\n"); return -1; } do { ucust.print(); count++; } while (ucust.get_next()); return count; } void SampleTextFixture :: log_sql_upd(void *arg, sqlite3_stmt *stmt) { SampleTextFixture * stf = (SampleTextFixture*) arg; char * sql = sqlite3_expanded_sql(stmt); printf("** SQL UPDATE LOG: %s\n", sql); sqlite3_free(sql); } // static void SampleTextFixture :: log_sql_get(void *arg, sqlite3_stmt *stmt) { SampleTextFixture * stf = (SampleTextFixture*) arg; char * sql = sqlite3_expanded_sql(stmt); printf("** SQL GET LOG: %s\n", sql); sqlite3_free(sql); } // static void SampleTextFixture :: log_sql_row(void *arg, const std::string &msg) { SampleTextFixture * stf = (SampleTextFixture*) arg; fprintf(stderr, "** SQL ROW: %s\n", msg.c_str()); } // static void SampleTextFixture :: log_sql_err(void *arg, const std::string &msg) { SampleTextFixture * stf = (SampleTextFixture*) arg; fprintf(stderr, "** SQL ERROR: %s\n", msg.c_str()); } // static void SampleTextFixture :: table_callback(sqlite3 *pdb, const std::string &table_name, int before, int after) { printf("table '%s' goes from version %d to %d\n", table_name.c_str(), before, after); } void SampleTextFixture :: SetUp() { int sqlret = sqlite3_open(TEST_DATABASE, &pdb); ASSERT_EQ(sqlret,SQLITE_OK); user.set_db(pdb); ucust.set_db(pdb); library::SQL_TABLE_ALL_TABLES::register_log_funcs( &log_sql_upd, &log_sql_get, &log_sql_row, &log_sql_err, (void*) this); bool init_ok = library::SQL_TABLE_ALL_TABLES::init_all(pdb, &table_callback); ASSERT_EQ(init_ok,true); } void SampleTextFixture :: TearDown() { // this finalizes any open stmts and releases // reference counts/locks. user.set_db(NULL); ucust.set_db(NULL); ASSERT_EQ(ucust.was_properly_done(),true); int r = sqlite3_close(pdb); ASSERT_EQ(r,SQLITE_OK); sqlite3_shutdown(); } ///////////////////////////////// test cases ///////////////////////////////// TEST_F(SampleTextFixture, 1_descriptors) { std::vector<library::SQL_Column_Descriptor> cols; library::SQL_TABLE_User::get_column_descriptors(cols); printf("USER table column descriptors:\n"); for (size_t ind = 0; ind < cols.size(); ind++) { library::SQL_Column_Descriptor &c = cols[ind]; printf("tab '%s' field '%s' ctype '%s' sqty %d genty %d\n", c.tablename.c_str(), c.fieldname.c_str(), c.ctype.c_str(), c.sqlite_type, c.sqlite3gen_type); } } static int32_t userid_2to3 = -1; TEST_F(SampleTextFixture, 2_insert) { user.firstname = "flippy"; user.lastname = "kadoodle"; user.mi = "f"; user.SSN = 456789012; user.balance = 14.92; user.proto = "PROTOBUFS BABY"; ASSERT_EQ(user.insert(),true); userid_2to3 = user.userid; printf("inserted rowid %" PRId64 " userid %d\n", (int64_t) user.rowid, user.userid); ASSERT_EQ(get_all(),1); } TEST_F(SampleTextFixture, 3_getuserid) { if (userid_2to3 == -1) { printf("ERROR : test 2 must be run before test 3....\n"); ASSERT_NE(userid_2to3,-1); } ASSERT_EQ(ucust.get_by_userid(userid_2to3),true); ucust.print(); ASSERT_EQ(ucust.lastname,"kadoodle"); ASSERT_EQ(ucust.SSN,456789012); } TEST_F(SampleTextFixture, 4_getSSN) { ASSERT_EQ(user.get_by_SSN(456789012),true); user.balance = 15.44; ASSERT_EQ(user.update_balance(),true); printf("updated balance in row %" PRId64 "\n", (int64_t) user.rowid); } #ifdef INCLUDE_SQLITE3GEN_PROTOBUF_SUPPORT TEST_F(SampleTextFixture, 5_protobuf) { ASSERT_EQ(user.get_by_SSN(456789012),true); printf("encoding to protobuf!\n"); library::TABLE_User_m msg; std::string binary; user.copy_to_proto(msg); msg.SerializeToString(&binary); printf("encoded user to protobuf %d bytes long\n", (int) binary.size()); ASSERT_EQ((int) binary.size(),60); printf("decoding back from protobuf!\n"); msg.Clear(); ASSERT_EQ(msg.ParseFromString(binary),true); SQL_TABLE_user_custom t; t.copy_from_proto(msg); t.print(); ASSERT_EQ(t.SSN,456789012); ASSERT_EQ(t.lastname,"kadoodle"); } #endif TEST_F(SampleTextFixture,6_like) { ASSERT_EQ(get_like("%dood%"),1); } TEST_F(SampleTextFixture,7_custom1) { ASSERT_EQ(get_custom1(15.00),1); } TEST_F(SampleTextFixture,8_custom2) { ASSERT_EQ(get_custom2("flip%", "kad%"),1); } static int64_t rowid_9to10 = -1; TEST_F(SampleTextFixture,9_delete_SSN) { ASSERT_EQ(user.delete_SSN(456789012),true); // put it back again user.firstname = "flippy"; user.lastname = "kadoodle"; user.mi = "f"; user.SSN = 456789012; user.balance = 14.92; user.proto = "PROTOBUFS BABY"; ASSERT_EQ(user.insert(),true); rowid_9to10 = user.rowid; } TEST_F(SampleTextFixture,10_delete_rowid) { if (rowid_9to10 == -1) { printf("ERROR test 9 must be run before test 10\n"); ASSERT_NE(rowid_9to10,-1); } user.rowid = rowid_9to10; ASSERT_EQ(user.delete_rowid(),true); } static int32_t u1, u2, u3, b1, b2, b3; static bool test11run = false;; TEST_F(SampleTextFixture,11_insert_books) { library::SQL_TRANSACTION t(pdb); ASSERT_EQ(t.begin(),true); { library::SQL_TABLE_User u(pdb); library::SQL_TABLE_Book b(pdb); library::SQL_TABLE_Checkouts c(pdb); u.firstname = "fir1"; u.lastname = "las1"; u.SSN = 11; u.balance = 4.25; u.proto = "this is proto blob"; #ifdef INCLUDE_SQLITE3GEN_PROTOBUF_SUPPORT u.test3 = sample::library2::ENUM_TWO; #endif ASSERT_EQ(u.insert(),true); u1 = u.userid; u.firstname = "fir2"; u.lastname = "las2"; u.SSN = 22; u.balance = 8.50; u.proto = "this is proto blob 2"; #ifdef INCLUDE_SQLITE3GEN_PROTOBUF_SUPPORT u.test3 = sample::library2::ENUM_ONE; #endif ASSERT_EQ(u.insert(),true); u2 = u.userid; u.firstname = "fir3"; u.lastname = "las3"; u.SSN = 33; u.balance = 12.75; u.proto = "this is proto blob 3"; #ifdef INCLUDE_SQLITE3GEN_PROTOBUF_SUPPORT u.test3 = sample::library2::ENUM_TWO; #endif ASSERT_EQ(u.insert(),true); u3 = u.userid; printf("inserted userids %d, %d, and %d\n", u1, u2, u3); b.title = "book 1 title"; b.isbn = "111222"; b.price = 4.55; b.quantity = 6; ASSERT_EQ(b.insert(),true); b1 = b.bookid; b.title = "book 2 title"; b.isbn = "444555"; b.price = 8.15; b.quantity = 1; ASSERT_EQ(b.insert(),true); b2 = b.bookid; b.title = "book 3 title"; b.isbn = "12345"; b.price = 12.35; b.quantity = 2; ASSERT_EQ(b.insert(),true); b3 = b.bookid; printf("inserted bookids %d, %d, and %d\n", b1, b2, b3); c.bookid2 = b2; c.userid2 = u1; c.duedate = 5; ASSERT_EQ(c.insert(),true); c.bookid2 = b3; c.userid2 = u1; c.duedate = 6; ASSERT_EQ(c.insert(),true); c.bookid2 = b1; c.userid2 = u2; c.duedate = 12; ASSERT_EQ(c.insert(),true); c.bookid2 = b3; c.userid2 = u3; c.duedate = 2; ASSERT_EQ(c.insert(),true); printf("inserted 4 checkouts\n"); } ASSERT_EQ(t.commit(),true); test11run = true; } TEST_F(SampleTextFixture,12_checkouts_protobuf) { if (test11run == false) { printf("ERROR: 11 must be run before 12\n"); ASSERT_EQ(test11run,true); } #ifdef INCLUDE_SQLITE3GEN_PROTOBUF_SUPPORT SQL_TABLE_user_custom u2(pdb); ASSERT_EQ(ucust.get_by_userid(u1),true); printf("got userid %d!\n", u1); ASSERT_GT(ucust.get_subtable_Checkouts(),0); ucust.print(); library::TABLE_User_m msg; ucust.copy_to_proto(msg); u2.copy_from_proto(msg); printf("after protobuf marshaling:\n"); u2.print(); ASSERT_EQ(u2.firstname,"fir1"); ASSERT_EQ(u2.lastname,"las1"); ASSERT_EQ(u2.SSN,11); ASSERT_EQ(u2.Checkouts.size(),2); #endif } TEST_F(SampleTextFixture,13_checkouts_xml) { if (test11run == false) { printf("ERROR: 11 must be run before 12\n"); ASSERT_EQ(test11run,true); } #ifdef INCLUDE_SQLITE3GEN_TINYXML2_SUPPORT { tinyxml2::XMLPrinter printer; { tinyxml2::XMLDocument doc; library::SQL_TABLE_ALL_TABLES :: export_xml_all(pdb,doc); doc.Print( &printer ); printf("xml:\n%s\n", printer.CStr()); } { tinyxml2::XMLDocument doc; ASSERT_EQ(doc.Parse( printer.CStr() ),tinyxml2::XML_SUCCESS); if (0) // i trust this to work { tinyxml2::XMLPrinter printer2; doc.Print( &printer2 ); printf("reparsed xml:\n%s\n", printer2.CStr()); } sqlite3 * pdb2; printf("CREATING SECOND TEST DATABASE\n"); ASSERT_EQ(sqlite3_open(TEST_DATABASE2, &pdb2),SQLITE_OK); library::SQL_TABLE_ALL_TABLES::init_all(pdb2, &SampleTextFixture::table_callback); library::SQL_TABLE_ALL_TABLES::import_xml_all(pdb2,doc); SQL_TABLE_user_custom u2(pdb2); printf(" *** displaying full contents of second test database\n"); int count = 0; bool ok = u2.get_all(); while (ok) { u2.get_subtables(); u2.print(); count++; ok = u2.get_next(); } ASSERT_EQ(count,3); u2.set_db(NULL); ASSERT_EQ(sqlite3_close(pdb2),SQLITE_OK); unlink(TEST_DATABASE2); printf(" *** second test database done and gone\n"); } } #endif } TEST_F(SampleTextFixture,14_merge_from_proto) { if (ucust.get_by_userid(u2)) { printf("BEFORE MERGE:\n"); ucust.print(); library::TABLE_User_m msg; msg.set_lastname("las2"); ASSERT_EQ(ucust.merge_from_proto(msg),false); msg.set_mi("x"); ASSERT_EQ(ucust.merge_from_proto(msg),true); printf("AFTER MERGE:\n"); ucust.print(); } } TEST_F(SampleTextFixture,15_due1) { library::SQL_SELECT_due_books due(pdb); printf(" *** testing SQL_SELECT_due_books:\n"); bool ok = due.get(1,4); ASSERT_EQ(ok,true); int count = 0; while (ok) { printf("user_rid %" PRId64 " %s %s " "book_rid %" PRId64 " %s " "checkouts_rid %" PRId64 " due %" PRId64 "\n", (int64_t) due.User_rowid, due.User_firstname.c_str(), due.User_lastname.c_str(), (int64_t) due.Book_rowid, due.Book_title.c_str(), (int64_t) due.Checkouts_rowid, (int64_t) due.Checkouts_duedate); printf("TOSTRING: %s\n", due.toString().c_str()); count++; ok = due.get_next(); } ASSERT_EQ(count,3); } TEST_F(SampleTextFixture,16_due2) { library::SQL_SELECT_due_books2 due(pdb); printf(" *** testing SQL_SELECT_due_books2:\n"); bool ok = due.get(1,4); ASSERT_EQ(ok,true); int count = 0; while (ok) { printf("user_rid %" PRId64 " %s %s " "book_rid %" PRId64 " %s " "checkouts_rid %" PRId64 " due %" PRId64 "\n", (int64_t) due.User_rowid, due.User_firstname.c_str(), due.User_lastname.c_str(), (int64_t) due.Book_rowid, due.Book_title.c_str(), (int64_t) due.Checkouts_rowid, (int64_t) due.Checkouts_duedate); printf("TOSTRING: %s\n", due.toString().c_str()); count++; ok = due.get_next(); } ASSERT_EQ(count,3); }
24.485926
88
0.582043
[ "vector" ]
6e10fed15dce94a6e90b5fd69bcdfdc6f1c63ee7
7,941
cc
C++
src/keytree.cc
un-ch/bbkeys
6a28d4614d46df3d68f1f45ccde71eb14e6db6e6
[ "MIT" ]
7
2017-09-08T09:19:07.000Z
2021-11-09T13:02:26.000Z
src/keytree.cc
un-ch/bbkeys
6a28d4614d46df3d68f1f45ccde71eb14e6db6e6
[ "MIT" ]
4
2017-11-12T13:09:59.000Z
2022-02-03T06:31:24.000Z
src/keytree.cc
un-ch/bbkeys
6a28d4614d46df3d68f1f45ccde71eb14e6db6e6
[ "MIT" ]
1
2022-01-28T11:07:24.000Z
2022-01-28T11:07:24.000Z
// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*- // keytree.cc for Epistrophy - a key handler for NETWM/EWMH window managers. // Copyright (c) 2002 - 2002 Ben Jansens <ben at orodu.net> // // Modified for use and inclusion in bbkeys by Jason 'vanRijn' Kasper // // 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 "keytree.hh" #include <string> #include <sstream> #include <iostream> keytree::keytree(Display *display): _display(display) { _head = new keynode; _head->parent = NULL; _head->action = NULL; // head's action is always NULL _current = _head; // for complete initialization, initialize() has to be called as well. We // call initialize() when we are certain that the config object (which the // timer uses) has been fully initialized. (see parser::parse()) } keytree::~keytree() { clearTree(_head); } void keytree::unloadBindings() { ChildList::iterator it, end = _head->children.end(); for (it = _head->children.begin(); it != end; ++it) clearTree(*it); _head->children.clear(); reset(); } void keytree::clearTree(keynode *node) { if (!node) return; ChildList::iterator it, end = node->children.end(); for (it = node->children.begin(); it != end; ++it) clearTree(*it); node->children.clear(); if (node->action) delete node->action; delete node; node = NULL; } void keytree::grabDefaults(ScreenHandler *scr) { grabChildren(_head, scr); } void keytree::ungrabDefaults(ScreenHandler *scr) { Action *act; ChildList::const_iterator it, end = _head->children.end(); for (it = _head->children.begin(); it != end; ++it) { act = (*it)->action; if (act && act->type() != Action::toggleGrabs) scr->ungrabKey(act->keycode(), act->modifierMask()); } } void keytree::grabChildren(keynode *node, ScreenHandler *scr) { Action *act; ChildList::const_iterator it, end = node->children.end(); for (it = node->children.begin(); it != end; ++it) { act = (*it)->action; if (act) { bool ret = scr->grabKey(act->keycode(), act->modifierMask()); if (!ret) { string key; KeySym _sym = XkbKeycodeToKeysym(_display, act->keycode(), 0, 0); if (_sym == NoSymbol) key="key not found"; else key = XKeysymToString(_sym); cerr << BBTOOL << ": keytree : grabChildren : " << "could not activate keybinding for " << "key: [" << key << "], mask: [" << act->modifierMask() << "], action: [" << act->getActionName() << "]\n"; } } } } void keytree::ungrabChildren(keynode *node, ScreenHandler *scr) { ChildList::const_iterator head_it, head_end = _head->children.end(); ChildList::const_iterator it, end = node->children.end(); bool ungrab = true; // when ungrabbing children, make sure that we don't ungrab any topmost keys // (children of the head node) This would render those topmost keys useless. // Topmost keys are _never_ ungrabbed, since they are only grabbed at startup for (it = node->children.begin(); it != end; ++it) { if ( (*it)->action ) { for (head_it = _head->children.begin(); head_it != head_end; ++head_it) { if ( (*it)->action->modifierMask() == (*head_it)->action->modifierMask() && (*it)->action->keycode() == (*head_it)->action->keycode()) { ungrab = false; break; } } if (ungrab) scr->ungrabKey( (*it)->action->keycode(), (*it)->action->modifierMask()); ungrab = true; } } } Action * keytree::getAction(const XKeyEvent * const e, unsigned int & state, ScreenHandler *scr) { Action *act; // we're done with the children. ungrab them if (_current != _head) ungrabChildren(_current, scr); // With XKB e->xkey.state can hold the group index in high bits, in // addition to the standard modifier bits. This does not happen on the // first grabbed event, but happens when doing stacked cycling (when // XGrabKeyboard is active). In order to recognize subsequent keypresses, // we must clear all unneeded bits in the state field. state &= (ShiftMask | LockMask | ControlMask | Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask); ChildList::const_iterator it, end = _current->children.end(); for (it = _current->children.begin(); it != end; ++it) { act = (*it)->action; if (e->keycode == act->keycode() && state == act->modifierMask()) { if (act->type() == Action::cancelChain ) { // user is cancelling the chain explicitly _current = _head; return act; } else if ( isLeaf(*it) ) { // node is a leaf, so an action will be executed _current = _head; return act; } else { // node is not a leaf, so we advance down the tree, and grab the // children of the new current node. no action is executed _current = *it; grabChildren(_current, scr); return act; } } } // action not found. back to the head _current = _head; return (Action *)NULL; } void keytree::addAction(Action::ActionType action, unsigned int mask, string key, string arg) { if (action == Action::toggleGrabs && _current != _head) { // the toggleGrabs key can only be set up as a root key, since if // it was a chain key, we'd have to not ungrab the whole chain up // to that key. which kinda defeats the purpose of this function. return; } KeySym sym = XStringToKeysym(key.c_str()); KeyCode keyCode = XKeysymToKeycode(_display, sym); if (keyCode == 0) { cerr << BBTOOL << ": " << "keytree::addAction: keyCode for key: [" << key << "] not found. can't add it. skipping.\n"; return; } keynode *tmp = new keynode; tmp->action = new Action(action, _display, keyCode, mask, arg); tmp->parent = _current; _current->children.push_back(tmp); } void keytree::advanceOnNewNode() { keynode *tmp = new keynode; tmp->action = NULL; tmp->parent = _current; _current->children.push_back(tmp); _current = tmp; } void keytree::retract() { if (_current != _head) _current = _current->parent; } void keytree::setCurrentNodeProps(Action::ActionType action, unsigned int mask, string key, string arg) { if (_current->action) delete _current->action; KeySym sym = XStringToKeysym(key.c_str()); _current->action = new Action(action, _display, XKeysymToKeycode(_display, sym), mask, arg); } void keytree::showTree(keynode *node) { if (!node) return; ChildList::iterator it, end = node->children.end(); for (it = node->children.begin(); it != end; ++it) showTree(*it); if (node->action) { cout << BBTOOL << ": " << "showTree: [" << node->action->toString() << "]" << endl; } }
30.425287
103
0.632414
[ "render", "object" ]
6e12543bc00520858dea7ad148050310a1c8169d
1,646
cc
C++
peridot/public/lib/modular_test_harness/cpp/fake_agent.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
null
null
null
peridot/public/lib/modular_test_harness/cpp/fake_agent.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
peridot/public/lib/modular_test_harness/cpp/fake_agent.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 <lib/modular_test_harness/cpp/fake_agent.h> namespace modular { namespace testing { FakeAgent::FakeAgent() = default; FakeAgent::FakeAgent( fit::function<void(std::string client_url)> connect_callback) : on_connect_(std::move(connect_callback)) {} FakeAgent::~FakeAgent() = default; // |modular::testing::FakeComponent| void FakeAgent::OnCreate(fuchsia::sys::StartupInfo startup_info) { component_context()->svc()->Connect(component_context_.NewRequest()); component_context()->svc()->Connect(agent_context_.NewRequest()); component_context()->outgoing()->AddPublicService<fuchsia::modular::Agent>( bindings_.GetHandler(this)); } void FakeAgent::set_on_run_task( fit::function<void(std::string task_id, RunTaskCallback callback)> on_run_task) { on_run_task_ = std::move(on_run_task); } // |fuchsia::modular::Agent| void FakeAgent::Connect( std::string requestor_url, fidl::InterfaceRequest<fuchsia::sys::ServiceProvider> services_request) { services_.AddBinding(std::move(services_request)); if (on_connect_) { on_connect_(requestor_url); } } // |fuchsia::modular::Agent| void FakeAgent::RunTask(std::string task_id, RunTaskCallback callback) { if (on_run_task_) { on_run_task_(task_id, std::move(callback)); } } std::vector<std::string> FakeAgent::GetSandboxServices() { return {"fuchsia.modular.ComponentContext", "fuchsia.modular.AgentContext"}; } } // namespace testing } // namespace modular
29.392857
78
0.735723
[ "vector" ]
6e14ed73f6b16323a03a7bfdfd06a876995da945
402
cpp
C++
generator/affiliation.cpp
LaGrunge/geocore
b599eda29a32a14e5c02f51c66848959b50732f2
[ "Apache-2.0" ]
1
2019-10-02T16:17:31.000Z
2019-10-02T16:17:31.000Z
generator/affiliation.cpp
LaGrunge/omim
8ce6d970f8f0eb613531b16edd22ea8ab923e72a
[ "Apache-2.0" ]
6
2019-09-09T10:11:41.000Z
2019-10-02T15:04:21.000Z
generator/affiliation.cpp
LaGrunge/geocore
b599eda29a32a14e5c02f51c66848959b50732f2
[ "Apache-2.0" ]
null
null
null
#include "generator/affiliation.hpp" namespace feature { SingleAffiliation::SingleAffiliation(std::string const & filename) : m_filename(filename) { } std::vector<std::string> SingleAffiliation::GetAffiliations(FeatureBuilder const &) const { return {m_filename}; } bool SingleAffiliation::HasRegionByName(std::string const & name) const { return name == m_filename; } } // namespace feature
20.1
89
0.758706
[ "vector" ]
6e19718dc3b5e5d7cfc67f4a5c0b679a30793424
11,156
cpp
C++
Desarrollo(VS2017)/Motor2D/j1Scene.cpp
Sanmopre/DESARROLLO
4b601ca0862c6cf5831ec7fbe226fd97d52cf11b
[ "MIT" ]
null
null
null
Desarrollo(VS2017)/Motor2D/j1Scene.cpp
Sanmopre/DESARROLLO
4b601ca0862c6cf5831ec7fbe226fd97d52cf11b
[ "MIT" ]
null
null
null
Desarrollo(VS2017)/Motor2D/j1Scene.cpp
Sanmopre/DESARROLLO
4b601ca0862c6cf5831ec7fbe226fd97d52cf11b
[ "MIT" ]
1
2019-12-27T20:26:49.000Z
2019-12-27T20:26:49.000Z
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1Scene.h" #include "j1Player.h" #include "j1Collision.h" #include "j1FadeToBlack.h" #include "j1Entity.h" #include "j1EntityManager.h" #include "j1Gui.h" #include "j1MainMenu.h" #include "j1Fonts.h" #include <stdio.h> #include "Brofiler/Brofiler.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake() { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { Timer = 0; Lifes = 3; Coins = 0; player = nullptr; skeleton = nullptr; flying_enemy = nullptr; coin = App->EntityManager->Summon_Entity(j1Entity::Types::COIN, Coin_pos); Add_Console(); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { return true; } // Called each loop iteration bool j1Scene::Update(float dt) { BROFILER_CATEGORY("Scene_Update", Profiler::Color::Violet) bool ret = true; /* if (already_added == true) { Timer += dt; sprintf_s(Timer_T, "%.2f", Timer); App->tex->Unload(stats.Timer_label->texture); stats.Timer_label->text = Timer_T; sprintf_s(Lifes_T, "%d", Lifes); App->tex->Unload(stats.Lifes_label->texture); stats.Lifes_label->text = Lifes_T; sprintf_s(Coins_T, "%d", Coins); App->tex->Unload(stats.Coins_label->texture); stats.Coins_label->text = Coins_T; } */ if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) { Main_Menu = false; Change_Map(1); } if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN) { Main_Menu = false; Change_Map(2); } if (App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) { App->LoadGame(); } if (App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) { App->SaveGame(); } if (App->input->GetKey(SDL_SCANCODE_F8) == KEY_DOWN) { Main_Menu = true; Change_Map(3); Close_InGame_UI(); } //Game menu if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN && Main_Menu == false) { Activate_Menu(); } if (App->input->GetKey(SDL_SCANCODE_GRAVE) == KEY_DOWN ){ Activate_Console(); } //if (console.Input->focus) // ret = Console_Manager(); //UPDATES ALL UI POSITIONS if (already_added == true) { //App->gui->Update_Position(stats.Timer_label, { 220,(-App->render->camera.y / 2) + 22 }, { 0,(-App->render->camera.y / 2) }); App->gui->Update_Position(stats.Timer_icon, { 180,(-App->render->camera.y / 2) + 13 }, { 0, (-App->render->camera.y / 2) }); //App->gui->Update_Position(stats.Lifes_label, { 150,(-App->render->camera.y / 2) + 22 }, { 0, (-App->render->camera.y / 2) }); App->gui->Update_Position(stats.Lifes_icon, { 100,(-App->render->camera.y / 2) + 13 }, { 0, (-App->render->camera.y / 2) }); //App->gui->Update_Position(stats.Coins_label, { 55,(-App->render->camera.y / 2) + 22 }, { 0, (-App->render->camera.y / 2) }); App->gui->Update_Position(stats.Coins_icon, { 10,(-App->render->camera.y / 2) + 15 }, { 0, (-App->render->camera.y / 2) }); App->gui->Update_Position(menu.Image, { 160,(-App->render->camera.y / 2) + 5 }, { 0, (-App->render->camera.y / 2) }); App->gui->Update_Position(menu.Menu_button, { 450,(-App->render->camera.y / 2 )+13}, { 0, 0 }); App->gui->Update_Position(menu.Return_button, { 210,(-App->render->camera.y / 2) + 130 }, { -3, (-App->render->camera.y / 2) - 5 }); App->gui->Update_Position(menu.Title, { 205,(-App->render->camera.y / 2) + 50 }, { 30, (-App->render->camera.y / 2) }); App->gui->Update_Position(menu.Resume_button, { 210,(-App->render->camera.y / 2) + 100 }, { 10, (-App->render->camera.y / 2) - 5 }); App->gui->Update_Position(menu.Exit_button, { 210,(-App->render->camera.y / 2) + 220 }, { 20, (-App->render->camera.y / 2) - 5 }); App->gui->Update_Position(menu.Save, { 210,(-App->render->camera.y / 2) + 160 }, { 20, (-App->render->camera.y / 2) - 5 }); App->gui->Update_Position(menu.Load, { 210,(-App->render->camera.y / 2) + 190 }, { 20, (-App->render->camera.y / 2) - 5 }); App->gui->Update_Position(console.Image, { 160,(-App->render->camera.y / 2) + 60 }, { 0, (-App->render->camera.y / 2) }); App->gui->Update_Position(console.Input, { 170,(-App->render->camera.y / 2) + 220 }, { 0, (-App->render->camera.y / 2) }); } if (actual_map == 1) {App->map2->Draw();} if (actual_map == 2) {App->map->Draw();} return ret; } // Called each loop iteration bool j1Scene::PostUpdate() { bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } bool j1Scene::Change_Map(int map) { CleanUp(); if (map == 1) { if (already_added == false) { Add_UI(); } Open_InGame_UI(); Main_Menu = false; App->MainMenu->Disable_UI(); //App->EntityManager->Destroy_Entities(); if (player == nullptr) { player = App->EntityManager->Summon_Entity(j1Entity::Types::PLAYER, Player_Pos); } skeleton = App->EntityManager->Summon_Entity(j1Entity::Types::SKELETON, Skeleton_Position); flying_enemy = App->EntityManager->Summon_Entity(j1Entity::Types::FLYING_ENEMY, Fly_Position); player->Alive = false; App->fade->Fade_To_Black(2); App->map->CleanUp(); App->collision->MapCleanUp(); App->map2->Load("castle.tmx"); App->audio->PlayMusic("audio/music/castle.ogg"); actual_map = 1; return true; } if (map == 2) { if (already_added == false) { Add_UI(); } Open_InGame_UI(); Main_Menu = false; App->MainMenu->Disable_UI(); //App->EntityManager->Destroy_Entities(); skeleton = App->EntityManager->Summon_Entity(j1Entity::Types::SKELETON, Skeleton_Position); flying_enemy = App->EntityManager->Summon_Entity(j1Entity::Types::FLYING_ENEMY, Fly_Position); if (player == nullptr) { player = App->EntityManager->Summon_Entity(j1Entity::Types::PLAYER, Player_Pos); } player->Alive = false; App->fade->Fade_To_Black(2); App->map2->CleanUp(); App->collision->MapCleanUp(); App->map->Load("dungeon.tmx"); App->audio->PlayMusic("audio/music/ghost.ogg"); actual_map = 2; return false; } if (map == 3) { //Activate_Menu(); Main_Menu = true; App->MainMenu->Enable_UI(); App->fade->Fade_To_Black(2); App->map2->CleanUp(); App->map->CleanUp(); actual_map = 3; return false; } } bool j1Scene::Load(pugi::xml_node& data) { return true; } bool j1Scene::Save(pugi::xml_node& data) const { pugi::xml_node player = data.append_child("playerPos"); pugi::xml_node player_collider = data.append_child("player_collider"); return true; } // Called before quitting void j1Scene::Add_UI() { stats.Timer_label = App->gui->ADD_ELEMENT(GUItype::GUI_LABEL, nullptr, { 220,22 }, { 0,0 }, false, true, { 0,0,0,0 }, "0:00"); stats.Timer_icon = App->gui->ADD_ELEMENT(GUItype::GUI_IMAGE, nullptr, { 180, 13 }, { 0,0 }, false, true, { 0, 0, 30,30 }, nullptr, this); stats.Lifes_label = App->gui->ADD_ELEMENT(GUItype::GUI_LABEL, nullptr, { 146,22 }, { 0,0 }, false, true, { 0,0,0,0 }, "3"); stats.Lifes_icon = App->gui->ADD_ELEMENT(GUItype::GUI_IMAGE, nullptr, { 100, 13 }, { 0,0 }, false, true, { 0, 0, 30,30 }, nullptr, this); stats.Coins_label = App->gui->ADD_ELEMENT(GUItype::GUI_LABEL, nullptr, { 55,22 }, { 0,0 }, false, true, { 0,0,0,0 }, "0"); stats.Coins_icon = App->gui->ADD_ELEMENT(GUItype::GUI_IMAGE, nullptr, { 10, 15 }, { 0,0 }, false, true, { 0, 0, 30,30 }, nullptr, this); menu.Image = App->gui->ADD_ELEMENT(GUItype::GUI_IMAGE, nullptr, { 10, 60 }, { 0,0 }, false, false, { 0, 0, 200, 280 }, nullptr, this); menu.Menu_button = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 450,250 }, { 0,-235 }, true, true, { 0,0,70,30 }, "OPTIONS", this); menu.Return_button = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 210,130 }, { 20,5 }, true, false, { 0, 0,100,22 }, "RETURN", this); menu.Title = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 205,50 }, { 30,0 }, false, false, { 0, 0,109,27 }, "MENU", this, false, false, SCROLL_TYPE::SCROLL_NONE, true); menu.Resume_button = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 210,100 }, { 20,5 }, true, false, { 0, 0,100,22 }, "RESUME", this); menu.Exit_button = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 210,220 }, { 20,5 }, true, false, { 0, 0,100,22 }, "EXIT", this); menu.Save = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 210,160 }, { 20,5 }, true, false, { 0, 0,100,22 }, "SAVE", this); menu.Load = App->gui->ADD_ELEMENT(GUItype::GUI_BUTTON, nullptr, { 210,190 }, { 20,5 }, true, false, { 0, 0,100,22 }, "LOAD", this); already_added = true; } void j1Scene::Add_Console() { console.Image = App->gui->ADD_ELEMENT(GUItype::GUI_IMAGE, nullptr, { 160, 60 }, { 0,0 }, false, false, { 0, 0, 198, 200 }, nullptr, this); console.Input = App->gui->ADD_ELEMENT(GUItype::GUI_INPUTBOX, nullptr, { 168,220 }, { 0,0 }, true, false, { 0, 0,182,26 }, nullptr, this); } void j1Scene::Activate_Menu() { menu.Image->enabled = !menu.Image->enabled; menu.Resume_button->enabled = !menu.Resume_button->enabled; menu.Return_button->enabled = !menu.Return_button->enabled; menu.Title->enabled = !menu.Title->enabled; menu.Exit_button->enabled = !menu.Exit_button->enabled; menu.Load->enabled = !menu.Load->enabled; menu.Save->enabled = !menu.Save->enabled; } void j1Scene::Activate_Console() { console.Input->focus = !console.Input->focus; console.Input->enabled = !console.Input->enabled; console.Image->enabled = !console.Image->enabled; } void j1Scene::GUI_Event_Manager(GUI_Event type, j1GUIelement* element) { switch (type) { case GUI_Event::EVENT_ONCLICK: { App->audio->PlayFx(App->audio->LoadFx("audio/fx/UI_fx.wav")); if (element == menu.Return_button) { Activate_Menu(); } if (element == menu.Exit_button) { Main_Menu = true; Change_Map(3); } if (element == menu.Save) { App->SaveGame(); Activate_Menu(); } if (element == menu.Load) { Activate_Menu(); } if (element == menu.Resume_button) { Activate_Menu(); } if (element == menu.Menu_button) { Activate_Menu(); } if (element == menu.Exit_button) { Main_Menu = true; actual_map = Change_Map(3); Close_InGame_UI(); } } } } void j1Scene::Close_InGame_UI() { stats.Timer_label->enabled = false; stats.Timer_icon->enabled = false; stats.Lifes_label->enabled = false; stats.Lifes_icon->enabled = false; stats.Coins_label->enabled = false; stats.Coins_icon->enabled = false; menu.Image->enabled = false; menu.Menu_button->enabled = false; menu.Return_button->enabled = false; menu.Title->enabled = false; menu.Resume_button->enabled = false; menu.Exit_button->enabled = false; menu.Save->enabled = false; menu.Load->enabled = false; console.Image->enabled = false; console.Input->enabled = false; } void j1Scene::Open_InGame_UI() { stats.Timer_label->enabled = true; stats.Timer_icon->enabled = true; stats.Lifes_label->enabled = true; stats.Lifes_icon->enabled = true; stats.Coins_label->enabled = true; stats.Coins_icon->enabled = true; menu.Menu_button->enabled = true; }
28.976623
179
0.654087
[ "render" ]
6e1a3ba2fd9f698891794124b50011c1f59bf660
472
cpp
C++
LeetCode/C++/744. Find Smallest Letter Greater Than Target.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/744. Find Smallest Letter Greater Than Target.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/744. Find Smallest Letter Greater Than Target.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Runtime: 12 ms, faster than 93.52% of C++ online submissions for Find Smallest Letter Greater Than Target. //Memory Usage: 9 MB, less than 72.73% of C++ online submissions for Find Smallest Letter Greater Than Target. class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { for(char letter : letters){ if(letter > target){ return letter; } } return letters[0]; } };
31.466667
110
0.625
[ "vector" ]
6e1a7ee0765b61b4ddcdc7f32acb1eb967757bcb
14,201
cc
C++
tensorflow_lite_support/java/src/native/task/audio/classifier/audio_classifier_jni.cc
milindthakur177/support
c669f0b5330daec3713600debe49fb27bda2cf81
[ "Apache-2.0" ]
1
2022-03-02T05:39:58.000Z
2022-03-02T05:39:58.000Z
tensorflow_lite_support/java/src/native/task/audio/classifier/audio_classifier_jni.cc
milindthakur177/support
c669f0b5330daec3713600debe49fb27bda2cf81
[ "Apache-2.0" ]
null
null
null
tensorflow_lite_support/java/src/native/task/audio/classifier/audio_classifier_jni.cc
milindthakur177/support
c669f0b5330daec3713600debe49fb27bda2cf81
[ "Apache-2.0" ]
2
2021-06-23T01:14:12.000Z
2021-06-28T15:12:49.000Z
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <jni.h> #include <memory> #include <string> #include "tensorflow_lite_support/cc/port/statusor.h" #include "tensorflow_lite_support/cc/task/audio/audio_classifier.h" #include "tensorflow_lite_support/cc/task/audio/core/audio_buffer.h" #include "tensorflow_lite_support/cc/task/audio/proto/audio_classifier_options.pb.h" #include "tensorflow_lite_support/cc/task/audio/proto/class_proto_inc.h" #include "tensorflow_lite_support/cc/task/audio/proto/classifications_proto_inc.h" #include "tensorflow_lite_support/cc/utils/jni_utils.h" namespace { using ::tflite::support::StatusOr; using ::tflite::support::utils::kAssertionError; using ::tflite::support::utils::kInvalidPointer; using ::tflite::support::utils::StringListToVector; using ::tflite::support::utils::ThrowException; using ::tflite::task::audio::AudioBuffer; using ::tflite::task::audio::AudioClassifier; using ::tflite::task::audio::AudioClassifierOptions; using ::tflite::task::audio::Class; using ::tflite::task::audio::ClassificationResult; // TODO(b/183343074): Share the code below with ImageClassifier. constexpr char kCategoryClassName[] = "org/tensorflow/lite/support/label/Category"; constexpr char kStringClassName[] = "Ljava/lang/String;"; constexpr char kEmptyString[] = ""; jobject ConvertToCategory(JNIEnv* env, const Class& classification) { // jclass and init of Category. jclass category_class = env->FindClass(kCategoryClassName); jmethodID category_create = env->GetStaticMethodID( category_class, "create", absl::StrCat("(", kStringClassName, kStringClassName, "FI)L", kCategoryClassName, ";") .c_str()); std::string label_string = classification.has_class_name() ? classification.class_name() : std::to_string(classification.index()); jstring label = env->NewStringUTF(label_string.c_str()); std::string display_name_string = classification.has_display_name() ? classification.display_name() : kEmptyString; jstring display_name = env->NewStringUTF(display_name_string.c_str()); jobject jcategory = env->CallStaticObjectMethod( category_class, category_create, label, display_name, classification.score(), classification.index()); env->DeleteLocalRef(category_class); env->DeleteLocalRef(label); env->DeleteLocalRef(display_name); return jcategory; } jobject ConvertToClassificationResults(JNIEnv* env, const ClassificationResult& results) { // jclass and init of Classifications. jclass classifications_class = env->FindClass( "org/tensorflow/lite/task/audio/classifier/Classifications"); jmethodID classifications_create = env->GetStaticMethodID( classifications_class, "create", "(Ljava/util/List;ILjava/lang/String;)Lorg/tensorflow/lite/" "task/audio/classifier/Classifications;"); // jclass, init, and add of ArrayList. jclass array_list_class = env->FindClass("java/util/ArrayList"); jmethodID array_list_init = env->GetMethodID(array_list_class, "<init>", "(I)V"); jmethodID array_list_add_method = env->GetMethodID(array_list_class, "add", "(Ljava/lang/Object;)Z"); jobject classifications_list = env->NewObject(array_list_class, array_list_init, static_cast<jint>(results.classifications_size())); for (int i = 0; i < results.classifications_size(); i++) { auto classifications = results.classifications(i); jobject jcategory_list = env->NewObject(array_list_class, array_list_init, classifications.classes_size()); for (const auto& classification : classifications.classes()) { jobject jcategory = ConvertToCategory(env, classification); env->CallBooleanMethod(jcategory_list, array_list_add_method, jcategory); env->DeleteLocalRef(jcategory); } std::string head_name_string = classifications.has_head_name() ? classifications.head_name() : std::to_string(classifications.head_index()); jstring head_name = env->NewStringUTF(head_name_string.c_str()); jobject jclassifications = env->CallStaticObjectMethod( classifications_class, classifications_create, jcategory_list, classifications.head_index(), head_name); env->CallBooleanMethod(classifications_list, array_list_add_method, jclassifications); env->DeleteLocalRef(head_name); env->DeleteLocalRef(jcategory_list); env->DeleteLocalRef(jclassifications); } return classifications_list; } // Creates an AudioClassifierOptions proto based on the Java class. AudioClassifierOptions ConvertToProtoOptions(JNIEnv* env, jobject java_options) { AudioClassifierOptions proto_options; jclass java_options_class = env->FindClass( "org/tensorflow/lite/task/audio/classifier/" "AudioClassifier$AudioClassifierOptions"); jmethodID display_names_locale_id = env->GetMethodID( java_options_class, "getDisplayNamesLocale", "()Ljava/lang/String;"); jstring display_names_locale = static_cast<jstring>( env->CallObjectMethod(java_options, display_names_locale_id)); const char* pchars = env->GetStringUTFChars(display_names_locale, nullptr); proto_options.set_display_names_locale(pchars); env->ReleaseStringUTFChars(display_names_locale, pchars); jmethodID max_results_id = env->GetMethodID(java_options_class, "getMaxResults", "()I"); jint max_results = env->CallIntMethod(java_options, max_results_id); proto_options.set_max_results(max_results); jmethodID is_score_threshold_set_id = env->GetMethodID(java_options_class, "getIsScoreThresholdSet", "()Z"); jboolean is_score_threshold_set = env->CallBooleanMethod(java_options, is_score_threshold_set_id); if (is_score_threshold_set) { jmethodID score_threshold_id = env->GetMethodID(java_options_class, "getScoreThreshold", "()F"); jfloat score_threshold = env->CallFloatMethod(java_options, score_threshold_id); proto_options.set_score_threshold(score_threshold); } jmethodID allow_list_id = env->GetMethodID( java_options_class, "getLabelAllowList", "()Ljava/util/List;"); jobject allow_list = env->CallObjectMethod(java_options, allow_list_id); auto allow_list_vector = StringListToVector(env, allow_list); for (const auto& class_name : allow_list_vector) { proto_options.add_class_name_allowlist(class_name); } jmethodID deny_list_id = env->GetMethodID( java_options_class, "getLabelDenyList", "()Ljava/util/List;"); jobject deny_list = env->CallObjectMethod(java_options, deny_list_id); auto deny_list_vector = StringListToVector(env, deny_list); for (const auto& class_name : deny_list_vector) { proto_options.add_class_name_denylist(class_name); } return proto_options; } jlong CreateAudioClassifierFromOptions(JNIEnv* env, const AudioClassifierOptions& options) { StatusOr<std::unique_ptr<AudioClassifier>> audio_classifier_or = AudioClassifier::CreateFromOptions(options); if (audio_classifier_or.ok()) { // Deletion is handled at deinitJni time. return reinterpret_cast<jlong>(audio_classifier_or->release()); } else { ThrowException(env, kAssertionError, "Error occurred when initializing AudioClassifier: %s", audio_classifier_or.status().message().data()); } return kInvalidPointer; } extern "C" JNIEXPORT void JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_deinitJni( JNIEnv* env, jobject thiz, jlong native_handle) { delete reinterpret_cast<AudioClassifier*>(native_handle); } // Creates an AudioClassifier instance from the model file descriptor. // file_descriptor_length and file_descriptor_offset are optional. Non-possitive // values will be ignored. extern "C" JNIEXPORT jlong JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_initJniWithModelFdAndOptions( JNIEnv* env, jclass thiz, jint file_descriptor, jlong file_descriptor_length, jlong file_descriptor_offset, jobject java_options) { AudioClassifierOptions proto_options = ConvertToProtoOptions(env, java_options); auto file_descriptor_meta = proto_options.mutable_base_options() ->mutable_model_file() ->mutable_file_descriptor_meta(); file_descriptor_meta->set_fd(file_descriptor); if (file_descriptor_length > 0) { file_descriptor_meta->set_length(file_descriptor_length); } if (file_descriptor_offset > 0) { file_descriptor_meta->set_offset(file_descriptor_offset); } return CreateAudioClassifierFromOptions(env, proto_options); } extern "C" JNIEXPORT jlong JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_initJniWithByteBuffer( JNIEnv* env, jclass thiz, jobject model_buffer, jobject java_options) { AudioClassifierOptions proto_options = ConvertToProtoOptions(env, java_options); // External proto generated header does not overload `set_file_content` with // string_view, therefore GetMappedFileBuffer does not apply here. // Creating a std::string will cause one extra copying of data. Thus, the // most efficient way here is to set file_content using char* and its size. proto_options.mutable_base_options()->mutable_model_file()->set_file_content( static_cast<char*>(env->GetDirectBufferAddress(model_buffer)), static_cast<size_t>(env->GetDirectBufferCapacity(model_buffer))); return CreateAudioClassifierFromOptions(env, proto_options); } // TODO(b/183343074): JNI method invocation is very expensive, taking about .2ms // each time. Consider retrieving the AudioFormat during initialization and // caching it in JAVA layer. extern "C" JNIEXPORT jlong JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_getRequiredSampleRateNative( JNIEnv* env, jclass thiz, jlong native_handle) { auto* classifier = reinterpret_cast<AudioClassifier*>(native_handle); StatusOr<AudioBuffer::AudioFormat> format_or = classifier->GetRequiredAudioFormat(); if (format_or.ok()) { return format_or->sample_rate; } else { ThrowException( env, kAssertionError, "Error occurred when getting sample rate from AudioClassifier: %s", format_or.status().message()); return kInvalidPointer; } } extern "C" JNIEXPORT jlong JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_getRequiredChannelsNative( JNIEnv* env, jclass thiz, jlong native_handle) { auto* classifier = reinterpret_cast<AudioClassifier*>(native_handle); StatusOr<AudioBuffer::AudioFormat> format_or = classifier->GetRequiredAudioFormat(); if (format_or.ok()) { return format_or->channels; } else { ThrowException( env, kAssertionError, "Error occurred when gettng channels from AudioClassifier: %s", format_or.status().message()); return kInvalidPointer; } } extern "C" JNIEXPORT jlong JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_getRequiredInputBufferSizeNative( JNIEnv* env, jclass thiz, jlong native_handle) { auto* classifier = reinterpret_cast<AudioClassifier*>(native_handle); return classifier->GetRequiredInputBufferSize(); } extern "C" JNIEXPORT jobject JNICALL Java_org_tensorflow_lite_task_audio_classifier_AudioClassifier_classifyNative( JNIEnv* env, jclass thiz, jlong native_handle, jbyteArray java_array, jint channels, jint sample_rate) { // Get the primitive native array. Depending on the JAVA runtime, the returned // array might be a copy of the JAVA array (or not). jbyte* native_array = env->GetByteArrayElements(java_array, nullptr); if (native_array == nullptr) { ThrowException(env, kAssertionError, "Error occured when converting the java audio input array " "to native array."); return nullptr; } jobject classification_results = nullptr; // Prepare the AudioBuffer. AudioBuffer::AudioFormat format = {channels, sample_rate}; const int size_in_bytes = env->GetArrayLength(java_array); const int size_in_float = size_in_bytes / sizeof(float); const StatusOr<std::unique_ptr<AudioBuffer>> audio_buffer_or = AudioBuffer::Create(reinterpret_cast<float*>(native_array), size_in_float, format); if (audio_buffer_or.ok()) { // Actual classification auto* classifier = reinterpret_cast<AudioClassifier*>(native_handle); auto results_or = classifier->Classify(*(audio_buffer_or.value())); if (results_or.ok()) { classification_results = ConvertToClassificationResults(env, results_or.value()); } else { ThrowException(env, kAssertionError, "Error occurred when classifying the audio clip: %s", results_or.status().message().data()); } } else { ThrowException(env, kAssertionError, "Error occured when creating the AudioBuffer: %s", audio_buffer_or.status().message().data()); } // Mark native_array as no longer needed. // TODO(b/183343074): Wrap this in SimpleCleanUp. env->ReleaseByteArrayElements(java_array, native_array, /*mode=*/0); return classification_results; } } // namespace
43.164134
96
0.729808
[ "object", "model" ]
6e279f95aded6a50dd393ef30ec8fbf1e6de9c15
4,238
cpp
C++
samples/sum/main.cpp
denverdino/eEVM
233d0583dcefb4b4c90e6b351f813a4e9d697ba5
[ "MIT" ]
null
null
null
samples/sum/main.cpp
denverdino/eEVM
233d0583dcefb4b4c90e6b351f813a4e9d697ba5
[ "MIT" ]
null
null
null
samples/sum/main.cpp
denverdino/eEVM
233d0583dcefb4b4c90e6b351f813a4e9d697ba5
[ "MIT" ]
1
2018-11-03T08:31:12.000Z
2018-11-03T08:31:12.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "evm/simpleglobalstate.h" #include "include/opcode.h" #include "include/processor.h" #include <iostream> int usage(const char* bin_name) { std::cout << "Usage: " << bin_name << " [-v] hex_a hex_b" << std::endl; std::cout << "Prints sum of arguments (hex string representation of 256-bit " "uints)" << std::endl; return 1; } void push_uint256(std::vector<uint8_t>& code, const uint256_t& n) { // Append opcode code.push_back(evm::Opcode::PUSH32); // Resize code array const size_t pre_size = code.size(); code.resize(pre_size + 32); // Serialize number into code array to_big_endian(n, code.begin() + pre_size); } std::vector<uint8_t> create_a_plus_b_bytecode( const uint256_t& a, const uint256_t& b) { std::vector<uint8_t> code; constexpr uint8_t mdest = 0x0; //< Memory start address for result constexpr uint8_t rsize = 0x20; //< Size of result // Push args and ADD push_uint256(code, a); push_uint256(code, b); code.push_back(evm::Opcode::ADD); // Store result code.push_back(evm::Opcode::PUSH1); code.push_back(mdest); code.push_back(evm::Opcode::MSTORE); // Return code.push_back(evm::Opcode::PUSH1); code.push_back(rsize); code.push_back(evm::Opcode::PUSH1); code.push_back(mdest); code.push_back(evm::Opcode::RETURN); return code; } int main(int argc, char** argv) { // Validate args, read verbose option bool verbose = false; size_t first_arg = 1; if (argc < 3 || argc > 4) { return usage(argv[0]); } if (argc == 4) { if (strcmp(argv[1], "-v") != 0) { return usage(argv[0]); } verbose = true; first_arg = 2; } srand(time(nullptr)); // Parse args const uint256_t arg_a = from_hex_str(argv[first_arg]); const uint256_t arg_b = from_hex_str(argv[first_arg + 1]); if (verbose) { std::cout << "Calculating " << to_hex_str(arg_a) << " + " << to_hex_str(arg_b) << std::endl; } // Invent a random address to use as sender std::vector<uint8_t> raw_address(160); std::generate( raw_address.begin(), raw_address.end(), []() { return rand(); }); const evm::Address sender = from_big_endian(raw_address.begin(), raw_address.end()); // Generate a target address for the summing contract (this COULD be random, // but here we use the scheme for Contract Creation specified in the Yellow // Paper) const evm::Address to = evm::generate_address(sender, 0); // Create summing bytecode const evm::Code code = create_a_plus_b_bytecode(arg_a, arg_b); // Construct global state evm::SimpleGlobalState gs; // Populate the global state with the constructed contract const evm::AccountState contract = gs.create(to, 0, code); if (verbose) { std::cout << "Address " << to_hex_str(to) << " contains the following bytecode:" << std::endl; std::cout << evm::to_hex_string(contract.acc.code) << std::endl; } // Construct a transaction object evm::NullLogHandler ignore; //< Ignore any logs produced by this transaction evm::Transaction tx(sender, ignore); // Construct processor evm::Processor p(gs); if (verbose) { std::cout << "Executing a transaction from " << to_hex_str(sender) << " to " << to_hex_str(to) << std::endl; } // Run transaction evm::Trace tr; const evm::ExecResult e = p.run( tx, sender, contract, {}, //< No input - the arguments are hard-coded in the contract 0, //< No gas value &tr //< Record execution trace ); if (e.er != evm::ExitReason::returned) { std::cout << "Unexpected return code" << std::endl; return 2; } if (verbose) { std::cout << "Execution completed, and returned a result of " << e.output.size() << " bytes" << std::endl; } const uint256_t result = from_big_endian(e.output.begin(), e.output.end()); std::cout << to_hex_str(arg_a); std::cout << " + "; std::cout << to_hex_str(arg_b); std::cout << " = "; std::cout << to_hex_str(result); std::cout << std::endl; if (verbose) { std::cout << "Done" << std::endl; } return 0; }
24.639535
80
0.635677
[ "object", "vector" ]
6e3336bfcfd44488d6473156b8b3bb285922fbee
2,467
cpp
C++
src/vm/BitcoinVM.cpp
vimrull/vimrull
31e44c7aa3f195b3ef3639cc451bd1ecb4bbff71
[ "MIT" ]
null
null
null
src/vm/BitcoinVM.cpp
vimrull/vimrull
31e44c7aa3f195b3ef3639cc451bd1ecb4bbff71
[ "MIT" ]
1
2021-06-14T22:35:17.000Z
2021-06-14T22:35:17.000Z
src/vm/BitcoinVM.cpp
vimrull/vimrull
31e44c7aa3f195b3ef3639cc451bd1ecb4bbff71
[ "MIT" ]
null
null
null
#include <load.h> #include <crypto/util.h> #include "BitcoinVM.h" #include "opcodes.h" bool BitcoinVM::execute(std::vector<unsigned char> op_codes) { uint64_t pc=0; while(pc<op_codes.size()) { //TODO: do actual things - just not pretend to do it switch(op_codes[pc]) { case opcode::OP_DUP: { ENSURE_IS_VALID(stack_.size() > 0); auto v = stack_.top(); stack_.push(v); pc++; } break; case opcode::OP_HASH160: { // its 2:29 am and lets cheat for now variable v; v.type_ = value_type::STRING; v.str = "hello"; //TODO: generate stack_.push(v); assert(stack_.size() == 4); pc++; } break; case opcode::OP_EQUALVERIFY: { auto v1 = stack_.top(); stack_.pop(); auto v2 = stack_.top(); stack_.pop(); ENSURE_IS_VALID(v1 == v2); pc++; } break; case opcode::OP_CHECKSIG: { auto v0 = stack_.top(); stack_.pop(); auto v1 = stack_.top(); stack_.pop(); auto v2 = stack_.top(); stack_.pop(); auto valid = valid_signature(v1.data, v2.data, v0.data); variable v; v.type_ = value_type::BOOLEAN; v.value_.bval = valid; stack_.push(v); pc++; } break; default: if (op_codes[pc] >=1 && op_codes[pc] <= 75) { uint8_t data_len = op_codes[pc]; variable v; v.type_ = value_type::DATA; v.data = std::vector<unsigned char>(&op_codes[pc+1], &op_codes[pc+1+data_len]); stack_.push(v); pc++; pc+=data_len; } else { return false; } } } if(stack_.size() != 1) { return false; } auto v = stack_.top(); if(v.type_ == value_type::BOOLEAN) { return v.value_.bval; } return true; }
26.815217
99
0.393595
[ "vector" ]
6e3973ab639518fb0168a8ab66b0d937f441f274
2,872
cpp
C++
Modules/ACCoRD/src/DensityGridMovingPolysEst.cpp
5nefarious/icarous
bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8
[ "Unlicense" ]
null
null
null
Modules/ACCoRD/src/DensityGridMovingPolysEst.cpp
5nefarious/icarous
bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8
[ "Unlicense" ]
null
null
null
Modules/ACCoRD/src/DensityGridMovingPolysEst.cpp
5nefarious/icarous
bfd759d88a47d9ee079fe35deaa6cf6d4459dcd8
[ "Unlicense" ]
null
null
null
/* * Copyright (c) 2016-2017 United States Government as represented by * the National Aeronautics and Space Administration. No copyright * is claimed in the United States under Title 17, U.S.Code. All Other * Rights Reserved. */ #include "DensityGridMovingPolysEst.h" #include <string> #include <map> #include <set> #include <vector> #include <limits> #include "Plan.h" #include "Position.h" #include "PolyPath.h" #include "BoundingRectangle.h" #include "DensityGrid.h" #include "Triple.h" #include "NavPoint.h" #include <limits> #include <vector> namespace larcfm { DensityGridMovingPolysEst::DensityGridMovingPolysEst(const Plan& p, int buffer, double squareSize, double gs_, const std::vector<PolyPath>& ps, const std::vector<PolyPath>& containment) : DensityGridTimed(p, buffer, squareSize) { for (int i = 0; i < (int) ps.size(); i++) { Triple<Plan,double,double> pp = ps[i].buildPlan(); plans.push_back(pp); } if (containment.size() > 0) { for (int i = 0; i < (int) containment.size(); i++) { // static plans have already been handled in StratwayCore with a call to setWeightsWithin() if (!containment[i].isStatic()) { Triple<Plan,double,double> cc = containment[i].buildPlan(); contains.push_back(cc); } } } startTime_ = p.getFirstTime(); gs = gs_; } double DensityGridMovingPolysEst::getWeightT(int x, int y, double t) const { if (lookaheadEndTime > 0 && t > lookaheadEndTime) { return 0.0; } std::pair<int,int> xy = std::pair<int,int>(x,y); if (weights.find(xy) == weights.end()) { return std::numeric_limits<double>::infinity(); } double w = weights.find(xy)->second; double cost = 0; Position cent = center(x,y); // disallow anything within one of the weather cells for (int i = 0; i < (int) plans.size(); i++) { if (t >= plans[i].first.getFirstTime() && t <= plans[i].first.getLastTime()) { Position p = plans[i].first.position(t); double D = plans[i].second; double centdist = cent.distanceH(p); if (centdist <= D) { cost = std::numeric_limits<double>::infinity(); break; } } } // disallow anything outside of one of the contains bool within = (contains.size() == 0); for (int i = 0; i < (int) contains.size(); i++) { if (t >= contains[i].first.getFirstTime() && t <= contains[i].first.getLastTime()) { Position p = contains[i].first.position(t); double D = contains[i].second; double centdist = cent.distanceH(p); if (centdist <= D) { within = true; break; } } } if (!within) { cost = std::numeric_limits<double>::infinity(); } return w + cost; } double DensityGridMovingPolysEst::getWeightT(const std::pair<int,int>& xy, double t) const { return getWeightT(xy.first,xy.second,t); } double DensityGridMovingPolysEst::getWeightT(const Triple<int,int,int>& pii) const { return getWeightT(pii.first,pii.second, pii.third); } }
27.615385
187
0.672354
[ "vector" ]
6e3be6a347a1a6af9e1c9e1d36aecd32ec91843d
1,274
hpp
C++
engine/Material.hpp
shenchi/gllab
5d8fe33cd763d5fe5033da106b715751ae2e87ef
[ "MIT" ]
null
null
null
engine/Material.hpp
shenchi/gllab
5d8fe33cd763d5fe5033da106b715751ae2e87ef
[ "MIT" ]
null
null
null
engine/Material.hpp
shenchi/gllab
5d8fe33cd763d5fe5033da106b715751ae2e87ef
[ "MIT" ]
null
null
null
#ifndef MATERIAL_HPP #define MATERIAL_HPP #include "core/common.hpp" #include "core/Program.hpp" #include "core/Texture.hpp" #include "core/UniformBuffer.hpp" #include <unordered_map> #include <string> #include <vector> #include <glm/glm.hpp> class Material { Material(const Material& ) {} Material(Program *program): m_program(program) {} public: static Material* CreateMaterial(Program *program = 0); bool setUniform(const std::string& name, int size, const void* data); bool setUniform(const std::string& name, GLint data); bool setUniform(const std::string& name, float data); bool setUniform(const std::string& name, const glm::vec4& data); bool setUniform(const std::string& name, const glm::vec3& data); bool setUniform(const std::string& name, const glm::mat4& data); // etc.. // void setUniformBlock(const std::string& name, int size, const void* data); bool setTexture(const std::string& name, Texture *texture); const Program * getProgram() const { return m_program; } void bind(); private: Program *m_program; std::unordered_map<std::string, size_t > m_texNames; // std::unordered_map<std::string, std::pair<size_t, GLuint> > m_ubNames; std::vector<Texture*> m_textures; std::vector<UniformBuffer*> m_uniformBuffers; }; #endif
24.980392
78
0.728414
[ "vector" ]
6e3dd6b9f4de8f9433b5e58227a1c30621c0c986
3,636
cpp
C++
src/Core/src/GameObject.cpp
Megaxela/HGEngineReloaded
62d319308c2d8a62f6854721c31afc4981aa13df
[ "MIT" ]
2
2021-02-26T05:25:48.000Z
2021-09-16T22:30:41.000Z
src/Core/src/GameObject.cpp
Megaxela/HGEngineReloaded
62d319308c2d8a62f6854721c31afc4981aa13df
[ "MIT" ]
1
2019-10-19T10:36:43.000Z
2019-10-19T10:36:43.000Z
src/Core/src/GameObject.cpp
Megaxela/HGEngineReloaded
62d319308c2d8a62f6854721c31afc4981aa13df
[ "MIT" ]
2
2019-10-22T18:56:59.000Z
2020-03-12T04:38:31.000Z
// HG::Core #include <HG/Core/Behaviour.hpp> #include <HG/Core/BuildProperties.hpp> #include <HG/Core/GameObject.hpp> #include <HG/Core/Scene.hpp> #include <HG/Core/Transform.hpp> // HG::Rendering::Base #include <HG/Rendering/Base/RenderBehaviour.hpp> // HG::Utils #include <HG/Utils/Logging.hpp> #include <HG/Utils/SystemTools.hpp> namespace HG::Core { GameObject::GameObject() : m_behaviours(), m_transform(new (m_cache) Transform(this)), m_parentScene(nullptr), m_enabled(true), m_hidden(false) { } GameObject::~GameObject() { m_parentScene = nullptr; m_transform->setParent(nullptr); // Merge, to prevent double free m_behaviours.merge(); // Removing behaviours for (auto& m_behaviour : m_behaviours) { delete m_behaviour; } m_behaviours.clear(); // Merge, to prevent double free m_renderBehaviours.merge(); for (auto& m_renderBehaviour : m_renderBehaviours) { delete m_renderBehaviour; } m_renderBehaviours.clear(); delete m_transform; } void GameObject::update() { // Merging rendering behaviours m_renderBehaviours.merge(); auto newBehaviours = m_behaviours.added(); // Removing behaviours for (auto&& behaviour : m_behaviours.removable()) { delete behaviour; } // Merging m_behaviours.merge(); // Executing start on new behaviours for (auto&& iter : newBehaviours) { iter->start(); } // Executing update on existing behaviours for (auto&& iter : m_behaviours) { // Will this behaviour removed on // next frame. If yes - behaviour // will be skipped, because it can // be already deleted. So on the next frame // this behaviour will be removed from container. // If behaviour is disabled, it shouldn't be updated. if (m_behaviours.isRemoving(iter) || !iter->isEnabled()) { continue; } iter->update(); } } void GameObject::removeBehaviour(Behaviour* behaviour) { if constexpr (BuildProperties::isDebug()) { if (behaviour->gameObject() != this) { HGError("Trying to remove behaviour from GameObject, that's not it's parent."); return; } } // Remove this gameobject as parent behaviour->setParentGameObject(nullptr); m_behaviours.remove(behaviour); } Scene* GameObject::scene() const { return m_parentScene; } void GameObject::setParentScene(Scene* parent) { m_parentScene = parent; } void GameObject::addBehaviour(Behaviour* behaviour) { behaviour->setParentGameObject(this); switch (behaviour->type()) { case Behaviour::Type::Logic: { m_behaviours.add(behaviour); break; } case Behaviour::Type::Render: { auto casted = dynamic_cast<HG::Rendering::Base::RenderBehaviour*>(behaviour); if (!casted) { HGError("Can't add behaviour of type {}", HG::Utils::SystemTools::getTypeName(behaviour)); return; } m_renderBehaviours.add(casted); break; } } } void GameObject::setName(std::string name) { m_name = std::move(name); } std::string GameObject::name() const { return m_name; } Transform* GameObject::transform() { return m_transform; } bool GameObject::isEnabled() const { return m_enabled; } void GameObject::setEnabled(bool value) { m_enabled = value; } bool GameObject::isHidden() const { return m_hidden; } void GameObject::setHidden(bool value) { m_hidden = value; } } // namespace HG::Core
19.978022
102
0.635864
[ "render", "transform" ]
6e4b3e51bba4e7f5d603f17ee95ef6d19a327815
2,279
cpp
C++
src/OrbitGl/CaptureViewElementTest.cpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
1,847
2020-03-24T19:01:42.000Z
2022-03-31T13:18:57.000Z
src/OrbitGl/CaptureViewElementTest.cpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
1,100
2020-03-24T19:41:13.000Z
2022-03-31T14:27:09.000Z
src/OrbitGl/CaptureViewElementTest.cpp
tufeigunchu/orbit
407354cf7c9159ff7e3177c603a6850b95509e3a
[ "BSD-2-Clause" ]
228
2020-03-25T05:32:08.000Z
2022-03-31T11:27:39.000Z
// Copyright (c) 2021 The Orbit 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 <gtest/gtest.h> #include "CaptureViewElementTester.h" namespace orbit_gl { class UnitTestCaptureViewLeafElement : public CaptureViewElement { public: explicit UnitTestCaptureViewLeafElement(CaptureViewElement* parent, Viewport* viewport, TimeGraphLayout* layout) : CaptureViewElement(parent, viewport, layout) {} [[nodiscard]] float GetHeight() const override { return 10; } private: [[nodiscard]] std::unique_ptr<orbit_accessibility::AccessibleInterface> CreateAccessibleInterface() override { return nullptr; } }; class UnitTestCaptureViewContainerElement : public CaptureViewElement { public: explicit UnitTestCaptureViewContainerElement(CaptureViewElement* parent, Viewport* viewport, TimeGraphLayout* layout, int children_to_create = 0) : CaptureViewElement(parent, viewport, layout) { for (int i = 0; i < children_to_create; ++i) { children_.emplace_back( std::make_unique<UnitTestCaptureViewLeafElement>(this, viewport, layout)); } } [[nodiscard]] float GetHeight() const override { float result = 0; for (auto& child : GetAllChildren()) { result += child->GetHeight(); } return result; } [[nodiscard]] std::vector<CaptureViewElement*> GetAllChildren() const override { std::vector<CaptureViewElement*> result; for (auto& child : children_) { result.push_back(child.get()); } return result; }; private: std::vector<std::unique_ptr<UnitTestCaptureViewLeafElement>> children_; [[nodiscard]] std::unique_ptr<orbit_accessibility::AccessibleInterface> CreateAccessibleInterface() override { return nullptr; } }; TEST(CaptureViewElementTesterTest, PassesAllTestsOnExistingElement) { const int kChildCount = 2; CaptureViewElementTester tester; UnitTestCaptureViewContainerElement container_elem(nullptr, tester.GetViewport(), tester.GetLayout(), kChildCount); tester.RunTests(&container_elem); } } // namespace orbit_gl
33.028986
99
0.694603
[ "vector" ]
6e4c1b564bd95ac80b42af546fcab6d791b01270
73,920
cpp
C++
Implicit-Lagrange/FEA_Physics_Modules/FEA_Module_Inertial.cpp
Adrian-Diaz/Fierro
0f33803e3232d39e0db51ac656feffe809126988
[ "BSD-3-Clause" ]
null
null
null
Implicit-Lagrange/FEA_Physics_Modules/FEA_Module_Inertial.cpp
Adrian-Diaz/Fierro
0f33803e3232d39e0db51ac656feffe809126988
[ "BSD-3-Clause" ]
null
null
null
Implicit-Lagrange/FEA_Physics_Modules/FEA_Module_Inertial.cpp
Adrian-Diaz/Fierro
0f33803e3232d39e0db51ac656feffe809126988
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <math.h> // fmin, fmax, abs note: fminl is long #include <sys/stat.h> #include <mpi.h> #include <Teuchos_ScalarTraits.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_oblackholestream.hpp> #include <Teuchos_Tuple.hpp> #include <Teuchos_VerboseObject.hpp> #include <Teuchos_SerialDenseMatrix.hpp> #include <Teuchos_SerialDenseVector.hpp> #include <Teuchos_SerialDenseSolver.hpp> #include <Tpetra_Core.hpp> #include <Tpetra_Map.hpp> #include <Tpetra_MultiVector.hpp> #include <Tpetra_CrsMatrix.hpp> #include <Kokkos_View.hpp> #include <Kokkos_Parallel.hpp> #include <Kokkos_Parallel_Reduce.hpp> #include "Tpetra_Details_makeColMap.hpp" #include "Tpetra_Details_DefaultTypes.hpp" #include "Tpetra_Details_FixedHashTable.hpp" #include "Tpetra_Import.hpp" #include "elements.h" #include "matar.h" #include "utilities.h" #include "FEA_Module_Inertial.h" #include "Simulation_Parameters_Inertial.h" #include "Implicit_Solver.h" #define MAX_ELEM_NODES 8 #define DENSITY_EPSILON 0.0001 using namespace utils; FEA_Module_Inertial::FEA_Module_Inertial(Implicit_Solver *Solver_Pointer) :FEA_Module(Solver_Pointer){ //create parameter object simparam = new Simulation_Parameters_Inertial(); // ---- Read input file, define state and boundary conditions ---- // simparam->input(); //sets base class simparam pointer to avoid instancing the base simparam twice FEA_Module::simparam = simparam; //property initialization flags mass_init = false; com_init[0] = com_init[1] = com_init[2] = false; //property update counters mass_update = com_update[0] = com_update[1] = com_update[2] = -1; //RCP initialization mass_gradients_distributed = Teuchos::null; center_of_mass_gradients_distributed = Teuchos::null; //construct per element inertial property vectors Global_Element_Masses = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Volumes = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_x = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_y = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_z = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_of_Inertia_xx = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_of_Inertia_yy = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_of_Inertia_zz = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_of_Inertia_xy = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_of_Inertia_xz = Teuchos::rcp(new MV(element_map, 1)); Global_Element_Moments_of_Inertia_yz = Teuchos::rcp(new MV(element_map, 1)); } FEA_Module_Inertial::~FEA_Module_Inertial(){} /* ---------------------------------------------------------------------- Compute the mass of each element; estimated with quadrature ------------------------------------------------------------------------- */ void FEA_Module_Inertial::compute_element_masses(const_host_vec_array design_densities, bool max_flag){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //initialize memory for volume storage host_vec_array Element_Masses = Global_Element_Masses->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(!nodal_density_flag) compute_element_volumes(); const_host_vec_array Element_Volumes = Global_Element_Volumes->getLocalView<HostSpace>(Tpetra::Access::ReadOnly); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_vec_array all_design_densities; //bool nodal_density_flag = simparam->nodal_density_flag; if(nodal_density_flag) all_design_densities = all_node_densities_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int num_dim = simparam->num_dim; int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t Jacobian, current_density, weight_multiply; //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_density(elem->num_basis()); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int nonoverlapping_ielem = 0; nonoverlapping_ielem < nonoverlap_nelements; nonoverlapping_ielem++){ global_element_index = element_map->getGlobalElement(nonoverlapping_ielem); ielem = all_element_map->getLocalElement(global_element_index); if(nodal_density_flag){ //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); if(nodal_density_flag) nodal_density(node_loop) = all_design_densities(local_node_id,0); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< nodes_in_elem(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " //<< nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) << " " << nodal_density(node_loop) <<std::endl; } //debug print of index //std::cout << "nonoverlap element id on TASK " << myrank << " is " << nonoverlapping_ielem << std::endl; //std::fflush(stdout); //initialize element mass Element_Masses(nonoverlapping_ielem,0) = 0; if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; //compute density current_density = 0; if(max_flag){ current_density = 1; } else{ for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_density += nodal_density(node_loop)*basis_values(node_loop); } } Element_Masses(nonoverlapping_ielem,0) += current_density*weight_multiply*Jacobian; } } else{ Element_Masses(nonoverlapping_ielem,0) = Element_Volumes(nonoverlapping_ielem,0)*design_densities(nonoverlapping_ielem,0); } } //std::ostream &out = std::cout; //Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::fancyOStream(Teuchos::rcpFromRef(out)); //if(myrank==0) //*fos << "Global Element Masses:" << std::endl; //Global_Element_Masses->describe(*fos,Teuchos::VERB_EXTREME); //*fos << std::endl; } /* ---------------------------------------------------------------------- Compute the gradients of mass function with respect to nodal densities ------------------------------------------------------------------------- */ void FEA_Module_Inertial::compute_nodal_gradients(const_host_vec_array design_variables, host_vec_array design_gradients){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int num_dim = simparam->num_dim; const_host_vec_array all_node_densities; //bool nodal_density_flag = simparam->nodal_density_flag; if(nodal_density_flag) all_node_densities = all_node_densities_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t Jacobian, weight_multiply; //CArrayKokkos<real_t> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_density(elem->num_basis()); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //initialize design gradients to 0 for(int init = 0; init < nlocal_nodes; init++) design_gradients(init,0) = 0; //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int ielem = 0; ielem < rnum_elem; ielem++){ //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); if(nodal_density_flag) nodal_density(node_loop) = all_node_densities(local_node_id,0); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< nodes_in_elem(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " << nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) <<std::endl; } if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; //assign contribution to every local node this element has for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ if(map->isNodeGlobalElement(nodes_in_elem(ielem, node_loop))){ local_node_id = map->getLocalElement(nodes_in_elem(ielem, node_loop)); design_gradients(local_node_id,0)+=weight_multiply*basis_values(node_loop)*Jacobian; } } } } } /* ------------------------------------------------------------------------------------------------------------------------ Compute the moment of inertia of each element for a specified component of the inertia tensor; estimated with quadrature --------------------------------------------------------------------------------------------------------------------------- */ void FEA_Module_Inertial::compute_element_moments(const_host_vec_array design_densities, bool max_flag, int moment_component){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //initialize memory for volume storage host_vec_array Element_Masses = Global_Element_Masses->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); host_vec_array Element_Moments; if(moment_component==0) Element_Moments = Global_Element_Moments_x->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(moment_component==1) Element_Moments = Global_Element_Moments_y->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(moment_component==2) Element_Moments = Global_Element_Moments_z->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); const_host_vec_array Element_Volumes = Global_Element_Volumes->getLocalView<HostSpace>(Tpetra::Access::ReadOnly); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_vec_array all_design_densities; //bool nodal_density_flag = simparam->nodal_density_flag; if(nodal_density_flag) all_design_densities = all_node_densities_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int num_dim = simparam->num_dim; int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t Jacobian, current_density, weight_multiply; //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_density(elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> current_position(num_dim); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int nonoverlapping_ielem = 0; nonoverlapping_ielem < nonoverlap_nelements; nonoverlapping_ielem++){ global_element_index = element_map->getGlobalElement(nonoverlapping_ielem); ielem = all_element_map->getLocalElement(global_element_index); //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); if(nodal_density_flag) nodal_density(node_loop) = all_design_densities(local_node_id,0); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< nodes_in_elem(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " //<< nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) << " " << nodal_density(node_loop) <<std::endl; } //debug print of index //std::cout << "nonoverlap element id on TASK " << myrank << " is " << nonoverlapping_ielem << std::endl; //std::fflush(stdout); //initialize element mass Element_Moments(nonoverlapping_ielem,0) = 0; if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; //compute density if(max_flag){ current_density = 1; } else{ if(nodal_density_flag){ current_density = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_density += nodal_density(node_loop)*basis_values(node_loop); } }// if else{ current_density = design_densities(nonoverlapping_ielem,0); } } //compute current position current_position(0) = current_position(1) = current_position(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_position(moment_component) += nodal_positions(node_loop,moment_component)*basis_values(node_loop); } Element_Moments(nonoverlapping_ielem,0) += current_density*current_position(moment_component)*weight_multiply*Jacobian; } } //std::ostream &out = std::cout; //Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::fancyOStream(Teuchos::rcpFromRef(out)); //if(myrank==0) //*fos << "Global Element Masses:" << std::endl; //Global_Element_Masses->describe(*fos,Teuchos::VERB_EXTREME); //*fos << std::endl; } /* --------------------------------------------------------------------------------------------------- Compute the gradients of the specified moment of inertia component with respect to design densities ------------------------------------------------------------------------------------------------------ */ void FEA_Module_Inertial::compute_moment_gradients(const_host_vec_array design_variables, host_vec_array design_gradients, int moment_component){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int num_dim = simparam->num_dim; const_host_vec_array all_node_densities; //bool nodal_density_flag = simparam->nodal_density_flag; if(nodal_density_flag) all_node_densities = all_node_densities_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t Jacobian, weight_multiply; //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_density(elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> current_position(num_dim); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //initialize design gradients to 0 for(int init = 0; init < nlocal_nodes; init++) design_gradients(init,moment_component) = 0; //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int ielem = 0; ielem < rnum_elem; ielem++){ //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); if(nodal_density_flag) nodal_density(node_loop) = all_node_densities(local_node_id,0); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< nodes_in_elem(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " << nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) <<std::endl; } if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; //compute current position current_position(0) = current_position(1) = current_position(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_position(moment_component) += nodal_positions(node_loop,moment_component)*basis_values(node_loop); } //assign contribution to every local node this element has for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ if(map->isNodeGlobalElement(nodes_in_elem(ielem, node_loop))){ local_node_id = map->getLocalElement(nodes_in_elem(ielem, node_loop)); design_gradients(local_node_id,moment_component)+=weight_multiply*basis_values(node_loop)*current_position(moment_component)*Jacobian; } } } } } /* ------------------------------------------------------------------------------------------------------------------------ Compute the moment of inertia of each element for a specified component of the inertia tensor; estimated with quadrature --------------------------------------------------------------------------------------------------------------------------- */ void FEA_Module_Inertial::compute_element_moments_of_inertia(const_host_vec_array design_densities, bool max_flag, int inertia_component){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //initialize memory for volume storage host_vec_array Element_Masses = Global_Element_Masses->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); host_vec_array Element_Moments_of_Inertia; if(inertia_component==0) Element_Moments_of_Inertia = Global_Element_Moments_of_Inertia_xx->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(inertia_component==1) Element_Moments_of_Inertia = Global_Element_Moments_of_Inertia_yy->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(inertia_component==2) Element_Moments_of_Inertia = Global_Element_Moments_of_Inertia_zz->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(inertia_component==3) Element_Moments_of_Inertia = Global_Element_Moments_of_Inertia_xy->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(inertia_component==4) Element_Moments_of_Inertia = Global_Element_Moments_of_Inertia_xz->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); if(inertia_component==5) Element_Moments_of_Inertia = Global_Element_Moments_of_Inertia_yz->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); const_host_vec_array Element_Volumes = Global_Element_Volumes->getLocalView<HostSpace>(Tpetra::Access::ReadOnly); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_vec_array all_design_densities; //bool nodal_density_flag = simparam->nodal_density_flag; if(nodal_density_flag) all_design_densities = all_node_densities_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int num_dim = simparam->num_dim; int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t delx1, delx2; real_t Jacobian, current_density, weight_multiply; //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_density(elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> current_position(num_dim); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int nonoverlapping_ielem = 0; nonoverlapping_ielem < nonoverlap_nelements; nonoverlapping_ielem++){ global_element_index = element_map->getGlobalElement(nonoverlapping_ielem); ielem = all_element_map->getLocalElement(global_element_index); //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); if(nodal_density_flag) nodal_density(node_loop) = all_design_densities(local_node_id,0); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< nodes_in_elem(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " //<< nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) << " " << nodal_density(node_loop) <<std::endl; } //debug print of index //std::cout << "nonoverlap element id on TASK " << myrank << " is " << nonoverlapping_ielem << std::endl; //std::fflush(stdout); //initialize element mass Element_Moments_of_Inertia(nonoverlapping_ielem,0) = 0; if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; //compute density if(max_flag){ current_density = 1; } else{ if(nodal_density_flag){ current_density = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_density += nodal_density(node_loop)*basis_values(node_loop); } }// if else{ current_density = design_densities(nonoverlapping_ielem,0); } } //compute current position current_position(0) = current_position(1) = current_position(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_position(0) += nodal_positions(node_loop,0)*basis_values(node_loop); current_position(1) += nodal_positions(node_loop,1)*basis_values(node_loop); current_position(2) += nodal_positions(node_loop,2)*basis_values(node_loop); } if(inertia_component==0){ delx1 = current_position(1) - center_of_mass[1]; delx2 = current_position(2) - center_of_mass[2]; Element_Moments_of_Inertia(nonoverlapping_ielem,0) += current_density*(delx1*delx1 + delx2*delx2)*weight_multiply*Jacobian; } if(inertia_component==1){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(2) - center_of_mass[2]; Element_Moments_of_Inertia(nonoverlapping_ielem,0) += current_density*(delx1*delx1 + delx2*delx2)*weight_multiply*Jacobian; } if(inertia_component==2){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(1) - center_of_mass[1]; Element_Moments_of_Inertia(nonoverlapping_ielem,0) += current_density*(delx1*delx1 + delx2*delx2)*weight_multiply*Jacobian; } if(inertia_component==3){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(1) - center_of_mass[1]; Element_Moments_of_Inertia(nonoverlapping_ielem,0) -= current_density*(delx1*delx2)*weight_multiply*Jacobian; } if(inertia_component==4){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(2) - center_of_mass[2]; Element_Moments_of_Inertia(nonoverlapping_ielem,0) -= current_density*(delx1*delx2)*weight_multiply*Jacobian; } if(inertia_component==5){ delx1 = current_position(1) - center_of_mass[1]; delx2 = current_position(2) - center_of_mass[2]; Element_Moments_of_Inertia(nonoverlapping_ielem,0) -= current_density*(delx1*delx2)*weight_multiply*Jacobian; } } } //std::ostream &out = std::cout; //Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::fancyOStream(Teuchos::rcpFromRef(out)); //if(myrank==0) //*fos << "Global Element Masses:" << std::endl; //Global_Element_Masses->describe(*fos,Teuchos::VERB_EXTREME); //*fos << std::endl; } /* --------------------------------------------------------------------------------------------------- Compute the gradients of the specified moment of inertia component with respect to design densities ------------------------------------------------------------------------------------------------------ */ void FEA_Module_Inertial::compute_moment_of_inertia_gradients(const_host_vec_array design_variables, host_vec_array design_gradients, int inertia_component){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int num_dim = simparam->num_dim; const_host_vec_array all_node_densities; //bool nodal_density_flag = simparam->nodal_density_flag; if(nodal_density_flag) all_node_densities = all_node_densities_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t delx1, delx2; real_t Jacobian, weight_multiply; //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_density(elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> current_position(num_dim); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //initialize design gradients to 0 for(int init = 0; init < nlocal_nodes; init++) design_gradients(init,0) = 0; //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int ielem = 0; ielem < rnum_elem; ielem++){ //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); if(nodal_density_flag) nodal_density(node_loop) = all_node_densities(local_node_id,0); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< nodes_in_elem(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " << nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) <<std::endl; } if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; //compute current position current_position(0) = current_position(1) = current_position(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ current_position(0) += nodal_positions(node_loop,0)*basis_values(node_loop); current_position(1) += nodal_positions(node_loop,1)*basis_values(node_loop); current_position(2) += nodal_positions(node_loop,2)*basis_values(node_loop); } //assign contribution to every local node this element has for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ if(map->isNodeGlobalElement(nodes_in_elem(ielem, node_loop))){ local_node_id = map->getLocalElement(nodes_in_elem(ielem, node_loop)); if(inertia_component==0){ delx1 = current_position(1) - center_of_mass[1]; delx2 = current_position(2) - center_of_mass[2]; design_gradients(local_node_id,0)+=weight_multiply*basis_values(node_loop)*(delx1*delx1 + delx2*delx2)*Jacobian; } if(inertia_component==1){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(2) - center_of_mass[2]; design_gradients(local_node_id,0)+=weight_multiply*basis_values(node_loop)*(delx1*delx1 + delx2*delx2)*Jacobian; } if(inertia_component==2){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(1) - center_of_mass[1]; design_gradients(local_node_id,0)+=weight_multiply*basis_values(node_loop)*(delx1*delx1 + delx2*delx2)*Jacobian; } if(inertia_component==3){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(1) - center_of_mass[1]; design_gradients(local_node_id,0)-=weight_multiply*basis_values(node_loop)*(delx1*delx2)*Jacobian; } if(inertia_component==4){ delx1 = current_position(0) - center_of_mass[0]; delx2 = current_position(2) - center_of_mass[2]; design_gradients(local_node_id,0)-=weight_multiply*basis_values(node_loop)*(delx1*delx2)*Jacobian; } if(inertia_component==5){ delx1 = current_position(1) - center_of_mass[1]; delx2 = current_position(2) - center_of_mass[2]; design_gradients(local_node_id,0)-=weight_multiply*basis_values(node_loop)*(delx1*delx2)*Jacobian; } } } } } } /* ---------------------------------------------------------------------- Compute the volume of each element; estimated with quadrature ------------------------------------------------------------------------- */ void FEA_Module_Inertial::compute_element_volumes(){ //local number of uniquely assigned elements size_t nonoverlap_nelements = element_map->getNodeNumElements(); //local variable for host view in the dual view const_host_vec_array all_node_coords = all_node_coords_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); const_host_elem_conn_array nodes_in_elem = nodes_in_elem_distributed->getLocalView<HostSpace> (Tpetra::Access::ReadOnly); host_vec_array Element_Volumes = Global_Element_Volumes->getLocalView<HostSpace>(Tpetra::Access::ReadWrite); int num_dim = simparam->num_dim; int nodes_per_elem = elem->num_basis(); int num_gauss_points = simparam->num_gauss_points; int z_quad,y_quad,x_quad, direct_product_count; size_t local_node_id; LO ielem; GO global_element_index; real_t Jacobian, weight_multiply; //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_nodes_1D(num_gauss_points); //CArrayKokkos<real_t, array_layout, device_type, memory_traits> legendre_weights_1D(num_gauss_points); CArray<real_t> legendre_nodes_1D(num_gauss_points); CArray<real_t> legendre_weights_1D(num_gauss_points); real_t pointer_quad_coordinate[num_dim]; real_t pointer_quad_coordinate_weight[num_dim]; real_t pointer_interpolated_point[num_dim]; real_t pointer_JT_row1[num_dim]; real_t pointer_JT_row2[num_dim]; real_t pointer_JT_row3[num_dim]; ViewCArray<real_t> quad_coordinate(pointer_quad_coordinate,num_dim); ViewCArray<real_t> quad_coordinate_weight(pointer_quad_coordinate_weight,num_dim); ViewCArray<real_t> interpolated_point(pointer_interpolated_point,num_dim); ViewCArray<real_t> JT_row1(pointer_JT_row1,num_dim); ViewCArray<real_t> JT_row2(pointer_JT_row2,num_dim); ViewCArray<real_t> JT_row3(pointer_JT_row3,num_dim); real_t pointer_basis_values[elem->num_basis()]; real_t pointer_basis_derivative_s1[elem->num_basis()]; real_t pointer_basis_derivative_s2[elem->num_basis()]; real_t pointer_basis_derivative_s3[elem->num_basis()]; ViewCArray<real_t> basis_values(pointer_basis_values,elem->num_basis()); ViewCArray<real_t> basis_derivative_s1(pointer_basis_derivative_s1,elem->num_basis()); ViewCArray<real_t> basis_derivative_s2(pointer_basis_derivative_s2,elem->num_basis()); ViewCArray<real_t> basis_derivative_s3(pointer_basis_derivative_s3,elem->num_basis()); CArrayKokkos<real_t, array_layout, device_type, memory_traits> nodal_positions(elem->num_basis(),num_dim); //initialize weights elements::legendre_nodes_1D(legendre_nodes_1D,num_gauss_points); elements::legendre_weights_1D(legendre_weights_1D,num_gauss_points); //loop over elements and use quadrature rule to compute volume from Jacobian determinant for(int nonoverlapping_ielem = 0; nonoverlapping_ielem < nonoverlap_nelements; nonoverlapping_ielem++){ global_element_index = element_map->getGlobalElement(nonoverlapping_ielem); ielem = all_element_map->getLocalElement(global_element_index); //debug print //std::cout << "ELEMENT INDEX IS: " << ielem << " " <<global_element_index << std::endl; //acquire set of nodes for this local element for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ local_node_id = all_node_map->getLocalElement(nodes_in_elem(ielem, node_loop)); nodal_positions(node_loop,0) = all_node_coords(local_node_id,0); nodal_positions(node_loop,1) = all_node_coords(local_node_id,1); nodal_positions(node_loop,2) = all_node_coords(local_node_id,2); /* if(myrank==1&&nodal_positions(node_loop,2)>10000000){ std::cout << " LOCAL MATRIX DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 <<" " << local_node_id <<" "<< host_elem_conn_(ielem, node_loop) << " "<< nodal_positions(node_loop,2) << std::endl; std::fflush(stdout); } */ //std::cout << local_node_id << " " << nodes_in_elem(ielem, node_loop) << " " << nodal_positions(node_loop,0) << " " << nodal_positions(node_loop,1) << " "<< nodal_positions(node_loop,2) <<std::endl; } //initialize element volume Element_Volumes(nonoverlapping_ielem,0) = 0; if(Element_Types(ielem)==elements::elem_types::Hex8){ direct_product_count = std::pow(num_gauss_points,num_dim); } //loop over quadrature points for(int iquad=0; iquad < direct_product_count; iquad++){ //set current quadrature point if(num_dim==3) z_quad = iquad/(num_gauss_points*num_gauss_points); y_quad = (iquad % (num_gauss_points*num_gauss_points))/num_gauss_points; x_quad = iquad % num_gauss_points; quad_coordinate(0) = legendre_nodes_1D(x_quad); quad_coordinate(1) = legendre_nodes_1D(y_quad); if(num_dim==3) quad_coordinate(2) = legendre_nodes_1D(z_quad); //set current quadrature weight quad_coordinate_weight(0) = legendre_weights_1D(x_quad); quad_coordinate_weight(1) = legendre_weights_1D(y_quad); if(num_dim==3) quad_coordinate_weight(2) = legendre_weights_1D(z_quad); else quad_coordinate_weight(2) = 1; weight_multiply = quad_coordinate_weight(0)*quad_coordinate_weight(1)*quad_coordinate_weight(2); //compute shape functions at this point for the element type elem->basis(basis_values,quad_coordinate); //compute all the necessary coordinates and derivatives at this point //compute shape function derivatives elem->partial_xi_basis(basis_derivative_s1,quad_coordinate); elem->partial_eta_basis(basis_derivative_s2,quad_coordinate); elem->partial_mu_basis(basis_derivative_s3,quad_coordinate); //compute derivatives of x,y,z w.r.t the s,t,w isoparametric space needed by JT (Transpose of the Jacobian) //derivative of x,y,z w.r.t s JT_row1(0) = 0; JT_row1(1) = 0; JT_row1(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row1(0) += nodal_positions(node_loop,0)*basis_derivative_s1(node_loop); JT_row1(1) += nodal_positions(node_loop,1)*basis_derivative_s1(node_loop); JT_row1(2) += nodal_positions(node_loop,2)*basis_derivative_s1(node_loop); } //derivative of x,y,z w.r.t t JT_row2(0) = 0; JT_row2(1) = 0; JT_row2(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row2(0) += nodal_positions(node_loop,0)*basis_derivative_s2(node_loop); JT_row2(1) += nodal_positions(node_loop,1)*basis_derivative_s2(node_loop); JT_row2(2) += nodal_positions(node_loop,2)*basis_derivative_s2(node_loop); } //derivative of x,y,z w.r.t w JT_row3(0) = 0; JT_row3(1) = 0; JT_row3(2) = 0; for(int node_loop=0; node_loop < elem->num_basis(); node_loop++){ JT_row3(0) += nodal_positions(node_loop,0)*basis_derivative_s3(node_loop); JT_row3(1) += nodal_positions(node_loop,1)*basis_derivative_s3(node_loop); JT_row3(2) += nodal_positions(node_loop,2)*basis_derivative_s3(node_loop); //debug print /*if(myrank==1&&nodal_positions(node_loop,2)*basis_derivative_s3(node_loop)<-10000000){ std::cout << " ELEMENT VOLUME JACOBIAN DEBUG ON TASK " << myrank << std::endl; std::cout << node_loop+1 << " " << JT_row3(2) << " "<< nodal_positions(node_loop,2) <<" "<< basis_derivative_s3(node_loop) << std::endl; std::fflush(stdout); }*/ } //compute the determinant of the Jacobian Jacobian = JT_row1(0)*(JT_row2(1)*JT_row3(2)-JT_row3(1)*JT_row2(2))- JT_row1(1)*(JT_row2(0)*JT_row3(2)-JT_row3(0)*JT_row2(2))+ JT_row1(2)*(JT_row2(0)*JT_row3(1)-JT_row3(0)*JT_row2(1)); if(Jacobian<0) Jacobian = -Jacobian; Element_Volumes(nonoverlapping_ielem,0) += weight_multiply*Jacobian; } } std::ostream &out = std::cout; Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::fancyOStream(Teuchos::rcpFromRef(out)); //if(myrank==0) //*fos << "Global Element Volumes:" << std::endl; //Global_Element_Volumes->describe(*fos,Teuchos::VERB_EXTREME); //*fos << std::endl; } /* ------------------------------------------------------------------------------------------- Communicate ghosts using the current optimization design data ---------------------------------------------------------------------------------------------- */ void FEA_Module_Inertial::comm_variables(Teuchos::RCP<const MV> zp){ //set density vector to the current value chosen by the optimizer test_node_densities_distributed = zp; //debug print of design vector //std::ostream &out = std::cout; //Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::fancyOStream(Teuchos::rcpFromRef(out)); //if(myrank==0) //*fos << "Density data :" << std::endl; //node_densities_distributed->describe(*fos,Teuchos::VERB_EXTREME); //*fos << std::endl; //std::fflush(stdout); //communicate design densities //create import object using local node indices map and all indices map Tpetra::Import<LO, GO> importer(map, all_node_map); //comms to get ghosts all_node_densities_distributed->doImport(*test_node_densities_distributed, importer, Tpetra::INSERT); //update_count++; //if(update_count==1){ //MPI_Barrier(world); //MPI_Abort(world,4); //} }
49.912221
205
0.708401
[ "object", "shape", "vector" ]
6e5644be5489eabfe5d6f3e9e1c8369c0ef09cfb
1,471
hpp
C++
animeloop-cli/utils.hpp
moeoverflow/animeloop-cli
5211fdc7a4b7ee84f696f53eceb28eb2bd861831
[ "MIT" ]
100
2017-02-08T06:42:52.000Z
2022-03-22T05:45:45.000Z
animeloop-cli/utils.hpp
moeoverflow/animeloop-cli
5211fdc7a4b7ee84f696f53eceb28eb2bd861831
[ "MIT" ]
2
2018-04-15T06:13:52.000Z
2020-08-27T16:02:06.000Z
animeloop-cli/utils.hpp
moeoverflow/animeloop-cli
5211fdc7a4b7ee84f696f53eceb28eb2bd861831
[ "MIT" ]
7
2017-08-29T09:14:29.000Z
2020-08-02T05:27:39.000Z
// // utils.hpp // animeloop-cli // // Created by ShinCurry on 2017/4/3. // Copyright © 2017年 ShinCurry. All rights reserved. // #ifndef utils_hpp #define utils_hpp #include "models.hpp" #include <iostream> #include <string> #include <opencv2/opencv.hpp> #include <boost/filesystem/path.hpp> namespace al { VideoInfo get_info(boost::filesystem::path filename); VideoInfo get_info(cv::VideoCapture &capture); /** Resize a video and write into a new file. @param file intput path of origin video file @param output output path of resized video file @param size resizing size */ void resize_video(boost::filesystem::path input, boost::filesystem::path output, cv::Size size); bool get_frames(boost::filesystem::path file, FrameVector &frames); void get_hash_strings(boost::filesystem::path filename, std::string type, int length, int dct_length, al::HashVector &hash_strings, boost::filesystem::path hash_file); void get_cuts(boost::filesystem::path resized_filepath, CutVector &cuts, boost::filesystem::path cuts_filepath); double get_variance(std::vector<int> distances); double get_mean(cv::Mat image); cv::Vec3b get_mean_rgb(cv::Mat image); /** Convert seconds value to a time string. @param seconds seconds value @return Time string */ std::string time_string(double seconds); } bool detect_ffmpeg(); #endif /* utils_hpp */
23.349206
135
0.690687
[ "vector" ]
6e5c5b9b0532fac81c641dbefd907dd85aa0721c
7,380
cpp
C++
data/cws/src/quad/src/behind_leader.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
1
2015-03-06T06:01:17.000Z
2015-03-06T06:01:17.000Z
data/cws/src/quad/src/behind_leader.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/cws/src/quad/src/behind_leader.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
#include <iostream> #include "ros/ros.h" #include "gazebo_msgs/ModelState.h" #include "gazebo_msgs/GetModelState.h" #include "gazebo_msgs/SetModelState.h" #include "geometry_msgs/Twist.h" #include "tf/tf.h" #include <math.h> #include <sys/time.h> #include <stdio.h> using namespace std; //gain variables int InitialCondition = 0; float divider=10.0; float kr=3.0/divider; float ka=4.0/divider; float kb=6.0/divider; bool KeepGoing = true; const double PI= 3.141592653589793; float xpos; float ypos; float theta; float xLeader; float yLeader; float thetaLeader; float v; //constant for this exercise float w; //pose information float r; //rho: distance to goal float a; //alpha: angle to goal float b; //beta: desired pose respect to the robot/goal line float dr; float da; float db; float delta_x; //goal x coordinate in a world frame located at robot float delta_y; //goal y coordinate in a world frame located at robot //inputs float u_v; float u_w; int Sr=50; //sampling rate in hz float tsim; //simulation time float t; //program time (tsim normalized to t0=0 in code) float previous_t; float delta_t; bool initialTime = true; float x_initial[]={-4.5,-1.0,4.0,1.0,-5.0}; float y_initial[]={-5.6,-6.0,-6.0,6.0,5.0}; //for data saving const int fileQuantity =2; float X[fileQuantity][6]; //state to be saved to file void exportData(FILE *fp, float timestamp, float stats[6]) { int x; fprintf(fp, "%f,", timestamp); for (x = 0; x < 5; x++) fprintf(fp, "%f,",stats[x]); fprintf(fp, "%f\n", stats[5]); } int sgn(float sgnVal){ if (sgnVal > 0) return 1; if (sgnVal < 0) return -1; return 0; } //for calculating angle differences and angle wrapping double minAngle(double angle){ return atan2(sin(angle),cos(angle)); } // ***** MAIN ***** // int main(int argc, char **argv) { //FILE CONFIGURATION FOR EXPERIMENT SAVING char file_1[250]; sprintf(file_1,"follower_state_%i.csv",InitialCondition); char file_2[250]; sprintf(file_2,"follower_i bnput_%i.csv",InitialCondition); std::string fileNames[] = {file_1,file_2}; FILE *fp[2]; //array of file pointers, one for each robot. //file columns initialization for (int i = 0; i < fileQuantity; i++){ fp[i] = fopen(fileNames[i].c_str(),"w"); //uncomment if column names are needed //fprintf(fp[i],"time(seconds), x, y, theta, dx,dy,dtheta\n"); } //ROS SETUP ros::init(argc, argv, "behind_leader"); ros::NodeHandle goToGoalNode; ros::Rate loop_rate(Sr); //SETUP CLIENT TO GET MODEL STATE Follower ros::service::waitForService("/gazebo/get_model_state"); ros::ServiceClient getModelStateClient = goToGoalNode.serviceClient<gazebo_msgs::GetModelState>("/gazebo/get_model_state"); gazebo_msgs::GetModelState getModelState; getModelState.request.model_name = "mobile_base"; //SETUP CLIENT TO GET MODEL STATE Leader ros::service::waitForService("/gazebo/get_model_state"); ros::ServiceClient getModelStateClientLeader = goToGoalNode.serviceClient<gazebo_msgs::GetModelState>("/gazebo/get_model_state"); gazebo_msgs::GetModelState getModelStateLeader; getModelStateLeader.request.model_name = "quadrotor"; //SETUP AND CALL CLIENT SET MODEL STATE //Moves the robot to the desired initial pose/orientation ros::service::waitForService("/gazebo/set_model_state"); ros::ServiceClient setModelStateClient = goToGoalNode.serviceClient<gazebo_msgs::SetModelState>("/gazebo/set_model_state"); geometry_msgs::Pose start_pose; start_pose.position.x = x_initial[InitialCondition]; start_pose.position.y = y_initial[InitialCondition]; start_pose.position.z = 0.0; start_pose.orientation.x = 0.0; start_pose.orientation.y = 0.0; start_pose.orientation.z = 0.0; start_pose.orientation.w = 0.0; geometry_msgs::Twist start_twist; start_twist.linear.x = 0.0; start_twist.linear.y = 0.0; start_twist.linear.z = 0.0; start_twist.angular.x = 0.0; start_twist.angular.y = 0.0; start_twist.angular.z = 0.0; gazebo_msgs::ModelState modelstate; modelstate.model_name = (std::string) "mobile_base"; modelstate.reference_frame = (std::string) "world"; modelstate.pose = start_pose; modelstate.twist = start_twist; gazebo_msgs::SetModelState setModelState; setModelState.request.model_state = modelstate; setModelStateClient.call(setModelState); //COMMAND PUBLISHER TO THE ROBOT ros::Publisher pubName = goToGoalNode.advertise<geometry_msgs::Twist>("/tbot_ns/mobile_base/commands/velocity", 1000); //LOOP while (ros::ok()) { //get simulation time tsim = ros::Time::now().toSec(); if(tsim>0){ //setup initial time t0=0 if(initialTime == true){ previous_t=tsim; t=0; delta_t=0; initialTime = false; } else { delta_t = tsim-previous_t; previous_t=tsim; t=t+delta_t; } //get state from gazebo/vicon //better than odometry (provides data when robot //is moved by hand, and works for all models (not just robots)) getModelStateClient.call(getModelState); tf::Pose pose; tf::poseMsgToTF(getModelState.response.pose, pose); xpos = getModelState.response.pose.position.x; ypos = getModelState.response.pose.position.y; theta = tf::getYaw(pose.getRotation()); //get state from leader getModelStateClientLeader.call(getModelStateLeader); tf::Pose poseLeader; tf::poseMsgToTF(getModelStateLeader.response.pose, poseLeader); xLeader = getModelStateLeader.response.pose.position.x; yLeader = getModelStateLeader.response.pose.position.y; thetaLeader = tf::getYaw(poseLeader.getRotation()); // *********** CONTROL LAW CALCULATION ********** // r=sqrt(pow(xLeader-xpos,2)+pow(yLeader-ypos,2)); a=minAngle(atan2(yLeader-ypos,xLeader-xpos)-theta); b=minAngle(-theta-a); float error_delta = 0.1; if(r<error_delta && abs(minAngle(a)) < error_delta && abs(minAngle(b)) < error_delta){ KeepGoing = false; } //go to goal can do forward/reverse v=kr*r*cos(a); w=ka*a+kr*sin(a)*cos(a)*minAngle(a-kb*b)/(a+0.000001); // ********** print and save data ***********// printf("t %2.2f r %2.2f a % 2.2f b % 2.2f\n",t,r,a,b); printf("x %2.2f y %2.2f theta %2.2f \n",xpos,ypos,theta); printf("v %2.2f w %2.2f \n\n",v,w); //robot data X[0][0]=xpos; X[0][1]=ypos; X[0][2]=theta; X[0][3]=x_initial[InitialCondition]; X[0][4]=y_initial[InitialCondition]; X[0][5]=InitialCondition; //robot data X[1][0]=r; X[1][1]=a; X[1][2]=b; X[1][3]=v; X[1][4]=w; X[1][5]=0; //Save data to text files for analysis for (int fileIndex=0; fileIndex < fileQuantity; fileIndex++) { exportData(fp[fileIndex],t, X[fileIndex]); } if(KeepGoing == true){ geometry_msgs::Twist twistMsg; twistMsg.linear.x=v; twistMsg.linear.y=0.0; twistMsg.linear.z=0.0; twistMsg.angular.x=0.0; twistMsg.angular.y=0.0; twistMsg.angular.z=w; pubName.publish(twistMsg); } else { std::cout << " Stopped!!! \n"; geometry_msgs::Twist twistMsg; twistMsg.linear.x=0.0; twistMsg.linear.y=0.0; twistMsg.linear.z=0.0; twistMsg.angular.x=0.0; twistMsg.angular.y=0.0; twistMsg.angular.z=0.0; pubName.publish(twistMsg); } } ros::spinOnce(); loop_rate.sleep(); } for (int i = 0; i < 2; i++) fclose(fp[i]); }
27.232472
124
0.678862
[ "model" ]
6e5fdd7077b86b7b049903b4f1da7804d2ee74ea
9,477
cpp
C++
SurgSim/Devices/Oculus/OculusScaffold.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
24
2015-01-19T16:18:59.000Z
2022-03-13T03:29:11.000Z
SurgSim/Devices/Oculus/OculusScaffold.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
3
2018-12-21T14:54:08.000Z
2022-03-14T12:38:07.000Z
SurgSim/Devices/Oculus/OculusScaffold.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
8
2015-04-10T19:45:36.000Z
2022-02-02T17:00:59.000Z
// This file is a part of the OpenSurgSim project. // Copyright 2015-2016, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/Oculus/OculusScaffold.h" #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <list> #include <memory> #include <OVR_Version.h> #if 6 == OVR_MAJOR_VERSION #include <OVR_CAPI_0_6_0.h> #elif 5 == OVR_MAJOR_VERSION #include <OVR_CAPI_0_5_0.h> #endif #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Devices/Oculus/OculusDevice.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/SharedInstance.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" using SurgSim::DataStructures::DataGroup; using SurgSim::DataStructures::DataGroupBuilder; using SurgSim::Framework::Logger; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; namespace SurgSim { namespace Devices { struct OculusScaffold::DeviceData { /// Constructor /// \param device Device to be wrapped explicit DeviceData(OculusDevice* device) : deviceObject(device), handle(nullptr) { #if 6 == OVR_MAJOR_VERSION ovrHmd_Create(0, &handle); #elif 5 == OVR_MAJOR_VERSION handle = ovrHmd_Create(0); #endif } ~DeviceData() { if (handle != nullptr) { ovrHmd_Destroy(handle); } } /// The device object wrapped in this class. OculusDevice* const deviceObject; /// Device handle ovrHmd handle; }; struct OculusScaffold::StateData { /// List of registered devices. std::list<std::unique_ptr<OculusScaffold::DeviceData>> registeredDevices; /// The mutex that protects the list of registered devices. boost::mutex mutex; }; OculusScaffold::OculusScaffold() : Framework::BasicThread("OculusScaffold"), m_logger(Logger::getLogger("Devices/Oculus")), m_state(new StateData) { SURGSIM_LOG_DEBUG(m_logger) << "Oculus: Shared scaffold created."; // Oculus DK2 tracks Gyroscope, Accelerometer, Magnetometer at 1000Hz and // positional tracking is done at 60Hz. setRate(1000.0); } OculusScaffold::~OculusScaffold() { ovr_Shutdown(); } bool OculusScaffold::registerDevice(OculusDevice* device) { bool success = true; if (!isRunning()) { std::shared_ptr<SurgSim::Framework::Barrier> barrier = std::make_shared<SurgSim::Framework::Barrier>(2); start(barrier); barrier->wait(true); // Wait for initialize barrier->wait(true); // Wait for startup success = isInitialized(); } if (success) { boost::lock_guard<boost::mutex> lock(m_state->mutex); const std::string deviceName = device->getName(); auto sameName = [&deviceName](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == deviceName; }; auto found = std::find_if(m_state->registeredDevices.cbegin(), m_state->registeredDevices.cend(), sameName); if (found == m_state->registeredDevices.end()) { std::unique_ptr<DeviceData> info(new DeviceData(device)); success = doRegisterDevice(info.get()); if (success) { SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Registered"; m_state->registeredDevices.emplace_back(std::move(info)); } } else { SURGSIM_LOG_SEVERE(m_logger) << "Tried to register a device when the same name, '" << device->getName() << "', is already present!"; success = false; } } if (isRunning() && m_state->registeredDevices.size() == 0) { stop(); } return success; } bool OculusScaffold::doRegisterDevice(DeviceData* info) { if (ovrHmd_Detect() < 1) { SURGSIM_LOG_SEVERE(m_logger) << "No available Oculus device detected."; return false; } if (m_state->registeredDevices.size() > 0) { SURGSIM_LOG_SEVERE(m_logger) << "There is one registered Oculus device already. OculusScaffold only supports one device right now"; return false; } if (info->handle == nullptr) { SURGSIM_LOG_SEVERE(m_logger) << "Failed to obtain a handle to Oculus Device. Is an Oculus device plugged in?"; return false; } #if 6 == OVR_MAJOR_VERSION if (ovrSuccess != ovrHmd_ConfigureTracking(info->handle, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0)) #elif 5 == OVR_MAJOR_VERSION if (ovrTrue != ovrHmd_ConfigureTracking(info->handle, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0)) #endif { SURGSIM_LOG_SEVERE(m_logger) << "Failed to configure an Oculus Device. Registration failed"; return false; } // Query the HMD for the left and right projection matrices. ovrFovPort defaultLeftFov = info->handle->DefaultEyeFov[ovrEyeType::ovrEye_Left]; ovrFovPort defaultRightFov = info->handle->DefaultEyeFov[ovrEyeType::ovrEye_Right]; float nearPlane = info->deviceObject->getNearPlane(); float farPlane = info->deviceObject->getFarPlane(); ovrMatrix4f leftProjection = ovrMatrix4f_Projection(defaultLeftFov, nearPlane, farPlane, ovrProjectionModifier::ovrProjection_RightHanded); ovrMatrix4f rightProjection = ovrMatrix4f_Projection(defaultRightFov, nearPlane, farPlane, ovrProjectionModifier::ovrProjection_RightHanded); DataGroup& inputData = info->deviceObject->getInputData(); inputData.matrices().set(DataStructures::Names::LEFT_PROJECTION_MATRIX, Eigen::Map<const Eigen::Matrix<float, 4, 4, Eigen::RowMajor>> (&leftProjection.M[0][0]).cast<double>()); inputData.matrices().set(DataStructures::Names::RIGHT_PROJECTION_MATRIX, Eigen::Map<const Eigen::Matrix<float, 4, 4, Eigen::RowMajor>> (&rightProjection.M[0][0]).cast<double>()); info->deviceObject->pushInput(); return true; } bool OculusScaffold::unregisterDevice(const OculusDevice* const device) { bool result = false; { boost::lock_guard<boost::mutex> lock(m_state->mutex); auto match = std::find_if(m_state->registeredDevices.begin(), m_state->registeredDevices.end(), [&device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; }); if (match != m_state->registeredDevices.end()) { m_state->registeredDevices.erase(match); // the iterator is now invalid but that's OK SURGSIM_LOG_INFO(m_logger) << "Device " << getName() << ": unregistered."; result = true; } } // #threadsafety After unregistering, another thread could be in the process of registering. if (isRunning() && m_state->registeredDevices.size() == 0) { stop(); } SURGSIM_LOG_IF(!result, m_logger, SEVERE) << "Attempted to release a non-registered device."; return result; } bool OculusScaffold::doInitialize() { #if 6 == OVR_MAJOR_VERSION if (ovrSuccess != ovr_Initialize(nullptr)) #elif 5 == OVR_MAJOR_VERSION if (ovrTrue != ovr_Initialize(nullptr)) #endif { SURGSIM_LOG_SEVERE(m_logger) << "Oculus SDK initialization failed."; } return true; } bool OculusScaffold::doStartUp() { return true; } bool OculusScaffold::doUpdate(double dt) { boost::lock_guard<boost::mutex> lock(m_state->mutex); for (auto& device : m_state->registeredDevices) { DataGroup& inputData = device->deviceObject->getInputData(); // Query the HMD for the current tracking state. // If time in 2nd parameter is now or earlier, no pose prediction is made. // Pose is reported in a right handed coordinate system, X->RIGHT, Y->UP, Z->OUT. // Positive rotation is counterclockwise. // The XZ plane is ALWAYS aligned with the ground regardless of camera orientation. // Default tracking origin is one meter away from the camera. ovrTrackingState ts = ovrHmd_GetTrackingState(device->handle, ovr_GetTimeInSeconds()); if (ts.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked)) { ovrPosef ovrPose = ts.HeadPose.ThePose; Vector3d position(ovrPose.Position.x, ovrPose.Position.y, ovrPose.Position.z); Quaterniond orientation(ovrPose.Orientation.w, ovrPose.Orientation.x, ovrPose.Orientation.y, ovrPose.Orientation.z); RigidTransform3d pose = makeRigidTransform(orientation, position); inputData.poses().set(DataStructures::Names::POSE, pose); } else { inputData.poses().reset(DataStructures::Names::POSE); } device->deviceObject->pushInput(); } return true; } SurgSim::DataStructures::DataGroup OculusScaffold::buildDeviceInputData() { DataGroupBuilder builder; builder.addPose(DataStructures::Names::POSE); builder.addMatrix(DataStructures::Names::LEFT_PROJECTION_MATRIX); builder.addMatrix(DataStructures::Names::RIGHT_PROJECTION_MATRIX); return builder.createData(); } std::shared_ptr<OculusScaffold> OculusScaffold::getOrCreateSharedInstance() { static auto creator = []() { return std::shared_ptr<OculusScaffold>(new OculusScaffold); }; static Framework::SharedInstance<OculusScaffold> sharedInstance(creator); return sharedInstance.get(); } }; // namespace Devices }; // namespace SurgSim
29.340557
112
0.734621
[ "object" ]
6e60983af90ea6ca9add22d83a4e2e82be2ab2ec
1,081
hpp
C++
src/Engine/Managers/CameraManager/DefaultCameraManager.hpp
david49az/Radium-Engine
2600039e5c0658057b8b35f79222a332feceb026
[ "Apache-2.0" ]
1
2021-02-03T17:47:04.000Z
2021-02-03T17:47:04.000Z
src/Engine/Managers/CameraManager/DefaultCameraManager.hpp
david49az/Radium-Engine
2600039e5c0658057b8b35f79222a332feceb026
[ "Apache-2.0" ]
null
null
null
src/Engine/Managers/CameraManager/DefaultCameraManager.hpp
david49az/Radium-Engine
2600039e5c0658057b8b35f79222a332feceb026
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Engine/Managers/CameraManager/CameraManager.hpp> #include <Engine/Renderer/Camera/Camera.hpp> #include <memory> #include <vector> namespace Ra { namespace Engine { /** * Associated class. */ class RA_ENGINE_API DefaultCameraStorage : public CameraStorage { public: DefaultCameraStorage(); void add( Camera* cam ) override; void remove( Camera* cam ) override; size_t size() const override; void clear() override; Camera* operator[]( unsigned int n ) override; private: /** Vectors (by Camera type) of Camera references. */ std::multimap<Ra::Engine::Camera::ProjType, Ra::Engine::Camera*> m_Cameras; }; /** * @brief DefaultCameraManager. A simple Camera Manager with a list of Cameras. */ class RA_ENGINE_API DefaultCameraManager : public CameraManager { public: DefaultCameraManager(); /// Return the \p cam-th camera. const Camera* getCamera( size_t cam ) const override; /// Add \p cam for management. void addCamera( Camera* cam ) override; }; } // namespace Engine } // namespace Ra
23
79
0.699352
[ "vector" ]
6e672489cac47ab738e588da3c8a3425940c64d9
6,178
cc
C++
DomainSymbolicPlanner/smartsoft/src/DomainSymbolicPlanner/CommSymbolicPlannerPlan.cc
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
null
null
null
DomainSymbolicPlanner/smartsoft/src/DomainSymbolicPlanner/CommSymbolicPlannerPlan.cc
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
DomainSymbolicPlanner/smartsoft/src/DomainSymbolicPlanner/CommSymbolicPlannerPlan.cc
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // This file is generated once. Modify this file to your needs. // If you want the toolchain to re-generate this file, please // delete it before running the code generator. //-------------------------------------------------------------------------- // -------------------------------------------------------------------------- // // Copyright (C) 2010/2011 Andreas Steck, 2014 Matthias Lutz // // schlegel@hs-ulm.de // steck@hs-ulm.de // // ZAFH Servicerobotik Ulm // University of Applied Sciences // Prittwitzstr. 10 // D-89075 Ulm // Germany // // This file is part of the "SmartSoft Communication Classes". // It provides basic standardized data types for communication between // different components in the mobile robotics context. These classes // are designed to be used in conjunction with the SmartSoft Communication // Library. // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // -------------------------------------------------------------------------- #include "DomainSymbolicPlanner/CommSymbolicPlannerPlan.hh" #include<cstdlib> using namespace DomainSymbolicPlanner; CommSymbolicPlannerPlan::CommSymbolicPlannerPlan() : CommSymbolicPlannerPlanCore() { } /** * Constructor to set all values. * NOTE that you have to keep this constructor consistent with the model! * Use at your own choice. * * The preferred way to set values for initialization is: * CommRepository::MyCommObject obj; * obj.setX(1).setY(2).setZ(3)...; CommSymbolicPlannerPlan::CommSymbolicPlannerPlan(const std::string &plan) : CommSymbolicPlannerPlanCore() // base constructor sets default values as defined in the model { setPlan(plan); } */ CommSymbolicPlannerPlan::CommSymbolicPlannerPlan(const CommSymbolicPlannerPlanCore &commSymbolicPlannerPlan) : CommSymbolicPlannerPlanCore(commSymbolicPlannerPlan) { } CommSymbolicPlannerPlan::CommSymbolicPlannerPlan(const DATATYPE &commSymbolicPlannerPlan) : CommSymbolicPlannerPlanCore(commSymbolicPlannerPlan) { } CommSymbolicPlannerPlan::~CommSymbolicPlannerPlan() { } int CommSymbolicPlannerPlan::set_plan(std::string name) { idl_CommSymbolicPlannerPlan.plan = name.c_str(); return 0; } int CommSymbolicPlannerPlan::get_plan(std::string &name) const { name = idl_CommSymbolicPlannerPlan.plan.c_str(); return 0; } std::string CommSymbolicPlannerPlan::getPlanStatus(){ std::cout<<"WARNING: CODE NOT TESTED YET!"<<std::endl; std::string planString = getPlan(); std::string result("error"); std::string resultString ("(result "); std::size_t found; std::size_t endFound; found = planString.find(resultString); if(std::string::npos != found) { endFound = planString.find(")",found+resultString.length()); result = planString.substr(found+resultString.length(),endFound-(found+resultString.length())); } else { result = "error"; } return result; } unsigned int CommSymbolicPlannerPlan::getNumberOfOperations(){ std::cout<<"WARNING: CODE NOT TESTED YET!"<<std::endl; //std::cout<<"GetPlan|"<<planString<<std::endl; // ((result ok)(ops 3)(plan ((UNDOCK-ROBOT ROBOT-3)(PERFORM-TASK ROBOT-3 TASK-2)(PERFORM-TASK ROBOT-2 TASK-1)))(cost 0)) std::string planString = getPlan(); std::string result("error"); unsigned int res = 0; std::string resultString ("(ops "); std::size_t found; std::size_t endFound; found = planString.find(resultString); if(std::string::npos != found) { endFound = planString.find(")",found+resultString.length()); result = planString.substr(found+resultString.length(),endFound-(found+resultString.length())); } else { result = "error"; res = 0; } res = atoi(result.c_str()); return res; } unsigned int CommSymbolicPlannerPlan::getPlanCosts(){ std::cout<<"WARNING: CODE NOT TESTED YET!"<<std::endl; std::string planString = getPlan(); std::string result("error"); unsigned int res = 0; std::string resultString ("(cost "); std::size_t found; std::size_t endFound; found = planString.find(resultString); if(std::string::npos != found) { endFound = planString.find(")",found+resultString.length()); result = planString.substr(found+resultString.length(),endFound-(found+resultString.length())); res = atoi(result.c_str()); } else { result = "error"; res = 0; } return res; } std::list < std::string > CommSymbolicPlannerPlan::getPlanSteps(){ std::cout<<"WARNING: CODE NOT TESTED YET!"<<std::endl; std::list <std::string> planList; std::string INPUT = getPlan(); std::string result("error"); //unsigned int res = 0; std::string planString ("(plan ("); std::size_t found; std::size_t endFound; unsigned int numberofOps = getNumberOfOperations(); found = INPUT.find(planString); if(std::string::npos != found) { found += planString.length()+1; for(unsigned int i =0; i<numberofOps;i++){ std::string tmp; endFound = INPUT.find(")",found+planString.length()); tmp = INPUT.substr(found,endFound-(found)); //std::cout<<"TMP: "<<tmp<<std::endl; planList.push_back(tmp); found = endFound+2; } } return planList; }
29.419048
120
0.68145
[ "model" ]
6e69c5130c03abe854f2df65082c303bf8daf091
5,704
cc
C++
c/src/day03.cc
grgrzybek/adventofcode2021
1f697e9912071bc2f52bba7db0c343926c091f50
[ "ECL-2.0", "Apache-2.0" ]
3
2021-12-01T14:12:48.000Z
2021-12-03T07:43:17.000Z
c/src/day03.cc
grgrzybek/adventofcode2021
1f697e9912071bc2f52bba7db0c343926c091f50
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
c/src/day03.cc
grgrzybek/adventofcode2021
1f697e9912071bc2f52bba7db0c343926c091f50
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Grzegorz Grzybek * * 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 <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include "utils/utils.h" using namespace std; using namespace aoc2021; int main(int argc, char *argv[]) { Options options("Day 03", argc, argv); if (!options.check()) return options.result(); cout << "Starting " << options.program_name << endl; ifstream *input = options.file(); string line; vector<int> zeros; vector<int> ones; vector<string *> oxygen_values; vector<string *> co2_values; int c = 0; while (getline(*input, line)) { trim(line); // for part 2 oxygen_values.push_back(new string(line)); co2_values.push_back(new string(line)); int pos = 0; if (c == 0) { // init for (char ch: line) { if (ch == '0') { zeros.push_back(1); ones.push_back(0); } else { zeros.push_back(0); ones.push_back(1); } } } else { // update for (char ch: line) { if (ch == '0') { zeros[pos++]++; } else { ones[pos++]++; } } } c++; } // part 1 int gamma = 0; int epsilon = 0; int shift = 0; for (unsigned long i = ones.size(); i > 0; i--) { if (ones[i - 1] >= zeros[i - 1]) { gamma |= 1 << shift; } else { epsilon |= 1 << shift; } shift++; } int answer1 = gamma * epsilon; // part 2 int oxygen = 0; int co2 = 0; // the bit starting from left - to search the most common int bit = 0; // oxygen_values while (true) { // search for most common int zero_count = 0; int one_count = 0; for (string *&oxygen_value: oxygen_values) { if (!oxygen_value) { continue; } if ((*oxygen_value)[bit] == '0') { zero_count++; } else { one_count++; } } // removing not matching int values_left = 0; string *last_value; for (string *&oxygen_value: oxygen_values) { if (!oxygen_value) { continue; } if (one_count >= zero_count) { // keep value with 1 if ((*oxygen_value)[bit] != '1') { delete oxygen_value; oxygen_value = nullptr; } else { values_left++; last_value = oxygen_value; } } else { // keep value with 0 if ((*oxygen_value)[bit] != '0') { delete oxygen_value; oxygen_value = nullptr; } else { values_left++; last_value = oxygen_value; } } } shift = 0; if (values_left == 1) { for (unsigned long i = last_value->size(); i > 0; i--) { oxygen |= ((*last_value)[i - 1] == '0' ? 0 : 1) << shift; shift++; } break; } bit++; } bit = 0; // co2_values while (true) { // search for least common int zero_count = 0; int one_count = 0; for (string *&co2_value: co2_values) { if (!co2_value) { continue; } if ((*co2_value)[bit] == '0') { zero_count++; } else { one_count++; } } // removing not matching int values_left = 0; string *last_value; for (string *&co2_value: co2_values) { if (!co2_value) { continue; } if (zero_count <= one_count) { // keep value with 0 if ((*co2_value)[bit] != '0') { delete co2_value; co2_value = nullptr; } else { values_left++; last_value = co2_value; } } else { // keep value with 1 if ((*co2_value)[bit] != '1') { delete co2_value; co2_value = nullptr; } else { values_left++; last_value = co2_value; } } } shift = 0; if (values_left == 1) { for (unsigned long i = last_value->size(); i > 0; i--) { co2 |= ((*last_value)[i - 1] == '0' ? 0 : 1) << shift; shift++; } break; } bit++; } int answer2 = oxygen * co2; cout << "Answer 1: " << answer1 << endl; cout << "Answer 2: " << answer2 << endl; return EXIT_SUCCESS; }
25.578475
75
0.435484
[ "vector" ]
6e6be2446fcb041be165783ac553b1e4354e484a
5,488
cpp
C++
src/rendering/Engine.cpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
1
2021-11-12T08:42:43.000Z
2021-11-12T08:42:43.000Z
src/rendering/Engine.cpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
src/rendering/Engine.cpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
#include "Engine.hpp" #include "GLFW/glfw3.h" #include "device/vulkan/VulkanDevice.hpp" #include "features/GeometryPass.hpp" #include "features/LightingPass.hpp" #include "features/ScreenSpaceReflectionsPass.hpp" #include "features/AmbientOcclusionPass.hpp" #include "features/MomentShadowPass.hpp" #include "features/PostProcessPass.hpp" #include "features/DebugOverlayPass.hpp" #include "rendering/RenderSettings.hpp" #include "scene/Camera.hpp" #include "scene/Transform.hpp" namespace lucent { static void BuildDefaultSceneRenderer(Engine* engine, Renderer& renderer) { auto sceneRadiance = CreateSceneRadianceTarget(renderer); auto gBuffer = AddGeometryPass(renderer); auto hiZ = AddGenerateHiZPass(renderer, gBuffer.depth); auto shadowMoments = AddMomentShadowPass(renderer); auto gtao = AddGTAOPass(renderer, gBuffer, hiZ); auto ssr = AddScreenSpaceReflectionsPass(renderer, gBuffer, hiZ, sceneRadiance); AddLightingPass(renderer, gBuffer, hiZ, sceneRadiance, shadowMoments, gtao, ssr); auto output = AddPostProcessPass(renderer, sceneRadiance); AddDebugOverlayPass(renderer, engine->GetConsole(), output); renderer.AddPresentPass(output); } std::unique_ptr<Engine> Engine::s_Engine; Engine* Engine::Init(RenderSettings settings) { if (!s_Engine) { s_Engine = std::unique_ptr<Engine>(new Engine(std::move(settings))); } return s_Engine.get(); } Engine* Engine::Instance() { LC_ASSERT(s_Engine && "requires initialization!"); return s_Engine.get(); } // TODO: Remove or extract to separate file // Ideally user provides existing window to the engine, might have to change debug functions in this case class Window { public: GLFWwindow* window; }; Engine::Engine(RenderSettings settings) { // Set up GLFW if (!glfwInit()) return; // Create window glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); m_Window = std::make_unique<Window>(Window{ glfwCreateWindow((int)settings.viewportWidth, (int)settings.viewportHeight, "Lucent", nullptr, nullptr) }); LC_ASSERT(m_Window->window != nullptr); m_Device = std::make_unique<VulkanDevice>(m_Window->window); m_Input = std::make_unique<Input>(m_Window->window); m_Console = std::make_unique<DebugConsole>(*this, 120); settings.InitializeDefaultResources(m_Device.get()); m_SceneRenderer = std::make_unique<Renderer>(m_Device.get(), std::move(settings)); m_BuildSceneRenderer = BuildDefaultSceneRenderer; m_BuildSceneRenderer(this, *m_SceneRenderer); } bool Engine::Update() { if (glfwWindowShouldClose(m_Window->window)) return false; glfwPollEvents(); double time = glfwGetTime(); auto dt = float(time - m_LastUpdateTime); UpdateDebug(dt); if (!m_SceneRenderer->Render(*m_ActiveScene)) { LC_INFO("Rebuilding scene renderer"); m_Device->WaitIdle(); m_Device->RebuildSwapchain(); int width, height; glfwGetFramebufferSize(m_Window->window, &width, &height); auto& settings = m_SceneRenderer->GetSettings(); settings.viewportWidth = width; settings.viewportHeight = height; m_ActiveScene->mainCamera.Get<Camera>().aspectRatio = (float)width / (float)height; m_SceneRenderer->Clear(); m_BuildSceneRenderer(this, *m_SceneRenderer); }; m_Input->Reset(); m_LastUpdateTime = time; return true; } Device* Engine::GetDevice() { return m_Device.get(); } Scene* Engine::CreateScene() { auto scene = m_Scenes.emplace_back(std::make_unique<Scene>()).get(); m_ActiveScene = scene; return scene; } void Engine::UpdateDebug(float dt) { auto& input = m_Input->GetState(); if (!m_Console->Active()) { m_ActiveScene->Each<Transform, Camera>([&](auto& transform, auto& camera) { // TODO: Remove temporary camera movement controls to debug camera // Update camera pos const float hSensitivity = 0.8f; const float vSensitivity = 1.0f; camera.yaw += dt * hSensitivity * -input.cursorDelta.x; camera.pitch += dt * vSensitivity * -input.cursorDelta.y; camera.pitch = Clamp(camera.pitch, -kHalfPi, kHalfPi); auto rotation = Matrix4::RotationY(camera.yaw); Vector3 velocity; if (input.KeyDown(LC_KEY_W)) velocity += Vector3::Forward(); if (input.KeyDown(LC_KEY_S)) velocity += Vector3::Back(); if (input.KeyDown(LC_KEY_A)) velocity += Vector3::Left(); if (input.KeyDown(LC_KEY_D)) velocity += Vector3::Right(); velocity.Normalize(); auto velocityWorld = Vector3(rotation * Vector4(velocity)); if (input.KeyDown(LC_KEY_SPACE)) velocityWorld += Vector3::Up(); if (input.KeyDown(LC_KEY_LEFT_SHIFT)) velocityWorld += Vector3::Down(); constexpr float kFlySpeedMultiplier = 3.0f; float multiplier = input.KeyDown(LC_KEY_LEFT_CONTROL) ? kFlySpeedMultiplier : 1.0f; const float speed = 5.0f; transform.position += dt * speed * multiplier * velocityWorld; }); } // Update debug console m_Console->Update(input, dt); } DebugConsole* Engine::GetConsole() { return m_Console.get(); } Input& Engine::GetInput() { return *m_Input; } const RenderSettings& Engine::GetRenderSettings() { return m_SceneRenderer->GetSettings(); } }
28.28866
111
0.676749
[ "render", "transform" ]
6e702748f739094675a6143da3dfffcc0eb6d881
32,188
cpp
C++
src/osapi/outwnd.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
src/osapi/outwnd.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
src/osapi/outwnd.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/OsApi/OutWnd.cpp $ * $Revision: 110 $ * $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $ * $Author: relnev $ * * Routines for debugging output * * $Log$ * Revision 1.3 2002/06/09 04:41:25 relnev * added copyright header * * Revision 1.2 2002/05/07 03:16:48 theoddone33 * The Great Newline Fix * * Revision 1.1.1.1 2002/05/03 03:28:10 root * Initial import. * * * 6 6/03/99 6:37p Dave * More TNT fun. Made perspective bitmaps more flexible. * * 5 6/02/99 6:18p Dave * Fixed TNT lockup problems! Wheeeee! * * 4 12/14/98 12:13p Dave * Spiffed up xfer system a bit. Put in support for squad logo file xfer. * Need to test now. * * 3 10/08/98 2:38p Dave * Cleanup up OsAPI code significantly. Removed old functions, centralized * registry functions. * * 2 10/07/98 10:53a Dave * Initial checkin. * * 1 10/07/98 10:50a Dave * * 49 5/15/98 3:36p John * Fixed bug with new graphics window code and standalone server. Made * hwndApp not be a global anymore. * * 48 5/14/98 5:42p John * Revamped the whole window position/mouse code for the graphics windows. * * 47 5/14/98 11:24a Allender * throw mprints to outtext regardless of gr mode * * 46 4/30/98 4:53p John * Restructured and cleaned up cfile code. Added capability to read off * of CD-ROM drive and out of multiple pack files. * * 45 4/16/98 6:31p Dave * Doubled MAX_FILTERS to 48 * * 44 3/31/98 5:18p John * Removed demo/save/restore. Made NDEBUG defined compile. Removed a * bunch of debug stuff out of player file. Made model code be able to * unload models and malloc out only however many models are needed. * * * 43 3/11/98 12:06p John * Made it so output window never gets focus upon startup * * 42 2/16/98 9:47a John * Made so only error, general, and warning are shown if no * debug_filter.cfg and .cfg file isn't saved if so. * * 41 2/05/98 9:21p John * Some new Direct3D code. Added code to monitor a ton of stuff in the * game. * * 40 1/15/98 9:14p John * Made it so general, error and warning can't be turned off. * * 39 9/13/97 10:44a Lawrance * allow logging of nprintf output to file * * 38 8/23/97 11:32a Dave * Made debug window size correctly in standalone mode. * * 37 8/22/97 3:42p Hoffoss * Lowered the filter limit to 24, and added support for filter recycling, * instead of the rather nasty Assert if we should happen to exceed this * limit. * * 36 8/05/97 4:29p Dave * Futzed with window sizes/placements for standalone mode. * * 35 8/04/97 3:15p Dave * Added an include for systemvars.h * * 34 5/20/97 1:13p Allender * fixes to make outwnd work better under Win95 * * 33 5/14/97 11:08a John * fixed bug under 95 that occasionally hung program. * * 32 5/07/97 3:01p Lawrance * check for NT in mono_init * * 31 5/07/97 3:06p John * disabled new mono direct stuff under NT. * * 30 5/07/97 2:59p John * Made so mono driver works under '95. * * 29 4/22/97 10:56a John * fixed some resource leaks. * * $NoKeywords: $ */ #ifndef NDEBUG #include <windows.h> #include <stdio.h> #include <stdarg.h> #include <string.h> // to disable otherwise well-lodged compiler warning #pragma warning(disable: 4201) #include <winioctl.h> #include <conio.h> #include "osapi.h" #include "outwnd.h" #include "cfile.h" #include "monopub.h" #include "2d.h" #include "freespaceresource.h" #include "systemvars.h" #define MAX_FILTERS 48 #define SCROLL_BUFFER_SIZE 512 #define MAX_LINE_WIDTH 128 #define TASKBAR_HEIGHT 30 #define ID_COPY 32000 #define ID_FIND 32010 #define ID_FILTER 32100 #define TIMER1 1 #define UP_FAST 65537 #define DOWN_FAST 65538 HANDLE hOutputThread=NULL; DWORD OutputThreadID; HWND hOutputWnd; char szOutputClass[] = "OutputWindow"; char spaces[MAX_LINE_WIDTH + 1]; int outwnd_filter_count = 0; int outwnd_filter_loaded = 0; char find_text[85]; struct outwnd_filter_struct { char name[FILTER_NAME_LENGTH]; int state; } *outwnd_filter[MAX_FILTERS], real_outwnd_filter[MAX_FILTERS]; int mprintf_last_line = -1; char outtext[SCROLL_BUFFER_SIZE][MAX_LINE_WIDTH]; int old_scroll_pos = -32768; int nTextHeight=0, nTextWidth=0, nCharRows=0; int outwnd_inited = FALSE; int outwnd_disabled = TRUE; int max_scroll_pos = SCROLL_BUFFER_SIZE - 1; static int marked = 0; int marked_top, marked_bottom, marked_left, marked_right; int old_marked = 0, old_marked_top, old_marked_bottom, old_marked_left, old_marked_right; int marking_started_x, marking_started_y, client_top_yoffset, cur_line_index, marking_active = 0; int scroll_wait = 1; BOOL OutputActive = FALSE; LPARAM last_mousemove; int Outwnd_changed = 0; int find_line = -1, find_pos; // monochrome screen info HANDLE mono_driver=NULL; // handle to the monochrome driver void outwnd_print(char *id, char *tmp); BOOL CALLBACK find_dlg_handler(HWND hwnd,UINT msg,WPARAM wParam, LPARAM lParam); void find_text_in_outwindow(int n, int p); void outwnd_copy_marked_selection(HWND hwnd); void outwnd_update_marking(LPARAM l_parm, HWND hwnd); void outwnd_paint(HWND hwnd); int Outwnd_no_filter_file = 0; // 0 = .cfg file found, 1 = not found and warning not printed yet, 2 = not found and warning printed // used for file logging #ifndef NDEBUG int Log_debug_output_to_file = 0; FILE *Log_fp; char *Freespace_logfilename = "fs.log"; #endif inline void text_hilight(HDC &hdc) { SetBkColor(hdc, RGB(0, 0, 0)); SetTextColor(hdc, RGB(255, 255, 255)); } inline void text_normal(HDC &hdc) { SetBkColor(hdc, RGB(255, 255, 255)); SetTextColor(hdc, RGB(0, 0, 0)); } inline void fix_marking_coords(int &x, int &y, LPARAM l_parm) { x = (signed short) LOWORD(l_parm) / nTextWidth; y = ((signed short) HIWORD(l_parm) - client_top_yoffset) / nTextHeight + cur_line_index; if (y < 0) y = x = 0; if (y > SCROLL_BUFFER_SIZE) { y = SCROLL_BUFFER_SIZE; x = 0; } if (x < 0) x = -1; if (x > MAX_LINE_WIDTH) { y++; x = 0; // marks to end of line } } // InvalidateRect(hOutputWnd,NULL,0); void load_filter_info(void) { FILE *fp; char pathname[256], inbuf[FILTER_NAME_LENGTH+4]; int z; outwnd_filter_loaded = 1; outwnd_filter_count = 0; strcpy(pathname, "Debug_filter.cfg" ); fp = fopen(pathname, "rt"); if (!fp) { Outwnd_no_filter_file = 1; outwnd_filter[outwnd_filter_count] = &real_outwnd_filter[outwnd_filter_count]; strcpy( outwnd_filter[outwnd_filter_count]->name, "error" ); outwnd_filter[outwnd_filter_count]->state = 1; outwnd_filter_count++; outwnd_filter[outwnd_filter_count] = &real_outwnd_filter[outwnd_filter_count]; strcpy( outwnd_filter[outwnd_filter_count]->name, "general" ); outwnd_filter[outwnd_filter_count]->state = 1; outwnd_filter_count++; outwnd_filter[outwnd_filter_count] = &real_outwnd_filter[outwnd_filter_count]; strcpy( outwnd_filter[outwnd_filter_count]->name, "warning" ); outwnd_filter[outwnd_filter_count]->state = 1; outwnd_filter_count++; return; } Outwnd_no_filter_file = 0; while (fgets(inbuf, FILTER_NAME_LENGTH+3, fp)) { if (outwnd_filter_count == MAX_FILTERS) break; outwnd_filter[outwnd_filter_count] = &real_outwnd_filter[outwnd_filter_count]; if (*inbuf == '+') outwnd_filter[outwnd_filter_count]->state = 1; else if (*inbuf == '-') outwnd_filter[outwnd_filter_count]->state = 0; else continue; // skip everything else z = strlen(inbuf) - 1; if (inbuf[z] == '\n') inbuf[z] = 0; Assert(strlen(inbuf+1) < FILTER_NAME_LENGTH); strcpy(outwnd_filter[outwnd_filter_count]->name, inbuf + 1); if ( !stricmp( outwnd_filter[outwnd_filter_count]->name, "error" ) ) { outwnd_filter[outwnd_filter_count]->state = 1; } else if ( !stricmp( outwnd_filter[outwnd_filter_count]->name, "general" ) ) { outwnd_filter[outwnd_filter_count]->state = 1; } else if ( !stricmp( outwnd_filter[outwnd_filter_count]->name, "warning" ) ) { outwnd_filter[outwnd_filter_count]->state = 1; } outwnd_filter_count++; } if (ferror(fp) && !feof(fp)) nprintf(("Error", "Error reading \"%s\"\n", pathname)); fclose(fp); } void save_filter_info(void) { FILE *fp; int i; char pathname[256]; if (!outwnd_filter_loaded) return; if ( Outwnd_no_filter_file ) { return; // No file, don't save } strcpy(pathname, "Debug_filter.cfg" ); fp = fopen(pathname, "wt"); if (fp) { for (i=0; i<outwnd_filter_count; i++) fprintf(fp, "%c%s\n", outwnd_filter[i]->state ? '+' : '-', outwnd_filter[i]->name); fclose(fp); } } void outwnd_printf2(char *format, ...) { char tmp[MAX_LINE_WIDTH*4]; va_list args; va_start(args, format); vsprintf(tmp, format, args); va_end(args); outwnd_print("General", tmp); } char mono_ram[80*25*2]; int mono_x, mono_y; int mono_found = 0; void mono_flush() { if ( !mono_found ) return; memcpy( (void *)0xb0000, mono_ram, 80*25*2 ); } void mono_init() { int i; OSVERSIONINFO ver; ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&ver); if ( ver.dwPlatformId == VER_PLATFORM_WIN32_NT ) { mono_found = 0; return; } _outp( 0x3b4, 0x0f ); _outp( 0x3b4+1, 0x55 ); if ( _inp( 0x3b4+1 ) == 0x55 ) { mono_found = 1; _outp( 0x3b4+1, 0 ); } else { mono_found = 0; return; } for (i=0; i<80*25; i++ ) { mono_ram[i*2+0] = ' '; mono_ram[i*2+1] = 0x07; } mono_flush(); mono_x = mono_y = 0; } void mono_print( char * text, int len ) { int i, j; if ( !mono_found ) return; for (i=0; i<len; i++ ) { int scroll_it = 0; switch( text[i] ) { case '\n': scroll_it = 1; break; default: mono_ram[mono_y*160+mono_x*2] = text[i]; if ( mono_x < 79 ) { mono_x++; } else { scroll_it = 1; } break; } if ( scroll_it ) { if ( mono_y < 24 ) { mono_y++; mono_x = 0; } else { memmove( mono_ram, mono_ram+160, 80*24*2 ); for (j=0; j<80; j++ ) { mono_ram[24*160+j*2] = ' '; } mono_y = 24; mono_x = 0; } } } mono_flush(); } void outwnd_printf(char *id, char *format, ...) { char tmp[MAX_LINE_WIDTH*4]; va_list args; va_start(args, format); vsprintf(tmp, format, args); va_end(args); outwnd_print(id, tmp); } void outwnd_print(char *id, char *tmp) { char *sptr; char *dptr; int i, nrows, ccol; outwnd_filter_struct *temp; if(gr_screen.mode == GR_DIRECT3D){ return; } if (!outwnd_inited) return; if ( Outwnd_no_filter_file == 1 ) { Outwnd_no_filter_file = 2; outwnd_print( "general", "==========================================================================\n" ); outwnd_print( "general", "DEBUG SPEW: No debug_filter.cfg found, so only general, error, and warning\n" ); outwnd_print( "general", "categories can be shown and no debug_filter.cfg info will be saved.\n" ); outwnd_print( "general", "==========================================================================\n" ); } if (!id) id = "General"; for (i=0; i<outwnd_filter_count; i++) if (!stricmp(id, outwnd_filter[i]->name)) break; if (i == outwnd_filter_count) // new id found that's not yet in filter list { // Only create new filters if there was a filter file if ( Outwnd_no_filter_file ) { return; } if (outwnd_filter_count >= MAX_FILTERS) { Assert(outwnd_filter_count == MAX_FILTERS); // how did it get over the max? Very bad.. outwnd_printf("General", "Outwnd filter limit reached. Recycling \"%s\" to add \"%s\"", outwnd_filter[MAX_FILTERS - 1]->name, id); i--; // overwrite the last element (oldest used filter in the list) } Assert(strlen(id) < FILTER_NAME_LENGTH); outwnd_filter[i] = &real_outwnd_filter[i]; // note: this assumes the list doesn't have gaps (from deleting an element for example) strcpy(outwnd_filter[i]->name, id); outwnd_filter[i]->state = 1; outwnd_filter_count = i + 1; save_filter_info(); } // sort the filters from most recently used to oldest, so oldest ones will get recycled first temp = outwnd_filter[i]; while (i--) outwnd_filter[i + 1] = outwnd_filter[i]; i++; outwnd_filter[i] = temp; if (!outwnd_filter[i]->state) return; if (mprintf_last_line == -1 ) { for (i=0; i<SCROLL_BUFFER_SIZE;i++) { outtext[i][0] = 0; } mprintf_last_line = 0; } // printf out to the monochrome screen first if ( mono_driver != ((HANDLE)-1) ) { DWORD cbReturned; DeviceIoControl (mono_driver, (DWORD)IOCTL_MONO_PRINT, tmp, strlen(tmp), NULL, 0, &cbReturned, 0 ); } else { mono_print(tmp, strlen(tmp) ); } sptr = tmp; ccol = strlen(outtext[mprintf_last_line] ); dptr = &outtext[mprintf_last_line][ccol]; nrows = 0; #ifndef NDEBUG if ( Log_debug_output_to_file ) { if ( Log_fp != NULL ) { fputs(tmp, Log_fp); fflush(Log_fp); } } #endif while(*sptr) { if ( (*sptr == '\n') || (ccol >= MAX_LINE_WIDTH-1 ) ) { nrows++; mprintf_last_line++; if (mprintf_last_line >= SCROLL_BUFFER_SIZE ) mprintf_last_line = 0; ccol = 0; if ( *sptr != '\n' ) { outtext[mprintf_last_line][ccol] = *sptr; ccol++; } outtext[mprintf_last_line][ccol] = '\0'; dptr = &outtext[mprintf_last_line][ccol]; } else { *dptr++ = *sptr; *dptr = '\0'; ccol++; } sptr++; } if(gr_screen.mode == GR_DIRECT3D){ return; } // if ( D3D_enabled ) { // return; // Direct3D seems to hang sometimes printing to window // } if ( outwnd_disabled ){ return; } if ( !OutputActive ) { int oldpos = GetScrollPos( hOutputWnd, SB_VERT ); if ( oldpos != max_scroll_pos ) { SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_POS; si.nPos = max_scroll_pos; SetScrollInfo(hOutputWnd, SB_VERT, &si, 1 ); InvalidateRect(hOutputWnd,NULL,0); UpdateWindow(hOutputWnd); } else { if ( nrows ) { RECT client; ScrollWindow(hOutputWnd,0,-nTextHeight*nrows,NULL,NULL); GetClientRect(hOutputWnd, &client); client.top = client.bottom - nTextHeight*(nrows+1); InvalidateRect(hOutputWnd,&client,0); UpdateWindow(hOutputWnd); } else { Outwnd_changed++; } } } } LRESULT CALLBACK outwnd_handler(HWND hwnd,UINT msg,WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_ACTIVATEAPP: // The application z-ordering has change // foreground application wParm will be OutputActive = (BOOL)wParam; break; case WM_CREATE: { SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_RANGE | SIF_POS; si.nMin = 0; si.nMax = max_scroll_pos; si.nPos = max_scroll_pos; SetScrollInfo(hwnd, SB_VERT, &si, 1 ); } break; case WM_TIMER: if (scroll_wait) PostMessage(hwnd, WM_MOUSEMOVE, 0, last_mousemove); if ( Outwnd_changed ) { RECT client; GetClientRect(hOutputWnd, &client); client.top = client.bottom - nTextHeight; InvalidateRect(hOutputWnd,&client,0); } scroll_wait = 0; break; case WM_COMMAND: { int z; z = LOWORD(wParam); if (z >= ID_FILTER && z < ID_FILTER + outwnd_filter_count) { z -= ID_FILTER; outwnd_filter[z]->state = !outwnd_filter[z]->state; if ( !stricmp( outwnd_filter[z]->name, "error" ) ) { outwnd_filter[z]->state = 1; } else if ( !stricmp( outwnd_filter[z]->name, "general" ) ) { outwnd_filter[z]->state = 1; } else if ( !stricmp( outwnd_filter[z]->name, "warning" ) ) { outwnd_filter[z]->state = 1; } save_filter_info(); break; } switch (z) { case ID_COPY: outwnd_copy_marked_selection(hwnd); break; /* case ID_FIND: if (DialogBox(GetModuleHandle(NULL), "FIND_DIALOG", hOutputWnd, (int (__stdcall *)(void)) find_dlg_handler) == IDOK) { find_text_in_outwindow(mprintf_last_line, 0); } break; */ } break; } case WM_RBUTTONDOWN: { HMENU h_menu = CreatePopupMenu(); HMENU h_sub_menu = CreatePopupMenu(); POINT pt; int i; for (i=0; i<outwnd_filter_count; i++) { UINT flags = MFT_STRING; //MF_GRAYED; if ( !stricmp( outwnd_filter[i]->name, "error" ) ) { flags |= MF_GRAYED; } else if ( !stricmp( outwnd_filter[i]->name, "general" ) ) { flags |= MF_GRAYED; } else if ( !stricmp( outwnd_filter[i]->name, "warning" ) ) { flags |= MF_GRAYED; } if (outwnd_filter[i]->state) AppendMenu(h_sub_menu, flags | MF_CHECKED, ID_FILTER + i, outwnd_filter[i]->name); else AppendMenu(h_sub_menu, flags, ID_FILTER + i, outwnd_filter[i]->name); } AppendMenu(h_menu, MFT_STRING, ID_COPY, "&Copy\tEnter"); AppendMenu(h_menu, MFT_STRING, ID_FIND, "&Find Text"); AppendMenu(h_menu, MF_POPUP, (unsigned int) h_sub_menu, "Filter &Messages"); pt.x = LOWORD(lParam); pt.y = HIWORD(lParam); ClientToScreen(hwnd, &pt); TrackPopupMenu(h_menu, 0, pt.x, pt.y, 0, hwnd, NULL); DestroyMenu(h_menu); break; } case WM_LBUTTONDOWN: fix_marking_coords(marking_started_x, marking_started_y, lParam); SetCapture(hwnd); // monopolize mouse marking_active = 1; outwnd_update_marking(lParam, hwnd); break; case WM_MOUSEMOVE: last_mousemove = lParam; if (marking_active){ outwnd_update_marking(lParam, hwnd); } break; case WM_LBUTTONUP: if (marking_active) { ReleaseCapture(); marking_active = 0; outwnd_update_marking(lParam, hwnd); } break; case WM_VSCROLL: { SCROLLINFO si; int vpos = GetScrollPos( hwnd, SB_VERT ); int old_vpos=vpos; switch (LOWORD(wParam)) { case SB_LINEDOWN: vpos++; break; case SB_LINEUP: vpos--; break; case SB_THUMBPOSITION: vpos = HIWORD(wParam); break; case SB_THUMBTRACK: vpos = HIWORD(wParam); break; case SB_PAGEDOWN: vpos += nCharRows; break; case SB_PAGEUP: vpos -= nCharRows; break; } if ( vpos < 0 ) vpos = 0; else if ( vpos > max_scroll_pos ) vpos = max_scroll_pos; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_POS; si.nPos = vpos; SetScrollInfo(hwnd, SB_VERT, &si, 1 ); ScrollWindow(hwnd,0,(old_vpos-vpos)*nTextHeight,NULL,NULL); UpdateWindow(hOutputWnd); //InvalidateRect(hOutputWnd,NULL,0); } break; case WM_KEYDOWN: { SCROLLINFO si; int vpos = GetScrollPos( hwnd, SB_VERT ); int old_vpos=vpos; int nVirtKey = (int) wParam; // virtual-key code switch(nVirtKey) { case VK_DOWN: case VK_RIGHT: vpos++; break; case VK_UP: case VK_LEFT: vpos--; break; case VK_NEXT: vpos += nCharRows; break; case VK_PRIOR: vpos -= nCharRows; break; case VK_END: vpos = 0; break; case VK_HOME: vpos = max_scroll_pos; break; case VK_RETURN: outwnd_copy_marked_selection(hwnd); break; case UP_FAST: // special value we define vpos -= 5; break; case DOWN_FAST: // special value we define vpos += 5; break; } if ( vpos < 0 ) vpos = 0; else if ( vpos > max_scroll_pos ) vpos = max_scroll_pos; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_POS; si.nPos = vpos; SetScrollInfo(hwnd, SB_VERT, &si, 1 ); ScrollWindow(hwnd, 0, (old_vpos-vpos)*nTextHeight, NULL, NULL); UpdateWindow(hOutputWnd); //InvalidateRect(hOutputWnd,NULL,0); } break; case WM_SIZE: InvalidateRect(hOutputWnd,NULL,0); break; case WM_PAINT: outwnd_paint(hwnd); break; case WM_DESTROY: outwnd_disabled = 1; PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); break; } return 0; } void outwnd_copy_marked_selection(HWND hwnd) { HGLOBAL h_text; int i, size = 1; char *ptr; if (marked_top == marked_bottom) { size += marked_right - marked_left; } else { i = marked_top; size += strlen(outtext[i++]) - marked_left + 2; while (i < marked_bottom) size += strlen(outtext[i++]) + 2; size += marked_right; } h_text = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size); ptr = (char *) GlobalLock(h_text); if (marked_top == marked_bottom) { i = marked_right - marked_left; memcpy(ptr, outtext[marked_top] + marked_left, i); ptr[i] = 0; } else { i = marked_top; strcpy(ptr, outtext[i] + marked_left); strcat(ptr, "\r\n"); i++; while (i < marked_bottom) { strcat(ptr, outtext[i++]); strcat(ptr, "\r\n"); } ptr[strlen(ptr) + marked_right] = 0; strncat(ptr, outtext[i], marked_right); } GlobalUnlock(h_text); OpenClipboard(hwnd); EmptyClipboard(); SetClipboardData(CF_TEXT, h_text); CloseClipboard(); marked = 0; InvalidateRect(hwnd, NULL, 0); } void outwnd_paint(HWND hwnd) { int i, n, x, y, len; int old_nrows, scroll_pos; HDC hdc; PAINTSTRUCT ps; RECT client; TEXTMETRIC tm; HFONT newfont, oldfont; HBRUSH newbrush, oldbrush; Outwnd_changed = 0; hdc = BeginPaint(hwnd, &ps); GetClientRect(hOutputWnd, &client); newfont = (HFONT)GetStockObject(ANSI_FIXED_FONT); oldfont = (HFONT)SelectObject(hdc,newfont); GetTextMetrics(hdc, &tm); nTextHeight = tm.tmHeight + tm.tmExternalLeading; nTextWidth = tm.tmAveCharWidth; old_nrows = nCharRows; nCharRows = ((client.bottom-client.top)/nTextHeight)+1; newbrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW)); oldbrush = (HBRUSH)SelectObject(hdc,newbrush); y = client.bottom - nTextHeight * nCharRows; // starting y position at top client_top_yoffset = y - nTextHeight; scroll_pos = (max_scroll_pos - GetScrollPos( hOutputWnd, SB_VERT )); cur_line_index = x = mprintf_last_line - scroll_pos - nCharRows; if (x >= marked_top && x < marked_bottom) // starting in marked area text_hilight(hdc); else text_normal(hdc); if (scroll_pos != old_scroll_pos) { if (!scroll_pos) { char tmp[1024]; sprintf( tmp, "Debug Spew"); SetWindowText( hOutputWnd, tmp ); } else { char tmp[1024]; sprintf( tmp, "Debug Spew [Scrolled back %d lines]", scroll_pos ); SetWindowText( hOutputWnd, tmp ); } old_scroll_pos = scroll_pos; } i = nCharRows; while (i--) { n = mprintf_last_line - scroll_pos - i; if (n < 0) n += SCROLL_BUFFER_SIZE; if (n >= 0 && n < SCROLL_BUFFER_SIZE) { len = strlen(outtext[n]); if (marked) { if (n == marked_top && n == marked_bottom) // special 1 line case { if (marked_left) TextOut(hdc, 0, y, outtext[n], marked_left); text_hilight(hdc); x = marked_left * nTextWidth; TextOut(hdc, x, y, outtext[n] + marked_left, marked_right - marked_left); text_normal(hdc); x = marked_right * nTextWidth; if (marked_right < len) TextOut(hdc, x, y, outtext[n] + marked_right, len - marked_right); x = len * nTextWidth; TextOut(hdc, x, y, spaces, MAX_LINE_WIDTH - len); } else if (n == marked_top) { // start marked on this line if (marked_left) TextOut(hdc, 0, y, outtext[n], marked_left); text_hilight(hdc); x = marked_left * nTextWidth; TextOut(hdc, x, y, outtext[n] + marked_left, len - marked_left); x = len * nTextWidth; if (marked_left < MAX_LINE_WIDTH) TextOut(hdc, x, y, spaces, MAX_LINE_WIDTH - marked_left); } else if (n == marked_bottom) { // end marked on this line if (marked_right) TextOut(hdc, 0, y, outtext[n], marked_right); text_normal(hdc); x = marked_right * nTextWidth; if (marked_right < len) TextOut(hdc, x, y, outtext[n] + marked_right, len - marked_right); x = len * nTextWidth; TextOut(hdc, x, y, spaces, MAX_LINE_WIDTH - len); } else { // whole line marked TextOut(hdc, 0, y, outtext[n], len); x = len * nTextWidth; TextOut(hdc, x, y, spaces, MAX_LINE_WIDTH - len); } } else { TextOut(hdc, 0, y, outtext[n], len); x = len * nTextWidth; TextOut(hdc, x, y, spaces, MAX_LINE_WIDTH - len); } } else TextOut(hdc, 0, y, spaces, MAX_LINE_WIDTH); y += nTextHeight; } text_normal(hdc); SelectObject(hdc, oldfont); SelectObject(hdc, oldbrush); DeleteObject(newbrush); if ( old_nrows != nCharRows ) { SCROLLINFO si; max_scroll_pos = SCROLL_BUFFER_SIZE-nCharRows - 1; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_RANGE; si.nMin = 0; si.nMax = max_scroll_pos; SetScrollInfo(hwnd, SB_VERT, &si, 1 ); } EndPaint(hwnd, &ps); } void outwnd_update_marking(LPARAM l_parm, HWND hwnd) { int x, y; RECT rect; if (!scroll_wait) { y = (signed short) HIWORD(l_parm); GetClientRect(hwnd, &rect); if (y < -150) { SendMessage(hwnd, WM_KEYDOWN, UP_FAST, 0); scroll_wait = 1; } else if (y < 0) { SendMessage(hwnd, WM_KEYDOWN, VK_UP, 0); scroll_wait = 1; } if (y >= rect.bottom + 150) { SendMessage(hwnd, WM_KEYDOWN, DOWN_FAST, 0); scroll_wait = 1; } else if (y >= rect.bottom) { SendMessage(hwnd, WM_KEYDOWN, VK_DOWN, 0); scroll_wait = 1; } } fix_marking_coords(x, y, l_parm); marked = 1; marked_top = marked_bottom = marking_started_y; marked_left = marking_started_x; marked_right = marking_started_x + 1; if (y < marked_top) { marked_top = y; marked_left = x; } else if (y > marked_bottom) { marked_bottom = y; marked_right = x + 1; } else { // must be single line case if (x < marked_left) marked_left = x; if (x >= marked_right) marked_right = x + 1; if (marked_left >= (signed int) strlen(outtext[y])) { marked = 0; // this isn't going to even show up return; } } if (marked_left >= (signed int) strlen(outtext[marked_top])) { marked_top++; marked_left = 0; } if (marked_right > (signed int) strlen(outtext[marked_bottom])) marked_right = strlen(outtext[marked_bottom]); if (marked && (marked_top > marked_bottom || (marked_top == marked_bottom && marked_left >= marked_right))) { char msg[1024]; sprintf(msg, "Marking limits invalid!\n" "(%d,%d) to (%d,%d)", marked_left, marked_top, marked_right, marked_bottom); MessageBox(hwnd, msg, "Error", MB_OK | MB_ICONERROR); marked = 0; } if (marked != old_marked || marked_top != old_marked_top || marked_bottom != old_marked_bottom || marked_left != old_marked_left || marked_right != old_marked_right) { old_marked = marked; old_marked_left = marked_left; old_marked_right = marked_right; old_marked_top = marked_top; old_marked_bottom = marked_bottom; InvalidateRect(hwnd, NULL, 0); } } BOOL outwnd_create(int display_under_freespace_window) { int x; WNDCLASSEX wclass; HINSTANCE hInst = GetModuleHandle(NULL); RECT rect; DWORD style; wclass.hInstance = hInst; wclass.lpszClassName = szOutputClass; wclass.lpfnWndProc = (WNDPROC) outwnd_handler; wclass.style = CS_BYTEALIGNCLIENT | CS_OWNDC; //CS_DBLCLKS | CS_PARENTDC| CS_VREDRAW | CS_HREDRAW |; wclass.cbSize = sizeof(WNDCLASSEX); wclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wclass.hCursor = LoadCursor(NULL, IDC_ARROW); wclass.lpszMenuName = NULL; //"FreeSpaceMenu"; wclass.cbClsExtra = 0; wclass.cbWndExtra = 0; wclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //(HBRUSH)NULL; if (!RegisterClassEx(&wclass)) return FALSE; if (display_under_freespace_window) { style = WS_OVERLAPPEDWINDOW;; RECT client_rect; client_rect.left = client_rect.top = 0; client_rect.right = 640; client_rect.bottom = 480; AdjustWindowRect(&client_rect,WS_CAPTION | WS_SYSMENU,FALSE); int x = (GetSystemMetrics( SM_CXSCREEN )-(client_rect.right - client_rect.left))/2; int y = 0; if ( x < 0 ) x = 0; rect.left = x; rect.top = y; rect.right = x + client_rect.right - client_rect.left - 1; rect.bottom = y + client_rect.bottom - client_rect.top - 1; if(!Is_standalone){ rect.top = rect.bottom; rect.bottom = GetSystemMetrics(SM_CYSCREEN) - TASKBAR_HEIGHT - rect.top; rect.right -= rect.left; } else { rect.left += 350; rect.right = 550; rect.bottom = 400; } } else { style = WS_OVERLAPPEDWINDOW | WS_MINIMIZE;; rect.top = rect.bottom = rect.left = rect.right = CW_USEDEFAULT; } // Create Game Window hOutputWnd = CreateWindow(szOutputClass, "Debug Spew", style, rect.left, rect.top, rect.right, rect.bottom, NULL, NULL, hInst, NULL); // Show it, but don't activate it. If you activate it, it cause problems // with fullscreen startups in main window. SetWindowPos( hOutputWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE|SWP_SHOWWINDOW ); outwnd_disabled = FALSE; SetTimer(hOutputWnd, TIMER1, 50, NULL); for (x=0; x<MAX_LINE_WIDTH; x++) spaces[x] = ' '; spaces[MAX_LINE_WIDTH] = 0; return TRUE; } DWORD outwnd_thread(int display_under_freespace_window) { MSG msg; if (!outwnd_create(display_under_freespace_window)) return 0; while (1) { if (WaitMessage()) { while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } if (outwnd_disabled) break; } return 0; } void close_mono() { // DeviceIoControl (mono_driver, (DWORD) IOCTL_MONO_CLEAR_SCREEN, NULL, 0, NULL, 0, &cbReturned, 0); if (hOutputThread) { CloseHandle(hOutputThread); hOutputThread = NULL; } if (mono_driver) { CloseHandle(mono_driver); mono_driver = NULL; } } void outwnd_init(int display_under_freespace_window) { #ifndef NMONO if (!outwnd_inited) { outwnd_inited = TRUE; hOutputThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)outwnd_thread, (LPVOID)display_under_freespace_window, 0, &OutputThreadID); //SetThreadPriority(hOutputThread, THREAD_PRIORITY_TIME_CRITICAL); // set up the monochrome drivers if ( (mono_driver = CreateFile("\\\\.\\MONO", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == ((HANDLE)-1)) { outwnd_printf2("Cannot get handle to monochrome driver.\n"); mono_init(); } atexit(close_mono); } #endif #ifndef NDEBUG if ( Log_fp == NULL ) { Log_fp = fopen(Freespace_logfilename, "wb"); } #endif } BOOL CALLBACK find_dlg_handler(HWND hwnd,UINT msg,WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: GetDlgItemText(hwnd, IDC_TEXT, find_text, 82); // get the text to find EndDialog(hwnd, IDOK); return 1; case IDCANCEL: EndDialog(hwnd, 0); return 1; } break; case WM_INITDIALOG: SendDlgItemMessage(hwnd, IDC_TEXT, EM_LIMITTEXT, 80, 0); // limit text to 80 chars if (GetDlgCtrlID((HWND) wParam) != IDC_TEXT) { SetFocus(GetDlgItem(hwnd, IDC_TEXT)); return FALSE; } return TRUE; } return 0; } void find_text_in_outwindow(int n, int p) { char *ptr, *str; str = outtext[n] + p; while (1) { ptr = strstr(str, find_text); if (ptr) { int scroll_pos, pos; find_pos = ptr - str; find_line = n; marked = 1; marked_top = marked_bottom = find_line; marked_left = find_pos; marked_right = find_pos + strlen(find_text); scroll_pos = (max_scroll_pos - GetScrollPos(hOutputWnd, SB_VERT)); pos = mprintf_last_line - scroll_pos; if (pos < 0) pos += SCROLL_BUFFER_SIZE; pos -= n; if (pos < 0) pos += SCROLL_BUFFER_SIZE; Assert(pos >= 0); if (pos >= nCharRows - 1) // outside of window viewport, so scroll { SCROLLINFO si; pos = mprintf_last_line - n - nCharRows / 2; if (pos < 0) pos += SCROLL_BUFFER_SIZE; if (pos > max_scroll_pos) pos = max_scroll_pos; scroll_pos = max_scroll_pos - GetScrollPos(hOutputWnd, SB_VERT); si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_POS; si.nPos = max_scroll_pos - pos; SetScrollInfo(hOutputWnd, SB_VERT, &si, 1); ScrollWindow(hOutputWnd, 0, (scroll_pos - pos) * nTextHeight, NULL, NULL); } InvalidateRect(hOutputWnd, NULL, 0); UpdateWindow(hOutputWnd); return; } n--; if (n < 0) n += SCROLL_BUFFER_SIZE; if (n == mprintf_last_line) { MessageBox(hOutputWnd, "Search text not found", "Find Error", MB_OK | MB_ICONERROR); find_line = -1; return; } str = outtext[n]; } } void outwnd_close() { #ifndef NDEBUG if ( Log_fp != NULL ) { fclose(Log_fp); Log_fp = NULL; } #endif } #endif //NDEBUG
23.494891
152
0.662048
[ "model" ]
6e798fce23282dbd3b4df50d95394f98c44c8585
43,280
cpp
C++
VirtualBox-5.0.0/src/VBox/Devices/PC/DevRTC.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
1
2015-04-30T14:18:45.000Z
2015-04-30T14:18:45.000Z
VirtualBox-5.0.0/src/VBox/Devices/PC/DevRTC.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
VirtualBox-5.0.0/src/VBox/Devices/PC/DevRTC.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
/* $Id: DevRTC.cpp $ */ /** @file * Motorola MC146818 RTC/CMOS Device with PIIX4 extensions. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * -------------------------------------------------------------------- * * This code is based on: * * QEMU MC146818 RTC emulation * * Copyright (c) 2003-2004 Fabrice Bellard * * 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. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_DEV_RTC #include <VBox/vmm/pdmdev.h> #include <VBox/log.h> #include <iprt/asm-math.h> #include <iprt/assert.h> #include <iprt/string.h> #ifdef IN_RING3 # include <iprt/alloc.h> # include <iprt/uuid.h> #endif /* IN_RING3 */ #include "VBoxDD.h" /******************************************************************************* * Defined Constants And Macros * *******************************************************************************/ /*#define DEBUG_CMOS*/ #define RTC_CRC_START 0x10 #define RTC_CRC_LAST 0x2d #define RTC_CRC_HIGH 0x2e #define RTC_CRC_LOW 0x2f #define RTC_SECONDS 0 #define RTC_SECONDS_ALARM 1 #define RTC_MINUTES 2 #define RTC_MINUTES_ALARM 3 #define RTC_HOURS 4 #define RTC_HOURS_ALARM 5 #define RTC_ALARM_DONT_CARE 0xC0 #define RTC_DAY_OF_WEEK 6 #define RTC_DAY_OF_MONTH 7 #define RTC_MONTH 8 #define RTC_YEAR 9 #define RTC_REG_A 10 #define RTC_REG_B 11 #define RTC_REG_C 12 #define RTC_REG_D 13 #define REG_A_UIP 0x80 #define REG_B_SET 0x80 #define REG_B_PIE 0x40 #define REG_B_AIE 0x20 #define REG_B_UIE 0x10 #define CMOS_BANK_LOWER_LIMIT 0x0E #define CMOS_BANK_UPPER_LIMIT 0x7F #define CMOS_BANK2_LOWER_LIMIT 0x80 #define CMOS_BANK2_UPPER_LIMIT 0xFF #define CMOS_BANK_SIZE 0x80 /** The saved state version. */ #define RTC_SAVED_STATE_VERSION 4 /** The saved state version used by VirtualBox pre-3.2. * This does not include the second 128-byte bank. */ #define RTC_SAVED_STATE_VERSION_VBOX_32PRE 3 /** The saved state version used by VirtualBox 3.1 and earlier. * This does not include disabled by HPET state. */ #define RTC_SAVED_STATE_VERSION_VBOX_31 2 /** The saved state version used by VirtualBox 3.0 and earlier. * This does not include the configuration. */ #define RTC_SAVED_STATE_VERSION_VBOX_30 1 /******************************************************************************* * Structures and Typedefs * *******************************************************************************/ /** @todo Replace struct my_tm with RTTIME. */ struct my_tm { int32_t tm_sec; int32_t tm_min; int32_t tm_hour; int32_t tm_mday; int32_t tm_mon; int32_t tm_year; int32_t tm_wday; int32_t tm_yday; }; typedef struct RTCSTATE { uint8_t cmos_data[256]; uint8_t cmos_index[2]; uint8_t Alignment0[6]; struct my_tm current_tm; /** The configured IRQ. */ int32_t irq; /** The configured I/O port base. */ RTIOPORT IOPortBase; /** Use UTC or local time initially. */ bool fUTC; /** Disabled by HPET legacy mode. */ bool fDisabledByHpet; /* periodic timer */ int64_t next_periodic_time; /* second update */ int64_t next_second_time; /** Pointer to the device instance - R3 Ptr. */ PPDMDEVINSR3 pDevInsR3; /** The periodic timer (rtcTimerPeriodic) - R3 Ptr. */ PTMTIMERR3 pPeriodicTimerR3; /** The second timer (rtcTimerSecond) - R3 Ptr. */ PTMTIMERR3 pSecondTimerR3; /** The second second timer (rtcTimerSecond2) - R3 Ptr. */ PTMTIMERR3 pSecondTimer2R3; /** Pointer to the device instance - R0 Ptr. */ PPDMDEVINSR0 pDevInsR0; /** The periodic timer (rtcTimerPeriodic) - R0 Ptr. */ PTMTIMERR0 pPeriodicTimerR0; /** The second timer (rtcTimerSecond) - R0 Ptr. */ PTMTIMERR0 pSecondTimerR0; /** The second second timer (rtcTimerSecond2) - R0 Ptr. */ PTMTIMERR0 pSecondTimer2R0; /** Pointer to the device instance - RC Ptr. */ PPDMDEVINSRC pDevInsRC; /** The periodic timer (rtcTimerPeriodic) - RC Ptr. */ PTMTIMERRC pPeriodicTimerRC; /** The second timer (rtcTimerSecond) - RC Ptr. */ PTMTIMERRC pSecondTimerRC; /** The second second timer (rtcTimerSecond2) - RC Ptr. */ PTMTIMERRC pSecondTimer2RC; /** The RTC registration structure. */ PDMRTCREG RtcReg; /** The RTC device helpers. */ R3PTRTYPE(PCPDMRTCHLP) pRtcHlpR3; /** Number of release log entries. Used to prevent flooding. */ uint32_t cRelLogEntries; /** The current/previous logged timer period. */ int32_t CurLogPeriod; /** The current/previous hinted timer period. */ int32_t CurHintPeriod; /** How many consecutive times the UIP has been seen. */ int32_t cUipSeen; /** HPET legacy mode notification interface. */ PDMIHPETLEGACYNOTIFY IHpetLegacyNotify; /** Number of IRQs that's been raised. */ STAMCOUNTER StatRTCIrq; /** Number of times the timer callback handler ran. */ STAMCOUNTER StatRTCTimerCB; } RTCSTATE; /** Pointer to the RTC device state. */ typedef RTCSTATE *PRTCSTATE; #ifndef VBOX_DEVICE_STRUCT_TESTCASE static void rtc_timer_update(PRTCSTATE pThis, int64_t current_time) { int period_code, period; uint64_t cur_clock, next_irq_clock; uint32_t freq; Assert(TMTimerIsLockOwner(pThis->CTX_SUFF(pPeriodicTimer))); Assert(PDMCritSectIsOwner(pThis->CTX_SUFF(pDevIns)->CTX_SUFF(pCritSectRo))); period_code = pThis->cmos_data[RTC_REG_A] & 0x0f; if ( period_code != 0 && (pThis->cmos_data[RTC_REG_B] & REG_B_PIE)) { if (period_code <= 2) period_code += 7; /* period in 32 kHz cycles */ period = 1 << (period_code - 1); /* compute 32 kHz clock */ freq = TMTimerGetFreq(pThis->CTX_SUFF(pPeriodicTimer)); cur_clock = ASMMultU64ByU32DivByU32(current_time, 32768, freq); next_irq_clock = (cur_clock & ~(uint64_t)(period - 1)) + period; pThis->next_periodic_time = ASMMultU64ByU32DivByU32(next_irq_clock, freq, 32768) + 1; TMTimerSet(pThis->CTX_SUFF(pPeriodicTimer), pThis->next_periodic_time); #ifdef IN_RING3 if (RT_UNLIKELY(period != pThis->CurLogPeriod)) #else if (RT_UNLIKELY(period != pThis->CurHintPeriod)) #endif { #ifdef IN_RING3 if (pThis->cRelLogEntries++ < 64) LogRel(("RTC: period=%#x (%d) %u Hz\n", period, period, _32K / period)); pThis->CurLogPeriod = period; #endif pThis->CurHintPeriod = period; TMTimerSetFrequencyHint(pThis->CTX_SUFF(pPeriodicTimer), _32K / period); } } else { #ifdef IN_RING3 if (TMTimerIsActive(pThis->CTX_SUFF(pPeriodicTimer)) && pThis->cRelLogEntries++ < 64) LogRel(("RTC: stopped the periodic timer\n")); #endif TMTimerStop(pThis->CTX_SUFF(pPeriodicTimer)); } } static void rtc_raise_irq(PRTCSTATE pThis, uint32_t iLevel) { if (!pThis->fDisabledByHpet) { PDMDevHlpISASetIrq(pThis->CTX_SUFF(pDevIns), pThis->irq, iLevel); if (iLevel) STAM_COUNTER_INC(&pThis->StatRTCIrq); } } DECLINLINE(int) to_bcd(PRTCSTATE pThis, int a) { if (pThis->cmos_data[RTC_REG_B] & 0x04) return a; return ((a / 10) << 4) | (a % 10); } DECLINLINE(int) from_bcd(PRTCSTATE pThis, int a) { if (pThis->cmos_data[RTC_REG_B] & 0x04) return a; return ((a >> 4) * 10) + (a & 0x0f); } static void rtc_set_time(PRTCSTATE pThis) { struct my_tm *tm = &pThis->current_tm; tm->tm_sec = from_bcd(pThis, pThis->cmos_data[RTC_SECONDS]); tm->tm_min = from_bcd(pThis, pThis->cmos_data[RTC_MINUTES]); tm->tm_hour = from_bcd(pThis, pThis->cmos_data[RTC_HOURS] & 0x7f); if (!(pThis->cmos_data[RTC_REG_B] & 0x02)) { tm->tm_hour %= 12; if (pThis->cmos_data[RTC_HOURS] & 0x80) tm->tm_hour += 12; } tm->tm_wday = from_bcd(pThis, pThis->cmos_data[RTC_DAY_OF_WEEK]); tm->tm_mday = from_bcd(pThis, pThis->cmos_data[RTC_DAY_OF_MONTH]); tm->tm_mon = from_bcd(pThis, pThis->cmos_data[RTC_MONTH]) - 1; tm->tm_year = from_bcd(pThis, pThis->cmos_data[RTC_YEAR]) + 100; } /* -=-=-=-=-=- I/O Port Handlers -=-=-=-=-=- */ /** * @callback_method_impl{FNIOMIOPORTIN} */ PDMBOTHCBDECL(int) rtcIOPortRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb) { NOREF(pvUser); if (cb != 1) return VERR_IOM_IOPORT_UNUSED; PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); if ((Port & 1) == 0) *pu32 = 0xff; else { unsigned bank = (Port >> 1) & 1; switch (pThis->cmos_index[bank]) { case RTC_SECONDS: case RTC_MINUTES: case RTC_HOURS: case RTC_DAY_OF_WEEK: case RTC_DAY_OF_MONTH: case RTC_MONTH: case RTC_YEAR: *pu32 = pThis->cmos_data[pThis->cmos_index[0]]; break; case RTC_REG_A: if (pThis->cmos_data[RTC_REG_A] & REG_A_UIP) ++pThis->cUipSeen; else pThis->cUipSeen = 0; if (pThis->cUipSeen >= 250) { pThis->cmos_data[pThis->cmos_index[0]] &= ~REG_A_UIP; pThis->cUipSeen = 0; } *pu32 = pThis->cmos_data[pThis->cmos_index[0]]; break; case RTC_REG_C: *pu32 = pThis->cmos_data[pThis->cmos_index[0]]; rtc_raise_irq(pThis, 0); pThis->cmos_data[RTC_REG_C] = 0x00; break; default: *pu32 = pThis->cmos_data[pThis->cmos_index[bank]]; break; } Log(("CMOS: Read bank %d idx %#04x: %#04x\n", bank, pThis->cmos_index[bank], *pu32)); } return VINF_SUCCESS; } /** * @callback_method_impl{FNIOMIOPORTOUT} */ PDMBOTHCBDECL(int) rtcIOPortWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb) { NOREF(pvUser); if (cb != 1) return VINF_SUCCESS; PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); uint32_t bank = (Port >> 1) & 1; if ((Port & 1) == 0) { pThis->cmos_index[bank] = (u32 & 0x7f) + (bank * CMOS_BANK_SIZE); /* HACK ALERT! Attempt to trigger VM_FF_TIMER and/or VM_FF_TM_VIRTUAL_SYNC for forcing the pSecondTimer2 timer to run be run and clear UIP in a timely fashion. */ if (u32 == RTC_REG_A) TMTimerGet(pThis->CTX_SUFF(pSecondTimer)); } else { Log(("CMOS: Write bank %d idx %#04x: %#04x (old %#04x)\n", bank, pThis->cmos_index[bank], u32, pThis->cmos_data[pThis->cmos_index[bank]])); int const idx = pThis->cmos_index[bank]; switch (idx) { case RTC_SECONDS_ALARM: case RTC_MINUTES_ALARM: case RTC_HOURS_ALARM: pThis->cmos_data[pThis->cmos_index[0]] = u32; break; case RTC_SECONDS: case RTC_MINUTES: case RTC_HOURS: case RTC_DAY_OF_WEEK: case RTC_DAY_OF_MONTH: case RTC_MONTH: case RTC_YEAR: pThis->cmos_data[pThis->cmos_index[0]] = u32; /* if in set mode, do not update the time */ if (!(pThis->cmos_data[RTC_REG_B] & REG_B_SET)) rtc_set_time(pThis); break; case RTC_REG_A: case RTC_REG_B: { /* We need to acquire the clock lock, because of lock ordering issues this means having to release the device lock. Since we're letting IOM do the locking, we must not return without holding the device lock.*/ PDMCritSectLeave(pThis->CTX_SUFF(pDevIns)->CTX_SUFF(pCritSectRo)); int rc1 = TMTimerLock(pThis->CTX_SUFF(pPeriodicTimer), VINF_SUCCESS /* must get it */); int rc2 = PDMCritSectEnter(pThis->CTX_SUFF(pDevIns)->CTX_SUFF(pCritSectRo), VINF_SUCCESS /* must get it */); AssertRCReturn(rc1, rc1); AssertRCReturnStmt(rc2, TMTimerUnlock(pThis->CTX_SUFF(pPeriodicTimer)), rc2); if (idx == RTC_REG_A) { /* UIP bit is read only */ pThis->cmos_data[RTC_REG_A] = (u32 & ~REG_A_UIP) | (pThis->cmos_data[RTC_REG_A] & REG_A_UIP); } else { if (u32 & REG_B_SET) { /* set mode: reset UIP mode */ pThis->cmos_data[RTC_REG_A] &= ~REG_A_UIP; #if 0 /* This is probably wrong as it breaks changing the time/date in OS/2. */ u32 &= ~REG_B_UIE; #endif } else { /* if disabling set mode, update the time */ if (pThis->cmos_data[RTC_REG_B] & REG_B_SET) rtc_set_time(pThis); } pThis->cmos_data[RTC_REG_B] = u32; } rtc_timer_update(pThis, TMTimerGet(pThis->CTX_SUFF(pPeriodicTimer))); TMTimerUnlock(pThis->CTX_SUFF(pPeriodicTimer)); /* the caller leaves the other lock. */ break; } case RTC_REG_C: case RTC_REG_D: /* cannot write to them */ break; default: pThis->cmos_data[pThis->cmos_index[bank]] = u32; break; } } return VINF_SUCCESS; } #ifdef IN_RING3 /* -=-=-=-=-=- Debug Info Handlers -=-=-=-=-=- */ /** * @callback_method_impl{FNDBGFHANDLERDEV, * Dumps the cmos Bank Info.} */ static DECLCALLBACK(void) rtcCmosBankInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); pHlp->pfnPrintf(pHlp, "First CMOS bank, offsets 0x0E - 0x7F\n" "Offset %02x : --- use 'info rtc' to show CMOS clock ---", 0); for (unsigned iCmos = CMOS_BANK_LOWER_LIMIT; iCmos <= CMOS_BANK_UPPER_LIMIT; iCmos++) { if ((iCmos & 15) == 0) pHlp->pfnPrintf(pHlp, "Offset %02x : %02x", iCmos, pThis->cmos_data[iCmos]); else if ((iCmos & 15) == 8) pHlp->pfnPrintf(pHlp, "-%02x", pThis->cmos_data[iCmos]); else if ((iCmos & 15) == 15) pHlp->pfnPrintf(pHlp, " %02x\n", pThis->cmos_data[iCmos]); else pHlp->pfnPrintf(pHlp, " %02x", pThis->cmos_data[iCmos]); } } /** * @callback_method_impl{FNDBGFHANDLERDEV, * Dumps the cmos Bank2 Info.} */ static DECLCALLBACK(void) rtcCmosBank2Info(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); pHlp->pfnPrintf(pHlp, "Second CMOS bank, offsets 0x80 - 0xFF\n"); for (uint16_t iCmos = CMOS_BANK2_LOWER_LIMIT; iCmos <= CMOS_BANK2_UPPER_LIMIT; iCmos++) { if ((iCmos & 15) == 0) pHlp->pfnPrintf(pHlp, "Offset %02x : %02x", iCmos, pThis->cmos_data[iCmos]); else if ((iCmos & 15) == 8) pHlp->pfnPrintf(pHlp, "-%02x", pThis->cmos_data[iCmos]); else if ((iCmos & 15) == 15) pHlp->pfnPrintf(pHlp, " %02x\n", pThis->cmos_data[iCmos]); else pHlp->pfnPrintf(pHlp, " %02x", pThis->cmos_data[iCmos]); } } /** * @callback_method_impl{FNDBGFHANDLERDEV, * Dumps the cmos RTC Info.} */ static DECLCALLBACK(void) rtcCmosClockInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); uint8_t u8Sec = from_bcd(pThis, pThis->cmos_data[RTC_SECONDS]); uint8_t u8Min = from_bcd(pThis, pThis->cmos_data[RTC_MINUTES]); uint8_t u8Hr = from_bcd(pThis, pThis->cmos_data[RTC_HOURS] & 0x7f); if ( !(pThis->cmos_data[RTC_REG_B] & 0x02) && (pThis->cmos_data[RTC_HOURS] & 0x80)) u8Hr += 12; uint8_t u8Day = from_bcd(pThis, pThis->cmos_data[RTC_DAY_OF_MONTH]); uint8_t u8Month = from_bcd(pThis, pThis->cmos_data[RTC_MONTH]) ; uint8_t u8Year = from_bcd(pThis, pThis->cmos_data[RTC_YEAR]); pHlp->pfnPrintf(pHlp, "Time: %02u:%02u:%02u Date: %02u-%02u-%02u\n", u8Hr, u8Min, u8Sec, u8Year, u8Month, u8Day); pHlp->pfnPrintf(pHlp, "REG A=%02x B=%02x C=%02x D=%02x\n", pThis->cmos_data[RTC_REG_A], pThis->cmos_data[RTC_REG_B], pThis->cmos_data[RTC_REG_C], pThis->cmos_data[RTC_REG_D]); } /* -=-=-=-=-=- Timers and their support code -=-=-=-=-=- */ /** * @callback_method_impl{FNTMTIMERDEV, periodic} */ static DECLCALLBACK(void) rtcTimerPeriodic(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); Assert(TMTimerIsLockOwner(pThis->CTX_SUFF(pPeriodicTimer))); Assert(PDMCritSectIsOwner(pThis->CTX_SUFF(pDevIns)->CTX_SUFF(pCritSectRo))); rtc_timer_update(pThis, pThis->next_periodic_time); STAM_COUNTER_INC(&pThis->StatRTCTimerCB); pThis->cmos_data[RTC_REG_C] |= 0xc0; rtc_raise_irq(pThis, 1); } /* month is between 0 and 11. */ static int get_days_in_month(int month, int year) { static const int days_tab[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int d; if ((unsigned )month >= 12) return 31; d = days_tab[month]; if (month == 1) { if ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0)) d++; } return d; } /* update 'tm' to the next second */ static void rtc_next_second(struct my_tm *tm) { int days_in_month; tm->tm_sec++; if ((unsigned)tm->tm_sec >= 60) { tm->tm_sec = 0; tm->tm_min++; if ((unsigned)tm->tm_min >= 60) { tm->tm_min = 0; tm->tm_hour++; if ((unsigned)tm->tm_hour >= 24) { tm->tm_hour = 0; /* next day */ tm->tm_wday++; if ((unsigned)tm->tm_wday >= 7) tm->tm_wday = 0; days_in_month = get_days_in_month(tm->tm_mon, tm->tm_year + 1900); tm->tm_mday++; if (tm->tm_mday < 1) tm->tm_mday = 1; else if (tm->tm_mday > days_in_month) { tm->tm_mday = 1; tm->tm_mon++; if (tm->tm_mon >= 12) { tm->tm_mon = 0; tm->tm_year++; } } } } } } /** * @callback_method_impl{FNTMTIMERDEV, Second timer.} */ static DECLCALLBACK(void) rtcTimerSecond(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); Assert(TMTimerIsLockOwner(pThis->CTX_SUFF(pPeriodicTimer))); Assert(PDMCritSectIsOwner(pThis->CTX_SUFF(pDevIns)->CTX_SUFF(pCritSectRo))); /* if the oscillator is not in normal operation, we do not update */ if ((pThis->cmos_data[RTC_REG_A] & 0x70) != 0x20) { pThis->next_second_time += TMTimerGetFreq(pThis->CTX_SUFF(pSecondTimer)); TMTimerSet(pThis->CTX_SUFF(pSecondTimer), pThis->next_second_time); } else { rtc_next_second(&pThis->current_tm); if (!(pThis->cmos_data[RTC_REG_B] & REG_B_SET)) { /* update in progress bit */ Log2(("RTC: UIP %x -> 1\n", !!(pThis->cmos_data[RTC_REG_A] & REG_A_UIP))); pThis->cmos_data[RTC_REG_A] |= REG_A_UIP; } /* 244140 ns = 8 / 32768 seconds */ uint64_t delay = TMTimerFromNano(pThis->CTX_SUFF(pSecondTimer2), 244140); TMTimerSet(pThis->CTX_SUFF(pSecondTimer2), pThis->next_second_time + delay); } } /* Used by rtc_set_date and rtcTimerSecond2. */ static void rtc_copy_date(PRTCSTATE pThis) { const struct my_tm *tm = &pThis->current_tm; pThis->cmos_data[RTC_SECONDS] = to_bcd(pThis, tm->tm_sec); pThis->cmos_data[RTC_MINUTES] = to_bcd(pThis, tm->tm_min); if (pThis->cmos_data[RTC_REG_B] & 0x02) { /* 24 hour format */ pThis->cmos_data[RTC_HOURS] = to_bcd(pThis, tm->tm_hour); } else { /* 12 hour format */ int h = tm->tm_hour % 12; pThis->cmos_data[RTC_HOURS] = to_bcd(pThis, h ? h : 12); if (tm->tm_hour >= 12) pThis->cmos_data[RTC_HOURS] |= 0x80; } pThis->cmos_data[RTC_DAY_OF_WEEK] = to_bcd(pThis, tm->tm_wday); pThis->cmos_data[RTC_DAY_OF_MONTH] = to_bcd(pThis, tm->tm_mday); pThis->cmos_data[RTC_MONTH] = to_bcd(pThis, tm->tm_mon + 1); pThis->cmos_data[RTC_YEAR] = to_bcd(pThis, tm->tm_year % 100); } /** * @callback_method_impl{FNTMTIMERDEV, Second2 timer.} */ static DECLCALLBACK(void) rtcTimerSecond2(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); Assert(TMTimerIsLockOwner(pThis->CTX_SUFF(pPeriodicTimer))); Assert(PDMCritSectIsOwner(pThis->CTX_SUFF(pDevIns)->CTX_SUFF(pCritSectRo))); if (!(pThis->cmos_data[RTC_REG_B] & REG_B_SET)) rtc_copy_date(pThis); /* check alarm */ if (pThis->cmos_data[RTC_REG_B] & REG_B_AIE) { if ( ( (pThis->cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0 || from_bcd(pThis, pThis->cmos_data[RTC_SECONDS_ALARM]) == pThis->current_tm.tm_sec) && ( (pThis->cmos_data[RTC_MINUTES_ALARM] & 0xc0) == 0xc0 || from_bcd(pThis, pThis->cmos_data[RTC_MINUTES_ALARM]) == pThis->current_tm.tm_min) && ( (pThis->cmos_data[RTC_HOURS_ALARM ] & 0xc0) == 0xc0 || from_bcd(pThis, pThis->cmos_data[RTC_HOURS_ALARM ]) == pThis->current_tm.tm_hour) ) { pThis->cmos_data[RTC_REG_C] |= 0xa0; rtc_raise_irq(pThis, 1); } } /* update ended interrupt */ if (pThis->cmos_data[RTC_REG_B] & REG_B_UIE) { pThis->cmos_data[RTC_REG_C] |= 0x90; rtc_raise_irq(pThis, 1); } /* clear update in progress bit */ Log2(("RTC: UIP %x -> 0\n", !!(pThis->cmos_data[RTC_REG_A] & REG_A_UIP))); pThis->cmos_data[RTC_REG_A] &= ~REG_A_UIP; pThis->next_second_time += TMTimerGetFreq(pThis->CTX_SUFF(pSecondTimer)); TMTimerSet(pThis->CTX_SUFF(pSecondTimer), pThis->next_second_time); } /* -=-=-=-=-=- Saved State -=-=-=-=-=- */ /** * @callback_method_impl{FNSSMDEVLIVEEXEC} */ static DECLCALLBACK(int) rtcLiveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uPass) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); SSMR3PutU8( pSSM, pThis->irq); SSMR3PutIOPort(pSSM, pThis->IOPortBase); SSMR3PutBool( pSSM, pThis->fUTC); return VINF_SSM_DONT_CALL_AGAIN; } /** * @callback_method_impl{FNSSMDEVSAVEEXEC} */ static DECLCALLBACK(int) rtcSaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); /* The config. */ rtcLiveExec(pDevIns, pSSM, SSM_PASS_FINAL); /* The state. */ SSMR3PutMem(pSSM, pThis->cmos_data, CMOS_BANK_SIZE); SSMR3PutU8(pSSM, pThis->cmos_index[0]); SSMR3PutS32(pSSM, pThis->current_tm.tm_sec); SSMR3PutS32(pSSM, pThis->current_tm.tm_min); SSMR3PutS32(pSSM, pThis->current_tm.tm_hour); SSMR3PutS32(pSSM, pThis->current_tm.tm_wday); SSMR3PutS32(pSSM, pThis->current_tm.tm_mday); SSMR3PutS32(pSSM, pThis->current_tm.tm_mon); SSMR3PutS32(pSSM, pThis->current_tm.tm_year); TMR3TimerSave(pThis->CTX_SUFF(pPeriodicTimer), pSSM); SSMR3PutS64(pSSM, pThis->next_periodic_time); SSMR3PutS64(pSSM, pThis->next_second_time); TMR3TimerSave(pThis->CTX_SUFF(pSecondTimer), pSSM); TMR3TimerSave(pThis->CTX_SUFF(pSecondTimer2), pSSM); SSMR3PutBool(pSSM, pThis->fDisabledByHpet); SSMR3PutMem(pSSM, &pThis->cmos_data[CMOS_BANK_SIZE], CMOS_BANK_SIZE); return SSMR3PutU8(pSSM, pThis->cmos_index[1]); } /** * @callback_method_impl{FNSSMDEVLOADEXEC} */ static DECLCALLBACK(int) rtcLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); int rc; if ( uVersion != RTC_SAVED_STATE_VERSION && uVersion != RTC_SAVED_STATE_VERSION_VBOX_32PRE && uVersion != RTC_SAVED_STATE_VERSION_VBOX_31 && uVersion != RTC_SAVED_STATE_VERSION_VBOX_30) return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION; /* The config. */ if (uVersion > RTC_SAVED_STATE_VERSION_VBOX_30) { uint8_t u8Irq; rc = SSMR3GetU8(pSSM, &u8Irq); AssertRCReturn(rc, rc); if (u8Irq != pThis->irq) return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - u8Irq: saved=%#x config=%#x"), u8Irq, pThis->irq); RTIOPORT IOPortBase; rc = SSMR3GetIOPort(pSSM, &IOPortBase); AssertRCReturn(rc, rc); if (IOPortBase != pThis->IOPortBase) return SSMR3SetCfgError(pSSM, RT_SRC_POS, N_("Config mismatch - IOPortBase: saved=%RTiop config=%RTiop"), IOPortBase, pThis->IOPortBase); bool fUTC; rc = SSMR3GetBool(pSSM, &fUTC); AssertRCReturn(rc, rc); if (fUTC != pThis->fUTC) LogRel(("RTC: Config mismatch - fUTC: saved=%RTbool config=%RTbool\n", fUTC, pThis->fUTC)); } if (uPass != SSM_PASS_FINAL) return VINF_SUCCESS; /* The state. */ SSMR3GetMem(pSSM, pThis->cmos_data, CMOS_BANK_SIZE); SSMR3GetU8(pSSM, &pThis->cmos_index[0]); SSMR3GetS32(pSSM, &pThis->current_tm.tm_sec); SSMR3GetS32(pSSM, &pThis->current_tm.tm_min); SSMR3GetS32(pSSM, &pThis->current_tm.tm_hour); SSMR3GetS32(pSSM, &pThis->current_tm.tm_wday); SSMR3GetS32(pSSM, &pThis->current_tm.tm_mday); SSMR3GetS32(pSSM, &pThis->current_tm.tm_mon); SSMR3GetS32(pSSM, &pThis->current_tm.tm_year); TMR3TimerLoad(pThis->CTX_SUFF(pPeriodicTimer), pSSM); SSMR3GetS64(pSSM, &pThis->next_periodic_time); SSMR3GetS64(pSSM, &pThis->next_second_time); TMR3TimerLoad(pThis->CTX_SUFF(pSecondTimer), pSSM); TMR3TimerLoad(pThis->CTX_SUFF(pSecondTimer2), pSSM); if (uVersion > RTC_SAVED_STATE_VERSION_VBOX_31) SSMR3GetBool(pSSM, &pThis->fDisabledByHpet); if (uVersion > RTC_SAVED_STATE_VERSION_VBOX_32PRE) { /* Second CMOS bank. */ SSMR3GetMem(pSSM, &pThis->cmos_data[CMOS_BANK_SIZE], CMOS_BANK_SIZE); SSMR3GetU8(pSSM, &pThis->cmos_index[1]); } int period_code = pThis->cmos_data[RTC_REG_A] & 0x0f; if ( period_code != 0 && (pThis->cmos_data[RTC_REG_B] & REG_B_PIE)) { if (period_code <= 2) period_code += 7; int period = 1 << (period_code - 1); LogRel(("RTC: period=%#x (%d) %u Hz (restore)\n", period, period, _32K / period)); PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VINF_SUCCESS); TMTimerSetFrequencyHint(pThis->CTX_SUFF(pPeriodicTimer), _32K / period); PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3); pThis->CurLogPeriod = period; pThis->CurHintPeriod = period; } else { LogRel(("RTC: stopped the periodic timer (restore)\n")); pThis->CurLogPeriod = 0; pThis->CurHintPeriod = 0; } pThis->cRelLogEntries = 0; return VINF_SUCCESS; } /* -=-=-=-=-=- PDM Interface provided by the RTC device -=-=-=-=-=- */ /** * Calculate and update the standard CMOS checksum. * * @param pThis Pointer to the RTC state data. */ static void rtcCalcCRC(PRTCSTATE pThis) { uint16_t u16 = 0; for (unsigned i = RTC_CRC_START; i <= RTC_CRC_LAST; i++) u16 += pThis->cmos_data[i]; pThis->cmos_data[RTC_CRC_LOW] = u16 & 0xff; pThis->cmos_data[RTC_CRC_HIGH] = (u16 >> 8) & 0xff; } /** * @interface_method_impl{PDMRTCREG,pfnWrite} */ static DECLCALLBACK(int) rtcCMOSWrite(PPDMDEVINS pDevIns, unsigned iReg, uint8_t u8Value) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); Assert(PDMCritSectIsOwner(pDevIns->pCritSectRoR3)); if (iReg < RT_ELEMENTS(pThis->cmos_data)) { pThis->cmos_data[iReg] = u8Value; /* does it require checksum update? */ if ( iReg >= RTC_CRC_START && iReg <= RTC_CRC_LAST) rtcCalcCRC(pThis); return VINF_SUCCESS; } AssertMsgFailed(("iReg=%d\n", iReg)); return VERR_INVALID_PARAMETER; } /** * @interface_method_impl{PDMRTCREG,pfnRead} */ static DECLCALLBACK(int) rtcCMOSRead(PPDMDEVINS pDevIns, unsigned iReg, uint8_t *pu8Value) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); Assert(PDMCritSectIsOwner(pDevIns->pCritSectRoR3)); if (iReg < RT_ELEMENTS(pThis->cmos_data)) { *pu8Value = pThis->cmos_data[iReg]; return VINF_SUCCESS; } AssertMsgFailed(("iReg=%d\n", iReg)); return VERR_INVALID_PARAMETER; } /** * @interface_method_impl{PDMIHPETLEGACYNOTIFY,pfnModeChanged} */ static DECLCALLBACK(void) rtcHpetLegacyNotify_ModeChanged(PPDMIHPETLEGACYNOTIFY pInterface, bool fActivated) { PRTCSTATE pThis = RT_FROM_MEMBER(pInterface, RTCSTATE, IHpetLegacyNotify); PDMCritSectEnter(pThis->pDevInsR3->pCritSectRoR3, VERR_IGNORED); pThis->fDisabledByHpet = fActivated; PDMCritSectLeave(pThis->pDevInsR3->pCritSectRoR3); } /* -=-=-=-=-=- IBase -=-=-=-=-=- */ /** * @interface_method_impl{PDMIBASE,pfnQueryInterface} */ static DECLCALLBACK(void *) rtcQueryInterface(PPDMIBASE pInterface, const char *pszIID) { PPDMDEVINS pDevIns = RT_FROM_MEMBER(pInterface, PDMDEVINS, IBase); PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDevIns->IBase); PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHPETLEGACYNOTIFY, &pThis->IHpetLegacyNotify); return NULL; } /* -=-=-=-=-=- PDMDEVREG -=-=-=-=-=- */ static void rtc_set_memory(PRTCSTATE pThis, int addr, int val) { if (addr >= 0 && addr <= 127) pThis->cmos_data[addr] = val; } static void rtc_set_date(PRTCSTATE pThis, const struct my_tm *tm) { pThis->current_tm = *tm; rtc_copy_date(pThis); } /** * @interface_method_impl{PDMDEVREG,pfnInitComplete} * * Used to set the clock. */ static DECLCALLBACK(int) rtcInitComplete(PPDMDEVINS pDevIns) { /** @todo this should be (re)done at power on if we didn't load a state... */ PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); /* * Set the CMOS date/time. */ RTTIMESPEC Now; PDMDevHlpTMUtcNow(pDevIns, &Now); RTTIME Time; if (pThis->fUTC) RTTimeExplode(&Time, &Now); else RTTimeLocalExplode(&Time, &Now); struct my_tm Tm; memset(&Tm, 0, sizeof(Tm)); Tm.tm_year = Time.i32Year - 1900; Tm.tm_mon = Time.u8Month - 1; Tm.tm_mday = Time.u8MonthDay; Tm.tm_wday = (Time.u8WeekDay + 1 + 7) % 7; /* 0 = Monday -> Sunday */ Tm.tm_yday = Time.u16YearDay - 1; Tm.tm_hour = Time.u8Hour; Tm.tm_min = Time.u8Minute; Tm.tm_sec = Time.u8Second; rtc_set_date(pThis, &Tm); int iYear = to_bcd(pThis, (Tm.tm_year / 100) + 19); /* tm_year is 1900 based */ rtc_set_memory(pThis, 0x32, iYear); /* 32h - Century Byte (BCD value for the century */ rtc_set_memory(pThis, 0x37, iYear); /* 37h - (IBM PS/2) Date Century Byte */ /* * Recalculate the checksum just in case. */ rtcCalcCRC(pThis); Log(("CMOS bank 0: \n%16.128Rhxd\n", &pThis->cmos_data[0])); Log(("CMOS bank 1: \n%16.128Rhxd\n", &pThis->cmos_data[CMOS_BANK_SIZE])); return VINF_SUCCESS; } /** * @interface_method_impl{PDMDEVREG,pfnRelocate} */ static DECLCALLBACK(void) rtcRelocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns); pThis->pPeriodicTimerRC = TMTimerRCPtr(pThis->pPeriodicTimerR3); pThis->pSecondTimerRC = TMTimerRCPtr(pThis->pSecondTimerR3); pThis->pSecondTimer2RC = TMTimerRCPtr(pThis->pSecondTimer2R3); } /** * @interface_method_impl{PDMDEVREG,pfnReset} */ static DECLCALLBACK(void) rtcReset(PPDMDEVINS pDevIns) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); /* If shutdown status is non-zero, log its value. */ if (pThis->cmos_data[0xF]) { LogRel(("CMOS shutdown status byte is %02X\n", pThis->cmos_data[0xF])); #if 0 /* It would be nice to log the warm reboot vector but alas, we already trashed it. */ uint32_t u32WarmVector; int rc; rc = PDMDevHlpPhysRead(pDevIns, 0x467, &u32WarmVector, sizeof(u32WarmVector)); AssertRC(rc); LogRel((", 40:67 contains %04X:%04X\n", u32WarmVector >> 16, u32WarmVector & 0xFFFF)); #endif /* If we're going to trash the VM's memory, we also have to clear this. */ pThis->cmos_data[0xF] = 0; } /* Reset index values (important for second bank). */ pThis->cmos_index[0] = 0; pThis->cmos_index[1] = CMOS_BANK_SIZE; /* Point to start of second bank. */ } /** * @interface_method_impl{PDMDEVREG,pfnConstruct} */ static DECLCALLBACK(int) rtcConstruct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg) { PRTCSTATE pThis = PDMINS_2_DATA(pDevIns, PRTCSTATE); int rc; Assert(iInstance == 0); /* * Validate configuration. */ if (!CFGMR3AreValuesValid(pCfg, "Irq\0" "Base\0" "UseUTC\0" "GCEnabled\0" "R0Enabled\0")) return VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES; /* * Init the data. */ uint8_t u8Irq; rc = CFGMR3QueryU8Def(pCfg, "Irq", &u8Irq, 8); if (RT_FAILURE(rc)) return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Querying \"Irq\" as a uint8_t failed")); pThis->irq = u8Irq; rc = CFGMR3QueryPortDef(pCfg, "Base", &pThis->IOPortBase, 0x70); if (RT_FAILURE(rc)) return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Querying \"Base\" as a RTIOPORT failed")); rc = CFGMR3QueryBoolDef(pCfg, "UseUTC", &pThis->fUTC, false); if (RT_FAILURE(rc)) return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: Querying \"UseUTC\" as a bool failed")); bool fGCEnabled; rc = CFGMR3QueryBoolDef(pCfg, "GCEnabled", &fGCEnabled, true); if (RT_FAILURE(rc)) return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: failed to read GCEnabled as boolean")); bool fR0Enabled; rc = CFGMR3QueryBoolDef(pCfg, "R0Enabled", &fR0Enabled, true); if (RT_FAILURE(rc)) return PDMDEV_SET_ERROR(pDevIns, rc, N_("Configuration error: failed to read R0Enabled as boolean")); Log(("RTC: Irq=%#x Base=%#x fGCEnabled=%RTbool fR0Enabled=%RTbool\n", u8Irq, pThis->IOPortBase, fGCEnabled, fR0Enabled)); pThis->pDevInsR3 = pDevIns; pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns); pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns); pThis->cmos_data[RTC_REG_A] = 0x26; pThis->cmos_data[RTC_REG_B] = 0x02; pThis->cmos_data[RTC_REG_C] = 0x00; pThis->cmos_data[RTC_REG_D] = 0x80; pThis->RtcReg.u32Version = PDM_RTCREG_VERSION; pThis->RtcReg.pfnRead = rtcCMOSRead; pThis->RtcReg.pfnWrite = rtcCMOSWrite; pThis->fDisabledByHpet = false; pThis->cmos_index[1] = CMOS_BANK_SIZE; /* Point to start of second bank. */ /* IBase */ pDevIns->IBase.pfnQueryInterface = rtcQueryInterface; /* IHpetLegacyNotify */ pThis->IHpetLegacyNotify.pfnModeChanged = rtcHpetLegacyNotify_ModeChanged; /* * Create timers. */ PTMTIMER pTimer; /* Periodic timer. */ rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, rtcTimerPeriodic, pThis, TMTIMER_FLAGS_DEFAULT_CRIT_SECT, "MC146818 RTC/CMOS - Periodic", &pTimer); if (RT_FAILURE(rc)) return rc; pThis->pPeriodicTimerR3 = pTimer; pThis->pPeriodicTimerR0 = TMTimerR0Ptr(pTimer); pThis->pPeriodicTimerRC = TMTimerRCPtr(pTimer); /* Seconds timer. */ rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, rtcTimerSecond, pThis, TMTIMER_FLAGS_DEFAULT_CRIT_SECT, "MC146818 RTC/CMOS - Second", &pTimer); if (RT_FAILURE(rc)) return rc; pThis->pSecondTimerR3 = pTimer; pThis->pSecondTimerR0 = TMTimerR0Ptr(pTimer); pThis->pSecondTimerRC = TMTimerRCPtr(pTimer); /* The second2 timer, this is always active. */ rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, rtcTimerSecond2, pThis, TMTIMER_FLAGS_DEFAULT_CRIT_SECT, "MC146818 RTC/CMOS - Second2", &pTimer); if (RT_FAILURE(rc)) return rc; pThis->pSecondTimer2R3 = pTimer; pThis->pSecondTimer2R0 = TMTimerR0Ptr(pTimer); pThis->pSecondTimer2RC = TMTimerRCPtr(pTimer); pThis->next_second_time = TMTimerGet(pTimer) + (TMTimerGetFreq(pTimer) * 99) / 100; rc = TMTimerLock(pTimer, VERR_IGNORED); AssertRCReturn(rc, rc); rc = TMTimerSet(pTimer, pThis->next_second_time); TMTimerUnlock(pTimer); AssertRCReturn(rc, rc); /* * Register I/O ports. */ rc = PDMDevHlpIOPortRegister(pDevIns, pThis->IOPortBase, 4, NULL, rtcIOPortWrite, rtcIOPortRead, NULL, NULL, "MC146818 RTC/CMOS"); if (RT_FAILURE(rc)) return rc; if (fGCEnabled) { rc = PDMDevHlpIOPortRegisterRC(pDevIns, pThis->IOPortBase, 4, NIL_RTRCPTR, "rtcIOPortWrite", "rtcIOPortRead", NULL, NULL, "MC146818 RTC/CMOS"); if (RT_FAILURE(rc)) return rc; } if (fR0Enabled) { rc = PDMDevHlpIOPortRegisterR0(pDevIns, pThis->IOPortBase, 4, NIL_RTR0PTR, "rtcIOPortWrite", "rtcIOPortRead", NULL, NULL, "MC146818 RTC/CMOS"); if (RT_FAILURE(rc)) return rc; } /* * Register the saved state. */ rc = PDMDevHlpSSMRegister3(pDevIns, RTC_SAVED_STATE_VERSION, sizeof(*pThis), rtcLiveExec, rtcSaveExec, rtcLoadExec); if (RT_FAILURE(rc)) return rc; /* * Register ourselves as the RTC/CMOS with PDM. */ rc = PDMDevHlpRTCRegister(pDevIns, &pThis->RtcReg, &pThis->pRtcHlpR3); if (RT_FAILURE(rc)) return rc; /* * Register debugger info callback. */ PDMDevHlpDBGFInfoRegister(pDevIns, "cmos1", "Display CMOS Bank 1 Info (0x0e-0x7f). No arguments. See also rtc.", rtcCmosBankInfo); PDMDevHlpDBGFInfoRegister(pDevIns, "cmos2", "Display CMOS Bank 2 Info (0x0e-0x7f). No arguments.", rtcCmosBank2Info); PDMDevHlpDBGFInfoRegister(pDevIns, "rtc", "Display CMOS RTC (0x00-0x0d). No arguments. See also cmos1 & cmos2", rtcCmosClockInfo); /* * Register statistics. */ PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRTCIrq, STAMTYPE_COUNTER, "/TM/RTC/Irq", STAMUNIT_OCCURENCES, "The number of times a RTC interrupt was triggered."); PDMDevHlpSTAMRegister(pDevIns, &pThis->StatRTCTimerCB, STAMTYPE_COUNTER, "/TM/RTC/TimerCB", STAMUNIT_OCCURENCES, "The number of times the RTC timer callback ran."); return VINF_SUCCESS; } /** * The device registration structure. */ const PDMDEVREG g_DeviceMC146818 = { /* u32Version */ PDM_DEVREG_VERSION, /* szName */ "mc146818", /* szRCMod */ "VBoxDDRC.rc", /* szR0Mod */ "VBoxDDR0.r0", /* pszDescription */ "Motorola MC146818 RTC/CMOS Device.", /* fFlags */ PDM_DEVREG_FLAGS_HOST_BITS_DEFAULT | PDM_DEVREG_FLAGS_GUEST_BITS_32_64 | PDM_DEVREG_FLAGS_PAE36 | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0, /* fClass */ PDM_DEVREG_CLASS_RTC, /* cMaxInstances */ 1, /* cbInstance */ sizeof(RTCSTATE), /* pfnConstruct */ rtcConstruct, /* pfnDestruct */ NULL, /* pfnRelocate */ rtcRelocate, /* pfnMemSetup */ NULL, /* pfnPowerOn */ NULL, /* pfnReset */ rtcReset, /* pfnSuspend */ NULL, /* pfnResume */ NULL, /* pfnAttach */ NULL, /* pfnDetach */ NULL, /* pfnQueryInterface */ NULL, /* pfnInitComplete */ rtcInitComplete, /* pfnPowerOff */ NULL, /* pfnSoftReset */ NULL, /* u32VersionEnd */ PDM_DEVREG_VERSION }; #endif /* IN_RING3 */ #endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
33.190184
174
0.60707
[ "vector" ]
6e7b748952e459b122cdad4e8f46507326ff71a8
26,506
cpp
C++
src/subgame_utils.cpp
tbdevo/slumbot2019
1e419e85259562d3123ed04a970e0674c5a2a0be
[ "MIT" ]
null
null
null
src/subgame_utils.cpp
tbdevo/slumbot2019
1e419e85259562d3123ed04a970e0674c5a2a0be
[ "MIT" ]
null
null
null
src/subgame_utils.cpp
tbdevo/slumbot2019
1e419e85259562d3123ed04a970e0674c5a2a0be
[ "MIT" ]
null
null
null
// There are up to four subgame strategies written per solve, which can be // confusing. If we are solving an asymmetric game, then there will be // a choice of which player's game we are solving, which affects the betting // tree. In addition, regardless of whether we are solving a symmetric or // asymmetric game, we have to write out both player's strategies in the // subgame. We refer to the first player parameter as the asym_p and the // second player parameter as the target_pa. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory> #include <string> #include <vector> #include "betting_abstraction.h" #include "betting_tree.h" #include "betting_trees.h" #include "betting_tree_builder.h" #include "board_tree.h" #include "buckets.h" #include "canonical_cards.h" #include "card_abstraction.h" #include "cfr_config.h" #include "cfr_values.h" #include "subgame_utils.h" #include "files.h" #include "game.h" #include "hand_tree.h" #include "io.h" #include "reach_probs.h" #include "resolving_method.h" using std::shared_ptr; using std::string; using std::unique_ptr; using std::vector; // Create a subtree for resolving rooted at the node (from a base tree) passed in. // Assumes the subtree is rooted at a street-initial node. // Doesn't support asymmetric yet // Doesn't support multiplayer yet (?) BettingTrees *CreateSubtrees(int st, int player_acting, int last_bet_to, int target_p, const BettingAbstraction &betting_abstraction) { // Assume subtree rooted at street-initial node int last_bet_size = 0; int num_street_bets = 0; BettingTreeBuilder betting_tree_builder(betting_abstraction, target_p); int num_terminals = 0; // Should call routine from mp_betting_tree.cpp instead shared_ptr<Node> subtree_root = betting_tree_builder.CreateNoLimitSubtree(st, last_bet_size, last_bet_to, num_street_bets, player_acting, target_p, &num_terminals); // Delete the nodes under subtree_root? Or does garbage collection // automatically take care of it because they are shared pointers. return new BettingTrees(subtree_root.get()); } // More flexible implementation that supports subtrees not rooted at street-initial node. // Don't really need to know num_bets. // We do need to know num_street_bets. Determines whether we can fold. // I think we need num_players_to_act. Should be 2 at street initial node, and 1 otherwise. // Only support heads-up for now. Assume no one has folded. BettingTrees *CreateSubtrees(int st, int last_bet_size, int last_bet_to, int num_street_bets, int num_bets, int player_acting, int num_players_to_act, int target_player, const BettingAbstraction &betting_abstraction) { int num_players = Game::NumPlayers(); unique_ptr<bool []> folded(new bool[num_players]); for (int p = 0; p < num_players; ++p) folded[p] = false; string key; int num_terminals = 0; BettingTreeBuilder betting_tree_builder(betting_abstraction, target_player); shared_ptr<Node> subtree_root = betting_tree_builder.CreateMPSubtree(st, last_bet_size, last_bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded.get(), target_player, &key, &num_terminals); return new BettingTrees(subtree_root.get()); } // Copies source tree for the current node. For successors of the current node, build according to // the betting abstraction. BettingTrees *BuildHybridTree(const BettingAbstraction &betting_abstraction, int target_p, Node *source, int last_bet_size, int num_street_bets, int num_bets) { BettingTreeBuilder betting_tree_builder(betting_abstraction, target_p); int csi = source->CallSuccIndex(); bool has_call = csi != -1; int fsi = source->FoldSuccIndex(); bool has_fold = fsi != -1; int num_succs = source->NumSuccs(); int num_bet_succs = num_succs - (has_call ? 1 : 0) - (has_fold ? 1 : 0); int st = source->Street(); int last_bet_to = source->LastBetTo(); int player_acting = source->PlayerActing(); int num_players = Game::NumPlayers(); if (num_players > 2) { fprintf(stderr, "Node::StreetInitial() doesn't support multiplayer\n"); exit(-1); } bool street_initial = source->StreetInitial(); int num_players_to_act = street_initial ? 2 : 1; unique_ptr<bool []> folded(new bool[num_players]); for (int p = 0; p < num_players; ++p) folded[p] = false; int num_terminals = 0; string key; shared_ptr<Node> fold_succ, call_succ; vector< shared_ptr<Node> > bet_succs; if (has_call) { call_succ = betting_tree_builder.CreateMPCallSucc(st, last_bet_size, last_bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded.get(), target_p, &key, &num_terminals); } if (has_fold) { fold_succ = betting_tree_builder.CreateMPFoldSucc(st, last_bet_size, last_bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded.get(), target_p, &key, &num_terminals); } for (int i = 0; i < num_bet_succs; ++i) { int s = i + (has_call ? 1 : 0) + (has_fold ? 1 : 0); int bet_size = source->IthSucc(s)->LastBetTo() - source->LastBetTo(); shared_ptr<Node> bet = betting_tree_builder.CreateMPSubtree(st, bet_size, last_bet_to + bet_size, num_street_bets + 1, num_bets + 1, player_acting^1, 1, folded.get(), -1, &key, &num_terminals); bet_succs.push_back(bet); } shared_ptr<Node> root(new Node(-1, st, player_acting, call_succ, fold_succ, &bet_succs, 2, last_bet_to)); return new BettingTrees(root.get()); } #if 0 // Builds a subtree rooted at a street-initial node on backup_st. We take a path from a source // tree as input. This path is a sequence of nodes from the root of the source tree to some // nonterminal node that is on backup_st or later. The new subtree we create is a) modeled // on the source tree along the subpart of the input path starting at backup_st, and b) dictated // by the input betting abstraction for the remainder. // What should I do at each step? // If the source node calls: // Create a call node // Otherwise: // Create a call subtree with the given betting abstraction // If the source node bets: // Create a bet node with the given bet size // Otherwise: // Create one or more bet subtrees with the given betting abstraction // If the source node has a fold succ // Create a fold succ // Create a call node, a fold node and a bet node? If the source node made a bet, then get the BettingTrees *BuildHybridTreeBackup(const BettingAbstraction &betting_abstraction, int target_p, const vector<Node *> &source_path, int backup_st) { BettingTreeBuilder betting_tree_builder(betting_abstraction, target_p); int sz = source_path.size(); int num_bets = 0, i; for (i = 0; i < sz; ++i) { Node *node = source_path[i]; if (node->Street() == backup_st) break; if (i < sz - 1) { Node *next_node = source_path[i+1]; int num_succs = node->NumSuccs(); int s; for (s = 0; s < num_succs; ++s) { if (node->IthSucc(s) == next_node) break; } if (s == num_succs) { fprintf(stderr, "Couldn't connect node to next node\n"); exit(-1); } if (s != node->CallSuccIndex() && s != node->FoldSuccIndex()) ++num_bets; } } if (i == sz) { fprintf(stderr, "No node on backup street on path\n"); exit(-1); } unique_ptr<bool []> folded(new bool[2]); string key; for (int p = 0; p < 2; ++p) folded[p] = false; int num_terminals = 0, last_bet_size = 0, num_street_bets = 0, num_players_to_act = 2; int last_st = backup_st; for (int j = i; j < sz - 1; ++j) { Node *node = source_path[j]; Node *next_node = source_path[j+1]; int num_succs = node->NumSuccs(); int s; for (s = 0; s < num_succs; ++s) { if (node->IthSucc(s) == next_node) break; } if (s == num_succs) { fprintf(stderr, "Couldn't connect node to next node\n"); exit(-1); } if (s == node->FoldSuccIndex()) { fprintf(stderr, "Shouldn't see fold along path\n"); exit(-1); } int st = node->Street(); if (st > last_st) { num_street_bets = 0; last_bet_size = 0; num_players_to_act = 2; st = last_st; } int pa = node->PlayerActing(); shared_ptr<Node> call_succ, fold_succ; if (node->HasCallSucc()) { // Should I create node or subtree? // call_succ.reset(new Node(-1, st, pa, call_succ, fold_succ, &bet_succs, num_rem, bet_to)); call_succ = betting_tree_builder.CreateMPCallSucc(st, last_bet_size, node->LastBetTo(), num_street_bets, num_bets, pa, num_players_to_act, folded.get(), target_p, &key, &num_terminals); } if (node->HasFoldSucc()) { fold_succ = betting_tree_builder.CreateMPFoldSucc(st, last_bet_size, node->LastBetTo(), num_street_bets, num_bets, pa, num_players_to_act, folded.get(), target_p, &key, &num_terminals); } int new_bet_size; if (s == node->CallSuccIndex()) { new_bet_size = 0; num_players_to_act = 1; } else if (s == node->FoldSuccIndex()) { } else { new_bet_size = next_node->LastBetTo() - node->LastBetTo(); ++num_street_bets; num_players_to_act = 1; } last_bet_size = new_bet_size; vector< shared_ptr<Node> > bet_succs; shared_ptr<Node> call_succ; shared_ptr<Node> fold_succ; vector< shared_ptr<Node> > bet_succs; CreateMPSuccs(st, last_bet_size, bet_to, num_street_bets, num_bets, player_acting, num_players_to_act, folded, target_player, key, terminal_id, &call_succ, &fold_succ, &bet_succs); if (s == node->CallSuccIndex()) { } } } #endif // I always load probabilities for both players because I need the reach // probabilities for both players. In addition, as long as we are // zero-summing the T-values, we need the strategy for both players for the // CBR computation. // Actually: for normal subgame solving, I think I only need both players' // strategies if we are zero-summing. unique_ptr<CFRValues> ReadBaseSubgameStrategy(const CardAbstraction &base_card_abstraction, const BettingAbstraction &base_betting_abstraction, const CFRConfig &base_cfr_config, const BettingTrees *base_betting_trees, const Buckets &base_buckets, const Buckets &subgame_buckets, int base_it, Node *base_node, int gbd, const string &action_sequence, double **reach_probs, BettingTree *subtree, bool current, int asym_p) { // We need probs for subgame streets only int max_street = Game::MaxStreet(); unique_ptr<bool []> subgame_streets(new bool[max_street + 1]); for (int st = 0; st <= max_street; ++st) { subgame_streets[st] = st >= base_node->Street(); } unique_ptr<CFRValues> strategy(new CFRValues(nullptr, subgame_streets.get(), gbd, base_node->Street(), base_buckets, base_betting_trees->GetBettingTree())); char dir[500]; sprintf(dir, "%s/%s.%u.%s.%i.%i.%i.%s.%s", Files::OldCFRBase(), Game::GameName().c_str(), Game::NumPlayers(), base_card_abstraction.CardAbstractionName().c_str(), Game::NumRanks(), Game::NumSuits(), Game::MaxStreet(), base_betting_abstraction.BettingAbstractionName().c_str(), base_cfr_config.CFRConfigName().c_str()); if (base_betting_abstraction.Asymmetric()) { char buf[100]; sprintf(buf, ".p%u", asym_p); strcat(dir, buf); } unique_ptr<int []> num_full_holdings(new int[max_street + 1]); for (int st = 0; st <= max_street; ++st) { if (subgame_buckets.None(st)) { num_full_holdings[st] = BoardTree::NumBoards(st) * Game::NumHoleCardPairs(st); } else { num_full_holdings[st] = subgame_buckets.NumBuckets(st); } } fprintf(stderr, "Need to implement ReadSubtreeFromFull()\n"); exit(-1); #if 0 strategy->ReadSubtreeFromFull(dir, base_it, base_betting_trees->Root(), base_node, subtree->Root(), action_sequence, num_full_holdings.get(), -1); #endif return strategy; } // Only write out strategy for nodes at or below below_action_sequence. void WriteSubgame(Node *node, const string &action_sequence, const string &below_action_sequence, int gbd, const CardAbstraction &base_card_abstraction, const CardAbstraction &subgame_card_abstraction, const BettingAbstraction &base_betting_abstraction, const BettingAbstraction &subgame_betting_abstraction, const CFRConfig &base_cfr_config, const CFRConfig &subgame_cfr_config, ResolvingMethod method, const CFRValues *sumprobs, int root_bd_st, int root_bd, int asym_p, int target_pa, int last_st) { if (node->Terminal()) return; int st = node->Street(); if (st > last_st) { int ngbd_begin = BoardTree::SuccBoardBegin(last_st, gbd, st); int ngbd_end = BoardTree::SuccBoardEnd(last_st, gbd, st); for (int ngbd = ngbd_begin; ngbd < ngbd_end; ++ngbd) { WriteSubgame(node, action_sequence, below_action_sequence, ngbd, base_card_abstraction, subgame_card_abstraction, base_betting_abstraction, subgame_betting_abstraction, base_cfr_config, subgame_cfr_config, method, sumprobs, root_bd_st, root_bd, asym_p, target_pa, st); } return; } int num_succs = node->NumSuccs(); if (node->PlayerActing() == target_pa && num_succs > 1) { if (below_action_sequence.size() <= action_sequence.size() && std::equal(below_action_sequence.begin(), below_action_sequence.end(), action_sequence.begin())) { char dir[500], dir2[500], dir3[500], filename[500]; sprintf(dir, "%s/%s.%u.%s.%u.%u.%u.%s.%s", Files::NewCFRBase(), Game::GameName().c_str(), Game::NumPlayers(), base_card_abstraction.CardAbstractionName().c_str(), Game::NumRanks(), Game::NumSuits(), Game::MaxStreet(), base_betting_abstraction.BettingAbstractionName().c_str(), base_cfr_config.CFRConfigName().c_str()); if (base_betting_abstraction.Asymmetric()) { sprintf(dir2, "%s.p%u/subgames.%s.%s.%s.%s.p%u.p%u", dir, asym_p, subgame_card_abstraction.CardAbstractionName().c_str(), subgame_betting_abstraction.BettingAbstractionName().c_str(), subgame_cfr_config.CFRConfigName().c_str(), ResolvingMethodName(method), asym_p, target_pa); } else { sprintf(dir2, "%s/subgames.%s.%s.%s.%s.p%u", dir, subgame_card_abstraction.CardAbstractionName().c_str(), subgame_betting_abstraction.BettingAbstractionName().c_str(), subgame_cfr_config.CFRConfigName().c_str(), ResolvingMethodName(method), target_pa); } Mkdir(dir2); if (action_sequence == "") { fprintf(stderr, "Empty action sequence not allowed\n"); exit(-1); } sprintf(dir3, "%s/%s", dir2, action_sequence.c_str()); Mkdir(dir3); sprintf(filename, "%s/%u", dir3, gbd); // If we resolve more than one street, things get a little tricky. We are writing one // file per final-street board, but this sumprobs object will contain more than one // board's data. Writer writer(filename); int num_hole_card_pairs = Game::NumHoleCardPairs(node->Street()); int lbd = BoardTree::LocalIndex(root_bd_st, root_bd, st, gbd); sumprobs->WriteBoardValuesForNode(node, &writer, nullptr, lbd, num_hole_card_pairs); } } for (int s = 0; s < num_succs; ++s) { string action = node->ActionName(s); WriteSubgame(node->IthSucc(s), action_sequence + action, below_action_sequence, gbd, base_card_abstraction, subgame_card_abstraction, base_betting_abstraction, subgame_betting_abstraction, base_cfr_config, subgame_cfr_config, method, sumprobs, root_bd_st, root_bd, asym_p, target_pa, st); } } static void ReadSubgame(Node *node, const string &action_sequence, int gbd, const CardAbstraction &base_card_abstraction, const CardAbstraction &subgame_card_abstraction, const BettingAbstraction &base_betting_abstraction, const BettingAbstraction &subgame_betting_abstraction, const CFRConfig &base_cfr_config, const CFRConfig &subgame_cfr_config, ResolvingMethod method, CFRValues *sumprobs, int root_bd_st, int root_bd, int asym_p, int target_pa, int last_st) { if (node->Terminal()) { return; } int st = node->Street(); if (st > last_st) { int ngbd_begin = BoardTree::SuccBoardBegin(last_st, gbd, st); int ngbd_end = BoardTree::SuccBoardEnd(last_st, gbd, st); for (int ngbd = ngbd_begin; ngbd < ngbd_end; ++ngbd) { ReadSubgame(node, action_sequence, ngbd, base_card_abstraction, subgame_card_abstraction, base_betting_abstraction, subgame_betting_abstraction, base_cfr_config, subgame_cfr_config, method, sumprobs, root_bd_st, root_bd, asym_p, target_pa, st); } return; } int num_succs = node->NumSuccs(); if (node->PlayerActing() == target_pa && num_succs > 1) { char dir[500], dir2[500], dir3[500], filename[500]; sprintf(dir, "%s/%s.%u.%s.%u.%u.%u.%s.%s", Files::NewCFRBase(), Game::GameName().c_str(), Game::NumPlayers(), base_card_abstraction.CardAbstractionName().c_str(), Game::NumRanks(), Game::NumSuits(), Game::MaxStreet(), base_betting_abstraction.BettingAbstractionName().c_str(), base_cfr_config.CFRConfigName().c_str()); if (base_betting_abstraction.Asymmetric()) { sprintf(dir2, "%s.p%u/subgames.%s.%s.%s.%s.p%u.p%u", dir, asym_p, subgame_card_abstraction.CardAbstractionName().c_str(), subgame_betting_abstraction.BettingAbstractionName().c_str(), subgame_cfr_config.CFRConfigName().c_str(), ResolvingMethodName(method), asym_p, target_pa); } else { sprintf(dir2, "%s/subgames.%s.%s.%s.%s.p%u", dir, subgame_card_abstraction.CardAbstractionName().c_str(), subgame_betting_abstraction.BettingAbstractionName().c_str(), subgame_cfr_config.CFRConfigName().c_str(), ResolvingMethodName(method), target_pa); } if (action_sequence == "") { fprintf(stderr, "Empty action sequence not allowed\n"); exit(-1); } sprintf(dir3, "%s/%s", dir2, action_sequence.c_str()); sprintf(filename, "%s/%u", dir3, gbd); Reader reader(filename); // Assume doubles in file // Also assume subgame solving is unabstracted // We write only one board's data per file, even on streets later than // solve street. int lbd = BoardTree::LocalIndex(root_bd_st, root_bd, st, gbd); int num_hole_card_pairs = Game::NumHoleCardPairs(node->Street()); sumprobs->ReadBoardValuesForNode(node, &reader, nullptr, lbd, num_hole_card_pairs); if (! reader.AtEnd()) { fprintf(stderr, "Reader didn't get to end; pos %lli size %lli\nFile: %s\n", reader.BytePos(), reader.FileSize(), filename); exit(-1); } } for (int s = 0; s < num_succs; ++s) { string action = node->ActionName(s); ReadSubgame(node->IthSucc(s), action_sequence + action, gbd, base_card_abstraction, subgame_card_abstraction, base_betting_abstraction, subgame_betting_abstraction, base_cfr_config, subgame_cfr_config, method, sumprobs, root_bd_st, root_bd, asym_p, target_pa, st); } } // I always load probabilities for both players because I need the reach // probabilities for both players in case we are performing nested subgame // solving. In addition, as long as we are zero-summing the T-values, we // need the strategy for both players for the CBR computation. unique_ptr<CFRValues> ReadSubgame(const string &action_sequence, BettingTrees *subtrees, int gbd, const CardAbstraction &base_card_abstraction, const CardAbstraction &subgame_card_abstraction, const BettingAbstraction &base_betting_abstraction, const BettingAbstraction &subgame_betting_abstraction, const CFRConfig &base_cfr_config, const CFRConfig &subgame_cfr_config, const Buckets &subgame_buckets, ResolvingMethod method, int root_bd_st, int root_bd, int asym_p) { int max_street = Game::MaxStreet(); unique_ptr<bool []> subgame_streets(new bool[max_street + 1]); for (int st = 0; st <= max_street; ++st) { // Assume symmetric? subgame_streets[st] = st >= subtrees->Root()->Street(); } // Buckets needed for num buckets and for knowing what streets are // bucketed. unique_ptr<CFRValues> sumprobs(new CFRValues(nullptr, subgame_streets.get(), gbd, subtrees->Root()->Street(), subgame_buckets, subtrees->GetBettingTree())); // Assume doubles for (int st = 0; st <= max_street; ++st) { if (subgame_streets[st]) sumprobs->CreateStreetValues(st, CFRValueType::CFR_DOUBLE, false); } for (int target_pa = 0; target_pa <= 1; ++target_pa) { ReadSubgame(subtrees->Root(), action_sequence, gbd, base_card_abstraction, subgame_card_abstraction, base_betting_abstraction, subgame_betting_abstraction, base_cfr_config, subgame_cfr_config, method, sumprobs.get(), root_bd_st, root_bd, asym_p, target_pa, subtrees->Root()->Street()); } return sumprobs; } void DeleteAllSubgames(const CardAbstraction &base_card_abstraction, const CardAbstraction &subgame_card_abstraction, const BettingAbstraction &base_betting_abstraction, const BettingAbstraction &subgame_betting_abstraction, const CFRConfig &base_cfr_config, const CFRConfig &subgame_cfr_config, ResolvingMethod method, int asym_p) { char dir[500], dir2[500]; sprintf(dir, "%s/%s.%s.%u.%u.%u.%s.%s", Files::OldCFRBase(), Game::GameName().c_str(), base_card_abstraction.CardAbstractionName().c_str(), Game::NumRanks(), Game::NumSuits(), Game::MaxStreet(), base_betting_abstraction.BettingAbstractionName().c_str(), base_cfr_config.CFRConfigName().c_str()); if (base_betting_abstraction.Asymmetric()) { for (int target_pa = 0; target_pa <= 1; ++target_pa) { sprintf(dir2, "%s.p%u/subgames.%s.%s.%s.%s.p%u.p%u", dir, asym_p, subgame_card_abstraction.CardAbstractionName().c_str(), subgame_betting_abstraction.BettingAbstractionName().c_str(), subgame_cfr_config.CFRConfigName().c_str(), ResolvingMethodName(method), asym_p, target_pa); if (FileExists(dir2)) { fprintf(stderr, "Recursively deleting %s\n", dir2); RecursivelyDeleteDirectory(dir2); } } } else { for (int target_pa = 0; target_pa <= 1; ++target_pa) { sprintf(dir2, "%s/subgames.%s.%s.%s.%s.p%u", dir, subgame_card_abstraction.CardAbstractionName().c_str(), subgame_betting_abstraction.BettingAbstractionName().c_str(), subgame_cfr_config.CFRConfigName().c_str(), ResolvingMethodName(method), target_pa); if (FileExists(dir2)) { fprintf(stderr, "Recursively deleting %s\n", dir2); RecursivelyDeleteDirectory(dir2); } } } } void FloorCVs(Node *subtree_root, double *opp_reach_probs, const CanonicalCards *hands, double *cvs) { int st = subtree_root->Street(); int num_hole_card_pairs = Game::NumHoleCardPairs(st); int maxcard1 = Game::MaxCard() + 1; for (int i = 0; i < num_hole_card_pairs; ++i) { const Card *our_cards = hands->Cards(i); Card our_hi = our_cards[0]; Card our_lo = our_cards[1]; double sum_opp_reach_probs = 0; for (int j = 0; j < num_hole_card_pairs; ++j) { const Card *opp_cards = hands->Cards(j); Card opp_hi = opp_cards[0]; Card opp_lo = opp_cards[1]; if (opp_hi == our_hi || opp_hi == our_lo || opp_lo == our_hi || opp_lo == our_lo) { continue; } int opp_enc = opp_hi * maxcard1 + opp_lo; sum_opp_reach_probs += opp_reach_probs[opp_enc]; } double our_norm_cv = cvs[i] / sum_opp_reach_probs; if (our_norm_cv < -(double)subtree_root->LastBetTo()) { cvs[i] = (-(double)subtree_root->LastBetTo()) * sum_opp_reach_probs; } } } static void CalculateMeanCVs(double *p0_cvs, double *p1_cvs, int num_hole_card_pairs, const ReachProbs &reach_probs, const CanonicalCards *hands, double *p0_mean_cv, double *p1_mean_cv) { int maxcard1 = Game::MaxCard() + 1; double sum_p0_cvs = 0, sum_p1_cvs = 0, sum_joint_probs = 0; for (int i = 0; i < num_hole_card_pairs; ++i) { const Card *our_cards = hands->Cards(i); Card our_hi = our_cards[0]; Card our_lo = our_cards[1]; int our_enc = our_hi * maxcard1 + our_lo; double sum_p0_opp_probs = 0; for (int j = 0; j < num_hole_card_pairs; ++j) { const Card *opp_cards = hands->Cards(j); Card opp_hi = opp_cards[0]; Card opp_lo = opp_cards[1]; if (opp_hi == our_hi || opp_hi == our_lo || opp_lo == our_hi || opp_lo == our_lo) { continue; } int opp_enc = opp_hi * maxcard1 + opp_lo; sum_p0_opp_probs += reach_probs.Get(0, opp_enc); } double p0_prob = reach_probs.Get(0, our_enc); double p1_prob = reach_probs.Get(1, our_enc); sum_p0_cvs += p0_cvs[i] * p0_prob; sum_p1_cvs += p1_cvs[i] * p1_prob; sum_joint_probs += p1_prob * sum_p0_opp_probs; } *p0_mean_cv = sum_p0_cvs / sum_joint_probs; *p1_mean_cv = sum_p1_cvs / sum_joint_probs; } void ZeroSumCVs(double *p0_cvs, double *p1_cvs, int num_hole_card_pairs, const ReachProbs &reach_probs, const CanonicalCards *hands) { double p0_mean_cv, p1_mean_cv; CalculateMeanCVs(p0_cvs, p1_cvs, num_hole_card_pairs, reach_probs, hands, &p0_mean_cv, &p1_mean_cv); // fprintf(stderr, "Mean CVs: %f, %f\n", p0_mean_cv, p1_mean_cv); double avg = (p0_mean_cv + p1_mean_cv) / 2.0; double adj = -avg; int maxcard1 = Game::MaxCard() + 1; for (int i = 0; i < num_hole_card_pairs; ++i) { const Card *our_cards = hands->Cards(i); Card our_hi = our_cards[0]; Card our_lo = our_cards[1]; double sum_p0_opp_probs = 0, sum_p1_opp_probs = 0; for (int j = 0; j < num_hole_card_pairs; ++j) { const Card *opp_cards = hands->Cards(j); Card opp_hi = opp_cards[0]; Card opp_lo = opp_cards[1]; if (opp_hi == our_hi || opp_hi == our_lo || opp_lo == our_hi || opp_lo == our_lo) { continue; } int opp_enc = opp_hi * maxcard1 + opp_lo; sum_p0_opp_probs += reach_probs.Get(0, opp_enc); sum_p1_opp_probs += reach_probs.Get(1, opp_enc); } p0_cvs[i] += adj * sum_p1_opp_probs; p1_cvs[i] += adj * sum_p0_opp_probs; } // I can take this out double adj_p0_mean_cv, adj_p1_mean_cv; CalculateMeanCVs(p0_cvs, p1_cvs, num_hole_card_pairs, reach_probs, hands, &adj_p0_mean_cv, &adj_p1_mean_cv); // fprintf(stderr, "Adj mean CVs: P0 %f, P1 %f\n", adj_p0_mean_cv, adj_p1_mean_cv); }
41.094574
99
0.690297
[ "object", "vector" ]
6e80086c54011d4f1b5012518880a3dd8615c746
10,349
cpp
C++
EED/EEDTest/DataEnv.cpp
WebFreak001/mago
50ba766aabf5d395c3d15aaf080665906b76008b
[ "Apache-2.0" ]
39
2015-02-26T10:22:42.000Z
2021-11-13T23:07:57.000Z
EED/EEDTest/DataEnv.cpp
WebFreak001/mago
50ba766aabf5d395c3d15aaf080665906b76008b
[ "Apache-2.0" ]
29
2015-12-02T12:38:57.000Z
2021-03-31T16:43:34.000Z
EED/EEDTest/DataEnv.cpp
WebFreak001/mago
50ba766aabf5d395c3d15aaf080665906b76008b
[ "Apache-2.0" ]
15
2015-03-03T07:28:43.000Z
2021-03-30T14:22:00.000Z
/* Copyright (c) 2010 Aldo J. Nunez Licensed under the Apache License, Version 2.0. See the LICENSE text file for details. */ #include "Common.h" #include "DataEnv.h" #include "DataValue.h" #include "DataElement.h" using MagoEE::Type; using MagoEE::Declaration; DataEnv::DataEnv( size_t size ) : mBufSize( size ), mAllocSize( 4 ) { mBuf.Attach( new uint8_t[size] ); } DataEnv::DataEnv( const DataEnv& orig ) { mBuf.Attach( new uint8_t[ orig.mAllocSize ] ); mBufSize = orig.mAllocSize; mAllocSize = orig.mAllocSize; memcpy( mBuf.Get(), orig.mBuf.Get(), mBufSize ); } uint8_t* DataEnv::GetBuffer() { return mBuf.Get(); } uint8_t* DataEnv::GetBufferLimit() { return mBuf.Get() + mAllocSize; } MagoEE::Address DataEnv::Allocate( uint32_t size ) { MagoEE::Address addr = mAllocSize; mAllocSize += size; if ( mAllocSize > mBufSize ) throw L"Allocated memory out-of-bounds."; return addr; } std::shared_ptr<DataObj> DataEnv::GetValue( MagoEE::Declaration* decl ) { if ( decl->IsConstant() ) { return ((ConstantDataElement*) decl)->Evaluate(); } else if ( decl->IsVar() ) { MagoEE::Address addr = 0; RefPtr<Type> type; decl->GetAddress( addr ); decl->GetType( type.Ref() ); return GetValue( addr, type.Get(), decl ); } throw L"Can't get value."; } std::shared_ptr<DataObj> DataEnv::GetValue( MagoEE::Address address, MagoEE::Type* type ) { return GetValue( address, type, NULL ); } std::shared_ptr<DataObj> DataEnv::GetValue( MagoEE::Address address, MagoEE::Type* type, MagoEE::Declaration* decl ) { _ASSERT( type != NULL ); std::shared_ptr<LValueObj> val( new LValueObj( decl, address ) ); size_t size = 0; if ( type->IsPointer() || type->IsIntegral() || type->IsFloatingPoint() || type->IsDArray() ) size = type->GetSize(); if ( (address + size) > mAllocSize ) throw L"Reading memory out-of-bounds."; val->SetType( type ); if ( type->IsPointer() ) { memcpy( &val->Value.Addr, mBuf.Get() + address, size ); } else if ( type->IsIntegral() ) { val->Value.UInt64Value = ReadInt( address, size, type->IsSigned() ); } else if ( type->IsReal() || type->IsImaginary() ) { val->Value.Float80Value = ReadFloat( address, type ); } else if ( type->IsComplex() ) { val->Value.Complex80Value.RealPart = ReadFloat( address, type ); val->Value.Complex80Value.ImaginaryPart = ReadFloat( address + (size / 2), type ); } else if ( type->IsDArray() ) { const size_t LengthSize = type->AsTypeDArray()->GetLengthType()->GetSize(); const size_t AddressSize = type->AsTypeDArray()->GetPointerType()->GetSize(); val->Value.Array.Length = (MagoEE::dlength_t) ReadInt( address, LengthSize, false ); memcpy( &val->Value.Array.Addr, mBuf.Get() + address + LengthSize, AddressSize ); } return val; } void DataEnv::SetValue( MagoEE::Address address, DataObj* val ) { _ASSERT( val->GetType() != NULL ); Type* type = val->GetType(); uint8_t* buf = mBuf.Get() + address; uint8_t* bufLimit = mBuf.Get() + mBufSize; if ( type->IsPointer() ) { IntValueElement::WriteData( buf, bufLimit, type, val->Value.Addr ); } else if ( type->IsIntegral() ) { IntValueElement::WriteData( buf, bufLimit, type, val->Value.UInt64Value ); } else if ( type->IsReal() || type->IsImaginary() ) { RealValueElement::WriteData( buf, bufLimit, type, val->Value.Float80Value ); } else if ( type->IsComplex() ) { const size_t PartSize = type->GetSize() / 2; RealValueElement::WriteData( buf, bufLimit, type, val->Value.Complex80Value.RealPart ); RealValueElement::WriteData( buf + PartSize, bufLimit, type, val->Value.Complex80Value.ImaginaryPart ); } else if ( type->IsDArray() ) { RefPtr<Type> lenType = type->AsTypeDArray()->GetLengthType(); RefPtr<Type> ptrType = type->AsTypeDArray()->GetPointerType(); IntValueElement::WriteData( buf, bufLimit, lenType, val->Value.Array.Length ); IntValueElement::WriteData( buf + lenType->GetSize(), bufLimit, ptrType, val->Value.Array.Addr ); } } RefPtr<MagoEE::Declaration> DataEnv::GetThis() { _ASSERT( false ); return NULL; } RefPtr<MagoEE::Declaration> DataEnv::GetSuper() { _ASSERT( false ); return NULL; } bool DataEnv::GetArrayLength( MagoEE::dlength_t& length ) { return false; } uint64_t DataEnv::ReadInt( MagoEE::Address address, size_t size, bool isSigned ) { return ReadInt( mBuf.Get(), address, size, isSigned ); } uint64_t DataEnv::ReadInt( uint8_t* srcBuf, MagoEE::Address address, size_t size, bool isSigned ) { union Integer { uint8_t i8; uint16_t i16; uint32_t i32; uint64_t i64; }; Integer i = { 0 }; uint64_t u = 0; memcpy( &i, srcBuf + address, size ); switch ( size ) { case 1: if ( isSigned ) u = (int8_t) i.i8; else u = (uint8_t) i.i8; break; case 2: if ( isSigned ) u = (int16_t) i.i16; else u = (uint16_t) i.i16; break; case 4: if ( isSigned ) u = (int32_t) i.i32; else u = (uint32_t) i.i32; break; case 8: u = i.i64; break; } return u; } Real10 DataEnv::ReadFloat( MagoEE::Address address, MagoEE::Type* type ) { return ReadFloat( mBuf.Get(), address, type ); } Real10 DataEnv::ReadFloat( uint8_t* srcBuf, MagoEE::Address address, MagoEE::Type* type ) { union Float { float f32; double f64; Real10 f80; }; Float f = { 0 }; Real10 r; MagoEE::ENUMTY ty = MagoEE::Tnone; size_t size = 0; if ( type->IsComplex() ) { switch ( type->GetSize() ) { case 8: ty = MagoEE::Tfloat32; break; case 16: ty = MagoEE::Tfloat64; break; case 20: ty = MagoEE::Tfloat80; break; } } else if ( type->IsImaginary() ) { switch ( type->GetSize() ) { case 4: ty = MagoEE::Tfloat32; break; case 8: ty = MagoEE::Tfloat64; break; case 10: ty = MagoEE::Tfloat80; break; } } else // is real { switch ( type->GetSize() ) { case 4: ty = MagoEE::Tfloat32; break; case 8: ty = MagoEE::Tfloat64; break; case 10: ty = MagoEE::Tfloat80; break; } } switch ( ty ) { case MagoEE::Tfloat32: size = 4; break; case MagoEE::Tfloat64: size = 8; break; case MagoEE::Tfloat80: size = 10; break; } memcpy( &f, srcBuf + address, size ); switch ( ty ) { case MagoEE::Tfloat32: r.FromFloat( f.f32 ); break; case MagoEE::Tfloat64: r.FromDouble( f.f64 ); break; case MagoEE::Tfloat80: r = f.f80; break; } return r; } //---------------------------------------------------------------------------- DataEnvBinder::DataEnvBinder( IValueEnv* env, IScope* scope ) : mDataEnv( env ), mScope( scope ) { } HRESULT DataEnvBinder::FindObject( const wchar_t* name, MagoEE::Declaration*& decl, uint32_t findFlags ) { return mScope->FindObject( name, decl ); } HRESULT DataEnvBinder::GetThis( MagoEE::Declaration*& decl ) { return E_NOTIMPL; } HRESULT DataEnvBinder::GetSuper( MagoEE::Declaration*& decl ) { return E_NOTIMPL; } HRESULT DataEnvBinder::GetReturnType( MagoEE::Type*& type ) { return E_NOTIMPL; } HRESULT DataEnvBinder::NewTuple( const wchar_t* name, const std::vector<RefPtr<Declaration>>& decls, Declaration*& decl ) { return E_NOTIMPL; } HRESULT DataEnvBinder::GetValue( MagoEE::Declaration* decl, MagoEE::DataValue& value ) { std::shared_ptr<DataObj> val = mDataEnv->GetValue( decl ); if ( val == NULL ) throw L"No value."; value = val->Value; return S_OK; } HRESULT DataEnvBinder::GetValue( MagoEE::Address addr, MagoEE::Type* type, MagoEE::DataValue& value ) { std::shared_ptr<DataObj> val = mDataEnv->GetValue( addr, type ); if ( val == NULL ) throw L"No value."; value = val->Value; return S_OK; } HRESULT DataEnvBinder::GetValue( MagoEE::Address aArrayAddr, const MagoEE::DataObject& key, MagoEE::Address& valueAddr ) { return E_NOTIMPL; } int DataEnvBinder::GetAAVersion () { return -1; } HRESULT DataEnvBinder::GetClassName( MagoEE::Address addr, std::wstring& className, bool derefOnce ) { return E_NOTIMPL; } HRESULT DataEnvBinder::SetValue( MagoEE::Declaration* decl, const MagoEE::DataValue& value ) { MagoEE::Address addr = 0; RefPtr<Type> type; RValueObj obj; if ( !decl->GetAddress( addr ) ) throw L"Couldn't get address."; if ( !decl->GetType( type.Ref() ) ) throw L"Couldn't get type."; obj.SetType( type ); obj.Value = value; mDataEnv->SetValue( addr, &obj ); return S_OK; } HRESULT DataEnvBinder::SetValue( MagoEE::Address addr, MagoEE::Type* type, const MagoEE::DataValue& value ) { RValueObj obj; obj.SetType( type ); obj.Value = value; mDataEnv->SetValue( addr, &obj ); return S_OK; } HRESULT DataEnvBinder::ReadMemory( MagoEE::Address addr, uint32_t sizeToRead, uint32_t& sizeRead, uint8_t* buffer ) { return E_NOTIMPL; } HRESULT DataEnvBinder::SymbolFromAddr( MagoEE::Address addr, std::wstring& symName, MagoEE::Type** pType ) { return E_NOTIMPL; } HRESULT DataEnvBinder::CallFunction( MagoEE::Address addr, MagoEE::ITypeFunction* func, MagoEE::Address arg, MagoEE::DataObject& value, bool saveGC ) { return E_NOTIMPL; }
25.303178
150
0.574452
[ "vector" ]
6e82149885c6832046a8bb28933affa1a01df329
4,315
cpp
C++
03.Inheritance/School/Source.cpp
M-Yankov/CPlusPlus
76b8bc418e220f294bc5b0187b67d5210e8ec19e
[ "MIT" ]
null
null
null
03.Inheritance/School/Source.cpp
M-Yankov/CPlusPlus
76b8bc418e220f294bc5b0187b67d5210e8ec19e
[ "MIT" ]
null
null
null
03.Inheritance/School/Source.cpp
M-Yankov/CPlusPlus
76b8bc418e220f294bc5b0187b67d5210e8ec19e
[ "MIT" ]
null
null
null
#include "StudentStorage.h" #include "TeacherStorage.h" #include "GuestTeacherStorage.h" #include "Student.h" #include "Teacher.h" #include "GuestTeacher.h" #include <iostream> #include <array> #include <vector> #include <string> using namespace std; const int MIN_OPTION = 1; const int MAX_OPTION = 6; void WorkWithStudentStorage(int choice) { StudentStorage studentStorage = StudentStorage(); if (choice < 4) { unsigned short id; printf("Enter student id (number less than %d): ", USHRT_MAX); if (cin >> id) { cout << studentStorage.GetInfo(id) << endl; } else { cout << "id is not valid" << endl; } } else { unsigned short id; cout << "Enter student id " << "(" << 0 << "-" << USHRT_MAX << "):"; cin >> id; string name; cout << "Enter student name: "; cin.ignore(); getline(cin, name); int currentCourse; cout << "Enter student current course (int): "; cin >> currentCourse; int currentPoints; cout << "Enter student current points (int): "; cin >> currentPoints; // validation is missing - I am tired... Student student = Student(id, name, currentCourse, currentPoints); cout << studentStorage.AddToStorage(student) << endl; } } void WorkWithTeacherStorage(int choice) { TeacherStorage teacherStorage = TeacherStorage(); if (choice < 4) { unsigned short id; printf("Enter teacher id (number less than %d): ", USHRT_MAX); if (cin >> id) { cout << teacherStorage.GetInfo(id) << endl; } else { cout << "id is not valid" << endl; } } else { unsigned short id; cout << "Enter teacher id " << "(" << 0 << "-" << USHRT_MAX << "):"; cin >> id; string name; cout << "Enter teacher name: "; cin.ignore(); getline(cin, name); int currentCourse; cout << "Enter teacher current course (int): "; cin >> currentCourse; float salary; cout << "Enter teacher salary (float): "; cin >> salary; unsigned short daysInSoftUni; cout << "Enter teacher days in SoftUni " << "(" << 0 << "-" << USHRT_MAX << "):"; cin >> daysInSoftUni; // validation is missing - I am tired... Teacher teacher = Teacher(id, name, currentCourse, salary, daysInSoftUni); cout << teacherStorage.AddTeacherStorage(teacher) << endl; } } void WorkWithGuestTeacherStorage(int choice) { GuestTeacherStorage guestTeacherStorage = GuestTeacherStorage(); if (choice < 4) { unsigned short id; printf("Enter guest teacher id (number less than %d): ", USHRT_MAX); if (cin >> id) { cout << guestTeacherStorage.GetInfo(id) << endl; } else { cout << "id is not valid" << endl; } } else { unsigned short id; cout << "Enter guest teacher id " << "(" << 0 << "-" << USHRT_MAX << "):"; cin >> id; string name; cout << "Enter guest teacher name: "; cin.ignore(); getline(cin, name); int currentCourse; cout << "Enter guest teacher current course (int): "; cin >> currentCourse; float salary; cout << "Enter guest teacher salary for course (float): "; cin >> salary; // validation is missing - I am tired... GuestTeacher teacher = GuestTeacher(id, name, currentCourse, salary); cout << guestTeacherStorage.AddToStorage(teacher) << endl; } } int main() { // UINT16_MAX = 65535 // cout << UINT16_MAX << endl; // cout << USHRT_MAX << endl; // print Menu vector<string> menuOptions = { "Get data for student with ID", "Get data for teacher with ID", "Get data for guest teacher with ID", "Add data for new student", "Add data for new teacher", "Add data for new guest teacher" }; cout << "Menu:" << endl; for (size_t i = 0; i < menuOptions.size(); i++) { cout << i + 1 << ". " + menuOptions[i] << endl; } cout << "Enter an option number: "; int choice; while (!(cin >> choice) || MIN_OPTION > choice || choice > MAX_OPTION) { cout << "please enter a number between " << MIN_OPTION << " and " << MAX_OPTION << endl; cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } int storageChoice = choice % 3; switch (storageChoice) { case 1: WorkWithStudentStorage(choice); break; case 2: WorkWithTeacherStorage(choice); break; case 0: WorkWithGuestTeacherStorage(choice); break; default: throw "Invalid operation"; break; } cout << "\n\nEnd execution of program." << endl; return 0; }
21.683417
90
0.635921
[ "vector" ]
6e84cf532979725203a41aa3ed7a0d6138a14636
1,590
cpp
C++
problems/create_maximum_number/solution.cpp
sauravchandra1/Leetcode
be89c7d8d93083326a94906a28bfad2342aa1dfe
[ "MIT" ]
null
null
null
problems/create_maximum_number/solution.cpp
sauravchandra1/Leetcode
be89c7d8d93083326a94906a28bfad2342aa1dfe
[ "MIT" ]
null
null
null
problems/create_maximum_number/solution.cpp
sauravchandra1/Leetcode
be89c7d8d93083326a94906a28bfad2342aa1dfe
[ "MIT" ]
null
null
null
class Solution { public: bool compare(vector<int>& nums1, vector<int>& nums2, int start_i, int start_j) { int loop_size = min(nums1.size() - start_i, nums2.size() - start_j); for (int i = 0; i < loop_size; i++) { if (nums1[i + start_i] < nums2[i + start_j]) return true; else if (nums1[i + start_i] > nums2[i + start_j]) return false; } return nums1.size() - start_i < nums2.size() - start_j; } vector<vector<int>> largetsNum(vector<int>& nums) { vector<vector<int>> res; res.resize(nums.size() + 1); res.back() = nums; for (int i = res.size() - 2; i >= 0; i--) { int idx = 0; while (idx + 1 < res[i + 1].size()) { if (res[i + 1][idx] < res[i + 1][idx + 1]) break; idx++; } for (int j = 0; j < res[i + 1].size(); j++) { if (idx != j) res[i].push_back(res[i + 1][j]); } } return res; } vector<int> merge(vector<int>& nums1, vector<int>& nums2) { vector<int> res; int i = 0, j = 0; while (i < nums1.size() || j < nums2.size()) { if (compare(nums1, nums2, i, j)) res.push_back(nums2[j++]); else res.push_back(nums1[i++]); } return res; } vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, size_t k) { vector<vector<int>> largest_num1 = largetsNum(nums1); vector<vector<int>> largest_num2 = largetsNum(nums2); vector<int> res; int start = k > nums2.size() ? k - nums2.size() : 0; for (int i = start; i < largest_num1.size() && i <= k; i++) { vector<int> tmp = merge(largest_num1[i], largest_num2[k - i]); if (res.empty() || compare(res, tmp, 0, 0)) res = tmp; } return res; } };
21.2
78
0.579245
[ "vector" ]
6e8685d15b1b2701c093e5d8b71647ecf3321cc2
3,375
cpp
C++
src/crop_box/CropBoxFilter.cpp
Tobi2001/asr_next_best_view
7dace46b903d15e218a39f994802288103818f48
[ "BSD-3-Clause" ]
9
2019-12-10T07:39:07.000Z
2022-03-25T11:40:02.000Z
src/crop_box/CropBoxFilter.cpp
Tobi2001/asr_next_best_view
7dace46b903d15e218a39f994802288103818f48
[ "BSD-3-Clause" ]
null
null
null
src/crop_box/CropBoxFilter.cpp
Tobi2001/asr_next_best_view
7dace46b903d15e218a39f994802288103818f48
[ "BSD-3-Clause" ]
2
2020-01-13T17:41:33.000Z
2022-03-25T11:40:04.000Z
/** Copyright (c) 2016, Aumann Florian, Borella Jocelyn, Heller Florian, Meißner Pascal, Schleicher Ralf, Stöckle Patrick, Stroh Daniel, Trautmann Jeremias, Walter Milena, Wittenbeck Valerij 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. 4. The use is explicitly not permitted to any application which deliberately try to kill or do harm to any living creature. 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. */ #include "next_best_view/crop_box/CropBoxFilter.hpp" #include <vector> #include <set> namespace next_best_view { CropBoxFilter::CropBoxFilter(const std::string &xml_path) : GeneralFilter() { mCropBoxPtrList = CropBoxWrapper::readCropBoxDataFromXMLFile(xml_path); } void CropBoxFilter::doFiltering(IndicesPtr &indicesPtr) { ObjectPointCloudPtr inputObjectPointCloudPtr = this->getInputCloud(); ObjectPointCloudPtr processingPointCloudPtr = nullptr; if (getIndices() == nullptr) { processingPointCloudPtr = inputObjectPointCloudPtr; } else { processingPointCloudPtr = ObjectPointCloudPtr(new ObjectPointCloud(*inputObjectPointCloudPtr, *getIndices())); } //Filter the point cloud auto result = boost::make_shared<std::set<int>>(); for (CropBoxWrapperPtr cropBoxWrapper : *mCropBoxPtrList) { IndicesPtr filteredObjectIndices = IndicesPtr(new Indices()); CropBoxPtr cropBoxPtr = cropBoxWrapper->getCropBox(); cropBoxPtr->setInputCloud(processingPointCloudPtr); cropBoxPtr->filter(*filteredObjectIndices); // put all filtered objects into the result set result->insert(filteredObjectIndices->begin(), filteredObjectIndices->end()); } // put result set into indicesPtr vector std::copy(result->begin(), result->end(), std::back_inserter(*indicesPtr)); } boost::shared_ptr<std::vector<CropBoxWrapperPtr>> CropBoxFilter::getCropBoxWrapperPtrList() { return mCropBoxPtrList; } }
55.327869
755
0.752593
[ "vector" ]
6e8d4dc9da7582aa6b5c64de93b7f7d9f6c6ee37
42,331
cpp
C++
src/OpenRTMPlugin/RTSystemItem.cpp
jun0/choreonoid
37167e52bfa054088272e1924d2062604104ac08
[ "MIT" ]
null
null
null
src/OpenRTMPlugin/RTSystemItem.cpp
jun0/choreonoid
37167e52bfa054088272e1924d2062604104ac08
[ "MIT" ]
null
null
null
src/OpenRTMPlugin/RTSystemItem.cpp
jun0/choreonoid
37167e52bfa054088272e1924d2062604104ac08
[ "MIT" ]
null
null
null
#include "RTSystemItem.h" #include "RTSCommonUtil.h" #include <cnoid/MessageView> #include <cnoid/ItemManager> #include <cnoid/Archive> #include <cnoid/EigenArchive> #include <cnoid/AppConfig> #include <boost/format.hpp> #include "LoggerUtil.h" #include "gettext.h" using namespace cnoid; using namespace std; using namespace std::placeholders; using namespace RTC; using boost::format; namespace cnoid { struct RTSPortComparator { std::string name_; RTSPortComparator(std::string value) { name_ = value; } bool operator()(const RTSPortPtr elem) const { return (name_ == elem->name); } }; class RTSystemItemImpl { public: RTSystemItem* self; Connection locationChangedConnection; map<string, RTSCompPtr> rtsComps; RTSystemItem::RTSConnectionMap rtsConnections; int connectionNo; bool autoConnection; std::string vendorName; std::string version; int pollingCycle; bool checkAtLoading; #if defined(OPENRTM_VERSION12) int heartBeatPeriod; #endif enum State_Detection { POLLING_CHECK = 0, MANUAL_CHECK, #if defined(OPENRTM_VERSION12) OBSERVER_CHECK, #endif N_STATE_DETECTION }; Selection stateCheck; RTSystemItemImpl(RTSystemItem* self); RTSystemItemImpl(RTSystemItem* self, const RTSystemItemImpl& org); ~RTSystemItemImpl(); void initialize(); void onLocationChanged(std::string host, int port); RTSComp* addRTSComp(const string& name, const QPointF& pos); RTSComp* addRTSComp(const NamingContextHelper::ObjectInfo& info, const QPointF& pos); void deleteRTSComp(const string& name); RTSComp* nameToRTSComp(const string& name); bool compIsAlive(RTSComp* rtsComp); RTSConnection* addRTSConnection( const string& id, const string& name, RTSPort* sourcePort, RTSPort* targetPort, const std::vector<NamedValuePtr>& propList, const bool setPos, const Vector2 pos[]); RTSConnection* addRTSConnectionName( const string& id, const string& name, const string& sourceComp, const string& sourcePort, const string& targetComp, const string& targetPort, const string& dataflow, const string& subscription, const bool setPos, const Vector2 pos[]); bool connectionCheck(); void RTSCompToConnectionList(const RTSComp* rtsComp, list<RTSConnection*>& rtsConnectionList, int mode); void removeConnection(RTSConnection* connection); void doPutProperties(PutPropertyFunction& putProperty); bool saveRtsProfile(const string& filename); void restoreRTSystem(const Archive& archive); void restoreRTSComp(const string& name, const Vector2& pos, const vector<pair<string, bool>>& inPorts, const vector<pair<string, bool>>& outPorts); string getConnectionNumber(); void setStateCheckMethodByString(const string& value); bool checkStatus(); Signal<void(int)> sigTimerPeriodChanged; Signal<void(bool)> sigTimerChanged; Signal<void(bool)> sigLoaded; void changeStateCheck(); void changePollingPeriod(int value); private: void setStateCheckMethod(int value); }; } ////////// RTSPort::RTSPort(const string& name_, PortService_var port_, RTSComp* parent) : rtsComp(parent) { isInPort = true; name = name_; port = port_; // if (port) { RTC::PortProfile_var profile = port->get_port_profile(); RTC::PortInterfaceProfileList interfaceList = profile->interfaces; for (CORBA::ULong index = 0; index < interfaceList.length(); ++index) { RTC::PortInterfaceProfile ifProfile = interfaceList[index]; PortInterfacePtr portIf(new PortInterface()); if (parent) { portIf->rtc_name = parent->name; } const char* port_name; portIf->port_name = string((const char*)profile->name); if (ifProfile.polarity == PortInterfacePolarity::REQUIRED) { portIf->if_polarity = "required"; } else { portIf->if_polarity = "provided"; } const char* if_iname; const char* if_tname; if_iname = (const char*)ifProfile.instance_name; if_tname = (const char*)ifProfile.type_name; DDEBUG_V("name: %s, IF name: %s, instance_name: %s, type_name: %s", name_.c_str(), portIf->port_name.c_str(), if_iname, if_tname); portIf->if_tname = if_tname; portIf->if_iname = if_iname; interList.push_back(portIf); } } } bool RTSPort::isConnected() { if (!port || !isObjectAlive(port)) { return false; } ConnectorProfileList_var connectorProfiles = port->get_connector_profiles(); return connectorProfiles->length() != 0; } bool RTSPort::isConnectedWith(RTSPort* target) { if (!port || !target->port || CORBA::is_nil(port) || port->_non_existent() || CORBA::is_nil(target->port) || target->port->_non_existent()) { return false; } ConnectorProfileList_var connectorProfiles = port->get_connector_profiles(); for (CORBA::ULong i = 0; i < connectorProfiles->length(); ++i) { ConnectorProfile& connectorProfile = connectorProfiles[i]; PortServiceList& connectedPorts = connectorProfile.ports; for (CORBA::ULong j = 0; j < connectedPorts.length(); ++j) { PortService_ptr connectedPortRef = connectedPorts[j]; if (connectedPortRef->_is_equivalent(target->port)) { return true; } } } return false; } bool RTSPort::checkConnectablePort(RTSPort* target) { DDEBUG("RTSPort::checkConnectablePort"); if (rtsComp == target->rtsComp) { return false; } if (!port || !target->port) { return false; } if ((isInPort && target->isInPort) || (isInPort && target->isServicePort) || (!isInPort && !isServicePort && !target->isInPort) || (isServicePort && !target->isServicePort)) { return false; } //In case of connection between data ports if (!isServicePort && !target->isServicePort) { vector<string> dataTypes = RTCCommonUtil::getAllowDataTypes(this, target); vector<string> ifTypes = RTCCommonUtil::getAllowInterfaceTypes(this, target); vector<string> subTypes = RTCCommonUtil::getAllowSubscriptionTypes(this, target); if (dataTypes.size() == 0 || ifTypes.size() == 0 || subTypes.size() == 0) { return false; } } return true; } vector<string> RTSPort::getDataTypes() { return getProperty("dataport.data_type"); } vector<string> RTSPort::getInterfaceTypes() { return getProperty("dataport.interface_type"); } vector<string> RTSPort::getDataflowTypes() { return getProperty("dataport.dataflow_type"); } vector<string> RTSPort::getSubscriptionTypes() { return getProperty("dataport.subscription_type"); } vector<string> RTSPort::getProperty(const string& key) { vector<string> result; NVList properties = port->get_port_profile()->properties; for (int index = 0; index < properties.length(); ++index) { string strName(properties[index].name._ptr); if (strName == key) { const char* nvValue; properties[index].value >>= nvValue; string strValue(nvValue); result = RTCCommonUtil::split(strValue, ','); break; } } return result; } RTSConnection::RTSConnection(const string& id, const string& name, const string& sourceRtcName, const string& sourcePortName, const string& targetRtcName, const string& targetPortName) : id(id), name(name), sourceRtcName(sourceRtcName), sourcePortName(sourcePortName), targetRtcName(targetRtcName), targetPortName(targetPortName), setPos(false) { isAlive_ = false; } bool RTSConnection::connect() { DDEBUG("RTSConnection::connect"); if (!sourcePort || !targetPort) { return false; } if (!sourcePort->port || !targetPort->port || CORBA::is_nil(sourcePort->port) || sourcePort->port->_non_existent() || CORBA::is_nil(targetPort->port) || targetPort->port->_non_existent()) { DDEBUG("RTSConnection::connect False"); return false; } if (sourcePort->isConnectedWith(targetPort)) { return false; } ConnectorProfile cprof; cprof.connector_id = CORBA::string_dup(id.c_str()); cprof.name = CORBA::string_dup(name.c_str()); cprof.ports.length(2); cprof.ports[0] = PortService::_duplicate(sourcePort->port); cprof.ports[1] = PortService::_duplicate(targetPort->port); for (int index = 0; index < propList.size(); index++) { NamedValuePtr param = propList[index]; CORBA_SeqUtil::push_back( cprof.properties, NVUtil::newNV(param->name_.c_str(), param->value_.c_str())); } RTC::ReturnCode_t result = sourcePort->port->connect(cprof); if (result == RTC::RTC_OK) { PortProfile_var portprofile = sourcePort->port->get_port_profile(); ConnectorProfileList connections = portprofile->connector_profiles; for (CORBA::ULong i = 0; i < connections.length(); i++) { ConnectorProfile& connector = connections[i]; PortServiceList& connectedPorts = connector.ports; for (CORBA::ULong j = 0; j < connectedPorts.length(); ++j) { PortService_ptr connectedPortRef = connectedPorts[j]; if (connectedPortRef->_is_equivalent(targetPort->port)) { id = string(connector.connector_id); isAlive_ = true; DDEBUG("RTSConnection::connect End"); return true; } } } return false; } DDEBUG("connect Error"); return false; } bool RTSConnection::disconnect() { isAlive_ = false; if (CORBA::is_nil(sourcePort->port) || sourcePort->port->_non_existent()) { return false; } return (sourcePort->port->disconnect(id.c_str()) == RTC_OK); } void RTSConnection::setPosition(const Vector2 pos[]) { for (int i = 0; i < 6; ++i) { position[i] = pos[i]; } setPos = true; srcRTC->rts()->suggestFileUpdate(); } RTSComp::RTSComp(const string& name, const std::string& fullPath, RTC::RTObject_ptr rtc, RTSystemItem* rts, const QPointF& pos, const string& host, int port) : rts_(rts), pos_(pos), name(name), fullPath(fullPath), hostAddress(host), portNo(port) { setRtc(rtc); } void RTSComp::setRtc(RTObject_ptr rtc) { DDEBUG("RTSComp::setRtc"); rtc_ = 0; rts_->suggestFileUpdate(); setRTObject(rtc); if (!isObjectAlive(rtc)) { participatingExeContList = 0; for (auto it = inPorts.begin(); it != inPorts.end(); ++it) { RTSPort* port = *it; port->port = 0; } for (auto it = outPorts.begin(); it != outPorts.end(); ++it) { RTSPort* port = *it; port->port = 0; } DDEBUG("RTSComp::setRtc Failed"); return; } ComponentProfile_var cprofile = rtc_->get_component_profile(); participatingExeContList = rtc_->get_participating_contexts(); inPorts.clear(); outPorts.clear(); PortServiceList_var portlist = rtc_->get_ports(); for (CORBA::ULong i = 0; i < portlist->length(); ++i) { PortProfile_var portprofile = portlist[i]->get_port_profile(); coil::Properties pproperties = NVUtil::toProperties(portprofile->properties); string portType = pproperties["port.port_type"]; RTSPortPtr rtsPort = new RTSPort(string(portprofile->name), portlist[i], this); if (RTCCommonUtil::compareIgnoreCase(portType, "CorbaPort")) { rtsPort->isServicePort = true; rtsPort->isInPort = false; outPorts.push_back(rtsPort); } else { rtsPort->isServicePort = false; if (RTCCommonUtil::compareIgnoreCase(portType, "DataInPort")) { inPorts.push_back(rtsPort); } else { rtsPort->isInPort = false; outPorts.push_back(rtsPort); } } } list<RTSConnection*> rtsConnectionList; rts_->impl->RTSCompToConnectionList(this, rtsConnectionList, 0); for (auto it = rtsConnectionList.begin(); it != rtsConnectionList.end(); ++it) { RTSConnectionPtr connection = (*it); rts_->impl->removeConnection(*it); RTSPort* sourcePort = connection->srcRTC->nameToRTSPort(connection->sourcePortName); RTSPort* targetPort = connection->targetRTC->nameToRTSPort(connection->targetPortName); if (sourcePort && targetPort) { connection->sourcePort = sourcePort; connection->targetPort = targetPort; rts_->impl->rtsConnections[RTSystemItem::RTSPortPair(sourcePort, targetPort)] = connection; } } connectionCheck(); DDEBUG("RTSComp::setRtc End"); } RTSPort* RTSComp::nameToRTSPort(const string& name) { //DDEBUG_V("RTSComp::nameToRTSPort %s", name.c_str()); auto it = find_if(inPorts.begin(), inPorts.end(), RTSPortComparator(name)); if (it != inPorts.end()) { return *it; } it = find_if(outPorts.begin(), outPorts.end(), RTSPortComparator(name)); if (it != outPorts.end()) { return *it; } return nullptr; } bool RTSComp::connectionCheck() { //DDEBUG("RTSComp::connectionCheck"); bool updated = false; for (auto it = inPorts.begin(); it != inPorts.end(); ++it) { if (connectionCheckSub(*it)) { updated = true; } } for (auto it = outPorts.begin(); it != outPorts.end(); it++) { if (connectionCheckSub(*it)) { updated = true; } } return updated; } bool RTSComp::connectionCheckSub(RTSPort* rtsPort) { bool updated = false; if (isObjectAlive(rtsPort->port) == false) return updated; /** The get_port_profile() function should not be used here because it takes much time when the port has large data and its owner RTC is in a remote host. The get_connector_profiles() function does not seem to cause such a problem. */ ConnectorProfileList_var connectorProfiles = rtsPort->port->get_connector_profiles(); for (CORBA::ULong i = 0; i < connectorProfiles->length(); ++i) { ConnectorProfile& connectorProfile = connectorProfiles[i]; PortServiceList& connectedPorts = connectorProfile.ports; for (CORBA::ULong j = 0; j < connectedPorts.length(); ++j) { PortService_var connectedPortRef = connectedPorts[j]; if(CORBA::is_nil(connectedPortRef)){ continue; } PortProfile_var connectedPortProfile; try { connectedPortProfile = connectedPortRef->get_port_profile(); } catch (CORBA::SystemException& ex) { MessageView::instance()->putln( MessageView::WARNING, format(_("CORBA %1% (%2%), %3% in RTSComp::connectionCheckSub()")) % ex._name() % ex._rep_id() % ex.NP_minorString()); continue; } string portName = string(connectedPortProfile->name); vector<string> target; RTCCommonUtil::splitPortName(portName, target); if (target[0] == name) continue; string rtcPath; if(!getComponentPath(connectedPortRef, rtcPath)){ continue; } RTSComp* targetRTC = rts_->impl->nameToRTSComp("/" + rtcPath); if(!targetRTC){ continue; } //DDEBUG("targetRTC Found"); RTSPort* targetPort = targetRTC->nameToRTSPort(portName); if (targetPort) { auto itr = rts_->impl->rtsConnections.find(RTSystemItem::RTSPortPair(rtsPort, targetPort)); if (itr != rts_->impl->rtsConnections.end()) { continue; } RTSConnectionPtr rtsConnection = new RTSConnection( string(connectorProfile.connector_id), string(connectorProfile.name), name, rtsPort->name, target[0], portName); coil::Properties properties = NVUtil::toProperties(connectorProfile.properties); vector<NamedValuePtr> propList; NamedValuePtr dataType(new NamedValue("dataport.dataflow_type", properties["dataport.dataflow_type"])); propList.push_back(dataType); NamedValuePtr subscription(new NamedValue("dataport.subscription_type", properties["dataport.subscription_type"])); rtsConnection->propList = propList; rtsConnection->srcRTC = this; rtsConnection->sourcePort = nameToRTSPort(rtsConnection->sourcePortName); rtsConnection->targetRTC = targetRTC; rtsConnection->targetPort = targetRTC->nameToRTSPort(rtsConnection->targetPortName); rtsConnection->isAlive_ = true; rts_->impl->rtsConnections[RTSystemItem::RTSPortPair(rtsPort, targetPort)] = rtsConnection; rts_->suggestFileUpdate(); updated = true; } } } return updated; } bool RTSComp::getComponentPath(RTC::PortService_ptr source, std::string& out_path) { PortProfile_var portprofile = source->get_port_profile(); if(!CORBA::is_nil(portprofile->owner)){ ComponentProfile_var cprofile; try { cprofile = portprofile->owner->get_component_profile(); } catch (CORBA::SystemException& ex) { MessageView::instance()->putln( MessageView::WARNING, format(_("CORBA %1% (%2%), %3% in RTSComp::getComponentPath()")) % ex._name() % ex._rep_id() % ex.NP_minorString()); return false; } NVList properties = cprofile->properties; for(int index = 0; index < properties.length(); ++index){ string strName(properties[index].name._ptr); if(strName == "naming.names"){ const char* nvValue; properties[index].value >>= nvValue; out_path = string(nvValue); return true; } } } return false; } void RTSComp::setPos(const QPointF& p) { if (p != pos_) { pos_ = p; rts_->suggestFileUpdate(); } } void RTSystemItem::initializeClass(ExtensionManager* ext) { DDEBUG("RTSystemItem::initializeClass"); ItemManager& im = ext->itemManager(); im.registerClass<RTSystemItem>(N_("RTSystemItem")); im.addCreationPanel<RTSystemItem>(); im.addLoaderAndSaver<RTSystemItem>( _("RT-System"), "RTS-PROFILE-XML", "xml", [](RTSystemItem* item, const std::string& filename, std::ostream&, Item*) { return item->loadRtsProfile(filename); }, [](RTSystemItem* item, const std::string& filename, std::ostream&, Item*) { return item->saveRtsProfile(filename); }); } RTSystemItem::RTSystemItem() { DDEBUG("RTSystemItem::RTSystemItem"); impl = new RTSystemItemImpl(this); } RTSystemItemImpl::RTSystemItemImpl(RTSystemItem* self) : self(self) { initialize(); autoConnection = true; } RTSystemItem::RTSystemItem(const RTSystemItem& org) : Item(org) { impl = new RTSystemItemImpl(this, *org.impl); } RTSystemItemImpl::RTSystemItemImpl(RTSystemItem* self, const RTSystemItemImpl& org) : self(self), pollingCycle(1000) { initialize(); autoConnection = org.autoConnection; } void RTSystemItemImpl::initialize() { DDEBUG("RTSystemItemImpl::initialize"); connectionNo = 0; Mapping* config = AppConfig::archive()->openMapping("OpenRTM"); vendorName = config->get("defaultVendor", "AIST"); version = config->get("defaultVersion", "1.0.0"); stateCheck.setSymbol(POLLING_CHECK, "Polling"); stateCheck.setSymbol(MANUAL_CHECK, "Manual"); checkAtLoading = true; #if defined(OPENRTM_VERSION12) stateCheck.setSymbol(OBSERVER_CHECK, "Observer"); heartBeatPeriod = config->get("heartBeatPeriod", 500); #endif } RTSystemItem::~RTSystemItem() { delete impl; } RTSystemItemImpl::~RTSystemItemImpl() { locationChangedConnection.disconnect(); } Item* RTSystemItem::doDuplicate() const { return new RTSystemItem(*this); } void RTSystemItemImpl::onLocationChanged(string host, int port) { NameServerManager::instance()->getNCHelper()->setLocation(host, port); } RTSComp* RTSystemItem::nameToRTSComp(const string& name) { return impl->nameToRTSComp(name); } RTSComp* RTSystemItemImpl::nameToRTSComp(const string& name) { //DDEBUG_V("RTSystemItemImpl::nameToRTSComp:%s", name.c_str()); map<string, RTSCompPtr>::iterator it = rtsComps.find(name); if (it == rtsComps.end()) return 0; else return it->second.get(); } RTSComp* RTSystemItem::addRTSComp(const string& name, const QPointF& pos) { return impl->addRTSComp(name, pos); } RTSComp* RTSystemItemImpl::addRTSComp(const string& name, const QPointF& pos) { DDEBUG_V("RTSystemItemImpl::addRTSComp:%s", name.c_str()); if (!nameToRTSComp("/" + name + ".rtc")) { std::vector<NamingContextHelper::ObjectPath> pathList; NamingContextHelper::ObjectPath path(name, "rtc"); pathList.push_back(path); NamingContextHelper* ncHelper = NameServerManager::instance()->getNCHelper(); RTC::RTObject_ptr rtc = ncHelper->findObject<RTC::RTObject>(pathList); DDEBUG_V("ncHelper host:%s, port:%d", ncHelper->host().c_str(), ncHelper->port()); if (rtc == RTC::RTObject::_nil()) { DDEBUG("RTSystemItemImpl::addRTSComp Failed"); return nullptr; } string fullPath = "/" + name + ".rtc"; RTSCompPtr rtsComp = new RTSComp(name, fullPath, rtc, self, pos, ncHelper->host().c_str(), ncHelper->port()); rtsComps[fullPath] = rtsComp; self->suggestFileUpdate(); return rtsComp; } return nullptr; } RTSComp* RTSystemItem::addRTSComp(const NamingContextHelper::ObjectInfo& info, const QPointF& pos) { return impl->addRTSComp(info, pos); } RTSComp* RTSystemItemImpl::addRTSComp(const NamingContextHelper::ObjectInfo& info, const QPointF& pos) { DDEBUG("RTSystemItemImpl::addRTSComp"); string fullPath = info.getFullPath(); if (!nameToRTSComp(fullPath)) { std::vector<NamingContextHelper::ObjectPath> target = info.fullPath_; auto ncHelper = NameServerManager::instance()->getNCHelper(); ncHelper->setLocation(info.hostAddress_, info.portNo_); RTC::RTObject_ptr rtc = ncHelper->findObject<RTC::RTObject>(target); if (!isObjectAlive(rtc)) { CORBA::release(rtc); rtc = nullptr; } RTSCompPtr rtsComp = new RTSComp(info.id_, fullPath, rtc, self, pos, info.hostAddress_, info.portNo_); rtsComps[fullPath] = rtsComp; self->suggestFileUpdate(); return rtsComp.get(); } return nullptr; } void RTSystemItem::deleteRTSComp(const string& name) { impl->deleteRTSComp(name); } void RTSystemItemImpl::deleteRTSComp(const string& name) { if (rtsComps.erase(name) > 0) { self->suggestFileUpdate(); } } bool RTSystemItem::compIsAlive(RTSComp* rtsComp) { return impl->compIsAlive(rtsComp); } bool RTSystemItemImpl::compIsAlive(RTSComp* rtsComp) { //DDEBUG("RTSystemItemImpl::compIsAlive"); if (rtsComp->isAlive_ && rtsComp->rtc_ && rtsComp->rtc_ != nullptr) { if (isObjectAlive(rtsComp->rtc_)) { return true; } else { rtsComp->setRtc(nullptr); return false; } } else { //DDEBUG_V("Full Path = %s", rtsComp->fullPath.c_str()); QStringList nameList = QString::fromStdString(rtsComp->fullPath).split("/"); std::vector<NamingContextHelper::ObjectPath> pathList; for (int index = 0; index < nameList.count(); index++) { QString elem = nameList[index]; if (elem.length() == 0) continue; QStringList elemList = elem.split("."); if (elemList.size() != 2) return false; NamingContextHelper::ObjectPath path(elemList[0].toStdString(), elemList[1].toStdString()); pathList.push_back(path); } NameServerManager::instance()->getNCHelper()->setLocation(rtsComp->hostAddress, rtsComp->portNo); RTC::RTObject_ptr rtc = NameServerManager::instance()->getNCHelper()->findObject<RTC::RTObject>(pathList); if (!isObjectAlive(rtc)) { //DDEBUG("RTSystemItemImpl::compIsAlive NOT Alive"); return false; } else { DDEBUG("RTSystemItemImpl::compIsAlive Alive"); rtsComp->setRtc(rtc); if (autoConnection) { list<RTSConnection*> rtsConnectionList; RTSCompToConnectionList(rtsComp, rtsConnectionList, 0); for (auto it = rtsConnectionList.begin(); it != rtsConnectionList.end(); it++) { auto connection = *it; connection->connect(); } DDEBUG("autoConnection End"); } return true; } } } string RTSystemItemImpl::getConnectionNumber() { stringstream ss; ss << connectionNo; connectionNo++; return ss.str(); } RTSConnection* RTSystemItem::addRTSConnection (const std::string& id, const std::string& name, RTSPort* sourcePort, RTSPort* targetPort, const std::vector<NamedValuePtr>& propList, const Vector2 pos[]) { bool setPos = true; if (!pos) setPos = false; return impl->addRTSConnection(id, name, sourcePort, targetPort, propList, setPos, pos); } RTSConnection* RTSystemItemImpl::addRTSConnection (const string& id, const string& name, RTSPort* sourcePort, RTSPort* targetPort, const std::vector<NamedValuePtr>& propList, const bool setPos, const Vector2 pos[]) { DDEBUG("RTSystemItemImpl::addRTSConnection"); bool updated = false; RTSConnection* rtsConnection_; auto it = rtsConnections.find(RTSystemItem::RTSPortPair(sourcePort, targetPort)); if (it != rtsConnections.end()) { rtsConnection_ = it->second;; } else { RTSConnectionPtr rtsConnection = new RTSConnection( id, name, sourcePort->rtsComp->name, sourcePort->name, targetPort->rtsComp->name, targetPort->name); rtsConnection->srcRTC = sourcePort->rtsComp; rtsConnection->sourcePort = sourcePort; rtsConnection->targetRTC = targetPort->rtsComp; rtsConnection->targetPort = targetPort; rtsConnection->propList = propList; if (setPos) { rtsConnection->setPosition(pos); } rtsConnections[RTSystemItem::RTSPortPair(sourcePort, targetPort)] = rtsConnection; rtsConnection_ = rtsConnection; updated = true; } if (!CORBA::is_nil(sourcePort->port) && !sourcePort->port->_non_existent() && !CORBA::is_nil(targetPort->port) && !targetPort->port->_non_existent()) { if (rtsConnection_->connect()) { updated = true; } } if (rtsConnection_->id.empty()) { rtsConnection_->id = "NoConnection_" + getConnectionNumber(); updated = true; } if (updated) { self->suggestFileUpdate(); } return rtsConnection_; } RTSConnection* RTSystemItemImpl::addRTSConnectionName (const string& id, const string& name, const string& sourceCompName, const string& sourcePortName, const string& targetCompName, const string& targetPortName, const string& dataflow, const string& subscription, const bool setPos, const Vector2 pos[]) { string sourceId = "/" + sourceCompName + ".rtc"; RTSPort* sourcePort = 0; RTSComp* sourceRtc = nameToRTSComp(sourceId); if (sourceRtc) { sourcePort = sourceRtc->nameToRTSPort(sourcePortName); } string targetId = "/" + targetCompName + ".rtc"; RTSPort* targetPort = 0; RTSComp* targetRtc = nameToRTSComp(targetId); if (targetRtc) { targetPort = targetRtc->nameToRTSPort(targetPortName); } if (sourcePort && targetPort) { vector<NamedValuePtr> propList; NamedValuePtr paramDataFlow(new NamedValue("dataport.dataflow_type", dataflow)); propList.push_back(paramDataFlow); NamedValuePtr paramSubscription(new NamedValue("dataport.subscription_type", subscription)); propList.push_back(paramSubscription); NamedValuePtr sinterfaceProp(new NamedValue("dataport.interface_type", "corba_cdr")); propList.push_back(sinterfaceProp); return addRTSConnection(id, name, sourcePort, targetPort, propList, setPos, pos); } return nullptr; } bool RTSystemItem::connectionCheck() { return impl->connectionCheck(); } bool RTSystemItemImpl::connectionCheck() { //DDEBUG("RTSystemItemImpl::connectionCheck"); bool updated = false; for (auto it = rtsConnections.begin(); it != rtsConnections.end(); it++) { const RTSystemItem::RTSPortPair& ports = it->first; if (ports(0)->isConnectedWith(ports(1))) { if (!it->second->isAlive_) { it->second->isAlive_ = true; updated = true; } } else { if (it->second->isAlive_) { it->second->isAlive_ = false; updated = true; } } } for (auto it = rtsComps.begin(); it != rtsComps.end(); it++) { if (it->second->connectionCheck()) { updated = true; } } //DDEBUG("RTSystemItemImpl::connectionCheck End"); return updated; } void RTSystemItem::RTSCompToConnectionList (const RTSComp* rtsComp, list<RTSConnection*>& rtsConnectionList, int mode) { impl->RTSCompToConnectionList(rtsComp, rtsConnectionList, mode); } void RTSystemItemImpl::RTSCompToConnectionList (const RTSComp* rtsComp, list<RTSConnection*>& rtsConnectionList, int mode) { for (RTSystemItem::RTSConnectionMap::iterator it = rtsConnections.begin(); it != rtsConnections.end(); it++) { switch (mode) { case 0: default: if (it->second->sourceRtcName == rtsComp->name || it->second->targetRtcName == rtsComp->name) rtsConnectionList.push_back(it->second); break; case 1: if (it->second->sourceRtcName == rtsComp->name) rtsConnectionList.push_back(it->second); break; case 2: if (it->second->targetRtcName == rtsComp->name) rtsConnectionList.push_back(it->second); break; } } } map<string, RTSCompPtr>& RTSystemItem::rtsComps() { return impl->rtsComps; } RTSystemItem::RTSConnectionMap& RTSystemItem::rtsConnections() { return impl->rtsConnections; } void RTSystemItem::disconnectAndRemoveConnection(RTSConnection* connection) { connection->disconnect(); impl->removeConnection(connection); } void RTSystemItemImpl::removeConnection(RTSConnection* connection) { RTSystemItem::RTSPortPair pair(connection->sourcePort, connection->targetPort); if (rtsConnections.erase(pair) > 0) { self->suggestFileUpdate(); } } void RTSystemItem::doPutProperties(PutPropertyFunction& putProperty) { impl->doPutProperties(putProperty); } void RTSystemItemImpl::doPutProperties(PutPropertyFunction& putProperty) { DDEBUG("RTSystemItemImpl::doPutProperties"); putProperty(_("Auto Connection"), autoConnection, changeProperty(autoConnection)); putProperty(_("Vendor Name"), vendorName, changeProperty(vendorName)); putProperty(_("Version"), version, changeProperty(version)); putProperty(_("State Check"), stateCheck, [&](int value) { setStateCheckMethod(value); return true; }); putProperty(_("Polling Cycle"), pollingCycle, [&](int value) { changePollingPeriod(value); return true; }); putProperty(_("CheckAtLoading"), checkAtLoading, changeProperty(checkAtLoading)); #if defined(OPENRTM_VERSION12) putProperty(_("HeartBeat Period"), heartBeatPeriod, changeProperty(heartBeatPeriod)); #endif } void RTSystemItemImpl::changePollingPeriod(int value) { DDEBUG_V("RTSystemItemImpl::changePollingPeriod=%d", value); if (pollingCycle != value) { pollingCycle = value; sigTimerPeriodChanged(value); } } void RTSystemItemImpl::setStateCheckMethod(int value) { DDEBUG_V("RTSystemItemImpl::setStateCheckMethod=%d", value); stateCheck.selectIndex(value); changeStateCheck(); } void RTSystemItemImpl::setStateCheckMethodByString(const string& value) { DDEBUG_V("RTSystemItemImpl::setStateCheckMethodByString=%s", value.c_str()); stateCheck.select(value); DDEBUG_V("RTSystemItemImpl::setStateCheckMethodByString=%d", stateCheck.selectedIndex()); changeStateCheck(); } void RTSystemItemImpl::changeStateCheck() { int state = stateCheck.selectedIndex(); DDEBUG_V("RTSystemItemImpl::changeStateCheck=%d", state); switch (state) { case MANUAL_CHECK: sigTimerChanged(false); break; #if defined(OPENRTM_VERSION12) case OBSERVER_CHECK: break; #endif default: sigTimerChanged(true); break; } } bool RTSystemItem::loadRtsProfile(const string& filename) { DDEBUG_V("RTSystemItem::loadRtsProfile=%s", filename.c_str()); ProfileHandler::getRtsProfileInfo(filename, impl->vendorName, impl->version); if (ProfileHandler::restoreRtsProfile(filename, this)) { impl->sigLoaded(false); return true; } return false; } bool RTSystemItem::saveRtsProfile(const string& filename) { return impl->saveRtsProfile(filename); } bool RTSystemItemImpl::saveRtsProfile(const string& filename) { DDEBUG_V("RTSystemItem::saveRtsProfile=%s", filename.c_str()); if (vendorName.empty()) { vendorName = "Choreonoid"; } if (version.empty()) { version = "1.0.0"; } string systemId = "RTSystem:" + vendorName + ":" + self->name() + ":" + version; ProfileHandler::saveRtsProfile(filename, systemId, rtsComps, rtsConnections, MessageView::mainInstance()->cout()); return true; } int RTSystemItem::pollingCycle() const { return impl->pollingCycle; } void RTSystemItem::setVendorName(const std::string& name) { impl->vendorName = name; } void RTSystemItem::setVersion(const std::string& version) { impl->version = version; } int RTSystemItem::stateCheck() const { return impl->stateCheck.selectedIndex(); } bool RTSystemItem::checkStatus() { return impl->checkStatus(); } bool RTSystemItemImpl::checkStatus() { bool modified = false; for (auto it = rtsComps.begin(); it != rtsComps.end(); it++) { if (compIsAlive(it->second)) { if (!it->second->isAlive_) { modified = true; } it->second->isAlive_ = true; } else { if (it->second->isAlive_) { modified = true; } it->second->isAlive_ = false; } } // if (connectionCheck()) { modified = true; } return modified; } /////////// bool RTSystemItem::store(Archive& archive) { if (overwrite()) { archive.writeRelocatablePath("filename", filePath()); archive.write("format", fileFormat()); archive.write("autoConnection", impl->autoConnection); archive.write("pollingCycle", impl->pollingCycle); archive.write("stateCheck", impl->stateCheck.selectedSymbol()); archive.write("checkAtLoading", impl->checkAtLoading); #if defined(OPENRTM_VERSION12) archive.write("heartBeatPeriod", impl->heartBeatPeriod); #endif return true; } return true; } bool RTSystemItem::restore(const Archive& archive) { DDEBUG("RTSystemItemImpl::restore"); if (archive.read("autoConnection", impl->autoConnection) == false) { archive.read("AutoConnection", impl->autoConnection); } if( archive.read("checkAtLoading", impl->checkAtLoading)==false) { archive.read("CheckAtLoading", impl->checkAtLoading); } int pollingCycle = 1000; if( archive.read("pollingCycle", pollingCycle)==false) { archive.read("PollingCycle", pollingCycle); } impl->changePollingPeriod(pollingCycle); #if defined(OPENRTM_VERSION12) if(archive.read("HeartBeatPeriod", impl->heartBeatPeriod) == false) { archive.read("heartBeatPeriod", impl->heartBeatPeriod); } #endif /** The contents of RTSystemItem must be loaded after all the items are restored so that the states of the RTCs created by other items can be loaded. */ std::string filename, formatId; if (archive.readRelocatablePath("filename", filename)) { if (archive.read("format", formatId)) { archive.addPostProcess( [this, filename, formatId]() { load(filename, formatId); }); } } else { // old format data contained in a project file archive.addPostProcess([&]() { impl->restoreRTSystem(archive); }); } string stateCheck; if (archive.read("StateCheck", stateCheck)) { DDEBUG_V("StateCheck:%s", stateCheck.c_str()); impl->setStateCheckMethodByString(stateCheck); archive.addPostProcess([&]() { impl->changeStateCheck(); }); } return true; } void RTSystemItemImpl::restoreRTSystem(const Archive& archive) { DDEBUG("RTSystemItemImpl::restoreRTSystem"); const Listing& compListing = *archive.findListing("RTSComps"); if (compListing.isValid()) { for (int i = 0; i < compListing.size(); i++) { const Mapping& compMap = *compListing[i].toMapping(); string name; Vector2 pos; compMap.read("name", name); read(compMap, "pos", pos); vector<pair<string, bool>> inPorts; vector<pair<string, bool>> outPorts; const Listing& inportListing = *compMap.findListing("InPorts"); if (inportListing.isValid()) { for (int i = 0; i < inportListing.size(); i++) { const Mapping& inMap = *inportListing[i].toMapping(); string portName; bool isServicePort; inMap.read("name", portName); inMap.read("isServicePort", isServicePort); inPorts.push_back(make_pair(portName, isServicePort)); } } const Listing& outportListing = *compMap.findListing("OutPorts"); if (outportListing.isValid()) { for (int i = 0; i < outportListing.size(); i++) { const Mapping& outMap = *outportListing[i].toMapping(); string portName; bool isServicePort; outMap.read("name", portName); outMap.read("isServicePort", isServicePort); outPorts.push_back(make_pair(portName, isServicePort)); } } restoreRTSComp(name, pos, inPorts, outPorts); } } if (autoConnection) { const Listing& connectionListing = *archive.findListing("RTSConnections"); if (connectionListing.isValid()) { for (int i = 0; i < connectionListing.size(); i++) { const Mapping& connectMap = *connectionListing[i].toMapping(); string name, sR, sP, tR, tP, dataflow, subscription; connectMap.read("name", name); connectMap.read("sourceRtcName", sR); connectMap.read("sourcePortName", sP); connectMap.read("targetRtcName", tR); connectMap.read("targetPortName", tP); connectMap.read("dataflow", dataflow); connectMap.read("subscription", subscription); VectorXd p(12); bool readPos = false; Vector2 pos[6]; if (read(connectMap, "position", p)) { readPos = true; for (int i = 0; i < 6; i++) { pos[i] << p(2 * i), p(2 * i + 1); } } addRTSConnectionName("", name, sR, sP, tR, tP, dataflow, subscription, readPos, pos); } } } if (checkAtLoading) { checkStatus(); } sigLoaded(true); DDEBUG("RTSystemItemImpl::restoreRTSystem End"); } void RTSystemItemImpl::restoreRTSComp(const string& name, const Vector2& pos, const vector<pair<string, bool>>& inPorts, const vector<pair<string, bool>>& outPorts) { DDEBUG("RTSystemItemImpl::restoreRTSComp"); RTSComp* comp = addRTSComp(name, QPointF(pos(0), pos(1))); if (comp == 0) return; if (!comp->rtc_) { comp->inPorts.clear(); comp->outPorts.clear(); for (int i = 0; i < inPorts.size(); i++) { RTSPortPtr rtsPort = new RTSPort(inPorts[i].first, 0, comp); rtsPort->isInPort = true; rtsPort->isServicePort = inPorts[i].second; comp->inPorts.push_back(rtsPort); } for (int i = 0; i < outPorts.size(); i++) { RTSPortPtr rtsPort = new RTSPort(outPorts[i].first, 0, comp); rtsPort->isInPort = false; rtsPort->isServicePort = outPorts[i].second; comp->outPorts.push_back(rtsPort); } } DDEBUG("RTSystemItemImpl::restoreRTSComp End"); } SignalProxy<void(int)> RTSystemItem::sigTimerPeriodChanged() { return impl->sigTimerPeriodChanged; } SignalProxy<void(bool)> RTSystemItem::sigTimerChanged() { return impl->sigTimerChanged; } SignalProxy<void(bool)> RTSystemItem::sigLoaded() { return impl->sigLoaded; }
31.057227
157
0.624507
[ "vector" ]
6e8e0f9c703a9b5b795df7c860effbab6946f45a
1,551
cpp
C++
openvr/src/config_openvr.cpp
bluekyu/rpcpp_plugins
6ebc343160a408ac311f96fdb718d8954983c5d4
[ "MIT" ]
2
2017-11-14T12:31:23.000Z
2018-09-15T20:30:11.000Z
openvr/src/config_openvr.cpp
chic-yukim/rpcpp_plugins
c16749af43ac6aa9daa81bf3ca648807f9249222
[ "MIT" ]
20
2017-08-17T09:45:15.000Z
2019-04-20T14:11:43.000Z
openvr/src/config_openvr.cpp
chic-yukim/rpcpp_plugins
c16749af43ac6aa9daa81bf3ca648807f9249222
[ "MIT" ]
2
2018-07-27T05:35:35.000Z
2018-08-30T15:09:41.000Z
/** * Render Pipeline C++ * * Copyright (c) 2016-2017 Center of Human-centered Interaction for Coexistence. * * 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 <dconfig.h> #include "rpplugins/openvr/controller.hpp" #include "openvr_render_stage.hpp" Configure(config_rpplugins_openvr); ConfigureFn(config_rpplugins_openvr) { static bool initialized = false; if (initialized) return; initialized = true; rpplugins::OpenVRController::init_type(); rpplugins::SubmitCallback::init_type(); }
38.775
106
0.758221
[ "render" ]
6e8fde93ace2fad17a885baa32f5ff4e0902a971
1,714
cpp
C++
benchmark/verify_GradCalculator.cpp
kodack64/qulacs-osaka
4ccc3ff084f10942e22d8663a01ed67efd24d9f7
[ "MIT" ]
4
2022-01-26T06:56:00.000Z
2022-03-18T02:07:24.000Z
benchmark/verify_GradCalculator.cpp
kodack64/qulacs-osaka
4ccc3ff084f10942e22d8663a01ed67efd24d9f7
[ "MIT" ]
104
2021-11-12T04:15:02.000Z
2022-03-30T05:12:20.000Z
benchmark/verify_GradCalculator.cpp
kodack64/qulacs-osaka
4ccc3ff084f10942e22d8663a01ed67efd24d9f7
[ "MIT" ]
3
2021-12-19T11:52:38.000Z
2022-03-09T04:20:17.000Z
#include <chrono> #include <cppsim/observable.hpp> #include <cppsim/state.hpp> #include <iomanip> #include <iostream> #include <string> #include <vqcsim/GradCalculator.hpp> #include <vqcsim/parametric_circuit.hpp> int main() { omp_set_num_threads(10); printf("使用可能な最大スレッド数:%d\n", omp_get_max_threads()); std::chrono::system_clock::time_point start, end; start = std::chrono::system_clock::now(); srand(0); unsigned int n = 20; Observable observable(n); std::string Pauli_string = ""; for (int i = 0; i < n; ++i) { double coef = (float)rand() / (float)RAND_MAX; std::string Pauli_string = "Z "; Pauli_string += std::to_string(i); observable.add_operator(coef, Pauli_string.c_str()); } ParametricQuantumCircuit circuit(n); for (int depth = 0; depth < 5; ++depth) { for (int i = 0; i < n; ++i) { circuit.add_parametric_RX_gate(i, 0); circuit.add_parametric_RZ_gate(i, 0); } for (int i = 0; i + 1 < n; i += 2) { circuit.add_CNOT_gate(i, i + 1); } for (int i = 1; i + 1 < n; i += 2) { circuit.add_CNOT_gate(i, i + 1); } } GradCalculator hoge; std::vector<std::complex<double>> ans = hoge.calculate_grad(circuit, observable, rand()); end = std::chrono::system_clock::now(); double msec = static_cast<double>( std::chrono::duration_cast<std::chrono::microseconds>(end - start) .count() / 1000.0); std::cout << "GradCalculator msec: " << msec << " msec" << std::endl; for (int i = 0; i < ans.size(); ++i) { std::cout << ans[i] << std::endl; } return 0; }
27.645161
74
0.570595
[ "vector" ]
6e93aca2dd96f2b6574dd198b5eaabeef433670f
1,486
cpp
C++
Dataset/Leetcode/test/67/602.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/67/602.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/67/602.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: string XXX(string a, string b) { vector<int> A, B; for (char &c : a) A.push_back(int(c - '0')); for (char &c : b) B.push_back(int(c - '0')); vector<int> C; if (greater(A, B)) add(A, B, C); else add(B, A, C); string ans; for (int &c : C) ans += to_string(c); return ans; } // return ture if A is greater than B bool greater(vector<int>& A, vector<int>& B) { int sa = A.size(), sb = B.size(); if (sa < sb) return false; if (sa > sb) return true; for (int i = 0; i < sa; ++i) { if (A[i] < B[i]) return false; } return true; } // A is greater than B and C = A + B void add(vector<int>& A, vector<int>& B, vector<int>& C) { int sa = A.size(), sb = B.size(); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); C.clear(); int carry = 0, sum = 0, i = 0; while (i < sa && i < sb) { sum = A[i] + B[i] + carry; carry = sum / 2; C.push_back(sum % 2); i++; } while (i < sa) { sum = A[i] + carry; carry = sum / 2; C.push_back(sum % 2); i++; } if (carry > 0) C.push_back(carry); reverse(A.begin(), A.end()); reverse(B.begin(), B.end()); reverse(C.begin(), C.end()); } };
24.766667
62
0.415209
[ "vector" ]
6e974d296dcbba2981e8447a068dfe57b6e2865d
384
hpp
C++
FeatureExtractionCpp/FindHaemorages.hpp
fierval/retina
2bc50b3354e5e37f1cfd34f11fbe4b0a4178b7ac
[ "MIT" ]
3
2018-01-11T08:30:24.000Z
2022-01-09T16:07:37.000Z
FeatureExtractionCpp/FindHaemorages.hpp
fierval/retina
2bc50b3354e5e37f1cfd34f11fbe4b0a4178b7ac
[ "MIT" ]
null
null
null
FeatureExtractionCpp/FindHaemorages.hpp
fierval/retina
2bc50b3354e5e37f1cfd34f11fbe4b0a4178b7ac
[ "MIT" ]
5
2017-07-20T05:32:23.000Z
2022-01-11T16:42:32.000Z
#pragma once typedef struct { int cannyThresh; } ParamBag; void FindBlobContours(gpu::GpuMat& g_image, vector<vector<Point>>& contours, int thresh); void EnhanceImage(gpu::GpuMat& grayImage, gpu::GpuMat& equalizedImage); void FindHaemorages(Mat& grayImage, vector<vector<Point>>& contours, ParamBag params); void GetChannelImage(gpu::GpuMat& src, gpu::GpuMat& dst, int channel);
34.909091
89
0.765625
[ "vector" ]
6e98427132d4747032db46632e65dcaf924a3589
9,153
cpp
C++
src/ofxDraco.cpp
satcy/ofxDraco
ea0654958df6bb82aca624a3aed5b47c56582946
[ "Apache-2.0" ]
2
2018-06-05T13:32:46.000Z
2018-06-21T21:21:17.000Z
src/ofxDraco.cpp
satcy/ofxDraco
ea0654958df6bb82aca624a3aed5b47c56582946
[ "Apache-2.0" ]
1
2018-06-09T07:31:01.000Z
2018-06-09T07:31:01.000Z
src/ofxDraco.cpp
satcy/ofxDraco
ea0654958df6bb82aca624a3aed5b47c56582946
[ "Apache-2.0" ]
null
null
null
// // ofxDraco.cpp // test_draco // // Created by satcy on 2017/01/20. // // #include "ofxDraco.h" namespace ofxDraco { //ofMesh toOf(const draco::Mesh & m) {} //draco::Mesh toDraco(const ofMesh & m) {} ofMesh load(const string & path) { ofMesh m; decode(path, m); return m; } bool decode(const string & input_path, ofMesh & dst) { ofFile input_file(input_path, ofFile::ReadOnly, true); if ( !input_file.exists() ) { printf("Failed opening the input file.\n"); return false; } // Read the file stream into a buffer. std::streampos file_size = 0; input_file.seekg(0, std::ios::end); file_size = input_file.tellg() - file_size; input_file.seekg(0, std::ios::beg); std::vector<char> data(file_size); input_file.read(data.data(), file_size); if (data.empty()) { printf("Empty input file.\n"); return false; } // Create a draco decoding buffer. Note that no data is copied in this step. draco::DecoderBuffer buffer; buffer.Init(data.data(), data.size()); // Decode the input data into a geometry. std::unique_ptr<draco::PointCloud> pc; draco::Mesh *mesh = nullptr; const draco::EncodedGeometryType geom_type = draco::GetEncodedGeometryType(&buffer); if (geom_type == draco::TRIANGULAR_MESH) { std::unique_ptr<draco::Mesh> in_mesh = draco::DecodeMeshFromBuffer(&buffer); if (in_mesh) { mesh = in_mesh.get(); pc = std::move(in_mesh); const draco::PointAttribute *const att = pc->GetNamedAttribute(draco::GeometryAttribute::POSITION); if (att == nullptr || att->size() == 0) return false; // Position attribute must be valid. std::array<float, 3> value; vector<ofVec3f> verts; for (draco::AttributeValueIndex i(0); i < att->size(); ++i) { if (att->ConvertValue<float, 3>(i, &value[0]) ) { ofVec3f pt(value[0], value[1], value[2]); verts.emplace_back(pt); } } vector<ofIndexType> inds; for (draco::FaceIndex i(0); i < mesh->num_faces(); ++i) { for (int j = 0; j < 3; ++j) { const draco::PointIndex vert_index = mesh->face(i)[j]; ofIndexType index = att->mapped_index(vert_index).value(); inds.emplace_back(index); } } { const draco::PointAttribute *const att = pc->GetNamedAttribute(draco::GeometryAttribute::NORMAL); if (att == nullptr || att->size() == 0) { //no normal } else { std::array<float, 3> value; vector<ofVec3f> normals; for (draco::AttributeValueIndex i(0); i < att->size(); ++i) { if (att->ConvertValue<float, 3>(i, &value[0]) ) { ofVec3f pt(value[0], value[1], value[2]); normals.emplace_back(pt); } } dst.addNormals(normals); } } dst.addVertices(verts); dst.addIndices(inds); } } else if (geom_type == draco::POINT_CLOUD) { // Failed to decode it as mesh, so let's try to decode it as a point cloud. pc = draco::DecodePointCloudFromBuffer(&buffer); const draco::PointAttribute *const att = pc->GetNamedAttribute(draco::GeometryAttribute::POSITION); if (att == nullptr || att->size() == 0) return false; // Position attribute must be valid. std::array<float, 3> value; vector<ofVec3f> verts; for (draco::AttributeValueIndex i(0); i < att->size(); ++i) { if (!att->ConvertValue<float, 3>(i, &value[0]) ) { return false; } else { ofVec3f pt(value[0], value[1], value[2]); verts.emplace_back(pt); } } dst.addVertices(verts); } mesh = nullptr; return true; } // private int EncodePointCloudToFile(const draco::PointCloud &pc, const draco::EncoderOptions &options, const std::string &file) { // Encode the geometry. draco::EncoderBuffer buffer; if (!draco::EncodePointCloudToBuffer(pc, options, &buffer)) { printf("Failed to encode the point cloud.\n"); return -1; } // Save the encoded geometry into a file. std::ofstream out_file(file, std::ios::binary); if (!out_file) { printf("Failed to create the output file.\n"); return -1; } out_file.write(buffer.data(), buffer.size()); //printf("\nEncoded size = %zu bytes\n\n", buffer.size()); return 0; } // private int EncodeMeshToFile(const draco::Mesh &mesh, const draco::EncoderOptions &options, const std::string &file) { // Encode the geometry. draco::EncoderBuffer buffer; if (!draco::EncodeMeshToBuffer(mesh, options, &buffer)) { printf("Failed to encode the mesh.\n"); return -1; } // Save the encoded geometry into a file. std::ofstream out_file(file, std::ios::binary); if (!out_file) { printf("Failed to create the output file.\n"); return -1; } out_file.write(buffer.data(), buffer.size()); //printf("\nEncoded size = %zu bytes\n\n", buffer.size()); return 0; } bool encodeFromFile(const string & input_path, const string & output_path, bool is_absolute_path, bool is_point_cloud, int pos_quantization_bits, int tex_coords_quantization_bits, int normals_quantization_bits, int compression_level) { std::unique_ptr<draco::PointCloud> pc; draco::Mesh *mesh = nullptr; if ( !is_point_cloud ) { std::unique_ptr<draco::Mesh> in_mesh = draco::ReadMeshFromFile(is_absolute_path ? input_path : ofToDataPath(input_path, true)); if (!in_mesh) { printf("Failed loading the input mesh.\n"); return -1; } mesh = in_mesh.get(); pc = std::move(in_mesh); } else { pc = draco::ReadPointCloudFromFile(is_absolute_path ? input_path : ofToDataPath(input_path, true)); if (!pc) { printf("Failed loading the input point cloud.\n"); return -1; } } // Setup encoder options. draco::EncoderOptions encoder_options = draco::CreateDefaultEncoderOptions(); if (pos_quantization_bits > 0) { draco::SetNamedAttributeQuantization(&encoder_options, *pc.get(), draco::GeometryAttribute::POSITION, pos_quantization_bits); } if (tex_coords_quantization_bits > 0) { draco::SetNamedAttributeQuantization(&encoder_options, *pc.get(), draco::GeometryAttribute::TEX_COORD, tex_coords_quantization_bits); } if (normals_quantization_bits > 0) { draco::SetNamedAttributeQuantization(&encoder_options, *pc.get(), draco::GeometryAttribute::NORMAL, normals_quantization_bits); } // Convert compression level to speed (that 0 = slowest, 10 = fastest). const int speed = 10 - compression_level; draco::SetSpeedOptions(&encoder_options, speed, speed); if (mesh && mesh->num_faces() > 0) return EncodeMeshToFile(*mesh, encoder_options, is_absolute_path ? output_path : ofToDataPath(output_path, true)); return EncodePointCloudToFile(*pc.get(), encoder_options, is_absolute_path ? output_path : ofToDataPath(output_path, true)); return true; } } // namespace ofxDraco
38.948936
139
0.489676
[ "mesh", "geometry", "vector" ]
6e984df3c07fb7a94d445d5d83db080306c7669e
3,220
cpp
C++
test/testMatrixMultiplication.cpp
agrawalabhishek/NAOS
25ae383d2c3f9a52ecd2e06f34661e52e239478b
[ "MIT" ]
null
null
null
test/testMatrixMultiplication.cpp
agrawalabhishek/NAOS
25ae383d2c3f9a52ecd2e06f34661e52e239478b
[ "MIT" ]
null
null
null
test/testMatrixMultiplication.cpp
agrawalabhishek/NAOS
25ae383d2c3f9a52ecd2e06f34661e52e239478b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include <catch.hpp> #include <vector> #include "NAOS/basicMath.hpp" namespace naos { namespace tests { TEST_CASE( "Test Matrix Multiplication", "[matrix-multiplication]" ) { SECTION( "Two multi-dimensional matrices multiplied" ) { std::vector< std::vector< double > > firstMatrix { { 1.0, 1.0, 1.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; std::vector< std::vector< double > > secondMatrix { { 5.0, 6.0, 8.0 }, { 8.0, 4.0, 9.0 }, { 10.0, 63.0, 2.0 } }; std::vector< std::vector< double > > outputMatrix( 3, std::vector< double >( 3 ) ); naos::matrixMultiplication( firstMatrix, secondMatrix, outputMatrix, 3, 3, 3, 3 ); // check the computed values REQUIRE( outputMatrix[ 0 ][ 0 ] == Approx( 23.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 0 ][ 1 ] == Approx( 73.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 0 ][ 2 ] == Approx( 19.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 1 ][ 0 ] == Approx( 8.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 1 ][ 1 ] == Approx( 4.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 1 ][ 2 ] == Approx( 9.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 2 ][ 0 ] == Approx( 10.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 2 ][ 1 ] == Approx( 63.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 2 ][ 2 ] == Approx( 2.0 ).epsilon( 1.0e-15 ) ); } SECTION( "first matrix single dimension, second matrix multidimensional" ) { std::vector< std::vector< double > > firstMatrix { { 1.0, 0.0, 0.0 } }; std::vector< std::vector< double > > secondMatrix { { 5.0, 6.0, 8.0 }, { 8.0, 4.0, 9.0 }, { 10.0, 63.0, 2.0 } }; std::vector< std::vector< double > > outputMatrix( 1, std::vector< double >( 3 ) ); naos::matrixMultiplication( firstMatrix, secondMatrix, outputMatrix, 1, 3, 3, 3 ); // check the computed values REQUIRE( outputMatrix[ 0 ][ 0 ] == Approx( 5.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 0 ][ 1 ] == Approx( 6.0 ).epsilon( 1.0e-15 ) ); REQUIRE( outputMatrix[ 0 ][ 2 ] == Approx( 8.0 ).epsilon( 1.0e-15 ) ); } } } // namespace tests } // namespace naos
39.753086
91
0.432298
[ "vector" ]
6e9cc5e1962e300265a85b8ad61130164de1ee10
2,471
hpp
C++
src/objs/OctaNest.hpp
nama-gatsuo/GenerativeNature
e7fb1b52ef71d92a856e7171964acb3ff9c4f42e
[ "MIT" ]
20
2017-09-24T06:38:38.000Z
2021-12-03T11:36:41.000Z
src/objs/OctaNest.hpp
nama-gatsuo/GenerativeNature
e7fb1b52ef71d92a856e7171964acb3ff9c4f42e
[ "MIT" ]
1
2019-06-05T07:11:57.000Z
2019-06-05T09:14:02.000Z
src/objs/OctaNest.hpp
nama-gatsuo/GenerativeNature
e7fb1b52ef71d92a856e7171964acb3ff9c4f42e
[ "MIT" ]
null
null
null
#include "ofMain.h" #include "ObjBase.hpp" #include "CommonUtil.hpp" class OctaNest : public ObjBase { public: void setup(){ shader.setGeometryInputType(GL_TRIANGLES); shader.setGeometryOutputType(GL_TRIANGLE_STRIP); shader.setGeometryOutputCount(3); shader.load("shader/scene/OctaNest.vert", "shader/scene/wireframe.frag", "shader/scene/wireframe.geom"); ofVec3f ov[6] = { ofVec3f(1,0,0), ofVec3f(-1,0,0), ofVec3f(0,1,0), ofVec3f(0,-1,0), ofVec3f(0,0,1), ofVec3f(0,0,-1) }; unsigned oi[24] = { 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 }; for (int i = 0; i < 24; i += 3) { ofVec3f v1 = ov[oi[i]] * 0.1; ofVec3f v2 = ov[oi[i+1]] * 0.1; ofVec3f v3 = ov[oi[i+2]] * 0.1; mesh.addVertex(v1); mesh.addVertex(v2); mesh.addVertex(v3); } mesh.setMode(OF_PRIMITIVE_TRIANGLES); size = ofVec2f(18, 36); angleFactor.setSpeed(0.01); }; void update(float dt){ angleFactor.update(dt); scaleFactor.update(dt); phaseFactor.update(dt); wireWidth.update(dt); }; void draw(ofCamera &cam, bool isShadow){ shader.begin(); shader.setUniform1f("nearClip", cam.getNearClip()); shader.setUniform1f("farClip", cam.getFarClip()); shader.setUniform1f("wireWidth", 0.05+wireWidth.get()); shader.setUniform1i("isDrawFace", 0); shader.setUniform1i("isShadow", isShadow?1:0); shader.setUniform2f("size", size); shader.setUniform1f("scaleFactor", scaleFactor.get()); shader.setUniform1f("phaseFactor", phaseFactor.get()); shader.setUniform1f("angleFactor", angleFactor.get()); mesh.drawInstanced(OF_MESH_FILL, size.x * size.y); shader.end(); }; void randomize(int i){ if (i == 0) { angleFactor.to(ofRandom(PI, TWO_PI)); scaleFactor.to(ofRandom(1., 10.)); phaseFactor.to(ofRandom(0., PI)); } else if (i == 1) { wireWidth.addForce(0.2); } }; private: ofVboMesh mesh; ofShader shader; ofVec2f size; SmoothValue angleFactor; SmoothValue scaleFactor; SmoothValue phaseFactor; PhysicValue wireWidth; };
30.8875
63
0.544314
[ "mesh" ]
6eb6ce5defb4fbad291c58373a07c0afdea3b40f
907
cpp
C++
0201-0300/213-house-robber-ii/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
0201-0300/213-house-robber-ii/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
0201-0300/213-house-robber-ii/main.cpp
janreggie/leetcode
c59718e127b598c4de7d07c9c93064eb12b2e5c9
[ "MIT", "Unlicense" ]
null
null
null
#include <iostream> #include <vector> class Solution { public: int rob(const std::vector<int>& nums) { const size_t n = nums.size(); if (n == 0) { return 0; } if (n == 1) { return nums[0]; } return std::max( robLinear(std::vector(nums.begin(), nums.end() - 1)), robLinear(std::vector(nums.begin() + 1, nums.end()))); } private: int robLinear(const std::vector<int>& nums) { const size_t n = nums.size(); if (n == 0) { return 0; } if (n == 1) { return nums[0]; } std::vector<int> dp(n); dp[n - 1] = nums[n - 1]; dp[n - 2] = std::max(nums[n - 2], nums[n - 1]); for (size_t ind = n - 3; ind < n; --ind) { dp[ind] = std::max(nums[ind] + dp[ind + 2], dp[ind + 1]); } return std::max(dp[0], dp[1]); } }; int main() { const std::vector<int> houses{ 5, 6, 131, 4, 6, 696, 7, 420 }; Solution soln; std::cout << soln.rob(houses) << std::endl; }
17.784314
63
0.536935
[ "vector" ]
6eb88b184e9640679e47d7a30122af72e76ec798
2,880
cpp
C++
src/quickSort.cpp
Christine0312/Sorting-Algorithm
2e41d3b204c9493e139bc507779091a53fb2cbda
[ "MIT" ]
null
null
null
src/quickSort.cpp
Christine0312/Sorting-Algorithm
2e41d3b204c9493e139bc507779091a53fb2cbda
[ "MIT" ]
null
null
null
src/quickSort.cpp
Christine0312/Sorting-Algorithm
2e41d3b204c9493e139bc507779091a53fb2cbda
[ "MIT" ]
null
null
null
/**************************************************************************** FileName [ quickSort ] PackageName [ Sorting ] Author [ Wan Cyuan Fan , NTUEE ] ****************************************************************************/ #include <cstdio> #include <iostream> #include <vector> #include "parser.h" #include <fstream> using namespace std; // global variable static AlgParser p; static AlgTimer t; static vector<string> quickSort_text; static vector<string>::iterator it; static vector<int> quickSort_index; static vector<int>::iterator it_index; //my funcition definition //int accumulated_order(AlgParser& p,int i); void quickSort(AlgParser& p,int index_p,int index_r); int partition(int index_p,int index_r); void set_vector(AlgParser& p); void file_write(AlgParser& p,char* outputfilename); int main(int argc,char *argv[]) { // Declare the functional objects p.Parse(argv[1]); t.Begin(); cout << "##############################" << endl; cout << "1. Reading in the file..." << endl; set_vector(p); cout << "2. Processing quick sort..." << endl; quickSort(p,1,p.QueryTotalStringCount()); cout << "3. Write the data into the file \"" << argv[2] << "\""<< endl; file_write(p,argv[2]); cout << "The execution spends " << t.End() << " seconds" << endl; getchar(); cout << "Processing complete!" << endl; cout << "##############################" << endl; return 0; } void quickSort(AlgParser& p,int index_p,int index_r){ if (index_p < index_r){ int index_q = partition(index_p,index_r); quickSort(p,index_p,index_q); quickSort(p,index_q + 1,index_r); } } int partition(int index_p,int index_r){ string x = quickSort_text[index_p - 1]; int i = index_p - 2; int j = index_r; while(true){ //cout << i << j << endl; do { j--; //cout << "j--" << endl; } while((int)quickSort_text[j][0] > (int)x[0]); do { i++; //cout << "i--" << endl; } while((int)quickSort_text[i][0] < (int)x[0]); if ( i < j) { string tmp = quickSort_text[i]; int tmp_index = quickSort_index[i]; quickSort_text[i] = quickSort_text[j]; quickSort_index[i] = quickSort_index[j]; quickSort_text[j] = tmp; quickSort_index[j] = tmp_index; } else{ return j+1; } } } void set_vector(AlgParser& p){ for( int i = 0 ; i < p.QueryTotalStringCount() ; i++ ) { quickSort_text.push_back(p.QueryString(i)); quickSort_index.push_back(i+1); } } void file_write(AlgParser& p,char *outputfilename){ fstream myfile((string)outputfilename,ios::out); myfile << p.QueryTotalStringCount() << endl; for( int i = 0 ; i < p.QueryTotalStringCount() ; i++ ) { myfile << quickSort_text[i] << " " << quickSort_index[i] << endl; } }
28.514851
77
0.561458
[ "vector" ]
6ec63b1b461ce7b40a8f462f10d1b4277e022d85
4,013
hpp
C++
VKTS/include/vkts/image/data/IImageData.hpp
jjzhang166/Vulkan
655c1ac3131cdba81d3e84def2a1c35fa492bd52
[ "MIT" ]
2
2017-08-14T23:12:43.000Z
2019-12-03T15:56:17.000Z
VKTS/include/vkts/image/data/IImageData.hpp
jjzhang166/Vulkan
655c1ac3131cdba81d3e84def2a1c35fa492bd52
[ "MIT" ]
null
null
null
VKTS/include/vkts/image/data/IImageData.hpp
jjzhang166/Vulkan
655c1ac3131cdba81d3e84def2a1c35fa492bd52
[ "MIT" ]
1
2019-12-03T15:56:20.000Z
2019-12-03T15:56:20.000Z
/** * VKTS - VulKan ToolS. * * The MIT License (MIT) * * Copyright (c) since 2014 Norbert Nopper * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef VKTS_IIMAGEDATA_HPP_ #define VKTS_IIMAGEDATA_HPP_ #include <vkts/image/vkts_image.hpp> namespace vkts { class IImageData { public: IImageData() { } virtual ~IImageData() { } virtual const std::string& getName() const = 0; virtual VkImageType getImageType() const = 0; virtual const VkFormat& getFormat() const = 0; virtual const VkExtent3D& getExtent3D() const = 0; virtual uint32_t getWidth() const = 0; virtual uint32_t getHeight() const = 0; virtual uint32_t getDepth() const = 0; virtual uint32_t getMipLevels() const = 0; virtual uint32_t getArrayLayers() const = 0; virtual const void* getData() const = 0; virtual const uint8_t* getByteData() const = 0; virtual uint32_t getSize() const = 0; /** * Copy image data pixels into the given data pointer. */ virtual VkBool32 copy(void* data, const uint32_t mipLevel, const uint32_t arrayLayer, const VkSubresourceLayout& subresourceLayout) const = 0; /** * Uploads pixel data into image data. */ virtual VkBool32 upload(const void* data, const uint32_t mipLevel, const uint32_t arrayLayer, const VkSubresourceLayout& subresourceLayout) const = 0; virtual VkBool32 isBLOCK() const = 0; virtual VkBool32 isUNORM() const = 0; virtual VkBool32 isSFLOAT() const = 0; virtual VkBool32 isSRGB() const = 0; virtual uint32_t getBytesPerTexel() const = 0; virtual uint32_t getBytesPerChannel() const = 0; virtual uint32_t getNumberChannels() const = 0; virtual const std::vector<uint32_t>& getAllOffsets() const = 0; virtual void setTexel(const glm::vec4& rgba, const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t mipLevel, const uint32_t arrayLayer) = 0; virtual glm::vec4 getTexel(const uint32_t x, const uint32_t y, const uint32_t z, const uint32_t mipLevel, const uint32_t arrayLayer) const = 0; virtual glm::vec4 getSample(const float x, const VkFilter filterX, const VkSamplerAddressMode addressModeX, const float y, const VkFilter filterY, const VkSamplerAddressMode addressModeY, const float z, const VkFilter filterZ, const VkSamplerAddressMode addressModeZ, const uint32_t mipLevel, const uint32_t arrayLayer) const = 0; virtual glm::vec4 getSampleCubeMap(const float x, const float y, const float z, const VkFilter filter, const uint32_t mipLevel) const = 0; virtual VkBool32 getExtentAndOffset(VkExtent3D& currentExtent, uint32_t& currentOffset, const uint32_t mipLevel, const uint32_t arrayLayer) const = 0; virtual void freeHostMemory() = 0; virtual VkBool32 updateMaxLuminance() = 0; virtual float getMaxLuminance() const = 0; }; typedef std::shared_ptr<IImageData> IImageDataSP; } /* namespace vkts */ #endif /* VKTS_IIMAGEDATA_HPP_ */
33.165289
334
0.731124
[ "vector" ]
6ec8d5a7f4c0b7ec70c81d1035d2728aac46d46d
11,774
hh
C++
print/print/TAnaDump.hh
macndev/Stntuple
b5bb000edf015883eec32d87959cb7bd3ab88577
[ "Apache-2.0" ]
null
null
null
print/print/TAnaDump.hh
macndev/Stntuple
b5bb000edf015883eec32d87959cb7bd3ab88577
[ "Apache-2.0" ]
null
null
null
print/print/TAnaDump.hh
macndev/Stntuple
b5bb000edf015883eec32d87959cb7bd3ab88577
[ "Apache-2.0" ]
6
2019-11-21T15:27:27.000Z
2022-02-28T20:57:13.000Z
// #ifndef __murat_inc_TAnaDump_hh__ #define __murat_inc_TAnaDump_hh__ #include "TObject.h" #include "TObjArray.h" #include "TString.h" #include "TGraph.h" #include "TMarker.h" #include "TCanvas.h" #include "TEllipse.h" #include "TH1F.h" #include "TH2F.h" #include "TF1.h" #ifndef __CINT__ #include "art/Framework/Principal/Event.h" #include "MCDataProducts/inc/CaloClusterMCTruthAssn.hh" #include "MCDataProducts/inc/CaloHitMCTruthAssn.hh" #include "MCDataProducts/inc/StrawDigiMCCollection.hh" #include "RecoDataProducts/inc/ComboHit.hh" #include "RecoDataProducts/inc/HelixHit.hh" #include "RecoDataProducts/inc/StrawHitPositionCollection.hh" #include "DataProducts/inc/XYZVec.hh" #include "TrkReco/inc/TrkPrintUtils.hh" #else namespace art { class Event; } #endif namespace mu2e { #ifndef MCDataProducts_StrawDigiMC_hh class StrawDigiMCCollection; #endif class StrawHit; // class StrawHitMCTruth; class CaloCluster; class CaloProtoCluster; class CrvDigi; class CrvRecoPulse; class CrvCoincidence; class CrvCoincidenceCluster; class TrkToCaloExtrapol; class StepPointMC; class StrawGasStep; class GenParticle; class SimParticle; class TimeCluster; class KalSeed; class ComboHit; class HelixSeed; class TrackClusterMatch; class TrkCaloHit; class TrkStrawHit; class SimParticleTimeOffset; class TrkPrintUtils; } class KalRep; class TAnaDump : public TObject { public: const art::Event* fEvent; TObjArray* fListOfObjects; TString fFlagBgrHitsModuleLabel; TString fStrawDigiMCCollTag; mu2e::SimParticleTimeOffset* fTimeOffsets; const mu2e::StrawDigiMCCollection* _mcdigis; double fTmp[100]; // for testing mu2e::TrkPrintUtils* _printUtils; private: TAnaDump(const fhicl::ParameterSet* Pset = NULL); ~TAnaDump(); class Cleaner { public: Cleaner(); ~Cleaner(); }; friend class Cleaner; static TAnaDump* fgInstance; public: //----------------------------------------------------------------------------- // TAnaDump gets initialized by the first TModule instantiated //----------------------------------------------------------------------------- static TAnaDump* Instance(const fhicl::ParameterSet* PSet = NULL); //----------------------------------------------------------------------------- // accessors //----------------------------------------------------------------------------- mu2e::SimParticleTimeOffset* TimeOffsets() { return fTimeOffsets; } const art::Event* Event () { return fEvent ; } //----------------------------------------------------------------------------- // other methods //----------------------------------------------------------------------------- void AddObject (const char* Name, void* Object); void* FindNamedObject(const char* Name); void SetEvent(art::Event& Evt) { fEvent = &Evt; } void SetFlagBgrHitsModuleLabel(const char* Tag) { fFlagBgrHitsModuleLabel = Tag; } void SetStrawDigiMCCollTag (const char* Tag) { fStrawDigiMCCollTag = Tag; } double evalWeight(const mu2e::ComboHit* Hit , XYZVec& StrawDir , XYZVec& HelCenter, double Radius , int WeightMode, fhicl::ParameterSet const& Pset); void evalHelixInfo(const mu2e::HelixSeed* Helix, int &NLoops, int &NHitsLoopFailed); void printEventHeader(); //----------------------------------------------------------------------------- // calorimeter //----------------------------------------------------------------------------- void printCalorimeter(); void printCaloCrystalHits (const char* ModuleLabel, const char* ProductName = "", const char* ProcessName = ""); void printCaloDigiCollection(const char* ModuleLabel, const char* ProductName = "", const char* ProcessName = ""); void printCaloRecoDigiCollection(const char* ModuleLabel, const char* ProductName = "", const char* ProcessName = ""); void printCaloHits (const char* ModuleLabel, const char* ProductName = "", const char* ProcessName = ""); void printCaloCluster (const mu2e::CaloCluster* Cluster , const char* Opt = "", const mu2e::CaloHitMCTruthAssns* CaloHitTruth=NULL); void printCaloClusterCollection (const char* ModuleLabel, const char* ProductName= "", const char* ProcessName= "", double Emin=50., int hitOpt=0, const char* MCModuleLabel= ""); void printCaloProtoCluster (const mu2e::CaloProtoCluster* Clu , const char* Opt = ""); void printCaloProtoClusterCollection (const char* ModuleLabel, const char* ProductName, const char* ProcessName); //----------------------------------------------------------------------------- // CRV //----------------------------------------------------------------------------- void printCrvCoincidence (const mu2e::CrvCoincidence* CrvC , const char* Opt = ""); void printCrvCoincidenceCollection (const char* ModuleLabel, const char* ProductName= "", const char* ProcessName= ""); void printCrvCoincidenceCluster (const mu2e::CrvCoincidenceCluster* CrvC , const char* Opt = ""); void printCrvCoincidenceClusterCollection (const char* ModuleLabel, const char* ProductName= "", const char* ProcessName= ""); void printCrvRecoPulse (const mu2e::CrvRecoPulse* Pulse , const char* Opt = ""); void printCrvRecoPulseCollection (const char* ModuleLabel, const char* ProductName= "", const char* ProcessName= ""); void printCrvDigi (const mu2e::CrvDigi* Digi , const char* Opt = ""); void printCrvDigiCollection (const char* ModuleLabel, const char* ProductName= "", const char* ProcessName= ""); //----------------------------------------------------------------------------- // tracking //----------------------------------------------------------------------------- void printComboHit (const mu2e::ComboHit* Hit, const mu2e::StrawGasStep* Step, const char* Opt = "", int INit = -1, int Flags = -1); void printComboHitCollection (const char* StrawHitCollTag, const char* StrawDigiMCCollTag = nullptr, // "makeSD" or "compressDigiMCs" double TMin = -1.e6, double TMax = 1.e6); void printHelixSeed (const mu2e::HelixSeed* Helix , // const char* HelixSeedCollTag , const char* StrawHitCollTag , // usually - "makeSH" const char* StrawDigiCollTag = "makeSD", const char* Opt = "" ); void printHelixSeedCollection(const char* HelixSeedCollTag , // always needed int PrintHits = 0 , const char* StrawHitCollTag = "makeSH", // usually, "makeSH" const char* StrawDigiMCCollTag = nullptr ); // most often, "makeSD" or "compressDigiMCs" void printStrawHit (const mu2e::StrawHit* Hit, const mu2e::StrawGasStep* Step, const char* Opt = "", int INit = -1, int Flags = -1); void printStrawHitCollection (const char* StrawHitCollTag, const char* StrawDigiMCCollTag = "compressDigiMCs", double TMin = -1.e6, double TMax = 1.e6); void printStrawGasStep (const mu2e::StrawGasStep* Step , const char* Opt = "", int IStep = -1); void printStrawGasStepCollection (const char* CollTag, double TMin = -1.e6, double TMax = 1.e6); void printHelixHit (const mu2e::HelixHit* HelHit, const mu2e::ComboHit* Hit, const mu2e::StrawGasStep* Step, const char* Opt = "", int INit = -1, int Flags = -1); void printTrkCaloHit(const KalRep* Krep, mu2e::TrkCaloHit* CaloHit); void printTrackSeed (const mu2e::KalSeed* TrkSeed , const char* Opt = "" , const char* StrawHitCollTag = "makeSH" , const char* StrawDigiMCCollTag = "compressDigiMCs"); void printTrackSeedCollection(const char* CollTag , int hitOpt = 0 , const char* StrawHitCollTag = "makeSH" , const char* StrawDigiMCCollTag = "compressDigiMCs"); void printKalRep(const KalRep* Krep, const char* Opt = "", const char* Prefix = ""); void printKalRepCollection(const char* KalRepCollTag , int hitOpt = 0 , const char* StrawDigiMCCollTag = nullptr); //----------------------------------------------------------------------------- // time clusters //----------------------------------------------------------------------------- void printTimeCluster (const mu2e::TimeCluster* TimePeak, const char* Opt = "", const mu2e::ComboHitCollection* ChColl=0, const char*StrawDigiMCModuleLabel = "makeSD"); void printTimeClusterCollection(const char* ModuleLabel , const char* ComboHitModuleLabel, const char* ProductName = "" , const char* ProcessName = "" , int PrintHits = 0 , const char* StrawDigiMCModuleLabel = "makeSD"); //----------------------------------------------------------------------------- // MC truth: gen and sim particles //----------------------------------------------------------------------------- void printGenParticle (const mu2e::GenParticle* P , const char* Opt = ""); void printGenParticleCollections(); void printSimParticle (const mu2e::SimParticle* P , const char* Opt = "", const void* PrintData = nullptr); void printSimParticleCollection(const char* ModuleLabel , const char* ProductName = "", const char* ProcessName = ""); //----------------------------------------------------------------------------- // pass the detector name to know what to print for different detectors // tested for Detector = 'tracker', 'calorimeter' //----------------------------------------------------------------------------- void printStepPointMC(const mu2e::StepPointMC* Step, const char* Detector, const char* Opt = ""); void printStepPointMCCollection (const char* ModuleLabel , const char* ProductName = "", const char* ProcessName = ""); //----------------------------------------------------------------------------- // extrapolation and track-to-calorimeter matching //----------------------------------------------------------------------------- void printTrkToCaloExtrapol (const mu2e::TrkToCaloExtrapol*extrk, const char* Opt = ""); void printTrkToCaloExtrapolCollection (const char* ModuleLabel, const char* ProductName = "", const char* ProcessName = ""); void printTrackClusterMatch (const mu2e::TrackClusterMatch* TcMatch, const char* Option); void printTrackClusterMatchCollection(const char* ModuleLabel , const char* ProductName = "", const char* ProcessName = ""); // refit track dropping hits away > NSig sigma (0.1) void refitTrack(void* Trk, double NSig); void Test_000(const KalRep* Krep, mu2e::TrkStrawHit* Hit); ClassDef(TAnaDump,0) }; #endif
36.565217
115
0.537965
[ "object" ]
6ed6a0fc83415c3b641d336d9c2e5c95ad25f023
2,305
cpp
C++
compat/BSDecomposeVectorModifier_0.cpp
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
38
2015-03-24T00:41:59.000Z
2022-03-23T09:18:29.000Z
compat/BSDecomposeVectorModifier_0.cpp
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
2
2015-10-14T07:41:48.000Z
2015-12-14T02:19:05.000Z
compat/BSDecomposeVectorModifier_0.cpp
BlazesRus/hkxcmd
e00a554225234e40e111e808b095156ac1d4b1fe
[ "Intel" ]
24
2015-08-03T20:41:07.000Z
2022-03-27T03:58:37.000Z
#include "StdAfx.h" #include "BSDecomposeVectorModifier_0.h" #include <Common/Serialize/hkSerialize.h> #include <Common/Serialize/Util/hkSerializeUtil.h> #include <Common/Serialize/Version/hkVersionPatchManager.h> #include <Common/Serialize/Data/Dict/hkDataObjectDict.h> #include <Common/Serialize/Data/Native/hkDataObjectNative.h> #include <Common/Serialize/Data/Util/hkDataObjectUtil.h> #include <Common/Base/Reflection/Registry/hkDynamicClassNameRegistry.h> #include <Common/Base/Reflection/Registry/hkVtableClassRegistry.h> #include <Common/Base/Reflection/hkClass.h> #include <Common/Base/Reflection/hkInternalClassMember.h> #include <Common/Serialize/Util/hkSerializationCheckingUtils.h> #include <Common/Serialize/Util/hkVersionCheckingUtils.h> static const hkInternalClassMember BSDecomposeVectorModifierClass_Members[] = { { "vector",HK_NULL,HK_NULL,hkClassMember::TYPE_VECTOR4,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSDecomposeVectorModifier,m_vector) /*48*/,HK_NULL}, { "x",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSDecomposeVectorModifier,m_x) /*64*/,HK_NULL}, { "y",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSDecomposeVectorModifier,m_y) /*68*/,HK_NULL}, { "z",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSDecomposeVectorModifier,m_z) /*72*/,HK_NULL}, { "w",HK_NULL,HK_NULL,hkClassMember::TYPE_REAL,hkClassMember::TYPE_VOID,0,hkClassMember::FLAGS_NONE,HK_OFFSET_OF(BSDecomposeVectorModifier,m_w) /*76*/,HK_NULL}, }; // Signature: 31f6b8b6 extern const hkClass hkbModifierClass; extern const hkClass BSDecomposeVectorModifierClass; const hkClass BSDecomposeVectorModifierClass( "BSDecomposeVectorModifier", &hkbModifierClass, // parent sizeof(BSDecomposeVectorModifier), HK_NULL, 0, // interfaces HK_NULL, 0, // enums reinterpret_cast<const hkClassMember*>(BSDecomposeVectorModifierClass_Members), HK_COUNT_OF(BSDecomposeVectorModifierClass_Members), HK_NULL, // defaults HK_NULL, // attributes 0, // flags 0 // version ); HK_REFLECTION_DEFINE_VIRTUAL(BSDecomposeVectorModifier, BSDecomposeVectorModifier);
52.386364
176
0.809544
[ "vector" ]
6eefe27f92297879aa99bd919464f942fe455098
13,398
cpp
C++
tests/_matrix/algebra_Matrix_SanityTests.cpp
sarkarchandan/Francois
0abfa5cd4d3943f8dd109f2759d13e385bd1f53c
[ "MIT" ]
null
null
null
tests/_matrix/algebra_Matrix_SanityTests.cpp
sarkarchandan/Francois
0abfa5cd4d3943f8dd109f2759d13e385bd1f53c
[ "MIT" ]
null
null
null
tests/_matrix/algebra_Matrix_SanityTests.cpp
sarkarchandan/Francois
0abfa5cd4d3943f8dd109f2759d13e385bd1f53c
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "Matrix.hpp" #include <memory> TEST(MatrixSanityTests, canInstantiateMatrixWithInitializerListAndVector) { const std::initializer_list<std::vector<int>> givenList1 = { {1,2,3}, {4,6,7}, {9,10,11} }; const std::vector<std::vector<int>> givenVectors1 = { {1,2,3}, {4,6,7}, {9,10,11} }; EXPECT_NO_THROW(algebra::Matrix<int> {givenList1}); EXPECT_NO_THROW(algebra::Matrix<int> {givenVectors1}); const std::initializer_list<std::vector<float>> givenList2 = { {1.2f,3.4f,4.5f}, {6.7f,8.9f,10.11f} }; const std::vector<std::vector<float>> givenVectors2 = { {1.2f,3.4f,4.5f}, {6.7f,8.9f,10.11f} }; EXPECT_NO_THROW(algebra::Matrix<float> {givenList2}); EXPECT_NO_THROW(algebra::Matrix<float> {givenVectors2}); const std::initializer_list<std::vector<double>> givenList3 = { {3.5,1.9}, {1.2,6.2}, {1.56,3.7} }; const std::vector<std::vector<double>> givenVectors3 = { {3.5,1.9}, {1.2,6.2}, {1.56,3.7} }; EXPECT_NO_THROW(algebra::Matrix<double> {givenList3}); EXPECT_NO_THROW(algebra::Matrix<double> {givenVectors3}); } TEST(MatrixSanityTests_ExceptionTest, canDetermineIfMatrixIsInvalid) { const std::initializer_list<std::vector<int>> givenList1 = { {1,2,3}, {4,6,7,4}, {9,10,11,12} }; EXPECT_THROW(algebra::Matrix<int> {givenList1},std::invalid_argument); const std::initializer_list<std::vector<double>> givenList2 = { {3.5,1.9,8.1}, {1.2,6.2}, {1.56,3.7,2.9} }; EXPECT_THROW(algebra::Matrix<double> {givenList2},std::invalid_argument); const std::vector<std::vector<int>> givenVector1 = { {1,2,3}, {4,6,7,4}, {9,10,11,12} }; EXPECT_THROW(algebra::Matrix<int> {givenVector1},std::invalid_argument); const std::vector<std::vector<double>> givenVector2 = { {3.5,1.9,8.1}, {1.2,6.2}, {1.56,3.7,2.9} }; EXPECT_THROW(algebra::Matrix<double>{givenVector2},std::invalid_argument); const std::vector<algebra::Row<int>> givenRows1 = {{1,2,3,4},{5,6,8},{9,10,11,12}}; EXPECT_THROW(algebra::Matrix<int> {givenRows1},std::invalid_argument); const std::vector<algebra::Row<double>> givenRows2 = {{3.5,1.9,5.3},{1.2,6.2},{1.56,3.7,8.2},{4.7,1.8,7.4}}; EXPECT_THROW(algebra::Matrix<double>{givenRows2},std::invalid_argument); const std::vector<algebra::Column<int>> givenColumns1 = {{1,2,3,4},{5,6,8},{9,10,11,12}}; EXPECT_THROW(algebra::Matrix<int>{givenColumns1},std::invalid_argument); const std::vector<algebra::Column<double>> givenColumns2 = {{65.4,936.12,90.23,65.78},{47.1,93.15,43.98}}; EXPECT_THROW(algebra::Matrix<double>{givenColumns2},std::invalid_argument); } TEST(MatrixSanityTests, canDetermineMatrixOrder) { const algebra::Matrix<int> givenMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; const std::pair<size_t,size_t> intOrder = givenMatrix1.Order(); ASSERT_EQ(intOrder.first,3); ASSERT_EQ(intOrder.second,4); const algebra::Matrix<double> givenMatrix2 = { {3.5,1.9}, {1.2,6.2}, {1.56,3.7}, {4.7,1.8} }; const std::pair<size_t,size_t> doubleOrder = givenMatrix2.Order(); ASSERT_EQ(doubleOrder.first,4); ASSERT_EQ(doubleOrder.second,2); } TEST(MatrixSanityTests, canAccessElementsBySubscripting) { const algebra::Matrix<int> givenMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; ASSERT_EQ(givenMatrix1(0,0),1); ASSERT_EQ(givenMatrix1(1,1),6); ASSERT_EQ(givenMatrix1(2,2),11); ASSERT_EQ(givenMatrix1(0,3),4); ASSERT_EQ(givenMatrix1(1,3),8); ASSERT_EQ(givenMatrix1(2,3),12); const algebra::Matrix<double> givenMatrix2 = { {65.4,936.12}, {47.1,93.15}, {78.21,45.21}, {90.23,81.23} }; ASSERT_DOUBLE_EQ(givenMatrix2(0,0),65.4); ASSERT_DOUBLE_EQ(givenMatrix2(0,1),936.12); ASSERT_DOUBLE_EQ(givenMatrix2(1,0),47.1); ASSERT_DOUBLE_EQ(givenMatrix2(1,1),93.15); ASSERT_DOUBLE_EQ(givenMatrix2(2,0),78.21); ASSERT_DOUBLE_EQ(givenMatrix2(2,1),45.21); ASSERT_DOUBLE_EQ(givenMatrix2(3,0),90.23); ASSERT_DOUBLE_EQ(givenMatrix2(3,1),81.23); } TEST(MatrixSanityTests, canUpdateElementsOfMatrixBySubscripting) { algebra::Matrix<int> givenMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; givenMatrix1(1,1) = 12; givenMatrix1(0,3) = 23; givenMatrix1(2,2) = 66; const algebra::Matrix<int> expectedMatrix1 = { {1,2,3,23}, {4,12,7,8}, {9,10,66,12} }; ASSERT_TRUE(givenMatrix1 == expectedMatrix1); algebra::Matrix<double> givenMatrix2 = { {65.4,936.12}, {47.1,93.15}, {78.21,45.21}, {90.23,81.23} }; givenMatrix2(1,1) = 15.93; givenMatrix2(2,0) = 21.78; givenMatrix2(3,1) = 23.81; const algebra::Matrix<double> expectedMatrix2 = { {65.4,936.12}, {47.1,15.93}, {21.78,45.21}, {90.23,23.81} }; ASSERT_TRUE(givenMatrix2 == expectedMatrix2); } TEST(MatrixSanityTests_ExceptionTest, canDetermineOutOfRangeSubscriptingAttempts) { const algebra::Matrix<int> givenMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; EXPECT_THROW(givenMatrix1(3,3),std::out_of_range); const algebra::Matrix<double> givenMatrix2 = { {3.5,1.9}, {1.2,6.2}, {1.56,3.7}, {4.7,1.8} }; EXPECT_THROW(givenMatrix2(3,2),std::out_of_range); } TEST(MatrixSanityTests,canDetermineRowsAndColumnsSeparately) { const algebra::Matrix<int> givenMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; const std::vector<algebra::Row<int>> rows = givenMatrix1.Rows(); ASSERT_EQ(rows.size(),3); const algebra::Row<int> testableRow0 {1,2,3,4}; const algebra::Row<int> testableRow1 {4,6,7,8}; const algebra::Row<int> testableRow2 {9,10,11,12}; ASSERT_TRUE(rows[0] == testableRow0); ASSERT_TRUE(rows[1] == testableRow1); ASSERT_TRUE(rows[2] == testableRow2); const std::vector<algebra::Column<int>> columns = givenMatrix1.Columns(); ASSERT_EQ(columns.size(),4); const algebra::Column<int> testableColumn0 {1,4,9}; const algebra::Column<int> testableColumn1 {2,6,10}; const algebra::Column<int> testableColumn2 {3,7,11}; const algebra::Column<int> testableColumn3 {4,8,12}; ASSERT_TRUE(columns[0] == testableColumn0); ASSERT_TRUE(columns[1] == testableColumn1); ASSERT_TRUE(columns[2] == testableColumn2); ASSERT_TRUE(columns[3] == testableColumn3); } TEST(MatrixSanityTests, canUpdateIndividualElementOfRow) { algebra::Row<int> testableRow1 = {1,2,3,4,5,6}; testableRow1[1] = 12; testableRow1[3] = 11; const algebra::Row<int> expectedRow1 = {1,12,3,11,5,6}; ASSERT_TRUE(testableRow1 == expectedRow1); algebra::Row<double> testableRow2 = {1.3,1.4,1.5,1.6}; testableRow2[1] = 4.45; testableRow2[2] = 87.34; const algebra::Row<double> expectedRow2 = {1.3,4.45,87.34,1.6}; ASSERT_TRUE(testableRow2 == expectedRow2); } TEST(MatrixSanityTests, canUpdateIndividualElementOfColumn) { algebra::Column<int> testableColumn1 = {1,2,3,4,5,6}; testableColumn1[1] = 12; testableColumn1[3] = 11; const algebra::Column<int> expectedColumn1 = {1,12,3,11,5,6}; ASSERT_TRUE(testableColumn1 == expectedColumn1); algebra::Column<double> testableColumn2 = {1.3,1.4,1.5,1.6}; testableColumn2[1] = 4.45; testableColumn2[2] = 87.34; const algebra::Column<double> expectedColumn2 = {1.3,4.45,87.34,1.6}; ASSERT_TRUE(testableColumn2 == expectedColumn2); } TEST(MatrixSanityTests,canInitializeMatrixWithRows) { const std::vector<algebra::Row<int>> testableIntRows = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; const algebra::Matrix<int> testableIntMatrix = testableIntRows; const algebra::Matrix<int> expectedIntMatrix = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} }; ASSERT_TRUE(testableIntMatrix == expectedIntMatrix); const std::pair<size_t,size_t> expectedIntPair = std::make_pair<size_t,size_t>(3,4); ASSERT_TRUE(testableIntMatrix.Order() == expectedIntPair); const std::vector<algebra::Row<double>> testableDoubleRows = {{1.3,1.4,1.5},{2.7,2.8,2.9},{3.1,3.2,3.3}}; const algebra::Matrix<double> testableDoubleMatrix = testableDoubleRows; const algebra::Matrix<double> expectedDoubleMatrix = { {1.3,1.4,1.5}, {2.7,2.8,2.9}, {3.1,3.2,3.3} }; ASSERT_TRUE(testableDoubleMatrix == expectedDoubleMatrix); const std::pair<size_t,size_t> expectedDoublepair = std::make_pair<size_t,size_t>(3,3); ASSERT_TRUE(testableDoubleMatrix.Order() == expectedDoublepair); } TEST(MatrixSanityTests, canInitializeMatrixWithColumns) { const std::vector<algebra::Column<int>> testableIntColumns = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; const algebra::Matrix<int> testableIntMatrix = testableIntColumns; const algebra::Matrix<int> expectedIntMatrix = { {1,5,9}, {2,6,10}, {3,7,11}, {4,8,12} }; ASSERT_TRUE(testableIntMatrix == expectedIntMatrix); std::pair<size_t,size_t> expectedIntPair = std::make_pair<size_t,size_t>(4,3); ASSERT_TRUE(testableIntMatrix.Order() == expectedIntPair); const std::vector<algebra::Column<double>> testableDoubleColumns = {{65.4,36.12,90.23,65.78},{47.1,93.15,81.32,43.98}}; const algebra::Matrix<double> testableDoubleMatrix = testableDoubleColumns; const algebra::Matrix<double> expectedDoubleMatrix = { {65.4,47.1}, {36.12,93.15}, {90.23,81.32}, {65.78,43.98} }; ASSERT_TRUE(testableDoubleMatrix == expectedDoubleMatrix); std::pair<size_t,size_t> expectedDoublePair = std::make_pair<size_t,size_t>(4,2); ASSERT_TRUE(expectedDoubleMatrix.Order() == expectedDoublePair); } TEST(MatrixSanityTests, canUpdateRowWithCopyAssignmentOperator) { algebra::Row<int> testableRow1 = {1,2,3,4,5}; const algebra::Row<int> testableRow2 = {7,8,9,10,11}; testableRow1 = testableRow2; const algebra::Row<int> expectedRow1 = {7,8,9,10,11}; ASSERT_TRUE(testableRow1 == expectedRow1); algebra::Row<double> testableRow3 = {1.2,3.4,5.6,7.8}; const algebra::Row<double> testableRow4 = {9.10,11.12,13.14,15.16}; testableRow3 = testableRow4; const algebra::Row<double> expectedRow3 = {9.10,11.12,13.14,15.16}; ASSERT_TRUE(testableRow3 == expectedRow3); } TEST(MatrixSanityTests, canUpdateColumnWithCopyAssignmentOperator) { algebra::Column<int> testableColumn1 = {1,2,3,4,5}; const algebra::Column<int> testableColumn2 = {7,8,9,10,11}; testableColumn1 = testableColumn2; const algebra::Column<int> expectedColumn1 = {7,8,9,10,11}; ASSERT_TRUE(testableColumn1 == expectedColumn1); algebra::Column<double> testableColumn3 = {1.2,3.4,5.6,7.8}; const algebra::Column<double> testableColumn4 = {9.10,11.12,13.14,15.16}; testableColumn3 = testableColumn4; const algebra::Column<double> expectedColumn3 = {9.10,11.12,13.14,15.16}; ASSERT_TRUE(testableColumn3 == expectedColumn3); } TEST(MatrixSanityTests_ExceptionTest, canDetermineCopyAssignmentAttemptsForUnequalSizes) { algebra::Row<int> testableRow1 = {1,2,3,4,5}; const algebra::Row<int> testableRow2 = {7,8,9,10}; EXPECT_THROW(testableRow1 = testableRow2,std::length_error); algebra::Row<double> testableRow3 = {1.2,3.4,5.6,7.8}; const algebra::Row<double> testableRow4 = {9.10,11.12,13.14}; EXPECT_THROW(testableRow3 = testableRow4,std::length_error); algebra::Column<int> testableColumn1 = {1,2,3,4}; const algebra::Column<int> testableColumn2 = {7,8,9,10,11}; EXPECT_THROW(testableColumn1 = testableColumn2,std::length_error); algebra::Column<double> testableColumn3 = {1.2,3.4,5.6}; const algebra::Column<double> testableColumn4 = {9.10,11.12,13.14,15.16}; EXPECT_THROW(testableColumn3 = testableColumn4,std::length_error); } TEST(MatrixSanityTests, canUpdateMatrixWithCopyAssignmentOperator) { algebra::Matrix<int> testableMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; const algebra::Matrix<int> testableMatrix2 = { {13,14,15,16}, {17,18,19,20}, {21,22,23,24} }; testableMatrix1 = testableMatrix2; const algebra::Matrix<int> expectedMatrix1 = { {13,14,15,16}, {17,18,19,20}, {21,22,23,24} }; ASSERT_TRUE(testableMatrix1 == expectedMatrix1); algebra::Matrix<double> testableMatrix3 = { {23.65,12.54,19.64,17.23}, {98.12,186.32,12.87,145.32}, {98.123,76.12,984.12,12.98}, {198.43,12.87,164.76,983.1} }; const algebra::Matrix<double> testableMatrix4 = { {65.23,54.12,54.19,23.17}, {12.98,43.186,87.12,32.145}, {123.98,12.76,12.984,98.12}, {43.198,87.12,76.164,1.983} }; testableMatrix3 = testableMatrix4; const algebra::Matrix<double> expectedMatrix3 = { {65.23,54.12,54.19,23.17}, {12.98,43.186,87.12,32.145}, {123.98,12.76,12.984,98.12}, {43.198,87.12,76.164,1.983} }; ASSERT_TRUE(testableMatrix3 == expectedMatrix3); } TEST(MatrixSanityTests_ExceptionTest, canDetermineCopyAssignmentAttemptsForMatricesOfDifferentOrder) { algebra::Matrix<int> testableMatrix1 = { {1,2,3,4}, {4,6,7,8}, {9,10,11,12} }; const algebra::Matrix<int> testableMatrix2 = { {13,14,15}, {17,18,19}, {21,22,23} }; EXPECT_THROW(testableMatrix1 = testableMatrix2,std::length_error); algebra::Matrix<double> testableMatrix3 = { {23.65,12.54,19.64,17.23}, {98.12,186.32,12.87,145.32}, {98.123,76.12,984.12,12.98}, {198.43,12.87,164.76,983.1} }; const algebra::Matrix<double> testableMatrix4 = { {65.23,54.12,54.19,23.17}, {12.98,43.186,87.12,32.145}, {123.98,12.76,12.984,98.12} }; EXPECT_THROW(testableMatrix3 = testableMatrix4,std::length_error); }
31.377049
121
0.676519
[ "vector" ]
6ef2a051384ce0610c63d361acafbccd9e748508
653
cpp
C++
others/mos.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
others/mos.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
others/mos.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
int len = sqrt(n); struct query{ int l,r,id;//詢問的左界右界 以及 第幾筆詢問 friend bool operator<(const query& lhs,const query& rhs){ return ((lhs.l / len) == (rhs.l / len)) ? lhs.r<rhs.r : lhs.l<rhs.l; }//先判斷是不是在同一塊 不同塊的話就比較塊的順序,否則比較右界r }; int ans[200005] = {}, t = 0; vector<query> q; void add(int idx){...} void sub(int idx){...} void mos(){ sort(all(q)); for(int i = 0, l = -2, r = -1; i < q.size(); ++i){ while(l > q[i].l) add(--l); while(r < q[i].r) add(++r);//先做新增元素的 while(l < q[i].l) sub(l++);//再做移除元素的 while(r > q[i].r) sub(r--); ans[q[i].id] = t//移到區間後儲存答案 } }
29.681818
77
0.491577
[ "vector" ]
6ef706b6ddc20698cd3f3dfee6ffcb94488b9992
21,257
cc
C++
Studio/src/Application/Analysis/AnalysisTool.cc
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
Studio/src/Application/Analysis/AnalysisTool.cc
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
Studio/src/Application/Analysis/AnalysisTool.cc
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
// std #include <iostream> // qt #include <QXmlStreamWriter> #include <QThread> #include <QTemporaryFile> #include <QFileDialog> #include <QProcess> #include <QMessageBox> // shapeworks #include <Visualization/ShapeWorksStudioApp.h> #include <Visualization/ShapeworksWorker.h> #include <Data/Project.h> #include <Data/Mesh.h> #include <Data/Shape.h> #include <Analysis/AnalysisTool.h> #include <Visualization/Lightbox.h> #include <Visualization/DisplayObject.h> #include <ui_AnalysisTool.h> //--------------------------------------------------------------------------- AnalysisTool::AnalysisTool(Preferences& prefs) : preferences_(prefs) { this->ui_ = new Ui_AnalysisTool; this->ui_->setupUi(this); this->stats_ready_ = false; // defautl to linear scale this->ui_->log_radio->setChecked(false); this->ui_->linear_radio->setChecked(true); connect(this->ui_->allSamplesRadio, SIGNAL(clicked()), this, SLOT(handle_analysis_options())); connect(this->ui_->singleSamplesRadio, SIGNAL(clicked()), this, SLOT(handle_analysis_options())); connect(this->ui_->sampleSpinBox, SIGNAL(valueChanged(int)), this, SLOT(handle_analysis_options())); connect(this->ui_->medianButton, SIGNAL(clicked()), this, SLOT(handle_median())); connect(this->ui_->pcaAnimateCheckBox, SIGNAL(stateChanged(int)), this, SLOT(handle_pca_animate_state_changed())); connect(&this->pca_animate_timer_, SIGNAL(timeout()), this, SLOT(handle_pca_timer())); // group animation connect(this->ui_->group_animate_checkbox, &QCheckBox::clicked, this, &AnalysisTool::handle_group_animate_state_changed); connect(&this->group_animate_timer_, &QTimer::timeout, this, &AnalysisTool::handle_group_timer); connect(this->ui_->pca_radio_button, &QRadioButton::clicked, this, &AnalysisTool::pca_update); connect(this->ui_->group_radio_button, &QRadioButton::clicked, this, &AnalysisTool::pca_update); } //--------------------------------------------------------------------------- std::string AnalysisTool::getAnalysisMode() { if (this->ui_->tabWidget->currentWidget() == this->ui_->samples_tab) { if (this->ui_->allSamplesRadio->isChecked()) { return "all samples";} if (this->ui_->singleSamplesRadio->isChecked()) { return "single sample";} } if (this->ui_->tabWidget->currentWidget() == this->ui_->mean_tab) { return "mean";} if (this->ui_->tabWidget->currentWidget() == this->ui_->pca_tab) { return "pca";} if (this->ui_->tabWidget->currentWidget() == this->ui_->regression_tab) { return "regression";} return ""; } //--------------------------------------------------------------------------- bool AnalysisTool::get_group_difference_mode() { return this->ui_->difference_button->isChecked(); } //--------------------------------------------------------------------------- std::vector<Point> AnalysisTool::get_group_difference_vectors() { std::vector<Point> vecs; auto num_points = this->stats_.Mean().size() / 3; for (unsigned int i = 0; i < num_points; i++) { Point tmp; tmp.x = this->stats_.Group2Mean()[i * 3] - this->stats_.Group1Mean()[i * 3]; tmp.y = this->stats_.Group2Mean()[i * 3 + 1] - this->stats_.Group1Mean()[i * 3 + 1]; tmp.z = this->stats_.Group2Mean()[i * 3 + 2] - this->stats_.Group1Mean()[i * 3 + 2]; vecs.push_back(tmp); } return vecs; } //--------------------------------------------------------------------------- void AnalysisTool::on_linear_radio_toggled(bool b) { if (b) { this->ui_->graph_->set_log_scale(false); this->ui_->graph_->repaint(); } else { this->ui_->graph_->set_log_scale(true); this->ui_->graph_->repaint(); } } //--------------------------------------------------------------------------- void AnalysisTool::handle_reconstruction_complete() { this->project_->handle_clear_cache(); this->project_->calculate_reconstructed_samples(); emit progress(100); emit message("Reconstruction Complete"); emit reconstruction_complete(); ///TODO: Studio ///this->ui_->run_optimize_button->setEnabled(true); this->enableActions(); } //--------------------------------------------------------------------------- void AnalysisTool::on_reconstructionButton_clicked() { this->save_to_preferences(); emit message("Please wait: running reconstruction step..."); emit progress(5); //this->ui_->run_optimize_button->setEnabled(false); this->ui_->reconstructionButton->setEnabled(false); QThread* thread = new QThread; std::vector<std::vector<itk::Point<double>>> local, global; std::vector<ImageType::Pointer> images; auto shapes = this->project_->get_shapes(); local.resize(shapes.size()); global.resize(shapes.size()); images.resize(shapes.size()); size_t ii = 0; for (auto &s : shapes) { auto l = s->get_local_correspondence_points(); auto g = s->get_global_correspondence_points(); for (size_t i = 0; i < l.size(); i += 3) { itk::Point<double> pt, pt2; pt[0] = l[i]; pt[1] = l[i + 1]; pt[2] = l[i + 2]; pt2[0] = g[i]; pt2[1] = g[i + 1]; pt2[2] = g[i + 2]; local[ii].push_back(pt); global[ii].push_back(pt2); } images[ii] = s->get_groomed_image(); ii++; } ShapeworksWorker* worker = new ShapeworksWorker( ShapeworksWorker::ReconstructType, NULL, NULL, this->project_, local, global, images, this->ui_->maxAngle->value(), this->ui_->meshDecimation->value(), this->ui_->numClusters->value()); worker->moveToThread(thread); connect(thread, SIGNAL(started()), worker, SLOT(process())); connect(worker, SIGNAL(result_ready()), this, SLOT(handle_reconstruction_complete())); connect(worker, SIGNAL(error_message(std::string)), this, SLOT(handle_error(std::string))); connect(worker, SIGNAL(warning_message(std::string)), this, SLOT(handle_warning(std::string))); connect(worker, SIGNAL(message(std::string)), this, SLOT(handle_message(std::string))); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); thread->start(); emit progress(15); } //--------------------------------------------------------------------------- int AnalysisTool::getPCAMode() { return this->ui_->pcaModeSpinBox->value(); } //--------------------------------------------------------------------------- double AnalysisTool::get_group_value() { double groupSliderValue = this->ui_->group_slider->value(); double groupRatio = groupSliderValue / static_cast<double>(this->ui_->group_slider->maximum()); return groupRatio; } //--------------------------------------------------------------------------- bool AnalysisTool::pcaAnimate() { return this->ui_->pcaAnimateCheckBox->isChecked(); } //--------------------------------------------------------------------------- bool AnalysisTool::groupAnimate() { return this->ui_->group_animate_checkbox->isChecked(); } //--------------------------------------------------------------------------- void AnalysisTool::setLabels(QString which, QString value) { if (which == QString("pca")) { this->ui_->pcaValueLabel->setText(value); } else if (which == QString("eigen")) { this->ui_->pcaEigenValueLabel->setText(value); } else if (which == QString("lambda")) { this->ui_->pcaLambdaLabel->setText(value); } } //--------------------------------------------------------------------------- int AnalysisTool::getSampleNumber() { return this->ui_->sampleSpinBox->value(); } //--------------------------------------------------------------------------- AnalysisTool::~AnalysisTool() {} //--------------------------------------------------------------------------- void AnalysisTool::set_project(QSharedPointer<Project> project) { this->project_ = project; } //--------------------------------------------------------------------------- void AnalysisTool::set_app(ShapeWorksStudioApp* app) { this->app_ = app; } //--------------------------------------------------------------------------- void AnalysisTool::activate() { this->update_analysis_mode(); } //--------------------------------------------------------------------------- void AnalysisTool::update_analysis_mode() { // update UI this->handle_analysis_options(); // groups available } //--------------------------------------------------------------------------- void AnalysisTool::compute_mode_shape() {} //--------------------------------------------------------------------------- void AnalysisTool::handle_analysis_options() { if (this->ui_->tabWidget->currentWidget() == this->ui_->samples_tab) { if (this->ui_->singleSamplesRadio->isChecked()) { //one sample mode this->ui_->sampleSpinBox->setEnabled(true); this->ui_->medianButton->setEnabled(true); this->ui_->pcaSlider->setEnabled(false); this->ui_->pcaAnimateCheckBox->setEnabled(false); this->ui_->pcaModeSpinBox->setEnabled(false); this->ui_->pcaAnimateCheckBox->setChecked(false); } else { //all samples mode this->ui_->sampleSpinBox->setEnabled(false); this->ui_->medianButton->setEnabled(false); this->ui_->pcaSlider->setEnabled(false); this->ui_->pcaAnimateCheckBox->setEnabled(false); this->ui_->pcaModeSpinBox->setEnabled(false); this->ui_->pcaAnimateCheckBox->setChecked(false); } } else if (this->ui_->tabWidget->currentWidget() == this->ui_->mean_tab) { //mean mode this->ui_->sampleSpinBox->setEnabled(false); this->ui_->medianButton->setEnabled(false); this->ui_->pcaSlider->setEnabled(false); this->ui_->pcaAnimateCheckBox->setEnabled(false); this->ui_->pcaModeSpinBox->setEnabled(false); this->ui_->pcaAnimateCheckBox->setChecked(false); } else if (this->ui_->tabWidget->currentWidget() == this->ui_->pca_tab) { //pca mode this->ui_->sampleSpinBox->setEnabled(false); this->ui_->medianButton->setEnabled(false); this->ui_->pcaSlider->setEnabled(true); this->ui_->pcaAnimateCheckBox->setEnabled(true); this->ui_->pcaModeSpinBox->setEnabled(true); } else { //regression mode this->ui_->sampleSpinBox->setEnabled(false); this->ui_->medianButton->setEnabled(false); this->ui_->pcaSlider->setEnabled(false); this->ui_->pcaAnimateCheckBox->setEnabled(false); this->ui_->pcaModeSpinBox->setEnabled(false); } this->ui_->group1_button->setEnabled(this->project_->groups_available()); this->ui_->group2_button->setEnabled(this->project_->groups_available()); this->ui_->difference_button->setEnabled(this->project_->groups_available()); this->ui_->group_slider_widget->setEnabled(this->project_->groups_available()); emit update_view(); } //--------------------------------------------------------------------------- void AnalysisTool::handle_median() { if (!this->compute_stats()) { return;} this->ui_->sampleSpinBox->setValue(this->stats_.ComputeMedianShape(-32)); //-32 = both groups emit update_view(); } //----------------------------------------------------------------------------- void AnalysisTool::on_overall_button_clicked() { emit update_view(); } //----------------------------------------------------------------------------- void AnalysisTool::on_group1_button_clicked() { emit update_view(); } //----------------------------------------------------------------------------- void AnalysisTool::on_group2_button_clicked() { emit update_view(); } //----------------------------------------------------------------------------- void AnalysisTool::on_difference_button_clicked() { emit update_view(); } //----------------------------------------------------------------------------- bool AnalysisTool::compute_stats() { if (this->stats_ready_) { return true; } if (this->project_->get_shapes().size() == 0 || !this->project_->reconstructed_present()) { return false; } std::vector < vnl_vector < double >> points; std::vector<int> group_ids; foreach(ShapeHandle shape, this->project_->get_shapes()) { points.push_back(shape->get_global_correspondence_points()); group_ids.push_back(shape->get_group_id()); } this->stats_.ImportPoints(points, group_ids); this->stats_.ComputeModes(); this->stats_ready_ = true; std::vector<double> vals; for (int i = this->stats_.Eigenvalues().size() - 1; i > 0; i--) { vals.push_back(this->stats_.Eigenvalues()[i]); } this->ui_->graph_->set_data(vals); this->ui_->graph_->repaint(); // set widget enable state for groups bool groups_available = this->project_->groups_available(); this->ui_->group_slider->setEnabled(groups_available); this->ui_->group_animate_checkbox->setEnabled(groups_available); this->ui_->group_radio_button->setEnabled(groups_available); return true; } //----------------------------------------------------------------------------- const vnl_vector<double>& AnalysisTool::get_mean_shape() { if (!this->compute_stats()) { return this->empty_shape_; } if (this->ui_->group1_button->isChecked()) { return this->stats_.Group1Mean(); } else if (this->ui_->group2_button->isChecked()) { return this->stats_.Group2Mean(); } return this->stats_.Mean(); } //----------------------------------------------------------------------------- const vnl_vector<double>& AnalysisTool::get_shape(int mode, double value, double group_value) { if (!this->compute_stats() || this->stats_.Eigenvectors().size() <= 1) { return this->empty_shape_; } if (mode + 2 > this->stats_.Eigenvalues().size()) {mode = this->stats_.Eigenvalues().size() - 2;} unsigned int m = this->stats_.Eigenvectors().columns() - (mode + 1); vnl_vector<double> e = this->stats_.Eigenvectors().get_column(m); double lambda = sqrt(this->stats_.Eigenvalues()[m]); this->pca_labels_changed(QString::number(value, 'g', 2), QString::number(this->stats_.Eigenvalues()[m]), QString::number(value * lambda)); if (this->ui_->group_radio_button->isChecked()) { this->temp_shape_ = this->stats_.Group1Mean() + (this->stats_.GroupDifference() * group_value); } else { this->temp_shape_ = this->stats_.Mean() + (e * (value * lambda)); } return this->temp_shape_; } //--------------------------------------------------------------------------- ParticleShapeStatistics<3> AnalysisTool::get_stats() { this->compute_stats(); return this->stats_; } //--------------------------------------------------------------------------- void AnalysisTool::load_from_preferences() { this->ui_->numClusters->setValue( this->preferences_.get_preference("reconstruction_clusters", this->ui_->numClusters->value())); this->ui_->meshDecimation->setValue( this->preferences_.get_preference("reconstruction_decimation", this->ui_->meshDecimation->value())); this->ui_->maxAngle->setValue( this->preferences_.get_preference("reconstruction_maxAngle", this->ui_->maxAngle->value())); } //--------------------------------------------------------------------------- void AnalysisTool::save_to_preferences() { this->preferences_.set_preference("reconstruction_clusters", this->ui_->numClusters->value()); this->preferences_.set_preference("reconstruction_decimation", this->ui_->meshDecimation->value()); this->preferences_.set_preference("reconstruction_maxAngle", this->ui_->maxAngle->value()); } //--------------------------------------------------------------------------- void AnalysisTool::shutdown() { this->pca_animate_timer_.stop(); } //--------------------------------------------------------------------------- bool AnalysisTool::export_variance_graph(QString filename) { return this->ui_->graph_->grab().save(filename); } //--------------------------------------------------------------------------- void AnalysisTool::on_tabWidget_currentChanged() { this->update_analysis_mode(); } //--------------------------------------------------------------------------- void AnalysisTool::on_pcaSlider_valueChanged() { // this will make the slider handle redraw making the UI appear more responsive QCoreApplication::processEvents(); emit pca_update(); } //--------------------------------------------------------------------------- void AnalysisTool::on_group_slider_valueChanged() { // this will make the slider handle redraw making the UI appear more responsive QCoreApplication::processEvents(); emit pca_update(); } //--------------------------------------------------------------------------- void AnalysisTool::on_pcaModeSpinBox_valueChanged(int i) { emit pca_update(); } //--------------------------------------------------------------------------- void AnalysisTool::handle_pca_animate_state_changed() { if (this->pcaAnimate()) { //this->setPregenSteps(); this->pca_animate_timer_.setInterval(10); this->pca_animate_timer_.start(); } else { this->pca_animate_timer_.stop(); } } //--------------------------------------------------------------------------- void AnalysisTool::handle_pca_timer() { int value = this->ui_->pcaSlider->value(); if (this->pca_animate_direction_) { value += this->ui_->pcaSlider->singleStep(); } else { value -= this->ui_->pcaSlider->singleStep(); } if (value >= this->ui_->pcaSlider->maximum() || value <= this->ui_->pcaSlider->minimum()) { this->pca_animate_direction_ = !this->pca_animate_direction_; //this->setPregenSteps(); } this->ui_->pcaSlider->setValue(value); } //--------------------------------------------------------------------------- void AnalysisTool::handle_group_animate_state_changed() { if (this->groupAnimate()) { //this->setPregenSteps(); this->group_animate_timer_.setInterval(10); this->group_animate_timer_.start(); } else { this->group_animate_timer_.stop(); } } //--------------------------------------------------------------------------- void AnalysisTool::handle_group_timer() { int value = this->ui_->group_slider->value(); if (this->group_animate_direction_) { value += this->ui_->group_slider->singleStep(); } else { value -= this->ui_->group_slider->singleStep(); } if (value >= this->ui_->group_slider->maximum() || value <= this->ui_->group_slider->minimum()) { this->group_animate_direction_ = !this->group_animate_direction_; //this->setPregenSteps(); } this->ui_->group_slider->setValue(value); } //--------------------------------------------------------------------------- double AnalysisTool::get_pca_value() { int slider_value = this->ui_->pcaSlider->value(); float range = preferences_.get_preference("pca_range", 2.f); int halfRange = this->ui_->pcaSlider->maximum(); double value = (double)slider_value / (double)halfRange * range; return value; } //--------------------------------------------------------------------------- void AnalysisTool::pca_labels_changed(QString value, QString eigen, QString lambda) { this->setLabels(QString("pca"), value); this->setLabels(QString("eigen"), eigen); this->setLabels(QString("lambda"), lambda); } //--------------------------------------------------------------------------- void AnalysisTool::updateSlider() { auto steps = std::max(this->preferences_.get_preference("pca_steps", 20), 3); auto max = this->preferences_.get_preference("pca_range", 20.); auto sliderRange = this->ui_->pcaSlider->maximum() - this->ui_->pcaSlider->minimum(); this->ui_->pcaSlider->setSingleStep(sliderRange / steps); } //--------------------------------------------------------------------------- void AnalysisTool::reset_stats() { this->ui_->tabWidget->setCurrentWidget(this->ui_->mean_tab); this->ui_->allSamplesRadio->setChecked(true); this->ui_->singleSamplesRadio->setChecked(false); this->ui_->sampleSpinBox->setEnabled(false); this->ui_->medianButton->setEnabled(false); this->ui_->pcaSlider->setEnabled(false); this->ui_->pcaAnimateCheckBox->setEnabled(false); this->ui_->pcaModeSpinBox->setEnabled(false); this->ui_->pcaAnimateCheckBox->setChecked(false); this->stats_ready_ = false; this->stats_ = ParticleShapeStatistics<3>(); } //--------------------------------------------------------------------------- void AnalysisTool::enableActions() { this->ui_->reconstructionButton->setEnabled( this->project_->reconstructed_present() && this->project_->get_groomed_present()); } //--------------------------------------------------------------------------- void AnalysisTool::setAnalysisMode(std::string mode) { if (mode == "all samples" || mode == "single sample") { this->ui_->allSamplesRadio->setChecked(mode == "all samples"); this->ui_->singleSamplesRadio->setChecked(mode == "single sample"); this->ui_->tabWidget->setCurrentWidget(this->ui_->samples_tab); } else if (mode == "mean") { this->ui_->tabWidget->setCurrentWidget(this->ui_->mean_tab); } else if (mode == "pca") { this->ui_->tabWidget->setCurrentWidget(this->ui_->pca_tab); } else if (mode == "regression") { this->ui_->tabWidget->setCurrentWidget(this->ui_->regression_tab); } }
33.74127
101
0.569883
[ "mesh", "shape", "vector" ]
6efe1121aff93972eacb8f0b562ddb1fe3cd8e09
5,432
cc
C++
DPGAnalysis/SiStripTools/src/TSOSHistogramMaker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DPGAnalysis/SiStripTools/src/TSOSHistogramMaker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DPGAnalysis/SiStripTools/src/TSOSHistogramMaker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "DPGAnalysis/SiStripTools/interface/TSOSHistogramMaker.h" #include <iostream> #include "TH1F.h" #include "TH2F.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/TransientTrackingRecHit/interface/TransientTrackingRecHit.h" TSOSHistogramMaker::TSOSHistogramMaker(): m_2dhistos(false), m_detsels(), m_selnames(), m_seltitles(), m_histocluslenangle(), m_tsosy(), m_tsosx(), m_tsosxy(), m_ttrhy(), m_ttrhx(), m_ttrhxy(), m_tsosdy(), m_tsosdx(), m_tsosdxdy() {} TSOSHistogramMaker::TSOSHistogramMaker(const edm::ParameterSet& iConfig): m_2dhistos(iConfig.getUntrackedParameter<bool>("wanted2DHistos",false)), m_detsels(), m_selnames(), m_seltitles(), m_histocluslenangle(), m_tsosy(), m_tsosx(), m_tsosxy(), m_ttrhy(), m_ttrhx(), m_ttrhxy(), m_tsosdy(), m_tsosdx(), m_tsosdxdy() { edm::Service<TFileService> tfserv; std::vector<edm::ParameterSet> wantedsubds(iConfig.getParameter<std::vector<edm::ParameterSet> >("wantedSubDets")); std::cout << "selections found: " << wantedsubds.size() << std::endl; for(std::vector<edm::ParameterSet>::iterator ps=wantedsubds.begin();ps!=wantedsubds.end();++ps) { m_selnames.push_back(ps->getParameter<std::string>("detLabel")); if(ps->existsAs<std::string>("title")) { m_seltitles.push_back(ps->getParameter<std::string>("title")); } else { m_seltitles.push_back(ps->getParameter<std::string>("detLabel")); } m_detsels.push_back(DetIdSelector(ps->getUntrackedParameter<std::vector<std::string> >("selection"))); } for(unsigned int isel=0;isel<m_detsels.size();++isel) { TFileDirectory subdir = tfserv->mkdir(m_selnames[isel]); std::string name = "tsosy_" + m_selnames[isel]; std::string title = "TSOS y " + m_seltitles[isel]; m_tsosy.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),200,-20.,20.)); name = "tsosx_" + m_selnames[isel]; title = "TSOS x " + m_seltitles[isel]; m_tsosx.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),200,-20.,20.)); if(m_2dhistos) { name = "tsosxy_" + m_selnames[isel]; title = "TSOS y vs x " + m_seltitles[isel]; m_tsosxy.push_back(subdir.make<TH2F>(name.c_str(),title.c_str(),200,-20.,20.,200,-20.,20.)); } name = "tsosprojx_" + m_selnames[isel]; title = "TSOS x projection " + m_seltitles[isel]; m_tsosprojx.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),400,-2.,2.)); name = "tsosprojy_" + m_selnames[isel]; title = "TSOS y projection " + m_seltitles[isel]; m_tsosprojy.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),400,-2.,2.)); name = "ttrhy_" + m_selnames[isel]; title = "TT RecHit y " + m_seltitles[isel]; m_ttrhy.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),200,-20.,20.)); name = "ttrhx_" + m_selnames[isel]; title = "TT RecHit x " + m_seltitles[isel]; m_ttrhx.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),200,-20.,20.)); if(m_2dhistos) { name = "ttrhxy_" + m_selnames[isel]; title = "TT RecHit y vs x " + m_seltitles[isel]; m_ttrhxy.push_back(subdir.make<TH2F>(name.c_str(),title.c_str(),200,-20.,20.,200,-20.,20.)); } name = "tsosdy_" + m_selnames[isel]; title = "TSOS-TTRH y " + m_seltitles[isel]; m_tsosdy.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),200,-5.,5.)); name = "tsosdx_" + m_selnames[isel]; title = "TSOS-TTRH x " + m_seltitles[isel]; m_tsosdx.push_back(subdir.make<TH1F>(name.c_str(),title.c_str(),200,-0.1,0.1)); if(m_2dhistos) { name = "tsosdxdy_" + m_selnames[isel]; title = "TSOS-TTRH dy vs dy " + m_seltitles[isel]; m_tsosdxdy.push_back(subdir.make<TH2F>(name.c_str(),title.c_str(),200,-0.1,0.1,200,-5.,5.)); } name = "cluslenangle_" + m_selnames[isel]; title = "Cluster Length vs Track Angle " + m_seltitles[isel]; m_histocluslenangle.push_back(subdir.make<TH2F>(name.c_str(),title.c_str(),200,-1.,1.,40,-0.5,39.5)); } } void TSOSHistogramMaker::fill(const TrajectoryStateOnSurface& tsos, TransientTrackingRecHit::ConstRecHitPointer hit) const { if(hit==0 || !hit->isValid()) return; for(unsigned int i=0; i<m_detsels.size() ; ++i) { if(m_detsels[i].isSelected(hit->geographicalId())) { m_tsosy[i]->Fill(tsos.localPosition().y()); m_tsosx[i]->Fill(tsos.localPosition().x()); if(m_2dhistos) m_tsosxy[i]->Fill(tsos.localPosition().x(),tsos.localPosition().y()); m_ttrhy[i]->Fill(hit->localPosition().y()); m_ttrhx[i]->Fill(hit->localPosition().x()); if(m_2dhistos) m_ttrhxy[i]->Fill(hit->localPosition().x(),hit->localPosition().y()); m_tsosdy[i]->Fill(tsos.localPosition().y()-hit->localPosition().y()); m_tsosdx[i]->Fill(tsos.localPosition().x()-hit->localPosition().x()); if(m_2dhistos) m_tsosdxdy[i]->Fill(tsos.localPosition().x()-hit->localPosition().x(),tsos.localPosition().y()-hit->localPosition().y()); if(tsos.localDirection().z() != 0) { m_tsosprojx[i]->Fill(tsos.localDirection().x()/tsos.localDirection().z()); m_tsosprojy[i]->Fill(tsos.localDirection().y()/tsos.localDirection().z()); } } } }
41.784615
148
0.661267
[ "vector" ]
3e04f02be546123891d6aa7357437bb78a9f701c
37,798
cpp
C++
game/g_nav.cpp
kugelrund/Elite-Reinforce
a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca
[ "DOC" ]
10
2017-07-04T14:38:48.000Z
2022-03-08T22:46:39.000Z
game/g_nav.cpp
UberGames/SP-Mod-Source-Code
04e0e618d1ee57a2919f1a852a688c03b1aa155d
[ "DOC" ]
null
null
null
game/g_nav.cpp
UberGames/SP-Mod-Source-Code
04e0e618d1ee57a2919f1a852a688c03b1aa155d
[ "DOC" ]
2
2017-04-23T18:24:44.000Z
2021-11-19T23:27:03.000Z
#include "b_local.h" #include "g_nav.h" #include "g_navigator.h" //Global navigator CNavigator navigator; qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ); qboolean G_FindClosestPointOnLineSegment( const vec3_t start, const vec3_t end, const vec3_t from, vec3_t result ); //For debug graphics extern void CG_Line( vec3_t start, vec3_t end, vec3_t color, float alpha ); extern void CG_Cube( vec3_t mins, vec3_t maxs, vec3_t color, float alpha ); extern void G_AddVoiceEvent( gentity_t *self, int event, int speakDebounceTime ); extern qboolean NPC_CheckDisguise( gentity_t *ent ); #define MIN_STOP_DIST 64 /* ------------------------- NPC_Blocked ------------------------- */ #define MIN_BLOCKED_SPEECH_TIME 4000 void NPC_Blocked( gentity_t *self, gentity_t *blocker ) { if ( self->NPC == NULL ) return; //Don't do this too often if ( self->NPC->blockedSpeechDebounceTime > level.time ) return; //Attempt to run any blocked scripts if ( VALIDSTRING( self->behaviorSet[BSET_BLOCKED] ) ) { //Run our blocked script G_ActivateBehavior( self, BSET_BLOCKED ); return; } //If this is one of our enemies, then just attack him if ( blocker->client && ( blocker->client->playerTeam == self->client->enemyTeam ) ) { G_SetEnemy( self, blocker ); return; } Debug_Printf( debugNPCAI, DEBUG_LEVEL_WARNING, "%s: Excuse me, %s %s!\n", self->targetname, blocker->classname, blocker->targetname ); //If we're being blocked by the player, say something to them if ( ( blocker->s.number == 0 ) && ( ( blocker->client->playerTeam == self->client->playerTeam ) || NPC_CheckDisguise( blocker ) ) ) { //guys in formation are not trying to get to a critical point, //don't make them yell at the player (unless they have an enemy and //are in combat because BP thinks it sounds cool during battle) if ( self->NPC->behaviorState != BS_FORMATION || self->enemy ) { //NOTE: only imperials, misc crewmen and hazard team have these wav files now G_AddVoiceEvent( self, Q_irand(EV_BLOCKED1, EV_BLOCKED3), 0 ); } } self->NPC->blockedSpeechDebounceTime = level.time + MIN_BLOCKED_SPEECH_TIME + ( random() * 4000 ); self->NPC->blockingEntNum = blocker->s.number; } /* ------------------------- NPC_SetMoveGoal ------------------------- */ void NPC_SetMoveGoal( gentity_t *ent, vec3_t point, int radius, bool isNavGoal ) { //Must be an NPC if ( ent->NPC == NULL ) return; //Copy the origin //VectorCopy( point, ent->NPC->goalPoint ); //FIXME: Make it use this, and this alone! VectorCopy( point, ent->NPC->tempGoal->currentOrigin ); //Copy the mins and maxs to the tempGoal VectorCopy( ent->mins, ent->NPC->tempGoal->mins ); VectorCopy( ent->mins, ent->NPC->tempGoal->maxs ); ent->NPC->tempGoal->clipmask = ent->clipmask; ent->NPC->tempGoal->svFlags &= ~SVF_NAVGOAL; ent->NPC->tempGoal->waypoint = WAYPOINT_NONE; if ( isNavGoal ) ent->NPC->tempGoal->svFlags |= SVF_NAVGOAL; ent->NPC->goalEntity = ent->NPC->tempGoal; ent->NPC->goalRadius = radius; } /* ------------------------- NAV_HitNavGoal ------------------------- */ qboolean NAV_HitNavGoal( vec3_t point, vec3_t mins, vec3_t maxs, vec3_t dest, int radius ) { vec3_t dmins, dmaxs, pmins, pmaxs; if ( radius & NAVGOAL_USE_RADIUS ) { radius &= ~NAVGOAL_USE_RADIUS; //NOTE: This needs to do a DistanceSquared on navgoals that had // a radius manually set! We can't do the smaller navgoals against // walls to get around this because player-sized traces to them // from angles will not work... - MCG //FIXME: Allow for a little z difference? return ( DistanceSquared(dest, point) <= (radius*radius) ); //There is probably a better way to do this, either by preserving the original // mins and maxs of the navgoal and doing this check ONLY if the radius // is non-zero (like the original implementation) or some boolean to // tell us to do this check rather than the fake bbox overlap check... } else { //Construct a dummy bounding box from our radius value VectorSet( dmins, -radius, -radius, -radius ); VectorSet( dmaxs, radius, radius, radius ); //Translate it VectorAdd( dmins, dest, dmins ); VectorAdd( dmaxs, dest, dmaxs ); //Translate the starting box VectorAdd( point, mins, pmins ); VectorAdd( point, maxs, pmaxs ); //See if they overlap return G_BoundsOverlap( pmins, pmaxs, dmins, dmaxs ); } } /* ------------------------- NAV_ClearPathToPoint ------------------------- */ qboolean NAV_ClearPathToPoint(gentity_t *self, vec3_t pmins, vec3_t pmaxs, vec3_t point, int clipmask) { // trace_t trace; // return NAV_CheckAhead( self, point, trace, clipmask ); vec3_t mins, maxs; trace_t trace; //Test if they're even conceivably close to one another if ( !gi.inPVS( self->currentOrigin, point ) ) return qfalse; if ( self->svFlags & SVF_NAVGOAL ) { if ( !self->owner ) { //SHOULD NEVER HAPPEN!!! assert(0); return qfalse; } VectorCopy( self->owner->mins, mins ); VectorCopy( self->owner->maxs, maxs ); } else { VectorCopy( pmins, mins ); VectorCopy( pmaxs, maxs ); } if ( self->client || ( self->svFlags & SVF_NAVGOAL ) ) { //Clients can step up things, or if this is a navgoal check, a client will be using this info mins[2] += STEPSIZE; //don't let box get inverted if ( mins[2] > maxs[2] ) { mins[2] = maxs[2]; } } if ( self->svFlags & SVF_NAVGOAL ) { //Trace from point to navgoal gi.trace( &trace, point, mins, maxs, self->currentOrigin, self->owner->s.number, (clipmask|CONTENTS_MONSTERCLIP)&~CONTENTS_BODY );//clipmask ); if ( trace.startsolid || trace.allsolid ) { return qfalse; } //Made it if ( trace.fraction == 1.0 ) return qtrue; //Okay, didn't get all the way there, let's see if we got close enough: return NAV_HitNavGoal( self->currentOrigin, self->owner->mins, self->owner->maxs, trace.endpos, NPCInfo->goalRadius ); } else { gi.trace( &trace, self->currentOrigin, mins, maxs, point, self->s.number, clipmask|CONTENTS_MONSTERCLIP); if( ( ( trace.startsolid == qfalse ) && ( trace.allsolid == qfalse ) ) && ( trace.fraction == 1.0f ) ) {//FIXME: check for drops return qtrue; } return qfalse; } } /* ------------------------- NAV_FindClosestWaypointForEnt ------------------------- */ int NAV_FindClosestWaypointForEnt( gentity_t *ent, int targWp ) { //FIXME: Take the target into account return navigator.GetNearestNode( ent, ent->waypoint, NF_CLEAR_PATH ); } /* ------------------------- NAV_ClearBlockedInfo ------------------------- */ void NAV_ClearBlockedInfo( gentity_t *self ) { self->NPC->aiFlags &= ~NPCAI_BLOCKED; self->NPC->blockingEntNum = ENTITYNUM_WORLD; } /* ------------------------- NAV_SetBlockedInfo ------------------------- */ void NAV_SetBlockedInfo( gentity_t *self, int entId ) { self->NPC->aiFlags |= NPCAI_BLOCKED; self->NPC->blockingEntNum = entId; } /* ------------------------- NAV_Steer ------------------------- */ int NAV_Steer( gentity_t *self, vec3_t dir, float distance ) { vec3_t right_test, left_test; vec3_t deviation; float right_ang = dir[YAW] + 45; float left_ang = dir[YAW] - 45; //Get the steering angles VectorCopy( dir, deviation ); deviation[YAW] = right_ang; AngleVectors( deviation, right_test, NULL, NULL ); deviation[YAW] = left_ang; AngleVectors( deviation, left_test, NULL, NULL ); //Find the end positions VectorMA( self->currentOrigin, distance, right_test, right_test ); VectorMA( self->currentOrigin, distance, left_test, left_test ); //Draw for debug purposes if ( NAVDEBUG_showCollision ) { CG_DrawEdge( self->currentOrigin, right_test, EDGE_PATH ); CG_DrawEdge( self->currentOrigin, left_test, EDGE_PATH ); } //Find the right influence trace_t tr; NAV_CheckAhead( self, right_test, tr, self->clipmask ); float right_push = -45 * ( 1.0f - tr.fraction ); //Find the left influence NAV_CheckAhead( self, left_test, tr, self->clipmask ); float left_push = 45 * ( 1.0f - tr.fraction ); //Influence the mover to respond to the steering VectorCopy( dir, deviation ); deviation[YAW] += ( left_push + right_push ); return deviation[YAW]; } /* ------------------------- NAV_CheckAhead ------------------------- */ #define MIN_DOOR_BLOCK_DIST 16 #define MIN_DOOR_BLOCK_DIST_SQR ( MIN_DOOR_BLOCK_DIST * MIN_DOOR_BLOCK_DIST ) qboolean NAV_CheckAhead( gentity_t *self, vec3_t end, trace_t &trace, int clipmask ) { vec3_t mins; //Offset the step height VectorSet( mins, self->mins[0], self->mins[1], self->mins[2] + STEPSIZE ); gi.trace( &trace, self->currentOrigin, mins, self->maxs, end, self->s.number, clipmask ); //Do a simple check if ( ( trace.allsolid == qfalse ) && ( trace.startsolid == qfalse ) && ( trace.fraction == 1.0f ) ) return qtrue; //See if we're too far above if ( fabs( self->currentOrigin[2] - end[2] ) > 48 ) return qfalse; //This is a work around float radius = ( self->maxs[0] > self->maxs[1] ) ? self->maxs[0] : self->maxs[1]; float dist = Distance( self->currentOrigin, end ); float tFrac = 1.0f - ( radius / dist ); if ( trace.fraction >= tFrac ) return qtrue; //Do a special check for doors if ( trace.entityNum < ENTITYNUM_WORLD ) { gentity_t *blocker = &g_entities[trace.entityNum]; if VALIDSTRING( blocker->classname ) { if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { //We're too close, try and avoid the door (most likely stuck on a lip) if ( DistanceSquared( self->currentOrigin, trace.endpos ) < MIN_DOOR_BLOCK_DIST_SQR ) return qfalse; return qtrue; } } } return qfalse; } /* ------------------------- NAV_TestBypass ------------------------- */ static qboolean NAV_TestBypass( gentity_t *self, float yaw, float blocked_dist, vec3_t movedir ) { trace_t tr; vec3_t avoidAngles; vec3_t block_test, block_pos; VectorClear( avoidAngles ); avoidAngles[YAW] = yaw; AngleVectors( avoidAngles, block_test, NULL, NULL ); VectorMA( self->currentOrigin, blocked_dist, block_test, block_pos ); if ( NAVDEBUG_showCollision ) { CG_DrawEdge( self->currentOrigin, block_pos, EDGE_BROKEN ); } //See if we're clear to move in that direction if ( NAV_CheckAhead( self, block_pos, tr, ( self->clipmask & ~CONTENTS_BODY ) ) ) { VectorCopy( block_test, movedir ); return qtrue; } return qfalse; } /* ------------------------- NAV_Bypass ------------------------- */ qboolean NAV_Bypass( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir, float blocked_dist, vec3_t movedir ) { vec3_t right; //Draw debug info if requested if ( NAVDEBUG_showCollision ) { CG_DrawEdge( self->currentOrigin, blocker->currentOrigin, EDGE_NORMAL ); } AngleVectors( self->currentAngles, NULL, right, NULL ); //Get the blocked direction float yaw = vectoyaw( blocked_dir ); //Get the avoid radius float avoidRadius = sqrt( ( blocker->maxs[0] * blocker->maxs[0] ) + ( blocker->maxs[1] * blocker->maxs[1] ) ) + sqrt( ( self->maxs[0] * self->maxs[0] ) + ( self->maxs[1] * self->maxs[1] ) ); //See if we're inside our avoidance radius float arcAngle = ( blocked_dist <= avoidRadius ) ? 135 : ( ( avoidRadius / blocked_dist ) * 90 ); //FIXME: Although the below code will cause the NPC to take the "better" route, it can cause NPCs to become stuck on // one another in certain situations where both decide to take the same direction. float dot = DotProduct( blocked_dir, right ); //Go right on the first try if that works better if ( dot < 0.0f ) arcAngle *= -1; //Test full, best position first if ( NAV_TestBypass( self, AngleMod( yaw + arcAngle ), blocked_dist, movedir ) ) return qtrue; //Try a smaller arc if ( NAV_TestBypass( self, AngleMod( yaw + ( arcAngle * 0.5f ) ), blocked_dist, movedir ) ) return qtrue; //Try the other direction if ( NAV_TestBypass( self, AngleMod( yaw + ( arcAngle * -1 ) ), blocked_dist, movedir ) ) return qtrue; //Try the other direction more precisely if ( NAV_TestBypass( self, AngleMod( yaw + ( ( arcAngle * -1 ) * 0.5f ) ), blocked_dist, movedir ) ) return qtrue; //Unable to go around return qfalse; } /* ------------------------- NAV_MoveBlocker ------------------------- */ #define SHOVE_SPEED 200 #define SHOVE_LIFT 10 qboolean NAV_MoveBlocker( gentity_t *self, vec3_t shove_dir ) { //FIXME: This is a temporary method for making blockers move //FIXME: This will, of course, push blockers off of cliffs, into walls and all over the place vec3_t temp_dir, forward; vectoangles( shove_dir, temp_dir ); temp_dir[YAW] += 45; AngleVectors( temp_dir, forward, NULL, NULL ); VectorScale( forward, SHOVE_SPEED, self->client->ps.velocity ); self->client->ps.velocity[2] += SHOVE_LIFT; //self->NPC->shoveDebounce = level.time + 100; return qtrue; } /* ------------------------- NAV_ResolveBlock ------------------------- */ qboolean NAV_ResolveBlock( gentity_t *self, gentity_t *blocker, vec3_t blocked_dir ) { //Stop double waiting if ( ( blocker->NPC ) && ( blocker->NPC->blockingEntNum == self->s.number ) ) return qtrue; //For now, just complain about it NPC_Blocked( self, blocker ); NPC_FaceEntity( blocker ); return qfalse; } /* ------------------------- NAV_TrueCollision ------------------------- */ qboolean NAV_TrueCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t blocked_dir ) { //TODO: Handle all ents if ( blocker->client == NULL ) return qfalse; vec3_t velocityDir; //Get the player's move direction and speed float speed = VectorNormalize2( self->client->ps.velocity, velocityDir ); //See if it's even feasible float dot = DotProduct( movedir, velocityDir ); if ( dot < 0.85 ) return qfalse; vec3_t testPos; vec3_t ptmins, ptmaxs, tmins, tmaxs; VectorMA( self->currentOrigin, speed*FRAMETIME, velocityDir, testPos ); VectorAdd( blocker->currentOrigin, blocker->mins, tmins ); VectorAdd( blocker->currentOrigin, blocker->maxs, tmaxs ); VectorAdd( testPos, self->mins, ptmins ); VectorAdd( testPos, self->maxs, ptmaxs ); if ( G_BoundsOverlap( ptmins, ptmaxs, tmins, tmaxs ) ) { VectorCopy( velocityDir, blocked_dir ); return qtrue; } return qfalse; } /* ------------------------- NAV_StackedCanyon ------------------------- */ qboolean NAV_StackedCanyon( gentity_t *self, gentity_t *blocker, vec3_t pathDir ) { vec3_t perp, cross, test; float avoidRadius; PerpendicularVector( perp, pathDir ); CrossProduct( pathDir, perp, cross ); avoidRadius = sqrt( ( blocker->maxs[0] * blocker->maxs[0] ) + ( blocker->maxs[1] * blocker->maxs[1] ) ) + sqrt( ( self->maxs[0] * self->maxs[0] ) + ( self->maxs[1] * self->maxs[1] ) ); VectorMA( blocker->currentOrigin, avoidRadius, cross, test ); trace_t tr; gi.trace( &tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask ); if ( NAVDEBUG_showCollision ) { vec3_t mins, maxs; vec3_t RED = { 1.0f, 0.0f, 0.0f }; VectorAdd( test, self->mins, mins ); VectorAdd( test, self->maxs, maxs ); CG_Cube( mins, maxs, RED, 0.25 ); } if ( tr.startsolid == qfalse && tr.allsolid == qfalse ) return qfalse; VectorMA( blocker->currentOrigin, -avoidRadius, cross, test ); gi.trace( &tr, test, self->mins, self->maxs, test, self->s.number, self->clipmask ); if ( tr.startsolid == qfalse && tr.allsolid == qfalse ) return qfalse; if ( NAVDEBUG_showCollision ) { vec3_t mins, maxs; vec3_t RED = { 1.0f, 0.0f, 0.0f }; VectorAdd( test, self->mins, mins ); VectorAdd( test, self->maxs, maxs ); CG_Cube( mins, maxs, RED, 0.25 ); } return qtrue; } /* ------------------------- NAV_ResolveEntityCollision ------------------------- */ qboolean NAV_ResolveEntityCollision( gentity_t *self, gentity_t *blocker, vec3_t movedir, vec3_t pathDir ) { vec3_t blocked_dir; //Doors are ignored if ( Q_stricmp( blocker->classname, "func_door" ) == 0 ) { if ( DistanceSquared( self->currentOrigin, blocker->currentOrigin ) > MIN_DOOR_BLOCK_DIST_SQR ) return qtrue; } VectorSubtract( blocker->currentOrigin, self->currentOrigin, blocked_dir ); float blocked_dist = VectorNormalize( blocked_dir ); //Make sure an actual collision is going to happen // if ( NAV_PredictCollision( self, blocker, movedir, blocked_dir ) == qfalse ) // return qtrue; //See if we can get around the blocker at all (only for player!) if ( blocker->s.number == 0 ) { if ( NAV_StackedCanyon( self, blocker, pathDir ) ) { NPC_Blocked( self, blocker ); NPC_FaceEntity( blocker, qtrue ); return qfalse; } } //First, attempt to walk around the blocker if ( NAV_Bypass( self, blocker, blocked_dir, blocked_dist, movedir ) ) return qtrue; //Second, attempt to calculate a good move position for the blocker if ( NAV_ResolveBlock( self, blocker, blocked_dir ) ) return qtrue; return qfalse; } /* ------------------------- NAV_TestForBlocked ------------------------- */ qboolean NAV_TestForBlocked( gentity_t *self, gentity_t *goal, gentity_t *blocker, float distance, int &flags ) { if ( goal == NULL ) return qfalse; if ( blocker->s.eType == ET_ITEM ) return qfalse; if ( NAV_HitNavGoal( blocker->currentOrigin, blocker->mins, blocker->maxs, goal->currentOrigin, 12 ) ) { flags |= NIF_BLOCKED; if ( distance <= MIN_STOP_DIST ) { NPC_Blocked( self, blocker ); NPC_FaceEntity( blocker ); return qtrue; } } return qfalse; } /* ------------------------- NAV_AvoidCollsion ------------------------- */ qboolean NAV_AvoidCollision( gentity_t *self, gentity_t *goal, navInfo_t &info ) { vec3_t movedir; vec3_t movepos; //Clear our block info for this frame NAV_ClearBlockedInfo( NPC ); //Cap our distance if ( info.distance > MAX_COLL_AVOID_DIST ) { info.distance = MAX_COLL_AVOID_DIST; } //Get an end position VectorMA( self->currentOrigin, info.distance, info.direction, movepos ); VectorCopy( info.direction, movedir ); //Now test against entities if ( NAV_CheckAhead( self, movepos, info.trace, CONTENTS_BODY ) == qfalse ) { //Get the blocker info.blocker = &g_entities[ info.trace.entityNum ]; info.flags |= NIF_COLLISION; //Ok to hit our goal entity if ( goal == info.blocker ) return qtrue; //See if we're moving along with them //if ( NAV_TrueCollision( self, info.blocker, movedir, info.direction ) == qfalse ) // return qtrue; //Test for blocking by standing on goal if ( NAV_TestForBlocked( self, goal, info.blocker, info.distance, info.flags ) == qtrue ) return qfalse; //If the above function said we're blocked, don't do the extra checks if ( info.flags & NIF_BLOCKED ) return qtrue; //See if we can get that entity to move out of our way if ( NAV_ResolveEntityCollision( self, info.blocker, movedir, info.pathDirection ) == qfalse ) return qfalse; VectorCopy( movedir, info.direction ); return qtrue; } //Our path is clear, just move there if ( NAVDEBUG_showCollision ) { CG_DrawEdge( self->currentOrigin, movepos, EDGE_PATH ); } return qtrue; } /* ------------------------- NAV_TestBestNode ------------------------- */ int NAV_TestBestNode( vec3_t position, int startID, int endID ) { int bestNode = startID; int testNode = navigator.GetBestNode( bestNode, endID ); vec3_t p1, p2, dir1, dir2; navigator.GetNodePosition( bestNode, p1 ); navigator.GetNodePosition( testNode, p2 ); /* if ( DistanceSquared( p1, p2 ) < DistanceSquared( position, p1 ) ) return testNode; */ VectorSubtract( p2, p1, dir1 ); //VectorNormalize( dir1 ); VectorSubtract( position, p1, dir2 ); //VectorNormalize( dir2 ); if ( DotProduct( dir1, dir2 ) > 0 ) { trace_t trace; if ( NAV_CheckAhead( NPC, p2, trace, (NPC->clipmask&~CONTENTS_BODY) ) ) bestNode = testNode; } return bestNode; } /* ------------------------- NAV_GetNearestNode ------------------------- */ int NAV_GetNearestNode( gentity_t *self, int lastNode ) { return navigator.GetNearestNode( self, lastNode, NF_CLEAR_PATH );; } /* ------------------------- NAV_MicroError ------------------------- */ qboolean NAV_MicroError( vec3_t start, vec3_t end ) { if ( VectorCompare( start, end ) ) { if ( DistanceSquared( NPC->currentOrigin, start ) < (8*8) ) { return qtrue; } } return qfalse; } /* ------------------------- NAV_MoveToGoal ------------------------- */ int NAV_MoveToGoal( gentity_t *self, navInfo_t &info ) { //Must have a goal entity to move there if( self->NPC->goalEntity == NULL ) return WAYPOINT_NONE; //Check special player optimizations if ( self->NPC->goalEntity->s.number == 0 ) { //If we couldn't find the point, then we won't be able to this turn if ( self->NPC->goalEntity->waypoint == WAYPOINT_NONE ) return WAYPOINT_NONE; //NOTENOTE: Otherwise trust this waypoint for the whole frame (reduce all unnecessary calculations) } else { //Find the target's waypoint if ( ( self->NPC->goalEntity->waypoint = NAV_GetNearestNode( self->NPC->goalEntity, self->NPC->goalEntity->waypoint ) ) == WAYPOINT_NONE ) return WAYPOINT_NONE; } //Find our waypoint if ( ( self->waypoint = NAV_GetNearestNode( self, self->lastWaypoint ) ) == WAYPOINT_NONE ) return WAYPOINT_NONE; int bestNode = navigator.GetBestNode( self->waypoint, self->NPC->goalEntity->waypoint ); if ( bestNode == WAYPOINT_NONE ) { if ( NAVDEBUG_showEnemyPath ) { vec3_t origin, torigin; navigator.GetNodePosition( self->NPC->goalEntity->waypoint, torigin ); navigator.GetNodePosition( self->waypoint, origin ); CG_DrawNode( torigin, NODE_GOAL ); CG_DrawNode( origin, NODE_GOAL ); CG_DrawNode( self->NPC->goalEntity->currentOrigin, NODE_START ); } return WAYPOINT_NONE; } //Check this node bestNode = NAV_TestBestNode( self->currentOrigin, bestNode, self->NPC->goalEntity->waypoint ); vec3_t origin, end; //trace_t trace; //Get this position navigator.GetNodePosition( bestNode, origin ); navigator.GetNodePosition( self->waypoint, end ); //Basically, see if the path we have isn't helping //if ( NAV_MicroError( origin, end ) ) // return WAYPOINT_NONE; //Test the path connection from our current position to the best node if ( NAV_CheckAhead( self, origin, info.trace, (self->clipmask&~CONTENTS_BODY) ) == qfalse ) { //First attempt to move to the closest point on the line between the waypoints G_FindClosestPointOnLineSegment( origin, end, self->currentOrigin, origin ); //See if we can go there if ( NAV_CheckAhead( self, origin, info.trace, (self->clipmask&~CONTENTS_BODY) ) == qfalse ) { //Just move towards our current waypoint bestNode = self->waypoint; navigator.GetNodePosition( bestNode, origin ); } } //Setup our new move information VectorSubtract( origin, self->currentOrigin, info.direction ); info.distance = VectorNormalize( info.direction ); VectorSubtract( end, origin, info.pathDirection ); VectorNormalize( info.pathDirection ); //Draw any debug info, if requested if ( NAVDEBUG_showEnemyPath ) { vec3_t dest, start; //Get the positions navigator.GetNodePosition( self->NPC->goalEntity->waypoint, dest ); navigator.GetNodePosition( bestNode, start ); //Draw the route CG_DrawNode( start, NODE_START ); CG_DrawNode( dest, NODE_GOAL ); navigator.ShowPath( self->waypoint, self->NPC->goalEntity->waypoint ); } return bestNode; } /* ------------------------- waypoint_testDirection ------------------------- */ #define MAX_RADIUS_CHECK 1024 unsigned int waypoint_testDirection( vec3_t origin, float yaw ) { vec3_t trace_dir, test_pos; vec3_t maxs, mins; trace_t tr; //Setup the mins and max VectorSet( maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2 ); VectorSet( mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2 - STEPSIZE ); //Get our test direction vec3_t angles = { 0, yaw, 0 }; AngleVectors( angles, trace_dir, NULL, NULL ); //Move ahead VectorMA( origin, MAX_RADIUS_CHECK, trace_dir, test_pos ); gi.trace( &tr, origin, mins, maxs, test_pos, ENTITYNUM_WORLD, ( CONTENTS_SOLID | CONTENTS_MONSTERCLIP ) ); return (unsigned int) ( (float) MAX_RADIUS_CHECK * tr.fraction ); } /* ------------------------- waypoint_getRadius ------------------------- */ #define YAW_ITERATIONS 16 unsigned int waypoint_getRadius( gentity_t *ent ) { unsigned int minDist = (unsigned int) -1; unsigned int dist; for ( int i = 0; i < YAW_ITERATIONS; i++ ) { dist = waypoint_testDirection( ent->currentOrigin, ((360.0f/YAW_ITERATIONS) * i) ); if ( dist < minDist ) minDist = dist; } return minDist; } /*QUAKED waypoint (0.7 0.7 0) (-12 -12 -24) (12 12 32) ONEWAY a place to go. ONEWAY - this waypoint has a route TO it's target(s), but not FROM it/them radius is automatically calculated in-world. */ void SP_waypoint ( gentity_t *ent ) { if ( navCalculatePaths ) { VectorSet(ent->mins, DEFAULT_MINS_0, DEFAULT_MINS_1, DEFAULT_MINS_2); VectorSet(ent->maxs, DEFAULT_MAXS_0, DEFAULT_MAXS_1, DEFAULT_MAXS_2); ent->contents = CONTENTS_TRIGGER; ent->clipmask = MASK_DEADSOLID; gi.linkentity( ent ); ent->count = -1; ent->classname = "waypoint"; if(G_CheckInSolid (ent, qtrue)) { ent->maxs[2] = CROUCH_MAXS_2; if(G_CheckInSolid (ent, qtrue)) { gi.Printf(S_COLOR_RED"ERROR: Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0 && "Waypoint in solid!"); #ifndef FINAL_BUILD G_Error("Waypoint %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif G_FreeEntity(ent); return; } } unsigned int radius = waypoint_getRadius( ent ); ent->health = navigator.AddRawPoint( ent->currentOrigin, ent->spawnflags, radius ); return; } G_FreeEntity(ent); } /*QUAKED waypoint_small (0.7 0.7 0) (-2 -2 -24) (2 2 32) ONEWAY ONEWAY - this waypoint has a route TO it's target(s), but not FROM it/them */ void SP_waypoint_small (gentity_t *ent) { if ( navCalculatePaths ) { VectorSet(ent->mins, -2, -2, DEFAULT_MINS_2); VectorSet(ent->maxs, 2, 2, DEFAULT_MAXS_2); ent->contents = CONTENTS_TRIGGER; ent->clipmask = MASK_DEADSOLID; gi.linkentity( ent ); ent->count = -1; ent->classname = "waypoint"; if(G_CheckInSolid (ent, qtrue)) { ent->maxs[2] = CROUCH_MAXS_2; if(G_CheckInSolid (ent, qtrue)) { gi.Printf(S_COLOR_RED"ERROR: Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0); #ifndef FINAL_BUILD G_Error("Waypoint_small %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif G_FreeEntity(ent); return; } } ent->health = navigator.AddRawPoint( ent->currentOrigin, ent->spawnflags, 2 ); return; } G_FreeEntity(ent); } /*QUAKED waypoint_navgoal (0.3 1 0.3) (-12 -12 -24) (12 12 32) A waypoint for script navgoals Not included in navigation data targetname - name you would use in script when setting a navgoal (like so:) For example: if you give this waypoint a targetname of "console", make an NPC go to it in a script like so: set ("navgoal", "console"); radius - how far from the navgoal an ent can be before it thinks it reached it - default is "0" which means no radius check, just have to touch it */ void SP_waypoint_navgoal( gentity_t *ent ) { int radius = ( ent->radius ) ? ((int)(ent->radius)|NAVGOAL_USE_RADIUS) : 12; VectorSet( ent->mins, -12, -12, -24 ); VectorSet( ent->maxs, 12, 12, 32 ); if ( G_CheckInSolid( ent, qfalse ) ) { gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); assert(0); #ifndef FINAL_BUILD G_Error("Waypoint_navgoal %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif } TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, radius, RTF_NAVGOAL ); ent->classname = "navgoal"; //G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_8 (0.3 1 0.3) (-8 -8 -24) (8 8 32) A waypoint for script navgoals, 8 x 8 size Not included in navigation data targetname - name you would use in script when setting a navgoal (like so:) For example: if you give this waypoint a targetname of "console", make an NPC go to it in a script like so: set ("navgoal", "console"); You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ void SP_waypoint_navgoal_8( gentity_t *ent ) { VectorSet( ent->mins, -8, -8, -24 ); VectorSet( ent->maxs, 8, 8, 32 ); if ( G_CheckInSolid( ent, qfalse ) ) { gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_8 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD G_Error("Waypoint_navgoal_8 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif assert(0); } TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 8, RTF_NAVGOAL ); ent->classname = "navgoal"; //G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_4 (0.3 1 0.3) (-4 -4 -24) (4 4 32) A waypoint for script navgoals, 4 x 4 size Not included in navigation data targetname - name you would use in script when setting a navgoal (like so:) For example: if you give this waypoint a targetname of "console", make an NPC go to it in a script like so: set ("navgoal", "console"); You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ void SP_waypoint_navgoal_4( gentity_t *ent ) { VectorSet( ent->mins, -4, -4, -24 ); VectorSet( ent->maxs, 4, 4, 32 ); if ( G_CheckInSolid( ent, qfalse ) ) { gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_4 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD G_Error("Waypoint_navgoal_4 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif assert(0); } TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 4, RTF_NAVGOAL ); ent->classname = "navgoal"; //G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_2 (0.3 1 0.3) (-2 -2 -24) (2 2 32) A waypoint for script navgoals, 2 x 2 size Not included in navigation data targetname - name you would use in script when setting a navgoal (like so:) For example: if you give this waypoint a targetname of "console", make an NPC go to it in a script like so: set ("navgoal", "console"); You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ void SP_waypoint_navgoal_2( gentity_t *ent ) { VectorSet( ent->mins, -2, -2, -24 ); VectorSet( ent->maxs, 2, 2, 32 ); if ( G_CheckInSolid( ent, qfalse ) ) { gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_2 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD G_Error("Waypoint_navgoal_2 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif assert(0); } TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 2, RTF_NAVGOAL ); ent->classname = "navgoal"; //G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /*QUAKED waypoint_navgoal_1 (0.3 1 0.3) (-1 -1 -24) (1 1 32) A waypoint for script navgoals, 1 x 1 size Not included in navigation data targetname - name you would use in script when setting a navgoal (like so:) For example: if you give this waypoint a targetname of "console", make an NPC go to it in a script like so: set ("navgoal", "console"); You CANNOT set a radius on these navgoals, they are touch-reach ONLY */ void SP_waypoint_navgoal_1( gentity_t *ent ) { VectorSet( ent->mins, -1, -1, -24 ); VectorSet( ent->maxs, 1, 1, 32 ); if ( G_CheckInSolid( ent, qfalse ) ) { gi.Printf(S_COLOR_RED"ERROR: Waypoint_navgoal_1 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #ifndef FINAL_BUILD G_Error("Waypoint_navgoal_1 %s at %s in solid!\n", ent->targetname, vtos(ent->currentOrigin)); #endif assert(0); } TAG_Add( ent->targetname, NULL, ent->s.origin, ent->s.angles, 1, RTF_NAVGOAL ); ent->classname = "navgoal"; //G_FreeEntity( ent );//can't do this, they need to be found later by some functions, though those could be fixed, maybe? } /* ------------------------- Svcmd_Nav_f ------------------------- */ void Svcmd_Nav_f( void ) { char *cmd = gi.argv( 1 ); if ( Q_stricmp( cmd, "show" ) == 0 ) { cmd = gi.argv( 2 ); if ( Q_stricmp( cmd, "all" ) == 0 ) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; //NOTENOTE: This causes the two states to sync up if they aren't already NAVDEBUG_showCollision = NAVDEBUG_showNavGoals = NAVDEBUG_showCombatPoints = NAVDEBUG_showEnemyPath = NAVDEBUG_showEdges = NAVDEBUG_showNodes; } else if ( Q_stricmp( cmd, "nodes" ) == 0 ) { NAVDEBUG_showNodes = !NAVDEBUG_showNodes; } else if ( Q_stricmp( cmd, "edges" ) == 0 ) { NAVDEBUG_showEdges = !NAVDEBUG_showEdges; } else if ( Q_stricmp( cmd, "testpath" ) == 0 ) { NAVDEBUG_showTestPath = !NAVDEBUG_showTestPath; } else if ( Q_stricmp( cmd, "enemypath" ) == 0 ) { NAVDEBUG_showEnemyPath = !NAVDEBUG_showEnemyPath; } else if ( Q_stricmp( cmd, "combatpoints" ) == 0 ) { NAVDEBUG_showCombatPoints = !NAVDEBUG_showCombatPoints; } else if ( Q_stricmp( cmd, "navgoals" ) == 0 ) { NAVDEBUG_showNavGoals = !NAVDEBUG_showNavGoals; } else if ( Q_stricmp( cmd, "collision" ) == 0 ) { NAVDEBUG_showCollision = !NAVDEBUG_showCollision; } } else if ( Q_stricmp( cmd, "set" ) == 0 ) { cmd = gi.argv( 2 ); if ( Q_stricmp( cmd, "testgoal" ) == 0 ) { NAVDEBUG_curGoal = navigator.GetNearestNode( &g_entities[0], g_entities[0].waypoint, NF_CLEAR_PATH ); } } else if ( Q_stricmp( cmd, "totals" ) == 0 ) { Com_Printf("Navigation Totals:\n"); Com_Printf("------------------\n"); Com_Printf("Total Nodes: %d\n", navigator.GetNumNodes() ); Com_Printf("Total Combat Points: %d\n", level.numCombatPoints ); } else { //Print the available commands Com_Printf("nav - valid commands\n---\n" ); Com_Printf("show\n - nodes\n - edges\n - testpath\n - enemypath\n - combatpoints\n - navgoals\n---\n"); Com_Printf("set\n - testgoal\n---\n" ); } } // //JWEIER ADDITIONS START bool navCalculatePaths = false; bool NAVDEBUG_showNodes = false; bool NAVDEBUG_showEdges = false; bool NAVDEBUG_showTestPath = false; bool NAVDEBUG_showEnemyPath = false; bool NAVDEBUG_showCombatPoints = false; bool NAVDEBUG_showNavGoals = false; bool NAVDEBUG_showCollision = false; int NAVDEBUG_curGoal = 0; /* ------------------------- NAV_CalculatePaths ------------------------- */ void NAV_CalculatePaths( const char *filename, int checksum ) { gentity_t *ent = NULL; #if _HARD_CONNECT gentity_t *target = NULL; //Find all connections and hard connect them ent = NULL; while( ( ent = G_Find( ent, FOFS( classname ), "waypoint" ) ) != NULL ) { //Find the first connection target = G_Find( NULL, FOFS( targetname ), ent->target ); if ( target != NULL ) { navigator.HardConnect( ent->health, target->health, (ent->spawnflags&1) ); } //Find a possible second connection target = G_Find( NULL, FOFS( targetname ), ent->target2 ); if ( target != NULL ) { navigator.HardConnect( ent->health, target->health, (ent->spawnflags&1) ); } //Find a possible third connection target = G_Find( NULL, FOFS( targetname ), ent->target3 ); if ( target != NULL ) { navigator.HardConnect( ent->health, target->health, (ent->spawnflags&1) ); } //Find a possible fourth connection target = G_Find( NULL, FOFS( targetname ), ent->target4 ); if ( target != NULL ) { navigator.HardConnect( ent->health, target->health, (ent->spawnflags&1) ); } } #endif //Remove all waypoints now that they're done ent = NULL; while( ( ent = G_Find( ent, FOFS( classname ), "waypoint" ) ) != NULL ) { //We don't need these to stay around G_FreeEntity( ent ); } //Calculate the paths based on the supplied waypoints //navigator.CalculatePaths(); //Save the resulting information /* if ( navigator.Save( filename, checksum ) == qfalse ) { Com_Printf("Unable to save navigations data for map \"%s\" (checksum:%d)\n", filename, checksum ); } */ } /* ------------------------- NAV_Shutdown ------------------------- */ void NAV_Shutdown( void ) { navigator.Free(); } /* ------------------------- NAV_ShowDebugInfo ------------------------- */ void NAV_ShowDebugInfo( void ) { if ( NAVDEBUG_showNodes ) { navigator.ShowNodes(); } if ( NAVDEBUG_showEdges ) { navigator.ShowEdges(); } if ( NAVDEBUG_showTestPath ) { //Get the nearest node to the player int nearestNode = navigator.GetNearestNode( &g_entities[0], g_entities[0].waypoint, NF_ANY ); int testNode = navigator.GetBestNode( nearestNode, NAVDEBUG_curGoal ); nearestNode = NAV_TestBestNode( g_entities[0].currentOrigin, nearestNode, testNode ); //Show the connection vec3_t dest, start; //Get the positions navigator.GetNodePosition( NAVDEBUG_curGoal, dest ); navigator.GetNodePosition( nearestNode, start ); CG_DrawNode( start, NODE_START ); CG_DrawNode( dest, NODE_GOAL ); navigator.ShowPath( nearestNode, NAVDEBUG_curGoal ); } if ( NAVDEBUG_showCombatPoints ) { for ( int i = 0; i < level.numCombatPoints; i++ ) { CG_DrawCombatPoint( level.combatPoints[i].origin, 0 ); } } if ( NAVDEBUG_showNavGoals ) { TAG_ShowTags( RTF_NAVGOAL ); } } /* ------------------------- NAV_FindPlayerWaypoint ------------------------- */ void NAV_FindPlayerWaypoint( void ) { g_entities[0].waypoint = navigator.GetNearestNode( &g_entities[0], g_entities[0].lastWaypoint, NF_CLEAR_PATH ); } // //JWEIER ADDITIONS END
25.942347
146
0.665273
[ "solid" ]
3e1bb1684fa82f49f54bc207c063a0aea5bc18d0
24,937
cpp
C++
src/shared/matrix.cpp
Duskhorn/libprimis
3b1189d0f8c8ea31c4752ed1ce34e9289a26b6fc
[ "Zlib" ]
null
null
null
src/shared/matrix.cpp
Duskhorn/libprimis
3b1189d0f8c8ea31c4752ed1ce34e9289a26b6fc
[ "Zlib" ]
null
null
null
src/shared/matrix.cpp
Duskhorn/libprimis
3b1189d0f8c8ea31c4752ed1ce34e9289a26b6fc
[ "Zlib" ]
null
null
null
#include "../libprimis-headers/cube.h" #include "geomexts.h" /* This file defines matrix3, matrix4, and matrix4x3's member functions. * The definitions of the classes themselves are in geom.h (one of the shared * header files) * */ //needed for det3 /* det2x2() * * returns the determinant of a 2x2 matrix, provided a set of four doubles * (rather than as a matrix2 object) */ static double det2x2(double a, double b, double c, double d) { return a*d - b*c; } //needed to invert matrix below /* det3x3() * * returns the determinant of a 3x3 matrix, provided a set of nine doubles * (rather than as a matrix3 object) */ static double det3x3(double a1, double a2, double a3, double b1, double b2, double b3, double c1, double c2, double c3) { return a1 * det2x2(b2, b3, c2, c3) - b1 * det2x2(a2, a3, c2, c3) + c1 * det2x2(a2, a3, b2, b3); } // ============================================================================= // matrix3 (3x3) object // ============================================================================= matrix3::matrix3() { } matrix3::matrix3(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) { } matrix3::matrix3(const quat &q) { float x = q.x, y = q.y, z = q.z, w = q.w, tx = 2*x, ty = 2*y, tz = 2*z, txx = tx*x, tyy = ty*y, tzz = tz*z, txy = tx*y, txz = tx*z, tyz = ty*z, twx = w*tx, twy = w*ty, twz = w*tz; a = vec(1 - (tyy + tzz), txy + twz, txz - twy); b = vec(txy - twz, 1 - (txx + tzz), tyz + twx); c = vec(txz + twy, tyz - twx, 1 - (txx + tyy)); } matrix3::matrix3(float angle, const vec &axis) { rotate(angle, axis); } void matrix3::mul(const matrix3 &m, const matrix3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.a.y).madd(m.c, n.a.z); b = vec(m.a).mul(n.b.x).madd(m.b, n.b.y).madd(m.c, n.b.z); c = vec(m.a).mul(n.c.x).madd(m.b, n.c.y).madd(m.c, n.c.z); } void matrix3::mul(const matrix3 &n) { mul(matrix3(*this), n); } void matrix3::multranspose(const matrix3 &m, const matrix3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.b.x).madd(m.c, n.c.x); b = vec(m.a).mul(n.a.y).madd(m.b, m.b.y).madd(m.c, n.c.y); c = vec(m.a).mul(n.a.z).madd(m.b, n.b.z).madd(m.c, n.c.z); } void matrix3::multranspose(const matrix3 &n) { multranspose(matrix3(*this), n); } void matrix3::transposemul(const matrix3 &m, const matrix3 &n) { a = vec(m.a.dot(n.a), m.b.dot(n.a), m.c.dot(n.a)); b = vec(m.a.dot(n.b), m.b.dot(n.b), m.c.dot(n.b)); c = vec(m.a.dot(n.c), m.b.dot(n.c), m.c.dot(n.c)); } void matrix3::transposemul(const matrix3 &n) { transposemul(matrix3(*this), n); } void matrix3::transpose() { swap(a.y, b.x); swap(a.z, c.x); swap(b.z, c.y); } void matrix3::transpose(const matrix3 &m) { a = vec(m.a.x, m.b.x, m.c.x); b = vec(m.a.y, m.b.y, m.c.y); c = vec(m.a.z, m.b.z, m.c.z); } void matrix3::invert(const matrix3 &o) { vec unscale(1/o.a.squaredlen(), 1/o.b.squaredlen(), 1/o.c.squaredlen()); transpose(o); a.mul(unscale); b.mul(unscale); c.mul(unscale); } void matrix3::invert() { invert(matrix3(*this)); } void matrix3::normalize() { a.normalize(); b.normalize(); c.normalize(); } void matrix3::scale(float k) { a.mul(k); b.mul(k); c.mul(k); } void matrix3::rotate(float angle, const vec &axis) { rotate(cosf(angle), std::sin(angle), axis); } void matrix3::rotate(float ck, float sk, const vec &axis) { a = vec(axis.x*axis.x*(1-ck)+ck, axis.x*axis.y*(1-ck)+axis.z*sk, axis.x*axis.z*(1-ck)-axis.y*sk); b = vec(axis.x*axis.y*(1-ck)-axis.z*sk, axis.y*axis.y*(1-ck)+ck, axis.y*axis.z*(1-ck)+axis.x*sk); c = vec(axis.x*axis.z*(1-ck)+axis.y*sk, axis.y*axis.z*(1-ck)-axis.x*sk, axis.z*axis.z*(1-ck)+ck); } void matrix3::setyaw(float ck, float sk) { a = vec(ck, sk, 0); b = vec(-sk, ck, 0); c = vec(0, 0, 1); } void matrix3::setyaw(float angle) { setyaw(cosf(angle), std::sin(angle)); } float matrix3::trace() const { return a.x + b.y + c.z; } bool matrix3::calcangleaxis(float tr, float &angle, vec &axis, float threshold) const { if(tr <= -1) { if(a.x >= b.y && a.x >= c.z) { float r = 1 + a.x - b.y - c.z; if(r <= threshold) { return false; } r = sqrtf(r); axis.x = 0.5f*r; axis.y = b.x/r; axis.z = c.x/r; } else if(b.y >= c.z) { float r = 1 + b.y - a.x - c.z; if(r <= threshold) { return false; } r = sqrtf(r); axis.y = 0.5f*r; axis.x = b.x/r; axis.z = c.y/r; } else { float r = 1 + b.y - a.x - c.z; if(r <= threshold) { return false; } r = sqrtf(r); axis.z = 0.5f*r; axis.x = c.x/r; axis.y = c.y/r; } angle = M_PI; } else if(tr >= 3) { axis = vec(0, 0, 1); angle = 0; } else { axis = vec(b.z - c.y, c.x - a.z, a.y - b.x); float r = axis.squaredlen(); if(r <= threshold) { return false; } axis.mul(1/sqrtf(r)); angle = acosf(0.5f*(tr - 1)); } return true; } bool matrix3::calcangleaxis(float &angle, vec &axis, float threshold) const { return calcangleaxis(trace(), angle, axis, threshold); } vec matrix3::transform(const vec &o) const { return vec(a).mul(o.x).madd(b, o.y).madd(c, o.z); } vec matrix3::transposedtransform(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec matrix3::abstransform(const vec &o) const { return vec(a).mul(o.x).abs().add(vec(b).mul(o.y).abs()).add(vec(c).mul(o.z).abs()); } vec matrix3::abstransposedtransform(const vec &o) const { return vec(a.absdot(o), b.absdot(o), c.absdot(o)); } void matrix3::identity() { a = vec(1, 0, 0); b = vec(0, 1, 0); c = vec(0, 0, 1); } void matrix3::rotate_around_x(float ck, float sk) { vec rb = vec(b).mul(ck).madd(c, sk), rc = vec(c).mul(ck).msub(b, sk); b = rb; c = rc; } void matrix3::rotate_around_x(float angle) { rotate_around_x(cosf(angle), std::sin(angle)); } void matrix3::rotate_around_x(const vec2 &sc) { rotate_around_x(sc.x, sc.y); } void matrix3::rotate_around_y(float ck, float sk) { vec rc = vec(c).mul(ck).madd(a, sk), ra = vec(a).mul(ck).msub(c, sk); c = rc; a = ra; } void matrix3::rotate_around_y(float angle) { rotate_around_y(cosf(angle), std::sin(angle)); } void matrix3::rotate_around_y(const vec2 &sc) { rotate_around_y(sc.x, sc.y); } void matrix3::rotate_around_z(float ck, float sk) { vec ra = vec(a).mul(ck).madd(b, sk), rb = vec(b).mul(ck).msub(a, sk); a = ra; b = rb; } void matrix3::rotate_around_z(float angle) { rotate_around_z(cosf(angle), std::sin(angle)); } void matrix3::rotate_around_z(const vec2 &sc) { rotate_around_z(sc.x, sc.y); } vec matrix3::transform(const vec2 &o) { return vec(a).mul(o.x).madd(b, o.y); } vec matrix3::transposedtransform(const vec2 &o) const { return vec(a.dot2(o), b.dot2(o), c.dot2(o)); } vec matrix3::rowx() const { return vec(a.x, b.x, c.x); } vec matrix3::rowy() const { return vec(a.y, b.y, c.y); } vec matrix3::rowz() const { return vec(a.z, b.z, c.z); } // ============================================================================= // matrix4 (4x4) object // ============================================================================= /* invert() * * sets the matrix values to the inverse of the provided matrix A*A^-1 = I * returns false if singular (or nearly singular to within tolerance of mindet) * or true if matrix was inverted successfully * * &m: a matrix4 object to be inverted and assigned to the object * mindet: the minimum value at which matrices are considered */ bool matrix4::invert(const matrix4 &m, double mindet) { double a1 = m.a.x, a2 = m.a.y, a3 = m.a.z, a4 = m.a.w, b1 = m.b.x, b2 = m.b.y, b3 = m.b.z, b4 = m.b.w, c1 = m.c.x, c2 = m.c.y, c3 = m.c.z, c4 = m.c.w, d1 = m.d.x, d2 = m.d.y, d3 = m.d.z, d4 = m.d.w, det1 = det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4), det2 = -det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4), det3 = det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4), det4 = -det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4), det = a1*det1 + b1*det2 + c1*det3 + d1*det4; if(std::fabs(det) < mindet) { return false; } double invdet = 1/det; a.x = det1 * invdet; a.y = det2 * invdet; a.z = det3 * invdet; a.w = det4 * invdet; b.x = -det3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4) * invdet; b.y = det3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4) * invdet; b.z = -det3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4) * invdet; b.w = det3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4) * invdet; c.x = det3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4) * invdet; c.y = -det3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4) * invdet; c.z = det3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4) * invdet; c.w = -det3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4) * invdet; d.x = -det3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3) * invdet; d.y = det3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3) * invdet; d.z = -det3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3) * invdet; d.w = det3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3) * invdet; return true; } matrix4::matrix4() { } matrix4::matrix4(const float *m) : a(m), b(m+4), c(m+8), d(m+12) { } matrix4::matrix4(const vec &a, const vec &b, const vec &c) : a(a.x, b.x, c.x, 0), b(a.y, b.y, c.y, 0), c(a.z, b.z, c.z, 0), d(0, 0, 0, 1) { } matrix4::matrix4(const vec4<float> &a, const vec4<float> &b, const vec4<float> &c, const vec4<float> &d) : a(a), b(b), c(c), d(d) { } matrix4::matrix4(const matrix4x3 &m) : a(m.a, 0), b(m.b, 0), c(m.c, 0), d(m.d, 1) { } matrix4::matrix4(const matrix3 &rot, const vec &trans) : a(rot.a, 0), b(rot.b, 0), c(rot.c, 0), d(trans, 1) { } void matrix4::clip(const plane &p, const matrix4 &m) { float x = ((p.x<0 ? -1 : (p.x>0 ? 1 : 0)) + m.c.x) / m.a.x, y = ((p.y<0 ? -1 : (p.y>0 ? 1 : 0)) + m.c.y) / m.b.y, w = (1 + m.c.z) / m.d.z, scale = 2 / (x*p.x + y*p.y - p.z + w*p.offset); a = vec4<float>(m.a.x, m.a.y, p.x*scale, m.a.w); b = vec4<float>(m.b.x, m.b.y, p.y*scale, m.b.w); c = vec4<float>(m.c.x, m.c.y, p.z*scale + 1.0f, m.c.w); d = vec4<float>(m.d.x, m.d.y, p.offset*scale, m.d.w); } void matrix4::transposedtransform(const plane &in, plane &out) const { out.x = in.dist(a); out.y = in.dist(b); out.z = in.dist(c); out.offset = in.dist(d); } void matrix4::mul(const matrix4 &x, const matrix3 &y) { a = vec4<float>(x.a).mul(y.a.x).madd(x.b, y.a.y).madd(x.c, y.a.z); b = vec4<float>(x.a).mul(y.b.x).madd(x.b, y.b.y).madd(x.c, y.b.z); c = vec4<float>(x.a).mul(y.c.x).madd(x.b, y.c.y).madd(x.c, y.c.z); d = x.d; } void matrix4::mul(const matrix3 &y) { mul(matrix4(*this), y); } void matrix4::mul(const matrix4 &x, const matrix4 &y) { mult<vec4<float>>(x, y); } void matrix4::mul(const matrix4 &y) { mult<vec4<float>>(matrix4(*this), y); } void matrix4::muld(const matrix4 &x, const matrix4 &y) { mult<vec4<float>>(x, y); } void matrix4::muld(const matrix4 &y) { mult<vec4<float>>(matrix4(*this), y); } void matrix4::rotate_around_x(float ck, float sk) { vec4<float> rb = vec4<float>(b).mul(ck).madd(c, sk), rc = vec4<float>(c).mul(ck).msub(b, sk); b = rb; c = rc; } void matrix4::rotate_around_x(float angle) { rotate_around_x(cosf(angle), std::sin(angle)); } void matrix4::rotate_around_x(const vec2 &sc) { rotate_around_x(sc.x, sc.y); } void matrix4::rotate_around_y(float ck, float sk) { vec4<float> rc = vec4<float>(c).mul(ck).madd(a, sk), ra = vec4<float>(a).mul(ck).msub(c, sk); c = rc; a = ra; } void matrix4::rotate_around_y(float angle) { rotate_around_y(cosf(angle), std::sin(angle)); } void matrix4::rotate_around_y(const vec2 &sc) { rotate_around_y(sc.x, sc.y); } void matrix4::rotate_around_z(float ck, float sk) { vec4<float> ra = vec4<float>(a).mul(ck).madd(b, sk), rb = vec4<float>(b).mul(ck).msub(a, sk); a = ra; b = rb; } void matrix4::rotate_around_z(float angle) { rotate_around_z(cosf(angle), std::sin(angle)); } void matrix4::rotate_around_z(const vec2 &sc) { rotate_around_z(sc.x, sc.y); } void matrix4::rotate(float ck, float sk, const vec &axis) { matrix3 m; m.rotate(ck, sk, axis); mul(m); } void matrix4::rotate(float angle, const vec &dir) { rotate(cosf(angle), std::sin(angle), dir); } void matrix4::rotate(const vec2 &sc, const vec &dir) { rotate(sc.x, sc.y, dir); } void matrix4::identity() { a = vec4<float>(1, 0, 0, 0); b = vec4<float>(0, 1, 0, 0); c = vec4<float>(0, 0, 1, 0); d = vec4<float>(0, 0, 0, 1); } void matrix4::settranslation(const vec &v) { d.setxyz(v); } void matrix4::settranslation(float x, float y, float z) { d.x = x; d.y = y; d.z = z; } void matrix4::translate(const vec &p) { d.madd(a, p.x).madd(b, p.y).madd(c, p.z); } void matrix4::translate(float x, float y, float z) { translate(vec(x, y, z)); } void matrix4::translate(const vec &p, float scale) { translate(vec(p).mul(scale)); } void matrix4::setscale(float x, float y, float z) { a.x = x; b.y = y; c.z = z; } void matrix4::setscale(const vec &v) { setscale(v.x, v.y, v.z); } void matrix4::setscale(float n) { setscale(n, n, n); } void matrix4::scale(float x, float y, float z) { a.mul(x); b.mul(y); c.mul(z); } void matrix4::scale(const vec &v) { scale(v.x, v.y, v.z); } void matrix4::scale(float n) { scale(n, n, n); } void matrix4::scalexy(float x, float y) { a.x *= x; a.y *= y; b.x *= x; b.y *= y; c.x *= x; c.y *= y; d.x *= x; d.y *= y; } void matrix4::scalez(float k) { a.z *= k; b.z *= k; c.z *= k; d.z *= k; } void matrix4::reflectz(float z) { d.add(vec4(c).mul(2*z)); c.neg(); } void matrix4::jitter(float x, float y) { a.x += x * a.w; a.y += y * a.w; b.x += x * b.w; b.y += y * b.w; c.x += x * c.w; c.y += y * c.w; d.x += x * d.w; d.y += y * d.w; } void matrix4::transpose() { swap(a.y, b.x); swap(a.z, c.x); swap(a.w, d.x); swap(b.z, c.y); swap(b.w, d.y); swap(c.w, d.z); } void matrix4::transpose(const matrix4 &m) { a = vec4<float>(m.a.x, m.b.x, m.c.x, m.d.x); b = vec4<float>(m.a.y, m.b.y, m.c.y, m.d.y); c = vec4<float>(m.a.z, m.b.z, m.c.z, m.d.z); d = vec4<float>(m.a.w, m.b.w, m.c.w, m.d.w); } void matrix4::frustum(float left, float right, float bottom, float top, float znear, float zfar) { float width = right - left, height = top - bottom, zrange = znear - zfar; a = vec4<float>(2*znear/width, 0, 0, 0); b = vec4<float>(0, 2*znear/height, 0, 0); c = vec4<float>((right + left)/width, (top + bottom)/height, (zfar + znear)/zrange, -1); d = vec4<float>(0, 0, 2*znear*zfar/zrange, 0); } void matrix4::perspective(float fovy, float aspect, float znear, float zfar) { float ydist = znear * std::tan(fovy/2*RAD), xdist = ydist * aspect; frustum(-xdist, xdist, -ydist, ydist, znear, zfar); } void matrix4::ortho(float left, float right, float bottom, float top, float znear, float zfar) { float width = right - left, height = top - bottom, zrange = znear - zfar; a = vec4<float>(2/width, 0, 0, 0); b = vec4<float>(0, 2/height, 0, 0); c = vec4<float>(0, 0, 2/zrange, 0); d = vec4<float>(-(right+left)/width, -(top+bottom)/height, (zfar+znear)/zrange, 1); } void matrix4::transform(const vec &in, vec &out) const { out = vec(a).mul(in.x).add(vec(b).mul(in.y)).add(vec(c).mul(in.z)).add(vec(d)); } void matrix4::transform(const vec4<float> &in, vec &out) const { out = vec(a).mul(in.x).add(vec(b).mul(in.y)).add(vec(c).mul(in.z)).add(vec(d).mul(in.w)); } void matrix4::transform(const vec &in, vec4<float> &out) const { out = vec4<float>(a).mul(in.x).madd(b, in.y).madd(c, in.z).add(d); } void matrix4::transform(const vec4<float> &in, vec4<float> &out) const { out = vec4<float>(a).mul(in.x).madd(b, in.y).madd(c, in.z).madd(d, in.w); } void matrix4::transformnormal(const vec &in, vec &out) const { out = vec(a).mul(in.x).add(vec(b).mul(in.y)).add(vec(c).mul(in.z)); } void matrix4::transformnormal(const vec &in, vec4<float> &out) const { out = vec4<float>(a).mul(in.x).madd(b, in.y).madd(c, in.z); } void matrix4::transposedtransform(const vec &in, vec &out) const { vec p = vec(in).sub(vec(d)); out.x = a.dot3(p); out.y = b.dot3(p); out.z = c.dot3(p); } void matrix4::transposedtransformnormal(const vec &in, vec &out) const { out.x = a.dot3(in); out.y = b.dot3(in); out.z = c.dot3(in); } float matrix4::getscale() const { return sqrtf(a.x*a.y + b.x*b.x + c.x*c.x); } vec matrix4::gettranslation() const { return vec(d); } vec4<float> matrix4::rowx() const { return vec4<float>(a.x, b.x, c.x, d.x); } vec4<float> matrix4::rowy() const { return vec4<float>(a.y, b.y, c.y, d.y); } vec4<float> matrix4::rowz() const { return vec4<float>(a.z, b.z, c.z, d.z); } vec4<float> matrix4::roww() const { return vec4<float>(a.w, b.w, c.w, d.w); } vec2 matrix4::lineardepthscale() const { return vec2(d.w, -d.z).div(c.z*d.w - d.z*c.w); } // ============================================================================= // matrix4x3 object // ============================================================================= matrix4x3::matrix4x3() { } matrix4x3::matrix4x3(const vec &a, const vec &b, const vec &c, const vec &d) : a(a), b(b), c(c), d(d) { } matrix4x3::matrix4x3(const matrix3 &rot, const vec &trans) : a(rot.a), b(rot.b), c(rot.c), d(trans) { } matrix4x3::matrix4x3(const dualquat &dq) { vec4<float> r = vec4<float>(dq.real).mul(1/dq.real.squaredlen()), rr = vec4<float>(r).mul(dq.real); r.mul(2); float xy = r.x*dq.real.y, xz = r.x*dq.real.z, yz = r.y*dq.real.z, wx = r.w*dq.real.x, wy = r.w*dq.real.y, wz = r.w*dq.real.z; a = vec(rr.w + rr.x - rr.y - rr.z, xy + wz, xz - wy); b = vec(xy - wz, rr.w + rr.y - rr.x - rr.z, yz + wx); c = vec(xz + wy, yz - wx, rr.w + rr.z - rr.x - rr.y); d = vec(-(dq.dual.w*r.x - dq.dual.x*r.w + dq.dual.y*r.z - dq.dual.z*r.y), -(dq.dual.w*r.y - dq.dual.x*r.z - dq.dual.y*r.w + dq.dual.z*r.x), -(dq.dual.w*r.z + dq.dual.x*r.y - dq.dual.y*r.x - dq.dual.z*r.w)); } void matrix4x3::mul(float k) { a.mul(k); b.mul(k); c.mul(k); d.mul(k); } void matrix4x3::setscale(float x, float y, float z) { a.x = x; b.y = y; c.z = z; } void matrix4x3::setscale(const vec &v) { setscale(v.x, v.y, v.z); } void matrix4x3::setscale(float n) { setscale(n, n, n); } void matrix4x3::scale(float x, float y, float z) { a.mul(x); b.mul(y); c.mul(z); } void matrix4x3::scale(const vec &v) { scale(v.x, v.y, v.z); } void matrix4x3::scale(float n) { scale(n, n, n); } void matrix4x3::settranslation(const vec &p) { d = p; } void matrix4x3::settranslation(float x, float y, float z) { d = vec(x, y, z); } void matrix4x3::translate(const vec &p) { d.madd(a, p.x).madd(b, p.y).madd(c, p.z); } void matrix4x3::translate(float x, float y, float z) { translate(vec(x, y, z)); } void matrix4x3::translate(const vec &p, float scale) { translate(vec(p).mul(scale)); } void matrix4x3::accumulate(const matrix4x3 &m, float k) { a.madd(m.a, k); b.madd(m.b, k); c.madd(m.c, k); d.madd(m.d, k); } void matrix4x3::normalize() { a.normalize(); b.normalize(); c.normalize(); } void matrix4x3::lerp(const matrix4x3 &to, float t) { a.lerp(to.a, t); b.lerp(to.b, t); c.lerp(to.c, t); d.lerp(to.d, t); } void matrix4x3::lerp(const matrix4x3 &from, const matrix4x3 &to, float t) { a.lerp(from.a, to.a, t); b.lerp(from.b, to.b, t); c.lerp(from.c, to.c, t); d.lerp(from.d, to.d, t); } void matrix4x3::identity() { a = vec(1, 0, 0); b = vec(0, 1, 0); c = vec(0, 0, 1); d = vec(0, 0, 0); } void matrix4x3::mul(const matrix4x3 &m, const matrix4x3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.a.y).madd(m.c, n.a.z); b = vec(m.a).mul(n.b.x).madd(m.b, n.b.y).madd(m.c, n.b.z); c = vec(m.a).mul(n.c.x).madd(m.b, n.c.y).madd(m.c, n.c.z); d = vec(m.d).madd(m.a, n.d.x).madd(m.b, n.d.y).madd(m.c, n.d.z); } void matrix4x3::mul(const matrix4x3 &n) { mul(matrix4x3(*this), n); } void matrix4x3::mul(const matrix3 &m, const matrix4x3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.a.y).madd(m.c, n.a.z); b = vec(m.a).mul(n.b.x).madd(m.b, n.b.y).madd(m.c, n.b.z); c = vec(m.a).mul(n.c.x).madd(m.b, n.c.y).madd(m.c, n.c.z); d = vec(m.a).mul(n.d.x).madd(m.b, n.d.y).madd(m.c, n.d.z); } void matrix4x3::mul(const matrix3 &rot, const vec &trans, const matrix4x3 &n) { mul(rot, n); d.add(trans); } void matrix4x3::transpose() { d = vec(a.dot(d), b.dot(d), c.dot(d)).neg(); swap(a.y, b.x); swap(a.z, c.x); swap(b.z, c.y); } void matrix4x3::transpose(const matrix4x3 &o) { a = vec(o.a.x, o.b.x, o.c.x); b = vec(o.a.y, o.b.y, o.c.y); c = vec(o.a.z, o.b.z, o.c.z); d = vec(o.a.dot(o.d), o.b.dot(o.d), o.c.dot(o.d)).neg(); } void matrix4x3::transposemul(const matrix4x3 &m, const matrix4x3 &n) { vec t(m.a.dot(m.d), m.b.dot(m.d), m.c.dot(m.d)); a = vec(m.a.dot(n.a), m.b.dot(n.a), m.c.dot(n.a)); b = vec(m.a.dot(n.b), m.b.dot(n.b), m.c.dot(n.b)); c = vec(m.a.dot(n.c), m.b.dot(n.c), m.c.dot(n.c)); d = vec(m.a.dot(n.d), m.b.dot(n.d), m.c.dot(n.d)).sub(t); } void matrix4x3::multranspose(const matrix4x3 &m, const matrix4x3 &n) { vec t(n.a.dot(n.d), n.b.dot(n.d), n.c.dot(n.d)); a = vec(m.a).mul(n.a.x).madd(m.b, n.b.x).madd(m.c, n.c.x); b = vec(m.a).mul(n.a.y).madd(m.b, m.b.y).madd(m.c, n.c.y); c = vec(m.a).mul(n.a.z).madd(m.b, n.b.z).madd(m.c, n.c.z); d = vec(m.d).msub(m.a, t.x).msub(m.b, t.y).msub(m.c, t.z); } void matrix4x3::invert(const matrix4x3 &o) { vec unscale(1/o.a.squaredlen(), 1/o.b.squaredlen(), 1/o.c.squaredlen()); transpose(o); a.mul(unscale); b.mul(unscale); c.mul(unscale); d.mul(unscale); } void matrix4x3::invert() { invert(matrix4x3(*this)); } void matrix4x3::rotate(float angle, const vec &d) { rotate(cosf(angle), std::sin(angle), d); } void matrix4x3::rotate(float ck, float sk, const vec &axis) { matrix3 m; m.rotate(ck, sk, axis); *this = matrix4x3(m, vec(0, 0, 0)); } void matrix4x3::rotate_around_x(float ck, float sk) { vec rb = vec(b).mul(ck).madd(c, sk), rc = vec(c).mul(ck).msub(b, sk); b = rb; c = rc; } void matrix4x3::rotate_around_x(float angle) { rotate_around_x(cosf(angle), std::sin(angle)); } void matrix4x3::rotate_around_x(const vec2 &sc) { rotate_around_x(sc.x, sc.y); } void matrix4x3::rotate_around_y(float ck, float sk) { vec rc = vec(c).mul(ck).madd(a, sk), ra = vec(a).mul(ck).msub(c, sk); c = rc; a = ra; } void matrix4x3::rotate_around_y(float angle) { rotate_around_y(cosf(angle), std::sin(angle)); } void matrix4x3::rotate_around_y(const vec2 &sc) { rotate_around_y(sc.x, sc.y); } void matrix4x3::rotate_around_z(float ck, float sk) { vec ra = vec(a).mul(ck).madd(b, sk), rb = vec(b).mul(ck).msub(a, sk); a = ra; b = rb; } void matrix4x3::rotate_around_z(float angle) { rotate_around_z(cosf(angle), std::sin(angle)); } void matrix4x3::rotate_around_z(const vec2 &sc) { rotate_around_z(sc.x, sc.y); } vec matrix4x3::transform(const vec &o) const { return vec(d).madd(a, o.x).madd(b, o.y).madd(c, o.z); } vec matrix4x3::transposedtransform(const vec &o) const { vec p = vec(o).sub(d); return vec(a.dot(p), b.dot(p), c.dot(p)); } vec matrix4x3::transformnormal(const vec &o) const { return vec(a).mul(o.x).madd(b, o.y).madd(c, o.z); } vec matrix4x3::transposedtransformnormal(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec matrix4x3::transform(const vec2 &o) const { return vec(d).madd(a, o.x).madd(b, o.y); } vec4<float> matrix4x3::rowx() const { return vec4<float>(a.x, b.x, c.x, d.x); } vec4<float> matrix4x3::rowy() const { return vec4<float>(a.y, b.y, c.y, d.y); } vec4<float> matrix4x3::rowz() const { return vec4<float>(a.z, b.z, c.z, d.z); } //end matrix4x3
22.98341
104
0.54361
[ "object", "transform" ]
3e1bf53a814ae83287d3a47e7f05300cf56f2981
9,156
cc
C++
Cassie_Example/opt_two_step/gen/opt/d1y_time_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/gen/opt/d1y_time_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/gen/opt/d1y_time_RightStance.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Thu 14 Oct 2021 09:53:49 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1,const double *var2,const double *var3,const double *var4,const double *var5,const double *var6,const double *var7) { double t596; double t780; double t887; double t904; double t924; double t977; double t979; double t1033; double t1071; double t1088; double t1113; double t1151; double t1182; double t1196; double t1253; double t1256; double t1315; double t1322; double t1356; double t1421; double t1498; double t1530; t596 = -1.*var5[1]; t780 = var5[0] + t596; t887 = Power(t780,-5); t904 = -1. + var6[0]; t924 = -1. + var7[0]; t977 = 1/t924; t979 = -1.*var1[0]; t1033 = t979 + var1[1]; t1071 = t904*t977*t1033; t1088 = t596 + var1[0] + t1071; t1113 = Power(t1088,4); t1151 = Power(t780,-4); t1182 = Power(t1088,3); t1196 = 1/t780; t1253 = -1.*t1196*t1088; t1256 = 1. + t1253; t1315 = Power(t780,-3); t1322 = Power(t1088,2); t1356 = Power(t1256,2); t1421 = Power(t780,-2); t1498 = Power(t1256,3); t1530 = Power(t1256,4); p_output1[0]=var3[6] + 5.*t1196*t1530*var4[0] + 20.*t1088*t1421*t1498*var4[10] - 5.*t1196*t1530*var4[10] + 30.*t1315*t1322*t1356*var4[20] - 20.*t1088*t1421*t1498*var4[20] + 20.*t1151*t1182*t1256*var4[30] - 30.*t1315*t1322*t1356*var4[30] - 20.*t1151*t1182*t1256*var4[40] + 5.*t1113*t887*var4[40] - 5.*t1113*t887*var4[50]; p_output1[1]=var3[7] + 5.*t1196*t1530*var4[1] + 20.*t1088*t1421*t1498*var4[11] - 5.*t1196*t1530*var4[11] + 30.*t1315*t1322*t1356*var4[21] - 20.*t1088*t1421*t1498*var4[21] + 20.*t1151*t1182*t1256*var4[31] - 30.*t1315*t1322*t1356*var4[31] - 20.*t1151*t1182*t1256*var4[41] + 5.*t1113*t887*var4[41] - 5.*t1113*t887*var4[51]; p_output1[2]=var3[8] + 5.*t1196*t1530*var4[2] + 20.*t1088*t1421*t1498*var4[12] - 5.*t1196*t1530*var4[12] + 30.*t1315*t1322*t1356*var4[22] - 20.*t1088*t1421*t1498*var4[22] + 20.*t1151*t1182*t1256*var4[32] - 30.*t1315*t1322*t1356*var4[32] - 20.*t1151*t1182*t1256*var4[42] + 5.*t1113*t887*var4[42] - 5.*t1113*t887*var4[52]; p_output1[3]=var3[9] + 5.*t1196*t1530*var4[3] + 20.*t1088*t1421*t1498*var4[13] - 5.*t1196*t1530*var4[13] + 30.*t1315*t1322*t1356*var4[23] - 20.*t1088*t1421*t1498*var4[23] + 20.*t1151*t1182*t1256*var4[33] - 30.*t1315*t1322*t1356*var4[33] - 20.*t1151*t1182*t1256*var4[43] + 5.*t1113*t887*var4[43] - 5.*t1113*t887*var4[53]; p_output1[4]=var3[12] + 5.*t1196*t1530*var4[4] + 20.*t1088*t1421*t1498*var4[14] - 5.*t1196*t1530*var4[14] + 30.*t1315*t1322*t1356*var4[24] - 20.*t1088*t1421*t1498*var4[24] + 20.*t1151*t1182*t1256*var4[34] - 30.*t1315*t1322*t1356*var4[34] - 20.*t1151*t1182*t1256*var4[44] + 5.*t1113*t887*var4[44] - 5.*t1113*t887*var4[54]; p_output1[5]=var3[13] + 5.*t1196*t1530*var4[5] + 20.*t1088*t1421*t1498*var4[15] - 5.*t1196*t1530*var4[15] + 30.*t1315*t1322*t1356*var4[25] - 20.*t1088*t1421*t1498*var4[25] + 20.*t1151*t1182*t1256*var4[35] - 30.*t1315*t1322*t1356*var4[35] - 20.*t1151*t1182*t1256*var4[45] + 5.*t1113*t887*var4[45] - 5.*t1113*t887*var4[55]; p_output1[6]=var3[14] + 5.*t1196*t1530*var4[6] + 20.*t1088*t1421*t1498*var4[16] - 5.*t1196*t1530*var4[16] + 30.*t1315*t1322*t1356*var4[26] - 20.*t1088*t1421*t1498*var4[26] + 20.*t1151*t1182*t1256*var4[36] - 30.*t1315*t1322*t1356*var4[36] - 20.*t1151*t1182*t1256*var4[46] + 5.*t1113*t887*var4[46] - 5.*t1113*t887*var4[56]; p_output1[7]=var3[15] + 5.*t1196*t1530*var4[7] + 20.*t1088*t1421*t1498*var4[17] - 5.*t1196*t1530*var4[17] + 30.*t1315*t1322*t1356*var4[27] - 20.*t1088*t1421*t1498*var4[27] + 20.*t1151*t1182*t1256*var4[37] - 30.*t1315*t1322*t1356*var4[37] - 20.*t1151*t1182*t1256*var4[47] + 5.*t1113*t887*var4[47] - 5.*t1113*t887*var4[57]; p_output1[8]=var3[16] + 5.*t1196*t1530*var4[8] + 20.*t1088*t1421*t1498*var4[18] - 5.*t1196*t1530*var4[18] + 30.*t1315*t1322*t1356*var4[28] - 20.*t1088*t1421*t1498*var4[28] + 20.*t1151*t1182*t1256*var4[38] - 30.*t1315*t1322*t1356*var4[38] - 20.*t1151*t1182*t1256*var4[48] + 5.*t1113*t887*var4[48] - 5.*t1113*t887*var4[58]; p_output1[9]=var3[19] + 5.*t1196*t1530*var4[9] + 20.*t1088*t1421*t1498*var4[19] - 5.*t1196*t1530*var4[19] + 30.*t1315*t1322*t1356*var4[29] - 20.*t1088*t1421*t1498*var4[29] + 20.*t1151*t1182*t1256*var4[39] - 30.*t1315*t1322*t1356*var4[39] - 20.*t1151*t1182*t1256*var4[49] + 5.*t1113*t887*var4[49] - 5.*t1113*t887*var4[59]; } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1,*var2,*var3,*var4,*var5,*var6,*var7; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 7) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "Seven input(s) required (var1,var2,var3,var4,var5,var6,var7)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 2 && ncols == 1) && !(mrows == 1 && ncols == 2))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } mrows = mxGetM(prhs[1]); ncols = mxGetN(prhs[1]); if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || ( !(mrows == 20 && ncols == 1) && !(mrows == 1 && ncols == 20))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var2 is wrong."); } mrows = mxGetM(prhs[2]); ncols = mxGetN(prhs[2]); if( !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || ( !(mrows == 20 && ncols == 1) && !(mrows == 1 && ncols == 20))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var3 is wrong."); } mrows = mxGetM(prhs[3]); ncols = mxGetN(prhs[3]); if( !mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || ( !(mrows == 60 && ncols == 1) && !(mrows == 1 && ncols == 60))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var4 is wrong."); } mrows = mxGetM(prhs[4]); ncols = mxGetN(prhs[4]); if( !mxIsDouble(prhs[4]) || mxIsComplex(prhs[4]) || ( !(mrows == 2 && ncols == 1) && !(mrows == 1 && ncols == 2))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var5 is wrong."); } mrows = mxGetM(prhs[5]); ncols = mxGetN(prhs[5]); if( !mxIsDouble(prhs[5]) || mxIsComplex(prhs[5]) || ( !(mrows == 1 && ncols == 1) && !(mrows == 1 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var6 is wrong."); } mrows = mxGetM(prhs[6]); ncols = mxGetN(prhs[6]); if( !mxIsDouble(prhs[6]) || mxIsComplex(prhs[6]) || ( !(mrows == 1 && ncols == 1) && !(mrows == 1 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var7 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); var2 = mxGetPr(prhs[1]); var3 = mxGetPr(prhs[2]); var4 = mxGetPr(prhs[3]); var5 = mxGetPr(prhs[4]); var6 = mxGetPr(prhs[5]); var7 = mxGetPr(prhs[6]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 10, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1,var2,var3,var4,var5,var6,var7); } #else // MATLAB_MEX_FILE #include "d1y_time_RightStance.hh" namespace RightStance { void d1y_time_RightStance_raw(double *p_output1, const double *var1,const double *var2,const double *var3,const double *var4,const double *var5,const double *var6,const double *var7) { // Call Subroutines output1(p_output1, var1, var2, var3, var4, var5, var6, var7); } } #endif // MATLAB_MEX_FILE
39.636364
323
0.643512
[ "vector" ]
3e200174874d6d3484aef2638222cdc82241c972
3,979
hpp
C++
ThirdParty-mod/java2cpp/android/bluetooth/BluetoothServerSocket.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/bluetooth/BluetoothServerSocket.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/bluetooth/BluetoothServerSocket.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.bluetooth.BluetoothServerSocket ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_BLUETOOTH_BLUETOOTHSERVERSOCKET_HPP_DECL #define J2CPP_ANDROID_BLUETOOTH_BLUETOOTHSERVERSOCKET_HPP_DECL namespace j2cpp { namespace java { namespace io { class Closeable; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace android { namespace bluetooth { class BluetoothSocket; } } } #include <android/bluetooth/BluetoothSocket.hpp> #include <java/io/Closeable.hpp> #include <java/lang/Object.hpp> namespace j2cpp { namespace android { namespace bluetooth { class BluetoothServerSocket; class BluetoothServerSocket : public object<BluetoothServerSocket> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) explicit BluetoothServerSocket(jobject jobj) : object<BluetoothServerSocket>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<java::io::Closeable>() const; local_ref< android::bluetooth::BluetoothSocket > accept(); local_ref< android::bluetooth::BluetoothSocket > accept(jint); void close(); }; //class BluetoothServerSocket } //namespace bluetooth } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_BLUETOOTH_BLUETOOTHSERVERSOCKET_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_BLUETOOTH_BLUETOOTHSERVERSOCKET_HPP_IMPL #define J2CPP_ANDROID_BLUETOOTH_BLUETOOTHSERVERSOCKET_HPP_IMPL namespace j2cpp { android::bluetooth::BluetoothServerSocket::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::bluetooth::BluetoothServerSocket::operator local_ref<java::io::Closeable>() const { return local_ref<java::io::Closeable>(get_jobject()); } local_ref< android::bluetooth::BluetoothSocket > android::bluetooth::BluetoothServerSocket::accept() { return call_method< android::bluetooth::BluetoothServerSocket::J2CPP_CLASS_NAME, android::bluetooth::BluetoothServerSocket::J2CPP_METHOD_NAME(1), android::bluetooth::BluetoothServerSocket::J2CPP_METHOD_SIGNATURE(1), local_ref< android::bluetooth::BluetoothSocket > >(get_jobject()); } local_ref< android::bluetooth::BluetoothSocket > android::bluetooth::BluetoothServerSocket::accept(jint a0) { return call_method< android::bluetooth::BluetoothServerSocket::J2CPP_CLASS_NAME, android::bluetooth::BluetoothServerSocket::J2CPP_METHOD_NAME(2), android::bluetooth::BluetoothServerSocket::J2CPP_METHOD_SIGNATURE(2), local_ref< android::bluetooth::BluetoothSocket > >(get_jobject(), a0); } void android::bluetooth::BluetoothServerSocket::close() { return call_method< android::bluetooth::BluetoothServerSocket::J2CPP_CLASS_NAME, android::bluetooth::BluetoothServerSocket::J2CPP_METHOD_NAME(3), android::bluetooth::BluetoothServerSocket::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject()); } J2CPP_DEFINE_CLASS(android::bluetooth::BluetoothServerSocket,"android/bluetooth/BluetoothServerSocket") J2CPP_DEFINE_METHOD(android::bluetooth::BluetoothServerSocket,0,"<init>","()V") J2CPP_DEFINE_METHOD(android::bluetooth::BluetoothServerSocket,1,"accept","()Landroid/bluetooth/BluetoothSocket;") J2CPP_DEFINE_METHOD(android::bluetooth::BluetoothServerSocket,2,"accept","(I)Landroid/bluetooth/BluetoothSocket;") J2CPP_DEFINE_METHOD(android::bluetooth::BluetoothServerSocket,3,"close","()V") } //namespace j2cpp #endif //J2CPP_ANDROID_BLUETOOTH_BLUETOOTHSERVERSOCKET_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
32.08871
115
0.739633
[ "object" ]
4a3bafbb31e3e8656326fe45484a08eebf839dc1
1,989
hpp
C++
include/expressions/data/number.hpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
2
2021-01-14T11:19:02.000Z
2021-03-07T03:08:08.000Z
include/expressions/data/number.hpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
null
null
null
include/expressions/data/number.hpp
rationalis-petra/hydra
a1c14e560f5f1c64983468e5fd0be7b32824971d
[ "MIT" ]
null
null
null
#ifndef __MODULUS_EXPRESSIONS_DATA_NUMBER_HPP #define __MODULUS_EXPRESSIONS_DATA_NUMBER_HPP #include <string> #include <istream> #include <list> #include <vector> #include <gmp.h> #include "expressions/object.hpp" #include "expressions/parent.hpp" namespace expr { enum NumberType {hinteger, hfloat, hcomplex}; struct Number : public Object { static Parent* parent; NumberType numtype; virtual Number* add(Number* other) = 0; virtual Number* minus(Number* other) = 0; virtual Number* multiply(Number* other) = 0; virtual Number* divide(Number* other) = 0; }; struct Real : public Number { static Parent* parent; virtual Number* sqrt() = 0; }; //struct Rational : public Real {}; struct Integer : public Real { static Parent* parent; Integer(); Integer(long num); ~Integer(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); virtual Number* sqrt(); virtual Number* add(Number* other); virtual Number* minus(Number* other); virtual Number* multiply(Number* other); virtual Number* divide(Number* other); virtual signed long get_sl(); virtual unsigned long get_ul(); virtual int compare(Integer* other); friend struct Float; private: mpz_t value; }; struct Float : public Real { static Parent* parent; Float(double num); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); double value; virtual Number* sqrt(); virtual Number* add(Number* other); virtual Number* minus(Number* other); virtual Number* multiply(Number* other); virtual Number* divide(Number* other); }; struct Complex : public Number { Complex(Number* num1, Number* num2); void mark_node(); std::string to_string(interp::LocalRuntime &r, interp::LexicalScope& s); static Parent* parent; Real* num1; Real* num2; virtual Number* add(Number* other); virtual Number* minus(Number* other); virtual Number* multiply(Number* other); virtual Number* divide(Number* other); }; } #endif
22.348315
74
0.712921
[ "object", "vector" ]
4a3da455b8f8b382b0d879d0c1e53f53af09af97
8,295
cpp
C++
hal/src/driver/qt/ui/renderview_qt.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
hal/src/driver/qt/ui/renderview_qt.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
hal/src/driver/qt/ui/renderview_qt.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
#include "driver.h" #if EPUI_DRIVER == EPDRIVER_QT #include "driver/qt/epqt.h" #include <QtGui/QOpenGLFramebufferObject> #include <QSGSimpleTextureNode> #include <QOpenGLDebugLogger> #include "synchronisedptr.h" #include "renderscene.h" #include "components/viewimpl.h" #include "driver/qt/epkernel_qt.h" #include "driver/qt/ui/renderview_qt.h" #include "driver/qt/util/qmlbindings_qt.h" ep::KeyCode qtKeyToEPKey(Qt::Key qk); namespace qt { class QtFboRenderer : public QQuickFramebufferObject::Renderer { public: QtFboRenderer(const QQuickFramebufferObject *item) : m_item(item) { } void render() { if (spRenderableView) spRenderableView->RenderGPU(); // Qt doesn't reset the cull mode epRenderState_SetCullMode(false, epF_CCW); if (m_item->window()) m_item->window()->resetOpenGLState(); } QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) { // TODO: Set up appropriate format QOpenGLFramebufferObjectFormat format; //format.setInternalTextureFormat(GL_RGBA8); format.setAttachment(QOpenGLFramebufferObject::Depth); return new QOpenGLFramebufferObject(size, format); } void synchronize(QQuickFramebufferObject * item) { QtRenderView *pQtRenderView = (QtRenderView*)item; if (pQtRenderView->dirty) { spRenderableView = ep::SynchronisedPtr<ep::RenderableView>(pQtRenderView->spView->getImpl<ep::ViewImpl>()->getRenderableView(), QtApplication::kernel()); pQtRenderView->dirty = false; } } const QQuickFramebufferObject *m_item; ep::SynchronisedPtr<ep::RenderableView> spRenderableView; }; ep::MouseControls GetMouseButton(Qt::MouseButton button) { // TODO: qt mouse buttons is a bit field if (button & Qt::LeftButton) return ep::MouseControls::LeftButton; if (button & Qt::MiddleButton) return ep::MouseControls::MiddleButton; if (button & Qt::RightButton) return ep::MouseControls::RightButton; if (button & Qt::ExtraButton1) return ep::MouseControls::Button4; if (button & Qt::ExtraButton2) return ep::MouseControls::Button5; return ep::MouseControls::Max; // redundant return for not yet supported buttons. } QtRenderView::QtRenderView(QQuickItem *pParent) : QQuickFramebufferObject(pParent) { QObject::connect(this, &QQuickItem::widthChanged, this, &QtRenderView::onResize); QObject::connect(this, &QQuickItem::heightChanged, this, &QtRenderView::onResize); QObject::connect(this, &QQuickItem::visibleChanged, this, &QtRenderView::onVisibleChanged); setMirrorVertically(true); } QtRenderView::~QtRenderView() { if (spView) { spView->frameReady.unsubscribe(ep::Delegate<void()>(this, &QtRenderView::onFrameReady)); spView->getImpl<ep::ViewImpl>()->setLatestFrame(nullptr); } } QQuickFramebufferObject::Renderer *QtRenderView::createRenderer() const { return new QtFboRenderer(this); } void QtRenderView::setView(const QVariant &view) { using namespace ep; ViewRef newView = component_cast<View>(Variant(view).asComponent()); if (spView != newView) { if (spView) { spView->frameReady.unsubscribe(ep::Delegate<void()>(this, &QtRenderView::onFrameReady)); spView->getImpl<ep::ViewImpl>()->setLatestFrame(nullptr); } spView = newView; if (spView) { spView->logDebug(2, "Attaching View Component '{0}' to Render Viewport", spView->getUid()); spView->frameReady.subscribe(Delegate<void()>(this, &QtRenderView::onFrameReady)); } // TEMP HAX: QtApplication::kernel()->setFocusView(spView); } } void QtRenderView::onResize() { int w = (int)width(); int h = (int)height(); if (spView && w > 0 && h > 0) spView->resize(w, h); } void QtRenderView::onVisibleChanged() { if (spView) { if (isVisible()) spView->activate(); else spView->deactivate(); } } void QtRenderView::componentComplete() { QQuickFramebufferObject::componentComplete(); // TODO: Focus should be set based on mouse click from main window - possibly handle in QML setFocus(true); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::AllButtons); } void QtRenderView::focusInEvent(QFocusEvent * event) { ep::InputEvent ev; ev.deviceType = ep::InputDevice::Keyboard; ev.deviceId = 0; ev.eventType = ep::InputEvent::EventType::Focus; ev.hasFocus = true; if (spView && spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) event->accept(); else event->ignore(); } void QtRenderView::focusOutEvent(QFocusEvent * event) { ep::InputEvent ev; ev.deviceType = ep::InputDevice::Keyboard; ev.deviceId = 0; ev.eventType = ep::InputEvent::EventType::Focus; ev.hasFocus = false; if (spView && spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) event->accept(); else event->ignore(); } void QtRenderView::keyPressEvent(QKeyEvent *pEv) { if (!pEv->isAutoRepeat()) { ep::KeyCode kc = qtKeyToEPKey((Qt::Key)pEv->key()); if (kc == ep::KeyCode::Unknown) return; ep::InputEvent ev; ev.deviceType = ep::InputDevice::Keyboard; ev.deviceId = 0; // TODO: get keyboard id ev.eventType = ep::InputEvent::EventType::Key; ev.key.key = (int)kc; ev.key.state = 1; if (!spView || !spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) pEv->ignore(); } } void QtRenderView::keyReleaseEvent(QKeyEvent *pEv) { if (!pEv->isAutoRepeat()) { ep::KeyCode kc = qtKeyToEPKey((Qt::Key)pEv->key()); if (kc == ep::KeyCode::Unknown) return; ep::InputEvent ev; ev.deviceType = ep::InputDevice::Keyboard; ev.deviceId = 0; // TODO: get keyboard id ev.eventType = ep::InputEvent::EventType::Key; ev.key.key = (int)kc; ev.key.state = 0; if (!spView || !spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) pEv->ignore(); } } void QtRenderView::mouseDoubleClickEvent(QMouseEvent *pEv) { // TODO: translate and process pEv->ignore(); } void QtRenderView::mouseMoveEvent(QMouseEvent *pEv) { auto pos = pEv->localPos(); qreal x = pos.x(); qreal y = pos.y(); ep::InputEvent ev; ev.deviceType = ep::InputDevice::Mouse; ev.deviceId = 0; // TODO: get mouse id ev.eventType = ep::InputEvent::EventType::Move; ev.move.xDelta = (float)(mouseLastX - x); ev.move.yDelta = (float)(mouseLastY - y); ev.move.xAbsolute = (float)x; ev.move.yAbsolute = (float)y; mouseLastX = x; mouseLastY = y; if (spView && spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) pEv->accept(); else pEv->ignore(); } void QtRenderView::mousePressEvent(QMouseEvent *pEv) { if ((pEv->buttons() & Qt::LeftButton) && !hasActiveFocus()) forceActiveFocus(); ep::InputEvent ev; ev.deviceType = ep::InputDevice::Mouse; ev.deviceId = 0; // TODO: get mouse id ev.eventType = ep::InputEvent::EventType::Key; ev.key.key = GetMouseButton(pEv->button()); ev.key.state = 1; if (ev.key.key != ep::MouseControls::Max && spView && spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) pEv->accept(); else pEv->ignore(); } void QtRenderView::mouseReleaseEvent(QMouseEvent *pEv) { ep::InputEvent ev; ev.deviceType = ep::InputDevice::Mouse; ev.deviceId = 0; // TODO: get mouse id ev.eventType = ep::InputEvent::EventType::Key; ev.key.key = GetMouseButton(pEv->button()); ev.key.state = 0; if (ev.key.key != ep::MouseControls::Max && spView && spView->getImpl<ep::ViewImpl>()->inputEvent(ev)) pEv->accept(); else pEv->ignore(); } void QtRenderView::touchEvent(QTouchEvent *pEv) { // TODO: translate and process pEv->ignore(); } void QtRenderView::hoverMoveEvent(QHoverEvent *pEv) { auto pos = pEv->pos(); qreal x = pos.x(); qreal y = pos.y(); auto oldPos = pEv->oldPos(); mouseLastX = oldPos.x(); mouseLastY = oldPos.y(); ep::InputEvent ev; ev.deviceType = ep::InputDevice::Mouse; ev.deviceId = 0; // TODO: get mouse id ev.eventType = ep::InputEvent::EventType::Move; ev.move.xDelta = (float)(mouseLastX - x); ev.move.yDelta = (float)(mouseLastY - y); ev.move.xAbsolute = (float)x; ev.move.yAbsolute = (float)y; if (spView) spView->getImpl<ep::ViewImpl>()->inputEvent(ev); } void QtRenderView::wheelEvent(QWheelEvent *pEv) { // TODO: translate and process pEv->ignore(); } } // namespace qt #else EPEMPTYFILE #endif // EPUI_DRIVER == EPDRIVER_QT
25.841121
159
0.681013
[ "render" ]
4a400e3a517ee6a1dd0fb5d1beee2c43d36ce070
9,179
cpp
C++
aten/src/ATen/test/scalar_tensor_test.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
1
2019-07-21T02:13:22.000Z
2019-07-21T02:13:22.000Z
aten/src/ATen/test/scalar_tensor_test.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
aten/src/ATen/test/scalar_tensor_test.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "ATen/ATen.h" #include "test_seed.h" #include <algorithm> #include <iostream> #include <numeric> using namespace at; #define TRY_CATCH_ELSE(fn, catc, els) \ { \ /* avoid mistakenly passing if els code throws exception*/ \ bool _passed = false; \ try { \ fn; \ _passed = true; \ els; \ } catch (std::exception &e) { \ REQUIRE(!_passed); \ catc; \ } \ } void require_equal_size_dim(const Tensor &lhs, const Tensor &rhs) { REQUIRE(lhs.dim() == rhs.dim()); REQUIRE(lhs.sizes().equals(rhs.sizes())); } bool should_expand(const IntList &from_size, const IntList &to_size) { if(from_size.size() > to_size.size()) { return false; } for (auto from_dim_it = from_size.rbegin(); from_dim_it != from_size.rend(); ++from_dim_it) { for (auto to_dim_it = to_size.rbegin(); to_dim_it != to_size.rend(); ++to_dim_it) { if (*from_dim_it != 1 && *from_dim_it != *to_dim_it) { return false; } } } return true; } void test(Type &T) { std::vector<std::vector<int64_t> > sizes = { {}, {0}, {1}, {1, 1}, {2}}; // single-tensor/size tests for (auto s = sizes.begin(); s != sizes.end(); ++s) { // verify that the dim, sizes, strides, etc match what was requested. auto t = ones(*s, T); REQUIRE((size_t)t.dim() == s->size()); REQUIRE((size_t)t.ndimension() == s->size()); REQUIRE(t.sizes().equals(*s)); REQUIRE(t.strides().size() == s->size()); auto numel = std::accumulate(s->begin(), s->end(), 1, std::multiplies<int64_t>()); REQUIRE(t.numel() == numel); // verify we can output std::stringstream ss; REQUIRE_NOTHROW(ss << t << std::endl); // set_ auto t2 = ones(*s, T); t2.set_(); require_equal_size_dim(t2, ones({0}, T)); // unsqueeze REQUIRE(t.unsqueeze(0).dim() == t.dim() + 1); // unsqueeze_ { auto t2 = ones(*s, T); auto r = t2.unsqueeze_(0); REQUIRE(r.dim() == t.dim() + 1); } // squeeze (with dimension argument) if (t.dim() == 0 || t.sizes()[0] == 1) { REQUIRE(t.squeeze(0).dim() == std::max<int64_t>(t.dim() - 1, 0)); } else { // In PyTorch, it is a no-op to try to squeeze a dimension that has size != 1; // in NumPy this is an error. REQUIRE(t.squeeze(0).dim() == t.dim()); } // squeeze (with no dimension argument) { std::vector<int64_t> size_without_ones; for (auto size : *s) { if (size != 1) { size_without_ones.push_back(size); } } auto result = t.squeeze(); require_equal_size_dim(result, ones(size_without_ones, T)); } { // squeeze_ (with dimension argument) auto t2 = ones(*s, T); if (t2.dim() == 0 || t2.sizes()[0] == 1) { REQUIRE(t2.squeeze_(0).dim() == std::max<int64_t>(t.dim() - 1, 0)); } else { // In PyTorch, it is a no-op to try to squeeze a dimension that has size != 1; // in NumPy this is an error. REQUIRE(t2.squeeze_(0).dim() == t.dim()); } } // squeeze_ (with no dimension argument) { auto t2 = ones(*s, T); std::vector<int64_t> size_without_ones; for (auto size : *s) { if (size != 1) { size_without_ones.push_back(size); } } auto r = t2.squeeze_(); require_equal_size_dim(t2, ones(size_without_ones, T)); } // reduce (with dimension argument and with 1 return argument) if (t.numel() != 0) { REQUIRE(t.sum(0).dim() == std::max<int64_t>(t.dim() - 1, 0)); } else { REQUIRE(t.sum(0).equal(at::zeros({}, T))); } // reduce (with dimension argument and with 2 return arguments) if (t.numel() != 0) { auto ret = t.min(0); REQUIRE(std::get<0>(ret).dim() == std::max<int64_t>(t.dim() - 1, 0)); REQUIRE(std::get<1>(ret).dim() == std::max<int64_t>(t.dim() - 1, 0)); } else { REQUIRE_THROWS(t.min(0)); } // simple indexing if (t.dim() > 0 && t.numel() != 0) { REQUIRE(t[0].dim() == std::max<int64_t>(t.dim() - 1, 0)); } else { REQUIRE_THROWS(t[0]); } // fill_ (argument to fill_ can only be a 0-dim tensor) TRY_CATCH_ELSE(t.fill_(t.sum(0)), REQUIRE(t.dim() > 1), REQUIRE(t.dim() <= 1)); } for (auto lhs_it = sizes.begin(); lhs_it != sizes.end(); ++lhs_it) { for (auto rhs_it = sizes.begin(); rhs_it != sizes.end(); ++rhs_it) { // is_same_size should only match if they are the same shape { auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); if(*lhs_it != *rhs_it) { REQUIRE(!lhs.is_same_size(rhs)); REQUIRE(!rhs.is_same_size(lhs)); } } // forced size functions (resize_, resize_as, set_) { // resize_ { auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); lhs.resize_(*rhs_it); require_equal_size_dim(lhs, rhs); } // resize_as_ { auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); lhs.resize_as_(rhs); require_equal_size_dim(lhs, rhs); } // set_ { { // with tensor auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); lhs.set_(rhs); require_equal_size_dim(lhs, rhs); } { // with storage auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); auto storage = T.storage(rhs.numel()); lhs.set_(*storage); // should not be dim 0 because an empty storage is dim 1; all other storages aren't scalars REQUIRE(lhs.dim() != 0); } { // with storage, offset, sizes, strides auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); auto storage = T.storage(rhs.numel()); lhs.set_(*storage, rhs.storage_offset(), rhs.sizes(), rhs.strides()); require_equal_size_dim(lhs, rhs); } } } // view { auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); auto rhs_size = *rhs_it; TRY_CATCH_ELSE(auto result = lhs.view(rhs_size), REQUIRE(lhs.numel() != rhs.numel()), REQUIRE(lhs.numel() == rhs.numel()); require_equal_size_dim(result, rhs);); } // take { auto lhs = ones(*lhs_it, T); auto rhs = zeros(*rhs_it, T).toType(ScalarType::Long); TRY_CATCH_ELSE(auto result = lhs.take(rhs), REQUIRE(lhs.numel() == 0); REQUIRE(rhs.numel() != 0), require_equal_size_dim(result, rhs)); } // ger { auto lhs = ones(*lhs_it, T); auto rhs = ones(*rhs_it, T); TRY_CATCH_ELSE(auto result = lhs.ger(rhs), REQUIRE((lhs.numel() == 0 || rhs.numel() == 0 || lhs.dim() != 1 || rhs.dim() != 1)), [&]() { int64_t dim0 = lhs.dim() == 0 ? 1 : lhs.size(0); int64_t dim1 = rhs.dim() == 0 ? 1 : rhs.size(0); require_equal_size_dim(result, result.type().tensor({dim0, dim1})); }();); } // expand { auto lhs = ones(*lhs_it, T); auto lhs_size = *lhs_it; auto rhs = ones(*rhs_it, T); auto rhs_size = *rhs_it; bool should_pass = should_expand(lhs_size, rhs_size); TRY_CATCH_ELSE(auto result = lhs.expand(rhs_size), REQUIRE(!should_pass), REQUIRE(should_pass); require_equal_size_dim(result, rhs);); // in-place functions (would be good if we can also do a non-broadcasting one, b/c // broadcasting functions will always end up operating on tensors of same size; // is there an example of this outside of assign_ ?) { bool should_pass_inplace = should_expand(rhs_size, lhs_size); TRY_CATCH_ELSE(lhs.add_(rhs), REQUIRE(!should_pass_inplace), REQUIRE(should_pass_inplace); require_equal_size_dim(lhs, ones(*lhs_it, T));); } } } } } TEST_CASE( "scalar tensor test CPU", "[cpu]" ) { manual_seed(123, at::Backend::CPU); test(CPU(kFloat)); } TEST_CASE( "scalar tensor test CUDA", "[cuda]" ) { manual_seed(123, at::Backend::CUDA); if (at::hasCUDA()) { test(CUDA(kFloat)); } }
32.899642
107
0.493845
[ "shape", "vector" ]
4a48ac848f87f7c8e2b04ff04a1500f18187738e
2,475
cpp
C++
rf24com_tunnel.cpp
agambier/RF24Com
d02a90b3892a7deeb971856b76364afca21b3cec
[ "MIT" ]
null
null
null
rf24com_tunnel.cpp
agambier/RF24Com
d02a90b3892a7deeb971856b76364afca21b3cec
[ "MIT" ]
null
null
null
rf24com_tunnel.cpp
agambier/RF24Com
d02a90b3892a7deeb971856b76364afca21b3cec
[ "MIT" ]
null
null
null
#include "rf24com_tunnel.h" #include "rf24com_pingpong.h" namespace RF24Com { // // Tunnel::Tunnel( RF24 &rf24, const uint8_t *txPipe, const uint8_t *rxPipe, uint8_t channel ) : m_rf24( &rf24 ), m_txPipe( txPipe ), m_rxPipe( rxPipe ), m_channel( channel ), m_timeOut( 100 ), m_isReady( false ) { } // // bool Tunnel::begin() { // Initialize radio if( !m_rf24->begin() ) return false; m_rf24->setPALevel( RF24_PA_MIN ); // power level m_rf24->setDataRate( RF24_250KBPS ); m_rf24->setChannel( m_channel ); m_rf24->setAutoAck( true ); // Auto ACK m_rf24->setRetries( 15, 15 ); // 15 retries every 4ms m_rf24->setPayloadSize( RF24COM_OBJECT_PAYLOADSIZE ); m_rf24->openWritingPipe( m_txPipe ); m_rf24->openReadingPipe( 1, m_rxPipe ); m_isReady = m_rf24->isChipConnected(); if( m_isReady ) m_rf24->startListening(); return m_isReady; } // // bool Tunnel::sendObject( const Object &obj ) const { m_rf24->stopListening(); bool result = m_rf24->write( obj.data(), obj.size() ); m_rf24->startListening(); return result; } // // bool Tunnel::getObject( Object &obj ) const { bool result = false; if( m_rf24->available() ) { result = true; m_rf24->read( obj.dataPtr(), obj.size() ); // Process some core object ? if( Object::PingPong == obj.kind() ) { // Get ping object PingPong pingPong( true ); *dynamic_cast< Object* >( &pingPong ) = obj; if( pingPong.isPing() ) { // prepare and send pong pingPong.preparePong(); sendObject( *dynamic_cast< Object* >( &pingPong ) ); // It was a core object dont give it to the user app layer result = false; } } } // Core object has been handled or no object received... return result; } // // bool Tunnel::sendAndReceive( const Object &sentObj, Object &receivedObj, Object::Kind awaitedKind ) const { // tx if( !sendObject( sentObj ) ) return false; // Wait and filter unsigned long to = millis(); bool result = false; do { if( ( result = getObject( receivedObj ) ) ) { // filter it ? if( ( Object::Dummy != awaitedKind ) && ( receivedObj.kind() != awaitedKind ) ) result = false; } } while( !result && ( ( millis() - to ) < timeOut() ) ); return result; } // // bool Tunnel::ping() const { // Send ping...and wait for pong ! uint32_t key = millis(); PingPong pingPong( true, key ); if( !sendAndReceive( pingPong, pingPong, Object::PingPong ) ) return false; return pingPong.isPong() && ( ~key == pingPong.key() ); } }
20.974576
105
0.648889
[ "object" ]
4a4dc9c98c38197f9a5200ea7977925914d5e17b
8,821
cpp
C++
src/main.cpp
octurion/shapes-compiler
d5f165f457ad876b827ac64a1b0da6f6f718bbef
[ "MIT" ]
1
2022-03-29T04:28:00.000Z
2022-03-29T04:28:00.000Z
src/main.cpp
octurion/shapes-compiler
d5f165f457ad876b827ac64a1b0da6f6f718bbef
[ "MIT" ]
null
null
null
src/main.cpp
octurion/shapes-compiler
d5f165f457ad876b827ac64a1b0da6f6f718bbef
[ "MIT" ]
null
null
null
#include "parser.tab.h" #include "lexer.yy.h" #include "cst.h" #include "syntactic_analysis.h" #include "ast.h" #include "semantic_analysis.h" #include "ir.h" #include <cerrno> #include <cstdarg> #include <cstdio> #include <cstdlib> struct Line { size_t begin; size_t end; Line(size_t begin, size_t end) : begin(begin) , end(end) {} }; static const char* kind_str(Ast::ErrorKind kind) { switch (kind) { case Ast::ErrorKind::CLASS: return "Class"; case Ast::ErrorKind::FIELD: return "Field"; case Ast::ErrorKind::POOL: return "Pool"; case Ast::ErrorKind::POOL_BOUND: return "Pool bound"; case Ast::ErrorKind::VARIABLE: return "Variable"; case Ast::ErrorKind::TYPE: return "Type"; case Ast::ErrorKind::LAYOUT: return "Layout"; case Ast::ErrorKind::METHOD: return "Method"; default: unreachable("Did you introduce an additional error type?"); } } struct SemanticErrorPrinter { const std::string& file_contents; const std::vector<Line>& lines; SemanticErrorPrinter( const std::string& file_contents, const std::vector<Line>& lines) : file_contents(file_contents) , lines(lines) { } void print_error_line(const Location& loc) const { constexpr int TAB_SIZE = 4; if (loc.first_column == 0) { return; } int spaces_to_print = 0; int carets_to_print = 0; int chars_printed = 0; const auto& line_info = lines[loc.first_line - 1]; const auto* it = &file_contents[line_info.begin]; const auto* line_end = &file_contents[line_info.end]; for (int i = 1; it != line_end; i++, it++) { int chars; if (*it == '\t') { chars = TAB_SIZE - (chars_printed % TAB_SIZE); for (int k = 0; k < chars; k++) { fputc(' ', stderr); } } else { fputc(*it, stderr); chars = 1; } if (i < loc.first_column) { spaces_to_print += chars; } else if (loc.first_column <= i && i <= loc.last_column) { carets_to_print += chars; } } fputc('\n', stderr); for (int i = 0; i < spaces_to_print; i++) { fputc(' ', stderr); } for (int i = 0; i < carets_to_print; i++) { fputc('^', stderr); } fputc('\n', stderr); } void print_error(const Location& loc, const char* fmt, ...) const #if defined(__GNUC__) || defined(__clang__) __attribute__((format(printf, 3, 4))) #endif { va_list args; va_start(args, fmt); fprintf(stderr, "|Line %d| ", loc.first_line); vfprintf(stderr, fmt, args); print_error_line(loc); fputc('\n', stderr); va_end(args); } void print_syntax_error(const Location& loc, const char* msg) const { print_error(loc, "%s\n", msg); } void operator()(const Ast::DuplicateDefinition& e) const { print_error(e.loc(), "%s '%s' is already defined.\n", kind_str(e.kind()), e.name().c_str()); print_error(e.existing_loc(), "Existing definition is here:\n"); } void operator()(const Ast::MissingDefinition& e) const { print_error(e.loc(), "%s '%s' has not been defined.\n", kind_str(e.kind()), e.name().c_str()); } void operator()(const Ast::MissingBound& e) const { print_error(e.loc(), "No bound has been defined for pool '%s'.\n", e.pool_name().c_str()); } void operator()(const Ast::LayoutMissingField& e) const { print_error(e.layout_loc(), "Missing field '%s' in layout '%s'.\n", e.field_name().c_str(), e.layout_name().c_str()); print_error(e.field_loc(), "Field is defined here:\n"); } void operator()(const Ast::LayoutNameClash& e) const { print_error(e.layout_loc(), "Layout '%s' has the same name as another class.\n", e.layout_name().c_str()); print_error(e.class_loc(), "Existing class is defined here:\n"); } void operator()(const Ast::LayoutDuplicateField& e) const { print_error(e.field_loc(), "Field '%s' in layout '%s' already exists.\n", e.field_name().c_str(), e.layout_name().c_str()); print_error(e.existing_field_loc(), "Existing field is present here:\n"); } void operator()(const Ast::NoPoolParameters& e) const { print_error(e.loc(), "No pool parameters defined for class '%s'.\n", e.name().c_str()); } void operator()(const Ast::EmptyCluster& e) const { print_error(e.loc(), "Cluster is empty.\n"); } void operator()(const Ast::NotInsideLoop& e) const { print_error(e.loc(), "Statement is not inside loop.\n"); } void operator()(const Ast::IntegerOutOfBounds& e) const { print_error(e.loc(), "Integer constant is too large.\n"); } void operator()(const Ast::DoubleOutOfBounds& e) const { print_error(e.loc(), "Floating point constant is too large.\n"); } void operator()(const Ast::IncorrectFirstPoolParameter& e) const { print_error(e.loc(), "Expected pool parameter '%s', but got '%s'.\n", e.expected().c_str(), e.got().c_str()); } void operator()(const Ast::IncorrectType& e) const { print_error(e.loc(), "Expected type '%s', but got '%s'.\n", e.expected_type().c_str(), e.got_type().c_str()); } void operator()(const Ast::IncompatibleBound& e) const { print_error(e.loc(), "Type '%s' is not compatible with bound '%s'.\n", e.type().c_str(), e.bound().c_str()); } void operator()(const Ast::IncorrectPoolsNumber& e) const { print_error(e.loc(), "Expected %zu pool parameters, but got %zu.\n", e.num_expected(), e.num_got()); } void operator()(const Ast::ExpectedObjectType& e) const { print_error(e.loc(), "Expected an object type, but got '%s'.\n", e.type_got().c_str()); } void operator()(const Ast::ExpectedPrimitiveType& e) const { print_error(e.loc(), "Expected a primitive type, but got '%s'.\n", e.type_got().c_str()); } void operator()(const Ast::ExpectedBooleanType& e) const { print_error(e.loc(), "Expected a boolean type, but got '%s'.\n", e.type_got().c_str()); } void operator()(const Ast::ExpectedIntegerType& e) const { print_error(e.loc(), "Expected an integer type, but got '%s'.\n", e.type_got().c_str()); } void operator()(const Ast::ExpectedNumericType& e) const { print_error(e.loc(), "Expected an integer or floating-point type, but got '%s'.\n", e.type_got().c_str()); } void operator()(const Ast::ReturnWithExpression& e) const { print_error(e.loc(), "Return statement must not have an expression.\n"); } void operator()(const Ast::ReturnWithoutExpression& e) const { print_error(e.loc(), "Return statement has no expression.\n"); } void operator()(const Ast::NonAssignableType& e) const { print_error(e.loc(), "Cannot assign expression of type '%s' into type '%s'.\n", e.assigned_from().c_str(), e.assigned_to().c_str()); } void operator()(const Ast::NotLvalue& e) const { print_error(e.loc(), "Expression is not an lvalue.\n"); } void operator()(const Ast::IncorrectArgsNumber& e) const { print_error(e.loc(), "Expected %zu method arguments, but got %zu.\n", e.num_expected(), e.num_got()); } void operator()(const Ast::NotAllPathsReturn& e) const { print_error(e.loc(), "Not all paths return a value in method '%s'.\n", e.name().c_str()); } void operator()(const Ast::VarMaybeUninitialized& e) const { print_error(e.loc(), "Variable '%s' may be used uninitialized here.\n", e.name().c_str()); } }; int main(int argc, char** argv) { if (argc < 2) { fprintf(stderr, "You must specify an input file\n"); return EXIT_FAILURE; } FILE* in = fopen(argv[1], "r"); if (in == NULL) { perror(argv[1]); return EXIT_FAILURE; } fseek(in, 0, SEEK_END); long fsize = ftell(in); fseek(in, 0, SEEK_SET); std::string file_contents(fsize, '\0'); fread(&file_contents[0], 1, fsize, in); fclose(in); std::vector<Line> lines; size_t pos = 0; size_t prev = 0; while ((pos = file_contents.find('\n', prev)) != std::string::npos) { lines.emplace_back(prev, pos); prev = pos + 1; } lines.emplace_back(prev, lines.size()); Cst::Program cst; Cst::SyntaxErrorList syntax_errors; yyscan_t scanner; yylex_init(&scanner); auto lex_buffer = yy_scan_bytes( file_contents.data(), file_contents.size(), scanner); yyparse(scanner, &cst, &syntax_errors); yy_delete_buffer(lex_buffer, scanner); yylex_destroy(scanner); SemanticErrorPrinter printer(file_contents, lines); if (syntax_errors.has_errors()) { for (auto it = syntax_errors.begin(); it != syntax_errors.end(); it++) { const auto& e = *it; const auto& loc = e.loc(); printer.print_syntax_error(loc, e.msg().c_str()); } return EXIT_FAILURE; } Ast::Program ast; Ast::SemanticErrorList errors; Ast::run_semantic_analysis(cst, ast, errors); if (errors.has_errors()) { SemanticErrorPrinter printer(file_contents, lines); for (const auto& e: errors.errors()) { mpark::visit(printer, e); } return EXIT_FAILURE; } Ir::init_llvm(); Ir::Codegen codegen; codegen.ir(ast); codegen.emit("shapes.ll", "shapes.o"); codegen.emit_header("shapes.h"); return EXIT_SUCCESS; }
23.213158
85
0.656388
[ "object", "vector" ]
4a5c5d85503547a9496a55d3794912dadd109b62
5,833
cpp
C++
faceid/src/v20180301/model/WeChatBillDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
faceid/src/v20180301/model/WeChatBillDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
faceid/src/v20180301/model/WeChatBillDetail.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/faceid/v20180301/model/WeChatBillDetail.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Faceid::V20180301::Model; using namespace std; WeChatBillDetail::WeChatBillDetail() : m_bizTokenHasBeenSet(false), m_chargeCountHasBeenSet(false), m_chargeDetailsHasBeenSet(false), m_ruleIdHasBeenSet(false) { } CoreInternalOutcome WeChatBillDetail::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("BizToken") && !value["BizToken"].IsNull()) { if (!value["BizToken"].IsString()) { return CoreInternalOutcome(Core::Error("response `WeChatBillDetail.BizToken` IsString=false incorrectly").SetRequestId(requestId)); } m_bizToken = string(value["BizToken"].GetString()); m_bizTokenHasBeenSet = true; } if (value.HasMember("ChargeCount") && !value["ChargeCount"].IsNull()) { if (!value["ChargeCount"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `WeChatBillDetail.ChargeCount` IsUint64=false incorrectly").SetRequestId(requestId)); } m_chargeCount = value["ChargeCount"].GetUint64(); m_chargeCountHasBeenSet = true; } if (value.HasMember("ChargeDetails") && !value["ChargeDetails"].IsNull()) { if (!value["ChargeDetails"].IsArray()) return CoreInternalOutcome(Core::Error("response `WeChatBillDetail.ChargeDetails` is not array type")); const rapidjson::Value &tmpValue = value["ChargeDetails"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { ChargeDetail item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_chargeDetails.push_back(item); } m_chargeDetailsHasBeenSet = true; } if (value.HasMember("RuleId") && !value["RuleId"].IsNull()) { if (!value["RuleId"].IsString()) { return CoreInternalOutcome(Core::Error("response `WeChatBillDetail.RuleId` IsString=false incorrectly").SetRequestId(requestId)); } m_ruleId = string(value["RuleId"].GetString()); m_ruleIdHasBeenSet = true; } return CoreInternalOutcome(true); } void WeChatBillDetail::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_bizTokenHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BizToken"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_bizToken.c_str(), allocator).Move(), allocator); } if (m_chargeCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ChargeCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_chargeCount, allocator); } if (m_chargeDetailsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ChargeDetails"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_chargeDetails.begin(); itr != m_chargeDetails.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_ruleIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_ruleId.c_str(), allocator).Move(), allocator); } } string WeChatBillDetail::GetBizToken() const { return m_bizToken; } void WeChatBillDetail::SetBizToken(const string& _bizToken) { m_bizToken = _bizToken; m_bizTokenHasBeenSet = true; } bool WeChatBillDetail::BizTokenHasBeenSet() const { return m_bizTokenHasBeenSet; } uint64_t WeChatBillDetail::GetChargeCount() const { return m_chargeCount; } void WeChatBillDetail::SetChargeCount(const uint64_t& _chargeCount) { m_chargeCount = _chargeCount; m_chargeCountHasBeenSet = true; } bool WeChatBillDetail::ChargeCountHasBeenSet() const { return m_chargeCountHasBeenSet; } vector<ChargeDetail> WeChatBillDetail::GetChargeDetails() const { return m_chargeDetails; } void WeChatBillDetail::SetChargeDetails(const vector<ChargeDetail>& _chargeDetails) { m_chargeDetails = _chargeDetails; m_chargeDetailsHasBeenSet = true; } bool WeChatBillDetail::ChargeDetailsHasBeenSet() const { return m_chargeDetailsHasBeenSet; } string WeChatBillDetail::GetRuleId() const { return m_ruleId; } void WeChatBillDetail::SetRuleId(const string& _ruleId) { m_ruleId = _ruleId; m_ruleIdHasBeenSet = true; } bool WeChatBillDetail::RuleIdHasBeenSet() const { return m_ruleIdHasBeenSet; }
29.311558
146
0.678382
[ "vector", "model" ]
4a5f5b41338770563c93d0113006a18cd99d3be2
2,685
cc
C++
ash/common/shelf/overflow_bubble.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
ash/common/shelf/overflow_bubble.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
ash/common/shelf/overflow_bubble.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 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 "ash/common/shelf/overflow_bubble.h" #include "ash/common/shelf/overflow_bubble_view.h" #include "ash/common/shelf/overflow_button.h" #include "ash/common/shelf/shelf_view.h" #include "ash/common/shelf/wm_shelf.h" #include "ash/common/system/tray/tray_background_view.h" #include "ash/common/wm_shell.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/widget/widget.h" namespace ash { OverflowBubble::OverflowBubble(WmShelf* wm_shelf) : wm_shelf_(wm_shelf), bubble_(nullptr), overflow_button_(nullptr), shelf_view_(nullptr) { WmShell::Get()->AddPointerWatcher(this, views::PointerWatcherEventTypes::BASIC); } OverflowBubble::~OverflowBubble() { Hide(); WmShell::Get()->RemovePointerWatcher(this); } void OverflowBubble::Show(OverflowButton* overflow_button, ShelfView* shelf_view) { DCHECK(overflow_button); DCHECK(shelf_view); Hide(); bubble_ = new OverflowBubbleView(wm_shelf_); bubble_->InitOverflowBubble(overflow_button, shelf_view); shelf_view_ = shelf_view; overflow_button_ = overflow_button; TrayBackgroundView::InitializeBubbleAnimations(bubble_->GetWidget()); bubble_->GetWidget()->AddObserver(this); bubble_->GetWidget()->Show(); overflow_button->OnOverflowBubbleShown(); } void OverflowBubble::Hide() { if (!IsShowing()) return; OverflowButton* overflow_button = overflow_button_; bubble_->GetWidget()->RemoveObserver(this); bubble_->GetWidget()->Close(); bubble_ = nullptr; overflow_button_ = nullptr; shelf_view_ = nullptr; overflow_button->OnOverflowBubbleHidden(); } void OverflowBubble::ProcessPressedEvent( const gfx::Point& event_location_in_screen) { if (IsShowing() && !shelf_view_->IsShowingMenu() && !bubble_->GetBoundsInScreen().Contains(event_location_in_screen) && !overflow_button_->GetBoundsInScreen().Contains( event_location_in_screen)) { Hide(); } } void OverflowBubble::OnPointerEventObserved( const ui::PointerEvent& event, const gfx::Point& location_in_screen, views::Widget* target) { if (event.type() == ui::ET_POINTER_DOWN) ProcessPressedEvent(location_in_screen); } void OverflowBubble::OnWidgetDestroying(views::Widget* widget) { DCHECK(widget == bubble_->GetWidget()); // Update the overflow button in the parent ShelfView. overflow_button_->SchedulePaint(); bubble_ = nullptr; overflow_button_ = nullptr; shelf_view_ = nullptr; } } // namespace ash
28.56383
76
0.724022
[ "geometry" ]
4a6026aae8c08580f835d47905c6caaabb6eb56d
5,899
hpp
C++
include/VisionCore/WrapGL/impl/WrapGLFramebuffer_impl.hpp
lukier/vision_core
45cb1bf7b74e1e1d5aa1078494a328b317d5a368
[ "BSD-3-Clause" ]
29
2016-10-30T23:59:11.000Z
2021-11-30T12:27:40.000Z
include/VisionCore/WrapGL/impl/WrapGLFramebuffer_impl.hpp
jczarnowski/vision_core
924c53339b1d99ebb3b1e358edfaa1a4e8d3703b
[ "BSD-3-Clause" ]
2
2020-05-19T04:45:41.000Z
2021-12-07T01:32:22.000Z
include/VisionCore/WrapGL/impl/WrapGLFramebuffer_impl.hpp
lukier/vision_core
45cb1bf7b74e1e1d5aa1078494a328b317d5a368
[ "BSD-3-Clause" ]
4
2016-11-14T00:46:26.000Z
2021-06-01T08:55:11.000Z
/** * **************************************************************************** * Copyright (c) 2017, Robert Lukierski. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * **************************************************************************** * Frame/Render buffer objects. * **************************************************************************** */ #ifndef VISIONCORE_WRAPGL_FRAME_BUFFER_IMPL_HPP #define VISIONCORE_WRAPGL_FRAME_BUFFER_IMPL_HPP inline vc::wrapgl::RenderBuffer::RenderBuffer() : rbid(0), rbw(0), rbh(0) { } inline vc::wrapgl::RenderBuffer::~RenderBuffer() { destroy(); } inline vc::wrapgl::RenderBuffer::RenderBuffer(GLint w, GLint h, GLenum internal_format) : rbid(0) { create(w,h,internal_format); } inline void vc::wrapgl::RenderBuffer::create(GLint w, GLint h, GLenum internal_format) { destroy(); rbw = w; rbh = h; glGenRenderbuffers(1, &rbid); WRAPGL_CHECK_ERROR(); bind(); glRenderbufferStorage(GL_RENDERBUFFER, internal_format, rbw, rbh); WRAPGL_CHECK_ERROR(); unbind(); } inline void vc::wrapgl::RenderBuffer::destroy() { if(rbid != 0) { glDeleteRenderbuffers(1, &rbid); WRAPGL_CHECK_ERROR(); rbid = 0; } } inline bool vc::wrapgl::RenderBuffer::isValid() const { return rbid != 0; } inline void vc::wrapgl::RenderBuffer::bind() const { glBindRenderbuffer(GL_RENDERBUFFER, rbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::RenderBuffer::unbind() const { glBindRenderbuffer(GL_RENDERBUFFER, 0); WRAPGL_CHECK_ERROR(); } template<typename T> inline void vc::wrapgl::RenderBuffer::download(Buffer2DView<T,TargetHost>& buf, GLenum data_format) { download(buf.ptr(), data_format, internal::GLTypeTraits<typename type_traits<T>::ChannelType>::opengl_data_type); } inline void vc::wrapgl::RenderBuffer::download(GLvoid* data, GLenum data_format, GLenum data_type) { glReadPixels(0,0,width(),height(),data_format,data_type,data); } inline GLuint vc::wrapgl::RenderBuffer::id() const { return rbid; } inline GLint vc::wrapgl::RenderBuffer::width() const { return rbw; } inline GLint vc::wrapgl::RenderBuffer::height() const { return rbh; } inline vc::wrapgl::FrameBuffer::FrameBuffer() : attachments(0) { glGenFramebuffers(1, &fbid); WRAPGL_CHECK_ERROR(); } inline vc::wrapgl::FrameBuffer::~FrameBuffer() { glDeleteFramebuffers(1, &fbid); WRAPGL_CHECK_ERROR(); fbid = 0; } inline GLenum vc::wrapgl::FrameBuffer::attach(Texture2D& tex) { const GLenum color_attachment = GL_COLOR_ATTACHMENT0 + attachments; glFramebufferTexture2D(GL_FRAMEBUFFER, color_attachment, GL_TEXTURE_2D, tex.id(), 0); WRAPGL_CHECK_ERROR(); attachments++; return color_attachment; } inline GLenum vc::wrapgl::FrameBuffer::attachDepth(Texture2D& tex) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, tex.id(), 0); WRAPGL_CHECK_ERROR(); return GL_DEPTH_ATTACHMENT; } inline GLenum vc::wrapgl::FrameBuffer::attachDepth(RenderBuffer& rb) { glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb.id()); WRAPGL_CHECK_ERROR(); return GL_DEPTH_ATTACHMENT; } inline bool vc::wrapgl::FrameBuffer::isValid() const { return fbid != 0; } inline void vc::wrapgl::FrameBuffer::bind() const { glBindFramebuffer(GL_FRAMEBUFFER, fbid); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::FrameBuffer::unbind() const { glBindFramebuffer(GL_FRAMEBUFFER, 0); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::FrameBuffer::drawInto() const { glDrawBuffers( attachments, attachment_buffers.data() ); WRAPGL_CHECK_ERROR(); } inline GLenum vc::wrapgl::FrameBuffer::checkComplete() { const GLenum ret = glCheckFramebufferStatus(GL_FRAMEBUFFER); WRAPGL_CHECK_ERROR(); return ret; } inline void vc::wrapgl::FrameBuffer::clearBuffer(unsigned int idx, float* val) { glClearBufferfv(GL_COLOR, idx, val); WRAPGL_CHECK_ERROR(); } inline void vc::wrapgl::FrameBuffer::clearDepthBuffer(float val) { glClearBufferfv(GL_DEPTH, 0, &val); WRAPGL_CHECK_ERROR(); } inline GLuint vc::wrapgl::FrameBuffer::id() const { return fbid; } inline unsigned int vc::wrapgl::FrameBuffer::colorAttachmentCount() const { return attachments; } #endif // VISIONCORE_WRAPGL_FRAME_BUFFER_IMPL_HPP
27.957346
117
0.698593
[ "render" ]
4a6419d7a4f6fe48ecbdda64c8c54178740e4342
15,460
cpp
C++
src/nbl/video/CPropertyPoolHandler.cpp
guard252/Nabla
a775fc91c31e57a1c347fb8df01803869e3260a2
[ "Apache-2.0" ]
216
2020-08-27T20:04:48.000Z
2022-03-28T19:31:41.000Z
src/nbl/video/CPropertyPoolHandler.cpp
guard252/Nabla
a775fc91c31e57a1c347fb8df01803869e3260a2
[ "Apache-2.0" ]
165
2020-09-17T20:12:30.000Z
2022-03-30T21:32:18.000Z
src/nbl/video/CPropertyPoolHandler.cpp
guard252/Nabla
a775fc91c31e57a1c347fb8df01803869e3260a2
[ "Apache-2.0" ]
27
2020-09-09T16:15:07.000Z
2022-03-07T22:10:16.000Z
#include "nbl/video/CPropertyPoolHandler.h" #include "nbl/video/CPropertyPool.h" using namespace nbl; using namespace video; // constexpr char* copyCsSource = R"( layout(local_size_x=_NBL_BUILTIN_PROPERTY_COPY_GROUP_SIZE_) in; layout(set=0,binding=0) readonly restrict buffer Indices { uint elementCount[_NBL_BUILTIN_PROPERTY_COUNT_]; int propertyDWORDsize_upDownFlag[_NBL_BUILTIN_PROPERTY_COUNT_]; uint indexOffset[_NBL_BUILTIN_PROPERTY_COUNT_]; uint indices[]; }; layout(set=0, binding=1) readonly restrict buffer InData { uint data[]; } inBuff[_NBL_BUILTIN_PROPERTY_COUNT_]; layout(set=0, binding=2) writeonly restrict buffer OutData { uint data[]; } outBuff[_NBL_BUILTIN_PROPERTY_COUNT_]; #if 0 // optimization uint shared workgroupShared[_NBL_BUILTIN_PROPERTY_COPY_GROUP_SIZE_]; #endif void main() { const uint propID = gl_WorkGroupID.y; const int combinedFlag = propertyDWORDsize_upDownFlag[propID]; const bool download = combinedFlag<0; const uint propDWORDs = uint(download ? (-combinedFlag):combinedFlag); #if 0 // optimization const uint localIx = gl_LocalInvocationID.x; const uint MaxItemsToProcess = ; if (localIx<MaxItemsToProcess) workgroupShared[localIx] = indices[localIx+indexOffset[propID]]; barrier(); memoryBarrier(); #endif const uint index = gl_GlobalInvocationID.x/propDWORDs; if (index>=elementCount[propID]) return; const uint redir = ( #if 0 //optimization workgroupShared[index] #else indices[index+indexOffset[propID]] #endif // its equivalent to `indices[index]*propDWORDs+gl_GlobalInvocationID.x%propDWORDs` -index)*propDWORDs+gl_GlobalInvocationID.x; const uint inIndex = download ? redir:gl_GlobalInvocationID.x; const uint outIndex = download ? gl_GlobalInvocationID.x:redir; outBuff[propID].data[outIndex] = inBuff[propID].data[inIndex]; } )"; // CPropertyPoolHandler::CPropertyPoolHandler(IVideoDriver* driver, IGPUPipelineCache* pipelineCache) : m_driver(driver) { assert(m_driver); const auto maxSSBO = core::min(m_driver->getMaxSSBOBindings(),16u); // TODO: make sure not dynamic offset, support proper queries per stage! const uint32_t maxPropertiesPerPass = (maxSSBO-1u)/2u; m_perPropertyCountItems.reserve(maxPropertiesPerPass); m_tmpIndexRanges.reserve(maxPropertiesPerPass); const auto maxSteamingAllocations = maxPropertiesPerPass+1u; m_tmpAddresses.resize(maxSteamingAllocations); m_tmpSizes.resize(maxSteamingAllocations); m_alignments.resize(maxSteamingAllocations,alignof(uint32_t)); for (uint32_t i=0u; i<maxPropertiesPerPass; i++) { const auto propCount = i+1u; m_perPropertyCountItems.emplace_back(m_driver,pipelineCache,propCount); } } // CPropertyPoolHandler::transfer_result_t CPropertyPoolHandler::addProperties(const AllocationRequest* requestsBegin, const AllocationRequest* requestsEnd, const std::chrono::steady_clock::time_point& maxWaitPoint) { bool success = true; uint32_t transferCount = 0u; for (auto it=requestsBegin; it!=requestsEnd; it++) { success = it->pool->allocateProperties(it->outIndices.begin(),it->outIndices.end()) && success; transferCount += it->pool->getPropertyCount(); } if (!success) return {false,nullptr}; core::vector<TransferRequest> transferRequests(transferCount); auto oit = transferRequests.begin(); for (auto it=requestsBegin; it!=requestsEnd; it++) for (auto i=0u; i<it->pool->getPropertyCount(); i++) { oit->download = false; oit->pool = it->pool; oit->indices = { it->outIndices.begin(),it->outIndices.end() }; oit->propertyID = i; oit->readData = it->data[i]; oit++; } return transferProperties(transferRequests.data(),transferRequests.data()+transferCount,maxWaitPoint); } // CPropertyPoolHandler::transfer_result_t CPropertyPoolHandler::transferProperties(const TransferRequest* requestsBegin, const TransferRequest* requestsEnd, const std::chrono::steady_clock::time_point& maxWaitPoint) { const auto totalProps = std::distance(requestsBegin,requestsEnd); transfer_result_t retval = { true,nullptr }; if (totalProps!=0u) { const uint32_t maxPropertiesPerPass = m_perPropertyCountItems.size(); const auto fullPasses = totalProps/maxPropertiesPerPass; auto upBuff = m_driver->getDefaultUpStreamingBuffer(); auto downBuff = m_driver->getDefaultDownStreamingBuffer(); constexpr auto invalid_address = std::remove_reference_t<decltype(upBuff->getAllocator())>::invalid_address; uint8_t* upBuffPtr = reinterpret_cast<uint8_t*>(upBuff->getBufferPointer()); auto copyPass = [&](const TransferRequest* localRequests, uint32_t propertiesThisPass) -> void { const uint32_t headerSize = sizeof(uint32_t)*3u*propertiesThisPass; uint32_t upAllocations = 1u; uint32_t downAllocations = 0u; for (uint32_t i=0u; i<propertiesThisPass; i++) { if (localRequests[i].download) downAllocations++; else upAllocations++; } uint32_t* const upSizes = m_tmpSizes.data()+1u; uint32_t* const downAddresses = m_tmpAddresses.data()+upAllocations; uint32_t* const downSizes = m_tmpSizes.data()+upAllocations; // figure out the sizes to allocate uint32_t maxElements = 0u; auto RangeComparator = [](auto lhs, auto rhs)->bool{return lhs.source.begin()<rhs.source.begin();}; { m_tmpSizes[0u] = 3u*propertiesThisPass; uint32_t* upSizesIt = upSizes; uint32_t* downSizesIt = downSizes; m_tmpIndexRanges.resize(propertiesThisPass); for (uint32_t i=0; i<propertiesThisPass; i++) { const auto& request = localRequests[i]; const auto propSize = request.pool->getPropertySize(request.propertyID); const auto elementsByteSize = request.indices.size()*propSize; if (request.download) *(downSizesIt++) = elementsByteSize; else *(upSizesIt++) = elementsByteSize; m_tmpIndexRanges[i].source = request.indices; m_tmpIndexRanges[i].destOff = 0u; } // find slabs (reduce index duplication) std::sort(m_tmpIndexRanges.begin(),m_tmpIndexRanges.end(),RangeComparator); uint32_t indexOffset = 0u; auto oit = m_tmpIndexRanges.begin(); for (auto it=m_tmpIndexRanges.begin()+1u; it!=m_tmpIndexRanges.end(); it++) { const auto& inRange = it->source; maxElements = core::max<uint32_t>(inRange.size(),maxElements); // check for discontinuity auto& outRange = oit->source; if (inRange.begin()>outRange.end()) { indexOffset += outRange.size(); // begin a new slab oit++; *oit = *it; oit->destOff = indexOffset; } else reinterpret_cast<const uint32_t**>(&outRange)[1] = inRange.end(); } // note the size of the last slab indexOffset += oit->source.size(); m_tmpIndexRanges.resize(std::distance(m_tmpIndexRanges.begin(),++oit)); m_tmpSizes[0u] += indexOffset; m_tmpSizes[0u] *= sizeof(uint32_t); } // allocate indices and upload/allocate data { std::fill(m_tmpAddresses.begin(),m_tmpAddresses.begin()+propertiesThisPass+1u,invalid_address); upBuff->multi_alloc(maxWaitPoint,upAllocations,m_tmpAddresses.data(),m_tmpSizes.data(),m_alignments.data()); uint8_t* indexBufferPtr = upBuffPtr+m_tmpAddresses[0u]/sizeof(uint32_t); // write `elementCount` for (uint32_t i=0; i<propertiesThisPass; i++) *(indexBufferPtr++) = localRequests[i].indices.size(); // write `propertyDWORDsize_upDownFlag` for (uint32_t i=0; i<propertiesThisPass; i++) { const auto& request = localRequests[i]; int32_t propSize = request.pool->getPropertySize(request.propertyID); propSize /= sizeof(uint32_t); if (request.download) propSize = -propSize; *reinterpret_cast<int32_t*>(indexBufferPtr++) = propSize; } // write `indexOffset` for (uint32_t i=0; i<propertiesThisPass; i++) { const auto& originalRange = localRequests->indices; // find the slab IndexUploadRange dummy; dummy.source = originalRange; dummy.destOff = 0xdeadbeefu; auto aboveOrEqual = std::lower_bound(m_tmpIndexRanges.begin(),m_tmpIndexRanges.end(),dummy,RangeComparator); auto containing = aboveOrEqual->source.begin()!=originalRange.begin() ? (aboveOrEqual-1):aboveOrEqual; // assert(containing->source.begin()<=originalRange.begin() && originalRange.end()<=containing->source.end()); *(indexBufferPtr++) = containing->destOff+(originalRange.begin()-containing->source.begin()); } // write the indices for (auto slab : m_tmpIndexRanges) { const auto indexCount = slab.source.size(); memcpy(indexBufferPtr,slab.source.begin(),sizeof(uint32_t)*indexCount); indexBufferPtr += indexCount; } // upload auto upAddrIt = m_tmpAddresses.begin()+1; for (uint32_t i=0u; i<propertiesThisPass; i++) { const auto& request = localRequests[i]; if (request.download) continue; if ((*upAddrIt)!=invalid_address) { size_t propSize = request.pool->getPropertySize(request.propertyID); memcpy(upBuffPtr+(*(upAddrIt++)),request.writeData,request.indices.size()*propSize); } } if (downAllocations) downBuff->multi_alloc(maxWaitPoint,downAllocations,downAddresses,downSizes,m_alignments.data()); } const auto pipelineIndex = propertiesThisPass-1u; auto& items = m_perPropertyCountItems[pipelineIndex]; auto pipeline = items.pipeline.get(); m_driver->bindComputePipeline(pipeline); // update desc sets auto set = items.descriptorSetCache.getNextSet(m_driver,localRequests,m_tmpSizes[0],m_tmpAddresses.data(),downAddresses); if (!set) { retval.first = false; return; } // bind desc sets m_driver->bindDescriptorSets(EPBP_COMPUTE,pipeline->getLayout(),0u,1u,&set.get(),nullptr); // dispatch (this will need to change to a cmd buffer submission with a fence) m_driver->dispatch((maxElements+IdealWorkGroupSize-1u)/IdealWorkGroupSize,propertiesThisPass,1u); auto& fence = retval.second = m_driver->placeFence(true); // deferred release resources upBuff->multi_free(upAllocations,m_tmpAddresses.data(),m_tmpSizes.data(),core::smart_refctd_ptr(fence)); if (downAllocations) downBuff->multi_free(downAllocations,downAddresses,downSizes,core::smart_refctd_ptr(fence)); items.descriptorSetCache.releaseSet(core::smart_refctd_ptr(fence),std::move(set)); }; auto requests = requestsBegin; for (uint32_t i=0; i<fullPasses; i++) { copyPass(requests,maxPropertiesPerPass); requests += maxPropertiesPerPass; } const auto leftOverProps = totalProps-fullPasses*maxPropertiesPerPass; if (leftOverProps) copyPass(requests,leftOverProps); } return retval; } // CPropertyPoolHandler::PerPropertyCountItems::PerPropertyCountItems(IVideoDriver* driver, IGPUPipelineCache* pipelineCache, uint32_t propertyCount) : descriptorSetCache(driver,propertyCount) { std::string shaderSource("#version 440 core\n"); // property count shaderSource += "#define _NBL_BUILTIN_PROPERTY_COUNT_ "; shaderSource += std::to_string(propertyCount)+"\n"; // workgroup sizes shaderSource += "#define _NBL_BUILTIN_PROPERTY_COPY_GROUP_SIZE_ "; shaderSource += std::to_string(IdealWorkGroupSize)+"\n"; // shaderSource += copyCsSource; auto cpushader = core::make_smart_refctd_ptr<asset::ICPUShader>(shaderSource.c_str()); auto shader = driver->createGPUShader(std::move(cpushader)); auto specshader = driver->createGPUSpecializedShader(shader.get(),{nullptr,nullptr,"main",asset::ISpecializedShader::ESS_COMPUTE}); auto layout = driver->createGPUPipelineLayout(nullptr,nullptr,descriptorSetCache.getLayout()); pipeline = driver->createGPUComputePipeline(pipelineCache,std::move(layout),std::move(specshader)); } // CPropertyPoolHandler::DescriptorSetCache::DescriptorSetCache(IVideoDriver* driver, uint32_t _propertyCount) : propertyCount(_propertyCount) { IGPUDescriptorSetLayout::SBinding bindings[3]; for (auto j=0; j<3; j++) { bindings[j].binding = j; bindings[j].type = asset::EDT_STORAGE_BUFFER; bindings[j].count = j ? propertyCount:1u; bindings[j].stageFlags = asset::ISpecializedShader::ESS_COMPUTE; bindings[j].samplers = nullptr; } layout = driver->createGPUDescriptorSetLayout(bindings,bindings+3); unusedSets.reserve(4u); // 4 frames worth at least } CPropertyPoolHandler::DeferredDescriptorSetReclaimer::single_poll_t CPropertyPoolHandler::DeferredDescriptorSetReclaimer::single_poll; core::smart_refctd_ptr<IGPUDescriptorSet> CPropertyPoolHandler::DescriptorSetCache::getNextSet( IVideoDriver* driver, const TransferRequest* requests, uint32_t parameterBufferSize, const uint32_t* uploadAddresses, const uint32_t* downloadAddresses ) { deferredReclaims.pollForReadyEvents(DeferredDescriptorSetReclaimer::single_poll); core::smart_refctd_ptr<IGPUDescriptorSet> retval; if (unusedSets.size()) { retval = std::move(unusedSets.back()); unusedSets.pop_back(); } else retval = driver->createGPUDescriptorSet(core::smart_refctd_ptr(layout)); constexpr auto kSyntheticMax = 64; assert(propertyCount<kSyntheticMax); IGPUDescriptorSet::SDescriptorInfo info[kSyntheticMax]; IGPUDescriptorSet::SWriteDescriptorSet dsWrite[3u]; { auto upBuff = driver->getDefaultUpStreamingBuffer()->getBuffer(); auto downBuff = driver->getDefaultDownStreamingBuffer()->getBuffer(); info[0].desc = core::smart_refctd_ptr<asset::IDescriptor>(upBuff); info[0].buffer = { *(uploadAddresses++),parameterBufferSize }; for (uint32_t i=0u; i<propertyCount; i++) { const auto& request = requests[i]; const bool download = request.download; const auto* pool = request.pool; const auto& poolMemBlock = pool->getMemoryBlock(); const uint32_t propertySize = pool->getPropertySize(request.propertyID); const uint32_t transferPropertySize = request.indices.size()*propertySize; const uint32_t poolPropertyBlockSize = pool->getCapacity()*propertySize; auto& inDescInfo = info[i+1]; auto& outDescInfo = info[propertyCount+i+1]; if (download) { inDescInfo.desc = core::smart_refctd_ptr<asset::IDescriptor>(poolMemBlock.buffer); inDescInfo.buffer = { pool->getPropertyOffset(request.propertyID),poolPropertyBlockSize }; outDescInfo.desc = core::smart_refctd_ptr<asset::IDescriptor>(downBuff); outDescInfo.buffer = { *(downloadAddresses++),transferPropertySize }; } else { inDescInfo.desc = core::smart_refctd_ptr<asset::IDescriptor>(upBuff); inDescInfo.buffer = { *(uploadAddresses++),transferPropertySize }; outDescInfo.desc = core::smart_refctd_ptr<asset::IDescriptor>(poolMemBlock.buffer); outDescInfo.buffer = { pool->getPropertyOffset(request.propertyID),poolPropertyBlockSize }; } } } for (auto i=0u; i<3u; i++) { dsWrite[i].dstSet = retval.get(); dsWrite[i].binding = i; dsWrite[i].arrayElement = 0u; dsWrite[i].descriptorType = asset::EDT_STORAGE_BUFFER; } dsWrite[0].count = 1u; dsWrite[0].info = info+0; dsWrite[1].count = propertyCount; dsWrite[1].info = info+1; dsWrite[2].count = propertyCount; dsWrite[2].info = info+1+propertyCount; driver->updateDescriptorSets(3u,dsWrite,0u,nullptr); return retval; } void CPropertyPoolHandler::DescriptorSetCache::releaseSet(core::smart_refctd_ptr<IDriverFence>&& fence, core::smart_refctd_ptr<IGPUDescriptorSet>&& set) { deferredReclaims.addEvent(GPUEventWrapper(std::move(fence)),DeferredDescriptorSetReclaimer(&unusedSets,std::move(set))); }
35.377574
213
0.737646
[ "vector" ]
4a6e0e47dc1fa4b4b6bbe51d07f5eeceec697080
2,707
cpp
C++
python/pyngraph/function.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
python/pyngraph/function.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
python/pyngraph/function.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "ngraph/function.hpp" // ngraph::Function #include "ngraph/op/parameter.hpp" // ngraph::op::Parameter #include "pyngraph/function.hpp" namespace py = pybind11; void regclass_pyngraph_Function(py::module m) { py::class_<ngraph::Function, std::shared_ptr<ngraph::Function>> function(m, "Function"); function.doc() = "ngraph.impl.Function wraps ngraph::Function"; function.def(py::init<const std::vector<std::shared_ptr<ngraph::Node>>&, const std::vector<std::shared_ptr<ngraph::op::Parameter>>&, const std::string&>()); function.def(py::init<const std::shared_ptr<ngraph::Node>&, const std::vector<std::shared_ptr<ngraph::op::Parameter>>&, const std::string&>()); function.def("get_output_size", &ngraph::Function::get_output_size); function.def("get_output_op", &ngraph::Function::get_output_op); function.def("get_output_element_type", &ngraph::Function::get_output_element_type); function.def("get_output_shape", &ngraph::Function::get_output_shape); function.def("get_parameters", &ngraph::Function::get_parameters); function.def("get_results", &ngraph::Function::get_results); function.def("get_result", &ngraph::Function::get_result); function.def("get_unique_name", &ngraph::Function::get_name); function.def("get_name", &ngraph::Function::get_friendly_name); function.def("set_friendly_name", &ngraph::Function::set_friendly_name); function.def("__repr__", [](const ngraph::Function& self) { std::string class_name = py::cast(self).get_type().attr("__name__").cast<std::string>(); std::string shape = py::cast(self.get_output_shape(0)).attr("__str__")().cast<std::string>(); return "<" + class_name + ": '" + self.get_friendly_name() + "' (" + shape + ")>"; }); }
51.075472
96
0.640562
[ "shape", "vector" ]
4a6e41f587a9b2b2a29f72ca7f12ceed1bf5f539
952
hpp
C++
include/xaod_helpers.hpp
gordonwatts/func-adl-types-atlas
9d135371d4e21d69373a8e1611ea8118cf2fff7f
[ "MIT" ]
null
null
null
include/xaod_helpers.hpp
gordonwatts/func-adl-types-atlas
9d135371d4e21d69373a8e1611ea8118cf2fff7f
[ "MIT" ]
1
2022-02-23T17:56:48.000Z
2022-02-23T17:56:48.000Z
include/xaod_helpers.hpp
gordonwatts/func-adl-types-atlas
9d135371d4e21d69373a8e1611ea8118cf2fff7f
[ "MIT" ]
null
null
null
#ifndef __xaod_helpers__ #define __xaod_helpers__ #include "type_helpers.hpp" #include "class_info.hpp" #include <vector> #include <string> struct collection_info { // The C++ type name of the collection. std::string name; // The libraries that we need to load for this guy std::vector<std::string> link_libraries; // The type info of the collection typename_info type_info; // The include file for the collection std::string include_file; // The simplified type-info for the collection typename_info iterator_type_info; }; // Given the list of parsed classes, returns the class info for everything // that is a collection. std::vector<collection_info> find_collections(const std::vector<class_info> &all_classes); std::vector<collection_info> get_single_object_collections(const std::vector<class_info> &all_classes); std::ostream& operator <<(std::ostream& stream, const collection_info& ci); #endif
27.2
103
0.745798
[ "vector" ]
4a72f6feff5da916a86414498dacc0acf377e118
13,989
cpp
C++
src/test/bip47_tests.cpp
KuroGuo/firo
dbce40b3c7edb21fbebb014e6fe7ab700e649b6f
[ "MIT" ]
582
2016-09-26T00:08:04.000Z
2020-10-25T19:07:24.000Z
src/test/bip47_tests.cpp
notshillo/firo
9b0714e65cd69448819cbbe10e6272ccd3e69dc9
[ "MIT" ]
570
2016-09-28T07:29:53.000Z
2020-10-26T10:24:19.000Z
src/test/bip47_tests.cpp
notshillo/firo
9b0714e65cd69448819cbbe10e6272ccd3e69dc9
[ "MIT" ]
409
2016-09-21T12:37:31.000Z
2020-10-18T14:54:17.000Z
// Copyright (c) 2020 The Firo Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // An implementation of bip47 tests provided here: https://gist.github.com/SamouraiDev/6aad669604c5930864bd #include <boost/test/unit_test.hpp> #include "test/test_bitcoin.h" #include "test/fixtures.h" #include "key.h" #include "utilstrencodings.h" #include <bip47/bip47utils.h> #include <bip47/secretpoint.h> #include <bip47/account.h> #include "wallet/wallet.h" #include "bip47_test_data.h" using namespace bip47; struct ChangeBase58Prefixes: public CChainParams { ChangeBase58Prefixes(CChainParams const & params): instance((ChangeBase58Prefixes*) &params) { instance->base58Prefixes[CChainParams::PUBKEY_ADDRESS][0] = 0; } ~ChangeBase58Prefixes() { instance->base58Prefixes[CChainParams::PUBKEY_ADDRESS][0] = 82; } ChangeBase58Prefixes * instance; }; BOOST_FIXTURE_TEST_SUITE(bip47_basic_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(payment_codes) { { using namespace alice; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtPubKey pubkey = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}).Neuter(); bip47::CPaymentCode paymentCode(pubkey.pubkey, pubkey.chaincode); BOOST_CHECK_EQUAL(paymentCode.toString(), paymentcode); } { using namespace bob; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtPubKey pubkey = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}).Neuter(); bip47::CPaymentCode paymentCode = bip47::CPaymentCode(pubkey.pubkey, pubkey.chaincode); BOOST_CHECK_EQUAL(paymentCode.toString(), paymentcode); } } BOOST_AUTO_TEST_CASE(ecdh_parameters) { { using namespace alice; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey privkey = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0}); CExtPubKey pubkey = privkey.Neuter(); BOOST_CHECK_EQUAL(HexStr(privkey.key), HexStr(ecdhparams[0])); BOOST_CHECK_EQUAL(HexStr(pubkey.pubkey), HexStr(ecdhparams[1])); } { using namespace bob; for(size_t i = 0; i < bob::ecdhparams.size() / 2; ++i) { CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey privkey = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, uint32_t(i)}); CExtPubKey pubkey = privkey.Neuter(); BOOST_CHECK_EQUAL(HexStr(privkey.key), HexStr(ecdhparams[i*2])); BOOST_CHECK_EQUAL(HexStr(pubkey.pubkey), HexStr(ecdhparams[i*2+1])); } } } BOOST_AUTO_TEST_CASE(notification_addresses) { ChangeBase58Prefixes _(Params()); {using namespace alice; bip47::CPaymentCode paymentCode(paymentcode); BOOST_CHECK_EQUAL(paymentCode.getNotificationAddress().ToString(), notificationaddress); } {using namespace bob; bip47::CPaymentCode paymentCode(paymentcode); BOOST_CHECK_EQUAL(paymentCode.getNotificationAddress().ToString(), notificationaddress); } } BOOST_AUTO_TEST_CASE(shared_secrets) { for(size_t i = 0; i < sharedsecrets.size(); ++i) { CKey privkey; privkey.Set(alice::ecdhparams[0].begin(), alice::ecdhparams[0].end(), false); CPubKey pubkey(bob::ecdhparams[2 * i + 1].begin(), bob::ecdhparams[2 * i + 1].end()); bip47::CSecretPoint s(privkey, pubkey); BOOST_CHECK(s.getEcdhSecret() == sharedsecrets[i]); } CKey privkey_b; privkey_b.Set(bob::ecdhparams[0].begin(), bob::ecdhparams[0].end(), false); CPubKey pubkey_a(alice::ecdhparams[1].begin(), alice::ecdhparams[1].end()); bip47::CSecretPoint const s_ba(privkey_b, pubkey_a); BOOST_CHECK(s_ba.getEcdhSecret() == sharedsecrets[0]); CKey privkey_a; privkey_a.Set(alice::ecdhparams[0].begin(), alice::ecdhparams[0].end(), false); CPubKey pubkey_b(bob::ecdhparams[1].begin(), bob::ecdhparams[1].end()); bip47::CSecretPoint const s_ab(privkey_a, pubkey_b); BOOST_CHECK(s_ab.isShared(s_ba)); } BOOST_AUTO_TEST_CASE(sending_addresses) { ChangeBase58Prefixes _(Params()); {using namespace alice; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey privkey_alice = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}); CPaymentCode const paymentCode_bob(bob::paymentcode); CPaymentChannel paymentChannel(paymentCode_bob, privkey_alice, CPaymentChannel::Side::sender); std::vector<std::string>::const_iterator iter = sendingaddresses.begin(); for (CBitcoinAddress const & addr: paymentChannel.generateTheirSecretAddresses(0, 10)) { BOOST_CHECK_EQUAL(addr.ToString(), *iter++); } } {using namespace bob; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey privkey_bob = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}); CPaymentCode const paymentCode_alice(alice::paymentcode); CPaymentChannel paymentChannel(paymentCode_alice, privkey_bob, CPaymentChannel::Side::sender); std::vector<std::string>::const_iterator iter = sendingaddresses.begin(); for (CBitcoinAddress const & addr: paymentChannel.generateTheirSecretAddresses(0, 5)) { BOOST_CHECK_EQUAL(addr.ToString(), *iter++); } } {using namespace bob; CExtKey key; key.SetMaster(bob::bip32seed.data(), bob::bip32seed.size()); CExtKey privkey_bob = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}); CPaymentCode const paymentCode_alice(alice::paymentcode); CPaymentChannel paymentChannel_bob(paymentCode_alice, privkey_bob, CPaymentChannel::Side::receiver); std::vector<std::string>::const_iterator iter = alice::sendingaddresses.begin(); for(bip47::MyAddrContT::value_type const & addr: paymentChannel_bob.generateMySecretAddresses(0, 10)) { BOOST_CHECK_EQUAL(addr.first.ToString(), *iter++); } } } BOOST_AUTO_TEST_CASE(masked_paymentcode) { ChangeBase58Prefixes _(Params()); {using namespace alice; CPaymentCode const paymentCode_bob(bob::paymentcode); CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey key_alice = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}); CPaymentChannel paymentChannel(paymentCode_bob, key_alice, CPaymentChannel::Side::sender); std::vector<unsigned char> const outPointSer = ParseHex("86f411ab1c8e70ae8a0795ab7a6757aea6e4d5ae1826fc7b8f00c597d500609c01000000"); CDataStream ds(outPointSer, SER_NETWORK, 0); COutPoint outpoint; ds >> outpoint; CBitcoinSecret vchSecret; vchSecret.SetString("Kx983SRhAZpAhj7Aac1wUXMJ6XZeyJKqCxJJ49dxEbYCT4a1ozRD"); CKey outpointSecret = vchSecret.GetKey(); std::vector<unsigned char> maskedPayload_alice = paymentChannel.getMaskedPayload(outpoint, outpointSecret); BOOST_CHECK_EQUAL(HexStr(maskedPayload_alice), maskedpayload); // Unmasking at bob's side key.SetMaster(bob::bip32seed.data(), bob::bip32seed.size()); CExtKey key_bob = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT, 0x00}); std::unique_ptr<CPaymentCode> pcode_unmasked = bip47::utils::PcodeFromMaskedPayload(maskedPayload_alice, outpoint, key_bob.key, outpointSecret.GetPubKey()); BOOST_CHECK_EQUAL(pcode_unmasked->toString(), paymentcode); } } BOOST_AUTO_TEST_CASE(account_for_sending) { ChangeBase58Prefixes _(Params()); {using namespace alice; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey key_alice = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}); CPaymentCode const paymentCode_bob(bob::paymentcode); bip47::CAccountSender account(key_alice, 0, paymentCode_bob); std::vector<unsigned char> const outPointSer = ParseHex("86f411ab1c8e70ae8a0795ab7a6757aea6e4d5ae1826fc7b8f00c597d500609c01000000"); CDataStream ds(outPointSer, SER_NETWORK, 0); COutPoint outpoint; ds >> outpoint; CBitcoinSecret vchSecret; vchSecret.SetString("Kx983SRhAZpAhj7Aac1wUXMJ6XZeyJKqCxJJ49dxEbYCT4a1ozRD"); CKey outpoinSecret = vchSecret.GetKey(); BOOST_CHECK_EQUAL(HexStr(account.getMaskedPayload(outpoint, outpoinSecret)), maskedpayload); MyAddrContT addresses = account.getMyNextAddresses(); BOOST_CHECK_EQUAL(addresses.size(), 1); CBitcoinAddress notifAddr = addresses[0].first; BOOST_CHECK_EQUAL(addresses[0].first.ToString(), notificationaddress); BOOST_CHECK(account.addressUsed(addresses[0].first)); addresses = account.getMyNextAddresses(); BOOST_CHECK(addresses[0].first == notifAddr); BOOST_CHECK(account.addressUsed(notifAddr)); addresses = account.getMyUsedAddresses(); BOOST_CHECK(addresses.empty()); } } BOOST_AUTO_TEST_CASE(account_for_receiving) { ChangeBase58Prefixes _(Params()); {using namespace bob; CExtKey key; key.SetMaster(bip32seed.data(), bip32seed.size()); CExtKey key_bob = utils::Derive(key, {47 | BIP32_HARDENED_KEY_LIMIT, 0x00 | BIP32_HARDENED_KEY_LIMIT}); bip47::CAccountReceiver account(key_bob, 0, ""); BOOST_CHECK_EQUAL(account.getMyPcode().toString(), paymentcode); BOOST_CHECK_EQUAL(account.getMyNotificationAddress().ToString(), notificationaddress); std::vector<unsigned char> const outPointSer = ParseHex("86f411ab1c8e70ae8a0795ab7a6757aea6e4d5ae1826fc7b8f00c597d500609c01000000"); CDataStream ds(outPointSer, SER_NETWORK, 0); COutPoint outpoint; ds >> outpoint; CBitcoinSecret vchSecret; vchSecret.SetString("Kx983SRhAZpAhj7Aac1wUXMJ6XZeyJKqCxJJ49dxEbYCT4a1ozRD"); CPubKey outpointPubkey = vchSecret.GetKey().GetPubKey(); BOOST_CHECK(account.acceptMaskedPayload(ParseHex(alice::maskedpayload), outpoint, outpointPubkey)); MyAddrContT addrs = account.getMyNextAddresses(); BOOST_CHECK_EQUAL(addrs.size(), 1 + bip47::AddressLookaheadNumber); BOOST_CHECK_EQUAL(addrs[0].first.ToString(), notificationaddress); for(size_t i = 0; i < bip47::AddressLookaheadNumber; ++i) { BOOST_CHECK_EQUAL(addrs[i+1].first.ToString(), alice::sendingaddresses[i]); } BOOST_CHECK(account.addressUsed(addrs[0].first)); addrs = account.getMyNextAddresses(); BOOST_CHECK_EQUAL(addrs.size(), 1 + bip47::AddressLookaheadNumber); BOOST_CHECK_EQUAL(addrs[0].first.ToString(), notificationaddress); CBitcoinAddress someAddr = addrs[2].first; BOOST_CHECK(account.addressUsed(someAddr)); addrs = account.getMyNextAddresses(); BOOST_CHECK_EQUAL(addrs.size(), 1 + bip47::AddressLookaheadNumber); BOOST_CHECK_EQUAL(addrs[0].first.ToString(), notificationaddress); for(size_t i = 0; i < bip47::AddressLookaheadNumber - 2; ++i) { BOOST_CHECK_EQUAL(addrs[i+1].first.ToString(), alice::sendingaddresses[i + 2]); } addrs = account.getMyUsedAddresses(); BOOST_CHECK_EQUAL(addrs.size(), 2); for(size_t i = 0; i < addrs.size(); ++i) { BOOST_CHECK_EQUAL(addrs[i].first.ToString(), alice::sendingaddresses[i]); } BOOST_CHECK(!account.addressUsed(someAddr)); BOOST_CHECK_EQUAL(addrs.size(), 2); for(size_t i = 0; i < addrs.size(); ++i) { BOOST_CHECK_EQUAL(addrs[i].first.ToString(), alice::sendingaddresses[i]); } someAddr.SetString(alice::sendingaddresses[9]); BOOST_CHECK(account.addressUsed(someAddr)); addrs = account.getMyUsedAddresses(); BOOST_CHECK_EQUAL(addrs.size(), 10); for(size_t i = 0; i < addrs.size(); ++i) { BOOST_CHECK_EQUAL(addrs[i].first.ToString(), alice::sendingaddresses[i]); } addrs = account.getMyNextAddresses(); BOOST_CHECK_EQUAL(addrs.size(), 1 + bip47::AddressLookaheadNumber); BOOST_CHECK_EQUAL(addrs[0].first.ToString(), notificationaddress); for(std::string const & bobsaddr : alice::sendingaddresses) { someAddr.SetString(bobsaddr); BOOST_CHECK(addrs.end() == std::find_if(addrs.begin(), addrs.end(), bip47::FindByAddress(someAddr))); } } } BOOST_AUTO_TEST_CASE(address_match) { CExtKey keyBob; keyBob.SetMaster(bob::bip32seed.data(), bob::bip32seed.size()); std::srand(std::time(nullptr)); bip47::CAccountReceiver receiver(keyBob, std::rand(), ""); CExtKey keyAlice; keyAlice.SetMaster(alice::bip32seed.data(), alice::bip32seed.size()); bip47::CAccountSender sender(keyAlice, std::rand(), receiver.getMyPcode()); receiver.acceptPcode(sender.getMyPcode()); MyAddrContT receiverAddrs = receiver.getMyNextAddresses(); BOOST_CHECK(std::find_if(receiverAddrs.begin(), receiverAddrs.end(), FindByAddress(sender.generateTheirNextSecretAddress())) != receiverAddrs.end()); for (MyAddrContT::value_type const & addrPair: receiverAddrs) { BOOST_CHECK(addrPair.first == CBitcoinAddress(addrPair.second.GetPubKey().GetID())); } } BOOST_AUTO_TEST_SUITE_END()
42.779817
164
0.700979
[ "vector" ]