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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
173f67545228c863bfb4dfd4f32544c6a47b7beb | 848 | cpp | C++ | world/source/Currency.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | world/source/Currency.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | world/source/Currency.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | null | null | null | #include "Currency.hpp"
using namespace std;
Currency::Currency()
{
type = ItemType::ITEM_TYPE_CURRENCY;
symbol = '$';
status = ItemStatus::ITEM_STATUS_UNCURSED;
status_identified = true;
}
Currency::~Currency()
{
}
// Currency is always generated uncursed and shouldn't ever be set to another
// status.
void Currency::set_status(const ItemStatus status_to_ignore)
{
}
void Currency::set_status_identified(const bool new_status_identified)
{
}
bool Currency::additional_item_attributes_match(ItemPtr item) const
{
return true;
}
bool Currency::get_type_always_stacks() const
{
return true;
}
Item* Currency::clone()
{
return new Currency(*this);
}
ClassIdentifier Currency::internal_class_identifier() const
{
return ClassIdentifier::CLASS_ID_CURRENCY;
}
#ifdef UNIT_TESTS
#include "unit_tests/Currency_test.cpp"
#endif
| 16.627451 | 77 | 0.760613 | sidav |
174181d9ea03e20a47edfd7776d7362926c81837 | 6,617 | cpp | C++ | SdkCore/SdkCore/Environment/EnvironmentWindowsMsvc/Implementation/Atom.cpp | DexterDreeeam/DxtSdk2021 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | 1 | 2021-11-18T03:57:54.000Z | 2021-11-18T03:57:54.000Z | SdkCore/SdkCore/Environment/EnvironmentWindowsMsvc/Implementation/Atom.cpp | DexterDreeeam/P9 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | null | null | null | SdkCore/SdkCore/Environment/EnvironmentWindowsMsvc/Implementation/Atom.cpp | DexterDreeeam/P9 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | null | null | null |
#include "../../_Interface.hpp"
#include "../EnvironmentHeader.hpp"
template<typename Ty>
class shadow_class
{
public:
using DataType = volatile Ty;
DataType _data;
};
atom<s64>::atom()
{
assert(_mem_sz >= sizeof(shadow_class<s64>));
new (_mem) volatile s64(0);
}
atom<s64>::atom(const atom<s64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<s64>*);
shadow_self._data = shadow_rhs._data;
}
atom<s64>::atom(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
shadow_self._data = v;
}
atom<s64>::~atom()
{
}
s64 atom<s64>::get() const
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
return shadow_self._data;
}
void atom<s64>::set(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
shadow_self._data = v;
}
atom<s64>& atom<s64>::operator =(const atom<s64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<s64>*);
shadow_self._data = shadow_rhs._data;
return *this;
}
atom<s64>& atom<s64>::operator =(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
shadow_self._data = v;
return *this;
}
s64 atom<s64>::operator ++()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedIncrement(reinterpret_cast<volatile u64*>(&shadow_self._data));
return (s64)ret;
}
s64 atom<s64>::operator ++(int)
{
s64 ret = operator ++();
return ret - 1;
}
s64 atom<s64>::operator --()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedDecrement(reinterpret_cast<volatile u64*>(&shadow_self._data));
return (s64)ret;
}
s64 atom<s64>::operator --(int)
{
s64 ret = operator --();
return ret + 1;
}
s64 atom<s64>::weak_add(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
return shadow_self._data += v;
}
s64 atom<s64>::exchange(s64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedExchange(reinterpret_cast<volatile u64*>(&shadow_self._data), (u64)replace);
return (s64)ret;
}
s64 atom<s64>::compare_exchange(s64 expected, s64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*);
u64 ret = InterlockedCompareExchange(reinterpret_cast<volatile u64*>(&shadow_self._data), (u64)replace, (u64)expected);
return (s64)ret;
}
atom<u64>::atom()
{
assert(_mem_sz >= sizeof(shadow_class<u64>));
new (_mem) volatile u64(0);
}
atom<u64>::atom(const atom<u64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<u64>*);
shadow_self._data = shadow_rhs._data;
}
atom<u64>::atom(u64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
shadow_self._data = v;
}
atom<u64>::~atom()
{
}
u64 atom<u64>::get() const
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
return shadow_self._data;
}
void atom<u64>::set(u64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
shadow_self._data = v;
}
atom<u64>& atom<u64>::operator =(const atom<u64>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<u64>*);
shadow_self._data = shadow_rhs._data;
return *this;
}
atom<u64>& atom<u64>::operator =(u64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
shadow_self._data = v;
return *this;
}
u64 atom<u64>::operator ++()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedIncrement(&shadow_self._data);
return ret;
}
u64 atom<u64>::operator ++(int)
{
u64 ret = operator ++();
return ret - 1;
}
u64 atom<u64>::operator --()
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedDecrement(&shadow_self._data);
return ret;
}
u64 atom<u64>::operator --(int)
{
u64 ret = operator --();
return ret + 1;
}
u64 atom<u64>::weak_add(s64 v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
return shadow_self._data += v;
}
u64 atom<u64>::exchange(u64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedExchange(&shadow_self._data, replace);
return ret;
}
u64 atom<u64>::compare_exchange(u64 expected, u64 replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*);
u64 ret = InterlockedCompareExchange(&shadow_self._data, replace, expected);
return ret;
}
atom<void*>::atom()
{
assert(_mem_sz >= sizeof(shadow_class<void*>));
new (_mem) volatile void*(nullptr);
}
atom<void*>::atom(const atom<void*>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<void*>*);
shadow_self._data = shadow_rhs._data;
}
atom<void*>::atom(void* v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
shadow_self._data = v;
}
atom<void*>::~atom()
{
}
void* atom<void*>::get() const
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
return shadow_self._data;
}
void atom<void*>::set(void* v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
shadow_self._data = v;
}
atom<void*>& atom<void*>::operator =(const atom<void*>& rhs)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<void*>*);
shadow_self._data = shadow_rhs._data;
return *this;
}
atom<void*>& atom<void*>::operator =(void* v)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
shadow_self._data = v;
return *this;
}
void* atom<void*>::exchange(void* replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
void* ret = InterlockedExchangePointer(&shadow_self._data, replace);
return (void*)ret;
}
void* atom<void*>::compare_exchange(void* expected, void* replace)
{
auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*);
void* ret = InterlockedCompareExchangePointer(&shadow_self._data, replace, expected);
return (void*)ret;
}
| 22.130435 | 123 | 0.664652 | DexterDreeeam |
1743046c5a4b7ffe2ae6dac0b5741976c495f261 | 4,200 | cpp | C++ | proxygen/lib/http/codec/compress/HPACKDecodeBuffer.cpp | autoantwort/proxygen | 1cedfc101966163f647241b8c2564d55e4f31454 | [
"BSD-3-Clause"
] | 5,852 | 2015-01-01T06:12:49.000Z | 2022-03-31T07:28:30.000Z | proxygen/lib/http/codec/compress/HPACKDecodeBuffer.cpp | autoantwort/proxygen | 1cedfc101966163f647241b8c2564d55e4f31454 | [
"BSD-3-Clause"
] | 345 | 2015-01-02T22:15:43.000Z | 2022-03-28T23:33:28.000Z | proxygen/lib/http/codec/compress/HPACKDecodeBuffer.cpp | autoantwort/proxygen | 1cedfc101966163f647241b8c2564d55e4f31454 | [
"BSD-3-Clause"
] | 1,485 | 2015-01-04T14:39:26.000Z | 2022-03-22T02:32:08.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <proxygen/lib/http/codec/compress/HPACKDecodeBuffer.h>
#include <limits>
#include <memory>
#include <proxygen/lib/http/codec/compress/Huffman.h>
using folly::IOBuf;
using proxygen::HPACK::DecodeError;
using std::unique_ptr;
namespace proxygen {
void HPACKDecodeBuffer::EOB_LOG(std::string msg, DecodeError code) const {
if (endOfBufferIsError_ || code != DecodeError::BUFFER_UNDERFLOW) {
LOG(ERROR) << msg;
} else {
VLOG(4) << msg;
}
}
bool HPACKDecodeBuffer::empty() {
return remainingBytes_ == 0;
}
uint8_t HPACKDecodeBuffer::next() {
CHECK_GT(remainingBytes_, 0);
// in case we are the end of an IOBuf, peek() will move to the next one
uint8_t byte = peek();
cursor_.skip(1);
remainingBytes_--;
return byte;
}
uint8_t HPACKDecodeBuffer::peek() {
CHECK_GT(remainingBytes_, 0);
if (cursor_.length() == 0) {
cursor_.peek();
}
return *cursor_.data();
}
DecodeError HPACKDecodeBuffer::decodeLiteral(folly::fbstring& literal) {
return decodeLiteral(7, literal);
}
DecodeError HPACKDecodeBuffer::decodeLiteral(uint8_t nbit,
folly::fbstring& literal) {
literal.clear();
if (remainingBytes_ == 0) {
EOB_LOG("remainingBytes_ == 0");
return DecodeError::BUFFER_UNDERFLOW;
}
auto byte = peek();
uint8_t huffmanCheck = uint8_t(1 << nbit);
bool huffman = byte & huffmanCheck;
// extract the size
uint64_t size;
DecodeError result = decodeInteger(nbit, size);
if (result != DecodeError::NONE) {
EOB_LOG("Could not decode literal size", result);
return result;
}
if (size > remainingBytes_) {
EOB_LOG(folly::to<std::string>(
"size(", size, ") > remainingBytes_(", remainingBytes_, ")"));
return DecodeError::BUFFER_UNDERFLOW;
}
if (size > maxLiteralSize_) {
LOG(ERROR) << "Literal too large, size=" << size;
return DecodeError::LITERAL_TOO_LARGE;
}
const uint8_t* data;
unique_ptr<IOBuf> tmpbuf;
// handle the case where the buffer spans multiple buffers
if (cursor_.length() >= size) {
data = cursor_.data();
cursor_.skip(size);
} else {
// temporary buffer to pull the chunks together
tmpbuf = IOBuf::create(size);
// pull() will move the cursor
cursor_.pull(tmpbuf->writableData(), size);
data = tmpbuf->data();
}
if (huffman) {
static auto& huffmanTree = huffman::huffTree();
huffmanTree.decode(data, size, literal);
} else {
literal.append((const char*)data, size);
}
remainingBytes_ -= size;
return DecodeError::NONE;
}
DecodeError HPACKDecodeBuffer::decodeInteger(uint64_t& integer) {
return decodeInteger(8, integer);
}
DecodeError HPACKDecodeBuffer::decodeInteger(uint8_t nbit, uint64_t& integer) {
if (remainingBytes_ == 0) {
EOB_LOG("remainingBytes_ == 0");
return DecodeError::BUFFER_UNDERFLOW;
}
uint8_t byte = next();
uint8_t mask = HPACK::NBIT_MASKS[nbit];
// remove the first (8 - nbit) bits
byte = byte & mask;
integer = byte;
if (byte != mask) {
// the value fit in one byte
return DecodeError::NONE;
}
uint64_t f = 1;
uint32_t fexp = 0;
do {
if (remainingBytes_ == 0) {
EOB_LOG("remainingBytes_ == 0");
return DecodeError::BUFFER_UNDERFLOW;
}
byte = next();
if (fexp > 64) {
// overflow in factorizer, f > 2^64
LOG(ERROR) << "overflow fexp=" << fexp;
return DecodeError::INTEGER_OVERFLOW;
}
uint64_t add = (byte & 127) * f;
if (std::numeric_limits<uint64_t>::max() - integer <= add) {
// overflow detected - we disallow uint64_t max.
LOG(ERROR) << "overflow integer=" << integer << " add=" << add;
return DecodeError::INTEGER_OVERFLOW;
}
integer += add;
f = f << 7;
fexp += 7;
} while (byte & 128);
return DecodeError::NONE;
}
namespace HPACK {
std::ostream& operator<<(std::ostream& os, DecodeError err) {
return os << static_cast<uint32_t>(err);
}
} // namespace HPACK
} // namespace proxygen
| 27.45098 | 79 | 0.65619 | autoantwort |
174900a72e262fd0c8609f175b386fa1246d7392 | 5,335 | cpp | C++ | CxxProfiler/SyntaxHighlighter.cpp | mmozeiko/CxxProfiler | 5836f2a948cf97ad87bef0e357fd39c95d07189f | [
"Unlicense"
] | 110 | 2016-05-06T09:17:55.000Z | 2022-03-30T02:34:41.000Z | CxxProfiler/SyntaxHighlighter.cpp | mmozeiko/CxxProfiler | 5836f2a948cf97ad87bef0e357fd39c95d07189f | [
"Unlicense"
] | null | null | null | CxxProfiler/SyntaxHighlighter.cpp | mmozeiko/CxxProfiler | 5836f2a948cf97ad87bef0e357fd39c95d07189f | [
"Unlicense"
] | 5 | 2017-10-27T10:59:53.000Z | 2022-01-10T02:24:41.000Z | #include "SyntaxHighlighter.h"
// TODO http://www.kate-editor.org/syntax/3.9/isocpp.xml
SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
{
QTextCharFormat quotationFormat;
quotationFormat.setForeground(Qt::darkRed);
rule.pattern = QRegExp("\".*\"");
rule.pattern.setMinimal(true);
rule.format = quotationFormat;
mRules.append(rule);
rule.pattern = QRegExp("'.*'");
rule.pattern.setMinimal(true);
rule.format = quotationFormat;
mRules.append(rule);
rule.pattern = QRegExp("<[^\\s<]+>");
rule.format = quotationFormat;
mRules.append(rule);
}
mKeywordFormat.setForeground(Qt::blue);
static const char* keywords[] = {
"__abstract", "__alignof", "__asm", "__assume", "__based", "__box",
"__cdecl", "__declspec", "__delegate", "__event", "__fastcall",
"__forceinline", "__gc", "__hook", "__identifier", "__if_exists",
"__if_not_exists", "__inline", "__int16", "__int32", "__int64",
"__int8", "__interface", "__leave", "__m128", "__m128d", "__m128i",
"__m256", "__m256d", "__m256i", "__m64", "__multiple_inheritance",
"__nogc", "__noop", "__pin", "__property", "__raise", "__sealed",
"__single_inheritance", "__stdcall", "__super", "__thiscall",
"__try_cast", "__unaligned", "__unhook", "__uuidof", "__value",
"__vectorcall", "__virtual_inheritance", "__w64", "__wchar_t",
"abstract", "array", "auto", "bool", "break", "case", "catch",
"char", "class", "const", "const_cast", "continue", "decltype",
"default", "delegate", "delete", "deprecated", "dllexport",
"dllimport", "do", "double", "dynamic_cast", "each", "else", "event",
"explicit", "extern", "false", "finally", "float", "for", "friend",
"friend_as", "gcnew", "generic", "goto", "if", "in", "initonly",
"inline", "int", "interface", "interior_ptr", "literal", "long",
"mutable", "naked", "namespace", "new", "noinline", "noreturn",
"nothrow", "novtable", "nullptr", "operator", "private", "property",
"protected", "public", "ref", "register", "reinterpret_cast",
"return", "safecast", "sealed", "selectany", "short", "signed",
"sizeof", "static", "static_assert", "static_cast", "struct",
"switch", "template", "this", "thread", "throw", "true", "try",
"typedef", "typename", "union", "unsigned", "using", "uuid", "value",
"virtual", "void", "volatile", "wchar_t", "while"
};
for (const char* keyword : keywords)
{
QString pattern = QString("\\b%1\\b").arg(keyword);
rule.pattern = QRegExp(pattern);
rule.format = mKeywordFormat;
mRules.append(rule);
}
static const char* preprocKeywords[] = {
"#define", "#error", "#import", "#undef", "#elif", "#if", "#include",
"#using", "#else", "#ifdef", "#line", "#endif", "#ifndef", "#pragma"
};
for (const char* preprocKeyword : preprocKeywords)
{
QString pattern = QString("(\\b|^)%1\\b").arg(preprocKeyword);
rule.pattern = QRegExp(pattern);
rule.format = mKeywordFormat;
mRules.append(rule);
}
{
QTextCharFormat numberFormat;
numberFormat.setForeground(Qt::red);
rule.pattern = QRegExp("\\b[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?f?\\b");
rule.format = numberFormat;
mRules.append(rule);
rule.pattern = QRegExp("\\b0x[0-9a-fA-F]+U?L?L?\\b");
rule.format = numberFormat;
mRules.append(rule);
rule.pattern = QRegExp("\\b[0-9]+\\b");
rule.format = numberFormat;
mRules.append(rule);
}
{
QTextCharFormat singleLineCommentFormat;
singleLineCommentFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
mRules.append(rule);
}
mMultiLineCommentFormat.setForeground(Qt::darkGreen);
mCommentStart = QRegExp("/\\*");
mCommentEnd = QRegExp("\\*/");
}
SyntaxHighlighter::~SyntaxHighlighter()
{
}
void SyntaxHighlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule& rule : mRules)
{
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0)
{
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
{
startIndex = mCommentStart.indexIn(text);
}
while (startIndex >= 0)
{
int endIndex = mCommentEnd.indexIn(text, startIndex);
int commentLength;
if (endIndex == -1)
{
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
}
else
{
commentLength = endIndex - startIndex + mCommentEnd.matchedLength();
}
setFormat(startIndex, commentLength, mMultiLineCommentFormat);
startIndex = mCommentStart.indexIn(text, startIndex + commentLength);
}
} | 34.869281 | 80 | 0.582193 | mmozeiko |
174c9629aab8e0ea818e6c47f1e9614bb651452a | 3,457 | hpp | C++ | src/contrib/mlir/runtime/cpu/cpu_runtime.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/runtime/cpu/cpu_runtime.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/contrib/mlir/runtime/cpu/cpu_runtime.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
// NOTE: This file follows nGraph format style.
// Follows nGraph naming convention for public APIs only, else MLIR naming
// convention.
#pragma once
#include <memory>
#include <mlir/ExecutionEngine/ExecutionEngine.h>
#include <mlir/IR/Builders.h>
#include <mlir/IR/Module.h>
#include <mlir/IR/Types.h>
#include "contrib/mlir/backend/backend.hpp"
#include "contrib/mlir/runtime/runtime.hpp"
namespace ngraph
{
namespace runtime
{
namespace ngmlir
{
struct StaticMemRef
{
void* allocatedPtr;
void* alignedPtr;
int64_t offset;
int64_t shapeAndStrides[];
};
struct UnrankedMemRef
{
int64_t rank;
StaticMemRef* memRefDescPtr;
};
/// A CPU Runtime is an MLIR runtime that owns an MLIR context and a module
/// The module should be in LLVM dialect and ready to be lowered via an MLIR
/// ExecutionEngine. The runtime owns the context and must out-live any MLIR
/// code Compilation and execution.
class MLIRCPURuntime : public MLIRRuntime
{
public:
/// Executes a pre-compiled subgraph
void run(const std::vector<MemRefArg>& args, bool firstIteration) override;
private:
void run_internal(const std::vector<MemRefArg>& args, bool firstIteration);
// Bind external tensors to MLIR module entry point
void bindArguments(const std::vector<MemRefArg>& args);
// Invokes an MLIR module entry point with bound arguments
void execute(bool firstIteration);
// Cleans up allocated args
void cleanup();
/// Helper to create memref arguments for MLIR function signature
llvm::SmallVector<void*, 8> allocateMemrefArgs();
/// Helper to allocate a default MemRef descriptor for LLVM. Handles static
/// shapes
/// only for now.
StaticMemRef* allocateDefaultMemrefDescriptor(size_t);
private:
// Pointers to externally allocated memory for sub-graph's input and output
// tensors.
const std::vector<MemRefArg>* m_externalTensors;
// Arguments for the MLIR function generated for the nGraph sub-graph.
llvm::SmallVector<void*, 8> m_invokeArgs;
std::unique_ptr<::mlir::ExecutionEngine> m_engine;
std::vector<size_t> m_ranks;
};
}
}
}
| 38.411111 | 91 | 0.581429 | pqLee |
174e28567b7f8f09e81209419631ecd072a5b649 | 1,523 | cpp | C++ | src/TaskManager/src/system2.cpp | RemiMattheyDoret/TaskManager | bea51ba9fcdf7390b57148bfa8adba75f25dddaa | [
"MIT"
] | null | null | null | src/TaskManager/src/system2.cpp | RemiMattheyDoret/TaskManager | bea51ba9fcdf7390b57148bfa8adba75f25dddaa | [
"MIT"
] | null | null | null | src/TaskManager/src/system2.cpp | RemiMattheyDoret/TaskManager | bea51ba9fcdf7390b57148bfa8adba75f25dddaa | [
"MIT"
] | null | null | null |
/*
system2 runs a shell command in the background and return the PID.
I stole this piece of code from https://stackoverflow.com/questions/22802902/how-to-get-pid-of-process-executed-with-system-command-in-c and modified it a little bit to fit my needs
system2() does not pauses like system(). It is therefore easier to get the PID from the submitted process.
*/
#include "TypeDefinitions.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include "system2.h"
PID_t system2(const char * command)
{
//std::cout << command << "\n";
int p_stdin[2];
int p_stdout[2];
PID_t pid;
if (pipe(p_stdin) == -1)
return -1;
if (pipe(p_stdout) == -1) {
close(p_stdin[0]);
close(p_stdin[1]);
return -1;
}
pid = fork();
if (pid < 0) {
close(p_stdin[0]);
close(p_stdin[1]);
close(p_stdout[0]);
close(p_stdout[1]);
return pid;
} else if (pid == 0) {
close(p_stdin[1]);
dup2(p_stdin[0], 0);
close(p_stdout[0]);
dup2(p_stdout[1], 1);
dup2(::open("/dev/null", O_RDONLY), 2);
/// Close all other descriptors for the safety sake.
for (int i = 3; i < 4096; ++i)
::close(i);
setsid();
execl("/bin/sh", "sh", "-c", command, NULL);
_exit(1);
}
close(p_stdin[0]);
close(p_stdout[1]);
//std::cout << "pid = " << pid << std::endl;
return pid;
}
| 22.397059 | 185 | 0.560079 | RemiMattheyDoret |
17562622d3119f56a683652e446b6d9e8af2cb2f | 13,271 | cpp | C++ | src/3ds/Graphics.cpp | mysterypaint/Hmm2 | 61e7b6566c1bf3590dde055a7107d486db03b077 | [
"MIT"
] | null | null | null | src/3ds/Graphics.cpp | mysterypaint/Hmm2 | 61e7b6566c1bf3590dde055a7107d486db03b077 | [
"MIT"
] | null | null | null | src/3ds/Graphics.cpp | mysterypaint/Hmm2 | 61e7b6566c1bf3590dde055a7107d486db03b077 | [
"MIT"
] | null | null | null | #include "Graphics.hpp"
#include "../PHL.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../Resources.hpp"
PHL_Surface db = {0};
PHL_Surface backBuffer = {0};
PHL_Surface dbAlt = {0};
PHL_Surface backBufferAlt = {0};
const int cWidth = 320;
const int cHeight = 240;
Screen scrnTop = {
GFX_TOP,
GFX_LEFT,
400,
240
};
Screen scrnBottom = {
GFX_BOTTOM,
GFX_LEFT,
cWidth,
cHeight
};
Screen* activeScreen = nullptr; // Where graphics get rendered to
#ifdef _3DS
Screen* debugScreen = nullptr; // Bottom screen console, for debugging (or swapping screen locations)
#endif
PHL_Rect offset;
void PHL_GraphicsInit() {
gfxInitDefault();
//Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one
//gfxSet3D(false);
//consoleDebugInit(debugDevice_CONSOLE);
activeScreen = &scrnBottom;
debugScreen = &scrnTop;
PHL_ResetDrawbuffer();
//Create background image
backBuffer = PHL_NewSurface(cWidth * 2, cHeight * 2);
dbAlt = PHL_NewSurface(cWidth * 2, cHeight * 2);
backBufferAlt = PHL_NewSurface(cWidth * 2, cHeight * 2);
}
void PHL_GraphicsExit() {
gfxExit();
}
void PHL_StartDrawing() {
PHL_ResetDrawbuffer();
gfxFlushBuffers();
}
void PHL_EndDrawing() {
PHL_DrawOtherScreen();
gfxSwapBuffers();
gspWaitForVBlank();
}
void PHL_SetDrawbuffer(PHL_Surface surf) {
db = surf;
offset.w = db.width;
offset.h = db.height;
offset.x = 0;
offset.y = 0;
}
void PHL_ResetDrawbuffer() {
db.width = activeScreen->width;
db.height = activeScreen->height;
db.pxdata = gfxGetFramebuffer(activeScreen->screen, activeScreen->side, NULL, NULL);
offset.w = cWidth;
offset.h = cHeight;
offset.x = (activeScreen->width - offset.w) / 2;
offset.y = (activeScreen->height - offset.h) / 2;
}
PHL_RGB PHL_NewRGB(uint8_t r, uint8_t g, uint8_t b) {
PHL_RGB c = { r, g, b };
return c;
}
void PHL_SetColorKey(PHL_Surface surf, uint8_t r, uint8_t g, uint8_t b) {
PHL_RGB key = { r, g, b };
surf.colorKey = key;
}
PHL_Surface PHL_NewSurface(uint16_t w, uint16_t h) {
PHL_Surface surf;
surf.width = w / 2;
surf.height = h / 2;
surf.pxdata = (uint8_t *) malloc(surf.width * surf.height * 3 * sizeof(uint8_t));
surf.colorKey = PHL_NewRGB(0xFF, 0x00, 0xFF);
return surf;
}
void PHL_FreeSurface(PHL_Surface surf) {
if (surf.pxdata != NULL) {
free(surf.pxdata);
surf.pxdata = NULL;
}
}
PHL_Surface PHL_LoadTexture(int _img_index) {
PHL_Surface surf;
std::string _f_in = "romfs:/graphics/";
int fileSize = 77880; // The default filesize, in bytes (because nearly all the graphics in the game are this size)
switch(_img_index) {
case sprPlayer:
_f_in += "test_player.bmp";
fileSize = 12342;
break;
case sprTile0:
_f_in += "tile0.bmp";
fileSize = 1142;
break;
case sprProt1:
_f_in += "prot1.bmp";
break;
case sprTitle:
_f_in += "title.bmp";
break;
case sprMapG00:
_f_in += "mapg00.bmp";
break;
case sprMapG01:
_f_in += "mapg01.bmp";
break;
case sprMapG02:
_f_in += "mapg02.bmp";
break;
case sprMapG03:
_f_in += "mapg03.bmp";
break;
case sprMapG04:
_f_in += "mapg04.bmp";
break;
case sprMapG05:
_f_in += "mapg05.bmp";
break;
case sprMapG06:
_f_in += "mapg06.bmp";
break;
case sprMapG07:
_f_in += "mapg07.bmp";
break;
case sprMapG08:
_f_in += "mapg08.bmp";
break;
case sprMapG09:
_f_in += "mapg09.bmp";
break;
case sprMapG10:
_f_in += "mapg10.bmp";
break;
case sprMapG11:
_f_in += "mapg11.bmp";
break;
case sprMapG12:
_f_in += "mapg12.bmp";
break;
case sprMapG13:
_f_in += "mapg13.bmp";
break;
case sprMapG14:
_f_in += "mapg14.bmp";
break;
case sprMapG15:
_f_in += "mapg15.bmp";
break;
case sprMapG16:
_f_in += "mapg16.bmp";
break;
case sprMapG17:
_f_in += "mapg17.bmp";
break;
case sprMapG18:
_f_in += "mapg18.bmp";
break;
case sprMapG19:
_f_in += "mapg19.bmp";
break;
case sprMapG20:
_f_in += "mapg20.bmp";
break;
case sprMapG21:
_f_in += "mapg21.bmp";
break;
case sprMapG22:
_f_in += "mapg22.bmp";
break;
case sprMapG31:
_f_in += "mapg31.bmp";
break;
case sprMapG32:
_f_in += "mapg32.bmp";
break;
default:
fileSize = 77880;
}
FILE * f;
if ((f = fopen(_f_in.c_str(), "rb"))) {
//Save bmp data
uint8_t* bmpFile = (uint8_t*) malloc(fileSize * sizeof(uint8_t));
fread(bmpFile, fileSize, 1, f);
fclose(f);
//Create surface
uint16_t w, h;
memcpy(&w, &bmpFile[18], 2);
memcpy(&h, &bmpFile[22], 2);
surf = PHL_NewSurface(w * 2, h * 2);
//Load Palette
PHL_RGB palette[20][18];
int count = 0;
for (int dx = 0; dx < 20; dx++) {
for (int dy = 0; dy < 16; dy++) {
palette[dx][dy].b = bmpFile[54 + count];
palette[dx][dy].g = bmpFile[54 + count + 1];
palette[dx][dy].r = bmpFile[54 + count + 2];
count += 4;
}
}
//Fill pixels
count = 0;
for (int dx = w; dx > 0; dx--) {
for (int dy = 0; dy < h; dy++) {
int pix = w - dx + w * dy;
int px = bmpFile[1078 + pix] / 16;
int py = bmpFile[1078 + pix] % 16;
//Get transparency from first palette color
if (dx == w &&dy == 0)
surf.colorKey = palette[0][0];
PHL_RGB c = palette[px][py];
surf.pxdata[count] = c.b;
surf.pxdata[count+1] = c.g;
surf.pxdata[count+2] = c.r;
count += 3;
}
}
//Cleanup
free(bmpFile);
}
return surf;
}
void PHL_DrawRect(int16_t x, int16_t y, uint16_t w, uint16_t h, PHL_RGB col) {
// Everything is stored in memory at 2x size; Halve it for the 3ds port
if (x < 0 || y < 0 || x+w > db.width || y+h > db.height)
return;
//Shrink values for small 3ds screen
//x /= 2;
//y /= 2;
x += offset.x;
y += offset.y;
//w /= 2;
//h /= 2;
s16 x2 = x + w;
s16 y2 = y + h;
//Keep drawing within screen
if (x < offset.x) { x = offset.x; }
if (y < offset.y) { y = offset.y; }
if (x2 > offset.x + offset.w) { x2 = offset.x + offset.w; }
if (y2 > offset.y + offset.h) { y2 = offset.y + offset.h; }
w = x2 - x;
h = y2 - y;
u32 p = ((db.height - h - y) + (x * db.height)) * 3;
for (int i = 0; i < w; i++)
{
for (int a = 0; a < h; a++)
{
db.pxdata[p] = col.b;
db.pxdata[p+1] = col.g;
db.pxdata[p+2] = col.r;
p += 3;
}
p += (db.height - h) * 3;
}
}
void PHL_DrawSurface(int16_t x, int16_t y, PHL_Surface surf) {
PHL_DrawSurfacePart(x, y, 0, 0, surf.width * 2, surf.height * 2, surf);
}
void PHL_DrawSurfacePart(int16_t x, int16_t y, int16_t cropx, int16_t cropy, int16_t cropw, int16_t croph, PHL_Surface surf) {
if (surf.pxdata != NULL) {
/*
// Everything is stored in memory at 2x size; Halve it for the 3ds port
x = (int) x / 2;
y = (int) y / 2;
cropx = cropx / 2;
cropy = cropy / 2;
cropw /= 2;
croph /= 2;
*/
if (x > offset.w || y > offset.h || x + cropw < 0 || y + croph < 0) {
//image is outside of screen, so don't bother drawing
} else {
//Crop pixels that are outside of screen
if (x < 0) {
cropx += -(x);
cropw -= -(x);
x = 0;
}
if (y < 0) {
cropy += -(y);
croph -= -(y);
y = 0;
}
//3DS exclusive optimization
/*
//if (roomDarkness == 1) {
//if (1) {
int cornerX = 0;// (herox / 2) - 80;
int cornerY = 0;// (heroy / 2) + 10 - 80;
if (x < cornerX) {
cropx += cornerX - x;
cropw -= cornerX - x;
x = cornerX;
}
if (y < cornerY) {
cropy += cornerY - y;
croph -= cornerY - y;
y = cornerY;
}
if (x + cropw > cornerX + 160) {
cropw -= (x + cropw) - (cornerX + 160);
}
if (y + croph > cornerY + 160) {
croph -= (y + croph) - (cornerY + 160);
}
//}*/
if (x + cropw > offset.w)
cropw -= (x + cropw) - (offset.w);
if (y + croph > offset.h)
croph -= (y + croph) - (offset.h);
// Adjust the canvas' position based on the new offsets
x += offset.x;
y += offset.y;
// Find the first color and pixel that we're dealing with before we update the rest of the canvas
uint32_t p = ((offset.h - croph - y) + (x * offset.h)) * 3;
uint32_t c = ((surf.height - cropy - croph) + surf.height * cropx) * 3;
// Loop through every single pixel (draw columns from left to right, top to bottom) of the final output canvas and store the correct color at each pixel
for (int i = 0; i < cropw; i++) {
for (int a = 0; a < croph; a++) {
if (surf.colorKey.r != surf.pxdata[c + 2] ||
surf.colorKey.g != surf.pxdata[c + 1] ||
surf.colorKey.b != surf.pxdata[c]) {
// Only update this pixel's color if necessary
db.pxdata[p] = surf.pxdata[c];
db.pxdata[p + 1] = surf.pxdata[c + 1];
db.pxdata[p + 2] = surf.pxdata[c + 2];
}
c += 3;
p += 3;
}
// Skip drawing for all of the columns of pixels that we've cropped out (one pixel = 3 bytes of data {r,g,b})
p += (offset.h - croph) * 3;
c += (surf.height - croph) * 3;
}
}
}
}
void PHL_DrawBackground(PHL_Background back, PHL_Background fore) {
PHL_DrawSurface(0, 0, backBuffer);
}
void PHL_UpdateBackground(PHL_Background back, PHL_Background fore) {
PHL_SetDrawbuffer(backBuffer);
/*
int xx, yy;
for (yy = 0; yy < 12; yy++) {
for (xx = 0; xx < 16; xx++) {
//Draw Background tiles
PHL_DrawSurfacePart(xx * 40, yy * 40, back.tileX[xx][yy] * 40, back.tileY[xx][yy] * 40, 40, 40, images[imgTiles]);
//Only draw foreground tile if not a blank tile
if (fore.tileX[xx][yy] != 0 || fore.tileY[xx][yy] != 0) {
PHL_DrawSurfacePart(xx * 40, yy * 40, fore.tileX[xx][yy] * 40, fore.tileY[xx][yy] * 40, 40, 40, images[imgTiles]);
}
}
}
*/
PHL_ResetDrawbuffer();
}
//3DS exclusive. Changes which screen to draw on
void swapScreen(gfxScreen_t screen, gfx3dSide_t side) {
//Clear old screen
PHL_StartDrawing();
PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0));
PHL_EndDrawing();
PHL_StartDrawing();
PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0));
PHL_EndDrawing();
if (screen == GFX_TOP) {
activeScreen = &scrnTop;
debugScreen = &scrnBottom;
} else {
activeScreen = &scrnBottom;
debugScreen = &scrnTop;
}
PHL_ResetDrawbuffer();
}
void PHL_DrawOtherScreen() {
PHL_ResetAltDrawbuffer();
//printf(":wagu: :nodding: :nodding2: :slownod: :hypernodding: :wagu2: :oj100: :revolving_hearts: ");
}
void PHL_ResetAltDrawbuffer() {
dbAlt.width = debugScreen->width;
dbAlt.height = debugScreen->height;
dbAlt.pxdata = gfxGetFramebuffer(debugScreen->screen, debugScreen->side, NULL, NULL);
offset.w = cWidth;
offset.h = cHeight;
offset.x = (debugScreen->width - offset.w) / 2;
offset.y = (debugScreen->height - offset.h) / 2;
} | 28.057082 | 164 | 0.490619 | mysterypaint |
1757288b370f17004e7f385e0f07db58febb9e40 | 289 | cpp | C++ | Decorator/Decorator/Color.cpp | jayavardhanravi/DesignPatterns | aa6a37790f447c7caf69c6a1a9c6107074309a03 | [
"BSD-2-Clause"
] | 8 | 2020-01-23T23:20:40.000Z | 2022-01-08T13:04:08.000Z | Decorator/Decorator/Color.cpp | jayavardhanravi/DesignPatterns | aa6a37790f447c7caf69c6a1a9c6107074309a03 | [
"BSD-2-Clause"
] | null | null | null | Decorator/Decorator/Color.cpp | jayavardhanravi/DesignPatterns | aa6a37790f447c7caf69c6a1a9c6107074309a03 | [
"BSD-2-Clause"
] | 1 | 2020-01-28T14:27:54.000Z | 2020-01-28T14:27:54.000Z | #include "Color.h"
Color::Color(Mesh *mesh): MeshDecorator(mesh)
{
}
Color::~Color()
{
}
void Color::AddMeshProperties()
{
MeshDecorator::AddMeshProperties();
ColorFeatures();
}
void Color::ColorFeatures()
{
std::cout << "Added the Color Features" << std::endl;
} | 14.45 | 55 | 0.636678 | jayavardhanravi |
1760bcc6a7f257e9b16278992d6d2f2c8143bad0 | 56 | hpp | C++ | src/boost_spirit_home_qi_auxiliary_attr_cast.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_spirit_home_qi_auxiliary_attr_cast.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_spirit_home_qi_auxiliary_attr_cast.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/spirit/home/qi/auxiliary/attr_cast.hpp>
| 28 | 55 | 0.803571 | miathedev |
1764e3714e86b52ebefaf7fab17b045c75f3c7fe | 9,153 | cpp | C++ | src/services/http.cpp | devinsmith/tfstool | bccd7dc97a769a87fb576c1feae32290cf6bd8c3 | [
"MIT"
] | null | null | null | src/services/http.cpp | devinsmith/tfstool | bccd7dc97a769a87fb576c1feae32290cf6bd8c3 | [
"MIT"
] | null | null | null | src/services/http.cpp | devinsmith/tfstool | bccd7dc97a769a87fb576c1feae32290cf6bd8c3 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2012-2019 Devin Smith <devin@devinsmith.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <curl/curl.h>
#include <curl/easy.h>
#include <cstring>
#include <cstdlib>
#include <string>
#include "services/http.h"
#include "utils/logging.h"
namespace http {
/* HTTP Services version 1.102 (06-17-2019) */
struct http_context {
HttpRequest *req;
HttpResponse *resp;
};
/* Modern Chrome on Windows 10 */
static const char *chrome_win10_ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36";
#ifdef _WIN32
#define WAITMS(x) Sleep(x)
#else
/* Portable sleep for platforms other than Windows. */
#define WAITMS(x) \
struct timeval wait { 0, (x) * 1000 }; \
(void)select(0, NULL, NULL, NULL, &wait);
#endif
void
http_lib_startup(void)
{
curl_global_init(CURL_GLOBAL_ALL);
}
void
http_lib_shutdown(void)
{
}
HttpExecutor::HttpExecutor()
{
m_multi_handle = curl_multi_init();
}
HttpExecutor::~HttpExecutor()
{
curl_multi_cleanup(m_multi_handle);
}
/* Private generic response reading function */
static size_t
dk_httpread(char *ptr, size_t size, size_t nmemb, HttpResponse *hr)
{
size_t totalsz = size * nmemb;
if (strstr(ptr, "HTTP/1.1 100 Continue"))
return totalsz;
hr->body.append((char *)ptr, totalsz);
return totalsz;
}
const char *
http_get_error_str(int error_code)
{
return curl_easy_strerror((CURLcode)error_code);
}
static int
curl_debug_func(CURL *hnd, curl_infotype info, char *data, size_t len,
http_context *ctx)
{
std::string hdr;
std::string::size_type n;
switch (info) {
case CURLINFO_HEADER_OUT:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, "H>: %s", verb.c_str());
}
ctx->req->req_hdrs.append(data, len);
break;
case CURLINFO_TEXT:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, "T: %s", verb.c_str());
}
break;
case CURLINFO_HEADER_IN:
hdr = std::string(data, len);
if (ctx->req->verbose()) {
log_msgraw(0, "H<: %s", hdr.c_str());
}
n = hdr.find('\r');
if (n != std::string::npos) {
hdr.erase(n);
}
n = hdr.find('\n');
if (n != std::string::npos) {
hdr.erase(n);
}
ctx->resp->headers.push_back(hdr);
break;
case CURLINFO_DATA_IN:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, "<: %s", verb.c_str());
}
break;
case CURLINFO_DATA_OUT:
if (ctx->req->verbose()) {
std::string verb(data, len);
log_msgraw(0, ">: %s", verb.c_str());
}
break;
default:
break;
}
return 0;
}
static CURLcode
easy_perform(CURLM *mhnd, CURL *hnd)
{
CURLcode result = CURLE_OK;
CURLMcode mcode = CURLM_OK;
int done = 0; /* bool */
if (curl_multi_add_handle(mhnd, hnd)) {
return CURLE_FAILED_INIT;
}
while (!done && mcode == 0) {
int still_running = 0;
int rc;
mcode = curl_multi_wait(mhnd, NULL, 0, 1000, &rc);
if (mcode == 0) {
if (rc == 0) {
long sleep_ms;
/* If it returns without any file descriptor instantly, we need to
* avoid busy looping during periods where it has nothing particular
* to wait for. */
curl_multi_timeout(mhnd, &sleep_ms);
if (sleep_ms) {
if (sleep_ms > 1000)
sleep_ms = 1000;
WAITMS(sleep_ms);
}
}
mcode = curl_multi_perform(mhnd, &still_running);
}
/* Only read still-running if curl_multi_perform returns ok */
if (!mcode && still_running == 0) {
CURLMsg *msg = curl_multi_info_read(mhnd, &rc);
if (msg) {
result = msg->data.result;
done = 1;
}
}
}
if (mcode != 0) {
if ((int)mcode == CURLM_OUT_OF_MEMORY)
result = CURLE_OUT_OF_MEMORY;
else
result = CURLE_BAD_FUNCTION_ARGUMENT;
}
curl_multi_remove_handle(mhnd, hnd);
return result;
}
void HttpRequest::set_content(const char *content_type)
{
std::string ctype_hdr = "Content-Type: ";
ctype_hdr.append(content_type);
m_headers = curl_slist_append(m_headers, ctype_hdr.c_str());
}
HttpResponse HttpRequest::exec(const char *method, const char *data,
HttpExecutor& executor)
{
struct http_context ctx;
HttpResponse resp;
if (strcmp(method, "GET") == 0) {
curl_easy_setopt(m_handle, CURLOPT_HTTPGET, 1);
} else if (strcmp(method, "POST") == 0) {
curl_easy_setopt(m_handle, CURLOPT_POST, 1);
} else {
curl_easy_setopt(m_handle, CURLOPT_CUSTOMREQUEST, method);
}
if (data != NULL) {
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, (long)strlen(data));
} else {
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, 0);
}
curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str());
curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers);
curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_user_agent.c_str());
ctx.resp = &resp;
ctx.req = this;
curl_easy_setopt(m_handle, CURLOPT_DEBUGFUNCTION, curl_debug_func);
curl_easy_setopt(m_handle, CURLOPT_DEBUGDATA, &ctx);
curl_easy_setopt(m_handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, 0);
/* Verification of SSL is disabled on Windows. This is a limitation of
* curl */
curl_easy_setopt(m_handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(m_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, &resp);
curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, dk_httpread);
CURLcode res = easy_perform(executor.handle(), m_handle);
if (res != CURLE_OK) {
log_tmsg(0, "Failure performing request");
}
curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &resp.status_code);
curl_easy_getinfo(m_handle, CURLINFO_TOTAL_TIME, &elapsed);
resp.elapsed = elapsed;
return resp;
}
static size_t
write_file(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
bool
HttpRequest::get_file(const char *file)
{
FILE *fp;
fp = fopen(file, "w");
if (fp == NULL) {
return false;
}
bool ret = get_file_fp(fp);
fclose(fp);
return ret;
}
bool
HttpRequest::get_file_fp(FILE *fp)
{
long status_code;
curl_easy_setopt(m_handle, CURLOPT_HTTPGET, 1);
curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, 0);
curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str());
curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers);
curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_user_agent.c_str());
curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, 0);
curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, write_file);
curl_easy_setopt(m_handle, CURLOPT_FOLLOWLOCATION, 1L);
CURLcode res = easy_perform(HttpExecutor::default_instance().handle(), m_handle);
if (res != CURLE_OK) {
log_tmsg(0, "Failure performing request");
}
curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &status_code);
curl_easy_getinfo(m_handle, CURLINFO_TOTAL_TIME, &elapsed);
return true;
}
HttpRequest::HttpRequest(const std::string &url, bool verbose) :
m_headers(NULL), m_url(url), m_verbose(verbose), m_user_agent(chrome_win10_ua)
{
m_handle = curl_easy_init();
}
void
HttpRequest::set_cert(const std::string &cert, const std::string &key)
{
curl_easy_setopt(m_handle, CURLOPT_SSLCERT, cert.c_str());
curl_easy_setopt(m_handle, CURLOPT_SSLKEY, key.c_str());
}
void
HttpRequest::set_basic_auth(const std::string &user, const std::string &pass)
{
curl_easy_setopt(m_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(m_handle, CURLOPT_USERNAME, user.c_str());
curl_easy_setopt(m_handle, CURLOPT_PASSWORD, pass.c_str());
}
void HttpRequest::set_ntlm(const std::string &username, const std::string& password)
{
curl_easy_setopt(m_handle, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_easy_setopt(m_handle, CURLOPT_USERNAME, username.c_str());
curl_easy_setopt(m_handle, CURLOPT_PASSWORD, password.c_str());
}
void
HttpRequest::add_header(const char *key, const char *value)
{
char maxheader[2048];
snprintf(maxheader, sizeof(maxheader), "%s: %s", key, value);
m_headers = curl_slist_append(m_headers, maxheader);
}
HttpRequest::~HttpRequest()
{
curl_easy_cleanup(m_handle);
curl_slist_free_all(m_headers);
}
} // namespace http
| 25.783099 | 154 | 0.694417 | devinsmith |
17671c04293be639f9cf311ef66f46b0a86d035b | 6,620 | cpp | C++ | engine/engine/core/math/tests/so3.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | null | null | null | engine/engine/core/math/tests/so3.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | null | null | null | engine/engine/core/math/tests/so3.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2022-01-28T16:37:51.000Z | 2022-01-28T16:37:51.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include "engine/core/math/so3.hpp"
#include <vector>
#include "engine/core/constants.hpp"
#include "engine/core/math/quaternion.hpp"
#include "engine/core/math/types.hpp"
#include "engine/gems/math/test_utils.hpp"
#include "gtest/gtest.h"
namespace isaac {
TEST(SO3, composition) {
SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 1.0, 3.0));
SO3d rot2 = SO3d::FromAngleAxis(1.7, Vector3d(1.0, 1.0, 3.0));
SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(1.0, 1.0, 3.0));
SO3d rot4 = SO3d::FromAngleAxis(0.535, Vector3d(1.0, 1.0, 3.0));
EXPECT_NEAR((rot1 * rot2 * rot3 * rot4).angle(),
SO3d::FromAngleAxis(rot1.angle() + rot2.angle() + rot3.angle() + rot4.angle(),
Vector3d(1.0, 1.0, 3.0)).angle(), 1e-7);
}
TEST(SO3, angle) {
SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 0.0, 0.0));
SO3d rot2 = SO3d::FromAngleAxis(-1.7, Vector3d(0.0, 1.0, 0.0));
SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(0.0, 0.0, 1.0));
SO3d rot4 = SO3d::FromAngleAxis(-0.535, Vector3d(1.0, 1.0, 1.0));
EXPECT_NEAR(rot1.angle(), 1.1, 1e-7);
EXPECT_NEAR(rot2.angle(), 1.7, 1e-7);
EXPECT_NEAR(rot3.angle(), 2.5, 1e-7);
EXPECT_NEAR(rot4.angle(), 0.535, 1e-7);
}
TEST(SO3, inverse) {
SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 0.0, 0.0));
SO3d rot2 = SO3d::FromAngleAxis(1.7, Vector3d(0.0, 1.0, 0.0));
SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(0.0, 0.0, 1.0));
SO3d rot4 = SO3d::FromAngleAxis(0.535, Vector3d(1.0, 1.0, 1.0));
EXPECT_NEAR(rot1.inverse().angle(), rot1.angle(), 1e-7);
EXPECT_NEAR(rot2.inverse().angle(), rot2.angle(), 1e-7);
EXPECT_NEAR(rot3.inverse().angle(), rot3.angle(), 1e-7);
EXPECT_NEAR(rot4.inverse().angle(), rot4.angle(), 1e-7);
EXPECT_NEAR((rot1.inverse().axis()+rot1.axis()).norm(), 0.0, 1e-7)
<< rot1.axis() << " vs " << rot1.inverse().axis();
EXPECT_NEAR((rot2.inverse().axis()+rot2.axis()).norm(), 0.0, 1e-7)
<< rot2.axis() << " vs " << rot2.inverse().axis();
EXPECT_NEAR((rot3.inverse().axis()+rot3.axis()).norm(), 0.0, 1e-7)
<< rot3.axis() << " vs " << rot3.inverse().axis();
EXPECT_NEAR((rot4.inverse().axis()+rot4.axis()).norm(), 0.0, 1e-7)
<< rot4.axis() << " vs " << rot4.inverse().axis();
}
TEST(SO3, vector) {
Vector3d vec1 = SO3d::FromAngleAxis(Pi<double>/2, Vector3d(0.0, 0.0, 1.0)) * Vector3d(1.0, 2.0, 3.0);
EXPECT_NEAR(vec1.x(), -2.0, 1e-7);
EXPECT_NEAR(vec1.y(), 1.0, 1e-7);
EXPECT_NEAR(vec1.z(), 3.0, 1e-7);
}
TEST(SO3, euler_angles) {
enum EulerAngles {
kRoll = 0,
kPitch = 1,
kYaw = 2
};
constexpr double roll = 1.1;
constexpr double pitch = 1.7;
constexpr double yaw = 2.5;
SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0));
SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0));
SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0));
SO3d rot4 = rot1 * rot2 *rot3;
Vector3d rot1_euler = rot1.eulerAnglesRPY();
Vector3d rot2_euler = rot2.eulerAnglesRPY();
Vector3d rot3_euler = rot3.eulerAnglesRPY();
Vector3d rot4_euler = rot4.eulerAnglesRPY();
EXPECT_NEAR(rot1_euler[kRoll], roll, 1e-7);
EXPECT_NEAR(rot1_euler[kPitch], 0.0, 1e-7);
EXPECT_NEAR(rot1_euler[kYaw], 0.0, 1e-7);
EXPECT_NEAR(rot2_euler[kRoll], 0.0, 1e-7);
EXPECT_NEAR(rot2_euler[kPitch], pitch, 1e-7);
EXPECT_NEAR(rot2_euler[kYaw], 0.0, 1e-7);
EXPECT_NEAR(rot3_euler[kRoll], 0.0, 1e-7);
EXPECT_NEAR(rot3_euler[kPitch], 0.0, 1e-7);
EXPECT_NEAR(rot3_euler[kYaw], yaw, 1e-7);
EXPECT_NEAR(rot4_euler[kRoll], roll, 1e-7);
EXPECT_NEAR(rot4_euler[kPitch], pitch, 1e-7);
EXPECT_NEAR(rot4_euler[kYaw], yaw, 1e-7);
}
TEST(SO3, euler_angles_close_zero) {
enum EulerAngles {
kRoll = 0,
kPitch = 1,
kYaw = 2
};
for (double roll = -Pi<double> * 0.25; roll < Pi<double> * 0.25; roll += Pi<double> * 0.05) {
for (double pitch = -Pi<double> * 0.25; pitch < Pi<double> * 0.25; pitch += Pi<double> * 0.05) {
for (double yaw = -Pi<double> * 0.25; yaw < Pi<double> * 0.25; yaw += Pi<double> * 0.05) {
const SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0));
const SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0));
const SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0));
const SO3d rot4 = rot1 * rot2 *rot3;
const Vector3d rot4_euler = rot4.eulerAnglesRPY();
EXPECT_NEAR(rot4_euler[kRoll], roll, 1e-7);
EXPECT_NEAR(rot4_euler[kPitch], pitch, 1e-7);
EXPECT_NEAR(rot4_euler[kYaw], yaw, 1e-7);
}
}
}
}
TEST(SO3, euler_angles_conversion) {
enum EulerAngles {
kRoll = 0,
kPitch = 1,
kYaw = 2
};
constexpr double roll = 1.1;
constexpr double pitch = 1.7;
constexpr double yaw = 2.5;
const SO3d so3 = SO3d::FromEulerAnglesRPY(roll, pitch, yaw);
const Vector3d euler_angles = so3.eulerAnglesRPY();
EXPECT_NEAR(euler_angles[kRoll], roll, 1e-7);
EXPECT_NEAR(euler_angles[kPitch], pitch, 1e-7);
EXPECT_NEAR(euler_angles[kYaw], yaw, 1e-7);
}
TEST(SO3, rotation_jacobian) {
Vector3d v = Vector3d::Random();
for (double roll = -Pi<double> * 0.25; roll < Pi<double> * 0.25; roll += Pi<double> * 0.05) {
for (double pitch = -Pi<double> * 0.25; pitch < Pi<double> * 0.25; pitch += Pi<double> * 0.05) {
for (double yaw = -Pi<double> * 0.25; yaw < Pi<double> * 0.25; yaw += Pi<double> * 0.05) {
const SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0));
const SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0));
// const SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0));
const SO3d rot4 = rot1 * rot2;
Matrix<double, 3, 4> result_a = rot4.vectorRotationJacobian(v);
Matrix<double, 3, 4> result_b = rot1.matrix() * rot2.vectorRotationJacobian(v);
Matrix<double, 3, 4> result_c =
(QuaternionProductMatrixLeft(rot1.quaternion())
* result_b.transpose()).transpose();
for (int j = 0; j < result_a.cols(); j++) {
ISAAC_EXPECT_VEC_NEAR(result_a.col(j), result_c.col(j), 1e-3);
}
}
}
}
}
} // namespace isaac
| 38.045977 | 103 | 0.629154 | ddr95070 |
176af815ab84f5cfde7a5eaea80f8cccbfcb108d | 8,354 | cc | C++ | orb_slam3/Examples/ROS/ORB_SLAM3/src/mono_imu_tcw.cc | zhouyong1234/ORB-SLAM3 | 796fa6d8562c88355b78411f9f6915e287a14f5a | [
"Apache-2.0"
] | null | null | null | orb_slam3/Examples/ROS/ORB_SLAM3/src/mono_imu_tcw.cc | zhouyong1234/ORB-SLAM3 | 796fa6d8562c88355b78411f9f6915e287a14f5a | [
"Apache-2.0"
] | null | null | null | orb_slam3/Examples/ROS/ORB_SLAM3/src/mono_imu_tcw.cc | zhouyong1234/ORB-SLAM3 | 796fa6d8562c88355b78411f9f6915e287a14f5a | [
"Apache-2.0"
] | null | null | null | /**
* This file is part of ORB-SLAM3
*
* Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
* Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
*
* ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with ORB-SLAM3.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include<iostream>
#include<algorithm>
#include<fstream>
#include<chrono>
#include<vector>
#include<queue>
#include<thread>
#include<mutex>
#include<ros/ros.h>
#include<cv_bridge/cv_bridge.h>
#include<sensor_msgs/Imu.h>
#include<opencv2/core/core.hpp>
#include"../../../include/System.h"
#include"../include/ImuTypes.h"
#include <geometry_msgs/PoseStamped.h>
using namespace std;
class ImuGrabber
{
public:
ImuGrabber(){};
void GrabImu(const sensor_msgs::ImuConstPtr &imu_msg);
queue<sensor_msgs::ImuConstPtr> imuBuf;
std::mutex mBufMutex;
};
class ImageGrabber
{
ros::NodeHandle nh; //定义句柄初始化
ros::Publisher pub1,pub_tcw; //定义发布者
public:
ImageGrabber(ORB_SLAM3::System* pSLAM, ImuGrabber *pImuGb, const bool bClahe): mpSLAM(pSLAM), mpImuGb(pImuGb), mbClahe(bClahe),nh("~")
{
pub_tcw= nh.advertise<geometry_msgs::PoseStamped> ("CameraPose", 10);
}
void GrabImage(const sensor_msgs::ImageConstPtr& msg);
cv::Mat GetImage(const sensor_msgs::ImageConstPtr &img_msg);
void SyncWithImu();
queue<sensor_msgs::ImageConstPtr> img0Buf;
std::mutex mBufMutex;
ORB_SLAM3::System* mpSLAM;
ImuGrabber *mpImuGb;
const bool mbClahe;
cv::Ptr<cv::CLAHE> mClahe = cv::createCLAHE(3.0, cv::Size(8, 8));
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "Mono_Inertial");
ros::NodeHandle n("~");
ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Info);
bool bEqual = false;
if(argc < 1 || argc > 2)
{
cerr << endl << "Usage: rosrun ORB_SLAM3 Mono_Inertial path_to_vocabulary path_to_settings [do_equalize]" << endl;
ros::shutdown();
return 1;
}
if(argc==1)
{
std::string sbEqual(argv[3]);
if(sbEqual == "true")
bEqual = true;
}
string ORBvoc_path = "/home/lin/code/ORB_SLAM3/Vocabulary/ORBvoc.txt";
string config_path = "/home/lin/code/ORB_SLAM3/Examples/ROS/ORB_SLAM3/src/cam_inertial.yaml";
// Create SLAM system. It initializes all system threads and gets ready to process frames.
ORB_SLAM3::System SLAM(ORBvoc_path,config_path,ORB_SLAM3::System::IMU_MONOCULAR,true);
ImuGrabber imugb;
ImageGrabber igb(&SLAM,&imugb,bEqual); // TODO
// Maximum delay, 5 seconds
ros::Subscriber sub_imu = n.subscribe("/android/imu", 1000, &ImuGrabber::GrabImu, &imugb);
ros::Subscriber sub_img0 = n.subscribe("/usb_cam/image_raw", 100, &ImageGrabber::GrabImage,&igb);
std::thread sync_thread(&ImageGrabber::SyncWithImu,&igb);
ros::spin();
return 0;
}
void ImageGrabber::GrabImage(const sensor_msgs::ImageConstPtr &img_msg)
{
mBufMutex.lock();
if (!img0Buf.empty())
img0Buf.pop();
img0Buf.push(img_msg);
mBufMutex.unlock();
}
cv::Mat ImageGrabber::GetImage(const sensor_msgs::ImageConstPtr &img_msg)
{
// Copy the ros image message to cv::Mat.
cv_bridge::CvImageConstPtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvShare(img_msg, sensor_msgs::image_encodings::MONO8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
}
if(cv_ptr->image.type()==0)
{
return cv_ptr->image.clone();
}
else
{
std::cout << "Error type" << std::endl;
return cv_ptr->image.clone();
}
}
void ImageGrabber::SyncWithImu()
{
while(1)
{
cv::Mat im;
double tIm = 0;
if (!img0Buf.empty()&&!mpImuGb->imuBuf.empty())
{
tIm = img0Buf.front()->header.stamp.toSec();
if(tIm>mpImuGb->imuBuf.back()->header.stamp.toSec())
continue;
{
this->mBufMutex.lock();
im = GetImage(img0Buf.front());
img0Buf.pop();
this->mBufMutex.unlock();
}
vector<ORB_SLAM3::IMU::Point> vImuMeas;
mpImuGb->mBufMutex.lock();
// if(!mpImuGb->imuBuf.empty())
// {
// // Load imu measurements from buffer
// vImuMeas.clear();
// while(!mpImuGb->imuBuf.empty() && mpImuGb->imuBuf.front()->header.stamp.toSec()<=tIm)
// {
// double t = mpImuGb->imuBuf.front()->header.stamp.toSec();
// cv::Point3f acc(mpImuGb->imuBuf.front()->linear_acceleration.x, mpImuGb->imuBuf.front()->linear_acceleration.y, mpImuGb->imuBuf.front()->linear_acceleration.z);
// cv::Point3f gyr(mpImuGb->imuBuf.front()->angular_velocity.x, mpImuGb->imuBuf.front()->angular_velocity.y, mpImuGb->imuBuf.front()->angular_velocity.z);
// vImuMeas.push_back(ORB_SLAM3::IMU::Point(acc,gyr,t));
// mpImuGb->imuBuf.pop();
// }
// }
// 时间对齐
if(!mpImuGb->imuBuf.empty())
{
// Load imu measurements from buffer
vImuMeas.clear();
static bool time_flag = true;
static auto TIME_OFFSET = 0.0;
if(time_flag){
TIME_OFFSET = mpImuGb->imuBuf.front()->header.stamp.toSec()-tIm;
time_flag = false;
}
cout<<"imu_time: "<<setprecision(11)<<mpImuGb->imuBuf.front()->header.stamp.toSec()-TIME_OFFSET<<endl;
cout<<"image_time: "<<setprecision(11)<<tIm<<endl;
cout<<"---------------"<<endl;
while(!mpImuGb->imuBuf.empty() && mpImuGb->imuBuf.front()->header.stamp.toSec()-TIME_OFFSET<=tIm)
{
double t = mpImuGb->imuBuf.front()->header.stamp.toSec() - TIME_OFFSET;
cv::Point3f acc(mpImuGb->imuBuf.front()->linear_acceleration.x, mpImuGb->imuBuf.front()->linear_acceleration.y, mpImuGb->imuBuf.front()->linear_acceleration.z);
cv::Point3f gyr(mpImuGb->imuBuf.front()->angular_velocity.x, mpImuGb->imuBuf.front()->angular_velocity.y, mpImuGb->imuBuf.front()->angular_velocity.z);
cout<<"imudata: "<< t<<" "<<acc.x<<" "<<acc.y<<" "<<acc.z<<" "<<gyr.x<<" "<<gyr.y<<" "<<gyr.z<<endl;
vImuMeas.push_back(ORB_SLAM3::IMU::Point(acc,gyr,t));
mpImuGb->imuBuf.pop();
}
}
mpImuGb->mBufMutex.unlock();
if(mbClahe)
mClahe->apply(im,im);
cv::resize(im,im,cv::Size(640,480));
// if(cv::waitKey(10)=='q')
// break;
cv::Mat Tcw;
Tcw = mpSLAM->TrackMonocular(im,tIm,vImuMeas);
if(!Tcw.empty())
{
cv::Mat Twc =Tcw.inv();
cv::Mat RWC= Twc.rowRange(0,3).colRange(0,3);
cv::Mat tWC= Twc.rowRange(0,3).col(3);
Eigen::Matrix<double,3,3> eigMat ;
eigMat <<RWC.at<float>(0,0),RWC.at<float>(0,1),RWC.at<float>(0,2),
RWC.at<float>(1,0),RWC.at<float>(1,1),RWC.at<float>(1,2),
RWC.at<float>(2,0),RWC.at<float>(2,1),RWC.at<float>(2,2);
Eigen::Quaterniond q(eigMat);
geometry_msgs::PoseStamped tcw_msg;
tcw_msg.pose.position.x=tWC.at<float>(0);
tcw_msg.pose.position.y=tWC.at<float>(1);
tcw_msg.pose.position.z=tWC.at<float>(2);
tcw_msg.pose.orientation.x=q.x();
tcw_msg.pose.orientation.y=q.y();
tcw_msg.pose.orientation.z=q.z();
tcw_msg.pose.orientation.w=q.w();
pub_tcw.publish(tcw_msg);
}
else
{
cout<<"Twc is empty ..."<<endl;
}
}
std::chrono::milliseconds tSleep(1);
std::this_thread::sleep_for(tSleep);
}
}
void ImuGrabber::GrabImu(const sensor_msgs::ImuConstPtr &imu_msg)
{
mBufMutex.lock();
imuBuf.push(imu_msg);
mBufMutex.unlock();
return;
}
| 31.055762 | 180 | 0.625569 | zhouyong1234 |
176c14c56d38352d4afa91612a7dbf8873219b46 | 131 | cpp | C++ | src/core/DataStreamException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | null | null | null | src/core/DataStreamException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | 26 | 2017-12-13T12:45:32.000Z | 2018-02-06T11:08:04.000Z | src/core/DataStreamException.cpp | Neomer/binc | 3af615f36cb23f1cdc9319b7a6e15c6c342a53b9 | [
"Apache-2.0"
] | null | null | null | #include "DataStreamException.h"
DataStreamException::DataStreamException(const char * message) :
BaseException(message)
{
}
| 16.375 | 64 | 0.770992 | Neomer |
176d4e9093f4dd271a1818cb111d883b50d8c17c | 2,924 | cpp | C++ | manager.cpp | kwarehit/runtestcases | fe7b68a90b7d5051277e383c50a1e90fbeab8c73 | [
"BSL-1.0"
] | null | null | null | manager.cpp | kwarehit/runtestcases | fe7b68a90b7d5051277e383c50a1e90fbeab8c73 | [
"BSL-1.0"
] | null | null | null | manager.cpp | kwarehit/runtestcases | fe7b68a90b7d5051277e383c50a1e90fbeab8c73 | [
"BSL-1.0"
] | null | null | null | #include "manager.h"
#include "commonhdr.h"
#include "log.h"
#include "caseinfomodel.h"
#include "monitor.h"
#include "iocontextwrapper.h"
#include "datamanager.h"
#include "logtext.h"
#include "caseinfomodel.h"
Manager::Manager(QObject *parent)
: QObject(parent)
{
dataMgr_ = std::make_shared<DataManager>();
logText_ = std::make_shared<LogText>();
iocWrapper_ = std::make_shared<IOContextWrapper>();
monitor_ = std::make_shared<Monitor>(*iocWrapper_);
thread_ = std::make_shared<MonitorThread>(*iocWrapper_, *monitor_, dataMgr_, this);
dataMgr_->setMonitorThread(thread_);
connect(logText_.get(), &LogText::addLog, this, &Manager::onAddLogText);
connect(monitor_.get(), &Monitor::addText, this, &Manager::onAddMonitorText);
connect(thread_.get(), &MonitorThread::enableRunButton, this, &Manager::onEnabledRunButton);
connect(thread_.get(), &MonitorThread::enableStopButton, this, &Manager::onEnabledStopButton);
connect(this, &Manager::stopProcess, thread_.get(), &MonitorThread::onStopProcess);
}
Manager::~Manager()
{
}
void Manager::setDataMgr(CaseInfoModel* pModel)
{
model_ = pModel;
pModel->setDataManger(dataMgr_);
}
void Manager::onAddMonitorText(const QString& s)
{
Q_EMIT addMonitorText(s);
}
void Manager::onEnabledRunButton(bool b)
{
Q_EMIT setEnabledRunButton(b);
}
void Manager::onEnabledStopButton(bool b)
{
Q_EMIT setEnabledStopButton(b);
}
void Manager::onAddLogText(const QString& s)
{
Q_EMIT addLogText(s);
}
QString Manager::getRootDir()
{
try
{
return QString::fromStdString(dataMgr_->getRootDir());
}
catch (std::exception& e)
{
BOOST_LOG(processLog::get()) << e.what() << std::endl;
return "";
}
}
void Manager::setRootDir(const QString& rootDir)
{
try
{
dataMgr_->setRootDir(rootDir.toStdString());
}
catch (std::exception& e)
{
BOOST_LOG(processLog::get()) << e.what() << std::endl;
}
}
QString Manager::getCases()
{
try
{
return QString::fromStdString(dataMgr_->getCases());
}
catch (std::exception& e)
{
BOOST_LOG(processLog::get()) << e.what() << std::endl;
}
return {};
}
void Manager::onCaseTextChanged(const QString& text)
{
try
{
auto listStr = text.split('\n', QString::SkipEmptyParts);
std::set<std::string> cases;
for(auto i = 0; i<listStr.size(); ++i)
{
QString s = listStr[i].trimmed();
cases.insert(s.toStdString());
}
dataMgr_->clearCases();
dataMgr_->refine(cases);
if(model_)
{
model_->updateData();
}
}
catch (std::exception& ec)
{
BOOST_LOG(processLog::get()) << ec.what() << std::endl;
}
}
void Manager::start()
{
thread_->start();
}
void Manager::stop()
{
Q_EMIT stopProcess();
}
| 20.305556 | 98 | 0.626197 | kwarehit |
176e929ba649f73a9bb54d48b92cfc75971ffce0 | 967 | cpp | C++ | BookSamples/Capitolo7/Ritardo_BufferLineare/Ritardo_BufferLineare/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | BookSamples/Capitolo7/Ritardo_BufferLineare/Ritardo_BufferLineare/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | BookSamples/Capitolo7/Ritardo_BufferLineare/Ritardo_BufferLineare/main.cpp | mscarpiniti/ArtBook | ca74c773c7312d22329cc453f4a5a799fe2dd587 | [
"MIT"
] | null | null | null | #include <iostream>
#define SAMPLE_RATE 44100
using namespace std;
/* Buffer Lineare ---------------------------------------------------------- */
float D_LinBuffer(float *buffer, int D, float x)
{
int i;
for(i = D-1; i >= 1; i--)
buffer[i] = buffer[i-1];
buffer[0] = x;
return buffer[D-1];
}
int main()
{
int i, D;
const int N = 2000;
float rit = 0.005, *buffer, *y, x[N];
for (i = 0; i < N; i++)
x[i] = 2 * ((float)rand() / (float)RAND_MAX) - 1;
D = (int)(rit*SAMPLE_RATE);
buffer = (float *)calloc(D, sizeof(float));
y = (float *)calloc(N, sizeof(float));
for (i = 0; i < D; i++)
buffer[i] = 0;
for (i = 0; i < N; i++)
y[i] = D_LinBuffer(buffer, D, x[i]);
cout << "Posizione x y: " << endl << endl;
for (i = 0; i < N; i++)
cout << i + 1 << ": " << x[i] << " " << y[i] << endl;
return 0;
}
| 21.021739 | 80 | 0.416753 | mscarpiniti |
176f15fa2f0fe766ba00bdeec96e1621b8ce07d3 | 2,910 | ipp | C++ | boost/test/utils/runtime/cla/dual_name_parameter.ipp | UnPourTous/boost-159-for-rn | 47e2c37fcbd5e1b25561e5a4fc81bc4f31d2cbf4 | [
"BSL-1.0"
] | 2 | 2021-08-08T02:06:56.000Z | 2021-12-20T02:16:44.000Z | include/boost/test/utils/runtime/cla/dual_name_parameter.ipp | Acidburn0zzz/PopcornTorrent-1 | c12a30ef9e971059dae5f7ce24a8c37fef83c0c4 | [
"MIT"
] | null | null | null | include/boost/test/utils/runtime/cla/dual_name_parameter.ipp | Acidburn0zzz/PopcornTorrent-1 | c12a30ef9e971059dae5f7ce24a8c37fef83c0c4 | [
"MIT"
] | 1 | 2017-04-09T17:04:14.000Z | 2017-04-09T17:04:14.000Z | // (C) Copyright Gennadiy Rozental 2005-2014.
// Use, modification, and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : implements model of generic parameter with dual naming
// ***************************************************************************
#ifndef BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
#define BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>
#include <boost/test/utils/runtime/validation.hpp>
#include <boost/test/utils/runtime/cla/dual_name_parameter.hpp>
namespace boost {
namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE {
namespace cla {
// ************************************************************************** //
// ************** dual_name_policy ************** //
// ************************************************************************** //
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE
dual_name_policy::dual_name_policy()
{
m_primary.accept_modifier( prefix = BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "--" ) );
m_secondary.accept_modifier( prefix = BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "-" ) );
}
//____________________________________________________________________________//
namespace {
template<typename K>
inline void
split( string_name_policy& snp, char_name_policy& cnp, cstring src, K const& k )
{
cstring::iterator sep = std::find( src.begin(), src.end(), BOOST_TEST_UTILS_RUNTIME_PARAM_LITERAL( '|' ) );
if( sep != src.begin() )
snp.accept_modifier( k = cstring( src.begin(), sep ) );
if( sep != src.end() )
cnp.accept_modifier( k = cstring( sep+1, src.end() ) );
}
} // local namespace
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void
dual_name_policy::set_prefix( cstring src )
{
split( m_primary, m_secondary, src, prefix );
}
//____________________________________________________________________________//
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void
dual_name_policy::set_name( cstring src )
{
split( m_primary, m_secondary, src, name );
}
//____________________________________________________________________________//
BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void
dual_name_policy::set_separator( cstring src )
{
split( m_primary, m_secondary, src, separator );
}
//____________________________________________________________________________//
} // namespace cla
} // namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE
} // namespace boost
#endif // BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
| 31.978022 | 112 | 0.669416 | UnPourTous |
1771c5a32dfefdf6a35b913d0f935a71a823278f | 3,236 | cpp | C++ | src/MeteringSDK/MCORE/MSynchronizer.cpp | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 9 | 2016-09-02T17:24:58.000Z | 2021-12-14T19:43:48.000Z | src/MeteringSDK/MCORE/MSynchronizer.cpp | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 1 | 2018-09-06T21:48:42.000Z | 2018-09-06T21:48:42.000Z | src/MeteringSDK/MCORE/MSynchronizer.cpp | beroset/C12Adapter | 593b201db169481245b0673813e19d174560a41e | [
"MIT"
] | 4 | 2016-09-06T16:54:36.000Z | 2021-12-16T16:15:24.000Z | // File MCORE/MSynchronizer.cpp
#include "MCOREExtern.h"
#include "MSynchronizer.h"
#include "MException.h"
#if !M_NO_MULTITHREADING
MSynchronizer::Locker::Locker(const MSynchronizer& s)
:
m_synchronizer(const_cast<MSynchronizer&>(s)),
m_locked(false)
{
m_synchronizer.Lock();
m_locked = true;
}
MSynchronizer::Locker::Locker(const MSynchronizer& s, long timeout)
:
m_synchronizer(const_cast<MSynchronizer&>(s)),
m_locked(false)
{
m_locked = m_synchronizer.LockWithTimeout(timeout);
}
MSynchronizer::Locker::~Locker() M_NO_THROW
{
if ( m_locked )
m_synchronizer.Unlock();
}
MSynchronizer::~MSynchronizer() M_NO_THROW
{
#if (M_OS & M_OS_WIN32)
if ( m_handle != 0 )
CloseHandle(m_handle);
#elif (M_OS & M_OS_POSIX)
// In Pthreads there are pthread_mutex_t and pthread_cond_t types for synchronization objects, they are destroyed in the derived classes
#else
#error "No implementation of semaphore exists for this OS"
#endif
}
#if (M_OS & M_OS_WIN32)
bool MSynchronizer::LockWithTimeout(long timeout)
{
M_ASSERT(m_handle != 0);
switch( ::WaitForSingleObject(m_handle, timeout < 0 ? INFINITE : timeout) )
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
break;
default:
M_ASSERT(0); // An unknown code was returned once. Throw error in this case.
case WAIT_FAILED:
MESystemError::ThrowLastSystemError();
M_ENSURED_ASSERT(0);
}
return false;
}
#endif
#if (M_OS & M_OS_WIN32)
bool MSynchronizer::DoWaitForMany(long timeout, unsigned* which, MSynchronizer* p1, MSynchronizer* p2, MSynchronizer* p3, MSynchronizer* p4, MSynchronizer* p5)
{
M_ASSERT(p1 != NULL && p2 != NULL);
HANDLE handles [ 5 ];
handles[0] = p1->m_handle;
handles[1] = p2->m_handle;
DWORD handlesCount;
if ( p3 != NULL )
{
handles[2] = p3->m_handle;
if ( p4 != NULL )
{
handles[3] = p4->m_handle;
if ( p5 != NULL )
{
handles[4] = p5->m_handle;
handlesCount = 5;
}
else
handlesCount = 4;
}
else
{
M_ASSERT(p5 == NULL);
handlesCount = 3;
}
}
else
{
M_ASSERT(p4 == NULL && p5 == NULL);
handlesCount = 2;
}
DWORD ret = ::WaitForMultipleObjects(handlesCount, handles, ((which == NULL) ? TRUE : FALSE), timeout < 0 ? INFINITE : static_cast<DWORD>(timeout));
M_COMPILED_ASSERT(WAIT_OBJECT_0 == 0); // below code depends on it
if ( ret <= (WAIT_OBJECT_0 + 5) )
{
if ( which != NULL )
*which = ret;
return true;
}
if ( ret != WAIT_TIMEOUT )
{
M_ASSERT(ret == WAIT_FAILED); // WAIT_ABANDONED_x is not supported
MESystemError::ThrowLastSystemError();
M_ENSURED_ASSERT(0);
}
return false;
}
#endif
#endif
| 26.308943 | 162 | 0.554079 | beroset |
1776a2192a86edd7a26a00d7695fe7c2cbca732a | 88 | cpp | C++ | meditation_app/model/statsmodel.cpp | mikkac/meditation_app | 26c592e0c91fd2661ab91c2f7ce020293962aa99 | [
"MIT"
] | null | null | null | meditation_app/model/statsmodel.cpp | mikkac/meditation_app | 26c592e0c91fd2661ab91c2f7ce020293962aa99 | [
"MIT"
] | null | null | null | meditation_app/model/statsmodel.cpp | mikkac/meditation_app | 26c592e0c91fd2661ab91c2f7ce020293962aa99 | [
"MIT"
] | null | null | null | #include "statsmodel.h"
StatsModel::StatsModel(QObject *parent) : QObject(parent)
{
}
| 12.571429 | 57 | 0.727273 | mikkac |
17799c7bc5a2165217b53d8904404910a77fff2a | 10,622 | cpp | C++ | libs/spirit/example/x3/calc6.cpp | Abce/boost | 2d7491a27211aa5defab113f8e2d657c3d85ca93 | [
"BSL-1.0"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | libs/boost/libs/spirit/example/x3/calc6.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/boost/libs/spirit/example/x3/calc6.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | /*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
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)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
// Yet another calculator example! This time, we will compile to a simple
// virtual machine. This is actually one of the very first Spirit example
// circa 2000. Now, it's ported to Spirit2 (and X3).
//
// [ JDG Sometime 2000 ] pre-boost
// [ JDG September 18, 2002 ] spirit1
// [ JDG April 8, 2007 ] spirit2
// [ JDG February 18, 2011 ] Pure attributes. No semantic actions.
// [ JDG April 9, 2014 ] Spirit X3 (from qi calc6)
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Uncomment this if you want to enable debugging
//#define BOOST_SPIRIT_X3_DEBUG
#if defined(_MSC_VER)
# pragma warning(disable: 4345)
#endif
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include <string>
#include <list>
#include <numeric>
namespace x3 = boost::spirit::x3;
namespace client { namespace ast
{
///////////////////////////////////////////////////////////////////////////
// The AST
///////////////////////////////////////////////////////////////////////////
struct nil {};
struct signed_;
struct expression;
struct operand : x3::variant<
nil
, unsigned int
, x3::forward_ast<signed_>
, x3::forward_ast<expression>
>
{
using base_type::base_type;
using base_type::operator=;
};
struct signed_
{
char sign;
operand operand_;
};
struct operation
{
char operator_;
operand operand_;
};
struct expression
{
operand first;
std::list<operation> rest;
};
// print function for debugging
inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; }
}}
BOOST_FUSION_ADAPT_STRUCT(
client::ast::signed_,
(char, sign)
(client::ast::operand, operand_)
)
BOOST_FUSION_ADAPT_STRUCT(
client::ast::operation,
(char, operator_)
(client::ast::operand, operand_)
)
BOOST_FUSION_ADAPT_STRUCT(
client::ast::expression,
(client::ast::operand, first)
(std::list<client::ast::operation>, rest)
)
namespace client
{
///////////////////////////////////////////////////////////////////////////
// The Virtual Machine
///////////////////////////////////////////////////////////////////////////
enum byte_code
{
op_neg, // negate the top stack entry
op_add, // add top two stack entries
op_sub, // subtract top two stack entries
op_mul, // multiply top two stack entries
op_div, // divide top two stack entries
op_int, // push constant integer into the stack
};
class vmachine
{
public:
vmachine(unsigned stackSize = 4096)
: stack(stackSize)
, stack_ptr(stack.begin())
{
}
int top() const { return stack_ptr[-1]; };
void execute(std::vector<int> const& code);
private:
std::vector<int> stack;
std::vector<int>::iterator stack_ptr;
};
void vmachine::execute(std::vector<int> const& code)
{
std::vector<int>::const_iterator pc = code.begin();
stack_ptr = stack.begin();
while (pc != code.end())
{
switch (*pc++)
{
case op_neg:
stack_ptr[-1] = -stack_ptr[-1];
break;
case op_add:
--stack_ptr;
stack_ptr[-1] += stack_ptr[0];
break;
case op_sub:
--stack_ptr;
stack_ptr[-1] -= stack_ptr[0];
break;
case op_mul:
--stack_ptr;
stack_ptr[-1] *= stack_ptr[0];
break;
case op_div:
--stack_ptr;
stack_ptr[-1] /= stack_ptr[0];
break;
case op_int:
*stack_ptr++ = *pc++;
break;
}
}
}
///////////////////////////////////////////////////////////////////////////
// The Compiler
///////////////////////////////////////////////////////////////////////////
struct compiler
{
typedef void result_type;
std::vector<int>& code;
compiler(std::vector<int>& code)
: code(code) {}
void operator()(ast::nil) const { BOOST_ASSERT(0); }
void operator()(unsigned int n) const
{
code.push_back(op_int);
code.push_back(n);
}
void operator()(ast::operation const& x) const
{
boost::apply_visitor(*this, x.operand_);
switch (x.operator_)
{
case '+': code.push_back(op_add); break;
case '-': code.push_back(op_sub); break;
case '*': code.push_back(op_mul); break;
case '/': code.push_back(op_div); break;
default: BOOST_ASSERT(0); break;
}
}
void operator()(ast::signed_ const& x) const
{
boost::apply_visitor(*this, x.operand_);
switch (x.sign)
{
case '-': code.push_back(op_neg); break;
case '+': break;
default: BOOST_ASSERT(0); break;
}
}
void operator()(ast::expression const& x) const
{
boost::apply_visitor(*this, x.first);
for (ast::operation const& oper : x.rest)
{
(*this)(oper);
}
}
};
///////////////////////////////////////////////////////////////////////////////
// The calculator grammar
///////////////////////////////////////////////////////////////////////////////
namespace calculator_grammar
{
using x3::uint_;
using x3::char_;
struct expression_class;
struct term_class;
struct factor_class;
x3::rule<expression_class, ast::expression> const expression("expression");
x3::rule<term_class, ast::expression> const term("term");
x3::rule<factor_class, ast::operand> const factor("factor");
auto const expression_def =
term
>> *( (char_('+') > term)
| (char_('-') > term)
)
;
auto const term_def =
factor
>> *( (char_('*') > factor)
| (char_('/') > factor)
)
;
auto const factor_def =
uint_
| '(' > expression > ')'
| (char_('-') > factor)
| (char_('+') > factor)
;
BOOST_SPIRIT_DEFINE(
expression = expression_def
, term = term_def
, factor = factor_def
);
struct expression_class
{
// Our error handler
template <typename Iterator, typename Exception, typename Context>
x3::error_handler_result
on_error(Iterator&, Iterator const& last, Exception const& x, Context const& context)
{
std::cout
<< "Error! Expecting: "
<< x.which()
<< " here: \""
<< std::string(x.where(), last)
<< "\""
<< std::endl
;
return x3::error_handler_result::fail;
}
};
auto calculator = expression;
}
using calculator_grammar::calculator;
}
///////////////////////////////////////////////////////////////////////////////
// Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Expression parser...\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Type an expression...or [q or Q] to quit\n\n";
typedef std::string::const_iterator iterator_type;
typedef client::ast::expression ast_expression;
typedef client::compiler compiler;
std::string str;
while (std::getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
client::vmachine mach; // Our virtual machine
std::vector<int> code; // Our VM code
auto& calc = client::calculator; // Our grammar
ast_expression expression; // Our program (AST)
compiler compile(code); // Compiles the program
std::string::const_iterator iter = str.begin();
std::string::const_iterator end = str.end();
boost::spirit::x3::ascii::space_type space;
bool r = phrase_parse(iter, end, calc, space, expression);
if (r && iter == end)
{
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
compile(expression);
mach.execute(code);
std::cout << "\nResult: " << mach.top() << std::endl;
std::cout << "-------------------------\n";
}
else
{
std::string rest(iter, end);
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "-------------------------\n";
}
}
std::cout << "Bye... :-) \n\n";
return 0;
}
| 30.522989 | 98 | 0.419036 | Abce |
177c1a8537d1eaa642928e64cf949a250d44e614 | 10,313 | cpp | C++ | cpp/src/grammar.cpp | sapphire-lang/emerald | 5cb7209f918e8ebdb36bb0455f58d3e941fc6e52 | [
"MIT"
] | null | null | null | cpp/src/grammar.cpp | sapphire-lang/emerald | 5cb7209f918e8ebdb36bb0455f58d3e941fc6e52 | [
"MIT"
] | null | null | null | cpp/src/grammar.cpp | sapphire-lang/emerald | 5cb7209f918e8ebdb36bb0455f58d3e941fc6e52 | [
"MIT"
] | null | null | null | #include <string>
#include <regex>
#include <iostream>
#include "grammar.hpp"
// [START] Include nodes
#include "nodes/node.hpp"
#include "nodes/node_list.hpp"
#include "nodes/boolean.hpp"
#include "nodes/scope_fn.hpp"
#include "nodes/scope.hpp"
#include "nodes/line.hpp"
#include "nodes/value_list.hpp"
#include "nodes/literal_new_line.hpp"
#include "nodes/attribute.hpp"
#include "nodes/attributes.hpp"
#include "nodes/tag_statement.hpp"
#include "nodes/text_literal_content.hpp"
#include "nodes/escaped.hpp"
#include "nodes/comment.hpp"
#include "nodes/scoped_key_value_pairs.hpp"
#include "nodes/key_value_pair.hpp"
#include "nodes/unary_expr.hpp"
#include "nodes/binary_expr.hpp"
#include "nodes/each.hpp"
#include "nodes/with.hpp"
#include "nodes/conditional.hpp"
#include "nodes/variable_name.hpp"
#include "nodes/variable.hpp"
#include "nodes/scope.hpp"
// [END] Include nodes
namespace {
// Helper function to turn a maybe rule (one element, made optional with a ?) into its value or a default
template<typename T>
std::function<T(const peg::SemanticValues&)> optional(T default_value) {
return [=](const peg::SemanticValues &sv) -> T {
if (sv.size() > 0) {
return sv[0].get<T>();
} else {
return default_value;
}
};
}
// Helper to turn plural rules (one element, repeated with + or *) into a vector of a given type
template<typename T>
std::function<std::vector<T>(const peg::SemanticValues&)> repeated() {
return [](const peg::SemanticValues& sv) -> std::vector<T> {
std::vector<T> contents;
for (unsigned int n = 0; n < sv.size(); n++) {
contents.push_back(sv[n].get<T>());
}
return contents;
};
}
}
Grammar::Grammar() : emerald_parser(syntax) {
emerald_parser["ROOT"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs nodes = sv[0].get<NodePtrs>();
return NodePtr(new NodeList(nodes, "\n"));
};
emerald_parser["line"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr line = sv[0].get<NodePtr>();
return NodePtr(new Line(line));
};
emerald_parser["value_list"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr keyword = sv[0].get<NodePtr>();
NodePtrs literals = sv[1].get<NodePtrs>();
return NodePtr(new ValueList(keyword, literals));
};
emerald_parser["literal_new_line"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr inline_lit_str = sv[0].get<NodePtr>();
return NodePtr(new LiteralNewLine(inline_lit_str));
};
emerald_parser["pair_list"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs nodes;
std::string base_keyword = sv[0].get<std::string>();
std::vector<const peg::SemanticValues> semantic_values = sv[1].get<std::vector<const peg::SemanticValues>>();
std::transform(semantic_values.begin(), semantic_values.end(), nodes.begin(),
[=](const peg::SemanticValues& svs) {
NodePtrs pairs = svs[0].get<NodePtrs>();
return NodePtr(new ScopedKeyValuePairs(base_keyword, pairs));
});
return NodePtr(new NodeList(nodes, "\n"));
};
emerald_parser["scoped_key_value_pairs"] = repeated<const peg::SemanticValues>();
emerald_parser["scoped_key_value_pair"] =
[](const peg::SemanticValues& sv) -> const peg::SemanticValues {
return sv;
};
emerald_parser["key_value_pair"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string key = sv[0].get<std::string>();
NodePtr value = sv[1].get<NodePtr>();
return NodePtr(new KeyValuePair(key, value));
};
emerald_parser["comment"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtr text_content = sv[0].get<NodePtr>();
return NodePtr(new Comment(text_content));
};
emerald_parser["maybe_id_name"] = optional<std::string>("");
emerald_parser["class_names"] = repeated<std::string>();
emerald_parser["tag_statement"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string tag_name = sv[0].get<std::string>();
std::string id_name = sv[1].get<std::string>();
std::vector<std::string> class_names = sv[2].get<std::vector<std::string>>();
NodePtr body = sv[3].get<NodePtr>();
NodePtr attributes = sv[4].get<NodePtr>();
NodePtr nested = sv[5].get<NodePtr>();
return NodePtr(
new TagStatement(tag_name, id_name, class_names, body, attributes, nested));
};
emerald_parser["attr_list"] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs nodes = sv[0].get<NodePtrs>();
return NodePtr(new Attributes(nodes));
};
emerald_parser["attribute"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string key = sv[0].get<std::string>();
NodePtr value = sv[1].get<NodePtr>();
return NodePtr(new Attribute(key, value));
};
emerald_parser["escaped"] =
[](const peg::SemanticValues& sv) -> NodePtr {
return NodePtr(new Escaped(sv.str()));
};
emerald_parser["maybe_negation"] = optional<bool>(false);
emerald_parser["negation"] =
[](const peg::SemanticValues& sv) -> bool {
return true;
};
emerald_parser["unary_expr"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
bool negated = sv[0].get<bool>();
BooleanPtr expr = sv[1].get<BooleanPtr>();
return BooleanPtr(new UnaryExpr(negated, expr));
};
emerald_parser["binary_expr"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
BooleanPtr lhs = sv[0].get<BooleanPtr>();
std::string op_str = sv[1].get<peg::SemanticValues>().str();
BooleanPtr rhs = sv[2].get<BooleanPtr>();
BinaryExpr::Operator op;
if (op_str == BinaryExpr::OR_STR) {
op = BinaryExpr::Operator::OR;
} else if (op_str == BinaryExpr::AND_STR) {
op = BinaryExpr::Operator::AND;
} else {
throw "Invalid operator: " + op_str;
}
return BooleanPtr(new BinaryExpr(lhs, op, rhs));
};
emerald_parser["boolean_expr"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
return sv[0].get<BooleanPtr>();
};
emerald_parser["maybe_key_name"] = optional<std::string>("");
emerald_parser["each"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
std::string collection_name = sv[0].get<std::string>();
std::string val_name = sv[1].get<std::string>();
std::string key_name = sv[2].get<std::string>();
return ScopeFnPtr(new Each(collection_name, val_name, key_name));
};
emerald_parser["with"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
std::string var_name = sv[0].get<std::string>();
return ScopeFnPtr(new With(var_name));
};
emerald_parser["given"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
BooleanPtr condition = sv[0].get<BooleanPtr>();
return ScopeFnPtr(new Conditional(true, condition));
};
emerald_parser["unless"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
BooleanPtr condition = sv[0].get<BooleanPtr>();
return ScopeFnPtr(new Conditional(false, condition));
};
emerald_parser["scope_fn"] =
[](const peg::SemanticValues& sv) -> ScopeFnPtr {
return sv[0].get<ScopeFnPtr>();
};
emerald_parser["variable_name"] =
[](const peg::SemanticValues& sv) -> BooleanPtr {
std::string name = sv.str();
return BooleanPtr(new VariableName(name));
};
emerald_parser["variable"] =
[](const peg::SemanticValues& sv) -> NodePtr {
std::string name = sv.token(0);
return NodePtr(new Variable(name));
};
emerald_parser["scope"] =
[](const peg::SemanticValues& sv) -> NodePtr {
ScopeFnPtr scope_fn = sv[0].get<ScopeFnPtr>();
NodePtr body = sv[1].get<NodePtr>();
return NodePtr(new Scope(scope_fn, body));
};
// Repeated Nodes
const std::vector<std::string> repeated_nodes = {
"statements", "literal_new_lines", "key_value_pairs", "ml_lit_str_quoteds",
"ml_templess_lit_str_qs", "inline_literals", "il_lit_str_quoteds", "attributes"
};
for (std::string repeated_node : repeated_nodes) {
emerald_parser[repeated_node.c_str()] = repeated<NodePtr>();
}
// Wrapper Nodes
const std::vector<std::string> wrapper_nodes = {
"statement", "text_content", "ml_lit_str_quoted", "ml_templess_lit_str_q",
"inline_literal", "il_lit_str_quoted", "nested_tag"
};
for (std::string wrapper_node : wrapper_nodes) {
emerald_parser[wrapper_node.c_str()] =
[](const peg::SemanticValues& sv) -> NodePtr {
return sv[0].get<NodePtr>();
};
}
// Literals
const std::vector<std::string> literals = {
"multiline_literal", "inline_lit_str", "inline_literals_node"
};
for (std::string string_rule : literals) {
emerald_parser[string_rule.c_str()] =
[](const peg::SemanticValues& sv) -> NodePtr {
NodePtrs body = sv[0].get<NodePtrs>();
return NodePtr(new NodeList(body, ""));
};
}
// Literal Contents
const std::vector<std::string> literal_contents = {
"ml_lit_content", "il_lit_content", "il_lit_str_content"
};
for (std::string string_rule_content : literal_contents) {
emerald_parser[string_rule_content.c_str()] =
[](const peg::SemanticValues& sv) -> NodePtr {
return NodePtr(new TextLiteralContent(sv.str()));
};
}
const std::vector<std::string> optional_nodes = {
"maybe_text_content", "maybe_nested_tag", "maybe_attr_list"
};
for (std::string rule_name : optional_nodes) {
emerald_parser[rule_name.c_str()] = optional<NodePtr>(NodePtr());
}
// Terminals
const std::vector<std::string> terminals = {
"attr", "tag", "class_name", "id_name", "key_name"
};
for (std::string rule_name : terminals) {
emerald_parser[rule_name.c_str()] =
[](const peg::SemanticValues& sv) -> std::string {
return sv.str();
};
}
emerald_parser.enable_packrat_parsing();
}
Grammar& Grammar::get_instance() {
static Grammar instance;
return instance;
}
peg::parser Grammar::get_parser() {
return emerald_parser;
}
bool Grammar::valid(const std::string &input) {
std::string output;
emerald_parser.parse(input.c_str(), output);
return output.length() == input.length();
}
| 30.332353 | 115 | 0.641617 | sapphire-lang |
ed003a579b727db1c52ef8c442fafcd3068a77b8 | 2,121 | cpp | C++ | Playlist.cpp | Kazmi007/Music-Streaming-Platform | 78cd7d66c36332659e2dd0df5828c6331e177e0c | [
"OLDAP-2.7",
"OLDAP-2.8"
] | null | null | null | Playlist.cpp | Kazmi007/Music-Streaming-Platform | 78cd7d66c36332659e2dd0df5828c6331e177e0c | [
"OLDAP-2.7",
"OLDAP-2.8"
] | null | null | null | Playlist.cpp | Kazmi007/Music-Streaming-Platform | 78cd7d66c36332659e2dd0df5828c6331e177e0c | [
"OLDAP-2.7",
"OLDAP-2.8"
] | null | null | null | #include "Playlist.h"
Playlist::Playlist(const std::string &name) { // Custom consructor.
static int playlistId = 1;
this->name = name;
this->shared = false;
this->playlistId = playlistId;
playlistId += 1;
}
int Playlist::getPlaylistId() const { // Returns playlist ID.
return this->playlistId;
}
const std::string &Playlist::getName() const { // Returns playlist name.
return this->name;
}
bool Playlist::isShared() const { // Returns whether the playlist is shared or not.
return this->shared;
}
LinkedList<Song *> &Playlist::getSongs() { // Returns the list of songs.
return this->songs;
}
void Playlist::setShared(bool shared) { // Sets whether the playlist is shared.
this->shared = shared;
}
void Playlist::addSong(Song *song) { // Adds song to the end of the playlist
this->songs.insertAtTheEnd(song);
}
void Playlist::dropSong(Song *song) { // Removes given song from the playlist.
this->songs.removeNode(song);
}
void Playlist::shuffle(int seed) { // Shuffles the songs in the playlist with a given seed.
this->songs.shuffle(seed);
}
bool Playlist::operator==(const Playlist &rhs) const { // Overloaded equality operator.
return this->playlistId == rhs.playlistId && this->name == rhs.name && this->shared == rhs.shared;
}
bool Playlist::operator!=(const Playlist &rhs) const { // Overloaded inequality operator.
return !(rhs == *this);
}
std::ostream &operator<<(std::ostream &os, const Playlist &playlist) { // Overloaded operator to print playlist to output stream.
os << "playlistId: " << playlist.playlistId << " |";
os << " name: " << playlist.name << " |";
os << " shared: " << (playlist.shared ? "yes" : "no") << " |";
os << " songs: [";
Node<Song *> *firstSongNode = playlist.songs.getFirstNode();
Node<Song *> *songNode = firstSongNode;
if (songNode) {
do {
os << *(songNode->data);
if (songNode->next != firstSongNode) os << ", ";
songNode = songNode->next;
} while (songNode != firstSongNode);
}
os << "]";
return os;
}
| 29.458333 | 130 | 0.631306 | Kazmi007 |
ed01c56783d7c5aea9003ea35ea64f6145225a0e | 1,331 | cpp | C++ | unittests/BuildSystem/TempDir.cpp | dmbryson/swift-llbuild | 91f2c5dbeef135113c6574f5797c9e87ef8c3fe8 | [
"Apache-2.0"
] | 427 | 2018-05-29T14:21:02.000Z | 2022-03-16T03:17:54.000Z | unittests/BuildSystem/TempDir.cpp | dmbryson/swift-llbuild | 91f2c5dbeef135113c6574f5797c9e87ef8c3fe8 | [
"Apache-2.0"
] | 25 | 2018-07-23T08:34:15.000Z | 2021-11-05T07:13:36.000Z | unittests/BuildSystem/TempDir.cpp | dmbryson/swift-llbuild | 91f2c5dbeef135113c6574f5797c9e87ef8c3fe8 | [
"Apache-2.0"
] | 52 | 2018-07-19T19:57:32.000Z | 2022-03-11T16:05:38.000Z | //===- unittests/BuildSystem/TempDir.cpp --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "TempDir.h"
#include "llbuild/Basic/FileSystem.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
llbuild::TmpDir::TmpDir(llvm::StringRef namePrefix) {
llvm::SmallString<256> tempDirPrefix;
llvm::sys::path::system_temp_directory(true, tempDirPrefix);
llvm::sys::path::append(tempDirPrefix, namePrefix);
std::error_code ec = llvm::sys::fs::createUniqueDirectory(
tempDirPrefix.str(), tempDir);
assert(!ec);
(void)ec;
}
llbuild::TmpDir::~TmpDir() {
auto fs = basic::createLocalFileSystem();
bool result = fs->remove(tempDir.c_str());
assert(result);
(void)result;
}
const char *llbuild::TmpDir::c_str() { return tempDir.c_str(); }
std::string llbuild::TmpDir::str() const { return tempDir.str(); }
| 32.463415 | 80 | 0.643877 | dmbryson |
ed01f0bfc602fbadf8c3dfa7f86b8c977d7e3049 | 2,691 | cpp | C++ | src/padamose/BranchInspector.cpp | young-developer/padamose | ad827c67ed10125b6f1af3c9300ca122c5d4fcf2 | [
"BSD-3-Clause"
] | null | null | null | src/padamose/BranchInspector.cpp | young-developer/padamose | ad827c67ed10125b6f1af3c9300ca122c5d4fcf2 | [
"BSD-3-Clause"
] | null | null | null | src/padamose/BranchInspector.cpp | young-developer/padamose | ad827c67ed10125b6f1af3c9300ca122c5d4fcf2 | [
"BSD-3-Clause"
] | 1 | 2021-12-07T13:28:58.000Z | 2021-12-07T13:28:58.000Z | // Copyright (c) 2017-2018, Cryptogogue Inc. All Rights Reserved.
// http://cryptogogue.com
#include <padamose/AbstractVersionedBranch.h>
#include <padamose/BranchInspector.h>
namespace Padamose {
//================================================================//
// BranchInspector
//================================================================//
//----------------------------------------------------------------//
BranchInspector::BranchInspector ( shared_ptr < AbstractVersionedBranch > branch ) :
mBranch ( branch ) {
}
//----------------------------------------------------------------//
BranchInspector::BranchInspector ( const BranchInspector& branchInspector ) :
mBranch ( branchInspector.mBranch ) {
}
//----------------------------------------------------------------//
BranchInspector::~BranchInspector () {
}
//----------------------------------------------------------------//
size_t BranchInspector::countDependencies () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->countDependencies ();
}
//----------------------------------------------------------------//
size_t BranchInspector::getBaseVersion () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->getVersion ();
}
//----------------------------------------------------------------//
size_t BranchInspector::getImmutableTop () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->findImmutableTop ();
}
//----------------------------------------------------------------//
size_t BranchInspector::getTopVersion () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->getTopVersion ();
}
//----------------------------------------------------------------//
bool BranchInspector::hasKey ( size_t version, string key ) const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->hasKey ( version, key );
}
//----------------------------------------------------------------//
bool BranchInspector::isLocked () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->isLocked ();
}
//----------------------------------------------------------------//
bool BranchInspector::isPersistent () const {
shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock ();
assert ( branch );
return branch->isPersistent ();
}
} // namespace Padamose
| 32.035714 | 84 | 0.487923 | young-developer |
ed0269150e8aeec7c323422b4a231fc979611d5b | 15,219 | cpp | C++ | uring/relay.cpp | Mutinifni/urn | 9708606e05e8d4487ae9fd88654ef53dff413c07 | [
"MIT"
] | null | null | null | uring/relay.cpp | Mutinifni/urn | 9708606e05e8d4487ae9fd88654ef53dff413c07 | [
"MIT"
] | null | null | null | uring/relay.cpp | Mutinifni/urn | 9708606e05e8d4487ae9fd88654ef53dff413c07 | [
"MIT"
] | 2 | 2021-08-24T11:04:46.000Z | 2021-08-24T11:07:50.000Z | #include <arpa/inet.h>
#include <array>
#include <condition_variable>
#include <cstring>
#include <liburing.h>
#include <netdb.h>
#include <signal.h>
#include <string>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <uring/relay.hpp>
#include <vector>
#define ENABLE_FIXED_BUFFERS 1
#define ENABLE_FIXED_FILE 1
#define ENABLE_SQPOLL 0
namespace urn_uring {
config::config(int argc, const char* argv[])
: threads{static_cast<uint16_t>(std::thread::hardware_concurrency())} {
for (int i = 1; i < argc; i++) {
std::string_view arg(argv[i]);
if (arg == "--threads") {
threads = atoi(argv[++i]);
} else if (arg == "--client.port") {
client.port = argv[++i];
} else if (arg == "--peer.port") {
peer.port = argv[++i];
} else {
printf("unused flag: %s\n", argv[i]);
}
}
if (!threads) {
threads = 1;
}
std::cout << "threads = " << threads << "\nclient.port = " << client.port
<< "\npeer.port = " << peer.port << '\n';
}
namespace {
void ensure_success(int code) {
if (code >= 0) {
return;
}
fprintf(stderr, "%s\n", strerror(-code));
abort();
}
struct listen_context;
constexpr int32_t num_events = 16; // per thread
constexpr int32_t memory_per_packet = 1024;
volatile sig_atomic_t has_sigint = 0;
thread_local listen_context* local_io = nullptr;
enum ring_event_type {
ring_event_type_invalid = 0,
ring_event_type_client_rx = 1,
ring_event_type_peer_rx = 2,
ring_event_type_peer_tx = 3,
ring_event_type_timer = 4,
ring_event_MAX
};
struct ring_event {
ring_event_type type;
int32_t index;
union {
struct {
struct iovec iov;
struct sockaddr_in address;
struct msghdr message;
} rx;
__kernel_timespec timeout;
};
};
constexpr int64_t k_statistics_timeout_ms = 5000;
struct countdown_latch {
countdown_latch(int64_t count) : count{count} {}
void wait() {
std::unique_lock<std::mutex> lock(mtx);
int64_t gen = generation;
if (--count == 0) {
++generation;
cond.notify_all();
return;
}
cond.wait(lock, [&]() { return gen != generation; });
}
int64_t count;
int64_t generation = 0;
std::mutex mtx = {};
std::condition_variable cond = {};
};
struct worker_args {
urn_uring::relay* relay = nullptr;
struct addrinfo* local_client_address = nullptr;
struct addrinfo* local_peer_address = nullptr;
int32_t thread_index = 0;
countdown_latch* startup_latch = nullptr;
};
struct listen_context {
// Either FD or ID depending on the usage of registered fds
int peer_socket = -1;
int client_socket = -1;
struct io_uring ring = {};
urn_uring::relay* relay = nullptr;
uint8_t* messages_buffer = nullptr;
std::array<ring_event, num_events> io_events = {};
std::vector<int32_t> free_event_ids = {};
int peer_socket_fd = -1;
int client_socket_fd = -1;
int sockets[2] = {};
worker_args worker_info = {};
struct iovec buffers_mem = {};
};
void print_address(const struct addrinfo* address) {
char readable_ip[INET6_ADDRSTRLEN] = {0};
if (address->ai_family == AF_INET) {
struct sockaddr_in* ipv4 = (struct sockaddr_in*) address->ai_addr;
inet_ntop(ipv4->sin_family, &ipv4->sin_addr, readable_ip, sizeof(readable_ip));
printf("%s:%d\n", readable_ip, ntohs(ipv4->sin_port));
} else if (address->ai_family == AF_INET6) {
struct sockaddr_in6* ipv6 = (struct sockaddr_in6*) address->ai_addr;
inet_ntop(ipv6->sin6_family, &ipv6->sin6_addr, readable_ip, sizeof(readable_ip));
printf("[%s]:%d\n", readable_ip, ntohs(ipv6->sin6_port));
}
}
int create_udp_socket(struct addrinfo* address_list) {
// quickhack: only use the first address
struct addrinfo* address = address_list;
int socket_fd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
ensure_success(socket_fd);
{
int size = 4129920;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)));
}
{
int size = 4129920;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)));
}
{
int enable = 1;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)));
}
{
int enable = 1;
ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)));
}
return socket_fd;
}
void bind_socket(int fd, struct addrinfo* address) {
int bind_status = bind(fd, address->ai_addr, address->ai_addrlen);
if (bind_status == 0) {
return;
}
printf("error binding socket: %s\n", strerror(bind_status));
abort();
}
ring_event* alloc_event(listen_context* context, ring_event_type type) {
if (context->free_event_ids.size() == 0) {
printf("[thread %d] out of free events\n", context->worker_info.thread_index);
abort();
return nullptr;
}
int32_t free_id = context->free_event_ids.back();
context->free_event_ids.pop_back();
ring_event* event = &context->io_events[free_id];
event->type = type;
event->index = free_id;
event->rx.iov.iov_base = &context->messages_buffer[free_id * memory_per_packet];
event->rx.iov.iov_len = memory_per_packet;
event->rx.message.msg_name = &event->rx.address;
event->rx.message.msg_namelen = sizeof(event->rx.address);
event->rx.message.msg_iov = &event->rx.iov;
event->rx.message.msg_iovlen = 1;
return event;
}
void release_event(listen_context* context, ring_event* ev) {
context->free_event_ids.push_back(ev->index);
}
void report_features(const struct io_uring_params* params) {
uint32_t features = params->features;
auto get_name = [](uint32_t feature) {
switch (feature) {
case IORING_FEAT_SINGLE_MMAP:
return "IORING_FEAT_SINGLE_MMAP";
case IORING_FEAT_NODROP:
return "IORING_FEAT_NODROP";
case IORING_FEAT_SUBMIT_STABLE:
return "IORING_FEAT_SUBMIT_STABLE";
case IORING_FEAT_CUR_PERSONALITY:
return "IORING_FEAT_CUR_PERSONALITY";
case IORING_FEAT_FAST_POLL:
return "IORING_FEAT_FAST_POLL";
case IORING_FEAT_POLL_32BITS:
return "IORING_FEAT_POLL_32BITS";
case IORING_FEAT_SQPOLL_NONFIXED:
return "IORING_FEAT_SQPOLL_NONFIXED";
default:
return "unknown";
}
};
const uint32_t known_features[] = {IORING_FEAT_SINGLE_MMAP, IORING_FEAT_NODROP,
IORING_FEAT_SUBMIT_STABLE, IORING_FEAT_CUR_PERSONALITY,
IORING_FEAT_FAST_POLL, IORING_FEAT_POLL_32BITS,
IORING_FEAT_SQPOLL_NONFIXED};
printf("supported features:\n");
for (uint32_t feature : known_features) {
if (features & feature) {
printf("\t%s\n", get_name(feature));
}
}
}
bool is_main_worker(const listen_context* io) { return io->worker_info.thread_index == 0; }
void listen_context_initialize(listen_context* io, worker_args args) {
io->worker_info = args;
io->relay = args.relay;
struct io_uring_params params;
memset(¶ms, 0, sizeof(params));
if (ENABLE_SQPOLL) {
params.flags |= IORING_SETUP_SQPOLL;
params.sq_thread_idle = 1000;
printf("[thread %d] using SQPOLL\n", args.thread_index);
}
ensure_success(io_uring_queue_init_params(4096, &io->ring, ¶ms));
if (is_main_worker(io)) {
report_features(¶ms);
}
io->client_socket_fd = create_udp_socket(args.local_client_address);
io->peer_socket_fd = create_udp_socket(args.local_peer_address);
printf("[thread %d] sockets: %d %d\n", args.thread_index, io->client_socket_fd,
io->peer_socket_fd);
if (ENABLE_FIXED_FILE) {
io->sockets[0] = io->peer_socket_fd;
io->sockets[1] = io->client_socket_fd;
ensure_success(io_uring_register_files(&io->ring, io->sockets, 2));
io->peer_socket = 0;
io->client_socket = 1;
printf("[thread %d] using fixed files\n", args.thread_index);
} else {
io->client_socket = io->client_socket_fd;
io->peer_socket = io->peer_socket_fd;
}
io->messages_buffer = (uint8_t*) calloc(num_events, memory_per_packet);
io->free_event_ids.reserve(num_events);
for (int32_t i = 0; i < num_events; i++) {
io->free_event_ids.push_back(i);
}
if (ENABLE_FIXED_BUFFERS) {
io->buffers_mem.iov_base = io->messages_buffer;
io->buffers_mem.iov_len = num_events * memory_per_packet;
ensure_success(io_uring_register_buffers(&io->ring, &io->buffers_mem, 1));
printf("[thread %d] using fixed buffers\n", args.thread_index);
}
}
struct addrinfo* bindable_address(const char* port) {
struct addrinfo hints;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
struct addrinfo* addr = nullptr;
ensure_success(getaddrinfo(nullptr, port, &hints, &addr));
return addr;
}
__kernel_timespec create_timeout(int64_t milliseconds) {
__kernel_timespec spec;
spec.tv_sec = milliseconds / 1000;
spec.tv_nsec = (milliseconds % 1000) * 1000000;
return spec;
}
#if ENABLE_FIXED_FILE
void enable_fixed_file(struct io_uring_sqe* sqe) { sqe->flags |= IOSQE_FIXED_FILE; }
#else
void enable_fixed_file(struct io_uring_sqe*) {}
#endif
#if ENABLE_FIXED_BUFFERS
void enable_fixed_buffers(struct io_uring_sqe* sqe) {
// One huge slab is registered and then partitioned manually
sqe->buf_index = 0;
}
#else
void enable_fixed_buffers(struct io_uring_sqe*) {}
#endif
void add_recvmsg(struct io_uring* ring, ring_event* ev, int32_t socket_id) {
struct io_uring_sqe* sqe = io_uring_get_sqe(ring);
if (!sqe)
abort();
io_uring_prep_recvmsg(sqe, socket_id, &ev->rx.message, 0);
io_uring_sqe_set_data(sqe, ev);
enable_fixed_file(sqe);
enable_fixed_buffers(sqe);
}
void add_sendmsg(struct io_uring* ring, ring_event* ev, int32_t socket_id) {
struct io_uring_sqe* sqe = io_uring_get_sqe(ring);
if (!sqe)
abort();
io_uring_prep_sendmsg(sqe, socket_id, &ev->rx.message, 0);
io_uring_sqe_set_data(sqe, ev);
enable_fixed_file(sqe);
enable_fixed_buffers(sqe);
}
void add_timeout(struct io_uring* ring, ring_event* ev, int64_t milliseconds) {
ev->timeout = create_timeout(milliseconds);
struct io_uring_sqe* sqe = io_uring_get_sqe(ring);
if (!sqe)
abort();
io_uring_prep_timeout(sqe, &ev->timeout, 0, 0);
io_uring_sqe_set_data(sqe, ev);
}
void worker(worker_args args) {
auto iop = std::make_unique<listen_context>();
listen_context* io = iop.get();
local_io = io;
listen_context_initialize(io, args);
struct io_uring* ring = &io->ring;
args.startup_latch->wait();
bind_socket(io->client_socket_fd, args.local_client_address);
bind_socket(io->peer_socket_fd, args.local_peer_address);
io->relay->on_thread_start(args.thread_index);
{
ring_event* ev = alloc_event(io, ring_event_type_client_rx);
add_recvmsg(ring, ev, io->client_socket);
}
{
ring_event* ev = alloc_event(io, ring_event_type_peer_rx);
add_recvmsg(ring, ev, io->peer_socket);
}
if (is_main_worker(io)) {
ring_event* ev = alloc_event(io, ring_event_type_timer);
add_timeout(ring, ev, k_statistics_timeout_ms);
}
for (;;) {
io_uring_submit_and_wait(ring, 1);
struct io_uring_cqe* cqe;
uint32_t head;
uint32_t count = 0;
io_uring_for_each_cqe(ring, head, cqe) {
++count;
ring_event* event = (ring_event*) cqe->user_data;
switch (event->type) {
case ring_event_type_peer_rx: {
if (cqe->res < 0) {
printf("thread [%d] peer rx %s\n", args.thread_index, strerror(-cqe->res));
abort();
}
const msghdr* message = &event->rx.message;
uring::packet packet{(const std::byte*) message->msg_iov->iov_base, (uint32_t) cqe->res};
io->relay->on_peer_received(uring::endpoint(event->rx.address, io), packet);
release_event(io, event);
ring_event* rx_event = alloc_event(io, ring_event_type_peer_rx);
add_recvmsg(ring, rx_event, io->peer_socket);
break;
}
case ring_event_type_peer_tx: {
uring::packet packet{(const std::byte*) event->rx.message.msg_iov->iov_base,
(uint32_t) cqe->res};
io->relay->on_session_sent(packet);
release_event(io, event);
break;
}
case ring_event_type_client_rx: {
if (cqe->res < 0) {
printf("thread [%d] client rx: %s\n", args.thread_index, strerror(-cqe->res));
abort();
}
const msghdr* message = &event->rx.message;
io->relay->on_client_received(
uring::endpoint(event->rx.address, io),
uring::packet((const std::byte*) message->msg_iov->iov_base, cqe->res));
release_event(io, event);
ring_event* rx_event = alloc_event(io, ring_event_type_client_rx);
add_recvmsg(ring, rx_event, io->client_socket);
break;
}
case ring_event_type_timer: {
io->relay->on_statistics_tick();
add_timeout(ring, event, k_statistics_timeout_ms); // reuse
break;
}
default: {
printf("unhandled ev\n");
release_event(io, event);
break;
}
}
}
io_uring_cq_advance(ring, count);
if (has_sigint) {
break;
}
}
printf("%d worker exiting \n", io->worker_info.thread_index);
io_uring_queue_exit(ring);
}
void handle_sigint(int) { has_sigint = 1; }
} // namespace
relay::relay(const urn_uring::config& conf) noexcept
: config_{conf}, logic_{config_.threads, client_, peer_} {}
int relay::run() noexcept {
if (ENABLE_SQPOLL) {
if (geteuid() != 0) {
printf("SQPOLL needs sudo\n");
return 1;
}
}
signal(SIGINT, handle_sigint);
int32_t thread_count = std::max(uint16_t(1), config_.threads);
struct addrinfo* local_client_address = bindable_address("3478");
struct addrinfo* local_peer_address = bindable_address("3479");
print_address(local_client_address);
print_address(local_peer_address);
countdown_latch latch(thread_count);
auto make_worker_args = [=, &latch](int32_t thread_index) {
worker_args args;
args.relay = this;
args.local_client_address = local_client_address;
args.local_peer_address = local_peer_address;
args.thread_index = thread_index;
args.startup_latch = &latch;
return args;
};
std::vector<std::thread> worker_threads;
for (int32_t i = 1; i < thread_count; i++) {
worker_threads.emplace_back(worker, make_worker_args(i));
}
worker_args main_thread_args = make_worker_args(0);
worker(main_thread_args);
printf("joining\n");
for (auto& t : worker_threads) {
t.join();
}
printf("joined\n");
return 0;
}
void uring::session::start_send(const uring::packet& packet) noexcept {
listen_context* io = local_io;
ring_event* tx_event = alloc_event(io, ring_event_type_peer_tx);
tx_event->rx.address = client_endpoint.address;
memcpy(tx_event->rx.iov.iov_base, packet.data(), packet.size());
tx_event->rx.iov.iov_len = packet.size();
add_sendmsg(&io->ring, tx_event, io->client_socket);
}
} // namespace urn_uring
| 27.873626 | 99 | 0.67304 | Mutinifni |
ed0277bd2f37f0c7598d51e56627b22f5b7d4890 | 194 | hpp | C++ | include/sql/fusion/common.hpp | cviebig/lib-sql | fed42f80b5866503c5f5710d791feec213c051a1 | [
"MIT"
] | 4 | 2017-09-25T00:03:31.000Z | 2020-04-02T07:06:24.000Z | include/sql/fusion/common.hpp | cviebig/lib-sql | fed42f80b5866503c5f5710d791feec213c051a1 | [
"MIT"
] | 1 | 2018-05-16T20:00:42.000Z | 2018-05-30T13:21:20.000Z | include/sql/fusion/common.hpp | cviebig/lib-sql | fed42f80b5866503c5f5710d791feec213c051a1 | [
"MIT"
] | 1 | 2022-01-05T20:49:47.000Z | 2022-01-05T20:49:47.000Z | #ifndef SQL_PARSER_FUSION_COMMON_HPP
#define SQL_PARSER_FUSION_COMMON_HPP
#include "sql/ast/common.hpp"
#include <boost/fusion/include/adapt_struct.hpp>
#endif //SQL_PARSER_FUSION_COMMON_HPP
| 21.555556 | 48 | 0.840206 | cviebig |
ed05c033f63aea0e80feac1d7795b93ee266cbb5 | 15,059 | cpp | C++ | source/Image/JPEGLoader.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | source/Image/JPEGLoader.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | source/Image/JPEGLoader.cpp | badbrainz/pme | 1c8e6f3d154cc59613f5ef3f2f8293f488c64b28 | [
"WTFPL"
] | null | null | null | #include "image.h"
#include <stdio.h>
#ifndef max
#define max(a, b) (((a)>(b))?(a):(b))
#endif
#ifndef min
#define min(a, b) (((a)<(b))?(a):(b))
#endif
unsigned char getByte();
char fileOpen(const char *);
void decodeQTable(int);
void strmSkip(int n);
void decodeBlock();
void fileClose();
void getInfo();
void fidct();
int wordDec(int);
typedef unsigned short qTable[64];
typedef struct
{
struct tables
{
unsigned char size;
unsigned char code;
} small[512], large[65536];
} HuffTable;
void decodeHuffTable(int);
typedef struct
{
HuffTable *huffAC, *huffDC;
qTable *qTab;
int dcPrev,smpx, smpy;
float t[256];
}ComponentTable;
ComponentTable component[4];
HuffTable huffTableAC[4],
huffTableDC[4];
qTable qtable[4];
int xblock, yblock, blockx, blocky,
bsize, restartInt, bfree;
unsigned int dt;
unsigned char *data, *bpos , *dend,
eof , ssStart, ssEnd,
sbits, prec , ncomp;
float dctt[64];
int zigzag[64]=
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
};
char fileOpen(const char *filename)
{
FILE *stream;
data = NULL;
if ((stream=fopen(filename, "rb"))==NULL)
return 0;
else
{
fseek(stream, 0, SEEK_END);
bsize = ftell(stream);
fseek(stream, 0, SEEK_SET);
data = new unsigned char[bsize];
fread(data, 1, bsize, stream);
fclose(stream);
return 1;
}
}
void fileClose(void)
{
if (data)
delete[] data;
}
unsigned char getByte(void)
{
if (bpos>=dend)
{
eof = 1;
return 0;
}
else
return *bpos++;
}
void strmSkip(int n)
{
unsigned char a, b;
bfree+=n;
dt<<=n;
while (bfree>=8)
{
bfree-=8;
b = getByte();
if (b==255)
a=getByte();
dt|=(b<<bfree);
}
}
int huffDec(HuffTable *h)
{
unsigned int id, n, c;
id = (dt>>(23));
n = h->small[id].size;
c = h->small[id].code;
if (n==255)
{
id = (dt>>(16));
n = h->large[id].size;
c = h->large[id].code;
}
strmSkip(n);
return c;
}
int wordDec(int n)
{
int w;
unsigned int s;
if (n==0)
return 0;
else
{
s= (dt>>(31));
w= (dt>>(32-n));
strmSkip(n);
if (s==0)
w = (w|(0xffffffff<<n))+1;
}
return w;
}
void Image::getJPGInfo()
{
unsigned char cn, sf, qt;
int i;
prec = getByte();
if (prec!=8)
return;
height = ((getByte()<<8)+getByte());
width = ((getByte()<<8)+getByte());
ncomp = getByte();
if ((ncomp!=3)&&(ncomp!=1))
return;
for (i=0;i<ncomp;i++)
{
cn = getByte();
sf = getByte();
qt = getByte();
component[cn-1].qTab = &qtable[qt];
component[cn-1].smpy = sf&15;
component[cn-1].smpx = (sf>>4)&15;
}
if (component[0].smpx == 1)
blockx = 8;
else
blockx = 16;
if (component[0].smpy==1)
blocky = 8;
else
blocky = 16;
xblock=width/blockx;
if ((width & (blockx-1))!=0)
xblock++;
yblock = height/blocky;
if ((height&(blocky-1))!=0)
yblock++;
}
void decodeHuffTable(int len)
{
int length[257], i, j, n, code, codelen, delta, rcode, cd, rng;
unsigned char lengths[16], b, symbol[257];
HuffTable *h;
len-=2;
while (len>0)
{
b = getByte();
len--;
h = &huffTableDC[0];
switch (b)
{
case 0:
h = &huffTableDC[0];
break;
case 1:
h = &huffTableDC[1];
break;
case 16:
h = &huffTableAC[0];
break;
case 17:
h=&huffTableAC[1];
break;
}
for (i=0;i<16;i++)
lengths[i] = getByte();
len -= 16;
n = 0;
for (i=0;i<16;i++)
{
len-=lengths[i];
for (j=0;j<lengths[i];j++)
{
symbol[n] = getByte();
length[n++] = i+1;
}
}
code = 0;
codelen = length[0];
for (i=0;i<n;i++)
{
rcode = code<<(16-codelen);
cd = rcode>>7;
if (codelen<=9)
{
rng = 1 <<(9-codelen);
for (j=cd;j<cd+rng;j++)
{
h->small[j].code = (unsigned char)symbol[i];
h->small[j].size = (unsigned char)codelen;
}
}
else
{
h->small[cd].size=(unsigned char)255;
rng = 1<<(16-codelen);
for (j=rcode;j<rcode+rng;j++)
{
h->large[j].code=(unsigned char)symbol[i];
h->large[j].size=(unsigned char)codelen;
}
}
code++;
delta=length[i+1]-codelen;
code<<=delta;
codelen+=delta;
}
}
}
void fidct(void)
{
float a = 0.353553385f,
b = 0.490392625f,
c = 0.415734798f,
d = 0.277785122f,
e = 0.097545162f,
f = 0.461939752f,
g = 0.191341713f,
cd =0.6935199499f,
be =0.5879377723f,
bc =0.9061274529f,
de =0.3753302693f,
a0, f2, g2, a4, f6, g6, s0, s1, s2, s3,
t0, t1, t2, t3, m0, m1, m2, m3,
h0, h1, h2, h3, r0, r1, r2, r3, w;
int i;
for (i=0;i<64;i+=8)
{
if ((dctt[i+1]!=0)||(dctt[i+2]!=0)||(dctt[i+3]!=0)||(dctt[i+4]!=0)||(dctt[i+5]!=0)||(dctt[i+6]!=0)||(dctt[i+7]!=0))
{
a0 = a*dctt[i];
f2 = f*dctt[i+2];
g2 = g*dctt[i+2];
a4 = a*dctt[i+4];
g6 = g*dctt[i+6];
f6 = f*dctt[i+6];
m0 = a0+a4;
m1 = a0-a4;
m2 = f2+g6;
m3 = g2-f6;
s0 = m0+m2;
s1 = m1+m3;
s2 = m1-m3;
s3 = m0-m2;
h2 = dctt[i+7]+dctt[i+1];
h3 = dctt[i+7]-dctt[i+1];
r2 = dctt[i+3]+dctt[i+5];
r3 = dctt[i+3]-dctt[i+5];
h0 = cd*dctt[i+1];
h1 = be*dctt[i+1];
r0 = be*dctt[i+5];
r1 = cd*dctt[i+3];
w = de*r3;
t0 = h1+r1+e*(h3+r3)-w;
t1 = h0-r0-d*(h2-r3)-w;
w = bc*r2;
t2 = h0+r0+c*(h3+r2)-w;
t3 = h1-r1-b*(h2+r2)+w;
dctt[i] = s0+t0;
dctt[i+1] = s1+t1;
dctt[i+2] = s2+t2;
dctt[i+3] = s3+t3;
dctt[i+4] = s3-t3;
dctt[i+5] = s2-t2;
dctt[i+6] = s1-t1;
dctt[i+7] = s0-t0;
}
else
{
a0 = dctt[i]*a;
dctt[i]=dctt[i+1]=dctt[i+2]=dctt[i+3]=dctt[i+4]=dctt[i+5]=dctt[i+6]=dctt[i+7]=a0;
}
}
for (i=0;i<8;i++)
{
if ((dctt[8+i]!=0)||(dctt[16+i]!=0)||(dctt[24+i]!=0)||(dctt[32+i]!=0)||(dctt[40+i]!=0)||(dctt[48+i]!=0)||(dctt[56+i]!=0))
{
a0 = a*dctt[i];
f2 = f*dctt[16+i];
g2 = g*dctt[16+i];
a4 = a*dctt[32+i];
g6 = g*dctt[48+i];
f6 = f*dctt[48+i];
m0 = a0+a4;
m1 = a0-a4;
m2 = f2+g6;
m3 = g2-f6;
s0 = m0+m2;
s1 = m1+m3;
s2 = m1-m3;
s3 = m0-m2;
h2 = dctt[56+i]+dctt[8+i];
h3 = dctt[56+i]-dctt[8+i];
r2 = dctt[24+i]+dctt[40+i];
r3 = dctt[24+i]-dctt[40+i];
h0 = cd*dctt[8+i];
h1 = be*dctt[8+i];
r0 = be*dctt[40+i];
r1 = cd*dctt[24+i];
w = de*r3;
t0 = h1+r1+e*(h3+r3)-w;
t1 = h0-r0-d*(h2-r3)-w;
w = bc*r2;
t2 = h0+r0+c*(h3+r2)-w;
t3 = h1-r1-b*(h2+r2)+w;
dctt[i] = s0+t0;
dctt[i+8] = s1+t1;
dctt[i+16] = s2+t2;
dctt[i+24] = s3+t3;
dctt[i+32] = s3-t3;
dctt[i+40] = s2-t2;
dctt[i+48] = s1-t1;
dctt[i+56] = s0-t0;
}
else
{
a0 = dctt[i]*a;
dctt[i]=dctt[i+8]=dctt[i+16]=dctt[i+24]=dctt[i+32]=dctt[i+40]=dctt[i+48]=dctt[i+56]=a0;
}
}
}
void decodeQTable(int len)
{
int i;
unsigned char b;
len-=2;
while (len>0)
{
b = (unsigned char)getByte();
len--;
if ((b&16)==0)
{
for (i=0;i<64;i++)
qtable[b&15][i]=getByte();
len-=64;
}
else
{
for (i=0;i<64;i++)
qtable[b&15][i]=((getByte()<<8)+getByte());
len-=128;
}
}
}
void decodeBlock(void)
{
int compn, i, j, b, p, codelen, code, cx, cy, otab[64];
qTable *qtab;
for (compn=0;compn<ncomp;compn++)
{
qtab = component[compn].qTab;
for (cy=0;cy<component[compn].smpy;cy++)
{
for (cx=0;cx<component[compn].smpx;cx++)
{
for (i=0;i<64;i++)
otab[i]=0;
codelen= huffDec(component[compn].huffDC);
code=wordDec(codelen);
otab[0] = code+component[compn].dcPrev;
component[compn].dcPrev = otab[0];
i=1;
while (i<64)
{
codelen=huffDec(component[compn].huffAC);
if (codelen==0)
i=64;
else
if (codelen==0xf0)
i+=16;
else
{
code = wordDec(codelen&15);
i = i+(codelen>>4);
otab[i++]=code;
}
}
for (i=0;i<64;i++)
dctt[zigzag[i]]=(float)((*qtab)[i]*otab[i]);
fidct();
b=(cy<<7)+(cx<<3);
p=0;
for (i=0;i<8;i++)
{
for (j=0;j<8;j++)
component[compn].t[b++]=dctt[p++]+128;
b+=8;
}
}
}
}
}
int Image::decodeScanJPG()
{
int nnx, nny, i, j;
int xmin, ymin, xmax, ymax, blockn, adr1, adr2;
int y1, u1, v1, y2, u2, v2, u3, v3;
int dux, duy, dvx, dvy;
unsigned char sc, ts;
float cy, cu, cv;
components = int(getByte());
setFormat(GL_BGR);
setInternalFormat(GL_RGB8);
if (dataBuffer)
deleteArray(dataBuffer);
dataBuffer = new GLubyte[width*height*components];
for (i=0;i<components;i++)
{
sc = getByte();
ts = getByte();
component[sc-1].huffDC = &huffTableDC[ts>>4];
component[sc-1].huffAC = &huffTableAC[ts&15];
}
ssStart = getByte();
ssEnd = getByte();
sbits = getByte();
if ((ssStart!=0)||(ssEnd!=63))
return 0;
if (components == 3)
{
dux = 2+component[1].smpx-component[0].smpx;
duy = 2+component[1].smpy-component[0].smpy;
dvx = 2+component[2].smpx-component[0].smpx;
dvy = 2+component[2].smpy-component[0].smpy;
}
dt = 0;
bfree = 0;
strmSkip(32);
blockn=0;
ymin=0;
for (nny=0;nny<yblock;nny++)
{
ymax = ymin+blocky;
if (ymax>height)
ymax = height;
xmin=0;
for (nnx=0;nnx<xblock;nnx++)
{
xmax=xmin+blockx;
if (xmax>width)
xmax=width;
decodeBlock();
blockn++;
if ((blockn==restartInt)&&((nnx<xblock-1)||(nny<yblock-1)))
{
blockn=0;
if (bfree!=0)
strmSkip(8-bfree);
if (wordDec(8)!=255)
return 0;
for (i=0;i<components;i++)
component[i].dcPrev=0;
}
if (components ==3)
{
y1=u1=v1=0;
adr1=(height-1-ymin)*width+xmin;
for (i=ymin;i<ymax;i++)
{
adr2=adr1;
adr1-=width;
y2=y1;
y1+=16;
u3=(u1>>1)<<4;
u1+=duy;
v3=(v1>>1)<<4;
v1+=dvy;
u2=v2=0;
for (j=xmin;j<xmax;j++)
{
int cr, cg, cb;
cy=component[0].t[y2++];
cu=component[1].t[u3+(u2>>1)]-128.0f;
cv=component[2].t[v3+(v2>>1)]-128.0f;
cr=(int)(cy+1.402f*cv);
cg=(int)(cy-0.34414f*cu-0.71414f*cv);
cb=(int)(cy+1.772f*cu);
dataBuffer[3*adr2] = max(0, min(255, cb));
dataBuffer[3*adr2+1] = max(0, min(255, cg));
dataBuffer[3*adr2+2] = max(0, min(255, cr));
adr2++;
u2+=dux;
v2+=dvx;
}
}
}
else
if (components==1)
{
y1=0;
adr1=(height-1-ymin)*width+xmin;
for (i=ymin;i<ymax;i++)
{
adr2=adr1;
adr1-=width;
y2=y1;
y1+=16;
for (j=xmin;j<xmax;j++)
{
int lum=(int)component[0].t[y2++];
dataBuffer[adr2++]=max(0, min(255, lum));
}
}
}
xmin=xmax;
}
ymin=ymax;
}
return 1;
}
int Image::decodeJPG()
{
int w;
unsigned char a, hdr=0, scan=0;
eof=0;
bpos=data;
dend=bpos+bsize;
w=((getByte()<<8)+getByte());
if (w!=0xffd8)
return 0;
while (eof==0)
{
a=(unsigned char)getByte();
if (a!=0xff)
return 0;
a=(unsigned char)getByte();
w=((getByte()<<8)+getByte());
switch (a)
{
case 0xe0:
if (hdr!=0)
break;
if (getByte()!='J')
return 0;
if (getByte()!='F')
return 0;
if (getByte()!='I')
return 0;
if (getByte()!='F')
return 0;
hdr=1;
w-=4;
break;
case 0xc0:
getJPGInfo();
w=0;
break;
case 0xc4:
decodeHuffTable(w);
w=0;
break;
case 0xd9:
w=0;
break;
case 0xda:
if (scan!=0)
break;
scan=1;
if (!decodeScanJPG())
return 0;
w=0;
eof=1;
break;
case 0xdb:
decodeQTable(w);
w=0;
break;
case 0xdd:
restartInt=((getByte()<<8)+getByte());
w=0;
break;
}
while (w>2)
{
getByte();
w--;
}
}
return 1;
}
bool Image::loadJPG(const char *filename)
{
int i;
for (i=0;i<4;i++)
component[i].dcPrev=0;
restartInt=-1;
if (fileOpen(filename))
{
int ret= decodeJPG();
fileClose();
if (!ret)
return false;
return true;
}
else
return false;
}
| 19.972149 | 126 | 0.413042 | badbrainz |
ed0abd8c3d8ed4a09cd6b81ccbeb73e70dbf8c62 | 1,160 | hpp | C++ | bt/ActiveSelector.hpp | river34/game-bt | a0464ae782ebcddd638633016cd65c5b5db14cc3 | [
"MIT"
] | 1 | 2018-11-08T09:56:11.000Z | 2018-11-08T09:56:11.000Z | bt/ActiveSelector.hpp | river34/game-bt | a0464ae782ebcddd638633016cd65c5b5db14cc3 | [
"MIT"
] | null | null | null | bt/ActiveSelector.hpp | river34/game-bt | a0464ae782ebcddd638633016cd65c5b5db14cc3 | [
"MIT"
] | null | null | null | //
// ActiveSelector.hpp
// GameBT
//
// Created by River Liu on 15/1/2018.
// Copyright © 2018 River Liu. All rights reserved.
//
// ActiveSelector is a Selector that actively rechecks
// its children.
#ifndef ActiveSelector_hpp
#define ActiveSelector_hpp
#include "Selector.hpp"
namespace BT
{
class ActiveSelector : public Selector
{
public:
ActiveSelector() : Selector("ActiveSelector") { }
ActiveSelector(const std::string& _name) : Selector(_name) { }
virtual ~ActiveSelector() { }
inline virtual void onInitialize(Blackboard* _blackboard) override { m_CurrentChild = m_Children.end(); }
virtual Status onUpdate(Blackboard* _blackboard) override
{
auto prev = m_CurrentChild;
Selector::onInitialize(_blackboard);
Status status = Selector::onUpdate(_blackboard);
if (prev != m_Children.end() && prev != m_CurrentChild)
{
(*prev)->abort();
}
return status;
}
inline static Behavior* create(const BehaviorParams& _params) { return new ActiveSelector; }
};
}
#endif /* ActiveSelector_hpp */
| 28.292683 | 113 | 0.642241 | river34 |
ed0bdf697701d499334845ca3e4e059392307d34 | 3,729 | hpp | C++ | ngraph/core/include/openvino/op/util/convert_color_nv12_base.hpp | alexander-shchepetov/openvino | a9dae1e3f2ba8b3fec227c51f4c1948667309efc | [
"Apache-2.0"
] | 1 | 2021-07-14T07:20:24.000Z | 2021-07-14T07:20:24.000Z | ngraph/core/include/openvino/op/util/convert_color_nv12_base.hpp | alexander-shchepetov/openvino | a9dae1e3f2ba8b3fec227c51f4c1948667309efc | [
"Apache-2.0"
] | 34 | 2020-11-19T12:27:40.000Z | 2022-02-21T13:14:04.000Z | ngraph/core/include/openvino/op/util/convert_color_nv12_base.hpp | mznamens/openvino | ec126c6252aa39a6c63ddf124350a92687396771 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "openvino/op/op.hpp"
#include "openvino/op/util/attr_types.hpp"
namespace ov {
namespace op {
namespace util {
/// \brief Base class for color conversion operation from NV12 to RGB/BGR format.
/// Input:
/// - Operation expects input shape in NHWC layout.
/// - Input NV12 image can be represented in a two ways:
/// a) Single plane: NV12 height dimension is 1.5x bigger than image height. 'C' dimension shall be 1
/// b) Two separate planes: Y and UV. In this case
/// b1) Y plane has height same as image height. 'C' dimension equals to 1
/// b2) UV plane has dimensions: 'H' = image_h / 2; 'W' = image_w / 2; 'C' = 2.
/// - Supported element types: u8 or any supported floating-point type.
/// Output:
/// - Output node will have NHWC layout and shape HxW same as image spatial dimensions.
/// - Number of output channels 'C' will be 3
///
/// \details Conversion of each pixel from NV12 (YUV) to RGB space is represented by following formulas:
/// R = 1.164 * (Y - 16) + 1.596 * (V - 128)
/// G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128)
/// B = 1.164 * (Y - 16) + 2.018 * (U - 128)
/// Then R, G, B values are clipped to range (0, 255)
///
class OPENVINO_API ConvertColorNV12Base : public Op {
public:
/// \brief Exact conversion format details
/// Currently supports conversion from NV12 to RGB or BGR, in future can be extended with NV21_to_RGBA/BGRA, etc
enum class ColorConversion : int { NV12_TO_RGB = 0, NV12_TO_BGR = 1 };
protected:
ConvertColorNV12Base() = default;
/// \brief Constructs a conversion operation from input image in NV12 format
/// As per NV12 format definition, node height dimension shall be 1.5 times bigger than image height
/// so that image (w=640, h=480) is represented by NHWC shape {N,720,640,1} (height*1.5 x width)
///
/// \param arg Node that produces the input tensor. Input tensor represents image in NV12 format (YUV).
/// \param format Conversion format.
explicit ConvertColorNV12Base(const Output<Node>& arg, ColorConversion format);
/// \brief Constructs a conversion operation from 2-plane input image in NV12 format
/// In general case Y channel of image can be separated from UV channel which means that operation needs two nodes
/// for Y and UV planes respectively. Y plane has one channel, and UV has 2 channels, both expect 'NHWC' layout
///
/// \param arg_y Node that produces the input tensor for Y plane (NHWC layout). Shall have WxH dimensions
/// equal to image dimensions. 'C' dimension equals to 1.
///
/// \param arg_uv Node that produces the input tensor for UV plane (NHWC layout). 'H' is half of image height,
/// 'W' is half of image width, 'C' dimension equals to 2. Channel 0 represents 'U', channel 1 represents 'V'
/// channel
///
/// \param format Conversion format.
ConvertColorNV12Base(const Output<Node>& arg_y, const Output<Node>& arg_uv, ColorConversion format);
public:
OPENVINO_OP("ConvertColorNV12Base", "util");
void validate_and_infer_types() override;
bool visit_attributes(AttributeVisitor& visitor) override;
bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override;
bool has_evaluate() const override;
protected:
bool is_type_supported(const ov::element::Type& type) const;
ColorConversion m_format = ColorConversion::NV12_TO_RGB;
};
} // namespace util
} // namespace op
} // namespace ov
| 45.47561 | 120 | 0.668812 | alexander-shchepetov |
ed0e9f5386aaa1ef57e88ba106cd245c85cd7664 | 16,233 | cpp | C++ | PathNetwork.cpp | jeffreycassidy/osm2bin | 7a6751d1a5045d8fb260aaa723ae85da193b4c93 | [
"Apache-2.0"
] | 4 | 2015-10-31T01:33:25.000Z | 2021-04-29T08:04:51.000Z | PathNetwork.cpp | jeffreycassidy/osm2bin | 7a6751d1a5045d8fb260aaa723ae85da193b4c93 | [
"Apache-2.0"
] | null | null | null | PathNetwork.cpp | jeffreycassidy/osm2bin | 7a6751d1a5045d8fb260aaa723ae85da193b4c93 | [
"Apache-2.0"
] | 2 | 2016-06-14T05:05:04.000Z | 2020-04-11T05:56:39.000Z | /*
* PathNetwork.cpp
*
* Created on: Dec 15, 2015
* Author: jcassidy
*/
#include "PathNetwork.hpp"
#include "OSMDatabase.hpp"
#include <boost/container/flat_map.hpp>
using namespace std;
const char* OSMWayFilterRoads::includeHighwayTagValueStrings_[] = {
"residential",
"primary",
"primary_link",
"secondary",
"secondary_link",
"tertiary",
"tertiary_link",
"motorway",
"motorway_link",
"service",
"trunk",
"living_street",
"unclassified",
"road",
nullptr
};
PathNetwork buildNetwork(const OSMDatabase& db, const OSMEntityFilter<OSMWay>& wayFilter) {
PathNetwork G;
float defaultMax = 50.0f;
struct NodeWithRefCount {
PathNetwork::vertex_descriptor graphVertexDescriptor = -1U;
unsigned nodeVectorIndex = -1U;
unsigned refcount = 0;
};
std::unordered_map<unsigned long long, NodeWithRefCount> nodesByOSMID;
unsigned kiHighway = db.wayTags().getIndexForKeyString("highway");
if (kiHighway == -1U)
std::cerr << "ERROR in buildNetwork(db,wf): failed to find tag key 'highway'" << std::endl;
const std::vector<std::pair<std::string,float>> defaultMaxSpeedByHighwayString
{
std::make_pair("motorway",105.0f),
std::make_pair("trunk",90.0f),
std::make_pair("primary",90.0f),
std::make_pair("secondary",80.0f),
std::make_pair("tertiary",80.0f),
std::make_pair("unclassified",50.0f),
std::make_pair("residential",50.0f),
std::make_pair("living_street",40.0f),
};
// fetch tag numbers for the highway strings
boost::container::flat_map<unsigned,float> defaultMaxSpeedByHighwayTagValue;
for(const auto p : defaultMaxSpeedByHighwayString)
{
unsigned viString = db.wayTags().getIndexForValueString(p.first);
if (viString != -1U)
{
const auto res = defaultMaxSpeedByHighwayTagValue.insert(std::make_pair(viString,p.second));
if (!res.second)
std::cerr << "ERROR in buildNetwork(db,wf): duplicate tag value '" << p.first << "' ID=" << viString << std::endl;
}
}
// create OSM ID -> vector index mapping for all nodes
std::cout << "Computing index map" << std::endl;
for (unsigned i = 0; i < db.nodes().size(); ++i)
nodesByOSMID[db.nodes()[i].id()].nodeVectorIndex = i;
// traverse the listed ways, marking node reference counts
std::cout << "Computing reference counts" << std::endl;
for (const OSMWay& w : db.ways() | boost::adaptors::filtered(std::cref(wayFilter)))
for (const unsigned long long nd : w.ndrefs()) {
auto it = nodesByOSMID.find(nd);
if (it == nodesByOSMID.end())
std::cerr << "WARNING: Dangling reference to node " << nd << " in way " << w.id() << std::endl;
else
it->second.refcount++;
}
// calculate and print reference-count (# way refs for each node) histogram for fun
std::vector<unsigned> refhist;
std::cout << "Computing reference-count frequency histogram" << std::endl;
for (const auto ni : nodesByOSMID | boost::adaptors::map_values) {
if (ni.refcount >= refhist.size())
refhist.resize(ni.refcount + 1, 0);
refhist[ni.refcount]++;
}
for (unsigned i = 0; i < refhist.size(); ++i)
if (refhist[i] > 0)
std::cout << " " << std::setw(3) << i << " refs: " << refhist[i] << " nodes" << std::endl;
// iterate over ways, creating edges in the intersection graph with associated curvepoints)
size_t nCurvePoints = 0;
unsigned k_maxspeed = db.wayTags().getIndexForKeyString("maxspeed");
enum OneWayType {
Bidir, Forward, Backward, Reversible, Unknown
};
unsigned k_oneway = db.wayTags().getIndexForKeyString("oneway");
unsigned v_oneway_yes = db.wayTags().getIndexForValueString("yes");
unsigned v_oneway_one = db.wayTags().getIndexForValueString("1");
unsigned v_oneway_minus_one = db.wayTags().getIndexForValueString("-1");
unsigned v_oneway_reversible = db.wayTags().getIndexForValueString("reversible");
unsigned v_oneway_no = db.wayTags().getIndexForValueString("no");
unsigned nOnewayForward = 0, nOnewayBackward = 0, nOnewayReversible = 0, nBidir = 0, nUnknown = 0;
unsigned nWays = 0;
boost::container::flat_map<unsigned,float> speedValues;
for (const auto& w : db.ways() | boost::adaptors::filtered(std::cref(wayFilter))) {
++nWays;
PathNetwork::vertex_descriptor segmentStartVertex = -1ULL, segmentEndVertex = -1ULL;
vector<LatLon> curvePoints;
// max speed is per way; mark as NaN by default (change NaNs to other value later)
float speed = std::numeric_limits<float>::quiet_NaN();
unsigned v;
if ((v = w.getValueForKey(k_maxspeed)) != -1U) // has maxspeed tag
{
boost::container::flat_map<unsigned, float>::iterator it;
bool inserted;
tie(it, inserted) = speedValues.insert(make_pair(v, std::numeric_limits<float>::quiet_NaN()));
if (inserted) // need to map this string value to a number
{
float spd;
string str = db.wayTags().getValue(v);
stringstream ss(str);
ss >> spd;
if (ss.fail()) {
ss.clear();
cout << "truncating '" << str << "' to substring '";
str = str.substr(str.find_first_of(':') + 1);
cout << str << "'" << endl;
ss.str(str);
ss >> spd;
}
if (ss.fail())
std::cout << "Failed to convert value for maxspeed='" << str << "'" << endl;
else if (!ss.eof()) {
string rem;
ss >> rem;
if (rem == "kph")
it->second = spd;
else if (rem == "mph")
it->second = spd * 1.609f;
else {
std::cout << "Warning: trailing characters in maxspeed='" << str << "'" << endl;
std::cout << " remaining: '" << rem << "'" << endl;
}
} else
it->second = spd;
if (!isnan(it->second))
std::cout << "Added new speed '" << str << "' = " << it->second << endl;
else
std::cout << "Failed to convert speed '" << str << "'" << endl;
}
speed = it->second;
}
else // no maxspeed -> default based on road type
{
unsigned viHighwayValue = w.getValueForKey(kiHighway);
if (viHighwayValue == -1U)
std::cerr << "ERROR in buildNetwork(db,wf): missing highway tag!" << std::endl;
else
{
const auto it = defaultMaxSpeedByHighwayTagValue.find(viHighwayValue);
if (it != defaultMaxSpeedByHighwayTagValue.end())
speed = it->second;
}
}
// assume bidirectional if not specified
OneWayType oneway = Unknown;
if (k_oneway == -1U) {
oneway = Bidir;
++nBidir;
} else {
unsigned v_oneway = w.getValueForKey(k_oneway);
if (v_oneway == -1U || v_oneway == v_oneway_no) {
oneway = Bidir;
++nBidir;
} else if (v_oneway == v_oneway_one) {
oneway = Forward;
++nOnewayForward;
} else if (v_oneway == v_oneway_yes) {
oneway = Forward;
++nOnewayForward;
} else if (v_oneway == v_oneway_minus_one) {
oneway = Backward;
++nOnewayBackward;
} else if (v_oneway == v_oneway_reversible) {
oneway = Reversible;
++nOnewayReversible;
} else {
cout << "Unrecognized tag oneway='" << db.wayTags().getValue(v_oneway);
++nUnknown;
}
}
// hamilton_canada and newyork: k=oneway v=-1 | 1 | yes | no | yes;-1 | reversible
for (unsigned i = 0; i < w.ndrefs().size(); ++i) {
const auto currNodeIt = nodesByOSMID.find(w.ndrefs()[i]);
LatLon prevCurvePoint;
if (currNodeIt == nodesByOSMID.end()) // dangling node reference: discard
{
cout << "WARNING: Dangling node with OSM ID " << w.ndrefs()[i] << " on way with OSM ID " << w.id() << endl;
segmentEndVertex = -1U;
continue;
} else if (currNodeIt->second.refcount == 1) // referenced by only 1 way -> curve point
{
LatLon ll = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords();
curvePoints.push_back(ll);
} else if (currNodeIt->second.refcount > 1 || i == 0 || i == w.ndrefs().size() - 1)
// referenced by >1 way or first/last node ref in a way -> node is an intersection
{
segmentEndVertex = currNodeIt->second.graphVertexDescriptor;
// if vertex hasn't been added yet, add now
if (segmentEndVertex == -1U) {
currNodeIt->second.graphVertexDescriptor = segmentEndVertex = add_vertex(G);
G[segmentEndVertex].latlon = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords();
G[segmentEndVertex].osmid = currNodeIt->first;
}
// arriving at an intersection node via a way
if (segmentStartVertex != -1ULL) {
PathNetwork::edge_descriptor e;
bool inserted;
assert(segmentStartVertex < num_vertices(G));
assert(segmentEndVertex < num_vertices(G));
std::tie(e, inserted) = add_edge(segmentStartVertex, segmentEndVertex, G);
assert(inserted && "Duplicate edge");
G[e].wayOSMID = w.id();
if (oneway == Forward || oneway == Backward) {
// goes towards end vertex; if greater then goes towards greater
// flip it
bool towardsGreater = (segmentEndVertex > segmentStartVertex) ^ (oneway == Backward);
G[e].oneWay = towardsGreater ?
EdgeProperties::ToGreaterVertexNumber :
EdgeProperties::ToLesserVertexNumber;
} else
G[e].oneWay = EdgeProperties::Bidir;
G[e].maxspeed = speed;
nCurvePoints += curvePoints.size();
G[e].curvePoints = std::move(curvePoints);
}
segmentStartVertex = segmentEndVertex;
}
prevCurvePoint = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords();
}
}
std::cout << "PathNetwork created with " << num_vertices(G) << " vertices and " << num_edges(G) << " edges, with " << nCurvePoints << " curve points" << std::endl;
std::cout << " Used " << nWays << "/" << db.ways().size() << " ways" << endl;
std::cout << " One-way streets: " << (nOnewayForward + nOnewayBackward) << "/" << nWays << " (" << nOnewayReversible << " reversible and " << nUnknown << " unknown)" << std::endl;
assert(nOnewayForward + nOnewayBackward + nOnewayReversible + nBidir + nUnknown == nWays);
// create/print edge-degree histogram
std::cout << "Vertex degree histogram:" << std::endl;
std::vector<unsigned> dhist;
for (auto v : boost::make_iterator_range(vertices(G))) {
unsigned d = out_degree(v, G);
if (d >= dhist.size())
dhist.resize(d + 1, 0);
dhist[d]++;
}
unsigned Ndefault = 0;
for (auto e : boost::make_iterator_range(edges(G))) {
if (isnan(G[e].maxspeed)) {
++Ndefault;
G[e].maxspeed = defaultMax;
}
}
cout << "Assigned " << Ndefault << "/" << num_edges(G) << " street segments to default max speed for lack of information" << endl;
for (unsigned i = 0; i < dhist.size(); ++i)
if (dhist[i] > 0)
std::cout << " " << std::setw(3) << i << " refs: " << dhist[i] << " nodes" << std::endl;
return G;
}
class StreetEdgeVisitor {
public:
StreetEdgeVisitor(PathNetwork* G)
: m_G(G) {
}
std::vector<std::string> assign() {
m_streets.clear();
m_streets.push_back("<unknown>");
for (const auto e : edges(*m_G))
if ((*m_G)[e].streetVectorIndex == 0)
startWithEdge(e);
return std::move(m_streets);
}
// pick up the street name from the specified edge, add it to the vertex, and expand the source/target vertices
void startWithEdge(PathNetwork::edge_descriptor e);
// inspect all out-edges of the vertex, assigning and recursively expanding any which match the way ID or street name
void expandVertex(PathNetwork::vertex_descriptor v, OSMID wayID);
void osmDatabase(OSMDatabase* p) {
m_osmDatabase = p;
m_keyIndexName = p->wayTags().getIndexForKeyString("name");
m_keyIndexNameEn = p->wayTags().getIndexForKeyString("name:en");
}
private:
const std::string streetNameForWay(OSMID osmid) {
const OSMWay& w = m_osmDatabase->wayFromID(osmid);
unsigned valTag = -1U;
if ((valTag = w.getValueForKey(m_keyIndexNameEn)) == -1U)
valTag = w.getValueForKey(m_keyIndexName);
if (valTag == -1U)
return std::string();
else
return m_osmDatabase->wayTags().getValue(valTag);
}
static const std::string np;
PathNetwork* m_G = nullptr; // the path network
OSMDatabase* m_osmDatabase = nullptr; // OSM database with source data
unsigned m_keyIndexName = -1U, m_keyIndexNameEn = -1U; // cached values for key-value tables
std::vector<std::string> m_streets; // street name vector being built
unsigned m_currStreetVectorIndex = 0; // index of current street
};
const std::string StreetEdgeVisitor::np = {"<name-not-present>"};
void StreetEdgeVisitor::startWithEdge(PathNetwork::edge_descriptor e) {
// grab OSM ID of this way, look up its name
OSMID wID = (*m_G)[e].wayOSMID;
std::string streetName = streetNameForWay(wID);
if (!streetName.empty()) {
// insert the street name
(*m_G)[e].streetVectorIndex = m_currStreetVectorIndex = m_streets.size();
m_streets.push_back(streetName);
// expand the vertices at both ends
expandVertex(source(e, *m_G), wID);
expandVertex(target(e, *m_G), wID);
}
}
/** Recursively expand the specified vertex, along out-edges which have way OSMID == currWayID, or have the same street name */
void StreetEdgeVisitor::expandVertex(PathNetwork::vertex_descriptor v, OSMID currWayID) {
for (const auto e : out_edges(v, *m_G)) // for all out-edges of this vertex
{
if ((*m_G)[e].streetVectorIndex != 0) // skip if already assigned (prevents infinite recursion back to origin)
continue;
OSMID wID = (*m_G)[e].wayOSMID;
assert(wID != 0 && wID != -1U);
if (wID == currWayID) // (connected,same way -> same name) -> same street
(*m_G)[e].streetVectorIndex = m_currStreetVectorIndex;
else if (streetNameForWay(wID) == m_streets.back()) // (connected,same name) -> same street
(*m_G)[e].streetVectorIndex = m_currStreetVectorIndex;
else // different way, different name -> done expanding
continue;
// this is the fall-through case for the if/elseif above (terminates if reaches a different street)
expandVertex(target(e, *m_G), wID);
}
}
std::vector<std::string> assignStreets(OSMDatabase* db, PathNetwork& G) {
StreetEdgeVisitor sev(&G);
sev.osmDatabase(db);
// blank out existing street names
for (const auto e : edges(G))
G[e].streetVectorIndex = 0;
return sev.assign();
}
| 35.913717 | 184 | 0.56687 | jeffreycassidy |
ed109cc9f75dd7d93d2c930aa5e4705cc9f1448b | 10,076 | cpp | C++ | pandar_pointcloud/src/lib/decoder/pandar64_decoder.cpp | Perception-Engine/hesai_pandar | bbdfdf5d81423715c47c0526ac51084fef029edf | [
"Apache-2.0"
] | null | null | null | pandar_pointcloud/src/lib/decoder/pandar64_decoder.cpp | Perception-Engine/hesai_pandar | bbdfdf5d81423715c47c0526ac51084fef029edf | [
"Apache-2.0"
] | 6 | 2021-05-17T06:48:19.000Z | 2022-02-24T23:43:46.000Z | pandar_pointcloud/src/lib/decoder/pandar64_decoder.cpp | Perception-Engine/hesai_pandar | bbdfdf5d81423715c47c0526ac51084fef029edf | [
"Apache-2.0"
] | 1 | 2021-03-05T00:39:13.000Z | 2021-03-05T00:39:13.000Z | #include "pandar_pointcloud/decoder/pandar64_decoder.hpp"
#include "pandar_pointcloud/decoder/pandar64.hpp"
namespace
{
static inline double deg2rad(double degrees)
{
return degrees * M_PI / 180.0;
}
}
namespace pandar_pointcloud
{
namespace pandar64
{
Pandar64Decoder::Pandar64Decoder(Calibration& calibration, float scan_phase, double dual_return_distance_threshold, ReturnMode return_mode)
{
firing_offset_ = {
23.18, 21.876, 20.572, 19.268, 17.964, 16.66, 11.444, 46.796,
7.532, 36.956, 50.732, 54.668, 40.892, 44.828,31.052, 34.988,
48.764, 52.7, 38.924, 42.86, 29.084, 33.02, 46.796, 25.148,
36.956, 50.732, 27.116, 40.892, 44.828, 31.052, 34.988, 48.764,
25.148, 38.924, 42.86, 29.084, 33.02, 52.7, 6.228, 54.668,
15.356, 27.116, 10.14, 23.18, 4.924, 21.876, 14.052, 17.964,
8.836, 19.268, 3.62, 20.572, 12.748, 16.66, 7.532, 11.444,
6.228, 15.356, 10.14, 4.924, 3.62, 14.052, 8.836, 12.748
};
for (int block = 0; block < BLOCK_NUM; ++block) {
block_offset_single_[block] = 55.56f * (BLOCK_NUM - block - 1) + 28.58f;
block_offset_dual_[block] = 55.56f * ((BLOCK_NUM - block - 1) / 2) + 28.58f;
}
// TODO: add calibration data validation
// if(calibration.elev_angle_map.size() != num_lasers_){
// // calibration data is not valid!
// }
for (size_t laser = 0; laser < UNIT_NUM; ++laser) {
elev_angle_[laser] = calibration.elev_angle_map[laser];
azimuth_offset_[laser] = calibration.azimuth_offset_map[laser];
}
scan_phase_ = static_cast<uint16_t>(scan_phase * 100.0f);
return_mode_ = return_mode;
dual_return_distance_threshold_ = dual_return_distance_threshold;
last_phase_ = 0;
has_scanned_ = false;
scan_pc_.reset(new pcl::PointCloud<PointXYZIRADT>);
overflow_pc_.reset(new pcl::PointCloud<PointXYZIRADT>);
}
bool Pandar64Decoder::hasScanned()
{
return has_scanned_;
}
PointcloudXYZIRADT Pandar64Decoder::getPointcloud()
{
return scan_pc_;
}
void Pandar64Decoder::unpack(const pandar_msgs::PandarPacket& raw_packet)
{
if (!parsePacket(raw_packet)) {
return;
}
if (has_scanned_) {
scan_pc_ = overflow_pc_;
overflow_pc_.reset(new pcl::PointCloud<PointXYZIRADT>);
has_scanned_ = false;
}
bool dual_return = (packet_.return_mode == DUAL_RETURN);
auto step = dual_return ? 2 : 1;
if (!dual_return) {
if ((packet_.return_mode == STRONGEST_RETURN && return_mode_ != ReturnMode::STRONGEST) ||
(packet_.return_mode == LAST_RETURN && return_mode_ != ReturnMode::LAST)) {
ROS_WARN ("Sensor return mode configuration does not match requested return mode");
}
}
for (int block_id = 0; block_id < BLOCK_NUM; block_id += step) {
auto block_pc = dual_return ? convert_dual(block_id) : convert(block_id);
int current_phase = (static_cast<int>(packet_.blocks[block_id].azimuth) - scan_phase_ + 36000) % 36000;
if (current_phase > last_phase_ && !has_scanned_) {
*scan_pc_ += *block_pc;
}
else {
*overflow_pc_ += *block_pc;
has_scanned_ = true;
}
last_phase_ = current_phase;
}
}
PointXYZIRADT Pandar64Decoder::build_point(int block_id, int unit_id, uint8_t return_type)
{
const auto& block = packet_.blocks[block_id];
const auto& unit = block.units[unit_id];
auto unix_second = static_cast<double>(timegm(&packet_.t));
bool dual_return = (packet_.return_mode == DUAL_RETURN);
PointXYZIRADT point{};
double xyDistance = unit.distance * cosf(deg2rad(elev_angle_[unit_id]));
point.x = static_cast<float>(
xyDistance * sinf(deg2rad(azimuth_offset_[unit_id] + (static_cast<double>(block.azimuth)) / 100.0)));
point.y = static_cast<float>(
xyDistance * cosf(deg2rad(azimuth_offset_[unit_id] + (static_cast<double>(block.azimuth)) / 100.0)));
point.z = static_cast<float>(unit.distance * sinf(deg2rad(elev_angle_[unit_id])));
point.intensity = unit.intensity;
point.distance = static_cast<float>(unit.distance);
point.ring = unit_id;
point.azimuth = static_cast<float>(block.azimuth) + round(azimuth_offset_[unit_id] * 100.0f);
point.return_type = return_type;
point.time_stamp = unix_second + (static_cast<double>(packet_.usec)) / 1000000.0;
point.time_stamp += dual_return ? (static_cast<double>(block_offset_dual_[block_id] + firing_offset_[unit_id]) / 1000000.0f) :
(static_cast<double>(block_offset_single_[block_id] + firing_offset_[unit_id]) / 1000000.0f);
return point;
}
PointcloudXYZIRADT Pandar64Decoder::convert(const int block_id)
{
PointcloudXYZIRADT block_pc(new pcl::PointCloud<PointXYZIRADT>);
const auto& block = packet_.blocks[block_id];
for (size_t unit_id = 0; unit_id < UNIT_NUM; ++unit_id) {
PointXYZIRADT point{};
const auto& unit = block.units[unit_id];
// skip invalid points
if (unit.distance <= 0.1 || unit.distance > 200.0) {
continue;
}
block_pc->points.emplace_back(build_point(block_id, unit_id, (packet_.return_mode == STRONGEST_RETURN) ? ReturnType::SINGLE_STRONGEST : ReturnType::SINGLE_LAST));
}
return block_pc;
}
PointcloudXYZIRADT Pandar64Decoder::convert_dual(const int block_id)
{
// Under the Dual Return mode, the ranging data from each firing is stored in two adjacent blocks:
// · The even number block is the first return
// · The odd number block is the last return
// · The Azimuth changes every two blocks
// · Important note: Hesai datasheet block numbering starts from 0, not 1, so odd/even are reversed here
PointcloudXYZIRADT block_pc(new pcl::PointCloud<PointXYZIRADT>);
int even_block_id = block_id;
int odd_block_id = block_id + 1;
const auto& even_block = packet_.blocks[even_block_id];
const auto& odd_block = packet_.blocks[odd_block_id];
for (size_t unit_id = 0; unit_id < UNIT_NUM; ++unit_id) {
const auto& even_unit = even_block.units[unit_id];
const auto& odd_unit = odd_block.units[unit_id];
bool even_usable = !(even_unit.distance <= 0.1 || even_unit.distance > 200.0);
bool odd_usable = !(odd_unit.distance <= 0.1 || odd_unit.distance > 200.0);
if (return_mode_ == ReturnMode::STRONGEST && even_usable) {
// First return is in even block
block_pc->points.emplace_back(build_point(even_block_id, unit_id, ReturnType::SINGLE_STRONGEST));
}
else if (return_mode_ == ReturnMode::LAST && even_usable) {
// Last return is in odd block
block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::SINGLE_LAST));
}
else if (return_mode_ == ReturnMode::DUAL) {
// If the two returns are too close, only return the last one
if ((abs(even_unit.distance - odd_unit.distance) < dual_return_distance_threshold_) && odd_usable) {
block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::DUAL_ONLY));
}
else {
if (even_usable) {
block_pc->points.emplace_back(build_point(even_block_id, unit_id, ReturnType::DUAL_FIRST));
}
if (odd_usable) {
block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::DUAL_LAST));
}
}
}
}
return block_pc;
}
bool Pandar64Decoder::parsePacket(const pandar_msgs::PandarPacket& raw_packet)
{
if (raw_packet.size != PACKET_SIZE && raw_packet.size != PACKET_WITHOUT_UDPSEQ_SIZE) {
return false;
}
const uint8_t* buf = &raw_packet.data[0];
size_t index = 0;
// Parse 12 Bytes Header
packet_.header.sob = (buf[index] & 0xff) << 8| ((buf[index+1] & 0xff));
packet_.header.chLaserNumber = buf[index+2] & 0xff;
packet_.header.chBlockNumber = buf[index+3] & 0xff;
packet_.header.chReturnType = buf[index+4] & 0xff;
packet_.header.chDisUnit = buf[index+5] & 0xff;
index += HEAD_SIZE;
if (packet_.header.sob != 0xEEFF) {
// Error Start of Packet!
return false;
}
for (size_t block = 0; block < packet_.header.chBlockNumber; block++) {
packet_.blocks[block].azimuth = (buf[index] & 0xff) | ((buf[index + 1] & 0xff) << 8);
index += BLOCK_HEADER_AZIMUTH;
for (int unit = 0; unit < packet_.header.chLaserNumber; unit++) {
unsigned int unRange = (buf[index]& 0xff) | ((buf[index + 1]& 0xff) << 8);
packet_.blocks[block].units[unit].distance =
(static_cast<double>(unRange * packet_.header.chDisUnit)) / 1000.;
packet_.blocks[block].units[unit].intensity = (buf[index+2]& 0xff);
index += UNIT_SIZE;
}//end fot laser
}//end for block
index += RESERVED_SIZE; // skip reserved bytes
index += ENGINE_VELOCITY;
packet_.usec = (buf[index] & 0xff)| (buf[index+1] & 0xff) << 8 | ((buf[index+2] & 0xff) << 16) | ((buf[index+3] & 0xff) << 24);
index += TIMESTAMP_SIZE;
packet_.return_mode = buf[index] & 0xff;
index += RETURN_SIZE;
index += FACTORY_SIZE;
packet_.t.tm_year = (buf[index + 0] & 0xff) + 100;
// in case of time error
if (packet_.t.tm_year >= 200) {
packet_.t.tm_year -= 100;
}
packet_.t.tm_mon = (buf[index + 1] & 0xff) - 1;
packet_.t.tm_mday = buf[index + 2] & 0xff;
packet_.t.tm_hour = buf[index + 3] & 0xff;
packet_.t.tm_min = buf[index + 4] & 0xff;
packet_.t.tm_sec = buf[index + 5] & 0xff;
packet_.t.tm_isdst = 0;
index += UTC_SIZE;
return true;
}//parsePacket
}//pandar64
}//pandar_pointcloud | 39.206226 | 170 | 0.629813 | Perception-Engine |
ed131fe5b427cb67d5e58e91813206a3d106ffe5 | 1,634 | cpp | C++ | DXR_SoftShadows_Project/BeLuEngine/src/Renderer/DX12Tasks/RenderTask.cpp | jocke1995/DXR_SoftShadows | 00cb6b1cf560899a010c9e8504578d55e113c22c | [
"MIT"
] | null | null | null | DXR_SoftShadows_Project/BeLuEngine/src/Renderer/DX12Tasks/RenderTask.cpp | jocke1995/DXR_SoftShadows | 00cb6b1cf560899a010c9e8504578d55e113c22c | [
"MIT"
] | null | null | null | DXR_SoftShadows_Project/BeLuEngine/src/Renderer/DX12Tasks/RenderTask.cpp | jocke1995/DXR_SoftShadows | 00cb6b1cf560899a010c9e8504578d55e113c22c | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "RenderTask.h"
// DX12 Specifics
#include "../CommandInterface.h"
#include "../GPUMemory/GPUMemory.h"
#include "../PipelineState/GraphicsState.h"
#include "../RootSignature.h"
#include "../SwapChain.h"
RenderTask::RenderTask(
ID3D12Device5* device,
RootSignature* rootSignature,
const std::wstring& VSName, const std::wstring& PSName,
std::vector<D3D12_GRAPHICS_PIPELINE_STATE_DESC*>* gpsds,
const std::wstring& psoName)
:DX12Task(device, COMMAND_INTERFACE_TYPE::DIRECT_TYPE)
{
if (gpsds != nullptr)
{
for (auto gpsd : *gpsds)
{
m_PipelineStates.push_back(new GraphicsState(device, rootSignature, VSName, PSName, gpsd, psoName));
}
}
m_pRootSig = rootSignature->GetRootSig();
}
RenderTask::~RenderTask()
{
for (auto pipelineState : m_PipelineStates)
delete pipelineState;
}
PipelineState* RenderTask::GetPipelineState(unsigned int index)
{
return m_PipelineStates[index];
}
void RenderTask::AddRenderTargetView(std::string name, const RenderTargetView* renderTargetView)
{
m_RenderTargetViews[name] = renderTargetView;
}
void RenderTask::AddShaderResourceView(std::string name, const ShaderResourceView* shaderResourceView)
{
m_ShaderResourceViews[name] = shaderResourceView;
}
void RenderTask::SetRenderComponents(std::vector<RenderComponent*> *renderComponents)
{
m_RenderComponents = renderComponents;
}
void RenderTask::SetMainDepthStencil(DepthStencil* depthStencil)
{
m_pDepthStencil = depthStencil;
}
void RenderTask::SetCamera(BaseCamera* camera)
{
m_pCamera = camera;
}
void RenderTask::SetSwapChain(SwapChain* swapChain)
{
m_pSwapChain = swapChain;
}
| 22.383562 | 103 | 0.76989 | jocke1995 |
ed1498729e51bb7858cd00d50dd565ab4e53f33e | 568 | cpp | C++ | Permutation/Permutation.cpp | raza6/CSES | cfaec9d7bc103c7349cc17c0a07112d1e245dc3a | [
"MIT"
] | null | null | null | Permutation/Permutation.cpp | raza6/CSES | cfaec9d7bc103c7349cc17c0a07112d1e245dc3a | [
"MIT"
] | null | null | null | Permutation/Permutation.cpp | raza6/CSES | cfaec9d7bc103c7349cc17c0a07112d1e245dc3a | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int main()
{
// HACKERMAN
ios::sync_with_stdio(false);
cin.tie(0);
//Read inputs
int value;
cin >> value;
string res = "NO SOLUTION";
if (value > 3) {
res = "";
for (int i = 2; i <= value; i += 2) {
res += to_string(i) + " ";
}
for (int i = 1; i <= value; i += 2) {
res += to_string(i) + " ";
}
}
else if (value == 1) {
res = "1";
}
cout << res << endl;
}
| 16.705882 | 45 | 0.43838 | raza6 |
ed16403f90d5cb98d45293e480b4258b7ad5efee | 3,531 | hpp | C++ | src/utility/Confidence.hpp | wvDevAus/Expert-System-Shell | b0c92b1ecb31066c473e549878a9a157b4ea72c9 | [
"MIT"
] | null | null | null | src/utility/Confidence.hpp | wvDevAus/Expert-System-Shell | b0c92b1ecb31066c473e549878a9a157b4ea72c9 | [
"MIT"
] | null | null | null | src/utility/Confidence.hpp | wvDevAus/Expert-System-Shell | b0c92b1ecb31066c473e549878a9a157b4ea72c9 | [
"MIT"
] | null | null | null | #pragma once
#include "nlohmann/json.hpp"
namespace expert_system::utility {
/**
* @brief A managed confidence factor.
* Ensures that the confidence factor does not exceed the range of 0.0f and 1.0f.
*/
class Confidence {
public:
/**
* @brief Default constructor.
* Initial confidence factor value of 0.0f.
*/
Confidence();
/**
* @brief Parameterized constructor.
* @param [in] value The confidence factor value to assign.
* @note This will be replaced by the closest range bounds if outside them.
*/
explicit Confidence(float value);
/**
* @brief Attempts to assign a confidence factor value.
* @param [in] value The confidence factor value to assign.
* @note This will be replaced by the closest range bounds if outside them.
*/
void Set(float value);
/**
* @brief Provides a read-only access to the private confidence factor value.
* @return A copy of the stored confidence factor value.
*/
float Get() const;
/**
* @brief Creates a new confidence factor from combining this value with another.
* @param [in] value The confidence factor value to assign.
* @return A new Confidence, generated from multiplying the provided value with the stored value.
*/
[[nodiscard]] Confidence Combine(const Confidence& value) const;
/**
* @brief 'More than' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is more than this.
*/
bool operator<(const Confidence& target);
/**
* @brief 'Less than' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is less than this.
*/
bool operator>(const Confidence& target);
/**
* @brief 'Equal to' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is equal to this.
*/
bool operator==(const Confidence& target);
private:
/// The protected confidence factor value.
float confidence_factor_;
/// Enables JSON serializer access to private contents
friend void to_json(nlohmann::json& json_sys, const Confidence& target);
/// Enables JSON serializer access to private contents
friend void from_json(const nlohmann::json& json_sys, Confidence& target);
};
/**
* @brief Confidence serialization to JSON format.
* @param [in,out] json_sys A reference to a JSON object.
* @param [in] target A reference to the Confidence to export.
*/
void to_json(nlohmann::json& json_sys, const Confidence& target);
/**
* @brief Confidence serialization from JSON format.
* @param [in] json_sys A reference to a JSON object.
* @param [in,out] target A reference to the Confidence to import.
*/
void from_json(const nlohmann::json& json_sys, Confidence& target);
} // namespace expert_system::utility
| 37.967742 | 109 | 0.588219 | wvDevAus |
ed182479fd135847b311e09e06377096813da592 | 3,347 | cpp | C++ | src/TRGame/Lighting/Lighting.cpp | CXUtk/TRV2 | 945950012e2385aeb24e80bf5e876703445ba423 | [
"Apache-2.0"
] | null | null | null | src/TRGame/Lighting/Lighting.cpp | CXUtk/TRV2 | 945950012e2385aeb24e80bf5e876703445ba423 | [
"Apache-2.0"
] | 15 | 2021-09-04T13:02:51.000Z | 2021-10-05T05:51:31.000Z | src/TRGame/Lighting/Lighting.cpp | CXUtk/TRV2 | 945950012e2385aeb24e80bf5e876703445ba423 | [
"Apache-2.0"
] | null | null | null | #include "Lighting.h"
#include "LightCalculator/LightCommon.h"
#include "LightCalculator/BFSLightCalculator.h"
#include "LightCalculator/DirectionalLightCalculator.h"
#include <TRGame/TRGame.hpp>
#include <TRGame/Player/Player.h>
#include <TRGame/Worlds/GameWorld.h>
#include <TRGame/Worlds/WorldResources.h>
#include <TRGame/Worlds/Tile.h>
#include <TRGame/Worlds/TileSection.h>
#include <TREngine/Core/Render/SpriteRenderer.h>
#include <TREngine/Core/Utils/Utils.h>
#include <TREngine/Core/Assets/assets.h>
#include <TREngine/Core/Render/render.h>
#include <TREngine/Engine.h>
#include <set>
using namespace trv2;
Lighting::Lighting()
{
_lightCommonData = std::make_unique<LightCommon>();
_bfsCalculator = std::make_unique<BFSLightCalculator>(trv2::ptr(_lightCommonData));
_directionCalculator = std::make_unique<DirectionalLightCalculator>(trv2::ptr(_lightCommonData));
}
Lighting::~Lighting()
{}
static glm::vec3 Gamma(const glm::vec3 color)
{
return glm::pow(color, glm::vec3(2.2));
}
static glm::vec3 InvGamma(const glm::vec3 color)
{
return glm::pow(color, glm::vec3(1 / 2.2));
}
void Lighting::ClearLights()
{
_bfsCalculator->ClearLights();
_directionCalculator->ClearLights();
}
void Lighting::AddNormalLight(const Light& light)
{
_bfsCalculator->AddLight(light);
}
void Lighting::AddDirectionalLight(const Light& light)
{
_directionCalculator->AddLight(light);
}
void Lighting::CalculateLight(const trv2::RectI& tileRectCalc, const trv2::RectI& tileRectScreen)
{
_lightCommonData->TileRectScreen = tileRectScreen;
auto sectionRect = GameWorld::GetTileSectionRect(tileRectCalc);
_lightCommonData->SectionRect = sectionRect;
_lightCommonData->TileRectWorld = trv2::RectI(sectionRect.Position * GameWorld::TILE_SECTION_SIZE,
sectionRect.Size * GameWorld::TILE_SECTION_SIZE);
auto gameWorld = TRGame::GetInstance()->GetGameWorld();
_lightCommonData->GameWorld = gameWorld;
auto common = _lightCommonData.get();
const int totalBlocks = common->TileRectWorld.Size.x * common->TileRectWorld.Size.y;
common->SectionRect.ForEach([this, common](glm::ivec2 sectionCoord) {
const TileSection* section = common->GameWorld->GetSection(sectionCoord);
section->ForEachTile([this, common](glm::ivec2 coord, const Tile& tile) {
int id = common->GetBlockId(coord - common->TileRectWorld.Position);
common->CachedTile[id].Type = tile.Type;
});
});
_bfsCalculator->Calculate();
_directionCalculator->Calculate();
_directionCalculator->RasterizeLightTriangles();
}
void Lighting::DrawLightMap(trv2::SpriteRenderer* renderer, const glm::mat4& projection)
{
trv2::BatchSettings setting{};
renderer->Begin(projection, setting);
{
_lightCommonData->TileRectScreen.ForEach([this, renderer](glm::ivec2 coord) -> void {
auto& common = _lightCommonData;
int id = common->GetBlockId(coord - common->TileRectWorld.Position);
auto color = glm::vec3(common->TileColors[0][id],
common->TileColors[1][id],
common->TileColors[2][id]);
if (color == glm::vec3(0)) return;
renderer->Draw(coord, glm::vec2(1), glm::vec2(0),
0.f, glm::vec4(color, 1.f));
});
}
renderer->End();
}
void Lighting::DrawDirectionalTriangles(const glm::mat4& worldProjection)
{
_directionCalculator->DrawTriangles(worldProjection);
}
float Lighting::GetLight(glm::ivec2 coord)
{
return 0.f;
}
| 26.991935 | 99 | 0.747834 | CXUtk |
ed190a1496f87ff0fa3906b2cc16882613357aad | 3,237 | cpp | C++ | sensors/lidars/velodyne/impl/thin_reader.cpp | jackiecx/snark | 492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6 | [
"BSD-3-Clause"
] | 1 | 2019-06-14T15:21:24.000Z | 2019-06-14T15:21:24.000Z | sensors/lidars/velodyne/impl/thin_reader.cpp | jackiecx/snark | 492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6 | [
"BSD-3-Clause"
] | null | null | null | sensors/lidars/velodyne/impl/thin_reader.cpp | jackiecx/snark | 492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of snark, a generic and flexible library for robotics research
// Copyright (c) 2011 The University of Sydney
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the University of Sydney nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE. 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.
#ifdef WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "thin_reader.h"
namespace snark {
snark::thin_reader::thin_reader() : is_new_scan_( true )
{
#ifdef WIN32
_setmode( _fileno( stdin ), _O_BINARY );
#endif
}
const char* thin_reader::read()
{
if( !std::cin.good() || std::cin.eof() ) { return NULL; }
comma::uint16 size;
std::cin.read( reinterpret_cast< char* >( &size ), 2 );
if( std::cin.gcount() < 2 ) { return NULL; }
std::cin.read( m_buf, size );
if( std::cin.gcount() < size ) { return NULL; }
comma::int64 seconds;
comma::int32 nanoseconds;
::memcpy( &seconds, m_buf, sizeof( comma::int64 ) );
::memcpy( &nanoseconds, m_buf + sizeof( comma::int64 ), sizeof( comma::int32 ) );
m_timestamp = boost::posix_time::ptime( snark::timing::epoch, boost::posix_time::seconds( static_cast< long >( seconds ) ) + boost::posix_time::microseconds( nanoseconds / 1000 ) );
comma::uint32 scan = velodyne::thin::deserialize( m_packet, m_buf + timeSize );
is_new_scan_ = is_new_scan_ || !last_scan_ || *last_scan_ != scan; // quick and dirty; keep it set until we clear it in is_new_scan()
last_scan_ = scan;
return reinterpret_cast< char* >( &m_packet );
}
void thin_reader::close() {}
boost::posix_time::ptime thin_reader::timestamp() const { return m_timestamp; }
bool thin_reader::is_new_scan()
{
bool r = is_new_scan_;
is_new_scan_ = false;
return r;
}
} // namespace snark {
| 42.592105 | 185 | 0.71764 | jackiecx |
ed1a79bdc801741558e76b1f925ccf3a814cb406 | 1,807 | cpp | C++ | soundmanager.cpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | 6 | 2017-09-15T16:15:03.000Z | 2020-01-09T04:31:26.000Z | soundmanager.cpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | null | null | null | soundmanager.cpp | hckr/space-logic-adventure | 7465c7ffb70b0488ce4ff88620e3d35742f4fb06 | [
"MIT"
] | 1 | 2017-12-05T05:22:02.000Z | 2017-12-05T05:22:02.000Z | #include "soundmanager.hpp"
void SoundManager::lowerMusicVolume(bool lower) {
if (lower) {
sounds.at(MENU).setVolume(50);
sounds.at(LEVEL).setVolume(50);
} else {
sounds.at(MENU).setVolume(100);
sounds.at(LEVEL).setVolume(100);
}
}
SoundManager::SoundManager()
{
menuSB.loadFromFile(SOUNDS_DIR + "menu.ogg");
levelSB.loadFromFile(SOUNDS_DIR + "level.ogg");
levelCompletedSB.loadFromFile(SOUNDS_DIR + "level_completed.ogg");
gameOverSB.loadFromFile(SOUNDS_DIR + "game_over.ogg");
sounds.at(MENU).setLoop(true);
sounds.at(LEVEL).setLoop(true);
}
SoundManager* SoundManager::instance = 0;
SoundManager& SoundManager::getInstance() {
if (!instance) {
instance = new SoundManager();
}
return *instance;
}
void SoundManager::destroyInstance() {
if (instance) {
delete instance;
instance = 0;
}
}
void SoundManager::changeMusic(Sound music) {
if (musicPlaying == music) {
return;
}
switch (music) {
case NONE:
sounds.at(musicPlaying).stop();
break;
case MENU:
case LEVEL:
if (musicPlaying != NONE) {
sounds.at(musicPlaying).stop();
}
sounds.at(music).play();
musicPlaying = music;
break;
default:
break;
}
}
void SoundManager::playEffect(Sound effect) {
switch (effect) {
case LEVEL_COMPLETED:
case GAME_OVER:
lowerMusicVolume(true);
sounds.at(effect).play();
effectPlaying = effect;
break;
default:
break;
}
}
void SoundManager::update() {
if (effectPlaying != NONE && sounds.at(effectPlaying).getStatus() == sf::SoundSource::Stopped) {
lowerMusicVolume(false);
effectPlaying = NONE;
}
}
| 21.511905 | 100 | 0.60653 | hckr |
ed1bfd33453e41f099287ac92d62cd0efef6729a | 10,530 | cpp | C++ | rosflight_utils/src/turbomath.cpp | WangGY-Pro/rosflight | 000e3d79383e05d7cc574129644a12c694a876eb | [
"BSD-3-Clause"
] | 80 | 2017-05-27T16:21:32.000Z | 2022-03-09T13:24:38.000Z | rosflight_utils/src/turbomath.cpp | WangGY-Pro/rosflight | 000e3d79383e05d7cc574129644a12c694a876eb | [
"BSD-3-Clause"
] | 82 | 2017-05-17T17:10:04.000Z | 2021-06-06T04:25:44.000Z | rosflight_utils/src/turbomath.cpp | WangGY-Pro/rosflight | 000e3d79383e05d7cc574129644a12c694a876eb | [
"BSD-3-Clause"
] | 67 | 2017-05-16T19:26:53.000Z | 2022-03-27T15:04:34.000Z | /*
* Copyright (c) 2017 James Jackson, BYU MAGICC Lab.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <rosflight_utils/turbomath.h>
#include <cstdint>
static const int16_t atan_lookup_table[250] = {
0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 559, 599, 639, 679,
719, 759, 798, 838, 878, 917, 957, 997, 1036, 1076, 1115, 1155, 1194, 1234, 1273, 1312, 1352, 1391,
1430, 1469, 1508, 1548, 1587, 1626, 1664, 1703, 1742, 1781, 1820, 1858, 1897, 1935, 1974, 2012, 2051, 2089,
2127, 2166, 2204, 2242, 2280, 2318, 2355, 2393, 2431, 2469, 2506, 2544, 2581, 2618, 2656, 2693, 2730, 2767,
2804, 2841, 2878, 2915, 2951, 2988, 3024, 3061, 3097, 3133, 3169, 3206, 3241, 3277, 3313, 3349, 3385, 3420,
3456, 3491, 3526, 3561, 3596, 3631, 3666, 3701, 3736, 3771, 3805, 3839, 3874, 3908, 3942, 3976, 4010, 4044,
4078, 4112, 4145, 4179, 4212, 4245, 4278, 4311, 4344, 4377, 4410, 4443, 4475, 4508, 4540, 4572, 4604, 4636,
4668, 4700, 4732, 4764, 4795, 4827, 4858, 4889, 4920, 4951, 4982, 5013, 5044, 5074, 5105, 5135, 5166, 5196,
5226, 5256, 5286, 5315, 5345, 5375, 5404, 5434, 5463, 5492, 5521, 5550, 5579, 5608, 5636, 5665, 5693, 5721,
5750, 5778, 5806, 5834, 5862, 5889, 5917, 5944, 5972, 5999, 6026, 6053, 6080, 6107, 6134, 6161, 6187, 6214,
6240, 6267, 6293, 6319, 6345, 6371, 6397, 6422, 6448, 6473, 6499, 6524, 6549, 6574, 6599, 6624, 6649, 6674,
6698, 6723, 6747, 6772, 6796, 6820, 6844, 6868, 6892, 6916, 6940, 6963, 6987, 7010, 7033, 7057, 7080, 7103,
7126, 7149, 7171, 7194, 7217, 7239, 7261, 7284, 7306, 7328, 7350, 7372, 7394, 7416, 7438, 7459, 7481, 7502,
7524, 7545, 7566, 7587, 7608, 7629, 7650, 7671, 7691, 7712, 7733, 7753, 7773, 7794, 7814, 7834};
static const int16_t asin_lookup_table[250] = {
0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600,
640, 681, 721, 761, 801, 841, 881, 921, 961, 1002, 1042, 1082, 1122, 1163, 1203, 1243,
1284, 1324, 1364, 1405, 1445, 1485, 1526, 1566, 1607, 1647, 1688, 1729, 1769, 1810, 1851, 1891,
1932, 1973, 2014, 2054, 2095, 2136, 2177, 2218, 2259, 2300, 2341, 2382, 2424, 2465, 2506, 2547,
2589, 2630, 2672, 2713, 2755, 2796, 2838, 2880, 2921, 2963, 3005, 3047, 3089, 3131, 3173, 3215,
3257, 3300, 3342, 3384, 3427, 3469, 3512, 3554, 3597, 3640, 3683, 3726, 3769, 3812, 3855, 3898,
3941, 3985, 4028, 4072, 4115, 4159, 4203, 4246, 4290, 4334, 4379, 4423, 4467, 4511, 4556, 4601,
4645, 4690, 4735, 4780, 4825, 4870, 4916, 4961, 5007, 5052, 5098, 5144, 5190, 5236, 5282, 5329,
5375, 5422, 5469, 5515, 5562, 5610, 5657, 5704, 5752, 5800, 5848, 5896, 5944, 5992, 6041, 6089,
6138, 6187, 6236, 6286, 6335, 6385, 6435, 6485, 6535, 6586, 6637, 6687, 6739, 6790, 6841, 6893,
6945, 6997, 7050, 7102, 7155, 7208, 7262, 7315, 7369, 7423, 7478, 7532, 7587, 7643, 7698, 7754,
7810, 7867, 7923, 7981, 8038, 8096, 8154, 8213, 8271, 8331, 8390, 8450, 8511, 8572, 8633, 8695,
8757, 8820, 8883, 8947, 9011, 9076, 9141, 9207, 9273, 9340, 9407, 9476, 9545, 9614, 9684, 9755,
9827, 9900, 9973, 10047, 10122, 10198, 10275, 10353, 10432, 10512, 10593, 10675, 10759, 10844, 10930, 11018,
11107, 11198, 11290, 11385, 11481, 11580, 11681, 11784, 11890, 11999, 12111, 12226, 12346, 12469, 12597, 12730,
12870, 13017, 13171, 13336, 13513, 13705, 13917, 14157, 14442, 14813};
static const int16_t sin_lookup_table[250] = {
0, 63, 126, 188, 251, 314, 377, 440, 502, 565, 628, 691, 753, 816, 879, 941, 1004, 1066,
1129, 1191, 1253, 1316, 1378, 1440, 1502, 1564, 1626, 1688, 1750, 1812, 1874, 1935, 1997, 2059, 2120, 2181,
2243, 2304, 2365, 2426, 2487, 2548, 2608, 2669, 2730, 2790, 2850, 2910, 2970, 3030, 3090, 3150, 3209, 3269,
3328, 3387, 3446, 3505, 3564, 3623, 3681, 3740, 3798, 3856, 3914, 3971, 4029, 4086, 4144, 4201, 4258, 4315,
4371, 4428, 4484, 4540, 4596, 4652, 4707, 4762, 4818, 4873, 4927, 4982, 5036, 5090, 5144, 5198, 5252, 5305,
5358, 5411, 5464, 5516, 5569, 5621, 5673, 5724, 5776, 5827, 5878, 5929, 5979, 6029, 6079, 6129, 6179, 6228,
6277, 6326, 6374, 6423, 6471, 6518, 6566, 6613, 6660, 6707, 6753, 6800, 6845, 6891, 6937, 6982, 7026, 7071,
7115, 7159, 7203, 7247, 7290, 7333, 7375, 7417, 7459, 7501, 7543, 7584, 7624, 7665, 7705, 7745, 7785, 7824,
7863, 7902, 7940, 7978, 8016, 8053, 8090, 8127, 8163, 8200, 8235, 8271, 8306, 8341, 8375, 8409, 8443, 8477,
8510, 8543, 8575, 8607, 8639, 8671, 8702, 8733, 8763, 8793, 8823, 8852, 8881, 8910, 8938, 8966, 8994, 9021,
9048, 9075, 9101, 9127, 9152, 9178, 9202, 9227, 9251, 9274, 9298, 9321, 9343, 9365, 9387, 9409, 9430, 9451,
9471, 9491, 9511, 9530, 9549, 9567, 9585, 9603, 9620, 9637, 9654, 9670, 9686, 9701, 9716, 9731, 9745, 9759,
9773, 9786, 9799, 9811, 9823, 9834, 9846, 9856, 9867, 9877, 9887, 9896, 9905, 9913, 9921, 9929, 9936, 9943,
9950, 9956, 9961, 9967, 9972, 9976, 9980, 9984, 9987, 9990, 9993, 9995, 9997, 9998, 9999, 10000};
float sign(float y)
{
return (0 < y) - (y < 0);
}
float asin_lookup(float x)
{
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
{
return max;
}
else if (index < num_entries - 1)
{
return (float)asin_lookup_table[index] / scale
+ dx * (float)(asin_lookup_table[index + 1] - asin_lookup_table[index]) / scale;
}
else
{
return (float)asin_lookup_table[index] / scale
+ dx * (float)(asin_lookup_table[index] - asin_lookup_table[index - 1]) / scale;
}
}
float turboacos(float x)
{
if (x < 0)
return M_PI + asin_lookup(-x);
else
return M_PI - asin_lookup(x);
}
float turboasin(float x)
{
if (x < 0)
return -asin_lookup(-x);
else
return asin_lookup(x);
}
float sin_lookup(float x)
{
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
return max;
else if (index < num_entries - 1)
return (float)sin_lookup_table[index] / scale
+ dx * (float)(sin_lookup_table[index + 1] - sin_lookup_table[index]) / scale;
else
return (float)sin_lookup_table[index] / scale
+ dx * (float)(sin_lookup_table[index] - sin_lookup_table[index - 1]) / scale;
}
float turbosin(float x)
{
while (x > M_PI) x -= 2.0 * M_PI;
while (x <= -M_PI) x += 2.0 * M_PI;
if (0 <= x && x <= M_PI / 2.0)
return sin_lookup(x);
else if (-M_PI / 2.0 <= x && x < 0)
return -sin_lookup(-x);
else if (M_PI / 2.0 < x)
return sin_lookup(M_PI - x);
else
return -sin_lookup(x + M_PI);
}
float turbocos(float x)
{
return turbosin(x + M_PI);
}
float atan_lookup(float x)
{
if (x < 0)
return -1 * atan_lookup(-1 * x);
if (x > 1.0)
return M_PI - atan_lookup(1.0 / x);
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
return max;
else if (index < num_entries - 1)
return (float)atan_lookup_table[index] / scale
+ dx * (float)(atan_lookup_table[index + 1] - atan_lookup_table[index]) / scale;
else
return (float)atan_lookup_table[index] / scale
+ dx * (float)(atan_lookup_table[index] - atan_lookup_table[index - 1]) / scale;
}
float turboatan2(float y, float x)
{
if (y == 0)
{
if (x < 0)
return M_PI;
else
return 0;
}
else if (x == 0)
{
return M_PI / 2.0 * sign(y);
}
else
{
float arctan = atan_lookup(x / y);
if (y > 0)
return M_PI / 2.0 - arctan;
else if (y < 0)
return -M_PI / 2.0 - arctan;
else if (x < 0)
return arctan + M_PI;
else
return arctan;
}
}
double turbopow(double a, double b)
{
union
{
double d;
int x[2];
} u = {a};
u.x[1] = (int)(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
}
float turboInvSqrt(float x)
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = x * 0.5F;
y = x;
i = *(long*)&y; // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1);
y = *(float*)&i;
y = y * (threehalfs - (x2 * y * y)); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
| 40.19084 | 115 | 0.624501 | WangGY-Pro |
ed2361d4d9657c4cf13a717dbaa5fc190ed17e7b | 19,733 | cpp | C++ | ImageDetectionAccessPoint/CardAreaDetection.cpp | rWarder4/ImageDetectionAccessPoint | 43e4d1ece0f82e8b336fe99573432d3d26abdb69 | [
"MIT"
] | null | null | null | ImageDetectionAccessPoint/CardAreaDetection.cpp | rWarder4/ImageDetectionAccessPoint | 43e4d1ece0f82e8b336fe99573432d3d26abdb69 | [
"MIT"
] | null | null | null | ImageDetectionAccessPoint/CardAreaDetection.cpp | rWarder4/ImageDetectionAccessPoint | 43e4d1ece0f82e8b336fe99573432d3d26abdb69 | [
"MIT"
] | null | null | null | #include "CardAreaDetection.h"
#include <opencv2/videostab/ring_buffer.hpp>
// defines includes
#include <opencv2\imgcodecs\imgcodecs_c.h>
#include <opencv2\imgproc\types_c.h>
using namespace cv;
IDAP::CardAreaDetection::CardAreaDetection(int _id, int _playerID, int _sizeID, int _xPos, int _yPos, int _width, int _height, int imageWidth, int imageHeight, float mmInPixel, bool turn)
{
id = _id;
playerID = _playerID;
sizeID = _sizeID;
posX = _xPos;
posY = _yPos;
turned = turn;
// to over come the inaccuracy of calibration, the roi is 40 % bigger
const float bigger = 0.4;
const float deltaWidth = (_width / mmInPixel) * bigger;
const float deltaHeight = (_height / mmInPixel) * bigger;
const float newPosX = (posX * (imageWidth / 100.f)) - deltaWidth / 2.f;
const float newPosY = (posY * (imageHeight / 100.f)) - deltaHeight / 2.f;
if (!turned)
{
roi = cv::Rect(newPosX, newPosY, (_width / mmInPixel) + deltaWidth, (_height / mmInPixel) + deltaHeight);
const float ratio = static_cast<float>(roi.height) / static_cast<float>(roi.width);
sizeTM = cv::Size(CARD_MATCHING_WIDTH*(1.f + bigger), CARD_MATCHING_WIDTH*(1.f + bigger)*ratio);
}
else
{
roi = cv::Rect(newPosX, newPosY, (_height / mmInPixel) + deltaHeight, (_width / mmInPixel) + deltaWidth);
const float ratio = static_cast<float>(roi.width) / static_cast<float>(roi.height);
sizeTM = cv::Size(CARD_MATCHING_WIDTH*(1.f + bigger)*ratio, CARD_MATCHING_WIDTH*(1.f + bigger));
}
initState = true;
results = new TopThree();
}
IDAP::CardAreaDetection::~CardAreaDetection()
{
delete(results);
}
void IDAP::CardAreaDetection::isCardChanged(uint16_t& errorCode, cv::Mat currentFrame, std::vector<std::pair<int, cv::Mat>>& cardDataReference, std::vector<std::pair<int, cv::Mat>>& cardDataGradientReference, cv::Mat meanCardGrad, uint16_t& cardType) const
{
// cut roi from frame, settle up card in it, set the right direction and perform template matching
const cv::Mat area = currentFrame(roi);
// grayscale
cv::Mat gray;
cv::cvtColor(area, gray, cv::COLOR_RGB2GRAY);
// resize area
cv::Mat areaTM;
cv::resize(gray, areaTM, sizeTM);
// turn area if needed
if(turned)
{
cv::rotate(areaTM, areaTM, ROTATE_90_COUNTERCLOCKWISE);
}
// create gradient version
const int scale = 1;
const int delta = 0;
const int ddepth = CV_16S;
cv::Mat grad_x, grad_y;
cv::Mat abs_grad_x, abs_grad_y;
cv::Mat grad;
// Gradient X
Sobel(areaTM, grad_x, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
// Gradient Y
Sobel(areaTM, grad_y, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(grad_y, abs_grad_y);
// approximate total gradient calculation
cv::addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
cv::Mat img_display, result;
area.copyTo(img_display);
const int result_cols = areaTM.cols - meanCardGrad.cols + 1;
const int result_rows = areaTM.rows - meanCardGrad.rows + 1;
//cv::imshow("img", grad);
//cv::imshow("templ", meanCardGrad);
result.create(result_rows, result_cols, CV_32FC1);
cv::matchTemplate(grad, meanCardGrad, result, CV_TM_CCORR_NORMED);
double minVal; double maxVal;
cv::Point minLoc;
cv::Point maxLoc;
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());
const float meanValue = cv::mean(grad)[0];
if(meanValue >= MIN_MEAN_VALUE && maxVal >= TEMPLATE_MATCH_SCORE_MIN)
{
// perform SURF on imput image
// Detect and describe interest points using SURF Detector and Descriptor.
const int minHessian = 500; // min Hessian was experimentaly set, to obtain at least 8 matches on correct card class
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();
detector->setHessianThreshold(minHessian);
std::vector<KeyPoint> interestPointsArea;
Mat interestPointsAreaDesc;
detector->detectAndCompute(area, Mat(), interestPointsArea, interestPointsAreaDesc);
// classify using SURF and FLANN
results->SetMin(true);
for (std::vector<std::pair<int, cv::Mat>>::iterator it = cardDataReference.begin(); it != cardDataReference.end(); ++it)
{
// ----------------------------------- FLANN -------------------------------------
const uint16_t templCardType = static_cast<uint16_t>(it->first);
std::vector<KeyPoint> interestPointTempl;
Mat interestPointTemplDesc;
detector->detectAndCompute(it->second, Mat(), interestPointTempl, interestPointTemplDesc);
// Matching descriptor vectors using FLANN matcher - searching for nearest neighbors
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(interestPointsAreaDesc, interestPointTemplDesc, matches);
double maxDist = 0; double minDist = 100;
//-- Quick calculation of max and min distances between keypoints
for (int i = 0; i < interestPointsAreaDesc.rows; i++)
{
const double dist = matches[i].distance;
if (dist < minDist) minDist = dist;
if (dist > maxDist) maxDist = dist;
}
std::map<float, int> goodMatchesDistance;
// filter only good matches - the ones which are at worst two times minimal distance
std::vector< DMatch > good_matches;
for (int i = 0; i < interestPointsAreaDesc.rows; i++)
{
if (matches[i].distance <= max(2 * minDist, 0.02))
{
good_matches.push_back(matches[i]);
goodMatchesDistance.insert(std::make_pair(matches[i].distance, i));
}
}
// if at least 8 good matches were found, compare the sum of distance of these good matches with the previously classes
// if it is better, put this class to TopThree result
// the TopThree classes are then sorted by the best match -> this was experimentaly tested and lead to better result than using all 8 best matches
if (goodMatchesDistance.size() >= 8)
{
float bestEightSum = 0.f;
int count = 0;
for (std::map<float, int>::iterator it = goodMatchesDistance.begin(); it != goodMatchesDistance.end(); ++it)
{
if (++count > 8)
break;
bestEightSum += it->first;
}
if (results->isBetter(bestEightSum))
{
results->TryAddNew(templCardType, bestEightSum);
}
}
}
// return the class the card fit the best
cardType = results->GetFirst();
results->Init();
}
else
{
// return no card, if no card is detected
cardType = IDAP::BangCardTypes::NONE;
}
}
void IDAP::CardAreaDetection::CardDetectionTester(std::vector<std::pair<int, cv::Mat>> cardDataReference)
{
std::map<int, int> classifications;
for(int i = 1; i < 32; ++i)
{
classifications.insert(std::make_pair(i, 0));
}
const bool templateMethod = false;
const std::string path = "CardDetectionData/BANG_A";
const auto match_method = CV_TM_CCORR_NORMED;
if (templateMethod)
results->SetMin(false);
else
results->SetMin(true);
// variable settings for gradient
const int scale = 1;
const int delta = 0;
const int ddepth = CV_16S;
// list all files in given folder and load them to memory and provide them to card area detection for template matching
for (auto &file : std::experimental::filesystem::directory_iterator(path))
{
cv::Mat img = cv::imread(file.path().string().c_str(), CV_LOAD_IMAGE_COLOR);
std::cout << file.path().string().c_str() << std::endl;
if (file.path().string().find("Bang_06.png") == std::string::npos)
continue;
// variables
cv::Mat rotImg, templ, imgGray, templGray, imgGrayDenoise;
cv::Mat gradTempl, gradImage;
cv::Mat imgGradFinal;
// perform classification
if(templateMethod)
{
//----------------------------- TEMPLATE MATCHING -------------------------------
// hought transform to turn right -------------------------------------------------
cv::Mat edges, gray, dil, ero, dst, cdst;
cv::cvtColor(img, gray, CV_BGR2GRAY);
cv::Canny(gray, edges, 85, 255);
cv::cvtColor(edges, cdst, COLOR_GRAY2BGR);
cv::Mat cdstP = cdst.clone();
std::vector<Vec2f> lines; // will hold the results of the detection
// Probabilistic Line Transform
std::vector<Vec4i> linesP; // will hold the results of the detection
HoughLinesP(edges, linesP, 1, CV_PI / 180, 50, 50, 10); // runs the actual detection
// Draw the lines
float angleFin = 0.f;
float linesUsed = 0;
for (size_t i = 0; i < linesP.size(); i++)
{
Vec4i l = linesP[i];
line(cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
Point p1, p2;
p1 = Point(l[0], l[1]);
p2 = Point(l[2], l[3]);
// calculate angle in radian, to degrees: angle * 180 / PI
float angle = atan2(p1.y - p2.y, p1.x - p2.x) * 180 / CV_PI;
if (angle > 0)
angle -= 90;
else
angle += 90;
// limit the lines which will be used, to limit errors
if ((angle < MAX_LINE_ANGLE_FOR_HOUGH && angle > 0) ||
(angle > -MAX_LINE_ANGLE_FOR_HOUGH && angle < 0))
{
angleFin += angle;
++linesUsed;
}
}
if(linesUsed > 0)
angleFin /= linesUsed;
// rotate img
const cv::Mat rot = getRotationMatrix2D(Point2f(img.cols / 2, img.rows / 2), angleFin, 1);
cv::warpAffine(img, rotImg, rot, Size(img.cols, img.rows));
cv::cvtColor(rotImg, imgGray, CV_BGR2GRAY);
// gradient of input image
cv::Mat imgGradX, imgGradY;
cv::Mat absGradX, absGradY;
/// Gradient X
Sobel(imgGray, imgGradX, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(imgGradX, absGradX);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel(imgGray, imgGradY, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(imgGradY, absGradY);
// combine gradient
cv::addWeighted(absGradX, 0.5, absGradY, 0.5, 0, imgGradFinal);
}
for (std::vector<std::pair<int, cv::Mat>>::iterator it = cardDataReference.begin(); it != cardDataReference.end(); ++it)
{
uint16_t templCardType = static_cast<uint16_t>(it->first);
cv::Mat rawtempl = it->second;
cv::Mat mask;
// ----------------------------------- FLANN -------------------------------------
if (!templateMethod)
{
cv::Mat img_1, img_2;
img.copyTo(img_1);
rawtempl.copyTo(img_2);
const int minHessian = 500;
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();
detector->setHessianThreshold(minHessian);
std::vector<KeyPoint> keypoints_1, keypoints_2;
Mat descriptors_1, descriptors_2;
detector->detectAndCompute(img_1, Mat(), keypoints_1, descriptors_1);
detector->detectAndCompute(img_2, Mat(), keypoints_2, descriptors_2);
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(descriptors_1, descriptors_2, matches);
double max_dist = 0; double min_dist = 100;
for (int i = 0; i < descriptors_1.rows; i++)
{
const double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
//printf("-- Max dist : %f \n", max_dist);
//printf("-- Min dist : %f \n", min_dist);
std::map<float, int> goodMatchesDistance;
std::vector< DMatch > good_matches;
for (int i = 0; i < descriptors_1.rows; i++)
{
if (matches[i].distance <= max(2 * min_dist, 0.02))
{
good_matches.push_back(matches[i]);
goodMatchesDistance.insert(std::make_pair(matches[i].distance, i));
}
}
double evalNew = static_cast<double>(good_matches.size()) / static_cast<double>(matches.size());
//printf("EVAL: %d | %d : %f\n", static_cast<int>(good_matches.size()), static_cast<int>(matches.size()), eval);
if (goodMatchesDistance.size() >= 8)
{
float bestFive = 0.f;
int count = 0;
for (std::map<float, int>::iterator it2 = goodMatchesDistance.begin(); it2 != goodMatchesDistance.end(); ++it2)
{
if (++count > 8)
break;
bestFive += it2->first;
}
//std::cout << "Chesking add: " << templCardType << ", " << bestFive << std::endl;
if (results->isBetter(bestFive))
{
results->TryAddNew(templCardType, bestFive);
}
}
//-- Draw only "good" matches
Mat img_matches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
//-- Show detected matches
//imshow("Good Matches", img_matches);
//imwrite("goodMatches.png", img_matches);
for (int i = 0; i < (int)good_matches.size(); i++)
{
//printf("-- Good Match [%d] Keypoint 1: %d -- Keypoint 2: %d \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx);
}
//cv::waitKey(0);
}
else
{
cv::cvtColor(rawtempl, templGray, CV_BGR2GRAY);
// gradient of input image
cv::Mat templGradX, templGradY;
cv::Mat absGradXTempl, absGradYTempl;
cv::Mat templGradFinal;
/// Gradient X
Sobel(templGray, templGradX, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(templGradX, absGradXTempl);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel(templGray, templGradY, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(templGradY, absGradYTempl);
// combine gradient
cv::addWeighted(absGradXTempl, 0.5, absGradYTempl, 0.5, 0, templGradFinal);
cv::Point matchLoc;
/*for (float i = 1; i > 0.5; i -= 0.1)
{
// scale template
cv::Size newSize(rawtempl.cols*i, rawtempl.rows*i);
cv::resize(templGradFinal, templGradFinal, newSize);*/
cv::Mat img_display, result;
gradImage.copyTo(img_display);
int result_cols = imgGradFinal.cols - templGradFinal.cols + 1;
int result_rows = imgGradFinal.rows - templGradFinal.rows + 1;
result.create(result_rows, result_cols, CV_32FC1);
matchTemplate(imgGradFinal, templGradFinal, result, match_method);
double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
matchLoc = maxLoc;
results->TryAddNew(templCardType, maxVal);
cv::Mat locationMatch;
imgGradFinal.copyTo(locationMatch);
const cv::Rect rect(matchLoc.x, matchLoc.y, templGradFinal.size().width, templGradFinal.size().height);
cv::rectangle(locationMatch, rect, Scalar(255,0,0));
//}
}
}
//std::cout << "result for " << file.path().string() << ": " << results->GetFirst() << ", " << results->GetSecond() << ", " << results->GetThird() << std::endl;
//printf("eval: %f, %f, %f\n", results->firstEval, results->secondEval, results->thirdEval);
classifications.at(results->GetFirst()) += 1;
results->Init();
//cv::waitKey(0);
}
for(int i = 1; i < 32; ++i)
{
if(classifications.at(i) > 0)
std::cout << "template ID:" << i << " -> " << classifications.at(i) << std::endl;
}
//cv::waitKey(0);
}
void IDAP::TopThree::Init()
{
first = 0;
second = 0;
third = 0;
bestPoints = std::numeric_limits<double>::max();
if (min)
{
firstEval = std::numeric_limits<double>::max();
secondEval = std::numeric_limits<double>::max();
thirdEval = std::numeric_limits<double>::max();
}
else
{
firstEval = std::numeric_limits<double>::min();
secondEval = std::numeric_limits<double>::min();
thirdEval = std::numeric_limits<double>::min();
}
}
void IDAP::TopThree::TryAddNew(uint16_t cardType, float eval)
{
if (min)
{
if (eval < thirdEval)
{
// new top three
third = cardType;
thirdEval = eval;
SortTopThree();
}
}
else
{
if (eval > thirdEval)
{
// new top three
third = cardType;
thirdEval = eval;
SortTopThree();
}
}
}
bool IDAP::TopThree::isBetter(float val)
{
double curVal = static_cast<double>(val);
if (curVal < bestPoints)
{
bestPoints = curVal;
return true;
}
return false;
}
void IDAP::TopThree::SortTopThree()
{
if (min)
{
if (thirdEval < secondEval)
{
std::swap(third, second);
std::swap(thirdEval, secondEval);
}
if(secondEval < firstEval)
{
std::swap(first, second);
std::swap(firstEval, secondEval);
}
}
else
{
if (thirdEval > secondEval)
{
std::swap(third, second);
std::swap(thirdEval, secondEval);
}
if (secondEval > firstEval)
{
std::swap(first, second);
std::swap(firstEval, secondEval);
}
}
}
| 39.075248 | 257 | 0.539654 | rWarder4 |
ed2674d20a72a0a493fa68eb592abcf456cb9c53 | 28,956 | cpp | C++ | Source/CLI/Global.cpp | JeromeMartinez/RAWcooked | 41379cc9ebb9511eb7445dce7a4a9064125a92f0 | [
"BSD-2-Clause"
] | null | null | null | Source/CLI/Global.cpp | JeromeMartinez/RAWcooked | 41379cc9ebb9511eb7445dce7a4a9064125a92f0 | [
"BSD-2-Clause"
] | null | null | null | Source/CLI/Global.cpp | JeromeMartinez/RAWcooked | 41379cc9ebb9511eb7445dce7a4a9064125a92f0 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#include "CLI/Global.h"
#include "CLI/Help.h"
#include <iostream>
#include <cstring>
#include <iomanip>
#include <thread>
#if defined(_WIN32) || defined(_WINDOWS)
#include <direct.h>
#define getcwd _getcwd
#else
#include <unistd.h>
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Glue
void global_ProgressIndicator_Show(global* G)
{
G->ProgressIndicator_Show();
}
//---------------------------------------------------------------------------
int global::SetOutputFileName(const char* FileName)
{
OutputFileName = FileName;
OutputFileName_IsProvided = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetBinName(const char* FileName)
{
BinName = FileName;
return 0;
}
//---------------------------------------------------------------------------
int global::SetLicenseKey(const char* Key, bool StoreIt)
{
LicenseKey = Key;
StoreLicenseKey = StoreIt;
return 0;
}
//---------------------------------------------------------------------------
int global::SetSubLicenseId(uint64_t Id)
{
if (!Id || Id >= 127)
{
cerr << "Error: sub-licensee ID must be between 1 and 126.\n";
return 1;
}
SubLicenseId = Id;
return 0;
}
//---------------------------------------------------------------------------
int global::SetSubLicenseDur(uint64_t Dur)
{
if (Dur > 12)
{
cerr << "Error: sub-licensee duration must be between 0 and 12.\n";
return 1;
}
SubLicenseDur = Dur;
return 0;
}
//---------------------------------------------------------------------------
int global::SetDisplayCommand()
{
DisplayCommand = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetAcceptFiles()
{
AcceptFiles = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheck(bool Value)
{
Actions.set(Action_Check, Value);
Actions.set(Action_CheckOptionIsSet);
if (Value)
return SetDecode(false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetQuickCheck()
{
Actions.set(Action_Check, false);
Actions.set(Action_CheckOptionIsSet, false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheck(const char* Value, int& i)
{
if (Value && (strcmp(Value, "0") == 0 || strcmp(Value, "partial") == 0))
{
SetCheckPadding(false);
++i; // Next argument is used
cerr << "Warning: \" --check " << Value << "\" is deprecated, use \" --no-check-padding\" instead.\n" << endl;
return 0;
}
if (Value && (strcmp(Value, "1") == 0 || strcmp(Value, "full") == 0))
{
SetCheckPadding(true);
++i; // Next argument is used
cerr << "Warning: \" --check " << Value << "\" is deprecated, use \" --check-padding\" instead.\n" << endl;
return 0;
}
SetCheck(true);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheckPadding(bool Value)
{
Actions.set(Action_CheckPadding, Value);
Actions.set(Action_CheckPaddingOptionIsSet);
return 0;
}
//---------------------------------------------------------------------------
int global::SetQuickCheckPadding()
{
Actions.set(Action_CheckPadding, false);
Actions.set(Action_CheckPaddingOptionIsSet, false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetAcceptGaps(bool Value)
{
Actions.set(Action_AcceptGaps, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCoherency(bool Value)
{
Actions.set(Action_Coherency, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetConch(bool Value)
{
Actions.set(Action_Conch, Value);
if (Value)
{
SetDecode(false);
SetEncode(false);
}
return 0;
}
//---------------------------------------------------------------------------
int global::SetDecode(bool Value)
{
Actions.set(Action_Decode, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetEncode(bool Value)
{
Actions.set(Action_Encode, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetInfo(bool Value)
{
Actions.set(Action_Info, Value);
if (Value)
{
SetDecode(false);
SetEncode(false);
}
return 0;
}
//---------------------------------------------------------------------------
int global::SetFrameMd5(bool Value)
{
Actions.set(Action_FrameMd5, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetFrameMd5FileName(const char* FileName)
{
FrameMd5FileName = FileName;
return 0;
}
//---------------------------------------------------------------------------
int global::SetHash(bool Value)
{
Actions.set(Action_Hash, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetAll(bool Value)
{
if (int ReturnValue = SetInfo(Value))
return ReturnValue;
if (int ReturnValue = SetConch(Value))
return ReturnValue;
if (int ReturnValue = (Value?SetCheck(true):SetQuickCheck())) // Never implicitely set no check
return ReturnValue;
if (int ReturnValue = (Value && SetCheckPadding(Value))) // Never implicitely set no check padding
return ReturnValue;
if (int ReturnValue = SetAcceptGaps(Value))
return ReturnValue;
if (int ReturnValue = SetCoherency(Value))
return ReturnValue;
if (int ReturnValue = SetDecode(Value))
return ReturnValue;
if (int ReturnValue = SetEncode(Value))
return ReturnValue;
if (int ReturnValue = SetHash(Value))
return ReturnValue;
return 0;
}
//---------------------------------------------------------------------------
int Error_NotTested(const char* Option1, const char* Option2 = NULL)
{
cerr << "Error: option " << Option1;
if (Option2)
cerr << ' ' << Option2;
cerr << " not yet tested.\nPlease contact info@mediaarea.net if you want support of such option." << endl;
return 1;
}
//---------------------------------------------------------------------------
int Error_Missing(const char* Option1)
{
cerr << "Error: missing argument for option '" << Option1 << "'." << endl;
return 1;
}
//---------------------------------------------------------------------------
int global::SetOption(const char* argv[], int& i, int argc)
{
if (strcmp(argv[i], "-c:a") == 0)
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (strcmp(argv[i], "copy") == 0)
{
OutputOptions["c:a"] = argv[i];
License.Encoder(encoder::PCM);
return 0;
}
if (strcmp(argv[i], "flac") == 0)
{
OutputOptions["c:a"] = argv[i];
License.Encoder(encoder::FLAC);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-c:v"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "ffv1"))
{
OutputOptions["c:v"] = argv[i];
License.Encoder(encoder::FFV1);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-coder"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1")
|| !strcmp(argv[i], "2"))
{
OutputOptions["coder"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-context"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1"))
{
OutputOptions["context"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-f"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "matroska"))
{
OutputOptions["f"] = argv[i];
return 0;
}
return 0;
}
if (!strcmp(argv[i], "-framerate"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (atof(argv[i]))
{
VideoInputOptions["framerate"] = argv[i];
License.Feature(feature::InputOptions);
return 0;
}
return 0;
}
if (!strcmp(argv[i], "-g"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (atoi(argv[i]))
{
OutputOptions["g"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
cerr << "Invalid \"" << argv[i - 1] << " " << argv[i] << "\" value, it must be a number\n";
return 1;
}
if (!strcmp(argv[i], "-level"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1")
|| !strcmp(argv[i], "3"))
{
OutputOptions["level"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-loglevel"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "error")
|| !strcmp(argv[i], "warning"))
{
OutputOptions["loglevel"] = argv[i];
License.Feature(feature::GeneralOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (strcmp(argv[i], "-n") == 0)
{
OutputOptions["n"] = string();
OutputOptions.erase("y");
Mode = AlwaysNo; // Also RAWcooked itself
License.Feature(feature::GeneralOptions);
return 0;
}
if (!strcmp(argv[i], "-slicecrc"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1"))
{
OutputOptions["slicecrc"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-slices"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
int SliceCount = atoi(argv[i]);
if (SliceCount) //TODO: not all slice counts are accepted by FFmpeg, we should filter
{
OutputOptions["slices"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-threads"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
OutputOptions["threads"] = argv[i];
License.Feature(feature::GeneralOptions);
return 0;
}
if (strcmp(argv[i], "-y") == 0)
{
OutputOptions["y"] = string();
OutputOptions.erase("n");
Mode = AlwaysYes; // Also RAWcooked itself
License.Feature(feature::GeneralOptions);
return 0;
}
return Error_NotTested(argv[i]);
}
//---------------------------------------------------------------------------
int global::ManageCommandLine(const char* argv[], int argc)
{
if (argc < 2)
return Usage(argv[0]);
AttachmentMaxSize = (size_t)-1;
IgnoreLicenseKey = !License.IsSupported_License();
SubLicenseId = 0;
SubLicenseDur = 1;
ShowLicenseKey = false;
StoreLicenseKey = false;
DisplayCommand = false;
AcceptFiles = false;
OutputFileName_IsProvided = false;
Quiet = false;
Actions.set(Action_Encode);
Actions.set(Action_Decode);
Actions.set(Action_Coherency);
Hashes = hashes(&Errors);
ProgressIndicator_Thread = NULL;
for (int i = 1; i < argc; i++)
{
if ((argv[i][0] == '.' && argv[i][1] == '\0')
|| (argv[i][0] == '.' && (argv[i][1] == '/' || argv[i][1] == '\\') && argv[i][2] == '\0'))
{
//translate to "../xxx" in order to get the top level directory name
char buff[FILENAME_MAX];
if (getcwd(buff, FILENAME_MAX))
{
string Arg = buff;
size_t Path_Pos = Arg.find_last_of("/\\");
Arg = ".." + Arg.substr(Path_Pos);
Inputs.push_back(Arg);
}
else
{
cerr << "Error: " << argv[i] << " can not be transformed to a directory name." << endl;
return 1;
}
}
else if (strcmp(argv[i], "--all") == 0)
{
int Value = SetAll(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--attachment-max-size") == 0 || strcmp(argv[i], "-s") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
AttachmentMaxSize = atoi(argv[++i]);
License.Feature(feature::GeneralOptions);
}
else if ((strcmp(argv[i], "--bin-name") == 0 || strcmp(argv[i], "-b") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetBinName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--check") == 0)
{
if (i + 1 < argc)
{
// Deprecated version handling
int Value = SetCheck(argv[i + 1], i);
if (Value)
return Value;
}
else
{
int Value = SetCheck(true);
License.Feature(feature::GeneralOptions);
if (Value)
return Value;
}
}
else if (strcmp(argv[i], "--check-padding") == 0)
{
int Value = SetCheckPadding(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--accept-gaps") == 0)
{
int Value = SetAcceptGaps(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--coherency") == 0)
{
int Value = SetCoherency(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--conch") == 0)
{
int Value = SetConch(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--display-command") == 0 || strcmp(argv[i], "-d") == 0))
{
int Value = SetDisplayCommand();
if (Value)
return Value;
License.Feature(feature::GeneralOptions);
}
else if (strcmp(argv[i], "--decode") == 0)
{
int Value = SetDecode(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--encode") == 0)
{
int Value = SetEncode(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--framemd5") == 0)
{
int Value = SetFrameMd5(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--framemd5-name") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetFrameMd5FileName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--hash") == 0)
{
int Value = SetHash(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--file") == 0)
{
int Value = SetAcceptFiles();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
{
int Value = Help(argv[0]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--info") == 0)
{
int Value = SetInfo(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--license") == 0 || strcmp(argv[i], "--licence") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetLicenseKey(argv[++i], false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-check") == 0)
{
int Value = SetCheck(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-check-padding") == 0)
{
int Value = SetCheckPadding(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-coherency") == 0)
{
int Value = SetCoherency(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-conch") == 0)
{
int Value = SetConch(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-decode") == 0)
{
int Value = SetDecode(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-encode") == 0)
{
int Value = SetEncode(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-hash") == 0)
{
int Value = SetHash(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-info") == 0)
{
int Value = SetInfo(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--none") == 0)
{
int Value = SetAll(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quick-check") == 0)
{
int Value = SetQuickCheck();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quick-check-padding") == 0)
{
int Value = SetQuickCheckPadding();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--version") == 0)
{
int Value = Version();
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--output-name") == 0 || strcmp(argv[i], "-o") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetOutputFileName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quiet") == 0)
{
Quiet = true;
License.Feature(feature::GeneralOptions);
}
else if ((strcmp(argv[i], "--rawcooked-file-name") == 0 || strcmp(argv[i], "-r") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
rawcooked_reversibility_FileName = argv[++i];
}
else if (strcmp(argv[i], "--show-license") == 0 || strcmp(argv[i], "--show-licence") == 0)
{
ShowLicenseKey = true;
}
else if (strcmp(argv[i], "--sublicense") == 0 || strcmp(argv[i], "--sublicence") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
License.Feature(feature::SubLicense);
if (auto Value = SetSubLicenseId(atoi(argv[++i])))
return Value;
}
else if (strcmp(argv[i], "--sublicense-dur") == 0 || strcmp(argv[i], "--sublicence-dur") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
License.Feature(feature::SubLicense);
if (auto Value = SetSubLicenseDur(atoi(argv[++i])))
return Value;
}
else if ((strcmp(argv[i], "--store-license") == 0 || strcmp(argv[i], "--store-licence") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetLicenseKey(argv[++i], true);
if (Value)
return Value;
}
else if (argv[i][0] == '-' && argv[i][1] != '\0')
{
int Value = SetOption(argv, i, argc);
if (Value)
return Value;
}
else
Inputs.push_back(argv[i]);
}
// License
if (License.LoadLicense(LicenseKey, StoreLicenseKey))
return true;
if (!License.IsSupported())
{
cerr << "\nOne or more requested features are not supported with the current license key.\n";
cerr << "****** Please contact info@mediaarea.net for a quote or a temporary key." << endl;
if (!IgnoreLicenseKey)
return 1;
cerr << " Ignoring the license for the moment.\n" << endl;
}
if (License.ShowLicense(ShowLicenseKey, SubLicenseId, SubLicenseDur))
return 1;
if (Inputs.empty() && (ShowLicenseKey || SubLicenseId))
return 0;
return 0;
}
//---------------------------------------------------------------------------
int global::SetDefaults()
{
// Container format
if (OutputOptions.find("f") == OutputOptions.end())
OutputOptions["f"] = "matroska"; // Container format is Matroska
// Video format
if (OutputOptions.find("c:v") == OutputOptions.end())
OutputOptions["c:v"] = "ffv1"; // Video format is FFV1
// Audio format
if (OutputOptions.find("c:a") == OutputOptions.end())
OutputOptions["c:a"] = "flac"; // Audio format is FLAC
// FFV1 specific
if (OutputOptions["c:v"] == "ffv1")
{
if (OutputOptions.find("coder") == OutputOptions.end())
OutputOptions["coder"] = "1"; // Range Coder
if (OutputOptions.find("context") == OutputOptions.end())
OutputOptions["context"] = "1"; // Small context
if (OutputOptions.find("g") == OutputOptions.end())
OutputOptions["g"] = "1"; // Intra
if (OutputOptions.find("level") == OutputOptions.end())
OutputOptions["level"] = "3"; // FFV1 v3
if (OutputOptions.find("slicecrc") == OutputOptions.end())
OutputOptions["slicecrc"] = "1"; // Slice CRC on
// Check incompatible options
if (OutputOptions["level"] == "0" || OutputOptions["level"] == "1")
{
map<string, string>::iterator slices = OutputOptions.find("slices");
if (slices == OutputOptions.end() || slices->second != "1")
{
cerr << "\" -level " << OutputOptions["level"] << "\" does not permit slices, is it intended ? if so, add \" -slices 1\" to the command." << endl;
return 1;
}
}
}
return 0;
}
//---------------------------------------------------------------------------
void global::ProgressIndicator_Start(size_t Total)
{
if (ProgressIndicator_Thread)
return;
ProgressIndicator_Current = 0;
ProgressIndicator_Total = Total;
ProgressIndicator_Thread = new thread(global_ProgressIndicator_Show, this);
}
//---------------------------------------------------------------------------
void global::ProgressIndicator_Stop()
{
if (!ProgressIndicator_Thread)
return;
ProgressIndicator_Current = ProgressIndicator_Total;
ProgressIndicator_IsEnd.notify_one();
ProgressIndicator_Thread->join();
delete ProgressIndicator_Thread;
ProgressIndicator_Thread = NULL;
}
//---------------------------------------------------------------------------
// Progress indicator show
void global::ProgressIndicator_Show()
{
// Configure progress indicator precision
size_t ProgressIndicator_Value = (size_t)-1;
size_t ProgressIndicator_Frequency = 100;
streamsize Precision = 0;
cerr.setf(ios::fixed, ios::floatfield);
// Configure benches
using namespace chrono;
steady_clock::time_point Clock_Init = steady_clock::now();
steady_clock::time_point Clock_Previous = Clock_Init;
uint64_t FileCount_Previous = 0;
// Show progress indicator at a specific frequency
const chrono::seconds Frequency = chrono::seconds(1);
size_t StallDetection = 0;
mutex Mutex;
unique_lock<mutex> Lock(Mutex);
do
{
if (ProgressIndicator_IsPaused)
continue;
size_t ProgressIndicator_New = (size_t)(((float)ProgressIndicator_Current) * ProgressIndicator_Frequency / ProgressIndicator_Total);
if (ProgressIndicator_New == ProgressIndicator_Value)
{
StallDetection++;
if (StallDetection >= 4)
{
while (ProgressIndicator_New == ProgressIndicator_Value && ProgressIndicator_Frequency < 10000)
{
ProgressIndicator_Frequency *= 10;
ProgressIndicator_Value *= 10;
Precision++;
ProgressIndicator_New = (size_t)(((float)ProgressIndicator_Current) * ProgressIndicator_Frequency / ProgressIndicator_Total);
}
}
}
else
StallDetection = 0;
if (ProgressIndicator_New != ProgressIndicator_Value)
{
float FileRate = 0;
if (ProgressIndicator_Value != (size_t)-1)
{
steady_clock::time_point Clock_Current = steady_clock::now();
steady_clock::duration Duration = Clock_Current - Clock_Previous;
FileRate = (float)(ProgressIndicator_Current - FileCount_Previous) * 1000 / duration_cast<milliseconds>(Duration).count();
Clock_Previous = Clock_Current;
FileCount_Previous = ProgressIndicator_Current;
}
cerr << '\r';
cerr << "Analyzing files (" << setprecision(Precision) << ((float)ProgressIndicator_New) * 100 / ProgressIndicator_Frequency << "%)";
if (FileRate)
{
cerr << ", ";
cerr << setprecision(0) << FileRate;
cerr << " files/s";
}
cerr << " "; // Clean up in case there is less content outputed than the previous time
ProgressIndicator_Value = ProgressIndicator_New;
}
} while (ProgressIndicator_IsEnd.wait_for(Lock, Frequency) == cv_status::timeout && ProgressIndicator_Current != ProgressIndicator_Total);
// Show summary
cerr << '\r';
cerr << " \r"; // Clean up in case there is less content outputed than the previous time
}
| 32.461883 | 163 | 0.45355 | JeromeMartinez |
ed275cc17cde49f52def9dcc9f0c0470d9af7c14 | 1,617 | cpp | C++ | core/fxge/dib/fx_dib.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 16 | 2018-09-14T12:07:14.000Z | 2021-04-22T11:18:25.000Z | core/fxge/dib/fx_dib.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 1 | 2020-12-26T16:18:40.000Z | 2020-12-26T16:18:40.000Z | core/fxge/dib/fx_dib.cpp | yanxijian/pdfium | aba53245bf116a1d908f851a93236b500988a1ee | [
"Apache-2.0"
] | 6 | 2017-09-12T14:09:32.000Z | 2021-11-20T03:32:27.000Z | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxge/dib/fx_dib.h"
#include <tuple>
#include <utility>
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#if defined(OS_WIN)
static_assert(sizeof(FX_COLORREF) == sizeof(COLORREF),
"FX_COLORREF vs. COLORREF mismatch");
#endif
FXDIB_Format MakeRGBFormat(int bpp) {
switch (bpp) {
case 1:
return FXDIB_Format::k1bppRgb;
case 8:
return FXDIB_Format::k8bppRgb;
case 24:
return FXDIB_Format::kRgb;
case 32:
return FXDIB_Format::kRgb32;
default:
return FXDIB_Format::kInvalid;
}
}
FXDIB_ResampleOptions::FXDIB_ResampleOptions() = default;
bool FXDIB_ResampleOptions::HasAnyOptions() const {
return bInterpolateBilinear || bHalftone || bNoSmoothing || bLossy;
}
std::tuple<int, int, int, int> ArgbDecode(FX_ARGB argb) {
return std::make_tuple(FXARGB_A(argb), FXARGB_R(argb), FXARGB_G(argb),
FXARGB_B(argb));
}
std::pair<int, FX_COLORREF> ArgbToAlphaAndColorRef(FX_ARGB argb) {
return {FXARGB_A(argb), ArgbToColorRef(argb)};
}
FX_COLORREF ArgbToColorRef(FX_ARGB argb) {
return FXSYS_BGR(FXARGB_B(argb), FXARGB_G(argb), FXARGB_R(argb));
}
FX_ARGB AlphaAndColorRefToArgb(int a, FX_COLORREF colorref) {
return ArgbEncode(a, FXSYS_GetRValue(colorref), FXSYS_GetGValue(colorref),
FXSYS_GetBValue(colorref));
}
| 26.508197 | 80 | 0.710575 | yanxijian |
ed2fe22e3bebe19526b10a68bcb9cb728a082742 | 1,118 | cpp | C++ | codeforces/2020/round#630/C.cpp | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 5 | 2016-04-29T07:14:23.000Z | 2020-01-07T04:56:11.000Z | codeforces/2020/round#630/C.cpp | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | null | null | null | codeforces/2020/round#630/C.cpp | plusplus7/solutions | 31233c13ee2bd0da6a907a24adbaf5b49ebf843c | [
"CC0-1.0"
] | 1 | 2016-04-29T07:14:32.000Z | 2016-04-29T07:14:32.000Z | #include <bits/stdc++.h >
using namespace std;
int cnt[200005][26];
char s[200005];
int main()
{
int T;
scanf("%d", &T);
while (T--) {
int n, k;
scanf("%d%d", &n, &k);
scanf("%s", s);
for (int i=0; i<n; i++) {
for (int j=0; j<26; j++) {
cnt [i][j] = 0;
}
}
for (int i=0; i<n; i++) {
int x = i%k;
cnt[x][s[i]-'a'] ++;
}
int ans = 0;
for (int i=0; i<k/2; i++) {
int v = k-i-1;
int all = 0;
int m = 0;
for (int j=0; j<26; j++) {
cnt[i][j] += cnt[v][j];
all += cnt[i][j];
m = max(cnt[i][j], m);
}
ans += all-m;
}
if (k&1) {
int all = 0;
int m = 0;
int xx= k/2;
for (int j=0; j<26; j++) {
all += cnt[xx][j];
m = max(cnt[xx][j], m);
}
ans += all-m;
}
cout << ans << endl;
}
return 0;
}
| 20.703704 | 42 | 0.28712 | plusplus7 |
ed3090bc9abd62ac484ff5872db4b1682db29842 | 11,744 | cpp | C++ | src/system.cpp | marangisto/HAL | fa56b539f64b277fa122a010e4ee643463f58498 | [
"MIT"
] | 2 | 2019-09-12T04:12:16.000Z | 2020-09-23T19:13:06.000Z | src/system.cpp | marangisto/HAL | fa56b539f64b277fa122a010e4ee643463f58498 | [
"MIT"
] | 2 | 2019-09-10T13:47:50.000Z | 2020-02-24T03:27:47.000Z | src/system.cpp | marangisto/HAL | fa56b539f64b277fa122a010e4ee643463f58498 | [
"MIT"
] | 3 | 2019-08-31T12:58:28.000Z | 2020-03-26T22:56:34.000Z | #include <hal.h>
#include <algorithm>
namespace hal
{
using namespace device;
namespace internal
{
template<uint32_t x, uint32_t b, uint8_t nbits>
static constexpr uint32_t encode()
{
static_assert(x < (1 << nbits), "bit field overflow");
return ((x & (1 << 0)) ? (b << 0) : 0)
| ((x & (1 << 1)) ? (b << 1) : 0)
| ((x & (1 << 2)) ? (b << 2) : 0)
| ((x & (1 << 3)) ? (b << 3) : 0)
| ((x & (1 << 4)) ? (b << 4) : 0)
| ((x & (1 << 5)) ? (b << 5) : 0)
| ((x & (1 << 6)) ? (b << 6) : 0)
| ((x & (1 << 7)) ? (b << 7) : 0)
| ((x & (1 << 8)) ? (b << 8) : 0)
;
}
} // namespace internal
void sys_tick::delay_ms(uint32_t ms)
{
uint32_t now = ms_counter, then = now + ms;
while (ms_counter >= now && ms_counter < then)
; // busy wait
}
void sys_tick::delay_us(uint32_t us)
{
#if defined(STM32F051) || defined(STM32F072) || defined (STM32F767) || defined(STM32H743) || defined(STM32G070)
volatile uint32_t& c = STK.CVR;
const uint32_t c_max = STK.RVR;
#elif defined(STM32F103) || defined(STM32F411) || defined(STM32G431)
volatile uint32_t& c = STK.VAL;
const uint32_t c_max = STK.LOAD;
#else
static_assert(false, "no featured sys-tick micro-second delay");
#endif
const uint32_t fuzz = ticks_per_us - (ticks_per_us >> 2); // approx 3/4
const uint32_t n = us * ticks_per_us - fuzz;
const uint32_t now = c;
const uint32_t then = now >= n ? now - n : (c_max - n + now);
if (now > then)
while (c > then && c < now);
else
while (!(c > now && c < then));
}
void sys_tick::init(uint32_t n)
{
using namespace hal;
typedef stk_t _;
ms_counter = 0; // start new epoq
ticks_per_us = n / 1000; // for us in delay_us
#if defined(STM32F051) || defined(STM32F072) || defined (STM32F767) || defined(STM32H743) || defined(STM32G070)
STK.CSR = _::CSR_RESET_VALUE; // reset controls
STK.RVR = n - 1; // reload value
STK.CVR = _::CVR_RESET_VALUE; // current counter value
STK.CSR |= _::CSR_CLKSOURCE; // systick clock source
STK.CSR |= _::CSR_ENABLE | _::CSR_TICKINT; // enable counter & interrupts
#elif defined(STM32F103) || defined(STM32F411) || defined(STM32G431)
STK.CTRL = _::CTRL_RESET_VALUE; // reset controls
STK.LOAD = n - 1; // reload value
STK.VAL = _::VAL_RESET_VALUE; // current counter value
STK.CTRL |= _::CTRL_CLKSOURCE; // systick clock source
STK.CTRL |= _::CTRL_ENABLE | _::CTRL_TICKINT; // enable counter & interrupts
#else
static_assert(false, "no featured sys-tick initialzation");
#endif
}
volatile uint32_t sys_tick::ms_counter = 0;
uint32_t sys_tick::ticks_per_us = 0;
inline void sys_tick_init(uint32_t n) { sys_tick::init(n); }
inline void sys_tick_update() { ++sys_tick::ms_counter; } // N.B. wraps in 49 days!
uint32_t sys_clock::m_freq;
void sys_clock::init()
{
using namespace hal;
typedef rcc_t _;
// reset clock control registers (common for all families)
RCC.CR = _::CR_RESET_VALUE;
RCC.CFGR = _::CFGR_RESET_VALUE;
#if defined(STM32F051) || defined(STM32F072)
m_freq = 48000000;
// reset clock control registers
RCC.CFGR2 = _::CFGR2_RESET_VALUE;
RCC.CFGR3 = _::CFGR3_RESET_VALUE;
RCC.CR2 = _::CR2_RESET_VALUE;
RCC.CIR = _::CIR_RESET_VALUE;
// set system clock to HSI-PLL 48MHz
FLASH.ACR |= flash_t::ACR_PRFTBE | flash_t::ACR_LATENCY<0x1>;
RCC.CFGR |= _::CFGR_PLLMUL<0xa>; // PLL multiplier 12
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x2>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32F103)
m_freq = 72000000;
// set system clock to HSE-PLL 72MHz
FLASH.ACR |= flash_t::ACR_PRFTBE | flash_t::template ACR_LATENCY<0x2>;
RCC.CR |= _::CR_HSEON; // enable external clock
while (!(RCC.CR & _::CR_HSERDY)); // wait for HSE ready
RCC.CFGR |= _::CFGR_PLLSRC // clock from PREDIV1
| _::CFGR_PLLMUL<0x7> // pll multiplier = 9
| _::CFGR_PPRE1<0x4> // APB low-speed prescale = 2
;
RCC.CR |= _::CR_PLLON; // enable external clock
while (!(RCC.CR & _::CR_PLLRDY)); // wait for pll ready
RCC.CFGR |= _::CFGR_SW<0x2>; // use pll as clock source
// wait for clock switch completion
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32F411)
m_freq = 100000000;
// reset clock control registers
RCC.CIR = _::CIR_RESET_VALUE;
// set system clock to HSI-PLL 100MHz
constexpr uint8_t wait_states = 0x3; // 3 wait-states for 100MHz at 2.7-3.3V
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0x7>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
enum pllP_t { pllP_2 = 0x0, pllP_4 = 0x1, pllP_6 = 0x2, pllP_8 = 0x3 };
// fVCO = hs[ei] * pllN / pllM // must be 100MHz - 400MHz
// fSYS = fVCO / pllP // <= 100MHz
// fUSB = fVCO / pllQ // <= 48MHz
// pllN = 200, pllM = 8, pllP = 4, pllQ = 9, fSYS = 1.0e8, fUSB = 4.4445e7
constexpr uint16_t pllN = 200; // 9 bits, valid range [50..432]
constexpr uint8_t pllM = 8; // 6 bits, valid range [2..63]
constexpr pllP_t pllP = pllP_4; // 2 bits, enum range [2, 4, 6, 8]
constexpr uint8_t pllQ = 9; // 4 bits, valid range [2..15]
constexpr uint8_t pllSRC = 0; // 1 bit, 0 = HSI, 1 = HSE
using internal::encode;
RCC.PLLCFGR = encode<pllSRC, _::PLLCFGR_PLLSRC, 1>()
| encode<pllN, _::PLLCFGR_PLLN0, 9>()
| encode<pllM, _::PLLCFGR_PLLM0, 6>()
| encode<pllP, _::PLLCFGR_PLLP0, 2>()
| encode<pllQ, _::PLLCFGR_PLLQ0, 4>()
;
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= encode<0x2, _::CFGR_SW0, 2>(); // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & encode<0x3, _::CFGR_SWS0, 2>()) != encode<0x2, _::CFGR_SWS0, 2>());
#elif defined(STM32F767)
m_freq = 16000000;
#elif defined(STM32H743)
m_freq = 8000000;
#elif defined(STM32G070)
m_freq = 64000000;
// set system clock to HSI-PLL 64MHz and p-clock = 64MHz
constexpr uint8_t wait_states = 0x2; // 2 wait-states for 64Hz at Vcore range 1
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0x7>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
// fR (fSYS) = fVCO / pllR // <= 64MHz
// fP = fVCO / pllP // <= 122MHz
// pllN = 8.0, pllM = 1.0, pllP = 2.0, pllR = 2.0, fSYS = 6.4e7, fPllP = 6.4e7, fVCO = 1.28e8
constexpr uint16_t pllN = 8; // 7 bits, valid range [8..86]
constexpr uint8_t pllM = 1 - 1; // 3 bits, valid range [1..8]-1
constexpr uint8_t pllP = 2 - 1; // 5 bits, valid range [2..32]-1
constexpr uint8_t pllR = 2 - 1; // 3 bits, valid range [2..8]-1
constexpr uint8_t pllSRC = 2; // 2 bits, 2 = HSI16, 3 = HSE
RCC.PLLSYSCFGR = _::PLLSYSCFGR_PLLSRC<pllSRC>
| _::PLLSYSCFGR_PLLN<pllN>
| _::PLLSYSCFGR_PLLM<pllM>
| _::PLLSYSCFGR_PLLP<pllP>
| _::PLLSYSCFGR_PLLR<pllR>
| _::PLLSYSCFGR_PLLREN
| _::PLLSYSCFGR_PLLPEN
;
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x2>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32G431)
m_freq = 170000000;
// set system clock to HSI-PLL 170MHz (R) and same for P and Q clocks
constexpr uint8_t wait_states = 0x8; // 8 wait-states for 170MHz at Vcore range 1
FLASH.ACR = flash_t::ACR_RESET_VALUE;
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0xf>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
#if defined(HSE)
RCC.CR |= _::CR_HSEON; // enable external clock
while (!(RCC.CR & _::CR_HSERDY)); // wait for HSE ready
#if HSE == 24000000
constexpr uint8_t pllM = 6 - 1; // 3 bits, valid range [1..15]-1
#elif HSE == 8000000
constexpr uint8_t pllM = 2 - 1; // 3 bits, valid range [1..15]-1
#else
static_assert(false, "unsupported HSE frequency");
#endif
constexpr uint8_t pllSRC = 3; // 2 bits, 2 = HSI16, 3 = HSE
#else
// pllN = 85.0, pllM = 4.0, pllP = 7.0, pllPDIV = 2.0, pllQ = 2.0, pllR = 2.0, fSYS = 1.7e8, fPllP = 1.7e8, fPllQ = 1.7e8, fVCO = 3.4e8
constexpr uint8_t pllM = 4 - 1; // 3 bits, valid range [1..15]-1
constexpr uint8_t pllSRC = 2; // 2 bits, 2 = HSI16, 3 = HSE
#endif
constexpr uint16_t pllN = 85; // 7 bits, valid range [8..127]
constexpr uint8_t pllPDIV = 2; // 5 bits, valid range [2..31]
constexpr uint8_t pllR = 0; // 2 bits, 0 = 2, 1 = 4, 2 = 6, 3 = 8
constexpr uint8_t pllQ = 0; // 2 bits, 0 = 2, 1 = 4, 2 = 6, 3 = 8
RCC.PLLSYSCFGR = _::PLLSYSCFGR_PLLSRC<pllSRC>
| _::PLLSYSCFGR_PLLSYSN<pllN>
| _::PLLSYSCFGR_PLLSYSM<pllM>
| _::PLLSYSCFGR_PLLSYSPDIV<pllPDIV>
| _::PLLSYSCFGR_PLLSYSQ<pllQ>
| _::PLLSYSCFGR_PLLSYSR<pllR>
| _::PLLSYSCFGR_PLLPEN
| _::PLLSYSCFGR_PLLSYSQEN
| _::PLLSYSCFGR_PLLSYSREN
;
RCC.CR |= _::CR_PLLSYSON; // enable PLL
while (!(RCC.CR & _::CR_PLLSYSRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x3>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x3>);
// enable FPU
FPU_CPACR.CPACR |= fpu_cpacr_t::CPACR_CP<0xf>; // enable co-processors
__asm volatile ("dsb"); // data pipe-line reset
__asm volatile ("isb"); // instruction pipe-line reset
#else
static_assert(false, "no featured clock initialzation");
#endif
// initialize sys-tick for milli-second counts
hal::sys_tick_init(m_freq / 1000);
}
} // namespace hal
template<> void handler<interrupt::SYSTICK>()
{
hal::sys_tick_update();
}
extern void system_init(void)
{
hal::sys_clock::init();
}
| 38.006472 | 139 | 0.538658 | marangisto |
ed310c573883603a89722dd85d846cac70c032fc | 1,857 | cpp | C++ | platform/platform_std.cpp | LaGrunge/geocore | b599eda29a32a14e5c02f51c66848959b50732f2 | [
"Apache-2.0"
] | 1 | 2019-10-02T16:17:31.000Z | 2019-10-02T16:17:31.000Z | platform/platform_std.cpp | LaGrunge/omim | 8ce6d970f8f0eb613531b16edd22ea8ab923e72a | [
"Apache-2.0"
] | 6 | 2019-09-09T10:11:41.000Z | 2019-10-02T15:04:21.000Z | platform/platform_std.cpp | LaGrunge/geocore | b599eda29a32a14e5c02f51c66848959b50732f2 | [
"Apache-2.0"
] | null | null | null | #include "platform/constants.hpp"
#include "platform/measurement_utils.hpp"
#include "platform/platform.hpp"
#include "platform/settings.hpp"
#include "coding/file_reader.hpp"
#include "base/logging.hpp"
#include "platform/target_os.hpp"
#include <algorithm>
#include <future>
#include <memory>
#include <regex>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
namespace fs = boost::filesystem;
using namespace std;
unique_ptr<ModelReader> Platform::GetReader(string const & file, string const & searchScope) const
{
return make_unique<FileReader>(ReadPathForFile(file, searchScope), READER_CHUNK_LOG_SIZE,
READER_CHUNK_LOG_COUNT);
}
bool Platform::GetFileSizeByName(string const & fileName, uint64_t & size) const
{
try
{
return GetFileSizeByFullPath(ReadPathForFile(fileName), size);
}
catch (RootException const &)
{
return false;
}
}
void Platform::GetFilesByRegExp(string const & directory, string const & regexp,
FilesList & outFiles)
{
boost::system::error_code ec{};
regex exp(regexp);
for (auto const & entry : boost::make_iterator_range(fs::directory_iterator(directory, ec), {}))
{
string const name = entry.path().filename().string();
if (regex_search(name.begin(), name.end(), exp))
outFiles.push_back(name);
}
}
// static
Platform::EError Platform::MkDir(string const & dirName)
{
boost::system::error_code ec{};
fs::path dirPath{dirName};
if (fs::exists(dirPath, ec))
return Platform::ERR_FILE_ALREADY_EXISTS;
if (!fs::create_directory(dirPath, ec))
{
LOG(LWARNING, ("Can't create directory: ", dirName));
return Platform::ERR_UNKNOWN;
}
return Platform::ERR_OK;
}
extern Platform & GetPlatform()
{
static Platform platform;
return platform;
}
| 23.807692 | 98 | 0.699515 | LaGrunge |
ed341d5d54054a4f7820114ffb37bbcdb7a88045 | 2,113 | cpp | C++ | luogu/5105.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | luogu/5105.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | luogu/5105.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
typedef pair<ll, ll> pairs;
inline ll calc(ll x) {
switch (x % 4) {
case 0: return 0;
case 1: return x + x - 1;
case 2: return 2;
case 3: return x + x + 1;
}
return 19260817;
}
inline ll calc(ll l, ll r) {
return calc(l) ^ calc(r);
}
multiset<pairs> st;
deque<multiset<pairs>::iterator> rub;
ll now;
void update_left(multiset<pairs>::iterator x) {
if (x != st.begin()) {
ll u = (ll)x->first * x->first;
--x;
now ^= u - ((ll)x->second * x->second);
}
}
void update_right(multiset<pairs>::iterator x) {
if (x != --st.end()) {
ll u = (ll)x->second * x->second;
++x;
now ^= ((ll)x->first * x->first) - u;
}
}
void insert(ll l, ll r) {
pairs x = make_pair(l, r);
auto t = st.lower_bound(x), u = t;
while (true) {
if (u == st.begin())
break;
--u;
if (x.first - 1 <= u->second)
rub.push_front(u);
else
break;
}
u = t;
while (true) {
if (u == st.end())
break;
if (x.second + 1 >= u->first)
rub.push_back(u);
else
break;
++u;
}
for (auto u : rub) {
if (u->first < x.first)
x.first = u->first;
if (u->second > x.second)
x.second = u->second;
update_left(u);
now ^= calc(u -> first, u -> second);
}
if (rub.size())
update_right(*--rub.end());
else {
auto t = st.lower_bound(x);
if (t != st.end())
update_left(t);
}
for (auto u : rub)
st.erase(u);
rub.clear();
st.insert(x);
update_left(st.find(x));
update_right(st.find(x));
now ^= calc(x.second) ^ calc(x.first);
}
int main(int argc, char const *argv[]) {
// freopen("../tmp/.in", "r", stdin);
ll n = read();
while (n --) {
ll op = read();
if (op == 1) {
ll l = read(), r = read();
insert(l, r);
} else {
printf("%d\n", now);
}
}
return 0;
} | 19.747664 | 61 | 0.508755 | swwind |
ed3723efd8501d72d40c6428e25d6fe8bf1f9734 | 113 | hpp | C++ | src/afk/io/Time.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | src/afk/io/Time.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | src/afk/io/Time.hpp | christocs/ICT398 | 9fd7c17a72985ac2eb59a13c1d3761598e544771 | [
"ISC"
] | null | null | null | #pragma once
#include <string>
namespace afk {
namespace io {
auto get_date_time() -> std::string;
}
}
| 11.3 | 40 | 0.637168 | christocs |
ed37816ab920205a9631d33a5a5ec9ad7362cd8e | 413 | cpp | C++ | CPP.Part_2/week_4/01.Error_Handling/static_assert.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | 4 | 2017-11-17T12:02:21.000Z | 2021-02-08T11:24:16.000Z | CPP.Part_2/week_4/01.Error_Handling/static_assert.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | null | null | null | CPP.Part_2/week_4/01.Error_Handling/static_assert.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | null | null | null | #include <type_traits>
#include <iostream>
//#define NDEBUG
#include <cassert> // assert
template<class T>
void countdown(T start) {
// Compile time
static_assert(std::is_integral<T>::value
&& std::is_signed<T>::value,
"Requires signed integral type");
assert(start >= 0); // Runtime error
while (start >= 0) {
std::cout << start-- << std::endl;
}
}
| 22.944444 | 51 | 0.581114 | DGolgovsky |
ed407add37f5d554e19b171cfe8f4cbb407845c7 | 4,566 | cpp | C++ | src/vulkan/vulkan-commandlist.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 325 | 2021-07-19T13:55:23.000Z | 2022-03-31T20:38:58.000Z | src/vulkan/vulkan-commandlist.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 11 | 2021-07-20T00:15:59.000Z | 2022-03-12T08:50:33.000Z | src/vulkan/vulkan-commandlist.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 38 | 2021-07-19T15:04:17.000Z | 2022-03-28T09:09:09.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* 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 "vulkan-backend.h"
namespace nvrhi::vulkan
{
CommandList::CommandList(Device* device, const VulkanContext& context, const CommandListParameters& parameters)
: m_Device(device)
, m_Context(context)
, m_CommandListParameters(parameters)
, m_StateTracker(context.messageCallback)
, m_UploadManager(std::make_unique<UploadManager>(device, parameters.uploadChunkSize, 0, false))
, m_ScratchManager(std::make_unique<UploadManager>(device, parameters.scratchChunkSize, parameters.scratchMaxMemory, true))
{
}
nvrhi::Object CommandList::getNativeObject(ObjectType objectType)
{
switch (objectType)
{
case ObjectTypes::VK_CommandBuffer:
return Object(m_CurrentCmdBuf->cmdBuf);
default:
return nullptr;
}
}
void CommandList::open()
{
m_CurrentCmdBuf = m_Device->getQueue(m_CommandListParameters.queueType)->getOrCreateCommandBuffer();
auto beginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit);
(void)m_CurrentCmdBuf->cmdBuf.begin(&beginInfo);
m_CurrentCmdBuf->referencedResources.push_back(this); // prevent deletion of e.g. UploadManager
clearState();
}
void CommandList::close()
{
endRenderPass();
m_StateTracker.keepBufferInitialStates();
m_StateTracker.keepTextureInitialStates();
commitBarriers();
#ifdef NVRHI_WITH_RTXMU
if (!m_CurrentCmdBuf->rtxmuBuildIds.empty())
{
m_Context.rtxMemUtil->PopulateCompactionSizeCopiesCommandList(m_CurrentCmdBuf->cmdBuf, m_CurrentCmdBuf->rtxmuBuildIds);
}
#endif
m_CurrentCmdBuf->cmdBuf.end();
clearState();
flushVolatileBufferWrites();
}
void CommandList::clearState()
{
endRenderPass();
m_CurrentPipelineLayout = vk::PipelineLayout();
m_CurrentPipelineShaderStages = vk::ShaderStageFlagBits();
m_CurrentGraphicsState = GraphicsState();
m_CurrentComputeState = ComputeState();
m_CurrentMeshletState = MeshletState();
m_CurrentRayTracingState = rt::State();
m_CurrentShaderTablePointers = ShaderTableState();
m_AnyVolatileBufferWrites = false;
// TODO: add real context clearing code here
}
void CommandList::setPushConstants(const void* data, size_t byteSize)
{
assert(m_CurrentCmdBuf);
m_CurrentCmdBuf->cmdBuf.pushConstants(m_CurrentPipelineLayout, m_CurrentPipelineShaderStages, 0, uint32_t(byteSize), data);
}
void CommandList::executed(Queue& queue, const uint64_t submissionID)
{
assert(m_CurrentCmdBuf);
m_CurrentCmdBuf->submissionID = submissionID;
const CommandQueue queueID = queue.getQueueID();
const uint64_t recordingID = m_CurrentCmdBuf->recordingID;
m_CurrentCmdBuf = nullptr;
submitVolatileBuffers(recordingID, submissionID);
m_StateTracker.commandListSubmitted();
m_UploadManager->submitChunks(
MakeVersion(recordingID, queueID, false),
MakeVersion(submissionID, queueID, true));
m_ScratchManager->submitChunks(
MakeVersion(recordingID, queueID, false),
MakeVersion(submissionID, queueID, true));
m_VolatileBufferStates.clear();
}
} | 33.822222 | 131 | 0.70127 | Zwingling |
ed458e377aa8dc1d93a06d53c26c7680ac9fcdb0 | 4,296 | cpp | C++ | listen/tcp_listen_service.cpp | zhangdongai/libnetxcq | 59007e9cfa78a6ff2a8f2cf9c652a4e0cfc5c65d | [
"Apache-2.0"
] | null | null | null | listen/tcp_listen_service.cpp | zhangdongai/libnetxcq | 59007e9cfa78a6ff2a8f2cf9c652a4e0cfc5c65d | [
"Apache-2.0"
] | null | null | null | listen/tcp_listen_service.cpp | zhangdongai/libnetxcq | 59007e9cfa78a6ff2a8f2cf9c652a4e0cfc5c65d | [
"Apache-2.0"
] | null | null | null | #include "listen/tcp_listen_service.h"
#include <string.h>
#include "log/log.h"
#include "common/config/listen_flags.h"
#include "connector/connector_manager.h"
TCPListenService::TCPListenService() {
stop_ = false;
}
TCPListenService::~TCPListenService() {
stop();
close(listen_fd_);
}
void TCPListenService::stop() {
ListenService::stop();
}
void TCPListenService::init_config() {
}
bool TCPListenService::init_socket() {
DEBUG_LOG("listen port = %d", FLAGS_port);
DEBUG_LOG("communication type = %s", FLAGS_communication_type.c_str());
struct sockaddr_in listen_addr;
listen_fd_ = socket(AF_INET, SOCK_STREAM, 0);
bzero(&listen_addr, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_port = htons(FLAGS_port);
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(listen_fd_, (struct sockaddr*)&listen_addr, sizeof(listen_addr));
if (ret == invalid_id) {
const char* error = "error occured while bind";
switch (errno) {
case EADDRINUSE:
error = "The given address is already in use";
break;
case EINVAL:
error = "The socket is already bound to an address.";
break;
default:
break;
}
ERROR_LOG(error);
close(listen_fd_);
return false;
}
listen(listen_fd_, 256);
epoll_fd_ = epoll_create(MAX_EVENT);
if (epoll_fd_ == invalid_id) {
ERROR_LOG("create epoll error!");
close(listen_fd_);
return false;
}
struct epoll_event event;
event.data.fd = listen_fd_;
event.events = EPOLLIN | EPOLLHUP |EPOLLERR;
ret = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, listen_fd_, &event);
if (ret == invalid_id) {
ERROR_LOG("add epoll error!");
close(listen_fd_);
return false;
}
DEBUG_LOG("create socket success!");
return true;
}
void TCPListenService::run_logic() {
ListenService::run_logic();
// init ConnectorManager
ConnectorManager::instance();
}
void TCPListenService::main_loop() {
struct epoll_event events[MAX_EVENT];
while(!stop_) {
int fds = epoll_wait(epoll_fd_, events, MAX_EVENT, 100);
for (int i = 0; i < fds; ++i) {
struct epoll_event& tmp_ev = events[i];
if (tmp_ev.data.fd == listen_fd_) {
accept_connection();
}
else if (tmp_ev.events & EPOLLIN) {
}
else if (tmp_ev.events & EPOLLOUT) {
}
}
}
}
bool TCPListenService::accept_connection() {
struct sockaddr_in socket_in;
socklen_t socket_len = sizeof(struct sockaddr_in);
int new_socket_fd = accept(listen_fd_, (struct sockaddr*)&socket_in, &socket_len);
if (new_socket_fd == -1) {
const char* err_con = nullptr;
switch(errno) {
case EAGAIN:
err_con = "The socket is marked nonblocking and no connections are "
"present to be accepted";
break;
case EBADF:
err_con = "sockfd is not an open file descriptor";
break;
case EFAULT:
err_con = "The addr argument is not in a writable part of the user "
"address space";
break;
case EINTR:
err_con = "The system call was interrupted by a signal";
break;
case EINVAL:
err_con = "Socket is not listening for connections, or addrlen is invalid";
break;
case ENOMEM:
err_con = "Not enough free memory";
break;
case EPERM:
err_con = "Firewall rules forbid connection";
break;
default:
err_con = "unknown error";
break;
}
ERROR_LOG(err_con);
return false;
}
const char* addr_in = inet_ntoa(socket_in.sin_addr);
DEBUG_LOG("establish connection from %s", addr_in);
int flag = fcntl(new_socket_fd, F_GETFL, 0);
int ret = fcntl(new_socket_fd, F_SETFL, flag | O_NONBLOCK);
if (ret == invalid_id) {
ERROR_LOG("set non block for socket %d failed, errno = %d", new_socket_fd, ret);
return false;
}
ConnectorManager::instance()->accept_connector(new_socket_fd);
return true;
}
| 28.832215 | 88 | 0.606378 | zhangdongai |
ed484f059f358a65e49a0ae7051b35f682d81bbc | 27,224 | hpp | C++ | src/3rd/Simd/Simd/SimdDetection.hpp | inger147/AntiDupl | fb331c6312783bb74a62aa2efffcb7f5a5a54d3d | [
"MIT"
] | 674 | 2018-01-09T19:13:40.000Z | 2022-03-29T19:54:35.000Z | src/3rd/Simd/Simd/SimdDetection.hpp | inger147/AntiDupl | fb331c6312783bb74a62aa2efffcb7f5a5a54d3d | [
"MIT"
] | 124 | 2018-01-09T08:12:45.000Z | 2022-03-28T14:19:49.000Z | src/3rd/Simd/Simd/SimdDetection.hpp | inger147/AntiDupl | fb331c6312783bb74a62aa2efffcb7f5a5a54d3d | [
"MIT"
] | 78 | 2018-01-11T03:09:43.000Z | 2022-03-20T17:43:39.000Z | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2020 Yermalayeu Ihar,
* 2019-2019 Facundo Galan.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __SimdDetection_hpp__
#define __SimdDetection_hpp__
#include "Simd/SimdLib.hpp"
#include "Simd/SimdParallel.hpp"
#include <vector>
#include <map>
#include <memory>
#include <limits.h>
#ifndef SIMD_CHECK_PERFORMANCE
#define SIMD_CHECK_PERFORMANCE()
#endif
namespace Simd
{
/*! @ingroup cpp_detection
\short The Detection structure provides object detection with using of HAAR and LBP cascade classifiers.
Using example (face detection in the image):
\code
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main()
{
typedef Simd::Detection<Simd::Allocator> Detection;
Detection::View image;
image.Load("../../data/image/face/lena.pgm");
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
detection.Init(image.Size());
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, uint8_t(255));
image.Save("result.pgm");
return 0;
}
\endcode
Using example (face detection in the video captured by OpenCV):
\code
#include <iostream>
#include <string>
#include "opencv2/opencv.hpp"
#ifndef SIMD_OPENCV_ENABLE
#define SIMD_OPENCV_ENABLE
#endif
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "You have to set video source! It can be 0 for camera or video file name." << std::endl;
return 1;
}
std::string source = argv[1];
cv::VideoCapture capture;
if (source == "0")
capture.open(0);
else
capture.open(source);
if (!capture.isOpened())
{
std::cout << "Can't capture '" << source << "' !" << std::endl;
return 1;
}
typedef Simd::Detection<Simd::Allocator> Detection;
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
bool inited = false;
const char * WINDOW_NAME = "FaceDetection";
cv::namedWindow(WINDOW_NAME, 1);
for (;;)
{
cv::Mat frame;
capture >> frame;
Detection::View image = frame;
if (!inited)
{
detection.Init(image.Size(), 1.2, image.Size() / 20);
inited = true;
}
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, Simd::Pixel::Bgr24(0, 255, 255));
cv::imshow(WINDOW_NAME, frame);
if (cvWaitKey(1) == 27)// "press 'Esc' to break video";
break;
}
return 0;
}
\endcode
\note This is wrapper around low-level \ref object_detection API.
*/
template <template<class> class A>
struct Detection
{
typedef A<uint8_t> Allocator; /*!< Allocator type definition. */
typedef Simd::View<A> View; /*!< An image type definition. */
typedef Simd::Point<ptrdiff_t> Size; /*!< An image size type definition. */
typedef std::vector<Size> Sizes; /*!< A vector of image sizes type definition. */
typedef Simd::Rectangle<ptrdiff_t> Rect; /*!< A rectangle type definition. */
typedef std::vector<Rect> Rects; /*!< A vector of rectangles type definition. */
typedef int Tag; /*!< A tag type definition. */
static const Tag UNDEFINED_OBJECT_TAG = -1; /*!< The undefined object tag. */
/*!
\short The Object structure describes detected object.
*/
struct Object
{
Rect rect; /*!< \brief A bounding box around of detected object. */
int weight; /*!< \brief An object weight (number of elementary detections). */
Tag tag; /*!< \brief An object tag. It's useful if more than one detector works. */
/*!
Creates a new Object structure.
\param [in] r - initial bounding box.
\param [in] w - initial weight.
\param [in] t - initial tag.
*/
Object(const Rect & r = Rect(), int w = 0, Tag t = UNDEFINED_OBJECT_TAG)
: rect(r)
, weight(w)
, tag(t)
{
}
/*!
Creates a new Object structure on the base of another object.
\param [in] o - another object.
*/
Object(const Object & o)
: rect(o.rect)
, weight(o.weight)
, tag(o.tag)
{
}
};
typedef std::vector<Object> Objects; /*!< A vector of objects type defenition. */
/*!
Creates a new empty Detection structure.
*/
Detection()
{
}
/*!
A Detection destructor.
*/
~Detection()
{
for (size_t i = 0; i < _data.size(); ++i)
::SimdRelease(_data[i].handle);
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] xml - a string containing XML with cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool LoadStringXml(const std::string & xml, Tag tag = UNDEFINED_OBJECT_TAG)
{
// Copy the received string to a non const char pointer.
char * xmlTmp = new char[xml.size() + 1];
std::copy(xml.begin(), xml.end(), xmlTmp);
xmlTmp[xml.size()] = '\0';
Handle handle = ::SimdDetectionLoadStringXml(xmlTmp);
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] path - a path to cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool Load(const std::string & path, Tag tag = UNDEFINED_OBJECT_TAG)
{
Handle handle = ::SimdDetectionLoadA(path.c_str());
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Prepares Detection structure to work with image of given size.
\param [in] imageSize - a size of input image.
\param [in] scaleFactor - a scale factor. To detect objects of different sizes the algorithm uses many scaled image.
This parameter defines size difference between neighboring images. This parameter strongly affects to performance.
\param [in] sizeMin - a minimal size of detected objects. This parameter strongly affects to performance.
\param [in] sizeMax - a maximal size of detected objects.
\param [in] roi - a 8-bit image mask which defines Region Of Interest. User can restricts detection region with using this mask.
The mask affects to the center of detected object.
\param [in] threadNumber - a number of work threads. It useful for multi core CPU. Use value -1 to auto choose of thread number.
\return a result of this operation.
*/
bool Init(const Size & imageSize, double scaleFactor = 1.1, const Size & sizeMin = Size(0, 0),
const Size & sizeMax = Size(INT_MAX, INT_MAX), const View & roi = View(), ptrdiff_t threadNumber = -1)
{
if (_data.empty())
return false;
_imageSize = imageSize;
ptrdiff_t threadNumberMax = std::thread::hardware_concurrency();
_threadNumber = (threadNumber <= 0 || threadNumber > threadNumberMax) ? threadNumberMax : threadNumber;
return InitLevels(scaleFactor, sizeMin, sizeMax, roi);
}
/*!
Detects objects at given image.
\param [in] src - a input image.
\param [out] objects - detected objects.
\param [in] groupSizeMin - a minimal weight (number of elementary detections) of detected image.
\param [in] sizeDifferenceMax - a parameter to group elementary detections.
\param [in] motionMask - an using of motion detection flag. Useful for dynamical restriction of detection region to addition to ROI.
\param [in] motionRegions - a set of rectangles (motion regions) to restrict detection region to addition to ROI.
The regions affect to the center of detected object.
\return a result of this operation.
*/
bool Detect(const View & src, Objects & objects, int groupSizeMin = 3, double sizeDifferenceMax = 0.2,
bool motionMask = false, const Rects & motionRegions = Rects())
{
SIMD_CHECK_PERFORMANCE();
if (_levels.empty() || src.Size() != _imageSize)
return false;
FillLevels(src);
typedef std::map<Tag, Objects> Candidates;
Candidates candidates;
for (size_t i = 0; i < _levels.size(); ++i)
{
Level & level = *_levels[i];
View mask = level.roi;
Rect rect = level.rect;
if (motionMask)
{
FillMotionMask(motionRegions, level, rect);
mask = level.mask;
}
if (rect.Empty())
continue;
for (size_t j = 0; j < level.hids.size(); ++j)
{
Hid & hid = level.hids[j];
hid.Detect(mask, rect, level.dst, _threadNumber, level.throughColumn);
AddObjects(candidates[hid.data->tag], level.dst, rect, hid.data->size, level.scale,
level.throughColumn ? 2 : 1, hid.data->tag);
}
}
objects.clear();
for (typename Candidates::iterator it = candidates.begin(); it != candidates.end(); ++it)
GroupObjects(objects, it->second, groupSizeMin, sizeDifferenceMax);
return true;
}
private:
typedef void * Handle;
struct Data
{
Handle handle;
Tag tag;
Size size;
::SimdDetectionInfoFlags flags;
bool Haar() const { return (flags&::SimdDetectionInfoFeatureMask) == ::SimdDetectionInfoFeatureHaar; }
bool Tilted() const { return (flags&::SimdDetectionInfoHasTilted) != 0; }
bool Int16() const { return (flags&::SimdDetectionInfoCanInt16) != 0; }
};
typedef void(*DetectPtr)(const void * hid, const uint8_t * mask, size_t maskStride,
ptrdiff_t left, ptrdiff_t top, ptrdiff_t right, ptrdiff_t bottom, uint8_t * dst, size_t dstStride);
struct Worker;
typedef std::shared_ptr<Worker> WorkerPtr;
typedef std::vector<WorkerPtr> WorkerPtrs;
struct Hid
{
Handle handle;
Data * data;
DetectPtr detect;
void Detect(const View & mask, const Rect & rect, View & dst, size_t threadNumber, bool throughColumn)
{
SIMD_CHECK_PERFORMANCE();
Size s = dst.Size() - data->size;
View m = mask.Region(s, View::MiddleCenter);
Rect r = rect.Shifted(-data->size / 2).Intersection(Rect(s));
Simd::Fill(dst, 0);
::SimdDetectionPrepare(handle);
Parallel(r.top, r.bottom, [&](size_t thread, size_t begin, size_t end)
{
detect(handle, m.data, m.stride, r.left, begin, r.right, end, dst.data, dst.stride);
}, rect.Area() >= (data->Haar() ? 10000 : 30000) ? threadNumber : 1, throughColumn ? 2 : 1);
}
};
typedef std::vector<Hid> Hids;
struct Level
{
Hids hids;
double scale;
View src;
View roi;
View mask;
Rect rect;
View sum;
View sqsum;
View tilted;
View dst;
bool throughColumn;
bool needSqsum;
bool needTilted;
~Level()
{
for (size_t i = 0; i < hids.size(); ++i)
::SimdRelease(hids[i].handle);
}
};
typedef std::unique_ptr<Level> LevelPtr;
typedef std::vector<LevelPtr> LevelPtrs;
std::vector<Data> _data;
Size _imageSize;
bool _needNormalization;
ptrdiff_t _threadNumber;
LevelPtrs _levels;
bool InitLevels(double scaleFactor, const Size & sizeMin, const Size & sizeMax, const View & roi)
{
_needNormalization = false;
_levels.clear();
_levels.reserve(100);
double scale = 1.0;
do
{
std::vector<bool> inserts(_data.size(), false);
bool exit = true, insert = false;
for (size_t i = 0; i < _data.size(); ++i)
{
Size windowSize = _data[i].size * scale;
if (windowSize.x <= sizeMax.x && windowSize.y <= sizeMax.y &&
windowSize.x <= _imageSize.x && windowSize.y <= _imageSize.y)
{
if (windowSize.x >= sizeMin.x && windowSize.y >= sizeMin.y)
insert = inserts[i] = true;
exit = false;
}
}
if (exit)
break;
if (insert)
{
_levels.push_back(LevelPtr(new Level()));
Level & level = *_levels.back();
level.scale = scale;
level.throughColumn = scale <= 2.0;
Size scaledSize(_imageSize / scale);
level.src.Recreate(scaledSize, View::Gray8);
level.roi.Recreate(scaledSize, View::Gray8);
level.mask.Recreate(scaledSize, View::Gray8);
level.sum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.sqsum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.tilted.Recreate(scaledSize + Size(1, 1), View::Int32);
level.dst.Recreate(scaledSize, View::Gray8);
level.needSqsum = false, level.needTilted = false;
for (size_t i = 0; i < _data.size(); ++i)
{
if (!inserts[i])
continue;
Handle handle = ::SimdDetectionInit(_data[i].handle, level.sum.data, level.sum.stride, level.sum.width, level.sum.height,
level.sqsum.data, level.sqsum.stride, level.tilted.data, level.tilted.stride, level.throughColumn, _data[i].Int16());
if (handle)
{
Hid hid;
hid.handle = handle;
hid.data = &_data[i];
if (_data[i].Haar())
hid.detect = level.throughColumn ? ::SimdDetectionHaarDetect32fi : ::SimdDetectionHaarDetect32fp;
else
{
if (_data[i].Int16())
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect16ii : ::SimdDetectionLbpDetect16ip;
else
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect32fi : ::SimdDetectionLbpDetect32fp;
}
level.hids.push_back(hid);
}
else
return false;
level.needSqsum = level.needSqsum | _data[i].Haar();
level.needTilted = level.needTilted | _data[i].Tilted();
_needNormalization = _needNormalization | _data[i].Haar();
}
level.rect = Rect(level.roi.Size());
if (roi.format == View::None)
Simd::Fill(level.roi, 255);
else
{
Simd::ResizeBilinear(roi, level.roi);
Simd::Binarization(level.roi, 0, 255, 0, level.roi, SimdCompareGreater);
Simd::SegmentationShrinkRegion(level.roi, 255, level.rect);
}
}
scale *= scaleFactor;
} while (true);
return !_levels.empty();
}
void FillLevels(View src)
{
View gray;
if (src.format != View::Gray8)
{
gray.Recreate(src.Size(), View::Gray8);
Convert(src, gray);
src = gray;
}
Simd::ResizeBilinear(src, _levels[0]->src);
if (_needNormalization)
Simd::NormalizeHistogram(_levels[0]->src, _levels[0]->src);
EstimateIntegral(*_levels[0]);
for (size_t i = 1; i < _levels.size(); ++i)
{
Simd::ResizeBilinear(_levels[0]->src, _levels[i]->src);
EstimateIntegral(*_levels[i]);
}
}
void EstimateIntegral(Level & level)
{
if (level.needSqsum)
{
if (level.needTilted)
Simd::Integral(level.src, level.sum, level.sqsum, level.tilted);
else
Simd::Integral(level.src, level.sum, level.sqsum);
}
else
Simd::Integral(level.src, level.sum);
}
void FillMotionMask(const Rects & rects, Level & level, Rect & rect) const
{
Simd::Fill(level.mask, 0);
rect = Rect();
for (size_t i = 0; i < rects.size(); i++)
{
Rect r = rects[i] / level.scale;
rect |= r;
Simd::Fill(level.mask.Region(r).Ref(), 0xFF);
}
rect &= level.rect;
Simd::OperationBinary8u(level.mask, level.roi, level.mask, SimdOperationBinary8uAnd);
}
void AddObjects(Objects & objects, const View & dst, const Rect & rect, const Size & size, double scale, size_t step, Tag tag)
{
Size s = dst.Size() - size;
Rect r = rect.Shifted(-size / 2).Intersection(Rect(s));
for (ptrdiff_t row = r.top; row < r.bottom; row += step)
{
const uint8_t * mask = dst.data + row*dst.stride;
for (ptrdiff_t col = r.left; col < r.right; col += step)
{
if (mask[col] != 0)
objects.push_back(Object(Rect(col, row, col + size.x, row + size.y)*scale, 1, tag));
}
}
}
struct Similar
{
Similar(double sizeDifferenceMax)
: _sizeDifferenceMax(sizeDifferenceMax)
{}
SIMD_INLINE bool operator() (const Object & o1, const Object & o2) const
{
const Rect & r1 = o1.rect;
const Rect & r2 = o2.rect;
double delta = _sizeDifferenceMax*(std::min(r1.Width(), r2.Width()) + std::min(r1.Height(), r2.Height()))*0.5;
return
std::abs(r1.left - r2.left) <= delta && std::abs(r1.top - r2.top) <= delta &&
std::abs(r1.right - r2.right) <= delta && std::abs(r1.bottom - r2.bottom) <= delta;
}
private:
double _sizeDifferenceMax;
};
template<typename T> int Partition(const std::vector<T> & vec, std::vector<int> & labels, double sizeDifferenceMax)
{
Similar similar(sizeDifferenceMax);
int i, j, N = (int)vec.size();
const int PARENT = 0;
const int RANK = 1;
std::vector<int> _nodes(N * 2);
int(*nodes)[2] = (int(*)[2])&_nodes[0];
for (i = 0; i < N; i++)
{
nodes[i][PARENT] = -1;
nodes[i][RANK] = 0;
}
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
for (j = 0; j < N; j++)
{
if (i == j || !similar(vec[i], vec[j]))
continue;
int root2 = j;
while (nodes[root2][PARENT] >= 0)
root2 = nodes[root2][PARENT];
if (root2 != root)
{
int rank = nodes[root][RANK], rank2 = nodes[root2][RANK];
if (rank > rank2)
nodes[root2][PARENT] = root;
else
{
nodes[root][PARENT] = root2;
nodes[root2][RANK] += rank == rank2;
root = root2;
}
assert(nodes[root][PARENT] < 0);
int k = j, parent;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
k = i;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
}
}
}
labels.resize(N);
int nclasses = 0;
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
if (nodes[root][RANK] >= 0)
nodes[root][RANK] = ~nclasses++;
labels[i] = ~nodes[root][RANK];
}
return nclasses;
}
void GroupObjects(Objects & dst, const Objects & src, size_t groupSizeMin, double sizeDifferenceMax)
{
if (groupSizeMin == 0 || src.size() < groupSizeMin)
return;
std::vector<int> labels;
int nclasses = Partition(src, labels, sizeDifferenceMax);
Objects buffer;
buffer.resize(nclasses);
for (size_t i = 0; i < labels.size(); ++i)
{
int cls = labels[i];
buffer[cls].rect += src[i].rect;
buffer[cls].weight++;
buffer[cls].tag = src[i].tag;
}
for (size_t i = 0; i < buffer.size(); i++)
buffer[i].rect = buffer[i].rect / double(buffer[i].weight);
for (size_t i = 0; i < buffer.size(); i++)
{
Rect r1 = buffer[i].rect;
int n1 = buffer[i].weight;
if (n1 < (int)groupSizeMin)
continue;
size_t j;
for (j = 0; j < buffer.size(); j++)
{
int n2 = buffer[j].weight;
if (j == i || n2 < (int)groupSizeMin)
continue;
Rect r2 = buffer[j].rect;
int dx = Simd::Round(r2.Width() * sizeDifferenceMax);
int dy = Simd::Round(r2.Height() * sizeDifferenceMax);
if (i != j && (n2 > std::max(3, n1) || n1 < 3) &&
r1.left >= r2.left - dx && r1.top >= r2.top - dy &&
r1.right <= r2.right + dx && r1.bottom <= r2.bottom + dy)
break;
}
if (j == buffer.size())
dst.push_back(buffer[i]);
}
}
};
}
#endif//__SimdDetection_hpp__
| 37.242134 | 152 | 0.490192 | inger147 |
ed484f41521a3f09c7769954d090ee8c697f7ff4 | 5,499 | hpp | C++ | KFPlugin/KFTcpClient/KFTcpClientModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFPlugin/KFTcpClient/KFTcpClientModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFPlugin/KFTcpClient/KFTcpClientModule.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #ifndef __KF_CLIENT_MODULE_H__
#define __KF_CLIENT_MODULE_H__
/************************************************************************
// @Module : tcp客户端
// @Author : __凌_痕__
// @QQ : 7969936
// @Mail : lori227@qq.com
// @Date : 2017-1-8
************************************************************************/
#include "KFrame.h"
#include "KFTcpClientInterface.h"
#include "KFMessage/KFMessageInterface.h"
#include "KFNetwork/KFNetClientEngine.hpp"
namespace KFrame
{
class KFTcpClientModule : public KFTcpClientInterface
{
public:
KFTcpClientModule() = default;
~KFTcpClientModule() = default;
// 初始化
virtual void InitModule();
// 逻辑
virtual void BeforeRun();
virtual void Run();
// 关闭
virtual void BeforeShut();
virtual void ShutDown();
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// 添加客户端连接
virtual void StartClient( const KFNetData* netdata );
virtual void StartClient( const std::string& name, const std::string& type, uint64 id, const std::string& ip, uint32 port );
// 断开连接
virtual void CloseClient( uint64 serverid, const char* function, uint32 line );
/////////////////////////////////////////////////////////////////////////
// 发送消息
virtual void SendNetMessage( uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual bool SendNetMessage( uint64 serverid, uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual bool SendNetMessage( uint64 serverid, uint64 recvid, uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual void SendNetMessage( uint32 msgid, const char* data, uint32 length );
virtual bool SendNetMessage( uint64 serverid, uint32 msgid, const char* data, uint32 length );
virtual bool SendNetMessage( uint64 serverid, uint64 recvid, uint32 msgid, const char* data, uint32 length );
virtual void SendMessageToName( const std::string& servername, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToName( const std::string& servername, uint32 msgid, const char* data, uint32 length );;
virtual void SendMessageToType( const std::string& servertype, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToType( const std::string& servertype, uint32 msgid, const char* data, uint32 length );
virtual void SendMessageToServer( const std::string& servername, const std::string& servertype, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToServer( const std::string& servername, const std::string& servertype, uint32 msgid, const char* data, uint32 length );
////////////////////////////////////////////////////////////////////////////////////////////////////////
protected:
// 客户端连接
__KF_NET_EVENT_FUNCTION__( OnClientConnected );
// 客户端断开
__KF_NET_EVENT_FUNCTION__( OnClientDisconnect );
// 客户端关闭
__KF_NET_EVENT_FUNCTION__( OnClientShutdown );
// 客户端连接失败
__KF_NET_EVENT_FUNCTION__( OnClientFailed );
// 注册回馈
__KF_MESSAGE_FUNCTION__( HandleRegisterAck );
private:
// 连接回调
void AddConnectionFunction( KFModule* module, KFNetEventFunction& function );
void RemoveConnectionFunction( KFModule* module );
void CallClientConnectionFunction( const KFNetData* netdata );
// 断线函数
virtual void AddLostFunction( KFModule* module, KFNetEventFunction& function );
void RemoveLostFunction( KFModule* module );
void CallClientLostFunction( const KFNetData* netdata );
// 添加关闭函数
virtual void AddShutdownFunction( KFModule* module, KFNetEventFunction& function );
virtual void RemoveShutdownFunction( KFModule* module );
void CallClientShutdownFunction( const KFNetData* netdata );
// 添加失败函数
virtual void AddFailedFunction( KFModule* module, KFNetEventFunction& function );
virtual void RemoveFailedFunction( KFModule* module );
void CallClientFailedFunction( const KFNetData* netdata );
// 转发函数
virtual void AddTranspondFunction( KFModule* module, KFTranspondFunction& function );
virtual void RemoveTranspondFunction( KFModule* module );
////////////////////////////////////////////////////////////////
// 处理客户端消息
void HandleNetMessage( const Route& route, uint32 msgid, const char* data, uint32 length );
// 是否连接自己
bool IsSelfConnection( const std::string& name, const std::string& type, uint64 id );
public:
// 客户端引擎
KFNetClientEngine* _client_engine = nullptr;
// 转发函数
KFTranspondFunction _kf_transpond_function = nullptr;
// 注册成功回调函数
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_connection_function;
// 客户端掉线
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_lost_function;
// 客户端关闭
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_shutdown_function;
// 客户端失败
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_failed_function;
};
}
#endif | 41.345865 | 155 | 0.603019 | 282951387 |
ed4c3299ec2b60452ac666a9903ce85105463a48 | 1,906 | hpp | C++ | include/pcg/Random.hpp | TerensTare/tnt | 916067a9bf697101afb1d0785112aa34014e8126 | [
"MIT"
] | 29 | 2020-04-22T01:31:30.000Z | 2022-02-03T12:21:29.000Z | include/pcg/Random.hpp | TerensTare/tnt | 916067a9bf697101afb1d0785112aa34014e8126 | [
"MIT"
] | 6 | 2020-04-17T10:31:56.000Z | 2021-09-10T12:07:22.000Z | include/pcg/Random.hpp | TerensTare/tnt | 916067a9bf697101afb1d0785112aa34014e8126 | [
"MIT"
] | 7 | 2020-03-13T01:50:41.000Z | 2022-03-06T23:44:29.000Z | #ifndef TNT_PCG_RANDOM_HPP
#define TNT_PCG_RANDOM_HPP
#include <concepts>
#include "core/Config.hpp"
#include "math/Vector.hpp"
// TODO:
// randomColor, etc.
// constexpr halton*
namespace tnt
{
/// @brief Get a random float on range @c [min_,max_].
/// @param min_ The minimum value of the float.
/// @param max_ The maximum value of the float.
/// @return float
TNT_API float randomFloat(float min_, float max_);
/// @brief Get a random int on range @c [min_,max_].
/// @param min_ The minimum value of the int.
/// @param max_ The maximum value of the int.
/// @return int
TNT_API int randomInt(int min_, int max_);
/// @brief Get a tnt::Vector with randomly generated coordinates.
/// @param minX The minimum value of the x coordinate.
/// @param maxX The maximum value of the x coordinate.
/// @param minY The minimum value of the y coordinate.
/// @param maxY The maximum value of the y coordinate.
/// @return @ref tnt::Vector
TNT_API Vector randomVector(float minX, float maxX, float minY, float maxY);
/// @brief Create a randomly generated Vector with magnitude 1.
/// @return @ref tnt::Vector
TNT_API Vector randomUnitVector();
/// @brief Generate a random number using a Halton sequence.
template <std::integral I>
inline auto halton1(I const base, I index) noexcept
{
I result{0};
for (I denom{1}; index > 0; index = floor(index / base))
{
denom *= base;
result += (index % base) / denom;
}
return result;
}
/// @brief Generate a random Vector using Halton sequences.
template <std::integral I>
inline Vector halton2(I const baseX, I const baseY, I index) noexcept
{
return {(float)halton1<I>(baseX, index), (float)halton1<I>(baseY, index)};
}
} // namespace tnt
#endif //!TNT_PCG_RANDOM_HPP | 31.766667 | 82 | 0.644281 | TerensTare |
ed4d5bfd8b95769f8040728c1ade7d26d0a1c67c | 13,010 | cc | C++ | tunnel_localizer/src/range_based_tunnel_localizer.cc | ozaslan/estimators | ad78f2d395d4a6155f0b6d61541167a99959a1c9 | [
"MIT"
] | null | null | null | tunnel_localizer/src/range_based_tunnel_localizer.cc | ozaslan/estimators | ad78f2d395d4a6155f0b6d61541167a99959a1c9 | [
"MIT"
] | null | null | null | tunnel_localizer/src/range_based_tunnel_localizer.cc | ozaslan/estimators | ad78f2d395d4a6155f0b6d61541167a99959a1c9 | [
"MIT"
] | null | null | null | /*
See the header file for detailed explanations
of the below functions.
*/
#include "range_based_tunnel_localizer.hh"
RangeBasedTunnelLocalizer::RangeBasedTunnelLocalizer(int max_iter, double yz_tol, double yaw_tol){
_cloud = pcl::PointCloud<pcl::PointXYZ>().makeShared();
_cloud_aligned = pcl::PointCloud<pcl::PointXYZ>().makeShared();
_max_iters = max_iter;
_yz_tol = yz_tol;
_yaw_tol = yaw_tol;
}
bool RangeBasedTunnelLocalizer::_reset(){
_cloud->points.clear();
_cloud_aligned->points.clear();
_num_laser_pushes = 0;
_num_rgbd_pushes = 0;
_fim = Eigen::Matrix6d::Zero();
return true;
}
bool RangeBasedTunnelLocalizer::set_map(const pcl::PointCloud<pcl::PointXYZ>::Ptr &map){
// ### This will cause memory leak!!!
_octree = new pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>(0.05);
_octree->setInputCloud(map);
_octree->addPointsFromInputCloud();
return true;
}
bool RangeBasedTunnelLocalizer::push_laser_data(const LaserProc &laser_proc, bool clean_start){
const vector<int> &mask = laser_proc.get_mask();
const vector<Eigen::Vector3d> &_3d_pts = laser_proc.get_3d_points();
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + mask.size());
for(int i = 0 ; i < (int)mask.size() ; i++){
if(mask[i] <= 0)
continue;
_cloud->points.push_back(pcl::PointXYZ(_3d_pts[i](0), _3d_pts[i](1), _3d_pts[i](2)));
}
// Accumulate information due to the laser scanner onto the _fim matrix.
// Each additional information is in the body frame. In the 'get_covariance(...)'
// function (if points have to been registered) this is projected onto the world
// frame.
Eigen::Matrix3d fim_xyz = Eigen::Matrix3d::Zero(); // Fisher information for x, y, z coords.
Eigen::Matrix3d dcm = laser_proc.get_calib_params().relative_pose.topLeftCorner<3, 3>(); // Rotation matrix
Eigen::Matrix3d fim_xyp; // Fisher information for x, y, yaw
double fi_p = 0; // Fisher information for yaw only (neglecting correlative information)
fim_xyp = laser_proc.get_fim();
//cout << "fim_xyp = " << fim_xyp << endl;
fim_xyz.topLeftCorner<2, 2>() = fim_xyp.topLeftCorner<2, 2>();
fim_xyz = dcm * fim_xyz * dcm.transpose();
fi_p = fabs(fim_xyp(2, 2)) * fabs(dcm(2, 2));
//cout << "dcm = [" << dcm << "];" << endl;
// Here we use the ypr convention for compatibility with the 'quadrotor_ukf_lite' node.
_fim.block<3, 3>(0, 0) += fim_xyz;
_fim(3, 3) += fi_p;
//cout << "_fim = [" << _fim << "];" << endl;
return true;
}
bool RangeBasedTunnelLocalizer::push_laser_data(const Eigen::Matrix4d &rel_pose, const sensor_msgs::LaserScan &data, const vector<char> &mask, char cluster_id, bool clean_start){
// ### This still does not incorporate the color information
ASSERT(mask.size() == 0 || data.ranges.size() == mask.size(), "mask and data size should be the same.");
ASSERT(cluster_id != 0, "Cluster \"0\" is reserved.");
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + data.ranges.size());
Eigen::Vector4d pt;
double th = data.angle_min;
for(int i = 0 ; i < (int)data.ranges.size() ; i++, th += data.angle_increment){
if(mask.size() != 0 && mask[i] != cluster_id)
continue;
utils::laser::polar2euclidean(data.ranges[i], th, pt(0), pt(1));
pt(2) = pt(3) = 0;
pt = rel_pose * pt;
_cloud->points.push_back(pcl::PointXYZ(pt(0), pt(1), pt(2)));
}
// Accumulate information due to the laser scanner onto the _fim matrix.
// Each additional information is in the body frame. In the 'get_covariance(...)'
// function (if points have to been registered) this is projected onto the world
// frame.
Eigen::Matrix3d fim_xyz = Eigen::Matrix3d::Zero(); // Fisher information for x, y, z coords.
Eigen::Matrix3d dcm = rel_pose.topLeftCorner<3, 3>(); // Rotation matrix
Eigen::Matrix3d fim_xyp; // Fisher information for x, y, yaw
double fi_p = 0; // Fisher information for yaw only (neglecting correlative information)
utils::laser::get_fim(data, mask, fim_xyp, cluster_id);
fim_xyz.topLeftCorner<2, 2>() = fim_xyp.topLeftCorner<2, 2>();
fim_xyz = dcm.transpose() * fim_xyz * dcm;
fi_p = fim_xyp(2, 2) * dcm(2, 2);
// Here we use the ypr convention for compatibility with the 'quadrotor_ukf_lite' node.
_fim.block<3, 3>(0, 0) += fim_xyz;
_fim(3, 3) += fi_p;
_num_laser_pushes++;
return true;
}
bool RangeBasedTunnelLocalizer::push_rgbd_data(const Eigen::Matrix4d &rel_pose, const sensor_msgs::PointCloud2 &data, const vector<char> &mask, char cluster_id, bool clean_start){
// ### This still does not incorporate the color information
ASSERT(mask.size() == 0 || data.data.size() == mask.size(), "mask and data size should be the same.");
ASSERT(cluster_id != 0, "Cluster \"0\" is reserved.");
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + data.data.size());
Eigen::Vector4d pt;
ROS_WARN("\"push_rgbd_data(...)\" is not implemented yet!");
for(int i = 0 ; i < (int)data.data.size() ; i++){
if(mask.size() != 0 || mask[i] == false)
continue;
// ### To be implemented!
}
_num_rgbd_pushes++;
return true;
}
int RangeBasedTunnelLocalizer::estimate_pose(const Eigen::Matrix4d &init_pose, double heading){
// ### This will cause memory leak!!!
_cloud_aligned = pcl::PointCloud<pcl::PointXYZ>().makeShared();
// Initialize '_cloud_aligned' by transforming the collective point cloud
// with the initial pose.
pcl::transformPointCloud(*_cloud, *_cloud_aligned, init_pose);
// Steps :
// (1) - For each ray, find the point of intersection. Use ray-casting of PCL-Octree
// (2) - Prepare the matrix A and vector b s.t. A*x = b
// (3) - Solve for A*x = b where x = [cos(th) sin(th), dy, dz]'.
// (4) - Repeat for _max_iter's or tolerance conditions are met
// (*) - Use weighing to eliminate outliers.
int num_pts = _cloud_aligned->points.size();
int num_valid_pts = 0; // # of data points intersecting with the map.
double dTz = 0; // update along the z-coordinate.
Eigen::MatrixXd A(num_pts, 3);
Eigen::VectorXd b(num_pts);
Eigen::Vector3d x, rpy; // solution to Ax=b,
// roll-pitch-yaw
Eigen::Vector3f pos; // initial position of the robot.
// This is given as argument to ray-caster.
Eigen::Vector3f ray;
Eigen::Vector3d res_vec;
Eigen::Matrix4d curr_pose = init_pose; // 'current' pose after each iteration.
// container for ray-casting results :
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>::AlignedPointTVector voxel_centers;
pos = curr_pose.topRightCorner<3, 1>().cast<float>();
_matched_map_pts.resize(num_pts);
int iter;
for(iter = 0 ; iter < _max_iters ; iter++){
//cout << "projection pos = " << pos << endl;
num_valid_pts = 0;
_fitness_scores[0] = _fitness_scores[1] = _fitness_scores[2] = 0;
for(int i = 0 ; i < num_pts ; i++){
// Get the ray in the body frame ()
ray(0) = _cloud_aligned->points[i].x - pos(0);
ray(1) = _cloud_aligned->points[i].y - pos(1);
ray(2) = _cloud_aligned->points[i].z - pos(2);
A(i, 0) = ray(1);
A(i, 1) = -ray(0);
A(i, 2) = 1;
// Fetch only the first intersection point
_octree->getIntersectedVoxelCenters(pos, ray, voxel_centers , 1);
// If there is no intersection, nullify the effect by zero'ing the corresponding equation
if(voxel_centers.size() == 0){
A.block<1, 3>(i, 0) *= 0;
b(i) = 0;
_matched_map_pts[i].x =
_matched_map_pts[i].y =
_matched_map_pts[i].z = std::numeric_limits<float>::infinity();
} else {
// Save the matched point
_matched_map_pts[i] = voxel_centers[0];
// Use only the y-comp of the residual vector. Because
// this is going to contribute to y and yaw updates only.
b(i) = voxel_centers[0].y - pos(1);
// Get the residual vector
res_vec(0) = _cloud_aligned->points[i].x - voxel_centers[0].x;
res_vec(1) = _cloud_aligned->points[i].y - voxel_centers[0].y;
res_vec(2) = _cloud_aligned->points[i].z - voxel_centers[0].z;
// Update the delta-z-estimate according to the direction of the
// corresponding ray's z component. The update factor is weighed using
// ML outlier elimination.
dTz += -res_vec(2) * (exp(fabs(ray(2) / ray.norm())) - 1);
// Calculate a weighing coefficent for ML outlier elimination
// regarding y-yaw DOFs
double weight = exp(-pow(res_vec.squaredNorm(), 1.5));
b(i) *= weight;
A.block<1, 3>(i, 0) *= weight;
num_valid_pts++;
_fitness_scores[0] += res_vec[1] * res_vec[1];
_fitness_scores[1] += res_vec[2] * res_vec[2];
_fitness_scores[2] += res_vec[1] * res_vec[1] * ray(0) * ray(0);
}
}
// ####
/*
if(num_valid_pts < 100){
continue;
}
*/
/*
cout << "heading = " << heading << endl;
cout << "A = " << A << endl;
cout << "b = " << b << endl;
*/
// Solve for the least squares solution.
x = (A.transpose() * A).inverse() * A.transpose() * b;
// Get the mean of dTz since it has been accumulated
dTz /= num_valid_pts;
_fitness_scores[0] /= num_valid_pts;
_fitness_scores[1] /= num_valid_pts;
_fitness_scores[2] /= num_valid_pts;
// x = [cos(yaw) sin(yaw) dY]
x(0) = fabs(x(0)) > 1 ? x(0) / fabs(x(0)) : x(0);
double dyaw = -1.2 * atan2(x(1), x(0));
// Update the position
pos(1) += x(2); // y-update
pos(2) += dTz; // z-update
// Convert the orientation to 'rpy', update yaw and
// convert back to dcm.
Eigen::Matrix3d dcm = curr_pose.topLeftCorner<3, 3>();
rpy = utils::trans::dcm2rpy(dcm);
rpy(2) += dyaw;
//rpy(2) = heading; //####
dcm = utils::trans::rpy2dcm(rpy);
// Update the global pose matrix.
curr_pose.topLeftCorner(3, 3) = dcm;
curr_pose(1, 3) = pos(1);
curr_pose(2, 3) = pos(2);
// Transform points for next iteration.
pcl::transformPointCloud(*_cloud, *_cloud_aligned, curr_pose);
if(fabs(x(2)) < _yz_tol && fabs(dTz) < _yz_tol && fabs(dyaw) < _yaw_tol)
break;
}
_pose = curr_pose;
return iter;
}
bool RangeBasedTunnelLocalizer::get_pose(Eigen::Matrix4d &pose){
pose = _pose.cast<double>();
return true;
}
bool RangeBasedTunnelLocalizer::get_registered_pointcloud(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){
pc = _cloud_aligned;
return true;
}
bool RangeBasedTunnelLocalizer::get_covariance(Eigen::Matrix6d &cov, bool apply_fitness_result){
// ### I have to find a way to project uncertainties in orientation
// to other frame sets.
// ### I might have to fix some elements before inverting
Eigen::EigenSolver<Eigen::Matrix6d> es;
es.compute(_fim, true);
Eigen::MatrixXd D = es.eigenvalues().real().asDiagonal();
Eigen::MatrixXd V = es.eigenvectors().real();
bool reconstruct = false;
for(int i = 0 ; i < 6 ; i++)
if(D(i, i) < 0.00001){
D(i, i) = 0.00001;
reconstruct = true;
}
if(reconstruct)
_fim = (V.transpose() * D * V).real();
//cout << "FIM = [" << _fim << "];" << endl;
// ### This assumes uniform covariance for each rays, and superficially
// handles the uncertainties. I should first run ICP and then
// find '_fim' and so on. This will require a lot of bookkeeping etc.
// Thus leaving to a later version :)
if(apply_fitness_result){
// ### Is the rotation ypr/rpy ???
// We assume that 0.001 m^2 variance is perfect fit, or unit information.
D(0, 0) /= exp(_fitness_scores[0] / 0.001);
D(1, 1) /= exp(_fitness_scores[1] / 0.001);
D(2, 2) /= exp(_fitness_scores[2] / 0.001);
}
for(int i = 0 ; i < 6 ; i++)
D(i, i) = 1 / D(i, i) + 0.00001;
cov = (V * D * V.transpose());
//cout << "V = [" << V << "];" << endl;
//cout << "D = [" << D << "];" << endl;
//cout << "cov = [ " << cov << "];" << endl;
cov.topLeftCorner<3, 3> () = _pose.topLeftCorner<3, 3>().transpose() *
cov.topLeftCorner<3, 3>() *
_pose.topLeftCorner<3, 3>();
// Exclude the pose estimate along the x direction.
es.compute(cov, true);
D = es.eigenvalues().real().asDiagonal();
V = es.eigenvectors().real();
D(0, 0) = 0.00001;
D(4, 4) = 0.00009;
D(5, 5) = 0.00009;
cov = (V * D * V.transpose());
return true;
}
bool RangeBasedTunnelLocalizer::get_fitness_scores(double &y, double &z, double &yaw){
y = _fitness_scores[0];
z = _fitness_scores[1];
yaw = _fitness_scores[2];
return true;
}
bool RangeBasedTunnelLocalizer::get_correspondences(vector<pcl::PointXYZ> &sensor_pts, vector<pcl::PointXYZ> &map_pts){
int num_valid_pts = 0;
for(int i = 0 ; i < (int)_matched_map_pts.size() ; i++)
if(isfinite(_matched_map_pts[i].y))
num_valid_pts++;
map_pts.resize(num_valid_pts);
sensor_pts.resize(num_valid_pts);
for(int i = 0, j = 0 ; i < (int)_cloud_aligned->points.size() ; i++){
if(isfinite(_matched_map_pts[i].y)){
sensor_pts[j] = _cloud_aligned->points[i];
map_pts[j] = _matched_map_pts[i];
j++;
}
}
return true;
}
| 33.704663 | 179 | 0.657264 | ozaslan |
ed518a28c3b906413f7b0f6ec058afadb4bbea1b | 4,617 | inl | C++ | include/fileos/path.inl | napina/fileos | 44443d126d9c4faf1192196bfe88b556c4a7411f | [
"MIT"
] | 2 | 2017-05-10T06:05:54.000Z | 2021-03-31T13:14:49.000Z | include/fileos/path.inl | napina/fileos | 44443d126d9c4faf1192196bfe88b556c4a7411f | [
"MIT"
] | null | null | null | include/fileos/path.inl | napina/fileos | 44443d126d9c4faf1192196bfe88b556c4a7411f | [
"MIT"
] | null | null | null | /*=============================================================================
Copyright (c) 2013 Ville Ruusutie
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
#ifndef fileos_path_inl
#define fileos_path_inl
namespace fileos {
__forceinline Path::Path()
: m_buffer()
{
}
__forceinline Path::Path(size_t capasity)
: m_buffer(capasity)
{
}
__forceinline Path::Path(Path const& other)
: m_buffer(other.m_buffer)
{
}
/*template<typename T>
__forceinline Path::Path(T const* path)
: m_buffer(path)
{
fixSlashes();
}*/
template<typename T>
__forceinline Path::Path(T const* path, size_t count)
: m_buffer(path, count)
{
fixSlashes();
}
template<size_t Count>
__forceinline Path::Path(char const (&str)[Count])
: m_buffer(str)
{
fixSlashes();
}
template<size_t Count>
__forceinline Path::Path(wchar_t const (&str)[Count])
: m_buffer(str)
{
fixSlashes();
}
__forceinline void Path::reserve(size_t capasity)
{
m_buffer.reserve(capasity);
}
__forceinline void Path::clear()
{
m_buffer.clear();
}
__forceinline void Path::set(Path const& other)
{
m_buffer = other.m_buffer;
}
__forceinline void Path::set(containos::Utf8Slice const& slice)
{
m_buffer.set(slice);
fixSlashes();
}
template<>
__forceinline void Path::set(Path const* other)
{
m_buffer = other->m_buffer;
}
template<>
__forceinline void Path::set(containos::Utf8Slice const* slice)
{
m_buffer.set(*slice);
fixSlashes();
}
template<typename T>
__forceinline void Path::set(T const* path)
{
m_buffer.set(path);
fixSlashes();
}
template<typename T>
__forceinline void Path::set(T const* path, size_t count)
{
m_buffer.set(path, count);
fixSlashes();
}
__forceinline void Path::append(Path const& other)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(other.m_buffer);
fixSlashes();
}
__forceinline void Path::append(Utf8Slice const& slice)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(slice);
fixSlashes();
}
template<>
__forceinline void Path::append(Path const* other)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(other->m_buffer);
fixSlashes();
}
template<>
__forceinline void Path::append(Utf8Slice const* slice)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(*slice);
fixSlashes();
}
template<typename T>
__forceinline void Path::append(T const* str)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(str);
fixSlashes();
}
template<typename T>
__forceinline void Path::append(T const* str, size_t count)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(str, count);
fixSlashes();
}
__forceinline void Path::clone(Path const& from)
{
m_buffer.clone(from.m_buffer);
}
template<typename T>
__forceinline void Path::convertTo(T* buffer, size_t count) const
{
m_buffer.convertTo(buffer, count);
}
__forceinline uint8_t const* Path::data() const
{
return m_buffer.data();
}
__forceinline size_t Path::length() const
{
return m_buffer.length();
}
__forceinline bool Path::operator==(Path const& other) const
{
return m_buffer == other.m_buffer;
}
__forceinline bool Path::operator==(containos::Utf8Slice const& slice) const
{
return m_buffer == slice;
}
__forceinline bool Path::operator==(char const* str) const
{
return m_buffer == str;
}
__forceinline bool Path::operator==(wchar_t const* str) const
{
return m_buffer == str;
}
} // end of fileos
#endif
| 21.881517 | 79 | 0.690925 | napina |
ed51a54892790ba25f520c34ffed15509fb4b9e7 | 453 | cpp | C++ | S03/Enum.cpp | stevekeol/-Thinking-in-Cpp-PracticeCode | 5b147e704015bbda364ab069f1de58dcef7ab14a | [
"MIT"
] | 2 | 2017-06-20T12:16:30.000Z | 2021-11-12T12:06:57.000Z | S03/Enum.cpp | stevekeol/-Thinking-in-Cpp-PracticeCode | 5b147e704015bbda364ab069f1de58dcef7ab14a | [
"MIT"
] | null | null | null | S03/Enum.cpp | stevekeol/-Thinking-in-Cpp-PracticeCode | 5b147e704015bbda364ab069f1de58dcef7ab14a | [
"MIT"
] | null | null | null | //: S03:Enum.cpp
// From "Thinking in C++, 2nd Edition, Volume 1, Annotated Solutions Guide"
// by Chuck Allison, (c) 2001 MindView, Inc. all rights reserved
// Available at www.BruceEckel.com.
#include <iostream>
enum color {
BLACK,
RED,
GREEN,
BLUE,
WHITE
};
int main() {
using namespace std;
for (int hue = BLACK; hue <= WHITE; ++hue)
cout << hue << ' ';
}
/* Output:
0 1 2 3 4
*/
///:~
| 18.12 | 76 | 0.556291 | stevekeol |
ed544679088b86bdbec210bf4443dbe01fe57a0d | 3,869 | cpp | C++ | ThorEngine/Source Code/R_Mesh.cpp | markitus18/Game-Engine | ea9546a16f2e40d13002340b4cb6b42a33a41344 | [
"Unlicense"
] | null | null | null | ThorEngine/Source Code/R_Mesh.cpp | markitus18/Game-Engine | ea9546a16f2e40d13002340b4cb6b42a33a41344 | [
"Unlicense"
] | null | null | null | ThorEngine/Source Code/R_Mesh.cpp | markitus18/Game-Engine | ea9546a16f2e40d13002340b4cb6b42a33a41344 | [
"Unlicense"
] | null | null | null | #include "R_Mesh.h"
#include "OpenGL.h"
R_Mesh::R_Mesh() : Resource(ResourceType::MESH)
{
isExternal = true;
for (uint i = 0; i < max_buffer_type; i++)
{
buffers[i] = 0;
buffersSize[i] = 0;
}
}
R_Mesh::~R_Mesh()
{
}
void R_Mesh::CreateAABB()
{
aabb.SetNegativeInfinity();
aabb.Enclose((math::vec*)vertices, buffersSize[b_vertices]);
}
void R_Mesh::LoadOnMemory()
{
// Create a vertex array object which will hold all buffer objects
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Create a vertex buffer object to hold vertex positions
glGenBuffers(1, &buffers[b_vertices]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_vertices]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_vertices] * 3, vertices, GL_STATIC_DRAW);
// Create an element buffer object to hold indices
glGenBuffers(1, &buffers[b_indices]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[b_indices]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * buffersSize[b_indices], indices, GL_STATIC_DRAW);
// Set the vertex attrib pointer
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Create the array buffer for tex coords and enable attrib pointer
if (buffersSize[b_tex_coords] > 0)
{
glGenBuffers(1, &buffers[b_tex_coords]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_tex_coords]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_tex_coords] * 2, tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
// Create the array buffer for normals and enable attrib pointer
if (buffersSize[b_normals] > 0)
{
glGenBuffers(1, &buffers[b_normals]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_normals]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_normals] * 3, normals, GL_STATIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
void R_Mesh::LoadSkinnedBuffers(bool init)
{
if (init)
{
// Create a vertex array object which will hold all buffer objects
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Create a vertex buffer object to hold vertex positions
glGenBuffers(1, &buffers[b_vertices]);
// Create an element buffer object to hold indices
glGenBuffers(1, &buffers[b_indices]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[b_indices]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * buffersSize[b_indices], indices, GL_STATIC_DRAW);
// Set the vertex attrib pointer
glEnableVertexAttribArray(0);
//Create the array buffer for tex coords and enable attrib pointer
if (buffersSize[b_tex_coords] > 0)
{
glGenBuffers(1, &buffers[b_tex_coords]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_tex_coords]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_tex_coords] * 2, tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
glGenBuffers(1, &buffers[b_normals]);
}
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_vertices]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_vertices] * 3, vertices, GL_STREAM_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
// Create the array buffer for normals and enable attrib pointer
if (buffersSize[b_normals] > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_normals]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_normals] * 3, normals, GL_STREAM_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
void R_Mesh::FreeMemory()
{
//glDeleteBuffers(max_buffer_type, buffers);
} | 30.952 | 108 | 0.747738 | markitus18 |
ed56342a68c738c824389e349e942e22dc9c813c | 1,880 | cpp | C++ | src/model/seasonlistmodel.cpp | sailfish-os-apps/harbour-sailseries | df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c | [
"MIT"
] | null | null | null | src/model/seasonlistmodel.cpp | sailfish-os-apps/harbour-sailseries | df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c | [
"MIT"
] | null | null | null | src/model/seasonlistmodel.cpp | sailfish-os-apps/harbour-sailseries | df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c | [
"MIT"
] | null | null | null | #include "seasonlistmodel.h"
SeasonListModel::SeasonListModel(QObject *parent, DatabaseManager* dbmanager) :
QObject(parent)
{
m_dbmanager = dbmanager;
}
SeasonListModel::~SeasonListModel()
{
for (auto season : m_seasonListModel) {
delete season;
season = 0;
}
}
QQmlListProperty<SeasonData> SeasonListModel::getSeasonList()
{
return QQmlListProperty<SeasonData>(this, &m_seasonListModel, &SeasonListModel::seasonListCount, &SeasonListModel::seasonListAt);
}
// list handling methods
void SeasonListModel::seasonListAppend(QQmlListProperty<SeasonData>* prop, SeasonData* val)
{
SeasonListModel* seasonListModel = qobject_cast<SeasonListModel*>(prop->object);
seasonListModel->m_seasonListModel.append(val);
}
SeasonData* SeasonListModel::seasonListAt(QQmlListProperty<SeasonData>* prop, int index)
{
return (qobject_cast<SeasonListModel*>(prop->object))->m_seasonListModel.at(index);
}
int SeasonListModel::seasonListCount(QQmlListProperty<SeasonData>* prop)
{
return qobject_cast<SeasonListModel*>(prop->object)->m_seasonListModel.size();
}
void SeasonListModel::seasonListClear(QQmlListProperty<SeasonData>* prop)
{
qobject_cast<SeasonListModel*>(prop->object)->m_seasonListModel.clear();
}
void SeasonListModel::populateSeasonList(QString seriesID)
{
m_seasonListModel.clear();
int seasonsCount = m_dbmanager->seasonCount(seriesID.toInt());
for (int i = 1; i <= seasonsCount; ++i) {
QString banner = m_dbmanager->getSeasonBanner(seriesID.toInt(),i);
int watchedCount = m_dbmanager->watchedCountBySeason(seriesID.toInt(),i);
int totalCount = m_dbmanager->totalCountBySeason(seriesID.toInt(),i);
SeasonData* seasonData = new SeasonData(this, i, banner, watchedCount, totalCount);
m_seasonListModel.append(seasonData);
}
emit seasonListChanged();
}
| 29.84127 | 133 | 0.743617 | sailfish-os-apps |
ed5a55a0d431d28bd8c2e93e9da44b446141e59e | 20,129 | cc | C++ | code/machine/mips_sim.cc | barufa/nachos | c61004eb45144835180be12eefc250d470842d04 | [
"MIT"
] | 1 | 2019-10-21T02:22:16.000Z | 2019-10-21T02:22:16.000Z | code/machine/mips_sim.cc | barufa/Nachos | c61004eb45144835180be12eefc250d470842d04 | [
"MIT"
] | null | null | null | code/machine/mips_sim.cc | barufa/Nachos | c61004eb45144835180be12eefc250d470842d04 | [
"MIT"
] | null | null | null | /// Simulate a MIPS R2/3000 processor.
///
/// This code has been adapted from Ousterhout's MIPSSIM package. Byte
/// ordering is little-endian, so we can be compatible with DEC RISC systems.
///
/// DO NOT CHANGE -- part of the machine emulation
///
/// Copyright (c) 1992-1993 The Regents of the University of California.
/// 2016-2017 Docentes de la Universidad Nacional de Rosario.
/// All rights reserved. See `copyright.h` for copyright notice and
/// limitation of liability and disclaimer of warranty provisions.
#include "instruction.hh"
#include "machine.hh"
#include "threads/system.hh"
/// Simulate the execution of a user-level program on Nachos.
///
/// Called by the kernel when the program starts up; never returns.
///
/// This routine is re-entrant, in that it can be called multiple times
/// concurrently -- one for each thread executing user code.
void
Machine::Run()
{
Instruction * instr = new Instruction;
// Storage for decoded instruction.
if (debug.IsEnabled('m'))
printf("Starting to run at time %u\n", stats->totalTicks);
interrupt->SetStatus(USER_MODE);
for (;;) {
if (FetchInstruction(instr))
ExecInstruction(instr);
interrupt->OneTick();
if (singleStepper != nullptr && !singleStepper->Step())
singleStepper = nullptr;
}
}
/// Simulate effects of a delayed load.
///
/// NOTE -- `RaiseException`/`CheckInterrupts` must also call `DelayedLoad`,
/// since any delayed load must get applied before we trap to the kernel.
void
Machine::DelayedLoad(unsigned nextReg, int nextValue)
{
registers[registers[LOAD_REG]] = registers[LOAD_VALUE_REG];
registers[LOAD_REG] = nextReg;
registers[LOAD_VALUE_REG] = nextValue;
registers[0] = 0; // And always make sure R0 stays zero.
}
bool
Machine::FetchInstruction(Instruction * instr)
{
ASSERT(instr != nullptr);
int raw;
if (!ReadMem(registers[PC_REG], 4, &raw))
return false; // Exception occurred.
instr->value = raw;
instr->Decode();
if (debug.IsEnabled('m')) {
const struct OpString * str = &OP_STRINGS[instr->opCode];
ASSERT(instr->opCode <= MAX_OPCODE);
DEBUG('P', "At PC = 0x%X: ", registers[PC_REG]);
DEBUG_CONT('P', str->string, instr->RegFromType(str->args[0]),
instr->RegFromType(str->args[1]),
instr->RegFromType(str->args[2]));
DEBUG_CONT('P', "\n");
}
return true;
}
/// Simulate R2000 multiplication.
///
/// The words at `*hiPtr` and `*loPtr` are overwritten with the double-length
/// result of the multiplication.
static void
Mult(int a, int b, bool signedArith, int * hiPtr, int * loPtr)
{
ASSERT(hiPtr != nullptr);
ASSERT(loPtr != nullptr);
if (a == 0 || b == 0) {
*hiPtr = *loPtr = 0;
return;
}
// Compute the sign of the result, then make everything positive so
// unsigned computation can be done in the main loop.
bool negative = false;
if (signedArith) {
if (a < 0) {
negative = !negative;
a = -a;
}
if (b < 0) {
negative = !negative;
b = -b;
}
}
// Compute the result in unsigned arithmetic (check `a`'s bits one at a
// time, and add in a shifted value of `b`).
unsigned bLo = b;
unsigned bHi = 0;
unsigned lo = 0;
unsigned hi = 0;
for (unsigned i = 0; i < 32; i++) {
if (a & 1) {
lo += bLo;
if (lo < bLo) // Carry out of the low bits?
hi += 1;
hi += bHi;
if ((a & 0xFFFFFFFE) == 0)
break;
}
bHi <<= 1;
if (bLo & 0x80000000)
bHi |= 1;
bLo <<= 1;
a >>= 1;
}
// If the result is supposed to be negative, compute the two's complement
// of the double-word result.
if (negative) {
hi = ~hi;
lo = ~lo;
lo++;
if (lo == 0)
hi++;
}
*hiPtr = (int) hi;
*loPtr = (int) lo;
} // Mult
/// Execute one instruction from a user-level program.
///
/// If there is any kind of exception or interrupt, we invoke the exception
/// handler, and when it returns, we return to `Run`, which will re-invoke us
/// in a loop. This allows us to re-start the instruction execution from the
/// beginning, in case any of our state has changed. On a syscall, the OS
/// software must increment the PC so execution begins at the instruction
/// immediately after the syscall.
///
/// This routine is re-entrant, in that it can be called multiple times
/// concurrently -- one for each thread executing user code. We get
/// re-entrancy by never caching any data -- we always re-start the
/// simulation from scratch each time we are called (or after trapping back
/// to the Nachos kernel on an exception or interrupt), and we always store
/// all data back to the machine registers and memory before leaving. This
/// allows the Nachos kernel to control our behavior by controlling the
/// contents of memory, the translation table, and the register set.
void
Machine::ExecInstruction(const Instruction * instr)
{
int nextLoadReg = 0;
int nextLoadValue = 0; // Record delayed load operation, to apply in the
// future.
// Compute next pc, but do not install in case there is an error or
// branch.
int pcAfter = registers[NEXT_PC_REG] + 4;
int sum, diff, tmp, value;
unsigned rs, rt, imm;
// Execute the instruction (cf. Kane's book).
switch (instr->opCode) {
case OP_ADD:
sum = registers[instr->rs] + registers[instr->rt];
if (!((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT) &&
(registers[instr->rs] ^ sum) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rd] = sum;
break;
case OP_ADDI:
sum = registers[instr->rs] + instr->extra;
if (!((registers[instr->rs] ^ instr->extra) & SIGN_BIT) &&
(instr->extra ^ sum) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rt] = sum;
break;
case OP_ADDIU:
registers[instr->rt] = registers[instr->rs] + instr->extra;
break;
case OP_ADDU:
registers[instr->rd] = registers[instr->rs]
+ registers[instr->rt];
break;
case OP_AND:
registers[instr->rd] = registers[instr->rs]
& registers[instr->rt];
break;
case OP_ANDI:
registers[instr->rt] = registers[instr->rs]
& (instr->extra & 0xFFFF);
break;
case OP_BEQ:
if (registers[instr->rs] == registers[instr->rt])
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BGEZAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_BGEZ:
if (!(registers[instr->rs] & SIGN_BIT))
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BGTZ:
if (registers[instr->rs] > 0)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BLEZ:
if (registers[instr->rs] <= 0)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BLTZAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_BLTZ:
if (registers[instr->rs] & SIGN_BIT)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BNE:
if (registers[instr->rs] != registers[instr->rt])
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_DIV:
if (registers[instr->rt] == 0) {
registers[LO_REG] = 0;
registers[HI_REG] = 0;
} else {
registers[LO_REG] = registers[instr->rs]
/ registers[instr->rt];
registers[HI_REG] = registers[instr->rs]
% registers[instr->rt];
}
break;
case OP_DIVU:
rs = (unsigned) registers[instr->rs];
rt = (unsigned) registers[instr->rt];
if (rt == 0) {
registers[LO_REG] = 0;
registers[HI_REG] = 0;
} else {
tmp = rs / rt;
registers[LO_REG] = (int) tmp;
tmp = rs % rt;
registers[HI_REG] = (int) tmp;
}
break;
case OP_JAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_J:
pcAfter = (pcAfter & 0xF0000000) | IndexToAddr(instr->extra);
break;
case OP_JALR:
registers[instr->rd] = registers[NEXT_PC_REG] + 4;
case OP_JR:
pcAfter = registers[instr->rs];
break;
case OP_LB:
case OP_LBU:
tmp = registers[instr->rs] + instr->extra;
if (!ReadMem(tmp, 1, &value))
return;
if (value & 0x80 && instr->opCode == OP_LB)
value |= 0xFFFFFF00;
else
value &= 0xFF;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LH:
case OP_LHU:
tmp = registers[instr->rs] + instr->extra;
if (tmp & 0x1) {
RaiseException(ADDRESS_ERROR_EXCEPTION, tmp);
return;
}
if (!ReadMem(tmp, 2, &value))
return;
if (value & 0x8000 && instr->opCode == OP_LH)
value |= 0xFFFF0000;
else
value &= 0xFFFF;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LUI:
DEBUG('P', "Executing: LUI r%d,%d\n", instr->rt, instr->extra);
registers[instr->rt] = instr->extra << 16;
break;
case OP_LW:
tmp = registers[instr->rs] + instr->extra;
if (tmp & 0x3) {
RaiseException(ADDRESS_ERROR_EXCEPTION, tmp);
return;
}
if (!ReadMem(tmp, 4, &value))
return;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LWL:
tmp = registers[instr->rs] + instr->extra;
// `ReadMem` assumes all 4 byte requests are aligned on an even
// word boundary. Also, the little endian/big endian swap code
// would fail (I think) if the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp, 4, &value))
return;
if (registers[LOAD_REG] == instr->rt)
nextLoadValue = registers[LOAD_VALUE_REG];
else
nextLoadValue = registers[instr->rt];
switch (tmp & 0x3) {
case 0:
nextLoadValue = value;
break;
case 1:
nextLoadValue = (nextLoadValue & 0xFF) | value << 8;
break;
case 2:
nextLoadValue = (nextLoadValue & 0xFFFF) | value << 16;
break;
case 3:
nextLoadValue = (nextLoadValue & 0xFFFFFF) | value << 24;
break;
}
nextLoadReg = instr->rt;
break;
case OP_LWR:
tmp = registers[instr->rs] + instr->extra;
// `ReadMem` assumes all 4 byte requests are aligned on an even
// word boundary. Also, the little endian/big endian swap code
// would fail (I think) if the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp, 4, &value))
return;
if (registers[LOAD_REG] == instr->rt)
nextLoadValue = registers[LOAD_VALUE_REG];
else
nextLoadValue = registers[instr->rt];
switch (tmp & 0x3) {
case 0:
nextLoadValue = (nextLoadValue & 0xFFFFFF00)
| (value >> 24 & 0xFF);
break;
case 1:
nextLoadValue = (nextLoadValue & 0xFFFF0000)
| (value >> 16 & 0xFFFF);
break;
case 2:
nextLoadValue = (nextLoadValue & 0xFF000000)
| (value >> 8 & 0xFFFFFF);
break;
case 3:
nextLoadValue = value;
break;
}
nextLoadReg = instr->rt;
break;
case OP_MFHI:
registers[instr->rd] = registers[HI_REG];
break;
case OP_MFLO:
registers[instr->rd] = registers[LO_REG];
break;
case OP_MTHI:
registers[HI_REG] = registers[instr->rs];
break;
case OP_MTLO:
registers[LO_REG] = registers[instr->rs];
break;
case OP_MULT:
Mult(registers[instr->rs], registers[instr->rt],
true, ®isters[HI_REG], ®isters[LO_REG]);
break;
case OP_MULTU:
Mult(registers[instr->rs], registers[instr->rt],
false, ®isters[HI_REG], ®isters[LO_REG]);
break;
case OP_NOR:
registers[instr->rd] = ~(registers[instr->rs]
| registers[instr->rt]);
break;
case OP_OR:
registers[instr->rd] = registers[instr->rs]
| registers[instr->rt];
break;
case OP_ORI:
registers[instr->rt] = registers[instr->rs]
| (instr->extra & 0xFFFF);
break;
case OP_SB:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
1, registers[instr->rt]))
return;
break;
case OP_SH:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
2, registers[instr->rt]))
return;
break;
case OP_SLL:
registers[instr->rd] = registers[instr->rt] << instr->extra;
break;
case OP_SLLV:
registers[instr->rd] = registers[instr->rt]
<< (registers[instr->rs] & 0x1F);
break;
case OP_SLT:
if (registers[instr->rs] < registers[instr->rt])
registers[instr->rd] = 1;
else
registers[instr->rd] = 0;
break;
case OP_SLTI:
if (registers[instr->rs] < instr->extra)
registers[instr->rt] = 1;
else
registers[instr->rt] = 0;
break;
case OP_SLTIU:
rs = registers[instr->rs];
imm = instr->extra;
if (rs < imm)
registers[instr->rt] = 1;
else
registers[instr->rt] = 0;
break;
case OP_SLTU:
rs = registers[instr->rs];
rt = registers[instr->rt];
if (rs < rt)
registers[instr->rd] = 1;
else
registers[instr->rd] = 0;
break;
case OP_SRA:
registers[instr->rd] = registers[instr->rt] >> instr->extra;
break;
case OP_SRAV:
registers[instr->rd] = registers[instr->rt]
>> (registers[instr->rs] & 0x1F);
break;
case OP_SRL:
tmp = registers[instr->rt];
tmp >>= instr->extra;
registers[instr->rd] = tmp;
break;
case OP_SRLV:
tmp = registers[instr->rt];
tmp >>= registers[instr->rs] & 0x1F;
registers[instr->rd] = tmp;
break;
case OP_SUB:
diff = registers[instr->rs] - registers[instr->rt];
if ((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT &&
(registers[instr->rs] ^ diff) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rd] = diff;
break;
case OP_SUBU:
registers[instr->rd] = registers[instr->rs]
- registers[instr->rt];
break;
case OP_SW:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
4, registers[instr->rt]))
return;
break;
case OP_SWL:
tmp = registers[instr->rs] + instr->extra;
// The little endian/big endian swap code would fail (I think) if
// the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp & ~0x3, 4, &value))
return;
switch (tmp & 0x3) {
case 0:
value = registers[instr->rt];
break;
case 1:
value = (value & 0xFF000000)
| (registers[instr->rt] >> 8 & 0xFFFFFF);
break;
case 2:
value = (value & 0xFFFF0000)
| (registers[instr->rt] >> 16 & 0xFFFF);
break;
case 3:
value = (value & 0xFFFFFF00)
| (registers[instr->rt] >> 24 & 0xFF);
break;
}
if (!WriteMem(tmp & ~0x3, 4, value))
return;
break;
case OP_SWR:
tmp = registers[instr->rs] + instr->extra;
// The little endian/big endian swap code would fail (I think) if
// the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp & ~0x3, 4, &value))
return;
switch (tmp & 0x3) {
case 0:
value = (value & 0xFFFFFF)
| registers[instr->rt] << 24;
break;
case 1:
value = (value & 0xFFFF)
| registers[instr->rt] << 16;
break;
case 2:
value = (value & 0xFF) | registers[instr->rt] << 8;
break;
case 3:
value = registers[instr->rt];
break;
}
if (!WriteMem(tmp & ~0x3, 4, value))
return;
break;
case OP_SYSCALL:
RaiseException(SYSCALL_EXCEPTION, 0);
return;
case OP_XOR:
registers[instr->rd] = registers[instr->rs]
^ registers[instr->rt];
break;
case OP_XORI:
registers[instr->rt] = registers[instr->rs]
^ (instr->extra & 0xFFFF);
break;
case OP_RES:
case OP_UNIMP:
RaiseException(ILLEGAL_INSTR_EXCEPTION, 0);
return;
default:
ASSERT(false);
}
// Now we have successfully executed the instruction.
// Do any delayed load operation.
DelayedLoad(nextLoadReg, nextLoadValue);
// Advance program counters.
registers[PREV_PC_REG] = registers[PC_REG];
// For debugging, in case we are jumping into lala-land.
registers[PC_REG] = registers[NEXT_PC_REG];
registers[NEXT_PC_REG] = pcAfter;
} // Machine::ExecInstruction
| 31.063272 | 78 | 0.498038 | barufa |
ed5d40ec16569384379998e22dd30acdc9503ab0 | 8,022 | cpp | C++ | src/arch/ArchHooks/ArchHooks_Win32.cpp | caiohsr14/stepmania | 7d33efe587c75a683938aeabafc1ec2bec3007d6 | [
"MIT"
] | null | null | null | src/arch/ArchHooks/ArchHooks_Win32.cpp | caiohsr14/stepmania | 7d33efe587c75a683938aeabafc1ec2bec3007d6 | [
"MIT"
] | null | null | null | src/arch/ArchHooks/ArchHooks_Win32.cpp | caiohsr14/stepmania | 7d33efe587c75a683938aeabafc1ec2bec3007d6 | [
"MIT"
] | null | null | null | #include "global.h"
#include "ArchHooks_Win32.h"
#include "RageUtil.h"
#include "RageLog.h"
#include "RageThreads.h"
#include "ProductInfo.h"
#include "archutils/win32/AppInstance.h"
#include "archutils/win32/crash.h"
#include "archutils/win32/DebugInfoHunt.h"
#include "archutils/win32/ErrorStrings.h"
#include "archutils/win32/RestartProgram.h"
#include "archutils/win32/GotoURL.h"
#include "archutils/Win32/RegistryAccess.h"
static HANDLE g_hInstanceMutex;
static bool g_bIsMultipleInstance = false;
#if _MSC_VER >= 1400 // VC8
void InvalidParameterHandler( const wchar_t *szExpression, const wchar_t *szFunction, const wchar_t *szFile,
unsigned int iLine, uintptr_t pReserved )
{
FAIL_M( "Invalid parameter" ); //TODO: Make this more informative
}
#endif
ArchHooks_Win32::ArchHooks_Win32()
{
HOOKS = this;
/* Disable critical errors, and handle them internally. We never want the
* "drive not ready", etc. dialogs to pop up. */
SetErrorMode( SetErrorMode(0) | SEM_FAILCRITICALERRORS );
CrashHandler::CrashHandlerHandleArgs( g_argc, g_argv );
SetUnhandledExceptionFilter( CrashHandler::ExceptionHandler );
#if _MSC_VER >= 1400 // VC8
_set_invalid_parameter_handler( InvalidParameterHandler );
#endif
/* Windows boosts priority on keyboard input, among other things. Disable that for
* the main thread. */
SetThreadPriorityBoost( GetCurrentThread(), TRUE );
g_hInstanceMutex = CreateMutex( NULL, TRUE, PRODUCT_ID );
g_bIsMultipleInstance = false;
if( GetLastError() == ERROR_ALREADY_EXISTS )
g_bIsMultipleInstance = true;
}
ArchHooks_Win32::~ArchHooks_Win32()
{
CloseHandle( g_hInstanceMutex );
}
void ArchHooks_Win32::DumpDebugInfo()
{
/* This is a good time to do the debug search: before we actually
* start OpenGL (in case something goes wrong). */
SearchForDebugInfo();
}
struct CallbackData
{
HWND hParent;
HWND hResult;
};
// Like GW_ENABLEDPOPUP:
static BOOL CALLBACK GetEnabledPopup( HWND hWnd, LPARAM lParam )
{
CallbackData *pData = (CallbackData *) lParam;
if( GetParent(hWnd) != pData->hParent )
return TRUE;
if( (GetWindowLong(hWnd, GWL_STYLE) & WS_POPUP) != WS_POPUP )
return TRUE;
if( !IsWindowEnabled(hWnd) )
return TRUE;
pData->hResult = hWnd;
return FALSE;
}
bool ArchHooks_Win32::CheckForMultipleInstances(int argc, char* argv[])
{
if( !g_bIsMultipleInstance )
return false;
/* Search for the existing window. Prefer to use the class name, which is less likely to
* have a false match, and will match the gameplay window. If that fails, try the window
* name, which should match the loading window. */
HWND hWnd = FindWindow( PRODUCT_ID, NULL );
if( hWnd == NULL )
hWnd = FindWindow( NULL, PRODUCT_ID );
if( hWnd != NULL )
{
/* If the application has a model dialog box open, we want to be sure to give focus to it,
* not the main window. */
CallbackData data;
data.hParent = hWnd;
data.hResult = NULL;
EnumWindows( GetEnabledPopup, (LPARAM) &data );
if( data.hResult != NULL )
SetForegroundWindow( data.hResult );
else
SetForegroundWindow( hWnd );
// Send the command line to the existing window.
vector<RString> vsArgs;
for( int i=0; i<argc; i++ )
vsArgs.push_back( argv[i] );
RString sAllArgs = join("|", vsArgs);
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.cbData = sAllArgs.size();
cds.lpData = (void*)sAllArgs.data();
SendMessage(
(HWND)hWnd, // HWND hWnd = handle of destination window
WM_COPYDATA,
(WPARAM)NULL, // HANDLE OF SENDING WINDOW
(LPARAM)&cds ); // 2nd msg parameter = pointer to COPYDATASTRUCT
}
return true;
}
void ArchHooks_Win32::RestartProgram()
{
Win32RestartProgram();
}
void ArchHooks_Win32::SetTime( tm newtime )
{
SYSTEMTIME st;
ZERO( st );
st.wYear = (WORD)newtime.tm_year+1900;
st.wMonth = (WORD)newtime.tm_mon+1;
st.wDay = (WORD)newtime.tm_mday;
st.wHour = (WORD)newtime.tm_hour;
st.wMinute = (WORD)newtime.tm_min;
st.wSecond = (WORD)newtime.tm_sec;
st.wMilliseconds = 0;
SetLocalTime( &st );
}
void ArchHooks_Win32::BoostPriority()
{
/* We just want a slight boost, so we don't skip needlessly if something happens
* in the background. We don't really want to be high-priority--above normal should
* be enough. However, ABOVE_NORMAL_PRIORITY_CLASS is only supported in Win2000
* and later. */
OSVERSIONINFO version;
version.dwOSVersionInfoSize=sizeof(version);
if( !GetVersionEx(&version) )
{
LOG->Warn( werr_ssprintf(GetLastError(), "GetVersionEx failed") );
return;
}
#ifndef ABOVE_NORMAL_PRIORITY_CLASS
#define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000
#endif
DWORD pri = HIGH_PRIORITY_CLASS;
if( version.dwMajorVersion >= 5 )
pri = ABOVE_NORMAL_PRIORITY_CLASS;
/* Be sure to boost the app, not the thread, to make sure the
* sound thread stays higher priority than the main thread. */
SetPriorityClass( GetCurrentProcess(), pri );
}
void ArchHooks_Win32::UnBoostPriority()
{
SetPriorityClass( GetCurrentProcess(), NORMAL_PRIORITY_CLASS );
}
void ArchHooks_Win32::SetupConcurrentRenderingThread()
{
SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL );
}
bool ArchHooks_Win32::GoToURL( const RString &sUrl )
{
return ::GotoURL( sUrl );
}
float ArchHooks_Win32::GetDisplayAspectRatio()
{
DEVMODE dm;
ZERO( dm );
dm.dmSize = sizeof(dm);
BOOL bResult = EnumDisplaySettings( NULL, ENUM_REGISTRY_SETTINGS, &dm );
ASSERT( bResult != 0 );
return dm.dmPelsWidth / (float)dm.dmPelsHeight;
}
RString ArchHooks_Win32::GetClipboard()
{
HGLOBAL hgl;
LPTSTR lpstr;
RString ret;
// First make sure that the clipboard actually contains a string
// (or something stringifiable)
if(unlikely( !IsClipboardFormatAvailable( CF_TEXT ) )) return "";
// Yes. All this mess just to gain access to the string stored by the clipboard.
// I'm having flashbacks to Berkeley sockets.
if(unlikely( !OpenClipboard( NULL ) ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: OpenClipboard() failed" )); return ""; }
hgl = GetClipboardData( CF_TEXT );
if(unlikely( hgl == NULL ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: GetClipboardData() failed" )); CloseClipboard(); return ""; }
lpstr = (LPTSTR) GlobalLock( hgl );
if(unlikely( lpstr == NULL ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: GlobalLock() failed" )); CloseClipboard(); return ""; }
// And finally, we have a char (or wchar_t) array of the clipboard contents,
// pointed to by sToPaste.
// (Hopefully.)
#ifdef UNICODE
ret = WStringToRString( wstring()+*lpstr );
#else
ret = RString( lpstr );
#endif
// And now we clean up.
GlobalUnlock( hgl );
CloseClipboard();
return ret;
}
/*
* (c) 2003-2004 Glenn Maynard, Chris Danford
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 30.271698 | 133 | 0.733732 | caiohsr14 |
ed5ed317aacfd450f282d0974ada1bb154a12e85 | 709 | cc | C++ | Question/全排列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | Question/全排列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | Question/全排列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | class Solution {
public:
void Perm(vector<vector<int>>& ret, vector<int>& nums, int index, int size){
//结束条件
if(index == size){
vector<int> tmp = nums;
ret.push_back(tmp);
return;
}
for(int i = index; i < size; i++){
//在0位置依次固定nums中的每一个数
//之后再固定1,2,3位置
swap(nums[i], nums[index]);
//向下递归(分治思想)
Perm(ret, nums, index + 1, size);
//还原原数组,避免重复
swap(nums[i], nums[index]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ret;
Perm(ret, nums, 0, nums.size());
return ret;
}
};
| 23.633333 | 80 | 0.461213 | lkimprove |
ed5ff105e5090fa080564478bbcb3e570a821284 | 399 | cpp | C++ | warm-up-contest/data/star/gen.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | 3 | 2019-07-30T10:43:58.000Z | 2019-07-30T10:46:05.000Z | warm-up-contest/data/star/gen.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | null | null | null | warm-up-contest/data/star/gen.cpp | yuchong-pan/my-oi-lectures | 721ff870b5cc388ef81961bf1a96361a74e2d896 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
using namespace std;
char cmd[100];
int main() {
for (int i = 1; i <= 10; i++) {
sprintf(cmd, "cp star%d.in star.in", i);
system(cmd);
sprintf(cmd, "./star");
system(cmd);
sprintf(cmd, "mv star.out star%d.out", i);
system(cmd);
sprintf(cmd, "rm star.in");
system(cmd);
}
return 0;
}
| 19 | 50 | 0.506266 | yuchong-pan |
ed64f4379ab6d94dbefb2750a80656e68312ed4c | 1,307 | hpp | C++ | chapter03/InputComponent.hpp | AconCavy/gpcpp | 70d06e00f9ffc4dea580890a8b95027b32f5a9f6 | [
"MIT"
] | null | null | null | chapter03/InputComponent.hpp | AconCavy/gpcpp | 70d06e00f9ffc4dea580890a8b95027b32f5a9f6 | [
"MIT"
] | null | null | null | chapter03/InputComponent.hpp | AconCavy/gpcpp | 70d06e00f9ffc4dea580890a8b95027b32f5a9f6 | [
"MIT"
] | null | null | null | #ifndef GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
#define GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
#include "MoveComponent.hpp"
namespace gpcpp::c03 {
class InputComponent : public MoveComponent {
public:
explicit InputComponent(class Actor *Owner);
void processInput(const uint8_t *KeyState) override;
[[nodiscard]] float getMaxAngularSpeed() const { return MaxAngularSpeed; }
[[nodiscard]] float getMaxForward() const { return MaxForwardSpeed; }
[[nodiscard]] int getForwardKey() const { return ForwardKey; }
[[nodiscard]] int getBackKey() const { return BackKey; }
[[nodiscard]] int getClockwiseKey() const { return ClockwiseKey; }
[[nodiscard]] int getCounterClockwiseKey() const {
return CounterClockwiseKey;
}
void setMaxAngularSpeed(float Speed) { MaxAngularSpeed = Speed; }
void setMaxForwardSpeed(float Speed) { MaxForwardSpeed = Speed; }
void setForwardKey(int Key) { ForwardKey = Key; }
void setBackKey(int Key) { BackKey = Key; }
void setClockwiseKey(int Key) { ClockwiseKey = Key; }
void setCounterClockwiseKey(int Key) { CounterClockwiseKey = Key; }
private:
float MaxAngularSpeed;
float MaxForwardSpeed;
int ForwardKey;
int BackKey;
int ClockwiseKey;
int CounterClockwiseKey;
};
} // namespace gpcpp::c03
#endif // GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
| 31.119048 | 76 | 0.752104 | AconCavy |
ed6a08e905256517309d069a0b585d1fc66f6d7b | 348 | hpp | C++ | modules/math/source/blub/math/rectangle.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 96 | 2015-02-02T20:01:24.000Z | 2021-11-14T20:33:29.000Z | modules/math/source/blub/math/rectangle.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 12 | 2016-06-04T15:45:30.000Z | 2020-02-04T11:10:51.000Z | modules/math/source/blub/math/rectangle.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 19 | 2015-09-22T01:21:45.000Z | 2020-09-30T09:52:27.000Z | #ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "vector2.hpp"
namespace blub
{
class rectangle
{
public:
vector2 topLeft, rightBottom;
rectangle(void);
rectangle(const vector2 &topLeft_, const vector2 &rightBottom_);
void merge(const rectangle &other);
void merge(const vector2 &other);
};
}
#endif // RECTANGLE_HPP
| 14.5 | 68 | 0.721264 | qwertzui11 |
ed6ce8fb3e469fba323f9450e3f97fc44be7d8aa | 236 | cpp | C++ | cpp/new_features/cpp20/aggregate.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | 2 | 2019-12-21T00:53:47.000Z | 2020-01-01T10:36:30.000Z | cpp/new_features/cpp20/aggregate.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | cpp/new_features/cpp20/aggregate.cpp | KaiserLancelot/Cpp-Primer | a4791a6765f0b6c864e8881e6a5328e2a3d68974 | [
"MIT"
] | null | null | null | /**
* @ Author: KaiserLancelot
* @ Create Time: 2020-05-14 06:26:07
* @ Modified time: 2020-05-15 02:16:50
*/
#include <cstdint>
struct A {
std::int32_t x;
std::int32_t y;
std::int32_t z;
};
// TODO 编译器实现不完整
int main() {}
| 13.111111 | 39 | 0.605932 | KaiserLancelot |
ed6ea34c796889ff5aed0e4f2a185fe0c4836f90 | 1,374 | hpp | C++ | include/librandom/random.hpp | averrin/citygen-viewer | 6bf44a91c97d79bb9871f9571d3f8a7213b09505 | [
"MIT"
] | null | null | null | include/librandom/random.hpp | averrin/citygen-viewer | 6bf44a91c97d79bb9871f9571d3f8a7213b09505 | [
"MIT"
] | null | null | null | include/librandom/random.hpp | averrin/citygen-viewer | 6bf44a91c97d79bb9871f9571d3f8a7213b09505 | [
"MIT"
] | null | null | null | #ifndef __RANDOM_H_
#define __RANDOM_H_
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
namespace R {
// float R(float min, float max) {
// return min + static_cast<float>(rand()) /
// (static_cast<float>(RAND_MAX / (max - min)));
// ;
// }
// float R() { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX); }
// int Z(int min, int max) { return rand() % (max - min + 1) + min; }
// int Z() { return rand() % 100; }
// int N(int mean, int dev) {
// std::normal_distribution<> d{double(mean), double(dev)};
// return std::round(d(gen));
// }
class Generator {
private:
std::mt19937 *gen;
public:
int seed;
Generator() { updateSeed(); }
void updateSeed() {
setSeed(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
void setSeed(int s) {
seed = s;
gen = new std::mt19937(seed);
}
int R() {
std::uniform_int_distribution<> dis(0, RAND_MAX);
return dis(*gen);
}
int R(float min, float max) {
std::uniform_real_distribution<> dis(min, max);
return dis(*gen);
}
int R(int min, int max) {
std::uniform_int_distribution<> dis(min, max);
return dis(*gen);
}
};
} // namespace R
#endif // __RANDOM_H_
| 20.507463 | 82 | 0.597525 | averrin |
ed74c682f9694601e7855a9d62431763a70407b6 | 2,840 | cpp | C++ | shadow/core/network.cpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 20 | 2017-07-04T11:22:47.000Z | 2022-01-16T03:58:32.000Z | shadow/core/network.cpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 2 | 2017-12-03T13:07:39.000Z | 2021-01-13T11:11:52.000Z | shadow/core/network.cpp | junluan/shadow | 067d1c51d7c38bc1c985008a2e2e1599bbf11a8c | [
"Apache-2.0"
] | 10 | 2017-09-30T05:06:30.000Z | 2020-11-13T05:43:44.000Z | #include "network.hpp"
#include "network_impl.hpp"
namespace Shadow {
Network::Network() { engine_ = std::make_shared<NetworkImpl>(); }
void Network::LoadXModel(const shadow::NetParam& net_param,
const ArgumentHelper& arguments) {
engine_->LoadXModel(net_param, arguments);
}
void Network::Forward(
const std::map<std::string, void*>& data_map,
const std::map<std::string, std::vector<int>>& shape_map) {
engine_->Forward(data_map, shape_map);
}
#define INSTANTIATE_GET_BLOB(T) \
template <> \
const T* Network::GetBlobDataByName<T>(const std::string& blob_name, \
const std::string& locate) { \
return engine_->GetBlobDataByName<T>(blob_name, locate); \
} \
template <> \
std::vector<int> Network::GetBlobShapeByName<T>( \
const std::string& blob_name) const { \
return engine_->GetBlobShapeByName(blob_name); \
}
INSTANTIATE_GET_BLOB(std::int64_t);
INSTANTIATE_GET_BLOB(std::int32_t);
INSTANTIATE_GET_BLOB(std::int16_t);
INSTANTIATE_GET_BLOB(std::int8_t);
INSTANTIATE_GET_BLOB(std::uint64_t);
INSTANTIATE_GET_BLOB(std::uint32_t);
INSTANTIATE_GET_BLOB(std::uint16_t);
INSTANTIATE_GET_BLOB(std::uint8_t);
INSTANTIATE_GET_BLOB(float);
INSTANTIATE_GET_BLOB(bool);
#undef INSTANTIATE_GET_BLOB
const std::vector<std::string>& Network::in_blob() const {
return engine_->in_blob();
}
const std::vector<std::string>& Network::out_blob() const {
return engine_->out_blob();
}
bool Network::has_argument(const std::string& name) const {
return engine_->has_argument(name);
}
#define INSTANTIATE_ARGUMENT(T) \
template <> \
T Network::get_single_argument<T>(const std::string& name, \
const T& default_value) const { \
return engine_->get_single_argument<T>(name, default_value); \
} \
template <> \
std::vector<T> Network::get_repeated_argument<T>( \
const std::string& name, const std::vector<T>& default_value) const { \
return engine_->get_repeated_argument<T>(name, default_value); \
}
INSTANTIATE_ARGUMENT(float);
INSTANTIATE_ARGUMENT(int);
INSTANTIATE_ARGUMENT(bool);
INSTANTIATE_ARGUMENT(std::string);
#undef INSTANTIATE_ARGUMENT
} // namespace Shadow
| 38.378378 | 77 | 0.551408 | junluan |
ed7bec52e1ce340fcc0d8beffff026e9836b89b5 | 422 | cpp | C++ | polygons/translationgraphwidget.cpp | humble-barnacle001/qt-raster-lines | 7c5d38d6d6dd802901702b97084df3db12151e2e | [
"MIT"
] | null | null | null | polygons/translationgraphwidget.cpp | humble-barnacle001/qt-raster-lines | 7c5d38d6d6dd802901702b97084df3db12151e2e | [
"MIT"
] | null | null | null | polygons/translationgraphwidget.cpp | humble-barnacle001/qt-raster-lines | 7c5d38d6d6dd802901702b97084df3db12151e2e | [
"MIT"
] | null | null | null | #include "translationgraphwidget.h"
TranslationGraphWidget::TranslationGraphWidget(QWidget *parent)
: PolygonGraphWidget(parent), p(QPoint(0, 0))
{
}
void TranslationGraphWidget::translateXYChanged(const QPoint &p)
{
this->p = p;
}
void TranslationGraphWidget::performOperation()
{
foreach (auto pp, polygon)
{
editPixMap(QPoint(pp.x() + p.x(), pp.y() + p.y()), qMakePair(true, false));
}
}
| 21.1 | 83 | 0.682464 | humble-barnacle001 |
ed7c595698362fe1ed4489098912b9d9e642e69e | 1,868 | cpp | C++ | plugins/single_plugins/rotator.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | 3 | 2019-01-16T14:43:24.000Z | 2019-10-09T10:07:33.000Z | plugins/single_plugins/rotator.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | null | null | null | plugins/single_plugins/rotator.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | 1 | 2019-05-07T09:46:58.000Z | 2019-05-07T09:46:58.000Z | #include <output.hpp>
#include <core.hpp>
#include "../../shared/config.hpp"
#include <linux/input-event-codes.h>
#include <compositor.h>
class wayfire_rotator : public wayfire_plugin_t {
key_callback up, down, left, right;
public:
void init(wayfire_config *config) {
grab_interface->name = "rotator";
grab_interface->abilities_mask = WF_ABILITY_NONE;
auto section = config->get_section("rotator");
wayfire_key up_key = section->get_key("rotate_up",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_UP});
wayfire_key down_key = section->get_key("rotate_down",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_DOWN});
wayfire_key left_key = section->get_key("rotate_left",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_LEFT});
wayfire_key right_key = section->get_key("rotate_right",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_RIGHT});
up = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_NORMAL);
};
down = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_180);
};
left = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_270);
};
right = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_90);
};
output->add_key((weston_keyboard_modifier)up_key.mod, up_key.keyval, &up);
output->add_key((weston_keyboard_modifier)down_key.mod, down_key.keyval, &down);
output->add_key((weston_keyboard_modifier)left_key.mod, left_key.keyval, &left);
output->add_key((weston_keyboard_modifier)right_key.mod, right_key.keyval, &right);
}
};
extern "C" {
wayfire_plugin_t *newInstance() {
return new wayfire_rotator();
}
}
| 36.627451 | 91 | 0.645075 | SirCmpwn |
142ec8b1666cace04a2efd094e0f325bb83173fc | 647 | cpp | C++ | UVa/1203 - Argus.cpp | geniustanley/problem-solving | 2b83c5c8197fa8fe2277367027b392a2911d4a28 | [
"Apache-2.0"
] | 1 | 2018-11-21T07:36:16.000Z | 2018-11-21T07:36:16.000Z | UVa/1203 - Argus.cpp | geniustanley/problem-solving | 2b83c5c8197fa8fe2277367027b392a2911d4a28 | [
"Apache-2.0"
] | null | null | null | UVa/1203 - Argus.cpp | geniustanley/problem-solving | 2b83c5c8197fa8fe2277367027b392a2911d4a28 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <map>
using namespace std;
int main(void)
{
int qnum, r, n, f, s;
char c[10];
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
map<int, int> m;
while (EOF != scanf("%s", c) && strcmp(c, "#")) {
scanf("%d %d", &qnum, &r);
pq.push(pair<int, int> (r, qnum));
m[qnum] = r;
}
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("%d\n", pq.top().second);
f = pq.top().first;
s = pq.top().second;
pq.push(pair<int, int> (((f/m[s])+1)*m[s], s));
pq.pop();
}
return 0;
}
| 19.029412 | 88 | 0.517774 | geniustanley |
143193c52e1cd4b1ba91759295778bea80d8b65d | 21 | cpp | C++ | core/src/BVH.cpp | lonelywm/cuda_path_tracer | d99f0b682ad7f64fa127ca3604d0eab26f61452c | [
"MIT"
] | 1 | 2021-06-12T11:33:12.000Z | 2021-06-12T11:33:12.000Z | core/src/BVH.cpp | lonelywm/cuda_path_tracer | d99f0b682ad7f64fa127ca3604d0eab26f61452c | [
"MIT"
] | null | null | null | core/src/BVH.cpp | lonelywm/cuda_path_tracer | d99f0b682ad7f64fa127ca3604d0eab26f61452c | [
"MIT"
] | null | null | null | #include "../BVH.h"
| 7 | 19 | 0.52381 | lonelywm |
14365cef8d2e7da1381afc9eb47e07f73172b976 | 2,569 | hpp | C++ | gamebase/Player.hpp | GenBrg/MagicCastlevania | 76ed248d4f0362ea92d29a159a2027d5b16c8a7b | [
"CC-BY-4.0"
] | 2 | 2020-10-31T01:34:42.000Z | 2020-12-08T15:16:22.000Z | gamebase/Player.hpp | GenBrg/MagicCastlevania | 76ed248d4f0362ea92d29a159a2027d5b16c8a7b | [
"CC-BY-4.0"
] | 50 | 2020-10-31T01:31:56.000Z | 2020-12-11T15:13:43.000Z | gamebase/Player.hpp | GenBrg/MagicCastlevania | 76ed248d4f0362ea92d29a159a2027d5b16c8a7b | [
"CC-BY-4.0"
] | null | null | null | #pragma once
#include <engine/MovementComponent.hpp>
#include <engine/Transform2D.hpp>
#include <engine/InputSystem.hpp>
#include <engine/TimerGuard.hpp>
#include <engine/Animation.hpp>
#include <engine/Mob.hpp>
#include <engine/Attack.hpp>
#include <gamebase/Buff.hpp>
#include <gamebase/Inventory.hpp>
#include <Sprite.hpp>
#include <DrawSprites.hpp>
#include <glm/glm.hpp>
#include <chrono>
#include <string>
#include <unordered_map>
#include <string>
#include <vector>
class Room;
class Player : public Mob {
public:
virtual void UpdateImpl(float elapsed) override;
virtual void OnDie() override;
virtual Animation* GetAnimation(AnimationState state) override;
void UpdatePhysics(float elapsed, const std::vector<Collider*>& colliders_to_consider);
void StopMovement() { movement_component_.StopMovement(); }
void SetPosition(const glm::vec2& pos);
void Reset();
void AddBuff(const Buff& buff) { buff_ = buff; }
void ClearBuff();
void AddHp(int hp);
void AddMp(int mp);
void AddExp(int exp);
void AddCoin(int coin);
int GetLevel() {return cur_level_;}
int GetCurLevelExp() {return exp_;}
int GetCurLevelMaxExp() {
if (GetLevel() < (int)level_exps_.size()) {
return level_exps_[GetLevel()];
}
else {
return 10000;
}
}
int GetCoin() {return coin_;}
// Inventory
bool PickupItem(ItemPrototype* item);
void UseItem(size_t slot_num);
void UnequipItem(size_t slot_num);
void DropItem(size_t slot_num);
void DropEquipment(size_t slot_num);
ItemPrototype* GetItem(size_t slot_num);
EquipmentPrototype* GetEquipment(size_t slot_num);
bool IsInventoryFull() const { return inventory_.IsFull(); }
static Player* Create(Room** room, const std::string& player_config_file);
std::vector<Attack> GetAttackInfo() const;
virtual int GetAttackPoint() override;
virtual int GetDefense() override;
int GetMaxHP() { return max_hp_; }
virtual void OnTakeDamage() override;
protected:
virtual void DrawImpl(DrawSprites& draw) override;
private:
std::unordered_map<Mob::AnimationState, Animation*> animations_;
MovementComponent movement_component_;
Room** room_;
int max_hp_ { 100 };
int mp_ { 100 };
int max_mp_ { 100 };
int exp_ { 0 };
int cur_level_ {0};
int coin_ { 0 };
std::vector<int> level_exps_;
std::vector<Attack> skills_;
Buff buff_;
float shining_duration_ { 0.0f };
bool is_shining_ { false };
Inventory inventory_;
Player(const Player& player);
Player(Room** room, const glm::vec4 bounding_box);
void LevelUp();
void Shine(float duration) { shining_duration_ = duration; }
};
| 26.214286 | 88 | 0.734527 | GenBrg |
1436e44f34a66f681f3a04b47a858f83f4680ac2 | 1,006 | cpp | C++ | libnorth/src/Utils/FileSystem.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | libnorth/src/Utils/FileSystem.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | libnorth/src/Utils/FileSystem.cpp | lzmru/north | cc6c17d3049c514b5c754beed7be4170ef380864 | [
"MIT"
] | null | null | null | //===--- Utils/FileSystem.cpp - File system utilities -----------*- C++ -*-===//
//
// The North Compiler Infrastructure
//
// This file is distributed under the MIT License.
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Utils/FileSystem.h"
namespace north::utils {
llvm::SourceMgr *openFile(llvm::StringRef Path) {
auto MemBuff = llvm::MemoryBuffer::getFile(Path);
if (auto Error = MemBuff.getError()) {
llvm::errs() << Path << ": " << Error.message() << '\n';
std::exit(0);
}
if (!MemBuff->get()->getBufferSize())
std::exit(0);
auto SourceManager = new llvm::SourceMgr();
SourceManager->AddNewSourceBuffer(std::move(*MemBuff), llvm::SMLoc());
SourceManager->setDiagHandler([](const llvm::SMDiagnostic &SMD, void *Context) {
SMD.print("", llvm::errs());
std::exit(0);
});
return SourceManager;
}
} // north::utils
| 27.189189 | 82 | 0.538767 | lzmru |
1437068186c50e9c3d35e3556234f470e4f2775c | 3,000 | hpp | C++ | include/ImgIcon.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 47 | 2016-07-27T07:22:06.000Z | 2021-08-17T13:08:19.000Z | include/ImgIcon.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 1 | 2016-09-24T06:04:39.000Z | 2016-09-25T10:34:19.000Z | include/ImgIcon.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 13 | 2016-07-27T10:44:35.000Z | 2020-07-01T21:08:33.000Z | /**************************************************************************
** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):
**
** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds
** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell
**
** w.li AT cs.ucl.ac.uk
** http://visual.cs.ucl.ac.uk/pubs/rotopp
**
** Copyright (c) 2016, Wenbin Li
** 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 and data 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.
**
** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA IS PROVIDED BY
** THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
** NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
** INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
** BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
** USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#ifndef IMGICON_H
#define IMGICON_H
#include <QLabel>
#include <QPainter>
#include <QWidget>
#include <QMouseEvent>
#include "include/designZone/SpCurve.hpp"
#include "include/utils.hpp"
class QLabel;
class ImgIcon: public QLabel
{
Q_OBJECT
private:
QImage *img;
qreal num;
QColor color;
QList<SpCurve*> curves;
public:
EditType status;
explicit ImgIcon(QImage *image,QWidget *parent = 0);
explicit ImgIcon(QImage *image, int i,QWidget *parent = 0);
~ImgIcon(){}
void setStatus(EditType);
void paintEvent(QPaintEvent *event);
void setImage(QImage* im){img=im;}
QImage* getImage(){return img;}
int getNum(){return num;}
void designActionClick();
signals:
void pushImgIconClicked(qreal);
// void pushRecheckDesignActions();
protected:
void mousePressEvent(QMouseEvent *event);
public slots:
void updateCurves(QList<SpCurve*>);
void setEditingStatus();
void setNoEditStatus();
void setSuggestStatus();
void setKeyFrameStatus();
};
typedef QList<ImgIcon*> ImgIconList;
typedef QList<EditType> StatusList;
#endif
| 33.707865 | 86 | 0.698333 | vinben |
143bf37fad4d73b1758cc1de7432eee5b3325901 | 4,148 | cpp | C++ | example/src/ofApp.cpp | bakercp/ofxJitterNetworkSender | e04ef62f490e0f86cb020cd04393b2a158cb8a82 | [
"MIT"
] | 8 | 2015-03-17T17:30:23.000Z | 2020-12-06T21:34:00.000Z | example/src/ofApp.cpp | bakercp/ofxJitterNetworkSender | e04ef62f490e0f86cb020cd04393b2a158cb8a82 | [
"MIT"
] | 3 | 2017-02-07T19:57:31.000Z | 2021-09-16T14:24:50.000Z | example/src/ofApp.cpp | bakercp/ofxJitterNetworkSender | e04ef62f490e0f86cb020cd04393b2a158cb8a82 | [
"MIT"
] | 1 | 2018-10-19T21:09:21.000Z | 2018-10-19T21:09:21.000Z | // =============================================================================
//
// Copyright (c) 2009-2013 Christopher Baker <http://christopherbaker.net>
//
// 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 "ofApp.h"
//------------------------------------------------------------------------------
void ofApp::setup()
{
ofSetVerticalSync(true);
useGrabber = false;
vidGrabber.setVerbose(false);
vidGrabber.initGrabber(160,120);
fingerMovie.loadMovie("movies/fingers_160x120x15fps.mov");
fingerMovie.play();
// are we connected to the server - if this fails we
// will check every few seconds to see if the server exists
sender.setVerbose(false);
if(sender.setup("127.0.0.1", 8888))
{
connectTime = ofGetElapsedTimeMillis();
}
// some counter text
counter = 0.0;
}
//------------------------------------------------------------------------------
void ofApp::update()
{
// prepare our video frames
fingerMovie.update();
vidGrabber.update();
if(sender.isConnected())
{
if(useGrabber)
{
if (vidGrabber.isFrameNew())
{
sender.sendFrame(vidGrabber.getPixelsRef());
}
}
else
{
if(fingerMovie.isFrameNew())
{
sender.sendFrame(fingerMovie.getPixelsRef());
}
}
}
else
{
//if we are not connected lets try and reconnect every 5 seconds
if((ofGetElapsedTimeMillis() - connectTime) > 5000)
{
sender.setup("127.0.0.1", 8888);
}
}
}
//------------------------------------------------------------------------------
void ofApp::draw()
{
ofBackground(0);
ofSetColor(127);
ofRect(190,20,ofGetWidth()-160-40,ofGetHeight()-40);
ofSetColor(255,255,0);
if(useGrabber)
{
ofRect(18,158,164,124);
} else {
ofRect(18,18,164,124);
}
ofSetColor(255);
fingerMovie.draw(20,20);
vidGrabber.draw(20,160);
// send some text
std::string txt = "sent from of => " + ofToString(counter++);
sender.sendText(txt);
std::stringstream ss;
ss << "This video is being sent over TCP to port 8888 can be" << endl;
ss << "received in Jitter by using [jit.net.recv @port 8888]." << endl;
ss << "See ofxJitterNetworkSender_Example.maxpat for example" << endl;
ss << "usage. This also works in Jitter 4.5, 5, 6, etc." << endl;
ss << endl;
ss << "This message is also being sent:" << endl;
ss << endl;
ss << "[" << txt << "]" << endl;
ss << endl;
ss << "More complex messages including bangs, lists, etc" << endl;
ss << "are not fully implemented yet." << endl;
ss << "" << endl;
ss << endl;
ss << "SPACEBAR toggles between video sources." << endl;
ofDrawBitmapString(ss.str(), 200, 60);
}
//------------------------------------------------------------------------------
void ofApp::keyPressed(int key)
{
useGrabber = !useGrabber;
}
| 29.41844 | 80 | 0.558824 | bakercp |
1443b3c7f825ecd2a7796a8e32b0e3220460a221 | 1,383 | cpp | C++ | wirish/wirish_math.cpp | lacklustrlabs/libmaple | a2d1169b0b5a5de68140dad26982cf0f238e877b | [
"MIT"
] | 162 | 2015-01-07T18:26:13.000Z | 2022-03-07T09:50:31.000Z | wirish/wirish_math.cpp | lacklustrlabs/libmaple | a2d1169b0b5a5de68140dad26982cf0f238e877b | [
"MIT"
] | 25 | 2015-01-24T19:03:30.000Z | 2021-12-15T15:02:50.000Z | wirish/wirish_math.cpp | lacklustrlabs/libmaple | a2d1169b0b5a5de68140dad26982cf0f238e877b | [
"MIT"
] | 112 | 2015-01-16T08:58:13.000Z | 2022-03-23T20:01:06.000Z | /*
* Modified by LeafLabs, LLC.
*
* Part of the Wiring project - http://wiring.org.co Copyright (c)
* 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis
* for Arduino - http://www.arduino.cc/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <stdlib.h>
#include <wirish/wirish_math.h>
void randomSeed(unsigned int seed) {
if (seed != 0) {
srand(seed);
}
}
long random(long howbig) {
if (howbig == 0) {
return 0;
}
return rand() % howbig;
}
long random(long howsmall, long howbig) {
if (howsmall >= howbig) {
return howsmall;
}
long diff = howbig - howsmall;
return random(diff) + howsmall;
}
| 27.66 | 70 | 0.686189 | lacklustrlabs |
144ac5a16e795cef4206813168d18a72b70a4aef | 1,318 | cpp | C++ | cppLearningExercises/Main.cpp | QueeniePun/cppLearningExercises | 4c4181573d1b7de9f67acdea1b0fd6d2245b8806 | [
"MIT"
] | null | null | null | cppLearningExercises/Main.cpp | QueeniePun/cppLearningExercises | 4c4181573d1b7de9f67acdea1b0fd6d2245b8806 | [
"MIT"
] | null | null | null | cppLearningExercises/Main.cpp | QueeniePun/cppLearningExercises | 4c4181573d1b7de9f67acdea1b0fd6d2245b8806 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Chapter1Helper.h"
#include "Chapter2Helper.h"
#include "Chapter3Helper.h"
#include "Chapter4Helper.h"
#include "Chapter5Helper.h"
#include "Chapter6Helper.h"
#include "Chapter7Helper.h"
#include "Chapter8Helper.h"
#include "Chapter9Helper.h"
#include "Chapter10Helper.h"
#include "Chapter11Helper.h"
#include "Chapter12Helper.h"
#include "Chapter13Helper.h"
#include "Chapter14Helper.h"
#include "Chapter15Helper.h"
#include "Chapter16Helper.h"
#include "Chapter17Helper.h"
#include "Chapter18Helper.h"
#include "Chapter19Helper.h"
#include "Chapter19Helper.h"
#include "Chapter20Helper.h"
using namespace std;
// Programming Exercises
int main()
{
Chapter1Helper chapter1;
Chapter2Helper chapter2;
Chapter3Helper chapter3;
Chapter4Helper chapter4;
Chapter5Helper chapter5;
Chapter6Helper chapter6;
Chapter7Helper chapter7;
Chapter8Helper chapter8;
Chapter9Helper chapter9;
Chapter10Helper chapter10;
Chapter11Helper chapter11;
Chapter12Helper chapter12;
Chapter13Helper chapter13;
Chapter14Helper chapter14;
Chapter15Helper chapter15;
Chapter16Helper chapter16;
Chapter17Helper chapter17;
Chapter18Helper chapter18;
Chapter19Helper chapter19;
Chapter20Helper chapter20;
chapter20.RunExercise8();
}
| 24.407407 | 30 | 0.770865 | QueeniePun |
144bfa77bc363ad9f36acb87a40149d11826edb8 | 2,402 | cpp | C++ | project2D/CollisionManager.cpp | AlexMollard/Path-Finding | 76e96db39686f05995316d5147f2bbf746d8c4a0 | [
"MIT"
] | null | null | null | project2D/CollisionManager.cpp | AlexMollard/Path-Finding | 76e96db39686f05995316d5147f2bbf746d8c4a0 | [
"MIT"
] | null | null | null | project2D/CollisionManager.cpp | AlexMollard/Path-Finding | 76e96db39686f05995316d5147f2bbf746d8c4a0 | [
"MIT"
] | null | null | null | #include "CollisionManager.h"
#include <iostream>
CollisionManager::CollisionManager()
{
}
CollisionManager::~CollisionManager()
{
}
void CollisionManager::Update(float deltaTime)
{
for (int i = 0; i < _ObjectList.size(); i++)
{
GameObject* _Object = _ObjectList[i];
Collider* _FirstCollider = _Object->GetCollider();
for (int j = 0; j < _ObjectList.size(); j++)
{
GameObject* _OtherObject = _ObjectList[j];
Collider* _OtherCollider = _OtherObject->GetCollider();
if (!_OtherCollider)
continue;
if (i == j)
continue;
Vector2 _Min = _FirstCollider->GetMin();
Vector2 _Max = _FirstCollider->GetMax();
Vector2 _OtherMin = _OtherCollider->GetMin();
Vector2 _OtherMax = _OtherCollider->GetMax();
if (_Max.x > _OtherMin.x &&_Max.y > _OtherMin.y &&
_Min.x < _OtherMax.x &&_Min.y < _OtherMax.y)
{
if (_Object->GetName() == "Space_Ship" && _OtherObject->GetName() != "Bullet" )
_Object->OnCollision(_OtherObject);
if (_Object->GetName() == "Bullet" && _OtherObject->GetName() != "Space_Ship" && _OtherObject->GetName() != "Bullet")
_Object->OnCollision(_OtherObject);
}
}
}
}
void CollisionManager::Draw(aie::Renderer2D* renderer)
{
for (int i = 0; i < _ObjectList.size(); i++)
{
Collider* _collider = _ObjectList[i]->GetCollider();
Vector2 v2Min = _collider->GetMin();
Vector2 v2Max = _collider->GetMax();
renderer->drawLine(v2Min.x, v2Min.y, v2Min.x, v2Max.y);
renderer->drawLine(v2Min.x, v2Max.y, v2Max.x, v2Max.y);
renderer->drawLine(v2Max.x, v2Max.y, v2Max.x, v2Min.y);
renderer->drawLine(v2Max.x, v2Min.y, v2Min.x, v2Min.y);
if (_ObjectList[i]->HasCollider2())
{
Collider* _collider2 = _ObjectList[i]->GetCollider2();
Vector2 v2Min2 = _collider2->GetMin();
Vector2 v2Max2 = _collider2->GetMax();
renderer->drawLine(v2Min2.x, v2Min2.y, v2Min2.x, v2Max2.y);
renderer->drawLine(v2Min2.x, v2Max2.y, v2Max2.x, v2Max2.y);
renderer->drawLine(v2Max2.x, v2Max2.y, v2Max2.x, v2Min2.y);
renderer->drawLine(v2Max2.x, v2Min2.y, v2Min2.x, v2Min2.y);
}
}
}
void CollisionManager::AddObject(GameObject* object)
{
_ObjectList.push_back(object);
}
void CollisionManager::RemoveObject()
{
_ObjectList.pop_back();
}
GameObject* CollisionManager::GetObject()
{
return _ObjectList.back();
} | 26.395604 | 122 | 0.651124 | AlexMollard |
144ee5325cd11c827c601c2f031704313b482f6c | 269 | cpp | C++ | src/CWSDK/common/math.cpp | Mininoob/CWLevelSystem | ee5e06bcc0d1c4417d0a7eb2cf52897fa908e903 | [
"MIT"
] | 39 | 2021-02-28T04:17:16.000Z | 2022-02-23T14:25:41.000Z | src/CWSDK/common/math.cpp | Mininoob/CWLevelSystem | ee5e06bcc0d1c4417d0a7eb2cf52897fa908e903 | [
"MIT"
] | 16 | 2021-03-12T04:44:33.000Z | 2022-03-31T14:16:16.000Z | src/CWSDK/common/math.cpp | Mininoob/CWLevelSystem | ee5e06bcc0d1c4417d0a7eb2cf52897fa908e903 | [
"MIT"
] | 3 | 2021-09-10T14:19:08.000Z | 2021-12-19T20:45:04.000Z | #include "math.h"
i64 pydiv(i64 a, i64 b) {
i64 result = a / b;
if ((a < 0) ^ (b < 0)) {
if (pymod(a, b) != 0) {
result -= 1;
}
}
return result;
}
i64 pymod(i64 a, i64 b) {
i64 result = a % b;
if (result < 0) {
result = b + result;
}
return result;
}
| 14.157895 | 25 | 0.501859 | Mininoob |
145222f4a2d532f4a0c99e7e6175d206fc31aeba | 2,187 | cpp | C++ | archived/VoIP/cs/VoipBackEnd/BackEndAudioHelpers.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,504 | 2019-05-07T06:56:42.000Z | 2022-03-31T19:37:59.000Z | archived/VoIP/cs/VoipBackEnd/BackEndAudioHelpers.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 314 | 2019-05-08T16:56:30.000Z | 2022-03-21T07:13:45.000Z | archived/VoIP/cs/VoipBackEnd/BackEndAudioHelpers.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,219 | 2019-05-07T00:47:26.000Z | 2022-03-30T21:12:31.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "BackEndAudioHelpers.h"
// release and zero out a possible NULL pointer. note this will
// do the release on a temp copy to avoid reentrancy issues that can result from
// callbacks durring the release
template <class T> void SafeRelease(__deref_inout_opt T **ppT)
{
T *pTTemp = *ppT; // temp copy
*ppT = nullptr; // zero the input
if (pTTemp)
{
pTTemp->Release();
}
}
// Begin of audio helpers
size_t inline GetWaveFormatSize(const WAVEFORMATEX& format)
{
return (sizeof WAVEFORMATEX) + (format.wFormatTag == WAVE_FORMAT_PCM ? 0 : format.cbSize);
}
void FillPcmFormat(WAVEFORMATEX& format, WORD wChannels, int nSampleRate, WORD wBits)
{
format.wFormatTag = WAVE_FORMAT_PCM;
format.nChannels = wChannels;
format.nSamplesPerSec = nSampleRate;
format.wBitsPerSample = wBits;
format.nBlockAlign = format.nChannels * (format.wBitsPerSample / 8);
format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
format.cbSize = 0;
}
size_t BytesFromDuration(int nDurationInMs, const WAVEFORMATEX& format)
{
return size_t(nDurationInMs * FLOAT(format.nAvgBytesPerSec) / 1000);
}
size_t SamplesFromDuration(int nDurationInMs, const WAVEFORMATEX& format)
{
return size_t(nDurationInMs * FLOAT(format.nSamplesPerSec) / 1000);
}
BOOL WaveFormatCompare(const WAVEFORMATEX& format1, const WAVEFORMATEX& format2)
{
size_t cbSizeFormat1 = GetWaveFormatSize(format1);
size_t cbSizeFormat2 = GetWaveFormatSize(format2);
return (cbSizeFormat1 == cbSizeFormat2) && (memcmp(&format1, &format2, cbSizeFormat1) == 0);
}
// End of audio helpers
| 34.714286 | 97 | 0.657979 | dujianxin |
1457c8bf087de1d2746c8dfc46da03537892a899 | 914 | hpp | C++ | shared_model/backend/protobuf/commands/proto_command.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | shared_model/backend/protobuf/commands/proto_command.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | shared_model/backend/protobuf/commands/proto_command.hpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
#define IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
#include "interfaces/commands/command.hpp"
#include "commands.pb.h"
namespace shared_model {
namespace proto {
class Command final : public interface::Command {
public:
using TransportType = iroha::protocol::Command;
Command(const Command &o);
Command(Command &&o) noexcept;
explicit Command(const TransportType &ref);
explicit Command(TransportType &&ref);
~Command() override;
const CommandVariantType &get() const override;
protected:
Command *clone() const override;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace proto
} // namespace shared_model
#endif // IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
| 22.292683 | 53 | 0.696937 | coderintherye |
14615a1c0b433382482e1be95e9571a599fef25b | 1,959 | hpp | C++ | src/pyprx/utilities/data_structures/tree_py.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 3 | 2021-05-31T11:28:03.000Z | 2021-05-31T13:49:30.000Z | src/pyprx/utilities/data_structures/tree_py.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 1 | 2021-09-03T09:39:32.000Z | 2021-12-10T22:17:56.000Z | src/pyprx/utilities/data_structures/tree_py.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 2 | 2021-09-03T09:17:45.000Z | 2021-10-04T15:52:58.000Z | #include "prx/utilities/data_structures/tree.hpp"
PRX_SETTER(tree_t, vertex_id_counter)
PRX_GETTER(tree_t, vertex_id_counter)
void pyprx_utilities_data_structures_tree_py()
{
class_<prx::tree_node_t, std::shared_ptr<prx::tree_node_t>, bases<prx::abstract_node_t>>("tree_node", init<>())
.def("get_parent", &prx::tree_node_t::get_parent)
.def("get_index", &prx::tree_node_t::get_index)
.def("get_parent_edge", &prx::tree_node_t::get_parent_edge)
.def("get_children", &prx::tree_node_t::get_children, return_internal_reference<>())
;
class_<prx::tree_edge_t, std::shared_ptr<prx::tree_edge_t>, bases<prx::abstract_edge_t>, boost::noncopyable>("tree_edge", no_init)
.def("__init__", make_constructor(&init_as_ptr<prx::tree_edge_t>, default_call_policies()))
.def("get_index", &prx::tree_edge_t::get_index)
.def("get_source", &prx::tree_edge_t::get_source)
.def("get_target", &prx::tree_edge_t::get_target)
;
class_<prx::tree_t, std::shared_ptr<prx::tree_t>>("tree", init<>())
.def("allocate_memory", &prx::tree_t::allocate_memory<prx::tree_node_t, prx::tree_edge_t>)
.def("add_vertex", &prx::tree_t::add_vertex<prx::tree_node_t, prx::tree_edge_t>)
.def("get_vertex_as", &prx::tree_t::get_vertex_as<prx::tree_node_t>)
.def("get_edge_as", &prx::tree_t::get_edge_as<prx::tree_edge_t>)
.def("num_vertices", &prx::tree_t::num_vertices)
.def("num_edges", &prx::tree_t::num_edges)
.def("is_leaf", &prx::tree_t::is_leaf)
.def("edge", &prx::tree_t::edge)
.def("add_edge", &prx::tree_t::add_edge)
.def("add_safety_edge", &prx::tree_t::add_safety_edge)
.def("get_depth", &prx::tree_t::get_depth)
.def("remove_vertex", &prx::tree_t::remove_vertex)
.def("purge", &prx::tree_t::purge)
.def("clear", &prx::tree_t::clear)
.def("transplant", &prx::tree_t::transplant)
.add_property("vertex_id_counter", &get_tree_t_vertex_id_counter<unsigned>, &set_tree_t_vertex_id_counter<unsigned>)
// .def("", &prx::tree_t::)
;
} | 47.780488 | 131 | 0.722818 | aravindsiv |
14615b5b73d4ba2cf77c592fdece8422a32c6dc2 | 300 | cpp | C++ | libraries/lib-components/ConfigInterface.cpp | IshoAntar/AudMonkey | c9180745529960b147b49f659c4295d7dffb888c | [
"CC-BY-3.0"
] | 41 | 2021-07-07T13:22:16.000Z | 2022-03-15T19:46:27.000Z | libraries/lib-components/ConfigInterface.cpp | BeaterTeam/Beater | e92b0b85986d51e40fcccb41fec61bd261fc52e6 | [
"CC-BY-3.0"
] | 41 | 2021-07-07T16:47:48.000Z | 2022-02-23T03:43:25.000Z | libraries/lib-components/ConfigInterface.cpp | TheEvilSkeleton/AudMonkey | 848d951c3d4acf2687a9c83ece71de5940d0546c | [
"CC-BY-3.0"
] | 6 | 2021-07-07T09:39:48.000Z | 2021-12-28T01:06:58.000Z | /**********************************************************************
AudMonkey: A Digital Audio Editor
@file ConfigInterface.cpp
**********************************************************************/
#include "ConfigInterface.h"
ConfigClientInterface::~ConfigClientInterface() = default;
| 27.272727 | 71 | 0.406667 | IshoAntar |
1464a693e0bf3899f6f9ecd6df73fdef4395e068 | 4,822 | cpp | C++ | src/common.cpp | EDM-Developers/fastEDM | 9724bf609d09beae53a89ca5cbe52d407787dbf2 | [
"MIT"
] | 2 | 2021-04-27T00:21:57.000Z | 2022-01-23T03:46:04.000Z | src/common.cpp | EDM-Developers/fastEDM | 9724bf609d09beae53a89ca5cbe52d407787dbf2 | [
"MIT"
] | null | null | null | src/common.cpp | EDM-Developers/fastEDM | 9724bf609d09beae53a89ca5cbe52d407787dbf2 | [
"MIT"
] | 1 | 2021-09-17T17:14:07.000Z | 2021-09-17T17:14:07.000Z | #include "common.h"
#ifdef JSON
void to_json(json& j, const Algorithm& a)
{
if (a == Algorithm::Simplex) {
j = "Simplex";
} else {
j = "SMap";
}
}
void from_json(const json& j, Algorithm& a)
{
if (j == "Simplex") {
a = Algorithm::Simplex;
} else {
a = Algorithm::SMap;
}
}
void to_json(json& j, const Distance& d)
{
if (d == Distance::MeanAbsoluteError) {
j = "MeanAbsoluteError";
} else if (d == Distance::Euclidean) {
j = "Euclidean";
} else {
j = "Wasserstein";
}
}
void from_json(const json& j, Distance& d)
{
if (j == "MeanAbsoluteError") {
d = Distance::MeanAbsoluteError;
} else if (j == "Euclidean") {
d = Distance::Euclidean;
} else {
d = Distance::Wasserstein;
}
}
void to_json(json& j, const Metric& m)
{
if (m == Metric::Diff) {
j = "Diff";
} else {
j = "CheckSame";
}
}
void from_json(const json& j, Metric& m)
{
if (j == "Diff") {
m = Metric::Diff;
} else {
m = Metric::CheckSame;
}
}
void to_json(json& j, const Options& o)
{
j = json{ { "copredict", o.copredict },
{ "forceCompute", o.forceCompute },
{ "savePrediction", o.savePrediction },
{ "saveSMAPCoeffs", o.saveSMAPCoeffs },
{ "k", o.k },
{ "nthreads", o.nthreads },
{ "missingdistance", o.missingdistance },
{ "panelMode", o.panelMode },
{ "idw", o.idw },
{ "thetas", o.thetas },
{ "algorithm", o.algorithm },
{ "taskNum", o.taskNum },
{ "numTasks", o.numTasks },
{ "configNum", o.configNum },
{ "calcRhoMAE", o.calcRhoMAE },
{ "aspectRatio", o.aspectRatio },
{ "distance", o.distance },
{ "metrics", o.metrics },
{ "cmdLine", o.cmdLine } };
}
void from_json(const json& j, Options& o)
{
j.at("copredict").get_to(o.copredict);
j.at("forceCompute").get_to(o.forceCompute);
j.at("savePrediction").get_to(o.savePrediction);
j.at("saveSMAPCoeffs").get_to(o.saveSMAPCoeffs);
j.at("k").get_to(o.k);
j.at("nthreads").get_to(o.nthreads);
j.at("missingdistance").get_to(o.missingdistance);
j.at("panelMode").get_to(o.panelMode);
j.at("idw").get_to(o.idw);
j.at("thetas").get_to(o.thetas);
j.at("algorithm").get_to(o.algorithm);
j.at("taskNum").get_to(o.taskNum);
j.at("numTasks").get_to(o.numTasks);
j.at("configNum").get_to(o.configNum);
j.at("calcRhoMAE").get_to(o.calcRhoMAE);
j.at("aspectRatio").get_to(o.aspectRatio);
j.at("distance").get_to(o.distance);
j.at("metrics").get_to(o.metrics);
j.at("cmdLine").get_to(o.cmdLine);
}
void to_json(json& j, const PredictionStats& s)
{
j = json{ { "mae", s.mae }, { "rho", s.rho } };
}
void from_json(const json& j, PredictionStats& s)
{
j.at("mae").get_to(s.mae);
j.at("rho").get_to(s.rho);
}
void to_json(json& j, const PredictionResult& p)
{
std::vector<double> predictionsVec, coeffsVec;
if (p.predictions != nullptr) {
predictionsVec = std::vector<double>(p.predictions.get(), p.predictions.get() + p.numThetas * p.numPredictions);
}
if (p.coeffs != nullptr) {
coeffsVec = std::vector<double>(p.coeffs.get(), p.coeffs.get() + p.numPredictions * p.numCoeffCols);
}
j = json{ { "rc", p.rc },
{ "numThetas", p.numThetas },
{ "numPredictions", p.numPredictions },
{ "numCoeffCols", p.numCoeffCols },
{ "predictions", predictionsVec },
{ "coeffs", coeffsVec },
{ "stats", p.stats },
{ "predictionRows", p.predictionRows },
{ "kMin", p.kMin },
{ "kMax", p.kMax },
{ "cmdLine", p.cmdLine },
{ "configNum", p.configNum } };
}
void from_json(const json& j, PredictionResult& p)
{
j.at("rc").get_to(p.rc);
j.at("numThetas").get_to(p.numThetas);
j.at("numPredictions").get_to(p.numPredictions);
j.at("numCoeffCols").get_to(p.numCoeffCols);
j.at("predictionRows").get_to(p.predictionRows);
j.at("stats").get_to(p.stats);
j.at("kMin").get_to(p.kMin);
j.at("kMax").get_to(p.kMax);
j.at("cmdLine").get_to(p.cmdLine);
j.at("configNum").get_to(p.configNum);
// TODO: Test this coeffs/predictions loading works as expected
std::vector<double> predictions = j.at("predictions");
if (predictions.size()) {
p.predictions = std::make_unique<double[]>(predictions.size());
for (int i = 0; i < predictions.size(); i++) {
p.predictions[i] = predictions[i];
}
} else {
p.predictions = nullptr;
}
std::vector<double> coeffs = j.at("coeffs");
if (coeffs.size()) {
p.coeffs = std::make_unique<double[]>(coeffs.size());
for (int i = 0; i < coeffs.size(); i++) {
p.coeffs[i] = coeffs[i];
}
} else {
p.coeffs = nullptr;
}
}
#endif | 26.938547 | 116 | 0.575695 | EDM-Developers |
14670a76bd33d6a34a71529f0856211c03120f06 | 36,873 | cpp | C++ | apps/camera-calib/camera_calib_guiMain.cpp | waltzrobotics/mrpt | 540c52cebd4b7c31b104ebbeec369c800d73aa44 | [
"BSD-3-Clause"
] | 1 | 2019-05-08T18:58:54.000Z | 2019-05-08T18:58:54.000Z | apps/camera-calib/camera_calib_guiMain.cpp | waltzrobotics/mrpt | 540c52cebd4b7c31b104ebbeec369c800d73aa44 | [
"BSD-3-Clause"
] | null | null | null | apps/camera-calib/camera_calib_guiMain.cpp | waltzrobotics/mrpt | 540c52cebd4b7c31b104ebbeec369c800d73aa44 | [
"BSD-3-Clause"
] | null | null | null | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
/*---------------------------------------------------------------
APPLICATION: Camera calibration GUI
AUTHOR: Jose Luis Blanco, based on code from the OpenCV library.
---------------------------------------------------------------*/
#include "camera_calib_guiMain.h"
#include "CDlgCalibWizardOnline.h"
#include "CDlgPoseEst.h"
//(*InternalHeaders(camera_calib_guiDialog)
#include <wx/settings.h>
#include <wx/font.h>
#include <wx/intl.h>
#include <wx/string.h>
//*)
#include <wx/filedlg.h>
#include <wx/msgdlg.h>
#include <wx/progdlg.h>
#include <mrpt/gui/WxUtils.h>
#include <mrpt/system/filesystem.h>
#include <mrpt/opengl/CGridPlaneXY.h>
#include <mrpt/opengl/stock_objects.h>
#include <fstream>
#include <iostream>
#include <Eigen/Dense>
#include <mrpt/vision/pnp_algos.h>
using namespace mrpt;
using namespace mrpt::math;
using namespace mrpt::img;
using namespace mrpt::vision;
using namespace mrpt::gui;
using namespace std;
#include <mrpt/gui/CMyRedirector.h>
#include <mrpt/gui/about_box.h>
#define USE_EXTERNAL_STORAGE_IMGS 1
// VARIABLES ================================
TCalibrationImageList lst_images; // Here are all the images: file_name -> data
mrpt::img::TCamera camera_params;
// END VARIABLES ============================
#include "imgs/icono_main.xpm"
#include "../wx-common/mrpt_logo.xpm"
// A custom Art provider for customizing the icons:
class MyArtProvider : public wxArtProvider
{
protected:
wxBitmap CreateBitmap(
const wxArtID& id, const wxArtClient& client,
const wxSize& size) override;
};
// CreateBitmap function
wxBitmap MyArtProvider::CreateBitmap(
const wxArtID& id, const wxArtClient& client, const wxSize& size)
{
if (id == wxART_MAKE_ART_ID(MAIN_ICON)) return wxBitmap(icono_main_xpm);
if (id == wxART_MAKE_ART_ID(IMG_MRPT_LOGO)) return wxBitmap(mrpt_logo_xpm);
// Any wxWidgets icons not implemented here
// will be provided by the default art provider.
return wxNullBitmap;
}
//(*IdInit(camera_calib_guiDialog)
const long camera_calib_guiDialog::ID_BUTTON8 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON1 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON2 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON9 = wxNewId();
const long camera_calib_guiDialog::ID_LISTBOX1 = wxNewId();
const long camera_calib_guiDialog::ID_STATICTEXT5 = wxNewId();
const long camera_calib_guiDialog::ID_CHOICE1 = wxNewId();
const long camera_calib_guiDialog::ID_STATICTEXT1 = wxNewId();
const long camera_calib_guiDialog::ID_SPINCTRL1 = wxNewId();
const long camera_calib_guiDialog::ID_STATICTEXT2 = wxNewId();
const long camera_calib_guiDialog::ID_SPINCTRL2 = wxNewId();
const long camera_calib_guiDialog::ID_RADIOBOX1 = wxNewId();
const long camera_calib_guiDialog::ID_STATICTEXT3 = wxNewId();
const long camera_calib_guiDialog::ID_TEXTCTRL1 = wxNewId();
const long camera_calib_guiDialog::ID_STATICTEXT6 = wxNewId();
const long camera_calib_guiDialog::ID_TEXTCTRL3 = wxNewId();
const long camera_calib_guiDialog::ID_CHECKBOX1 = wxNewId();
const long camera_calib_guiDialog::ID_TEXTCTRL2 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON3 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON6 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON7 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON5 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON4 = wxNewId();
const long camera_calib_guiDialog::ID_CUSTOM2 = wxNewId();
const long camera_calib_guiDialog::ID_SCROLLEDWINDOW2 = wxNewId();
const long camera_calib_guiDialog::ID_PANEL2 = wxNewId();
const long camera_calib_guiDialog::ID_CUSTOM1 = wxNewId();
const long camera_calib_guiDialog::ID_SCROLLEDWINDOW3 = wxNewId();
const long camera_calib_guiDialog::ID_PANEL3 = wxNewId();
const long camera_calib_guiDialog::ID_XY_GLCANVAS = wxNewId();
const long camera_calib_guiDialog::ID_PANEL1 = wxNewId();
const long camera_calib_guiDialog::ID_NOTEBOOK1 = wxNewId();
const long camera_calib_guiDialog::ID_BUTTON10 = wxNewId();
//*)
BEGIN_EVENT_TABLE(camera_calib_guiDialog, wxDialog)
//(*EventTable(camera_calib_guiDialog)
//*)
END_EVENT_TABLE()
camera_calib_guiDialog::camera_calib_guiDialog(wxWindow* parent, wxWindowID id)
{
// Load my custom icons:
#if wxCHECK_VERSION(2, 8, 0)
wxArtProvider::Push(new MyArtProvider);
#else
wxArtProvider::PushProvider(new MyArtProvider);
#endif
//(*Initialize(camera_calib_guiDialog)
wxStaticBoxSizer* StaticBoxSizer2;
wxFlexGridSizer* FlexGridSizer4;
wxFlexGridSizer* FlexGridSizer16;
wxStaticBoxSizer* StaticBoxSizer4;
wxFlexGridSizer* FlexGridSizer10;
wxFlexGridSizer* FlexGridSizer3;
wxFlexGridSizer* FlexGridSizer5;
wxFlexGridSizer* FlexGridSizer9;
wxFlexGridSizer* FlexGridSizer2;
wxFlexGridSizer* FlexGridSizer7;
wxStaticBoxSizer* StaticBoxSizer3;
wxFlexGridSizer* FlexGridSizer15;
wxFlexGridSizer* FlexGridSizer18;
wxFlexGridSizer* FlexGridSizer8;
wxFlexGridSizer* FlexGridSizer13;
wxFlexGridSizer* FlexGridSizer12;
wxFlexGridSizer* FlexGridSizer6;
wxStaticBoxSizer* StaticBoxSizer1;
wxFlexGridSizer* FlexGridSizer1;
wxFlexGridSizer* FlexGridSizer17;
wxStaticBoxSizer* StaticBoxSizer5;
Create(
parent, id, _("Camera calibration GUI - Part of the MRPT project"),
wxDefaultPosition, wxDefaultSize,
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX, _T("id"));
FlexGridSizer1 = new wxFlexGridSizer(1, 2, 0, 0);
FlexGridSizer1->AddGrowableCol(1);
FlexGridSizer1->AddGrowableRow(0);
FlexGridSizer2 = new wxFlexGridSizer(3, 1, 0, 0);
FlexGridSizer2->AddGrowableCol(0);
FlexGridSizer2->AddGrowableRow(0);
FlexGridSizer2->AddGrowableRow(2);
StaticBoxSizer1 =
new wxStaticBoxSizer(wxHORIZONTAL, this, _("List of images"));
FlexGridSizer4 = new wxFlexGridSizer(2, 1, 0, 0);
FlexGridSizer4->AddGrowableCol(0);
FlexGridSizer4->AddGrowableRow(1);
FlexGridSizer5 = new wxFlexGridSizer(0, 4, 0, 0);
btnCaptureNow = new wxButton(
this, ID_BUTTON8, _("Grab now..."), wxDefaultPosition, wxDefaultSize, 0,
wxDefaultValidator, _T("ID_BUTTON8"));
wxFont btnCaptureNowFont(
wxDEFAULT, wxDEFAULT, wxFONTSTYLE_NORMAL, wxBOLD, false, wxEmptyString,
wxFONTENCODING_DEFAULT);
btnCaptureNow->SetFont(btnCaptureNowFont);
FlexGridSizer5->Add(
btnCaptureNow, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
btnPoseEstimateNow = new wxButton(
this, ID_BUTTON10, _("Pose Est. now..."), wxDefaultPosition,
wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON10"));
wxFont btnPoseEstimateNowFont(
wxDEFAULT, wxDEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false,
wxEmptyString, wxFONTENCODING_DEFAULT);
btnPoseEstimateNow->SetFont(btnPoseEstimateNowFont);
FlexGridSizer5->Add(
btnPoseEstimateNow, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP,
5);
Button11 = new wxButton(
this, ID_BUTTON1, _("Add image(s)..."), wxDefaultPosition,
wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1"));
FlexGridSizer5->Add(
Button11, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
Button22 = new wxButton(
this, ID_BUTTON2, _("Clear all"), wxDefaultPosition, wxDefaultSize, 0,
wxDefaultValidator, _T("ID_BUTTON2"));
FlexGridSizer5->Add(
Button22, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
btnSaveImages = new wxButton(
this, ID_BUTTON9, _("Save all..."), wxDefaultPosition, wxDefaultSize, 0,
wxDefaultValidator, _T("ID_BUTTON9"));
btnSaveImages->Disable();
FlexGridSizer5->Add(
btnSaveImages, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
FlexGridSizer4->Add(
FlexGridSizer5, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 0);
FlexGridSizer15 = new wxFlexGridSizer(1, 2, 0, 0);
FlexGridSizer15->AddGrowableCol(0);
FlexGridSizer15->AddGrowableRow(0);
lbFiles = new wxListBox(
this, ID_LISTBOX1, wxDefaultPosition, wxSize(294, 84), 0, nullptr,
wxLB_ALWAYS_SB | wxVSCROLL | wxHSCROLL | wxALWAYS_SHOW_SB,
wxDefaultValidator, _T("ID_LISTBOX1"));
FlexGridSizer15->Add(
lbFiles, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
FlexGridSizer16 = new wxFlexGridSizer(0, 1, 0, 0);
StaticText5 = new wxStaticText(
this, ID_STATICTEXT5, _("Zoom:"), wxDefaultPosition, wxDefaultSize, 0,
_T("ID_STATICTEXT5"));
FlexGridSizer16->Add(
StaticText5, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
cbZoom = new wxChoice(
this, ID_CHOICE1, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0,
wxDefaultValidator, _T("ID_CHOICE1"));
cbZoom->Append(_("25%"));
cbZoom->Append(_("50%"));
cbZoom->Append(_("75%"));
cbZoom->SetSelection(cbZoom->Append(_("100%")));
cbZoom->Append(_("150%"));
cbZoom->Append(_("200%"));
cbZoom->Append(_("300%"));
cbZoom->Append(_("400%"));
cbZoom->Append(_("500%"));
FlexGridSizer16->Add(
cbZoom, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL,
5);
FlexGridSizer15->Add(
FlexGridSizer16, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer4->Add(
FlexGridSizer15, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
StaticBoxSizer1->Add(
FlexGridSizer4, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer2->Add(
StaticBoxSizer1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2);
StaticBoxSizer3 = new wxStaticBoxSizer(
wxHORIZONTAL, this, _("Checkerboard detection parameters"));
FlexGridSizer6 = new wxFlexGridSizer(2, 2, 0, 0);
FlexGridSizer6->AddGrowableCol(0);
FlexGridSizer6->AddGrowableCol(1);
StaticBoxSizer4 = new wxStaticBoxSizer(
wxHORIZONTAL, this, _("Number of inner corners: "));
FlexGridSizer17 = new wxFlexGridSizer(1, 4, 0, 0);
StaticText1 = new wxStaticText(
this, ID_STATICTEXT1, _("In X:"), wxDefaultPosition, wxDefaultSize, 0,
_T("ID_STATICTEXT1"));
FlexGridSizer17->Add(
StaticText1, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
edSizeX = new wxSpinCtrl(
this, ID_SPINCTRL1, _T("9"), wxDefaultPosition, wxSize(50, -1), 0, 1,
200, 5, _T("ID_SPINCTRL1"));
edSizeX->SetValue(_T("9"));
FlexGridSizer17->Add(
edSizeX, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL,
5);
StaticText2 = new wxStaticText(
this, ID_STATICTEXT2, _("In Y:"), wxDefaultPosition, wxDefaultSize, 0,
_T("ID_STATICTEXT2"));
FlexGridSizer17->Add(
StaticText2, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
edSizeY = new wxSpinCtrl(
this, ID_SPINCTRL2, _T("6"), wxDefaultPosition, wxSize(50, -1), 0, 1,
200, 8, _T("ID_SPINCTRL2"));
edSizeY->SetValue(_T("6"));
FlexGridSizer17->Add(
edSizeY, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL,
5);
StaticBoxSizer4->Add(
FlexGridSizer17, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer6->Add(
StaticBoxSizer4, 1, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, 2);
wxString __wxRadioBoxChoices_1[2] = {_("OpenCV\'s default"),
_("Scaramuzza et al.\'s")};
rbMethod = new wxRadioBox(
this, ID_RADIOBOX1, _(" Detector method: "), wxDefaultPosition,
wxDefaultSize, 2, __wxRadioBoxChoices_1, 1, 0, wxDefaultValidator,
_T("ID_RADIOBOX1"));
FlexGridSizer6->Add(
rbMethod, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2);
StaticBoxSizer5 =
new wxStaticBoxSizer(wxHORIZONTAL, this, _(" Size of quads (in mm): "));
FlexGridSizer18 = new wxFlexGridSizer(1, 4, 0, 0);
StaticText3 = new wxStaticText(
this, ID_STATICTEXT3, _("In X:"), wxDefaultPosition, wxDefaultSize, 0,
_T("ID_STATICTEXT3"));
FlexGridSizer18->Add(
StaticText3, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
edLengthX = new wxTextCtrl(
this, ID_TEXTCTRL1, _("25.0"), wxDefaultPosition, wxSize(40, -1), 0,
wxDefaultValidator, _T("ID_TEXTCTRL1"));
FlexGridSizer18->Add(
edLengthX, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
StaticText6 = new wxStaticText(
this, ID_STATICTEXT6, _("In Y:"), wxDefaultPosition, wxDefaultSize, 0,
_T("ID_STATICTEXT6"));
FlexGridSizer18->Add(
StaticText6, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
edLengthY = new wxTextCtrl(
this, ID_TEXTCTRL3, _("25.0"), wxDefaultPosition, wxSize(40, -1), 0,
wxDefaultValidator, _T("ID_TEXTCTRL3"));
FlexGridSizer18->Add(
edLengthY, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
StaticBoxSizer5->Add(
FlexGridSizer18, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer6->Add(
StaticBoxSizer5, 1, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, 2);
cbNormalize = new wxCheckBox(
this, ID_CHECKBOX1, _("Normalize image"), wxDefaultPosition,
wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1"));
cbNormalize->SetValue(true);
FlexGridSizer6->Add(
cbNormalize, 1,
wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);
StaticBoxSizer3->Add(
FlexGridSizer6, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer2->Add(
StaticBoxSizer3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2);
StaticBoxSizer2 =
new wxStaticBoxSizer(wxHORIZONTAL, this, _("Calibration"));
FlexGridSizer7 = new wxFlexGridSizer(2, 1, 0, 0);
FlexGridSizer7->AddGrowableCol(0);
FlexGridSizer7->AddGrowableRow(0);
FlexGridSizer9 = new wxFlexGridSizer(1, 1, 0, 0);
FlexGridSizer9->AddGrowableCol(0);
FlexGridSizer9->AddGrowableRow(0);
txtLog = new wxTextCtrl(
this, ID_TEXTCTRL2, _("(Calibration results)"), wxDefaultPosition,
wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxHSCROLL | wxVSCROLL,
wxDefaultValidator, _T("ID_TEXTCTRL2"));
wxFont txtLogFont = wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT);
if (!txtLogFont.Ok())
txtLogFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
txtLogFont.SetPointSize(9);
txtLog->SetFont(txtLogFont);
FlexGridSizer9->Add(
txtLog, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
FlexGridSizer7->Add(
FlexGridSizer9, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer8 = new wxFlexGridSizer(2, 3, 0, 0);
FlexGridSizer8->AddGrowableCol(0);
FlexGridSizer8->AddGrowableCol(1);
btnRunCalib = new wxButton(
this, ID_BUTTON3, _("Calibrate"), wxDefaultPosition, wxDefaultSize, 0,
wxDefaultValidator, _T("ID_BUTTON3"));
btnRunCalib->SetDefault();
wxFont btnRunCalibFont(
wxDEFAULT, wxDEFAULT, wxFONTSTYLE_NORMAL, wxBOLD, false, wxEmptyString,
wxFONTENCODING_DEFAULT);
btnRunCalib->SetFont(btnRunCalibFont);
FlexGridSizer8->Add(
btnRunCalib, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
btnSave = new wxButton(
this, ID_BUTTON6, _("Save matrices..."), wxDefaultPosition,
wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON6"));
FlexGridSizer8->Add(
btnSave, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
FlexGridSizer8->Add(
-1, -1, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL,
5);
btnManualRect = new wxButton(
this, ID_BUTTON7, _("Manual params..."), wxDefaultPosition,
wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON7"));
FlexGridSizer8->Add(
btnManualRect, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
btnAbout = new wxButton(
this, ID_BUTTON5, _("About"), wxDefaultPosition, wxDefaultSize, 0,
wxDefaultValidator, _T("ID_BUTTON5"));
FlexGridSizer8->Add(
btnAbout, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
btnClose = new wxButton(
this, ID_BUTTON4, _("Quit"), wxDefaultPosition, wxDefaultSize, 0,
wxDefaultValidator, _T("ID_BUTTON4"));
FlexGridSizer8->Add(
btnClose, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);
FlexGridSizer7->Add(
FlexGridSizer8, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
StaticBoxSizer2->Add(
FlexGridSizer7, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer2->Add(
StaticBoxSizer2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2);
FlexGridSizer1->Add(
FlexGridSizer2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
FlexGridSizer3 = new wxFlexGridSizer(1, 1, 0, 0);
FlexGridSizer3->AddGrowableCol(0);
FlexGridSizer3->AddGrowableRow(0);
Notebook1 = new wxNotebook(
this, ID_NOTEBOOK1, wxDefaultPosition, wxSize(719, 570), 0,
_T("ID_NOTEBOOK1"));
Panel2 = new wxPanel(
Notebook1, ID_PANEL2, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL,
_T("ID_PANEL2"));
FlexGridSizer13 = new wxFlexGridSizer(1, 1, 0, 0);
FlexGridSizer13->AddGrowableCol(0);
FlexGridSizer13->AddGrowableRow(0);
ScrolledWindow2 = new wxScrolledWindow(
Panel2, ID_SCROLLEDWINDOW2, wxDefaultPosition, wxDefaultSize,
wxHSCROLL | wxVSCROLL, _T("ID_SCROLLEDWINDOW2"));
FlexGridSizer11 = new wxFlexGridSizer(0, 1, 0, 0);
FlexGridSizer11->AddGrowableCol(0);
FlexGridSizer11->AddGrowableRow(0);
bmpOriginal = new mrpt::gui::wxMRPTImageControl(
ScrolledWindow2, ID_CUSTOM2, wxDefaultPosition.x, wxDefaultPosition.y,
wxSize(640, 480).GetWidth(), wxSize(640, 480).GetHeight());
FlexGridSizer11->Add(bmpOriginal, 1, wxALL | wxALIGN_LEFT | wxALIGN_TOP, 0);
ScrolledWindow2->SetSizer(FlexGridSizer11);
FlexGridSizer11->Fit(ScrolledWindow2);
FlexGridSizer11->SetSizeHints(ScrolledWindow2);
FlexGridSizer13->Add(
ScrolledWindow2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
Panel2->SetSizer(FlexGridSizer13);
FlexGridSizer13->Fit(Panel2);
FlexGridSizer13->SetSizeHints(Panel2);
Panel3 = new wxPanel(
Notebook1, ID_PANEL3, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL,
_T("ID_PANEL3"));
FlexGridSizer10 = new wxFlexGridSizer(1, 1, 0, 0);
FlexGridSizer10->AddGrowableCol(0);
FlexGridSizer10->AddGrowableRow(0);
ScrolledWindow3 = new wxScrolledWindow(
Panel3, ID_SCROLLEDWINDOW3, wxDefaultPosition, wxDefaultSize,
wxHSCROLL | wxVSCROLL, _T("ID_SCROLLEDWINDOW3"));
FlexGridSizer14 = new wxFlexGridSizer(1, 1, 0, 0);
FlexGridSizer14->AddGrowableCol(0);
FlexGridSizer14->AddGrowableRow(0);
bmpRectified = new mrpt::gui::wxMRPTImageControl(
ScrolledWindow3, ID_CUSTOM1, wxDefaultPosition.x, wxDefaultPosition.y,
wxSize(640, 480).GetWidth(), wxSize(640, 480).GetHeight());
FlexGridSizer14->Add(
bmpRectified, 1, wxALL | wxALIGN_LEFT | wxALIGN_TOP, 0);
ScrolledWindow3->SetSizer(FlexGridSizer14);
FlexGridSizer14->Fit(ScrolledWindow3);
FlexGridSizer14->SetSizeHints(ScrolledWindow3);
FlexGridSizer10->Add(
ScrolledWindow3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
Panel3->SetSizer(FlexGridSizer10);
FlexGridSizer10->Fit(Panel3);
FlexGridSizer10->SetSizeHints(Panel3);
Panel1 = new wxPanel(
Notebook1, ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL,
_T("ID_PANEL1"));
FlexGridSizer12 = new wxFlexGridSizer(1, 1, 0, 0);
FlexGridSizer12->AddGrowableCol(0);
FlexGridSizer12->AddGrowableRow(0);
m_3Dview = new CMyGLCanvas(
Panel1, ID_XY_GLCANVAS, wxDefaultPosition, wxSize(-1, 300),
wxTAB_TRAVERSAL, _T("ID_XY_GLCANVAS"));
FlexGridSizer12->Add(
m_3Dview, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
Panel1->SetSizer(FlexGridSizer12);
FlexGridSizer12->Fit(Panel1);
FlexGridSizer12->SetSizeHints(Panel1);
Notebook1->AddPage(Panel2, _("Original Image"), false);
Notebook1->AddPage(
Panel3, _("Rectified image and reprojected points"), true);
Notebook1->AddPage(Panel1, _("3D view"), false);
FlexGridSizer3->Add(
Notebook1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2);
FlexGridSizer1->Add(
FlexGridSizer3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);
SetSizer(FlexGridSizer1);
FlexGridSizer1->Fit(this);
FlexGridSizer1->SetSizeHints(this);
Connect(
ID_BUTTON8, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnCaptureNowClick);
Connect(
ID_BUTTON1, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnAddImage);
Connect(
ID_BUTTON2, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnListClear);
Connect(
ID_BUTTON9, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnSaveImagesClick);
Connect(
ID_LISTBOX1, wxEVT_COMMAND_LISTBOX_SELECTED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnlbFilesSelect);
Connect(
ID_CHOICE1, wxEVT_COMMAND_CHOICE_SELECTED,
(wxObjectEventFunction)&camera_calib_guiDialog::OncbZoomSelect);
Connect(
ID_BUTTON3, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnRunCalibClick);
Connect(
ID_BUTTON6, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnSaveClick);
Connect(
ID_BUTTON7, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnManualRectClick);
Connect(
ID_BUTTON5, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnAboutClick);
Connect(
ID_BUTTON4, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::OnbtnCloseClick);
Connect(
ID_BUTTON10, wxEVT_COMMAND_BUTTON_CLICKED,
(wxObjectEventFunction)&camera_calib_guiDialog::
OnbtnPoseEstimateNowClick);
//*)
camera_params.intrinsicParams(0, 0) = 0; // Indicate calib didn't run yet.
wxIcon icon;
icon.CopyFromBitmap(wxBitmap(wxImage(icono_main_xpm)));
this->SetIcon(icon);
this->show3Dview(); // Empty 3D scene
Center();
this->SetTitle(format(
"Camera calibration %s - Part of the MRPT project",
CAMERA_CALIB_GUI_VERSION)
.c_str());
Maximize();
}
camera_calib_guiDialog::~camera_calib_guiDialog()
{
//(*Destroy(camera_calib_guiDialog)
//*)
this->clearListImages();
}
// Ask the user for new files to add to the list:
void camera_calib_guiDialog::OnAddImage(wxCommandEvent& event)
{
try
{
wxFileDialog dlg(
this, _("Select image(s) to open"), _("."), _(""),
_("Image files (*.bmp;*.png;*.jpg)|*.bmp;*.png;*.jpg|All files "
"(*.*)|*.*"),
wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_PREVIEW);
if (wxID_OK != dlg.ShowModal()) return;
wxBusyCursor waitcur;
wxArrayString files;
dlg.GetPaths(files);
wxProgressDialog progDia(
wxT("Adding image files"), wxT("Processing..."),
files.Count(), // range
this, // parent
wxPD_CAN_ABORT | wxPD_APP_MODAL | wxPD_SMOOTH | wxPD_AUTO_HIDE |
wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME);
wxTheApp->Yield(); // Let the app. process messages
int counter_loops = 0;
for (unsigned int i = 0; i < files.Count(); i++)
{
if (counter_loops++ % 5 == 0)
{
if (!progDia.Update(i)) break;
wxTheApp->Yield(); // Let the app. process messages
}
const string fil = string(files[i].mb_str());
TImageCalibData dat;
#if USE_EXTERNAL_STORAGE_IMGS
// Optimization: Use external storage:
// ---------------------------------------
// string tmp_check = mrpt::system::getTempFileName()+".jpg";
// string tmp_rectified = mrpt::system::getTempFileName()+".jpg";
// dat.img_original.saveToFile(tmp_check);
// dat.img_original.saveToFile(tmp_rectified);
// mark all imgs. as external storage:
dat.img_original.setExternalStorage(fil);
// dat.img_checkboard.setExternalStorage(tmp_check);
// dat.img_rectified.setExternalStorage(tmp_rectified);
dat.img_original.unload();
// dat.img_checkboard.unload();
// dat.img_rectified.unload();
#else
// All in memory:
if (!dat.img_original.loadFromFile(fil))
{
wxMessageBox(
format("Error loading file: %s", fil.c_str()).c_str()),
_("Error");
this->updateListOfImages();
return;
}
#endif
lst_images[fil] = dat;
}
this->updateListOfImages();
}
catch (const std::exception& e)
{
wxMessageBox(
mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this);
}
}
void camera_calib_guiDialog::clearListImages() { lst_images.clear(); }
// Clear list of images.
void camera_calib_guiDialog::OnListClear(wxCommandEvent& event)
{
this->clearListImages();
this->updateListOfImages();
}
void camera_calib_guiDialog::OnbtnRunCalibClick(wxCommandEvent& event)
{
try
{
txtLog->Clear();
CMyRedirector redire(txtLog, true, 10);
const unsigned int check_size_x = edSizeX->GetValue();
const unsigned int check_size_y = edSizeY->GetValue();
const double check_squares_length_X_meters =
0.001 * atof(string(edLengthX->GetValue().mb_str()).c_str());
const double check_squares_length_Y_meters =
0.001 * atof(string(edLengthY->GetValue().mb_str()).c_str());
const bool normalize_image = cbNormalize->GetValue();
const bool useScaramuzzaAlternativeDetector =
rbMethod->GetSelection() == 1;
wxBusyCursor waitcur;
bool res = mrpt::vision::checkerBoardCameraCalibration(
lst_images, check_size_x, check_size_y,
check_squares_length_X_meters, check_squares_length_Y_meters,
camera_params, normalize_image, nullptr /* MSE */,
false /* skip draw */, useScaramuzzaAlternativeDetector);
refreshDisplayedImage();
if (!res)
wxMessageBox(
_("Calibration finished with error: Please check the text log "
"to see what's wrong"),
_("Error"));
if (res) show3Dview();
}
catch (const std::exception& e)
{
wxMessageBox(
mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this);
}
}
void camera_calib_guiDialog::OnbtnCloseClick(wxCommandEvent&) { Close(); }
void camera_calib_guiDialog::OnbtnAboutClick(wxCommandEvent&)
{
mrpt::gui::show_mrpt_about_box_wxWidgets(this, "camera-calib");
}
// save matrices:
void camera_calib_guiDialog::OnbtnSaveClick(wxCommandEvent& event)
{
if (camera_params.intrinsicParams(0, 0) == 0)
{
wxMessageBox(_("Run the calibration first"), _("Error"));
return;
}
{
wxFileDialog dlg(
this, _("Save intrinsic parameters matrix"), _("."),
_("intrinsic_matrix.txt"),
_("Text files (*.txt)|*.txt|All files (*.*)|*.*"),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (wxID_OK != dlg.ShowModal()) return;
camera_params.intrinsicParams.saveToTextFile(
string(dlg.GetPath().mb_str()));
}
{
wxFileDialog dlg(
this, _("Save distortion parameters"), _("."),
_("distortion_matrix.txt"),
_("Text files (*.txt)|*.txt|All files (*.*)|*.*"),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (wxID_OK != dlg.ShowModal()) return;
CMatrixDouble M(1, 5);
for (unsigned i = 0; i < 5; i++) M(0, i) = camera_params.dist[i];
M.saveToTextFile(string(dlg.GetPath().mb_str()));
}
}
// Update the listbox from lst_img_files
void camera_calib_guiDialog::updateListOfImages()
{
lbFiles->Clear();
for (auto s = lst_images.begin(); s != lst_images.end(); ++s)
lbFiles->Append(s->first.c_str());
btnSaveImages->Enable(!lst_images.empty());
refreshDisplayedImage();
}
// Shows the image selected in the listbox:
void camera_calib_guiDialog::refreshDisplayedImage()
{
try
{
if (!lbFiles->GetCount())
{
// No images:
return;
}
// Assure there's one selected:
if (lbFiles->GetSelection() == wxNOT_FOUND) lbFiles->SetSelection(0);
const string selFile = string(lbFiles->GetStringSelection().mb_str());
auto it = lst_images.find(selFile);
if (it == lst_images.end()) return;
// Zoom:
const std::string strZoom =
string(cbZoom->GetStringSelection().mb_str());
const double zoomVal = 0.01 * atof(strZoom.c_str());
ASSERT_(zoomVal > 0 && zoomVal < 30);
TImageSize imgSizes(0, 0);
// Generate the images on-the-fly:
CImage imgOrgColor;
it->second.img_original.colorImage(imgOrgColor);
imgSizes = imgOrgColor.getSize();
// Rectify:
CImage imgRect;
if (camera_params.intrinsicParams(0, 0) == 0)
{
// Not calibrated yet:
imgRect = imgOrgColor;
imgRect.scaleImage(
imgRect, imgSizes.x * zoomVal, imgSizes.y * zoomVal,
IMG_INTERP_NN);
}
else
{
imgOrgColor.undistort(imgRect, camera_params);
imgRect.scaleImage(
imgRect, imgSizes.x * zoomVal, imgSizes.y * zoomVal,
IMG_INTERP_NN);
// Draw reprojected:
for (auto& k : it->second.projectedPoints_undistorted)
imgRect.drawCircle(
zoomVal * k.x, zoomVal * k.y, 4, TColor(0, 255, 64));
imgRect.drawCircle(10, 10, 4, TColor(0, 255, 64));
imgRect.textOut(18, 4, "Reprojected corners", TColor::white());
}
// Zoom images:
imgOrgColor.scaleImage(
imgOrgColor, imgSizes.x * zoomVal, imgSizes.y * zoomVal,
IMG_INTERP_NN);
imgSizes = imgOrgColor.getSize();
CImage imgCheck = imgOrgColor;
// Draw the board:
for (unsigned int k = 0; k < it->second.detected_corners.size(); k++)
{
imgCheck.cross(
it->second.detected_corners[k].x * zoomVal,
it->second.detected_corners[k].y * zoomVal, TColor::blue(), '+',
3);
imgCheck.drawCircle(
it->second.projectedPoints_distorted[k].x * zoomVal,
it->second.projectedPoints_distorted[k].y * zoomVal, 4,
TColor(0, 255, 64));
}
imgCheck.drawCircle(10, 10, 4, TColor(0, 255, 64));
imgCheck.textOut(18, 4, "Reprojected corners", TColor::white());
imgCheck.cross(10, 30, TColor::blue(), '+', 3);
imgCheck.textOut(18, 24, "Detected corners", TColor::white());
this->bmpOriginal->AssignImage(imgCheck);
this->bmpRectified->AssignImage(imgRect);
it->second.img_original.unload();
// Plot:
this->bmpOriginal->SetMinSize(wxSize(imgSizes.x, imgSizes.y));
this->bmpOriginal->SetMaxSize(wxSize(imgSizes.x, imgSizes.y));
this->bmpOriginal->SetSize(imgSizes.x, imgSizes.y);
this->bmpRectified->SetMinSize(wxSize(imgSizes.x, imgSizes.y));
this->bmpRectified->SetMaxSize(wxSize(imgSizes.x, imgSizes.y));
this->bmpRectified->SetSize(imgSizes.x, imgSizes.y);
this->FlexGridSizer11->RecalcSizes();
this->FlexGridSizer14->RecalcSizes();
// this->ScrolledWindow2->SetVirtualSize(wxSize(imgSizes.x,imgSizes.y));
// this->ScrolledWindow3->SetVirtualSize(wxSize(imgSizes.x,imgSizes.y));
this->ScrolledWindow2->SetScrollbars(1, 1, imgSizes.x, imgSizes.y);
this->ScrolledWindow3->SetScrollbars(1, 1, imgSizes.x, imgSizes.y);
this->bmpOriginal->Refresh(false);
this->bmpRectified->Refresh(false);
}
catch (const std::exception& e)
{
wxMessageBox(
mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this);
}
}
void camera_calib_guiDialog::OnlbFilesSelect(wxCommandEvent& event)
{
refreshDisplayedImage();
}
void camera_calib_guiDialog::show3Dview()
{
mrpt::opengl::COpenGLScene::Ptr scene =
mrpt::make_aligned_shared<mrpt::opengl::COpenGLScene>();
const unsigned int check_size_x = edSizeX->GetValue();
const unsigned int check_size_y = edSizeY->GetValue();
const double check_squares_length_X_meters =
0.001 * atof(string(edLengthX->GetValue().mb_str()).c_str());
const double check_squares_length_Y_meters =
0.001 * atof(string(edLengthY->GetValue().mb_str()).c_str());
if (!check_squares_length_X_meters || !check_squares_length_Y_meters)
return;
opengl::CGridPlaneXY::Ptr grid =
mrpt::make_aligned_shared<opengl::CGridPlaneXY>(
0, check_size_x * check_squares_length_X_meters, 0,
check_size_y * check_squares_length_Y_meters, 0,
check_squares_length_X_meters);
scene->insert(grid);
for (auto& lst_image : lst_images)
{
if (!lst_image.second.detected_corners.empty())
{
mrpt::opengl::CSetOfObjects::Ptr cor =
mrpt::opengl::stock_objects::CornerXYZ();
cor->setName(mrpt::system::extractFileName(lst_image.first));
cor->enableShowName(true);
cor->setScale(0.1f);
cor->setPose(lst_image.second.reconstructed_camera_pose);
scene->insert(cor);
}
}
// scene->insert( mrpt::opengl::stock_objects::CornerXYZ() );
this->m_3Dview->setOpenGLSceneRef(scene);
this->m_3Dview->Refresh();
}
// Enter calib. params manually:
void camera_calib_guiDialog::OnbtnManualRectClick(wxCommandEvent& event)
{
wxMessageBox(
_("Please, enter calibration parameters manually next to overpass "
"automatically obtained parameters."),
_("Manual parameters"));
wxString s;
if (camera_params.intrinsicParams(0, 0) == 0)
{
wxMessageBox(_("Run the calibration first"), _("Error"));
return;
}
s = wxGetTextFromUser(
_("Focus length in X pixel size (fx):"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(0, 0)),
this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.intrinsicParams(0, 0)))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Focus length in Y pixel size (fy):"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(1, 1)),
this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.intrinsicParams(1, 1)))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Image center X (cx):"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(0, 2)),
this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.intrinsicParams(0, 2)))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Image center Y (cy):"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(1, 2)),
this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.intrinsicParams(1, 2)))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Distortion param p1:"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.dist[0]), this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.dist[0]))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Distortion param p2:"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.dist[1]), this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.dist[1]))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Distortion param k1:"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.dist[2]), this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.dist[2]))
{
wxMessageBox(_("Invalid number"));
return;
}
s = wxGetTextFromUser(
_("Distortion param k2:"), _("Manual parameters"),
wxString::Format(wxT("%.07f"), camera_params.dist[3]), this);
if (s.IsEmpty()) return;
if (!s.ToDouble(&camera_params.dist[3]))
{
wxMessageBox(_("Invalid number"));
return;
}
refreshDisplayedImage();
}
void camera_calib_guiDialog::OnbtnCaptureNowClick(wxCommandEvent& event)
{
CDlgCalibWizardOnline dlg(this);
// Set pattern params:
dlg.edLengthX->SetValue(this->edLengthX->GetValue());
dlg.edLengthY->SetValue(this->edLengthY->GetValue());
dlg.edSizeX->SetValue(this->edSizeX->GetValue());
dlg.edSizeY->SetValue(this->edSizeY->GetValue());
dlg.cbNormalize->SetValue(this->cbNormalize->GetValue());
// Run:
dlg.ShowModal();
// Get params:
this->edLengthX->SetValue(dlg.edLengthX->GetValue());
this->edLengthY->SetValue(dlg.edLengthY->GetValue());
this->edSizeX->SetValue(dlg.edSizeX->GetValue());
this->edSizeY->SetValue(dlg.edSizeY->GetValue());
this->cbNormalize->SetValue(dlg.cbNormalize->GetValue());
// Get images:
lst_images = dlg.m_calibFrames;
this->updateListOfImages();
}
void camera_calib_guiDialog::OnbtnPoseEstimateNowClick(wxCommandEvent& event)
{
// Compute pose using PnP Algorithms toolkit
CDlgPoseEst dlg(this);
// Set pattern params:
dlg.edLengthX->SetValue(this->edLengthX->GetValue());
dlg.edLengthY->SetValue(this->edLengthY->GetValue());
dlg.edSizeX->SetValue(this->edSizeX->GetValue());
dlg.edSizeY->SetValue(this->edSizeY->GetValue());
dlg.cbNormalize->SetValue(this->cbNormalize->GetValue());
// Run:
dlg.ShowModal();
// Get params:
this->edLengthX->SetValue(dlg.edLengthX->GetValue());
this->edLengthY->SetValue(dlg.edLengthY->GetValue());
this->edSizeX->SetValue(dlg.edSizeX->GetValue());
this->edSizeY->SetValue(dlg.edSizeY->GetValue());
this->cbNormalize->SetValue(dlg.cbNormalize->GetValue());
// Get images:
lst_images = dlg.m_calibFrames;
this->updateListOfImages();
}
void camera_calib_guiDialog::OnbtnSaveImagesClick(wxCommandEvent& event)
{
try
{
if (lst_images.empty()) return;
wxDirDialog dlg(
this, _("Select the directory where to save the images"), _("."));
if (dlg.ShowModal() == wxID_OK)
{
string dir = string(dlg.GetPath().mb_str());
for (auto& lst_image : lst_images)
lst_image.second.img_original.saveToFile(
dir + string("/") + lst_image.first + string(".png"));
}
}
catch (const std::exception& e)
{
wxMessageBox(
mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this);
}
}
void camera_calib_guiDialog::OncbZoomSelect(wxCommandEvent& event)
{
refreshDisplayedImage();
}
| 33.766484 | 80 | 0.724297 | waltzrobotics |
14721df9fd0e5d7acd839bd5ec78de00e0f0cdf3 | 2,125 | cpp | C++ | Chapter05-physics/005-forces/src/ofApp.cpp | jeffcrouse/ccof | d9c5773b9913209e3ff06a4777115d750487cb44 | [
"MIT"
] | 6 | 2017-09-27T14:13:44.000Z | 2020-06-24T18:16:22.000Z | Chapter05-physics/005-forces/src/ofApp.cpp | jeffcrouse/ccof | d9c5773b9913209e3ff06a4777115d750487cb44 | [
"MIT"
] | null | null | null | Chapter05-physics/005-forces/src/ofApp.cpp | jeffcrouse/ccof | d9c5773b9913209e3ff06a4777115d750487cb44 | [
"MIT"
] | 3 | 2017-10-27T20:33:33.000Z | 2019-09-17T05:42:13.000Z | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetWindowShape(1280, 800);
ofSetWindowTitle("forces");
ofSetFrameRate(60);
ofBackground(255, 255, 255);
ofEnableSmoothing();
ofSetCircleResolution(40);
gravity.x = 0;
gravity.y = 0.08;
wind.x = -0.1;
wind.y = 0;
}
//--------------------------------------------------------------
void ofApp::update(){
t.applyForce(gravity);
t.applyForce(wind);
// Make the Thing slow down as it passes through some "liquid"
// Do this by applying a negative force
// 1. Decide on a drag coeffecient (negative)
// 2. Multiply it by the vel
// 3. Apply the force
// 4. update()
t.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
t.draw();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
t.reset();
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 22.606383 | 66 | 0.356706 | jeffcrouse |
1474a1984a53c1d6cb08d767e15adf8abab34914 | 30,372 | cpp | C++ | library/src/blas2/rocblas_trsv.cpp | YvanMokwinski/rocBLAS | f02952487c7019cbde04c4ddcb596aaf71e51ec6 | [
"MIT"
] | null | null | null | library/src/blas2/rocblas_trsv.cpp | YvanMokwinski/rocBLAS | f02952487c7019cbde04c4ddcb596aaf71e51ec6 | [
"MIT"
] | 1 | 2019-09-26T01:51:09.000Z | 2019-09-26T18:09:56.000Z | library/src/blas2/rocblas_trsv.cpp | YvanMokwinski/rocBLAS | f02952487c7019cbde04c4ddcb596aaf71e51ec6 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright 2016-2019 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "../blas3/trtri_trsm.hpp"
#include "handle.h"
#include "logging.h"
#include "rocblas.h"
#include "rocblas_gemv.hpp"
#include "utility.h"
#include <algorithm>
#include <cstdio>
#include <tuple>
namespace
{
using std::max;
using std::min;
constexpr rocblas_int NB_X = 1024;
constexpr rocblas_int STRSV_BLOCK = 128;
constexpr rocblas_int DTRSV_BLOCK = 128;
template <typename T>
constexpr T negative_one = -1;
template <typename T>
constexpr T zero = 0;
template <typename T>
constexpr T one = 1;
template <typename T>
__global__ void flip_vector_kernel(T* __restrict__ data,
T* __restrict__ data_end,
rocblas_int size,
rocblas_int abs_incx)
{
ptrdiff_t tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
if(tx < size)
{
auto offset = tx * abs_incx;
auto temp = data[offset];
data[offset] = data_end[-offset];
data_end[-offset] = temp;
}
}
template <typename T>
void flip_vector(rocblas_handle handle, T* data, rocblas_int m, rocblas_int abs_incx)
{
T* data_end = data + (m - 1) * abs_incx;
rocblas_int size = (m + 1) / 2;
rocblas_int blocksX = (size - 1) / NB_X + 1;
dim3 grid = blocksX;
dim3 threads = NB_X;
hipLaunchKernelGGL(flip_vector_kernel,
grid,
threads,
0,
handle->rocblas_stream,
data,
data_end,
size,
abs_incx);
}
template <typename T>
__global__ void strided_vector_copy_kernel(T* __restrict__ dst,
rocblas_int dst_incx,
const T* __restrict__ src,
rocblas_int src_incx,
rocblas_int size)
{
ptrdiff_t tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
if(tx < size)
dst[tx * dst_incx] = src[tx * src_incx];
}
template <typename T>
void strided_vector_copy(rocblas_handle handle,
T* dst,
rocblas_int dst_incx,
T* src,
rocblas_int src_incx,
rocblas_int size)
{
rocblas_int blocksX = (size - 1) / NB_X + 1;
dim3 grid = blocksX;
dim3 threads = NB_X;
hipLaunchKernelGGL(strided_vector_copy_kernel,
grid,
threads,
0,
handle->rocblas_stream,
dst,
dst_incx,
src,
src_incx,
size);
}
template <rocblas_int BLOCK, typename T>
rocblas_status rocblas_trsv_left(rocblas_handle handle,
rocblas_fill uplo,
rocblas_operation transA,
rocblas_int m,
const T* A,
rocblas_int lda,
T* B,
rocblas_int incx,
const T* invA,
T* X)
{
rocblas_int i, jb;
if(transA == rocblas_operation_none)
{
if(uplo == rocblas_fill_lower)
{
// left, lower no-transpose
jb = min(BLOCK, m);
rocblas_gemv_template(
handle, transA, jb, jb, &one<T>, invA, BLOCK, B, incx, &zero<T>, X, 1);
if(BLOCK < m)
{
rocblas_gemv_template(handle,
transA,
m - BLOCK,
BLOCK,
&negative_one<T>,
A + BLOCK,
lda,
X,
1,
&one<T>,
B + BLOCK * incx,
incx);
// remaining blocks
for(i = BLOCK; i < m; i += BLOCK)
{
jb = min(m - i, BLOCK);
rocblas_gemv_template(handle,
transA,
jb,
jb,
&one<T>,
invA + i * BLOCK,
BLOCK,
B + i * incx,
incx,
&zero<T>,
X + i,
1);
if(i + BLOCK < m)
rocblas_gemv_template(handle,
transA,
m - i - BLOCK,
BLOCK,
&negative_one<T>,
A + i + BLOCK + i * lda,
lda,
X + i,
1,
&one<T>,
B + (i + BLOCK) * incx,
incx);
}
}
}
else
{
// left, upper no-transpose
jb = m % BLOCK == 0 ? BLOCK : m % BLOCK;
i = m - jb;
// if m=n=35=lda=ldb, BLOCK =32, then jb = 3, i = 32; {3, 35, 3, 32, 35, 35}
rocblas_gemv_template(handle,
transA,
jb,
jb,
&one<T>,
invA + i * BLOCK,
BLOCK,
B + i * incx,
incx,
&zero<T>,
X + i,
1);
if(i >= BLOCK)
{
rocblas_gemv_template(handle,
transA,
i,
jb,
&negative_one<T>,
A + i * lda,
lda,
X + i,
1,
&one<T>,
B,
incx);
// remaining blocks
for(i = m - jb - BLOCK; i >= 0; i -= BLOCK)
{
//{32, 35, 32, 32, 35, 35}
rocblas_gemv_template(handle,
transA,
BLOCK,
BLOCK,
&one<T>,
invA + i * BLOCK,
BLOCK,
B + i * incx,
incx,
&zero<T>,
X + i,
1);
if(i >= BLOCK)
rocblas_gemv_template(handle,
transA,
i,
BLOCK,
&negative_one<T>,
A + i * lda,
lda,
X + i,
1,
&one<T>,
B,
incx);
}
}
}
}
else
{ // transA == rocblas_operation_transpose || transA == rocblas_operation_conjugate_transpose
if(uplo == rocblas_fill_lower)
{
// left, lower transpose
jb = m % BLOCK == 0 ? BLOCK : m % BLOCK;
i = m - jb;
rocblas_gemv_template(handle,
transA,
jb,
jb,
&one<T>,
invA + i * BLOCK,
BLOCK,
B + i * incx,
incx,
&zero<T>,
X + i,
1);
if(i - BLOCK >= 0)
{
rocblas_gemv_template(handle,
transA,
jb,
i,
&negative_one<T>,
A + i,
lda,
X + i,
1,
&one<T>,
B,
incx);
// remaining blocks
for(i = m - jb - BLOCK; i >= 0; i -= BLOCK)
{
rocblas_gemv_template(handle,
transA,
BLOCK,
BLOCK,
&one<T>,
invA + i * BLOCK,
BLOCK,
B + i * incx,
incx,
&zero<T>,
X + i,
1);
if(i >= BLOCK)
rocblas_gemv_template(handle,
transA,
BLOCK,
i,
&negative_one<T>,
A + i,
lda,
X + i,
1,
&one<T>,
B,
incx);
}
}
}
else
{
// left, upper transpose
jb = min(BLOCK, m);
rocblas_gemv_template(
handle, transA, jb, jb, &one<T>, invA, BLOCK, B, incx, &zero<T>, X, 1);
if(BLOCK < m)
{
rocblas_gemv_template(handle,
transA,
BLOCK,
m - BLOCK,
&negative_one<T>,
A + BLOCK * lda,
lda,
X,
1,
&one<T>,
B + BLOCK * incx,
incx);
// remaining blocks
for(i = BLOCK; i < m; i += BLOCK)
{
jb = min(m - i, BLOCK);
rocblas_gemv_template(handle,
transA,
jb,
jb,
&one<T>,
invA + i * BLOCK,
BLOCK,
B + i * incx,
incx,
&zero<T>,
X + i,
1);
if(i + BLOCK < m)
rocblas_gemv_template(handle,
transA,
BLOCK,
m - i - BLOCK,
&negative_one<T>,
A + i + (i + BLOCK) * lda,
lda,
X + i,
1,
&one<T>,
B + (i + BLOCK) * incx,
incx);
}
}
}
} // transpose
return rocblas_status_success;
}
template <rocblas_int BLOCK, typename T>
rocblas_status special_trsv_template(rocblas_handle handle,
rocblas_fill uplo,
rocblas_operation transA,
rocblas_diagonal diag,
rocblas_int m,
const T* A,
rocblas_int lda,
T* B,
ptrdiff_t incx,
const T* invA,
T* x_temp)
{
bool parity = (transA == rocblas_operation_none) ^ (uplo == rocblas_fill_lower);
size_t R = m / BLOCK;
for(size_t r = 0; r < R; r++)
{
size_t q = R - r;
size_t j = parity ? q - 1 : r;
// copy a BLOCK*n piece we are solving at a time
strided_vector_copy<T>(handle, x_temp, 1, B + incx * j * BLOCK, incx, BLOCK);
if(r)
{
rocblas_int M = BLOCK;
rocblas_int N = BLOCK;
const T* A_current;
T* B_current = parity ? B + q * BLOCK * incx : B;
if(transA == rocblas_operation_none)
{
N *= r;
A_current = parity ? A + BLOCK * ((lda + 1) * q - 1) : A + N;
}
else
{
M *= r;
A_current = parity ? A + BLOCK * ((lda + 1) * q - lda) : A + M * lda;
}
rocblas_gemv_template(handle,
transA,
M,
N,
&negative_one<T>,
A_current,
lda,
B_current,
incx,
&one<T>,
x_temp,
1);
}
rocblas_gemv_template(handle,
transA,
BLOCK,
BLOCK,
&one<T>,
invA + j * BLOCK * BLOCK,
BLOCK,
x_temp,
1,
&zero<T>,
B + j * BLOCK * incx,
incx);
}
return rocblas_status_success;
}
template <typename>
constexpr char rocblas_trsv_name[] = "unknown";
template <>
constexpr char rocblas_trsv_name<float>[] = "rocblas_strsv";
template <>
constexpr char rocblas_trsv_name<double>[] = "rocblas_dtrsv";
template <rocblas_int BLOCK, typename T>
rocblas_status rocblas_trsv_ex_impl(rocblas_handle handle,
rocblas_fill uplo,
rocblas_operation transA,
rocblas_diagonal diag,
rocblas_int m,
const T* A,
rocblas_int lda,
T* B,
rocblas_int incx,
const T* supplied_invA = nullptr,
rocblas_int supplied_invA_size = 0)
{
if(!handle)
return rocblas_status_invalid_handle;
auto layer_mode = handle->layer_mode;
if(layer_mode & rocblas_layer_mode_log_trace)
log_trace(handle, rocblas_trsv_name<T>, uplo, transA, diag, m, A, lda, B, incx);
if(layer_mode & (rocblas_layer_mode_log_bench | rocblas_layer_mode_log_profile))
{
auto uplo_letter = rocblas_fill_letter(uplo);
auto transA_letter = rocblas_transpose_letter(transA);
auto diag_letter = rocblas_diag_letter(diag);
if(layer_mode & rocblas_layer_mode_log_bench)
{
if(handle->pointer_mode == rocblas_pointer_mode_host)
log_bench(handle,
"./rocblas-bench -f trsv -r",
rocblas_precision_string<T>,
"--uplo",
uplo_letter,
"--transposeA",
transA_letter,
"--diag",
diag_letter,
"-m",
m,
"--lda",
lda,
"--incx",
incx);
}
if(layer_mode & rocblas_layer_mode_log_profile)
log_profile(handle,
rocblas_trsv_name<T>,
"uplo",
uplo_letter,
"transA",
transA_letter,
"diag",
diag_letter,
"M",
m,
"lda",
lda,
"incx",
incx);
}
if(uplo != rocblas_fill_lower && uplo != rocblas_fill_upper)
return rocblas_status_not_implemented;
if(!A || !B)
return rocblas_status_invalid_pointer;
if(m < 0 || lda < m || lda < 1 || !incx)
return rocblas_status_invalid_size;
// quick return if possible.
// return rocblas_status_size_unchanged if device memory size query
if(!m)
return handle->is_device_memory_size_query() ? rocblas_status_size_unchanged
: rocblas_status_success;
// Whether size is an exact multiple of blocksize
const bool exact_blocks = (m % BLOCK) == 0;
// perf_status indicates whether optimal performance is obtainable with available memory
rocblas_status perf_status = rocblas_status_success;
size_t invA_bytes = 0;
size_t c_temp_bytes = 0;
// For user-supplied invA, check to make sure size is large enough
// If not large enough, indicate degraded performance and ignore supplied invA
if(supplied_invA && supplied_invA_size / BLOCK < m)
{
static int msg = fputs("WARNING: TRSV invA_size argument is too small; invA argument "
"is being ignored; TRSV performance is degraded\n",
stderr);
perf_status = rocblas_status_perf_degraded;
supplied_invA = nullptr;
}
if(!supplied_invA)
{
// Only allocate bytes for invA if supplied_invA == nullptr or supplied_invA_size is too small
invA_bytes = sizeof(T) * BLOCK * m;
// When m < BLOCK, C is unnecessary for trtri
c_temp_bytes = (m / BLOCK) * (sizeof(T) * (BLOCK / 2) * (BLOCK / 2));
// For the TRTRI last diagonal block we need remainder space if m % BLOCK != 0
if(!exact_blocks)
{
// TODO: Make this more accurate -- right now it's much larger than necessary
size_t remainder_bytes = sizeof(T) * ROCBLAS_TRTRI_NB * BLOCK * 2;
// C is the maximum of the temporary space needed for TRTRI
c_temp_bytes = max(c_temp_bytes, remainder_bytes);
}
}
// Temporary solution vector
// If the special solver can be used, then only BLOCK words are needed instead of m words
size_t x_temp_bytes = exact_blocks ? sizeof(T) * BLOCK : sizeof(T) * m;
// X and C temporaries can share space, so the maximum size is allocated
size_t x_c_temp_bytes = max(x_temp_bytes, c_temp_bytes);
// If this is a device memory size query, set optimal size and return changed status
if(handle->is_device_memory_size_query())
return handle->set_optimal_device_memory_size(x_c_temp_bytes, invA_bytes);
// Attempt to allocate optimal memory size, returning error if failure
auto mem = handle->device_malloc(x_c_temp_bytes, invA_bytes);
if(!mem)
return rocblas_status_memory_error;
// Get pointers to allocated device memory
// Note: Order of pointers in std::tie(...) must match order of sizes in handle->device_malloc(...)
void* x_temp;
void* invA;
std::tie(x_temp, invA) = mem;
// Temporarily switch to host pointer mode, restoring on return
auto saved_pointer_mode = handle->push_pointer_mode(rocblas_pointer_mode_host);
rocblas_status status = rocblas_status_success;
if(supplied_invA)
invA = const_cast<T*>(supplied_invA);
else
{
// batched trtri invert diagonal part (BLOCK*BLOCK) of A into invA
auto c_temp = x_temp; // Uses same memory as x_temp
status = rocblas_trtri_trsm_template<BLOCK>(
handle, (T*)c_temp, uplo, diag, m, A, lda, (T*)invA);
if(status != rocblas_status_success)
return status;
}
if(transA == rocblas_operation_conjugate_transpose)
transA = rocblas_operation_transpose;
// TODO: workaround to fix negative incx issue
rocblas_int abs_incx = incx < 0 ? -incx : incx;
if(incx < 0)
flip_vector(handle, B, m, abs_incx);
if(exact_blocks)
{
status = special_trsv_template<BLOCK>(
handle, uplo, transA, diag, m, A, lda, B, abs_incx, (const T*)invA, (T*)x_temp);
if(status != rocblas_status_success)
return status;
// TODO: workaround to fix negative incx issue
if(incx < 0)
flip_vector(handle, B, m, abs_incx);
}
else
{
status = rocblas_trsv_left<BLOCK>(
handle, uplo, transA, m, A, lda, B, abs_incx, (const T*)invA, (T*)x_temp);
if(status != rocblas_status_success)
return status;
// copy solution X into B
// TODO: workaround to fix negative incx issue
strided_vector_copy(handle,
B,
abs_incx,
incx < 0 ? (T*)x_temp + m - 1 : (T*)x_temp,
incx < 0 ? -1 : 1,
m);
}
return perf_status;
}
} // namespace
/*
* ===========================================================================
* C wrapper
* ===========================================================================
*/
extern "C" {
rocblas_status rocblas_strsv(rocblas_handle handle,
rocblas_fill uplo,
rocblas_operation transA,
rocblas_diagonal diag,
rocblas_int m,
const float* A,
rocblas_int lda,
float* x,
rocblas_int incx)
{
return rocblas_trsv_ex_impl<STRSV_BLOCK>(handle, uplo, transA, diag, m, A, lda, x, incx);
}
rocblas_status rocblas_dtrsv(rocblas_handle handle,
rocblas_fill uplo,
rocblas_operation transA,
rocblas_diagonal diag,
rocblas_int m,
const double* A,
rocblas_int lda,
double* x,
rocblas_int incx)
{
return rocblas_trsv_ex_impl<DTRSV_BLOCK>(handle, uplo, transA, diag, m, A, lda, x, incx);
}
rocblas_status rocblas_trsv_ex(rocblas_handle handle,
rocblas_fill uplo,
rocblas_operation transA,
rocblas_diagonal diag,
rocblas_int m,
const void* A,
rocblas_int lda,
void* x,
rocblas_int incx,
const void* invA,
rocblas_int invA_size,
rocblas_datatype compute_type)
{
switch(compute_type)
{
case rocblas_datatype_f64_r:
return rocblas_trsv_ex_impl<DTRSV_BLOCK>(handle,
uplo,
transA,
diag,
m,
static_cast<const double*>(A),
lda,
static_cast<double*>(x),
incx,
static_cast<const double*>(invA),
invA_size);
case rocblas_datatype_f32_r:
return rocblas_trsv_ex_impl<STRSV_BLOCK>(handle,
uplo,
transA,
diag,
m,
static_cast<const float*>(A),
lda,
static_cast<float*>(x),
incx,
static_cast<const float*>(invA),
invA_size);
default:
return rocblas_status_not_implemented;
}
}
} // extern "C"
| 41.892414 | 107 | 0.317859 | YvanMokwinski |
14802d5e52e55151331428b93f76038bb810446a | 1,288 | cc | C++ | Phase2Sim/src/PRIMSD.cc | uiowahep/Old | e52c4a67960028010904a1214f7d060c92f3da8c | [
"Apache-2.0"
] | null | null | null | Phase2Sim/src/PRIMSD.cc | uiowahep/Old | e52c4a67960028010904a1214f7d060c92f3da8c | [
"Apache-2.0"
] | null | null | null | Phase2Sim/src/PRIMSD.cc | uiowahep/Old | e52c4a67960028010904a1214f7d060c92f3da8c | [
"Apache-2.0"
] | null | null | null | #include "PRIMSD.hh"
#include "G4UnitsTable.hh"
#include "G4TrackStatus.hh"
#include "G4VProcess.hh"
using namespace CLHEP;
//
// Constructor
//
PRIMSD::PRIMSD(G4String name, RunParams runParams, int id,
HGCReadoutModule *readout)
: G4VSensitiveDetector(name),
_runParams(runParams), _readout(readout)
{
// _readout = (HGCReadoutModule*)readout;
G4cout << "### Setting up PRIMSD for id: " << id << " " << name << G4endl;
_id = id;
_readout->Book(id);
}
//
// Destructor
//
PRIMSD::~PRIMSD()
{
}
//
// Pre Event TODO
//
void PRIMSD::Initialize(G4HCofThisEvent*)
{
_readout->BeginEvent(_id);
}
//
// End of Event TODO
//
void PRIMSD::EndOfEvent(G4HCofThisEvent*)
{
_readout->FinishEvent(_id);
}
//
// Process Hit
//
G4bool PRIMSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
//
// Look at Primary Tracks only
//
if (aStep->GetTrack()->GetParentID() == 0)
{
PRIMHit aHit;
aHit.pos = aStep->GetPreStepPoint()->GetPosition();
aHit.mom = aStep->GetPreStepPoint()->GetMomentum();
aHit.ene = aStep->GetPreStepPoint()->GetKineticEnergy();
aHit.name =
aStep->GetTrack()->GetParticleDefinition()->GetParticleName();
aHit.id = aStep->GetTrack()->GetParticleDefinition()->GetPDGEncoding();
_readout->PushHit(aHit);
}
return true;
}
| 14.976744 | 76 | 0.67236 | uiowahep |
1481c8692ad5a3d42770a9c7933c63cdd26738a1 | 529 | hpp | C++ | posix/subsystem/src/nl-socket.hpp | robertlipe/managarm | 5e6173abb2f2b1c365e6774074380255bcccf3a5 | [
"MIT"
] | null | null | null | posix/subsystem/src/nl-socket.hpp | robertlipe/managarm | 5e6173abb2f2b1c365e6774074380255bcccf3a5 | [
"MIT"
] | null | null | null | posix/subsystem/src/nl-socket.hpp | robertlipe/managarm | 5e6173abb2f2b1c365e6774074380255bcccf3a5 | [
"MIT"
] | null | null | null |
#include "file.hpp"
namespace nl_socket {
// Configures the given netlink protocol.
// TODO: Let this take a callback that is called on receive?
void configure(int proto_idx, int num_groups);
// Broadcasts a kernel message to the given netlink multicast group.
void broadcast(int proto_idx, int grp_idx, std::string buffer);
smarter::shared_ptr<File, FileHandle> createSocketFile(int proto_idx, bool nonBlock);
std::array<smarter::shared_ptr<File, FileHandle>, 2> createSocketPair(int proto_idx);
} // namespace nl_socket
| 29.388889 | 85 | 0.775047 | robertlipe |
148443f31e06c8ad291dbfd6383580d424ab1f1c | 327 | cpp | C++ | LeetCode/974.subarray-sums-divisible-by-k.ac.cpp | Kresnt/AlgorithmTraining | 3dec1e712f525b4f406fe669d97888f322dfca97 | [
"MIT"
] | null | null | null | LeetCode/974.subarray-sums-divisible-by-k.ac.cpp | Kresnt/AlgorithmTraining | 3dec1e712f525b4f406fe669d97888f322dfca97 | [
"MIT"
] | null | null | null | LeetCode/974.subarray-sums-divisible-by-k.ac.cpp | Kresnt/AlgorithmTraining | 3dec1e712f525b4f406fe669d97888f322dfca97 | [
"MIT"
] | null | null | null | class Solution {
public:
int subarraysDivByK(vector<int>& A, int K) {
const int maxm = 10000 + 7;
const int n = A.size();
int c[maxm] = {0};
int ans = 0;
c[0] = 1;
for(int i = 0, l = 0; i < n; ++i) {
l = (l + A[i] % K + K) % K;
c[l]++;
ans += c[l] - 1;
}
return ans;
}
};
| 19.235294 | 46 | 0.425076 | Kresnt |
148559db6a70da2bc408c303d4be7d6dd2ce1227 | 1,334 | cpp | C++ | Lamia/src/Systems/Systems.cpp | Alorafae/Lamia | bf2dd1cf7427fae8728abbb6a718a5223ab68caa | [
"MIT"
] | null | null | null | Lamia/src/Systems/Systems.cpp | Alorafae/Lamia | bf2dd1cf7427fae8728abbb6a718a5223ab68caa | [
"MIT"
] | null | null | null | Lamia/src/Systems/Systems.cpp | Alorafae/Lamia | bf2dd1cf7427fae8728abbb6a718a5223ab68caa | [
"MIT"
] | null | null | null |
#include "Systems.h"
using namespace LamiaSystems;
static Systems* g_LamiaSystem;
LAMIA_RESULT LamiaSystems::LamiaSystemsInit(void)
{
// initialize the system itself
g_LamiaSystem = new Systems;
// initialize our sub systems file, audio, graphics, etc
bool ret = LamiaFileInit();
if (ret == false)
return LAMIA_E_AUDIO_SYS;
// this is setting our file system pointer lf in g_LamiaSystem
g_LamiaSystem->SetFileSystemPtr(LamiaFileGetSystem());
//-- end audio
ret = LamiaInputInit();
if (ret == false)
return LAMIA_E_INPUT_SYS;
g_LamiaSystem->SetInputSystemPtr(LamiaInputGetSystem());
return LAMIA_E_SUCCESS;
}
LAMIA_RESULT LamiaSystems::LamiaSystemsShutdown(void)
{
delete g_LamiaSystem;
return LAMIA_E_SUCCESS;
}
Systems* const LamiaSystems::LamiaSystem(void)
{
return g_LamiaSystem;
}
Systems::Systems()
{
}
Systems::~Systems()
{
}
LamiaFile* const Systems::FileSystem(void)
{
return LFileSys; // should no longer be null anymore
}
LamiaInput * const LamiaSystems::Systems::InputSystem(void)
{
return LInputSys;
}
void LamiaSystems::Systems::SetFileSystemPtr(LamiaFile * fileSys)
{
LFileSys = fileSys;
}
void LamiaSystems::Systems::SetInputSystemPtr(LamiaInput * inputSys)
{
LInputSys = inputSys;
}
| 18.788732 | 69 | 0.703898 | Alorafae |
14859d765d2a4c7ce6aafacedef25ab335c77686 | 13,531 | cpp | C++ | common/contrib/QSsh/src/sshcryptofacility.cpp | cbtek/ClockNGo | 4b23043a8b535059990e4eedb2c0f3a4fb079415 | [
"MIT"
] | null | null | null | common/contrib/QSsh/src/sshcryptofacility.cpp | cbtek/ClockNGo | 4b23043a8b535059990e4eedb2c0f3a4fb079415 | [
"MIT"
] | null | null | null | common/contrib/QSsh/src/sshcryptofacility.cpp | cbtek/ClockNGo | 4b23043a8b535059990e4eedb2c0f3a4fb079415 | [
"MIT"
] | null | null | null | /**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/
#include "sshcryptofacility_p.h"
#include "sshbotanconversions_p.h"
#include "sshcapabilities_p.h"
#include "sshexception_p.h"
#include "sshkeyexchange_p.h"
#include "sshkeypasswordretriever_p.h"
#include "sshpacket_p.h"
#include <botan/inc/botan.h>
#include <QDebug>
#include <QList>
#include <string>
using namespace Botan;
namespace QSsh {
namespace Internal {
SshAbstractCryptoFacility::SshAbstractCryptoFacility()
: m_cipherBlockSize(0), m_macLength(0)
{
}
SshAbstractCryptoFacility::~SshAbstractCryptoFacility() {}
void SshAbstractCryptoFacility::clearKeys()
{
m_cipherBlockSize = 0;
m_macLength = 0;
m_sessionId.clear();
m_pipe.reset(0);
m_hMac.reset(0);
}
void SshAbstractCryptoFacility::recreateKeys(const SshKeyExchange &kex)
{
checkInvariant();
if (m_sessionId.isEmpty())
m_sessionId = kex.h();
Algorithm_Factory &af = global_state().algorithm_factory();
const std::string &cryptAlgo = botanCryptAlgoName(cryptAlgoName(kex));
BlockCipher * const cipher = af.prototype_block_cipher(cryptAlgo)->clone();
m_cipherBlockSize = cipher->block_size();
const QByteArray ivData = generateHash(kex, ivChar(), m_cipherBlockSize);
const InitializationVector iv(convertByteArray(ivData), m_cipherBlockSize);
const quint32 keySize = cipher->key_spec().maximum_keylength();
const QByteArray cryptKeyData = generateHash(kex, keyChar(), keySize);
SymmetricKey cryptKey(convertByteArray(cryptKeyData), keySize);
Keyed_Filter * const cipherMode = makeCipherMode(cipher, new Null_Padding, iv, cryptKey);
m_pipe.reset(new Pipe(cipherMode));
m_macLength = botanHMacKeyLen(hMacAlgoName(kex));
const QByteArray hMacKeyData = generateHash(kex, macChar(), macLength());
SymmetricKey hMacKey(convertByteArray(hMacKeyData), macLength());
const HashFunction * const hMacProto
= af.prototype_hash_function(botanHMacAlgoName(hMacAlgoName(kex)));
m_hMac.reset(new HMAC(hMacProto->clone()));
m_hMac->set_key(hMacKey);
}
void SshAbstractCryptoFacility::convert(QByteArray &data, quint32 offset,
quint32 dataSize) const
{
Q_ASSERT(offset + dataSize <= static_cast<quint32>(data.size()));
checkInvariant();
// Session id empty => No key exchange has happened yet.
if (dataSize == 0 || m_sessionId.isEmpty())
return;
if (dataSize % cipherBlockSize() != 0) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid packet size");
}
m_pipe->process_msg(reinterpret_cast<const byte *>(data.constData()) + offset,
dataSize);
quint32 bytesRead = m_pipe->read(reinterpret_cast<byte *>(data.data()) + offset,
dataSize, m_pipe->message_count() - 1); // Can't use Pipe::LAST_MESSAGE because of a VC bug.
Q_ASSERT(bytesRead == dataSize);
}
QByteArray SshAbstractCryptoFacility::generateMac(const QByteArray &data,
quint32 dataSize) const
{
return m_sessionId.isEmpty()
? QByteArray()
: convertByteArray(m_hMac->process(reinterpret_cast<const byte *>(data.constData()),
dataSize));
}
QByteArray SshAbstractCryptoFacility::generateHash(const SshKeyExchange &kex,
char c, quint32 length)
{
const QByteArray &k = kex.k();
const QByteArray &h = kex.h();
QByteArray data(k);
data.append(h).append(c).append(m_sessionId);
SecureVector<byte> key
= kex.hash()->process(convertByteArray(data), data.size());
while (key.size() < length) {
SecureVector<byte> tmpKey;
tmpKey += SecureVector<byte>(convertByteArray(k), k.size());
tmpKey += SecureVector<byte>(convertByteArray(h), h.size());
tmpKey += key;
key += kex.hash()->process(tmpKey);
}
return QByteArray(reinterpret_cast<const char *>(key.begin()), length);
}
void SshAbstractCryptoFacility::checkInvariant() const
{
Q_ASSERT(m_sessionId.isEmpty() == !m_pipe);
}
const QByteArray SshEncryptionFacility::PrivKeyFileStartLineRsa("-----BEGIN RSA PRIVATE KEY-----");
const QByteArray SshEncryptionFacility::PrivKeyFileStartLineDsa("-----BEGIN DSA PRIVATE KEY-----");
const QByteArray SshEncryptionFacility::PrivKeyFileEndLineRsa("-----END RSA PRIVATE KEY-----");
const QByteArray SshEncryptionFacility::PrivKeyFileEndLineDsa("-----END DSA PRIVATE KEY-----");
QByteArray SshEncryptionFacility::cryptAlgoName(const SshKeyExchange &kex) const
{
return kex.encryptionAlgo();
}
QByteArray SshEncryptionFacility::hMacAlgoName(const SshKeyExchange &kex) const
{
return kex.hMacAlgoClientToServer();
}
Keyed_Filter *SshEncryptionFacility::makeCipherMode(BlockCipher *cipher,
BlockCipherModePaddingMethod *paddingMethod, const InitializationVector &iv,
const SymmetricKey &key)
{
return new CBC_Encryption(cipher, paddingMethod, key, iv);
}
void SshEncryptionFacility::encrypt(QByteArray &data) const
{
convert(data, 0, data.size());
}
void SshEncryptionFacility::createAuthenticationKey(const QByteArray &privKeyFileContents)
{
if (privKeyFileContents == m_cachedPrivKeyContents)
return;
#ifdef CREATOR_SSH_DEBUG
qDebug("%s: Key not cached, reading", Q_FUNC_INFO);
#endif
QList<BigInt> pubKeyParams;
QList<BigInt> allKeyParams;
QString error1;
QString error2;
if (!createAuthenticationKeyFromPKCS8(privKeyFileContents, pubKeyParams, allKeyParams, error1)
&& !createAuthenticationKeyFromOpenSSL(privKeyFileContents, pubKeyParams, allKeyParams,
error2)) {
#ifdef CREATOR_SSH_DEBUG
qDebug("%s: %s\n\t%s\n", Q_FUNC_INFO, qPrintable(error1), qPrintable(error2));
#endif
throw SshClientException(SshKeyFileError, SSH_TR("Decoding of private key file failed: "
"Format not understood."));
}
foreach (const BigInt &b, allKeyParams) {
if (b.is_zero()) {
throw SshClientException(SshKeyFileError,
SSH_TR("Decoding of private key file failed: Invalid zero parameter."));
}
}
m_authPubKeyBlob = AbstractSshPacket::encodeString(m_authKeyAlgoName);
foreach (const BigInt &b, pubKeyParams)
m_authPubKeyBlob += AbstractSshPacket::encodeMpInt(b);
m_cachedPrivKeyContents = privKeyFileContents;
}
bool SshEncryptionFacility::createAuthenticationKeyFromPKCS8(const QByteArray &privKeyFileContents,
QList<BigInt> &pubKeyParams, QList<BigInt> &allKeyParams, QString &error)
{
try {
Pipe pipe;
pipe.process_msg(convertByteArray(privKeyFileContents), privKeyFileContents.size());
Private_Key * const key = PKCS8::load_key(pipe, m_rng, SshKeyPasswordRetriever());
if (DSA_PrivateKey * const dsaKey = dynamic_cast<DSA_PrivateKey *>(key)) {
m_authKeyAlgoName = SshCapabilities::PubKeyDss;
m_authKey.reset(dsaKey);
pubKeyParams << dsaKey->group_p() << dsaKey->group_q()
<< dsaKey->group_g() << dsaKey->get_y();
allKeyParams << pubKeyParams << dsaKey->get_x();
} else if (RSA_PrivateKey * const rsaKey = dynamic_cast<RSA_PrivateKey *>(key)) {
m_authKeyAlgoName = SshCapabilities::PubKeyRsa;
m_authKey.reset(rsaKey);
pubKeyParams << rsaKey->get_e() << rsaKey->get_n();
allKeyParams << pubKeyParams << rsaKey->get_p() << rsaKey->get_q()
<< rsaKey->get_d();
} else {
qWarning("%s: Unexpected code flow, expected success or exception.", Q_FUNC_INFO);
return false;
}
} catch (const Botan::Exception &ex) {
error = QLatin1String(ex.what());
return false;
} catch (const Botan::Decoding_Error &ex) {
error = QLatin1String(ex.what());
return false;
}
return true;
}
bool SshEncryptionFacility::createAuthenticationKeyFromOpenSSL(const QByteArray &privKeyFileContents,
QList<BigInt> &pubKeyParams, QList<BigInt> &allKeyParams, QString &error)
{
try {
bool syntaxOk = true;
QList<QByteArray> lines = privKeyFileContents.split('\n');
while (lines.last().isEmpty())
lines.removeLast();
if (lines.count() < 3) {
syntaxOk = false;
} else if (lines.first() == PrivKeyFileStartLineRsa) {
if (lines.last() != PrivKeyFileEndLineRsa)
syntaxOk = false;
else
m_authKeyAlgoName = SshCapabilities::PubKeyRsa;
} else if (lines.first() == PrivKeyFileStartLineDsa) {
if (lines.last() != PrivKeyFileEndLineDsa)
syntaxOk = false;
else
m_authKeyAlgoName = SshCapabilities::PubKeyDss;
} else {
syntaxOk = false;
}
if (!syntaxOk) {
error = SSH_TR("Unexpected format.");
return false;
}
QByteArray privateKeyBlob;
for (int i = 1; i < lines.size() - 1; ++i)
privateKeyBlob += lines.at(i);
privateKeyBlob = QByteArray::fromBase64(privateKeyBlob);
BER_Decoder decoder(convertByteArray(privateKeyBlob), privateKeyBlob.size());
BER_Decoder sequence = decoder.start_cons(SEQUENCE);
size_t version;
sequence.decode (version);
if (version != 0) {
error = SSH_TR("Key encoding has version %1, expected 0.").arg(version);
return false;
}
if (m_authKeyAlgoName == SshCapabilities::PubKeyDss) {
BigInt p, q, g, y, x;
sequence.decode (p).decode (q).decode (g).decode (y).decode (x);
DSA_PrivateKey * const dsaKey = new DSA_PrivateKey(m_rng, DL_Group(p, q, g), x);
m_authKey.reset(dsaKey);
pubKeyParams << p << q << g << y;
allKeyParams << pubKeyParams << x;
} else {
BigInt p, q, e, d, n;
sequence.decode(n).decode(e).decode(d).decode(p).decode(q);
RSA_PrivateKey * const rsaKey = new RSA_PrivateKey(m_rng, p, q, e, d, n);
m_authKey.reset(rsaKey);
pubKeyParams << e << n;
allKeyParams << pubKeyParams << p << q << d;
}
sequence.discard_remaining();
sequence.verify_end();
} catch (const Botan::Exception &ex) {
error = QLatin1String(ex.what());
return false;
} catch (const Botan::Decoding_Error &ex) {
error = QLatin1String(ex.what());
return false;
}
return true;
}
QByteArray SshEncryptionFacility::authenticationAlgorithmName() const
{
Q_ASSERT(m_authKey);
return m_authKeyAlgoName;
}
QByteArray SshEncryptionFacility::authenticationKeySignature(const QByteArray &data) const
{
Q_ASSERT(m_authKey);
QScopedPointer<PK_Signer> signer(new PK_Signer(*m_authKey,
botanEmsaAlgoName(m_authKeyAlgoName)));
QByteArray dataToSign = AbstractSshPacket::encodeString(sessionId()) + data;
QByteArray signature
= convertByteArray(signer->sign_message(convertByteArray(dataToSign),
dataToSign.size(), m_rng));
return AbstractSshPacket::encodeString(m_authKeyAlgoName)
+ AbstractSshPacket::encodeString(signature);
}
QByteArray SshEncryptionFacility::getRandomNumbers(int count) const
{
QByteArray data;
data.resize(count);
m_rng.randomize(convertByteArray(data), count);
return data;
}
SshEncryptionFacility::~SshEncryptionFacility() {}
QByteArray SshDecryptionFacility::cryptAlgoName(const SshKeyExchange &kex) const
{
return kex.decryptionAlgo();
}
QByteArray SshDecryptionFacility::hMacAlgoName(const SshKeyExchange &kex) const
{
return kex.hMacAlgoServerToClient();
}
Keyed_Filter *SshDecryptionFacility::makeCipherMode(BlockCipher *cipher,
BlockCipherModePaddingMethod *paddingMethod, const InitializationVector &iv,
const SymmetricKey &key)
{
return new CBC_Decryption(cipher, paddingMethod, key, iv);
}
void SshDecryptionFacility::decrypt(QByteArray &data, quint32 offset,
quint32 dataSize) const
{
convert(data, offset, dataSize);
#ifdef CREATOR_SSH_DEBUG
qDebug("Decrypted data:");
const char * const start = data.constData() + offset;
const char * const end = start + dataSize;
for (const char *c = start; c < end; ++c)
qDebug() << "'" << *c << "' (0x" << (static_cast<int>(*c) & 0xff) << ")";
#endif
}
} // namespace Internal
} // namespace QSsh
| 35.421466 | 101 | 0.670313 | cbtek |
148619e5823c1dbced2f88975d7fe0f28e494288 | 3,002 | cpp | C++ | Frontend/GItems/Mini/RUBorderComponent.cpp | Gattic/gfxplusplus | f0c05a0f424fd65c8f7fd26ee0dee1802a033336 | [
"MIT"
] | 3 | 2020-02-12T23:22:45.000Z | 2020-02-19T01:03:07.000Z | Frontend/GItems/Mini/RUBorderComponent.cpp | MeeseeksLookAtMe/gfxplusplus | f0c05a0f424fd65c8f7fd26ee0dee1802a033336 | [
"MIT"
] | null | null | null | Frontend/GItems/Mini/RUBorderComponent.cpp | MeeseeksLookAtMe/gfxplusplus | f0c05a0f424fd65c8f7fd26ee0dee1802a033336 | [
"MIT"
] | null | null | null | // Copyright 2020 Robert Carneiro, Derek Meer, Matthew Tabak, Eric Lujan
//
// 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 "RUBorderComponent.h"
#include "../../Graphics/graphics.h"
#include "../GItem.h"
#include "../RUColors.h"
RUBorderComponent::RUBorderComponent()
{
borderEnabled = false;
borderWidth = 1;
setBorderColor(RUColors::DEFAULT_COLOR_BORDER);
}
RUBorderComponent::RUBorderComponent(int newWidth)
{
borderEnabled = true;
borderWidth = newWidth;
setBorderColor(RUColors::DEFAULT_COLOR_BORDER);
}
RUBorderComponent::RUBorderComponent(SDL_Color newBorderColor)
{
borderEnabled = true;
borderWidth = 1;
setBorderColor(newBorderColor);
}
RUBorderComponent::RUBorderComponent(int newWidth, SDL_Color newBorderColor)
{
borderEnabled = true;
borderWidth = newWidth;
setBorderColor(newBorderColor);
}
RUBorderComponent::~RUBorderComponent()
{
borderEnabled = false;
}
bool RUBorderComponent::getBorderEnabled() const
{
return borderEnabled;
}
SDL_Color RUBorderComponent::getBorderColor() const
{
return borderColor;
}
int RUBorderComponent::getBorderWidth() const
{
return borderWidth;
}
void RUBorderComponent::toggleBorder(bool newBorder)
{
borderEnabled = newBorder;
drawUpdate = true;
}
void RUBorderComponent::setBorderColor(SDL_Color newBorderColor)
{
borderColor = newBorderColor;
}
void RUBorderComponent::setBorderWidth(int newBorderWidth)
{
borderWidth = newBorderWidth;
}
void RUBorderComponent::updateBorderBackground(gfxpp* cGfx)
{
if (!borderEnabled)
return;
if (!((getWidth() > 0) && (getHeight() > 0)))
return;
for (int i = 0; i < borderWidth; ++i)
{
// draw the border
SDL_Rect borderRect;
borderRect.x = i;
borderRect.y = i;
borderRect.w = getWidth() - (borderWidth - 1);
borderRect.h = getHeight() - (borderWidth - 1);
SDL_SetRenderDrawColor(cGfx->getRenderer(), borderColor.r, borderColor.g, borderColor.b,
borderColor.a);
SDL_RenderDrawRect(cGfx->getRenderer(), &borderRect);
}
}
| 27.796296 | 100 | 0.758161 | Gattic |
1489b159b85c69900140ef57b2e9bac4b1010849 | 34,667 | cpp | C++ | ext/include/osgEarthDrivers/engine_osgterrain/OSGTileFactory.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthDrivers/engine_osgterrain/OSGTileFactory.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthDrivers/engine_osgterrain/OSGTileFactory.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth 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 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include "OSGTileFactory"
#include "TerrainNode"
#include "StreamingTerrainNode"
#include "FileLocationCallback"
#include "TransparentLayer"
#include <osgEarth/Map>
#include <osgEarth/HeightFieldUtils>
#include <osgEarth/Registry>
#include <osgEarth/ImageUtils>
#include <osgEarth/TileSource>
#include <osg/Image>
#include <osg/Notify>
#include <osg/PagedLOD>
#include <osg/ClusterCullingCallback>
#include <osg/CoordinateSystemNode>
#include <osgFX/MultiTextureControl>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgTerrain/Locator>
#include <osgTerrain/GeometryTechnique>
#include <OpenThreads/ReentrantMutex>
#include <sstream>
#include <stdlib.h>
using namespace OpenThreads;
using namespace osgEarth_engine_osgterrain;
using namespace osgEarth;
using namespace osgEarth::Drivers;
#define LC "[OSGTileFactory] "
/*****************************************************************************/
namespace
{
//TODO: get rid of this, and move it to the CustomTerrain CULL traversal....?????
struct PopulateStreamingTileDataCallback : public osg::NodeCallback
{
PopulateStreamingTileDataCallback( const MapFrame& mapf ) : _mapf(mapf) { }
void operator()( osg::Node* node, osg::NodeVisitor* nv )
{
if ( nv->getVisitorType() == osg::NodeVisitor::CULL_VISITOR )
{
if ( node->asGroup()->getNumChildren() > 0 )
{
StreamingTile* tile = static_cast<StreamingTile*>( node->asGroup()->getChild(0) );
tile->servicePendingImageRequests( _mapf, nv->getFrameStamp()->getFrameNumber() );
}
}
traverse( node, nv );
}
const MapFrame& _mapf;
};
}
/*****************************************************************************/
OSGTileFactory::OSGTileFactory(unsigned int engineId,
const MapFrame& cull_thread_mapf,
const OSGTerrainOptions& props ) :
osg::Referenced( true ),
_engineId( engineId ),
_cull_thread_mapf( cull_thread_mapf ),
_terrainOptions( props )
{
LoadingPolicy::Mode mode = _terrainOptions.loadingPolicy()->mode().value();
}
const OSGTerrainOptions&
OSGTileFactory::getTerrainOptions() const
{
return _terrainOptions;
}
std::string
OSGTileFactory::createURI( unsigned int id, const TileKey& key )
{
std::stringstream ss;
ss << key.str() << "." <<id<<".osgearth_osgterrain_tile";
std::string ssStr;
ssStr = ss.str();
return ssStr;
}
// Make a MatrixTransform suitable for use with a Locator object based on the given extents.
// Calling Locator::setTransformAsExtents doesn't work with OSG 2.6 due to the fact that the
// _inverse member isn't updated properly. Calling Locator::setTransform works correctly.
osg::Matrixd
OSGTileFactory::getTransformFromExtents(double minX, double minY, double maxX, double maxY) const
{
osg::Matrixd transform;
transform.set(
maxX-minX, 0.0, 0.0, 0.0,
0.0, maxY-minY, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
minX, minY, 0.0, 1.0);
return transform;
}
osg::Node*
OSGTileFactory::createSubTiles( const MapFrame& mapf, TerrainNode* terrain, const TileKey& key, bool populateLayers )
{
TileKey k0 = key.createChildKey(0);
TileKey k1 = key.createChildKey(1);
TileKey k2 = key.createChildKey(2);
TileKey k3 = key.createChildKey(3);
bool hasValidData = false;
bool validData;
bool fallback = false;
osg::ref_ptr<osg::Node> q0 = createTile( mapf, terrain, k0, populateLayers, true, fallback, validData);
if (!hasValidData && validData) hasValidData = true;
osg::ref_ptr<osg::Node> q1 = createTile( mapf, terrain, k1, populateLayers, true, fallback, validData );
if (!hasValidData && validData) hasValidData = true;
osg::ref_ptr<osg::Node> q2 = createTile( mapf, terrain, k2, populateLayers, true, fallback, validData );
if (!hasValidData && validData) hasValidData = true;
osg::ref_ptr<osg::Node> q3 = createTile( mapf, terrain, k3, populateLayers, true, fallback, validData );
if (!hasValidData && validData) hasValidData = true;
if (!hasValidData)
{
OE_DEBUG << LC << "Couldn't create any quadrants for " << key.str() << " time to stop subdividing!" << std::endl;
return NULL;
}
osg::Group* tile_parent = new osg::Group();
fallback = true;
//Fallback on tiles if we couldn't create any
if (!q0.valid())
{
q0 = createTile( mapf, terrain, k0, populateLayers, true, fallback, validData);
}
if (!q1.valid())
{
q1 = createTile( mapf, terrain, k1, populateLayers, true, fallback, validData);
}
if (!q2.valid())
{
q2 = createTile( mapf, terrain, k2, populateLayers, true, fallback, validData);
}
if (!q3.valid())
{
q3 = createTile( mapf, terrain, k3, populateLayers, true, fallback, validData);
}
tile_parent->addChild( q0.get() );
tile_parent->addChild( q1.get() );
tile_parent->addChild( q2.get() );
tile_parent->addChild( q3.get() );
return tile_parent;
}
bool
OSGTileFactory::createValidGeoImage(ImageLayer* layer,
const TileKey& key,
GeoImage& out_image,
TileKey& out_actualTileKey,
ProgressCallback* progress)
{
//TODO: Redo this to just grab images from the parent TerrainTiles
//Try to create the image with the given key
out_actualTileKey = key;
while (out_actualTileKey.valid())
{
if ( layer->isKeyValid(out_actualTileKey) )
{
out_image = layer->createImage( out_actualTileKey, progress );
if ( out_image.valid() )
{
return true;
}
}
out_actualTileKey = out_actualTileKey.createParentKey();
}
return false;
}
bool
OSGTileFactory::hasMoreLevels( Map* map, const TileKey& key )
{
//Threading::ScopedReadLock lock( map->getMapDataMutex() );
bool more_levels = false;
ImageLayerVector imageLayers;
map->getImageLayers( imageLayers );
for ( ImageLayerVector::const_iterator i = imageLayers.begin(); i != imageLayers.end(); i++ )
{
const ImageLayerOptions& opt = i->get()->getImageLayerOptions();
if ( !opt.maxLevel().isSet() || key.getLevelOfDetail() < (unsigned int)*opt.maxLevel() )
{
more_levels = true;
break;
}
}
if ( !more_levels )
{
ElevationLayerVector elevLayers;
map->getElevationLayers( elevLayers );
for( ElevationLayerVector::const_iterator j = elevLayers.begin(); j != elevLayers.end(); j++ )
{
const ElevationLayerOptions& opt = j->get()->getElevationLayerOptions();
if ( !opt.maxLevel().isSet() || key.getLevelOfDetail() < (unsigned int)*opt.maxLevel() )
//if ( !j->get()->maxLevel().isSet() || key.getLevelOfDetail() < j->get()->maxLevel().get() )
{
more_levels = true;
break;
}
}
}
return more_levels;
}
osg::HeightField*
OSGTileFactory::createEmptyHeightField( const TileKey& key, unsigned numCols, unsigned numRows )
{
return HeightFieldUtils::createReferenceHeightField( key.getExtent(), numCols, numRows );
}
void
OSGTileFactory::addPlaceholderImageLayers(Tile* tile, Tile* ancestorTile )
{
if ( !ancestorTile )
{
//OE_NOTICE << "No ancestorTile for key " << key.str() << std::endl;
return;
}
// Now if we have a valid ancestor tile, go through and make a temporary tile consisting only of
// layers that exist in the new map layer image list as well.
//int layer = 0;
ColorLayersByUID colorLayers;
ancestorTile->getCustomColorLayers( colorLayers );
tile->setCustomColorLayers( colorLayers );
}
void
OSGTileFactory::addPlaceholderHeightfieldLayer(StreamingTile* tile,
StreamingTile* ancestorTile,
GeoLocator* defaultLocator,
const TileKey& key,
const TileKey& ancestorKey)
{
osgTerrain::HeightFieldLayer* newHFLayer = 0L;
if ( ancestorTile && ancestorKey.valid() )
{
osg::ref_ptr<osgTerrain::HeightFieldLayer> ancestorLayer;
{
Threading::ScopedReadLock sharedLock( ancestorTile->getTileLayersMutex() );
ancestorLayer = dynamic_cast<osgTerrain::HeightFieldLayer*>(ancestorTile->getElevationLayer());
}
if ( ancestorLayer.valid() )
{
osg::ref_ptr<osg::HeightField> ancestorHF = ancestorLayer->getHeightField();
if ( ancestorHF.valid() )
{
osg::HeightField* newHF = HeightFieldUtils::createSubSample(
ancestorHF.get(),
ancestorKey.getExtent(),
key.getExtent());
newHFLayer = new osgTerrain::HeightFieldLayer( newHF );
newHFLayer->setLocator( defaultLocator );
// lock to set the elevation layerdata:
{
Threading::ScopedWriteLock exclusiveLock( tile->getTileLayersMutex() );
tile->setElevationLayer( newHFLayer );
tile->setElevationLOD( ancestorTile->getElevationLOD() );
}
}
}
}
// lock the tile to write the elevation data.
{
Threading::ScopedWriteLock exclusiveLock( tile->getTileLayersMutex() );
if ( !newHFLayer )
{
newHFLayer = new osgTerrain::HeightFieldLayer();
newHFLayer->setHeightField( createEmptyHeightField( key, 8, 8 ) );
newHFLayer->setLocator( defaultLocator );
tile->setElevationLOD( -1 );
}
if ( newHFLayer )
{
tile->setElevationLayer( newHFLayer );
}
}
}
osgTerrain::HeightFieldLayer*
OSGTileFactory::createPlaceholderHeightfieldLayer(osg::HeightField* ancestorHF,
const TileKey& ancestorKey,
const TileKey& key,
GeoLocator* keyLocator )
{
osgTerrain::HeightFieldLayer* hfLayer = NULL;
osg::HeightField* newHF = HeightFieldUtils::createSubSample(
ancestorHF,
ancestorKey.getExtent(),
key.getExtent() );
newHF->setSkirtHeight( ancestorHF->getSkirtHeight() / 2.0 );
hfLayer = new osgTerrain::HeightFieldLayer( newHF );
hfLayer->setLocator( keyLocator );
return hfLayer;
}
osg::Node*
OSGTileFactory::createTile(const MapFrame& mapf,
TerrainNode* terrain,
const TileKey& key,
bool populateLayers,
bool wrapInPagedLOD,
bool fallback,
bool& out_validData )
{
if ( populateLayers )
{
return createPopulatedTile( mapf, terrain, key, wrapInPagedLOD, fallback, out_validData);
}
else
{
//Placeholders always contain valid data
out_validData = true;
return createPlaceholderTile(
mapf,
static_cast<StreamingTerrainNode*>(terrain),
key );
}
}
osg::Node*
OSGTileFactory::createPlaceholderTile(const MapFrame& mapf,
StreamingTerrainNode* terrain,
const TileKey& key )
{
// Start out by finding the nearest registered ancestor tile, since the placeholder is
// going to be based on inherited data. Note- the ancestor may not be the immediate
// parent, b/c the parent may or may not be in the scene graph.
TileKey ancestorKey = key.createParentKey();
osg::ref_ptr<StreamingTile> ancestorTile;
while( !ancestorTile.valid() && ancestorKey.valid() )
{
terrain->getTile( ancestorKey.getTileId(), ancestorTile );
if ( !ancestorTile.valid() )
ancestorKey = ancestorKey.createParentKey();
}
if ( !ancestorTile.valid() )
{
OE_WARN << LC << "cannot find ancestor tile for (" << key.str() << ")" <<std::endl;
return 0L;
}
OE_DEBUG << LC << "Creating placeholder for " << key.str() << std::endl;
const MapInfo& mapInfo = mapf.getMapInfo();
bool hasElevation = mapf.elevationLayers().size() > 0;
// Build a "placeholder" tile.
double xmin, ymin, xmax, ymax;
key.getExtent().getBounds( xmin, ymin, xmax, ymax );
// A locator will place the tile on the globe:
osg::ref_ptr<GeoLocator> locator = GeoLocator::createForKey( key, mapInfo );
// The empty tile:
StreamingTile* tile = new StreamingTile( key, locator.get(), terrain->getQuickReleaseGLObjects() );
tile->setTerrainTechnique( terrain->cloneTechnique() );
tile->setVerticalScale( _terrainOptions.verticalScale().value() );
tile->setDataVariance( osg::Object::DYNAMIC );
//tile->setLocator( locator.get() );
// Generate placeholder imagery and elevation layers. These "inherit" data from an
// ancestor tile.
{
//Threading::ScopedReadLock parentLock( ancestorTile->getTileLayersMutex() );
addPlaceholderImageLayers ( tile, ancestorTile.get() );
addPlaceholderHeightfieldLayer( tile, ancestorTile.get(), locator.get(), key, ancestorKey );
}
// calculate the switching distances:
osg::BoundingSphere bs = tile->getBound();
double max_range = 1e10;
double radius = bs.radius();
double min_range = radius * _terrainOptions.minTileRangeFactor().get();
// Set the skirt height of the heightfield
osgTerrain::HeightFieldLayer* hfLayer = static_cast<osgTerrain::HeightFieldLayer*>(tile->getElevationLayer());
if (!hfLayer)
{
OE_WARN << LC << "Warning: Couldn't get hfLayer for " << key.str() << std::endl;
}
hfLayer->getHeightField()->setSkirtHeight(radius * _terrainOptions.heightFieldSkirtRatio().get() );
// In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees
if ( mapInfo.isPlateCarre() && hfLayer->getHeightField() )
HeightFieldUtils::scaleHeightFieldToDegrees( hfLayer->getHeightField() );
bool markTileLoaded = false;
if ( _terrainOptions.loadingPolicy()->mode().get() != LoadingPolicy::MODE_STANDARD )
{
markTileLoaded = true;
tile->setHasElevationHint( hasElevation );
}
// install a tile switcher:
tile->attachToTerrain( terrain );
//tile->setTerrain( terrain );
//terrain->registerTile( tile );
osg::Node* result = 0L;
// create a PLOD so we can keep subdividing:
osg::PagedLOD* plod = new osg::PagedLOD();
plod->setCenter( bs.center() );
plod->addChild( tile, min_range, max_range );
if (key.getLevelOfDetail() < getTerrainOptions().maxLOD().get())
{
plod->setFileName( 1, createURI( _engineId, key ) ); //map->getId(), key ) );
plod->setRange( 1, 0.0, min_range );
}
else
{
plod->setRange( 0, 0, FLT_MAX );
}
#if 0 //USE_FILELOCATIONCALLBACK
osgDB::Options* options = Registry::instance()->cloneOrCreateOptions();
options->setFileLocationCallback( new FileLocationCallback);
plod->setDatabaseOptions( options );
#endif
result = plod;
// Install a callback that will load the actual tile data via the pager.
result->addCullCallback( new PopulateStreamingTileDataCallback( _cull_thread_mapf ) );
// Install a cluster culler (FIXME for cube mode)
//bool isCube = map->getMapOptions().coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE;
if ( mapInfo.isGeocentric() && !mapInfo.isCube() )
{
osg::ClusterCullingCallback* ccc = createClusterCullingCallback( tile, locator->getEllipsoidModel() );
result->addCullCallback( ccc );
}
return result;
}
namespace
{
struct GeoImageData
{
GeoImageData() : _layerUID(-1) , _imageTileKey(0,0,0,0L) { }
GeoImage _image;
UID _layerUID;
TileKey _imageTileKey;
};
}
osg::Node*
OSGTileFactory::createPopulatedTile(const MapFrame& mapf,
TerrainNode* terrain,
const TileKey& key,
bool wrapInPagedLOD,
bool fallback,
bool& validData )
{
const MapInfo& mapInfo = mapf.getMapInfo();
bool isPlateCarre = !mapInfo.isGeocentric() && mapInfo.isGeographicSRS();
typedef std::vector<GeoImageData> GeoImageDataVector;
GeoImageDataVector image_tiles;
// Collect the image layers
bool empty_map = mapf.imageLayers().size() == 0 && mapf.elevationLayers().size() == 0;
// Create the images for the tile
for( ImageLayerVector::const_iterator i = mapf.imageLayers().begin(); i != mapf.imageLayers().end(); ++i )
{
ImageLayer* layer = i->get();
GeoImageData imageData;
// Only try to create images if the key is valid
if ( layer->isKeyValid( key ) )
{
imageData._image = layer->createImage( key );
imageData._layerUID = layer->getUID();
imageData._imageTileKey = key;
}
// always push images, even it they are empty, so that the image_tiles vector is one-to-one
// with the imageLayers() vector.
image_tiles.push_back( imageData );
}
bool hasElevation = false;
//Create the heightfield for the tile
osg::ref_ptr<osg::HeightField> hf;
if ( mapf.elevationLayers().size() > 0 )
{
mapf.getHeightField( key, false, hf, 0L);
}
//If we are on the first LOD and we couldn't get a heightfield tile, just create an empty one. Otherwise you can run into the situation
//where you could have an inset heightfield on one hemisphere and the whole other hemisphere won't show up.
if ( mapInfo.isGeocentric() && key.getLevelOfDetail() <= 1 && !hf.valid())
{
hf = createEmptyHeightField( key );
}
hasElevation = hf.valid();
//Determine if we've created any images
unsigned int numValidImages = 0;
for (unsigned int i = 0; i < image_tiles.size(); ++i)
{
if (image_tiles[i]._image.valid()) numValidImages++;
}
//If we couldn't create any imagery or heightfields, bail out
if (!hf.valid() && (numValidImages == 0) && !empty_map)
{
OE_DEBUG << LC << "Could not create any imagery or heightfields for " << key.str() <<". Not building tile" << std::endl;
validData = false;
//If we're not asked to fallback on previous LOD's and we have no data, return NULL
if (!fallback)
{
return NULL;
}
}
else
{
validData = true;
}
//Try to interpolate any missing image layers from parent tiles
for (unsigned int i = 0; i < mapf.imageLayers().size(); i++ )
{
if (!image_tiles[i]._image.valid())
{
if (mapf.getImageLayerAt(i)->isKeyValid(key))
{
//If the key was valid and we have no image, then something possibly went wrong with the image creation such as a server being busy.
createValidGeoImage(mapf.getImageLayerAt(i), key, image_tiles[i]._image, image_tiles[i]._imageTileKey);
}
//If we still couldn't create an image, either something is really wrong or the key wasn't valid, so just create a transparent placeholder image
if (!image_tiles[i]._image.valid())
{
//If the image is not valid, create an empty texture as a placeholder
image_tiles[i]._image = GeoImage(ImageUtils::createEmptyImage(), key.getExtent());
image_tiles[i]._imageTileKey = key;
}
}
}
//Fill in missing heightfield information from parent tiles
if (!hf.valid())
{
//We have no heightfield sources,
if ( mapf.elevationLayers().size() == 0 )
{
hf = createEmptyHeightField( key );
}
else
{
//Try to get a heightfield again, but this time fallback on parent tiles
if ( mapf.getHeightField( key, true, hf, 0L ) )
{
hasElevation = true;
}
else
{
//We couldn't get any heightfield, so just create an empty one.
hf = createEmptyHeightField( key );
}
}
}
// In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees
if ( isPlateCarre )
{
HeightFieldUtils::scaleHeightFieldToDegrees( hf.get() );
}
osg::ref_ptr<GeoLocator> locator = GeoLocator::createForKey( key, mapInfo );
osgTerrain::HeightFieldLayer* hf_layer = new osgTerrain::HeightFieldLayer();
hf_layer->setLocator( locator.get() );
hf_layer->setHeightField( hf.get() );
bool isStreaming =
_terrainOptions.loadingPolicy()->mode() == LoadingPolicy::MODE_SEQUENTIAL ||
_terrainOptions.loadingPolicy()->mode() == LoadingPolicy::MODE_PREEMPTIVE;
Tile* tile = terrain->createTile( key, locator.get() );
tile->setTerrainTechnique( terrain->cloneTechnique() );
tile->setVerticalScale( _terrainOptions.verticalScale().value() );
//tile->setLocator( locator.get() );
tile->setElevationLayer( hf_layer );
//tile->setRequiresNormals( true );
tile->setDataVariance(osg::Object::DYNAMIC);
//Assign the terrain system to the TerrainTile.
//It is very important the terrain system is set while the MapConfig's sourceMutex is locked.
//This registers the terrain tile so that adding/removing layers are always in sync. If you don't do this
//you can end up with a situation where the database pager is waiting to merge a tile, then a layer is added, then
//the tile is finally merged and is out of sync.
double min_units_per_pixel = DBL_MAX;
#if 0
// create contour layer:
if (map->getContourTransferFunction() != NULL)
{
osgTerrain::ContourLayer* contourLayer(new osgTerrain::ContourLayer(map->getContourTransferFunction()));
contourLayer->setMagFilter(_terrainOptions.getContourMagFilter().value());
contourLayer->setMinFilter(_terrainOptions.getContourMinFilter().value());
tile->setCustomColorLayer(layer,contourLayer); //TODO: need layerUID, not layer index here -GW
++layer;
}
#endif
for (unsigned int i = 0; i < image_tiles.size(); ++i)
{
if (image_tiles[i]._image.valid())
{
const GeoImage& geo_image = image_tiles[i]._image;
double img_xmin, img_ymin, img_xmax, img_ymax;
geo_image.getExtent().getBounds( img_xmin, img_ymin, img_xmax, img_ymax );
//Specify a new locator for the color with the coordinates of the TileKey that was actually used to create the image
osg::ref_ptr<GeoLocator> img_locator = key.getProfile()->getSRS()->createLocator(
img_xmin, img_ymin, img_xmax, img_ymax,
isPlateCarre );
if ( mapInfo.isGeocentric() )
img_locator->setCoordinateSystemType( osgTerrain::Locator::GEOCENTRIC );
tile->setCustomColorLayer( CustomColorLayer(
mapf.getImageLayerAt(i),
geo_image.getImage(),
img_locator.get(),
key.getLevelOfDetail(),
key) );
double upp = geo_image.getUnitsPerPixel();
// Scale the units per pixel to degrees if the image is mercator (and the key is geo)
if ( geo_image.getSRS()->isMercator() && key.getExtent().getSRS()->isGeographic() )
upp *= 1.0f/111319.0f;
min_units_per_pixel = osg::minimum(upp, min_units_per_pixel);
}
}
osg::BoundingSphere bs = tile->getBound();
double maxRange = 1e10;
double radius = bs.radius();
#if 0
//Compute the min range based on the actual bounds of the tile. This can break down if you have very high resolution
//data with elevation variations and you can run out of memory b/c the elevation change is greater than the actual size of the tile so you end up
//inifinitely subdividing (or at least until you run out of data or memory)
double minRange = bs.radius() * _terrainOptions.minTileRangeFactor().value();
#else
//double origMinRange = bs.radius() * _options.minTileRangeFactor().value();
//Compute the min range based on the 2D size of the tile
GeoExtent extent = tile->getKey().getExtent();
GeoPoint lowerLeft(extent.getSRS(), extent.xMin(), extent.yMin(), 0.0, ALTMODE_ABSOLUTE);
GeoPoint upperRight(extent.getSRS(), extent.xMax(), extent.yMax(), 0.0, ALTMODE_ABSOLUTE);
osg::Vec3d ll, ur;
lowerLeft.toWorld( ll );
upperRight.toWorld( ur );
double minRange = (ur - ll).length() / 2.0 * _terrainOptions.minTileRangeFactor().value();
#endif
// a skirt hides cracks when transitioning between LODs:
hf->setSkirtHeight(radius * _terrainOptions.heightFieldSkirtRatio().get() );
// for now, cluster culling does not work for CUBE rendering
//bool isCube = mapInfo.isCube(); //map->getMapOptions().coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE;
if ( mapInfo.isGeocentric() && !mapInfo.isCube() )
{
//TODO: Work on cluster culling computation for cube faces
osg::ClusterCullingCallback* ccc = createClusterCullingCallback(tile, locator->getEllipsoidModel() );
tile->setCullCallback( ccc );
}
// Wait until now, when the tile is fully baked, to assign the terrain to the tile.
// Placeholder tiles might try to locate this tile as an ancestor, and access its layers
// and locators...so they must be intact before making this tile available via setTerrain.
//
// If there's already a placeholder tile registered, this will be ignored. If there isn't,
// this will register the new tile.
tile->attachToTerrain( terrain );
//tile->setTerrain( terrain );
//terrain->registerTile( tile );
if ( isStreaming && key.getLevelOfDetail() > 0 )
{
static_cast<StreamingTile*>(tile)->setHasElevationHint( hasElevation );
}
osg::Node* result = 0L;
if (wrapInPagedLOD)
{
// create a PLOD so we can keep subdividing:
osg::PagedLOD* plod = new osg::PagedLOD();
plod->setCenter( bs.center() );
plod->addChild( tile, minRange, maxRange );
std::string filename = createURI( _engineId, key ); //map->getId(), key );
//Only add the next tile if it hasn't been blacklisted
bool isBlacklisted = osgEarth::Registry::instance()->isBlacklisted( filename );
if (!isBlacklisted && key.getLevelOfDetail() < (unsigned int)getTerrainOptions().maxLOD().value() && validData )
{
plod->setFileName( 1, filename );
plod->setRange( 1, 0.0, minRange );
}
else
{
plod->setRange( 0, 0, FLT_MAX );
}
#if USE_FILELOCATIONCALLBACK
osgDB::Options* options = Registry::instance()->cloneOrCreateOptions();
options->setFileLocationCallback( new FileLocationCallback() );
plod->setDatabaseOptions( options );
#endif
result = plod;
if ( isStreaming )
result->addCullCallback( new PopulateStreamingTileDataCallback( _cull_thread_mapf ) );
}
else
{
result = tile;
}
return result;
}
CustomColorLayerRef*
OSGTileFactory::createImageLayer(const MapInfo& mapInfo,
ImageLayer* layer,
const TileKey& key,
ProgressCallback* progress)
{
if ( !layer )
return 0L;
GeoImage geoImage;
//If the key is valid, try to get the image from the MapLayer
bool keyValid = layer->isKeyValid( key );
if ( keyValid )
{
geoImage = layer->createImage(key, progress);
}
else
{
//If the key is not valid, simply make a transparent tile
geoImage = GeoImage(ImageUtils::createEmptyImage(), key.getExtent());
}
if (geoImage.valid())
{
osg::ref_ptr<GeoLocator> imgLocator = GeoLocator::createForKey( key, mapInfo );
if ( mapInfo.isGeocentric() )
imgLocator->setCoordinateSystemType( osgTerrain::Locator::GEOCENTRIC );
return new CustomColorLayerRef( CustomColorLayer(
layer,
geoImage.getImage(),
imgLocator.get(),
key.getLevelOfDetail(),
key) );
}
return NULL;
}
osgTerrain::HeightFieldLayer*
OSGTileFactory::createHeightFieldLayer( const MapFrame& mapf, const TileKey& key, bool exactOnly )
{
const MapInfo& mapInfo = mapf.getMapInfo();
bool isPlateCarre = !mapInfo.isGeocentric() && mapInfo.isGeographicSRS();
// try to create a heightfield at native res:
osg::ref_ptr<osg::HeightField> hf;
if ( !mapf.getHeightField( key, !exactOnly, hf, 0L ) )
{
if ( exactOnly )
return NULL;
else
hf = createEmptyHeightField( key );
}
// In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees
if ( isPlateCarre )
{
HeightFieldUtils::scaleHeightFieldToDegrees( hf.get() );
}
osgTerrain::HeightFieldLayer* hfLayer = new osgTerrain::HeightFieldLayer( hf.get() );
GeoLocator* locator = GeoLocator::createForKey( key, mapInfo );
hfLayer->setLocator( locator );
return hfLayer;
}
osg::ClusterCullingCallback*
OSGTileFactory::createClusterCullingCallback(Tile* tile, osg::EllipsoidModel* et)
{
//This code is a very slightly modified version of the DestinationTile::createClusterCullingCallback in VirtualPlanetBuilder.
osg::HeightField* grid = ((osgTerrain::HeightFieldLayer*)tile->getElevationLayer())->getHeightField();
if (!grid) return 0;
float verticalScale = 1.0f;
Tile* customTile = dynamic_cast<Tile*>(tile);
if (customTile)
{
verticalScale = customTile->getVerticalScale();
}
double globe_radius = et ? et->getRadiusPolar() : 1.0;
unsigned int numColumns = grid->getNumColumns();
unsigned int numRows = grid->getNumRows();
double midLong = grid->getOrigin().x()+grid->getXInterval()*((double)(numColumns-1))*0.5;
double midLat = grid->getOrigin().y()+grid->getYInterval()*((double)(numRows-1))*0.5;
double midZ = grid->getOrigin().z();
double midX,midY;
et->convertLatLongHeightToXYZ(osg::DegreesToRadians(midLat),osg::DegreesToRadians(midLong),midZ, midX,midY,midZ);
osg::Vec3 center_position(midX,midY,midZ);
osg::Vec3 center_normal(midX,midY,midZ);
center_normal.normalize();
osg::Vec3 transformed_center_normal = center_normal;
unsigned int r,c;
// populate the vertex/normal/texcoord arrays from the grid.
double orig_X = grid->getOrigin().x();
double delta_X = grid->getXInterval();
double orig_Y = grid->getOrigin().y();
double delta_Y = grid->getYInterval();
double orig_Z = grid->getOrigin().z();
float min_dot_product = 1.0f;
float max_cluster_culling_height = 0.0f;
float max_cluster_culling_radius = 0.0f;
for(r=0;r<numRows;++r)
{
for(c=0;c<numColumns;++c)
{
double X = orig_X + delta_X*(double)c;
double Y = orig_Y + delta_Y*(double)r;
double Z = orig_Z + grid->getHeight(c,r) * verticalScale;
double height = Z;
et->convertLatLongHeightToXYZ(
osg::DegreesToRadians(Y), osg::DegreesToRadians(X), Z,
X, Y, Z);
osg::Vec3d v(X,Y,Z);
osg::Vec3 dv = v - center_position;
double d = sqrt(dv.x()*dv.x() + dv.y()*dv.y() + dv.z()*dv.z());
double theta = acos( globe_radius/ (globe_radius + fabs(height)) );
double phi = 2.0 * asin (d*0.5/globe_radius); // d/globe_radius;
double beta = theta+phi;
double cutoff = osg::PI_2 - 0.1;
//log(osg::INFO,"theta="<<theta<<"\tphi="<<phi<<" beta "<<beta);
if (phi<cutoff && beta<cutoff)
{
float local_dot_product = -sin(theta + phi);
float local_m = globe_radius*( 1.0/ cos(theta+phi) - 1.0);
float local_radius = static_cast<float>(globe_radius * tan(beta)); // beta*globe_radius;
min_dot_product = osg::minimum(min_dot_product, local_dot_product);
max_cluster_culling_height = osg::maximum(max_cluster_culling_height,local_m);
max_cluster_culling_radius = osg::maximum(max_cluster_culling_radius,local_radius);
}
else
{
//log(osg::INFO,"Turning off cluster culling for wrap around tile.");
return 0;
}
}
}
osg::ClusterCullingCallback* ccc = new osg::ClusterCullingCallback;
ccc->set(center_position + transformed_center_normal*max_cluster_culling_height ,
transformed_center_normal,
min_dot_product,
max_cluster_culling_radius);
return ccc;
}
| 35.739175 | 156 | 0.615484 | energonQuest |
148a93b4de5d6cd5f069be01687639c56d3461d9 | 6,176 | hpp | C++ | osc-daemon/datainjest/jsonparser.hpp | oranellis/AeroRTEP | 53f36642ab62702b68b60105045c4c5ed1e0933b | [
"MIT"
] | 1 | 2022-01-26T07:38:19.000Z | 2022-01-26T07:38:19.000Z | osc-daemon/datainjest/jsonparser.hpp | oranellis/AeroRTEP | 53f36642ab62702b68b60105045c4c5ed1e0933b | [
"MIT"
] | 4 | 2022-01-26T07:32:32.000Z | 2022-02-21T22:08:53.000Z | osc-daemon/datainjest/jsonparser.hpp | oranellis/openSatCon | 53f36642ab62702b68b60105045c4c5ed1e0933b | [
"MIT"
] | null | null | null | #ifndef JSONPARSER_H
#define JSONPARSER_H
#include <iostream>
#include <list>
#include <vector>
#include <fstream>
#include "../../includes/json.hpp"
#include "../components/component.hpp"
#include "../components/fueltank.hpp"
#include "../components/actuators/thruster.hpp"
#include "../components/actuators/rotator.hpp"
#include "../osctypes.hpp"
using namespace std;
using json = nlohmann::json;
namespace osc {
/** \mainpage openSatCon's project documentation */
/** \struct craftconfig
\brief craft configuration
craftconfiguration type containing components, fueltanks, thrusters and rotators
*/
struct craftconfig {
std::map<std::string, component> components;
std::map<std::string, fueltank> fueltanks;
std::map<std::string, thruster> thrusters;
std::map<std::string, rotator> rotators;
bool populated() {
if (components.empty()) return false;
else return true;
}
};
/** \parseJson(jsonPath)
parses the json file from the path and produces a craft config object with mapped
components
@param[in] jsonPath path to json file
*/
inline craftconfig parseJson(std::string jsonPath) {
// std::cout << "start"; // debug
// map<string, std::list<double> > Components;
//json j = json::parse(jsonPath);
std::ifstream ifs(jsonPath);
json j = json::parse(ifs);
craftconfig returnConfig;
//parse and map mass components
for(int i = 0; i < j["MassComponentNo"]; i++)
{
double mass = j["MassComponents"][std::to_string(i)]["mass"];
momentofinertia moi;
position pos;
moi.Ixx = j["MassComponents"][std::to_string(i)]["moi"][0u];
moi.Iyy = j["MassComponents"][std::to_string(i)]["moi"][1u];
moi.Izz = j["MassComponents"][std::to_string(i)]["moi"][2u];
pos.x = j["MassComponents"][std::to_string(i)]["position"][0u];
pos.y = j["MassComponents"][std::to_string(i)]["position"][1u];
pos.z = j["MassComponents"][std::to_string(i)]["position"][2u];
powermodel power;
power.off = j["MassComponents"][std::to_string(i)]["powermodel"][0u];
power.idle = j["MassComponents"][std::to_string(i)]["powermodel"][1u];
power.use = j["MassComponents"][std::to_string(i)]["powermodel"][2u];
power.max = j["MassComponents"][std::to_string(i)]["powermodel"][3u];
quaternion rot;
component massComponent(mass, moi, pos, rot, power);
std::string key = j["MassComponents"][std::to_string(i)]["key"];
returnConfig.components.insert(std::pair<std::string, component>(key, massComponent));
}
// parse and map thruster components
for(int i = 0; i < j["ThrusterComponentNo"]; i++)
{
double maxT = j["ThrusterComponents"][std::to_string(i)]["maxThrust"];
double mTFrac = j["ThrusterComponents"][std::to_string(i)]["minThrustFraction"];
double tFrac = j["ThrusterComponents"][std::to_string(i)]["thrustFraction"];
double spImpulse = j["ThrusterComponents"][std::to_string(i)]["specificImpulse"];
bool attitudeControl;
if (j["ThrusterComponents"][std::to_string(i)]["attitudeControl"] == 0) {
attitudeControl = false;
} else {
attitudeControl = true;
}
std::array<double, 3> tAxis;
tAxis[0] = j["ThrusterComponents"][std::to_string(i)]["thrustAxis"][0u];
tAxis[1] = j["ThrusterComponents"][std::to_string(i)]["thrustAxis"][1u];
tAxis[2] = j["ThrusterComponents"][std::to_string(i)]["thrustAxis"][2u];
position tCenter;
tCenter.x = j["ThrusterComponents"][std::to_string(i)]["thrustCenter"][0u];
tCenter.y = j["ThrusterComponents"][std::to_string(i)]["thrustCenter"][1u];
tCenter.z = j["ThrusterComponents"][std::to_string(i)]["thrustCenter"][2u];
thruster ThrusterComponent(maxT, mTFrac, tFrac, spImpulse, attitudeControl, tAxis, tCenter);
std::string key = j["ThrusterComponents"][std::to_string(i)]["key"];
returnConfig.thrusters.insert (std::pair<std::string, thruster>(key, ThrusterComponent));
}
// parse and map fuel tanks
for(int i = 0; i < j["FuelTankNo"]; i++)
{
double fuelmass = j["FuelTanks"][std::to_string(i)]["fuelMass"];
double fuelcap = j["FuelTanks"][std::to_string(i)]["fuelCapacity"];
std::string fueltype = j["FuelTanks"][std::to_string(i)]["fuelType"];
position pos;
pos.x = j["FuelTanks"][std::to_string(i)]["position"][0u];
pos.y = j["FuelTanks"][std::to_string(i)]["position"][1u];
pos.z = j["FuelTanks"][std::to_string(i)]["position"][2u];
fueltank FuelTank(fueltype, fuelmass, fuelcap, pos);
std::string key = j["FuelTanks"][std::to_string(i)]["key"];
returnConfig.fueltanks.insert (std::pair<std::string, fueltank>(key, FuelTank));
}
// // parse and map rotators
for(int i = 0; i < j["RotatorNo"]; i++)
{
double mDipole = j["Rotators"][std::to_string(i)]["maxDipoleMoment"];
double torque = j["Rotators"][std::to_string(i)]["torque"];
double storedMomentum = j["Rotators"][std::to_string(i)]["storedMomentum"];
double rotSpeed = j["Rotators"][std::to_string(i)]["rotationSpeed"];
momentofinertia moi;
moi.Ixx = j["Rotators"][std::to_string(i)]["moi"][0u];
moi.Iyy = j["Rotators"][std::to_string(i)]["moi"][1u];
moi.Izz = j["Rotators"][std::to_string(i)]["moi"][2u];
std::array<double, 3> direction;
direction[0] = j["Rotators"][std::to_string(i)]["normalVector"][0u];
direction[1] = j["Rotators"][std::to_string(i)]["normalVector"][1u];
direction[2] = j["Rotators"][std::to_string(i)]["normalVector"][2u];
rotator RotatorComponent(mDipole, torque, storedMomentum, rotSpeed, moi, direction);
std::string key = j["Rotators"][std::to_string(i)]["key"];
returnConfig.rotators.insert (std::pair<std::string, rotator>(key, RotatorComponent));
}
return returnConfig;
};
}
#endif // JSONPARSER_H.begin(); | 38.842767 | 100 | 0.61739 | oranellis |
1499268379b786c7f9ca67f5e1345a27cf997ae6 | 2,130 | cpp | C++ | aws-cpp-sdk-xray/source/model/ResponseTimeRootCauseEntity.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-xray/source/model/ResponseTimeRootCauseEntity.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-xray/source/model/ResponseTimeRootCauseEntity.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/xray/model/ResponseTimeRootCauseEntity.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace XRay
{
namespace Model
{
ResponseTimeRootCauseEntity::ResponseTimeRootCauseEntity() :
m_nameHasBeenSet(false),
m_coverage(0.0),
m_coverageHasBeenSet(false),
m_remote(false),
m_remoteHasBeenSet(false)
{
}
ResponseTimeRootCauseEntity::ResponseTimeRootCauseEntity(JsonView jsonValue) :
m_nameHasBeenSet(false),
m_coverage(0.0),
m_coverageHasBeenSet(false),
m_remote(false),
m_remoteHasBeenSet(false)
{
*this = jsonValue;
}
ResponseTimeRootCauseEntity& ResponseTimeRootCauseEntity::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Coverage"))
{
m_coverage = jsonValue.GetDouble("Coverage");
m_coverageHasBeenSet = true;
}
if(jsonValue.ValueExists("Remote"))
{
m_remote = jsonValue.GetBool("Remote");
m_remoteHasBeenSet = true;
}
return *this;
}
JsonValue ResponseTimeRootCauseEntity::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_coverageHasBeenSet)
{
payload.WithDouble("Coverage", m_coverage);
}
if(m_remoteHasBeenSet)
{
payload.WithBool("Remote", m_remote);
}
return payload;
}
} // namespace Model
} // namespace XRay
} // namespace Aws
| 20.480769 | 88 | 0.723474 | curiousjgeorge |
1499b5aee1367c1c968dd5feb57f343cc1732286 | 218 | hpp | C++ | rapidxml/include/rapidxml/utility.hpp | Berrysoft/XamlCpp | cc7da0cf83892ceb88926292b7c90b9f8da6128d | [
"MIT"
] | 27 | 2020-01-02T07:40:57.000Z | 2022-03-09T14:43:56.000Z | rapidxml/include/rapidxml/utility.hpp | Berrysoft/XamlCpp | cc7da0cf83892ceb88926292b7c90b9f8da6128d | [
"MIT"
] | null | null | null | rapidxml/include/rapidxml/utility.hpp | Berrysoft/XamlCpp | cc7da0cf83892ceb88926292b7c90b9f8da6128d | [
"MIT"
] | 3 | 2020-05-21T07:02:08.000Z | 2021-07-01T00:56:38.000Z | #ifndef XAML_RAPIDXML_UTILITY_HPP
#define XAML_RAPIDXML_UTILITY_HPP
#include <xaml/utility.h>
#ifndef RAPIDXML_API
#define RAPIDXML_API __XAML_IMPORT
#endif // !RAPIDXML_API
#endif // !XAML_RAPIDXML_UTILITY_HPP
| 19.818182 | 38 | 0.811927 | Berrysoft |
149e527a514999a5743443fb29371858a8d8af53 | 50,286 | cpp | C++ | test/adiar/zdd/test_binop.cpp | logsem/adiar | 056c62a37eedcc5a9e46ccc8c235b5aacedebe32 | [
"MIT"
] | null | null | null | test/adiar/zdd/test_binop.cpp | logsem/adiar | 056c62a37eedcc5a9e46ccc8c235b5aacedebe32 | [
"MIT"
] | null | null | null | test/adiar/zdd/test_binop.cpp | logsem/adiar | 056c62a37eedcc5a9e46ccc8c235b5aacedebe32 | [
"MIT"
] | null | null | null | go_bandit([]() {
describe("adiar/zdd/binop.cpp", []() {
node_file zdd_F;
node_file zdd_T;
{ // Garbage collect writers to free write-lock
node_writer nw_F(zdd_F);
nw_F << create_sink(false);
node_writer nw_T(zdd_T);
nw_T << create_sink(true);
}
ptr_t sink_T = create_sink_ptr(true);
ptr_t sink_F = create_sink_ptr(false);
node_file zdd_x0;
node_file zdd_x1;
{ // Garbage collect writers early
node_writer nw_x0(zdd_x0);
nw_x0 << create_node(0,MAX_ID, sink_F, sink_T);
node_writer nw_x1(zdd_x1);
nw_x1 << create_node(1,MAX_ID, sink_F, sink_T);
}
describe("zdd_union", [&]() {
it("should shortcut Ø on same file", [&]() {
__zdd out = zdd_union(zdd_F, zdd_F);
AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_F._file_ptr));
});
it("should shortcut { Ø } on same file", [&]() {
__zdd out = zdd_union(zdd_T, zdd_T);
AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_T._file_ptr));
});
it("should shortcut { {0} } on same file", [&]() {
__zdd out = zdd_union(zdd_x0, zdd_x0);
AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr));
});
it("should shortcut { {1} } on same file", [&]() {
__zdd out = zdd_union(zdd_x1, zdd_x1);
AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_x1._file_ptr));
});
it("computes Ø U { {Ø} }", [&]() {
__zdd out = zdd_union(zdd_F, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true)));
AssertThat(out_nodes.can_pull(), Is().False());
level_info_test_stream<node_t> ms(out);
AssertThat(ms.can_pull(), Is().False());
});
it("computes { Ø } U Ø", [&]() {
__zdd out = zdd_union(zdd_T, zdd_F);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true)));
AssertThat(out_nodes.can_pull(), Is().False());
level_info_test_stream<node_t> ms(out);
AssertThat(ms.can_pull(), Is().False());
});
it("should shortcut on irrelevance for { {0} } U Ø", [&]() {
/*
1 ---- x0
/ \
F T
*/
__zdd out_1 = zdd_union(zdd_x0, zdd_F);
AssertThat(out_1.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr));
__zdd out_2 = zdd_union(zdd_F, zdd_x0);
AssertThat(out_2.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr));
});
it("computes { {0} } U { Ø }", [&]() {
/*
1 ---- x0
/ \
T T
*/
__zdd out = zdd_union(zdd_x0, zdd_T);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0} } U { {1} }", [&]() {
/*
1 ---- x0
/ \
2 T ---- x1
/ \
F T
*/
__zdd out = zdd_union(zdd_x0, zdd_x1);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0,1}, {0,3} } U { {0,2}, {2} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ X
F 2 | | (2,2) \ ---- x1
/ \ \ / ==> / \ \
| T 2 (3,2) T (F,2) ---- x2
| / \ / \ / \
3 F T (3,F) T F T ---- x3
/ \ / \
F T F T
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(3,MAX_ID, sink_F, sink_T)
<< create_node(1,MAX_ID, create_node_ptr(3,MAX_ID), sink_T)
<< create_node(0,MAX_ID, sink_F, create_node_ptr(1,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID))
;
}
__zdd out = zdd_union(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,1) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0,1}, {1} } U { {0,2}, {2} }", [&]() {
/*
1 1 (1,1)
|| / \ | |
2 | | (2,2)
/ \ \ / ==> / \
F T 2 (F,2) (T,F) <-- since 2nd (2) skipped level
/ \ / \
F T F T
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(1,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID))
;
}
__zdd out = zdd_union(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0}, {1,3}, {2,3}, {1} } U { {0,3}, {3} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
2 T | | (2,2) \ ---- x1
/ \ | | / \ \
3 \ | | ==> (3,2) | \ ---- x2
\\ / \ / / \ | |
4 2 (4,2) (4,F) (T,2) ---- x3
/ \ / \ / \ / \ / \
F T F T T T T T T T
The high arc on (2) and (3) on the left is shortcutting the
second ZDD, to compensate for the omitted nodes.
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(3,MAX_ID, sink_F, sink_T)
<< create_node(2,MAX_ID, create_node_ptr(3,MAX_ID), create_node_ptr(3,MAX_ID))
<< create_node(1,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(3,MAX_ID))
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T)
;
node_writer nw_b(zdd_b);
nw_b << create_node(3,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(3,MAX_ID), create_node_ptr(3,MAX_ID))
;
}
__zdd out = zdd_union(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(3,1) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(3,2) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,2), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,2)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,3u)));
AssertThat(level_info.can_pull(), Is().False());
});
});
describe("zdd_intsec", [&]() {
it("should shortcut on same file", [&]() {
__zdd out_1 = zdd_intsec(zdd_x0, zdd_x0);
AssertThat(out_1.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr));
__zdd out_2 = zdd_intsec(zdd_x1, zdd_x1);
AssertThat(out_2.get<node_file>()._file_ptr, Is().EqualTo(zdd_x1._file_ptr));
});
it("computes Ø ∩ { {Ø} }", [&]() {
__zdd out = zdd_intsec(zdd_F, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { Ø } ∩ Ø", [&]() {
__zdd out = zdd_intsec(zdd_T, zdd_F);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes (and shortcut) { {0} } ∩ Ø", [&]() {
/*
1 F F ---- x0
/ \ ==>
F T
*/
__zdd out = zdd_intsec(zdd_x0, zdd_F);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes (and shortcut) Ø ∩ { {0} }", [&]() {
__zdd out = zdd_intsec(zdd_F, zdd_x0);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { {0} } ∩ { Ø }", [&]() {
/*
1 T F ---- x0
/ \ ==>
F T
*/
__zdd out = zdd_intsec(zdd_x0, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { Ø, {0} } ∩ { Ø }", [&]() {
/*
1 T T ---- x0
/ \ ==>
T T
*/
node_file zdd_a;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(0,MAX_ID, sink_T, sink_T);
}
__zdd out = zdd_intsec(zdd_a, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { {0}, {1} } ∩ { Ø }", [&]() {
/*
1 T F ---- x0
/ \
2 T ==> ---- x1
/ \
F T
*/
node_file zdd_a;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T)
;
}
__zdd out = zdd_intsec(zdd_a, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes (and shortcut) { {0,1}, {1} } ∩ { {0,1} }", [&]() {
/*
_1_ 1 1 ---- x0
/ \ / \ / \
2 3 F 2 ==> F 2 ---- x1
/ \ / \ / \ / \
T T F T F T F T
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(1,MAX_ID-1, sink_T, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID-1), create_node_ptr(1,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, sink_F, create_node_ptr(1,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes (and skip to sink) { {0}, {1}, {0,1} } ∩ { Ø }", [&]() {
/*
1 T F ---- x0
/ \
\ / ==>
2 ---- x1
/ \
F T
*/
node_file zdd_a;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(1,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes (and skip to sink) { {0,2}, {0}, {2} } \\ { {1}, {2}, Ø }", [&]() {
/*
1 F ---- x0
/ \
/ \ _1_ ---- x1
| | / \ =>
2 3 2 3 ---- x2
/ \ / \ / \ / \
F T T T T F F T
Where (2) and (3) are swapped in order on the right. Notice,
that (2) on the right technically is illegal, but it makes
for a much simpler counter-example that catches
prod_pq_1.peek() throwing an error on being empty.
*/
node_file zdd_a;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(2,MAX_ID-1, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(2,MAX_ID))
;
}
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_T, sink_F)
<< create_node(2,MAX_ID-1, sink_F, sink_T)
<< create_node(1,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID-1))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes (and skips in) { {0,1,2}, {0,2}, {0}, {2} } } ∩ { {0,2}, {0}, {1}, {2} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
| _2_ 2 \ / \
\/ \ / \ | ==> | |
3 4 3 T 4 (3,3) (3,4)
/ \ / \ / \ / \ / \ / \
T T F T F T T T F T T T
where (3) and (4) are swapped in order on the left one.
(3,3) : ((2,1), (2,0)) , (3,4) : ((2,1), (2,1))
so (3,3) is forwarded while (3,4) is not and hence (3,3) is output first.
*/
node_file zdd_a;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(2,MAX_ID-1, sink_F, sink_T)
<< create_node(1,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID-1))
<< create_node(0,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(1,MAX_ID))
;
}
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(2,MAX_ID-1, sink_F, sink_T)
<< create_node(1,MAX_ID, create_node_ptr(2,MAX_ID-1), sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0}, {1} } ∩ { {0,1} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
2 T F 2 F (T,2) ---- x1
/ \ / \ ==> / \
F T F T F F
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T)
;
node_writer nw_b(zdd_b);
nw_b << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, sink_F, create_node_ptr(1,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes (and skip) { {0}, {1}, {2}, {1,2}, {0,2} } ∩ { {0}, {2}, {0,2}, {0,1,2} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
2 | | 2 / \ ---- x1
/ \| |/ \ ==> | |
3 4 3 4 (3,3) (4,3) ---- x2
/ \/ \ / \/ \ / \ / \
F T T F T T F T F T
Notice, how (2,3) and (4,2) was skipped on the low and high of (1,1)
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(2,MAX_ID-1, sink_F, sink_T)
<< create_node(1,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(2,MAX_ID))
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(2,MAX_ID-1, sink_F, sink_T)
<< create_node(1,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(2,MAX_ID))
<< create_node(0,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(1,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes (and skip) { {0}, {1} } ∩ { {1}, {0,2} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
2 T 2 \ (2,2) F ---- x1
/ \ / \ | => / \
F T F T 3 F T ---- x2
/ \
F T
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T)
;
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_F, sink_T)
<< create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes (and skip) { {0,2}, {1,2}, Ø } ∩ { {0,1}, {0}, {1} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
2 \ 2 T (2,2) | ---- x1
/ \ / / \ => / \ |
T 3 T T T F F ---- x2
/ \
F T
This shortcuts the (3,T) tuple twice.
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(2,MAX_ID, sink_F, sink_T)
<< create_node(1,MAX_ID, sink_T, create_node_ptr(2,MAX_ID))
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(1,MAX_ID, sink_T, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T)
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes (and shortcut) { {0,2}, {1,2}, Ø } ∩ { {0,2}, {0} }", [&]() {
/*
1 1 (1,1) ---- x0
/ \ / \ / \
2 \ F | F | ---- x1
/ \ / | ==> |
T 3 2 (2,3) ---- x2
/ \ / \ / \
F T T T F T
This shortcuts the (3,T) tuple twice.
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(2,MAX_ID, sink_F, sink_T)
<< create_node(1,MAX_ID, sink_T, create_node_ptr(2,MAX_ID))
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(0,MAX_ID, sink_F, create_node_ptr(2,MAX_ID))
;
}
__zdd out = zdd_intsec(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
});
describe("zdd_diff", [&]() {
it("should shortcut to Ø on same file for { {x0} }", [&]() {
__zdd out = zdd_diff(zdd_x0, zdd_x0);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("should shortcut to Ø on same file for { {x1} }", [&]() {
__zdd out = zdd_diff(zdd_x1, zdd_x1);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { Ø } \\ Ø", [&]() {
__zdd out = zdd_diff(zdd_T, zdd_F);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes Ø \\ { Ø }", [&]() {
__zdd out = zdd_diff(zdd_F, zdd_T);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("should shortcut on irrelevance on { {x0} } \\ Ø", [&]() {
__zdd out_1 = zdd_diff(zdd_x0, zdd_F);
AssertThat(out_1.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr));
});
it("should shortcut on irrelevance on { {x1} } \\ Ø", [&]() {
__zdd out_2 = zdd_diff(zdd_x1, zdd_F);
AssertThat(out_2.get<node_file>()._file_ptr, Is().EqualTo(zdd_x1._file_ptr));
});
it("computes (and shortcut) Ø \\ { {0} }", [&]() {
__zdd out = zdd_intsec(zdd_F, zdd_x0);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { {Ø} } \\ { {0} }", [&]() {
__zdd out = zdd_diff(zdd_T, zdd_x0);
node_test_stream out_nodes(out);
AssertThat(out_nodes.can_pull(), Is().True());
AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true)));
AssertThat(out_nodes.can_pull(), Is().False());
AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u));
});
it("computes { {0} } \\ { Ø }", [&]() {
/*
1 T 1 ---- x0
/ \ ==> / \
F T F T
*/
__zdd out = zdd_diff(zdd_x0, zdd_T);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0}, Ø } \\ { Ø }", [&]() {
/*
1 T 1 ---- x0
/ \ ==> / \
T T F T
*/
node_file zdd_a;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(0,MAX_ID, sink_T, sink_T);
}
__zdd out = zdd_diff(zdd_a, zdd_T);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0,1}, {1} } \\ { {1}, Ø }", [&]() {
/*
1 (1,1) ---- x0
|| / \
2 1 ==> (2,1) (2,F) ---- x1
/ \ / \ / \ / \
F T T T F F F T
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(1,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(1,MAX_ID, sink_T, sink_T);
}
__zdd out = zdd_diff(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
it("computes { {0,1}, {1,2}, {1} } \\ { {1}, Ø }", [&]() {
/*
_1_ (1,1) ---- x0
/ \ / \
3 2 1 ==> (3,1) (2,F) ---- x1
/ \ / \ / \ / \ / \
F 4 F T T T F (3,T) F T ---- x2
/ \ / \
T T F T
*/
node_file zdd_a;
node_file zdd_b;
{ // Garbage collect writers early
node_writer nw_a(zdd_a);
nw_a << create_node(2,MAX_ID, sink_T, sink_T)
<< create_node(1,MAX_ID, sink_F, sink_T)
<< create_node(1,MAX_ID-1, sink_F, create_node_ptr(2,MAX_ID))
<< create_node(0,MAX_ID, create_node_ptr(1,MAX_ID-1), create_node_ptr(1,MAX_ID))
;
node_writer nw_b(zdd_b);
nw_b << create_node(1,MAX_ID, sink_T, sink_T);
}
__zdd out = zdd_diff(zdd_a, zdd_b);
node_arc_test_stream node_arcs(out);
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) }));
AssertThat(node_arcs.can_pull(), Is().True());
AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,0) }));
AssertThat(node_arcs.can_pull(), Is().False());
sink_arc_test_stream sink_arcs(out);
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F }));
AssertThat(sink_arcs.can_pull(), Is().True());
AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T }));
AssertThat(sink_arcs.can_pull(), Is().False());
level_info_test_stream<arc_t> level_info(out);
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u)));
AssertThat(level_info.can_pull(), Is().True());
AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u)));
AssertThat(level_info.can_pull(), Is().False());
});
});
});
});
| 37.752252 | 109 | 0.518474 | logsem |
14a15cb872a5518f55b20c5292e451f1211f3c42 | 321 | hpp | C++ | src/header_hpp/tcp_header.hpp | Maxim-byte/pcap_parser- | 3f34b824699ec595ff34518d83b278d1cbcdeef5 | [
"MIT"
] | null | null | null | src/header_hpp/tcp_header.hpp | Maxim-byte/pcap_parser- | 3f34b824699ec595ff34518d83b278d1cbcdeef5 | [
"MIT"
] | null | null | null | src/header_hpp/tcp_header.hpp | Maxim-byte/pcap_parser- | 3f34b824699ec595ff34518d83b278d1cbcdeef5 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <iosfwd>
#include <system_error>
struct tcp_header
{
std::uint16_t s_port;
std::uint16_t d_port;
static tcp_header read_tcp_header(std::istream & stream, std::error_code & ec);
static void print_tcp_header(std::ostream & stream, const tcp_header & header);
};
| 20.0625 | 83 | 0.719626 | Maxim-byte |
14a336dc3427d323f6920fa0a13597de3d4ec19f | 7,637 | cpp | C++ | src/rtc/momo_video_encoder_factory.cpp | S-YOU/momo | 9047dd4eb58345e9fea151ee2e04deb876033947 | [
"Apache-2.0"
] | null | null | null | src/rtc/momo_video_encoder_factory.cpp | S-YOU/momo | 9047dd4eb58345e9fea151ee2e04deb876033947 | [
"Apache-2.0"
] | null | null | null | src/rtc/momo_video_encoder_factory.cpp | S-YOU/momo | 9047dd4eb58345e9fea151ee2e04deb876033947 | [
"Apache-2.0"
] | null | null | null | #include "momo_video_encoder_factory.h"
// WebRTC
#include <absl/memory/memory.h>
#include <absl/strings/match.h>
#include <api/video_codecs/sdp_video_format.h>
#include <media/base/codec.h>
#include <media/base/media_constants.h>
#include <media/base/vp9_profile.h>
#include <media/engine/simulcast_encoder_adapter.h>
#include <modules/video_coding/codecs/h264/include/h264.h>
#include <modules/video_coding/codecs/vp8/include/vp8.h>
#include <modules/video_coding/codecs/vp9/include/vp9.h>
#include <rtc_base/logging.h>
#if !defined(__arm__) || defined(__aarch64__) || defined(__ARM_NEON__)
#include <modules/video_coding/codecs/av1/libaom_av1_encoder.h>
#endif
#if defined(__APPLE__)
#include "mac_helper/objc_codec_factory_helper.h"
#endif
#if USE_MMAL_ENCODER
#include "hwenc_mmal/mmal_h264_encoder.h"
#endif
#if USE_JETSON_ENCODER
#include "hwenc_jetson/jetson_video_encoder.h"
#endif
#if USE_NVCODEC_ENCODER
#include "hwenc_nvcodec/nvcodec_h264_encoder.h"
#endif
#include "h264_format.h"
MomoVideoEncoderFactory::MomoVideoEncoderFactory(
VideoCodecInfo::Type vp8_encoder,
VideoCodecInfo::Type vp9_encoder,
VideoCodecInfo::Type av1_encoder,
VideoCodecInfo::Type h264_encoder,
bool simulcast)
: vp8_encoder_(vp8_encoder),
vp9_encoder_(vp9_encoder),
av1_encoder_(av1_encoder),
h264_encoder_(h264_encoder) {
#if defined(__APPLE__)
video_encoder_factory_ = CreateObjCEncoderFactory();
#endif
if (simulcast) {
internal_encoder_factory_.reset(new MomoVideoEncoderFactory(
vp8_encoder, vp9_encoder, av1_encoder, h264_encoder, false));
}
}
std::vector<webrtc::SdpVideoFormat>
MomoVideoEncoderFactory::GetSupportedFormats() const {
std::vector<webrtc::SdpVideoFormat> supported_codecs;
// VP8
if (vp8_encoder_ == VideoCodecInfo::Type::Software ||
vp8_encoder_ == VideoCodecInfo::Type::Jetson) {
supported_codecs.push_back(webrtc::SdpVideoFormat(cricket::kVp8CodecName));
}
// VP9
if (vp9_encoder_ == VideoCodecInfo::Type::Software) {
for (const webrtc::SdpVideoFormat& format : webrtc::SupportedVP9Codecs()) {
supported_codecs.push_back(format);
}
} else if (vp9_encoder_ == VideoCodecInfo::Type::Jetson) {
#if USE_JETSON_ENCODER
supported_codecs.push_back(webrtc::SdpVideoFormat(
cricket::kVp9CodecName,
{{webrtc::kVP9FmtpProfileId,
webrtc::VP9ProfileToString(webrtc::VP9Profile::kProfile0)}}));
#endif
}
// AV1
// 今のところ Software のみ
if (av1_encoder_ == VideoCodecInfo::Type::Software) {
supported_codecs.push_back(webrtc::SdpVideoFormat(cricket::kAv1CodecName));
}
// H264
std::vector<webrtc::SdpVideoFormat> h264_codecs = {
CreateH264Format(webrtc::H264::kProfileBaseline, webrtc::H264::kLevel3_1,
"1"),
CreateH264Format(webrtc::H264::kProfileBaseline, webrtc::H264::kLevel3_1,
"0"),
CreateH264Format(webrtc::H264::kProfileConstrainedBaseline,
webrtc::H264::kLevel3_1, "1"),
CreateH264Format(webrtc::H264::kProfileConstrainedBaseline,
webrtc::H264::kLevel3_1, "0")};
if (h264_encoder_ == VideoCodecInfo::Type::VideoToolbox) {
// VideoToolbox の場合は video_encoder_factory_ から H264 を拾ってくる
for (auto format : video_encoder_factory_->GetSupportedFormats()) {
if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName)) {
supported_codecs.push_back(format);
}
}
} else if (h264_encoder_ == VideoCodecInfo::Type::NVIDIA) {
#if USE_NVCODEC_ENCODER
// NVIDIA の場合は対応してる場合のみ追加
if (NvCodecH264Encoder::IsSupported()) {
for (const webrtc::SdpVideoFormat& format : h264_codecs) {
supported_codecs.push_back(format);
}
}
#endif
} else if (h264_encoder_ != VideoCodecInfo::Type::NotSupported) {
// その他のエンコーダの場合は手動で追加
for (const webrtc::SdpVideoFormat& format : h264_codecs) {
supported_codecs.push_back(format);
}
}
return supported_codecs;
}
std::unique_ptr<webrtc::VideoEncoder>
MomoVideoEncoderFactory::CreateVideoEncoder(
const webrtc::SdpVideoFormat& format) {
if (absl::EqualsIgnoreCase(format.name, cricket::kVp8CodecName)) {
if (vp8_encoder_ == VideoCodecInfo::Type::Software) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return webrtc::VP8Encoder::Create();
});
}
#if USE_JETSON_ENCODER
if (vp8_encoder_ == VideoCodecInfo::Type::Jetson) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return std::unique_ptr<webrtc::VideoEncoder>(
absl::make_unique<JetsonVideoEncoder>(cricket::VideoCodec(format)));
});
}
#endif
}
if (absl::EqualsIgnoreCase(format.name, cricket::kVp9CodecName)) {
if (vp9_encoder_ == VideoCodecInfo::Type::Software) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return webrtc::VP9Encoder::Create(cricket::VideoCodec(format));
});
}
#if USE_JETSON_ENCODER
if (vp9_encoder_ == VideoCodecInfo::Type::Jetson) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return std::unique_ptr<webrtc::VideoEncoder>(
absl::make_unique<JetsonVideoEncoder>(cricket::VideoCodec(format)));
});
}
#endif
}
if (absl::EqualsIgnoreCase(format.name, cricket::kAv1CodecName)) {
#if !defined(__arm__) || defined(__aarch64__) || defined(__ARM_NEON__)
if (av1_encoder_ == VideoCodecInfo::Type::Software) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return webrtc::CreateLibaomAv1Encoder();
});
}
#endif
}
if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName)) {
#if defined(__APPLE__)
if (h264_encoder_ == VideoCodecInfo::Type::VideoToolbox) {
return WithSimulcast(
format, [this](const webrtc::SdpVideoFormat& format) {
return video_encoder_factory_->CreateVideoEncoder(format);
});
}
#endif
#if USE_MMAL_ENCODER
if (h264_encoder_ == VideoCodecInfo::Type::MMAL) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return std::unique_ptr<webrtc::VideoEncoder>(
absl::make_unique<MMALH264Encoder>(cricket::VideoCodec(format)));
});
}
#endif
#if USE_JETSON_ENCODER
if (h264_encoder_ == VideoCodecInfo::Type::Jetson) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return std::unique_ptr<webrtc::VideoEncoder>(
absl::make_unique<JetsonVideoEncoder>(cricket::VideoCodec(format)));
});
}
#endif
#if USE_NVCODEC_ENCODER
if (h264_encoder_ == VideoCodecInfo::Type::NVIDIA &&
NvCodecH264Encoder::IsSupported()) {
return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) {
return std::unique_ptr<webrtc::VideoEncoder>(
absl::make_unique<NvCodecH264Encoder>(cricket::VideoCodec(format)));
});
}
#endif
}
RTC_LOG(LS_ERROR) << "Trying to created encoder of unsupported format "
<< format.name;
return nullptr;
}
std::unique_ptr<webrtc::VideoEncoder> MomoVideoEncoderFactory::WithSimulcast(
const webrtc::SdpVideoFormat& format,
std::function<std::unique_ptr<webrtc::VideoEncoder>(
const webrtc::SdpVideoFormat&)> create) {
if (internal_encoder_factory_) {
return std::unique_ptr<webrtc::VideoEncoder>(
new webrtc::SimulcastEncoderAdapter(internal_encoder_factory_.get(),
format));
} else {
return create(format);
}
}
| 34.400901 | 80 | 0.698049 | S-YOU |
14a3fc3a17136a8fb0c0304476b086058ef673ee | 4,009 | hpp | C++ | include/boost/winapi/init_once.hpp | xentrax/winapi | 66564382fa780a6f3d88d875181667728a4c4ba0 | [
"BSL-1.0"
] | null | null | null | include/boost/winapi/init_once.hpp | xentrax/winapi | 66564382fa780a6f3d88d875181667728a4c4ba0 | [
"BSL-1.0"
] | null | null | null | include/boost/winapi/init_once.hpp | xentrax/winapi | 66564382fa780a6f3d88d875181667728a4c4ba0 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright 2010 Vicente J. Botet Escriba
* Copyright 2015 Andrey Semashev
*
* Distributed under the Boost Software License, Version 1.0.
* See http://www.boost.org/LICENSE_1_0.txt
*/
#ifndef BOOST_WINAPI_INIT_ONCE_HPP_INCLUDED_
#define BOOST_WINAPI_INIT_ONCE_HPP_INCLUDED_
#include <boost/winapi/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6
#include <boost/winapi/basic_types.hpp>
#if !defined(BOOST_USE_WINDOWS_H)
extern "C" {
#if defined(BOOST_WINAPI_IS_CYGWIN) || defined(BOOST_WINAPI_IS_MINGW_W64)
struct _RTL_RUN_ONCE;
#else
union _RTL_RUN_ONCE;
#endif
typedef boost::winapi::BOOL_
(BOOST_WINAPI_WINAPI_CC *PINIT_ONCE_FN) (
::_RTL_RUN_ONCE* InitOnce,
boost::winapi::PVOID_ Parameter,
boost::winapi::PVOID_ *Context);
BOOST_WINAPI_IMPORT boost::winapi::VOID_ BOOST_WINAPI_WINAPI_CC
InitOnceInitialize(::_RTL_RUN_ONCE* InitOnce);
BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC
InitOnceExecuteOnce(
::_RTL_RUN_ONCE* InitOnce,
::PINIT_ONCE_FN InitFn,
boost::winapi::PVOID_ Parameter,
boost::winapi::LPVOID_ *Context);
BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC
InitOnceBeginInitialize(
::_RTL_RUN_ONCE* lpInitOnce,
boost::winapi::DWORD_ dwFlags,
boost::winapi::PBOOL_ fPending,
boost::winapi::LPVOID_ *lpContext);
BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC
InitOnceComplete(
::_RTL_RUN_ONCE* lpInitOnce,
boost::winapi::DWORD_ dwFlags,
boost::winapi::LPVOID_ lpContext);
}
#endif
namespace boost {
namespace winapi {
typedef union BOOST_MAY_ALIAS _RTL_RUN_ONCE {
PVOID_ Ptr;
} INIT_ONCE_, *PINIT_ONCE_, *LPINIT_ONCE_;
extern "C" {
typedef BOOL_ (BOOST_WINAPI_WINAPI_CC *PINIT_ONCE_FN_) (PINIT_ONCE_ lpInitOnce, PVOID_ Parameter, PVOID_ *Context);
}
BOOST_FORCEINLINE VOID_ InitOnceInitialize(PINIT_ONCE_ lpInitOnce)
{
::InitOnceInitialize(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce));
}
BOOST_FORCEINLINE BOOL_ InitOnceExecuteOnce(PINIT_ONCE_ lpInitOnce, PINIT_ONCE_FN_ InitFn, PVOID_ Parameter, LPVOID_ *Context)
{
return ::InitOnceExecuteOnce(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce), reinterpret_cast< ::PINIT_ONCE_FN >(InitFn), Parameter, Context);
}
BOOST_FORCEINLINE BOOL_ InitOnceBeginInitialize(PINIT_ONCE_ lpInitOnce, DWORD_ dwFlags, PBOOL_ fPending, LPVOID_ *lpContext)
{
return ::InitOnceBeginInitialize(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce), dwFlags, fPending, lpContext);
}
BOOST_FORCEINLINE BOOL_ InitOnceComplete(PINIT_ONCE_ lpInitOnce, DWORD_ dwFlags, LPVOID_ lpContext)
{
return ::InitOnceComplete(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce), dwFlags, lpContext);
}
#if defined( BOOST_USE_WINDOWS_H )
#define BOOST_WINAPI_INIT_ONCE_STATIC_INIT INIT_ONCE_STATIC_INIT
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_ASYNC_ = INIT_ONCE_ASYNC;
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CHECK_ONLY_ = INIT_ONCE_CHECK_ONLY;
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_INIT_FAILED_ = INIT_ONCE_INIT_FAILED;
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CTX_RESERVED_BITS_ = INIT_ONCE_CTX_RESERVED_BITS;
#else // defined( BOOST_USE_WINDOWS_H )
#define BOOST_WINAPI_INIT_ONCE_STATIC_INIT {0}
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_ASYNC_ = 0x00000002UL;
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CHECK_ONLY_ = 0x00000001UL;
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_INIT_FAILED_ = 0x00000004UL;
BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CTX_RESERVED_BITS_ = 2;
#endif // defined( BOOST_USE_WINDOWS_H )
BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_async = INIT_ONCE_ASYNC_;
BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_check_only = INIT_ONCE_CHECK_ONLY_;
BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_init_failed = INIT_ONCE_INIT_FAILED_;
BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_ctx_reserved_bits = INIT_ONCE_CTX_RESERVED_BITS_;
}
}
#endif // BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6
#endif // BOOST_WINAPI_INIT_ONCE_HPP_INCLUDED_
| 33.132231 | 148 | 0.817411 | xentrax |
14a80a42984b1e4aaf97c5db6ac8e3ba79c13417 | 274 | cpp | C++ | example/main.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | example/main.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | example/main.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | #include "Engine.hpp"
#include "ExtendingScene.hpp"
#include <memory>
#include <iostream>
int main()
{
std::cout << "running";
Engine engine;
std::shared_ptr<ExtendingScene> scene = std::make_shared<ExtendingScene>();
engine.load(scene);
engine.run();
} | 21.076923 | 79 | 0.675182 | That-Cool-Coder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.