hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8d451901383a043d62cdc80e5fb6fda54d59fc55
3,103
cpp
C++
src/config_loader.cpp
oeone/ClashSubGenerator
3188f336a4388ed304c82d2d24b9ef69f21f32d5
[ "MIT" ]
2
2021-12-16T11:20:00.000Z
2021-12-16T11:20:11.000Z
src/config_loader.cpp
oeone/ClashSubGenerator
3188f336a4388ed304c82d2d24b9ef69f21f32d5
[ "MIT" ]
1
2020-08-04T02:09:40.000Z
2020-08-04T02:09:40.000Z
src/config_loader.cpp
oeone/ClashSubGenerator
3188f336a4388ed304c82d2d24b9ef69f21f32d5
[ "MIT" ]
3
2020-08-01T07:06:07.000Z
2021-12-14T12:33:36.000Z
// // Created by Kotarou on 2020/8/7. // #include <fstream> #include <fmt/format.h> #include <yaml-cpp/yaml.h> #include <spdlog/spdlog.h> #include "config_loader.h" #include "uri.h" #include "hash.h" #include "httpclient.h" #include "filesystem.h" #include "exception/invalid_uri_exception.h" std::shared_ptr<ConfigLoader> ConfigLoader::instance() { static const std::shared_ptr<ConfigLoader> instance{new ConfigLoader{}}; return instance; } std::string ConfigLoader::load_raw(std::string_view uri, bool local_only, bool use_cache) { auto uri_result = Uri::Parse(uri); validate_schema(uri_result); // add support of protocol file:// if (uri_result.getSchema() == "file" || local_only) { SPDLOG_DEBUG("Load local file {}", uri); auto path = uri_result.getBody(); try { if (FileSystem::exists(path)) { std::fstream fin(path.data()); return std::string((std::istreambuf_iterator<char>(fin)), std::istreambuf_iterator<char>()); } } catch (std::exception &e) { throw FileSystemException(fmt::format("Load file {} filed, error: {}", path, e.what())); } throw FileSystemException(fmt::format("File {} doesn't exist", path)); } else { return cache_loader(uri_result, use_cache); } } YAML::Node ConfigLoader::load_yaml(std::string_view uri, bool local_only, bool use_cache) { auto uri_result = Uri::Parse(uri); validate_schema(uri_result); // add support of protocol file:// if (uri_result.getSchema() == "file" || local_only) { SPDLOG_DEBUG("load local yaml file {}", uri_result.getBody()); auto path = uri_result.getBody(); if (FileSystem::exists(path)) { return YAML::LoadFile(path.data()); } throw FileSystemException(fmt::format("File {} doesn't exist", path)); } else { return YAML::Load(cache_loader(uri_result, use_cache)); } } std::string ConfigLoader::cache_loader(const Uri &uri, bool use_cache) { if (use_cache) { const auto sha1_hash = Hash::sha1(uri.getRawUri()); if (cache.find(sha1_hash) == cache.end()) { // download and cache auto content = HttpClient::get(uri); cache.emplace(sha1_hash, content); SPDLOG_DEBUG("Uri {} downloaded and cached", uri.getRawUri()); return content; } else { SPDLOG_DEBUG("Uri {} loaded from cache", uri.getRawUri()); return cache[sha1_hash]; } } else { return HttpClient::get(uri); } } void ConfigLoader::destroy_cache() { auto size = cache.size(); cache.clear(); SPDLOG_DEBUG("{} cached data deleted", size); } void ConfigLoader::validate_schema(const Uri &uri) { constexpr std::string_view valid_schema[] = {"http", "https", "file"}; for (const auto &schema : valid_schema) { if (schema == uri.getSchema()) { return; } } throw InvalidURIException(fmt::format("URI {} doesn't have a valid schema", uri.getRawUri())); }
31.663265
108
0.617145
oeone
8d4753a57f45e5e2681497ef18b41ef86c7aaa30
813
cpp
C++
kernel/posix/string.cpp
mschwartz/amos
345a4f8f52b9805722c10ac4cedb24b480fe2dc7
[ "MIT" ]
4
2020-08-18T00:11:09.000Z
2021-04-05T11:16:32.000Z
kernel/posix/string.cpp
mschwartz/amos
345a4f8f52b9805722c10ac4cedb24b480fe2dc7
[ "MIT" ]
1
2020-08-15T20:39:13.000Z
2020-08-15T20:39:13.000Z
kernel/posix/string.cpp
mschwartz/amos
345a4f8f52b9805722c10ac4cedb24b480fe2dc7
[ "MIT" ]
null
null
null
#include <posix.h> #include <posix/string.h> size_t strlen(char *s) { int count = 0; while (*s++) { count++; } return count; } void strcpy(char *dst, const char *src) { while ((*dst++ = *src++)); } void reverse(char *src) { int l = strlen(src); char work[l+1]; char *dst = work, *end_ptr = &src[l-1]; for (int i=0; i<l; i++) { *dst++ = *end_ptr--; } *dst++ = '\0'; strcpy(src, work); } void memcpy(void *dst, void *src, size_t size) { uint8_t *s = (uint8_t *)src, *d = (uint8_t *)dst; for (size_t i = 0; i < size; i++) { *d++ = *s++; } } void memset(void *dst, uint8_t v, size_t size) { uint8_t *d = (uint8_t *)dst; // size = 4096; // kprint("memset(%x, %d, %d)\n", d, v, 4096); for (size_t i = 0; i < size; i++) { *d++ = v; } }
16.9375
49
0.499385
mschwartz
8d481bc1adad90985207ec3cbeae0668734d7fa6
1,519
cpp
C++
3666 THE MATRIX PROBLEM/main.cpp
sqc1999-oi/HDU
5583755c5b7055e4a7254b2124f67982cc49b72d
[ "MIT" ]
1
2016-07-18T12:05:44.000Z
2016-07-18T12:05:44.000Z
3666 THE MATRIX PROBLEM/main.cpp
sqc1999-oi/HDU
5583755c5b7055e4a7254b2124f67982cc49b72d
[ "MIT" ]
null
null
null
3666 THE MATRIX PROBLEM/main.cpp
sqc1999-oi/HDU
5583755c5b7055e4a7254b2124f67982cc49b72d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stack> #include <cstring> #include <cmath> using namespace std; struct Edge { int To, Next; double Pow; Edge(int to, double pow, int next) : To(to), Pow(pow), Next(next) { } Edge() { } } E[1000001]; int G[1001], cnt, Cnt[1001]; double dis[1001]; bool inq[1001]; void AddEdge(int from, int to, double pow) { E[++cnt] = Edge(to, pow, G[from]); G[from] = cnt; } int a[401][401]; int main() { ios::sync_with_stdio(false); int n, m, l, u; while (cin >> n >> m >> l >> u) { memset(G, 0, sizeof G); cnt = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int w; cin >> w; AddEdge(j + n, i, log(u) - log(w)); AddEdge(i, j + n, log(w) - log(l)); } for (int i = 1; i <= n + m; i++) AddEdge(0, i, 0); memset(dis, 0x3f, sizeof dis); memset(Cnt, 0, sizeof Cnt); memset(inq, 0, sizeof inq); dis[0] = 0; stack<int> q; q.push(0); inq[0] = true; bool flag = true; while (!q.empty()) { int u = q.top(); q.pop(); inq[u] = false; for (int i = G[u]; i != 0; i = E[i].Next) { int &v = E[i].To; double tmp = dis[v]; dis[v] = min(dis[v], dis[u] + E[i].Pow); if (tmp != dis[v] && !inq[v]) { if (++Cnt[v] > n + m + 1) { flag = false; break; } q.push(v); inq[v] = true; } } if (!flag) break; } cout << (flag ? "YES" : "NO") << endl; } }
18.301205
45
0.463463
sqc1999-oi
8d4a5ff37dbf9d49be0181b68162842065d0664f
2,140
hpp
C++
Sources/SF2Lib/include/SF2Lib/Render/LowPassFilter.hpp
bradhowes/SF2Lib
766c38c9c49e3cf66f4161edc1695e071c345b63
[ "MIT" ]
null
null
null
Sources/SF2Lib/include/SF2Lib/Render/LowPassFilter.hpp
bradhowes/SF2Lib
766c38c9c49e3cf66f4161edc1695e071c345b63
[ "MIT" ]
null
null
null
Sources/SF2Lib/include/SF2Lib/Render/LowPassFilter.hpp
bradhowes/SF2Lib
766c38c9c49e3cf66f4161edc1695e071c345b63
[ "MIT" ]
null
null
null
// Copyright © 2022 Brad Howes. All rights reserved. #pragma once #include <cassert> #include <iostream> #include "SF2Lib/DSP/DSP.hpp" #include "DSPHeaders/Biquad.hpp" namespace SF2::Render { class LowPassFilter { public: using Coefficients = DSPHeaders::Biquad::Coefficients<Float>; inline static Float defaultFrequency = 13500; inline static Float defaultResonance = 0.0; LowPassFilter(Float sampleRate) noexcept : filter_{Coefficients()}, sampleRate_{sampleRate}, lastFrequency_{defaultFrequency}, lastResonance_{defaultResonance} { updateSettings(defaultFrequency, defaultResonance); } /** Update the filter to use the given frequency and resonance settings. @param frequency frequency represented in cents @param resonance resonance in centiBels */ Float transform(Float frequency, Float resonance, Float sample) noexcept { // return sample; if (lastFrequency_ != frequency || lastResonance_ != resonance) { updateSettings(frequency, resonance); // Bounds taken from FluidSynth, where the upper bound serves as an anti-aliasing filter, just below the // Nyquist frequency. frequency = DSP::clamp(DSP::centsToFrequency(frequency), 5.0, 0.45 * sampleRate_); resonance = DSP::centibelsToResonance(resonance); filter_.setCoefficients(Coefficients::LPF2(sampleRate_, frequency, resonance)); } return filter_.transform(sample); } void reset() noexcept { filter_.reset(); } private: void updateSettings(Float frequency, Float resonance) noexcept { lastFrequency_ = frequency; lastResonance_ = resonance; // Bounds taken from FluidSynth, where the upper bound serves as an anti-aliasing filter, just below the // Nyquist frequency. frequency = DSP::clamp(DSP::centsToFrequency(frequency), 5.0, 0.45 * sampleRate_); resonance = DSP::centibelsToResonance(resonance); filter_.setCoefficients(Coefficients::LPF2(sampleRate_, frequency, resonance)); } DSPHeaders::Biquad::Direct<Float> filter_; Float sampleRate_; Float lastFrequency_; Float lastResonance_; }; } // end namespace SF2::Render
29.315068
110
0.732243
bradhowes
8d4d75eba468a4a2046fb087e3730c283fee453c
490
cpp
C++
ch04/DemoConstCast.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
3
2019-09-21T13:03:57.000Z
2020-04-05T02:42:53.000Z
ch04/DemoConstCast.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
null
null
null
ch04/DemoConstCast.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
null
null
null
/************************************************************************* > File Name: DemoConstCast.cpp > Author: shenzhuo > Mail: im.shenzhuo@gmail.com > Created Time: 2019年08月29日 星期四 10时39分19秒 ************************************************************************/ #include<iostream> using namespace std; int main() { int i = 99; const int *p = &i; // error // *p = -99; int *newp = const_cast<int *>(p); *newp = -99; cout << i << endl; return 0; }
18.148148
74
0.408163
imshenzhuo
8d4f50cddfb2355f2a867d814a27879a5dc18d15
8,129
cpp
C++
ql/experimental/commodities/energycommodity.cpp
igitur/quantlib
3f6b7271a68004cdb6db90f0e87346e8208234a2
[ "BSD-3-Clause" ]
1
2021-04-28T02:21:54.000Z
2021-04-28T02:21:54.000Z
ql/experimental/commodities/energycommodity.cpp
wangpeng-personal/QuantLib
2e4e4f1662bf15d18d19b396079feb36acb60150
[ "BSD-3-Clause" ]
4
2021-02-08T06:07:05.000Z
2022-03-29T12:23:40.000Z
ql/experimental/commodities/energycommodity.cpp
westonsteimel/QuantLib
739ea894961dc6da5e8aa0b61c392d40637d39c1
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 J. Erik Radmall This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/currencies/exchangeratemanager.hpp> #include <ql/experimental/commodities/commoditysettings.hpp> #include <ql/experimental/commodities/energycommodity.hpp> #include <ql/experimental/commodities/unitofmeasureconversionmanager.hpp> #include <iomanip> #include <utility> namespace QuantLib { EnergyDailyPosition::EnergyDailyPosition() = default; EnergyDailyPosition::EnergyDailyPosition(const Date& date, Real payLegPrice, Real receiveLegPrice, bool unrealized) : date(date), quantityAmount(0), payLegPrice(payLegPrice), receiveLegPrice(receiveLegPrice), unrealized(unrealized) {} std::ostream& operator<<(std::ostream& out, const EnergyDailyPositions& dailyPositions) { out << std::setw(12) << std::left << "positions" << std::setw(12) << std::right << "pay" << std::setw(12) << std::right << "receive" << std::setw(10) << std::right << "qty" << std::setw(14) << std::right << "delta" << std::setw(10) << std::right << "open" << std::endl; for (const auto& i : dailyPositions) { const EnergyDailyPosition& dailyPosition = i.second; out << std::setw(4) << io::iso_date(i.first) << " " << std::setw(12) << std::right << std::fixed << std::setprecision(6) << dailyPosition.payLegPrice << std::setw(12) << std::right << std::fixed << std::setprecision(6) << dailyPosition.receiveLegPrice << std::setw(10) << std::right << std::fixed << std::setprecision(2) << dailyPosition.quantityAmount << std::setw(14) << std::right << std::fixed << std::setprecision(2) << dailyPosition.riskDelta << std::setw(10) << std::right << std::fixed << std::setprecision(2) << (dailyPosition.unrealized ? dailyPosition.quantityAmount : 0) << std::endl; } return out; } void EnergyCommodity::setupArguments(PricingEngine::arguments* args) const { auto* arguments = dynamic_cast<EnergyCommodity::arguments*>(args); QL_REQUIRE(arguments != nullptr, "wrong argument type"); //arguments->legs = legs_; //arguments->payer = payer_; } void EnergyCommodity::fetchResults(const PricingEngine::results* r) const { Instrument::fetchResults(r); const auto* results = dynamic_cast<const EnergyCommodity::results*>(r); QL_REQUIRE(results != nullptr, "wrong result type"); } EnergyCommodity::EnergyCommodity(CommodityType commodityType, const ext::shared_ptr<SecondaryCosts>& secondaryCosts) : Commodity(secondaryCosts), commodityType_(std::move(commodityType)) {} const CommodityType& EnergyCommodity::commodityType() const { return commodityType_; } Real EnergyCommodity::calculateUomConversionFactor( const CommodityType& commodityType, const UnitOfMeasure& fromUnitOfMeasure, const UnitOfMeasure& toUnitOfMeasure) { if (toUnitOfMeasure != fromUnitOfMeasure) { UnitOfMeasureConversion uomConv = UnitOfMeasureConversionManager::instance().lookup( commodityType, fromUnitOfMeasure, toUnitOfMeasure); return uomConv.conversionFactor(); } return 1; } Real EnergyCommodity::calculateFxConversionFactor( const Currency& fromCurrency, const Currency& toCurrency, const Date& evaluationDate) { if (fromCurrency != toCurrency) { ExchangeRate exchRate = ExchangeRateManager::instance().lookup( fromCurrency, toCurrency, evaluationDate /*, ExchangeRate::Direct*/); if (fromCurrency == exchRate.target()) return 1.0 / exchRate.rate(); return exchRate.rate(); } return 1; } Real EnergyCommodity::calculateUnitCost(const CommodityType& commodityType, const CommodityUnitCost& unitCost, const Date& evaluationDate) const { if (unitCost.amount().value() != 0) { const Currency& baseCurrency = CommoditySettings::instance().currency(); const UnitOfMeasure baseUnitOfMeasure = CommoditySettings::instance().unitOfMeasure(); Real unitCostUomConversionFactor = calculateUomConversionFactor(commodityType, unitCost.unitOfMeasure(), baseUnitOfMeasure); Real unitCostFxConversionFactor = calculateFxConversionFactor(unitCost.amount().currency(), baseCurrency, evaluationDate); return unitCost.amount().value() * unitCostUomConversionFactor * unitCostFxConversionFactor; } return 0; } void EnergyCommodity::calculateSecondaryCostAmounts( const CommodityType& commodityType, Real totalQuantityValue, const Date& evaluationDate) const { secondaryCostAmounts_.clear(); if (secondaryCosts_ != nullptr) { const Currency& baseCurrency = CommoditySettings::instance().currency(); try { for (SecondaryCosts::const_iterator i = secondaryCosts_->begin(); i != secondaryCosts_->end(); ++i) { if (boost::any_cast<CommodityUnitCost>(&i->second) != nullptr) { Real value = calculateUnitCost( commodityType, boost::any_cast<CommodityUnitCost>(i->second), evaluationDate) * totalQuantityValue; secondaryCostAmounts_[i->first] = Money(baseCurrency, value); } else if (boost::any_cast<Money>(&i->second) != nullptr) { const Money& amount = boost::any_cast<Money>(i->second); Real fxConversionFactor = calculateFxConversionFactor(amount.currency(), baseCurrency, evaluationDate); secondaryCostAmounts_[i->first] = Money(baseCurrency, amount.value() * fxConversionFactor); } } } catch (const std::exception& e) { QL_FAIL("error calculating secondary costs: " << e.what()); } } } }
45.926554
100
0.546193
igitur
8d52f5de01200eee6b2c6a4af694c61dbc8cd553
4,026
cpp
C++
10b/Chapter_13_Binary_Search_Tree_Code.cpp
mparsakia/pic-ucla
bca66812d2ce9daa8dcaa7ab126260c75f9c9ab4
[ "Unlicense" ]
1
2020-08-07T13:03:14.000Z
2020-08-07T13:03:14.000Z
10b/Chapter_13_Binary_Search_Tree_Code.cpp
mparsakia/pic-ucla
bca66812d2ce9daa8dcaa7ab126260c75f9c9ab4
[ "Unlicense" ]
null
null
null
10b/Chapter_13_Binary_Search_Tree_Code.cpp
mparsakia/pic-ucla
bca66812d2ce9daa8dcaa7ab126260c75f9c9ab4
[ "Unlicense" ]
null
null
null
#include <vector> #include <iostream> #include <assert.h> #include <stdio.h> #include <algorithm> #include <fstream> #include <cstring> #include <string> #include <iomanip> #include <sstream> #include <map> #include <set> #include <list> // Binary Search Tree using namespace std; class TreeNode { public: void insert_node(TreeNode* new_node); void print_nodes() const; bool find(string value) const; private: string data; TreeNode* left; TreeNode* right; }; class BinarySearchTree { public: BinarySearchTree(); void insert(string data); void erase(string data); int count(string data) const; void print() const; private: TreeNode* root; }; BinarySearchTree::BinarySearchTree() { root = NULL; } void BinarySearchTree::print() const { if (root != NULL) root->print_nodes(); } void BinarySearchTree::insert(string data) { TreeNode* new_node = new TreeNode; new_node->data = data; new_node->left = NULL; new_node->right = NULL; if (root == NULL) root = new_node; else root->insert_node(new_node); } void TreeNode::insert_node(TreeNode* new_node) { if (new_node->data < data) { if (left == NULL) left = new_node; else left->insert_node(new_node); } else if (data < new_node->data) { if (right == NULL) right = new_node; else right->insert_node(new_node); } } int BinarySearchTree::count(string data) const { if (root == NULL) return 0; else if (root->find(data)) return 1; else return 0; } void BinarySearchTree::erase(string data) { // Find node to be removed TreeNode* to_be_removed = root; TreeNode* parent = NULL; bool found = false; while (!found && to_be_removed != NULL) { if (to_be_removed->data < data) { parent = to_be_removed; to_be_removed = to_be_removed->right; } else if (data < to_be_removed->data) { parent = to_be_removed; to_be_removed = to_be_removed->left; } else found = true; } if (!found) return; // to_be_removed contains data // If one of the children is empty, use the other if (to_be_removed->left == NULL || to_be_removed->right == NULL) { TreeNode* new_child; if (to_be_removed->left == NULL) new_child = to_be_removed->right; else new_child = to_be_removed->left; if (parent == NULL) // Found in root root = new_child; else if (parent->left == to_be_removed) parent->left = new_child; else parent->right = new_child; return; } // Neither subtree is empty // Find smallest element of the right subtree TreeNode* smallest_parent = to_be_removed; TreeNode* smallest = to_be_removed->right; while (smallest->left != NULL) { smallest_parent = smallest; smallest = smallest->left; } // smallest contains smallest child in right subtree // Move contents, unlink child to_be_removed->data = smallest->data; if (smallest_parent == to_be_removed) smallest_parent->right = smallest->right; else smallest_parent->left = smallest->right; } bool TreeNode::find(string value) const { if (value < data) { if (left == NULL) return false; else return left->find(value); } else if (data < value) { if (right == NULL) return false; else return right->find(value); } else { return true; } } void TreeNode::print_nodes() const { if (left != NULL) // LEFT left->print_nodes(); cout << data << "\n"; // DATA if (right != NULL) right->print_nodes(); // RIGHT THIS IS LDR (IN ORDER) } int main() { BinarySearchTree t; t.insert("D"); t.insert("B"); t.insert("A"); t.insert("C"); t.insert("F"); t.insert("E"); t.insert("I"); t.insert("G"); t.insert("H"); t.insert("J"); t.erase("A"); // Removing leaf t.erase("B"); // Removing element with one child t.erase("F"); // Removing element with two children t.erase("D"); // Removing root t.print(); cout << t.count("E") << "\n"; cout << t.count("F") << "\n"; return 0; }
19.930693
66
0.633631
mparsakia
8d55c465e9037f1d5bb43fa3ec412752ad98af06
984
hpp
C++
sdk/storage/azure-storage-files-datalake/test/ut/datalake_file_system_client_test.hpp
varchar-io/azure-sdk-for-cpp
4d498c59baf21fa9160ea913d379380ecc60e65d
[ "MIT" ]
null
null
null
sdk/storage/azure-storage-files-datalake/test/ut/datalake_file_system_client_test.hpp
varchar-io/azure-sdk-for-cpp
4d498c59baf21fa9160ea913d379380ecc60e65d
[ "MIT" ]
null
null
null
sdk/storage/azure-storage-files-datalake/test/ut/datalake_file_system_client_test.hpp
varchar-io/azure-sdk-for-cpp
4d498c59baf21fa9160ea913d379380ecc60e65d
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include <azure/storage/files/datalake.hpp> #include "datalake_service_client_test.hpp" #include "test/ut/test_base.hpp" namespace Azure { namespace Storage { namespace Test { class DataLakeFileSystemClientTest : public DataLakeServiceClientTest { protected: void SetUp(); void TearDown(); void CreateDirectoryList(); std::vector<Files::DataLake::Models::PathItem> ListAllPaths( bool recursive, const std::string& directory = std::string()); Files::DataLake::Models::PathHttpHeaders GetInterestingHttpHeaders(); std::shared_ptr<Files::DataLake::DataLakeFileSystemClient> m_fileSystemClient; std::string m_fileSystemName; // Path related std::vector<std::string> m_pathNameSetA; std::string m_directoryA; std::vector<std::string> m_pathNameSetB; std::string m_directoryB; }; }}} // namespace Azure::Storage::Test
28.941176
82
0.727642
varchar-io
8d5a723da6ca46440e400b17cb83be03294901c3
596
hpp
C++
tcob/include/tcob/game/Config.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
2
2021-08-18T19:14:35.000Z
2021-12-01T14:14:49.000Z
tcob/include/tcob/game/Config.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
tcob/include/tcob/game/Config.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Tobias Bohnen // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #pragma once #include <tcob/tcob_config.hpp> #include <tcob/script/LuaScript.hpp> #include <tcob/script/LuaTable.hpp> namespace tcob { //////////////////////////////////////////////////////////// class Config final : public script::lua::Table { public: Config() = default; ~Config() override; void save() const; auto load() -> bool; private: auto operator=(const script::lua::Ref& other) -> Config&; script::lua::Script _script {}; }; }
22.074074
61
0.60906
TobiasBohnen
8d64dc75a23e683306389a96bd8e232ccdb68390
1,179
hpp
C++
src/HTMLElements/HTMLElement.hpp
windlessStorm/WebWhir
0ed261427d4f4e4f81b62816dc0d94bfacd0890b
[ "MIT" ]
90
2017-04-03T21:42:57.000Z
2022-01-22T11:08:56.000Z
src/HTMLElements/HTMLElement.hpp
windlessStorm/WebWhir
0ed261427d4f4e4f81b62816dc0d94bfacd0890b
[ "MIT" ]
21
2017-03-06T21:45:36.000Z
2017-03-06T21:45:37.000Z
src/HTMLElements/HTMLElement.hpp
windlessStorm/WebWhir
0ed261427d4f4e4f81b62816dc0d94bfacd0890b
[ "MIT" ]
17
2017-04-15T22:42:13.000Z
2021-12-20T09:50:15.000Z
#ifndef HTMLELEMENT_H #define HTMLELEMENT_H #include <string> #include <vector> #include <memory> class HTMLElement { public: HTMLElement(); HTMLElement(const HTMLElement &element); virtual ~HTMLElement(); std::wstring get_id() const; std::wstring get_title() const; void set_title(const std::wstring &element_title); void add_child(const std::shared_ptr<HTMLElement> child_node); std::vector<std::shared_ptr<HTMLElement>> get_children() const; void add_text(const std::shared_ptr<HTMLElement> text_node); // Text Node functions virtual bool is_text_node() const { return false; }; virtual void add_char(const wchar_t &next_char) {}; virtual void add_char(const std::wstring &next_char) {}; virtual wchar_t get_char() const { return L'\0'; }; virtual std::wstring get_text() const { return L""; }; // Paragraph Node functions virtual bool is_paragraph_node() const { return false; }; protected: std::wstring id; std::wstring title; std::vector<std::shared_ptr<HTMLElement>> child_nodes; }; #endif
31.026316
71
0.64631
windlessStorm
8d65d0ce0bc4f84d1a9f3a7f41375fea055d62b3
18,694
cpp
C++
src/materialsystem/checkmaterials.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/materialsystem/checkmaterials.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/materialsystem/checkmaterials.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "pch_materialsystem.h" // NOTE: currently this file is marked as "exclude from build" //#define _CHECK_MATERIALS_FOR_PROBLEMS 1 #ifdef _CHECK_MATERIALS_FOR_PROBLEMS #include "vtf/vtf.h" #include "tier1/utlbuffer.h" #include "tier1/utlstring.h" void CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory ); #endif #ifdef _CHECK_MATERIALS_FOR_PROBLEMS //----------------------------------------------------------------------------- // Does a texture have alpha? //----------------------------------------------------------------------------- static bool DoesTextureUseAlpha( const char *pTextureName, const char *pMaterialName ) { if ( IsX360() ) { // not supporting return false; } // Special textures start with '_'.. if ( pTextureName[0] == '_' ) return false; // The texture name doubles as the relative file name // It's assumed to have already been set by this point // Compute the cache name char pCacheFileName[MATERIAL_MAX_PATH]; Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName ); CUtlBuffer buf; FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE) { Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName ); return false; } // Check the .vtf for an alpha channel IVTFTexture *pVTFTexture = CreateVTFTexture(); int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION ); buf.EnsureCapacity( nHeaderSize ); // read the header first.. it's faster!! g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle ); buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize ); // Unserialize the header bool bUsesAlpha = false; if (!pVTFTexture->Unserialize( buf, true )) { Warning( "Error reading material \"%s\"\n", pCacheFileName ); g_pFullFileSystem->Close(fileHandle); } else { if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) ) { bUsesAlpha = true; } } DestroyVTFTexture( pVTFTexture ); g_pFullFileSystem->Close( fileHandle ); return bUsesAlpha; } //----------------------------------------------------------------------------- // Does a texture have alpha? //----------------------------------------------------------------------------- static bool DoesTextureUseNormal( const char *pTextureName, const char *pMaterialName, bool &bUsesAlpha, bool &bIsCompressed, int &nSizeInBytes ) { nSizeInBytes = 0; bUsesAlpha = false; if ( IsX360() ) { // not supporting return false; } // Special textures start with '_'.. if ( !pTextureName || ( pTextureName[0] == '_' ) || ( pTextureName[0] == 0 ) ) return false; // The texture name doubles as the relative file name // It's assumed to have already been set by this point // Compute the cache name char pCacheFileName[MATERIAL_MAX_PATH]; Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName ); CUtlBuffer buf; FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE) { // Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName ); return false; } // Check the .vtf for an alpha channel IVTFTexture *pVTFTexture = CreateVTFTexture(); int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION ); buf.EnsureCapacity( nHeaderSize ); // read the header first.. it's faster!! g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle ); buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize ); // Unserialize the header bool bUsesNormal = false; if ( !pVTFTexture->Unserialize( buf, true ) ) { Warning( "Error reading material \"%s\"\n", pCacheFileName ); } else { if ( pVTFTexture->Flags() & TEXTUREFLAGS_NORMAL ) { bUsesAlpha = false; bUsesNormal = true; bIsCompressed = ImageLoader::IsCompressed( pVTFTexture->Format() ) || ( pVTFTexture->Format() == IMAGE_FORMAT_A8 ); nSizeInBytes = pVTFTexture->ComputeTotalSize(); if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) ) { bUsesAlpha = true; } } } DestroyVTFTexture( pVTFTexture ); g_pFullFileSystem->Close( fileHandle ); return bUsesNormal; } //----------------------------------------------------------------------------- // Is this a real texture //----------------------------------------------------------------------------- static bool IsTexture( const char *pTextureName ) { // Special textures start with '_'.. if ( pTextureName[0] == '_' ) return false; // The texture name doubles as the relative file name // It's assumed to have already been set by this point // Compute the cache name char pCacheFileName[MATERIAL_MAX_PATH]; Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName ); FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" ); if ( fileHandle == FILESYSTEM_INVALID_HANDLE) return false; g_pFullFileSystem->Close( fileHandle ); return true; } //----------------------------------------------------------------------------- // Scan material + all subsections for key //----------------------------------------------------------------------------- static float MaterialFloatKeyValue( KeyValues *pKeyValues, const char *pKeyName, float flDefault ) { float flValue = pKeyValues->GetFloat( pKeyName, flDefault ); if ( flValue != flDefault ) return flValue; for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { float flValue = MaterialFloatKeyValue( pSubKey, pKeyName, flDefault ); if ( flValue != flDefault ) return flValue; } return flDefault; } int ParseVectorFromKeyValueString( KeyValues *pKeyValue, const char *pMaterialName, float vecVal[4] ); static bool AsVectorsEqual( int nDim1, float *pVector1, int nDim2, float *pVector2 ) { if ( nDim1 != nDim2 ) return false; for ( int i = 0; i < nDim1; ++i ) { if ( fabs( pVector1[i] - pVector2[i] ) > 1e-3 ) return false; } return true; } static bool MaterialVectorKeyValue( KeyValues *pKeyValues, const char *pKeyName, int nDefaultDim, float *pDefault, int *pDim, float *pVector ) { int nDim; float retVal[4]; KeyValues *pValue = pKeyValues->FindKey( pKeyName ); if ( pValue ) { switch( pValue->GetDataType() ) { case KeyValues::TYPE_INT: { int nInt = pValue->GetInt(); for ( int i = 0; i < 4; ++i ) { retVal[i] = nInt; } if ( !AsVectorsEqual( nDefaultDim, pDefault, nDefaultDim, retVal ) ) { *pDim = nDefaultDim; memcpy( pVector, retVal, nDefaultDim * sizeof(float) ); return true; } } break; case KeyValues::TYPE_FLOAT: { float flFloat = pValue->GetFloat(); for ( int i = 0; i < 4; ++i ) { retVal[i] = flFloat; } if ( !AsVectorsEqual( nDefaultDim, pDefault, nDefaultDim, retVal ) ) { *pDim = nDefaultDim; memcpy( pVector, retVal, nDefaultDim * sizeof(float) ); return true; } } break; case KeyValues::TYPE_STRING: { nDim = ParseVectorFromKeyValueString( pValue, "", retVal ); if ( !AsVectorsEqual( nDefaultDim, pDefault, nDim, retVal ) ) { *pDim = nDim; memcpy( pVector, retVal, nDim * sizeof(float) ); return true; } } break; } } for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { if ( MaterialVectorKeyValue( pSubKey, pKeyName, nDefaultDim, pDefault, &nDim, retVal ) ) { *pDim = nDim; memcpy( pVector, retVal, nDim * sizeof(float) ); return true; } } *pDim = nDefaultDim; memcpy( pVector, pDefault, nDefaultDim * sizeof(float) ); return false; } //----------------------------------------------------------------------------- // Scan material + all subsections for key //----------------------------------------------------------------------------- static bool DoesMaterialHaveKey( KeyValues *pKeyValues, const char *pKeyName ) { if ( pKeyValues->GetString( pKeyName, NULL ) != NULL ) return true; for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { if ( DoesMaterialHaveKey( pSubKey, pKeyName ) ) return true; } return false; } //----------------------------------------------------------------------------- // Scan all materials for errors //----------------------------------------------------------------------------- static int s_nNormalBytes; static int s_nNormalCompressedBytes; static int s_nNormalPalettizedBytes; static int s_nNormalWithAlphaBytes; static int s_nNormalWithAlphaCompressedBytes; struct VTFInfo_t { CUtlString m_VTFName; bool m_bFoundInVMT; }; void CheckKeyValues( KeyValues *pKeyValues, CUtlVector<VTFInfo_t> &vtf ) { for ( KeyValues *pSubKey = pKeyValues->GetFirstValue(); pSubKey; pSubKey = pSubKey->GetNextValue() ) { if ( pSubKey->GetDataType() != KeyValues::TYPE_STRING ) continue; if ( IsTexture( pSubKey->GetString() ) ) { int nLen = Q_strlen( pSubKey->GetString() ) + 1; char *pTemp = (char*)_alloca( nLen ); memcpy( pTemp, pSubKey->GetString(), nLen ); Q_FixSlashes( pTemp ); int nCount = vtf.Count(); for ( int i = 0; i < nCount; ++i ) { if ( Q_stricmp( vtf[i].m_VTFName, pTemp ) ) continue; vtf[i].m_bFoundInVMT = true; break; } } } for ( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() ) { CheckKeyValues( pSubKey, vtf ); } } void CheckMaterial( KeyValues *pKeyValues, const char *pRoot, const char *pFileName, CUtlVector<VTFInfo_t> &vtf ) { const char *pShaderName = pKeyValues->GetName(); /* if ( Q_stristr( pShaderName, "Water" ) || Q_stristr( pShaderName, "Eyeball" ) || Q_stristr( pShaderName, "Shadow" ) || Q_stristr( pShaderName, "Refract" ) || Q_stristr( pShaderName, "Predator" ) || Q_stristr( pShaderName, "ParticleSphere" ) || Q_stristr( pShaderName, "DebugLuxels" ) || Q_stristr( pShaderName, "GooInGlass" ) || Q_stristr( pShaderName, "Modulate" ) || Q_stristr( pShaderName, "UnlitTwoTexture" ) || Q_stristr( pShaderName, "Cloud" ) || Q_stristr( pShaderName, "WorldVertexTransition" ) || Q_stristr( pShaderName, "DecalModulate" ) || Q_stristr( pShaderName, "DecalBaseTimesLightmapAlphaBlendSelfIllum" ) || Q_stristr( pShaderName, "Sprite" ) ) { return; } // Check for alpha channels const char *pBaseTextureName = pKeyValues->GetString( "$basetexture", NULL ); if ( pBaseTextureName != NULL ) { if ( DoesTextureUseAlpha( pBaseTextureName, pFileName ) ) { float flAlpha = MaterialFloatKeyValue( pKeyValues, "$alpha", 1.0f ); bool bHasVertexAlpha = DoesMaterialHaveKey( pKeyValues, "$vertexalpha" ); // Modulation always happens here whether we want it to or not bool bHasAlphaTest = DoesMaterialHaveKey( pKeyValues, "$alphatest" ); bool bHasTranslucent = DoesMaterialHaveKey( pKeyValues, "$translucent" ); bool bHasSelfIllum = DoesMaterialHaveKey( pKeyValues, "$selfillum" ); bool bHasBaseAlphaEnvMapMask = DoesMaterialHaveKey( pKeyValues, "$basealphaenvmapmask" ); if ( (flAlpha == 1.0f) && !bHasVertexAlpha && !bHasAlphaTest && !bHasTranslucent && !bHasSelfIllum && !bHasBaseAlphaEnvMapMask ) { Warning("Material \"%s\": BASETEXTURE \"%s\"\n", pFileName, pBaseTextureName ); } } } */ /* // Check for bump, spec, and no normalmapalphaenvmapmask const char *pBumpmapName = pKeyValues->GetString( "$bumpmap", NULL ); if ( pBumpmapName != NULL ) { if ( DoesTextureUseAlpha( pBumpmapName, pFileName ) ) { bool bHasEnvmap = DoesMaterialHaveKey( pKeyValues, "$envmap" ); bool bHasNormalMapAlphaEnvMapMask = DoesMaterialHaveKey( pKeyValues, "$normalmapalphaenvmapmask" ); if ( !bHasEnvmap || !bHasNormalMapAlphaEnvMapMask ) { Warning("Material \"%s\": BUMPMAP \"%s\"\n", pFileName, pBumpmapName ); } } } */ /* if ( !Q_stristr( pShaderName, "LightmappedGeneric" ) && !Q_stristr( pShaderName, "VertexLitGeneric" ) ) { return; } if ( DoesMaterialHaveKey( pKeyValues, "$envmap" ) && DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) ) { int nDim; float retVal[4]; float defaultVal[4] = { 1, 1, 1, 1 }; if ( MaterialVectorKeyValue( pKeyValues, "$envmaptint", 3, defaultVal, &nDim, retVal ) ) { Warning("ENVMAP + ENVMAPTINT : Material \"%s\"\n", pFileName ); } // else // { // Warning("ENVMAP only: Material \"%s\"\n", pFileName ); // } } */ /* if ( !Q_stristr( pShaderName, "Refract" ) ) { return; } if ( !DoesMaterialHaveKey( pKeyValues, "$envmap" ) ) { bool bUsesAlpha, bIsCompressed, bIsPalettized; int nSizeInBytes; if ( DoesTextureUseNormal( pKeyValues->GetString( "$normalmap" ), pFileName, bUsesAlpha, bIsCompressed, bIsPalettized, nSizeInBytes ) ) { if ( bIsCompressed ) { Warning("Bad : Material compressed \"%s\"\n", pFileName ); } else { Warning("Bad : Material \"%s\"\n", pFileName ); } } } */ /* if ( !Q_stristr( pShaderName, "WorldTwoTextureBlend" ) ) { return; } if ( DoesMaterialHaveKey( pKeyValues, "$envmap" ) || DoesMaterialHaveKey( pKeyValues, "$parallaxmap" ) || DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) || DoesMaterialHaveKey( pKeyValues, "$vertexcolor" ) || DoesMaterialHaveKey( pKeyValues, "$basetexture2" ) ) { Warning("Bad : Material \"%s\"\n", pFileName ); } */ for ( KeyValues *pSubKey = pKeyValues->GetFirstValue(); pSubKey; pSubKey = pSubKey->GetNextValue() ) { // Msg( " Checking %s\n", pSubKey->GetString() ); if ( pSubKey->GetDataType() != KeyValues::TYPE_STRING ) continue; bool bUsesAlpha, bIsCompressed; int nSizeInBytes; if ( DoesTextureUseNormal( pSubKey->GetString(), pFileName, bUsesAlpha, bIsCompressed, nSizeInBytes ) ) { if ( bUsesAlpha ) { if ( bIsCompressed ) { s_nNormalWithAlphaCompressedBytes += nSizeInBytes; } else { s_nNormalWithAlphaBytes += nSizeInBytes; Msg( "Normal texture w alpha uncompressed %s\n", pSubKey->GetString() ); } } else { if ( bIsCompressed ) { s_nNormalCompressedBytes += nSizeInBytes; } else { s_nNormalBytes += nSizeInBytes; } } } } /* if ( !Q_stristr( pShaderName, "VertexLitGeneric" ) ) return; if ( !DoesMaterialHaveKey( pKeyValues, "$envmap" ) && DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) ) { Warning("BUMPMAP + no ENVMAP : Material \"%s\"\n", pFileName ); } */ // CheckKeyValues( pKeyValues, vtf ); } //----------------------------------------------------------------------------- // Build list of all VTFs //----------------------------------------------------------------------------- void CheckVTFInDirectoryRecursive( const char *pRoot, const char *pDirectory, CUtlVector< VTFInfo_t > &vtf ) { #define BUF_SIZE 1024 char buf[BUF_SIZE]; WIN32_FIND_DATA wfd; HANDLE findHandle; sprintf( buf, "%s/%s/*.vtf", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { int i = vtf.AddToTail( ); char buf[MAX_PATH]; char buf2[MAX_PATH]; Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName ); Q_FixSlashes( buf ); Q_StripExtension( buf, buf2, sizeof(buf2) ); Assert( !Q_strnicmp( buf2, "materials\\", 10 ) ); vtf[i].m_VTFName = &buf2[10]; vtf[i].m_bFoundInVMT = false; } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } // do subdirectories sprintf( buf, "%s/%s/*.*", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { if( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if( ( strcmp( wfd.cFileName, ".." ) == 0 ) || ( strcmp( wfd.cFileName, "." ) == 0 ) ) { continue; } char buf[MAX_PATH]; Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName ); CheckVTFInDirectoryRecursive( pRoot, buf, vtf ); } } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } #undef BUF_SIZE } //----------------------------------------------------------------------------- // Scan all materials for errors //----------------------------------------------------------------------------- void _CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory, CUtlVector< VTFInfo_t > &vtf ) { #define BUF_SIZE 1024 char buf[BUF_SIZE]; WIN32_FIND_DATA wfd; HANDLE findHandle; sprintf( buf, "%s/%s/*.vmt", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { KeyValues * vmtKeyValues = new KeyValues("vmt"); char pFileName[MAX_PATH]; Q_snprintf( pFileName, sizeof( pFileName ), "%s/%s", pDirectory, wfd.cFileName ); if ( !vmtKeyValues->LoadFromFile( g_pFullFileSystem, pFileName, "GAME" ) ) { Warning( "CheckMateralsInDirectoryRecursive: can't open \"%s\"\n", pFileName ); continue; } CheckMaterial( vmtKeyValues, pRoot, pFileName, vtf ); vmtKeyValues->deleteThis(); } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } // do subdirectories sprintf( buf, "%s/%s/*.*", pRoot, pDirectory ); findHandle = FindFirstFile( buf, &wfd ); if ( findHandle != INVALID_HANDLE_VALUE ) { do { if( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if( ( strcmp( wfd.cFileName, ".." ) == 0 ) || ( strcmp( wfd.cFileName, "." ) == 0 ) ) { continue; } char buf[MAX_PATH]; Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName ); _CheckMateralsInDirectoryRecursive( pRoot, buf, vtf ); } } while ( FindNextFile ( findHandle, &wfd ) ); FindClose ( findHandle ); } // Msg( "Normal only %d/%d/%d Normal w alpha %d/%d\n", s_nNormalBytes, s_nNormalPalettizedBytes, s_nNormalCompressedBytes, s_nNormalWithAlphaBytes, s_nNormalWithAlphaCompressedBytes ); #undef BUF_SIZE } void CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory ) { CUtlVector< VTFInfo_t > vtfNames; // CheckVTFInDirectoryRecursive( pRoot, pDirectory, vtfNames ); _CheckMateralsInDirectoryRecursive( pRoot, pDirectory, vtfNames ); /* int nCount = vtfNames.Count(); for ( int i = 0; i < nCount; ++i ) { if ( !vtfNames[i].m_bFoundInVMT ) { Msg( "Unused VTF %s\n", vtfNames[i].m_VTFName ); } } */ } #endif // _CHECK_MATERIALS_FOR_PROBLEMS
28.111278
184
0.626993
cstom4994
8d66d37fee5dcf53c2a2864894cf5d9dc2201831
4,844
cc
C++
tests/whitebox/db/wb_redis_db.cc
rohitjoshi/waflz
220945e6472762af8d8d7e0849699adcfd488605
[ "Apache-2.0" ]
null
null
null
tests/whitebox/db/wb_redis_db.cc
rohitjoshi/waflz
220945e6472762af8d8d7e0849699adcfd488605
[ "Apache-2.0" ]
null
null
null
tests/whitebox/db/wb_redis_db.cc
rohitjoshi/waflz
220945e6472762af8d8d7e0849699adcfd488605
[ "Apache-2.0" ]
null
null
null
//: ---------------------------------------------------------------------------- //: Copyright (C) 2016 Verizon. All Rights Reserved. //: All Rights Reserved //: //: \file: TODO.cc //: \details: TODO //: \author: Reed P. Morrison //: \date: 12/06/2016 //: //: 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. //: //: ---------------------------------------------------------------------------- //: ---------------------------------------------------------------------------- //: includes //: ---------------------------------------------------------------------------- #include "catch/catch.hpp" #include "waflz/def.h" #include "waflz/db/redis_db.h" #include "support/time_util.h" #include "support/ndebug.h" #include <unistd.h> #include <string.h> //: ---------------------------------------------------------------------------- //: constants //: ---------------------------------------------------------------------------- #define MONKEY_KEY "TEST::KEY::MONKEY::BONGO" #define BANANA_KEY "TEST::KEY::BANANA::SMELLY" //: ---------------------------------------------------------------------------- //: kycb_db //: ---------------------------------------------------------------------------- TEST_CASE( "redis db test", "[redis]" ) { SECTION("validate bad init") { ns_waflz::redis_db l_db; REQUIRE((l_db.get_init() == false)); const char l_bad_host[] = "128.0.0.1"; int32_t l_s; l_s = l_db.set_opt(ns_waflz::redis_db::OPT_REDIS_HOST, l_bad_host, strlen(l_bad_host)); REQUIRE((l_s == WAFLZ_STATUS_OK)); l_s = l_db.init(); REQUIRE((l_s == WAFLZ_STATUS_ERROR)); //printf("error: %s\n", l_db.get_err_msg()); } SECTION("validate good init") { ns_waflz::redis_db l_db; REQUIRE((l_db.get_init() == false)); const char l_host[] = "127.0.0.1"; int32_t l_s; l_s = l_db.set_opt(ns_waflz::redis_db::OPT_REDIS_HOST, l_host, strlen(l_host)); l_s = l_db.set_opt(ns_waflz::redis_db::OPT_REDIS_PORT, NULL, 6379); REQUIRE((l_s == WAFLZ_STATUS_OK)); l_s = l_db.init(); REQUIRE((l_s == WAFLZ_STATUS_OK)); int64_t l_val; l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 1)); l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 2)); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 1)); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); //NDBG_PRINT("PRINT ALL KEYS\n"); //l_db.print_all_keys(); l_s = l_db.get_key(l_val, MONKEY_KEY, strlen(MONKEY_KEY)); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 2)); l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //printf("l_val: %ld\n", l_val); REQUIRE((l_val == 3)); l_s = l_db.increment_key(l_val, BANANA_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 4)); //sprintf("error: %s\n", l_db.get_err_msg()); // wait for monkey key to expire sleep(1); l_s = l_db.get_key(l_val, MONKEY_KEY, strlen(MONKEY_KEY)); REQUIRE((l_s == WAFLZ_STATUS_ERROR)); l_s = l_db.increment_key(l_val, MONKEY_KEY, 1000); REQUIRE((l_s == WAFLZ_STATUS_OK)); //NDBG_PRINT("l_val: %ld\n", l_val); REQUIRE((l_val == 1)); } }
47.029126
103
0.469447
rohitjoshi
8d6cb3dee50f6e889499ed9969d9f70c016d518e
752
cpp
C++
test/transducer/remove.cpp
Yohsi/zug
ec11ca4642c51eb07de76a5b4a3b90a675cc428e
[ "BSL-1.0" ]
163
2019-11-19T20:58:55.000Z
2022-03-07T10:30:10.000Z
test/transducer/remove.cpp
Yohsi/zug
ec11ca4642c51eb07de76a5b4a3b90a675cc428e
[ "BSL-1.0" ]
26
2019-09-16T18:09:44.000Z
2022-01-25T10:04:13.000Z
test/transducer/remove.cpp
Yohsi/zug
ec11ca4642c51eb07de76a5b4a3b90a675cc428e
[ "BSL-1.0" ]
16
2019-09-08T15:22:18.000Z
2022-02-11T20:33:04.000Z
// // zug: transducers for C++ // Copyright (C) 2019 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #include <catch2/catch.hpp> #include <zug/compose.hpp> #include <zug/transduce.hpp> #include <zug/transducer/map.hpp> #include <zug/transducer/remove.hpp> #include <zug/util.hpp> using namespace zug; TEST_CASE("remove, simple") { // example1 { auto v = std::vector<int>{1, 2, 3, 6}; auto times2 = [](int x) { return x * 2; }; auto odd = [](int x) { return x % 2 == 0; }; auto res = transduce(remove(odd) | map(times2), std::plus<int>{}, 1, v); CHECK(res == 9); // } }
25.931034
79
0.631649
Yohsi
8d6e3fb5d66937ef9de5f31123ca3d62f514b952
1,343
cpp
C++
source/hougfx/test/hou/gfx/test_text_box_formatting_params.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/test/hou/gfx/test_text_box_formatting_params.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/test/hou/gfx/test_text_box_formatting_params.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/test.hpp" #include "hou/gfx/text_box_formatting_params.hpp" using namespace hou; using namespace testing; namespace { class test_text_box_formatting_params : public Test {}; } // namespace TEST_F(test_text_box_formatting_params, constructor) { text_flow text_flow_ref = text_flow::left_right; vec2f max_size_ref(1.f, 2.f); text_box_formatting_params tbfp(text_flow_ref, max_size_ref); EXPECT_EQ(text_flow_ref, tbfp.get_text_flow()); EXPECT_FLOAT_CLOSE(max_size_ref, tbfp.get_max_size()); } TEST_F(test_text_box_formatting_params, text_flow_values) { std::vector<text_flow> text_flow_values{text_flow::left_right, text_flow::right_left, text_flow::top_bottom, text_flow::bottom_top}; for(auto textFlow : text_flow_values) { text_box_formatting_params tbfp(textFlow, vec2f::zero()); EXPECT_EQ(textFlow, tbfp.get_text_flow()); } } TEST_F(test_text_box_formatting_params, max_size_values) { std::vector<vec2f> max_size_values{ vec2f(-1.f, -2.f), vec2f::zero(), vec2f(1.f, 2.f), vec2f(1024.5f, 768.25f), }; for(auto max_size : max_size_values) { text_box_formatting_params tbfp(text_flow::left_right, max_size); EXPECT_EQ(max_size, tbfp.get_max_size()); } }
21.31746
73
0.743857
DavideCorradiDev
8d724197a25d463b41babf68fd595e0f1a389599
42,743
cpp
C++
pkgs/apps/fluidanimate/src/pthreads.cpp
mariobadr/parsec-benchmarks
df65311b02d96fc6525fd49cf915a1885987d5a1
[ "BSD-3-Clause" ]
null
null
null
pkgs/apps/fluidanimate/src/pthreads.cpp
mariobadr/parsec-benchmarks
df65311b02d96fc6525fd49cf915a1885987d5a1
[ "BSD-3-Clause" ]
null
null
null
pkgs/apps/fluidanimate/src/pthreads.cpp
mariobadr/parsec-benchmarks
df65311b02d96fc6525fd49cf915a1885987d5a1
[ "BSD-3-Clause" ]
null
null
null
//Code written by Richard O. Lee and Christian Bienia //Modified by Christian Fensch #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #if defined(WIN32) #define NOMINMAX #include <windows.h> #endif #include <math.h> #include <pthread.h> #include <assert.h> #include <float.h> #include "fluid.hpp" #include "cellpool.hpp" #include <pthread.h> #ifdef ENABLE_VISUALIZATION #include "fluidview.hpp" #endif #ifdef ENABLE_PARSEC_HOOKS #include <hooks.h> #endif //Uncomment to add code to check that Courant–Friedrichs–Lewy condition is satisfied at runtime //#define ENABLE_CFL_CHECK //////////////////////////////////////////////////////////////////////////////// cellpool *pools; //each thread has its private cell pool fptype restParticlesPerMeter, h, hSq; fptype densityCoeff, pressureCoeff, viscosityCoeff; int nx, ny, nz; // number of grid cells in each dimension Vec3 delta; // cell dimensions int numParticles = 0; int numCells = 0; Cell *cells = 0; Cell *cells2 = 0; int *cnumPars = 0; int *cnumPars2 = 0; Cell **last_cells = NULL; //helper array with pointers to last cell structure of "cells" array lists #ifdef ENABLE_VISUALIZATION Vec3 vMax(0.0,0.0,0.0); Vec3 vMin(0.0,0.0,0.0); #endif int XDIVS = 1; // number of partitions in X int ZDIVS = 1; // number of partitions in Z #define NUM_GRIDS ((XDIVS) * (ZDIVS)) #define MUTEXES_PER_CELL 1 #define CELL_MUTEX_ID 0 struct Grid { union { struct { int sx, sy, sz; int ex, ey, ez; }; unsigned char pp[CACHELINE_SIZE]; }; } *grids; bool *border; pthread_attr_t attr; pthread_t *thread; pthread_mutex_t **mutex; // used to lock cells in RebuildGrid and also particles in other functions pthread_barrier_t barrier; // global barrier used by all threads #ifdef ENABLE_VISUALIZATION pthread_barrier_t visualization_barrier; // global barrier to separate (serial) visualization phase from (parallel) fluid simulation #endif typedef struct __thread_args { int tid; //thread id, determines work partition int frames; //number of frames to compute } thread_args; //arguments for threads //////////////////////////////////////////////////////////////////////////////// /* * hmgweight * * Computes the hamming weight of x * * x - input value * lsb - if x!=0 position of smallest bit set, else -1 * * return - the hamming weight */ unsigned int hmgweight(unsigned int x, int *lsb) { unsigned int weight=0; unsigned int mask= 1; unsigned int count=0; *lsb=-1; while(x > 0) { unsigned int temp; temp=(x&mask); if((x&mask) == 1) { weight++; if(*lsb == -1) *lsb = count; } x >>= 1; count++; } return weight; } void InitSim(char const *fileName, unsigned int threadnum) { //Compute partitioning based on square root of number of threads //NOTE: Other partition sizes are possible as long as XDIVS * ZDIVS == threadnum, // but communication is minimal (and hence optimal) if XDIVS == ZDIVS int lsb; if(hmgweight(threadnum,&lsb) != 1) { std::cerr << "Number of threads must be a power of 2" << std::endl; exit(1); } XDIVS = 1<<(lsb/2); ZDIVS = 1<<(lsb/2); if(XDIVS*ZDIVS != threadnum) XDIVS*=2; assert(XDIVS * ZDIVS == threadnum); thread = new pthread_t[NUM_GRIDS]; grids = new struct Grid[NUM_GRIDS]; assert(sizeof(Grid) <= CACHELINE_SIZE); // as we put and aligh grid on the cacheline size to avoid false-sharing // if asserts fails - increase pp union member in Grid declarationi // and change this macro pools = new cellpool[NUM_GRIDS]; //Load input particles std::cout << "Loading file \"" << fileName << "\"..." << std::endl; std::ifstream file(fileName, std::ios::binary); if(!file) { std::cerr << "Error opening file. Aborting." << std::endl; exit(1); } //Always use single precision float variables b/c file format uses single precision float restParticlesPerMeter_le; int numParticles_le; file.read((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT); file.read((char *)&numParticles_le, FILE_SIZE_INT); if(!isLittleEndian()) { restParticlesPerMeter = bswap_float(restParticlesPerMeter_le); numParticles = bswap_int32(numParticles_le); } else { restParticlesPerMeter = restParticlesPerMeter_le; numParticles = numParticles_le; } for(int i=0; i<NUM_GRIDS; i++) cellpool_init(&pools[i], numParticles/NUM_GRIDS); h = kernelRadiusMultiplier / restParticlesPerMeter; hSq = h*h; #ifndef ENABLE_DOUBLE_PRECISION fptype coeff1 = 315.0 / (64.0*pi*powf(h,9.0)); fptype coeff2 = 15.0 / (pi*powf(h,6.0)); fptype coeff3 = 45.0 / (pi*powf(h,6.0)); #else fptype coeff1 = 315.0 / (64.0*pi*pow(h,9.0)); fptype coeff2 = 15.0 / (pi*pow(h,6.0)); fptype coeff3 = 45.0 / (pi*pow(h,6.0)); #endif //ENABLE_DOUBLE_PRECISION fptype particleMass = 0.5*doubleRestDensity / (restParticlesPerMeter*restParticlesPerMeter*restParticlesPerMeter); densityCoeff = particleMass * coeff1; pressureCoeff = 3.0*coeff2 * 0.50*stiffnessPressure * particleMass; viscosityCoeff = viscosity * coeff3 * particleMass; Vec3 range = domainMax - domainMin; nx = (int)(range.x / h); ny = (int)(range.y / h); nz = (int)(range.z / h); assert(nx >= 1 && ny >= 1 && nz >= 1); numCells = nx*ny*nz; std::cout << "Number of cells: " << numCells << std::endl; delta.x = range.x / nx; delta.y = range.y / ny; delta.z = range.z / nz; assert(delta.x >= h && delta.y >= h && delta.z >= h); std::cout << "Grids steps over x, y, z: " << delta.x << " " << delta.y << " " << delta.z << std::endl; assert(nx >= XDIVS && nz >= ZDIVS); int gi = 0; int sx, sz, ex, ez; ex = 0; for(int i = 0; i < XDIVS; ++i) { sx = ex; ex = (int)((fptype)(nx)/(fptype)(XDIVS) * (i+1) + 0.5); assert(sx < ex); ez = 0; for(int j = 0; j < ZDIVS; ++j, ++gi) { sz = ez; ez = (int)((fptype)(nz)/(fptype)(ZDIVS) * (j+1) + 0.5); assert(sz < ez); grids[gi].sx = sx; grids[gi].ex = ex; grids[gi].sy = 0; grids[gi].ey = ny; grids[gi].sz = sz; grids[gi].ez = ez; } } assert(gi == NUM_GRIDS); border = new bool[numCells]; for(int i = 0; i < NUM_GRIDS; ++i) for(int iz = grids[i].sz; iz < grids[i].ez; ++iz) for(int iy = grids[i].sy; iy < grids[i].ey; ++iy) for(int ix = grids[i].sx; ix < grids[i].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; border[index] = false; for(int dk = -1; dk <= 1; ++dk) { for(int dj = -1; dj <= 1; ++dj) { for(int di = -1; di <= 1; ++di) { int ci = ix + di; int cj = iy + dj; int ck = iz + dk; if(ci < 0) ci = 0; else if(ci > (nx-1)) ci = nx-1; if(cj < 0) cj = 0; else if(cj > (ny-1)) cj = ny-1; if(ck < 0) ck = 0; else if(ck > (nz-1)) ck = nz-1; if( ci < grids[i].sx || ci >= grids[i].ex || cj < grids[i].sy || cj >= grids[i].ey || ck < grids[i].sz || ck >= grids[i].ez ) { border[index] = true; break; } } // for(int di = -1; di <= 1; ++di) if(border[index]) break; } // for(int dj = -1; dj <= 1; ++dj) if(border[index]) break; } // for(int dk = -1; dk <= 1; ++dk) } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); mutex = new pthread_mutex_t *[numCells]; for(int i = 0; i < numCells; ++i) { assert(CELL_MUTEX_ID < MUTEXES_PER_CELL); int n = (border[i] ? MUTEXES_PER_CELL : CELL_MUTEX_ID+1); mutex[i] = new pthread_mutex_t[n]; for(int j = 0; j < n; ++j) pthread_mutex_init(&mutex[i][j], NULL); } pthread_barrier_init(&barrier, NULL, NUM_GRIDS); #ifdef ENABLE_VISUALIZATION //visualization barrier is used by all NUM_GRIDS worker threads and 1 master thread pthread_barrier_init(&visualization_barrier, NULL, NUM_GRIDS+1); #endif //make sure Cell structure is multiple of estiamted cache line size assert(sizeof(Cell) % CACHELINE_SIZE == 0); //make sure helper Cell structure is in sync with real Cell structure assert(offsetof(struct Cell_aux, padding) == offsetof(struct Cell, padding)); #if defined(WIN32) cells = (struct Cell*)_aligned_malloc(sizeof(struct Cell) * numCells, CACHELINE_SIZE); cells2 = (struct Cell*)_aligned_malloc(sizeof(struct Cell) * numCells, CACHELINE_SIZE); cnumPars = (int*)_aligned_malloc(sizeof(int) * numCells, CACHELINE_SIZE); cnumPars2 = (int*)_aligned_malloc(sizeof(int) * numCells, CACHELINE_SIZE); last_cells = (struct Cell **)_aligned_malloc(sizeof(struct Cell *) * numCells, CACHELINE_SIZE); assert((cells!=NULL) && (cells2!=NULL) && (cnumPars!=NULL) && (cnumPars2!=NULL) && (last_cells!=NULL)); #elif defined(SPARC_SOLARIS) cells = (Cell*)memalign(CACHELINE_SIZE, sizeof(struct Cell) * numCells); cells2 = (Cell*)memalign(CACHELINE_SIZE, sizeof(struct Cell) * numCells); cnumPars = (int*)memalign(CACHELINE_SIZE, sizeof(int) * numCells); cnumPars2 = (int*)memalign(CACHELINE_SIZE, sizeof(int) * numCells); last_cells = (Cell**)memalign(CACHELINE_SIZE, sizeof(struct Cell *) * numCells); assert((cells!=0) && (cells2!=0) && (cnumPars!=0) && (cnumPars2!=0) && (last_cells!=0)); #else int rv0 = posix_memalign((void **)(&cells), CACHELINE_SIZE, sizeof(struct Cell) * numCells); int rv1 = posix_memalign((void **)(&cells2), CACHELINE_SIZE, sizeof(struct Cell) * numCells); int rv2 = posix_memalign((void **)(&cnumPars), CACHELINE_SIZE, sizeof(int) * numCells); int rv3 = posix_memalign((void **)(&cnumPars2), CACHELINE_SIZE, sizeof(int) * numCells); int rv4 = posix_memalign((void **)(&last_cells), CACHELINE_SIZE, sizeof(struct Cell *) * numCells); assert((rv0==0) && (rv1==0) && (rv2==0) && (rv3==0) && (rv4==0)); #endif // because cells and cells2 are not allocated via new // we construct them here for(int i=0; i<numCells; ++i) { new (&cells[i]) Cell; new (&cells2[i]) Cell; } memset(cnumPars, 0, numCells*sizeof(int)); //Always use single precision float variables b/c file format uses single precision float int pool_id = 0; float px, py, pz, hvx, hvy, hvz, vx, vy, vz; for(int i = 0; i < numParticles; ++i) { file.read((char *)&px, FILE_SIZE_FLOAT); file.read((char *)&py, FILE_SIZE_FLOAT); file.read((char *)&pz, FILE_SIZE_FLOAT); file.read((char *)&hvx, FILE_SIZE_FLOAT); file.read((char *)&hvy, FILE_SIZE_FLOAT); file.read((char *)&hvz, FILE_SIZE_FLOAT); file.read((char *)&vx, FILE_SIZE_FLOAT); file.read((char *)&vy, FILE_SIZE_FLOAT); file.read((char *)&vz, FILE_SIZE_FLOAT); if(!isLittleEndian()) { px = bswap_float(px); py = bswap_float(py); pz = bswap_float(pz); hvx = bswap_float(hvx); hvy = bswap_float(hvy); hvz = bswap_float(hvz); vx = bswap_float(vx); vy = bswap_float(vy); vz = bswap_float(vz); } int ci = (int)((px - domainMin.x) / delta.x); int cj = (int)((py - domainMin.y) / delta.y); int ck = (int)((pz - domainMin.z) / delta.z); if(ci < 0) ci = 0; else if(ci > (nx-1)) ci = nx-1; if(cj < 0) cj = 0; else if(cj > (ny-1)) cj = ny-1; if(ck < 0) ck = 0; else if(ck > (nz-1)) ck = nz-1; int index = (ck*ny + cj)*nx + ci; Cell *cell = &cells[index]; //go to last cell structure in list int np = cnumPars[index]; while(np > PARTICLES_PER_CELL) { cell = cell->next; np = np - PARTICLES_PER_CELL; } //add another cell structure if everything full if( (np % PARTICLES_PER_CELL == 0) && (cnumPars[index] != 0) ) { //Get cells from pools in round-robin fashion to balance load during parallel phase cell->next = cellpool_getcell(&pools[pool_id]); pool_id = (pool_id+1) % NUM_GRIDS; cell = cell->next; np = np - PARTICLES_PER_CELL; } cell->p[np].x = px; cell->p[np].y = py; cell->p[np].z = pz; cell->hv[np].x = hvx; cell->hv[np].y = hvy; cell->hv[np].z = hvz; cell->v[np].x = vx; cell->v[np].y = vy; cell->v[np].z = vz; #ifdef ENABLE_VISUALIZATION vMin.x = std::min(vMin.x, cell->v[np].x); vMax.x = std::max(vMax.x, cell->v[np].x); vMin.y = std::min(vMin.y, cell->v[np].y); vMax.y = std::max(vMax.y, cell->v[np].y); vMin.z = std::min(vMin.z, cell->v[np].z); vMax.z = std::max(vMax.z, cell->v[np].z); #endif ++cnumPars[index]; } std::cout << "Number of particles: " << numParticles << std::endl; } //////////////////////////////////////////////////////////////////////////////// void SaveFile(char const *fileName) { std::cout << "Saving file \"" << fileName << "\"..." << std::endl; std::ofstream file(fileName, std::ios::binary); assert(file); //Always use single precision float variables b/c file format uses single precision if(!isLittleEndian()) { float restParticlesPerMeter_le; int numParticles_le; restParticlesPerMeter_le = bswap_float((float)restParticlesPerMeter); numParticles_le = bswap_int32(numParticles); file.write((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT); file.write((char *)&numParticles_le, FILE_SIZE_INT); } else { file.write((char *)&restParticlesPerMeter, FILE_SIZE_FLOAT); file.write((char *)&numParticles, FILE_SIZE_INT); } int count = 0; for(int i = 0; i < numCells; ++i) { Cell *cell = &cells[i]; int np = cnumPars[i]; for(int j = 0; j < np; ++j) { //Always use single precision float variables b/c file format uses single precision float px, py, pz, hvx, hvy, hvz, vx,vy, vz; if(!isLittleEndian()) { px = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].x)); py = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].y)); pz = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].z)); hvx = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].x)); hvy = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].y)); hvz = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].z)); vx = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].x)); vy = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].y)); vz = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].z)); } else { px = (float)(cell->p[j % PARTICLES_PER_CELL].x); py = (float)(cell->p[j % PARTICLES_PER_CELL].y); pz = (float)(cell->p[j % PARTICLES_PER_CELL].z); hvx = (float)(cell->hv[j % PARTICLES_PER_CELL].x); hvy = (float)(cell->hv[j % PARTICLES_PER_CELL].y); hvz = (float)(cell->hv[j % PARTICLES_PER_CELL].z); vx = (float)(cell->v[j % PARTICLES_PER_CELL].x); vy = (float)(cell->v[j % PARTICLES_PER_CELL].y); vz = (float)(cell->v[j % PARTICLES_PER_CELL].z); } file.write((char *)&px, FILE_SIZE_FLOAT); file.write((char *)&py, FILE_SIZE_FLOAT); file.write((char *)&pz, FILE_SIZE_FLOAT); file.write((char *)&hvx, FILE_SIZE_FLOAT); file.write((char *)&hvy, FILE_SIZE_FLOAT); file.write((char *)&hvz, FILE_SIZE_FLOAT); file.write((char *)&vx, FILE_SIZE_FLOAT); file.write((char *)&vy, FILE_SIZE_FLOAT); file.write((char *)&vz, FILE_SIZE_FLOAT); ++count; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } assert(count == numParticles); } //////////////////////////////////////////////////////////////////////////////// void CleanUpSim() { // first return extended cells to cell pools for(int i=0; i< numCells; ++i) { Cell& cell = cells[i]; while(cell.next) { Cell *temp = cell.next; cell.next = temp->next; cellpool_returncell(&pools[0], temp); } } // now return cell pools //NOTE: Cells from cell pools can migrate to different pools during the parallel phase. // This is no problem as long as all cell pools are destroyed together. Each pool // uses its internal meta information to free exactly the cells which it allocated // itself. This guarantees that all allocated cells will be freed but it might // render other cell pools unusable so they also have to be destroyed. for(int i=0; i<NUM_GRIDS; i++) cellpool_destroy(&pools[i]); pthread_attr_destroy(&attr); for(int i = 0; i < numCells; ++i) { assert(CELL_MUTEX_ID < MUTEXES_PER_CELL); int n = (border[i] ? MUTEXES_PER_CELL : CELL_MUTEX_ID+1); for(int j = 0; j < n; ++j) pthread_mutex_destroy(&mutex[i][j]); delete[] mutex[i]; } delete[] mutex; pthread_barrier_destroy(&barrier); #ifdef ENABLE_VISUALIZATION pthread_barrier_destroy(&visualization_barrier); #endif delete[] border; #if defined(WIN32) _aligned_free(cells); _aligned_free(cells2); _aligned_free(cnumPars); _aligned_free(cnumPars2); _aligned_free(last_cells); #else free(cells); free(cells2); free(cnumPars); free(cnumPars2); free(last_cells); #endif delete[] thread; delete[] grids; } //////////////////////////////////////////////////////////////////////////////// void ClearParticlesMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; cnumPars[index] = 0; cells[index].next = NULL; last_cells[index] = &cells[index]; } } //////////////////////////////////////////////////////////////////////////////// void RebuildGridMT(int tid) { // Note, in parallel versions the below swaps // occure outside RebuildGrid() // swap src and dest arrays with particles // std::swap(cells, cells2); // swap src and dest arrays with counts of particles // std::swap(cnumPars, cnumPars2); //iterate through source cell lists for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index2 = (iz*ny + iy)*nx + ix; Cell *cell2 = &cells2[index2]; int np2 = cnumPars2[index2]; //iterate through source particles for(int j = 0; j < np2; ++j) { //get destination for source particle int ci = (int)((cell2->p[j % PARTICLES_PER_CELL].x - domainMin.x) / delta.x); int cj = (int)((cell2->p[j % PARTICLES_PER_CELL].y - domainMin.y) / delta.y); int ck = (int)((cell2->p[j % PARTICLES_PER_CELL].z - domainMin.z) / delta.z); if(ci < 0) ci = 0; else if(ci > (nx-1)) ci = nx-1; if(cj < 0) cj = 0; else if(cj > (ny-1)) cj = ny-1; if(ck < 0) ck = 0; else if(ck > (nz-1)) ck = nz-1; #if 0 assert(ci>=ix-1); assert(ci<=ix+1); assert(cj>=iy-1); assert(cj<=iy+1); assert(ck>=iz-1); assert(ck<=iz+1); #endif #ifdef ENABLE_CFL_CHECK //check that source cell is a neighbor of destination cell bool cfl_cond_satisfied=false; for(int di = -1; di <= 1; ++di) for(int dj = -1; dj <= 1; ++dj) for(int dk = -1; dk <= 1; ++dk) { int ii = ci + di; int jj = cj + dj; int kk = ck + dk; if(ii >= 0 && ii < nx && jj >= 0 && jj < ny && kk >= 0 && kk < nz) { int index = (kk*ny + jj)*nx + ii; if(index == index2) { cfl_cond_satisfied=true; break; } } } if(!cfl_cond_satisfied) { std::cerr << "FATAL ERROR: Courant–Friedrichs–Lewy condition not satisfied." << std::endl; exit(1); } #endif //ENABLE_CFL_CHECK int index = (ck*ny + cj)*nx + ci; // this assumes that particles cannot travel more than one grid cell per time step if(border[index]) pthread_mutex_lock(&mutex[index][CELL_MUTEX_ID]); Cell *cell = last_cells[index]; int np = cnumPars[index]; //add another cell structure if everything full if( (np % PARTICLES_PER_CELL == 0) && (cnumPars[index] != 0) ) { cell->next = cellpool_getcell(&pools[tid]); cell = cell->next; last_cells[index] = cell; } ++cnumPars[index]; if(border[index]) pthread_mutex_unlock(&mutex[index][CELL_MUTEX_ID]); //copy source to destination particle cell->p[np % PARTICLES_PER_CELL] = cell2->p[j % PARTICLES_PER_CELL]; cell->hv[np % PARTICLES_PER_CELL] = cell2->hv[j % PARTICLES_PER_CELL]; cell->v[np % PARTICLES_PER_CELL] = cell2->v[j % PARTICLES_PER_CELL]; //move pointer to next source cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { Cell *temp = cell2; cell2 = cell2->next; //return cells to pool that are not statically allocated head of lists if(temp != &cells2[index2]) { //NOTE: This is thread-safe because temp and pool are thread-private, no need to synchronize cellpool_returncell(&pools[tid], temp); } } } // for(int j = 0; j < np2; ++j) //return cells to pool that are not statically allocated head of lists if((cell2 != NULL) && (cell2 != &cells2[index2])) { cellpool_returncell(&pools[tid], cell2); } } } //////////////////////////////////////////////////////////////////////////////// int InitNeighCellList(int ci, int cj, int ck, int *neighCells) { int numNeighCells = 0; // have the nearest particles first -> help branch prediction int my_index = (ck*ny + cj)*nx + ci; neighCells[numNeighCells] = my_index; ++numNeighCells; for(int di = -1; di <= 1; ++di) for(int dj = -1; dj <= 1; ++dj) for(int dk = -1; dk <= 1; ++dk) { int ii = ci + di; int jj = cj + dj; int kk = ck + dk; if(ii >= 0 && ii < nx && jj >= 0 && jj < ny && kk >= 0 && kk < nz) { int index = (kk*ny + jj)*nx + ii; if((index < my_index) && (cnumPars[index] != 0)) { neighCells[numNeighCells] = index; ++numNeighCells; } } } return numNeighCells; } //////////////////////////////////////////////////////////////////////////////// void InitDensitiesAndForcesMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { cell->density[j % PARTICLES_PER_CELL] = 0.0; cell->a[j % PARTICLES_PER_CELL] = externalAcceleration; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void ComputeDensitiesMT(int tid) { int neighCells[3*3*3]; for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; int np = cnumPars[index]; if(np == 0) continue; int numNeighCells = InitNeighCellList(ix, iy, iz, neighCells); Cell *cell = &cells[index]; for(int ipar = 0; ipar < np; ++ipar) { for(int inc = 0; inc < numNeighCells; ++inc) { int indexNeigh = neighCells[inc]; Cell *neigh = &cells[indexNeigh]; int numNeighPars = cnumPars[indexNeigh]; for(int iparNeigh = 0; iparNeigh < numNeighPars; ++iparNeigh) { //Check address to make sure densities are computed only once per pair if(&neigh->p[iparNeigh % PARTICLES_PER_CELL] < &cell->p[ipar % PARTICLES_PER_CELL]) { fptype distSq = (cell->p[ipar % PARTICLES_PER_CELL] - neigh->p[iparNeigh % PARTICLES_PER_CELL]).GetLengthSq(); if(distSq < hSq) { fptype t = hSq - distSq; fptype tc = t*t*t; if(border[index]) { pthread_mutex_lock(&mutex[index][ipar % MUTEXES_PER_CELL]); cell->density[ipar % PARTICLES_PER_CELL] += tc; pthread_mutex_unlock(&mutex[index][ipar % MUTEXES_PER_CELL]); } else cell->density[ipar % PARTICLES_PER_CELL] += tc; if(border[indexNeigh]) { pthread_mutex_lock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); neigh->density[iparNeigh % PARTICLES_PER_CELL] += tc; pthread_mutex_unlock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); } else neigh->density[iparNeigh % PARTICLES_PER_CELL] += tc; } } //move pointer to next cell in list if end of array is reached if(iparNeigh % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { neigh = neigh->next; } } } //move pointer to next cell in list if end of array is reached if(ipar % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void ComputeDensities2MT(int tid) { const fptype tc = hSq*hSq*hSq; for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { cell->density[j % PARTICLES_PER_CELL] += tc; cell->density[j % PARTICLES_PER_CELL] *= densityCoeff; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void ComputeForcesMT(int tid) { int neighCells[3*3*3]; for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; int np = cnumPars[index]; if(np == 0) continue; int numNeighCells = InitNeighCellList(ix, iy, iz, neighCells); Cell *cell = &cells[index]; for(int ipar = 0; ipar < np; ++ipar) { for(int inc = 0; inc < numNeighCells; ++inc) { int indexNeigh = neighCells[inc]; Cell *neigh = &cells[indexNeigh]; int numNeighPars = cnumPars[indexNeigh]; for(int iparNeigh = 0; iparNeigh < numNeighPars; ++iparNeigh) { //Check address to make sure forces are computed only once per pair if(&neigh->p[iparNeigh % PARTICLES_PER_CELL] < &cell->p[ipar % PARTICLES_PER_CELL]) { Vec3 disp = cell->p[ipar % PARTICLES_PER_CELL] - neigh->p[iparNeigh % PARTICLES_PER_CELL]; fptype distSq = disp.GetLengthSq(); if(distSq < hSq) { #ifndef ENABLE_DOUBLE_PRECISION fptype dist = sqrtf(std::max(distSq, (fptype)1e-12)); #else fptype dist = sqrt(std::max(distSq, 1e-12)); #endif //ENABLE_DOUBLE_PRECISION fptype hmr = h - dist; Vec3 acc = disp * pressureCoeff * (hmr*hmr/dist) * (cell->density[ipar % PARTICLES_PER_CELL]+neigh->density[iparNeigh % PARTICLES_PER_CELL] - doubleRestDensity); acc += (neigh->v[iparNeigh % PARTICLES_PER_CELL] - cell->v[ipar % PARTICLES_PER_CELL]) * viscosityCoeff * hmr; acc /= cell->density[ipar % PARTICLES_PER_CELL] * neigh->density[iparNeigh % PARTICLES_PER_CELL]; if( border[index]) { pthread_mutex_lock(&mutex[index][ipar % MUTEXES_PER_CELL]); cell->a[ipar % PARTICLES_PER_CELL] += acc; pthread_mutex_unlock(&mutex[index][ipar % MUTEXES_PER_CELL]); } else cell->a[ipar % PARTICLES_PER_CELL] += acc; if( border[indexNeigh]) { pthread_mutex_lock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); neigh->a[iparNeigh % PARTICLES_PER_CELL] -= acc; pthread_mutex_unlock(&mutex[indexNeigh][iparNeigh % MUTEXES_PER_CELL]); } else neigh->a[iparNeigh % PARTICLES_PER_CELL] -= acc; } } //move pointer to next cell in list if end of array is reached if(iparNeigh % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { neigh = neigh->next; } } } //move pointer to next cell in list if end of array is reached if(ipar % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// // ProcessCollisions() with container walls // Under the assumptions that // a) a particle will not penetrate a wall // b) a particle will not migrate further than once cell // c) the parSize is smaller than a cell // then only the particles at the perimiters may be influenced by the walls #if 0 void ProcessCollisionsMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { Vec3 pos = cell->p[j % PARTICLES_PER_CELL] + cell->hv[j % PARTICLES_PER_CELL] * timeStep; fptype diff = parSize - (pos.x - domainMin.x); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].x += stiffnessCollisions*diff - damping*cell->v[j % PARTICLES_PER_CELL].x; diff = parSize - (domainMax.x - pos.x); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].x -= stiffnessCollisions*diff + damping*cell->v[j % PARTICLES_PER_CELL].x; diff = parSize - (pos.y - domainMin.y); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].y += stiffnessCollisions*diff - damping*cell->v[j % PARTICLES_PER_CELL].y; diff = parSize - (domainMax.y - pos.y); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].y -= stiffnessCollisions*diff + damping*cell->v[j % PARTICLES_PER_CELL].y; diff = parSize - (pos.z - domainMin.z); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].z += stiffnessCollisions*diff - damping*cell->v[j % PARTICLES_PER_CELL].z; diff = parSize - (domainMax.z - pos.z); if(diff > epsilon) cell->a[j % PARTICLES_PER_CELL].z -= stiffnessCollisions*diff + damping*cell->v[j % PARTICLES_PER_CELL].z; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } #else void ProcessCollisionsMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) { for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) { for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { if(!((ix==0)||(iy==0)||(iz==0)||(ix==(nx-1))||(iy==(ny-1))==(iz==(nz-1)))) continue; // not on domain wall int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { int ji = j % PARTICLES_PER_CELL; Vec3 pos = cell->p[ji] + cell->hv[ji] * timeStep; if(ix==0) { fptype diff = parSize - (pos.x - domainMin.x); if(diff > epsilon) cell->a[ji].x += stiffnessCollisions*diff - damping*cell->v[ji].x; } if(ix==(nx-1)) { fptype diff = parSize - (domainMax.x - pos.x); if(diff > epsilon) cell->a[ji].x -= stiffnessCollisions*diff + damping*cell->v[ji].x; } if(iy==0) { fptype diff = parSize - (pos.y - domainMin.y); if(diff > epsilon) cell->a[ji].y += stiffnessCollisions*diff - damping*cell->v[ji].y; } if(iy==(ny-1)) { fptype diff = parSize - (domainMax.y - pos.y); if(diff > epsilon) cell->a[ji].y -= stiffnessCollisions*diff + damping*cell->v[ji].y; } if(iz==0) { fptype diff = parSize - (pos.z - domainMin.z); if(diff > epsilon) cell->a[ji].z += stiffnessCollisions*diff - damping*cell->v[ji].z; } if(iz==(nz-1)) { fptype diff = parSize - (domainMax.z - pos.z); if(diff > epsilon) cell->a[ji].z -= stiffnessCollisions*diff + damping*cell->v[ji].z; } //move pointer to next cell in list if end of array is reached if(ji == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } } } #endif #define USE_ImpeneratableWall #if defined(USE_ImpeneratableWall) void ProcessCollisions2MT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) { for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) { for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { #if 0 // Chris, the following test should be valid // *** provided that a particle does not migrate more than 1 cell // *** per integration step. This does not appear to be the case // *** in the pthreads version. Serial version it seems to be OK if(!((ix==0)||(iy==0)||(iz==0)||(ix==(nx-1))||(iy==(ny-1))==(iz==(nz-1)))) continue; // not on domain wall #endif int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { int ji = j % PARTICLES_PER_CELL; Vec3 pos = cell->p[ji]; if(ix==0) { fptype diff = pos.x - domainMin.x; if(diff < Zero) { cell->p[ji].x = domainMin.x - diff; cell->v[ji].x = -cell->v[ji].x; cell->hv[ji].x = -cell->hv[ji].x; } } if(ix==(nx-1)) { fptype diff = domainMax.x - pos.x; if(diff < Zero) { cell->p[ji].x = domainMax.x + diff; cell->v[ji].x = -cell->v[ji].x; cell->hv[ji].x = -cell->hv[ji].x; } } if(iy==0) { fptype diff = pos.y - domainMin.y; if(diff < Zero) { cell->p[ji].y = domainMin.y - diff; cell->v[ji].y = -cell->v[ji].y; cell->hv[ji].y = -cell->hv[ji].y; } } if(iy==(ny-1)) { fptype diff = domainMax.y - pos.y; if(diff < Zero) { cell->p[ji].y = domainMax.y + diff; cell->v[ji].y = -cell->v[ji].y; cell->hv[ji].y = -cell->hv[ji].y; } } if(iz==0) { fptype diff = pos.z - domainMin.z; if(diff < Zero) { cell->p[ji].z = domainMin.z - diff; cell->v[ji].z = -cell->v[ji].z; cell->hv[ji].z = -cell->hv[ji].z; } } if(iz==(nz-1)) { fptype diff = domainMax.z - pos.z; if(diff < Zero) { cell->p[ji].z = domainMax.z + diff; cell->v[ji].z = -cell->v[ji].z; cell->hv[ji].z = -cell->hv[ji].z; } } //move pointer to next cell in list if end of array is reached if(ji == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } } } #endif //////////////////////////////////////////////////////////////////////////////// void AdvanceParticlesMT(int tid) { for(int iz = grids[tid].sz; iz < grids[tid].ez; ++iz) for(int iy = grids[tid].sy; iy < grids[tid].ey; ++iy) for(int ix = grids[tid].sx; ix < grids[tid].ex; ++ix) { int index = (iz*ny + iy)*nx + ix; Cell *cell = &cells[index]; int np = cnumPars[index]; for(int j = 0; j < np; ++j) { Vec3 v_half = cell->hv[j % PARTICLES_PER_CELL] + cell->a[j % PARTICLES_PER_CELL]*timeStep; #if defined(USE_ImpeneratableWall) // N.B. The integration of the position can place the particle // outside the domain. Although we could place a test in this loop // we would be unnecessarily testing particles on interior cells. // Therefore, to reduce the amount of computations we make a later // pass on the perimiter cells to account for particle migration // beyond domain #endif cell->p[j % PARTICLES_PER_CELL] += v_half * timeStep; cell->v[j % PARTICLES_PER_CELL] = cell->hv[j % PARTICLES_PER_CELL] + v_half; cell->v[j % PARTICLES_PER_CELL] *= 0.5; cell->hv[j % PARTICLES_PER_CELL] = v_half; //move pointer to next cell in list if end of array is reached if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) { cell = cell->next; } } } } //////////////////////////////////////////////////////////////////////////////// void AdvanceFrameMT(int tid) { //swap src and dest arrays with particles if(tid==0) { std::swap(cells, cells2); std::swap(cnumPars, cnumPars2); } pthread_barrier_wait(&barrier); ClearParticlesMT(tid); pthread_barrier_wait(&barrier); RebuildGridMT(tid); pthread_barrier_wait(&barrier); InitDensitiesAndForcesMT(tid); pthread_barrier_wait(&barrier); ComputeDensitiesMT(tid); pthread_barrier_wait(&barrier); ComputeDensities2MT(tid); pthread_barrier_wait(&barrier); ComputeForcesMT(tid); pthread_barrier_wait(&barrier); ProcessCollisionsMT(tid); pthread_barrier_wait(&barrier); AdvanceParticlesMT(tid); pthread_barrier_wait(&barrier); #if defined(USE_ImpeneratableWall) // N.B. The integration of the position can place the particle // outside the domain. We now make a pass on the perimiter cells // to account for particle migration beyond domain. ProcessCollisions2MT(tid); pthread_barrier_wait(&barrier); #endif } #ifndef ENABLE_VISUALIZATION void *AdvanceFramesMT(void *args) { thread_args *targs = (thread_args *)args; for(int i = 0; i < targs->frames; ++i) { AdvanceFrameMT(targs->tid); } return NULL; } #else //Frame advancement function for worker threads void *AdvanceFramesMT(void *args) { thread_args *targs = (thread_args *)args; #if 1 while(1) #else for(int i = 0; i < targs->frames; ++i) #endif { pthread_barrier_wait(&visualization_barrier); //Phase 1: Compute frame, visualization code blocked AdvanceFrameMT(targs->tid); pthread_barrier_wait(&visualization_barrier); //Phase 2: Visualize, worker threads blocked } return NULL; } //Frame advancement function for master thread (executes serial visualization code) void AdvanceFrameVisualization() { //End of phase 2: Worker threads blocked, visualization code busy (last frame) pthread_barrier_wait(&visualization_barrier); //Phase 1: Visualization thread blocked, worker threads busy (next frame) pthread_barrier_wait(&visualization_barrier); //Begin of phase 2: Worker threads blocked, visualization code busy (next frame) } #endif //ENABLE_VISUALIZATION //////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { #ifdef PARSEC_VERSION #define __PARSEC_STRING(x) #x #define __PARSEC_XSTRING(x) __PARSEC_STRING(x) std::cout << "PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION) << std::endl << std::flush; #else std::cout << "PARSEC Benchmark Suite" << std::endl << std::flush; #endif //PARSEC_VERSION #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_begin(__parsec_fluidanimate); #endif if(argc < 4 || argc >= 6) { std::cout << "Usage: " << argv[0] << " <threadnum> <framenum> <.fluid input file> [.fluid output file]" << std::endl; return -1; } int threadnum = atoi(argv[1]); int framenum = atoi(argv[2]); //Check arguments if(threadnum < 1) { std::cerr << "<threadnum> must at least be 1" << std::endl; return -1; } if(framenum < 1) { std::cerr << "<framenum> must at least be 1" << std::endl; return -1; } #ifdef ENABLE_CFL_CHECK std::cout << "WARNING: Check for Courant–Friedrichs–Lewy condition enabled. Do not use for performance measurements." << std::endl; #endif InitSim(argv[3], threadnum); #ifdef ENABLE_VISUALIZATION InitVisualizationMode(&argc, argv, &AdvanceFrameVisualization, &numCells, &cells, &cnumPars); #endif #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_begin(); #endif #if defined(WIN32) thread_args* targs = (thread_args*)alloca(sizeof(thread_args)*threadnum); #else thread_args targs[threadnum]; #endif for(int i = 0; i < threadnum; ++i) { targs[i].tid = i; targs[i].frames = framenum; pthread_create(&thread[i], &attr, AdvanceFramesMT, &targs[i]); } // *** PARALLEL PHASE *** // #ifdef ENABLE_VISUALIZATION Visualize(); #endif for(int i = 0; i < threadnum; ++i) { pthread_join(thread[i], NULL); } #ifdef ENABLE_PARSEC_HOOKS __parsec_roi_end(); #endif if(argc > 4) SaveFile(argv[4]); CleanUpSim(); #ifdef ENABLE_PARSEC_HOOKS __parsec_bench_end(); #endif return 0; } ////////////////////////////////////////////////////////////////////////////////
33.445227
179
0.563624
mariobadr
8d736a42ca153192fb308eac032136f93f9f8d9b
4,668
cpp
C++
src/GuiLayout.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
14
2020-06-27T18:51:41.000Z
2022-03-30T18:20:02.000Z
src/GuiLayout.cpp
codenamecpp/GLKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
1
2020-06-07T09:48:11.000Z
2020-06-07T09:48:11.000Z
src/GuiLayout.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
2
2020-08-27T09:38:10.000Z
2021-08-12T01:17:30.000Z
#include "pch.h" #include "GuiLayout.h" #include "GuiWidget.h" GuiLayout::GuiLayout() : mOrientation(eGuiLayoutOrientation_Horizontal) , mCols(1) , mRows(1) , mSpacingHorz() , mSpacingVert() , mPaddingL() , mPaddingT() , mPaddingR() , mPaddingB() , mLayoutType(eGuiLayout_None) { } void GuiLayout::LoadProperties(cxx::json_node_object documentNode) { cxx::json_get_attribute(documentNode, "type", mLayoutType); cxx::json_get_attribute(documentNode, "orientation", mOrientation); if (cxx::json_get_attribute(documentNode, "num_cols", mCols)) { if (mCols < 1) { debug_assert(false); mCols = 1; } } if (cxx::json_get_attribute(documentNode, "num_rows", mRows)) { if (mRows < 1) { debug_assert(false); mRows = 1; } } if (cxx::json_node_object spacingNode = documentNode["spacing"]) { cxx::json_get_attribute(spacingNode, "horz", mSpacingHorz); cxx::json_get_attribute(spacingNode, "vert", mSpacingVert); } if (cxx::json_node_object paddingNode = documentNode["padding"]) { cxx::json_get_attribute(paddingNode, "left", mPaddingL); cxx::json_get_attribute(paddingNode, "top", mPaddingT); cxx::json_get_attribute(paddingNode, "bottom", mPaddingB); cxx::json_get_attribute(paddingNode, "right", mPaddingR); } } void GuiLayout::Clear() { mLayoutType = eGuiLayout_None; mOrientation = eGuiLayoutOrientation_Horizontal; mCols = 1; mRows = 1; mSpacingHorz = 0; mSpacingVert = 0; mPaddingL = 0; mPaddingT = 0; mPaddingR = 0; mPaddingB = 0; } void GuiLayout::SetOrientation(eGuiLayoutOrientation orientation) { if (orientation == mOrientation) return; mOrientation = orientation; } void GuiLayout::SetColsCount(int numCols) { if (numCols < 1) numCols = 1; if (numCols == mCols) return; mCols = numCols; } void GuiLayout::SetRowsCount(int numRows) { if (numRows < 1) numRows = 1; if (numRows == mRows) return; mRows = numRows; } void GuiLayout::SetSpacing(int spacingHorz, int spacingVert) { if (mSpacingHorz == spacingHorz && mSpacingVert == spacingVert) return; mSpacingHorz = spacingHorz; mSpacingVert = spacingVert; } void GuiLayout::SetPadding(int paddingL, int paddingT, int paddingR, int paddingB) { if (mPaddingB == paddingB && mPaddingL == paddingL && mPaddingR == paddingR && mPaddingT == paddingT) { return; } mPaddingB = paddingB; mPaddingL = paddingL; mPaddingR = paddingR; mPaddingT = paddingT; } void GuiLayout::LayoutSimpleGrid(GuiWidget* container) { Point currPos(mPaddingL, mPaddingT); int currIndex = 0; int currLineMaxElementSize = 0; const int maxElementsInLine = mOrientation == eGuiLayoutOrientation_Horizontal ? mCols : mRows; debug_assert(maxElementsInLine > 0); for (GuiWidget* curr_child = container->GetChild(); curr_child; curr_child = curr_child->NextSibling()) { if (!curr_child->IsVisible()) continue; curr_child->SetPosition(currPos); if (mOrientation == eGuiLayoutOrientation_Horizontal) { if (currLineMaxElementSize < curr_child->mSize.y) currLineMaxElementSize = curr_child->mSize.y; currPos.x += curr_child->mSize.x + mSpacingHorz; } else // vertical { if (currLineMaxElementSize < curr_child->mSize.x) currLineMaxElementSize = curr_child->mSize.x; currPos.y += curr_child->mSize.y + mSpacingVert; } if (++currIndex == maxElementsInLine) { if (mOrientation == eGuiLayoutOrientation_Horizontal) { currPos.x = mPaddingL; currPos.y += currLineMaxElementSize + mSpacingVert; } else // vertical { currPos.x += currLineMaxElementSize + mSpacingHorz; currPos.y = mPaddingT; } currLineMaxElementSize = 0; currIndex = 0; } } // for } void GuiLayout::LayoutElements(GuiWidget* container) { if (container == nullptr) { debug_assert(false); return; } switch (mLayoutType) { case eGuiLayout_SimpleGrid: LayoutSimpleGrid(container); break; } }
25.096774
99
0.591688
codenamecpp
8d740ee14c6eba58a6d514970a59c5e79e2c3b21
550
hpp
C++
src/AST/Statements/ProcedureCallStatement.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/AST/Statements/ProcedureCallStatement.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
src/AST/Statements/ProcedureCallStatement.hpp
CarsonFox/CPSL
07a949166d9399f273ddf15e239ade6e5ea6e4a5
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <memory> #include "Statement.hpp" #include <src/AST/Expressions/Expression.hpp> #include <src/AST/Expressions/ExpressionList.hpp> struct ProcedureCallStatement : Statement { std::string id; std::vector<std::shared_ptr<Expression>> args; ProcedureCallStatement(char *, ExpressionList *); ~ProcedureCallStatement() override = default; void print() const override; void fold_constants() override; void emit(SymbolTable &table, RegisterPool &pool) override; };
22.916667
63
0.732727
CarsonFox
8d7600502f946ed0f5cb6f0ce49cf39a1d62ff17
2,691
cpp
C++
src/viewlinecache.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
null
null
null
src/viewlinecache.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
2
2016-11-25T19:52:09.000Z
2017-04-15T14:49:52.000Z
src/viewlinecache.cpp
alexezh/trv
1dd97096ed9f60ffb64c4e44e2e309e9c5002224
[ "MIT" ]
null
null
null
// Copyright (c) 2013 Alexandre Grigorovitch (alexezh@gmail.com). // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "stdafx.h" #include <strsafe.h> #include "traceapp.h" #include "viewlinecache.h" #include "js/apphost.h" ViewLineCache::ViewLineCache(IDispatchQueue* uiQueue, Js::IAppHost* host) { m_UiQueue = uiQueue; m_Host = host; } void ViewLineCache::SetCacheRange(DWORD dwStart, DWORD dwEnd) { if (m_Cache.GetItemCount() < 2000) return; m_Cache.ResetIfNot(dwStart, dwEnd); } bool ViewLineCache::ProcessNextLine(const std::function<std::unique_ptr<ViewLine>(DWORD)>& func) { DWORD idx; { std::lock_guard<std::mutex> guard(m_Lock); if (m_RequestedLines.size() == 0) return false; idx = m_RequestedLines.back(); auto& line = func(idx); m_Cache.Set(idx, std::move(line)); // remove line from list and map m_RequestedLines.pop_back(); m_RequestedMap.erase(idx); } m_UiQueue->Post([this, idx]() { if (!m_OnLineAvailable) return; m_OnLineAvailable(idx); }); return true; } const ViewLine* ViewLineCache::GetLine(DWORD idx) { std::lock_guard<std::mutex> guard(m_Lock); const ViewLine* line = nullptr; if(idx < m_Cache.GetSize()) line = m_Cache.GetAt(idx).get(); if (line == nullptr && m_RequestedMap.find(idx) == m_RequestedMap.end()) { m_RequestedLines.push_back(idx); m_RequestedMap.insert(idx); m_Host->RequestViewLine(); } return line; } void ViewLineCache::RegisterLineAvailableListener(const LiveAvailableHandler& handler) { m_OnLineAvailable = handler; } void ViewLineCache::Resize(size_t n) { m_Cache.Resize(n); } void ViewLineCache::Reset() { m_Cache.ResetIfNot(-1, -1); }
26.126214
96
0.733928
alexezh
8d76ce6d49188f6daad29d6f68a26819f056b6c3
1,087
hpp
C++
missions/_missions1/dcg.takistan/cfgParams.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
missions/_missions1/dcg.takistan/cfgParams.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
missions/_missions1/dcg.takistan/cfgParams.hpp
ademirt/Arma3
f75c28f59deb45e56d021d9d1d3458b145432bd8
[ "MIT" ]
null
null
null
/* Types (SCALAR, BOOL, SIDE) */ class dcg_main_debug { title = "Debug Mode"; values[] = {0,1}; texts[] = {"Off", "On"}; default = 0; setParam = 1; typeName = ""; }; class dcg_main_loadData { title = "Load Mission Data"; values[] = {0,1}; texts[] = {"Off", "On"}; default = 1; setParam = 1; typeName = "BOOL"; }; class dcg_main_enemySide { title = "Enemy Side"; values[] = {0,2}; texts[] = {"East", "Independent"}; default = 0; setParam = 1; typeName = "SIDE"; }; class dcg_mission_disableCam { title = "Disable Third Person Camera"; values[] = {0,1}; texts[] = {"Off", "On"}; default = 0; setParam = 1; typeName = "BOOL"; }; class dcg_weather_season { title = "Season"; values[] = {-1,0,1,2,3}; texts[] = {"Random","Summer","Fall","Winter","Spring"}; default = -1; setParam = 1; typeName = ""; }; class dcg_weather_time { title = "Time of Day"; values[] = {-1,0,1,2,3}; texts[] = {"Random","Morning","Midday","Evening","Night"}; default = 0; setParam = 1; typeName = ""; };
20.903846
61
0.543698
ademirt
8d7711a46890e79e299c6f3a5a3576b8420c06a6
2,153
hpp
C++
modules/kvm/include/virt86/kvm/kvm_platform.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
148
2019-02-19T11:05:28.000Z
2022-02-26T11:57:05.000Z
modules/kvm/include/virt86/kvm/kvm_platform.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
16
2019-02-19T02:51:48.000Z
2019-12-11T21:17:12.000Z
modules/kvm/include/virt86/kvm/kvm_platform.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
17
2019-02-19T04:05:33.000Z
2021-05-02T12:14:13.000Z
/* Declares the implementation class for the KVM hypervisor platform adapter. Include this file to use KVM as a platform. The platform instance is exposed as a singleton: auto& instance = virt86::kvm::KvmPlatform::Instance(); ------------------------------------------------------------------------------- MIT License Copyright (c) 2019 Ivan Roberto de Oliveira Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "virt86/platform/platform.hpp" namespace virt86::kvm { class KvmPlatform : public Platform { public: ~KvmPlatform() noexcept final; // Prevent copy construction and copy assignment KvmPlatform(const KvmPlatform&) = delete; KvmPlatform& operator=(const KvmPlatform&) = delete; // Prevent move construction and move assignment KvmPlatform(KvmPlatform&&) = delete; KvmPlatform&& operator=(KvmPlatform&&) = delete; // Disallow taking the address KvmPlatform *operator&() = delete; static KvmPlatform& Instance() noexcept; protected: std::unique_ptr<VirtualMachine> CreateVMImpl(const VMSpecifications& specifications) override; private: KvmPlatform() noexcept; int m_fd; }; }
34.174603
98
0.739898
dmiller423
8d78a7cbedccd8599f2906804066cfde7f4782a4
553
cpp
C++
gamma/system/packed_data.cpp
mbellman/gamma
a11a15492366682c2aec0a4570c6d091a83fe632
[ "Unlicense" ]
null
null
null
gamma/system/packed_data.cpp
mbellman/gamma
a11a15492366682c2aec0a4570c6d091a83fe632
[ "Unlicense" ]
null
null
null
gamma/system/packed_data.cpp
mbellman/gamma
a11a15492366682c2aec0a4570c6d091a83fe632
[ "Unlicense" ]
null
null
null
#include "system/packed_data.h" #include "system/type_aliases.h" #define CLAMP(f) (f < 0.0f ? 0.0f : f > 1.0f ? 1.0f : f) namespace Gamma { /** * pVec4 * ----- */ pVec4::pVec4(const Vec3f& value) { r = uint8(CLAMP(value.x) * 255.0f); g = uint8(CLAMP(value.y) * 255.0f); b = uint8(CLAMP(value.z) * 255.0f); a = 255; } pVec4::pVec4(const Vec4f& value) { r = uint8(CLAMP(value.x) * 255.0f); g = uint8(CLAMP(value.y) * 255.0f); b = uint8(CLAMP(value.z) * 255.0f); a = uint8(CLAMP(value.w) * 255.0f); } }
23.041667
56
0.551537
mbellman
8d7930c6c57473ce4bfd2a0f3acb576cb0a0a2b0
6,468
cpp
C++
serverS.cpp
ksuryakrishna/Socket-Programming
03c8903f060a59f126156214da191799b0653ac1
[ "MIT" ]
null
null
null
serverS.cpp
ksuryakrishna/Socket-Programming
03c8903f060a59f126156214da191799b0653ac1
[ "MIT" ]
null
null
null
serverS.cpp
ksuryakrishna/Socket-Programming
03c8903f060a59f126156214da191799b0653ac1
[ "MIT" ]
null
null
null
/* ** serverS.cpp: - Creates a map of scores and names - Receives requests from the central and sends the scores to the central - Closes the socket - by Surya Krishna Kasiviswanathan, USC ID: 9083261716 */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <string> #include <map> #include <fstream> #include <cstring> using namespace std; #define MYPORT "22716" // the port users will be connecting to #define CENTRAL_PORT "24716" //the port S uses to connect to central #define MAXBUFLEN 512 int sockfd_binded, sockfd_to_central; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; socklen_t addr_len; char s[INET6_ADDRSTRLEN]; string st1, st2; string file_name = "scores.txt"; map<string,int> m; //map created based on string as key and score as value int numVertices = 0, numVfromC = 0; //total no.of vertices int Vertno = 0; fstream fs(file_name); struct score_map{ //struct to convert map to struct to be sent to central int score_value; char names[512]; }obj_score[400]; struct numV{ //struct that stores the number of vertices in the graph sent int numstruct; }numobj; struct convert_map_to_struct{ //struct to store the map received int indexvalue; char names[512]; }obj[400]; // // get sockaddr, IPv4 or IPv6: // void *get_in_addr(struct sockaddr *sa) // { // if (sa->sa_family == AF_INET) { // return &(((struct sockaddr_in*)sa)->sin_addr); // } // return &(((struct sockaddr_in6*)sa)->sin6_addr); // } //function to connect to central through UDP socket and send the scores //snippets from Beej's guide is used here to establish connection and use sendto void Connect_to_Central_to_send_score(){ //add content of talker here memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; if ((rv = getaddrinfo("127.0.0.1", CENTRAL_PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd_to_central = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "talker: failed to create socket\n"); return; } //send map as struct objs for (auto x = 0; x < numVertices; x++){ if ((numbytes = sendto(sockfd_to_central, (char*) &obj_score[x], sizeof(score_map), 0, p->ai_addr, p->ai_addrlen)) == -1) { perror("talker: sendto"); exit(1); } for(int w = 0; w < 1000; w++); //delay to wait for other side to process // printf("talker: sent %d bytes to central\n", numbytes); } freeaddrinfo(servinfo); close(sockfd_to_central); } //function that receives the required from central //snippets from Beej's guide is used to recvfrom the central void Recv_from_central(){ addr_len = sizeof their_addr; if ((numbytes = recvfrom(sockfd_binded, (char*) &numobj, sizeof(numobj), 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } numVfromC = numobj.numstruct; // cout << "numobj.numstruct (numVertices) = "<<numVertices<<endl; // printf("listener: got packet from %s\n", // inet_ntop(their_addr.ss_family, // get_in_addr((struct sockaddr *)&their_addr), // s, sizeof s)); // printf("listener: packet is %d bytes long\n", numbytes); //get ready to receive the adjacency matrix and the map in the form of struct objects //get the map of nodes for(auto x = 0; x < numVfromC; x++){ addr_len = sizeof their_addr; if ((numbytes = recvfrom(sockfd_binded, (char*) &obj[x], sizeof(convert_map_to_struct), 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } } // cout<<"going to display received map \n"; // //sample display // for(auto x = 0; x<numVertices;x++){ // cout<<x<<": \t" <<obj[x].indexvalue<<" "<<obj[x].names<<endl; // } } //function that reads the contents of score.txt and forms a map based on the names and score void generate_score_map(){ while(fs>>st1){ //cout<<s<<endl; if(fs>>st2){ if(!m.count(st1)){ m.insert(make_pair(st1,stoi(st2))); } numVertices += 1; } } // //sample display map<string,int>::iterator i; // for(i=m.begin();i!=m.end();i++) { // cout<<i->first<<"\t"<<i->second<<endl; // } fs.close(); //add the map values on to a struct obj - total numVertices for(i=m.begin(); i!=m.end(), Vertno < numVertices; Vertno++, i++){ obj_score[Vertno].score_value = i->second; strcpy(obj_score[Vertno].names, i->first.c_str()); } // //sample display // for(Vertno = 0; Vertno < numVertices; Vertno++){ // cout<<obj_score[Vertno].score_value<<"\t"; // printf("%s\n",obj_score[Vertno].names); // } } // the main function // Snippets from Beej's guide are used for binding the UDP socket and listen int main(){ generate_score_map(); memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo("127.0.0.1", MYPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd_binded = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } if (bind(sockfd_binded, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd_binded); perror("listener: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); printf("The ServerS is up and running using UDP on port 22716.\n"); while(1){ Recv_from_central(); // received the two usernames up until this point printf("The ServerS received a request from Central to get the scores.\n"); //send the score map Connect_to_Central_to_send_score(); printf("The ServerS finished sending the scores to Central.\n"); } return 1; }
26.4
92
0.655071
ksuryakrishna
8d7a0c4969e09c863b8e69d40d7da40793af029e
493
cpp
C++
digitanks/src/dtintro/main.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
5
2015-07-03T18:42:32.000Z
2017-08-25T10:28:12.000Z
digitanks/src/dtintro/main.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
digitanks/src/dtintro/main.cpp
BSVino/Digitanks
1bd1ed115493bce22001ae6684b70b8fcf135db0
[ "BSD-4-Clause" ]
null
null
null
#include "intro_window.h" extern tvector<Color> FullScreenShot(int& iWidth, int& iHeight); void CreateApplication(int argc, char** argv) { int iWidth, iHeight; tvector<Color> aclrScreenshot = FullScreenShot(iWidth, iHeight); CIntroWindow oWindow(argc, argv); oWindow.SetScreenshot(aclrScreenshot, iWidth, iHeight); oWindow.OpenWindow(); oWindow.SetupEngine(); oWindow.Run(); } int main(int argc, char** argv) { CreateApplicationWithErrorHandling(CreateApplication, argc, argv); }
22.409091
67
0.762677
BSVino
8d7c18984a43edbda71911ed108cf2c37a42bc24
2,892
cc
C++
test/tilehierarchy.cc
molind/valhalla
7d4cde8587d38fcb20f7a9ea9df34a8fc49bf68c
[ "BSD-2-Clause", "MIT" ]
79
2017-02-15T17:35:48.000Z
2022-03-30T06:16:10.000Z
test/tilehierarchy.cc
molind/valhalla
7d4cde8587d38fcb20f7a9ea9df34a8fc49bf68c
[ "BSD-2-Clause", "MIT" ]
null
null
null
test/tilehierarchy.cc
molind/valhalla
7d4cde8587d38fcb20f7a9ea9df34a8fc49bf68c
[ "BSD-2-Clause", "MIT" ]
12
2017-06-16T06:30:54.000Z
2021-12-16T00:43:12.000Z
#include "baldr/tilehierarchy.h" #include "baldr/graphid.h" #include "midgard/pointll.h" #include "test.h" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> using namespace std; using namespace valhalla::baldr; using namespace valhalla::midgard; namespace { void test_parse() { if(TileHierarchy::levels().size() != 3) throw runtime_error("Incorrect number of hierarchy levels"); if((++TileHierarchy::levels().begin())->second.name != "arterial") throw runtime_error("Middle hierarchy should be named arterial"); if(TileHierarchy::levels().begin()->second.level != 0) throw runtime_error("Top hierarchy should have level 0"); if(TileHierarchy::levels().rbegin()->second.tiles.TileSize() != .25f) throw runtime_error("Bottom hierarchy should have tile size of .25f"); if(TileHierarchy::levels().find(5) != TileHierarchy::levels().end()) throw runtime_error("There should only be levels 0, 1, 2"); if(TileHierarchy::levels().find(2) == TileHierarchy::levels().end()) throw runtime_error("There should be a level 2"); GraphId id = TileHierarchy::GetGraphId(PointLL(0,0), 34); if(id.Is_Valid()) throw runtime_error("GraphId should be invalid as the level doesn't exist"); //there are 1440 cols and 720 rows, this spot lands on col 414 and row 522 id = TileHierarchy::GetGraphId(PointLL(-76.5, 40.5), 2); if(id.level() != 2 || id.tileid() != (522 * 1440) + 414 || id.id() != 0) throw runtime_error("Expected different graph id for this location"); if(TileHierarchy::levels().begin()->second.importance != RoadClass::kPrimary) throw runtime_error("Importance should be set to primary"); if((++TileHierarchy::levels().begin())->second.importance != RoadClass::kTertiary) throw runtime_error("Importance should be set to tertiary"); if(TileHierarchy::levels().rbegin()->second.importance != RoadClass::kServiceOther) throw runtime_error("Importance should be set to service/other"); } void test_tiles() { //there are 1440 cols and 720 rows, this spot lands on col 414 and row 522 AABB2<PointLL> bbox{{-76.49, 40.51}, {-76.48, 40.52}}; auto ids = TileHierarchy::GetGraphIds(bbox, 2); if (ids.size() != 1) { throw runtime_error("Should have only found one result."); } auto id = ids[0]; if (id.level() != 2 || id.tileid() != (522 * 1440) + 414 || id.id() != 0) { throw runtime_error("Didn't find correct tile ID."); } bbox = AABB2<PointLL>{{-76.51, 40.49}, {-76.49, 40.51}}; ids = TileHierarchy::GetGraphIds(bbox, 2); if (ids.size() != 4) { throw runtime_error("Should have found 4 results."); } } } int main(void) { test::suite suite("tilehierarchy"); suite.test(TEST_CASE(test_parse)); suite.test(TEST_CASE(test_tiles)); return suite.tear_down(); }
39.616438
87
0.667358
molind
8d7e5dfd75db551d178140dcaacb404d3444bc49
11,236
cpp
C++
installer/hachi_patch.cpp
LRFLEW/AM64DS_WiiU
37d4ada1d06a2b02d0ad82cd9b235018f6a25939
[ "Apache-2.0" ]
8
2021-11-02T04:07:37.000Z
2022-01-15T22:49:36.000Z
installer/hachi_patch.cpp
LRFLEW/AM64DS_WiiU
37d4ada1d06a2b02d0ad82cd9b235018f6a25939
[ "Apache-2.0" ]
null
null
null
installer/hachi_patch.cpp
LRFLEW/AM64DS_WiiU
37d4ada1d06a2b02d0ad82cd9b235018f6a25939
[ "Apache-2.0" ]
null
null
null
#include "hachi_patch.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstring> #include <numeric> #include <string> #include <string_view> #include <utility> #include <vector> #include <elf.h> #include "exception.hpp" #include "iosufsa.hpp" #include "log.hpp" #include "util.hpp" #include "zlib.hpp" #include "inject_bin.h" #include "inject_s.h" using namespace std::string_view_literals; namespace { constexpr Elf32_Half RPX_TYPE = 0xFE01; constexpr unsigned char RPX_ABI1 = 0xCA; constexpr unsigned char RPX_ABI2 = 0xFE; constexpr Elf32_Word RPX_CRCS = 0x80000003; constexpr std::uint32_t ZLIB_SECT = 0x08000000; constexpr std::string_view hachi_file = "/code/hachihachi_ntr.rpx"sv; constexpr std::uint32_t magic_amds = util::magic_const("AMDS"); static_assert(sizeof(Elf32_Ehdr) == 52); static_assert(sizeof(Elf32_Shdr) == 40); constexpr Elf32_Ehdr expected_ehdr = { { ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3, ELFCLASS32, ELFDATA2MSB, EV_CURRENT, RPX_ABI1, RPX_ABI2 }, RPX_TYPE, EM_PPC, EV_CURRENT, 0x02026798, 0x00, 0x40, 0, sizeof(Elf32_Ehdr), 0, 0, sizeof(Elf32_Shdr), 29, 26, }; constexpr std::array<std::uint32_t, expected_ehdr.e_shnum> expected_crcs = { 0x00000000, 0x14596B94, 0x165C39F2, 0xFA312336, 0x9BF039EE, 0xB3241733, 0x00000000, 0x60DA42CF, 0xEB7267F9, 0xF124402E, 0x01F80C21, 0x5E06092F, 0xD4CE0752, 0x72FA23E0, 0x940942DB, 0xBCFBF24D, 0x6B6574C9, 0x8D5FEDD5, 0x040E8EE3, 0xD5CEFF4A, 0xCFB2B47E, 0xE94CF6E0, 0x085C47BB, 0x279F690F, 0x598C85C9, 0x82F59D73, 0x2316975E, 0x00000000, 0x7D6C2996, }; bool good_layout(const std::vector<Elf32_Shdr> &shdr, const std::vector<std::size_t> &sorted) { std::uint32_t last_off = 0x40 + sizeof(Elf32_Shdr) * shdr.size(); for (std::size_t i : sorted) { const Elf32_Shdr &sect = shdr[i]; LOG("Check Header %d", i); if (sect.sh_offset - last_off >= 0x40) return false; last_off = sect.sh_offset + sect.sh_size; } return true; } bool decompress_sect(Elf32_Shdr &shdr, std::vector<std::uint8_t> &data) { if (!(shdr.sh_flags & ZLIB_SECT)) return true; if (shdr.sh_size != data.size()) return false; if (shdr.sh_size < 4) return false; std::uint32_t dec_len = *reinterpret_cast<const std::uint32_t *>(data.data()); LOG("Inflate"); data = Zlib::decompress(data, dec_len, true); shdr.sh_size = dec_len; shdr.sh_flags &= ~ZLIB_SECT; return true; } bool compress_sect(Elf32_Shdr &shdr, std::vector<std::uint8_t> &data) { if (shdr.sh_flags & ZLIB_SECT) return true; if (shdr.sh_size != data.size()) return false; std::vector<std::uint8_t> cmp; LOG("Deflate"); cmp = Zlib::compress(data, true); if (cmp.size() < data.size()) { shdr.sh_size = cmp.size(); data = std::move(cmp); shdr.sh_flags |= ZLIB_SECT; } return true; } void shift_for_resize(std::size_t resized, std::vector<Elf32_Shdr> &shdr, const std::vector<std::size_t> &sorted) { auto it = std::find(sorted.begin(), sorted.end(), resized); if (it == sorted.end()) return; Elf32_Shdr &resized_sect = shdr[*it]; std::uint32_t last_off = resized_sect.sh_offset + resized_sect.sh_size; for (++it; it != sorted.end(); ++it) { Elf32_Shdr &sect = shdr[*it]; sect.sh_offset = (last_off + 0x3F) & ~0x3F; last_off = sect.sh_offset + sect.sh_size; } } void make_b(std::vector<std::uint8_t> &data, std::size_t offset, std::size_t target) { std::uint32_t inst = (0x48000000 | (target - offset)) & 0xFFFFFFFC; *reinterpret_cast<std::uint32_t *>(data.data() + offset) = inst; } void make_u16(std::vector<std::uint8_t> &data, std::size_t offset, std::uint16_t value) { *reinterpret_cast<std::uint16_t *>(data.data() + offset) = value; } const std::uint8_t zero_pad[0x40] = { }; class HachiPatch : public Patch { public: HachiPatch(const IOSUFSA &fsa, std::string_view title) : fsa(fsa), path(util::concat_sv({ title, hachi_file })) { } virtual ~HachiPatch() override = default; virtual void Read() override { LOG("Open RPX"); IOSUFSA::File rpx(fsa); if (!rpx.open(path, "rb")) throw error("RPX: Read FileOpen"); LOG("Read Header"); if (!rpx.readall(&ehdr, sizeof(ehdr))) throw error("RPX: Read Header"); if (!util::memequal(ehdr, expected_ehdr)) throw error("RPX: Invalid Header"); LOG("Read Sections Table"); shdr.resize(ehdr.e_shnum); LOG("Read Sections Table - seek %X", ehdr.e_shoff); if (!rpx.seek(ehdr.e_shoff)) throw error("RPX: Seek Sections"); LOG("Read Sections Table - read"); if (!rpx.readall(shdr)) throw error("RPX: Read Sections"); LOG("Read Sections Table - done"); LOG("Get Sorted Sections"); sorted_sects.resize(ehdr.e_shnum); std::iota(sorted_sects.begin(), sorted_sects.end(), 0); sorted_sects.erase(std::remove_if(sorted_sects.begin(), sorted_sects.end(), [this](std::size_t i) -> bool { return shdr[i].sh_offset == 0; }), sorted_sects.end()); std::sort(sorted_sects.begin(), sorted_sects.end(), [this](std::size_t a, std::size_t b) -> bool { return shdr[a].sh_offset < shdr[b].sh_offset; }); LOG("Validate Sorted Sections"); if (!good_layout(shdr, sorted_sects)) throw error("RPX: Bad Layout"); sections.resize(ehdr.e_shnum); for (std::size_t i : sorted_sects) { if (shdr[i].sh_size > 0) { LOG("Read Section %d", i); sections[i].resize(shdr[i].sh_size); if (!rpx.seek(shdr[i].sh_offset)) throw error("RPX: Seek Sect"); if (!rpx.readall(sections[i])) throw error("RPX: Read Sect"); } } LOG("Close RPX"); if (!rpx.close()) throw error("RPX: Read CloseFile"); } virtual void Modify() override { Elf32_Shdr &text_hdr = shdr[2]; std::vector<std::uint8_t> &text = sections[2]; LOG("Decompress Text"); if (!decompress_sect(text_hdr, text)) throw error("RPX: Decompress Text"); LOG("Patch Loaded Text"); make_u16(text, 0x006CEA, 0x6710); make_b( text, 0x00CC1C, text.size() + off_inject_apply_angle - off_inject_start); make_b( text, 0x01DA28, text.size() + off_inject_comp_angle - off_inject_start); make_u16(text, 0x01DA42, 0x0018); // vpad->rstick.y offset make_u16(text, 0x01DAD2, 0x0014); // vpad->rstick.x offset make_u16(text, 0x03ED0E, 0x0BB0); make_b( text, 0x050938, text.size() + off_inject_init_angle - off_inject_start); make_b( text, 0x053F70, text.size() + off_inject_get_angle - off_inject_start); text.insert(text.end(), inject_bin, inject_bin_end); text_hdr.sh_size += inject_bin_size; LOG("CRC Calc"); std::uint32_t crc = Zlib::crc32(text); reinterpret_cast<std::uint32_t *>(sections[27].data())[2] = crc; LOG("Compress Text"); if (!compress_sect(text_hdr, text)) throw error("RPX: Compress Text"); LOG("Shift for Resize"); shift_for_resize(2, shdr, sorted_sects); } virtual void Write() override { LOG("Open RPX Write"); IOSUFSA::File rpx(fsa); if (!rpx.open(path, "wb")) throw error("RPX: Write FileOpen"); LOG("Write Header"); if (!rpx.writeall(&ehdr, sizeof(ehdr))) throw error("RPX: Write Header"); LOG("Write Pad"); if (!rpx.writeall(&magic_amds, sizeof(magic_amds))) throw error("RPX: Write Magic"); if (!rpx.writeall(zero_pad, ehdr.e_shoff - sizeof(ehdr) - sizeof(magic_amds))) throw error("RPX: Write ShPad"); LOG("Write Section Table"); if (!rpx.writeall(shdr)) throw error("RPX: Write Sections"); std::uint32_t last_off = 0x40 + sizeof(Elf32_Shdr) * shdr.size(); for (std::size_t i : sorted_sects) { if (shdr[i].sh_size > 0) { LOG("Write Section %d", i); const Elf32_Shdr &sect = shdr[i]; if (!rpx.writeall(zero_pad, sect.sh_offset - last_off)) throw error("RPX: Write StPad"); if (!rpx.writeall(sections[i])) throw error("RPX: Write Sect"); last_off = sect.sh_offset + sect.sh_size; } } if (!rpx.writeall(zero_pad, -last_off & 0x3F)) throw error("RPX: Write FlPad"); LOG("Close RPX Write"); if (!rpx.close()) throw error("RPX: Write FileClose"); } private: const IOSUFSA &fsa; std::string path; Elf32_Ehdr ehdr; std::vector<Elf32_Shdr> shdr; std::vector<std::size_t> sorted_sects; std::vector<std::vector<std::uint8_t>> sections; }; } #define ret(X) do { rpx.close(); return X; } while(0) Patch::Status hachi_check(const IOSUFSA &fsa, std::string_view title) { std::string rpx_path = util::concat_sv({ title, hachi_file }); LOG("Open RPX"); IOSUFSA::File rpx(fsa); if (!rpx.open(rpx_path, "rb")) ret(Patch::Status::MISSING_RPX); LOG("Read Header"); Elf32_Ehdr ehdr; if (!rpx.readall(&ehdr, sizeof(ehdr))) ret(Patch::Status::INVALID_RPX); if (!util::memequal(ehdr, expected_ehdr)) ret(Patch::Status::INVALID_RPX); LOG("Read Patch Signature"); std::uint32_t sig; if (!rpx.readall(&sig, sizeof(sig))) ret(Patch::Status::INVALID_RPX); if (sig == magic_amds) ret(Patch::Status::PATCHED); LOG("Read CRC Section Header"); Elf32_Shdr crc_shdr; if (!rpx.seek(ehdr.e_shoff + 27 * sizeof(Elf32_Shdr))) ret(Patch::Status::INVALID_RPX); if (!rpx.readall(&crc_shdr, sizeof(crc_shdr))) ret(Patch::Status::INVALID_RPX); if (crc_shdr.sh_type != RPX_CRCS) ret(Patch::Status::INVALID_RPX); if (crc_shdr.sh_size != sizeof(expected_crcs)) ret(Patch::Status::INVALID_RPX); LOG("Read CRC Data"); std::array<std::uint32_t, expected_ehdr.e_shnum> crcs; if (!rpx.seek(crc_shdr.sh_offset)) ret(Patch::Status::INVALID_RPX); if (!rpx.readall(&crcs, sizeof(crcs))) ret(Patch::Status::INVALID_RPX); if (!util::memequal(crcs, expected_crcs)) ret(Patch::Status::INVALID_RPX); LOG("HACHI GOOD"); ret(Patch::Status::RPX_ONLY); } std::unique_ptr<Patch> hachi_patch(const IOSUFSA &fsa, std::string_view title) { return std::make_unique<HachiPatch>(fsa, title); }
39.424561
99
0.590068
LRFLEW
8d838ece296a499f0a7e6ab06e5cb82f6a51d141
1,755
hpp
C++
psychic-ui/components/Button.hpp
WolfieWerewolf/psychic-ui
d67fc4871a3957cd16c15a42d9ed3e64b65f56bf
[ "MIT" ]
29
2018-01-31T04:58:35.000Z
2022-03-24T16:37:02.000Z
psychic-ui/components/Button.hpp
WolfieWerewolf/psychic-ui
d67fc4871a3957cd16c15a42d9ed3e64b65f56bf
[ "MIT" ]
2
2018-03-27T22:43:46.000Z
2022-03-25T14:09:32.000Z
psychic-ui/components/Button.hpp
WolfieWerewolf/psychic-ui
d67fc4871a3957cd16c15a42d9ed3e64b65f56bf
[ "MIT" ]
11
2017-08-28T16:36:49.000Z
2020-03-26T00:02:55.000Z
#pragma once #include <functional> #include <utility> #include "psychic-ui/psychic-ui.hpp" #include "psychic-ui/Component.hpp" #include "psychic-ui/Skin.hpp" #include "Label.hpp" namespace psychic_ui { class Button; class ButtonSkin : public Skin<Button> { public: ButtonSkin() : Skin<Button>() { setTag("ButtonSkin"); } virtual void setLabel(const std::string &/*label*/) {}; }; class Button : public Component<ButtonSkin> { public: Button(const std::string &label, ClickCallback onClick); explicit Button(const std::string &label = "") : Button(label, nullptr) {} explicit Button(const ClickCallback &onClick) : Button("", std::move(onClick)) {} const std::string &label() const; void setLabel(const std::string &label); bool toggle() const { return _toggle; } Button *setToggle(const bool toggle) { _toggle = toggle; return this; } bool autoToggle() const { return _autoToggle; } Button *setAutoToggle(const bool autoToggle) { _autoToggle = autoToggle; return this; } bool selected() const; Button *setSelected(bool selected); bool active() const override; Button *onChange(std::function<void(bool)> onChange) { _onChange = std::move(onChange); return this; } protected: std::string _label{}; bool _toggle{false}; bool _autoToggle{true}; bool _selected{false}; std::function<void(bool)> _onChange{nullptr}; void skinChanged() override; }; }
25.808824
89
0.565812
WolfieWerewolf
8d8c3e1b5f9188fcb7dd5f617a2c59533ae50128
1,715
cpp
C++
Courses/001 - Algorithms Toolbox/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp
aKhfagy/Data-Structures-and-Algorithms-Specialization
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
1
2021-01-25T09:56:15.000Z
2021-01-25T09:56:15.000Z
Courses/001 - Algorithms Toolbox/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
Courses/001 - Algorithms Toolbox/week6_dynamic_programming2/3_maximum_value_of_an_arithmetic_expression/placing_parentheses.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <cassert> #include <string> #include <vector> #include <cmath> #include <algorithm> #include <climits> using std::vector; using std::string; using std::max; using std::min; using ll = long long; long long eval(long long a, long long b, char op) { if (op == '*') { return a * b; } else if (op == '+') { return a + b; } else if (op == '-') { //puts("HAHA"); return b - a; } else { assert(0); } } ll mi[30][30] = {}; ll ma[30][30] = {}; long long get_maximum_value(const string& exp) { int n = exp.size() / 2 + (exp.size() & 1); for (int i = 0; i < n; ++i) { int num = exp[2 * i] - '0'; mi[i][i] = ma[i][i] = num; } for (int s = 0; s < n - 1; ++s) { for (int i = 0; i < n - s - 1; ++i) { int j = i + s + 1; ll mn = LLONG_MAX, mx = LLONG_MIN; for (int k = i; k < j; ++k) { ll num[4] = { eval(mi[k + 1][j], mi[i][k], exp[k * 2 + 1]), eval(mi[k + 1][j], ma[i][k], exp[k * 2 + 1]), eval(ma[k + 1][j], mi[i][k], exp[k * 2 + 1]), eval(ma[k + 1][j], ma[i][k], exp[k * 2 + 1]) }; for (int t = 0; t < 4; ++t) { //std::cout << num[t] << " \n"[t == 3]; mn = min(mn, num[t]); mx = max(mx, num[t]); } } //std::cout << mn << ' ' << mx << '\n'; mi[i][j] = mn; ma[i][j] = mx; } } --n; return ma[0][n]; } int main() { string s; std::cin >> s; std::cout << get_maximum_value(s) << '\n'; }
23.175676
75
0.377843
aKhfagy
8d8caec8ba8a05cb849aab8543e869882170d457
8,111
cc
C++
old/rama_dialogblocks/sweep.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
null
null
null
old/rama_dialogblocks/sweep.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
127
2017-11-01T01:28:28.000Z
2021-03-18T05:12:21.000Z
old/rama_dialogblocks/sweep.cc
teenylasers/eggshell
7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e
[ "ICU", "OpenSSL" ]
2
2017-10-20T01:16:49.000Z
2018-11-04T02:36:53.000Z
///////////////////////////////////////////////////////////////////////////// // Name: sweep.cc // Purpose: // Author: // Modified by: // Created: // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// // Precompiled header: #include "../stdwx.h" ////@begin includes ////@end includes #include "sweep.h" #include "../cavity.h" #include "../../toolkit/mystring.h" ////@begin XPM images ////@end XPM images /* * SweepDialog type definition */ IMPLEMENT_DYNAMIC_CLASS( SweepDialog, wxDialog ) /* * SweepDialog event table definition */ BEGIN_EVENT_TABLE( SweepDialog, wxDialog ) ////@begin SweepDialog event table entries EVT_CHOICE( ID_SWEEP_PARAMETER, SweepDialog::OnSweepParameterSelected ) EVT_BUTTON( wxID_OK, SweepDialog::OnOk ) ////@end SweepDialog event table entries END_EVENT_TABLE() /* * SweepDialog constructors */ SweepDialog::SweepDialog() { Init(); } SweepDialog::SweepDialog( wxWindow* parent, Cavity* viewer, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); viewer_ = viewer; Create(parent, id, caption, pos, size, style); } /* * Sweep creator */ bool SweepDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin SweepDialog creation SetExtraStyle(wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end SweepDialog creation return true; } /* * SweepDialog destructor */ SweepDialog::~SweepDialog() { ////@begin SweepDialog destruction ////@end SweepDialog destruction } /* * Member initialisation */ void SweepDialog::Init() { ////@begin SweepDialog member initialisation parameters_ctrl_ = NULL; start_value_ctrl_ = NULL; end_value_ctrl_ = NULL; num_steps_text_ = NULL; num_steps_ctrl_ = NULL; ////@end SweepDialog member initialisation viewer_ = NULL; integer_ = false; start_value_ = end_value_ = min_value_ = max_value_ = 0; num_steps_ = 0; } /* * Control creation for Sweep */ void SweepDialog::CreateControls() { ////@begin SweepDialog content construction SweepDialog* itemDialog1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemDialog1->SetSizer(itemBoxSizer2); wxFlexGridSizer* itemFlexGridSizer3 = new wxFlexGridSizer(0, 2, 0, 0); itemBoxSizer2->Add(itemFlexGridSizer3, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxStaticText* itemStaticText4 = new wxStaticText( itemDialog1, wxID_STATIC, _("Parameter to sweep"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(itemStaticText4, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxArrayString parameters_ctrl_Strings; parameters_ctrl_ = new wxChoice( itemDialog1, ID_SWEEP_PARAMETER, wxDefaultPosition, wxDefaultSize, parameters_ctrl_Strings, 0 ); itemFlexGridSizer3->Add(parameters_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText6 = new wxStaticText( itemDialog1, wxID_STATIC, _("Start value"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(itemStaticText6, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); start_value_ctrl_ = new wxTextCtrl( itemDialog1, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(start_value_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticText* itemStaticText8 = new wxStaticText( itemDialog1, wxID_STATIC, _("End value"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(itemStaticText8, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); end_value_ctrl_ = new wxTextCtrl( itemDialog1, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(end_value_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); num_steps_text_ = new wxStaticText( itemDialog1, wxID_STATIC, _("Number of steps"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(num_steps_text_, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5); num_steps_ctrl_ = new wxTextCtrl( itemDialog1, wxID_ANY, _("50"), wxDefaultPosition, wxDefaultSize, 0 ); itemFlexGridSizer3->Add(num_steps_ctrl_, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); wxStaticLine* itemStaticLine12 = new wxStaticLine( itemDialog1, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); itemBoxSizer2->Add(itemStaticLine12, 0, wxGROW|wxALL, 5); wxBoxSizer* itemBoxSizer13 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer13, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxButton* itemButton14 = new wxButton( itemDialog1, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, 0 ); itemButton14->SetDefault(); itemBoxSizer13->Add(itemButton14, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* itemButton15 = new wxButton( itemDialog1, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer13->Add(itemButton15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); ////@end SweepDialog content construction std::vector<std::string> names; viewer_->GetParamControlNames(&names); for (int i = 0; i < names.size(); i++) { parameters_ctrl_->Append(names[i]); } parameters_ctrl_->SetSelection(0); if (!names.empty()) { SetParameter(names[0]); } } /* * Should we show tooltips? */ bool SweepDialog::ShowToolTips() { return true; } /* * Get bitmap resources */ wxBitmap SweepDialog::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin SweepDialog bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end SweepDialog bitmap retrieval } /* * Get icon resources */ wxIcon SweepDialog::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin SweepDialog icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end SweepDialog icon retrieval } /* * wxEVT_COMMAND_CHOICE_SELECTED event handler for ID_SWEEP_PARAMETER */ void SweepDialog::OnSweepParameterSelected( wxCommandEvent& event ) { SetParameter((const char*) parameters_ctrl_->GetString(event.GetInt()).c_str()); } void SweepDialog::SetParameter(const std::string &name) { parameter_ = name; const Parameter &param = viewer_->GetParameter(name); start_value_ctrl_->SetValue(wxString::Format("%.10g", param.the_min)); end_value_ctrl_->SetValue(wxString::Format("%.10g", param.the_max)); num_steps_ctrl_->Enable(!param.integer); num_steps_text_->Enable(!param.integer); integer_ = param.integer; min_value_ = param.the_min; max_value_ = param.the_max; } void SweepDialog::OnOk( wxCommandEvent& event ) { if (!StrToDouble(start_value_ctrl_->GetValue().c_str(), &start_value_)) { wxLogError("Bad start value"); return; } if (!StrToDouble(end_value_ctrl_->GetValue().c_str(), &end_value_)) { wxLogError("Bad end value"); return; } if (!StrToInt(num_steps_ctrl_->GetValue().c_str(), &num_steps_) || num_steps_ <= 0) { wxLogError("Bad number of steps"); return; } if (start_value_ >= end_value_) { wxLogError("Start value must be less than end value"); return; } if (start_value_ < min_value_ || end_value_ > max_value_) { wxLogError("Start and end must be in the range %g to %g", min_value_, max_value_); return; } if (integer_) { if (start_value_ != int(start_value_) || end_value_ != int(end_value_)) { wxLogError("Start and end values must be integers"); return; } } event.Skip(); }
30.152416
153
0.670078
teenylasers
8d8d3317296e0016bc5ce73a2f7d0e60fe2f33d7
12,565
cpp
C++
compiler/luci/import/src/GraphBuilderRegistry.cpp
wateret/ONE
4b1c4721248887d68a18f97d6903e459675163fc
[ "Apache-2.0" ]
null
null
null
compiler/luci/import/src/GraphBuilderRegistry.cpp
wateret/ONE
4b1c4721248887d68a18f97d6903e459675163fc
[ "Apache-2.0" ]
1
2020-09-23T23:12:23.000Z
2020-09-23T23:20:34.000Z
compiler/luci/import/src/GraphBuilderRegistry.cpp
s-barannikov/ONE
608121ca5a790a36a87889934f78574d27df7077
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 "luci/Import/GraphBuilderRegistry.h" #include "luci/Import/Nodes.h" #include <memory> namespace luci { GraphBuilderRegistry::GraphBuilderRegistry() { #define CIRCLE_NODE(OPCODE, CLASS) add(circle::BuiltinOperator_##OPCODE, std::make_unique<CLASS>()); CIRCLE_NODE(ABS, CircleAbsGraphBuilder); // 101 CIRCLE_NODE(ADD, CircleAddGraphBuilder); // 0 CIRCLE_NODE(ADD_N, CircleAddNGraphBuilder); // 106 CIRCLE_NODE(ARG_MAX, CircleArgMaxGraphBuilder); // 56 CIRCLE_NODE(ARG_MIN, CircleArgMinGraphBuilder); // 79 CIRCLE_NODE(AVERAGE_POOL_2D, CircleAveragePool2DGraphBuilder); // 1 CIRCLE_NODE(BATCH_MATMUL, CircleBatchMatMulGraphBuilder); // 126 CIRCLE_NODE(BATCH_TO_SPACE_ND, CircleBatchToSpaceNDGraphBuilder); // 37 CIRCLE_NODE(BCQ_FULLY_CONNECTED, CircleBCQFullyConnectedGraphBuilder); // 253 CIRCLE_NODE(BCQ_GATHER, CircleBCQGatherGraphBuilder); // 252 CIRCLE_NODE(CAST, CircleCastGraphBuilder); // 53 CIRCLE_NODE(CEIL, CircleCeilGraphBuilder); // 104 CIRCLE_NODE(CUSTOM, CircleCustomGraphBuilder); // 32 CIRCLE_NODE(CONCATENATION, CircleConcatenationGraphBuilder); // 2 CIRCLE_NODE(CONV_2D, CircleConv2DGraphBuilder); // 3 CIRCLE_NODE(COS, CircleCosGraphBuilder); // 108 CIRCLE_NODE(DEPTH_TO_SPACE, CircleDepthToSpaceGraphBuilder); // 5 CIRCLE_NODE(DEPTHWISE_CONV_2D, CircleDepthwiseConv2DGraphBuilder); // 4 CIRCLE_NODE(DEQUANTIZE, CircleDequantizeGraphBuilder); // 6 CIRCLE_NODE(DIV, CircleDivGraphBuilder); // 42 CIRCLE_NODE(ELU, CircleEluGraphBuilder); // 111 CIRCLE_NODE(EQUAL, CircleEqualGraphBuilder); // 71 CIRCLE_NODE(EXP, CircleExpGraphBuilder); // 47 CIRCLE_NODE(EXPAND_DIMS, CircleExpandDimsGraphBuilder); // 70 CIRCLE_NODE(FILL, CircleFillGraphBuilder); // 94 CIRCLE_NODE(FLOOR, CircleFloorGraphBuilder); // 8 CIRCLE_NODE(FLOOR_DIV, CircleFloorDivGraphBuilder); // 90 CIRCLE_NODE(FLOOR_MOD, CircleFloorModGraphBuilder); // 95 CIRCLE_NODE(FULLY_CONNECTED, CircleFullyConnectedGraphBuilder); // 9 CIRCLE_NODE(GATHER, CircleGatherGraphBuilder); // 36 CIRCLE_NODE(GATHER_ND, CircleGatherNdGraphBuilder); // 107 CIRCLE_NODE(GREATER, CircleGreaterGraphBuilder); // 61 CIRCLE_NODE(GREATER_EQUAL, CircleGreaterEqualGraphBuilder); // 62 CIRCLE_NODE(IF, CircleIfGraphBuilder); // 118 CIRCLE_NODE(INSTANCE_NORM, CircleInstanceNormGraphBuilder); // 254 CIRCLE_NODE(L2_NORMALIZATION, CircleL2NormalizeGraphBuilder); // 11 CIRCLE_NODE(L2_POOL_2D, CircleL2Pool2DGraphBuilder); // 12 CIRCLE_NODE(LEAKY_RELU, CircleLeakyReluGraphBuilder); // 98, CIRCLE_NODE(LESS, CircleLessGraphBuilder); // 58 CIRCLE_NODE(LESS_EQUAL, CircleLessEqualGraphBuilder); // 63 CIRCLE_NODE(LOCAL_RESPONSE_NORMALIZATION, CircleLocalResponseNormalizationGraphBuilder); // 13 CIRCLE_NODE(LOG, CircleLogGraphBuilder); // 73 CIRCLE_NODE(LOGICAL_AND, CircleLogicalAndGraphBuilder); // 86 CIRCLE_NODE(LOGICAL_NOT, CircleLogicalNotGraphBuilder); // 87 CIRCLE_NODE(LOGICAL_OR, CircleLogicalOrGraphBuilder); // 84 CIRCLE_NODE(LOGISTIC, CircleLogisticGraphBuilder); // 14 CIRCLE_NODE(LOG_SOFTMAX, CircleLogSoftmaxGraphBuilder); // 50 CIRCLE_NODE(MATRIX_DIAG, CircleMatrixDiagGraphBuilder); // 113 CIRCLE_NODE(MATRIX_SET_DIAG, CircleMatrixSetDiagGraphBuilder); // 115 CIRCLE_NODE(MAXIMUM, CircleMaximumGraphBuilder); // 55 CIRCLE_NODE(MAX_POOL_2D, CircleMaxPool2DGraphBuilder); // 17 CIRCLE_NODE(MEAN, CircleMeanGraphBuilder); // 40 CIRCLE_NODE(MINIMUM, CircleMinimumGraphBuilder); // 57 CIRCLE_NODE(MIRROR_PAD, CircleMirrorPadGraphBuilder); // 100 CIRCLE_NODE(MUL, CircleMulGraphBuilder); // 18 CIRCLE_NODE(NEG, CircleNegGraphBuilder); // 59 CIRCLE_NODE(NON_MAX_SUPPRESSION_V4, CircleNonMaxSuppressionV4GraphBuilder); // 120, CIRCLE_NODE(NON_MAX_SUPPRESSION_V5, CircleNonMaxSuppressionV5GraphBuilder); // 121, CIRCLE_NODE(NOT_EQUAL, CircleNotEqualGraphBuilder); // 72 CIRCLE_NODE(ONE_HOT, CircleOneHotGraphBuilder); // 85 CIRCLE_NODE(PACK, CirclePackGraphBuilder); // 83 CIRCLE_NODE(PAD, CirclePadGraphBuilder); // 34 CIRCLE_NODE(PADV2, CirclePadV2GraphBuilder); // 60 CIRCLE_NODE(POW, CirclePowGraphBuilder); // 78 CIRCLE_NODE(PRELU, CirclePReluGraphBuilder); // 54, CIRCLE_NODE(RANGE, CircleRangeGraphBuilder); // 96 CIRCLE_NODE(RANK, CircleRankGraphBuilder); // 110 CIRCLE_NODE(REDUCE_ANY, CircleReduceAnyGraphBuilder); // 91 CIRCLE_NODE(REDUCE_MAX, CircleReduceMaxGraphBuilder); // 82 CIRCLE_NODE(REDUCE_MIN, CircleReduceMinGraphBuilder); // 89 CIRCLE_NODE(REDUCE_PROD, CircleReduceProdGraphBuilder); // 81 CIRCLE_NODE(RELU, CircleReluGraphBuilder); // 19 CIRCLE_NODE(RELU6, CircleRelu6GraphBuilder); // 21 CIRCLE_NODE(RELU_N1_TO_1, CircleReluN1To1GraphBuilder); // 20 CIRCLE_NODE(RESHAPE, CircleReshapeGraphBuilder); // 22 CIRCLE_NODE(RESIZE_BILINEAR, CircleResizeBilinearGraphBuilder); // 23 CIRCLE_NODE(RESIZE_NEAREST_NEIGHBOR, CircleResizeNearestNeighborGraphBuilder); // 97 CIRCLE_NODE(REVERSE_SEQUENCE, CircleReverseSequenceGraphBuilder); // 112 CIRCLE_NODE(REVERSE_V2, CircleReverseV2GraphBuilder); // 105 CIRCLE_NODE(ROUND, CircleRoundGraphBuilder); // 116 CIRCLE_NODE(RSQRT, CircleRsqrtGraphBuilder); // 76 CIRCLE_NODE(SCATTER_ND, CircleScatterNdGraphBuilder); // 122 CIRCLE_NODE(SEGMENT_SUM, CircleSegmentSumGraphBuilder); // 125 CIRCLE_NODE(SELECT, CircleSelectGraphBuilder); // 64 CIRCLE_NODE(SELECT_V2, CircleSelectV2GraphBuilder); // 123 CIRCLE_NODE(SHAPE, CircleShapeGraphBuilder); // 77 CIRCLE_NODE(SIN, CircleSinGraphBuilder); // 66 CIRCLE_NODE(SLICE, CircleSliceGraphBuilder); // 65 CIRCLE_NODE(SOFTMAX, CircleSoftmaxGraphBuilder); // 25 CIRCLE_NODE(SPACE_TO_BATCH_ND, CircleSpaceToBatchNDGraphBuilder); // 38 CIRCLE_NODE(SPACE_TO_DEPTH, CircleSpaceToDepthGraphBuilder); // 26 CIRCLE_NODE(SPARSE_TO_DENSE, CircleSparseToDenseGraphBuilder); // 68 CIRCLE_NODE(SPLIT, CircleSplitGraphBuilder); // 49 CIRCLE_NODE(SPLIT_V, CircleSplitVGraphBuilder); // 102 CIRCLE_NODE(SQRT, CircleSqrtGraphBuilder); // 75 CIRCLE_NODE(SQUARE, CircleSquareGraphBuilder); // 92 CIRCLE_NODE(SQUARED_DIFFERENCE, CircleSquaredDifferenceGraphBuilder); // 99 CIRCLE_NODE(SQUEEZE, CircleSqueezeGraphBuilder); // 43 CIRCLE_NODE(STRIDED_SLICE, CircleStridedSliceGraphBuilder); // 45 CIRCLE_NODE(SUB, CircleSubGraphBuilder); // 41 CIRCLE_NODE(SUM, CircleSumGraphBuilder); // 74 CIRCLE_NODE(TANH, CircleTanhGraphBuilder); // 28 CIRCLE_NODE(TILE, CircleTileGraphBuilder); // 69 CIRCLE_NODE(TOPK_V2, CircleTopKV2GraphBuilder); // 48 CIRCLE_NODE(TRANSPOSE, CircleTransposeGraphBuilder); // 39 CIRCLE_NODE(TRANSPOSE_CONV, CircleTransposeConvGraphBuilder); // 67 CIRCLE_NODE(UNIQUE, CircleUniqueGraphBuilder); // 103 CIRCLE_NODE(UNPACK, CircleUnpackGraphBuilder); // 88 CIRCLE_NODE(WHERE, CircleWhereGraphBuilder); // 109 CIRCLE_NODE(WHILE, CircleWhileGraphBuilder); // 119 CIRCLE_NODE(ZEROS_LIKE, CircleZerosLikeGraphBuilder); // 93 #undef CIRCLE_NODE // BuiltinOperator_EMBEDDING_LOOKUP = 7, // BuiltinOperator_HASHTABLE_LOOKUP = 10, // BuiltinOperator_LSH_PROJECTION = 15, // BuiltinOperator_LSTM = 16, // BuiltinOperator_RNN = 24, // BuiltinOperator_SVDF = 27, // BuiltinOperator_CONCAT_EMBEDDINGS = 29, // BuiltinOperator_SKIP_GRAM = 30, // BuiltinOperator_CALL = 31, // BuiltinOperator_EMBEDDING_LOOKUP_SPARSE = 33, // BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_RNN = 35, // BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_LSTM = 44, // BuiltinOperator_BIDIRECTIONAL_SEQUENCE_RNN = 46, // BuiltinOperator_DELEGATE = 51, // BuiltinOperator_BIDIRECTIONAL_SEQUENCE_LSTM = 52, // BuiltinOperator_ARG_MAX = 56, // BuiltinOperator_FAKE_QUANT = 80, // BuiltinOperator_QUANTIZE = 114, // BuiltinOperator_HARD_SWISH = 117, // BuiltinOperator_DENSIFY = 124, } } // namespace luci
75.239521
100
0.52877
wateret
8d944ad508ecbc8b3457f025a558c30d21065fea
2,273
cpp
C++
cheats/hooks/paintTraverse.cpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
cheats/hooks/paintTraverse.cpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
cheats/hooks/paintTraverse.cpp
DemonLoverHvH/csgo
f7ff0211fd843bbf00cac5aa62422e5588552b23
[ "MIT" ]
null
null
null
#include "hooks.hpp" #include "../menu/menuX88.hpp" #include "../features/visuals/player.hpp" #include "../features/aimbot/aimbot.hpp" #include "../features/visuals/world.hpp" #include "../features/visuals/radar.hpp" #include "../features/misc/misc.hpp" #include "../menu/GUI/drawing.hpp" #include "../globals.hpp" #pragma region "Paint Helpers" bool shouldReloadsFonts() { static int oldX, oldY, x, y; interfaces::engine->getScreenSize(x, y); if (x != oldX || y != oldY) { oldX = x; oldY = y; return true; } return false; } bool isValidWindow() { // sub window is better, for cs as they recently updated main window name #ifdef _DEBUG if (auto window = FindWindowA("Valve001", NULL); GetForegroundWindow() != window) return false; #else if (auto window = LF(FindWindowA).cached()(XOR("Valve001"), NULL); LF(GetForegroundWindow).cached()() != window) return false; #endif return true; } void guiStates() { #ifdef _DEBUG for (short i = 0; i < 256; i++) { globals::previousKeyState[i] = globals::keyState[i]; globals::keyState[i] = static_cast<bool>(GetAsyncKeyState(i)); } #else for (short i = 0; i < 256; i++) { globals::previousKeyState[i] = globals::keyState[i]; globals::keyState[i] = static_cast<bool>(LF(GetAsyncKeyState).cached()(i)); } #endif interfaces::surface->getCursor(globals::mouseX, globals::mouseY); } #pragma endregion void __stdcall hooks::paintTraverse::hooked(unsigned int panel, bool forceRepaint, bool allowForce) { if (!isValidWindow()) return; // will run first no matter what, you can edit the function a bit or add ghetto static counter if (shouldReloadsFonts()) render::init(); if (strstr(interfaces::panel->getName(panel), XOR("HudZoom"))) { if (interfaces::engine->isInGame()) return; } original(interfaces::panel, panel, forceRepaint, allowForce); if (strstr(interfaces::panel->getName(panel), XOR("MatSystemTopPanel"))) { guiStates(); //Menu::g().draw(); //Menu::g().handleKeys(); esp::run(); world::drawMisc(); radar::run(); misc::drawLocalInfo(); misc::drawFpsPlot(); misc::drawVelocityPlot(); misc::drawHitmarker(); world::drawZeusRange(); misc::drawNoScope(); misc::drawCrosshair(); // testing image, all good //test::run(); GUI::draw(); } }
23.677083
113
0.678839
DemonLoverHvH
8d94fb1a5d590c30fa82d32647ef6540e428086d
9,299
cpp
C++
ex_4/ex_4.cpp
davidjgmarques/Monte-Carlo-exercises
6c31d524ebfcb434799b86714a7209193729d2d7
[ "MIT" ]
null
null
null
ex_4/ex_4.cpp
davidjgmarques/Monte-Carlo-exercises
6c31d524ebfcb434799b86714a7209193729d2d7
[ "MIT" ]
null
null
null
ex_4/ex_4.cpp
davidjgmarques/Monte-Carlo-exercises
6c31d524ebfcb434799b86714a7209193729d2d7
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <math.h> #include <chrono> #include <ctime> #include <cstdlib> #include <time.h> #include <vector> #include <random> #include "TCanvas.h" #include "TStyle.h" #include "TGraph.h" #include "TEllipse.h" #include "TAxis.h" #include "TLine.h" #include "TH1F.h" #include "TF1.h" #include "TApplication.h" using namespace std; double f_rng (double min, double max) { double val = ( (double)rand() / RAND_MAX ) * ( max - min ) + min; return val; } int f_rng_int ( int min, int max ) { int val = rand() % max + min; return val; } vector <int> throw_n_dice ( int n ) { vector<int> val; int rgn; for(int i = 0; i < n; i++){ rgn = f_rng_int(1,6); val.push_back(rgn); } sort ( val.begin(), val.end(), greater<int>()); return val; } tuple < int , int > Single_round ( vector<int> attack, vector<int> def ) { int won = 0.; int lost = 0.; int diff = min ( attack.size(), def.size() ); for ( size_t i = 0; i < diff; ++i ) { if ( attack[i] > def[i] ) won++; else lost++; } return make_tuple ( won, lost ); } tuple < int , int > Complete_war ( int initial_attack, int initial_defence ) { int attack = initial_attack; int defence = initial_defence; int win_attack; int lose_attack; vector <int> dice_attack; vector <int> dice_defence; while ( ( attack > 1 ) && ( defence > 0 ) ) { dice_attack = throw_n_dice ( min ( 3, attack - 1 ) ); dice_defence = throw_n_dice ( min ( 3, defence ) ); tie ( win_attack, lose_attack ) = Single_round ( dice_attack, dice_defence ); defence -= win_attack; attack -= lose_attack; } return make_tuple(attack,defence); } int main() { TApplication *myapp=new TApplication("myapp",0,0); int nBins1 = 26; int nBins2 = 10; TH1F * hDistrNumb = new TH1F("","",6,0.5,6.5); TH1F * hQuickFight = new TH1F("","",6,-1.5,4.5); TH1F * hArmiesWon80 = new TH1F("","",nBins1,-0.5,25.5); TH1F * hLeftArmiesWon80 = new TH1F("","",nBins2,-0.5,9.5); TH1F * h6LeftArmiesWon80 = new TH1F("","",nBins1,-0.5,25.5); vector<int> quick_attack; vector<int> quick_defence; ////////////////// 4.0 ////////////////// double rolls = 1e5; for ( int k = 0; k < rolls; k++ ){ quick_attack = throw_n_dice(3); quick_defence = throw_n_dice(3); int quick_survivors; int quick_deseased; for ( size_t i = 0; i < quick_attack.size(); ++i ) hDistrNumb->Fill( quick_attack [i] ); tie ( quick_survivors, quick_deseased ) = Single_round ( quick_attack, quick_defence ); hQuickFight -> Fill( quick_survivors ); } double average_survivors = hQuickFight->GetMean()/3.; cout << "Average number of armies won by dice roll: " << average_survivors << endl; ////////////////// 4.1 ////////////////// int initial_def = 3; int attackers_left; int defencers_left; for ( int init_at = 0; init_at < nBins1; init_at++){ for ( int k = 0; k < rolls; k++ ){ tie ( attackers_left, defencers_left ) = Complete_war ( init_at, initial_def ); if ( attackers_left > defencers_left ) { hArmiesWon80 -> Fill ( init_at ); if ( attackers_left > 5 ) { h6LeftArmiesWon80 -> Fill ( init_at ); } } if ( init_at == 9){ hLeftArmiesWon80 -> Fill ( attackers_left ); } } } double ThreshProb = 80; TLine * L_ThreshProb = new TLine(-0.5,ThreshProb,25.5,ThreshProb); L_ThreshProb->SetLineColor(kRed); L_ThreshProb->SetLineWidth(2); L_ThreshProb->SetLineStyle(2); gStyle->SetOptStat(110); TCanvas * c2 = new TCanvas("c2","c2",1000,700); c2->cd(); double factor = (double) 100. / rolls; hQuickFight->Scale((double) factor); hQuickFight->SetLineColor(kAzure-5); hQuickFight->SetTitle(""); hQuickFight->SetLineWidth(2); hQuickFight->SetFillStyle(3003); hQuickFight->SetFillColor(kAzure+5); hQuickFight->GetYaxis()->SetTitle("Probability [%]"); hQuickFight->GetYaxis()->SetTitleOffset(1.0); hQuickFight->GetYaxis()->SetTitleSize(0.045); hQuickFight->GetXaxis()->SetTitleSize(0.045); hQuickFight->GetXaxis()->SetTitle("Number of surviving armies"); hQuickFight->GetYaxis()->SetRangeUser(0,50); hQuickFight->Draw("hist"); c2->SaveAs("Distr_won_armies_single_round.pdf"); gStyle->SetOptStat(0); TCanvas * c3 = new TCanvas("c3","c3",1000,700); c3->cd(); double factor1 = (double) 100. / rolls; hArmiesWon80->Scale((double) factor1); hArmiesWon80->SetLineColor(kAzure-5); hArmiesWon80->SetTitle(""); hArmiesWon80->SetLineWidth(2); hArmiesWon80->SetFillStyle(3003); hArmiesWon80->SetFillColor(kAzure+5); hArmiesWon80->GetYaxis()->SetTitle("Probability [%]"); hArmiesWon80->GetYaxis()->SetTitleOffset(1.0); hArmiesWon80->GetYaxis()->SetTitleSize(0.045); hArmiesWon80->GetXaxis()->SetTitleOffset(1.0); hArmiesWon80->GetXaxis()->SetTitleSize(0.045); hArmiesWon80->GetXaxis()->SetTitle("Number of initial armies"); hArmiesWon80->Draw("HIST"); L_ThreshProb->Draw("same"); c3->SaveAs("Distribution_80_percent.pdf"); // TCanvas * c4 = new TCanvas("c4","c4",1000,700); // c4->cd(); // hDistrNumb->SetLineColor(kAzure-5); // hDistrNumb->SetTitle(""); // hDistrNumb->SetLineWidth(2); // hDistrNumb->SetFillStyle(3003); // hDistrNumb->SetFillColor(kAzure+5); // hDistrNumb->GetYaxis()->SetTitle("Counts"); // hDistrNumb->GetYaxis()->SetTitleOffset(1.0); // hDistrNumb->GetYaxis()->SetTitleSize(0.045); // hDistrNumb->GetXaxis()->SetTitleOffset(1.0); // hDistrNumb->GetXaxis()->SetTitleSize(0.045); // hDistrNumb->GetXaxis()->SetTitle("Dice outcome"); // hDistrNumb->GetYaxis()->SetRangeUser(0,int((rolls*3/6)+rolls*0.2)); // hDistrNumb->Draw(); // c4->SaveAs("Distribution_numbers_per_die.pdf"); TCanvas * c5 = new TCanvas("c5","c5",1000,700); c5->cd(); double factor2 = (double) 100. / rolls; hLeftArmiesWon80->Scale((double) factor2); hLeftArmiesWon80->SetLineColor(kAzure-5); hLeftArmiesWon80->SetTitle(""); hLeftArmiesWon80->SetLineWidth(2); hLeftArmiesWon80->SetFillStyle(3003); hLeftArmiesWon80->SetFillColor(kAzure+5); hLeftArmiesWon80->GetYaxis()->SetTitle("Probability [%]"); hLeftArmiesWon80->GetYaxis()->SetTitleOffset(1.0); hLeftArmiesWon80->GetYaxis()->SetTitleSize(0.045); hLeftArmiesWon80->GetXaxis()->SetTitleOffset(1.0); hLeftArmiesWon80->GetXaxis()->SetTitleSize(0.045); hLeftArmiesWon80->GetXaxis()->SetTitle("Number of attacker surviving armies"); hLeftArmiesWon80->Draw("HIST"); c5->SaveAs("Distribution_of_armies_won2.pdf"); TCanvas * c6 = new TCanvas("c6","c6",1000,700); c6->cd(); double factor3 = (double) 100. / rolls; h6LeftArmiesWon80->Scale((double) factor3); h6LeftArmiesWon80->SetLineColor(kAzure-5); h6LeftArmiesWon80->SetTitle(""); h6LeftArmiesWon80->SetLineWidth(2); h6LeftArmiesWon80->SetFillStyle(3003); h6LeftArmiesWon80->SetFillColor(kAzure+5); h6LeftArmiesWon80->GetYaxis()->SetTitle("Probability [%]"); h6LeftArmiesWon80->GetYaxis()->SetTitleOffset(1.0); h6LeftArmiesWon80->GetYaxis()->SetTitleOffset(1.0); h6LeftArmiesWon80->GetYaxis()->SetTitleSize(0.045); h6LeftArmiesWon80->GetXaxis()->SetTitleOffset(1.0); h6LeftArmiesWon80->GetXaxis()->SetTitleSize(0.045); h6LeftArmiesWon80->GetXaxis()->SetTitle("Number of initial armies"); h6LeftArmiesWon80->Draw("HIST"); L_ThreshProb->Draw("same"); c6->SaveAs("Distribution_of_armies_won_6_80.pdf"); int minArmies; for ( int i = 0; i < nBins1 + 1; i++ ) { cout << "i: " << i << ", with prob: " << hArmiesWon80 -> GetBinContent( i + 1 ) << endl; if ( hArmiesWon80 -> GetBinContent( i + 1 ) >= 80){ minArmies = i; break; } } cout << "Minimum armies to win the war with probability superior to 80%: " << minArmies << "\n" << endl; int n_rem_min = 6; double prob_n_rem_min = 0.; for ( int i = 0; i < nBins2 + 1; i++ ) { cout << "i: " << i << ", with prob: " << hLeftArmiesWon80 -> GetBinContent ( i + 1 ) << endl; if ( i >= n_rem_min ) prob_n_rem_min += hLeftArmiesWon80 -> GetBinContent ( i + 1 ); } cout << "The prob. of finishing the attack with 6 or more armies is: " << prob_n_rem_min << "\n" << endl; int minArmiesAt80; for ( int i = 0; i < nBins1 + 1; i++ ) { cout << "i: " << i << ", with prob: " << h6LeftArmiesWon80 -> GetBinContent( i + 1 ) << endl; if ( h6LeftArmiesWon80 -> GetBinContent( i + 1 ) >= 80){ minArmiesAt80 = i; break; } } cout << "Minimum armies to finish the war with more than 6 armies in 80% of the cases: " << minArmiesAt80 << "\n" << endl; myapp->Run(); return 0; }
30.488525
126
0.600172
davidjgmarques
8d95b9dab635a3344095a5716af257b108db208f
43
hh
C++
Include/Luce/IsOriginalType.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
23
2017-02-09T11:48:01.000Z
2017-04-08T10:19:21.000Z
Include/Luce/IsOriginalType.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
null
null
null
Include/Luce/IsOriginalType.hh
kmc7468/luce
6f71407f250dbc0428ceba33aeef345cc601db34
[ "MIT" ]
null
null
null
#include <Luce/TypeTrait/IsOriginalType.hh>
43
43
0.837209
kmc7468
8d95dbe987289460d119fa679b03aa406d3fc39d
1,345
cpp
C++
201-300/279-Perfect_Squares-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
201-300/279-Perfect_Squares-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
201-300/279-Perfect_Squares-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given a positive integer n, find the least number of perfect square numbers // (for example, 1, 4, 9, 16, ...) which sum to n. // For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, // return 2 because 13 = 4 + 9. // Credits: // Special thanks to @jianchao.li.fighter for adding this problem and creating // all test cases. class Solution { public: int numSquares(int n) { vector<int> dp(n + 1, INT_MAX); dp[0] = 0; // for(int i = 1; i <= n; ++i) // for(int j = 1, j_squ; (j_squ = j * j) <= i; ++j) for (int j = 1, j_squ; (j_squ = j * j) <= n; ++j) for (int i = j_squ; i <= n; ++i) dp[i] = min(dp[i], dp[i - j_squ] + 1); return dp[n]; } }; // mathematical way // https://www.alpertron.com.ar/4SQUARES.HTM class Solution { public: int is_square(int n) { int t = sqrt(n); return t * t == n; } int numSquares(int n) { // case 1 if (is_square(n)) return 1; // case 4: 4^r(8k + 7) while (n % 4 == 0) n /= 4; if (n % 8 == 7) return 4; // case 2 for (int i = 1, i_squ; (i_squ = i * i) <= n; ++i) if (is_square(n - i_squ)) return 2; // case 3 return 3; } };
24.907407
79
0.466171
ysmiles
8d9ddecdf67249e20cdf8922b70bda0bb92f2f9e
7,037
cpp
C++
source/common/rendering/gles/gles_samplers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
1
2022-03-30T15:53:09.000Z
2022-03-30T15:53:09.000Z
source/common/rendering/gles/gles_samplers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
null
null
null
source/common/rendering/gles/gles_samplers.cpp
Quake-Backup/Raze
16c81f0b1f409436ebf576d2c23f2459a29b34b4
[ "RSA-MD" ]
null
null
null
/* ** gl_samplers.cpp ** ** Texture sampler handling ** **--------------------------------------------------------------------------- ** Copyright 2015-2019 Christoph Oelckers ** 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. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "gles_system.h" #include "c_cvars.h" #include "hw_cvars.h" #include "gles_renderer.h" #include "gles_samplers.h" #include "hw_material.h" #include "i_interface.h" namespace OpenGLESRenderer { extern TexFilter_s TexFilter[]; FSamplerManager::FSamplerManager() { SetTextureFilterMode(); } FSamplerManager::~FSamplerManager() { } void FSamplerManager::UnbindAll() { } uint8_t FSamplerManager::Bind(int texunit, int num, int lastval) { int filter = sysCallbacks.DisableTextureFilter && sysCallbacks.DisableTextureFilter() ? 0 : gl_texture_filter; glActiveTexture(GL_TEXTURE0 + texunit); switch (num) { case CLAMP_NONE: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_X: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_Y: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_XY: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (lastval >= CLAMP_XY_NOMIP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); } break; case CLAMP_XY_NOMIP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); break; case CLAMP_NOFILTER: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_NOFILTER_X: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_NOFILTER_Y: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_NOFILTER_XY: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case CLAMP_CAMTEX: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); break; } glActiveTexture(GL_TEXTURE0); return 255; } void FSamplerManager::SetTextureFilterMode() { /* GLRenderer->FlushTextures(); GLint bounds[IHardwareTexture::MAX_TEXTURES]; // Unbind all for(int i = IHardwareTexture::MAX_TEXTURES-1; i >= 0; i--) { glActiveTexture(GL_TEXTURE0 + i); glGetIntegerv(GL_SAMPLER_BINDING, &bounds[i]); glBindSampler(i, 0); } int filter = sysCallbacks.DisableTextureFilter && sysCallbacks.DisableTextureFilter() ? 0 : gl_texture_filter; for (int i = 0; i < 4; i++) { glSamplerParameteri(mSamplers[i], GL_TEXTURE_MIN_FILTER, TexFilter[filter].minfilter); glSamplerParameteri(mSamplers[i], GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); glSamplerParameterf(mSamplers[i], GL_TEXTURE_MAX_ANISOTROPY_EXT, filter > 0? gl_texture_filter_anisotropic : 1.0); } glSamplerParameteri(mSamplers[CLAMP_XY_NOMIP], GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glSamplerParameteri(mSamplers[CLAMP_XY_NOMIP], GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); glSamplerParameteri(mSamplers[CLAMP_CAMTEX], GL_TEXTURE_MIN_FILTER, TexFilter[filter].magfilter); glSamplerParameteri(mSamplers[CLAMP_CAMTEX], GL_TEXTURE_MAG_FILTER, TexFilter[filter].magfilter); for(int i = 0; i < IHardwareTexture::MAX_TEXTURES; i++) { glBindSampler(i, bounds[i]); } */ } }
35.903061
116
0.77533
Quake-Backup
8d9f59e551cb8ff562e4f7744edbcd051282d481
2,193
hpp
C++
modules/boost/simd/base/include/boost/simd/swar/functions/splatted_minimum.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/swar/functions/splatted_minimum.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/swar/functions/splatted_minimum.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2013 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SWAR_FUNCTIONS_SPLATTED_MINIMUM_HPP_INCLUDED #define BOOST_SIMD_SWAR_FUNCTIONS_SPLATTED_MINIMUM_HPP_INCLUDED #include <boost/simd/include/functor.hpp> #include <boost/dispatch/include/functor.hpp> namespace boost { namespace simd { namespace tag { /*! @brief splatted_minimum generic tag Represents the splatted_minimum function in generic contexts. **/ struct splatted_minimum_ : ext::unspecified_<splatted_minimum_> { /// @brief Parent hierarchy typedef ext::unspecified_<splatted_minimum_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_splatted_minimum_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site, class... Ts> BOOST_FORCEINLINE generic_dispatcher<tag::splatted_minimum_, Site> dispatching_splatted_minimum_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...) { return generic_dispatcher<tag::splatted_minimum_, Site>(); } template<class... Args> struct impl_splatted_minimum_; } /*! @brief Splatted minimum Computes the splatted minimum of the element of its argument. @par Semantic @code Type r = splatted_minimum(v); @endcode @code for(int i=0;i<Type::static_size;++i) x[i] = minimum(v); @endcode @param a0 @return a value of the same type as the parameter */ BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::splatted_minimum_, splatted_minimum, 1) } } #endif
31.782609
191
0.639307
psiha
8da01051e45342f754ec1a84c61711a99458bbc5
40,282
ipp
C++
src/maral/mtl/matrix_ops.ipp
arminms/maral
72ac000aa5e37702beec3b3423db7ab2e43da01e
[ "BSL-1.0" ]
1
2022-03-01T19:00:17.000Z
2022-03-01T19:00:17.000Z
src/maral/mtl/matrix_ops.ipp
arminms/maral
72ac000aa5e37702beec3b3423db7ab2e43da01e
[ "BSL-1.0" ]
2
2016-04-28T18:51:08.000Z
2016-05-25T19:43:19.000Z
src/maral/mtl/matrix_ops.ipp
arminms/maral
72ac000aa5e37702beec3b3423db7ab2e43da01e
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // MARAL // (Molecular Architectural Record & Assembly Library) // // Copyright (C) by Armin Madadkar-Sobhani arminms@gmail.com // // See the LICENSE file for terms of use // //------------------------------------------------------------------------------ // $Id$ //------------------------------------------------------------------------------ // Filename: // matrix_ops.ipp //------------------------------------------------------------------------------ // Remarks: // This file contains implementation for all operations related to matrices. //------------------------------------------------------------------------------ /// \ingroup mtx22ops /// \name matrix22 Operations /// @{ //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix22 objects to see if they are /// exactly the same . /// \see operator!=(const matrix22&, const matrix22&) template<typename T> inline bool operator== ( const matrix22<T>& m1, const matrix22<T>& m2) { return ( m1(0) == m2(0) && m1(1) == m2(1) && m1(2) == m2(2) && m1(3) == m2(3) ); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 does not equal \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix22 objects to see if they are /// NOT exactly the same with zero tolerance. /// \see operator==(const matrix22&, const matrix22&) template<typename T> inline bool operator!= ( const matrix22<T>& m1, const matrix22<T>& m2) { return ( m1(0) != m2(0) || m1(1) != m2(1) || m1(2) != m2(2) || m1(3) != m2(3) ); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2 within the tolerance; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \param eps The epsilon tolerance value. /// \pre eps must be >= 0 /// \remarks /// Compares \a m1 and \a m2 to see if they are the same within the given /// epsilon tolerance. /// \see operator==(const matrix22&, const matrix22&) template<typename T> inline bool is_equal( const matrix22<T>& m1, const matrix22<T>& m2, const T eps = T(0.0005) ) { BOOST_ASSERT_MSG(eps >= 0, "negative tolerance!"); return ( std::abs(m1(0) - m2(0)) <= eps && std::abs(m1(1) - m2(1)) <= eps && std::abs(m1(2) - m2(2)) <= eps && std::abs(m1(3) - m2(3)) <= eps ); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// You can safely pass either \a lhs or \a rhs as \a r. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This function puts results of the \a lhs and \a rhs matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a lhs * \a rhs (where \a rhs is applied first). /// \see operator*(const matrix22&, const matrix22&) template<typename T> inline matrix22<T>& mult( matrix22<T>& r, const matrix22<T>& lhs, const matrix22<T>& rhs) { matrix22<T> ret; // prevents aliasing ret.zero(); ret(0) += lhs(0) * rhs(0); ret(0) += lhs(2) * rhs(1); ret(1) += lhs(1) * rhs(0); ret(1) += lhs(3) * rhs(1); ret(2) += lhs(0) * rhs(2); ret(2) += lhs(2) * rhs(3); ret(3) += lhs(1) * rhs(2); ret(3) += lhs(3) * rhs(3); return r = ret; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a operand * \a r /// \remarks /// This function puts results of the \a operand and \a r matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a operand * \a r. /// \see mult(matrix22<T>&,const matrix22&, const matrix22&), /// postMult(matrix22<T>&,const matrix22<T>& operand) template<typename T> inline matrix22<T>& pre_mult( matrix22<T>& r, const matrix22<T>& operand) { return mult(r, operand, r); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This function puts results of the \a r and \a operand matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a r * \a operand. /// \see mult(matrix22<T>&,const matrix22&, const matrix22&), /// preMult(matrix22<T>&,const matrix22<T>& operand) template<typename T> inline matrix22<T>& post_mult( matrix22<T>& r, const matrix22<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This overloaded binary operator multiplies \a rhs by \a lhs then returns the /// result. This is equivalent to the expression \a r = \a lhs * \a rhs (where /// \a rhs is applied first). /// \see mult(matrix22<T>&,const matrix22&, const matrix22&) template<typename T> inline matrix22<T> operator* ( const matrix22<T>& lhs, const matrix22<T>& rhs) { matrix22<T> temp; return mult(temp, lhs, rhs); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This overloaded binary operator multiplies \a r by \a operand and then /// returns reference to \a r. In this way, it can be used as a parameter for /// another function. This is equivalent to the expression \a r = \a r * /// \a operand. /// \see postMult(matrix22<T>&,const matrix22<T>& operand) template<typename T> inline matrix22<T>& operator*= ( matrix22<T>& r, const matrix22<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix to be transposed. /// \remarks /// This function transposes the given matrix \a r in place and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix22&, const matrix22&) template<typename T> inline matrix22<T>& transpose( matrix22<T>& r) { std::swap(r(1), r(2)); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \remarks /// This function puts the result of transposing \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix22&) template<typename T> inline matrix22<T>& transpose( matrix22<T>& r, const matrix22<T>& s) { r(0) = s(0); r(1) = s(2); r(2) = s(1); r(3) = s(3); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return The determinant of the matrix. /// \param m Reference to the matrix used for the determinant calculation. /// \remarks /// This function computes the determinant of the \a m matrix. Determinant is /// used for the calculation of the inverse of a matrix. /// \see invert(matrix22&, const matrix22&) template<typename T> inline T determinant( const matrix22<T>& m) { return ( (m(0)*m(3)) - (m(1)*m(2)) ); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \pre Only works with float types (e.g. matrix22<int> is not acceptable). /// \remarks /// This function puts the result of inverting \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see invert(const matrix22&) template<typename T> inline matrix22<T>& invert( matrix22<T>& r, const matrix22<T>& s) { T det = ( (s(0)*s(3)) - (s(1)*s(2)) ); BOOST_ASSERT_MSG(std::abs(det) > SMALL, "not invertible!"); T one_over_det = T(1) / det; r(0) = s(3) * one_over_det; r(1) = -s(1) * one_over_det; r(2) = -s(2) * one_over_det; r(3) = s(0) * one_over_det; return r; } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param m Reference to the matrix to be inverted. /// \pre Only works with float types (e.g. matrix22<int> is not acceptable). /// \remarks /// This function inverts the given matrix \a m and then returns the result. In /// this way, it can be used as a parameter for another function. /// \see invert(matrix22&, const matrix22&) template<typename T> inline matrix22<T> invert( const matrix22<T>& m) { matrix22<T> r; return invert(r, m); } /// @} /// \ingroup mtx33ops /// \name matrix33 Operations /// @{ //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix33 objects to see if they are /// exactly the same . /// \see operator!=(const matrix33&, const matrix33&) template<typename T> inline bool operator== ( const matrix33<T>& m1, const matrix33<T>& m2) { return ( m1(0) == m2(0) && m1(1) == m2(1) && m1(2) == m2(2) && m1(3) == m2(3) && m1(4) == m2(4) && m1(5) == m2(5) && m1(6) == m2(6) && m1(7) == m2(7) && m1(8) == m2(8)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 does not equal \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix33 objects to see if they are /// NOT exactly the same with zero tolerance. /// \see operator==(const matrix33&, const matrix33&) template<typename T> inline bool operator!= ( const matrix33<T>& m1, const matrix33<T>& m2) { return ( m1(0) != m2(0) || m1(1) != m2(1) || m1(2) != m2(2) || m1(3) != m2(3) || m1(4) != m2(4) || m1(5) != m2(5) || m1(6) != m2(6) || m1(7) != m2(7) || m1(8) != m2(8)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2 within the tolerance; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \param eps The epsilon tolerance value. /// \pre eps must be >= 0 /// \remarks /// Compares \a m1 and \a m2 to see if they are the same within the given /// epsilon tolerance. /// \see operator==(const matrix33&, const matrix33&) template<typename T> inline bool is_equal( const matrix33<T>& m1, const matrix33<T>& m2, const T eps = T(0.0005) ) { BOOST_ASSERT_MSG(eps >= 0, "negative tolerance!"); return ( std::abs(m1(0) - m2(0)) <= eps && std::abs(m1(1) - m2(1)) <= eps && std::abs(m1(2) - m2(2)) <= eps && std::abs(m1(3) - m2(3)) <= eps && std::abs(m1(4) - m2(4)) <= eps && std::abs(m1(5) - m2(5)) <= eps && std::abs(m1(6) - m2(6)) <= eps && std::abs(m1(7) - m2(7)) <= eps && std::abs(m1(8) - m2(8)) <= eps); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// You can safely pass either \a lhs or \a rhs as \a r. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This function puts results of the \a lhs and \a rhs matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a lhs * \a rhs (where \a rhs is applied first). /// \see operator*(const matrix33&, const matrix33&) template<typename T> inline matrix33<T>& mult( matrix33<T>& r, const matrix33<T>& lhs, const matrix33<T>& rhs) { matrix33<T> ret; // prevents aliasing ret.zero(); ret(0) += lhs(0) * rhs(0); ret(0) += lhs(3) * rhs(1); ret(0) += lhs(6) * rhs(2); ret(1) += lhs(1) * rhs(0); ret(1) += lhs(4) * rhs(1); ret(1) += lhs(7) * rhs(2); ret(2) += lhs(2) * rhs(0); ret(2) += lhs(5) * rhs(1); ret(2) += lhs(8) * rhs(2); ret(3) += lhs(0) * rhs(3); ret(3) += lhs(3) * rhs(4); ret(3) += lhs(6) * rhs(5); ret(4) += lhs(1) * rhs(3); ret(4) += lhs(4) * rhs(4); ret(4) += lhs(7) * rhs(5); ret(5) += lhs(2) * rhs(3); ret(5) += lhs(5) * rhs(4); ret(5) += lhs(8) * rhs(5); ret(6) += lhs(0) * rhs(6); ret(6) += lhs(3) * rhs(7); ret(6) += lhs(6) * rhs(8); ret(7) += lhs(1) * rhs(6); ret(7) += lhs(4) * rhs(7); ret(7) += lhs(7) * rhs(8); ret(8) += lhs(2) * rhs(6); ret(8) += lhs(5) * rhs(7); ret(8) += lhs(8) * rhs(8); return r = ret; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a operand * \a r /// \remarks /// This function puts results of the \a operand and \a r matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a operand * \a r. /// \see mult(matrix33<T>&,const matrix33&, const matrix33&), /// postMult(matrix33<T>&,const matrix33<T>& operand) template<typename T> inline matrix33<T>& pre_mult( matrix33<T>& r, const matrix33<T>& operand) { return mult(r, operand, r); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This function puts results of the \a r and \a operand matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a r * \a operand. /// \see mult(matrix33<T>&,const matrix33&, const matrix33&), /// preMult(matrix33<T>&,const matrix33<T>& operand) template<typename T> inline matrix33<T>& post_mult( matrix33<T>& r, const matrix33<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This overloaded binary operator multiplies \a rhs by \a lhs then returns the /// result. This is equivalent to the expression \a r = \a lhs * \a rhs (where /// \a rhs is applied first). /// \see mult(matrix33<T>&,const matrix33&, const matrix33&) template<typename T> inline matrix33<T> operator* ( const matrix33<T>& lhs, const matrix33<T>& rhs) { matrix33<T> temp; return mult(temp, lhs, rhs); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This overloaded binary operator multiplies \a r by \a operand and then /// returns reference to \a r. In this way, it can be used as a parameter for /// another function. This is equivalent to the expression \a r = \a r * /// \a operand. /// \see postMult(matrix33<T>&,const matrix33<T>& operand) template<typename T> inline matrix33<T>& operator*= ( matrix33<T>& r, const matrix33<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix to be transposed. /// \remarks /// This function transposes the given matrix \a r in place and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix33&, const matrix33&) template<typename T> inline matrix33<T>& transpose( matrix33<T>& r) { std::swap(r(1), r(3)); std::swap(r(2), r(6)); std::swap(r(5), r(7)); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \remarks /// This function puts the result of transposing \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix33&) template<typename T> inline matrix33<T>& transpose( matrix33<T>& r, const matrix33<T>& s) { r(0) = s(0); r(1) = s(3); r(2) = s(6); r(3) = s(1); r(4) = s(4); r(5) = s(7); r(6) = s(2); r(7) = s(5); r(8) = s(8); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return The determinant of the matrix. /// \param m Reference to the matrix used for the determinant calculation. /// \remarks /// This function computes the determinant of the \a m matrix. Determinant is /// used for the calculation of the inverse of a matrix. /// \see invert(matrix33&, const matrix33&) template<typename T> inline T determinant( const matrix33<T>& m) { return ((((m(3)*m(7)) - (m(6)*m(4))) * m(2)) + (((m(6)*m(1)) - (m(0)*m(7))) * m(5)) + (((m(0)*m(4)) - (m(3)*m(1))) * m(8))); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \pre Only works with float types (e.g. matrix33<int> is not acceptable). /// \remarks /// This function puts the result of inverting \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. It uses the \a classical \a adjoint method to compute the inverse. /// \see invert(const matrix33&) template<typename T> inline matrix33<T>& invert( matrix33<T>& r, const matrix33<T>& s) { T det = determinant(s); BOOST_ASSERT_MSG(std::abs(det) > SMALL, "not invertible!"); T one_over_det = T(1) / det; r(0) = ((s(4)*s(8))-(s(7)*s(5)))*one_over_det; r(1) = ((s(7)*s(2))-(s(1)*s(8)))*one_over_det; r(2) = ((s(1)*s(5))-(s(4)*s(2)))*one_over_det; r(3) = ((s(6)*s(5))-(s(3)*s(8)))*one_over_det; r(4) = ((s(0)*s(8))-(s(6)*s(2)))*one_over_det; r(5) = ((s(3)*s(2))-(s(0)*s(5)))*one_over_det; r(6) = ((s(3)*s(7))-(s(6)*s(4)))*one_over_det; r(7) = ((s(6)*s(1))-(s(0)*s(7)))*one_over_det; r(8) = ((s(0)*s(4))-(s(3)*s(1)))*one_over_det; return r; } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param m Reference to the matrix to be inverted. /// \pre Only works with float types (e.g. matrix33<int> is not acceptable). /// \remarks /// This function inverts the given matrix \a m and then returns the result. In /// this way, it can be used as a parameter for another function. It uses the \a /// classical \a adjoint method to compute the inverse. /// \see invert(matrix33&, const matrix33&) template<typename T> inline matrix33<T> invert( const matrix33<T>& m) { matrix33<T> r; return invert(r, m); } /// @} /// \ingroup mtx44ops /// \name matrix44 Operations /// @{ //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix44 objects to see if they are /// exactly the same . /// \see operator!=(const matrix44&, const matrix44&) template<typename T> inline bool operator== ( const matrix44<T>& m1, const matrix44<T>& m2) { return ( m1 (0) == m2 (0) && m1 (1) == m2 (1) && m1 (2) == m2 (2) && m1 (3) == m2 (3) && m1 (4) == m2 (4) && m1 (5) == m2 (5) && m1 (6) == m2 (6) && m1 (7) == m2 (7) && m1 (8) == m2 (8) && m1 (9) == m2 (9) && m1(10) == m2(10) && m1(11) == m2(11) && m1(12) == m2(12) && m1(13) == m2(13) && m1(14) == m2(14) && m1(15) == m2(15)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 does not equal \a m2; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \remarks /// This overloaded operator compares two matrix44 objects to see if they are /// NOT exactly the same with zero tolerance. /// \see operator==(const matrix44&, const matrix44&) template<typename T> inline bool operator!= ( const matrix44<T>& m1, const matrix44<T>& m2) { return ( m1 (0) != m2 (0) || m1 (1) != m2 (1) || m1 (2) != m2 (2) || m1 (3) != m2 (3) || m1 (4) != m2 (4) || m1 (5) != m2 (5) || m1 (6) != m2 (6) || m1 (7) != m2 (7) || m1 (8) != m2 (8) || m1 (9) != m2 (9) || m1(10) != m2(10) || m1(11) != m2(11) || m1(12) != m2(12) || m1(13) != m2(13) || m1(14) != m2(14) || m1(15) != m2(15)); } //////////////////////////////////////////////////////////////////////////////// /// \return A \b bool type containing result of the comparison. \a true if /// \a m1 equals \a m2 within the tolerance; \a false otherwise. /// \param m1 Reference to the first matrix. /// \param m2 Reference to the second matrix. /// \param eps The epsilon tolerance value. /// \pre eps must be >= 0 /// \remarks /// Compares \a m1 and \a m2 to see if they are the same within the given /// epsilon tolerance. /// \see operator==(const matrix44&, const matrix44&) template<typename T> inline bool is_equal( const matrix44<T>& m1, const matrix44<T>& m2, const T eps = T(0.0005) ) { BOOST_ASSERT_MSG(eps >= 0, "negative tolerance!"); return ( std::abs(m1 (0) - m2 (0)) <= eps && std::abs(m1 (1) - m2 (1)) <= eps && std::abs(m1 (2) - m2 (2)) <= eps && std::abs(m1 (3) - m2 (3)) <= eps && std::abs(m1 (4) - m2 (4)) <= eps && std::abs(m1 (5) - m2 (5)) <= eps && std::abs(m1 (6) - m2 (6)) <= eps && std::abs(m1 (7) - m2 (7)) <= eps && std::abs(m1 (8) - m2 (8)) <= eps && std::abs(m1 (9) - m2 (9)) <= eps && std::abs(m1(10) - m2(10)) <= eps && std::abs(m1(11) - m2(11)) <= eps && std::abs(m1(12) - m2(12)) <= eps && std::abs(m1(13) - m2(13)) <= eps && std::abs(m1(14) - m2(14)) <= eps && std::abs(m1(15) - m2(15)) <= eps); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// You can safely pass either \a lhs or \a rhs as \a r. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This function puts results of the \a lhs and \a rhs matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a lhs * \a rhs (where \a rhs is applied first). /// \see operator*(const matrix44&, const matrix44&) template<typename T> inline matrix44<T>& mult( matrix44<T>& r, const matrix44<T>& lhs, const matrix44<T>& rhs) { matrix44<T> ret; // prevents aliasing ret.zero(); ret (0) += lhs (0) * rhs (0); ret (0) += lhs (4) * rhs (1); ret (0) += lhs (8) * rhs (2); ret (0) += lhs(12) * rhs (3); ret (1) += lhs (1) * rhs (0); ret (1) += lhs (5) * rhs (1); ret (1) += lhs (9) * rhs (2); ret (1) += lhs(13) * rhs (3); ret (2) += lhs (2) * rhs (0); ret (2) += lhs (6) * rhs (1); ret (2) += lhs(10) * rhs (2); ret (2) += lhs(14) * rhs (3); ret (3) += lhs (3) * rhs (0); ret (3) += lhs (7) * rhs (1); ret (3) += lhs(11) * rhs (2); ret (3) += lhs(15) * rhs (3); ret (4) += lhs (0) * rhs (4); ret (4) += lhs (4) * rhs (5); ret (4) += lhs (8) * rhs (6); ret (4) += lhs(12) * rhs (7); ret (5) += lhs (1) * rhs (4); ret (5) += lhs (5) * rhs (5); ret (5) += lhs (9) * rhs (6); ret (5) += lhs(13) * rhs (7); ret (6) += lhs (2) * rhs (4); ret (6) += lhs (6) * rhs (5); ret (6) += lhs(10) * rhs (6); ret (6) += lhs(14) * rhs (7); ret (7) += lhs (3) * rhs (4); ret (7) += lhs (7) * rhs (5); ret (7) += lhs(11) * rhs (6); ret (7) += lhs(15) * rhs (7); ret (8) += lhs (0) * rhs (8); ret (8) += lhs (4) * rhs (9); ret (8) += lhs (8) * rhs(10); ret (8) += lhs(12) * rhs(11); ret (9) += lhs (1) * rhs (8); ret (9) += lhs (5) * rhs (9); ret (9) += lhs (9) * rhs(10); ret (9) += lhs(13) * rhs(11); ret(10) += lhs (2) * rhs (8); ret(10) += lhs (6) * rhs (9); ret(10) += lhs(10) * rhs(10); ret(10) += lhs(14) * rhs(11); ret(11) += lhs (3) * rhs (8); ret(11) += lhs (7) * rhs (9); ret(11) += lhs(11) * rhs(10); ret(11) += lhs(15) * rhs(11); ret(12) += lhs (0) * rhs(12); ret(12) += lhs (4) * rhs(13); ret(12) += lhs (8) * rhs(14); ret(12) += lhs(12) * rhs(15); ret(13) += lhs (1) * rhs(12); ret(13) += lhs (5) * rhs(13); ret(13) += lhs (9) * rhs(14); ret(13) += lhs(13) * rhs(15); ret(14) += lhs (2) * rhs(12); ret(14) += lhs (6) * rhs(13); ret(14) += lhs(10) * rhs(14); ret(14) += lhs(14) * rhs(15); ret(15) += lhs (3) * rhs(12); ret(15) += lhs (7) * rhs(13); ret(15) += lhs(11) * rhs(14); ret(15) += lhs(15) * rhs(15); return r = ret; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a operand * \a r /// \remarks /// This function puts results of the \a operand and \a r matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a operand * \a r. /// \see mult(matrix44<T>&,const matrix44&, const matrix44&), /// postMult(matrix44<T>&,const matrix44<T>& operand) template<typename T> inline matrix44<T>& pre_mult( matrix44<T>& r, const matrix44<T>& operand) { return mult(r, operand, r); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This function puts results of the \a r and \a operand matrix multiplication /// into \a r and then returns reference to \a r. In this way, it can be used as /// a parameter for another function. This is equivalent to the expression \a r /// = \a r * \a operand. /// \see mult(matrix44<T>&,const matrix44&, const matrix44&), /// preMult(matrix44<T>&,const matrix44<T>& operand) template<typename T> inline matrix44<T>& post_mult( matrix44<T>& r, const matrix44<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param lhs Reference to the left-hand side matrix. /// \param rhs Reference to the right-hand side matrix. /// \remarks /// This overloaded binary operator multiplies \a rhs by \a lhs then returns the /// result. This is equivalent to the expression \a r = \a lhs * \a rhs (where /// \a rhs is applied first). /// \see mult(matrix44<T>&,const matrix44&, const matrix44&) template<typename T> inline matrix44<T> operator* ( const matrix44<T>& lhs, const matrix44<T>& rhs) { matrix44<T> temp; return mult(temp, lhs, rhs); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after getting the result of the operation. /// \param r Reference to a matrix that receives the result of the operation. /// \param operand Reference to a matrix. /// \post \a r = \a r * \a operand /// \remarks /// This overloaded binary operator multiplies \a r by \a operand and then /// returns reference to \a r. In this way, it can be used as a parameter for /// another function. This is equivalent to the expression \a r = \a r * /// \a operand. /// \see postMult(matrix44<T>&,const matrix44<T>& operand) template<typename T> inline matrix44<T>& operator*= ( matrix44<T>& r, const matrix44<T>& operand) { return mult(r, r, operand); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix to be transposed. /// \remarks /// This function transposes the given matrix \a r in place and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix44&, const matrix44&) template<typename T> inline matrix44<T>& transpose( matrix44<T>& r) { std::swap(r (1), r (4)); std::swap(r (2), r (8)); std::swap(r (3), r(12)); std::swap(r (6), r (9)); std::swap(r (7), r(13)); std::swap(r(11), r(14)); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \remarks /// This function puts the result of transposing \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. /// \see transpose(matrix44&) template<typename T> inline matrix44<T>& transpose( matrix44<T>& r, const matrix44<T>& s) { r (0) = s (0); r (1) = s (4); r (2) = s (8); r (3) = s(12); r (4) = s (1); r (5) = s (5); r (6) = s (9); r (7) = s(13); r (8) = s (2); r (9) = s (6); r(10) = s(10); r(11) = s(14); r(12) = s (3); r(13) = s (7); r(14) = s(11); r(15) = s(15); return r; } //////////////////////////////////////////////////////////////////////////////// /// \return The determinant of the matrix. /// \param m Reference to the matrix used for the determinant calculation. /// \remarks /// This function computes the determinant of the \a m matrix. Determinant is /// used for the calculation of the inverse of a matrix. /// \see invert(matrix44&, const matrix44&) template<typename T> inline T determinant( const matrix44<T>& m) { return ((( (((m(10)*m(15))-(m(14)*m(11)))*m (5)) + (((m(14)*m (7))-(m (6)*m(15)))*m (9)) + (((m (6)*m(11))-(m(10)*m (7)))*m(13))) *m (0)) - (( (((m(10)*m(15))-(m(14)*m(11)))*m (1)) + (((m(14)*m (3))-(m (2)*m(15)))*m (9)) + (((m (2)*m(11))-(m(10)*m (3)))*m(13))) *m (4)) + (( (((m (6)*m(15))-(m(14)*m (7)))*m (1)) + (((m(14)*m (3))-(m (2)*m(15)))*m (5)) + (((m (2)*m (7))-(m (6)*m (3)))*m(13))) *m (8)) - (( (((m (6)*m(11))-(m(10)*m (7)))*m (1)) + (((m(10)*m (3))-(m (2)*m(11)))*m (5)) + (((m (2)*m (7))-(m (6)*m (3)))*m (9))) *m(12) )); } //////////////////////////////////////////////////////////////////////////////// /// \return \a r after the operation. /// \param r Reference to the matrix that receives the result of the operation. /// \param s Reference to the source matrix. /// \pre Only works with float types (e.g. matrix44<int> is not acceptable). /// \remarks /// This function puts the result of inverting \a s into \a r and then returns /// reference to \a r. In this way, it can be used as a parameter for another /// function. It uses the \a classical \a adjoint method to compute the inverse. /// \see invert(const matrix44&) template<typename T> inline matrix44<T>& invert( matrix44<T>& r, const matrix44<T>& s) { T det = determinant(s); BOOST_ASSERT_MSG(std::abs(det) > SMALL, "not invertible!"); T one_over_det = T(1) / det; r (0) = ((s (5)*s(10)*s(15)) + (s (9)*s(14)*s (7)) + (s(13)*s (6)*s(11)) - (s (5)*s(14)*s(11)) - (s (9)*s (6)*s(15)) - (s(13)*s(10)*s (7))) * one_over_det; r (1) = ((s (1)*s(14)*s(11)) + (s (9)*s (2)*s(15)) + (s(13)*s(10)*s (3)) - (s (1)*s(10)*s(15)) - (s (9)*s(14)*s (3)) - (s(13)*s (2)*s(11))) * one_over_det; r (2) = ((s (1)*s (6)*s(15)) + (s (5)*s(14)*s (3)) + (s(13)*s (2)*s (7)) - (s (1)*s(14)*s (7)) - (s (5)*s (2)*s(15)) - (s(13)*s (6)*s (3))) * one_over_det; r (3) = ((s (1)*s(10)*s (7)) + (s (5)*s (2)*s(11)) + (s (9)*s (6)*s (3)) - (s (1)*s (6)*s(11)) - (s (5)*s(10)*s (3)) - (s (9)*s (2)*s (7))) * one_over_det; r (4) = ((s (4)*s(14)*s(11)) + (s (8)*s (6)*s(15)) + (s(12)*s(10)*s (7)) - (s (4)*s(10)*s(15)) - (s (8)*s(14)*s (7)) - (s(12)*s (6)*s(11))) * one_over_det; r (5) = ((s (0)*s(10)*s(15)) + (s (8)*s(14)*s (3)) + (s(12)*s (2)*s(11)) - (s (0)*s(14)*s(11)) - (s (8)*s (2)*s(15)) - (s(12)*s(10)*s (3))) * one_over_det; r (6) = ((s (0)*s(14)*s (7)) + (s (4)*s (2)*s(15)) + (s(12)*s (6)*s (3)) - (s (0)*s (6)*s(15)) - (s (4)*s(14)*s (3)) - (s(12)*s (2)*s (7))) * one_over_det; r (7) = ((s (0)*s (6)*s(11)) + (s (4)*s(10)*s (3)) + (s (8)*s (2)*s (7)) - (s (0)*s(10)*s (7)) - (s (4)*s (2)*s(11)) - (s (8)*s (6)*s (3))) * one_over_det; r (8) = ((s (4)*s (9)*s(15)) + (s (8)*s(13)*s (7)) + (s(12)*s (5)*s(11)) - (s (4)*s(13)*s(11)) - (s (8)*s (5)*s(15)) - (s(12)*s (9)*s (7))) * one_over_det; r (9) = ((s (0)*s(13)*s(11)) + (s (8)*s (1)*s(15)) + (s(12)*s (9)*s (3)) - (s (0)*s (9)*s(15)) - (s (8)*s(13)*s (3)) - (s(12)*s (1)*s(11))) * one_over_det; r(10) = ((s (0)*s (5)*s(15)) + (s (4)*s(13)*s (3)) + (s(12)*s (1)*s (7)) - (s (0)*s(13)*s (7)) - (s (4)*s (1)*s(15)) - (s(12)*s (5)*s (3))) * one_over_det; r(11) = ((s (0)*s (9)*s (7)) + (s (4)*s (1)*s(11)) + (s (8)*s (5)*s (3)) - (s (0)*s (5)*s(11)) - (s (4)*s (9)*s (3)) - (s (8)*s (1)*s (7))) * one_over_det; r(12) = ((s (4)*s(13)*s(10)) + (s (8)*s (5)*s(14)) + (s(12)*s (9)*s (6)) - (s (4)*s (9)*s(14)) - (s (8)*s(13)*s (6)) - (s(12)*s (5)*s(10))) * one_over_det; r(13) = ((s (0)*s (9)*s(14)) + (s (8)*s(13)*s (2)) + (s(12)*s (1)*s(10)) - (s (0)*s(13)*s(10)) - (s (8)*s (1)*s(14)) - (s(12)*s (9)*s (2))) * one_over_det; r(14) = ((s (0)*s(13)*s (6)) + (s (4)*s (1)*s(14)) + (s(12)*s (5)*s (2)) - (s (0)*s (5)*s(14)) - (s (4)*s(13)*s (2)) - (s(12)*s (1)*s (6))) * one_over_det; r(15) = ((s (0)*s (5)*s(10)) + (s (4)*s (9)*s (2)) + (s (8)*s (1)*s (6)) - (s (0)*s (9)*s (6)) - (s (4)*s (1)*s(10)) - (s (8)*s (5)*s (2))) * one_over_det; return r; } //////////////////////////////////////////////////////////////////////////////// /// \return Result of the operation. /// \param m Reference to the matrix to be inverted. /// \pre Only works with float types (e.g. matrix44<int> is not acceptable). /// \remarks /// This function inverts the given matrix \a m and then returns the result. In /// this way, it can be used as a parameter for another function. It uses the \a /// classical \a adjoint method to compute the inverse. /// \see invert(matrix44&, const matrix44&) template<typename T> inline matrix44<T> invert( const matrix44<T>& m) { matrix44<T> r; return invert(r, m); } /// @}
34.666093
80
0.502408
arminms
8daa226990508d749b8fe10c744ea91111c11ad8
14,755
cpp
C++
tcp_client/imager/Image_viewer.cpp
v0d0m3r/testing_task
d5fbb01bf4b6736dce43101397247da725df9c65
[ "MIT" ]
null
null
null
tcp_client/imager/Image_viewer.cpp
v0d0m3r/testing_task
d5fbb01bf4b6736dce43101397247da725df9c65
[ "MIT" ]
null
null
null
tcp_client/imager/Image_viewer.cpp
v0d0m3r/testing_task
d5fbb01bf4b6736dce43101397247da725df9c65
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // Qt #include <QtWidgets> #include <QAction> //------------------------------------------------------------------------------ // Local #include "Image_viewer.hpp" #include "imager_lib/Transmit_image_dialog.hpp" //------------------------------------------------------------------------------ namespace Imager { //------------------------------------------------------------------------------ Image_viewer::Image_viewer() : image_label(new QLabel), scroll_area(new QScrollArea), scale_factor(1) { image_label->setBackgroundRole(QPalette::Base); image_label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); image_label->setScaledContents(true); scroll_area->setBackgroundRole(QPalette::Dark); scroll_area->setWidget(image_label); scroll_area->setVisible(false); setCentralWidget(scroll_area); create_actions(); resize(QGuiApplication::primaryScreen()->availableSize() * 3 / 5); } //------------------------------------------------------------------------------ bool Image_viewer::load_file(const QString& file_name) { QImageReader reader(file_name); reader.setAutoTransform(true); const QImage new_image = reader.read(); if (new_image.isNull()) { QMessageBox::information(this, QGuiApplication::applicationDisplayName(), tr("Cannot load %1: %2") .arg(QDir::toNativeSeparators(file_name), reader.errorString())); return false; } curr_img_feat = Image_features(new_image.size(),reader.quality()); prev_img_feat = curr_img_feat; curr_name_image = file_name; set_image(new_image); setWindowFilePath(file_name); const QString message = tr("Opened \"%1\", %2x%3, Depth: %4") .arg(QDir::toNativeSeparators(file_name)).arg(image.width()).arg(image.height()).arg(image.depth()); statusBar()->showMessage(message); return true; } //------------------------------------------------------------------------------ void Image_viewer::set_image(const QImage& new_image) { image = new_image; image_label->setPixmap(QPixmap::fromImage(image)); scale_factor = 1.0; scroll_area->setVisible(true); fit_to_window_act->setEnabled(true); update_actions(); if (!fit_to_window_act->isChecked()) image_label->adjustSize(); } //------------------------------------------------------------------------------ bool Image_viewer::save_file(const QString& file_name) { QImageWriter writer(file_name); writer.setCompression(curr_img_feat.info.compression_level); writer.setQuality(curr_img_feat.info.quality); qDebug() << writer.compression(); qDebug() << writer.quality(); if (!writer.write(image)) { QMessageBox::information(this, QGuiApplication::applicationDisplayName(), tr("Cannot write %1: %2") .arg(QDir::toNativeSeparators(file_name)), writer.errorString()); return false; } const QString message = tr("Wrote \"%1\"").arg(QDir::toNativeSeparators(file_name)); statusBar()->showMessage(message); return true; } //------------------------------------------------------------------------------ static void init_image_file_dialog(QFileDialog& dialog, QFileDialog::AcceptMode accept_mode) { static bool first_dialog = true; if (first_dialog) { first_dialog = false; const QStringList pictures_locations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation); dialog.setDirectory(pictures_locations.isEmpty() ? QDir::currentPath() : pictures_locations.last()); } QStringList mime_type_filters; const auto supported_mime_types = (accept_mode == QFileDialog::AcceptOpen) ? QImageReader::supportedMimeTypes() : QImageWriter::supportedMimeTypes(); foreach (const auto& mime_type_name, supported_mime_types) mime_type_filters.append(mime_type_name); mime_type_filters.sort(); dialog.setMimeTypeFilters(mime_type_filters); dialog.selectMimeTypeFilter("image/png"); if (accept_mode == QFileDialog::AcceptSave) dialog.setDefaultSuffix("png"); } //------------------------------------------------------------------------------ void Image_viewer::open_cb() { QFileDialog dialog(this, tr("Open File")); init_image_file_dialog(dialog, QFileDialog::AcceptOpen); while (dialog.exec() == QDialog::Accepted && !load_file(dialog.selectedFiles().first())) {} } //------------------------------------------------------------------------------ void Image_viewer::save_cb() { prev_img_feat = curr_img_feat; previous_state_act->setEnabled(false); save_file(curr_name_image); } //------------------------------------------------------------------------------ void Image_viewer::save_as_cb() { QFileDialog dialog(this, tr("Save File As")); init_image_file_dialog(dialog, QFileDialog::AcceptSave); while (dialog.exec() == QDialog::Accepted && !save_file(dialog.selectedFiles().first())) {} } //------------------------------------------------------------------------------ void Image_viewer::transmission_cb() { Q_ASSERT(image_label->pixmap()); Transmit_image_dialog d(image); d.exec(); } //------------------------------------------------------------------------------ void Image_viewer::copy_cb() { #ifndef QT_NO_CLIPBOARD QGuiApplication::clipboard()->setImage(image); #endif // !QT_NO_CLIPBOARD } //------------------------------------------------------------------------------ #ifndef QT_NO_CLIPBOARD static QImage clipboardImage() { if (const QMimeData* mime_data = QGuiApplication::clipboard()->mimeData()) { if (mime_data->hasImage()) { const QImage image = qvariant_cast<QImage>(mime_data->imageData()); if (!image.isNull()) return image; } } return QImage(); } #endif // !QT_NO_CLIPBOARD //------------------------------------------------------------------------------ void Image_viewer::paste_cb() { #ifndef QT_NO_CLIPBOARD const QImage new_image = clipboardImage(); if (new_image.isNull()) statusBar()->showMessage(tr("No image in clipboard")); else { curr_img_feat = Image_features(new_image.size()); prev_img_feat = curr_img_feat; set_image(new_image); setWindowFilePath(QString()); const QString message = tr("Obtained image from clipboard, %1x%2, Depth: %3") .arg(new_image.width()).arg(new_image.height()).arg(new_image.depth()); statusBar()->showMessage(message); } #endif // !QT_NO_CLIPBOARD } //------------------------------------------------------------------------------ void Image_viewer::resize_cb() { Q_ASSERT(image_label->pixmap()); Resize_image_dialog rid; rid.set_original_size(curr_img_feat.size); if (rid.exec() == QDialog::Accepted) { prev_img_feat.size = curr_img_feat.size; curr_img_feat.size = rid.size(); if (prev_img_feat.size == curr_img_feat.size) { previous_state_act->setEnabled(curr_img_feat.info != prev_img_feat.info); return; } set_image(image.scaled(curr_img_feat.size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); previous_state_act->setEnabled(true); save_act->setEnabled(true); } } //------------------------------------------------------------------------------ void Image_viewer::compress_cb() { Q_ASSERT(image_label->pixmap()); Compress_image_dialog cid; cid.set_original_info(curr_img_feat.info); if (cid.exec() == QDialog::Accepted) { prev_img_feat.info = curr_img_feat.info; curr_img_feat.info = cid.compression_info(); if (curr_img_feat.info == prev_img_feat.info) previous_state_act->setEnabled(prev_img_feat.size != curr_img_feat.size); else { previous_state_act->setEnabled(true); save_act->setEnabled(true); } } } //------------------------------------------------------------------------------ void Image_viewer::previous_cb() { Q_ASSERT(image_label->pixmap()); bool enabled = true; if (prev_img_feat.size != curr_img_feat.size) { set_image(image.scaled(prev_img_feat.size)); curr_img_feat.size = prev_img_feat.size; enabled = false; } if ( prev_img_feat.info.compression_level != curr_img_feat.info.compression_level || prev_img_feat.info.quality != curr_img_feat.info.quality) { curr_img_feat.info = prev_img_feat.info; enabled = false; } previous_state_act->setEnabled(enabled); } //------------------------------------------------------------------------------ void Image_viewer::zoom_in_cb() { scale_image(1.25); } //------------------------------------------------------------------------------ void Image_viewer::zoom_out_cb() { scale_image(0.8); } //------------------------------------------------------------------------------ void Image_viewer::normal_size_cb() { image_label->adjustSize(); scale_factor = 1.0; } //------------------------------------------------------------------------------ void Image_viewer::fit_to_window_cb() { bool fit_to_window = fit_to_window_act->isChecked(); scroll_area->setWidgetResizable(fit_to_window); if (!fit_to_window) normal_size_cb(); update_actions(); } //------------------------------------------------------------------------------ void Image_viewer::about_cb() { QMessageBox::about(this, tr("About Image Viewer"), tr("<p>The <b>Image Viewer</b> is first aplication of testing task." "For more information follow to " "https://github.com/v0d0m3r/testing_task</p>")); } //------------------------------------------------------------------------------ void Image_viewer::create_actions() { auto file_menu = menuBar()->addMenu(tr("&File")); auto open_act = file_menu->addAction(tr("&Open..."), this, &Image_viewer::open_cb); open_act->setShortcut(QKeySequence::Open); save_act = file_menu->addAction(tr("&Save"), this, &Image_viewer::save_cb); save_act->setShortcut(Qt::CTRL + Qt::Key_S); save_act->setEnabled(false); save_as_act = file_menu->addAction(tr("Save &As..."), this, &Image_viewer::save_as_cb); save_as_act->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_S); save_as_act->setEnabled(false); file_menu->addSeparator(); transmission_act = file_menu->addAction(tr("&Transmission"), this, &Image_viewer::transmission_cb); transmission_act->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_T); transmission_act->setEnabled(false); file_menu->addSeparator(); auto exit_act = file_menu->addAction(tr("E&xit"), this, &QWidget::close); exit_act->setShortcut(tr("Ctrl+Q")); auto edit_menu = menuBar()->addMenu(tr("&Edit")); copy_act = edit_menu->addAction(tr("&Copy"), this, &Image_viewer::copy_cb); copy_act->setShortcut(QKeySequence::Copy); copy_act->setEnabled(false); auto paste_act = edit_menu->addAction(tr("&Paste"), this, &Image_viewer::paste_cb); paste_act->setShortcut(QKeySequence::Paste); edit_menu->addSeparator(); resize_act = edit_menu->addAction(tr("&Resize"), this, &Image_viewer::resize_cb); resize_act->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_R)); resize_act->setEnabled(false); compress_act = edit_menu->addAction(tr("Co&mpress"), this, &Image_viewer::compress_cb); compress_act->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_M)); compress_act->setEnabled(false); previous_state_act = edit_menu->addAction(tr("Pr&evious"), this, &Image_viewer::previous_cb); previous_state_act->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_E)); previous_state_act->setEnabled(false); auto view_menu = menuBar()->addMenu(tr("&View")); zoom_in_act = view_menu->addAction(tr("Zoom &In (25%)"), this, &Image_viewer::zoom_in_cb); zoom_in_act->setShortcut(QKeySequence::ZoomIn); zoom_in_act->setEnabled(false); zoom_out_act = view_menu->addAction(tr("Zoom &Out (25%)"), this, &Image_viewer::zoom_out_cb); zoom_out_act->setShortcut(QKeySequence::ZoomOut); zoom_out_act->setEnabled(false); normal_size_act = view_menu->addAction(tr("&Normal Size"), this, &Image_viewer::normal_size_cb); normal_size_act->setShortcut(tr("Ctrl+S")); normal_size_act->setEnabled(false); view_menu->addSeparator(); fit_to_window_act = view_menu->addAction(tr("&Fit to Window"), this, &Image_viewer::fit_to_window_cb); fit_to_window_act->setEnabled(false); fit_to_window_act->setCheckable(true); fit_to_window_act->setShortcut(tr("Ctrl+F")); auto help_menu = menuBar()->addMenu(tr("&Help")); help_menu->addAction(tr("&About"), this, &Image_viewer::about_cb); } //------------------------------------------------------------------------------ void Image_viewer::update_actions() { save_as_act->setEnabled(!image.isNull()); transmission_act->setEnabled(!image.isNull()); copy_act->setEnabled(!image.isNull()); resize_act->setEnabled(!image.isNull()); compress_act->setEnabled(!image.isNull()); zoom_in_act->setEnabled(!fit_to_window_act->isChecked()); zoom_out_act->setEnabled(!fit_to_window_act->isChecked()); normal_size_act->setEnabled(!fit_to_window_act->isChecked()); } //------------------------------------------------------------------------------ void Image_viewer::scale_image(double factor) { Q_ASSERT(image_label->pixmap()); scale_factor *= factor; image_label->resize(scale_factor * image_label->pixmap()->size()); adjust_scroll_bar(scroll_area->horizontalScrollBar(), factor); adjust_scroll_bar(scroll_area->verticalScrollBar(), factor); zoom_in_act->setEnabled(scale_factor < 3.0); zoom_out_act->setEnabled(scale_factor > 0.333); } //------------------------------------------------------------------------------ void Image_viewer::adjust_scroll_bar(QScrollBar* scroll_bar, double factor) { if (scroll_bar == nullptr) return; scroll_bar->setValue(int(factor * scroll_bar->value() + ((factor - 1) * scroll_bar->pageStep()/2))); } //------------------------------------------------------------------------------ } // Imager //------------------------------------------------------------------------------
33.008949
115
0.564351
v0d0m3r
8daa6dd5b5470d4783705cc0136e8ddc06d4b50a
6,135
cc
C++
tests/unit/test_reconstruct.cc
PhilMiller/checkpoint
7d44a3b56057272fc492a3d7e882a568d1fd411b
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_reconstruct.cc
PhilMiller/checkpoint
7d44a3b56057272fc492a3d7e882a568d1fd411b
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_reconstruct.cc
PhilMiller/checkpoint
7d44a3b56057272fc492a3d7e882a568d1fd411b
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ***************************************************************************** // // test_reconstruct.cc // DARMA Toolkit v. 1.0.0 // DARMA/checkpoint => Serialization Library // // Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // 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 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. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "test_harness.h" #include <serdes_headers.h> #include <serialization_library_headers.h> #include <gtest/gtest.h> #include <vector> #include <cstdio> namespace serdes { namespace tests { namespace unit { template <typename T> struct TestReconstruct : TestHarness { }; TYPED_TEST_CASE_P(TestReconstruct); static constexpr int const u_val = 43; /* * Unit test with `UserObjectA` with a default constructor for deserialization * purposes */ struct UserObjectA { UserObjectA() = default; explicit UserObjectA(int in_u) : u_(in_u) { } void check() { EXPECT_EQ(u_, u_val); } template <typename SerializerT> void serialize(SerializerT& s) { s | u_; } int u_; }; /* * Unit test with `UserObjectB` with non-intrusive reconstruct for * deserialization purposes */ struct UserObjectB { explicit UserObjectB(int in_u) : u_(in_u) { } void check() { EXPECT_EQ(u_, u_val); } template <typename SerializerT> void serialize(SerializerT& s) { s | u_; } int u_; }; template <typename SerializerT> void reconstruct(SerializerT& s, UserObjectB*& obj, void* buf) { obj = new (buf) UserObjectB(100); } }}} // end namespace serdes::tests::unit /* * Unit test with `UserObjectC` with non-intrusive reconstruct for * deserialization purposes in the serdes namespace (ADL check) */ // Forward-declare UserObjectC namespace serdes { namespace tests { namespace unit { struct UserObjectC; }}} // end namespace serdes::tests::unit // Forward-declare serialize/reconstruct methods namespace serdes { // This using declaration is only used for convenience using UserObjType = serdes::tests::unit::UserObjectC; template <typename SerializerT> void reconstruct(SerializerT& s, UserObjType*& obj, void* buf); template <typename SerializerT> void serialize(SerializerT& s, UserObjType& x); } /* end namespace serdes */ // Actually define the UserObjectC namespace serdes { namespace tests { namespace unit { struct UserObjectC { explicit UserObjectC(int in_u) : u_(std::to_string(in_u)) { } public: void check() { EXPECT_EQ(u_, std::to_string(u_val)); } template <typename SerializerT> friend void serdes::serialize(SerializerT&, UserObjectC&); template <typename SerializerT> friend void serdes::reconstruct(SerializerT&, UserObjectC*&, void*); private: std::string u_ = {}; }; }}} // end namespace serdes::tests::unit // Implement the serialize and reconstruct in `serdes` namespace namespace serdes { // This using declaration is only used for convenience using UserObjType = serdes::tests::unit::UserObjectC; template <typename SerializerT> void reconstruct(SerializerT& s, UserObjType*& obj, void* buf) { obj = new (buf) UserObjType(100); } template <typename SerializerT> void serialize(SerializerT& s, UserObjType& x) { s | x.u_; } } /* end namespace serdes */ namespace serdes { namespace tests { namespace unit { /* * Unit test with `UserObjectD` with intrusive reconstruct for deserialization * purposes */ struct UserObjectD { explicit UserObjectD(int in_u) : u_(in_u) { } static UserObjectD& reconstruct(void* buf) { auto t = new (buf) UserObjectD(100); return *t; } void check() { EXPECT_EQ(u_, u_val); } template <typename SerializerT> void serialize(SerializerT& s) { s | u_; } int u_; }; /* * General test of serialization/deserialization for input object types */ TYPED_TEST_P(TestReconstruct, test_reconstruct_multi_type) { namespace ser = serialization::interface; using TestType = TypeParam; TestType in(u_val); in.check(); auto ret = ser::serialize<TestType>(in); auto out = ser::deserialize<TestType>(std::move(ret)); out->check(); } using ConstructTypes = ::testing::Types< UserObjectA, UserObjectB, UserObjectC, UserObjectD >; REGISTER_TYPED_TEST_CASE_P(TestReconstruct, test_reconstruct_multi_type); INSTANTIATE_TYPED_TEST_CASE_P(Test_reconstruct, TestReconstruct, ConstructTypes); }}} // end namespace serdes::tests::unit
26.217949
81
0.704645
PhilMiller
8daac0cc288d290bcc9ddf7aac1a4b8862db03a9
1,403
cpp
C++
source/framework/benchmark/src/dummy_benchmark.cpp
OliverSchmitz/lue
da097e8c1de30724bfe7667cc04344b6535b40cd
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/benchmark/src/dummy_benchmark.cpp
OliverSchmitz/lue
da097e8c1de30724bfe7667cc04344b6535b40cd
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/benchmark/src/dummy_benchmark.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#include "lue/framework/benchmark/benchmark.hpp" #include "lue/framework/benchmark/main.hpp" #include <iostream> #include <random> #include <thread> static void dummy( lue::benchmark::Environment const& environment, lue::benchmark::Task const& task) { using namespace std::chrono_literals; auto const nr_workers{environment.nr_workers()}; auto const work_size = task.nr_elements(); std::random_device device; std::default_random_engine engine(device()); std::uniform_real_distribution<double> distribution(0.0, 2000.0); auto const noise = distribution(engine); auto const parallelization_overhead = nr_workers * noise; // in ms → 10s auto const duration_per_work_item = 10000.0 + parallelization_overhead; auto const duration_of_work_size = work_size * duration_per_work_item; auto const duration_in_case_of_perfect_scaling = duration_of_work_size / nr_workers; std::chrono::duration<double, std::milli> duration{ duration_in_case_of_perfect_scaling}; std::this_thread::sleep_for(duration); } auto setup_benchmark( int /* argc */, char* /* argv */[], lue::benchmark::Environment const& environment, lue::benchmark::Task const& task) { auto callable = dummy; return lue::benchmark::Benchmark{ std::move(callable), environment, task}; } LUE_CONFIGURE_BENCHMARK()
26.980769
75
0.709195
OliverSchmitz
8dada646277b764f546a21946958702c52f79cb9
337
cpp
C++
1. Algoritmi elementari/Prelucrarea cifrelor unui numar/mediaAritmetica.cpp
RegusAl/School
87deb27f241aab1a93fd1cab0de2c7d8ee93df71
[ "MIT" ]
2
2021-04-20T21:22:37.000Z
2021-04-20T21:23:09.000Z
1. Algoritmi elementari/Prelucrarea cifrelor unui numar/mediaAritmetica.cpp
RegusAl/School
87deb27f241aab1a93fd1cab0de2c7d8ee93df71
[ "MIT" ]
null
null
null
1. Algoritmi elementari/Prelucrarea cifrelor unui numar/mediaAritmetica.cpp
RegusAl/School
87deb27f241aab1a93fd1cab0de2c7d8ee93df71
[ "MIT" ]
null
null
null
// media aritmetica a cifrelor nenule #include <iostream> using namespace std; int main() { int sum = 0, nrcif = 0, medie = 0; int n; cin>>n; while(n) { int uc = n%10; if(uc > 0) { sum += uc; nrcif++; } n = n/10; } medie = sum/nrcif; cout<<"Media aritmetica este "<<medie; return 0; }
13.48
40
0.525223
RegusAl
8dae4a9315bd5bcae393e27e7d9e4a008b502a12
2,474
cpp
C++
Engine/Src/Runtime/Run/Implementations/Windows/RunWindows.cpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Run/Implementations/Windows/RunWindows.cpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Run/Implementations/Windows/RunWindows.cpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS 1 #include <Windows.h> #include <windowsx.h> #include <ApplicationBase//Application.hpp> #include <Application/ApplicationFactory.hpp> #include <PlatformCore/PlatformCore.hpp> #include <Core/Log.hpp> #include <Core/Containers/UniquePointer.hpp> #include <Core/Timer.hpp> #include <Core/Math/Vector2.hpp> #include <PlatformCore/Window/Window.hpp> #include <iostream> #include <Application/WindowsContext.hpp> int WINAPI WinMain( _In_ HINSTANCE a_InstanceHandle, _In_opt_ HINSTANCE a_PreviousInstanceHandle, _In_ LPSTR a_CommandLine, _In_ int a_CommandShow) { // Instantiate the logger on the stack, then save a static pointer for the public getter function Fade::CCompositeLogger CompositeLogger; CompositeLogger.RegisterLogger(new Fade::CFileLogger("./Intermediate/Logs/Log.txt")); // Temporary creation of console window #ifdef FADE_DEBUG if (!AllocConsole()) { DWORD ErrorID = ::GetLastError(); if (ErrorID == 0) { MessageBox(NULL, TEXT("Unable to allocate console"), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION); } else { MessageBox(nullptr, Fade::PlatformCore::GetLastErrorMessage(), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION); } return 1; } freopen("conin$","r",stdin); freopen("conout$","w",stdout); freopen("conout$","w",stderr); CompositeLogger.RegisterLogger(new Fade::CStreamLogger(&std::cout)); FADE_LOG(Info, Run, "Console created."); #endif Fade::PlatformCore::Windows::g_InstanceHandle = a_InstanceHandle; bool g_ShouldQuit = false; // Create an application Fade::TUniquePtr<Fade::IApplication> g_Application = Fade::GetApplication(); FADE_LOG(Info, Run, "Application created."); if (g_Application->Initialize() != Fade::EInitializationResult::SUCCESS || g_Application->PostInitialize() != Fade::EInitializationResult::SUCCESS) { return 1; } const Fade::u32 DesiredFPS = 120; const float FrameTime = 1.0f / (float)DesiredFPS; float CurrentTime = FrameTime; MSG Message; Fade::CTimer TickTimer; TickTimer.Start(); while (!g_ShouldQuit) { if (CurrentTime >= FrameTime) { TickTimer.Reset(); g_ShouldQuit = g_Application->Tick(CurrentTime) != Fade::ETickResult::CONTINUE || g_Application->PostTick(CurrentTime) != Fade::ETickResult::CONTINUE; } while (PeekMessage(&Message, NULL, 0, 0, PM_REMOVE) > 0) { TranslateMessage(&Message); DispatchMessage(&Message); } CurrentTime = TickTimer.Elapsed<float>(); } return 0; }
26.319149
109
0.731205
Septus10
8daeb8b490e76bb7e5ae3363951261a4bcd50e36
26,662
cpp
C++
samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp
fynv/Vulkan-Samples
bdb733ca258686668078de9026e11ca21580d6a7
[ "Apache-2.0" ]
null
null
null
samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp
fynv/Vulkan-Samples
bdb733ca258686668078de9026e11ca21580d6a7
[ "Apache-2.0" ]
null
null
null
samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp
fynv/Vulkan-Samples
bdb733ca258686668078de9026e11ca21580d6a7
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2019, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 the "License"; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Runtime mip map generation */ #include "texture_mipmap_generation.h" TextureMipMapGeneration::TextureMipMapGeneration() { zoom = -2.5f; rotation = {0.0f, 15.0f, 0.0f}; title = "Texture MipMap generation"; } TextureMipMapGeneration::~TextureMipMapGeneration() { if (device) { vkDestroyPipeline(get_device().get_handle(), pipeline, nullptr); vkDestroyPipelineLayout(get_device().get_handle(), pipeline_layout, nullptr); vkDestroyDescriptorSetLayout(get_device().get_handle(), descriptor_set_layout, nullptr); for (auto sampler : samplers) { vkDestroySampler(get_device().get_handle(), sampler, nullptr); } } destroy_texture(texture); uniform_buffer.reset(); } // Enable physical device features required for this example void TextureMipMapGeneration::get_device_features() { // Enable anisotropic filtering if supported if (supported_device_features.samplerAnisotropy) { requested_device_features.samplerAnisotropy = VK_TRUE; }; } /* Load the base texture containing only the first mip level and generate the whole mip-chain at runtime */ void TextureMipMapGeneration::load_texture_generate_mipmaps(std::string file_name) { VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; ktxTexture * ktx_texture; KTX_error_code result; result = ktxTexture_CreateFromNamedFile(file_name.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktx_texture); // @todo: get format from libktx if (ktx_texture == nullptr) { throw std::runtime_error("Couldn't load texture"); } texture.width = ktx_texture->baseWidth; texture.height = ktx_texture->baseHeight; // Calculate number of mip levels as per Vulkan specs: // numLevels = 1 + floor(log2(max(w, h, d))) texture.mip_levels = static_cast<uint32_t>(floor(log2(std::max(texture.width, texture.height))) + 1); // Get device properites for the requested texture format // Check if the selected format supports blit source and destination, which is required for generating the mip levels // If this is not supported you could implement a fallback via compute shader image writes and stores VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(get_device().get_physical_device(), format, &formatProperties); if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) || !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT)) { throw std::runtime_error("Selected image format does not support blit source and destination"); } VkMemoryAllocateInfo memory_allocate_info = vkb::initializers::memory_allocate_info(); VkMemoryRequirements memory_requirements = {}; ktx_uint8_t *ktx_image_data = ktxTexture_GetData(ktx_texture); ktx_size_t ktx_texture_size = ktxTexture_GetSize(ktx_texture); // Create a host-visible staging buffer that contains the raw image data VkBuffer staging_buffer; VkDeviceMemory staging_memory; VkBufferCreateInfo buffer_create_info = vkb::initializers::buffer_create_info(); buffer_create_info.size = ktx_texture_size; // This buffer is used as a transfer source for the buffer copy buffer_create_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VK_CHECK(vkCreateBuffer(get_device().get_handle(), &buffer_create_info, nullptr, &staging_buffer)); // Get memory requirements for the staging buffer (alignment, memory type bits) vkGetBufferMemoryRequirements(get_device().get_handle(), staging_buffer, &memory_requirements); memory_allocate_info.allocationSize = memory_requirements.size; // Get memory type index for a host visible buffer memory_allocate_info.memoryTypeIndex = get_device().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &staging_memory)); VK_CHECK(vkBindBufferMemory(get_device().get_handle(), staging_buffer, staging_memory, 0)); // Copy ktx image data into host local staging buffer uint8_t *data; VK_CHECK(vkMapMemory(get_device().get_handle(), staging_memory, 0, memory_requirements.size, 0, (void **) &data)); memcpy(data, ktx_image_data, ktx_texture_size); vkUnmapMemory(get_device().get_handle(), staging_memory); // Create optimal tiled target image on the device VkImageCreateInfo image_create_info = vkb::initializers::image_create_info(); image_create_info.imageType = VK_IMAGE_TYPE_2D; image_create_info.format = format; image_create_info.mipLevels = texture.mip_levels; image_create_info.arrayLayers = 1; image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_create_info.extent = {texture.width, texture.height, 1}; image_create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VK_CHECK(vkCreateImage(get_device().get_handle(), &image_create_info, nullptr, &texture.image)); vkGetImageMemoryRequirements(get_device().get_handle(), texture.image, &memory_requirements); memory_allocate_info.allocationSize = memory_requirements.size; memory_allocate_info.memoryTypeIndex = get_device().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &texture.device_memory)); VK_CHECK(vkBindImageMemory(get_device().get_handle(), texture.image, texture.device_memory, 0)); VkCommandBuffer copy_command = device->create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); // Optimal image will be used as destination for the copy, so we must transfer from our initial undefined image layout to the transfer destination layout vkb::insert_image_memory_barrier( copy_command, texture.image, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); // Copy the first mip of the chain, remaining mips will be generated VkBufferImageCopy buffer_copy_region = {}; buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; buffer_copy_region.imageSubresource.mipLevel = 0; buffer_copy_region.imageSubresource.baseArrayLayer = 0; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent.width = texture.width; buffer_copy_region.imageExtent.height = texture.height; buffer_copy_region.imageExtent.depth = 1; vkCmdCopyBufferToImage(copy_command, staging_buffer, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); // Transition first mip level to transfer source so we can blit(read) from it vkb::insert_image_memory_barrier( copy_command, texture.image, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); device->flush_command_buffer(copy_command, queue, true); // Clean up staging resources vkFreeMemory(device->get_handle(), staging_memory, nullptr); vkDestroyBuffer(device->get_handle(), staging_buffer, nullptr); // Generate the mip chain // --------------------------------------------------------------- // We copy down the whole mip chain doing a blit from mip-1 to mip // An alternative way would be to always blit from the first mip level and sample that one down VkCommandBuffer blit_command = device->create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); // Copy down mips from n-1 to n for (uint32_t i = 1; i < texture.mip_levels; i++) { VkImageBlit image_blit{}; // Source image_blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_blit.srcSubresource.layerCount = 1; image_blit.srcSubresource.mipLevel = i - 1; image_blit.srcOffsets[1].x = int32_t(texture.width >> (i - 1)); image_blit.srcOffsets[1].y = int32_t(texture.height >> (i - 1)); image_blit.srcOffsets[1].z = 1; // Destination image_blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; image_blit.dstSubresource.layerCount = 1; image_blit.dstSubresource.mipLevel = i; image_blit.dstOffsets[1].x = int32_t(texture.width >> i); image_blit.dstOffsets[1].y = int32_t(texture.height >> i); image_blit.dstOffsets[1].z = 1; // Prepare current mip level as image blit destination vkb::insert_image_memory_barrier( blit_command, texture.image, 0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, i, 1, 0, 1}); // Blit from previous level vkCmdBlitImage( blit_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_blit, VK_FILTER_LINEAR); // Prepare current mip level as image blit source for next level vkb::insert_image_memory_barrier( blit_command, texture.image, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, i, 1, 0, 1}); } // After the loop, all mip layers are in TRANSFER_SRC layout, so transition all to SHADER_READ vkb::insert_image_memory_barrier( blit_command, texture.image, VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, {VK_IMAGE_ASPECT_COLOR_BIT, 0, texture.mip_levels, 0, 1}); device->flush_command_buffer(blit_command, queue, true); // --------------------------------------------------------------- // Create samplers for different mip map demonstration cases samplers.resize(3); VkSamplerCreateInfo sampler = vkb::initializers::sampler_create_info(); sampler.magFilter = VK_FILTER_LINEAR; sampler.minFilter = VK_FILTER_LINEAR; sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; sampler.mipLodBias = 0.0f; sampler.compareOp = VK_COMPARE_OP_NEVER; sampler.minLod = 0.0f; sampler.maxLod = 0.0f; sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; sampler.maxAnisotropy = 1.0; sampler.anisotropyEnable = VK_FALSE; // Without mip mapping VK_CHECK(vkCreateSampler(device->get_handle(), &sampler, nullptr, &samplers[0])); // With mip mapping sampler.maxLod = static_cast<float>(texture.mip_levels); VK_CHECK(vkCreateSampler(device->get_handle(), &sampler, nullptr, &samplers[1])); // With mip mapping and anisotropic filtering (when supported) if (device->get_features().samplerAnisotropy) { sampler.maxAnisotropy = device->get_properties().limits.maxSamplerAnisotropy; sampler.anisotropyEnable = VK_TRUE; } VK_CHECK(vkCreateSampler(device->get_handle(), &sampler, nullptr, &samplers[2])); // Create image view VkImageViewCreateInfo view = vkb::initializers::image_view_create_info(); view.image = texture.image; view.viewType = VK_IMAGE_VIEW_TYPE_2D; view.format = format; view.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}; view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view.subresourceRange.baseMipLevel = 0; view.subresourceRange.baseArrayLayer = 0; view.subresourceRange.layerCount = 1; view.subresourceRange.levelCount = texture.mip_levels; VK_CHECK(vkCreateImageView(device->get_handle(), &view, nullptr, &texture.view)); } // Free all Vulkan resources used by a texture object void TextureMipMapGeneration::destroy_texture(Texture texture) { vkDestroyImageView(get_device().get_handle(), texture.view, nullptr); vkDestroyImage(get_device().get_handle(), texture.image, nullptr); vkFreeMemory(get_device().get_handle(), texture.device_memory, nullptr); } void TextureMipMapGeneration::load_assets() { load_texture_generate_mipmaps(vkb::fs::path::get(vkb::fs::path::Assets, "textures/checkerboard_rgba.ktx")); scene = load_model("scenes/tunnel_cylinder.gltf"); } void TextureMipMapGeneration::build_command_buffers() { VkCommandBufferBeginInfo command_buffer_begin_info = vkb::initializers::command_buffer_begin_info(); VkClearValue clear_values[2]; clear_values[0].color = default_clear_color; clear_values[1].depthStencil = {1.0f, 0}; VkRenderPassBeginInfo render_pass_begin_info = vkb::initializers::render_pass_begin_info(); render_pass_begin_info.renderPass = render_pass; render_pass_begin_info.renderArea.offset.x = 0; render_pass_begin_info.renderArea.offset.y = 0; render_pass_begin_info.renderArea.extent.width = width; render_pass_begin_info.renderArea.extent.height = height; render_pass_begin_info.clearValueCount = 2; render_pass_begin_info.pClearValues = clear_values; for (int32_t i = 0; i < draw_cmd_buffers.size(); ++i) { render_pass_begin_info.framebuffer = framebuffers[i]; VK_CHECK(vkBeginCommandBuffer(draw_cmd_buffers[i], &command_buffer_begin_info)); vkCmdBeginRenderPass(draw_cmd_buffers[i], &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vkb::initializers::viewport((float) width, (float) height, 0.0f, 1.0f); vkCmdSetViewport(draw_cmd_buffers[i], 0, 1, &viewport); VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); draw_model(scene, draw_cmd_buffers[i]); draw_ui(draw_cmd_buffers[i]); vkCmdEndRenderPass(draw_cmd_buffers[i]); VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); } } void TextureMipMapGeneration::draw() { ApiVulkanSample::prepare_frame(); // Command buffer to be sumitted to the queue submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &draw_cmd_buffers[current_buffer]; // Submit to queue VK_CHECK(vkQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE)); ApiVulkanSample::submit_frame(); } void TextureMipMapGeneration::setup_descriptor_pool() { // Example uses one ubo and one image sampler std::vector<VkDescriptorPoolSize> pool_sizes = { vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLER, 3), }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info( static_cast<uint32_t>(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void TextureMipMapGeneration::setup_descriptor_set_layout() { std::vector<VkDescriptorSetLayoutBinding> set_layout_bindings = { // Binding 0 : Parameter uniform buffer vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), // Binding 1 : Fragment shader image sampler vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 1), // Binding 2 : Sampler array (3 descriptors) vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2, 3), }; VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info( set_layout_bindings.data(), static_cast<uint32_t>(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info( &descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void TextureMipMapGeneration::setup_descriptor_set() { VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info( descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*uniform_buffer); VkDescriptorImageInfo image_descriptor; image_descriptor.imageView = texture.view; image_descriptor.sampler = VK_NULL_HANDLE; image_descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; std::vector<VkWriteDescriptorSet> write_descriptor_sets = { // Binding 0 : Vertex shader uniform buffer vkb::initializers::write_descriptor_set( descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 1 : Fragment shader texture sampler vkb::initializers::write_descriptor_set( descriptor_set, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, &image_descriptor)}; // Binding 2: Sampler array std::vector<VkDescriptorImageInfo> sampler_descriptors; for (auto i = 0; i < samplers.size(); i++) { sampler_descriptors.push_back({samplers[i], VK_NULL_HANDLE, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}); } VkWriteDescriptorSet write_descriptor_set{}; write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_descriptor_set.dstSet = descriptor_set; write_descriptor_set.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; write_descriptor_set.descriptorCount = static_cast<uint32_t>(sampler_descriptors.size()); write_descriptor_set.pImageInfo = sampler_descriptors.data(); write_descriptor_set.dstBinding = 2; write_descriptor_set.dstArrayElement = 0; write_descriptor_sets.push_back(write_descriptor_set); vkUpdateDescriptorSets(get_device().get_handle(), static_cast<uint32_t>(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } void TextureMipMapGeneration::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info( 1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info( dynamic_state_enables.data(), static_cast<uint32_t>(dynamic_state_enables.size()), 0); // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shader_stages; shader_stages[0] = load_shader("texture_mipmap_generation/texture.vert", VK_SHADER_STAGE_VERTEX_BIT); shader_stages[1] = load_shader("texture_mipmap_generation/texture.frag", VK_SHADER_STAGE_FRAGMENT_BIT); // Vertex bindings and attributes const std::vector<VkVertexInputBindingDescription> vertex_input_bindings = { vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), }; const std::vector<VkVertexInputAttributeDescription> vertex_input_attributes = { vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 0: Position vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 6), // Location 1: UV vkb::initializers::vertex_input_attribute_description(0, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Location 2: Color }; VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); vertex_input_state.vertexBindingDescriptionCount = static_cast<uint32_t>(vertex_input_bindings.size()); vertex_input_state.pVertexBindingDescriptions = vertex_input_bindings.data(); vertex_input_state.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; pipeline_create_info.pRasterizationState = &rasterization_state; pipeline_create_info.pColorBlendState = &color_blend_state; pipeline_create_info.pMultisampleState = &multisample_state; pipeline_create_info.pViewportState = &viewport_state; pipeline_create_info.pDepthStencilState = &depth_stencil_state; pipeline_create_info.pDynamicState = &dynamic_state; pipeline_create_info.stageCount = static_cast<uint32_t>(shader_stages.size()); pipeline_create_info.pStages = shader_stages.data(); VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &pipeline)); } void TextureMipMapGeneration::prepare_uniform_buffers() { // Shared parameter uniform buffer block uniform_buffer = std::make_unique<vkb::core::Buffer>(get_device(), sizeof(ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } void TextureMipMapGeneration::update_uniform_buffers(float delta_time) { ubo.projection = camera.matrices.perspective; ubo.model = camera.matrices.view; ubo.model = glm::rotate(ubo.model, glm::radians(90.0f + timer * 360.0f), glm::vec3(0.0f, 0.0f, 1.0f)); ubo.model = glm::scale(ubo.model, glm::vec3(0.5f)); timer += delta_time * 0.005f; if (timer > 1.0f) { timer -= 1.0f; } uniform_buffer->convert_and_update(ubo); } bool TextureMipMapGeneration::prepare(vkb::Platform &platform) { if (!ApiVulkanSample::prepare(platform)) { return false; } camera.type = vkb::CameraType::FirstPerson; camera.set_perspective(60.0f, (float) width / (float) height, 0.1f, 1024.0f); camera.set_translation(glm::vec3(0.0f, 0.0f, -12.5f)); load_assets(); prepare_uniform_buffers(); setup_descriptor_set_layout(); prepare_pipelines(); setup_descriptor_pool(); setup_descriptor_set(); build_command_buffers(); prepared = true; return true; } void TextureMipMapGeneration::render(float delta_time) { if (!prepared) return; draw(); if (rotate_scene) update_uniform_buffers(delta_time); } void TextureMipMapGeneration::view_changed() { update_uniform_buffers(); } void TextureMipMapGeneration::on_update_ui_overlay(vkb::Drawer &drawer) { if (drawer.header("Settings")) { drawer.checkbox("Rotate", &rotate_scene); if (drawer.slider_float("LOD bias", &ubo.lod_bias, 0.0f, (float) texture.mip_levels)) { update_uniform_buffers(); } if (drawer.combo_box("Sampler type", &ubo.sampler_index, sampler_names)) { update_uniform_buffers(); } } } std::unique_ptr<vkb::Application> create_texture_mipmap_generation() { return std::make_unique<TextureMipMapGeneration>(); }
40.830015
181
0.746231
fynv
8dafa14508f0b02ad248e15e43b72c3c6f628979
4,819
cpp
C++
Source/ShooterGame/Private/UI/Style/ShooterStyle.cpp
wangminzt/AI_FPS
f04c1d6202a92e362b86eaa60245f2e9f3c252d1
[ "MIT" ]
3
2020-07-19T22:44:25.000Z
2020-08-06T08:11:31.000Z
Source/ShooterGame/Private/UI/Style/ShooterStyle.cpp
wangminzt/AI_FPS
f04c1d6202a92e362b86eaa60245f2e9f3c252d1
[ "MIT" ]
null
null
null
Source/ShooterGame/Private/UI/Style/ShooterStyle.cpp
wangminzt/AI_FPS
f04c1d6202a92e362b86eaa60245f2e9f3c252d1
[ "MIT" ]
1
2021-04-15T05:56:04.000Z
2021-04-15T05:56:04.000Z
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "ShooterGame.h" #include "ShooterStyle.h" #include "SlateGameResources.h" TSharedPtr< FSlateStyleSet > FShooterStyle::ShooterStyleInstance = NULL; void FShooterStyle::Initialize() { if ( !ShooterStyleInstance.IsValid() ) { ShooterStyleInstance = Create(); FSlateStyleRegistry::RegisterSlateStyle( *ShooterStyleInstance ); } } void FShooterStyle::Shutdown() { FSlateStyleRegistry::UnRegisterSlateStyle( *ShooterStyleInstance ); ensure( ShooterStyleInstance.IsUnique() ); ShooterStyleInstance.Reset(); } FName FShooterStyle::GetStyleSetName() { static FName StyleSetName(TEXT("ShooterStyle")); return StyleSetName; } #define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".png"), __VA_ARGS__ ) #define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".png"), __VA_ARGS__ ) #define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".png"), __VA_ARGS__ ) #define TTF_FONT( RelativePath, ... ) FSlateFontInfo( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".ttf"), __VA_ARGS__ ) #define OTF_FONT( RelativePath, ... ) FSlateFontInfo( FPaths::GameContentDir() / "Slate"/ RelativePath + TEXT(".otf"), __VA_ARGS__ ) TSharedRef< FSlateStyleSet > FShooterStyle::Create() { TSharedRef<FSlateStyleSet> StyleRef = FSlateGameResources::New(FShooterStyle::GetStyleSetName(), "/Game/UI/Styles", "/Game/UI/Styles"); FSlateStyleSet& Style = StyleRef.Get(); // Load the speaker icon to be used for displaying when a user is talking Style.Set("ShooterGame.Speaker", new IMAGE_BRUSH("Images/SoundCue_SpeakerIcon", FVector2D(32, 32))); // The border image used to draw the replay timeline bar Style.Set("ShooterGame.ReplayTimelineBorder", new BOX_BRUSH("Images/ReplayTimeline", FMargin(3.0f / 8.0f))); // The border image used to draw the replay timeline bar Style.Set("ShooterGame.ReplayTimelineIndicator", new IMAGE_BRUSH("Images/ReplayTimelineIndicator", FVector2D(4.0f, 26.0f))); // The image used to draw the replay pause button Style.Set("ShooterGame.ReplayPauseIcon", new IMAGE_BRUSH("Images/ReplayPause", FVector2D(32.0f, 32.0f))); // Fonts still need to be specified in code for now Style.Set("ShooterGame.MenuServerListTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 14)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.ScoreboardListTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 14)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.MenuProfileNameStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 18)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.MenuTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 20)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.MenuHeaderTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 26)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.WelcomeScreen.WelcomeTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Medium", 32)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); Style.Set("ShooterGame.DefaultScoreboard.Row.HeaderTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 24)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FVector2D(0,1)) ); Style.Set("ShooterGame.DefaultScoreboard.Row.StatTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Regular", 18)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FVector2D(0,1)) ); Style.Set("ShooterGame.SplitScreenLobby.StartMatchTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Regular", 16)) .SetColorAndOpacity(FLinearColor::Green) .SetShadowOffset(FVector2D(0,1)) ); Style.Set("ShooterGame.DemoListCheckboxTextStyle", FTextBlockStyle() .SetFont(TTF_FONT("Fonts/Roboto-Black", 12)) .SetColorAndOpacity(FLinearColor::White) .SetShadowOffset(FIntPoint(-1,1)) ); return StyleRef; } #undef IMAGE_BRUSH #undef BOX_BRUSH #undef BORDER_BRUSH #undef TTF_FONT #undef OTF_FONT void FShooterStyle::ReloadTextures() { FSlateApplication::Get().GetRenderer()->ReloadTextureResources(); } const ISlateStyle& FShooterStyle::Get() { return *ShooterStyleInstance; }
36.233083
140
0.736252
wangminzt
8db3164e1e1928594f36744cdde0b2d221b8b750
509
cpp
C++
Searching & Sorting/Two number with sum closeset to zero.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
9
2020-10-01T09:29:10.000Z
2022-02-12T04:58:41.000Z
Searching & Sorting/Two number with sum closeset to zero.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
6
2020-10-03T16:08:58.000Z
2020-10-14T12:06:25.000Z
Searching & Sorting/Two number with sum closeset to zero.cpp
vermagaurav8/GeeksforGeeks
f54d3297337981b5fc5054272cfa6788011c2c5a
[ "Apache-2.0" ]
17
2020-10-01T09:17:27.000Z
2021-06-18T09:36:31.000Z
#include<bits/stdc++.h> using namespace std; int main() { int n;cin>>n; while(n--) { int m; cin>>m; vector<int>v(m); for(int i=0;i<m;i++) cin>>v[i]; sort(v.begin(),v.end()); int l=0,r=v.size()-1,sum=0; int m_sum=v[0]+v[r]; while(l<r) { sum=v[l]+v[r]; if(sum>0) r--; else l++; m_sum=abs(m_sum)<=abs(sum)?m_sum:sum; } cout<<m_sum<<endl; } return 0; }
14.138889
45
0.400786
vermagaurav8
8dba60880f4e8f98eb53bb8235ed7a749ee3480c
2,758
cpp
C++
CMinus/CMinus/evaluator/class_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/class_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/class_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
#include "../type/class_type.h" #include "class_evaluator.h" cminus::evaluator::class_::~class_() = default; std::shared_ptr<cminus::memory::reference> cminus::evaluator::class_::evaluate_unary_left(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ auto callable = find_operator_(runtime, op, target); if (callable == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); return callable->get_value()->call(runtime, callable->get_context(), std::vector<std::shared_ptr<memory::reference>>{target}); } std::shared_ptr<cminus::memory::reference> cminus::evaluator::class_::evaluate_unary_right(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ auto callable = find_operator_(runtime, op, target); if (callable == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); std::vector<std::shared_ptr<memory::reference>> args{ target, runtime.global_storage->create_scalar(0) }; return callable->get_value()->call(runtime, callable->get_context(), args); } std::shared_ptr<cminus::memory::reference> cminus::evaluator::class_::evaluate_binary(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> left_value, const operand_type &right) const{ auto callable = find_operator_(runtime, op, left_value); if (callable == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); return callable->get_value()->call(runtime, callable->get_context(), std::vector<std::shared_ptr<memory::reference>>{ left_value, right->evaluate(runtime) }); } cminus::memory::function_reference *cminus::evaluator::class_::find_operator_(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ std::shared_ptr<memory::reference> entry; if (std::holds_alternative<operator_id>(op)){ entry = dynamic_cast<type::class_ *>(target->get_type().get())->find_operator( runtime, std::get<operator_id>(op), logic::storage::object::namesless_search_options{ nullptr, target, false } ); } else//String value entry = dynamic_cast<type::class_ *>(target->get_type().get())->find(runtime, logic::storage::object::search_options{ nullptr, target, std::get<std::string>(op), false }); if (entry == nullptr) return nullptr; if (auto callable = dynamic_cast<memory::function_reference *>(entry->get_non_raw()); callable != nullptr) return callable; throw logic::exception("Bad operator definition", 0u, 0u); return nullptr; }
48.385965
216
0.741842
benbraide
8dbb81d0405ac9ac1d8493331358cd49c1650292
3,530
cc
C++
src/search_local/index_storage/common/plugin_dgram.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_storage/common/plugin_dgram.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_storage/common/plugin_dgram.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <sys/un.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <linux/sockios.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include "plugin_agent_mgr.h" #include "plugin_dgram.h" #include "plugin_unit.h" #include "poll_thread.h" #include "mem_check.h" #include "log.h" extern "C" { extern unsigned int get_local_ip(); } static int GetSocketFamily(int fd) { struct sockaddr addr; bzero(&addr, sizeof(addr)); socklen_t alen = sizeof(addr); getsockname(fd, &addr, &alen); return addr.sa_family; } PluginDgram::PluginDgram(PluginDecoderUnit *plugin_decoder, int fd) : PollerObject(plugin_decoder->owner_thread(), fd), mtu(0), _addr_len(0), _owner(plugin_decoder), _worker_notifier(NULL), _plugin_receiver(fd, PluginAgentManager::Instance()->get_dll()), _plugin_sender(fd, PluginAgentManager::Instance()->get_dll()), _local_ip(0) { } PluginDgram::~PluginDgram() { } int PluginDgram::Attach() { /* init local ip */ _local_ip = get_local_ip(); switch (GetSocketFamily(netfd)) { default: case AF_UNIX: mtu = 16 << 20; _addr_len = sizeof(struct sockaddr_un); break; case AF_INET: mtu = 65535; _addr_len = sizeof(struct sockaddr_in); break; case AF_INET6: mtu = 65535; _addr_len = sizeof(struct sockaddr_in6); break; } //get worker notifier _worker_notifier = PluginAgentManager::Instance()->get_worker_notifier(); if (NULL == _worker_notifier) { log_error("worker notifier is invalid."); return -1; } enable_input(); return attach_poller(); } //server peer int PluginDgram::recv_request(void) { //create dgram request PluginDatagram *dgram_request = NULL; NEW(PluginDatagram(this, PluginAgentManager::Instance()->get_dll()), dgram_request); if (NULL == dgram_request) { log_error("create PluginRequest for dgram failed, msg:%s", strerror(errno)); return -1; } //set request info dgram_request->_skinfo.sockfd = netfd; dgram_request->_skinfo.type = SOCK_DGRAM; dgram_request->_skinfo.local_ip = _local_ip; dgram_request->_skinfo.local_port = 0; dgram_request->_incoming_notifier = _owner->get_incoming_notifier(); dgram_request->_addr_len = _addr_len; dgram_request->_addr = MALLOC(_addr_len); if (NULL == dgram_request->_addr) { log_error("malloc failed, msg:%m"); DELETE(dgram_request); return -1; } if (_plugin_receiver.recvfrom(dgram_request, mtu) != 0) { DELETE(dgram_request); return -1; } dgram_request->set_time_info(); if (_worker_notifier->Push(dgram_request) != 0) { log_error("push plugin request failed, fd[%d]", netfd); DELETE(dgram_request); return -1; } return 0; } void PluginDgram::input_notify(void) { if (recv_request() < 0) /* */; }
26.541353
134
0.561473
jdisearch
8dbd09b2d4428c42a845c34d3c2d54bcf4c221e8
3,921
cpp
C++
lesson15/src/mainDijkstra.cpp
forsakenmap/CPPExercises2021
48b91b86aa0f02d462fd7fac3d08fed8468c1506
[ "MIT" ]
null
null
null
lesson15/src/mainDijkstra.cpp
forsakenmap/CPPExercises2021
48b91b86aa0f02d462fd7fac3d08fed8468c1506
[ "MIT" ]
null
null
null
lesson15/src/mainDijkstra.cpp
forsakenmap/CPPExercises2021
48b91b86aa0f02d462fd7fac3d08fed8468c1506
[ "MIT" ]
null
null
null
#include <vector> #include <sstream> #include <iostream> #include <stdexcept> // беда не работает дайте руки и мозг int debugPoint(int line) { if (line < 0) return 0; // You can put breakpoint at the following line to catch any rassert failure: return line; } #define rassert(condition, message) if (!(condition)) { std::stringstream ss; (ss << "Assertion \"" << message << "\" failed at line " << debugPoint(__LINE__) << "!"); throw std::runtime_error(ss.str()); } bool found(std::vector<int> a, int b) { for(int i = 0; i < a.size(); i++) { if(a.at(i) == b) { return true; } } return false; } struct Edge { int u, v; // номера вершин которые это ребро соединяет int w; // длина ребра (т.е. насколько длинный путь предстоит преодолеть переходя по этому ребру между вершинами) Edge(int u, int v, int w) : u(u), v(v), w(w) {} }; void run() { // https://codeforces.com/problemset/problem/20/C?locale=ru // Не требуется сделать оптимально быструю версию, поэтому если вы получили: // // Превышено ограничение времени на тесте 31 // // То все замечательно и вы молодец. int nvertices, medges; std::cin >> nvertices; std::cin >> medges; std::vector<std::vector<Edge>> edges_by_vertex(nvertices); std::vector<bool> edg_be(nvertices, false); for (int i = 0; i < medges; ++i) { int ai, bi, w; std::cin >> ai >> bi >> w; rassert(ai >= 1 && ai <= nvertices, 23472894792020); rassert(bi >= 1 && bi <= nvertices, 23472894792021); ai -= 1; bi -= 1; rassert(ai >= 0 && ai < nvertices, 3472897424024); rassert(bi >= 0 && bi < nvertices, 3472897424025); Edge edgeAB(ai, bi, w); edges_by_vertex[ai].push_back(edgeAB); edges_by_vertex[bi].push_back(Edge(bi, ai, w)); // а тут - обратное ребро, можно конструировать объект прямо в той же строчке где он и потребовался } int start = 0; const int finish = nvertices - 1; const int INF = std::numeric_limits<int>::max(); Edge a(0, 0, 0); int s = 0; std::vector<int> distances(nvertices, INF); distances.at(0) = 0; int min = INF; int num = 0; std::vector<std::string> put(nvertices, ""); std::vector<int> first_s; first_s.push_back(0); std::vector<int> second_s; // TODO ... while (true) { for (int i = 0; i < first_s.size(); i++) { for (int k = 0; k < edges_by_vertex[first_s.at(i)].size(); k++) { a = edges_by_vertex[first_s.at(i)].at(k); if ((!edg_be.at(first_s.at(i))) && (!found(second_s, a.v))) { second_s.push_back(a.v); } if (distances.at(a.v) > distances.at(a.u) + a.w) { if(!found(second_s, a.v)) { second_s.push_back(a.v); } distances.at(a.v) = distances.at(a.u) + a.w; put.at(a.v) = put.at(a.u) + " " + std::to_string(a.v + 1); } } edg_be.at(first_s.at(i)) = true; } if (second_s.empty()) { break; } first_s = second_s; second_s = std::vector<int>(); } if (put.at(nvertices-1) == "") { std::cout << "-1"; } else { std::cout << "1" + put.at(nvertices - 1); } // while (true) { // // } // if (...) { // ... // for (...) { // std::cout << (path[i] + 1) << " "; // } // std::cout << std::endl; // } else { // std::cout << -1 << std::endl; // } } using namespace std; int main() { try { run(); } catch (const std::exception &e) { std::cout << "Exception! " << e.what() << std::endl; } }
29.704545
205
0.502678
forsakenmap
8dbd74f8d6df869cf70a0e3d78d38b3a892d5fdd
4,711
cpp
C++
Test.cpp
shaiBonfil/CPP-Ex1
ec9a82b8de9b99e3dd4488781b363ec36c95509e
[ "MIT" ]
null
null
null
Test.cpp
shaiBonfil/CPP-Ex1
ec9a82b8de9b99e3dd4488781b363ec36c95509e
[ "MIT" ]
null
null
null
Test.cpp
shaiBonfil/CPP-Ex1
ec9a82b8de9b99e3dd4488781b363ec36c95509e
[ "MIT" ]
null
null
null
/** * * AUTHOR: <Shai Bonfil> * * This is a test that gets input of eight characters(less or more * is invalid input), and the purpose is to represent snowman in * a format like you can see in the link below - HNLRXYTB. * Each valid letter is number between 1 to 4 which presets * the following things: * * H - Hat * N - Nose * L - Left eye * R - Right eye * X - Left arm * Y - Right arm * T - Torso * B - Base * * https://codegolf.stackexchange.com/q/49671/12019 * * Date: 2021-03 */ #include "doctest.h" #include <iostream> #include <string> #include <algorithm> using namespace std; #include "snowman.hpp" using namespace ariel; string nospaces(string input) { std::erase(input, ' '); std::erase(input, '\t'); std::erase(input, '\n'); std::erase(input, '\r'); return input; } TEST_CASE("Good snowman code") { CHECK(nospaces(snowman(11114411)) == nospaces("_===_\n(.,.)\n( : )\n( : )")); } TEST_CASE("All Hats"){ // H CHECK(nospaces(snowman(12341234)) == nospaces("_===_ \n(...)\n(O:-)\n<(> <)/\n( )")); CHECK(nospaces(snowman(21341321)) == nospaces(" ___ \n ..... \n(O,-)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(34324123)) == nospaces(" _ \n /_\\ \n(O o)\n( : )>\n(___)")); CHECK(nospaces(snowman(44123212)) == nospaces(" ___ \n (_*_) \n(. o)\n/(] [)/\n(\" \")")); } TEST_CASE("All Noses"){ // N CHECK(nospaces(snowman(11341234)) == nospaces("_===_ \n(...)\n(O,-)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12341321)) == nospaces("_===_ \n(...)\n(O.-)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(23324123)) == nospaces(" ___ \n ..... \n(O_o)\n( : )>\n(___)")); CHECK(nospaces(snowman(14123212)) == nospaces("_===_ \n(...)\n(. o)\n/(] [)/\n(\" \")")); } TEST_CASE("All Left Eyes"){ // L CHECK(nospaces(snowman(11141234)) == nospaces("_===_ \n(...)\n(.,-)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12241321)) == nospaces("_===_ \n(...)\n(o.-)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(23324123)) == nospaces(" ___ \n ..... \n(O_o)\n( : )>\n(___)")); CHECK(nospaces(snowman(14423212)) == nospaces("_===_ \n(...)\n(- o)\n/(] [)/\n(\" \")")); } TEST_CASE("All Right Eyes"){ // R CHECK(nospaces(snowman(11111234)) == nospaces("_===_ \n(...)\n(.,.)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12221321)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)\\n( : )")); CHECK(nospaces(snowman(23334123)) == nospaces(" ___ \n ..... \n(O_O)\n( : )>\n(___)")); CHECK(nospaces(snowman(11443212)) == nospaces("_===_ \n(...)\n(-,-)\n/(] [)/\n(\" \")")); } TEST_CASE("All Left Arms"){ // X CHECK(nospaces(snowman(11111234)) == nospaces("_===_ \n(...)\n(.,.)\n<(> <)/\n( )")); CHECK(nospaces(snowman(12222321)) == nospaces("_===_ \n(...)\n(o.o)\n\\(] [)\\n( : )")); CHECK(nospaces(snowman(23333123)) == nospaces(" ___ \n ..... \n(O_O)\n/( : )>\n(___)")); CHECK(nospaces(snowman(11444212)) == nospaces("_===_ \n(...)\n(-,-)\n(] [)/\n(\" \")")); } TEST_CASE("All Right Arms"){ // Y CHECK(nospaces(snowman(11311134)) == nospaces("_===_ \n(...)\n(O,.)\n<(> <)>\n( )")); CHECK(nospaces(snowman(12221221)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)/\n( : )")); CHECK(nospaces(snowman(23133323)) == nospaces(" ___ \n ..... \n(._O)\n/( : )\\\n(___)")); CHECK(nospaces(snowman(11143412)) == nospaces("_===_ \n(...)\n(.,-)\n/(] [)\n(\" \")")); } TEST_CASE("All Torsos"){ // T CHECK(nospaces(snowman(11311114)) == nospaces("_===_ \n(...)\n(O,.)\n<( : )>\n( )")); CHECK(nospaces(snowman(12221221)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)/\n( : )")); CHECK(nospaces(snowman(23133333)) == nospaces(" ___ \n ..... \n(._O)\n/(> <)\\\n(___)")); CHECK(nospaces(snowman(11143442)) == nospaces("_===_ \n(...)\n(.,-)\n/( )\n(\" \")")); } TEST_CASE("All Bases"){ // B CHECK(nospaces(snowman(11311211)) == nospaces("_===_ \n(...)\n(O,.)\n<( : )/\n( : )")); CHECK(nospaces(snowman(12221222)) == nospaces("_===_ \n(...)\n(o.o)\n<(] [)/\n(\" \")")); CHECK(nospaces(snowman(23133233)) == nospaces(" ___ \n ..... \n(._O)\n/(> <)/\n(___)")); CHECK(nospaces(snowman(11143144)) == nospaces("_===_ \n(...)\n(.,-)\n/( )>\n( )")); } TEST_CASE("Bad snowman code: short or long input") { CHECK_THROWS(nospaces(snowman(1111))); CHECK_THROWS(nospaces(snowman(123456789))); CHECK_THROWS(nospaces(snowman(0))); CHECK_THROWS(nospaces(snowman(-123))); } TEST_CASE("Bad snowman code: invalid letter") { CHECK_THROWS(nospaces(snowman(11234353))); CHECK_THROWS(nospaces(snowman(56789005))); CHECK_THROWS(nospaces(snowman(14232319))); }
35.421053
96
0.525791
shaiBonfil
8dbda768e6214c57f275a3994a6e46cb9fb44ef4
393
cpp
C++
pbe/src/pbe/Core/Math/Common.cpp
pavilbezpravil/pbEngine
55c051bdb296f0960ad05447d385a554334c4b5c
[ "Apache-2.0" ]
null
null
null
pbe/src/pbe/Core/Math/Common.cpp
pavilbezpravil/pbEngine
55c051bdb296f0960ad05447d385a554334c4b5c
[ "Apache-2.0" ]
null
null
null
pbe/src/pbe/Core/Math/Common.cpp
pavilbezpravil/pbEngine
55c051bdb296f0960ad05447d385a554334c4b5c
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "Common.h" #include <glm/gtx/matrix_decompose.hpp> std::tuple<glm::vec3, glm::quat, glm::vec3> GetTransformDecomposition(const glm::mat4& transform) { glm::vec3 scale, translation, skew; glm::vec4 perspective; glm::quat orientation; glm::decompose(transform, scale, orientation, translation, skew, perspective); return { translation, orientation, scale }; }
24.5625
97
0.740458
pavilbezpravil
8dc01928c6b39a89fb33198e40721f77c62e262f
5,077
cpp
C++
Modules/Core/vaMemory.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
110
2018-09-04T20:33:59.000Z
2021-12-17T08:46:11.000Z
Modules/Core/vaMemory.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
5
2018-09-05T20:57:08.000Z
2021-02-24T09:02:31.000Z
Modules/Core/vaMemory.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
20
2018-09-05T00:41:13.000Z
2021-08-04T01:31:50.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Intel Corporation // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@intel.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "vaMemory.h" using namespace VertexAsylum; #include "IntegratedExternals/vaAssimpIntegration.h" _CrtMemState s_memStateStart; void vaMemory::Initialize( ) { // initialize some of the annoying globals so they appear before the s_memStateStart checkpoint { #ifdef VA_ASSIMP_INTEGRATION_ENABLED { Assimp::Importer importer; static unsigned char s_simpleObj [] = {35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,86,101,114,116,105,99,101,115,58,32,56,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,80,111,105,110,116,115,58,32,48,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,76,105,110,101,115,58,32,48,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,70,97,99,101,115,58,32,54,13,10,35,9,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,77,97,116,101,114,105,97,108,115,58,32,49,13,10,13,10,111,32,49,13,10,13,10,35,32,86,101,114,116,101,120,32,108,105,115,116,13,10,13,10,118,32,45,48,46,53,32,45,48,46,53,32,48,46,53,13,10,118,32,45,48,46,53,32,45,48,46,53,32,45,48,46,53,13,10,118,32,45,48,46,53,32,48,46,53,32,45,48,46,53,13,10,118,32,45,48,46,53,32,48,46,53,32,48,46,53,13,10,118,32,48,46,53,32,45,48,46,53,32,48,46,53,13,10,118,32,48,46,53,32,45,48,46,53,32,45,48,46,53,13,10,118,32,48,46,53,32,48,46,53,32,45,48,46,53,13,10,118,32,48,46,53,32,48,46,53,32,48,46,53,13,10,13,10,35,32,80,111,105,110,116,47,76,105,110,101,47,70,97,99,101,32,108,105,115,116,13,10,13,10,117,115,101,109,116,108,32,68,101,102,97,117,108,116,13,10,102,32,52,32,51,32,50,32,49,13,10,102,32,50,32,54,32,53,32,49,13,10,102,32,51,32,55,32,54,32,50,13,10,102,32,56,32,55,32,51,32,52,13,10,102,32,53,32,56,32,52,32,49,13,10,102,32,54,32,55,32,56,32,53,13,10,13,10,35,32,69,110,100,32,111,102,32,102,105,108,101,13,10,}; const aiScene * scene = importer.ReadFileFromMemory( s_simpleObj, _countof(s_simpleObj), 0, "obj" ); scene; //const aiScene * scene = importer.ReadFile( "C:\\Work\\Art\\crytek-sponza-other\\banner.obj", 0 ); } #endif // not needed // #ifdef VA_ENKITS_INTEGRATION_ENABLED // { // enki::TaskScheduler tempTS; // tempTS.Initialize(); // } // #endif } { #if defined(DEBUG) || defined(_DEBUG) // _CrtSetDbgFlag( 0 // | _CRTDBG_ALLOC_MEM_DF // | _CRTDBG_CHECK_CRT_DF // | _CRTDBG_CHECK_EVERY_128_DF // | _CRTDBG_LEAK_CHECK_DF // ); vaCore::DebugOutput( L"CRT memory checkpoint start" ); _CrtMemCheckpoint( &s_memStateStart ); //_CrtSetBreakAlloc( 291 ); // <- if this didn't work, the allocation probably happens before Initialize() or is a global variable #endif } } void vaMemory::Deinitialize() { #if defined(DEBUG) || defined(_DEBUG) _CrtMemState memStateStop, memStateDiff; _CrtMemCheckpoint( &memStateStop ); vaCore::DebugOutput( L"Checking for memory leaks...\n" ); if( _CrtMemDifference( &memStateDiff, &s_memStateStart, &memStateStop ) ) { _CrtMemDumpStatistics( &memStateDiff ); // doesn't play nice with .net runtime _CrtDumpMemoryLeaks(); VA_WARN( L"Memory leaks detected - check debug output; using _CrtSetBreakAlloc( allocationIndex ) in vaMemory::Initialize() might help to track it down. " ); // note: assimp sometimes leaks during importing - that's benign assert( false ); } else { vaCore::DebugOutput( L"No memory leaks detected!\n" ); } #endif }
52.340206
1,446
0.637187
magcius
8dc09ebb1c96844d37a252c065006eefe7b439ea
2,919
cpp
C++
A07_Supersampling&Anti_aliasing/source/raytracing_stats.cpp
satoshiSchubert/MIT_6.837_CG
df17d4daafbdf2350d44076205a06f87593bbc4a
[ "MIT" ]
null
null
null
A07_Supersampling&Anti_aliasing/source/raytracing_stats.cpp
satoshiSchubert/MIT_6.837_CG
df17d4daafbdf2350d44076205a06f87593bbc4a
[ "MIT" ]
null
null
null
A07_Supersampling&Anti_aliasing/source/raytracing_stats.cpp
satoshiSchubert/MIT_6.837_CG
df17d4daafbdf2350d44076205a06f87593bbc4a
[ "MIT" ]
null
null
null
#include <stdio.h> #include "raytracing_stats.h" int RayTracingStats::width; int RayTracingStats::height; BoundingBox *RayTracingStats::bbox; int RayTracingStats::num_x; int RayTracingStats::num_y; int RayTracingStats::num_z; unsigned long long RayTracingStats::start_time; unsigned long long RayTracingStats::num_nonshadow_rays; unsigned long long RayTracingStats::num_shadow_rays; unsigned long long RayTracingStats::num_intersections; unsigned long long RayTracingStats::num_grid_cells_traversed; // ==================================================================== // ==================================================================== void RayTracingStats::Initialize(int _width, int _height, BoundingBox *_bbox, int nx, int ny, int nz) { width = _width; height = _height; bbox = _bbox; num_x = nx; num_y = ny; num_z = nz; start_time = time(NULL); num_nonshadow_rays = 0; num_shadow_rays = 0; num_intersections = 0; num_grid_cells_traversed = 0; } // ==================================================================== // ==================================================================== void RayTracingStats::PrintStatistics() { int delta_time = time(NULL) - start_time; if (delta_time == 0) delta_time = 1; int secs = delta_time % 60; int min = (delta_time / 60) % 60; int hours = delta_time / (60 * 60); int num_rays = num_nonshadow_rays + num_shadow_rays; float rays_per_sec = float(num_rays) / float(delta_time); float rays_per_pixel = float(num_rays) / float(width * height); float intersections_per_ray = num_intersections / float(num_rays); float traversed_per_ray = num_grid_cells_traversed / float(num_rays); printf("********************************************\n"); printf("RAY TRACING STATISTICS\n"); printf(" total time %ld:%02d:%02d\n", hours, min, secs); printf(" num pixels %d (%dx%d)\n", width * height, width, height); printf(" scene bounds "); if (bbox == NULL) printf("NULL\n"); else bbox->Print(); printf(" num grid cells "); if (num_x == 0) printf("NULL\n"); else printf("%d (%dx%dx%d)\n", num_x * num_y * num_z, num_x, num_y, num_z); printf(" num non-shadow rays %lld\n", num_nonshadow_rays); printf(" num shadow rays %lld\n", num_shadow_rays); printf(" total intersections %lld\n", num_intersections); printf(" total cells traversed %lld\n", num_grid_cells_traversed); printf(" rays per second %0.1f\n", rays_per_sec); printf(" rays per pixel %0.1f\n", rays_per_pixel); printf(" intersections per ray %0.1f\n", intersections_per_ray); printf(" cells traversed per ray %0.1f\n", traversed_per_ray); printf("********************************************\n"); } // ==================================================================== // ====================================================================
39.986301
103
0.566975
satoshiSchubert
8dc1efe285244301c8bc86b56fd353a27ed544a3
10,193
cpp
C++
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
1
2019-01-09T08:20:18.000Z
2019-01-09T08:20:18.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkVolumeVisualizationView.h" #include <QComboBox> #include <vtkVersionMacros.h> #include <vtkSmartVolumeMapper.h> #include <berryISelectionProvider.h> #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> //#include <berryISelectionService.h> #include <mitkDataNodeObject.h> #include <mitkProperties.h> #include <mitkNodePredicateDataType.h> #include <mitkTransferFunction.h> #include <mitkTransferFunctionProperty.h> #include <mitkTransferFunctionInitializer.h> #include "mitkHistogramGenerator.h" #include "QmitkPiecewiseFunctionCanvas.h" #include "QmitkColorTransferFunctionCanvas.h" #include "mitkBaseRenderer.h" #include "mitkVtkVolumeRenderingProperty.h" #include <mitkIRenderingManager.h> #include <QToolTip> const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization"; enum {DEFAULT_RENDERMODE = 0, RAYCAST_RENDERMODE = 1, GPU_RENDERMODE = 2}; QmitkVolumeVisualizationView::QmitkVolumeVisualizationView() : QmitkAbstractView(), m_Controls(nullptr) { } QmitkVolumeVisualizationView::~QmitkVolumeVisualizationView() { } void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { m_Controls = new Ui::QmitkVolumeVisualizationViewControls; m_Controls->setupUi(parent); // Fill the tf presets in the generator widget std::vector<std::string> names; mitk::TransferFunctionInitializer::GetPresetNames(names); for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); ++it) { m_Controls->m_TransferFunctionGeneratorWidget->AddPreset(QString::fromStdString(*it)); } // see enum in vtkSmartVolumeMapper m_Controls->m_RenderMode->addItem("Default"); m_Controls->m_RenderMode->addItem("RayCast"); m_Controls->m_RenderMode->addItem("GPU"); // see vtkVolumeMapper::BlendModes m_Controls->m_BlendMode->addItem("Comp"); m_Controls->m_BlendMode->addItem("Max"); m_Controls->m_BlendMode->addItem("Min"); m_Controls->m_BlendMode->addItem("Avg"); m_Controls->m_BlendMode->addItem("Add"); connect( m_Controls->m_EnableRenderingCB, SIGNAL( toggled(bool) ),this, SLOT( OnEnableRendering(bool) )); connect(m_Controls->m_RenderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int))); connect(m_Controls->m_BlendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int))); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL( SignalUpdateCanvas( ) ), m_Controls->m_TransferFunctionWidget, SLOT( OnUpdateCanvas( ) ) ); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)), SLOT(OnMitkInternalPreset(int))); m_Controls->m_EnableRenderingCB->setEnabled(false); m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); } } void QmitkVolumeVisualizationView::OnMitkInternalPreset( int mode ) { if (m_SelectedNode.IsNull()) return; mitk::DataNode::Pointer node(m_SelectedNode.GetPointer()); mitk::TransferFunctionProperty::Pointer transferFuncProp; if (node->GetProperty(transferFuncProp, "TransferFunction")) { //first item is only information if( --mode == -1 ) return; // -- Creat new TransferFunction mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue()); tfInit->SetTransferFunctionMode(mode); RequestRenderWindowUpdate(); m_Controls->m_TransferFunctionWidget->OnUpdateCanvas(); } } void QmitkVolumeVisualizationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& nodes) { bool weHadAnImageButItsNotThreeDeeOrFourDee = false; mitk::DataNode::Pointer node; for (mitk::DataNode::Pointer currentNode: nodes) { if( currentNode.IsNotNull() && dynamic_cast<mitk::Image*>(currentNode->GetData()) ) { if( dynamic_cast<mitk::Image*>(currentNode->GetData())->GetDimension()>=3 ) { if (node.IsNull()) { node = currentNode; } } else { weHadAnImageButItsNotThreeDeeOrFourDee = true; } } } if( node.IsNotNull() ) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_SelectedImageLabel->show(); std::string infoText; if (node->GetName().empty()) infoText = std::string("Selected Image: [currently selected image has no name]"); else infoText = std::string("Selected Image: ") + node->GetName(); m_Controls->m_SelectedImageLabel->setText( QString( infoText.c_str() ) ); m_SelectedNode = node; } else { if(weHadAnImageButItsNotThreeDeeOrFourDee) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->show(); std::string infoText; infoText = std::string("only 3D or 4D images are supported"); m_Controls->m_ErrorImageLabel->setText( QString( infoText.c_str() ) ); } else { m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); } m_SelectedNode = 0; } UpdateInterface(); } void QmitkVolumeVisualizationView::UpdateInterface() { if(m_SelectedNode.IsNull()) { // turnoff all m_Controls->m_EnableRenderingCB->setChecked(false); m_Controls->m_EnableRenderingCB->setEnabled(false); m_Controls->m_BlendMode->setCurrentIndex(0); m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } bool enabled = false; m_SelectedNode->GetBoolProperty("volumerendering",enabled); m_Controls->m_EnableRenderingCB->setEnabled(true); m_Controls->m_EnableRenderingCB->setChecked(enabled); if(!enabled) { // turnoff all except volumerendering checkbox m_Controls->m_BlendMode->setCurrentIndex(0); m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } // otherwise we can activate em all m_Controls->m_BlendMode->setEnabled(true); m_Controls->m_RenderMode->setEnabled(true); // Determine Combo Box mode { bool usegpu=false; bool useray=false; bool usemip=false; m_SelectedNode->GetBoolProperty("volumerendering.usegpu",usegpu); m_SelectedNode->GetBoolProperty("volumerendering.useray",useray); m_SelectedNode->GetBoolProperty("volumerendering.usemip",usemip); int blendMode; if (m_SelectedNode->GetIntProperty("volumerendering.blendmode", blendMode)) m_Controls->m_BlendMode->setCurrentIndex(blendMode); if (usemip) m_Controls->m_BlendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND); int mode = DEFAULT_RENDERMODE; if (useray) mode = RAYCAST_RENDERMODE; else if(usegpu) mode = GPU_RENDERMODE; m_Controls->m_RenderMode->setCurrentIndex(mode); } m_Controls->m_TransferFunctionWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionWidget->setEnabled(true); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(true); } void QmitkVolumeVisualizationView::OnEnableRendering(bool state) { if(m_SelectedNode.IsNull()) return; m_SelectedNode->SetProperty("volumerendering",mitk::BoolProperty::New(state)); UpdateInterface(); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::OnBlendMode(int mode) { if (m_SelectedNode.IsNull()) return; bool usemip = false; if (mode == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND) usemip = true; m_SelectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip)); m_SelectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode)); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::OnRenderMode(int mode) { if(m_SelectedNode.IsNull()) return; bool usegpu = false; if (mode == GPU_RENDERMODE) usegpu = true; bool useray = false; if (mode == RAYCAST_RENDERMODE) useray = true; if (mode == DEFAULT_RENDERMODE) { useray = true; usegpu = true; } m_SelectedNode->SetProperty("volumerendering.usegpu",mitk::BoolProperty::New(usegpu)); m_SelectedNode->SetProperty("volumerendering.useray",mitk::BoolProperty::New(useray)); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::SetFocus() { } void QmitkVolumeVisualizationView::NodeRemoved(const mitk::DataNode* node) { if(m_SelectedNode == node) { m_SelectedNode=0; m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); UpdateInterface(); } }
29.544928
161
0.725596
ZP-Hust
8dc4be40baf57c5481b922d3345f37176d7c3963
1,937
cpp
C++
tests/Ontology/AddressTests.cpp
baophucct/wallet-core
9583b45d732fa442f73090c02903a97f09dff6a8
[ "MIT" ]
null
null
null
tests/Ontology/AddressTests.cpp
baophucct/wallet-core
9583b45d732fa442f73090c02903a97f09dff6a8
[ "MIT" ]
null
null
null
tests/Ontology/AddressTests.cpp
baophucct/wallet-core
9583b45d732fa442f73090c02903a97f09dff6a8
[ "MIT" ]
1
2019-03-11T08:54:14.000Z
2019-03-11T08:54:14.000Z
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "PublicKey.h" #include "HexCoding.h" #include "Ontology/Signer.h" #include "Ontology/Address.h" #include <gtest/gtest.h> using namespace TW; using namespace TW::Ontology; TEST(OntologyAddress, validation) { ASSERT_FALSE(Address::isValid("abc")); ASSERT_FALSE(Address::isValid("abeb60f3e94c1b9a09f33669435e7ef12eacd")); ASSERT_FALSE(Address::isValid("abcb60f3e94c9b9a09f33669435e7ef1beaedads")); ASSERT_TRUE(Address::isValid("ANDfjwrUroaVtvBguDtrWKRMyxFwvVwnZD")); } TEST(OntologyAddress, fromPubKey) { auto address = Address(PublicKey(parse_hex("031bec1250aa8f78275f99a6663688f31085848d0ed92f1203e447125f927b7486"))); EXPECT_EQ("AeicEjZyiXKgUeSBbYQHxsU1X3V5Buori5", address.string()); } TEST(OntologyAddress, fromString) { auto b58Str = "AYTxeseHT5khTWhtWX1pFFP1mbQrd4q1zz"; auto address = Address(b58Str); EXPECT_EQ(b58Str, address.string()); auto errB58Str = "AATxeseHT5khTWhtWX1pFFP1mbQrd4q1zz"; ASSERT_THROW(new Address(errB58Str), std::runtime_error); } TEST(OntologyAddress, fromMultiPubKeys) { auto signer1 = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464646"))); auto signer2 = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464652"))); auto signer3 = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464658"))); std::vector<Data> pubKeys{signer1.getPublicKey().bytes, signer2.getPublicKey().bytes, signer3.getPublicKey().bytes}; uint8_t m = 2; auto multiAddress = Address(m, pubKeys); EXPECT_EQ("AYGWgijVZnrUa2tRoCcydsHUXR1111DgdW", multiAddress.string()); }
43.044444
120
0.782137
baophucct
44ef77164d82668b870baabd6ceb74c9317b7813
3,902
cpp
C++
thirdparty/vesta/interaction/ObserverController.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
thirdparty/vesta/interaction/ObserverController.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
thirdparty/vesta/interaction/ObserverController.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
/* * $Revision: 223 $ $Date: 2010-03-30 05:44:44 -0700 (Tue, 30 Mar 2010) $ * * Copyright by Astos Solutions GmbH, Germany * * this file is published under the Astos Solutions Free Public License * For details on copyright and terms of use see * http://www.astos.de/Astos_Solutions_Free_Public_License.html */ #include "ObserverController.h" #include "../WorldGeometry.h" #include "../Debug.h" #include <cmath> using namespace vesta; using namespace Eigen; using namespace std; ObserverController::ObserverController() : m_orbitAngularVelocity(Vector3d::Zero()), m_panAngularVelocity(Vector3d::Zero()), m_dollyVelocity(1.0), m_rotationDampingFactor(5.0) { } ObserverController::~ObserverController() { } /** Update the position and orientation of the observer. * * \param dt the amount of real time in seconds elapsed since the last tick */ void ObserverController::tick(double dt) { double damping = exp(-dt * m_rotationDampingFactor); m_orbitAngularVelocity *= damping; m_panAngularVelocity *= damping; m_dollyVelocity = pow(m_dollyVelocity, damping); double w = m_orbitAngularVelocity.norm(); if (w > 1.0e-6) { m_observer->orbit(Quaterniond(AngleAxisd(w * dt, m_orbitAngularVelocity / w))); } w = m_panAngularVelocity.norm(); if (w > 1.0e-6) { m_observer->rotate(Quaterniond(AngleAxisd(w * dt, m_panAngularVelocity / w))); } if (abs(m_dollyVelocity - 1.0) > 1.0e-6) { Entity* center = m_observer->center(); double f = pow(m_dollyVelocity, dt * 1000.0); if (center) { // Special case for world geometry, where the distance is to the surface of the // planet, not the center. // TODO: It would be a better design to have a method that reports the appropriate // distance to use for any geometry. WorldGeometry* world = dynamic_cast<WorldGeometry*>(center->geometry()); if (world) { double distance = m_observer->position().norm() - world->maxRadius(); m_observer->setPosition(m_observer->position().normalized() * (world->maxRadius() + distance * f)); } else { m_observer->changeDistance(f); } } } } /** Apply a torque to the observer that causes it to rotate * about its center. */ void ObserverController::applyTorque(const Vector3d& torque) { m_panAngularVelocity += torque; } /** Apply a 'torque' that causes the observer to rotate about the * center object. */ void ObserverController::applyOrbitTorque(const Vector3d& torque) { m_orbitAngularVelocity += torque; } /** Rotate the observer about its local x axis (horizontal axis on * the screen. */ void ObserverController::pitch(double f) { applyTorque(Vector3d::UnitX() * f); } /** Rotate the observer about its local y axis (vertical axis on * the screen. */ void ObserverController::yaw(double f) { applyTorque(Vector3d::UnitY() * f); } /** Rotate the observer about its local z axis (which points out of * the screen back toward the user.) */ void ObserverController::roll(double f) { applyTorque(Vector3d::UnitZ() * f); } /** Move the camera along a line between the positions of the observer and * the object of interest. The rate of movement varies exponentially with * the distance to the object of interest. A factor of less than one moves * the observer toward the object of interest, and a factor greater than * one moves the observer away. */ void ObserverController::dolly(double factor) { m_dollyVelocity *= factor; } /** Stop all translational and rotational motion. */ void ObserverController::stop() { m_dollyVelocity = 1.0; m_panAngularVelocity = Vector3d::Zero(); m_orbitAngularVelocity = Vector3d::Zero(); }
25.337662
115
0.665812
hoehnp
44f6c833a316625f1aec35de8f1722bfcaa615d8
922
hpp
C++
include/mizuiro/color/format/homogenous_ns/types/pointer.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/color/format/homogenous_ns/types/pointer.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/color/format/homogenous_ns/types/pointer.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_TYPES_POINTER_HPP_INCLUDED #define MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_TYPES_POINTER_HPP_INCLUDED #include <mizuiro/apply_const.hpp> #include <mizuiro/access/pointer.hpp> #include <mizuiro/color/format/homogenous_ns/tag.hpp> #include <mizuiro/color/types/pointer_ns/tag.hpp> namespace mizuiro::color::types::pointer_ns { template <typename Access, typename Format, typename Constness> mizuiro::apply_const<mizuiro::access::pointer<Access, typename Format::channel_type *>, Constness> pointer_adl( mizuiro::color::types::pointer_ns::tag, Access, mizuiro::color::format::homogenous_ns::tag<Format>, Constness); } #endif
32.928571
98
0.752711
cpreh
44f99489ab1e36fc67b8b82f4daf4bf263a0c57a
55,164
cpp
C++
src/slam/Debug.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
src/slam/Debug.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
src/slam/Debug.cpp
meitiever/SLAM-BA
57ee2af8508300e818feb67f7adbe026eee3ada7
[ "MIT" ]
null
null
null
/* +-----------------------------------+ | | | *** Debugging functionality *** | | | | Copyright (c) -tHE SWINe- 2015 | | | | Debug.cpp | | | +-----------------------------------+ */ /** * @file src/slam/Debug.cpp * @brief basic debugging functionality * @author -tHE SWINe- * @date 2015-10-07 */ #include "slam/Debug.h" #include <csparse/cs.hpp> #include "slam/Tga.h" #include "slam/Parser.h" #include "slam/BlockMatrix.h" #include <math.h> #include <cmath> /* * === globals === */ #if !defined(_WIN32) && !defined(_WIN64) #include <stdio.h> #include <ctype.h> #include <string.h> // sprintf bool _finite(double x) { #ifdef __FAST_MATH__ // handle https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25975 char p_s_str[256]; size_t l = sprintf(p_s_str, "%f", x); // total number of characters written is returned, this count does not include the additional null //size_t l = strlen(p_s_str); std::transform(p_s_str, p_s_str + l, p_s_str, tolower); return !strstr(p_s_str, "nan") && !strstr(p_s_str, "ind") && !strstr(p_s_str, "inf"); // https://en.wikipedia.org/wiki/NaN#Display #else // __FAST_MATH__ //return isfinite(x); // math.h, did not work in some later versions of g++ return std::isfinite(x); // cmath, should work #endif // __FAST_MATH__ } bool _isnan(double x) { #ifdef __FAST_MATH__ // handle https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25975 char p_s_str[256]; size_t l = sprintf(p_s_str, "%f", x); // total number of characters written is returned, this count does not include the additional null //size_t l = strlen(p_s_str); std::transform(p_s_str, p_s_str + l, p_s_str, tolower); return strstr(p_s_str, "nan") != 0 || strstr(p_s_str, "ind") != 0; // https://en.wikipedia.org/wiki/NaN#Display #else // __FAST_MATH__ //return isnan(x); // math.h, should work return std::isnan(x); // cmath, should work #endif // __FAST_MATH__ } #endif // !_WIN32 && !_WIN64 /* * === ~globals === */ /* * === CDebug::CSparseMatrixShapedIterator === */ CDebug::CSparseMatrixShapedIterator::CSparseMatrixShapedIterator(const cs *p_matrix) :m_p_matrix(p_matrix), m_n_rows(p_matrix->m), m_n_columns(p_matrix->n), m_n_column(0), m_n_row(0), m_n_row_pointer(p_matrix->p[0]), m_n_row_pointer_column_end(p_matrix->p[1]), m_n_row_pointer_end(p_matrix->p[p_matrix->n]) { if(m_n_row_pointer <= m_n_row_pointer_column_end) { size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } } CDebug::CSparseMatrixShapedIterator::CSparseMatrixShapedIterator(const cs *p_matrix, size_t n_rows, size_t n_cols) :m_p_matrix(p_matrix), m_n_rows(n_rows), m_n_columns(n_cols), m_n_column(0), m_n_row(0), m_n_row_pointer(p_matrix->p[0]), m_n_row_pointer_column_end(p_matrix->p[1]), m_n_row_pointer_end(p_matrix->p[p_matrix->n]) { if(m_n_row_pointer <= m_n_row_pointer_column_end) { size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } } double CDebug::CSparseMatrixShapedIterator::operator *() const { _ASSERTE(m_n_column < m_n_columns && m_n_row < m_n_rows); // make sure the iterator is dereferencable if(m_n_row_pointer < m_n_row_pointer_column_end) { _ASSERTE(unsigned(m_p_matrix->i[m_n_row_pointer]) >= m_n_row); if(size_t(m_p_matrix->i[m_n_row_pointer]) == m_n_row) return (m_p_matrix->x)? m_p_matrix->x[m_n_row_pointer] : 1; } return 0; // no data (outside the matrix or being in "sparse area") } double CDebug::CSparseMatrixShapedIterator::f_Get(bool &r_b_value) const { _ASSERTE(m_n_column < m_n_columns && m_n_row < m_n_rows); // make sure the iterator is dereferencable if(m_n_row_pointer < m_n_row_pointer_column_end) { _ASSERTE(unsigned(m_p_matrix->i[m_n_row_pointer]) >= m_n_row); if(size_t(m_p_matrix->i[m_n_row_pointer]) == m_n_row) { r_b_value = true; return (m_p_matrix->x)? m_p_matrix->x[m_n_row_pointer] : 1; } } r_b_value = false; return 0; // no data (outside the matrix or being in "sparse area") } void CDebug::CSparseMatrixShapedIterator::operator ++() { _ASSERTE(m_n_column < m_n_columns); _ASSERTE(m_n_row < m_n_rows); // make sure we're not iterating too far if(m_n_column >= unsigned(m_p_matrix->n)) { if(++ m_n_row == m_n_rows) { m_n_row = 0; ++ m_n_column; } // we are below the matrix data, just iterating zeroes } else if(m_n_row >= unsigned(m_p_matrix->m)) { if(++ m_n_row == m_n_rows) { m_n_row = 0; ++ m_n_column; _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); /*if(m_n_column <= m_p_matrix->n) */ { // always true // m_p_matrix->n is a valid index in p (sets m_n_row_pointer_offset equal to m_n_row_pointer_end) m_n_row_pointer = m_p_matrix->p[m_n_column]; m_n_row_pointer_column_end = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; } } // we are right of the matrix data, just iterating zeroes (the same code) } else { if(++ m_n_row == m_n_rows) { m_n_row = 0; ++ m_n_column; _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); /*if(m_n_column <= m_p_matrix->n) */ { // always true // m_p_matrix->n is a valid index in p (sets m_n_row_pointer_offset equal to m_n_row_pointer_end) m_n_row_pointer = m_p_matrix->p[m_n_column]; m_n_row_pointer_column_end = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; } } // shift to the next row / column size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; _ASSERTE(e >= p); _ASSERTE(m_n_row_pointer_column_end == e); _ASSERTE(m_n_row_pointer >= p && m_n_row_pointer <= e); // note that m_n_row_pointer == e is a valid state in case there is not enough data on the row // we are inside the matrix data; just need to find row in the CSC array if(m_n_row_pointer <= m_n_row_pointer_column_end) { // have to check if we hit the last nonzero row in the column size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; while(n_data_row < m_n_row && m_n_row_pointer < m_n_row_pointer_column_end) n_data_row = m_p_matrix->i[++ m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } // makes sure that m_n_row_pointer points to an element at the current or greater } _ASSERTE((m_n_column < m_n_columns && m_n_row < m_n_rows) || (m_n_column == m_n_columns && !m_n_row)); // make sure we are still inside, or just outside if(m_n_column < unsigned(m_p_matrix->n)) { #ifdef _DEBUG size_t p = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column] : m_n_row_pointer_end, e = (m_n_column + 1 < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer_end; #endif // _DEBUG _ASSERTE(m_n_row_pointer_column_end == e); if(m_n_row < unsigned(m_p_matrix->m)) { _ASSERTE(m_n_row_pointer == e || m_n_row <= unsigned(m_p_matrix->i[m_n_row_pointer])); // either we are at the end of data, or m_n_row_pointer points at or after current row } else { _ASSERTE(m_n_row_pointer == e); // we are at the end of the row for sure } } else { _ASSERTE(m_n_row_pointer == m_n_row_pointer_end); _ASSERTE(m_n_row_pointer_column_end == m_n_row_pointer_end); // we are at the end } // iterator integrity check } /* * === ~CDebug::CSparseMatrixShapedIterator === */ /* * === CDebug::CSparseMatrixIterator === */ CDebug::CSparseMatrixIterator::CSparseMatrixIterator(const cs *p_matrix) :m_p_matrix(p_matrix), m_n_column(0), m_n_row(0), m_n_row_pointer(p_matrix->p[0]), m_n_row_pointer_column_end(p_matrix->p[1]) { if(m_n_row_pointer <= m_n_row_pointer_column_end) { size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { size_t p = m_p_matrix->p[m_n_column], e = (m_n_column + 1 <= size_t(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : p; for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } } double CDebug::CSparseMatrixIterator::operator *() const { _ASSERTE(m_n_column < unsigned(m_p_matrix->n) && m_n_row < unsigned(m_p_matrix->m)); // make sure the iterator is dereferencable if(m_n_row_pointer < m_n_row_pointer_column_end) { _ASSERTE(unsigned(m_p_matrix->i[m_n_row_pointer]) >= m_n_row); if(size_t(m_p_matrix->i[m_n_row_pointer]) == m_n_row) return (m_p_matrix->x)? m_p_matrix->x[m_n_row_pointer] : 1; } return 0; // no data (being in "sparse area") } void CDebug::CSparseMatrixIterator::operator ++() { _ASSERTE(m_n_column < unsigned(m_p_matrix->n)); _ASSERTE(m_n_row < unsigned(m_p_matrix->m)); // make sure we're not iterating too far { if(++ m_n_row == size_t(m_p_matrix->m)) { m_n_row = 0; ++ m_n_column; _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); /*if(m_n_column <= m_p_matrix->n) */ { // always true // m_p_matrix->n is a valid index in p (sets m_n_row_pointer_offset equal to the ebd) m_n_row_pointer = m_p_matrix->p[m_n_column]; m_n_row_pointer_column_end = (m_n_column < unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : m_n_row_pointer; // m_n_row_pointer == p_matrix->p[p_matrix->n] by then _ASSERTE(m_n_column < unsigned(m_p_matrix->n) || m_n_row_pointer == m_p_matrix->p[m_p_matrix->n]); // just to make sure } } // shift to the next row / column _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); size_t p = m_p_matrix->p[m_n_column], e = (m_n_column + 1 <= unsigned(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : p; _ASSERTE(e >= p); _ASSERTE(m_n_row_pointer_column_end == e); _ASSERTE(m_n_row_pointer >= p && m_n_row_pointer <= e); // note that m_n_row_pointer == e is a valid state in case there is not enough data on the row // we are inside the matrix data; just need to find row in the CSC array if(m_n_row_pointer <= m_n_row_pointer_column_end) { // have to check if we hit the last nonzero row in the column size_t n_data_row = m_p_matrix->i[m_n_row_pointer]; while(n_data_row < m_n_row && m_n_row_pointer < m_n_row_pointer_column_end) n_data_row = m_p_matrix->i[++ m_n_row_pointer]; if(m_n_row_pointer == m_n_row_pointer_column_end || n_data_row != m_n_row) { for(size_t i = p; i < e; ++ i) { if(size_t(m_p_matrix->i[i]) == m_n_row) { m_n_row_pointer = i; break; } } // e.g. cs_multiply() produces matrices where i is not sorted :( } } // makes sure that m_n_row_pointer points to an element at the current or greater } _ASSERTE((m_n_column < unsigned(m_p_matrix->n) && m_n_row < unsigned(m_p_matrix->m)) || (m_n_column == m_p_matrix->n && !m_n_row)); // make sure we are still inside, or just outside if(m_n_column < unsigned(m_p_matrix->n)) { _ASSERTE(m_n_column <= unsigned(m_p_matrix->n)); #ifdef _DEBUG size_t p = m_p_matrix->p[m_n_column], e = (m_n_column + 1 <= size_t(m_p_matrix->n))? m_p_matrix->p[m_n_column + 1] : p; #endif // _DEBUG _ASSERTE(m_n_row_pointer_column_end == e); if(m_n_row < unsigned(m_p_matrix->m)) { _ASSERTE(m_n_row_pointer == e || m_n_row <= unsigned(m_p_matrix->i[m_n_row_pointer])); // either we are at the end of data, or m_n_row_pointer points at or after current row } else { _ASSERTE(m_n_row_pointer == e); // we are at the end of the row for sure } } else { _ASSERTE(m_n_row_pointer == m_n_row_pointer_column_end); _ASSERTE(m_n_row_pointer_column_end == m_p_matrix->p[m_p_matrix->n]); // we are at the end } // iterator integrity check } /* * === ~CDebug::CSparseMatrixIterator === */ /* * === CDebug === */ bool CDebug::Dump_SparseMatrix(const char *p_s_filename, const cs *A, const cs *A_prev /*= 0*/, int n_scalar_size /*= 5*/) { _ASSERTE(CS_CSC(A)); _ASSERTE(!A_prev || CS_CSC(A_prev)); // the matrices need to be in compressed column form const uint32_t n_background = 0xffffffffU, n_nonzero = 0xff8080ffU, n_nonzero_new = 0xffff0000U, n_zero_new = 0xff00ff00U; // colors of the individual areas const uint32_t n_nonzero_border = 0x80000000U | ((n_nonzero >> 1) & 0x7f7f7f7fU), n_nonzero_new_border = 0x80000000U | ((n_nonzero_new >> 1) & 0x7f7f7f7fU), n_zero_new_border = 0x80000000U | ((n_zero_new >> 1) & 0x7f7f7f7fU); // colors of borders (just darker) size_t m = (A_prev)? std::max(A->m, A_prev->m) : A->m; size_t n = (A_prev)? std::max(A->n, A_prev->n) : A->n; if(m == SIZE_MAX || n == SIZE_MAX || m > INT_MAX || n > INT_MAX || m * (n_scalar_size - 1) + 1 > INT_MAX || n * (n_scalar_size - 1) + 1 > INT_MAX || uint64_t(m * (n_scalar_size - 1) + 1) * (m * (n_scalar_size - 1) + 1) > INT_MAX) return false; TBmp *p_bitmap; if(!(p_bitmap = TBmp::p_Alloc(int(n * (n_scalar_size - 1) + 1), int(m * (n_scalar_size - 1) + 1)))) return false; p_bitmap->Clear(n_background); if(A_prev) { CSparseMatrixShapedIterator p_a_it(A, m, n); CSparseMatrixShapedIterator p_a_prev_it(A_prev, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it, ++ p_a_prev_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); _ASSERTE(n_row == p_a_prev_it.n_Row() && n_col == p_a_prev_it.n_Column()); // make sure it iterates to the right position bool b_is; double f_value = p_a_it.f_Get(b_is);// = *p_a_it; double f_prev_value = *p_a_prev_it; // read the value double f_value_thr = (fabs(f_value) < 1e-10)? 0 : f_value; double f_prev_value_thr = (fabs(f_prev_value) < 1e-10)? 0 : f_prev_value; // threshold if(b_is || f_value != 0 || f_prev_value != 0) { uint32_t n_fill_color = (f_value_thr != 0 && f_prev_value_thr != 0)? n_nonzero : (f_value_thr != 0 && f_prev_value_thr == 0)? n_nonzero_new : (f_value != 0 && f_prev_value != 0)? n_nonzero : n_zero_new; uint32_t n_line_color = (f_value_thr != 0 && f_prev_value_thr != 0)? n_nonzero_border : (f_value_thr != 0 && f_prev_value_thr == 0)? n_nonzero_new_border : (f_value != 0 && f_prev_value != 0)? n_nonzero_border : n_zero_new_border; size_t n_x = n_col * (n_scalar_size - 1); size_t n_y = n_row * (n_scalar_size - 1); for(int dy = 1; dy < n_scalar_size - 1; ++ dy) for(int dx = 1; dx < n_scalar_size - 1; ++ dx) p_bitmap->PutPixel(int(n_x + dx), int(n_y + dy), n_fill_color); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x + n_scalar_size - 1), float(n_y), n_line_color); p_bitmap->DrawLine_SP(float(n_x), float(n_y + n_scalar_size - 1), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_line_color); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x), float(n_y + n_scalar_size - 1), n_line_color); p_bitmap->DrawLine_SP(float(n_x + n_scalar_size - 1), float(n_y), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_line_color); } // draw a square into the bitmap } } } else { CSparseMatrixShapedIterator p_a_it(A, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); // make sure it iterates to the right position double f_value = *p_a_it; // read the value if(f_value != 0) { size_t n_x = n_col * (n_scalar_size - 1); size_t n_y = n_row * (n_scalar_size - 1); for(int dy = 1; dy < n_scalar_size - 1; ++ dy) for(int dx = 1; dx < n_scalar_size - 1; ++ dx) p_bitmap->PutPixel(int(n_x + dx), int(n_y + dy), n_nonzero); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x + n_scalar_size - 1), float(n_y), n_nonzero_border); p_bitmap->DrawLine_SP(float(n_x), float(n_y + n_scalar_size - 1), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_nonzero_border); p_bitmap->DrawLine_SP(float(n_x), float(n_y), float(n_x), float(n_y + n_scalar_size - 1), n_nonzero_border); p_bitmap->DrawLine_SP(float(n_x + n_scalar_size - 1), float(n_y), float(n_x + n_scalar_size - 1), float(n_y + n_scalar_size - 1), n_nonzero_border); } // draw a square into the bitmap } } } // iterate the matrix, draw small tiles bool b_result = CTgaCodec::Save_TGA(p_s_filename, *p_bitmap, false); p_bitmap->Delete(); /*for(int j = 0; j < n; ++ j) { //printf(" col %d\n", j); int y = 0; if(j < A->n) { for(int p = A->p[j]; p < A->p[j + 1]; ++ p, ++ y) { int n_cur_y = A->i[p]; for(; y < n_cur_y; ++ y) ;//printf(" %f, ", .0f); // zero entries double f_value = (A->x)? A->x[p] : 1; // nonzero entry } for(; y < m; ++ y) ;//printf(" %f%s", .0f, (x + 1 == m)? "\n" : ", "); // zero entries } }*/ // t_odo - make this an iterator anyway // t_odo - rasterize the matrix (A_prev is used to mark difference areas) // todo - implement libPNG image writing return b_result; } static inline void PutPixel_Max(TBmp *p_bitmap, int x, int y, uint32_t n_color) { uint32_t *p_buffer = p_bitmap->p_buffer; const int n_width = p_bitmap->n_width; const int n_height = p_bitmap->n_height; if(x >= 0 && x < n_width && y >= 0 && y < n_height) { uint32_t &r_n_pixel = p_buffer[int(x) + n_width * int(y)]; if((r_n_pixel & 0xffffff) < (n_color & 0xffffff)) r_n_pixel = n_color; } } #define BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS // optimize bitmap write routines to access the bitmaps row-wise for better cache reuse #define BITMAP_SUBSAMPLE_DUMP_PARALLELIZE // parallelize Dump_SparseMatrix_Subsample() and Dump_SparseMatrix_Subsample_AA() (only if BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS is defined) bool CDebug::Dump_SparseMatrix_Subsample(const char *p_s_filename, const cs *A, const cs *A_prev /*= 0*/, size_t n_max_bitmap_size /*= 640*/, bool b_symmetric /*= false*/) { _ASSERTE(CS_CSC(A)); _ASSERTE(!A_prev || CS_CSC(A_prev)); // the matrices need to be in compressed column form const uint32_t n_background = 0xffffffffU, n_nonzero = 0xff8080ffU, n_nonzero_new = 0xffff0000U, n_zero_new = 0xff00ff00U; // colors of the individual areas size_t m = (A_prev)? std::max(A->m, A_prev->m) : A->m; size_t n = (A_prev)? std::max(A->n, A_prev->n) : A->n; size_t mb = m, nb = n; double f_scale = double(n_max_bitmap_size) / std::max(m, n); if(f_scale < 1) { mb = std::max(size_t(1), size_t(m * f_scale)); nb = std::max(size_t(1), size_t(n * f_scale)); } else f_scale = 1; // scale the bitmap down if needed if(mb == SIZE_MAX || nb == SIZE_MAX || mb > INT_MAX || nb > INT_MAX || uint64_t(mb) * nb > INT_MAX) return false; TBmp *p_bitmap; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(mb), int(nb)))) // transposed return false; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(nb), int(mb)))) return false; #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(A_prev) { p_bitmap->Clear(0/*n_background*/); CSparseMatrixShapedIterator p_a_it(A, m, n); CSparseMatrixShapedIterator p_a_prev_it(A_prev, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it, ++ p_a_prev_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); _ASSERTE(n_row == p_a_prev_it.n_Row() && n_col == p_a_prev_it.n_Column()); // make sure it iterates to the right position bool b_is; double f_value = p_a_it.f_Get(b_is);// = *p_a_it; double f_prev_value = *p_a_prev_it; // read the value double f_value_thr = (fabs(f_value) < 1e-10)? 0 : f_value; double f_prev_value_thr = (fabs(f_prev_value) < 1e-10)? 0 : f_prev_value; // threshold if(b_is || f_value != 0 || f_prev_value != 0) { uint32_t n_fill_color = (f_value_thr != 0 && f_prev_value_thr != 0)? 1/*n_nonzero*/ : (f_value_thr != 0 && f_prev_value_thr == 0)? 3/*n_nonzero_new*/ : (f_value != 0 && f_prev_value != 0)? 1/*n_nonzero*/ : 2/*n_zero_new*/; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_y = size_t(n_col * f_scale); size_t n_x = size_t(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_x = size_t(n_col * f_scale); size_t n_y = size_t(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS PutPixel_Max(p_bitmap, /*->PutPixel(*/int(n_x), int(n_y), n_fill_color); //if(b_symmetric && n_x != n_y) // PutPixel_Max(p_bitmap, /*->PutPixel(*/int(n_y), int(n_x), n_fill_color); // use PutPixel_Max() to get some deterministic precedences of the colors } // draw a dot into the bitmap } } if(b_symmetric) { uint32_t *p_buff = p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); uint32_t *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); uint32_t *p_lo = p_buff + (y + x * w); *p_up = std::max(*p_up, *p_lo); // choose the "color" with higher priority *p_lo = *p_up; // duplicate the result to the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices uint32_t p_color_table[] = {n_background, n_nonzero, n_zero_new, n_nonzero_new}; for(uint32_t *p_buffer = p_bitmap->p_buffer, *p_end = p_bitmap->p_buffer + nb * mb; p_buffer != p_end; ++ p_buffer) { _ASSERTE(*p_buffer < sizeof(p_color_table) / sizeof(p_color_table[0])); *p_buffer = p_color_table[*p_buffer]; } // look the color table up } else { p_bitmap->Clear(n_background); /*CSparseMatrixShapedIterator p_a_it(A, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); // make sure it iterates to the right position*/ #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS #ifdef BITMAP_SUBSAMPLE_DUMP_PARALLELIZE if(n < INT_MAX && A->p[n] >= 10000) { const int _n = int(n); #pragma omp parallel for schedule(dynamic, 1) for(int n_col = 0; n_col < _n; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; double f_value = (A->x)? A->x[n_p0] : 1; // read the value if(f_value != 0) p_bitmap->PutPixel(int(n_row * f_scale), int(n_col * f_scale), n_nonzero); // draw a dot into the bitmap } } } else #endif // BITMAP_SUBSAMPLE_DUMP_PARALLELIZE { for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; const double f_one = 1, *p_a_it = (A->x)? A->x + n_p0 : &f_one; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS { CSparseMatrixIterator p_a_it(A); // can use the simple iterator here for(; p_a_it.n_Column() < n; ++ p_a_it) { size_t n_col = p_a_it.n_Column(); size_t n_row = p_a_it.n_Row(); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS double f_value = *p_a_it; // read the value if(f_value != 0) { #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_y = size_t(n_col * f_scale); size_t n_x = size_t(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS size_t n_x = size_t(n_col * f_scale); size_t n_y = size_t(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS p_bitmap->PutPixel(int(n_x), int(n_y), n_nonzero); //if(b_symmetric && n_x != n_y) // p_bitmap->PutPixel(int(n_y), int(n_x), n_nonzero); } // draw a square into the bitmap } } } if(b_symmetric) { uint32_t *p_buff = p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); uint32_t *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); uint32_t *p_lo = p_buff + (y + x * w); *p_up = std::min(*p_up, *p_lo); // choose the darker color *p_lo = *p_up; // duplicate the result to the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices } // iterate the matrix, draw small tiles #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if((m != n || !b_symmetric) && !p_bitmap->Transpose()) { p_bitmap->Delete(); return false; } #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS bool b_result = CTgaCodec::Save_TGA(p_s_filename, *p_bitmap, false); p_bitmap->Delete(); return b_result; } static inline void AlphaBlend_RGBA_HQ(uint32_t &r_n_dest, uint32_t n_src, float f_alpha) { int n_dest_a = (r_n_dest >> 24) & 0xff; int n_dest_r = (r_n_dest >> 16) & 0xff; int n_dest_g = (r_n_dest >> 8) & 0xff; int n_dest_b = (r_n_dest) & 0xff; int n_src_a = (n_src >> 24) & 0xff; int n_src_r = (n_src >> 16) & 0xff; int n_src_g = (n_src >> 8) & 0xff; int n_src_b = (n_src) & 0xff; n_dest_a = std::max(0, std::min(255, int(n_dest_a + f_alpha * (n_src_a - n_dest_a) + .5f))); n_dest_r = std::max(0, std::min(255, int(n_dest_r + f_alpha * (n_src_r - n_dest_r) + .5f))); n_dest_g = std::max(0, std::min(255, int(n_dest_g + f_alpha * (n_src_g - n_dest_g) + .5f))); n_dest_b = std::max(0, std::min(255, int(n_dest_b + f_alpha * (n_src_b - n_dest_b) + .5f))); r_n_dest = (n_dest_a << 24) | (n_dest_r << 16) | (n_dest_g << 8) | n_dest_b; } static inline void PutPixel_AA_RGBA_HQ(TBmp *p_bitmap, float f_x, float f_y, uint32_t n_color) { uint32_t *p_buffer = p_bitmap->p_buffer; const int n_width = p_bitmap->n_width; const int n_height = p_bitmap->n_height; int x = int(floor(f_x)), y = int(floor(f_y)); float f_frac_x = f_x - x; float f_frac_y = f_y - y; const float f_alpha = ((n_color >> 24) & 0xff) / 255.0f; // alpha of the incoming pixel float f_weight_00 = (f_alpha * (1 - f_frac_x) * (1 - f_frac_y)); float f_weight_10 = (f_alpha * f_frac_x * (1 - f_frac_y)); float f_weight_01 = (f_alpha * (1 - f_frac_x) * f_frac_y); float f_weight_11 = (f_alpha * f_frac_x * f_frac_y); if(x >= 0 && x < n_width && y >= 0 && y < n_height) AlphaBlend_RGBA_HQ(p_buffer[x + n_width * y], n_color, f_weight_00); if(x + 1 >= 0 && x + 1 < n_width && y >= 0 && y < n_height) AlphaBlend_RGBA_HQ(p_buffer[(x + 1) + n_width * y], n_color, f_weight_10); if(x >= 0 && x < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_RGBA_HQ(p_buffer[x + n_width * (y + 1)], n_color, f_weight_01); if(x + 1 >= 0 && x + 1 < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_RGBA_HQ(p_buffer[(x + 1) + n_width * (y + 1)], n_color, f_weight_11); } static inline void AlphaBlend_Float(float &r_f_dest, float f_src, float f_alpha) { //r_f_dest = (r_f_dest * (1 - f_alpha)) + f_src * f_alpha; //r_f_dest = r_f_dest * 1 + f_src * f_alpha - r_f_dest * f_alpha; //r_f_dest = r_f_dest + (f_src - r_f_dest) * f_alpha; r_f_dest = r_f_dest + f_alpha * (f_src - r_f_dest); } static inline void PutPixel_AA_Float(TBmp *p_bitmap, float f_x, float f_y) // this is likely quite slow { _ASSERTE(sizeof(float) == sizeof(uint32_t)); float *p_buffer = (float*)p_bitmap->p_buffer; const int n_width = p_bitmap->n_width; const int n_height = p_bitmap->n_height; int x = int(floor(f_x)), y = int(floor(f_y)); float f_frac_x = f_x - x; float f_frac_y = f_y - y; const float f_alpha = 1; // alpha of the incoming pixel float f_weight_00 = (f_alpha * (1 - f_frac_x) * (1 - f_frac_y)); float f_weight_10 = (f_alpha * f_frac_x * (1 - f_frac_y)); float f_weight_01 = (f_alpha * (1 - f_frac_x) * f_frac_y); float f_weight_11 = (f_alpha * f_frac_x * f_frac_y); if(x >= 0 && x < n_width && y >= 0 && y < n_height) AlphaBlend_Float(p_buffer[x + n_width * y], 1, f_weight_00); if(x + 1 >= 0 && x + 1 < n_width && y >= 0 && y < n_height) AlphaBlend_Float(p_buffer[(x + 1) + n_width * y], 1, f_weight_10); if(x >= 0 && x < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_Float(p_buffer[x + n_width * (y + 1)], 1, f_weight_01); if(x + 1 >= 0 && x + 1 < n_width && y + 1 >= 0 && y + 1 < n_height) AlphaBlend_Float(p_buffer[(x + 1) + n_width * (y + 1)], 1, f_weight_11); } bool CDebug::Dump_SparseMatrix_Subsample_AA(const char *p_s_filename, const cs *A, const cs *A_prev /*= 0*/, size_t n_max_bitmap_size /*= 640*/, bool b_symmetric /*= false*/) { _ASSERTE(CS_CSC(A)); _ASSERTE(!A_prev || CS_CSC(A_prev)); // the matrices need to be in compressed column form const uint32_t n_background = 0x00ffffffU, n_nonzero = 0xff8080ffU, n_nonzero_new = 0xffff0000U, n_zero_new = 0xff00ff00U; // colors of the individual areas size_t m = (A_prev)? std::max(A->m, A_prev->m) : A->m; size_t n = (A_prev)? std::max(A->n, A_prev->n) : A->n; size_t mb = m, nb = n; double f_scale = double(n_max_bitmap_size) / std::max(m, n); if(f_scale < 1) { mb = std::max(size_t(1), size_t(m * f_scale)); nb = std::max(size_t(1), size_t(n * f_scale)); } else f_scale = 1; // scale the bitmap down if needed if(mb == SIZE_MAX || nb == SIZE_MAX || mb > INT_MAX || nb > INT_MAX || uint64_t(mb) * nb > INT_MAX) return false; TBmp *p_bitmap; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(mb), int(nb)))) // transposed return false; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if(!(p_bitmap = TBmp::p_Alloc(int(nb), int(mb)))) return false; #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS // t_odo - dont use p_bitmap->PutPixel_AA(), the division of 0-255 by 256 diminishes // the color, yielding black pixels in cases of extreme overdraw. use a float // buffer or a fraction buffer instead if(A_prev) { p_bitmap->Clear(n_background); CSparseMatrixShapedIterator p_a_it(A, m, n); CSparseMatrixShapedIterator p_a_prev_it(A_prev, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it, ++ p_a_prev_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); _ASSERTE(n_row == p_a_prev_it.n_Row() && n_col == p_a_prev_it.n_Column()); // make sure it iterates to the right position bool b_is; double f_value = p_a_it.f_Get(b_is);// = *p_a_it; double f_prev_value = *p_a_prev_it; // read the value double f_value_thr = (fabs(f_value) < 1e-10)? 0 : f_value; double f_prev_value_thr = (fabs(f_prev_value) < 1e-10)? 0 : f_prev_value; // threshold if(b_is || f_value != 0 || f_prev_value != 0) { uint32_t n_fill_color = (f_value_thr != 0 && f_prev_value_thr != 0)? n_nonzero : (f_value_thr != 0 && f_prev_value_thr == 0)? n_nonzero_new : (f_value != 0 && f_prev_value != 0)? n_nonzero : n_zero_new; #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_y = float(n_col * f_scale); float f_x = float(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_x = float(n_col * f_scale); float f_y = float(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS PutPixel_AA_RGBA_HQ(p_bitmap, /*->PutPixel_AA(*/f_x, f_y, n_fill_color); //if(b_symmetric && f_x != f_y) // PutPixel_AA_RGBA_HQ(p_bitmap, /*->PutPixel_AA(*/f_y, f_x, n_fill_color); // t_odo - float rgba? some more elaborate reweighting? } // draw a dot into the bitmap } } if(b_symmetric) { uint32_t *p_buff = p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); uint32_t *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); uint32_t *p_lo = p_buff + (y + x * w); AlphaBlend_RGBA_HQ(*p_up, *p_lo, ((*p_lo >> 24) & 0xff) / 255.0f); // blend the two colors *p_lo = *p_up; // duplicate the result in the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices } else { _ASSERTE(sizeof(float) == sizeof(uint32_t)); std::fill((float*)p_bitmap->p_buffer, ((float*)p_bitmap->p_buffer) + nb * mb, .0f); // use as a float buffer /*CSparseMatrixShapedIterator p_a_it(A, m, n); for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_row = 0; n_row < m; ++ n_row, ++ p_a_it) { _ASSERTE(n_row == p_a_it.n_Row() && n_col == p_a_it.n_Column()); // make sure it iterates to the right position*/ #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS #ifdef BITMAP_SUBSAMPLE_DUMP_PARALLELIZE if(n > 16 && n < INT_MAX && A->p[n] >= 10000) { size_t n_half_stripe_num = nb / 8 - 1; // want four-pixel stripes with at least four pixel clearance (the blend will overflow up to two pixels - one on the left, one on the right from each stripe), want the last one to be wider than the others _ASSERTE(n_half_stripe_num < INT_MAX); const int _n_half_stripe_num = int(n_half_stripe_num); for(int n_pass = 0; n_pass < 2; ++ n_pass) { // draw even stripes in one pass, odd stripes in the next, this guarantees that two threads never blend over each other's area #pragma omp parallel for schedule(dynamic, 1) for(int n_stripe = 0; n_stripe < _n_half_stripe_num; ++ n_stripe) { // each thread processes a single stripe size_t n_stripe_b = (n / n_half_stripe_num) * n_stripe; size_t n_stripe_e = (n_stripe + 1 == _n_half_stripe_num)? n : n_stripe_b + n / n_half_stripe_num; _ASSERTE(n_stripe_e >= n_stripe_b + 8); if(n_pass) n_stripe_b = (n_stripe_b + n_stripe_e) / 2; else n_stripe_e = (n_stripe_b + n_stripe_e) / 2; _ASSERTE(n_stripe_e >= n_stripe_b + 2); // begin and end of a stripe for(size_t n_col = n_stripe_b; n_col < n_stripe_e; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; double f_value = (A->x)? A->x[n_p0] : 1; // read the value if(f_value != 0) PutPixel_AA_Float(p_bitmap, float(n_row * f_scale), float(n_col * f_scale)); // draw a dot into the bitmap } } } // implicit thread synchronization here } } else #endif // BITMAP_SUBSAMPLE_DUMP_PARALLELIZE { for(size_t n_col = 0; n_col < n; ++ n_col) { for(size_t n_p0 = A->p[n_col], n_p1 = A->p[n_col + 1]; n_p0 != n_p1; ++ n_p0) { size_t n_row = A->i[n_p0]; const double f_one = 1, *p_a_it = (A->x)? A->x + n_p0 : &f_one; #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS { CSparseMatrixIterator p_a_it(A); // can use the simple iterator here for(; p_a_it.n_Column() < n; ++ p_a_it) { size_t n_col = p_a_it.n_Column(); size_t n_row = p_a_it.n_Row(); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS double f_value = *p_a_it; // read the value if(f_value != 0) { #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_y = float(n_col * f_scale); float f_x = float(n_row * f_scale); // transposed #else // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS float f_x = float(n_col * f_scale); float f_y = float(n_row * f_scale); #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS PutPixel_AA_Float(p_bitmap, /*->PutPixel_AA(*/f_x, f_y/*, n_nonzero*/); //if(b_symmetric && f_x != f_y) // PutPixel_AA_Float(p_bitmap, /*->PutPixel_AA(*/f_y, f_x/*, n_nonzero*/); } // draw a square into the bitmap } } } // alpha = 0 // alpha = 0 + a1 * (1 - 0) = a1 // alpha = a1 + a2 * (1 - a1) = a1 + a2 - a1a2 // // alpha = 0 // alpha = 0 + a2 * (1 - 0) = a2 // alpha = a2 + a1 * (1 - a2) = a2 + a1 - a1a2 // the order of blending does not make a difference if(b_symmetric) { float *p_buff = (float*)p_bitmap->p_buffer; for(size_t x = 0, w = p_bitmap->n_width, h = p_bitmap->n_height, s = std::min(w, h); x < s; ++ x) { for(size_t y = 0; y < x; ++ y) { // only the upper triangle _ASSERTE(x < w && y < h); float *p_up = p_buff + (x + w * y); _ASSERTE(y < w && x < h); float *p_lo = p_buff + (y + x * w); AlphaBlend_Float(*p_up, 1, *p_lo); // blend the two alphas *p_lo = *p_up; // duplicate the result in the other triangle as well } } } // if symmetric, transpose the raster to save half the time on very large matrices for(float *p_buffer = (float*)p_bitmap->p_buffer, *p_end = p_buffer + nb * mb; p_buffer != p_end; ++ p_buffer) { float f_alpha = *p_buffer; int n_alpha = std::min(255, std::max(0, int(255 * f_alpha))); *(uint32_t*)p_buffer = TBmp::n_Modulate(n_background, 255 - n_alpha) + TBmp::n_Modulate(n_nonzero, n_alpha); // integer blend should be enough now, only once per pixel } // convert float buffer to RGBA } // iterate the matrix, draw small tiles #ifdef BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS if((m != n || !b_symmetric) && !p_bitmap->Transpose()) { p_bitmap->Delete(); return false; } #endif // BITMAP_SUBSAMPLE_DUMP_ROW_MAJOR_ACCESS bool b_result = CTgaCodec::Save_TGA(p_s_filename, *p_bitmap, false); p_bitmap->Delete(); return b_result; } void CDebug::Print_SparseMatrix(const cs *A, const char *p_s_label /*= 0*/) { if(p_s_label) printf("matrix \'%s\' = ", p_s_label); csi m, n, nzmax, /*nz,*/ *Ap, *Ai; double *Ax; if(!A) { printf("(null)\n"); return; } cs *Ac = 0; if(CS_TRIPLET(A) && !(Ac = cs_compress(A))) { printf("[not enough memory]\n"); return; } cs *At; if(!(At = cs_transpose((Ac)? Ac : A, 1))) { if(Ac) cs_spfree(Ac); printf("[not enough memory]\n"); return; } m = At->m; n = At->n; Ap = At->p; Ai = At->i; Ax = At->x; nzmax = At->nzmax; //nz = At->nz; // unused _ASSERTE(CS_CSC(At)); { _ASSERTE(n <= INT_MAX); _ASSERTE(m <= INT_MAX); _ASSERTE(nzmax <= INT_MAX); _ASSERTE(Ap[n] <= INT_MAX); printf("%d-by-%d, nzmax: %d nnz: %d, 1-norm: %g\n", int(n), int(m), int(nzmax), int(Ap[n]), cs_norm(A)); for(csi j = 0; j < n; ++ j) { printf(" row %d\n", int(j)); int x = 0; for(csi p = Ap[j]; p < Ap[j + 1]; ++ p, ++ x) { csi n_cur_x = Ai[p]; for(; x < n_cur_x; ++ x) printf(" %f, ", .0f); printf("%s%f%s", (Ax && Ax[p] < 0)? "" : " ", (Ax)? Ax[p] : 1, (n_cur_x + 1 == m)? "\n" : ", "); } for(; x < m; ++ x) printf(" %f%s", .0f, (x + 1 == m)? "\n" : ", "); } } cs_spfree(At); if(Ac) cs_spfree(Ac); } void CDebug::Print_SparseMatrix_in_MatlabFormat(const cs *A, const char *p_s_label /*= 0*/) { if(p_s_label) printf("matrix \'%s\' = ", p_s_label); csi m, n, /*nzmax, nz,*/ *Ap, *Ai; double *Ax; if(!A) { printf("(null)\n"); return; } cs *Ac = 0; if(CS_TRIPLET(A) && !(Ac = cs_compress(A))) { printf("[not enough memory]\n"); return; } cs *At; if(!(At = cs_transpose((Ac)? Ac : A, 1))) { if(Ac) cs_spfree(Ac); printf("[not enough memory]\n"); return; } m = At->m; n = At->n; Ap = At->p; Ai = At->i; Ax = At->x; //nzmax = At->nzmax; nz = At->nz; _ASSERTE(CS_CSC(At)); { printf("["); for(csi j = 0; j < n; ++ j) { csi x = 0; for(csi p = Ap[j]; p < Ap[j + 1]; ++ p, ++ x) { csi n_cur_x = Ai[p]; for(; x < n_cur_x; ++ x) printf("%f ", .0f); printf("%f%s", (Ax)? Ax[p] : 1, (n_cur_x + 1 == m)? ((j + 1 == n)? "" : "; ") : " "); } for(; x < m; ++ x) printf("%f%s", .0f, (x + 1 == m)? ((j + 1 == n)? "" : "; ") : " "); } printf("]\n"); } cs_spfree(At); if(Ac) cs_spfree(Ac); } bool CDebug::Print_SparseMatrix_in_MatlabFormat(FILE *p_fw, const cs *A, const char *p_s_prefix /*= 0*/, const char *p_s_suffix /*= ";\n"*/) { if(p_s_prefix) fprintf(p_fw, "%s", p_s_prefix); { fprintf(p_fw, "["); CSparseMatrixShapedIterator it(A); // @todo - replace this by a simple iterator as soon as it's tested for(size_t i = 0, m = A->m; i < m; ++ i) { // iterate rows in the outer loop for(size_t j = 0, n = A->n; j < n; ++ j, ++ it) { // iterate columns in the inner loop double f_value = *it; fprintf(p_fw, " %f", f_value); } if(i + 1 != m) fprintf(p_fw, "; "); } fprintf(p_fw, "]"); } // "to define a matrix, you can treat it like a column of row vectors" /* * >> A = [ 1 2 3; 3 4 5; 6 7 8] * * A = * * 1 2 3 * 3 4 5 * 6 7 8 */ if(p_s_suffix) fprintf(p_fw, "%s", p_s_suffix); return true; } bool CDebug::Print_SparseMatrix_in_MatlabFormat2(FILE *p_fw, const cs *A, const char *p_s_label, const char *p_s_prefix /*= 0*/, const char *p_s_suffix /*= 0*/) { if(p_s_prefix) fprintf(p_fw, "%s", p_s_prefix); fprintf(p_fw, "%s = sparse(" PRIdiff ", " PRIdiff ");\n", p_s_label, A->m, A->n); for(csi i = 0; i < A->n; ++ i) { for(csi p = A->p[i], e = A->p[i + 1]; p < e; ++ p) { csi j = A->i[p]; double x = (A->x)? A->x[p] : 1; if(x != 0) { // hard comparison here, try to avoid zero lines introduced by conversion from block matrices fprintf(p_fw, (fabs(x) > 1)? "%s(" PRIdiff ", " PRIdiff ") = %f;\n" : "%s(" PRIdiff ", " PRIdiff ") = %g;\n", p_s_label, j + 1, i + 1, x); } } } // to make sparse unit matrix, one writes: /* * >> A = sparse(2, 2); * >> A(1, 1) = 1 * >> A(2, 2) = 1 * * A = * (1, 1) 1 * (2, 2) 1 */ if(p_s_suffix) fprintf(p_fw, "%s", p_s_suffix); return true; } void CDebug::Print_DenseVector(const double *b, size_t n_vector_length, const char *p_s_label /*= 0*/) { //_ASSERTE(n_vector_length > 0); // doesn't work for empties double f_min_abs = (n_vector_length)? fabs(b[0]) : 0; for(size_t i = 1; i < n_vector_length; ++ i) f_min_abs = (fabs(b[i]) > 0 && (!f_min_abs || f_min_abs > fabs(b[i])))? fabs(b[i]) : f_min_abs; int n_log10 = (f_min_abs > 0)? int(ceil(log(f_min_abs) / log(10.0))) : 0; // calculate log10 to display the smallest nonzero value as 0 to 1 number if(n_log10 < -1) n_log10 += 2; else if(n_log10 < 0) ++ n_log10; // it's ok to have two first places 0 (in matlab it is, apparently) double f_scale = pow(10.0, -n_log10); // calculatze scale if(p_s_label) printf("%s = ", p_s_label); if(n_vector_length) { printf("vec(" PRIsize ") = 1e%+d * [%.4f", n_vector_length, n_log10, f_scale * b[0]); for(size_t i = 1; i < n_vector_length; ++ i) printf(", %.4f", f_scale * b[i]); printf("]\n"); } else printf("[ ]\n"); // print with scale } void CDebug::Print_DenseVector_in_MatlabFormat(FILE *p_fw, const double *b, size_t n_vector_length, const char *p_s_prefix /*= 0*/, const char *p_s_suffix /*= ";\n"*/) { //_ASSERTE(n_vector_length > 0); // doesn't work for empties double f_min_abs = (n_vector_length)? fabs(b[0]) : 0; for(size_t i = 1; i < n_vector_length; ++ i) f_min_abs = (fabs(b[i]) > 0 && (!f_min_abs || f_min_abs > fabs(b[i])))? fabs(b[i]) : f_min_abs; int n_log10 = (f_min_abs > 0)? int(ceil(log(f_min_abs) / log(10.0))) : 0; // calculate log10 to display the smallest nonzero value as 0 to 1 number if(n_log10 < -1) n_log10 += 2; else if(n_log10 < 0) ++ n_log10; // it's ok to have two first places 0 (in matlab it is, apparently) double f_scale = pow(10.0, -n_log10); // calculatze scale if(p_s_prefix) fprintf(p_fw, "%s", p_s_prefix); if(n_vector_length) { if(fabs(f_scale * b[0]) > 1) fprintf(p_fw, "1e%+d * [%.15f", n_log10, f_scale * b[0]); else fprintf(p_fw, "1e%+d * [%.15g", n_log10, f_scale * b[0]); for(size_t i = 1; i < n_vector_length; ++ i) fprintf(p_fw, (fabs(f_scale * b[i]) > 1)? " %.15f" : " %.15g", f_scale * b[i]); fprintf(p_fw, "]"); } else fprintf(p_fw, "[ ]"); if(p_s_suffix) fprintf(p_fw, "%s", p_s_suffix); // print with scale } #if (defined(_M_X64) || defined(_M_AMD64) || defined(_M_IA64) || defined(__x86_64) || defined(__amd64) || defined(__ia64) || \ defined(_M_I86) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) || defined(__IA32__) || defined(__i386)) && \ 1 // in case the below include is not found or _mm_clflush() or _mm_mfence() are undefined, switch to 0. this will only affect some debugging / performance profiling functionality #include <emmintrin.h> void CDebug::Evict_Buffer(const void *p_begin, size_t n_size) { if(!p_begin) return; for(intptr_t n_addr = intptr_t(p_begin), n_end = intptr_t(p_begin) + n_size; n_addr != n_end; ++ n_addr) { _mm_clflush((const void*)n_addr); // flush the corresponding cache line } _mm_mfence(); // memory fence; force all operations to complete before going on } #else // (x86 || x64) && 1 //#pragma message "warning: emmintrin.h likely not present, evict semantics will not be available" void CDebug::Evict_Buffer(const void *UNUSED(p_begin), size_t UNUSED(n_size)) { // we're not on x86, can't use _mm_*() intrinsics // this is needed if building e.g. for ARM } #endif // (x86 || x64) && 1 void CDebug::Evict(const cs *p_mat) { if(CS_TRIPLET(p_mat)) Evict_Buffer(p_mat->p, sizeof(csi) * p_mat->nzmax); else Evict_Buffer(p_mat->p, sizeof(csi) * (p_mat->n + 1)); Evict_Buffer(p_mat->i, sizeof(csi) * p_mat->nzmax); Evict_Buffer(p_mat->x, sizeof(double) * p_mat->nzmax); // evict the internal buffers Evict_Buffer(p_mat, sizeof(cs)); // evict the structure } void CDebug::Evict(const CUberBlockMatrix &r_mat) { CUBM_EvictUtil<blockmatrix_detail::CUberBlockMatrix_Base>::EvictMembers(r_mat); // evict the internal vectors Evict_Buffer(&r_mat, sizeof(r_mat)); // evict the structure } void CDebug::Swamp_Cache(size_t n_buffer_size /*= 100 * 1048576*/) // throw(std::bad_alloc) { std::vector<uint8_t> buffer(n_buffer_size); for(size_t i = 0; i < n_buffer_size; ++ i) buffer[i] = uint8_t(n_SetBit_Num(i)); // alloc a large buffer and fill it using nontrivial // ops, so that cache would not be bypassed by DMA as // e.g. for memset or memcpy } /* * === ~CDebug === */ /* * === CSparseMatrixMemInfo === */ uint64_t CSparseMatrixMemInfo::n_Allocation_Size(const cs *p_matrix) { if(!p_matrix) return 0; if(p_matrix->nz <= 0) { return sizeof(cs) + (p_matrix->n + 1) * sizeof(csi) + p_matrix->p[p_matrix->n] * ((p_matrix->x)? sizeof(double) + sizeof(csi) : sizeof(csi)); } else { return sizeof(cs) + p_matrix->nzmax * ((p_matrix->x)? sizeof(double) + 2 * sizeof(csi) : 2 * sizeof(csi)); } } bool CSparseMatrixMemInfo::Peek_MatrixMarket_Header(const char *p_s_filename, CSparseMatrixMemInfo::TMMHeader &r_t_header) { bool b_symmetric = false, b_binary = false; bool b_had_specifier = false; bool b_had_header = false; size_t n_rows, n_cols, n_nnz = -1, n_read_nnz = 0, n_full_nnz = 0; FILE *p_fr; if(!(p_fr = fopen(p_s_filename, "r"))) return false; // open the matrix market file try { std::string s_line; while(!feof(p_fr)) { if(!CParserBase::ReadLine(s_line, p_fr)) { fclose(p_fr); return false; } // read a single line size_t n_pos; if(!b_had_specifier && (n_pos = s_line.find("%%MatrixMarket")) != std::string::npos) { s_line.erase(0, n_pos + strlen("%%MatrixMarket")); // get rid of header b_binary = s_line.find("pattern") != std::string::npos; if(s_line.find("matrix") == std::string::npos || s_line.find("coordinate") == std::string::npos || (s_line.find("real") == std::string::npos && s_line.find("integer") == std::string::npos && !b_binary)) // integer matrices are not real, but have values and are loadable return false; // must be matrix coordinate real if(s_line.find("general") != std::string::npos) b_symmetric = false; else if(s_line.find("symmetric") != std::string::npos) b_symmetric = true; else { b_symmetric = false; /*//fclose(p_fr); return false;*/ // or assume general } // either general or symmetric b_had_specifier = true; continue; } if((n_pos = s_line.find('%')) != std::string::npos) s_line.erase(n_pos); CParserBase::TrimSpace(s_line); if(s_line.empty()) continue; // trim comments, skip empty lines if(!b_had_header) { if(!b_had_specifier) { fclose(p_fr); return false; } // specifier must come before header #if defined(_MSC_VER) && !defined(__MWERKS__) && _MSC_VER >= 1400 if(sscanf_s(s_line.c_str(), PRIsize " " PRIsize " " PRIsize, &n_rows, &n_cols, &n_nnz) != 3) { #else //_MSC_VER && !__MWERKS__ && _MSC_VER >= 1400 if(sscanf(s_line.c_str(), PRIsize " " PRIsize " " PRIsize, &n_rows, &n_cols, &n_nnz) != 3) { #endif //_MSC_VER && !__MWERKS__ && _MSC_VER >= 1400 fclose(p_fr); return false; } // read header if(n_rows <= SIZE_MAX / std::max(size_t(1), n_cols) && n_nnz > n_rows * n_cols) { fclose(p_fr); return false; } // sanity check (may also fail on big matrices) b_had_header = true; break; } } if(!b_had_header) { fclose(p_fr); return false; } if(b_symmetric) { _ASSERTE(b_had_header && b_had_specifier); while(!feof(p_fr)) { // only elements follow if(!CParserBase::ReadLine(s_line, p_fr)) { fclose(p_fr); return false; } // read a single line CParserBase::TrimSpace(s_line); if(s_line.empty() || s_line[0] == '%') // only handles comments at the beginning of the line; comments at the end will simply be ignored continue; // trim comments, skip empty lines double f_value; size_t n_rowi, n_coli; do { const char *b = s_line.c_str(); _ASSERTE(*b && !isspace(uint8_t(*b))); // not empty and not space for(n_rowi = 0; *b && isdigit(uint8_t(*b)); ++ b) // ignores overflows n_rowi = 10 * n_rowi + *b - '0'; // parse the first number if(!*b || !isspace(uint8_t(*b))) { fclose(p_fr); return false; } ++ b; // skip the first space while(*b && isspace(uint8_t(*b))) ++ b; if(!*b || !isdigit(uint8_t(*b))) { fclose(p_fr); return false; } // skip space to the second number for(n_coli = 0; *b && isdigit(uint8_t(*b)); ++ b) // ignores overflows n_coli = 10 * n_coli + *b - '0'; // parse the second number if(!*b) { f_value = 1; // a binary matrix? break; } if(!isspace(uint8_t(*b))) { fclose(p_fr); return false; // bad character } ++ b; // skip the first space while(*b && isspace(uint8_t(*b))) ++ b; _ASSERTE(*b); // there must be something since the string sure does not end with space (called TrimSpace() above) // skip space to the value f_value = 1;//atof(b); // don't care about the values here } while(0); // read a triplet -- n_rowi; -- n_coli; // indices are 1-based, i.e. a(1,1) is the first element if(n_rowi >= n_rows || n_coli >= n_cols || n_read_nnz >= n_nnz) { fclose(p_fr); return false; } // make sure it figures _ASSERTE(b_symmetric); n_full_nnz += (n_rowi != n_coli)? 2 : 1; ++ n_read_nnz; // append the nonzero } // read the file line by line if(ferror(p_fr) || !b_had_header || n_read_nnz != n_nnz) { fclose(p_fr); return false; } // make sure no i/o errors occurred, and that the entire matrix was read } // in case the matrix is symmetric, need to read the indices to see which ones are at the // diagonal; does not actually store them, just goes through them quickly; the floats are // not parsed fclose(p_fr); } catch(std::bad_alloc&) { fclose(p_fr); return false; } r_t_header.b_binary = b_binary; r_t_header.b_symmetric = b_symmetric; r_t_header.n_nnz = n_nnz; r_t_header.n_rows = n_rows; r_t_header.n_cols = n_cols; if(!b_symmetric) r_t_header.n_full_nnz = n_nnz; else r_t_header.n_full_nnz = n_full_nnz; return true; } uint64_t CSparseMatrixMemInfo::n_Peek_MatrixMarket_SizeInMemory(const char *p_s_filename) { TMMHeader t_header; if(!Peek_MatrixMarket_Header(p_s_filename, t_header)) return uint64_t(-1); cs spmat = {0, 0, 0, 0, 0, 0, 0}; // put all to avoid -Wmissing-field-initializers return t_header.n_AllocationSize_CSC(sizeof(*spmat.p), sizeof(*spmat.x)); } /* * === ~CSparseMatrixMemInfo === */
36.339921
247
0.619335
meitiever
44feed8c45f1dcf885a76fabaf3620aecb80c7bc
4,294
hpp
C++
plugin/augmented_reality_plugin_wikitude/ios/Frameworks/WikitudeSDK.xcframework/ios-x86_64-simulator/WikitudeSDK.framework/Headers/Plane.hpp
Wikitude/wikitude-flutter-plugin-examples
8ed5e18e8f32e7570328e89df5c69000fda13153
[ "Apache-2.0" ]
9
2019-12-22T09:03:13.000Z
2021-08-20T00:46:05.000Z
plugin/augmented_reality_plugin_wikitude/ios/Frameworks/WikitudeSDK.framework/Headers/Plane.hpp
Wikitude/wikitude-flutter-plugin-examples
8ed5e18e8f32e7570328e89df5c69000fda13153
[ "Apache-2.0" ]
11
2019-09-03T15:45:44.000Z
2022-03-30T11:20:44.000Z
plugin/augmented_reality_plugin_wikitude/ios/Frameworks/WikitudeSDK.xcframework/ios-arm64/WikitudeSDK.framework/Headers/Plane.hpp
Wikitude/wikitude-flutter-plugin-examples
8ed5e18e8f32e7570328e89df5c69000fda13153
[ "Apache-2.0" ]
3
2021-09-01T13:02:11.000Z
2021-11-26T12:02:26.000Z
// // Plane.hpp // WikitudeUniversalSDK // // Created by Alexandru Florea on 01.08.18. // Copyright © 2018 Wikitude. All rights reserved. // #ifndef Plane_hpp #define Plane_hpp #ifdef __cplusplus #include <vector> #include "PlaneType.hpp" #include "Geometry.hpp" #include "CompilerAttributes.hpp" namespace wikitude::sdk { /** @addtogroup InstantTracking * @{ */ /** @class Plane * @brief A class that represents a plane found by an instant tracker. */ class Matrix4; class Vector3; class WT_EXPORT_API Plane { public: virtual ~Plane() = default; /** @brief Gets the combined modelview matrix that should be applied to augmentations when rendering. * In cases where the orientation of the rendering surface and orientation of the camera do not match, and a correct cameraToRenderSurfaceRotation is passed to the SDK, * this matrix will also be rotate to account for the mismatch. * * For example, on mobile devices running in portrait mode, that have a camera sensor is landscape right position, the cameraToRenderSurfaceRotation should be 90 degrees. * The matrix will be rotated by 90 degrees around the Z axis. * * @return The matrix that should be applied to the target augmentation when rendering. */ virtual const Matrix4& getMatrix() const = 0; /** @brief Gets the transformation from local space to world space. * When the CameraFrame doesn't contain a valid device pose, world space and camera space are the same. * When combined with the viewMatrix, this results in the modelViewMatrix that should be applied to the target augmentation when rendering. * * @return The matrix that transforms the target from local space to world space. */ virtual const Matrix4& getModelMatrix() const = 0; /** @brief Gets the transformation from world space to camera space. * When the CameraFrame doesn't contain a valid device pose, world space and camera space are the same. * When combined with the modelMatrix, this results in the modelViewMatrix that should be applied to the target augmentation when rendering. * * @return The matrix that transform the target from world space to camera space. */ virtual const Matrix4& getViewMatrix() const = 0; /** @brief Gets the unique id of the Plane. * * @return The unique id of the plane. */ virtual long getUniqueId() const = 0; /** @brief Gets the type for this plane. * * Please refer to the PlaneType documentation for more details. * * @return The plane type. */ virtual PlaneType getPlaneType() const = 0; /** @brief Returns the confidence level for the plane. * * The confidence level is mapped between 0 and 1. * * @return The confidence level for the plane. */ virtual float getConfidence() const = 0; /** @brief Gets the extents of the plane in the X axis. * * @return The extents of the plane in the X axis. */ virtual const Extent<float>& getExtentX() const = 0; /** @brief Gets the extents of the plane in the Y axis. * * @return The extents of the plane in the Y axis. */ virtual const Extent<float>& getExtentY() const = 0; /** @brief Gets the convex hull of the plane. * * The convex hull can be used to render the plane mesh as a triangle fan. * All the points are relative to the plane coordinate system and can also be used as texture coordinates. * * @return The convex hull of the plane. */ virtual const std::vector<Point<float>>& getConvexHull() const = 0; }; } #endif /* __cplusplus */ #endif /* Plane_hpp */
38.684685
183
0.591057
Wikitude
44ff9431bee60cd6197bd404e35abce7d38e993a
15,303
cpp
C++
cc/vision/vision.cpp
PEQUI-VSSS/VSSS-EMC
0c2b61e308f754ca91df52e46ba48828168223df
[ "MIT" ]
9
2017-07-18T12:37:09.000Z
2018-05-01T14:41:48.000Z
cc/vision/vision.cpp
PEQUI-MEC/VSSS-EMC
0c2b61e308f754ca91df52e46ba48828168223df
[ "MIT" ]
31
2018-07-31T13:10:01.000Z
2022-03-26T16:00:25.000Z
cc/vision/vision.cpp
PEQUI-MEC/VSSS-EMC
0c2b61e308f754ca91df52e46ba48828168223df
[ "MIT" ]
2
2017-10-01T16:09:20.000Z
2018-05-01T17:39:59.000Z
#include <Geometry/Geometry.h> #include <Strategy2/Field.h> #include "vision.hpp" using namespace vision; std::map<unsigned int, Vision::RecognizedTag> Vision::run(cv::Mat raw_frame) { in_frame = raw_frame.clone(); preProcessing(); findTags(); //findElements(); return pick_a_tag(); } void Vision::preProcessing() { cv::cvtColor(in_frame, lab_frame, cv::COLOR_RGB2Lab); } void Vision::findTags() { for (unsigned int color = 0; color < MAX_COLORS; color++) { threshold_threads.add_thread(new boost::thread(&Vision::segmentAndSearch, this, color)); } threshold_threads.join_all(); } void Vision::segmentAndSearch(const unsigned long color) { cv::Mat frame = lab_frame.clone(); inRange(frame, cv::Scalar(cieL[color][Limit::Min], cieA[color][Limit::Min], cieB[color][Limit::Min]), cv::Scalar(cieL[color][Limit::Max], cieA[color][Limit::Max], cieB[color][Limit::Max]), threshold_frame.at(color)); posProcessing(color); searchTags(color); } void Vision::posProcessing(const unsigned long color) { int morphShape; cv::Size size; if (color == Color::Ball) { morphShape = cv::MORPH_ELLIPSE; size = cv::Size(15, 15); } else { morphShape = cv::MORPH_RECT; size = cv::Size(3, 3); } cv::Mat erodeElement = cv::getStructuringElement(morphShape, size); cv::Mat dilateElement = cv::getStructuringElement(morphShape, size); if (blur[color] > 0) { cv::medianBlur(threshold_frame.at(color), threshold_frame.at(color), blur[color]); } cv::erode(threshold_frame.at(color), threshold_frame.at(color), erodeElement, cv::Point(-1, -1), erode[color]); cv::dilate(threshold_frame.at(color), threshold_frame.at(color), dilateElement, cv::Point(-1, -1), dilate[color]); } void Vision::searchTags(const unsigned long color) { std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; tags.at(color).clear(); cv::findContours(threshold_frame.at(color), contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_NONE); for (const auto &contour : contours) { double area = contourArea(contour); if (area >= areaMin[color]) { cv::Moments moment = moments((cv::Mat) contour); auto moment_x = static_cast<int>(moment.m10 / area); auto moment_y = static_cast<int>(moment.m01 / area); // seta as linhas para as tags principais do pick-a-tag if (color == Color::Main) { tags.at(color).emplace_back(cv::Point(moment_x, moment_y), area); // tem que ter jogado a tag no vetor antes de mexer nos valores dela cv::Vec4f line; cv::fitLine(cv::Mat(contour), line, 2, 0, 0.01, 0.01); unsigned long tagsInVec = tags.at(color).size() - 1; tags.at(color).at(tagsInVec).setLine(line); } else if (color == Color::Adv) { if (tags.at(color).size() >= 3) { // pega o menor índice unsigned long smaller = 0; for (unsigned long j = 1; j < 3; j++) { if (tags.at(color).at(j).area < tags.at(color).at(smaller).area) smaller = j; } if (smaller < tags.at(color).size() && area > tags.at(color).at(smaller).area) tags.at(color).at(smaller) = Tag(cv::Point(moment_x, moment_y), area); } else { tags.at(color).emplace_back(cv::Point(moment_x, moment_y), area); } } else { tags.at(color).emplace_back(cv::Point(moment_x, moment_y), area); } } } } /// <summary> /// Seleciona um conjunto de tags para representar cada robô /// </summary> /// <description> /// P.S.: Aqui eu uso a flag 'isOdd' para representar quando um robô tem as duas bolas laterais. /// </description> std::map<unsigned int, Vision::RecognizedTag> Vision::pick_a_tag() { std::map<unsigned int, RecognizedTag> found_tags; advRobots.clear(); // OUR ROBOTS for (unsigned int i = 0; i < tags.at(Color::Main).size() && i < 3; i++) { std::vector<Tag> secondary_tags; Tag main_tag = tags.at(Color::Main).at(i); // Posição do robô cv::Point position = main_tag.position; // Cálculo da orientação de acordo com os pontos rear e front double orientation = atan2((main_tag.frontPoint.y - position.y) * field::field_height / height, (main_tag.frontPoint.x - position.x) * field::field_width / width); // Para cada tag principal, verifica quais são as secundárias correspondentes for (Tag &secondary_tag : tags.at(Color::Green)) { // Altera a orientação caso esteja errada int tag_side = in_sphere(secondary_tag.position, main_tag, orientation); if (tag_side != 0) { secondary_tag.left = tag_side > 0; // calculos feitos, joga tag no vetor secondary_tags.push_back(secondary_tag); } } if (secondary_tags.size() > 1) { // tag 3 tem duas tags secundárias RecognizedTag tag = {position, orientation, main_tag.frontPoint, main_tag.rearPoint}; found_tags.insert(std::make_pair(2, tag)); } else if (!secondary_tags.empty()) { RecognizedTag tag = {position, orientation, main_tag.frontPoint, main_tag.rearPoint}; if (secondary_tags[0].left) { found_tags.insert(std::make_pair(0, tag)); } else { found_tags.insert(std::make_pair(1, tag)); } } } // OUR ROBOTS // ADV ROBOTS for (unsigned long i = 0; i < MAX_ADV; i++) { if (i < tags.at(Color::Adv).size()) advRobots.push_back(tags.at(Color::Adv).at(i).position); } // BALL POSITION if (!tags[Color::Ball].empty()) { ball.position = tags.at(Color::Ball).at(0).position; ball.isFound = true; } else { // É importante que a posição da bola permaneça sendo a última encontrada // para que os robôs funcionem corretamente em caso de oclusão da bola na imagem // portanto, a posição da bola não deve ser alterada aqui ball.isFound = false; } return found_tags; } /// <summary> /// Verifica se uma tag secundária pertence a esta pick-a e calcula seu delta. /// </summary> /// <param name="position">Posição central do robô</param> /// <param name="secondary">O suposto ponto que marca uma bola da tag</param> /// <param name="orientation">A orientação do robô</param> /// <returns> /// 0, se esta não é uma tag secundária; /// -1, caso a secundária esteja à esquerda; /// 1, caso a secundária esteja à direita /// </returns> int Vision::in_sphere(cv::Point secondary, Tag &main_tag, double &orientation) { // se esta secundária faz parte do robô if (calcDistance(main_tag.position, secondary) <= ROBOT_RADIUS) { if (calcDistance(main_tag.frontPoint, secondary) < calcDistance(main_tag.rearPoint, secondary)) { main_tag.switchPoints(); // calcula a orientação do robô orientation = atan2((main_tag.frontPoint.y - main_tag.position.y) * field::field_height / height, (main_tag.frontPoint.x - main_tag.position.x) * field::field_width / width); } double secSide = atan2((secondary.y - main_tag.position.y) * field::field_height / height, (secondary.x - main_tag.position.x) * field::field_width / width); // Cálculo do ângulo de orientação para diferenciar robôs de mesma cor return (atan2(sin(secSide - orientation + 3.1415), cos(secSide - orientation + 3.1415))) > 0 ? 1 : -1; } return 0; } double Vision::calcDistance(const cv::Point p1, const cv::Point p2) const { return sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2)); } void Vision::switchMainWithAdv() { int tmp; for (int i = Limit::Min; i <= Limit::Max; i++) { tmp = cieL[Color::Main][i]; cieL[Color::Main][i] = cieL[Color::Adv][i]; cieL[Color::Adv][i] = tmp; tmp = cieA[Color::Main][i]; cieA[Color::Main][i] = cieA[Color::Adv][i]; cieA[Color::Adv][i] = tmp; tmp = cieB[Color::Main][i]; cieB[Color::Main][i] = cieB[Color::Adv][i]; cieB[Color::Adv][i] = tmp; } tmp = areaMin[Color::Main]; areaMin[Color::Main] = areaMin[Color::Adv]; areaMin[Color::Adv] = tmp; tmp = erode[Color::Main]; erode[Color::Main] = erode[Color::Adv]; erode[Color::Adv] = tmp; tmp = dilate[Color::Main]; dilate[Color::Main] = dilate[Color::Adv]; dilate[Color::Adv] = tmp; tmp = blur[Color::Main]; blur[Color::Main] = blur[Color::Adv]; blur[Color::Adv] = tmp; } cv::Mat Vision::getSplitFrame() { cv::Mat horizontal[2], vertical[2]; for (unsigned long index = 0; index < 3; index++) { cv::cvtColor(threshold_frame.at(index), threshold_frame.at(index), cv::COLOR_GRAY2RGB); } cv::pyrDown(in_frame, vertical[0]); cv::pyrDown(threshold_frame.at(0), vertical[1]); cv::hconcat(vertical, 2, horizontal[0]); cv::pyrDown(threshold_frame.at(1), vertical[0]); cv::pyrDown(threshold_frame.at(2), vertical[1]); cv::hconcat(vertical, 2, horizontal[1]); cv::vconcat(horizontal, 2, splitFrame); return splitFrame; } void Vision::saveCamCalibFrame() { // cv::Mat temp = rawFrameCamcalib.clone(); cv::Mat temp = in_frame.clone(); savedCamCalibFrames.push_back(temp); std::string text = "CamCalib_" + std::to_string(getCamCalibFrames().size()); saveCameraCalibPicture(text, "media/pictures/camCalib/"); std::cout << "Saving picture " << std::endl; } void Vision::collectImagesForCalibration() { std::cout << "Collecting pictures " << std::endl; cv::String path("media/pictures/camCalib/*.png"); //select only png std::vector<cv::String> fn; std::vector<cv::Mat> data; try{ cv::glob(path, fn, true); // recurse for (auto &index : fn) { cv::Mat im = cv::imread(index); if (im.empty()) continue; //only proceed if sucsessful // you probably want to do some preprocessing savedCamCalibFrames.push_back(im); } std::cout << "Pictures collected: " << savedCamCalibFrames.size() << std::endl; cameraCalibration(); }catch (...){ std::cout << "An exception occurred. No images for calibration. \n"; } } void Vision::cameraCalibration() { std::vector<std::vector<cv::Point2f>> checkerBoardImageSpacePoints; std::vector<std::vector<cv::Point3f>> worldSpaceCornersPoints; getChessBoardCorners(savedCamCalibFrames, worldSpaceCornersPoints, checkerBoardImageSpacePoints); std::cout << "Image Space Points " << checkerBoardImageSpacePoints.size() << std::endl; std::cout << "world SpaceCorners Points " << worldSpaceCornersPoints.size() << std::endl; std::vector<cv::Mat> rVectors, tVectors; distanceCoeficents = cv::Mat::zeros(8, 1, CV_64F); int flag = 0; flag |= cv::CALIB_FIX_K4; flag |= cv::CALIB_FIX_K5; //root mean square (RMS) reprojection error and should be between 0.1 and 1.0 pixels in a good calibration. double rms = cv::calibrateCamera(worldSpaceCornersPoints, checkerBoardImageSpacePoints, in_frame.size(), cameraMatrix, distanceCoeficents, rVectors, tVectors, flag); savedCamCalibFrames.clear(); flag_cam_calibrated = true; std::cout << "Camera parameters matrix." << std::endl; std::cout << cameraMatrix << std::endl; std::cout << "Camera distortion coefficients" << std::endl; std::cout << distanceCoeficents << std::endl; std::cout << "RMS" << std::endl; std::cout << rms << std::endl; std::cout << "End of calibration" << std::endl; } void Vision::getChessBoardCorners(std::vector<cv::Mat> images, std::vector<std::vector<cv::Point3f>>& pts3d,std::vector<std::vector<cv::Point2f>>& pts2d) const { cv::TermCriteria termCriteria = cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 40, 0.001); cv::Mat grayFrame; //std::vector<std::vector<cv::Point2f>> allFoundCorners; for (auto &image : images) { std::vector<cv::Point2f> pointBuf; std::vector<cv::Point3f> corners; bool found = cv::findChessboardCorners(image, CHESSBOARD_DIMENSION, pointBuf, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE); for (int i = 0; i < CHESSBOARD_DIMENSION.height; i++) { for (int j = 0; j < CHESSBOARD_DIMENSION.width; ++j) { corners.emplace_back(j * CALIBRATION_SQUARE_DIMENSION, i * CALIBRATION_SQUARE_DIMENSION, 0.0f); } } if (found) { cv::cvtColor(image, grayFrame, cv::COLOR_RGB2GRAY); cv::cornerSubPix(grayFrame, pointBuf, cv::Size(5, 5), cv::Size(-1, -1), termCriteria); pts2d.push_back(pointBuf); pts3d.push_back(corners); } } } bool Vision::foundChessBoardCorners() const { std::vector<cv::Vec2f> foundPoints; cv::Mat temp; temp = in_frame.clone(); return cv::findChessboardCorners(temp, CHESSBOARD_DIMENSION, foundPoints, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE); } void Vision::saveCameraCalibPicture(const std::string in_name, const std::string directory) { cv::Mat frame = in_frame.clone(); std::string picName = directory + in_name + ".png"; cv::cvtColor(frame, frame, cv::COLOR_RGB2BGR); cv::imwrite(picName, frame); } cv::Mat Vision::getThreshold(const unsigned long index) { cv::cvtColor(threshold_frame.at(index), threshold_frame.at(index), cv::COLOR_GRAY2RGB); return threshold_frame.at(index); } void Vision::setFlagCamCalibrated(const bool value) { this->flag_cam_calibrated = value; } void Vision::popCamCalibFrames() { savedCamCalibFrames.pop_back(); } void Vision::setCIE_L(const unsigned long index0, const int index1, const int inValue) { if (index0 < MAX_COLORS && (index1 == Limit::Min || index1 == Limit::Max)) cieL[index0][index1] = inValue; else std::cout << "Vision:setCIE_L: could not set (invalid index)" << std::endl; } void Vision::setCIE_A(const unsigned long index0, const int index1, const int inValue) { if (index0 < MAX_COLORS && (index1 == Limit::Min || index1 == Limit::Max)) cieA[index0][index1] = inValue; else std::cout << "Vision:setCIE_A: could not set (invalid index)" << std::endl; } void Vision::setCIE_B(const unsigned long index0, const int index1, const int inValue) { if (index0 < MAX_COLORS && (index1 == Limit::Min || index1 == Limit::Max)) cieB[index0][index1] = inValue; else std::cout << "Vision:setCIE_B: could not set (invalid index)" << std::endl; } void Vision::setErode(const unsigned long index, const int inValue) { if (index < MAX_COLORS) erode[index] = inValue; else std::cout << "Vision:setErode: could not set (invalid index or convert type)" << std::endl; } void Vision::setDilate(const unsigned long index, const int inValue) { if (index < MAX_COLORS) dilate[index] = inValue; else std::cout << "Vision:setDilate: could not set (invalid index or convert type)" << std::endl; } void Vision::setBlur(const unsigned long index, int inValue) { if (index < MAX_COLORS) { if (inValue == 0 || inValue % 2 == 1) blur[index] = inValue; else blur[index] = inValue+1; } else { std::cout << "Vision:setBlur: could not set (invalid index or convert type)" << std::endl; } } void Vision::setAmin(const unsigned long index, const int inValue) { if (index < MAX_COLORS) areaMin[index] = inValue; else std::cout << "Vision:setAmin: could not set (invalid index or convert type)" << std::endl; } void Vision::setFrameSize(const int inWidth, const int inHeight) { if (inWidth >= 0) width = inWidth; if (inHeight >= 0) height = inHeight; } Vision::Vision(int w, int h) : width(w), height(h), threshold_frame(MAX_COLORS), tags(MAX_COLORS), cieL{{0, 255}, {0, 255}, {0, 255}, {0, 255}}, cieA{{0, 255}, {0, 255}, {0, 255}, {0, 255}}, cieB{{0, 255}, {0, 255}, {0, 255}, {0, 255}}, dilate{0, 0, 0, 0}, erode{0, 0, 0, 0}, blur{3, 3, 3, 3}, areaMin{50, 20, 30, 30} { } Vision::~Vision() = default;
33.632967
161
0.673071
PEQUI-VSSS
7800d16778bc873e2a6022ce7c163fe5bd3223cf
464
hh
C++
TrkFitter/TrkLineMaker.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkFitter/TrkLineMaker.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkFitter/TrkLineMaker.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: TrkLineMaker.hh 104 2010-01-15 12:13:14Z stroili $ // // Author(s): Gerhard Raven // //------------------------------------------------------------------------ #ifndef TRKLINEMAKER_HH #define TRKLINEMAKER_HH #include "TrkFitter/TrkSimpleMaker.hh" #include "TrkFitter/TrkLineRep.hh" typedef TrkSimpleMaker<TrkLineRep> TrkLineMaker; #endif
27.294118
76
0.506466
brownd1978
78019d43eaf3bd8f6b49eaf96e4ec72b9aa73015
4,238
cpp
C++
src/Base/View.cpp
geenux/choreonoid
25e534dd4dbf1ac890cdfe80b51add9c4f81e505
[ "MIT" ]
null
null
null
src/Base/View.cpp
geenux/choreonoid
25e534dd4dbf1ac890cdfe80b51add9c4f81e505
[ "MIT" ]
null
null
null
src/Base/View.cpp
geenux/choreonoid
25e534dd4dbf1ac890cdfe80b51add9c4f81e505
[ "MIT" ]
null
null
null
/** @author Shin'ichiro Nakaoka */ #include "View.h" #include "ViewArea.h" #include "ViewManager.h" #include "App.h" #include "AppConfig.h" #include <QLayout> #include <QKeyEvent> #include <QTabWidget> using namespace std; using namespace cnoid; View::View() { isActive_ = false; viewArea_ = 0; defaultLayoutArea_ = CENTER; isFontSizeZoomKeysEnabled = false; fontZoom = 0; } View::~View() { if(isActive_){ onDeactivated(); } if(viewArea_){ viewArea_->removeView(this); } View* focusView = lastFocusView(); if(this == focusView){ App::clearFocusView(); } } bool View::isActive() const { return isActive_; } void View::showEvent(QShowEvent* event) { if(!isActive_){ isActive_ = true; onActivated(); sigActivated_(); } } void View::hideEvent(QHideEvent* event) { if(isActive_){ isActive_ = false; onDeactivated(); sigDeactivated_(); } } /** Virtual function which is called when the view becomes visible on the main window. @note In the current implementation, this function may be continuously called two or three times when the perspective changes, and the number of calles does not necessarily corresponds to the number of 'onDeactivated()' calles. @todo improve the behavior written as note */ void View::onActivated() { } void View::onDeactivated() { if(isFontSizeZoomKeysEnabled){ AppConfig::archive()->openMapping(viewClass()->className())->write("fontZoom", fontZoom); } } void View::setName(const std::string& name) { setObjectName(name.c_str()); setWindowTitle(name.c_str()); } ViewClass* View::viewClass() const { return ViewManager::viewClass(typeid(*this)); } void View::bringToFront() { if(viewArea_){ QTabWidget* tab = 0; for(QWidget* widget = parentWidget(); widget; widget = widget->parentWidget()){ if(tab = dynamic_cast<QTabWidget*>(widget)){ tab->setCurrentWidget(this); } } } } void View::setDefaultLayoutArea(LayoutArea area) { defaultLayoutArea_ = area; } View::LayoutArea View::defaultLayoutArea() const { return defaultLayoutArea_; } void View::setLayout(QLayout* layout) { const int margin = 0; layout->setContentsMargins(margin, margin, margin, margin); QWidget::setLayout(layout); } QWidget* View::indicatorOnInfoBar() { return 0; } void View::enableFontSizeZoomKeys(bool on) { isFontSizeZoomKeysEnabled = on; if(on){ MappingPtr config = AppConfig::archive()->openMapping(viewClass()->className()); int storedZoom; if(config->read("fontZoom", storedZoom)){ zoomFontSize(storedZoom); } } } void View::keyPressEvent(QKeyEvent* event) { bool processed = false; if(isFontSizeZoomKeysEnabled){ if(event->modifiers() & Qt::ControlModifier){ switch(event->key()){ case Qt::Key_Plus: case Qt::Key_Semicolon: zoomFontSize(1); processed = true; break; case Qt::Key_Minus: zoomFontSize(-1); processed = true; break; defaut: break; } } } if(!processed){ QWidget::keyPressEvent(event); } } void View::zoomFontSize(int zoom) { zoomFontSizeSub(zoom, findChildren<QWidget*>()); fontZoom += zoom; } void View::zoomFontSizeSub(int zoom, const QList<QWidget*>& widgets) { int n = widgets.size(); for(int i=0; i < n; ++i){ QWidget* widget = widgets[i]; QFont font = widget->font(); font.setPointSize(font.pointSize() + zoom); widget->setFont(font); // The following recursive iteration is disabled because // it makes doubled zooming for some composite widgets // zoomFontSizeSub(zoom, widget->findChildren<QWidget*>()); } } void View::onAttachedMenuRequest(MenuManager& menuManager) { } bool View::storeState(Archive& archive) { return true; } bool View::restoreState(const Archive& archive) { return true; }
18.752212
97
0.614205
geenux
78029370fa5c23f92c6e5694ed03dcd806a2a202
3,091
cc
C++
srcs/lox/passes/pass_runner.cc
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
2
2021-12-25T01:45:26.000Z
2022-02-10T00:50:25.000Z
srcs/lox/passes/pass_runner.cc
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
null
null
null
srcs/lox/passes/pass_runner.cc
edimetia3d/cppLox
394bb0855c2a9d9b53f179330c2daa341786a04d
[ "MIT" ]
null
null
null
// // LICENSE: MIT // #include "pass_runner.h" #define RUNPASS_AND_UPDATE(KEY_NAME) \ { \ auto old_value = (KEY_NAME)(); \ auto new_value = RunPass(old_value); \ if (new_value != old_value) { \ (KEY_NAME)(new_value); \ } \ } #define RUNPASS_ON_VEC_AND_UPDATE(KEY_NAME) \ { \ auto cpy = (KEY_NAME)(); \ for (auto &node : cpy) { \ { \ auto new_value = RunPass(node); \ node = new_value; \ }; \ } \ if ((KEY_NAME)() != cpy) { \ (KEY_NAME)(cpy); \ } \ } namespace lox { void PassRunner::Visit(BlockStmt *state) { RUNPASS_ON_VEC_AND_UPDATE(state->statements) } void PassRunner::Visit(VarDeclStmt *state) { if (IsValid(state->initializer())) { RUNPASS_AND_UPDATE(state->initializer); } } void PassRunner::Visit(VariableExpr *state) {} void PassRunner::Visit(AssignExpr *state) { RUNPASS_AND_UPDATE(state->value); } void PassRunner::Visit(FunctionStmt *state) { RUNPASS_ON_VEC_AND_UPDATE(state->body); } void PassRunner::Visit(LogicalExpr *state) { RUNPASS_AND_UPDATE(state->left); RUNPASS_AND_UPDATE(state->right); } void PassRunner::Visit(BinaryExpr *state) { RUNPASS_AND_UPDATE(state->left); RUNPASS_AND_UPDATE(state->right); } void PassRunner::Visit(GroupingExpr *state) { RUNPASS_AND_UPDATE(state->expression); } void PassRunner::Visit(LiteralExpr *state) {} void PassRunner::Visit(UnaryExpr *state) { RUNPASS_AND_UPDATE(state->right); } void PassRunner::Visit(CallExpr *state) { RUNPASS_AND_UPDATE(state->callee); RUNPASS_ON_VEC_AND_UPDATE(state->arguments) } void PassRunner::Visit(PrintStmt *state) { RUNPASS_AND_UPDATE(state->expression); } void PassRunner::Visit(ReturnStmt *state) { if (IsValid(state->value())) { RUNPASS_AND_UPDATE(state->value); } } void PassRunner::Visit(WhileStmt *state) { RUNPASS_AND_UPDATE(state->condition); RUNPASS_AND_UPDATE(state->body); } void PassRunner::Visit(BreakStmt *state) {} void PassRunner::Visit(ExprStmt *state) { RUNPASS_AND_UPDATE(state->expression); } void PassRunner::Visit(IfStmt *state) { RUNPASS_AND_UPDATE(state->condition); RUNPASS_AND_UPDATE(state->thenBranch); if (IsValid(state->elseBranch())) { RUNPASS_AND_UPDATE(state->elseBranch); } } void PassRunner::Visit(ClassStmt *state) { if (IsValid(state->superclass())) { RUNPASS_AND_UPDATE(state->superclass); } RUNPASS_ON_VEC_AND_UPDATE(state->methods) } void PassRunner::Visit(GetAttrExpr *state) { RUNPASS_AND_UPDATE(state->src_object); } void PassRunner::Visit(SetAttrExpr *state) { RUNPASS_AND_UPDATE(state->src_object); RUNPASS_AND_UPDATE(state->value); } } // namespace lox
36.364706
89
0.601747
edimetia3d
78056c583afccd8a1339aff0304be824bd66ecc4
26
cpp
C++
components/core/src/streaming_compression/Compressor.cpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
28
2021-07-18T02:21:14.000Z
2021-09-30T22:46:24.000Z
components/core/src/streaming_compression/Compressor.cpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
15
2021-10-12T03:55:07.000Z
2022-03-24T09:04:35.000Z
components/core/src/streaming_compression/Compressor.cpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
11
2021-10-06T11:35:47.000Z
2022-03-20T11:40:49.000Z
#include "Compressor.hpp"
13
25
0.769231
kirkrodrigues
7806073556f48b53e9f81b5b30dd04733b5ab553
515
hpp
C++
src/KawaiiEngine/include/graphics/deps.hpp
Mathieu-Lala/Cute_Solar_System_-3
0bfe496991344709481995af348da2be37a19cac
[ "MIT" ]
4
2021-06-03T11:20:09.000Z
2022-02-11T06:52:54.000Z
src/KawaiiEngine/include/graphics/deps.hpp
Mathieu-Lala/Cute_Solar_System_-3
0bfe496991344709481995af348da2be37a19cac
[ "MIT" ]
35
2021-05-29T09:25:57.000Z
2021-06-28T04:49:22.000Z
src/KawaiiEngine/include/graphics/deps.hpp
Mathieu-Lala/Kawaii_Engine
0bfe496991344709481995af348da2be37a19cac
[ "MIT" ]
null
null
null
#pragma once #include "helpers/warnings.hpp" DISABLE_WARNING_PUSH DISABLE_WARNING_OLD_CAST #include <imgui.h> DISABLE_WARNING_POP #include <imgui_impl_glfw.h> #include <imgui_impl_opengl3.h> #include <GL/glew.h> #include <GLFW/glfw3.h> namespace kawe { namespace ImGuiHelper { template<typename... Args> inline auto Text(const std::string_view format, Args &&... args) { ::ImGui::TextUnformatted(fmt::format(format, std::forward<Args>(args)...).c_str()); } } // namespace ImGuiHelper } // namespace kawe
19.074074
87
0.741748
Mathieu-Lala
7808eb640a7731eb8e80fc180d245ebebb8d74f0
7,658
cpp
C++
libcaf_core/test/typed_response_promise.cpp
v2nero/actor-framework
c2f811809143d32c598471a20363238b0882a761
[ "BSL-1.0", "BSD-3-Clause" ]
1
2020-07-16T19:01:52.000Z
2020-07-16T19:01:52.000Z
libcaf_core/test/typed_response_promise.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/test/typed_response_promise.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
1
2021-02-19T11:25:15.000Z
2021-02-19T11:25:15.000Z
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <map> #include "caf/config.hpp" #define CAF_SUITE typed_response_promise #include "caf/test/unit_test.hpp" #include "caf/all.hpp" using namespace caf; namespace { using foo_actor = typed_actor<replies_to<int>::with<int>, replies_to<get_atom, int>::with<int>, replies_to<get_atom, int, int>::with<int, int>, replies_to<get_atom, double>::with<double>, replies_to<get_atom, double, double> ::with<double, double>, reacts_to<put_atom, int, int>, reacts_to<put_atom, int, int, int>>; using foo_promise = typed_response_promise<int>; using foo2_promise = typed_response_promise<int, int>; using foo3_promise = typed_response_promise<double>; using get1_helper = typed_actor<replies_to<int, int>::with<put_atom, int, int>>; using get2_helper = typed_actor<replies_to<int, int, int>::with<put_atom, int, int, int>>; class foo_actor_impl : public foo_actor::base { public: foo_actor_impl(actor_config& cfg) : foo_actor::base(cfg) { // nop } behavior_type make_behavior() override { return { [=](int x) -> foo_promise { auto resp = response(x * 2); CAF_CHECK(!resp.pending()); return resp.deliver(x * 4); // has no effect }, [=](get_atom, int x) -> foo_promise { auto calculator = spawn([]() -> get1_helper::behavior_type { return { [](int promise_id, int value) -> result<put_atom, int, int> { return {put_atom::value, promise_id, value * 2}; } }; }); send(calculator, next_id_, x); auto& entry = promises_[next_id_++]; entry = make_response_promise<foo_promise>(); return entry; }, [=](get_atom, int x, int y) -> foo2_promise { auto calculator = spawn([]() -> get2_helper::behavior_type { return { [](int promise_id, int v0, int v1) -> result<put_atom, int, int, int> { return {put_atom::value, promise_id, v0 * 2, v1 * 2}; } }; }); send(calculator, next_id_, x, y); auto& entry = promises2_[next_id_++]; entry = make_response_promise<foo2_promise>(); // verify move semantics CAF_CHECK(entry.pending()); foo2_promise tmp(std::move(entry)); CAF_CHECK(!entry.pending()); CAF_CHECK(tmp.pending()); entry = std::move(tmp); CAF_CHECK(entry.pending()); CAF_CHECK(!tmp.pending()); return entry; }, [=](get_atom, double) -> foo3_promise { auto resp = make_response_promise<double>(); return resp.deliver(make_error(sec::unexpected_message)); }, [=](get_atom, double x, double y) { return response(x * 2, y * 2); }, [=](put_atom, int promise_id, int x) { auto i = promises_.find(promise_id); if (i == promises_.end()) return; i->second.deliver(x); promises_.erase(i); }, [=](put_atom, int promise_id, int x, int y) { auto i = promises2_.find(promise_id); if (i == promises2_.end()) return; i->second.deliver(x, y); promises2_.erase(i); } }; } private: int next_id_ = 0; std::map<int, foo_promise> promises_; std::map<int, foo2_promise> promises2_; }; struct fixture { fixture() : system(cfg), self(system, true), foo(system.spawn<foo_actor_impl>()) { // nop } actor_system_config cfg; actor_system system; scoped_actor self; foo_actor foo; }; } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture) CAF_TEST(typed_response_promise) { typed_response_promise<int> resp; CAF_MESSAGE("trigger 'invalid response promise' error"); resp.deliver(1); // delivers on an invalid promise has no effect auto f = make_function_view(foo); CAF_CHECK_EQUAL(f(get_atom::value, 42), 84); CAF_CHECK_EQUAL(f(get_atom::value, 42, 52), std::make_tuple(84, 104)); CAF_CHECK_EQUAL(f(get_atom::value, 3.14, 3.14), std::make_tuple(6.28, 6.28)); } CAF_TEST(typed_response_promise_chained) { auto f = make_function_view(foo * foo * foo); CAF_CHECK_EQUAL(f(1), 8); } // verify that only requests get an error response message CAF_TEST(error_response_message) { auto f = make_function_view(foo); CAF_CHECK_EQUAL(f(get_atom::value, 3.14), sec::unexpected_message); self->send(foo, get_atom::value, 42); self->receive( [](int x) { CAF_CHECK_EQUAL(x, 84); }, [](double x) { CAF_ERROR("unexpected ordinary response message received: " << x); } ); self->send(foo, get_atom::value, 3.14); self->receive( [&](error& err) { CAF_CHECK_EQUAL(err, sec::unexpected_message); self->send(self, message{}); } ); } // verify that delivering to a satisfied promise has no effect CAF_TEST(satisfied_promise) { self->send(foo, 1); self->send(foo, get_atom::value, 3.14, 3.14); int i = 0; self->receive_for(i, 2) ( [](int x) { CAF_CHECK_EQUAL(x, 1 * 2); }, [](double x, double y) { CAF_CHECK_EQUAL(x, 3.14 * 2); CAF_CHECK_EQUAL(y, 3.14 * 2); } ); } CAF_TEST(delegating_promises) { using task = std::pair<typed_response_promise<int>, int>; struct state { std::vector<task> tasks; }; using bar_actor = typed_actor<replies_to<int>::with<int>, reacts_to<ok_atom>>; auto bar_fun = [](bar_actor::stateful_pointer<state> self, foo_actor worker) -> bar_actor::behavior_type { return { [=](int x) -> typed_response_promise<int> { auto& tasks = self->state.tasks; tasks.emplace_back(self->make_response_promise<int>(), x); self->send(self, ok_atom::value); return tasks.back().first; }, [=](ok_atom) { auto& tasks = self->state.tasks; if (!tasks.empty()) { auto& task = tasks.back(); task.first.delegate(worker, task.second); tasks.pop_back(); } } }; }; auto f = make_function_view(system.spawn(bar_fun, foo)); CAF_CHECK_EQUAL(f(42), 84); } CAF_TEST_FIXTURE_SCOPE_END()
33.884956
90
0.536432
v2nero
780983d251b485f9e963bd8bf9de538eec72a7d9
310
cpp
C++
657. Judge Route Circle.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
657. Judge Route Circle.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
657. Judge Route Circle.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: bool judgeCircle(string moves) { int v = 0, h = 0; unordered_map<char, int>m{{'R', 1}, {'L', -1}, {'U', -1}, {'D', 1}}; for(auto x: moves) if(x == 'L' || x == 'R') h += m[x]; else v += m[x]; return v == 0 && h == 0; } };
25.833333
76
0.387097
rajeev-ranjan-au6
7818f610f9d012020338ac08ac054864afd454c0
565
cpp
C++
codeforces/contests/round/646-div2/c.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/contests/round/646-div2/c.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/contests/round/646-div2/c.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int t; cin >> t; while(t--){ int n, x; cin >> n >> x; int cnt = 0; for(int i=1; i<n; ++i){ int a, b; cin >> a >> b; if(a == x or b == x) cnt++; } if(cnt <= 1) cout << "Ayush" << endl; else{ int till = n-2; if(till%2) cout << "Ashish" << endl; else cout << "Ayush" << endl; } } return 0; }
19.482759
41
0.316814
tysm
781969a6b52dc866a1f04fd36357081fcd7d0d5b
7,030
cpp
C++
cpp/open3d/visualization/gui/Button.cpp
Dudulle/Open3D
ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab
[ "MIT" ]
1
2021-05-10T04:23:24.000Z
2021-05-10T04:23:24.000Z
cpp/open3d/visualization/gui/Button.cpp
Dudulle/Open3D
ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab
[ "MIT" ]
null
null
null
cpp/open3d/visualization/gui/Button.cpp
Dudulle/Open3D
ffed2d1bee6d45b6acc4b7ae7133752e50d6ecab
[ "MIT" ]
1
2021-11-05T01:16:13.000Z
2021-11-05T01:16:13.000Z
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2021 www.open3d.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 "open3d/visualization/gui/Button.h" #include <imgui.h> #include <cmath> #include <string> #include "open3d/visualization/gui/Theme.h" #include "open3d/visualization/gui/Util.h" namespace open3d { namespace visualization { namespace gui { namespace { static int g_next_button_id = 1; } // namespace struct Button::Impl { std::string id_; std::string title_; std::shared_ptr<UIImage> image_; float padding_horizontal_em_ = 0.5f; float padding_vertical_em_ = 0.5f; bool is_toggleable_ = false; bool is_on_ = false; std::function<void()> on_clicked_; }; Button::Button(const char* title) : impl_(new Button::Impl()) { impl_->id_ = std::string("##button") + std::to_string(g_next_button_id++); impl_->title_ = title; } Button::Button(std::shared_ptr<UIImage> image) : impl_(new Button::Impl()) { impl_->image_ = image; } Button::~Button() {} const char* Button::GetText() const { return impl_->title_.c_str(); } void Button::SetText(const char* text) { impl_->title_ = text; } float Button::GetHorizontalPaddingEm() const { return impl_->padding_horizontal_em_; } float Button::GetVerticalPaddingEm() const { return impl_->padding_vertical_em_; } void Button::SetPaddingEm(float horiz_ems, float vert_ems) { impl_->padding_horizontal_em_ = horiz_ems; impl_->padding_vertical_em_ = vert_ems; } bool Button::GetIsToggleable() const { return impl_->is_toggleable_; } void Button::SetToggleable(bool toggles) { impl_->is_toggleable_ = toggles; } bool Button::GetIsOn() const { return impl_->is_on_; } void Button::SetOn(bool is_on) { if (impl_->is_toggleable_) { impl_->is_on_ = is_on; } } void Button::SetOnClicked(std::function<void()> on_clicked) { impl_->on_clicked_ = on_clicked; } Size Button::CalcPreferredSize(const LayoutContext& context, const Constraints& constraints) const { auto em = float(context.theme.font_size); auto padding_horiz = int(std::ceil(impl_->padding_horizontal_em_ * em)); auto padding_vert = int(std::ceil(impl_->padding_vertical_em_ * em)); if (impl_->image_) { auto size = impl_->image_->CalcPreferredSize(context, constraints); return Size(size.width + 2 * padding_horiz, size.height + 2 * padding_vert); } else { auto font = ImGui::GetFont(); auto imguiVertPadding = ImGui::GetTextLineHeightWithSpacing() - ImGui::GetTextLineHeight(); auto size = font->CalcTextSizeA(float(context.theme.font_size), float(constraints.width), 10000, impl_->title_.c_str()); // When ImGUI draws text, it draws text in a box of height // font_size + spacing. The padding on the bottom is essentially the // descender height, and the box height ends up giving a visual padding // of descender_height on the top and bottom. So while we only need to // 1 * imguiVertPadding on the bottom, we need to add 2x on the sides. // Note that padding of 0 doesn't actually produce a padding of zero, // because that would look horrible. (And also because if we do that, // ImGUI will position the text so that the descender is cut off, // because it is assuming that it gets a little extra on the bottom. // This looks really bad...) return Size( int(std::ceil(size.x + 2.0f + imguiVertPadding)) + 2 * padding_horiz, int(std::ceil(ImGui::GetTextLineHeight() + imguiVertPadding)) + 2 * padding_vert); } } Widget::DrawResult Button::Draw(const DrawContext& context) { auto& frame = GetFrame(); auto result = Widget::DrawResult::NONE; ImGui::SetCursorScreenPos(ImVec2(float(frame.x), float(frame.y))); bool was_on = impl_->is_on_; if (was_on) { ImGui::PushStyleColor(ImGuiCol_Text, colorToImgui(context.theme.button_on_text_color)); ImGui::PushStyleColor(ImGuiCol_Button, colorToImgui(context.theme.button_on_color)); ImGui::PushStyleColor( ImGuiCol_ButtonHovered, colorToImgui(context.theme.button_on_hover_color)); ImGui::PushStyleColor( ImGuiCol_ButtonActive, colorToImgui(context.theme.button_on_active_color)); } DrawImGuiPushEnabledState(); bool pressed = false; if (impl_->image_) { auto params = impl_->image_->CalcDrawParams(context.renderer, frame); ImTextureID image_id = reinterpret_cast<ImTextureID>(params.texture.GetId()); pressed = ImGui::ImageButton( image_id, ImVec2(params.width, params.height), ImVec2(params.u0, params.v0), ImVec2(params.u1, params.v1)); } else { pressed = ImGui::Button( (impl_->title_ + impl_->id_).c_str(), ImVec2(float(GetFrame().width), float(GetFrame().height))); } if (pressed) { if (impl_->is_toggleable_) { impl_->is_on_ = !impl_->is_on_; } if (impl_->on_clicked_) { impl_->on_clicked_(); } result = Widget::DrawResult::REDRAW; } DrawImGuiPopEnabledState(); DrawImGuiTooltip(); if (was_on) { ImGui::PopStyleColor(4); } return result; } } // namespace gui } // namespace visualization } // namespace open3d
37.393617
80
0.624609
Dudulle
781b076387a86f0610600e89ede7e4e78c99712f
370
cpp
C++
Symboltable/src/SymtabEntry.cpp
SystemOfAProg/SysProgTotallyNotTheSolution
0a3b1b65c084b0cd9eac7b35cc486ad0ae6d0bb9
[ "MIT" ]
null
null
null
Symboltable/src/SymtabEntry.cpp
SystemOfAProg/SysProgTotallyNotTheSolution
0a3b1b65c084b0cd9eac7b35cc486ad0ae6d0bb9
[ "MIT" ]
null
null
null
Symboltable/src/SymtabEntry.cpp
SystemOfAProg/SysProgTotallyNotTheSolution
0a3b1b65c084b0cd9eac7b35cc486ad0ae6d0bb9
[ "MIT" ]
null
null
null
#include "../includes/SymtabEntry.h" #include <cstring> SymtabEntry::SymtabEntry(Information* info) { this->info = info; this->next = NULL; } SymtabEntry::~SymtabEntry() { } SymtabEntry* SymtabEntry::getNext() { return this->next; } void SymtabEntry::setNext(SymtabEntry* next) { this->next = next; } Information* SymtabEntry::getInfo() { return this->info; }
16.086957
46
0.7
SystemOfAProg
781e455ed73908ed72b4682a72adeb0c9ad4993a
4,625
hpp
C++
OptimExplorer/core/utils.hpp
MarkTuddenham/OptimExplorer
1fb724bb80b099ade76d9f8d6179cb561dedb9bd
[ "MIT" ]
1
2020-08-18T20:55:26.000Z
2020-08-18T20:55:26.000Z
OptimExplorer/core/utils.hpp
MarkTuddenham/OptimExplorer
1fb724bb80b099ade76d9f8d6179cb561dedb9bd
[ "MIT" ]
4
2020-10-11T12:57:29.000Z
2020-10-11T14:06:17.000Z
OptimExplorer/core/utils.hpp
MarkTuddenham/OptimExplorer
1fb724bb80b099ade76d9f8d6179cb561dedb9bd
[ "MIT" ]
null
null
null
#if defined(_MSC_VER) && !defined(NDEBUG) #define DISABLE_WARNING_PUSH __pragma(warning(push)) #define DISABLE_WARNING_PUSH_ALL __pragma(warning(push, 0)) #define DISABLE_WARNING_POP __pragma(warning(pop)) #define DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber)) #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER DISABLE_WARNING(4100) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(4505) #define DISABLE_WARNING_PRAGMAS #define DISABLE_WARNING_SIGN_CONVERSION #define DISABLE_WARNING_OLD_STYLE_CAST #define DISABLE_WARNING_IMPLICIT_INT_CONVERSION #define DISABLE_WARNING_SHORTEN_64_TO_32 #define DISABLE_WARNING_MISSING_PROTOTYPES #define DISABLE_WARNING_SHADOW #define DISABLE_WARNING_ENUM_ENUM_CONVERSION #define DISABLE_WARNING_USELESS_CAST #define DISABLE_WARNING_PEDANTIC #define DISABLE_WARNING_IGNORED_QUALIFIERS #define DISABLE_WARNING_REORDER #define DISABLE_WARNING_NON_VIRTUAL_DTOR #elif (defined(__GNUC__) || defined(__clang__)) && !defined(NDEBUG) #define DO_PRAGMA(X) _Pragma(#X) #define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) #define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) #define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) #define DISABLE_WARNING_PRAGMAS DISABLE_WARNING(-Wpragmas) #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER DISABLE_WARNING(-Wunused-parameter) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(-Wunused-function) #define DISABLE_WARNING_SIGN_CONVERSION DISABLE_WARNING(-Wsign-conversion) #define DISABLE_WARNING_OLD_STYLE_CAST DISABLE_WARNING(-Wold-style-cast) #define DISABLE_WARNING_IMPLICIT_INT_CONVERSION DISABLE_WARNING(-Wimplicit-int-conversion) #define DISABLE_WARNING_SHORTEN_64_TO_32 DISABLE_WARNING(-Wshorten-64-to-32) #define DISABLE_WARNING_MISSING_PROTOTYPES DISABLE_WARNING(-Wmissing-prototypes) #define DISABLE_WARNING_SHADOW DISABLE_WARNING(-Wshadow) #define DISABLE_WARNING_ENUM_ENUM_CONVERSION DISABLE_WARNING(-Wenum-enum-conversion) #define DISABLE_WARNING_USELESS_CAST DISABLE_WARNING(-Wuseless-cast) #define DISABLE_WARNING_PEDANTIC DISABLE_WARNING(-Wpedantic) #define DISABLE_WARNING_IGNORED_QUALIFIERS DISABLE_WARNING(-Wignored-qualifiers) #define DISABLE_WARNING_REORDER DISABLE_WARNING(-Wreorder) #define DISABLE_WARNING_NON_VIRTUAL_DTOR DISABLE_WARNING(-Wnon-virtual-dtor) #define DISABLE_WARNING_PUSH_ALL \ DISABLE_WARNING_PRAGMAS \ DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER \ DISABLE_WARNING_UNREFERENCED_FUNCTION \ DISABLE_WARNING_SIGN_CONVERSION \ DISABLE_WARNING_OLD_STYLE_CAST \ DISABLE_WARNING_IMPLICIT_INT_CONVERSION \ DISABLE_WARNING_SHORTEN_64_TO_32 \ DISABLE_WARNING_MISSING_PROTOTYPES \ DISABLE_WARNING_SHADOW \ DISABLE_WARNING_ENUM_ENUM_CONVERSION \ DISABLE_WARNING_USELESS_CAST \ DISABLE_WARNING_PEDANTIC \ DISABLE_WARNING_IGNORED_QUALIFIERS \ DISABLE_WARNING_REORDER \ DISABLE_WARNING_NON_VIRTUAL_DTOR #else #define DISABLE_WARNING_PUSH_ALL #define DISABLE_WARNING_PUSH #define DISABLE_WARNING_POP #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER #define DISABLE_WARNING_UNREFERENCED_FUNCTION #define DISABLE_WARNING_PRAGMAS #define DISABLE_WARNING_SIGN_CONVERSION #define DISABLE_WARNING_OLD_STYLE_CAST #define DISABLE_WARNING_IMPLICIT_INT_CONVERSION #define DISABLE_WARNING_SHORTEN_64_TO_32 #define DISABLE_WARNING_MISSING_PROTOTYPES #define DISABLE_WARNING_SHADOW #define DISABLE_WARNING_ENUM_ENUM_CONVERSION #define DISABLE_WARNING_USELESS_CAST #define DISABLE_WARNING_PEDANTIC #define DISABLE_WARNING_IGNORED_QUALIFIERS #define DISABLE_WARNING_REORDER #define DISABLE_WARNING_NON_VIRTUAL_DTOR #endif
56.402439
92
0.697297
MarkTuddenham
781eb578aa62046cf3cd83874e434580b0264997
934
hh
C++
src/utils/matrix/MatrixOperations.hh
LeoRya/py-orbit
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
[ "MIT" ]
17
2018-02-09T23:39:06.000Z
2022-03-04T16:27:04.000Z
src/utils/matrix/MatrixOperations.hh
LeoRya/py-orbit
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
[ "MIT" ]
22
2017-05-31T19:40:14.000Z
2021-09-24T22:07:47.000Z
src/utils/matrix/MatrixOperations.hh
LeoRya/py-orbit
340b14b6fd041ed8ec2cc25b0821b85742aabe0c
[ "MIT" ]
37
2016-12-08T19:39:35.000Z
2022-02-11T19:59:34.000Z
#ifndef __MATRIX_OPERATIONS_H_ #define __MATRIX_OPERATIONS_H_ #include "Matrix.hh" #include "PhaseVector.hh" #include "Bunch.hh" namespace OrbitUtils{ /** The collection of the static methods for matrices. */ class MatrixOperations{ public: /** Inverts the 2D array as a matrix. */ static int invert(double **a, int n); /** Inversts the matrix in place. */ static int invert(Matrix* matrix); /** Multiplies a vector with the transposed matrix. */ static int mult(PhaseVector* v, Matrix* mtrx, PhaseVector* v_res); /** Multiplies a vector with the matrix. */ static int mult(Matrix* mtrx, PhaseVector* v, PhaseVector* v_res); /** Calculates determinant of the matrix. */ static int det(Matrix* mtrx_in, double& det); /** Tracks the bunch through the transport matrix. The matrix should be 6x6 or 7x7. */ static void track(Bunch* bunch,Matrix* mtrx); }; }; #endif
22.780488
68
0.683084
LeoRya
781fbeaa2b4f0bff4d81099f43017283c50ddd3a
7,936
cpp
C++
source/modules/examples/roles/roles.cpp
noglass/FarageBot
f8fbb3a70275230719916fb5083757e8fcf5753b
[ "MIT" ]
null
null
null
source/modules/examples/roles/roles.cpp
noglass/FarageBot
f8fbb3a70275230719916fb5083757e8fcf5753b
[ "MIT" ]
null
null
null
source/modules/examples/roles/roles.cpp
noglass/FarageBot
f8fbb3a70275230719916fb5083757e8fcf5753b
[ "MIT" ]
null
null
null
#include "api/farage.h" #include <unordered_map> #include <unordered_set> #include <fstream> using namespace Farage; #define VERSION "v0.0.4" extern "C" Info Module { "User Roles", "Madison", "User Role Granting System", VERSION, "http://farage.justca.me/", FARAGE_API_VERSION }; namespace role { std::unordered_map<std::string,std::unordered_set<std::string>> roles; } int addroleCmd(Handle&,int,const std::string[],const Message&); int delroleCmd(Handle&,int,const std::string[],const Message&); int giveroleCmd(Handle&,int,const std::string[],const Message&); extern "C" int onModuleStart(Handle &handle, Global *global) { recallGlobal(global); handle.createGlobVar("roles_version",VERSION,"User Roles Version",GVAR_CONSTANT); handle.regChatCmd("addrole",&addroleCmd,ROLE,"Allow an already existing role to the roster."); handle.regChatCmd("delrole",&delroleCmd,ROLE,"Remove a role from the roster."); handle.regChatCmd("role",&giveroleCmd,NOFLAG,"Grant a role for yourself."); return 0; } extern "C" int onReady(Handle &handle, Event event, void *data, void *nil, void *foo, void *bar) { Ready* readyData = (Ready*)data; for (auto it = readyData->guilds.begin(), ite = readyData->guilds.end();it != ite;++it) { std::unordered_set<std::string> r; std::ifstream file ("roles/" + *it); if (file.is_open()) { std::string line; while (std::getline(file,line)) r.emplace(line); file.close(); } role::roles.emplace(*it,std::move(r)); } return PLUGIN_CONTINUE; } int addroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message) { Global *global = recallGlobal(); auto server = getGuildCache(message.guild_id); auto roles = role::roles.find(message.guild_id); if (roles == role::roles.end()) { role::roles.emplace(message.guild_id,std::unordered_set<std::string>()); roles = role::roles.find(message.guild_id); } if (argc < 2) { sendMessage(message.channel_id,"Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>`"); return PLUGIN_HANDLED; } std::string role = argv[1]; for (int i = 2;i < argc;++i) role.append(1,' ').append(argv[i]); if ((role.substr(0,3) == "<@&") && (role.back() == '>')) role = role.substr(3,role.size()-4); std::string name = strlower(role); if ((name.front() == '"') && (name.back() == '"')) name = name.substr(1,name.size()-2); bool found = false; for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it) { if ((strlower(it->name) == name) || (it->id == role)) { role = it->id; name = it->name; found = true; break; } } if ((found) && (roles->second.find(role) == roles->second.end())) { roles->second.emplace(role); std::ofstream file ("roles/" + message.guild_id); if (file.is_open()) { for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it) file<<*it<<std::endl; file.close(); } sendMessage(message.channel_id,"Added the role: `" + name + "`!"); } else if (found) sendMessage(message.channel_id,"Role is already registered: `" + name + "`!"); else sendMessage(message.channel_id,"Not a valid role: `" + role + "`!"); return PLUGIN_HANDLED; } int delroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message) { Global *global = recallGlobal(); auto server = getGuildCache(message.guild_id); auto roles = role::roles.find(message.guild_id); if (argc < 2) { sendMessage(message.channel_id,"Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>`"); return PLUGIN_HANDLED; } if ((roles == role::roles.end()) || (roles->second.size() == 0)) { sendMessage(message.channel_id,"There are no registered roles!"); return PLUGIN_HANDLED; } std::string role = argv[1]; for (int i = 2;i < argc;++i) role.append(1,' ').append(argv[i]); if ((role.substr(0,3) == "<@&") && (role.back() == '>')) role = role.substr(3,role.size()-4); std::string name = strlower(role); if ((name.front() == '"') && (name.back() == '"')) name = name.substr(1,name.size()-2); for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it) { if ((strlower(it->name) == name) || (it->id == role)) { role = it->id; name = it->name; break; } } auto r = roles->second.find(role); if (r == roles->second.end()) { sendMessage(message.channel_id,"Not a valid role: `" + role + "`!"); return PLUGIN_HANDLED; } roles->second.erase(r); std::ofstream file ("roles/" + message.guild_id); if (file.is_open()) { for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it) file<<*it<<std::endl; file.close(); } sendMessage(message.channel_id,"Removed the role: `" + name + "`!"); return PLUGIN_HANDLED; } int giveroleCmd(Handle& handle, int argc, const std::string argv[], const Message& message) { Global *global = recallGlobal(); auto server = getGuildCache(message.guild_id); auto roles = role::roles.find(message.guild_id); if ((roles == role::roles.end()) || (roles->second.size() == 0)) { sendMessage(message.channel_id,"There are no registered roles!"); return PLUGIN_HANDLED; } if (argc < 2) { Embed out; out.color = 11614177; out.title = "Usage: `" + global->prefix(message.guild_id) + argv[0] + " <role>` to give yourself a role."; for (auto it = roles->second.begin(), ite = roles->second.end();it != ite;++it) for (auto sit = server.roles.begin(), site = server.roles.end();sit != site;++sit) if (sit->id == *it) out.description.append(1,'\n').append(sit->name); sendEmbed(message.channel_id,out); return PLUGIN_HANDLED; } std::string role = argv[1]; for (int i = 2;i < argc;++i) role.append(1,' ').append(argv[i]); std::string name = strlower(role); if ((role.substr(0,3) == "<@&") && (role.back() == '>')) role = role.substr(3,role.size()-4); else { if ((name.front() == '"') && (name.back() == '"')) name = name.substr(1,name.size()-2); for (auto it = server.roles.begin(), ite = server.roles.end();it != ite;++it) { if (strlower(it->name) == name) { role = it->id; name = it->name; break; } } } if (roles->second.find(role) == roles->second.end()) { sendMessage(message.channel_id,"Not a valid role: `" + role + "`!"); return PLUGIN_HANDLED; } else { auto mroles = message.member.roles; for (auto it = mroles.begin(), ite = mroles.end();it != ite;++it) { if (*it == role) { mroles.erase(it); editMember(message.guild_id,message.author.id,(message.member.nick.size() > 0 ? message.member.nick : message.author.username),mroles); sendMessage(message.channel_id,"You have left the `" + name + "` role."); return PLUGIN_HANDLED; } } mroles.push_back(role); editMember(message.guild_id,message.author.id,(message.member.nick.size() > 0 ? message.member.nick : message.author.username),mroles); sendMessage(message.channel_id,"You have joined the `" + name + "` role."); } return PLUGIN_HANDLED; }
34.960352
151
0.559098
noglass
7822532491068056bccda67af9935be670d60aa6
2,312
cpp
C++
collector/src/main_win32.cpp
tyoma/micro-profiler
32f6981c643b93997752d414f631fd6684772b28
[ "MIT" ]
194
2015-07-27T09:54:24.000Z
2022-03-21T20:50:22.000Z
collector/src/main_win32.cpp
tyoma/micro-profiler
32f6981c643b93997752d414f631fd6684772b28
[ "MIT" ]
63
2015-08-19T16:42:33.000Z
2022-02-22T20:30:49.000Z
collector/src/main_win32.cpp
tyoma/micro-profiler
32f6981c643b93997752d414f631fd6684772b28
[ "MIT" ]
33
2015-08-21T17:48:03.000Z
2022-02-23T03:54:17.000Z
// Copyright (c) 2011-2021 by Artem A. Gevorkyan (gevorkyan.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 <crtdbg.h> #include "detour.h" #include "main.h" #include <tchar.h> #include <windows.h> using namespace std; namespace micro_profiler { namespace { collector_app_instance *g_instance_singleton = nullptr; shared_ptr<void> *g_exit_process_detour = nullptr; void WINAPI ExitProcessHooked(UINT exit_code) { if (g_exit_process_detour) g_exit_process_detour->reset(); g_instance_singleton->terminate(); ::ExitProcess(exit_code); } } void collector_app_instance::platform_specific_init() { _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); static shared_ptr<void> exit_process_detour; g_instance_singleton = this; g_exit_process_detour = &exit_process_detour; HMODULE hmodule; ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, _T("kernel32"), &hmodule); const auto exit_process = ::GetProcAddress(hmodule, "ExitProcess"); ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, reinterpret_cast<LPCTSTR>(&ExitProcessHooked), &hmodule); exit_process_detour = detour(exit_process, &ExitProcessHooked); } }
34.507463
101
0.773356
tyoma
7822a8e6784939bc2e3f32e0ac89b7080553b9aa
68
cpp
C++
BrowserPivotingIE/HTTPProxy/payload.cpp
ZwCreatePhoton/BrowserPivotingIE
5cc0b8f46b29ec7559de164bc8677457b70607e9
[ "MIT" ]
null
null
null
BrowserPivotingIE/HTTPProxy/payload.cpp
ZwCreatePhoton/BrowserPivotingIE
5cc0b8f46b29ec7559de164bc8677457b70607e9
[ "MIT" ]
null
null
null
BrowserPivotingIE/HTTPProxy/payload.cpp
ZwCreatePhoton/BrowserPivotingIE
5cc0b8f46b29ec7559de164bc8677457b70607e9
[ "MIT" ]
null
null
null
#include "HTTPProxy.h" void Payload() { run(DEFAULT_PROXY_PORT); }
11.333333
25
0.720588
ZwCreatePhoton
7825c118fddfb25686acd603cadb9fb07bf4b437
4,568
cpp
C++
engine/modules/openx/opendrive/opendrive_dynamic_mesh.cpp
blab-liuliang/Echo
ba75816e449d2f20a375ed44b0f706a6b7bc21a1
[ "MIT" ]
58
2018-05-10T17:06:42.000Z
2019-01-24T13:42:22.000Z
engine/modules/openx/opendrive/opendrive_dynamic_mesh.cpp
blab-liuliang/echo
ba75816e449d2f20a375ed44b0f706a6b7bc21a1
[ "MIT" ]
290
2018-01-24T16:29:42.000Z
2019-01-24T07:11:16.000Z
engine/modules/openx/opendrive/opendrive_dynamic_mesh.cpp
blab-liuliang/Echo
ba75816e449d2f20a375ed44b0f706a6b7bc21a1
[ "MIT" ]
9
2018-08-26T04:06:21.000Z
2019-01-14T03:47:39.000Z
#include "opendrive_dynamic_mesh.h" #include "engine/core/log/log.h" #include "engine/core/scene/node_tree.h" #include "base/renderer.h" #include "base/shader/shader_program.h" #include "engine/core/main/Engine.h" namespace Echo { OpenDriveDynamicMesh::OpenDriveDynamicMesh() : Render() { setRenderType("3d"); } OpenDriveDynamicMesh::~OpenDriveDynamicMesh() { reset(); } void OpenDriveDynamicMesh::bindMethods() { CLASS_BIND_METHOD(OpenDriveDynamicMesh, getStepLength); CLASS_BIND_METHOD(OpenDriveDynamicMesh, setStepLength); CLASS_BIND_METHOD(OpenDriveDynamicMesh, getMaterial); CLASS_BIND_METHOD(OpenDriveDynamicMesh, setMaterial); CLASS_REGISTER_PROPERTY(OpenDriveDynamicMesh, "StepLength", Variant::Type::Real, getStepLength, setStepLength); CLASS_REGISTER_PROPERTY(OpenDriveDynamicMesh, "Material", Variant::Type::Object, getMaterial, setMaterial); CLASS_REGISTER_PROPERTY_HINT(OpenDriveDynamicMesh, "Material", PropertyHintType::ObjectType, "Material"); } void OpenDriveDynamicMesh::reset() { m_controlPoints.clear(); m_renderable.reset(); m_mesh.reset(); } void OpenDriveDynamicMesh::add(const Vector3& position, const Vector3& forward, const Vector3& up, float width, const Color& color, bool separator) { ControlPoint controlPoint; controlPoint.m_position = position; controlPoint.m_forward = forward; controlPoint.m_up = up; controlPoint.m_width = width; controlPoint.m_length = m_controlPoints.empty() ? 0.f : m_controlPoints.back().m_length + (m_controlPoints.back().m_position - position).len(); controlPoint.m_color = color; controlPoint.m_separator = separator; m_controlPoints.emplace_back(controlPoint); m_isRenderableDirty = true; } void OpenDriveDynamicMesh::setStepLength(float stepLength) { if (m_stepLength != stepLength) { m_stepLength = stepLength; m_isRenderableDirty = true; } } void OpenDriveDynamicMesh::setMaterial(Object* material) { m_material = (Material*)material; m_isRenderableDirty = true; } void OpenDriveDynamicMesh::buildRenderable() { if (m_isRenderableDirty) { if (!m_material) { StringArray macros = { "HAS_NORMALS" }; ShaderProgramPtr shader = ShaderProgram::getDefault3D(macros); m_material = ECHO_CREATE_RES(Material); m_material->setShaderPath(shader->getPath()); } // mesh updateMeshBuffer(); // create render able m_renderable = RenderProxy::create(m_mesh, m_material, this, true); m_isRenderableDirty = false; } } void OpenDriveDynamicMesh::updateInternal(float elapsedTime) { if (isNeedRender()) buildRenderable(); if (m_renderable) m_renderable->setSubmitToRenderQueue(isNeedRender()); } void OpenDriveDynamicMesh::updateMeshBuffer() { if (!m_mesh) { if (m_controlPoints.size()>1) m_mesh = Mesh::create(true, true); } if (m_mesh) { IndiceArray indices; VertexArray vertices; for (size_t i = 0; i < m_controlPoints.size(); i++) { const ControlPoint& controlPoint = m_controlPoints[i]; Vector3 halfRightDir = controlPoint.m_forward.cross(controlPoint.m_up) * controlPoint.m_width * 0.5f; // Update Vertices VertexFormat v0; v0.m_position = controlPoint.m_position + halfRightDir; v0.m_normal = controlPoint.m_up; //v0.m_color = controlPoint.Color; v0.m_uv = Vector2(0.f, controlPoint.m_length / controlPoint.m_width) * m_uvScale; VertexFormat v1; v1.m_position = controlPoint.m_position - halfRightDir; v1.m_normal = controlPoint.m_up; //v1.Color = controlPoint.Color; v1.m_uv = Vector2(1.f, controlPoint.m_length / controlPoint.m_width) * m_uvScale; vertices.push_back(v0); vertices.push_back(v1); // Update Indices if (i != 0 && !controlPoint.m_separator) { i32 base = vertices.size() - 4; indices.push_back(base); indices.push_back(base + 3); indices.push_back(base + 2); indices.push_back(base); indices.push_back(base + 1); indices.push_back(base + 3); } } // format MeshVertexFormat define; define.m_isUseNormal = true; define.m_isUseUV = true; m_mesh->updateIndices(static_cast<ui32>(indices.size()), sizeof(ui32), indices.data()); m_mesh->updateVertexs(define, static_cast<ui32>(vertices.size()), (const Byte*)vertices.data()); m_localAABB = m_mesh->getLocalBox(); } } void* OpenDriveDynamicMesh::getGlobalUniformValue(const String& name) { if (name == "u_WorldMatrix") return (void*)(&Matrix4::IDENTITY); return Render::getGlobalUniformValue(name); } }
26.252874
148
0.721103
blab-liuliang
782734aaf28fea2fbf28536efde825f2d7d9af08
34,650
cpp
C++
marxan.cpp
hotzevzl/marxan
23ba3a0ada90e721c745b922363458bece3477dc
[ "MIT" ]
5
2021-02-16T07:50:47.000Z
2021-09-14T00:17:13.000Z
marxan.cpp
hotzevzl/marxan
23ba3a0ada90e721c745b922363458bece3477dc
[ "MIT" ]
7
2021-02-17T00:03:09.000Z
2021-10-05T14:46:22.000Z
marxan.cpp
hotzevzl/marxan
23ba3a0ada90e721c745b922363458bece3477dc
[ "MIT" ]
2
2020-10-02T18:08:17.000Z
2021-06-18T09:03:01.000Z
// C++ code for Marxan // version 2.3 introduced multiple connectivity files and their associated weighting file // version 2.4.3 introduced 1D and 2D probability // version 3.0.0 is refactoring of code in 2019 #include <algorithm> #include <chrono> #include <ctime> #include <cfloat> #include <iostream> #include <omp.h> #include <chrono> // load the required function definition modules #include "utils.hpp" #include "algorithms.hpp" #include "computation.hpp" #include "clumping.hpp" #include "anneal.hpp" #include "heuristics.hpp" #include "probability.hpp" #include "input.hpp" #include "output.hpp" #include "score_change.hpp" #include "iterative_improvement.hpp" #include "quantum_annealing.hpp" #include "thermal_annealing.hpp" #include "hill_climbing.hpp" #include "marxan.hpp" #include "defines.hpp" namespace marxan { using namespace algorithms; using namespace utils; // Initialize global constants double delta; long int RandSeed1; int iMemoryUsed = 0; int fSpecPROPLoaded = 0; int iProbFieldPresent = 0; int iOptimisationCalcPenalties = 1; int savelog; int verbosity = 0; int asymmetricconnectivity = 0; string sVersionString = "Marxan v 4.0.6"; string sMarxanWebSite = "https://marxansolutions.org/"; string sTraceFileName; string sApplicationPathName; string savelogname; FILE* fsavelog; // init global structures sanneal anneal_global; vector<sconnections> connections; sfname fnames; vector<spu> SMGlobal; vector<spusporder> SMsporder; vector<spustuff> pu; map<int, int> PULookup, SPLookup; vector<sspecies> specGlobal, bestSpec; chrono::high_resolution_clock::time_point startTime; double rProbabilityWeighting = 1; double rStartDecThresh = 0.7, rEndDecThresh = 0.3, rStartDecMult = 3, rEndDecMult = 1; int fProb2D = 0, fProb1D = 0, fUserPenalties = 0; int fOptimiseConnectivityIn = 0; // number of the best solution int bestRun = 1; // score of the best solution double bestScore; // R vector of planning unit status for the best solution vector<int> bestR; // is marxan being called by another program? int marxanIsSecondary = 0; // runs the loop for each "solution" marxan is generating void executeRunLoop(long int repeats, int puno, int spno, double cm, int aggexist, double prop, int clumptype, double misslevel, string savename, double costthresh, double tpf1, double tpf2, int heurotype, srunoptions& runoptions, int itimptype, vector<int>& sumsoln, rng_engine& rngEngineGlobal) { string bestRunString; vector<string> summaries(repeats); // stores individual summaries for each run bestR.resize(puno); bestScore = DBL_MAX; bestSpec.resize(spno); // best species config // Locks for bestR and bestScore as it will be read/written by multiple threads omp_lock_t bestR_write_lock; omp_init_lock(&bestR_write_lock); // Locks for solution matrix append omp_lock_t solution_matrix_append_lock; omp_init_lock(&solution_matrix_append_lock); // Locks for sumsoln omp_lock_t solution_sum_lock; omp_init_lock(&solution_sum_lock); // for each repeat run int maxThreads = omp_get_max_threads(); printf("Running multithreaded over number of threads: %d\n", maxThreads); displayProgress1("Running multithreaded over number of threads: " + to_string(maxThreads) + "\n"); displayProgress1("Runs will be printed as they complete, and may not be in order due to parallelisation.\n"); //create seeds for local rng engines vector<unsigned int> seeds(repeats); for (int run_id = 1; run_id <= repeats; run_id++) seeds[run_id - 1] = rngEngineGlobal(); bool quitting_loop = false; #pragma omp parallel for schedule(dynamic) for (int run_id = 1; run_id <= repeats; run_id++) { if(quitting_loop) continue; //skipping iterations. It is not allowed to break or throw out omp for loop. // Create run specific structures int thread = omp_get_thread_num(); rng_engine rngEngine(seeds[run_id - 1]); string tempname2; stringstream appendLogBuffer; // stores the trace file log stringstream runConsoleOutput; // stores the console message for the run. This is needed for more organized printing output due to multithreading. sanneal anneal = anneal_global; scost reserve; scost change; vector<int> R(puno); vector<sspecies> spec = specGlobal; // make local copy of original spec vector<spu_out> SM_out; // make local copy output part of SMGlobal. //if (aggexist) SM_out.resize(SMGlobal.size()); appendLogBuffer << "\n Start run loop run " << run_id << endl; try { if (runoptions.ThermalAnnealingOn) { // Annealing Setup if (anneal.type == 2) { appendLogBuffer << "before initialiseConnollyAnnealing run " << run_id << endl; initialiseConnollyAnnealing(puno, spno, pu, connections, spec, SMGlobal, SM_out, cm, anneal, aggexist, R, prop, clumptype, run_id, appendLogBuffer, rngEngine); appendLogBuffer << "after initialiseConnollyAnnealing run " << run_id << endl; } if (anneal.type == 3) { appendLogBuffer << "before initialiseAdaptiveAnnealing run " << run_id << endl; initialiseAdaptiveAnnealing(puno, spno, prop, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, anneal, clumptype, appendLogBuffer, rngEngine); appendLogBuffer << "after initialiseAdaptiveAnnealing run " << run_id << endl; } if (verbosity > 1) runConsoleOutput << "\nRun " << run_id << ": Using Calculated Tinit = " << anneal.Tinit << " Tcool = " << anneal.Tcool << "\n"; anneal.temp = anneal.Tinit; } appendLogBuffer << "before computeReserveValue run " << run_id << endl; initialiseReserve(prop, pu, R, rngEngine); // Create Initial Reserve SpeciesAmounts(spno, puno, spec, pu, SMGlobal, R, clumptype); // Re-added this from v2.4 because spec amounts need to be refreshed when initializing if (aggexist) ClearClumps(spno, spec, pu, SMGlobal, SM_out); computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); appendLogBuffer << "after computeReserveValue run " << run_id << endl; if (verbosity > 1) { runConsoleOutput << "Run " << run_id << " Init: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } if (verbosity > 5) { displayTimePassed(startTime); } if (runoptions.ThermalAnnealingOn) { appendLogBuffer << "before thermalAnnealing run " << run_id << endl; thermalAnnealing(spno, puno, connections, R, cm, spec, pu, SMGlobal, SM_out, reserve, repeats, run_id, savename, misslevel, aggexist, costthresh, tpf1, tpf2, clumptype, anneal, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " ThermalAnnealing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after thermalAnnealing run " << run_id << endl; } if (runoptions.HillClimbingOn) { appendLogBuffer << "before hill climbing run " << run_id << endl; hill_climbing( puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, costthresh, tpf1, tpf2, clumptype, run_id, anneal.iterations, savename, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Hill climbing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after hill climbing run " << run_id << endl; } if (runoptions.TwoStepHillClimbingOn) { appendLogBuffer << "before two step hill climbing run " << run_id << endl; hill_climbing_two_steps( puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, costthresh, tpf1, tpf2, clumptype, run_id, anneal.iterations, savename, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Two Step Hill climbing: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after hill climbing run " << run_id << endl; } if (runoptions.HeuristicOn) { appendLogBuffer << "before Heuristics run " << run_id << endl; Heuristics(spno, puno, pu, connections, R, cm, spec, SMGlobal, SM_out, reserve, costthresh, tpf1, tpf2, heurotype, clumptype, appendLogBuffer, rngEngine); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Heuristic: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } appendLogBuffer << "after Heuristics run " << run_id << endl; } if (runoptions.ItImpOn) { appendLogBuffer << "before iterativeImprovement run " << run_id << endl; iterativeImprovement(puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, change, costthresh, tpf1, tpf2, clumptype, run_id, savename, appendLogBuffer, rngEngine); if (itimptype == 3) iterativeImprovement(puno, spno, pu, connections, spec, SMGlobal, SM_out, R, cm, reserve, change, costthresh, tpf1, tpf2, clumptype, run_id, savename, appendLogBuffer, rngEngine); appendLogBuffer << "after iterativeImprovement run " << run_id << endl; if (aggexist) ClearClumps(spno, spec, pu, SMGlobal, SM_out); if (verbosity > 1) { computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, reserve, clumptype, appendLogBuffer); runConsoleOutput << "Run " << run_id << " Iterative Improvement: " << displayValueForPUs(puno, spno, R, reserve, spec, misslevel).str(); } } // Activate Iterative Improvement appendLogBuffer << "before file output run " << run_id << endl; string fileNumber = utils::intToPaddedString(run_id, 5); if (fnames.saverun) { tempname2 = savename + "_r" + fileNumber + getFileNameSuffix(fnames.saverun); writeSolution(puno, R, pu, tempname2, fnames.saverun, fnames); } if (fnames.savespecies && fnames.saverun) { tempname2 = savename + "_mv" + fileNumber + getFileNameSuffix(fnames.savespecies); writeSpecies(spno, spec, tempname2, fnames.savespecies, misslevel); } if (fnames.savesum) { // summaries get stored and aggregated to prevent race conditions. summaries[run_id - 1] = computeSummary(puno, spno, R, spec, reserve, run_id, misslevel, fnames.savesum); } // Print results from run. displayProgress1(runConsoleOutput.str()); // compute and store objective function score for this reserve system computeReserveValue(puno, spno, R, pu, connections, SMGlobal, SM_out, cm, spec, aggexist, change, clumptype, appendLogBuffer); // remember the bestScore and bestRun if (change.total < bestScore) { omp_set_lock(&bestR_write_lock); // After locking, do another check in case bestScore has changed if (change.total < bestScore) { // this is best run so far bestScore = change.total; bestRun = run_id; // store bestR bestR = R; bestRunString = runConsoleOutput.str(); bestSpec = spec; // make a copy of best spec. } omp_unset_lock(&bestR_write_lock); } if (fnames.savesolutionsmatrix) { appendLogBuffer << "before appendSolutionsMatrix savename " << run_id << endl; tempname2 = savename + "_solutionsmatrix" + getFileNameSuffix(fnames.savesolutionsmatrix); omp_set_lock(&solution_matrix_append_lock); appendSolutionsMatrix(run_id, puno, R, tempname2, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders); omp_unset_lock(&solution_matrix_append_lock); appendLogBuffer << "after appendSolutionsMatrix savename " << run_id << endl; } // Save solution sum if (fnames.savesumsoln) { omp_set_lock(&solution_sum_lock); for (int k = 0; k < puno; k++) { if (R[k] == 1 || R[k] == 2) { sumsoln[k]++; } } omp_unset_lock(&solution_sum_lock); } if (aggexist) ClearClumps(spno, spec, pu, SMGlobal, SM_out); } catch (const exception& e) { // On exceptions, append exception to log file in addition to existing buffer. displayProgress1(runConsoleOutput.str()); appendLogBuffer << "Exception occurred on run " << run_id << ": " << e.what() << endl; displayProgress1(appendLogBuffer.str()); appendTraceFile(appendLogBuffer.str()); //cannot throw or break out of omp loop quitting_loop = true; continue; } appendLogBuffer << "after file output run " << run_id << endl; appendLogBuffer << "end run " << run_id << endl; appendTraceFile(appendLogBuffer.str()); if (marxanIsSecondary == 1) writeSecondarySyncFileRun(run_id); if (verbosity > 1) { stringstream done_message; done_message << "Run " << run_id << " is finished (out of " << repeats << "). "; #pragma omp critical { displayProgress1(done_message.str()); displayTimePassed(startTime); } } } if(quitting_loop) { displayProgress1("\nRuns were aborted due to error.\n"); throw runtime_error("Runs were aborted due to error.\n"); } // Write all summaries for each run. if (fnames.savesum) { string tempname2 = savename + "_sum" + getFileNameSuffix(fnames.savesum); writeSummary(tempname2, summaries, fnames.saverun); } stringstream bestOut; bestOut << "\nBest run: " << bestRun << " Best score: " << bestScore << "\n" << bestRunString; cout << bestOut.str(); displayProgress1(bestOut.str()); } // executeRunLoop int executeMarxan(string sInputFileName) { long int repeats; int puno, spno, gspno; double cm, prop; int heurotype, clumptype, itimptype; string savename, tempname2; double misslevel; int iseed = time(NULL), seedinit; int aggexist = 0, sepexist = 0; vector<int> R_CalcPenalties; vector<int> sumsoln; double costthresh, tpf1, tpf2; long int itemp; int isp; int maxThreads = omp_get_max_threads(); srunoptions runoptions; displayStartupMessage(); startTime = chrono::high_resolution_clock::now(); // set program start time. readInputOptions(cm, prop, anneal_global, iseed, repeats, savename, fnames, sInputFileName, runoptions, misslevel, heurotype, clumptype, itimptype, verbosity, costthresh, tpf1, tpf2); sTraceFileName = savename + "_TraceFile.txt"; createTraceFile(); appendTraceFile("%s begin execution\n\n", sVersionString.c_str()); appendTraceFile("LoadOptions\n"); #ifdef DEBUGCHECKCHANGE createDebugFile("debug_MarOpt_CheckChange.csv", "ipu,puid,R,total,cost,connection,penalty,threshpen,probability\n", fnames); #endif #ifdef DEBUGCHANGEPEN createDebugFile("debug_MarOpt_ChangePen.csv", "ipu,puid,isp,spid,penalty,target,targetocc,occurrence,sepnum,amount,newamount,fractionAmount\n", fnames); #endif #ifdef DEBUGCALCPENALTIES createDebugFile("debug_MarZone_CalcPenalties.csv", "\n", fnames); #endif if (fnames.savelog) { tempname2 = savename + "_log.dat"; createLogFile(fnames.savelog, tempname2); } delta = 1e-14; // This would more elegantly be done as a constant // init rng engine rng_engine rngEngine(iseed); RandSeed1 = iseed; seedinit = iseed; appendTraceFile("RandSeed iseed %i RandSeed1 %li\n", iseed, RandSeed1); // read the data files displayProgress1("\nEntering in the data files \n"); displayProgress3(" Reading in the Planning Unit names \n"); appendTraceFile("before readPlanningUnits\n"); itemp = readPlanningUnits(puno, pu, fnames); appendTraceFile("after readPlanningUnits\n"); if (iProbFieldPresent == 1) appendTraceFile("prob field present\n"); else appendTraceFile("prob field not present\n"); #ifdef DEBUG_PROB1D if (iProbFieldPresent == 1) writeProbData(puno, pu, fnames); #endif displayProgress1(" There are %i Planning units.\n %i Planning Unit names read in \n", puno, itemp); displayProgress3(" Reading in the species file \n"); appendTraceFile("before readSpecies\n"); itemp = readSpecies(spno, specGlobal, fnames); appendTraceFile("after readSpecies\n"); displayProgress1(" %i species read in \n", itemp); appendTraceFile("before build search arrays\n"); // create the fast lookup tables for planning units and species names populateLookupTables(puno, spno, pu, specGlobal, PULookup, SPLookup); appendTraceFile("after build search arrays\n"); if (fnames.savesumsoln) sumsoln.resize(puno); connections.resize(puno); displayProgress3(" Reading in the Connection file :\n"); itemp = 0; if (!fnames.connectionname.empty()) { appendTraceFile("before readConnections\n"); if (!fnames.connectionfilesname.empty()) writeWeightedConnectivityFile(fnames); itemp = readConnections(puno, connections, pu, PULookup, fnames); appendTraceFile("after readConnections\n"); if (asymmetricconnectivity) { appendTraceFile("Asymmetric connectivity is on.\n"); writeAsymmetricConnectionFile(puno, connections, pu, fnames); } if (fOptimiseConnectivityIn) appendTraceFile("Optimising 'Connectivity In'.\n"); } displayProgress1(" %i connections entered \n", itemp); if (asymmetricconnectivity) displayProgress1(" Asymmetric connectivity is on.\n"); if (fOptimiseConnectivityIn) displayProgress1(" Optimising 'Connectivity In'.\n"); displayProgress3(" Reading in the Planning Unit versus Species File \n"); appendTraceFile("before readSparseMatrix\n"); readSparseMatrix(SMGlobal, puno, spno, pu, PULookup, SPLookup, fnames); appendTraceFile("after readSparseMatrix\n"); if (fProb2D == 1) appendTraceFile("Prob2D is on\n"); else appendTraceFile("Prob2D is off\n"); #ifdef DEBUG_PROB2D writeSparseMatrix(iSparseMatrixFileLength, puno, pu, spec, SM, fnames); #endif if (fnames.saverichness) { tempname2 = savename + "_richness" + getFileNameSuffix(fnames.saverichness); writeRichness(puno, pu, tempname2, fnames.saverichness); } if (!fnames.matrixspordername.empty()) { appendTraceFile("before readSparseMatrixSpOrder\n"); displayWarningMessage("input.dat option: MATRIXSPORDERNAME is no longer needed, however the supplied file will still be read and processed. Please refer to the version 4 feature changelog.md."); readSparseMatrixSpOrder(SMsporder, puno, spno, PULookup, SPLookup, specGlobal, fnames); appendTraceFile("after readSparseMatrixSpOrder\n"); } appendTraceFile("before process block definitions\n"); if (!fnames.blockdefname.empty()) { displayProgress1(" Reading in the Block Definition File \n"); vector<sgenspec> gspec; // declare within this scope of usage readSpeciesBlockDefinition(gspno, gspec, fnames); setBlockDefinitions(gspno, spno, puno, gspec, specGlobal, pu, SMGlobal); } setDefaultTargets(specGlobal); appendTraceFile("after process block definitions\n"); appendTraceFile("before computeTotalAreas\n"); computeTotalAreas(puno, spno, pu, specGlobal, SMGlobal); appendTraceFile("after computeTotalAreas\n"); if (fnames.savetotalareas) { tempname2 = savename + "totalareas" + getFileNameSuffix(fnames.savetotalareas); writeTotalAreas(puno, spno, pu, specGlobal, SMGlobal, tempname2, fnames.savepenalty); } if (fSpecPROPLoaded > 0) { appendTraceFile("before computeSpecProp\n"); // species have prop value specified computeSpecProp(spno, specGlobal, puno, pu, SMGlobal); appendTraceFile("after computeSpecProp\n"); } displayProgress2("Checking to see if there are aggregating or separating species.\n"); for (isp = 0; isp < spno; isp++) { if (specGlobal[isp].target2 > 0) aggexist = 1; if (specGlobal[isp].sepdistance > 0) sepexist = 1; } if (fnames.savesen) { appendTraceFile("before writeScenario\n"); tempname2 = savename + "_sen.dat"; writeScenario(puno, spno, prop, cm, anneal_global, seedinit, repeats, clumptype, runoptions, heurotype, costthresh, tpf1, tpf2, tempname2); appendTraceFile("after writeScenario\n"); } if (verbosity > 1) displayTimePassed(startTime); // ******* Pre-processing ************ displayProgress1("\nPre-processing Section. \n"); displayProgress2(" Calculating all the penalties \n"); R_CalcPenalties.resize(puno); // load penalties from file if they are present if (!fnames.penaltyname.empty()) { fUserPenalties = 1; appendTraceFile("before readPenalties\n"); readPenalties(specGlobal, spno, fnames, SPLookup); appendTraceFile("after readPenalties\n"); } if (runoptions.CalcPenaltiesOn == 0) { // if penalties have not been loaded, then stop error message if (fUserPenalties == 0) { appendTraceFile("Data error: CalcPenalties off but no PENALTYNAME specified, exiting.\n"); displayProgress1("Data error: CalcPenalties off but no PENALTYNAME specified, exiting.\n"); exit(EXIT_FAILURE); } // transfer loaded penalties to correct data structrure applyUserPenalties(specGlobal); } else { vector<spu_out> SM_out; // make local copy output part of SMGlobal. //if (aggexist) SM_out.resize(SMGlobal.size()); // we are computing penalties if (fnames.matrixspordername.empty()) { appendTraceFile("before CalcPenalties\n"); // we don't have sporder matrix available, so use slow CalcPenalties method itemp = computePenalties(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, R_CalcPenalties, aggexist, cm, clumptype, rngEngine); appendTraceFile("after CalcPenalties\n"); } else { // we have sporder matrix available, so use optimised CalcPenalties method if (iOptimisationCalcPenalties == 1) { appendTraceFile("before CalcPenaltiesOptimise\n"); itemp = computePenaltiesOptimise(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, SMsporder, R_CalcPenalties, aggexist, cm, clumptype, rngEngine); appendTraceFile("after CalcPenaltiesOptimise\n"); } else { appendTraceFile("before CalcPenalties\n"); // we have optimise calc penalties switched off, so use slow CalcPenalties method itemp = computePenalties(puno, spno, pu, specGlobal, connections, SMGlobal, SM_out, R_CalcPenalties, aggexist, cm, clumptype, rngEngine); appendTraceFile("after CalcPenalties\n"); } } } if (itemp > 0) displayProgress("%d species cannot meet target%c.\n", itemp, itemp == 1 ? ' ' : 's'); if (runoptions.ThermalAnnealingOn) { displayProgress2(" Calculating temperatures.\n"); if (!anneal_global.Titns) displayErrorMessage("Initial Temperature is set to zero. Fatal Error \n"); anneal_global.Tlen = anneal_global.iterations / anneal_global.Titns; displayProgress2(" Temperature length %ld \n", anneal_global.Tlen); displayProgress2(" iterations %lld, repeats %ld \n", anneal_global.iterations, repeats); } // Annealing Preprocessing. Should be moved to SetAnnealingOptions if (fnames.savepenalty) { tempname2 = savename + "_penalty" + getFileNameSuffix(fnames.savepenalty); writePenalty(spno, specGlobal, tempname2, fnames.savepenalty); tempname2 = savename + "_penalty_planning_units" + getFileNameSuffix(fnames.savepenalty); writePenaltyPlanningUnits(puno, pu, R_CalcPenalties, tempname2, fnames.savepenalty); } //free(R_CalcPenalties); if (fnames.savespec) { tempname2 = savename + "_spec.csv"; writeSpec(spno, specGlobal, tempname2); } if (fnames.savepu) { tempname2 = savename + "_pu.csv"; writePu(puno, pu, tempname2); } // If we are in a runmode with only CalcPenalties, we stop/exit here gracefully because we are finished. if (runoptions.HeuristicOn == 0 && runoptions.ThermalAnnealingOn == 0 && runoptions.HillClimbingOn == 0 && runoptions.ItImpOn == 0 && runoptions.TwoStepHillClimbingOn == 0) { appendTraceFile("end final file output\n"); appendTraceFile("\nMarxan end execution\n"); displayShutdownMessage(startTime); if (marxanIsSecondary == 1) secondaryExit(); exit(EXIT_FAILURE); } if (fnames.savesolutionsmatrix) { tempname2 = savename + "_solutionsmatrix" + getFileNameSuffix(fnames.savesolutionsmatrix); #ifdef DEBUG_CLUSTERANALYSIS appendTraceFile("before createSolutionsMatrix savename %s\n", savename); #endif createSolutionsMatrix(puno, pu, tempname2, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders); #ifdef DEBUG_CLUSTERANALYSIS appendTraceFile("after createSolutionsMatrix savename %s\n", savename); #endif } if (fProb1D == 1) { tempname2 = savename + "_ComputeP_AllPUsSelected_1D.csv"; ComputeP_AllPUsSelected_1D(tempname2, puno, spno, pu, SMGlobal, specGlobal); } if (fProb2D == 1) { tempname2 = savename + "_ComputeP_AllPUsSelected_2D.csv"; ComputeP_AllPUsSelected_2D(tempname2, puno, spno, pu, SMGlobal, specGlobal); } try { executeRunLoop(repeats, puno, spno, cm, aggexist, prop, clumptype, misslevel, savename, costthresh, tpf1, tpf2, heurotype, runoptions, itimptype, sumsoln, rngEngine); } catch (const exception& e) { appendTraceFile("Error during main loop.\n"); exit(EXIT_FAILURE); } appendTraceFile("before final file output\n"); if (fnames.savebest) { tempname2 = savename + "_best" + getFileNameSuffix(fnames.savebest); writeSolution(puno, bestR, pu, tempname2, fnames.savebest, fnames); appendTraceFile("Best solution is run %i\n", bestRun); displayProgress1("\nBest solution is run %i\n", bestRun); } if (fnames.savespecies && fnames.savebest) { tempname2 = savename + "_mvbest" + getFileNameSuffix(fnames.savespecies); // TODO ADBAI - need to write best spec, NOT spec_global writeSpecies(spno, bestSpec, tempname2, fnames.savespecies, misslevel); } if (fnames.savesumsoln) { tempname2 = savename + "_ssoln" + getFileNameSuffix(fnames.savesumsoln); writeSumSoln(puno, sumsoln, pu, tempname2, fnames.savesumsoln); } if (fnames.savesolutionsmatrix) { if (fnames.rexecutescript) { if (marxanIsSecondary == 1) secondaryExit(); } } displayShutdownMessage(startTime); appendTraceFile("end final file output\n"); appendTraceFile("\nMarxan end execution. Press any key to continue\n"); return 0; } // executeMarxan // handle command line parameters for the marxan executable void handleOptions(int argc, char* argv[], string& sInputFileName, int& marxanIsSecondary) { if (argc > 4) { // if more than one commandline argument then exit displayUsage(argv[0]); exit(1); } for (int i = 1; i < argc; i++) { // Deal with all arguments if (argv[i][0] == '/' || argv[i][0] == '-') { switch (argv[i][1]) { case 'C': case 'c': case 'S': case 's': marxanIsSecondary = 1; break; default: fprintf(stderr, "unknown option %s\n", argv[i]); break; } } else { sInputFileName = argv[i]; /* If not a -option then must be input.dat name */ } } } // marxan is running as a secondary process and has finished. create a sync file so the calling software will know marxan has finished creating the output files // secondaryExit does not deliver a message prior to exiting, but creates a file so C-Plan/Zonae Cogito/etc knows marxan has exited void secondaryExit(void) { writeSecondarySyncFile(); } } // namespace marxan // main needs to be defined outside of namespace int main(int argc, char* argv[]) { std::string sInputFileName = "input.dat"; // store application name marxan::sApplicationPathName = argv[0]; if (argc > 1) { // handle the program options marxan::handleOptions(argc, argv, sInputFileName, marxan::marxanIsSecondary); } try { if (marxan::executeMarxan(sInputFileName)) // Calls the main annealing unit { if (marxan::marxanIsSecondary == 1) { marxan::secondaryExit(); } return 1; } // Abnormal Exit } catch(const std::exception& e) { std::cerr << "Error during Marxan execution." << '\n'; exit(EXIT_FAILURE); } if (marxan::marxanIsSecondary == 1) { marxan::secondaryExit(); } return 0; }
38.715084
206
0.579711
hotzevzl
7829431a53fb619a77d9d90b26c090cf99083836
8,699
cpp
C++
HUST_ComputerNetworks_Labs/lab8/myping/myping.cpp
HoverWings/IOTCommunicationTechnologyLabs
376866db63086ddce39aae0d492cc6e95f3df1c1
[ "MIT" ]
1
2019-01-13T06:35:06.000Z
2019-01-13T06:35:06.000Z
HUST_ComputerNetworks_Labs/lab8/myping/myping.cpp
HoverWings/IOTCommunicationTechnologyLabs
376866db63086ddce39aae0d492cc6e95f3df1c1
[ "MIT" ]
null
null
null
HUST_ComputerNetworks_Labs/lab8/myping/myping.cpp
HoverWings/IOTCommunicationTechnologyLabs
376866db63086ddce39aae0d492cc6e95f3df1c1
[ "MIT" ]
1
2019-11-29T14:04:22.000Z
2019-11-29T14:04:22.000Z
/* FileName: myping.cpp * Author: Hover * E-Mail: hover@hust.edu.cn * GitHub: HoverWings * Description: the Hover's impletation of ping * Attention: you may need sudo to run this code */ #include <cstdio> #include <iostream> #include <algorithm> #include <iomanip> #include <vector> #include <getopt.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/time.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <netdb.h> #include <setjmp.h> #include <errno.h> using namespace std; #define MAX_WAIT_TIME 5 #define PACKET_SIZE 4096 int max_no_packets=5; int interval=1; char sendpacket[PACKET_SIZE]; char recvpacket[PACKET_SIZE]; pid_t pid; int sockfd; int datalen = 56; int nsend = 0; int nreceived = 0; struct sockaddr_in dest_addr; struct sockaddr_in from_addr; struct timeval tvrecv; vector<double> rtt_vec; void statistics(int signo); unsigned short cal_chksum(unsigned short *addr,int len); int pack(int pack_no); void send_packet(void); void recv_packet(void); int unpack(char *buf,int len); void timediff(struct timeval *out,struct timeval *in); bool opt_t = false; // set ttl bool opt_i = false; // interval void Stop(int signo) { statistics(signo); _exit(0); } int main(int argc,char *argv[]) { signal(SIGINT, Stop); //set exit function char opt; int option_index = 0; static struct option long_options[] = { {"help", no_argument, NULL, 'h'} }; char str[256]; strcpy(str,argv[1]); while ((opt = getopt_long(argc, argv, "t:i:h", long_options, &option_index)) != -1) { //printf("%c",opt); //cout<<argv[optind - 1]; switch (opt) { case 't': max_no_packets=atoi(argv[optind - 1]); opt_t = true; break; case 'i': interval==atoi(argv[optind - 1]); opt_i = true; break; case 'h': opt_i = true; break; } } struct hostent *host; //host entry struct protoent *protocol; unsigned long inaddr = 0l; int size = 50*1024; //50k if(argc < 2) { printf("use : %s hostname/IP address \n", argv[0]); exit(1); } if((protocol = getprotobyname("icmp")) == NULL) { perror("getprotobyname"); exit(1); } // setuid(getpid()); // need root to create socket if((sockfd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0){ perror("socket error"); exit(1); } setuid(getuid()); // recycle root privilage // case: broadcast address then there will be a lot of reply // so the buf need enough size setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size) ); bzero(&dest_addr, sizeof(dest_addr)); dest_addr.sin_family = AF_INET; // domain or address judge printf("%s",str); if((inaddr=inet_addr(str)) == INADDR_NONE) { if((host = gethostbyname(str)) == NULL) { perror("gethostbyname error"); exit(1); } memcpy((char*)&dest_addr.sin_addr, host->h_addr, host->h_length); } else { memcpy((char*)&dest_addr.sin_addr, (char*)&inaddr, sizeof(inaddr)); } pid = getpid(); printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1], inet_ntoa(dest_addr.sin_addr), datalen); send_packet(); statistics(SIGALRM); return 0; } void statistics(int signo) { printf("\n--------------------PING statistics-------------------\n"); printf("%d packets transmitted, %d received , %%%d lost\n",nsend, nreceived, (nsend-nreceived)/nsend*100); printf("rtt min/avg/max/mdev = "); sort(rtt_vec.begin(), rtt_vec.end()); double min=rtt_vec.front(); double max=rtt_vec[rtt_vec.size()-1]; double total; for(vector<double>::iterator iter=rtt_vec.begin();iter!=rtt_vec.end();iter++) { // cout << (*iter) << endl; total+=*iter; } double avg=total/nsend; double mdev=max-min; cout<<fixed<<setprecision(3) <<min<<"/"<<avg<<"/"<<max<<"/"<<mdev<<"ms"<<endl; close(sockfd); exit(1); } /* I: addr: check data buffer check data len(byte) */ unsigned short cal_chksum(unsigned short *addr,int len) { int sum=0; int nleft = len; unsigned short *w = addr; unsigned short answer = 0; while(nleft > 1) { sum += *w++; nleft -= 2; } //if the ICMP head len is odd, then the final data is high bit and add it if(nleft == 1) { *(unsigned char *)(&answer) = *(unsigned char *)w; sum += answer; //transfer answer to int } sum = (sum >> 16) + (sum & 0xffff); // add high bit and low bit sum += (sum >> 16); // add overflow answer = ~sum; // 16 bit checksum return answer; } /* I: icmp struct sequence O: packed icmp */ int pack(int pack_no) { int packsize; struct icmp *icmp; struct timeval *tval; icmp = (struct icmp*)sendpacket; icmp->icmp_type = ICMP_ECHO; // type of service icmp->icmp_code = 0; icmp->icmp_cksum = 0; icmp->icmp_seq = pack_no; icmp->icmp_id = pid; packsize = 8 + datalen; //64=8(head)+56 tval = (struct timeval *)icmp->icmp_data; // 获得icmp结构中最后的数据部分的指针 gettimeofday(tval, NULL); // 将发送的时间填入icmp结构中最后的数据部分 icmp->icmp_cksum = cal_chksum((unsigned short *)icmp, packsize);/*填充发送方的校验和*/ return packsize; } void send_packet() { int packetsize; while(nsend < max_no_packets) { nsend++; packetsize = pack(nsend); // set ICMP message head if(sendto(sockfd, sendpacket, packetsize, 0,(struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0) { perror("sendto error"); continue; } recv_packet(); sleep((uint)interval); } } void recv_packet() { int n; extern int errno; signal(SIGALRM,statistics); int from_len = sizeof(from_addr); while(nreceived < nsend) { alarm(MAX_WAIT_TIME); if((n = recvfrom(sockfd, recvpacket, sizeof(recvpacket), 0,(struct sockaddr *)&from_addr, (socklen_t *)&from_len)) < 0) { if(errno == EINTR) { continue; } perror("recvfrom error"); continue; } gettimeofday(&tvrecv, NULL); // get receive time if(unpack(recvpacket, n) == -1) continue; nreceived++; } } /* I:buf IP buf len IP message len addr ICMP dest address O:error code */ int unpack(char *buf, int len) { int iphdrlen; struct ip *ip; struct icmp *icmp; struct timeval *tvsend; double rtt; ip = (struct ip *)buf; iphdrlen = ip->ip_hl << 2; //ip head len icmp = (struct icmp *)(buf + iphdrlen); // seek to IP message len -= iphdrlen; if(len < 8) // less than ICMP head len { printf("ICMP packets\'s length is less than 8\n"); return -1; } // check ICMP reply if((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == pid)) { tvsend = (struct timeval *)icmp->icmp_data; timediff(&tvrecv, tvsend); rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0; rtt_vec.push_back(rtt); printf("%d byte from %s: icmp_seq=%u ttl=%d time=%.3f ms\n", len, // total message len inet_ntoa(from_addr.sin_addr), icmp->icmp_seq, ip->ip_ttl, rtt); //ms rtt return 0; } else return -1; } /* I:begin_time endtime O:ms diff */ void timediff(struct timeval *recv, struct timeval *send) { if((recv->tv_usec -= send->tv_usec) < 0) { --recv->tv_sec; recv->tv_usec += 1000000; } recv->tv_sec -= send->tv_sec; }
26.440729
127
0.528911
HoverWings
782cd72175b8921fa2cb51cff5fb26574814e471
748
hpp
C++
src/Core/External/unsw/unsw/motion/generator/ClippedGenerator.hpp
pedrohsreis/boulos
a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e
[ "MIT" ]
3
2018-09-18T18:05:05.000Z
2019-10-23T17:47:07.000Z
src/Core/External/unsw/unsw/motion/generator/ClippedGenerator.hpp
pedrohsreis/boulos
a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e
[ "MIT" ]
1
2020-06-08T18:48:32.000Z
2020-06-19T21:41:16.000Z
src/Core/External/unsw/unsw/motion/generator/ClippedGenerator.hpp
pedrohsreis/boulos
a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e
[ "MIT" ]
9
2018-09-11T17:19:16.000Z
2019-07-30T16:43:56.000Z
#pragma once #include "motion/generator/Generator.hpp" class ClippedGenerator : Generator { public: explicit ClippedGenerator(Generator* g); ~ClippedGenerator(); virtual JointValues makeJoints(ActionCommand::All* request, Odometry* odometry, const SensorValues &sensors, BodyModel &bodyModel, float ballX, float ballY); virtual bool isActive(); void reset(); void readOptions(const boost::program_options::variables_map &config); private: Generator* generator; JointValues old_j; bool old_exists; };
31.166667
76
0.536096
pedrohsreis
782d226c5d26f8f1df931900d2cc9c874fc226bb
318
cpp
C++
Diameter Of Binary Tree .cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Diameter Of Binary Tree .cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
1
2021-10-01T18:00:09.000Z
2021-10-01T18:00:09.000Z
Diameter Of Binary Tree .cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
int diameterOfBinaryTree(TreeNode* root) { int d=0; rec(root, d); return d; } int rec(TreeNode* root, int &d) { if(root == NULL) return 0; int ld = rec(root->left, d); int rd = rec(root->right, d); d=max(d,ld+rd); return max(ld,rd)+1; }
22.714286
42
0.477987
Subhash3
782d63ef335a860c41b2b6f0ba060154c0ab87d0
3,456
cpp
C++
src/maiken/app.cpp
PhilipDeegan/mkn
399dd01990e130c4deeb0c2800204836d3875ae9
[ "BSD-3-Clause" ]
3
2019-02-07T20:50:36.000Z
2019-08-05T19:22:59.000Z
src/maiken/app.cpp
mkn/mkn
a05b542497270def02200df6620804b89429259b
[ "BSD-3-Clause" ]
null
null
null
src/maiken/app.cpp
mkn/mkn
a05b542497270def02200df6620804b89429259b
[ "BSD-3-Clause" ]
null
null
null
/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "maiken/app.hpp" #include "maiken/env.hpp" maiken::Application* maiken::Applications::getOrCreate(maiken::Project const& proj, std::string const& _profile, bool setup) KTHROW(mkn::kul::Exception) { std::string pDir(proj.dir().real()); std::string profile = _profile.empty() ? "@" : _profile; if (!m_apps.count(pDir) || !m_apps[pDir].count(profile)) { auto app = std::make_unique<Application>(proj, _profile); auto pp = app.get(); m_appPs.push_back(std::move(app)); m_apps[pDir][profile] = pp; if (setup) { mkn::kul::os::PushDir pushd(proj.dir()); pp->setup(); } } return m_apps[pDir][profile]; } maiken::Application* maiken::Applications::getOrCreateRoot(maiken::Project const& proj, std::string const& _profile, bool setup) KTHROW(mkn::kul::Exception) { std::string pDir(proj.dir().real()); std::string profile = _profile.empty() ? "@" : _profile; if (!m_apps.count(pDir) || !m_apps[pDir].count(profile)) { auto* pp = getOrCreate(proj, _profile, /*setup = */ false); pp->ro = 1; if (setup) { mkn::kul::os::PushDir pushd(proj.dir()); pp->setup(); } } return m_apps[pDir][profile]; } maiken::Application* maiken::Applications::getOrNullptr(std::string const& project) { uint32_t count = 0; Application* app = nullptr; for (auto const& p1 : m_apps) for (auto const& p2 : p1.second) { if (p2.second->project().root()[STR_NAME].Scalar() == project) { count++; app = p2.second; } } if (count > 1) { KEXIT(1, "Cannot deduce project version as") << " there are multiple versions in the dependency tree"; } return app; } mkn::kul::cli::EnvVar maiken::Application::PARSE_ENV_NODE(YAML::Node const& n, Application const& app) { return maiken::PARSE_ENV_NODE(n, app, app.project().file()); }
37.978022
104
0.688079
PhilipDeegan
782e5d07868a1bc4f1ef192aa6941837cf8123f8
114
hpp
C++
Music/OnMei/Pitch/OnDo/a_Alias.hpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
2
2020-09-13T07:31:22.000Z
2022-03-26T08:37:32.000Z
Music/OnMei/Pitch/OnDo/a_Alias.hpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
Music/OnMei/Pitch/OnDo/a_Alias.hpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
// c:/Users/user/Documents/Programming/Music/OnMei/Pitch/OnDo/a_Alias.hpp #pragma once using DoSuu = uint;
19
74
0.72807
p-adic
783255735e65bcabcc634f0512064bc0808cbecf
4,323
cpp
C++
src/vecmath/cross_product.cpp
dogesoulseller/weirdlib
35d3be8a7621890e6870a48f3839f00b87d5ced9
[ "MIT" ]
null
null
null
src/vecmath/cross_product.cpp
dogesoulseller/weirdlib
35d3be8a7621890e6870a48f3839f00b87d5ced9
[ "MIT" ]
null
null
null
src/vecmath/cross_product.cpp
dogesoulseller/weirdlib
35d3be8a7621890e6870a48f3839f00b87d5ced9
[ "MIT" ]
null
null
null
#ifdef WEIRDLIB_ENABLE_VECTOR_MATH #include "../../include/weirdlib_vecmath.hpp" #include "../../include/cpu_detection.hpp" #include "../../include/weirdlib_simdhelper.hpp" #include <array> namespace wlib::vecmath { #if X86_SIMD_LEVEL >= LV_AVX2 static const auto PERM_MASK_CROSSP_LHS = _mm256_set_epi32(0, 0, 1, 0, 2, 0, 2, 1); static const auto PERM_MASK_CROSSP_RHS = _mm256_set_epi32(0, 0, 0, 2, 1, 1, 0, 2); static const auto PERM_MASK_CROSSP_SUB = _mm256_set_epi32(0, 0, 5, 2, 4, 1, 3, 0); #endif Vector3<float> CrossProduct(const Vector3<float>& lhs, const Vector3<float>& rhs) { #if X86_SIMD_LEVEL >= LV_AVX2 auto lhs_vec = _mm256_loadu_ps(&lhs.x); auto rhs_vec = _mm256_loadu_ps(&rhs.x); auto lhs_yzxzxy = _mm256_permutevar8x32_ps(lhs_vec, PERM_MASK_CROSSP_LHS); auto rhs_zxyyzx = _mm256_permutevar8x32_ps(rhs_vec, PERM_MASK_CROSSP_RHS); auto product = _mm256_mul_ps(lhs_yzxzxy, rhs_zxyyzx); // Set up for subtraction auto prod_hsub = _mm256_permutevar8x32_ps(product, PERM_MASK_CROSSP_SUB); auto result = _mm256_hsub_ps(prod_hsub, prod_hsub); alignas(32) std::array<float, 8> outvec; _mm256_store_ps(outvec.data(), result); return Vector3(outvec[0], outvec[1], outvec[4]); #elif X86_SIMD_LEVEL >= LV_SSE auto lhs_vec = _mm_loadu_ps(&lhs.x); auto rhs_vec = _mm_loadu_ps(&rhs.x); auto lhs_yzx = _mm_shuffle_ps(lhs_vec, lhs_vec, _MM_SHUFFLE(0, 0, 2, 1)); auto lhs_zxy = _mm_shuffle_ps(lhs_vec, lhs_vec, _MM_SHUFFLE(0, 1, 0, 2)); auto rhs_zxy = _mm_shuffle_ps(rhs_vec, rhs_vec, _MM_SHUFFLE(0, 1, 0, 2)); auto rhs_yzx = _mm_shuffle_ps(rhs_vec, rhs_vec, _MM_SHUFFLE(0, 0, 2, 1)); auto left_side = _mm_mul_ps(lhs_yzx, rhs_zxy); auto right_side = _mm_mul_ps(lhs_zxy, rhs_yzx); auto result = _mm_sub_ps(left_side, right_side); alignas(16) std::array<float, 4> outvec; _mm_store_ps(outvec.data(), result); return Vector3(outvec[0], outvec[1], outvec[2]); #else float x = (lhs.y * rhs.z) - (lhs.z * rhs.y); float y = (lhs.z * rhs.x) - (lhs.x * rhs.z); float z = (lhs.x * rhs.y) - (lhs.y * rhs.x); return Vector3(x, y, z); #endif } Vector3<double> CrossProduct(const Vector3<double>& lhs, const Vector3<double>& rhs) { #if X86_SIMD_LEVEL >= LV_AVX2 auto lhs_vec = _mm256_loadu_pd(&lhs.x); auto rhs_vec = _mm256_loadu_pd(&rhs.x); auto lhs_yzx = _mm256_permute4x64_pd(lhs_vec, 0b00001001); auto lhs_zxy = _mm256_permute4x64_pd(lhs_vec, 0b00010010); auto rhs_yzx = _mm256_permute4x64_pd(rhs_vec, 0b00001001); auto rhs_zxy = _mm256_permute4x64_pd(rhs_vec, 0b00010010); auto left_side = _mm256_mul_pd(lhs_yzx, rhs_zxy); auto right_side = _mm256_mul_pd(lhs_zxy, rhs_yzx); auto result = _mm256_sub_pd(left_side, right_side); alignas(32) std::array<double, 4> outvec; _mm256_store_pd(outvec.data(), result); return Vector3(outvec[0], outvec[1], outvec[2]); #elif X86_SIMD_LEVEL >= LV_SSE2 auto lhs_vec_xy = _mm_loadu_pd(&lhs.x); auto lhs_vec_z_ = _mm_loadu_pd(&lhs.z); auto rhs_vec_xy = _mm_loadu_pd(&rhs.x); auto rhs_vec_z_ = _mm_loadu_pd(&rhs.z); auto lhs_yz = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_z_, 0b00000001); auto lhs_zx = _mm_shuffle_pd(lhs_vec_z_, lhs_vec_xy, 0b00000000); auto lhs_x_ = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_xy, 0b00000000); auto lhs_y_ = _mm_shuffle_pd(lhs_vec_xy, lhs_vec_xy, 0b00000001); auto rhs_yz = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_z_, 0b00000001); auto rhs_zx = _mm_shuffle_pd(rhs_vec_z_, rhs_vec_xy, 0b00000000); auto rhs_x_ = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_xy, 0b00000000); auto rhs_y_ = _mm_shuffle_pd(rhs_vec_xy, rhs_vec_xy, 0b00000001); auto l0 = _mm_mul_pd(lhs_yz, rhs_zx); auto r0 = _mm_mul_pd(lhs_zx, rhs_yz); auto l1 = _mm_mul_pd(lhs_x_, rhs_y_); auto r1 = _mm_mul_pd(lhs_y_, rhs_x_); auto result0 = _mm_sub_pd(l0, r0); auto result1 = _mm_sub_pd(l1, r1); alignas(16) std::array<double, 4> outvec; _mm_store_pd(outvec.data(), result0); _mm_store_pd(outvec.data()+2, result1); return Vector3(outvec[0], outvec[1], outvec[2]); #else double x = (lhs.y * rhs.z) - (lhs.z * rhs.y); double y = (lhs.z * rhs.x) - (lhs.x * rhs.z); double z = (lhs.x * rhs.y) - (lhs.y * rhs.x); return Vector3(x, y, z); #endif } } // namespace wlib::vecmath #endif
36.025
87
0.703909
dogesoulseller
783a5175903571c1c754e056cd78e2084ce1d2d1
6,497
cpp
C++
Nacro/SDK/FN_GAB_AthenaDBNO_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_GAB_AthenaDBNO_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_GAB_AthenaDBNO_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.GetInitialHealAmount // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // float Health (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UGAB_AthenaDBNO_C::GetInitialHealAmount(float* Health) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.GetInitialHealAmount"); UGAB_AthenaDBNO_C_GetInitialHealAmount_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Health != nullptr) *Health = params.Health; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.InitializeDeathHitDirection // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGameplayEventData EventHitData (Parm) void UGAB_AthenaDBNO_C::InitializeDeathHitDirection(const struct FGameplayEventData& EventHitData) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.InitializeDeathHitDirection"); UGAB_AthenaDBNO_C_InitializeDeathHitDirection_Params params; params.EventHitData = EventHitData; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCancelled_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnCancelled_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCancelled_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnCancelled_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnInterrupted_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnInterrupted_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnInterrupted_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnInterrupted_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnBlendOut_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnBlendOut_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnBlendOut_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnBlendOut_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCompleted_F0F6785443BD2E74F5591884CB19F35F // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnCompleted_F0F6785443BD2E74F5591884CB19F35F() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnCompleted_F0F6785443BD2E74F5591884CB19F35F"); UGAB_AthenaDBNO_C_OnCompleted_F0F6785443BD2E74F5591884CB19F35F_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6 // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6"); UGAB_AthenaDBNO_C_OnStateInterrupted_C85094F843D5075FE4872C95AFC5D6B6_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6 // (BlueprintCallable, BlueprintEvent) void UGAB_AthenaDBNO_C::OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6"); UGAB_AthenaDBNO_C_OnStateEnded_C85094F843D5075FE4872C95AFC5D6B6_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_ActivateAbilityFromEvent // (Event, Protected, HasOutParms, BlueprintEvent) // Parameters: // struct FGameplayEventData* EventData (ConstParm, Parm, OutParm, ReferenceParm) void UGAB_AthenaDBNO_C::K2_ActivateAbilityFromEvent(struct FGameplayEventData* EventData) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_ActivateAbilityFromEvent"); UGAB_AthenaDBNO_C_K2_ActivateAbilityFromEvent_Params params; params.EventData = EventData; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_OnEndAbility // (Event, Protected, BlueprintEvent) void UGAB_AthenaDBNO_C::K2_OnEndAbility() { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.K2_OnEndAbility"); UGAB_AthenaDBNO_C_K2_OnEndAbility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.ExecuteUbergraph_GAB_AthenaDBNO // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UGAB_AthenaDBNO_C::ExecuteUbergraph_GAB_AthenaDBNO(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function GAB_AthenaDBNO.GAB_AthenaDBNO_C.ExecuteUbergraph_GAB_AthenaDBNO"); UGAB_AthenaDBNO_C_ExecuteUbergraph_GAB_AthenaDBNO_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.39819
145
0.785901
Milxnor
78432ee9cf1d62b320b491645d09370833fcc2f4
16,513
cpp
C++
src/Parameters.cpp
MikeHeiber/Ising_OPV
6a108675bdee1847abee0273b7874d9d312b048e
[ "MIT" ]
8
2015-10-26T22:27:51.000Z
2021-09-01T19:40:29.000Z
src/Parameters.cpp
MikeHeiber/Ising_OPV
6a108675bdee1847abee0273b7874d9d312b048e
[ "MIT" ]
13
2017-04-14T18:27:26.000Z
2020-11-27T19:03:22.000Z
src/Parameters.cpp
MikeHeiber/Ising_OPV
6a108675bdee1847abee0273b7874d9d312b048e
[ "MIT" ]
5
2018-05-22T19:15:10.000Z
2020-02-27T02:23:31.000Z
// Copyright (c) 2014-2019 Michael C. Heiber // This source file is part of the Ising_OPV project, which is subject to the MIT License. // For more information, see the LICENSE file that accompanies this software. // The Ising_OPV project can be found on Github at https://github.com/MikeHeiber/Ising_OPV #include "Parameters.h" using namespace std; namespace Ising_OPV { Parameters::Parameters() { } bool Parameters::checkParameters() const { bool Error_found = false; // Check for valid lattice dimensions if (Length <= 0 || Width <= 0 || Height <= 0) { cout << "Parameter error! The input Length, Width, and Height of the lattice must be greater than zero." << endl; Error_found = true; } // Check the input mix fraction if (Mix_fraction < 0 || Mix_fraction > 1) { cout << "Parameter error! The input Mix_fraction must be between 0 and 1." << endl; Error_found = true; } // Check the input interaction energies if (Interaction_energy1 < 0 || Interaction_energy2 < 0) { cout << "Parameter error! The input Interaction_energy1 and Interaction_energy2 parameters cannot be negative." << endl; Error_found = true; } // Check the input number of Monte Carlo steps if (MC_steps < 0) { cout << "Parameter error! The input MC_steps parameter cannot be negative." << endl; Error_found = true; } // Check the smoothing parameters if (Enable_smoothing && !(Smoothing_threshold > 0)) { cout << "Parameter error! When performing smoothing, the input Smoothing_threshold must be greater than zero." << endl; Error_found = true; } // Check the lattice resclae parameters if (Enable_rescale && !(Rescale_factor > 0)) { cout << "Parameter error! When rescaling the lattice, the input Rescale_factor must be greater than zero." << endl; Error_found = true; } if (Enable_rescale && Enable_shrink && (Length % Rescale_factor != 0 || Width % Rescale_factor != 0 || Height % Rescale_factor != 0)) { cout << "Parameter error! When shrinking the lattice, the input Rescale_factor must be an integer multiple of the Length, Width, and Height." << endl; Error_found = true; } // Check the interfacial mixing parameters if (Enable_interfacial_mixing && !(Interface_width > 0)) { cout << "Parameter error! When performing interfacial mixing, the input Interface_width must be greater than zero." << endl; Error_found = true; } if (Enable_interfacial_mixing && (!(Interface_conc > 0) || !(Interface_conc < 1))) { cout << "Parameter error! When performing interfacial mixing, the input Interface_conc must be greater than zero and less than 1." << endl; Error_found = true; } // Check the correlation calculation parameters if (Enable_correlation_calc && !(N_sampling_max > 0)) { cout << "Parameter error! When performing the correlation calculation, the mix fraction method and the 1/e method cannot both be enabled." << endl; Error_found = true; } if (Enable_correlation_calc && Enable_mix_frac_method && Enable_e_method) { cout << "Parameter error! When performing the correlation calculation, the mix fraction method and the 1/e method cannot both be enabled." << endl; Error_found = true; } if (Enable_correlation_calc && !Enable_mix_frac_method && !Enable_e_method) { cout << "Parameter error! When performing the correlation calculation, either the mix fraction method or the 1/e method must be enabled." << endl; Error_found = true; } if (Enable_correlation_calc && Enable_extended_correlation_calc && !(Extended_correlation_cutoff_distance > 0)) { cout << "Parameter error! When performing the extended correlation calculation, Extended_correlation_cutoff_distance must be greater than zero." << endl; Error_found = true; } // Check the growth preference parameters if (Enable_growth_pref && (Growth_direction < 1 || Growth_direction > 3)) { cout << "Parameter error! When performing phase separation with a directional growth preference, the input Growth_direction paramter must be 1, 2, or 3." << endl; Error_found = true; } if (Enable_growth_pref && !(Additional_interaction > 0) && !(Additional_interaction < 0)) { cout << "Parameter error! When performing phase separation with a directional growth preference, the input Additional_interaction parameter must not be zero." << endl; Error_found = true; } // Check tomogram import parameters if (Enable_import_morphologies && Enable_import_tomogram) { cout << "Parameter error! The import morphologies and import tomogram options cannot both be enabled." << endl; Error_found = true; } if (Enable_import_tomogram && !(Desired_unit_size > 0)) { cout << "Parameter error! When importing a tomogram dataset, the input Desired_unit_size must not be zero." << endl; Error_found = true; } if (Enable_import_tomogram && !(Mixed_frac < 1)) { cout << "Parameter error! When importing a tomogram dataset, the Mixed_frac must be graeter than equal to 0 and less than 1." << endl; Error_found = true; } if (Enable_import_tomogram && (!(Mixed_conc > 0) || !(Mixed_conc < 1))) { cout << "Parameter error! When importing a tomogram dataset, the Mixed_conc must be greater than zero and less than 1." << endl; Error_found = true; } //if (Enable_import_tomogram && !Enable_cutoff_analysis && !Enable_probability_analysis) { // cout << "Parameter error! When importing a tomogram dataset, the cutoff analysis or the probability analysis option must be enabled." << endl; // Error_found = true; //} //if (Enable_import_tomogram && Enable_cutoff_analysis && Enable_probability_analysis) { // cout << "Parameter error! When importing a tomogram dataset, the cutoff analysis and the probability analysis options cannot both be enabled." << endl; // Error_found = true; //} //if (Enable_import_tomogram && Enable_probability_analysis && Probability_scaling_exponent < 0) { // cout << "Parameter error! When importing a tomogram dataset and using the probability analysis option, the Probability_scaling_exponent must not be negative." << endl; // Error_found = true; //} if (Enable_import_tomogram && N_extracted_segments <= 0) { cout << "Parameter error! When importing a tomogram dataset, the input N_extracted segments must be greater than zero." << endl; Error_found = true; } if (Enable_import_tomogram && N_variants <= 0) { cout << "Parameter error! When importing a tomogram dataset, the input N_variants segments must be greater than zero." << endl; Error_found = true; } if (Enable_import_tomogram && N_extracted_segments != intpow((int)floor(sqrt(N_extracted_segments)), 2)) { cout << "Parameter error! When importing a tomogram dataset, the input value for N_extracted_segments must be 1, 4, 9, 16, 25, 36, 49, 64, 89, 100, 121, 144, 169, or 196 but " << N_extracted_segments << " was entered." << endl; Error_found = true; } // Check other parameter conflicts if (Enable_analysis_only && !Enable_import_morphologies && !Enable_import_tomogram) { cout << "Parameter error! The 'analysis only' option can only be used when importing morphologies." << endl; Error_found = true; } if (Error_found) { return false; } return true; } bool Parameters::importParameters(ifstream& parameterfile) { Version min_version("4.0.0-rc.1"); string line; // Parse header file line getline(parameterfile, line); line = line.substr(line.find('v') + 1); Version file_version; try { file_version = Version(line); } catch (invalid_argument exception) { cout << "Error! Unable to load parameter file with version " << line << ". Only parameter files formatted for Ising_OPV v4.0.0-rc.1 or greater are supported." << endl; return false; } if (file_version < min_version) { cout << "Error! Unable to load parameter file with v" << file_version << ". Only parameter files formatted for Ising_OPV v4.0.0-rc.1 or greater are supported." << endl; return false; } string var; vector<string> stringvars; // Read input file line by line. while (getline(parameterfile, line)) { // Skip lines designated as section breaks and section headers. if ((line.substr(0, 2)).compare("--") != 0 && (line.substr(0, 2)).compare("##") != 0) { // Strip off trailing comments from each line. var = line.substr(0, line.find("//")); var = removeWhitespace(var); // Add parameter value strings to a vector. stringvars.push_back(var); } } // Check that correct number of parameters have been imported if ((int)stringvars.size() != 42) { cout << "Error! Incorrect number of parameters were loaded from the parameter file." << endl; return false; } bool Error_found = false; int i = 0; // Convert strings into the correct data type and assign them to their corresponding parameter variable. // General Parameters Length = atoi(stringvars[i].c_str()); i++; Width = atoi(stringvars[i].c_str()); i++; Height = atoi(stringvars[i].c_str()); i++; //enable_z_periodic_boundary try { Enable_periodic_z = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting z-direction periodic boundary conditions!" << endl; Error_found = true; } i++; Mix_fraction = atof(stringvars[i].c_str()); i++; Interaction_energy1 = atof(stringvars[i].c_str()); i++; Interaction_energy2 = atof(stringvars[i].c_str()); i++; MC_steps = atoi(stringvars[i].c_str()); i++; //enable_smoothing try { Enable_smoothing = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology smoothing options" << endl; Error_found = true; } i++; Smoothing_threshold = atof(stringvars[i].c_str()); i++; //enable_rescale try { Enable_rescale = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology rescale options" << endl; Error_found = true; } i++; Rescale_factor = atoi(stringvars[i].c_str()); i++; try { Enable_shrink = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology shrink options" << endl; Error_found = true; } i++; //enable_interfacial_mixing try { Enable_interfacial_mixing = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting interfacial mixing options" << endl; Error_found = true; } i++; Interface_width = atof(stringvars[i].c_str()); i++; Interface_conc = atof(stringvars[i].c_str()); i++; //enable_analysis_only try { Enable_analysis_only = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting analysis options" << endl; Error_found = true; } i++; //enable_correlation_calc try { Enable_correlation_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting correlation calculation options" << endl; Error_found = true; } i++; N_sampling_max = atoi(stringvars[i].c_str()); i++; //enable_mix_frac_method try { Enable_mix_frac_method = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting correlation calculation domain size determination method options" << endl; Error_found = true; } i++; //enable_e_method try { Enable_e_method = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting correlation calculation domain size determination method options" << endl; Error_found = true; } i++; //enable_extended_correlation_calc try { Enable_extended_correlation_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting extended correlation calculation options" << endl; Error_found = true; } i++; Extended_correlation_cutoff_distance = atoi(stringvars[i].c_str()); i++; //enable_interfacial_distance_calc try { Enable_interfacial_distance_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting interfacial distance calculation options" << endl; Error_found = true; } i++; //enable_tortuosity_calc try { Enable_tortuosity_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting tortuosity calculation options" << endl; Error_found = true; } i++; //enable_reduced_memory_tortuosity_calc try { Enable_reduced_memory_tortuosity_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting reduced memory tortuosity calculation options" << endl; Error_found = true; } i++; //enable_depth_dependent_cal try { Enable_depth_dependent_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting areal mapping calculation options" << endl; Error_found = true; } i++; //enable_areal_maps_cal try { Enable_areal_maps_calc = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting depth dependent calculation options" << endl; Error_found = true; } i++; //enable_checkerboard_start try { Enable_checkerboard_start = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting checkerboard starting condition" << endl; Error_found = true; } i++; //enable_growth_pref try { Enable_growth_pref = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting growth preference conditions" << endl; Error_found = true; } i++; Growth_direction = atoi(stringvars[i].c_str()); i++; Additional_interaction = atof(stringvars[i].c_str()); i++; // Export Morphology Parameters //Enable_export_compressed_files try { Enable_export_compressed_files = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting export options" << endl; Error_found = true; } i++; //Enable_export_cross_section try { Enable_export_cross_section = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting export cross-section options" << endl; Error_found = true; } i++; // Import Morphology Options //Enable_import_morphologies try { Enable_import_morphologies = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting morphology import option" << endl; Error_found = true; } i++; // Tomogram Import Options //Enable_import_tomogram try { Enable_import_tomogram = str2bool(stringvars[i]); } catch (invalid_argument& exception) { cout << exception.what() << endl; cout << "Error setting tomogram import option" << endl; Error_found = true; } i++; Tomogram_name = stringvars[i]; i++; Desired_unit_size = atof(stringvars[i].c_str()); i++; //try { // Enable_cutoff_analysis = str2bool(stringvars[i]); //} //catch (invalid_argument& exception) { // cout << exception.what() << endl; // cout << "Error setting tomogram import conditions" << endl; // Error_found = true; //} //i++; Mixed_frac = atof(stringvars[i].c_str()); i++; Mixed_conc = atof(stringvars[i].c_str()); i++; //try { // Enable_probability_analysis = str2bool(stringvars[i]); //} //catch (invalid_argument& exception) { // cout << exception.what() << endl; // cout << "Error setting tomogram import conditions" << endl; // Error_found = true; //} //i++; //Probability_scaling_exponent = atof(stringvars[i].c_str()); //i++; N_extracted_segments = atoi(stringvars[i].c_str()); i++; N_variants = atoi(stringvars[i].c_str()); i++; return !Error_found; } }
36.212719
230
0.690002
MikeHeiber
7845268ec5d8209992670ff50587909751d8c545
2,028
cc
C++
libqpdf/Pl_ASCIIHexDecoder.cc
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
1,812
2015-01-27T09:07:20.000Z
2022-03-30T23:03:15.000Z
libqpdf/Pl_ASCIIHexDecoder.cc
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
584
2015-01-24T00:31:12.000Z
2022-03-24T21:42:38.000Z
libqpdf/Pl_ASCIIHexDecoder.cc
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
204
2015-04-09T16:28:06.000Z
2022-03-29T14:29:45.000Z
#include <qpdf/Pl_ASCIIHexDecoder.hh> #include <qpdf/QTC.hh> #include <stdexcept> #include <string.h> #include <ctype.h> Pl_ASCIIHexDecoder::Pl_ASCIIHexDecoder(char const* identifier, Pipeline* next) : Pipeline(identifier, next), pos(0), eod(false) { this->inbuf[0] = '0'; this->inbuf[1] = '0'; this->inbuf[2] = '\0'; } Pl_ASCIIHexDecoder::~Pl_ASCIIHexDecoder() { } void Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len) { if (this->eod) { return; } for (size_t i = 0; i < len; ++i) { char ch = static_cast<char>(toupper(buf[i])); switch (ch) { case ' ': case '\f': case '\v': case '\t': case '\r': case '\n': QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space"); // ignore whitespace break; case '>': this->eod = true; flush(); break; default: if (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'F'))) { this->inbuf[this->pos++] = ch; if (this->pos == 2) { flush(); } } else { char t[2]; t[0] = ch; t[1] = 0; throw std::runtime_error( std::string("character out of range" " during base Hex decode: ") + t); } break; } if (this->eod) { break; } } } void Pl_ASCIIHexDecoder::flush() { if (this->pos == 0) { QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush"); return; } int b[2]; for (int i = 0; i < 2; ++i) { if (this->inbuf[i] >= 'A') { b[i] = this->inbuf[i] - 'A' + 10; } else { b[i] = this->inbuf[i] - '0'; } } unsigned char ch = static_cast<unsigned char>((b[0] << 4) + b[1]); QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", (this->pos == 2) ? 0 : 1); // Reset before calling getNext()->write in case that throws an // exception. this->pos = 0; this->inbuf[0] = '0'; this->inbuf[1] = '0'; this->inbuf[2] = '\0'; getNext()->write(&ch, 1); } void Pl_ASCIIHexDecoder::finish() { flush(); getNext()->finish(); }
17.482759
80
0.52071
tomty89
784e1c675e1798b69faa732596d74064692a0655
11,561
cpp
C++
FEBioFluid/FEFluidSolutesNaturalFlux.cpp
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
59
2020-06-15T12:38:49.000Z
2022-03-29T19:14:47.000Z
FEBioFluid/FEFluidSolutesNaturalFlux.cpp
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
36
2020-06-14T21:10:01.000Z
2022-03-12T12:03:14.000Z
FEBioFluid/FEFluidSolutesNaturalFlux.cpp
AlexandraAllan23/FEBio
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
[ "MIT" ]
26
2020-06-25T15:02:13.000Z
2022-03-10T09:14:03.000Z
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ //For now only allows for one solute at a time, jn=-d0*gradc+c*vf //Stiffness does not include effect from different solutes #include "stdafx.h" #include "FEFluidSolutesNaturalFlux.h" #include "FEFluidMaterial.h" #include "FEFluidSolutes.h" #include "FEBioFluidSolutes.h" #include <FECore/FELinearSystem.h> #include <FECore/FEModel.h> #include <FECore/FEAnalysis.h> //----------------------------------------------------------------------------- // Parameter block for pressure loads BEGIN_FECORE_CLASS(FEFluidSolutesNaturalFlux, FESurfaceLoad) ADD_PARAMETER(m_beta, "beta"); ADD_PARAMETER(m_isol , "solute_id"); END_FECORE_CLASS() //----------------------------------------------------------------------------- //! constructor FEFluidSolutesNaturalFlux::FEFluidSolutesNaturalFlux(FEModel* pfem) : FESurfaceLoad(pfem), m_dofW(pfem), m_dofC(pfem) { m_beta = 1.0; m_isol = 1; } //----------------------------------------------------------------------------- //! initialize bool FEFluidSolutesNaturalFlux::Init() { if (m_isol == -1) return false; // set up the dof lists FEModel* fem = GetFEModel(); m_dofC.Clear(); m_dofW.Clear(); m_dofC.AddDof(fem->GetDOFIndex(FEBioFluidSolutes::GetVariableName(FEBioFluidSolutes::FLUID_CONCENTRATION), m_isol-1)); m_dofW.AddVariable(FEBioFluidSolutes::GetVariableName(FEBioFluidSolutes::RELATIVE_FLUID_VELOCITY)); m_dof.Clear(); m_dof.AddDofs(m_dofW); m_dof.AddDofs(m_dofC); FESurface& surf = GetSurface(); if (FESurfaceLoad::Init() == false) return false; // get the list of FluidSolutes elements connected to this interface int NF = surf.Elements(); m_elem.resize(NF); for (int j = 0; j<NF; ++j) { FESurfaceElement& el = surf.Element(j); // extract the first of two elements on this interface m_elem[j] = el.m_elem[0]; // get its material and check if FluidSolutes FEMaterial* pm = fem->GetMaterial(m_elem[j]->GetMatID()); FEFluidSolutes* pfsi = dynamic_cast<FEFluidSolutes*>(pm); if (pfsi == nullptr) { pm = fem->GetMaterial(el.m_elem[1]->GetMatID()); pfsi = dynamic_cast<FEFluidSolutes*>(pm); if (pfsi == nullptr) return false; m_elem[j] = el.m_elem[1]; } } return true; } //----------------------------------------------------------------------------- void FEFluidSolutesNaturalFlux::Serialize(DumpStream& ar) { FESurfaceLoad::Serialize(ar); if (ar.IsShallow() == false) { ar & m_dofC & m_dofW; } if (ar.IsShallow() == false) { if (ar.IsSaving()) { int NE = (int)m_elem.size(); ar << NE; for (int i = 0; i < NE; ++i) { FEElement* pe = m_elem[i]; int nid = (pe ? pe->GetID() : -1); ar << nid; } } else { FEMesh& mesh = ar.GetFEModel().GetMesh(); int NE, nid; ar >> NE; m_elem.resize(NE, nullptr); for (int i = 0; i < NE; ++i) { ar >> nid; if (nid != -1) { FEElement* pe = mesh.FindElementFromID(nid); assert(pe); m_elem[i] = pe; } } } } } //----------------------------------------------------------------------------- void FEFluidSolutesNaturalFlux::StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp) { m_psurf->LoadStiffness(LS, m_dof, m_dof, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, const FESurfaceDofShape& dof_b, matrix& Kab) { FESurfaceElement& el = *mp.SurfaceElement(); int iel = el.m_lid; int neln = el.Nodes(); // get the diffusivity FEElement* pe = el.m_elem[0]; FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); FEFluidSolutes* pfsm = dynamic_cast<FEFluidSolutes*>(pm); double d0 = pfsm->GetSolute(m_isol-1)->m_pDiff->Free_Diffusivity(mp); double d0p = pfsm->GetSolute(m_isol-1)->m_pDiff->Tangent_Free_Diffusivity_Concentration(mp, m_isol-1); double* N = el.H (mp.m_index); double* Gr = el.Gr(mp.m_index); double* Gs = el.Gs(mp.m_index); // tangent vectors vec3d rt[FEElement::MAX_NODES]; m_psurf->GetNodalCoordinates(el, tp.alphaf, rt); vec3d dxr = el.eval_deriv1(rt, mp.m_index); vec3d dxs = el.eval_deriv2(rt, mp.m_index); vec3d n = dxr ^ dxs; //double da = n.unit(); double alpha = tp.alphaf; vector<vec3d> gradN(neln); // Fluid velocity vec3d v = FluidVelocity(mp, tp.alphaf); double c = EffectiveConcentration(mp, tp.alphaf); //vec3d v = FluidVelocityElm(mp); //double c = EffectiveConcentrationElm(mp); vec3d gradc = EffectiveCGrad(mp); vec3d gcnt[2], gcntp[2]; m_psurf->ContraBaseVectors(el, mp.m_index, gcnt); m_psurf->ContraBaseVectorsP(el, mp.m_index, gcntp); for (int i = 0; i<neln; ++i) gradN[i] = (gcnt[0] * alpha + gcntp[0] * (1 - alpha))*Gr[i] + (gcnt[1] * alpha + gcntp[1] * (1 - alpha))*Gs[i]; Kab.zero(); // calculate stiffness component int i = dof_a.index; int j = dof_b.index; vec3d kcw = n*(N[i]*N[j]*c*tp.alphaf); double kcc = n*((-gradc*d0p+v)*N[j]-gradN[j]*d0)*(tp.alphaf*N[i]); Kab[3][0] -= kcw.x; Kab[3][1] -= kcw.y; Kab[3][2] -= kcw.z; Kab[3][3] -= kcc; }); } //----------------------------------------------------------------------------- vec3d FEFluidSolutesNaturalFlux::FluidVelocity(FESurfaceMaterialPoint& mp, double alpha) { vec3d vt[FEElement::MAX_NODES]; FESurfaceElement& el = *mp.SurfaceElement(); int neln = el.Nodes(); for (int j = 0; j<neln; ++j) { FENode& node = m_psurf->Node(el.m_lnode[j]); vt[j] = node.get_vec3d(m_dofW[0], m_dofW[1], m_dofW[2])*alpha + node.get_vec3d_prev(m_dofW[0], m_dofW[1], m_dofW[2])*(1 - alpha); } return el.eval(vt, mp.m_index); } //----------------------------------------------------------------------------- double FEFluidSolutesNaturalFlux::EffectiveConcentration(FESurfaceMaterialPoint& mp, double alpha) { double c = 0; FESurfaceElement& el = *mp.SurfaceElement(); double* H = el.H(mp.m_index); int neln = el.Nodes(); for (int j = 0; j < neln; ++j) { FENode& node = m_psurf->Node(el.m_lnode[j]); double cj = node.get(m_dofC[0])*alpha + node.get_prev(m_dofC[0])*(1.0 - alpha); c += cj*H[j]; } return c; } //----------------------------------------------------------------------------- vec3d FEFluidSolutesNaturalFlux::EffectiveCGrad(FESurfaceMaterialPoint& pt) { FESurfaceElement& face = *pt.SurfaceElement(); int iel = face.m_lid; // Get the fluid stress from the fluid-FSI element vec3d gradc(0.0); FEElement* pe = m_elem[iel]; int nint = pe->GaussPoints(); for (int n = 0; n<nint; ++n) { FEMaterialPoint& mp = *pe->GetMaterialPoint(n); FEFluidSolutesMaterialPoint& spt = *(mp.ExtractData<FEFluidSolutesMaterialPoint>()); gradc += spt.m_gradc[m_isol-1]; } gradc /= nint; return gradc; } //----------------------------------------------------------------------------- double FEFluidSolutesNaturalFlux::EffectiveConcentrationElm(FESurfaceMaterialPoint& pt) { FESurfaceElement& face = *pt.SurfaceElement(); int iel = face.m_lid; // Get the fluid stress from the fluid-FSI element double c = 0.0; FEElement* pe = m_elem[iel]; int nint = pe->GaussPoints(); for (int n = 0; n<nint; ++n) { FEMaterialPoint& mp = *pe->GetMaterialPoint(n); FEFluidSolutesMaterialPoint& spt = *(mp.ExtractData<FEFluidSolutesMaterialPoint>()); c += spt.m_c[m_isol-1]; } c /= nint; return c; } //----------------------------------------------------------------------------- vec3d FEFluidSolutesNaturalFlux::FluidVelocityElm(FESurfaceMaterialPoint& pt) { FESurfaceElement& face = *pt.SurfaceElement(); int iel = face.m_lid; // Get the fluid stress from the fluid-FSI element vec3d v(0.0); FEElement* pe = m_elem[iel]; int nint = pe->GaussPoints(); for (int n = 0; n<nint; ++n) { FEMaterialPoint& mp = *pe->GetMaterialPoint(n); FEFluidMaterialPoint& fpt = *(mp.ExtractData<FEFluidMaterialPoint>()); v += fpt.m_vft; } v /= nint; return v; } //----------------------------------------------------------------------------- void FEFluidSolutesNaturalFlux::LoadVector(FEGlobalVector& R, const FETimeInfo& tp) { m_psurf->LoadVector(R, m_dofC, false, [=](FESurfaceMaterialPoint& mp, const FESurfaceDofShape& dof_a, vector<double>& fa) { FESurfaceElement& el = *mp.SurfaceElement(); // get the diffusivity FEElement* pe = el.m_elem[0]; FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); FEFluidSolutes* pfsm = dynamic_cast<FEFluidSolutes*>(pm); double d0 = pfsm->GetSolute(m_isol-1)->m_pDiff->Free_Diffusivity(mp); // tangent vectors vec3d rt[FEElement::MAX_NODES]; m_psurf->GetNodalCoordinates(el, tp.alphaf, rt); vec3d dxr = el.eval_deriv1(rt, mp.m_index); vec3d dxs = el.eval_deriv2(rt, mp.m_index); // normal and area element vec3d n = dxr ^ dxs; //double da = n.unit(); // fluid velocity vec3d v = FluidVelocity(mp, tp.alphaf); double c = EffectiveConcentration(mp, tp.alphaf); //vec3d v = FluidVelocityElm(mp); //double c = EffectiveConcentrationElm(mp); vec3d gradc = EffectiveCGrad(mp); // force vector (change sign for inflow vs outflow) double f = n*(-gradc*d0+v*c)*(m_beta); double H = dof_a.shape; fa[0] = H * f; }); }
34.927492
155
0.564398
AlexandraAllan23
784e40066228e00614cbf5ff86b6fe1e99c73de0
38,680
cpp
C++
Source/ArchQOR/x86/HLAssembler/Emittables/EInstruction.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/ArchQOR/x86/HLAssembler/Emittables/EInstruction.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/ArchQOR/x86/HLAssembler/Emittables/EInstruction.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//EInstruction.cpp // Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com> // Copyright (c) Querysoft Limited 2012 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Implement an x86 instruction emittable #include "ArchQOR.h" #if ( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 ) #include "ArchQOR/x86/HLAssembler/Emittables/EInstruction.h" #include "ArchQOR/x86/HLAssembler/x86HLAContext.h" #include <assert.h> //------------------------------------------------------------------------------ namespace nsArch { //------------------------------------------------------------------------------ namespace nsx86 { //------------------------------------------------------------------------------ CEInstruction::CEInstruction( Cx86HLAIntrinsics* c, Cmp_unsigned__int32 code, COperand** operandsData, Cmp_unsigned__int32 operandsCount ) __QCMP_THROW : CEmittable( (nsArch::CHighLevelAssemblerBase*)c, EMITTABLE_INSTRUCTION ) { m_uiCode = code; m_uiEmitOptions = c->getEmitOptions(); c->setEmitOptions( 0 );// Each created instruction takes emit options and clears it. m_pOperands = operandsData; m_uiOperandsCount = operandsCount; m_pVariables = 0; m_uiVariablesCount = 0; m_pMemOp = 0; Cmp_unsigned__int32 i; for( i = 0; i < operandsCount; i++ ) { if( m_pOperands[ i ]->isMem() ) { m_pMemOp = dynamic_cast< CMem* >( m_pOperands[ i ] ); break; } } const InstructionDescription* id = &instructionDescription[ m_uiCode ]; m_bIsSpecial = id->isSpecial(); m_bIsFPU = id->isFPU(); m_bIsGPBLoUsed = false; m_bIsGPBHiUsed = false; if( m_bIsSpecial ) { // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN} switch( m_uiCode ) { case INST_CPUID: // Special... break; case INST_CBW: case INST_CDQE: case INST_CWDE: // Special... break; case INST_CMPXCHG: case INST_CMPXCHG8B: # if ( QOR_ARCH_WORDSIZE == 64 ) case INST_CMPXCHG16B: # endif // ASMJIT_X64 // Special... break; # if ( QOR_ARCH_WORDSIZE == 64 ) case INST_DAA: case INST_DAS: // Special... break; # endif // case INST_IMUL: switch (operandsCount) { case 2: // IMUL dst, src is not special instruction. m_bIsSpecial = false; break; case 3: if( !( m_pOperands[ 0 ]->isVar() && m_pOperands[ 1 ]->isVar() && m_pOperands[ 2 ]->isVarMem() ) ) { m_bIsSpecial = false; // Only IMUL dst_lo, dst_hi, reg/mem is special, all others not. } break; } break; case INST_MUL: case INST_IDIV: case INST_DIV: // Special... break; case INST_MOV_PTR: // Special... break; case INST_LAHF: case INST_SAHF: // Special... break; case INST_MASKMOVQ: case INST_MASKMOVDQU: // Special... break; case INST_ENTER: case INST_LEAVE: // Special... break; case INST_RET: // Special... break; case INST_MONITOR: case INST_MWAIT: // Special... break; case INST_POP: case INST_POPAD: case INST_POPFD: case INST_POPFQ: // Special... break; case INST_PUSH: case INST_PUSHAD: case INST_PUSHFD: case INST_PUSHFQ: // Special... break; case INST_RCL: case INST_RCR: case INST_ROL: case INST_ROR: case INST_SAL: case INST_SAR: case INST_SHL: case INST_SHR: // Rot instruction is special only if last operand is variable (register). m_bIsSpecial = m_pOperands[ 1 ]->isVar(); break; case INST_SHLD: case INST_SHRD: // Shld/Shrd instruction is special only if last operand is variable (register). m_bIsSpecial = m_pOperands[ 2 ]->isVar(); break; case INST_RDTSC: case INST_RDTSCP: // Special... break; case INST_REP_LODSB: case INST_REP_LODSD: case INST_REP_LODSQ: case INST_REP_LODSW: case INST_REP_MOVSB: case INST_REP_MOVSD: case INST_REP_MOVSQ: case INST_REP_MOVSW: case INST_REP_STOSB: case INST_REP_STOSD: case INST_REP_STOSQ: case INST_REP_STOSW: case INST_REPE_CMPSB: case INST_REPE_CMPSD: case INST_REPE_CMPSQ: case INST_REPE_CMPSW: case INST_REPE_SCASB: case INST_REPE_SCASD: case INST_REPE_SCASQ: case INST_REPE_SCASW: case INST_REPNE_CMPSB: case INST_REPNE_CMPSD: case INST_REPNE_CMPSQ: case INST_REPNE_CMPSW: case INST_REPNE_SCASB: case INST_REPNE_SCASD: case INST_REPNE_SCASQ: case INST_REPNE_SCASW: // Special... break; default: assert( 0 ); } // ${SPECIAL_INSTRUCTION_HANDLING_END} } } //------------------------------------------------------------------------------ CEInstruction::~CEInstruction() __QCMP_THROW { } //------------------------------------------------------------------------------ void CEInstruction::getVariable( VarData* _candidate, VarAllocRecord*& cur, VarAllocRecord*& var ) { for( var = cur; ;) { if( var == m_pVariables ) { var = cur++; var->vdata = _candidate; var->vflags = 0; var->regMask = 0xFFFFFFFF; break; } var--; if( var->vdata == _candidate ) { break; } } assert( var != 0 ); } //------------------------------------------------------------------------------ void CEInstruction::prepare( CHLAssemblerContextBase& hlac ) __QCMP_THROW { Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac ); /* # define __GET_VARIABLE(__vardata__) \ { \ VarData* _candidate = __vardata__; \ \ for (var = cur; ;) \ { \ if (var == m_pVariables) \ { \ var = cur++; \ var->vdata = _candidate; \ var->vflags = 0; \ var->regMask = 0xFFFFFFFF; \ break; \ } \ \ var--; \ \ if (var->vdata == _candidate) \ { \ break; \ } \ } \ \ assert(var != 0); \ } */ m_uiOffset = cc.GetCurrentOffset(); const InstructionDescription* id = &instructionDescription[ m_uiCode ]; Cmp_unsigned__int32 i, len = m_uiOperandsCount; Cmp_unsigned__int32 variablesCount = 0; for( i = 0; i < len; i++ ) { COperand* o = m_pOperands[ i ]; if( o->isVar() ) { assert( o->getId() != INVALID_VALUE ); VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( o->getId() ); assert( vdata != 0 ); CBaseVar* pVar = dynamic_cast< CBaseVar* >( o ); if( pVar && pVar->isGPVar() ) { if( pVar->isGPBLo() ) { m_bIsGPBLoUsed = true; vdata->registerGPBLoCount++; }; if( pVar->isGPBHi() ) { m_bIsGPBHiUsed = true; vdata->registerGPBHiCount++; }; } if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } else if( o->isMem() ) { CMem& m( dynamic_cast< CMem& >( *o ) ); if( ( m.getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getId() ); assert( vdata != 0 ); cc._markMemoryUsed( vdata ); if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } else if( ( m.getBase() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getBase() ); assert( vdata != 0 ); if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } if( ( m.getIndex() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getIndex() ); assert( vdata != 0 ); if( vdata->workOffset != m_uiOffset ) { if( !cc._isActive( vdata ) ) { cc._addActive( vdata ); } vdata->workOffset = m_uiOffset; variablesCount++; } } } } if( !variablesCount ) { cc.IncrementCurrentOffset(); return; } m_pVariables = reinterpret_cast< VarAllocRecord* >( ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->getZone().zalloc( sizeof( VarAllocRecord ) * variablesCount ) ); if( !m_pVariables ) { ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->setError( ERROR_NO_HEAP_MEMORY ); cc.IncrementCurrentOffset(); return; } m_uiVariablesCount = variablesCount; VarAllocRecord* cur = m_pVariables; VarAllocRecord* var = 0; bool _isGPBUsed = m_bIsGPBLoUsed || m_bIsGPBHiUsed; Cmp_unsigned__int32 gpRestrictMask = nsCodeQOR::maskUpToIndex( REG_NUM_GP ); # if ( QOR_ARCH_WORDSIZE == 64 ) if( m_bIsGPBHiUsed ) { gpRestrictMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) | nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBP ) | nsCodeQOR::maskFromIndex( REG_INDEX_ESI ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDI ) ; } # endif // ASMJIT_X64 for( i = 0; i < len; i++ ) { COperand* o = m_pOperands[ i ]; if( o->isVar() ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( o->getId() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); var->vflags |= VARIABLE_ALLOC_REGISTER; CBaseVar* pVar = dynamic_cast< CBaseVar* >( o ); if( _isGPBUsed ) { CGPVar* pGPVar = dynamic_cast< CGPVar* >( pVar ); # if ( QOR_ARCH_WORDSIZE == 32 ) if( pGPVar->isGPB() ) { var->regMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) | nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDX ) ; } # else // Restrict all BYTE registers to RAX/RBX/RCX/RDX if HI BYTE register // is used (REX prefix makes HI BYTE addressing unencodable). if( m_bIsGPBHiUsed ) { if( pGPVar->isGPB() ) { var->regMask &= nsCodeQOR::maskFromIndex( REG_INDEX_EAX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EBX ) | nsCodeQOR::maskFromIndex( REG_INDEX_ECX ) | nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); } } # endif // } if( isSpecial() ) { // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN} switch( m_uiCode ) { case INST_CPUID: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EBX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; case 3: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_CBW: case INST_CDQE: case INST_CWDE: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_CMPXCHG: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; default: assert( 0 ); } break; case INST_CMPXCHG8B: # if ( QOR_ARCH_WORDSIZE == 64 ) case INST_CMPXCHG16B: # endif // ASMJIT_X64 switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; case 3: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EBX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; # if ( QOR_ARCH_WORDSIZE == 32 ) case INST_DAA: case INST_DAS: assert( i == 0 ); vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; # endif // ( QOR_ARCH_WORDSIZE == 32 ) case INST_IMUL: case INST_MUL: case INST_IDIV: case INST_DIV: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; default: assert( 0 ); } break; case INST_MOV_PTR: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_LAHF: assert( i == 0 ); vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case INST_SAHF: assert( i == 0 ); vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case INST_MASKMOVQ: case INST_MASKMOVDQU: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; } break; case INST_ENTER: case INST_LEAVE: // TODO: SPECIAL INSTRUCTION. break; case INST_RET: // TODO: SPECIAL INSTRUCTION. break; case INST_MONITOR: case INST_MWAIT: // TODO: MONITOR/MWAIT (COMPILER). break; case INST_POP: // TODO: SPECIAL INSTRUCTION. break; case INST_POPAD: case INST_POPFD: case INST_POPFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_PUSH: // TODO: SPECIAL INSTRUCTION. break; case INST_PUSHAD: case INST_PUSHFD: case INST_PUSHFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_RCL: case INST_RCR: case INST_ROL: case INST_ROR: case INST_SAL: case INST_SAR: case INST_SHL: case INST_SHR: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_SHLD: case INST_SHRD: switch( i ) { case 0: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; break; case 2: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_RDTSC: case INST_RDTSCP: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: assert( m_uiCode == INST_RDTSCP ); vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REP_LODSB: case INST_REP_LODSD: case INST_REP_LODSQ: case INST_REP_LODSW: switch( i ) { case 0: vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ESI ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REP_MOVSB: case INST_REP_MOVSD: case INST_REP_MOVSQ: case INST_REP_MOVSW: case INST_REPE_CMPSB: case INST_REPE_CMPSD: case INST_REPE_CMPSQ: case INST_REPE_CMPSW: case INST_REPNE_CMPSB: case INST_REPNE_CMPSD: case INST_REPNE_CMPSQ: case INST_REPNE_CMPSW: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ESI ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REP_STOSB: case INST_REP_STOSD: case INST_REP_STOSQ: case INST_REP_STOSW: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; case INST_REPE_SCASB: case INST_REPE_SCASD: case INST_REPE_SCASQ: case INST_REPE_SCASW: case INST_REPNE_SCASB: case INST_REPNE_SCASD: case INST_REPNE_SCASQ: case INST_REPNE_SCASW: switch( i ) { case 0: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EDI ); gpRestrictMask &= ~var->regMask; break; case 1: vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_EAX ); gpRestrictMask &= ~var->regMask; break; case 2: vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE | VARIABLE_ALLOC_SPECIAL; var->regMask = nsCodeQOR::maskFromIndex( REG_INDEX_ECX ); gpRestrictMask &= ~var->regMask; break; default: assert( 0 ); } break; default: assert( 0 ); } // ${SPECIAL_INSTRUCTION_HANDLING_END} } else { if( i == 0 ) { // CMP/TEST instruction. if( id->code == INST_CMP || id->code == INST_TEST ) { // Read-only case. vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; } // CVTTSD2SI/CVTTSS2SI instructions. else if( id->code == INST_CVTTSD2SI || id->code == INST_CVTTSS2SI ) { // In 32-bit mode the whole destination is replaced. In 64-bit mode // we need to check whether the destination operand size is 64-bits. #if ( QOR_ARCH_WORDSIZE == 64 ) if (m_pOperands[0]->isRegType(REG_TYPE_GPQ)) { #endif // X64 // Write-only case. vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE; #if ( QOR_ARCH_WORDSIZE == 64 ) } else { // Read/Write. vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; } #endif // ASMJIT_X64 } // MOV/MOVSS/MOVSD instructions. // // If instruction is MOV (source replaces the destination) or // MOVSS/MOVSD and source operand is memory location then register // allocator should know that previous destination value is lost // (write only operation). else if( ( id->isMov()) || ( ( id->code == INST_MOVSS || id->code == INST_MOVSD ) /* && _operands[1].isMem() */ ) || ( id->code == INST_IMUL && m_uiOperandsCount == 3 && !isSpecial() ) ) { // Write-only case. vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE; } else if( id->code == INST_LEA ) { // Write. vdata->registerWriteCount++; var->vflags |= VARIABLE_ALLOC_WRITE; } else { // Read/Write. vdata->registerRWCount++; var->vflags |= VARIABLE_ALLOC_READWRITE; } } else { // Second, third, ... operands are read-only. vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_READ; } if( !m_pMemOp && i < 2 && ( id->oflags[ i ] & InstructionDescription::O_MEM ) != 0 ) { var->vflags |= VARIABLE_ALLOC_MEMORY; } } // If variable must be in specific register we could add some hint to allocator. if( var->vflags & VARIABLE_ALLOC_SPECIAL ) { vdata->prefRegisterMask |= nsCodeQOR::maskFromIndex( var->regMask ); cc._newRegisterHomeIndex( vdata, nsCodeQOR::findFirstBit( var->regMask ) ); } } else if( o->isMem() ) { CMem& m( dynamic_cast< CMem& >( *o ) ); if( ( m.getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getId() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); if( i == 0 ) { // If variable is MOV instruction type (source replaces the destination) // or variable is MOVSS/MOVSD instruction then register allocator should // know that previous destination value is lost (write only operation). if( id->isMov() || ( ( id->code == INST_MOVSS || id->code == INST_MOVSD ) ) ) { // Write only case. vdata->memoryWriteCount++; } else { vdata->memoryRWCount++; } } else { vdata->memoryReadCount++; } } else if( ( m.getBase() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getBase() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_REGISTER | VARIABLE_ALLOC_READ; var->regMask &= gpRestrictMask; } if( ( m.getIndex() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m.getIndex() ); assert( vdata != 0 ); //__GET_VARIABLE( vdata ) getVariable( vdata, cur, var ); vdata->registerReadCount++; var->vflags |= VARIABLE_ALLOC_REGISTER | VARIABLE_ALLOC_READ; var->regMask &= gpRestrictMask; } } } // Traverse all variables and update firstEmittable / lastEmittable. This // function is called from iterator that scans emittables using forward // direction so we can use this knowledge to optimize the process. // Similar to ECall::prepare(). for( i = 0; i < m_uiVariablesCount; i++ ) { VarData* v = m_pVariables[ i ].vdata; // Update GP register allocator restrictions. if( isVariableInteger( v->type ) ) { if( m_pVariables[ i ].regMask == 0xFFFFFFFF ) { m_pVariables[ i ].regMask &= gpRestrictMask; } } // Update first/last emittable (begin of variable scope). if( v->firstEmittable == 0 ) { v->firstEmittable = this; } v->lastEmittable = this; } // There are some instructions that can be used to clear register or to set // register to some value (ideal case is all zeros or all ones). // // xor/pxor reg, reg ; Set all bits in reg to 0. // sub/psub reg, reg ; Set all bits in reg to 0. // andn reg, reg ; Set all bits in reg to 0. // pcmpgt reg, reg ; Set all bits in reg to 0. // pcmpeq reg, reg ; Set all bits in reg to 1. if( m_uiVariablesCount == 1 && m_uiOperandsCount > 1 && m_pOperands[ 0 ]->isVar() && m_pOperands[ 1 ]->isVar() && !m_pMemOp ) { switch( m_uiCode ) { // XOR Instructions. case INST_XOR: case INST_XORPD: case INST_XORPS: case INST_PXOR: // ANDN Instructions. case INST_PANDN: // SUB Instructions. case INST_SUB: case INST_PSUBB: case INST_PSUBW: case INST_PSUBD: case INST_PSUBQ: case INST_PSUBSB: case INST_PSUBSW: case INST_PSUBUSB: case INST_PSUBUSW: // PCMPEQ Instructions. case INST_PCMPEQB: case INST_PCMPEQW: case INST_PCMPEQD: case INST_PCMPEQQ: // PCMPGT Instructions. case INST_PCMPGTB: case INST_PCMPGTW: case INST_PCMPGTD: case INST_PCMPGTQ: // Clear the read flag. This prevents variable alloc/spill. m_pVariables[ 0 ].vflags = VARIABLE_ALLOC_WRITE; m_pVariables[ 0 ].vdata->registerReadCount--; break; } } cc.IncrementCurrentOffset(); //# undef __GET_VARIABLE } //------------------------------------------------------------------------------ nsArch::CEmittable* CEInstruction::translate( CHLAssemblerContextBase& hlac ) __QCMP_THROW { Cx86HLAContext& cc = dynamic_cast< Cx86HLAContext& >( hlac ); Cmp_unsigned__int32 i; Cmp_unsigned__int32 variablesCount = m_uiVariablesCount; if( variablesCount > 0 ) { // These variables are used by the instruction and we set current offset // to their work offsets -> getSpillCandidate never return the variable // used this instruction. for( i = 0; i < variablesCount; i++ ) { m_pVariables->vdata->workOffset = cc.GetCurrentOffset(); } // Alloc variables used by the instruction (special first). for( i = 0; i < variablesCount; i++ ) { VarAllocRecord& r = m_pVariables[ i ]; // Alloc variables with specific register first. if( ( r.vflags & VARIABLE_ALLOC_SPECIAL ) != 0 ) { cc.allocVar( r.vdata, r.regMask, r.vflags ); } } for( i = 0; i < variablesCount; i++ ) { VarAllocRecord& r = m_pVariables[ i ]; // Alloc variables without specific register last. if( ( r.vflags & VARIABLE_ALLOC_SPECIAL ) == 0 ) { cc.allocVar( r.vdata, r.regMask, r.vflags ); } } cc.translateOperands( m_pOperands, m_uiOperandsCount ); } if( m_pMemOp && ( m_pMemOp->getId() & OPERAND_ID_TYPE_MASK ) == OPERAND_ID_TYPE_VAR ) { VarData* vdata = ( dynamic_cast< Cx86HLAIntrinsics* >( m_pHLAssembler ) )->_getVarData( m_pMemOp->getId() ); assert( vdata != 0 ); switch( vdata->state ) { case VARIABLE_STATE_UNUSED: vdata->state = VARIABLE_STATE_MEMORY; break; case VARIABLE_STATE_REGISTER: vdata->changed = false; cc.unuseVar( vdata, VARIABLE_STATE_MEMORY ); break; } } for( i = 0; i < variablesCount; i++ ) { cc._unuseVarOnEndOfScope( this, &m_pVariables[ i ] ); } return translated(); } //------------------------------------------------------------------------------ void CEInstruction::emit( CHighLevelAssemblerBase& ab ) __QCMP_THROW { CCPU* pAssembler = dynamic_cast< CCPU* >( ( dynamic_cast< Cx86HLAIntrinsics& >( ab ) ).getAssembler() ); pAssembler->SetComment( m_szComment ); pAssembler->SetEmitOptions( m_uiEmitOptions ); if( isSpecial() ) { // ${SPECIAL_INSTRUCTION_HANDLING_BEGIN} switch( m_uiCode ) { case INST_CPUID: pAssembler->_emitInstruction( m_uiCode ); return; case INST_CBW: case INST_CDQE: case INST_CWDE: pAssembler->_emitInstruction( m_uiCode ); return; case INST_CMPXCHG: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 1 ], m_pOperands[ 2 ] ); return; case INST_CMPXCHG8B: #if ( QOR_ARCH_WORDSIZE == 64 ) case INST_CMPXCHG16B: #endif // ASMJIT_X64 pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 4 ] ); return; #if ( QOR_ARCH_WORDSIZE == 64 ) case INST_DAA: case INST_DAS: pAssembler->_emitInstruction( m_uiCode ); return; #endif // case INST_IMUL: case INST_MUL: case INST_IDIV: case INST_DIV: // INST dst_lo (implicit), dst_hi (implicit), src (explicit) assert( m_uiOperandsCount == 3 ); pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 2 ] ); return; case INST_MOV_PTR: break; case INST_LAHF: case INST_SAHF: pAssembler->_emitInstruction( m_uiCode ); return; case INST_MASKMOVQ: case INST_MASKMOVDQU: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 1 ], m_pOperands[ 2 ] ); return; case INST_ENTER: case INST_LEAVE: // TODO: SPECIAL INSTRUCTION. break; case INST_RET: // TODO: SPECIAL INSTRUCTION. break; case INST_MONITOR: case INST_MWAIT: // TODO: MONITOR/MWAIT (COMPILER). break; case INST_POP: case INST_POPAD: case INST_POPFD: case INST_POPFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_PUSH: case INST_PUSHAD: case INST_PUSHFD: case INST_PUSHFQ: // TODO: SPECIAL INSTRUCTION. break; case INST_RCL: case INST_RCR: case INST_ROL: case INST_ROR: case INST_SAL: case INST_SAR: case INST_SHL: case INST_SHR: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], &Cx86CPUCore::cl ); return; case INST_SHLD: case INST_SHRD: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ], &Cx86CPUCore::cl ); return; case INST_RDTSC: case INST_RDTSCP: pAssembler->_emitInstruction( m_uiCode ); return; case INST_REP_LODSB: case INST_REP_LODSD: case INST_REP_LODSQ: case INST_REP_LODSW: case INST_REP_MOVSB: case INST_REP_MOVSD: case INST_REP_MOVSQ: case INST_REP_MOVSW: case INST_REP_STOSB: case INST_REP_STOSD: case INST_REP_STOSQ: case INST_REP_STOSW: case INST_REPE_CMPSB: case INST_REPE_CMPSD: case INST_REPE_CMPSQ: case INST_REPE_CMPSW: case INST_REPE_SCASB: case INST_REPE_SCASD: case INST_REPE_SCASQ: case INST_REPE_SCASW: case INST_REPNE_CMPSB: case INST_REPNE_CMPSD: case INST_REPNE_CMPSQ: case INST_REPNE_CMPSW: case INST_REPNE_SCASB: case INST_REPNE_SCASD: case INST_REPNE_SCASQ: case INST_REPNE_SCASW: pAssembler->_emitInstruction( m_uiCode ); return; default: assert( 0 ); } // ${SPECIAL_INSTRUCTION_HANDLING_END} } switch( m_uiOperandsCount ) { case 0: pAssembler->_emitInstruction( m_uiCode ); break; case 1: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ] ); break; case 2: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ] ); break; case 3: pAssembler->_emitInstruction( m_uiCode, m_pOperands[ 0 ], m_pOperands[ 1 ], m_pOperands[ 2 ] ); break; default: assert( 0 ); break; } } //------------------------------------------------------------------------------ int CEInstruction::getMaxSize() const __QCMP_THROW { // TODO: Do something more exact. return 15; } //------------------------------------------------------------------------------ bool CEInstruction::tryUnuseVar( nsArch::CommonVarData* vdata ) __QCMP_THROW { VarData* v = reinterpret_cast< VarData* >( vdata ); for( Cmp_unsigned__int32 i = 0; i < m_uiVariablesCount; i++ ) { if( m_pVariables[ i ].vdata == v ) { m_pVariables[ i ].vflags |= VARIABLE_ALLOC_UNUSE_AFTER_USE; return true; } } return false; } //------------------------------------------------------------------------------ CETarget* CEInstruction::getJumpTarget() const __QCMP_THROW { return 0; } }//nsx86 }//nsArch #endif//( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
27.569494
228
0.594907
mfaithfull
7854be80c217f33d28aa45dad4e7ff06fb4cb6d7
1,507
hpp
C++
src/collection_iterator.hpp
stanislav-podlesny/cpp-driver
be08fd0f6cfbf90ec98fdfbe1745e3470bdeeb1d
[ "Apache-2.0" ]
null
null
null
src/collection_iterator.hpp
stanislav-podlesny/cpp-driver
be08fd0f6cfbf90ec98fdfbe1745e3470bdeeb1d
[ "Apache-2.0" ]
null
null
null
src/collection_iterator.hpp
stanislav-podlesny/cpp-driver
be08fd0f6cfbf90ec98fdfbe1745e3470bdeeb1d
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2014-2015 DataStax 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 __CASS_COLLECTION_ITERATOR_HPP_INCLUDED__ #define __CASS_COLLECTION_ITERATOR_HPP_INCLUDED__ #include "cassandra.h" #include "iterator.hpp" #include "value.hpp" #include "serialization.hpp" namespace cass { class CollectionIterator : public Iterator { public: CollectionIterator(const Value* collection) : Iterator(CASS_ITERATOR_TYPE_COLLECTION) , collection_(collection) , position_(collection->buffer().data()) , index_(-1) , count_(collection_->type() == CASS_VALUE_TYPE_MAP ? (2 * collection_->count()) : collection->count()) {} virtual bool next(); const Value* value() { assert(index_ >= 0 && index_ < count_); return &value_; } private: char* decode_value(char* position); private: const Value* collection_; char* position_; Value value_; int32_t index_; const int32_t count_; }; } // namespace cass #endif
25.542373
74
0.711347
stanislav-podlesny
7856065930e739509cee13ad26aea5f0acf43ca8
1,035
cpp
C++
jsUnits/jsEnergy.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
jsUnits/jsEnergy.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
jsUnits/jsEnergy.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include <jsUnits/jsEnergy.h> #include <jsUnits/jsUnitClass.h> #include <Units/Energy.h> #include "jsMomentOfForce.h" #include "jsRotationalStiffness.h" using namespace DNVS::MoFa::Units; Runtime::DynamicPhenomenon jsEnergy::GetPhenomenon() { return EnergyPhenomenon(); } void jsEnergy::init(jsTypeLibrary& typeLibrary) { jsUnitClass<jsEnergy,Energy> cls(typeLibrary); if(cls.reinit()) return; cls.ImplicitConstructorConversion(&jsUnitClass<jsEnergy,Energy>::ConstructEquivalentQuantity<jsMomentOfForce>); cls.ImplicitConstructorConversion(&jsUnitClass<jsEnergy,Energy>::ConstructEquivalentQuantity<jsRotationalStiffness>); cls.ImplicitConstructorConversion([](const jsEnergy& val) {return MomentOfForce(val); }); cls.ImplicitConstructorConversion([](const jsEnergy& val) {return RotationalStiffness(val); }); }
34.5
126
0.770048
dnv-opensource
785914de32d34ecb74d516c667d9108859f24afa
697
cpp
C++
Source/Runtime/Foundation/Filesystem/FileStream.cpp
simeks/Sandbox
394b7ab774b172b6e8bc560eb2740620a8dee399
[ "MIT" ]
null
null
null
Source/Runtime/Foundation/Filesystem/FileStream.cpp
simeks/Sandbox
394b7ab774b172b6e8bc560eb2740620a8dee399
[ "MIT" ]
null
null
null
Source/Runtime/Foundation/Filesystem/FileStream.cpp
simeks/Sandbox
394b7ab774b172b6e8bc560eb2740620a8dee399
[ "MIT" ]
null
null
null
// Copyright 2008-2014 Simon Ekström #include "Common.h" #include "FileStream.h" namespace sb { FileStream::FileStream(const File& file) : _file(file) { Assert(_file.IsOpen()); } FileStream::~FileStream() { _file.Close(); } size_t FileStream::Read(void* dst, size_t size) { return _file.Read(dst, (uint32_t)size); } size_t FileStream::Write(const void* src, size_t size) { return _file.Write(src, (uint32_t)size); } int64_t FileStream::Seek(int64_t offset) { return _file.Seek(offset, File::SEEK_ORIGIN_BEGIN); } int64_t FileStream::Tell() const { return _file.Tell(); } int64_t FileStream::Length() const { return _file.Length(); } } // namespace sb
15.152174
55
0.681492
simeks
785d578f6507848e8cf41c80bbecf74b5faf81d2
7,764
cpp
C++
NtpRsk/NtpRsk.cpp
bochen8709/core
d523ee47c0cbe2db1f3cfe9e71ed77bfd4d2254d
[ "MIT" ]
1
2021-07-11T10:27:46.000Z
2021-07-11T10:27:46.000Z
NtpRsk/NtpRsk.cpp
bochen8709/core
d523ee47c0cbe2db1f3cfe9e71ed77bfd4d2254d
[ "MIT" ]
null
null
null
NtpRsk/NtpRsk.cpp
bochen8709/core
d523ee47c0cbe2db1f3cfe9e71ed77bfd4d2254d
[ "MIT" ]
null
null
null
#include <openssl/bn.h> #include "NtpRsk.h" #include <openssl/rand.h> #include <iostream> /** * A is signature, X is the signed message hash * A^e = X * * e is the RSA exponent, typically 2^16 + 1 * * The proof is d where 1 < d < e (typically 2^16) * * r is a random number, then: * * (A^d *r)^e = X^d * (r^e) mod n * t T * * * (A^d1 *r)^e = X^d1 * (r^e) mod n * (A^d2 *r)^e = X^d2 * (r^e) mod n * (A^d3 *r)^e = X^d3 * (r^e) mod n * (A^d4 *r)^e = X^d4 * (r^e) mod n * (A^d5 *r)^e = X^d5 * (r^e) mod n * * what is published is T = (r^e) * t1 = (A^d1 *r) * t2 = (A^d2 *r) * t3 = (A^d3 *r) * t4 = (A^d4 *r) * t5 = (A^d5 *r) * */ NtpRskSignatureVerificationObject* NtpRsk::signWithNtpRsk(NtpRskSignatureRequestObject *ntpRskSignatureRequestObject) { NtpRskSignatureVerificationObject *ntpRskSignatureVerificationObject = new NtpRskSignatureVerificationObject(); const BIGNUM* n = ntpRskSignatureRequestObject->getN(); const BIGNUM* e = ntpRskSignatureRequestObject->getE(); BIGNUM* e2 = BN_new(); BIGNUM* sub = BN_new(); BIGNUM* add = BN_new(); BN_dec2bn(&add, "2"); BN_dec2bn(&sub, "4"); BN_sub(e2, e, sub); BIGNUM* signature = ntpRskSignatureRequestObject->getSignature(); BIGNUM* nm = ntpRskSignatureRequestObject->getNm(); BN_CTX *ctx = BN_CTX_new(); BIGNUM* r = randomBignum(n); BIGNUM* d = BN_new(); BN_mod(d, nm, e2, ctx); BN_add(d, d, add); BIGNUM* t1 = BN_new(); BIGNUM* T = BN_new(); BIGNUM* salt = BN_new(); std::cout << "d1 : " << BN_bn2dec(d) << std::endl; std::cout << "e : " << BN_bn2dec(e) << std::endl; std::cout << "n : " << BN_bn2dec(n) << std::endl; // T = r^v BN_mod_exp(T, r, e, n, ctx); ntpRskSignatureVerificationObject->setT(T); std::cout << "T : " << BN_bn2dec(T) << std::endl; // t1 = (A^d *r) BN_mod_exp(t1, signature, d, n, ctx); BN_mod_mul(t1, t1, r, n, ctx); ntpRskSignatureVerificationObject->setT1(t1); // t2 = (A^d *r) BIGNUM* t2 = BN_new(); BIGNUM* XT = BN_new(); BN_mod_exp(XT, t1, e, n, ctx); BN_dec2bn(&salt, "1618446177786864861468428776289946168463"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t2, signature, d, n, ctx); BN_mod_mul(t2, t2, r, n, ctx); ntpRskSignatureVerificationObject->setT2(t2); // t3 = (A^d *r) BIGNUM* t3 = BN_new(); BN_mod_exp(XT, t2, e, n, ctx); BN_dec2bn(&salt, "2468284666624768462658468131846646451821"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t3, signature, d, n, ctx); BN_mod_mul(t3, t3, r, n, ctx); ntpRskSignatureVerificationObject->setT3(t3); // t4 = (A^d *r) BIGNUM* t4 = BN_new(); BN_mod_exp(XT, t3, e, n, ctx); BN_dec2bn(&salt, "386846284626847646244761844687764462164"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t4, signature, d, n, ctx); BN_mod_mul(t4, t4, r, n, ctx); ntpRskSignatureVerificationObject->setT4(t4); // t5 = (A^d *r) BIGNUM* t5 = BN_new(); BN_mod_exp(XT, t4, e, n, ctx); BN_dec2bn(&salt, "456156843515512741515122247552415322464"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t5, signature, d, n, ctx); BN_mod_mul(t5, t5, r, n, ctx); ntpRskSignatureVerificationObject->setT5(t5); ntpRskSignatureVerificationObject->setPaddedM(ntpRskSignatureRequestObject->getPaddedM()); ntpRskSignatureVerificationObject->setM(ntpRskSignatureRequestObject->getM()); ntpRskSignatureVerificationObject->setNm(ntpRskSignatureRequestObject->getNm()); ntpRskSignatureVerificationObject->setE(ntpRskSignatureRequestObject->getE()); ntpRskSignatureVerificationObject->setN(ntpRskSignatureRequestObject->getN()); ntpRskSignatureVerificationObject->setMdAlg(ntpRskSignatureRequestObject->getMdAlg()); ntpRskSignatureVerificationObject->setSignedPayload(ntpRskSignatureRequestObject->getSignedPayload()); return ntpRskSignatureVerificationObject; } bool NtpRsk::verifyNtpRsk(NtpRskSignatureVerificationObject *ntpRskSignatureVerificationObject) { BIGNUM* T = ntpRskSignatureVerificationObject->getT(); BIGNUM* t1 = ntpRskSignatureVerificationObject->getT1(); BIGNUM* t2 = ntpRskSignatureVerificationObject->getT2(); BIGNUM* t3 = ntpRskSignatureVerificationObject->getT3(); BIGNUM* t4 = ntpRskSignatureVerificationObject->getT4(); BIGNUM* t5 = ntpRskSignatureVerificationObject->getT5(); const BIGNUM* e = ntpRskSignatureVerificationObject->getE(); BIGNUM* e2 = BN_new(); BIGNUM* sub = BN_new(); BIGNUM* add = BN_new(); BN_dec2bn(&add, "2"); BN_dec2bn(&sub, "4"); BN_sub(e2, e, sub); const BIGNUM* n = ntpRskSignatureVerificationObject->getN(); BIGNUM* m = ntpRskSignatureVerificationObject->getPaddedM(); BIGNUM* nm = ntpRskSignatureVerificationObject->getNm(); BN_CTX *ctx = BN_CTX_new(); // verify t^v = X^d * T mod n BIGNUM* XT = BN_new(); BIGNUM* salt = BN_new(); BIGNUM* d = BN_new(); BN_mod(d, nm, e2, ctx); BN_add(d, d, add); BN_mod_exp(t1, t1, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t1) != 0) { std::cout << "d1 : " << BN_bn2dec(d) << std::endl; std::cout << "e1 : " << BN_bn2dec(e) << std::endl; std::cout << "n1 : " << BN_bn2dec(n) << std::endl; std::cout << "T1 : " << BN_bn2dec(T) << std::endl; std::cout << "BN_cmp(XT, t1) failed" << std::endl; std::cout << "XT " << BN_bn2dec(XT) << std::endl; std::cout << "t1 " << BN_bn2dec(t1) << std::endl; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "1618446177786864861468428776289946168463"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t2, t2, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t2) != 0) { std::cout << "BN_cmp(XT, t2) failed"; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "2468284666624768462658468131846646451821"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t3, t3, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t3) != 0) { std::cout << "BN_cmp(XT, t3) failed" << std::endl; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "386846284626847646244761844687764462164"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t4, t4, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t4) != 0) { std::cout << "BN_cmp(XT, t4) failed" << std::endl; BN_CTX_free(ctx); return false; } // verify t^v = X^d * T mod n BN_dec2bn(&salt, "456156843515512741515122247552415322464"); BN_add(XT, XT, salt); BN_mod(d, XT, e2, ctx); BN_add(d, d, add); BN_mod_exp(t5, t5, e, n, ctx); BN_mod_exp(XT, m, d, n, ctx); BN_mod_mul(XT, XT, T, n, ctx); if(BN_cmp(XT, t5) != 0) { std::cout << "BN_cmp(XT, t5) failed" << std::endl; BN_CTX_free(ctx); return false; } BN_CTX_free(ctx); return true; } BIGNUM* NtpRsk::randomBignum(const BIGNUM* maxSize) { int byteLength = BN_num_bytes(maxSize); unsigned char buf[byteLength]; RAND_bytes(buf, byteLength); return BN_bin2bn(buf, byteLength, NULL); }
30.932271
119
0.607805
bochen8709
785e169d4eb1829aa7edce93cd7a20a7269ce9f2
6,418
hpp
C++
SU2-Quantum/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CCGNSMeshReaderFVM.hpp * \brief Header file for the class CCGNSMeshReaderFVM. * The implementations are in the <i>CCGNSMeshReaderFVM.cpp</i> file. * \author T. Economon * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 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. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #ifdef HAVE_CGNS #include "cgnslib.h" #endif #include "CMeshReaderFVM.hpp" /*! * \class CCGNSMeshReaderFVM * \brief Reads a CGNS zone into linear partitions for the finite volume solver (FVM). * \author: T. Economon */ class CCGNSMeshReaderFVM: public CMeshReaderFVM { private: #ifdef HAVE_CGNS int cgnsFileID; /*!< \brief CGNS file identifier. */ int cgnsBase; /*!< \brief CGNS database index. */ int cgnsZone; /*!< \brief CGNS zone index. */ int nZones; /*!< \brief Total number of zones in the CGNS file. */ int nSections; /*!< \brief Total number of sections in the CGNS file. */ vector<bool> isInterior; /*!< \brief Vector of booleans to store whether each section in the CGNS file is an interior or boundary section. */ vector<unsigned long> nElems; /*!< \brief Vector containing the local number of elements found within each CGNS section. */ vector<unsigned long> elemOffset; /*!< \brief Global ID offset for each interior section (i.e., the total number of global elements that came before it). */ vector<vector<cgsize_t> > connElems; /*!< \brief Vector containing the local element connectivity found within each CGNS section. First index is the section, second contains the connectivity in format [globalID VTK n1 n2 n3 n4 n5 n6 n7 n8] for each element. */ vector<vector<char> > sectionNames; /*!< \brief Vector for storing the names of each boundary section (marker). */ /*! * \brief Open the CGNS file and checks for errors. * \param[in] val_filename - string name of the CGNS file to be read. */ void OpenCGNSFile(string val_filename); /*! * \brief Reads all CGNS database metadata and checks for errors. */ void ReadCGNSDatabaseMetadata(); /*! * \brief Reads all CGNS zone metadata and checks for errors. */ void ReadCGNSZoneMetadata(); /*! * \brief Reads the grid points from a CGNS zone into linear partitions across all ranks. */ void ReadCGNSPointCoordinates(); /*! * \brief Reads the metadata for each CGNS section in a zone and collect information, including the size and whether it is an interior or boundary section. */ void ReadCGNSSectionMetadata(); /*! * \brief Reads the interior volume elements from one section of a CGNS zone into linear partitions across all ranks. * \param[in] val_section - CGNS section index. */ void ReadCGNSVolumeSection(int val_section); /*! * \brief Reads the surface (boundary) elements from the CGNS zone. Only the master rank currently reads and stores the connectivity, which is linearly partitioned later. * \param[in] val_section - CGNS section index. */ void ReadCGNSSurfaceSection(int val_section); /*! * \brief Reformats the CGNS volume connectivity from file into the standard base class data structures. */ void ReformatCGNSVolumeConnectivity(); /*! * \brief Reformats the CGNS volume connectivity from file into the standard base class data structures. */ void ReformatCGNSSurfaceConnectivity(); /*! * \brief Get the VTK type and string name for a CGNS element type. * \param[in] val_elem_type - CGNS element type. * \param[out] val_vtk_type - VTK type identifier index. * \returns String containing the name of the element type. */ string GetCGNSElementType(ElementType_t val_elem_type, int &val_vtk_type); #endif /*! * \brief Routine to launch non-blocking sends and recvs amongst all processors. * \param[in] bufSend - Buffer of data to be sent. * \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage format. * \param[in] sendReq - Array of MPI send requests. * \param[in] bufRecv - Buffer of data to be received. * \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative storage format. * \param[in] sendReq - Array of MPI recv requests. * \param[in] countPerElem - Pieces of data per element communicated. */ void InitiateCommsAll(void *bufSend, const int *nElemSend, SU2_MPI::Request *sendReq, void *bufRecv, const int *nElemRecv, SU2_MPI::Request *recvReq, unsigned short countPerElem, unsigned short commType); /*! * \brief Routine to complete the set of non-blocking communications launched with InitiateComms() with MPI_Waitany(). * \param[in] nSends - Number of sends to be completed. * \param[in] sendReq - Array of MPI send requests. * \param[in] nRecvs - Number of receives to be completed. * \param[in] sendReq - Array of MPI recv requests. */ void CompleteCommsAll(int nSends, SU2_MPI::Request *sendReq, int nRecvs, SU2_MPI::Request *recvReq); public: /*! * \brief Constructor of the CCGNSMeshReaderFVM class. */ CCGNSMeshReaderFVM(CConfig *val_config, unsigned short val_iZone, unsigned short val_nZone); /*! * \brief Destructor of the CCGNSMeshReaderFVM class. */ ~CCGNSMeshReaderFVM(void); };
38.89697
262
0.677158
Agony5757
78644bcea21477a3d64a6355845324d2669e0442
11,011
cpp
C++
rmf_task/src/rmf_task/requests/Delivery.cpp
Rouein/rmf_task
32de25ff127aed754ca760ef462ef8c3e7dd56a1
[ "Apache-2.0" ]
null
null
null
rmf_task/src/rmf_task/requests/Delivery.cpp
Rouein/rmf_task
32de25ff127aed754ca760ef462ef8c3e7dd56a1
[ "Apache-2.0" ]
null
null
null
rmf_task/src/rmf_task/requests/Delivery.cpp
Rouein/rmf_task
32de25ff127aed754ca760ef462ef8c3e7dd56a1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <map> #include <rmf_task/requests/Delivery.hpp> namespace rmf_task { namespace requests { //============================================================================== class Delivery::Model : public Task::Model { public: std::optional<Estimate> estimate_finish( const State& initial_state, const Constraints& task_planning_constraints, const TravelEstimator& travel_estimator) const final; rmf_traffic::Duration invariant_duration() const final; Model( const rmf_traffic::Time earliest_start_time, const Parameters& parameters, std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait); private: rmf_traffic::Time _earliest_start_time; Parameters _parameters; std::size_t _pickup_waypoint; std::size_t _dropoff_waypoint; rmf_traffic::Duration _invariant_duration; double _invariant_battery_drain; }; //============================================================================== Delivery::Model::Model( const rmf_traffic::Time earliest_start_time, const Parameters& parameters, std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait) : _earliest_start_time(earliest_start_time), _parameters(parameters), _pickup_waypoint(pickup_waypoint), _dropoff_waypoint(dropoff_waypoint) { // Calculate duration of invariant component of task _invariant_duration = pickup_wait + dropoff_wait; _invariant_battery_drain = _parameters.ambient_sink()->compute_change_in_charge( rmf_traffic::time::to_seconds(pickup_wait + dropoff_wait)); if (_pickup_waypoint != _dropoff_waypoint) { rmf_traffic::agv::Planner::Start start{ _earliest_start_time, _pickup_waypoint, 0.0}; rmf_traffic::agv::Planner::Goal goal{_dropoff_waypoint}; const auto result_to_dropoff = _parameters.planner()->plan(start, goal); auto itinerary_start_time = _earliest_start_time; for (const auto& itinerary : result_to_dropoff->get_itinerary()) { const auto& trajectory = itinerary.trajectory(); const auto& finish_time = *trajectory.finish_time(); const auto itinerary_duration = finish_time - itinerary_start_time; // Compute the invariant battery drain const double dSOC_motion = _parameters.motion_sink()->compute_change_in_charge(trajectory); const double dSOC_device = _parameters.ambient_sink()->compute_change_in_charge( rmf_traffic::time::to_seconds(itinerary_duration)); _invariant_battery_drain += dSOC_motion + dSOC_device; _invariant_duration += itinerary_duration; itinerary_start_time = finish_time; } } } //============================================================================== std::optional<rmf_task::Estimate> Delivery::Model::estimate_finish( const State& initial_state, const Constraints& task_planning_constraints, const TravelEstimator& travel_estimator) const { rmf_traffic::agv::Plan::Start final_plan_start{ initial_state.time().value(), _dropoff_waypoint, initial_state.orientation().value()}; auto state = State().load_basic( std::move(final_plan_start), initial_state.dedicated_charging_waypoint().value(), initial_state.battery_soc().value()); rmf_traffic::Duration variant_duration(0); double battery_soc = initial_state.battery_soc().value(); const bool drain_battery = task_planning_constraints.drain_battery(); const auto& ambient_sink = *_parameters.ambient_sink(); const double battery_threshold = task_planning_constraints.threshold_soc(); // Factor in battery drain while moving to start waypoint of task if (initial_state.waypoint() != _pickup_waypoint) { const auto travel = travel_estimator.estimate( initial_state.extract_plan_start().value(), _pickup_waypoint); if (!travel) return std::nullopt; variant_duration = travel->duration(); if (drain_battery) battery_soc = battery_soc - travel->change_in_charge(); if (battery_soc <= battery_threshold) return std::nullopt; } const rmf_traffic::Time ideal_start = _earliest_start_time - variant_duration; const rmf_traffic::Time wait_until = initial_state.time().value() > ideal_start ? initial_state.time().value() : ideal_start; // Factor in battery drain while waiting to move to start waypoint. If a robot // is initially at a charging waypoint, it is assumed to be continually charging if (drain_battery && wait_until > initial_state.time().value() && initial_state.waypoint() != initial_state.dedicated_charging_waypoint()) { const rmf_traffic::Duration wait_duration( wait_until - initial_state.time().value()); const double dSOC_device = ambient_sink.compute_change_in_charge( rmf_traffic::time::to_seconds(wait_duration)); battery_soc = battery_soc - dSOC_device; if (battery_soc <= battery_threshold) return std::nullopt; } // Factor in invariants state.time(wait_until + variant_duration + _invariant_duration); if (drain_battery) { // Calculate how much battery is drained while waiting for the pickup and // waiting for the dropoff battery_soc -= _invariant_battery_drain; if (battery_soc <= battery_threshold) return std::nullopt; // Check if the robot has enough charge to head back to nearest charger if (_dropoff_waypoint != state.dedicated_charging_waypoint().value()) { const auto travel = travel_estimator.estimate( state.extract_plan_start().value(), state.dedicated_charging_waypoint().value()); if (!travel.has_value()) return std::nullopt; if (battery_soc - travel->change_in_charge() <= battery_threshold) return std::nullopt; } state.battery_soc(battery_soc); } return Estimate(state, wait_until); } //============================================================================== rmf_traffic::Duration Delivery::Model::invariant_duration() const { return _invariant_duration; } //============================================================================== class Delivery::Description::Implementation { public: std::size_t pickup_waypoint; rmf_traffic::Duration pickup_wait; std::size_t dropoff_waypoint; rmf_traffic::Duration dropoff_wait; rmf_task::Payload payload; std::string pickup_from_dispenser; std::string dropoff_to_ingestor; }; //============================================================================== Task::ConstDescriptionPtr Delivery::Description::make( std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait, Payload payload, std::string pickup_from_dispenser, std::string dropoff_to_ingestor) { std::shared_ptr<Description> delivery(new Description()); delivery->_pimpl = rmf_utils::make_impl<Implementation>( Implementation{ pickup_waypoint, pickup_wait, dropoff_waypoint, dropoff_wait, std::move(payload), std::move(pickup_from_dispenser), std::move(dropoff_to_ingestor) }); return delivery; } //============================================================================== Delivery::Description::Description() { // Do nothing } //============================================================================== Task::ConstModelPtr Delivery::Description::make_model( rmf_traffic::Time earliest_start_time, const Parameters& parameters) const { return std::make_shared<Delivery::Model>( earliest_start_time, parameters, _pimpl->pickup_waypoint, _pimpl->pickup_wait, _pimpl->dropoff_waypoint, _pimpl->dropoff_wait); } //============================================================================== auto Delivery::Description::generate_info( const State&, const Parameters& parameters) const -> Info { const auto& graph = parameters.planner()->get_configuration().graph(); return Info{ "Delivery from " + standard_waypoint_name(graph, _pimpl->pickup_waypoint) + " to " + standard_waypoint_name(graph, _pimpl->dropoff_waypoint), "" // TODO(MXG): Add details about the payload }; } //============================================================================== std::size_t Delivery::Description::pickup_waypoint() const { return _pimpl->pickup_waypoint; } //============================================================================== std::string Delivery::Description::pickup_from_dispenser() const { return _pimpl->pickup_from_dispenser; } //============================================================================== std::string Delivery::Description::dropoff_to_ingestor() const { return _pimpl->dropoff_to_ingestor; } //============================================================================== rmf_traffic::Duration Delivery::Description::pickup_wait() const { return _pimpl->pickup_wait; } //============================================================================== rmf_traffic::Duration Delivery::Description::dropoff_wait() const { return _pimpl->dropoff_wait; } //============================================================================== std::size_t Delivery::Description::dropoff_waypoint() const { return _pimpl->dropoff_waypoint; } //============================================================================== const Payload& Delivery::Description::payload() const { return _pimpl->payload; } //============================================================================== ConstRequestPtr Delivery::make( std::size_t pickup_waypoint, rmf_traffic::Duration pickup_wait, std::size_t dropoff_waypoint, rmf_traffic::Duration dropoff_wait, Payload payload, const std::string& id, rmf_traffic::Time earliest_start_time, ConstPriorityPtr priority, bool automatic, std::string pickup_from_dispenser, std::string dropoff_to_ingestor) { const auto description = Description::make( pickup_waypoint, pickup_wait, dropoff_waypoint, dropoff_wait, std::move(payload), std::move(pickup_from_dispenser), std::move(dropoff_to_ingestor)); return std::make_shared<Request>( id, earliest_start_time, std::move(priority), description, automatic); } } // namespace requests } // namespace rmf_task
31.550143
82
0.647625
Rouein
786c621a3913178ff704534f47c67e734488b933
2,324
cpp
C++
Test/ListenerTest/Test_listener.cpp
tzimer/private-transaction-families
f67a1fe9fdb8a4525736114dc2e464eb4b6d595e
[ "Apache-2.0" ]
null
null
null
Test/ListenerTest/Test_listener.cpp
tzimer/private-transaction-families
f67a1fe9fdb8a4525736114dc2e464eb4b6d595e
[ "Apache-2.0" ]
null
null
null
Test/ListenerTest/Test_listener.cpp
tzimer/private-transaction-families
f67a1fe9fdb8a4525736114dc2e464eb4b6d595e
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "data_map.h" #include "rest_handler.h" #include "Enclave_u.h" #include "mock_sawtooth.h" #include "config.h" #include "txn_handler.h" //declare the extern global std::string config::g_key_path; std::string config::g_rest_url; std::string addr1, addr2, addr3; namespace txn_handler { sawtooth::GlobalStateUPtr contextPtr; } using namespace listener; void set_sawtooth_mock() { std::unique_ptr<SawtoothStateMock> mock_ctx_uptr(new SawtoothStateMock); txn_handler::contextPtr = std::move(mock_ctx_uptr); } void SetUpListener() { set_sawtooth_mock(); std::array<uint8_t, ADDRESS_LENGTH / 2> addr_bytes = {}; std::iota(std::begin(addr_bytes), std::end(addr_bytes), 13); addr1 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str(); std::iota(std::begin(addr_bytes), std::end(addr_bytes), 25); addr2 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str(); std::iota(std::begin(addr_bytes), std::end(addr_bytes), 41); addr3 = ToHexString(addr_bytes.data(), addr_bytes.size()).c_str(); } TEST(Listener, tl_call_stl_write) { std::string str = "mock value in addr1"; ASSERT_EQ(tl_call_stl_write(addr1.c_str(), str.c_str(), str.size() + 1), 0); } TEST(Listener, tl_call_stl_read) { uint32_t id; std::vector<char> value = {}; std::string res_str = "mock value in addr1"; int res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), 0); ASSERT_EQ(res_len, res_str.size() + 1); value.reserve(res_len); res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), res_len); ASSERT_EQ(res_len, res_str.size() + 1); ASSERT_EQ(std::string(std::begin(value), std::begin(value) + res_len - 1), res_str.c_str()); // read again should return empty string res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), res_len); ASSERT_EQ(res_len, 0); } TEST(Listener, tl_call_stl_delete) { ASSERT_EQ(tl_call_stl_delete(addr1.c_str(), 1), 0); uint32_t id; std::vector<char> value = {}; int res_len = tl_call_stl_read(&id, addr1.c_str(), value.data(), 0); ASSERT_EQ(res_len, 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); SetUpListener(); auto ret = RUN_ALL_TESTS(); deleteAllValues(); return ret; }
29.794872
96
0.686317
tzimer
786c9acf12e9132b25b1f5767186dfd6a1a0e1b3
2,680
cpp
C++
mygraphicsscene.cpp
rbax/qtKabuChart
0604b32389e897174da3bb342bdee21ead498c7c
[ "MIT" ]
1
2021-02-16T10:49:00.000Z
2021-02-16T10:49:00.000Z
mygraphicsscene.cpp
rbax/qtKabuChart
0604b32389e897174da3bb342bdee21ead498c7c
[ "MIT" ]
null
null
null
mygraphicsscene.cpp
rbax/qtKabuChart
0604b32389e897174da3bb342bdee21ead498c7c
[ "MIT" ]
null
null
null
/********************************************************************* * Copyright (c) 2016 nari * This source is released under the MIT license * http://opensource.org/licenses/mit-license.php * * This source code is a modification of article website below. * http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php * Cppyright (c) Walletfox.com, 2014 * *******************************************************************/ #include "mygraphicsscene.h" #include <QDebug> /* *refer to * How to draw QGraphicsLineItem during run time with mouse coordinates * http://www.walletfox.com/course/qgraphicsitemruntimedrawing.php */ MyGraphicsScene::MyGraphicsScene(QObject* parent) { sceneMode = NoMode; itemToDraw = 0; } void MyGraphicsScene::setLineColor(QString colorname){ lineColor = colorname; } void MyGraphicsScene::clearDraw(){ //lineを消せない //itemToDraw->~QGraphicsLineItem(); if(freeLines.count() > 0){ for(int i = 0; i < freeLines.count() ; i++){ //freeLines.at(i)->setVisible(false); QGraphicsLineItem *item = freeLines.at(i); freeLines.removeAt(i); //これ必要 delete item; //freeLines.at(i)->~QGraphicsLineItem(); } } } void MyGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event){ if(sceneMode == DrawLine) origPoint = event->scenePos(); QGraphicsScene::mousePressEvent(event); } void MyGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event){ if(sceneMode == DrawLine){ if(!itemToDraw && origPoint.x() > 0 && origPoint.y() > 0){ itemToDraw = new QGraphicsLineItem; this->addItem(itemToDraw); freeLines.append(itemToDraw); QPen pen; pen.setColor(lineColor); pen.setWidth(3); pen.setStyle(Qt::SolidLine); itemToDraw->setPen(pen); itemToDraw->setPos(origPoint); } if(origPoint.x() > 0 && origPoint.y() > 0){ itemToDraw->setLine(0,0,event->scenePos().x() - origPoint.x(),event->scenePos().y() - origPoint.y()); } } else QGraphicsScene::mouseMoveEvent(event); } void MyGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ itemToDraw = 0; sceneMode = NoMode; QGraphicsScene::mouseReleaseEvent(event); } void MyGraphicsScene::setMode(Mode mode){ sceneMode = mode; itemToDraw = 0; } void MyGraphicsScene::setModeDraw(){ sceneMode = DrawLine; origPoint.setX(-1); origPoint.setY(-1); itemToDraw = 0; }
29.130435
114
0.587687
rbax
786fcc1bb43f7f1a89aee484c9057dbaf2eb0488
8,152
hxx
C++
include/crab/streams.hxx
hrissan/crablib
db86e5f52acddcc233aec755d5fce0e6f19c0e21
[ "MIT" ]
3
2020-02-13T02:08:06.000Z
2020-10-06T16:26:30.000Z
include/crab/streams.hxx
hrissan/crablib
db86e5f52acddcc233aec755d5fce0e6f19c0e21
[ "MIT" ]
null
null
null
include/crab/streams.hxx
hrissan/crablib
db86e5f52acddcc233aec755d5fce0e6f19c0e21
[ "MIT" ]
null
null
null
// Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan // Licensed under the MIT License. See LICENSE for details. #include <algorithm> #include <cstring> #include <iostream> #include <limits> #include <stdexcept> #include "streams.hpp" namespace crab { CRAB_INLINE void IStream::read(uint8_t *val, size_t count) { while (count != 0) { size_t rc = read_some(val, count); if (rc == 0) throw std::runtime_error("crab::IStream reading from empty stream"); val += rc; count -= rc; } } CRAB_INLINE void OStream::write(const uint8_t *val, size_t count) { while (count != 0) { size_t wc = write_some(val, count); if (wc == 0) throw std::runtime_error("crab::OStream writing to full stream"); val += wc; count -= wc; } } CRAB_INLINE size_t Buffer::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, read_count()); std::memcpy(val, read_ptr(), rc); did_read(rc); return rc; } CRAB_INLINE size_t Buffer::write_some(const uint8_t *val, size_t count) { size_t rc = std::min(count, write_count()); std::memcpy(write_ptr(), val, rc); did_write(rc); return rc; } CRAB_INLINE size_t Buffer::read_from(IStream &in) { size_t total_count = 0; while (true) { size_t wc = write_count(); if (wc == 0) break; size_t count = in.read_some(write_ptr(), wc); did_write(count); total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t Buffer::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(read_count(), max_count); if (rc == 0) break; size_t count = out.write_some(read_ptr(), rc); did_read(count); max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE bool Buffer::read_enough_data(IStream &in, size_t count) { if (size() < count) read_from(in); return size() >= count; } CRAB_INLINE bool Buffer::peek(uint8_t *val, size_t count) const { // Compiler thinks memcpy can affect "this", local vars greatly help auto rc = read_count(); auto rc2 = read_count2(); if (rc + rc2 < count) return false; auto rp = read_ptr(); if (rc >= count) { std::memcpy(val, rp, count); return true; } std::memcpy(val, rp, rc); std::memcpy(val + rc, read_ptr2(), count - rc); return true; } /* // Invariant - at least 1 chunk in rope container to avoid ifs Rope::Rope(size_t chunk_size) : chunk_size(chunk_size) { rope.emplace_back(chunk_size); } void Rope::clear() { if (rope.size() >= 1) { Buffer buf = std::move(rope.front()); rope.clear(); rope.push_back(std::move(buf)); } else { rope.clear(); rope.emplace_back(chunk_size); } rope_size = 0; } void Rope::did_write(size_t count) { rope_size += count; rope.back().did_write(count); if (rope.back().full()) rope.emplace_back(chunk_size); } void Rope::did_read(size_t count) { invariant(count <= rope_size, "Rope underflow"); rope_size -= count; rope.front().did_read(count); if (rope.front().empty()) { rope.pop_front(); if (rope.empty()) rope.emplace_back(chunk_size); } } size_t Rope::read_from(IStream &in) { size_t total_count = 0; while (true) { size_t wc = write_count(); if (wc == 0) break; size_t count = in.read_some(write_ptr(), wc); did_write(count); total_count += count; if (count == 0) break; } return total_count; } size_t Rope::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(read_count(), max_count); if (rc == 0) break; size_t count = out.write_some(read_ptr(), rc); did_read(count); max_count -= count; total_count += count; if (count == 0) break; } return total_count; }*/ /*void Buffer::write(const uint8_t *val, size_t count) { size_t rc = std::min(count, write_count()); std::memcpy(write_ptr(), val, rc); did_write(rc); val += rc; count -= rc; if (count == 0) return; rc = std::min(count, write_count()); std::memcpy(write_ptr(), val, rc); did_write(rc); val += rc; count -= rc; if (count == 0) return; throw std::runtime_error("Buffer overflow"); } void Buffer::write(const char *val, size_t count) { write(reinterpret_cast<const uint8_t *>(val), count); }*/ CRAB_INLINE size_t IMemoryStream::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, si); std::memcpy(val, data, rc); data += rc; si -= rc; return rc; } CRAB_INLINE size_t IMemoryStream::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(size(), max_count); if (rc == 0) break; size_t count = out.write_some(data, rc); data += count; si -= rc; max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t OMemoryStream::write_some(const uint8_t *val, size_t count) { size_t rc = std::min(count, si); std::memcpy(data, val, rc); data += rc; si -= rc; return rc; } CRAB_INLINE size_t IVectorStream::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, rimpl->size() - read_pos); std::memcpy(val, rimpl->data() + read_pos, rc); read_pos += rc; return rc; } CRAB_INLINE size_t IVectorStream::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(size(), max_count); if (rc == 0) break; size_t count = out.write_some(rimpl->data() + read_pos, rc); read_pos += count; max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t OVectorStream::write_some(const uint8_t *val, size_t count) { wimpl->insert(wimpl->end(), val, val + count); return count; } CRAB_INLINE size_t IStringStream::read_some(uint8_t *val, size_t count) { size_t rc = std::min(count, rimpl->size() - read_pos); std::memcpy(val, rimpl->data() + read_pos, rc); read_pos += rc; return rc; } CRAB_INLINE size_t IStringStream::write_to(OStream &out, size_t max_count) { size_t total_count = 0; while (true) { size_t rc = std::min(size(), max_count); if (rc == 0) break; size_t count = out.write_some(rimpl->data() + read_pos, rc); read_pos += count; max_count -= count; total_count += count; if (count == 0) break; } return total_count; } CRAB_INLINE size_t OStringStream::write_some(const uint8_t *val, size_t count) { wimpl->insert(wimpl->end(), val, val + count); return count; } /* // Some experimental code // Inspirated by boost::streams class IStreamBuffer { static constexpr size_t SMALL_READ = 256; static constexpr size_t BUFFER_SIZE = SMALL_READ * 4; uint8_t buffer_storage[BUFFER_SIZE]; uint8_t *buffer = buffer_storage; size_t buffer_size = 0; IStreamRaw *raw_stream; public: void read(uint8_t *data, size_t size) { if (size <= buffer_size) { // Often, also when zero size std::memcpy(data, buffer, size); buffer += size; buffer_size -= size; return; } // size > 0 here std::memcpy(data, buffer, buffer_size); buffer = buffer_storage; buffer_size = 0; size -= buffer_size; data += buffer_size; if (size < BUFFER_SIZE / 4) { // Often buffer_size = raw_stream->read_some(buffer, BUFFER_SIZE); if (buffer_size == 0) throw std::runtime_error("IStreamRaw underflow"); std::memcpy(data, buffer, size); buffer += size; buffer_size -= size; return; } // size > 0 here while (true) { size_t cou = raw_stream->read_some(data, size); if (cou == 0) throw std::runtime_error("IStreamRaw underflow"); size -= cou; data += cou; if (size == 0) return; } }; }; */ } // namespace crab
24.70303
80
0.616658
hrissan
7870d51f7968bced59fbe92f44aaadb74120d3b1
935
hpp
C++
entregas/01-cifrado/CifradoVigenere.hpp
gerardogtn/Calidad-y-Pruebas-de-Software
ed338b5627a343b7dee366aaa36cd735f74e53af
[ "MIT" ]
null
null
null
entregas/01-cifrado/CifradoVigenere.hpp
gerardogtn/Calidad-y-Pruebas-de-Software
ed338b5627a343b7dee366aaa36cd735f74e53af
[ "MIT" ]
null
null
null
entregas/01-cifrado/CifradoVigenere.hpp
gerardogtn/Calidad-y-Pruebas-de-Software
ed338b5627a343b7dee366aaa36cd735f74e53af
[ "MIT" ]
null
null
null
// Copyright 2017 Gerardo Teruel #ifndef UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_ #define UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_ #include <string> class CifradoVigenere : public Cifrado { private: const std::string key; public: explicit CifradoVigenere(const std::string key) : key(key) {} virtual ~CifradoVigenere() {} virtual std::string decipher(const std::string& cipher) { std::string out = ""; int special = 0; for (int i = 0; i < cipher.size(); i++) { if (cipher[i] == '.' || cipher[i] == ' ') { special++; out.append(1, cipher[i]); } else { /** int to be able to hold negative numbers */ int c = cipher[i] - key[(i - special) % key.size()]; if (c < 0) { out.append(1, 91 + c); } else { out.append(1, (c % 26) + 65); } } } return out; } }; #endif // UNITARIAS_EJERCICIO03_CIFRADOVIGENERE_H_
23.375
63
0.581818
gerardogtn
787601bab6e036ffa10b8ead9aa11363a2b98cb0
5,170
cpp
C++
src/asm/Instruction.cpp
rigred/VC4C
6c900c0e2fae2cbdd22c5adb044f385ae005468a
[ "MIT" ]
null
null
null
src/asm/Instruction.cpp
rigred/VC4C
6c900c0e2fae2cbdd22c5adb044f385ae005468a
[ "MIT" ]
null
null
null
src/asm/Instruction.cpp
rigred/VC4C
6c900c0e2fae2cbdd22c5adb044f385ae005468a
[ "MIT" ]
null
null
null
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "Instruction.h" #include "../Values.h" #include "ALUInstruction.h" #include "BranchInstruction.h" #include "LoadInstruction.h" #include "SemaphoreInstruction.h" #include <cstdbool> #include <memory> using namespace vc4c; using namespace vc4c::qpu_asm; LCOV_EXCL_START std::string Instruction::toASMString() const { if(auto op = as<ALUInstruction>()) return op->toASMString(); if(auto op = as<BranchInstruction>()) return op->toASMString(); if(auto op = as<LoadInstruction>()) return op->toASMString(); if(auto op = as<SemaphoreInstruction>()) return op->toASMString(); throw CompilationError(CompilationStep::CODE_GENERATION, "Invalid instruction type", std::to_string(value)); } std::string Instruction::toHexString(bool withAssemblerCode) const { uint64_t binaryCode = toBinaryCode(); if(withAssemblerCode) { return qpu_asm::toHexString(binaryCode) + "//" + toASMString(); } return qpu_asm::toHexString(binaryCode); } LCOV_EXCL_STOP bool Instruction::isValidInstruction() const { return as<ALUInstruction>() || as<BranchInstruction>() || as<LoadInstruction>() || as<SemaphoreInstruction>(); } Register Instruction::getAddOutput() const { Register reg{RegisterFile::PHYSICAL_ANY, getAddOut()}; if(reg.isAccumulator() && reg.getAccumulatorNumber() != 4) // cannot write to accumulator r4, instead will write "tmu_noswap" which should be handled as such return Register{RegisterFile::ACCUMULATOR, reg.num}; if(getWriteSwap() == WriteSwap::SWAP) return Register{RegisterFile::PHYSICAL_B, reg.num}; return Register{RegisterFile::PHYSICAL_A, reg.num}; } Register Instruction::getMulOutput() const { Register reg{RegisterFile::PHYSICAL_ANY, getMulOut()}; if(reg.isAccumulator() && reg.getAccumulatorNumber() != 4) // cannot write to accumulator r4, instead will write "tmu_noswap" which should be handled as such return Register{RegisterFile::ACCUMULATOR, reg.num}; if(getWriteSwap() == WriteSwap::DONT_SWAP) return Register{RegisterFile::PHYSICAL_B, reg.num}; return Register{RegisterFile::PHYSICAL_A, reg.num}; } LCOV_EXCL_START std::string Instruction::toInputRegister( const InputMultiplex mux, const Address regA, const Address regB, const bool hasImmediate) { if(mux == InputMultiplex::ACC0) return "r0"; if(mux == InputMultiplex::ACC1) return "r1"; if(mux == InputMultiplex::ACC2) return "r2"; if(mux == InputMultiplex::ACC3) return "r3"; if(mux == InputMultiplex::ACC4) return "r4"; if(mux == InputMultiplex::ACC5) return "r5"; // general register-file if(mux == InputMultiplex::REGA) { const Register tmp{RegisterFile::PHYSICAL_A, regA}; return tmp.to_string(true, true); } else if(hasImmediate) { // is immediate value return static_cast<SmallImmediate>(regB).to_string(); } else { const Register tmp{RegisterFile::PHYSICAL_B, regB}; return tmp.to_string(true, true); } } std::string Instruction::toOutputRegister(bool regFileA, const Address reg) { const Register tmp{regFileA ? RegisterFile::PHYSICAL_A : RegisterFile::PHYSICAL_B, reg}; return tmp.to_string(true, false); } std::string Instruction::toExtrasString(const Signaling sig, const ConditionCode cond, const SetFlag flags, const Unpack unpack, const Pack pack, bool usesOutputA, bool usesInputAOrR4) { std::string result{}; if(sig != SIGNAL_NONE && sig != SIGNAL_ALU_IMMEDIATE) result += std::string(".") + sig.to_string(); if(cond != COND_ALWAYS) result += std::string(".") + cond.to_string(); if(flags == SetFlag::SET_FLAGS) result += std::string(".") + toString(flags); if(usesInputAOrR4 && unpack.hasEffect()) result += std::string(".") + unpack.to_string(); if(usesOutputA && pack.hasEffect()) result += std::string(".") + pack.to_string(); return result; } std::string qpu_asm::toHexString(const uint64_t code) { // lower half before upper half char buffer[64]; snprintf(buffer, sizeof(buffer), "0x%08x, 0x%08x, ", static_cast<uint32_t>(code & 0xFFFFFFFFLL), static_cast<uint32_t>((code & 0xFFFFFFFF00000000LL) >> 32)); return buffer; } std::string DecoratedInstruction::toASMString(bool addComments) const { auto tmp = instruction.toASMString(); return addComments ? addComment(std::move(tmp)) : tmp; } std::string DecoratedInstruction::toHexString(bool withAssemblerCode) const { auto tmp = instruction.toHexString(withAssemblerCode); if(withAssemblerCode) { return addComment(std::move(tmp)); } return tmp; } std::string DecoratedInstruction::addComment(std::string&& s) const { std::string r; if(!comment.empty()) r = s.append(" // ").append(comment); else r = s; if(!previousComment.empty()) r = "// " + previousComment + "\n" + r; return r; } LCOV_EXCL_STOP
30.77381
114
0.67234
rigred
78796f3c89bf6e8a8d616f7be1ffc902210e22fe
67,345
cpp
C++
test/word_break_34.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
null
null
null
test/word_break_34.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
1
2021-03-05T12:56:59.000Z
2021-03-05T13:11:53.000Z
test/word_break_34.cpp
eightysquirrels/text
d935545648777786dc196a75346cde8906da846a
[ "BSL-1.0" ]
3
2019-10-30T18:38:15.000Z
2021-03-05T12:10:13.000Z
// Warning! This file is autogenerated. #include <boost/text/word_break.hpp> #include <gtest/gtest.h> #include <algorithm> TEST(word, breaks_34) { // ÷ 0031 × 002E × 2060 × 0031 ÷ 0027 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] APOSTROPHE (Single_Quote) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x27 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 0027 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] APOSTROPHE (Single_Quote) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x27 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 002E × 2060 × 0031 ÷ 002C ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x2c }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 002C ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x2c }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 002E × 2060 × 0031 ÷ 002E × 2060 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x2e, 0x2060, 0x31, 0x2e, 0x2060 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 002E × 2060 × 0308 × 0031 ÷ 002E × 2060 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [12.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [11.0] DIGIT ONE (Numeric) ÷ [999.0] FULL STOP (MidNumLet) × [4.0] WORD JOINER (Format_FE) ÷ [0.3] { std::array<uint32_t, 7> cps = {{ 0x31, 0x2e, 0x2060, 0x308, 0x31, 0x2e, 0x2060 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 7, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 7); } // ÷ 000D × 000A ÷ 0061 ÷ 000A ÷ 0308 ÷ // ÷ [0.2] <CARRIAGE RETURN (CR)> (CR) × [3.0] <LINE FEED (LF)> (LF) ÷ [3.1] LATIN SMALL LETTER A (ALetter) ÷ [3.2] <LINE FEED (LF)> (LF) ÷ [3.1] COMBINING DIAERESIS (Extend_FE) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0xd, 0xa, 0x61, 0xa, 0x308 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0061 × 0308 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] COMBINING DIAERESIS (Extend_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x61, 0x308 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0020 × 200D ÷ 0646 ÷ // ÷ [0.2] SPACE (WSegSpace) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] ARABIC LETTER NOON (ALetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x20, 0x200d, 0x646 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 0646 × 200D ÷ 0020 ÷ // ÷ [0.2] ARABIC LETTER NOON (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] SPACE (WSegSpace) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x646, 0x200d, 0x20 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 0041 × 0041 × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [5.0] LATIN CAPITAL LETTER A (ALetter) × [5.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x41, 0x41, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0041 × 003A × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [6.0] COLON (MidLetter) × [7.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x41, 0x3a, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0041 ÷ 003A ÷ 003A ÷ 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x41, 0x3a, 0x3a, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 05D0 × 0027 ÷ // ÷ [0.2] HEBREW LETTER ALEF (Hebrew_Letter) × [7.1] APOSTROPHE (Single_Quote) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x5d0, 0x27 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 05D0 × 0022 × 05D0 ÷ // ÷ [0.2] HEBREW LETTER ALEF (Hebrew_Letter) × [7.2] QUOTATION MARK (Double_Quote) × [7.3] HEBREW LETTER ALEF (Hebrew_Letter) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x5d0, 0x22, 0x5d0 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0041 × 0030 × 0030 × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [9.0] DIGIT ZERO (Numeric) × [8.0] DIGIT ZERO (Numeric) × [10.0] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x41, 0x30, 0x30, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); } // ÷ 0030 × 002C × 0030 ÷ // ÷ [0.2] DIGIT ZERO (Numeric) × [12.0] COMMA (MidNum) × [11.0] DIGIT ZERO (Numeric) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x30, 0x2c, 0x30 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0030 ÷ 002C ÷ 002C ÷ 0030 ÷ // ÷ [0.2] DIGIT ZERO (Numeric) ÷ [999.0] COMMA (MidNum) ÷ [999.0] COMMA (MidNum) ÷ [999.0] DIGIT ZERO (Numeric) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x30, 0x2c, 0x2c, 0x30 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 3031 × 3031 ÷ // ÷ [0.2] VERTICAL KANA REPEAT MARK (Katakana) × [13.0] VERTICAL KANA REPEAT MARK (Katakana) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x3031, 0x3031 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 0041 × 005F × 0030 × 005F × 3031 × 005F ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ZERO (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] VERTICAL KANA REPEAT MARK (Katakana) × [13.1] LOW LINE (ExtendNumLet) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x41, 0x5f, 0x30, 0x5f, 0x3031, 0x5f }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); } // ÷ 0041 × 005F × 005F × 0041 ÷ // ÷ [0.2] LATIN CAPITAL LETTER A (ALetter) × [13.1] LOW LINE (ExtendNumLet) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN CAPITAL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x41, 0x5f, 0x5f, 0x41 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 4); } // ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [15.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); } // ÷ 0061 ÷ 1F1E6 × 1F1E7 × 200D ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x200d, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0061 ÷ 1F1E6 × 200D × 1F1E7 ÷ 1F1E8 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x200d, 0x1f1e7, 0x1f1e8, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0061 ÷ 1F1E6 × 1F1E7 ÷ 1F1E8 × 1F1E9 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER A (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER B (RI) ÷ [999.0] REGIONAL INDICATOR SYMBOL LETTER C (RI) × [16.0] REGIONAL INDICATOR SYMBOL LETTER D (RI) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x61, 0x1f1e6, 0x1f1e7, 0x1f1e8, 0x1f1e9, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 1F476 × 1F3FF ÷ 1F476 ÷ // ÷ [0.2] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [999.0] BABY (ExtPict) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x1f476, 0x1f3ff, 0x1f476 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); } // ÷ 1F6D1 × 200D × 1F6D1 ÷ // ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x1f6d1, 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0061 × 200D × 1F6D1 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x61, 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 2701 × 200D × 2701 ÷ // ÷ [0.2] UPPER BLADE SCISSORS (Other) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] UPPER BLADE SCISSORS (Other) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x2701, 0x200d, 0x2701 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 0061 × 200D × 2701 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] UPPER BLADE SCISSORS (Other) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x61, 0x200d, 0x2701 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 1F476 × 1F3FF × 0308 × 200D × 1F476 × 1F3FF ÷ // ÷ [0.2] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] BABY (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x1f476, 0x1f3ff, 0x308, 0x200d, 0x1f476, 0x1f3ff }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 6); } // ÷ 1F6D1 × 1F3FF ÷ // ÷ [0.2] OCTAGONAL SIGN (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x1f6d1, 0x1f3ff }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 200D × 1F6D1 × 1F3FF ÷ // ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) × [4.0] EMOJI MODIFIER FITZPATRICK TYPE-6 (Extend_FE) ÷ [0.3] { std::array<uint32_t, 3> cps = {{ 0x200d, 0x1f6d1, 0x1f3ff }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); } // ÷ 200D × 1F6D1 ÷ // ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 200D × 1F6D1 ÷ // ÷ [0.2] ZERO WIDTH JOINER (ZWJ_FE) × [3.3] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x200d, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 2); } // ÷ 1F6D1 ÷ 1F6D1 ÷ // ÷ [0.2] OCTAGONAL SIGN (ExtPict) ÷ [999.0] OCTAGONAL SIGN (ExtPict) ÷ [0.3] { std::array<uint32_t, 2> cps = {{ 0x1f6d1, 0x1f6d1 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); } // ÷ 0061 × 0308 × 200D × 0308 × 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) × [4.0] COMBINING DIAERESIS (Extend_FE) × [4.0] ZERO WIDTH JOINER (ZWJ_FE) × [4.0] COMBINING DIAERESIS (Extend_FE) × [5.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 5> cps = {{ 0x61, 0x308, 0x200d, 0x308, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 5); } // ÷ 0061 ÷ 0020 × 0020 ÷ 0062 ÷ // ÷ [0.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] SPACE (WSegSpace) × [3.4] SPACE (WSegSpace) ÷ [999.0] LATIN SMALL LETTER B (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x61, 0x20, 0x20, 0x62 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 ÷ 003A ÷ 003A ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x3a, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 003A ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x3a, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 005F × 0061 ÷ 003A ÷ 003A ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x3a, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 ÷ 003A ÷ 003A ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x3a, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 003A ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x3a, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 005F × 0061 ÷ 003A ÷ 003A ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x3a, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 ÷ 003A ÷ 002E ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x2e, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 002E ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x2e, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 × 005F × 0061 ÷ 003A ÷ 002E ÷ 0031 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] LATIN SMALL LETTER A (ALetter) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] DIGIT ONE (Numeric) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x61, 0x3a, 0x2e, 0x31 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } // ÷ 0031 ÷ 003A ÷ 002E ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 4> cps = {{ 0x31, 0x3a, 0x2e, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 1); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 1, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 2); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 2, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); } // ÷ 0031 × 005F × 0031 ÷ 003A ÷ 002E ÷ 0061 ÷ // ÷ [0.2] DIGIT ONE (Numeric) × [13.1] LOW LINE (ExtendNumLet) × [13.2] DIGIT ONE (Numeric) ÷ [999.0] COLON (MidLetter) ÷ [999.0] FULL STOP (MidNumLet) ÷ [999.0] LATIN SMALL LETTER A (ALetter) ÷ [0.3] { std::array<uint32_t, 6> cps = {{ 0x31, 0x5f, 0x31, 0x3a, 0x2e, 0x61 }}; EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 0, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 1, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 2, cps.end()) - cps.begin(), 0); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 0, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 3, cps.end()) - cps.begin(), 3); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 3, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 4, cps.end()) - cps.begin(), 4); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 4, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 5, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); EXPECT_EQ(boost::text::prev_word_break(cps.begin(), cps.begin() + 6, cps.end()) - cps.begin(), 5); EXPECT_EQ(boost::text::next_word_break(cps.begin() + 5, cps.end()) - cps.begin(), 6); } }
76.010158
292
0.594239
eightysquirrels
787d6eac8148288a839a06c366f15b75c55bee35
2,711
cpp
C++
Src/Server/OSSupport/IPLookup.cpp
lcmftianci/licodeanalysis
62e2722eba1b75ef82f7c1328585873d08bb41cc
[ "Apache-2.0" ]
2
2019-11-17T14:01:21.000Z
2019-12-24T14:29:45.000Z
Src/Server/OSSupport/IPLookup.cpp
lcmftianci/licodeanalysis
62e2722eba1b75ef82f7c1328585873d08bb41cc
[ "Apache-2.0" ]
null
null
null
Src/Server/OSSupport/IPLookup.cpp
lcmftianci/licodeanalysis
62e2722eba1b75ef82f7c1328585873d08bb41cc
[ "Apache-2.0" ]
3
2019-08-28T14:37:01.000Z
2020-06-17T16:46:32.000Z
// IPLookup.cpp // Implements the cIPLookup class representing an IP-to-hostname lookup in progress. #include "stdafx.h" #include "IPLookup.h" #include <event2/dns.h> #include "NetworkSingleton.h" #include <log4z.h> using namespace zsummer::log4z; //////////////////////////////////////////////////////////////////////////////// // cIPLookup: cIPLookup::cIPLookup(cNetwork::cResolveNameCallbacksPtr a_Callbacks): m_Callbacks(a_Callbacks) { ASSERT(a_Callbacks != nullptr); } bool cIPLookup::Lookup(const AString & a_IP) { // Parse the IP address string into a sockaddr structure: m_IP = a_IP; sockaddr_storage sa; int salen = static_cast<int>(sizeof(sa)); memset(&sa, 0, sizeof(sa)); if (evutil_parse_sockaddr_port(a_IP.c_str(), reinterpret_cast<sockaddr *>(&sa), &salen) != 0) { LOGD("Failed to parse IP address \"%s\"." << a_IP.c_str()); return false; } // Call the proper resolver based on the address family: // Note that there's no need to store the evdns_request handle returned, LibEvent frees it on its own. switch (sa.ss_family) { case AF_INET: { sockaddr_in * sa4 = reinterpret_cast<sockaddr_in *>(&sa); evdns_base_resolve_reverse(cNetworkSingleton::Get().GetDNSBase(), &(sa4->sin_addr), 0, Callback, this); break; } case AF_INET6: { sockaddr_in6 * sa6 = reinterpret_cast<sockaddr_in6 *>(&sa); evdns_base_resolve_reverse_ipv6(cNetworkSingleton::Get().GetDNSBase(), &(sa6->sin6_addr), 0, Callback, this); break; } default: { LOGWARNING("%s: Unknown address family: %d", __FUNCTION__, sa.ss_family); ASSERT(!"Unknown address family"); return false; } } // switch (address family) return true; } void cIPLookup::Callback(int a_Result, char a_Type, int a_Count, int a_Ttl, void * a_Addresses, void * a_Self) { // Get the Self class: cIPLookup * Self = reinterpret_cast<cIPLookup *>(a_Self); ASSERT(Self != nullptr); // Call the proper callback based on the event received: if ((a_Result != 0) || (a_Addresses == nullptr)) { // An error has occurred, notify the error callback: Self->m_Callbacks->OnError(a_Result, evutil_socket_error_to_string(a_Result)); } else { // Call the success handler: Self->m_Callbacks->OnNameResolved(*(reinterpret_cast<char **>(a_Addresses)), Self->m_IP); Self->m_Callbacks->OnFinished(); } cNetworkSingleton::Get().RemoveIPLookup(Self); } //////////////////////////////////////////////////////////////////////////////// // cNetwork API: bool cNetwork::IPToHostName( const AString & a_IP, cNetwork::cResolveNameCallbacksPtr a_Callbacks ) { auto res = std::make_shared<cIPLookup>(a_Callbacks); cNetworkSingleton::Get().AddIPLookup(res); return res->Lookup(a_IP); }
25.819048
112
0.669864
lcmftianci
787e7f8cd1c9c5266eef712814c2dcafd3c3c3af
1,570
cpp
C++
src/io/spoiler_writer.cpp
Nanarki/randstalker
003afdccaa46935d8a7879d6bdaf5d4ab7dfc4a5
[ "MIT" ]
10
2020-01-19T22:10:01.000Z
2021-12-27T15:30:22.000Z
src/io/spoiler_writer.cpp
Nanarki/randstalker
003afdccaa46935d8a7879d6bdaf5d4ab7dfc4a5
[ "MIT" ]
34
2020-01-19T14:31:02.000Z
2022-03-31T22:02:47.000Z
src/io/spoiler_writer.cpp
Nanarki/randstalker
003afdccaa46935d8a7879d6bdaf5d4ab7dfc4a5
[ "MIT" ]
6
2020-01-19T09:37:47.000Z
2022-01-06T01:12:17.000Z
#include "io.hpp" #include <landstalker_lib/tools/json.hpp> #include <landstalker_lib/model/world_teleport_tree.hpp> #include <landstalker_lib/model/entity_type.hpp> #include "../logic_model/world_region.hpp" #include "../logic_model/randomizer_world.hpp" #include "../logic_model/hint_source.hpp" #include "../randomizer_options.hpp" Json SpoilerWriter::build_spoiler_json(const RandomizerWorld& world, const RandomizerOptions& options) { Json json; // Export dark node json["spawnLocation"] = world.spawn_location().id(); json["darkRegion"] = world.dark_region()->name(); // Export hints for(HintSource* hint_source : world.used_hint_sources()) json["hints"][hint_source->description()] = hint_source->text(); if(options.shuffle_tibor_trees()) { json["tiborTrees"] = Json::array(); for(auto& pair : world.teleport_tree_pairs()) json["tiborTrees"].emplace_back(pair.first->name() + " <--> " + pair.second->name()); } // Export item sources for(WorldRegion* region : world.regions()) { for(WorldNode* node : region->nodes()) { for(ItemSource* source : node->item_sources()) { Item* item = world.item(source->item_id()); json["itemSources"][region->name()][source->name()] = item->name(); } } } // Fahl enemies json["fahlEnemies"] = Json::array(); for(EntityType* enemy : world.fahl_enemies()) json["fahlEnemies"].emplace_back(enemy->name()); return json; }
30.784314
102
0.63121
Nanarki